Repository navigation
Keep the JavaScript stack size within the thread's stack - #17
marcobambini merged 2 commits into
Conversation
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
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.
|
Merged into The Apple branch you could not test works correctly. I verified it on macOS/arm64:
And it does prevent a real crash. With I checked the implementation against QuickJS too: One fix needed on merge: the test calls 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. |
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]>
|
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
With Two fixes:
This also means the Windows branch is safer: if 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; CI is green on all 15 jobs now, musl x86_64 and arm64 included. |
|
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] |
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 toJS_SetMaxStackSize()unchecked, throughsqlite3_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 bySELECT js_eval('(function f(n){ return f(n+1); })(0)');segfaultssqlite3. 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 throughdb.exec. It usespthread_getattr_np()on Linux and Android,pthread_get_stackaddr_np()andpthread_get_stacksize_np()on Apple platforms, andVirtualQuery()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.test_threadrelies on.Test: a new Stack size test checks that:
db.exec, fails cleanly just below the largest size allowed and at a smaller one;It fails without this change.
make testpasses 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()andcheck_error()at the same place intest/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