Skip to content

fix: Never use query text or SQLite messages as a printf() format, and guard fetch_blob() against NULL - #869

Merged
krlmlr merged 3 commits into
mainfrom
claude/printf-format-strings
Nov 13, 2026
Merged

krlmlr merged 3 commits into
mainfrom
claude/printf-format-strings

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Decided in #829 (comment): a small separate pull request from main, independent of the Arrow stack.

What changes and why

cpp11::warning() and cpp11::stop() treat their first argument as a printf() format unless CPP11_USE_FMT is defined. Three calls passed user-controlled text there, so a %n in a query, a table name or a column name aborted R with *** %n in writable segment detected ***, and other conversions such as %d%d printed garbage:

  • SqliteResultImpl::prepare(): the "Ignoring remaining part of query: " warning appended the rest of a multi-statement query (dbGetQuery(con, "SELECT 1; SELECT '%n'")).
  • SqliteResultImpl::raise_sqlite_exception(): passed sqlite3_errmsg(), which quotes table and column names (dbGetQuery(con, 'SELECT * FROM "x%n"')).
  • DbColumn::warn_type_conflicts(): the mixed-type warning includes the column name. This is the column-name variant found in the review of fix: Validate blobs that are read into a text column #799; that reimplementation no longer carries the fix, so it lands here.

All three now pass a fixed "%s"-style format with the text as an argument. A remaining query that merely contains a literal %, such as SELECT 1; SELECT 'café 100%', gave an empty warning on main (confirmed by the review); the warning now shows the remaining query as written. The "Query requires %i params; %i supplied." error passed params.size(), an R_xlen_t, for %i; it is now cast to int. Every other cpp11::stop(), cpp11::warning(), Rf_error() and Rf_warning() call in src/ (outside the vendored SQLite) already uses a literal format.

SqliteColumnDataSource::fetch_blob() passed the pointer from sqlite3_column_blob() to memcpy() unchecked. For an empty blob (SELECT X'' AS x) that pointer is NULL, which is undefined behavior even for zero bytes (UBSan reports "null pointer passed as argument 2"). An empty blob now returns raw(0) without memcpy(), and a NULL pointer with a nonzero size, which means SQLite ran out of memory, raises an error instead of crashing. A comment notes that sqlite3_column_bytes() must stay before sqlite3_column_blob(), since that check relies on the order.

Left out

raise_sqlite_exception() is replaced by a std::runtime_error in #795 of the Arrow stack; this pull request fixes main now and does not anticipate that change. With the bundled SQLite, zeroblob() is materialized when the statement is stepped, so an out-of-memory zeroblob() already fails with "out of memory" from dbSendQuery(); the new NULL check in fetch_blob() is a guard for the case where the expansion happens on access, and has no test because it could not be triggered here.

