Repository navigation
Description
A db.exec result set that is dropped while it is partway through a query that computes a JavaScript window function frees memory that is still in use. In the sqlite3 shell this ends with double free or corruption (!prev) (abort), or with SIGSEGV. Seen on 1.4.1, unpatched, x86_64 Linux, with SQLite 3.46.1 (shell) and with SQLite 3.49.1 built in.
Reproduce (with the extension built as js.so):
.load ./js
SELECT js_create_window('w', 'n = 0;', '(function (args) { n++; })',
'(function () { for (let i = 0; i < 50; i++) { const o = { a: [1, 2, 3] }; } return n; })',
'(function () { return n; })', '(function (args) { n--; })');
SELECT js_eval('for (let i = 0; i < 20000; i++) { db.exec("SELECT w(column1) OVER (ORDER BY column1) FROM (VALUES (1), (2), (3))").next(); } 7');The last statement aborts with double free or corruption (!prev), or with SIGSEGV under MALLOC_PERTURB_=165. Built with -fsanitize=address, 20 iterations are enough: heap-use-after-free in free_object (quickjs.c:16771).
What it needs, from cutting the case down:
- A window function whose
finalallocates. Afinalthat only returnsndoesn't fail. The objects don't need to form cycles. - A result set that has stepped into the window query (
next()once) and is then dropped. One that is read to the end withtoArray()doesn't fail. - An aggregate with
GROUP BYinstead of a window function didn't fail in the same test.
Why. Dropping the result set frees its Rowset object, and js_rowset_finalizer (sqlitejs.c:234) calls sqlite3_finalize(). The statement still holds the window function's state, so SQLite calls its xFinal while finalizing (sqlite3VdbeMemFinalize). That is js_execute_final, which runs JavaScript inside QuickJS's free_object. When that JavaScript allocates, it can start a collection (js_trigger_gc → JS_RunGC → gc_free_cycles), which frees the object whose finalizer is running. free_object then writes to it after the finalizer returns.
ASan, abridged:
WRITE of size 2 ... free_object quickjs.c:16771 <- free_gc_object <- free_zero_refcount <- JS_FreeValue <- JS_CallInternal <- ... <- js_eval sqlitejs.c:1568
freed by: js_mem_free sqlitejs.c:327 <- gc_free_cycles quickjs.c:17155 <- JS_RunGC <- js_trigger_gc <- JS_NewObject <- JS_CallInternal
<- js_execute_common sqlitejs.c:1190 <- js_execute_final sqlitejs.c:1252 <- sqlite3VdbeMemFinalize <- ... <- sqlite3_finalize
<- js_rowset_finalizer sqlitejs.c:234 <- free_object quickjs.c:16768 <- ...
A QuickJS class finalizer must not run JavaScript, and sqlite3_finalize() can run it when the statement is mid-query and computes a JavaScript aggregate or window function.
A possible fix. Don't finalize such a statement from the finalizer. A statement that isn't mid-query (sqlite3_stmt_busy() is false) holds no aggregate state, so finalizing it can't call back into JavaScript and is safe there. A busy one could go onto a per-connection list, finalized where JavaScript may run: when the outermost call into JavaScript returns, or before the next one. #24 adds a per-connection list of result sets, which this could build on. We can send a pull request if that direction suits you.
This issue originated with AI: Claude, Anthropic's AI model, found the bug while reviewing a patch for App Dev For All, and wrote this report. Contact: [email protected]
Activity
marcobambini commentedon Nov 13, 2026
Fixed in 1.4.2, released a few minutes ago. Thank you for the report — the diagnosis was right in every part, and the
sqlite3_stmt_busy()direction you proposed is what the fix is built on. No need for the pull request you offered; it went in with the release.Confirmed as described
Reproduced on Linux glibc arm64 and, worth adding, on macOS arm64 too — it is not specific to x86_64 Linux. A matrix of ten ways to drop a result set, each case in a process of its own, matched your cut-down conditions exactly: the allocating
finalis needed, afinalthat only returnsnis clean,toArray()andnext()to the end are clean, and an aggregate withGROUP BYdoes not fire, with one row per group or three.Two things to add to the report:
There is a second crash site. When the result set is cyclic garbage, so the collector frees it rather than the reference count, the use after free lands in
JS_FreeValueRT(quickjs.c:16886, insidegc_free_cycles) rather than infree_object. Same root cause, but a fix that only covered the refcount path would have missed it.It does not need a sanitizer. With no instrumentation and
MALLOC_PERTURB_=165, 60 turns of the loop are enough: SIGSEGV for the plain case, SIGABRT with glibc's "double free or corruption" for the cyclic one.And a second bug alongside it
Chasing the close path turned up that a result set JavaScript keeps, in a global, leaks the whole connection: its statement stays open, so
sqlite3_close()returns SQLITE_BUSY and never closes, andsqlite3_close_v2()leaves a zombie for good — only closing frees the runtime, and only freeing the runtime frees the result set that holds the statement. About 63 KB of SQLite memory per connection, plus the runtime's own. Both are now fixed together, since fixing one without the other leaves the suite's memory check failing.The fix
A statement that is not busy holds no aggregate or window state, so finalizing it from the class finalizer cannot come back into JavaScript and still happens there. A busy one is left on the connection's list and ended from
js_end_rowsets(), which runs where JavaScript may run: when the call into JavaScript returns, and at the top ofdb.exec.That second point is the one thing testing added to the design. With the drain only at the outermost return, your own 20,000-iteration reproducer runs out of memory at about 2,000: the whole loop is inside one
js_eval, so every dropped statement waits for it to return.db.execis a safe point that a loop like that passes through, which bounds it.js_end_rowsets()now also ends every result set still open when the call returns, not only on an interrupted connection, which is what closes the leak. That changes behavior: reading a result set after the call that created it has returned now throws, wherenext()reported the end of its rows. Keeping one across calls never worked as it looked — it held a read transaction open, kept an interrupt in effect until the connection closed, and leaked the connection. It is in the 1.4.2 changelog under Changed, and the README now states the rule.Tested
A new Result set lifetime test drops a result set computing a window function 200 times, by reference count and as a cycle, then keeps one in a global and checks that
next(),toArray(),get()andname()all throw, that one read to its end still reports the end of its rows, and thatsqlite3_close()then closes. On the previous main it crashes the process.The suite passes 16 of 16 on macOS arm64, Linux glibc and musl in arm64 and x86_64, Windows and Android, and under AddressSanitizer and UndefinedBehaviorSanitizer; your reproducer passes at 20,000 iterations both sanitized and plain; no leaks under ASan leak detection.
Reviewed, fixed and tested with Claude, Anthropic's AI model.
fix: do not let a db.exec result set outlive the call that created it