Skip to content

Keep the JavaScript stack size within the thread's stack - #17

Merged
marcobambini merged 2 commits into
sqliteai:mainfrom
davidschachterADFA:keep-stack-size-within-thread-stack
Nov 12, 2026
Merged

marcobambini merged 2 commits into
sqliteai:mainfrom
davidschachterADFA:keep-stack-size-within-thread-stack

Conversation

@davidschachterADFA

Copy link
Copy Markdown
Contributor

QuickJS stops code that calls itself too deeply when the stack falls below a limit it computes from the size it was given. It trusts that size, so a size larger than the thread's stack never trips the check, and code that calls itself without end crashes the process instead of failing with "Maximum call stack size exceeded".

js_set_max_stack_size() passes its argument to JS_SetMaxStackSize() unchecked, through sqlite3_value_int(). Text such as '1MB' or 'abc' reads as 1 or 0, and 0 turns the check off. A size above the thread's stack also crashes: with 8 MB of stack, SELECT js_set_max_stack_size(16777216); followed by SELECT js_eval('(function f(n){ return f(n+1); })(0)'); segfaults sqlite3. The 1 MB default can be too large by itself. On a thread with 512 KB of stack, the same recursion crashes at the default. Windows gives a main thread 1 MB, and apps often give their threads no more.

This measures the calling thread's stack and keeps a margin, SQLITE_JS_STACK_MARGIN (256 KB), for the native code that runs between two of QuickJS's checks, such as SQLite when JavaScript runs SQL through db.exec. It uses pthread_getattr_np() on Linux and Android, pthread_get_stackaddr_np() and pthread_get_stacksize_np() on Apple platforms, and VirtualQuery() on Windows.

  • js_set_max_stack_size() accepts an integer up to what the stack allows. Its error message names the largest size. Where the stack can't be measured, it allows up to the default.
  • When the extension is loaded, the default is lowered to what the loading thread's stack allows.
  • The stack position is read the way QuickJS reads it, because under AddressSanitizer a local variable lives on a separate stack.
  • 0 still turns the check off, as the 1.3.7 changelog documents for a connection used from several threads, and as test_thread relies on.
  • The README documents the function.

Test: a new Stack size test checks that:

  • endless recursion fails at the default;
  • text, negative, fractional, NULL, BLOB and too-large sizes are errors;
  • endless recursion, also through db.exec, fails cleanly just below the largest size allowed and at a smaller one;
  • 0 is still accepted.

It fails without this change. make test passes on x86_64 Linux, also under ASan and UBSan, and the extension builds for Android (arm64 and armv7, NDK r29). The Apple and Windows branches are written to each platform's documented API but untested: I had no such machine.

This is a seventh pull request, after #11 to #16, and independent of them. Like each of those, it adds the test helpers test_open() and check_error() at the same place in test/main.c, so whichever merges later needs a small rebase, which we will do.

This pull request originated with AI. Claude, Anthropic's AI model, wrote the code, the tests and this description while packaging sqlite-js for Code on the Go, App Dev For All's Android IDE, which ships sqlite-js with this change. Contact: [email protected]

🤖 Generated with Claude Code

https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw

davidschachterADFA and others added 2 commits November 11, 2026 11:53
QuickJS stops code that calls itself too deeply when the stack falls
below a limit it computes from the size it was given. It trusts that
size, so a size larger than the thread's stack never trips the check,
and code that calls itself without end crashes the process instead of
failing with "Maximum call stack size exceeded".

js_set_max_stack_size() passed its argument to JS_SetMaxStackSize()
unchecked, through sqlite3_value_int(): text such as '1MB' or 'abc'
read as 1 or 0, and a size above the thread's stack, such as 16 MB on
a thread with 8 MB, crashed sqlite3 on endless recursion. The 1 MB
default could itself be too large: on a thread with 512 KB of stack,
endless recursion crashed at the default, and Windows gives a main
thread 1 MB, apps often their threads no more.

Measure the calling thread's stack (pthread_getattr_np() on Linux and
Android, pthread_get_stackaddr_np() and pthread_get_stacksize_np() on
Apple platforms, VirtualQuery() on Windows) and keep a margin,
SQLITE_JS_STACK_MARGIN (256 KB), for the native code that runs between
two of QuickJS's checks, such as SQLite when JavaScript runs SQL
through db.exec. js_set_max_stack_size() now accepts an integer up to
what the stack allows, and reports the largest size in its error
message; elsewhere it allows up to the default. When the extension is
loaded, the default is lowered to what the loading thread's stack
allows. The stack position is read the way QuickJS reads it, because
under AddressSanitizer a local variable lives on a separate stack.

0 still turns the check off, as the 1.3.7 changelog documents for a
connection used from several threads, and test_thread relies on.

Add a Stack size test: endless recursion fails at the default, invalid
sizes are errors, and endless recursion, also through db.exec, fails
cleanly just below the largest size allowed and at a smaller one. It
fails without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
Whether an SQL error in db.exec() reaches next() as false, as now, or
as an exception, as a separate pull request proposes, the recursion
ends with the same "stopped" error, so the test passes either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
marcobambini added a commit that referenced this pull request Nov 12, 2026
PR #17's test calls strtoll(); with no <stdlib.h> that is an implicit
declaration, which clang rejects, so test/main.c did not build on macOS.
@marcobambini
marcobambini merged commit 0a5f776 into sqliteai:main Nov 12, 2026
@marcobambini

Copy link
Copy Markdown
Member

Merged into main as part of a review of #11–#19 together, with one portability fix (d167c65).

The Apple branch you could not test works correctly. I verified it on macOS/arm64:

  • main thread: the largest allowed size reports as 8,100,240 bytes — 8 MB minus the 256 KB margin and the current frame, exactly right for macOS;
  • a 512 KB thread: 270,640 bytes;
  • endless recursion fails cleanly with "Maximum call stack size exceeded" on both, including when it recurses through db.exec.

And it does prevent a real crash. With js_stack_room forced to return false, the 512 KB thread case kills the process with SIGBUS (exit 138), because the 1 MB default puts QuickJS's stack_limit below the real stack bottom and the check never fires. That is the bug, reproduced and then fixed.

I checked the implementation against QuickJS too: js_stack_room mirrors js_get_stack_pointer branch for branch (libs/quickjs.c:12116), which is what makes the ASan note in your description correct, and pthread_get_stackaddr_np returning the high address with low = addr - size is right for Apple.

One fix needed on merge: the test calls strtoll with no #include <stdlib.h>. GCC treats that as an implicit declaration; clang rejects it, so test/main.c did not compile on macOS at all. Added the include.

Also worth recording for anyone sizing threads later: on a 512 KB stack, JavaScript recursion tops out between 160 and 320 levels in an optimized build, and between 80 and 160 under ASan. See #19, where that turned out to matter for the test.

Thanks — this one turns a process crash into an error message, which is the right trade.

marcobambini added a commit that referenced this pull request Nov 12, 2026
Two unrelated breakages, on the two platforms the merged PRs were never
built on. CI had not run on the pull requests themselves, so neither showed
up before the merge.

musl (both arches): the extension failed to load at all, with SQLite
reporting "error during initialization:" and no message, which is what it
says when the entry point returns non-OK without setting pzErrMsg.

PR #17's js_stack_room() asks pthread_getattr_np() for the thread's stack.
For the initial thread musl reports only the part of the stack that is
mapped so far -- 132 KB at load time, measured on musl 1.2.6 -- rather than
the 8 MB it may still grow to; glibc reads /proc/self/maps and reports all
of it. Taking the 256 KB margin off 132 KB left zero room, globaljs_init()
then set a stack size of 1 byte, and JS_NewContext() could not create a
context at all, so globaljs_init() returned NULL.

RLIMIT_STACK is how far the initial thread may grow, so it is the bound that
counts there; the thread is recognized by gettid() == getpid(). Both libcs
now measure the same stack, 8,123,840 on musl against 8,123,808 on glibc.

The fallback was the worse half of the bug: a measurement that leaves no
room must not cripple the runtime. QuickJS reads a size of 0 as "no check at
all" and cannot create a context below about 16 KB (measured: 4 KB fails,
16 KB works), so a stack smaller than twice the margin is now split rather
than reported as no room, and anything under SQLITE_JS_STACK_MIN is treated
as no measurement, leaving the default alone. Missing a runaway recursion is
the lesser evil next to an extension that cannot load. A thread with a
64 KB stack now loads the extension, runs JavaScript, and still stops
endless recursion with an error.

Windows: PR #11's test called alarm(30) to avoid hanging forever if
JavaScript cannot be interrupted. alarm() is POSIX only and mingw does not
declare it, so test/main.c did not compile. Replaced with a watchdog thread,
using the usleep() and pthreads the test already relies on there; verified
that it still fires, and aborts with a clear message, when the interrupt
handler is removed.

Verified green on macOS/arm64, Alpine musl, Debian glibc and under
ASan + UBSan: 15/15 sections, no leaks, no sanitizer reports, and no new
warnings from sqlitejs.c on either arch.

Co-Authored-By: Claude Opus 5 <[email protected]>
@marcobambini

Copy link
Copy Markdown
Member

Follow-up: this broke the build on musl after merge, fixed in c8ae85a. Worth reading, because the cause is interesting and it affects the Android target you care about.

Both musl jobs failed with SQLite reporting error during initialization: and no message — its wording for an entry point returning non-OK without setting pzErrMsg, i.e. globaljs_init() returned NULL. I reproduced it in Alpine and traced it:

pthread_getattr_np() does not mean the same thing on musl. For the initial thread musl reports only the part of the stack that is currently mapped — 132 KB at extension-load time on musl 1.2.6 — not the 8 MB it may still grow to. glibc reads /proc/self/maps and reports the whole stack, which is why only musl broke.

pthread_attr_getstack -> size=135168 (132 KB)
sp - low = 129 KB
room after the 256 KB margin = 0

With room == 0, globaljs_init() ran JS_SetMaxStackSize(rt, 1), and JS_NewContext() cannot create a context with a 1-byte stack, so the extension failed to load outright.

Two fixes:

  1. Measure the initial thread with RLIMIT_STACK, which is how far it may actually grow, detected by gettid() == getpid(). Created threads are unaffected, since musl reports those correctly. Both libcs now agree: 8,123,840 on musl against 8,123,808 on glibc.

  2. The fallback must not cripple the runtime — this was the worse half. QuickJS reads 0 as "no check at all" and cannot create a context below about 16 KB (I measured: 4 KB fails, 16 KB works). So a stack smaller than twice the margin is now split rather than reported as no room, and anything under a 32 KB floor is treated as no measurement, leaving the default alone. Missing a runaway recursion is the lesser evil next to an extension that cannot load. A thread with a 64 KB stack now loads the extension, runs JavaScript, and still stops endless recursion with an error — there is a new test for exactly that case.

This also means the Windows branch is safer: if VirtualQuery ever reports something odd there, it degrades instead of bricking the extension.

My earlier comment said I had verified the measurement — that was true for Apple, but I only tested glibc on the Linux side, and CI had never run on the PR. That is on me, not on you. The approach is sound and the crash it prevents is real; pthread_getattr_np just does not promise what glibc happens to deliver.

CI is green on all 15 jobs now, musl x86_64 and arm64 included.

@davidschachterADFA

Copy link
Copy Markdown
Contributor Author

Thank you for testing the Apple branch, and for adding the include that clang needed.

This reply originated with AI: Claude, Anthropic's AI model, wrote it for App Dev For All. Contact: [email protected]

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