Tests

  • New tests/testthat/test-format-strings.R: the multi-statement warning with %n, %d%d and %s%s%s; "no such table" errors with the same patterns; a table and a column named with %n%s, read back unchanged, with the "already exists", "no such column" and mixed-type messages intact. These abort R on main.
  • tests/testthat/test-blob.R: empty blobs from X'' and zeroblob(0), next to a non-empty one, and an empty blob round-tripped through dbWriteTable() and dbReadTable().
  • The new tests pass under UBSan (package built with -fsanitize=undefined) without reports; the same build of the old fetch_blob() reports the NULL argument to memcpy().
  • devtools::test(): all pass apart from the three test-httpvfs.R errors that also happen on main (test: Run the HTTP VFS tests for real, and make their errors fail the check #832, testthat hides a test's error when the test records another result after it #837) and one "interrupt in busy handler" error in test-dbConnect.R that needs RSQLite installed in the library its callr subprocess uses.

https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn


Generated by Claude Code

`cpp11::warning()` and `cpp11::stop()` treat their first argument as a format.
The warning for the ignored rest of a multi-statement query,
the error raised from `sqlite3_errmsg()`,
and the mixed-type column warning passed user-controlled text there,
so a `%n` in a query, a table name or a column name aborted R
and other conversions printed garbage.
These calls now pass a fixed format with the text as an argument.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
`sqlite3_column_blob()` returns `NULL` for an empty blob,
and passing it to `memcpy()` is undefined behavior even for zero bytes.
An empty blob now returns `raw(0)` directly,
and a `NULL` pointer with a nonzero size, which means that SQLite ran out of memory,
raises an error instead of crashing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 27a8236, by a Claude Code reviewer with clean context that read the description, the two commits and the diff against main at 3b7bea3, the code around every change and the new tests, audited every printf-style call in src/ outside the vendored code, built the pull request and its base normally and with UndefinedBehaviorSanitizer, ran the new tests on both, ran each fix as a mutant, compared user-visible messages between the two builds, and ran the full test suite. I posted nothing myself.

What was run

  • R CMD INSTALL of 27a8236 and 3b7bea3 into separate libraries, plus a second pair built with -fsanitize=undefined (gcc 13, libubsan preloaded).
  • Each test_that() block of test-format-strings.R and the new "empty blobs" block, each in a fresh R process right after pkgload::load_all(), on both commits.
  • Three mutants of the pull request, each reverting one of the three format-string fixes, against the three format-string blocks.
  • A script printing the warnings and errors for ordinary names, multi-statement queries, syntax errors, parameter-count errors, mixed-type columns and blobs (X'', zeroblob(0), zeroblob(5), CAST('' AS BLOB), NULL, and '' text in a blob column), diffed between the two builds.
  • The new tests and the blob reproducers under UBSan on both builds.
  • devtools::test() with NOT_CRAN=true on the pull request, with its library on R_LIBS for the callr subprocess.

What holds

  • On main, all three format-string blocks abort R with *** %n in writable segment detected ***; on the pull request they pass. Each mutant aborts exactly the block that covers its fix (the multi-statement block, the "no such table" block and the third block's "already exists" step, the mixed-type step), so every fix has its own failing test (Confirmed).
  • The audit is complete: every other cpp11::stop(), cpp11::warning(), Rf_error() and Rf_warning() in src/*.c, src/*.cpp and src/*.h passes a string literal as the format, including the std::string("...") overloads in SqliteColumnDataSource.cpp (no % in them); sqlite3_errmsg() elsewhere (DbConnection.cpp, import-file.c) already goes through "%s". There are no Rprintf(), REprintf() or non-literal snprintf() calls outside vendor/ (Confirmed by grep).
  • User-visible messages are byte-identical between main and the pull request for every ordinary case in the script. The only difference is an improvement the description does not mention: on main, dbGetQuery(con, "SELECT 1; SELECT 'café 100%'") warns with an empty message, because %' is consumed as a conversion; the pull request prints the query text (Confirmed). No snapshot under tests/testthat/_snaps/ covers these messages, and git status stays clean after the suite.
  • fetch_blob(): X'', zeroblob(0), CAST('' AS BLOB) and an empty string in a blob column now return raw(0); NULL values never reach fetch_blob() because DbColumnStorage::append_col() checks is_null() first and they come back as NULL list elements; zeroblob(5) returns five zero bytes. UBSan on main reports SqliteColumnDataSource.cpp:92:9: runtime error: null pointer passed as argument 2, which is declared to never be null for the new blob test; the pull request build is silent for the new blob and format-string tests and the reproducers (Confirmed).
  • Calling sqlite3_column_bytes() before sqlite3_column_blob() is the right order for the new guard: bytes() reports the full size of a zero-filled blob without expanding it, and if blob() then fails to expand it, SQLite turns the value into NULL and returns a null pointer, so size > 0 && blob == NULL is exactly the out-of-memory case. In the opposite order the failed expansion would make bytes() return 0 and silently yield raw(0) (by reading the bundled sqlite3_value_blob() and valueBytes()). The %d matches int size.
  • devtools::test(): everything passes except the three test-httpvfs.R errors known from main (test: Run the HTTP VFS tests for real, and make their errors fail the check #832, testthat hides a test's error when the test records another result after it #837); the test-dbConnect.R callr test passes once the built package is on R_LIBS, as the description says.
  • The description matches the code and the title matches the scope; no src/*.dd file is touched.

High

None.

Medium

None.

Low

  1. %i receives an R_xlen_t in the parameter-count error; it is real but harmless in practice and can stay out of this pull request.
    if (params.size() != cache.nparams_) {
    cpp11::stop(
    "Query requires %i params; %i supplied.",
    cache.nparams_,
    params.size()
    );
    }
    — cpp11::list::size() returns R_xlen_t (64-bit ptrdiff_t) and is passed for %i, which is undefined behavior in varargs; on the x86-64 and arm64 calling conventions the low 32 bits are read and the message is correct for any realistic count (Query requires 1 params; 2 supplied. on both builds) (Confirmed for the output, by reading for the mismatch). Because cpp11::stop() has no format attribute, the compiler cannot flag it. It is a literal-format type mismatch, not user-controlled text, so it is outside this pull request's title; adding the one-line cast here would still be in the spirit of the audit, and either choice is fine. The other %i/%d arguments in src/ are int, and %ld in connection.cpp gets a long. Suggested fix: static_cast<int>(params.size()), here or in a follow-up.
  2. The out-of-memory guard in fetch_blob() depends on the call order and has no test.
    SEXP SqliteColumnDataSource::fetch_blob() const {
    int size = sqlite3_column_bytes(get_stmt(), get_j());
    const void* blob = sqlite3_column_blob(get_stmt(), get_j());
    // An empty blob may come back as a NULL pointer,
    // which must not reach memcpy().
    if (size == 0) {
    return Rf_allocVector(RAWSXP, 0);
    }
    // A NULL pointer with a nonzero size means that SQLite ran out of memory.
    if (blob == NULL) {
    cpp11::stop("Out of memory while fetching a blob of %d bytes.", size);
    }
    — as shown above, swapping sqlite3_column_bytes() and sqlite3_column_blob() (as SQLite's documentation suggests for the general case) would turn the guard into silent data loss, and nothing would catch it (by reading); the description already says the branch could not be triggered. Suggested fix: extend the comment to say that sqlite3_column_bytes() must come first so that a failed expansion is seen as a null pointer with a nonzero size.

Generated by Claude Code

`params.size()` is an `R_xlen_t`,
which does not match the `%i` in "Query requires %i params; %i supplied.".
Also note in `fetch_blob()` that `sqlite3_column_bytes()` must stay
before `sqlite3_column_blob()`, since the out-of-memory check relies on it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review of 27a8236 found nothing above Low: each new format-string test aborts R on main and passes here, the audit of src/ is complete, messages for ordinary names and queries are byte-identical to main, empty blobs return raw(0), UBSan is silent, and devtools::test() shows only the three known test-httpvfs.R errors. Both of its Lows are fixed in a617dbc (an int for %i, and a comment that pins the order of the two SQLite calls in fetch_blob()). This remains:

  • src/SqliteColumnDataSource.cpp#L88-L101: the out-of-memory guard of fetch_blob() has no test, since the bundled SQLite materializes a zeroblob() during the step and reports running out of memory there; it relies on sqlite3_column_bytes() coming before sqlite3_column_blob(), which the comment pins. Relevance: low; reviewer's confidence: high. (recorded)

Generated by Claude Code

@krlmlr
krlmlr merged commit 6e7b0b9 into main Nov 13, 2026
8 checks passed
@krlmlr
krlmlr deleted the claude/printf-format-strings branch November 13, 2026 13:05
krlmlr pushed a commit that referenced this pull request Nov 13, 2026
Bring in #853 (gcc continuation lines in the generated `.dd` files)
and #869 (no query text or SQLite message as a `printf()` format, `fetch_blob()` guarded against `NULL`).

The conflict in `SqliteResultImpl::raise_sqlite_exception()` keeps this branch's
`throw std::runtime_error(sqlite3_errmsg(conn))`:
a failed prepare reaches R at cpp11's entry point like every other step error here,
and cpp11 passes the message through `"%s"`, so it is not a format string either.
The `.dd` files regenerated with the new `src/Makevars.deps` are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants