From d89431e96acdb313fb1d1105589e12f1f920fe6d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 17:08:11 -0800 Subject: [PATCH 001/203] ADFA-7082: Vendor sqlite-js 1.3.7 with our patches sqlite-js 1.3.7 (Apache-2.0, with QuickJS/quickjs-ng amalgamated in libs/quickjs.c, MIT), only the files the AAR build uses, with patches/ applied: 0001-0008 are the Termux package's (terminal-packages packages/sqlite-js), 0009 makes each call measure its own thread's stack, and 0010 adds sqlitejs_cancel_all(). 0001-0009 are sent upstream as sqliteai/sqlite-js #11-#19. vendor.sh rebuilds upstream/ and the license notices from the release (checked against its SHA-256) and patches/, or with --check tells whether they match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...t-when-the-connection-is-interrupted.patch | 172 + ...the-memory-of-the-JavaScript-runtime.patch | 277 + ...ions-that-run-code-out-of-the-schema.patch | 148 + ...rayBuffers-and-typed-arrays-as-BLOBs.patch | 247 + ...005-Return-whole-numbers-as-INTEGERs.patch | 164 + ...s-thrown-by-aggregate-and-window-ste.patch | 96 + ...ipt-stack-size-within-the-thread-s-s.patch | 276 + ...-SQL-errors-from-db.exec-result-sets.patch | 161 + ...tack-of-the-thread-each-call-runs-on.patch | 411 + ...e-host-cancel-all-running-JavaScript.patch | 183 + .../resources/META-INF/LICENSE-quickjs.txt | 33 + .../resources/META-INF/LICENSE-sqlite-js.txt | 201 + subprojects/sqlite-js/upstream/LICENSE | 201 + .../sqlite-js/upstream/LICENSE.quickjs | 33 + .../sqlite-js/upstream/libs/quickjs-libc.h | 79 + subprojects/sqlite-js/upstream/libs/quickjs.c | 82922 ++++++++++++++++ subprojects/sqlite-js/upstream/libs/quickjs.h | 1405 + subprojects/sqlite-js/upstream/libs/sqlite3.h | 13715 +++ .../sqlite-js/upstream/libs/sqlite3ext.h | 719 + subprojects/sqlite-js/upstream/src/sqlitejs.c | 1666 + subprojects/sqlite-js/upstream/src/sqlitejs.h | 26 + subprojects/sqlite-js/vendor.sh | 49 + 22 files changed, 103184 insertions(+) create mode 100644 subprojects/sqlite-js/patches/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch create mode 100644 subprojects/sqlite-js/patches/0002-Limit-the-memory-of-the-JavaScript-runtime.patch create mode 100644 subprojects/sqlite-js/patches/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch create mode 100644 subprojects/sqlite-js/patches/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch create mode 100644 subprojects/sqlite-js/patches/0005-Return-whole-numbers-as-INTEGERs.patch create mode 100644 subprojects/sqlite-js/patches/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch create mode 100644 subprojects/sqlite-js/patches/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch create mode 100644 subprojects/sqlite-js/patches/0008-Report-SQL-errors-from-db.exec-result-sets.patch create mode 100644 subprojects/sqlite-js/patches/0009-Measure-the-stack-of-the-thread-each-call-runs-on.patch create mode 100644 subprojects/sqlite-js/patches/0010-Let-the-host-cancel-all-running-JavaScript.patch create mode 100644 subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-quickjs.txt create mode 100644 subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-sqlite-js.txt create mode 100644 subprojects/sqlite-js/upstream/LICENSE create mode 100644 subprojects/sqlite-js/upstream/LICENSE.quickjs create mode 100644 subprojects/sqlite-js/upstream/libs/quickjs-libc.h create mode 100644 subprojects/sqlite-js/upstream/libs/quickjs.c create mode 100644 subprojects/sqlite-js/upstream/libs/quickjs.h create mode 100644 subprojects/sqlite-js/upstream/libs/sqlite3.h create mode 100644 subprojects/sqlite-js/upstream/libs/sqlite3ext.h create mode 100644 subprojects/sqlite-js/upstream/src/sqlitejs.c create mode 100644 subprojects/sqlite-js/upstream/src/sqlitejs.h create mode 100755 subprojects/sqlite-js/vendor.sh diff --git a/subprojects/sqlite-js/patches/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch b/subprojects/sqlite-js/patches/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch new file mode 100644 index 0000000000..8c3a68afa8 --- /dev/null +++ b/subprojects/sqlite-js/patches/0001-Stop-JavaScript-when-the-connection-is-interrupted.patch @@ -0,0 +1,172 @@ +From 8704591e47af9f9ac685c3e9e62f73ec3b106592 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 20:56:10 -0800 +Subject: [PATCH 01/10] Stop JavaScript when the connection is interrupted + +JavaScript runs inside the SQL statement that calls it, but QuickJS had +no interrupt handler, so sqlite3_interrupt() could not stop code that +never returns to SQLite. `SELECT js_eval('while (true) {}')` hung the +sqlite3 shell, where Ctrl-C calls sqlite3_interrupt(), and an app could +not cancel the query. + +Install a QuickJS interrupt handler that reports the connection's +sqlite3_is_interrupted(). QuickJS then stops the code with an +uncatchable "interrupted" error, and the statement fails as interrupted. +sqlite3_is_interrupted() is new in SQLite 3.41.0, so the handler is only +installed when the library is at least that version. + +Add an Interrupt test that interrupts endless loops in js_eval() and in a +scalar function from another thread, and checks that the connection +still works afterwards. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 4 +++ + src/sqlitejs.c | 15 ++++++++++- + test/main.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 85 insertions(+), 1 deletion(-) + +diff --git a/README.md b/README.md +index e389272..45bf583 100644 +--- a/README.md ++++ b/README.md +@@ -410,6 +410,10 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB + ``` + ++### Interrupting JavaScript ++ ++JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. ++ + ## Examples + + ### Example 1: String Manipulation +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 024a2f8..524581e 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -187,6 +187,15 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + + // MARK: - Initializer - + ++// QuickJS calls this from time to time while it runs code. A non-zero result stops the code ++// with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, ++// a cancelled query in an app) also stops JavaScript that never returns to SQLite. ++static int js_interrupt_handler (JSRuntime *rt, void *opaque) { ++ UNUSED(rt); ++ globaljs_context *js = (globaljs_context *)opaque; ++ return (js->db != NULL) && sqlite3_is_interrupted(js->db); ++} ++ + static globaljs_context *globaljs_init (sqlite3 *db) { + JSRuntime *rt = NULL; + JSContext *ctx = NULL; +@@ -200,7 +209,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + + //JS_SetMemoryLimit(rt, 80 * 1024); + //JS_SetMaxStackSize(rt, 10 * 1024); +- ++ ++ // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry ++ // in its sqlite3_api_routines, so JavaScript cannot be interrupted there ++ if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); ++ + js_std_init_handlers(rt); + JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); + +diff --git a/test/main.c b/test/main.c +index d0ed2e7..0f8da0c 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + + #define DB_PATH "js_functions.sqlite" + #define VERBOSE 1 +@@ -488,6 +489,71 @@ abort_test: + return rc; + } + ++// MARK: - Interrupt - ++ ++int test_open (sqlite3 **db) { ++ int rc = sqlite3_open(":memory:", db); ++ if (rc != SQLITE_OK) return rc; ++ ++ #if JS_LOAD_EMBEDDED ++ return sqlite3_js_init(*db, NULL, NULL); ++ #else ++ rc = sqlite3_enable_load_extension(*db, 1); ++ if (rc != SQLITE_OK) return rc; ++ return db_exec(*db, "SELECT load_extension('./dist/js');"); ++ #endif ++} ++ ++void *test_interrupt_worker (void *ptr) { ++ // give the statement time to start running JavaScript ++ usleep(200 * 1000); ++ sqlite3_interrupt((sqlite3 *)ptr); ++ return NULL; ++} ++ ++// Runs sql, which never ends unless it is interrupted, and interrupts it from another thread. ++// The statement must fail as interrupted, and the connection must stay usable. ++int test_interrupt_sql (sqlite3 *db, const char *sql) { ++ pthread_t thread; ++ if (pthread_create(&thread, NULL, test_interrupt_worker, (void *)db) != 0) return SQLITE_ERROR; ++ int rc = sqlite3_exec(db, sql, NULL, NULL, NULL); ++ pthread_join(thread, NULL); ++ ++ if (rc == SQLITE_OK || strstr(sqlite3_errmsg(db), "interrupted") == NULL) { ++ printf("FAIL: %s\n Expected: interrupted, Got: %d %s\n", sql, rc, sqlite3_errmsg(db)); ++ return SQLITE_ERROR; ++ } ++ return check_query(db, "SELECT js_eval('1+1');", "2"); ++} ++ ++int test_interrupt (void) { ++ sqlite3 *db = NULL; ++ ++ // if the code cannot be interrupted, end the test program instead of hanging forever ++ alarm(30); ++ ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = test_interrupt_sql(db, "SELECT js_eval('while (true) {}');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "SELECT js_create_scalar('forever', '(function(args){ for (;;) {} })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = test_interrupt_sql(db, "SELECT forever();"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // JavaScript catch blocks cannot keep running code alive ++ rc = test_interrupt_sql(db, "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ alarm(0); ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -504,6 +570,7 @@ int main (void) { + result += test_report("Serialization 2", test_serialization(DB_PATH, false, 2)); // update functions previously registered in the js_functions table + result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations + result += test_report("Thread", test_thread()); ++ result += test_report("Interrupt", test_interrupt()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0002-Limit-the-memory-of-the-JavaScript-runtime.patch b/subprojects/sqlite-js/patches/0002-Limit-the-memory-of-the-JavaScript-runtime.patch new file mode 100644 index 0000000000..91d5a16df0 --- /dev/null +++ b/subprojects/sqlite-js/patches/0002-Limit-the-memory-of-the-JavaScript-runtime.patch @@ -0,0 +1,277 @@ +From e530beb47807093059d4de4c1ce3bc6cf3def417 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 20:58:13 -0800 +Subject: [PATCH 02/10] Limit the memory of the JavaScript runtime + +The JavaScript runtime had no memory limit (the JS_SetMemoryLimit call +was commented out), so code that keeps allocating took all the memory of +the process. On a phone that ends with the operating system killing the +process, which in an app takes the app down with it. + +Set a default limit of 64 MB per connection, which SQLITE_JS_DEFAULT_ +MEMORY_LIMIT changes at build time, and add js_set_memory_limit(bytes) +to change it at run time; 0 means no limit, as in JS_SetMemoryLimit(). +Code that needs more fails with an "out of memory" error, and the +connection stays usable. A QuickJS context takes about 54 KB, so the +default leaves room for over a thousand aggregate contexts at once. + +QuickJS cannot always recover from running out of memory while it +creates a context: it can crash. So the limit is set once the +connection's context exists, and the context of each aggregate or +window function, and the trial one that js_create_aggregate() and +js_create_window() make, is created with the limit lifted; the limit +then applies again to the code that runs in it. + +Add a Memory limit test: allocations under and over the default, code +that never stops allocating, raising, removing and lowering the limit, +and invalid arguments. It also creates and runs an aggregate under +small limits and with little memory left, which crashed while QuickJS +created its context under the limit. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 9 +++++ + src/sqlitejs.c | 53 +++++++++++++++++++++++----- + test/main.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 147 insertions(+), 9 deletions(-) + +diff --git a/README.md b/README.md +index 45bf583..52efd7b 100644 +--- a/README.md ++++ b/README.md +@@ -410,6 +410,15 @@ Configures the maximum stack size (in bytes) for the JavaScript engine. + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB + ``` + ++### js_set_memory_limit ++ ++Sets the most memory, in bytes, that JavaScript may allocate on this connection; 0 means no limit. The default is 64 MB (64 × 1024 × 1024 bytes); build with `-DSQLITE_JS_DEFAULT_MEMORY_LIMIT=bytes` to change it. Code that needs more fails with an "out of memory" error, and the connection stays usable. ++ ++```sql ++SELECT js_set_memory_limit(268435456); -- Allow 256 MB ++SELECT js_set_memory_limit(0); -- No limit ++``` ++ + ### Interrupting JavaScript + + JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 524581e..6f00635 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -31,6 +31,7 @@ typedef struct { + sqlite3 *db; + JSClassID rowSetClassID; + int ref_count; ++ size_t memory_limit; // in bytes, 0 for none: see js_set_memory_limit() + } globaljs_context; + + typedef struct { +@@ -187,6 +188,14 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + + // MARK: - Initializer - + ++// The most memory, in bytes, the JavaScript runtime of a connection may allocate until ++// js_set_memory_limit() changes it; 0 means no limit. Without a limit, code that keeps ++// allocating takes all the memory of the process, which on a phone ends with the operating ++// system killing it. 64 MB is room for over a thousand aggregate contexts (about 54 KB each). ++#ifndef SQLITE_JS_DEFAULT_MEMORY_LIMIT ++#define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) ++#endif ++ + // QuickJS calls this from time to time while it runs code. A non-zero result stops the code + // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, + // a cancelled query in an app) also stops JavaScript that never returns to SQLite. +@@ -228,7 +237,12 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + JS_SetContextOpaque(ctx, js); + JS_SetRuntimeOpaque(rt, js); + js_global_init(ctx, js); +- ++ ++ // set only now: QuickJS cannot always recover from running out of memory while it creates ++ // a context (see js_setup_aggregate) ++ js->memory_limit = SQLITE_JS_DEFAULT_MEMORY_LIMIT; ++ JS_SetMemoryLimit(rt, js->memory_limit); ++ + return js; + + abort_init: +@@ -655,16 +669,22 @@ static bool js_setup_aggregate (sqlite3_context *context, globaljs_context *js, + } + + // create a separate context for testing purpose ++ // QuickJS cannot always recover from running out of memory while it creates a context: it ++ // can crash. So the context is created without the memory limit (it takes about 54 KB), ++ // which then applies again to the code that runs in it. ++ JS_SetMemoryLimit(js->runtime, 0); + JSContext *ctx = JS_NewContext(js->runtime); ++ if (ctx) { ++ // setup global object ++ JS_SetContextOpaque(ctx, js); ++ js_global_init(ctx, js); ++ } ++ JS_SetMemoryLimit(js->runtime, js->memory_limit); + if (!ctx) { + sqlite3_result_error(context, "Unable to create a JS context.", -1); + return false; + } +- +- // setup global object +- JS_SetContextOpaque(ctx, js); +- js_global_init(ctx, js); +- ++ + // init code is optional + if (init_code) { + JSValue init_result = JS_Eval(ctx, init_code, strlen(init_code), NULL, JS_EVAL_TYPE_GLOBAL); +@@ -1305,6 +1325,21 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + JS_SetMaxStackSize(js->runtime, stack_size); + } + ++void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { ++ UNUSED(argc); ++ globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); ++ ++ if ((sqlite3_value_type(argv[0]) != SQLITE_INTEGER) || (sqlite3_value_int64(argv[0]) < 0)) { ++ sqlite3_result_error(context, "The memory limit must be an integer number of bytes, or 0 for no limit", -1); ++ return; ++ } ++ ++ // a limit beyond the address space (on a 32-bit system) can never be reached, so it is no limit ++ sqlite3_uint64 limit = (sqlite3_uint64)sqlite3_value_int64(argv[0]); ++ js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; ++ JS_SetMemoryLimit(js->runtime, js->memory_limit); ++} ++ + // MARK: - + + const char *sqlitejs_version (void) { +@@ -1325,9 +1360,9 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r + globaljs_context *js = globaljs_init(db); + if (!js) return SQLITE_NOMEM; + +- const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size"}; +- const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size}; +- int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1}; ++ const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; ++ const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; ++ int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; + + size_t f_count = sizeof(f_name) / sizeof(const char *); + for (size_t i=0; i x * 2).join()');", "2,4,6"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a higher limit, then no limit ++ rc = db_exec(db, "SELECT js_set_memory_limit(256 * 1024 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');", "134217728"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_set_memory_limit(0);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(128 * 1024 * 1024).byteLength');", "134217728"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a lower limit ++ rc = db_exec(db, "SELECT js_set_memory_limit(8 * 1024 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');", "out of memory"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // only a non-negative integer is a limit ++ const char *invalid[] = {"-1", "1.5", "'1000000'", "NULL", "x'00'"}; ++ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { ++ char sql[128]; ++ snprintf(sql, sizeof(sql), "SELECT js_set_memory_limit(%s);", invalid[i]); ++ rc = check_error(db, sql, "The memory limit must be an integer number of bytes"); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++ // aggregates fail cleanly near the limit: under small limits, and with little memory left ++ for (int kb = 100; kb <= 420; kb += 8) { ++ rc = test_aggregate_near_limit(kb, 0); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ for (int kb = 0; kb <= 16; ++kb) { ++ rc = test_aggregate_near_limit(0, kb); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -571,6 +664,7 @@ int main (void) { + result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); ++ result += test_report("Memory limit", test_memory_limit()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch b/subprojects/sqlite-js/patches/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch new file mode 100644 index 0000000000..ef037e0f1e --- /dev/null +++ b/subprojects/sqlite-js/patches/0003-Keep-the-functions-that-run-code-out-of-the-schema.patch @@ -0,0 +1,148 @@ +From 24122de40f992d098f022576b41af596d6e438ac Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 20:59:46 -0800 +Subject: [PATCH 03/10] Keep the functions that run code out of the schema + +js_eval(), js_create_*(), js_load_text(), js_load_blob(), js_init_table() +and the js_set_* functions were registered without SQLITE_DIRECTONLY, so +a view, trigger, CHECK constraint or generated column could call them. +With PRAGMA trusted_schema ON, the default of the SQLite library (the +sqlite3 shell turns it off), a database from an untrusted source could +run JavaScript or read files just by being queried: +`CREATE VIEW v AS SELECT js_eval('...')`. + +Register every function but js_version() with SQLITE_DIRECTONLY, so only +top-level SQL can call them. The functions created with js_create_* are +unchanged, so they still work in views, triggers and indexes. The flag +is computed from the function's name rather than from a table that +parallels the function list, so a function added later gets it without +a matching edit. + +Add a Direct only test: every function but js_version() has the flag in +function_list; with trusted_schema ON, a view, a trigger and a +generated column cannot call js_eval() or js_load_text(), a top-level +statement can, and a view can still use js_version() and a function made +with js_create_scalar(). + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 6 ++++++ + src/sqlitejs.c | 9 +++++++-- + test/main.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 66 insertions(+), 2 deletions(-) + +diff --git a/README.md b/README.md +index 52efd7b..ff51b2f 100644 +--- a/README.md ++++ b/README.md +@@ -419,6 +419,12 @@ SELECT js_set_memory_limit(268435456); -- Allow 256 MB + SELECT js_set_memory_limit(0); -- No limit + ``` + ++### Using the functions from the schema ++ ++Every function above but `js_version` runs JavaScript, reads files or changes the JavaScript runtime, so it is registered with `SQLITE_DIRECTONLY`: only top-level SQL can call it, never a view, trigger, CHECK constraint, generated column or index. That way a database from an untrusted source cannot run JavaScript just by being queried. The functions you create with `js_create_scalar`, `js_create_aggregate`, `js_create_window` and `js_create_collation` are not restricted. ++ ++A database can still store JavaScript in its `js_functions` table, and `js_init_table(1)` runs it. Call it only on databases you trust. ++ + ### Interrupting JavaScript + + JavaScript runs inside the SQL statement that calls it, so `sqlite3_interrupt()` stops it as it stops any statement: the statement fails with an "interrupted" error, even if the code catches exceptions. In the `sqlite3` shell, Ctrl-C does this. Interrupting JavaScript needs SQLite 3.41.0 or later. +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 6f00635..6b48ef2 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -1363,11 +1363,16 @@ APIEXPORT int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_r + const char *f_name[] = {"js_version", "js_version", "js_create_scalar", "js_create_aggregate", "js_create_window", "js_create_collation", "js_eval", "js_load_text", "js_load_blob", "js_init_table", "js_init_table", "js_set_max_stack_size", "js_set_memory_limit"}; + const void *f_ptr[] = {js_version0, js_version1, js_create_scalar, js_create_aggregate, js_create_window, js_create_collation, js_eval, js_load_text, js_load_blob, js_init_table0, js_init_table1, js_set_max_stack_size, js_set_memory_limit}; + int f_arg[] = {0, 1, 2, 4, 6, 2, 1, 1, 1, 0, 1, 1, 1}; +- ++ + size_t f_count = sizeof(f_name) / sizeof(const char *); + for (size_t i=0; iref_count++; +- int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); ++ // Every function but js_version runs JavaScript, reads files or changes the JavaScript ++ // runtime. SQLITE_DIRECTONLY keeps them out of the schema (views, triggers, CHECK ++ // constraints, generated columns, indexes), so that a database from an untrusted source ++ // cannot run JavaScript just by being queried, whatever PRAGMA trusted_schema says. ++ int flags = (strcmp(f_name[i], "js_version") == 0) ? 0 : SQLITE_DIRECTONLY; ++ int rc = sqlite3_create_function_v2(db, f_name[i], f_arg[i], SQLITE_UTF8 | flags, (void *)js, f_ptr[i], NULL, NULL, globaljs_dec_and_free_if_needed); + if (rc != SQLITE_OK) { + if (pzErrMsg) *pzErrMsg = sqlite3_mprintf("Error creating function %s: %s", f_name[i], sqlite3_errmsg(db)); + // sqlite3_create_function_v2 always invokes the xDestroy callback when it fails, +diff --git a/test/main.c b/test/main.c +index 7855bfb..dfa3306 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -647,6 +647,58 @@ abort_test: + return rc; + } + ++// MARK: - Direct only - ++ ++int test_direct_only (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // every function but js_version is SQLITE_DIRECTONLY (0x80000 in the flags of function_list) ++ rc = check_query_v2(db, "SELECT count(*) > 10, sum(((flags & 0x80000) != 0) != (name <> 'js_version')) FROM pragma_function_list WHERE name LIKE 'js\\_%' ESCAPE '\\';", (const char*[]){"1", "0"}, 2); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // trusted_schema ON lets the schema use any function that is not SQLITE_DIRECTONLY ++ rc = db_exec(db, "PRAGMA trusted_schema = ON; CREATE TABLE t (a); CREATE TABLE log (msg);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a view, a trigger and a generated column cannot run JavaScript or read files ++ // (SQLite reports these either when the schema is created or when it is used) ++ sqlite3_exec(db, "CREATE VIEW v_eval AS SELECT js_eval('6 * 7') AS x;", NULL, NULL, NULL); ++ rc = check_error(db, "SELECT x FROM v_eval;", "unsafe use of js_eval()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "CREATE VIEW v_load AS SELECT js_load_text('/etc/hosts') AS x;", NULL, NULL, NULL); ++ rc = check_error(db, "SELECT x FROM v_load;", "unsafe use of js_load_text()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "CREATE TRIGGER t_insert AFTER INSERT ON t BEGIN INSERT INTO log VALUES (js_eval('\"trigger ran\"')); END;", NULL, NULL, NULL); ++ rc = check_error(db, "INSERT INTO t VALUES (1);", "unsafe use of js_eval()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT count(*) FROM log;", "0"); ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_exec(db, "DROP TRIGGER IF EXISTS t_insert;", NULL, NULL, NULL); ++ if (sqlite3_exec(db, "CREATE TABLE g (a, b AS (js_eval('1')));", NULL, NULL, NULL) == SQLITE_OK) { ++ rc = check_error(db, "INSERT INTO g (a) VALUES (1);", "unsafe use of js_eval()"); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++ // a top-level statement can still use them ++ rc = check_query(db, "SELECT js_eval('6 * 7');", "42"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // and the schema can still use js_version() and the functions created with js_create_* ++ rc = db_exec(db, "SELECT js_create_scalar('twice', '(function(args){ return args[0] * 2; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "CREATE VIEW v_ok AS SELECT js_version() IS NOT NULL AS has_version, twice(21) AS answer;"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query_v2(db, "SELECT has_version, answer FROM v_ok;", (const char*[]){"1", "42"}, 2); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -665,6 +717,7 @@ int main (void) { + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); ++ result += test_report("Direct only", test_direct_only()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch b/subprojects/sqlite-js/patches/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch new file mode 100644 index 0000000000..0a7357b1c1 --- /dev/null +++ b/subprojects/sqlite-js/patches/0004-Return-ArrayBuffers-and-typed-arrays-as-BLOBs.patch @@ -0,0 +1,247 @@ +From 7695849c414c04fd6b237a6a50325c43402ddfbf Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 21:01:52 -0800 +Subject: [PATCH 04/10] Return ArrayBuffers and typed arrays as BLOBs + +A BLOB argument reaches JavaScript as an ArrayBuffer, but a function +that returned an ArrayBuffer, or a typed array such as Uint8Array, gave +NULL: js_value_to_sqlite() turned every object into NULL. So no function +could return binary data, and `identity(x'00ff')` with +`(function(args){ return args[0]; })` returned NULL. db.exec() bound an +ArrayBuffer but not a typed array, and bound an empty ArrayBuffer as +NULL. + +Add js_get_bytes(), which gets the bytes of an ArrayBuffer or of the part +of a buffer that a typed array views, and use it for function results and +for db.exec() parameters. An empty buffer is an empty BLOB. Returning a +detached buffer is an error; binding one still binds NULL, as before. +A typed array's offset and length come from its byteOffset and +byteLength getters, read before its bytes: one that tracks the length +of a resizable buffer keeps the length QuickJS recorded when it was +made, which goes stale when the buffer is resized, and reading it +after a shrink would read past the buffer. A typed array of fixed +length that its shrunken buffer no longer holds is an error. +Document how values convert in both directions in the README. + +Add a Blobs test: BLOBs round-trip through a function, typed arrays, +subarrays and ArrayBuffers made in JavaScript become BLOBs, a function +can build a BLOB from a BLOB, a detached buffer is an error, and +db.exec() binds typed arrays and empty buffers as BLOBs. It also checks +typed arrays over resizable buffers that shrink and grow. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 13 ++++++++ + src/sqlitejs.c | 82 +++++++++++++++++++++++++++++++++++++++++++++----- + test/main.c | 50 ++++++++++++++++++++++++++++++ + 3 files changed, 138 insertions(+), 7 deletions(-) + +diff --git a/README.md b/README.md +index ff51b2f..99abfb9 100644 +--- a/README.md ++++ b/README.md +@@ -176,6 +176,19 @@ SQLite-JS provides several ways to extend SQLite functionality with JavaScript: + | Collation Sequences | Define custom sort orders for text values | + | JavaScript Evaluation | Directly evaluate JavaScript code within SQLite | + ++### Values ++ ++SQL values reach JavaScript as follows: ++ ++| SQL | JavaScript | ++|-----|------------| ++| NULL | `null` | ++| INTEGER, REAL | number | ++| TEXT | string | ++| BLOB | `ArrayBuffer` | ++ ++A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number in the 32-bit range and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. ++ + ## Scalar Functions + + Scalar functions process one row at a time and return a single value. They are useful for data transformation, calculations, text manipulation, etc. +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 6b48ef2..cb4d75d 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -372,6 +372,56 @@ static void functionjs_free (functionjs_context *fctx) { + + // MARK: - Utils - + ++// Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such ++// as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an ++// ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be ++// NULL when *psize is 0), 0 if it is not, and -1 with a pending JavaScript exception if its ++// buffer is detached or the typed array is out of its bounds. ++static int js_get_bytes (JSContext *ctx, JSValueConst value, const uint8_t **pbytes, size_t *psize) { ++ *pbytes = NULL; ++ *psize = 0; ++ ++ if (JS_IsArrayBuffer(value)) { ++ uint8_t *buf = JS_GetArrayBuffer(ctx, psize, value); ++ if (!buf && JS_HasException(ctx)) return -1; ++ *pbytes = buf; ++ return 1; ++ } ++ ++ if (JS_GetTypedArrayType(value) >= 0) { ++ // The offset and length come from the byteOffset and byteLength getters: a typed array ++ // can track the length of a resizable buffer, and the length QuickJS records when the ++ // array is made goes stale when the buffer is resized. They are read before the bytes, ++ // because a getter can run JavaScript, which could resize or detach the buffer. ++ int64_t offset = 0, length = 0; ++ JSValue prop = JS_GetPropertyStr(ctx, value, "byteOffset"); ++ int rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &offset, prop); ++ JS_FreeValue(ctx, prop); ++ if (rc < 0) return -1; ++ prop = JS_GetPropertyStr(ctx, value, "byteLength"); ++ rc = JS_IsException(prop) ? -1 : JS_ToInt64(ctx, &length, prop); ++ JS_FreeValue(ctx, prop); ++ if (rc < 0) return -1; ++ ++ size_t size = 0; ++ JSValue buffer = JS_GetTypedArrayBuffer(ctx, value, NULL, NULL, NULL); ++ if (JS_IsException(buffer)) return -1; ++ uint8_t *buf = JS_GetArrayBuffer(ctx, &size, buffer); ++ // the typed array keeps its buffer alive, so buf stays valid ++ JS_FreeValue(ctx, buffer); ++ if (!buf && JS_HasException(ctx)) return -1; ++ if ((offset < 0) || (length < 0) || ((uint64_t)offset > size) || ((uint64_t)length > size - (size_t)offset)) { ++ JS_ThrowRangeError(ctx, "typed array is out of the bounds of its buffer"); ++ return -1; ++ } ++ *pbytes = (buf) ? buf + offset : NULL; ++ *psize = (size_t)length; ++ return 1; ++ } ++ ++ return 0; ++} ++ + static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueConst val) { + if (JS_IsNull(val) || JS_IsUndefined(val)) { + return sqlite3_bind_null(vm, index); +@@ -406,14 +456,18 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo + JS_FreeCString(ctx, str); + return rc; + } +- if (JS_IsArrayBuffer(val)) { +- size_t size = 0; +- uint8_t *buf = JS_GetArrayBuffer(ctx, &size, val); +- if (buf) { +- return sqlite3_bind_blob(vm, index, buf, (int)size, SQLITE_TRANSIENT); +- } ++ const uint8_t *bytes = NULL; ++ size_t size = 0; ++ int is_blob = js_get_bytes(ctx, val, &bytes, &size); ++ if (is_blob < 0) { ++ // a detached buffer has no bytes to bind, so it binds NULL ++ JS_FreeValue(ctx, JS_GetException(ctx)); + return sqlite3_bind_null(vm, index); + } ++ if (is_blob) { ++ if (size == 0) return sqlite3_bind_zeroblob(vm, index, 0); ++ return sqlite3_bind_blob64(vm, index, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); ++ } + return sqlite3_bind_null(vm, index); + } + +@@ -642,11 +696,25 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + return; + } + ++ // handle ArrayBuffer and typed arrays, the forms a BLOB takes in JavaScript ++ const uint8_t *bytes = NULL; ++ size_t size = 0; ++ int is_blob = js_get_bytes(js_ctx, value, &bytes, &size); ++ if (is_blob < 0) { ++ js_error_to_sqlite(context, js_ctx, JS_EXCEPTION, NULL); ++ return; ++ } ++ if (is_blob) { ++ if (size == 0) sqlite3_result_zeroblob(context, 0); ++ else sqlite3_result_blob64(context, bytes, (sqlite3_uint64)size, SQLITE_TRANSIENT); ++ return; ++ } ++ + if (JS_IsObject(value)) { + sqlite3_result_null(context); + return; + } +- ++ + // fallback for unsupported types + sqlite3_result_error(context, "Unsupported JS value type", -1); + } +diff --git a/test/main.c b/test/main.c +index dfa3306..b6c6a8a 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -699,6 +699,55 @@ abort_test: + return rc; + } + ++// MARK: - Blobs - ++ ++int test_blobs (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a BLOB arrives as an ArrayBuffer and goes back as the same BLOB ++ rc = db_exec(db, "SELECT js_create_scalar('identity', '(function(args){ return args[0]; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query_v2(db, "SELECT quote(identity(x'00ff10')), quote(identity(x'')), typeof(identity(zeroblob(3)));", (const char*[]){"X'00FF10'", "X''", "blob"}, 3); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // ArrayBuffers and typed arrays made in JavaScript, including a view of part of a buffer ++ rc = check_query_v2(db, "SELECT quote(js_eval('new Uint8Array([1, 2, 3])')), quote(js_eval('new Uint8Array([1, 2, 3, 4, 5]).subarray(1, 3)')), quote(js_eval('new Uint8Array([7, 8]).buffer')), quote(js_eval('new ArrayBuffer(0)'));", (const char*[]){"X'010203'", "X'0203'", "X'0708'", "X''"}, 4); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a function that makes a BLOB from a BLOB ++ rc = db_exec(db, "SELECT js_create_scalar('reverse_bytes', '(function(args){ return new Uint8Array(args[0]).reverse(); })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT quote(reverse_bytes(x'010203'));", "X'030201'"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a detached buffer has no bytes, so returning it is an error ++ rc = check_error(db, "SELECT js_eval('(function () { const b = new ArrayBuffer(4); b.transfer(); return b; })()');", "detached"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // db.exec() binds them as BLOBs too ++ rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT quote(?), quote(?)\", new Uint8Array([1, 2]), new ArrayBuffer(0)); rs.next(); return rs.get(0) + \" \" + rs.get(1); })()');", "X'0102' X''"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a typed array that tracks the length of a resizable buffer has the buffer's current length, ++ // after the buffer shrinks (by 1 MB, so that reading the old length would read far past it) ++ // or grows ++ rc = check_query_v2(db, "SELECT quote(js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab); u.fill(7); ab.resize(2); return u; })()')), length(js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(1); return u; })()')), length(js_eval('(function () { const ab = new ArrayBuffer(4, { maxByteLength: 16 }); const u = new Uint8Array(ab, 2); ab.resize(16); return u; })()'));", (const char*[]){"X'0707'", "1", "14"}, 3); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(1024 * 1024, { maxByteLength: 1024 * 1024 }); const u = new Uint8Array(ab); ab.resize(3); const rs = db.exec(\"SELECT length(?)\", u); rs.next(); return rs.get(0); })()');", "3"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a typed array of fixed length that a shrunken buffer no longer holds is an error ++ rc = check_error(db, "SELECT js_eval('(function () { const ab = new ArrayBuffer(16, { maxByteLength: 16 }); const u = new Uint8Array(ab, 0, 8); ab.resize(4); return u; })()');", "detached or resized"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -718,6 +767,7 @@ int main (void) { + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); + result += test_report("Direct only", test_direct_only()); ++ result += test_report("Blobs", test_blobs()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0005-Return-whole-numbers-as-INTEGERs.patch b/subprojects/sqlite-js/patches/0005-Return-whole-numbers-as-INTEGERs.patch new file mode 100644 index 0000000000..b4760aef66 --- /dev/null +++ b/subprojects/sqlite-js/patches/0005-Return-whole-numbers-as-INTEGERs.patch @@ -0,0 +1,164 @@ +From d620ccae124cf2dfe3abc67865f300a65b2db0fd Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 21:03:54 -0800 +Subject: [PATCH 05/10] Return whole numbers as INTEGERs + +QuickJS keeps the small whole numbers it can as 32-bit integers, and any +other number as a double, which went back to SQL as a REAL. So an INTEGER +outside the 32-bit range changed type on its way through a function: +`identity(2147483648)` returned 2147483648.0. The result of arithmetic +did too: js_eval('2 + 3') returned the INTEGER 5 but js_eval('2.5 * 2') +the REAL 5.0, and a JavaScript sum of large integers was a REAL. + +Return a number that is a whole number from -(2^53 - 1) to 2^53 - 1 +(Number.isSafeInteger), which a double holds exactly, as an INTEGER, and +any other number as a REAL, for function results and db.exec() +parameters alike. JavaScript cannot tell 3.0 from 3, so a REAL that holds +a whole number now comes back as an INTEGER; the README says so, and how +to pass an INTEGER beyond 2^53 - 1 without losing precision. + +Add a Numbers test: integers in and beyond the 32-bit range round-trip +as INTEGERs, other REALs stay REAL, integers beyond 2^53 - 1 are REALs, +arithmetic results, an aggregate result past the 32-bit range, and +db.exec() parameters. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 4 +++- + src/sqlitejs.c | 19 ++++++++++++++++++- + test/main.c | 43 +++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 64 insertions(+), 2 deletions(-) + +diff --git a/README.md b/README.md +index 99abfb9..d2cf41b 100644 +--- a/README.md ++++ b/README.md +@@ -187,7 +187,9 @@ SQL values reach JavaScript as follows: + | TEXT | string | + | BLOB | `ArrayBuffer` | + +-A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number in the 32-bit range and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. ++A JavaScript result goes back to SQL as follows: `null` and `undefined` become NULL, a boolean an INTEGER (1 or 0), a number an INTEGER if it is a whole number from -(2^53 - 1) to 2^53 - 1 (`Number.isSafeInteger`) and a REAL otherwise, a BigInt an INTEGER, a string TEXT, and an `ArrayBuffer` or a typed array such as `Uint8Array` a BLOB. Other objects become NULL; return `JSON.stringify(value)` to keep one as TEXT. The parameters of `db.exec()` convert the same way. ++ ++JavaScript has a single number type, a double. So a REAL that holds a whole number, such as 3.0, comes back as the INTEGER 3, and an INTEGER beyond ±(2^53 - 1) loses precision in JavaScript: pass it as TEXT, `CAST(x AS TEXT)`, and convert it with `BigInt(args[0])`. + + ## Scalar Functions + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index cb4d75d..c56b241 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + #include "sqlitejs.h" + #include "quickjs.h" + #include "quickjs-libc.h" +@@ -372,6 +373,18 @@ static void functionjs_free (functionjs_context *fctx) { + + // MARK: - Utils - + ++// A JavaScript number is a double. QuickJS keeps the small whole numbers it can as 32-bit ++// integers, but an INTEGER outside that range, or the result of arithmetic such as 2.5 * 2, ++// is a double too. A whole number that a double holds exactly, from -(2^53 - 1) to 2^53 - 1 ++// (Number.isSafeInteger), goes back to SQL as an INTEGER; any other number is a REAL. ++static bool js_number_to_int64 (double num, sqlite3_int64 *out) { ++ const double max_safe_integer = 9007199254740991.0; ++ // NaN fails both comparisons ++ if (!(num >= -max_safe_integer && num <= max_safe_integer) || (num != floor(num))) return false; ++ *out = (sqlite3_int64)num; ++ return true; ++} ++ + // Gets the bytes of an ArrayBuffer, or of the part of an ArrayBuffer that a typed array such + // as a Uint8Array views: the forms a BLOB takes in JavaScript (a BLOB arrives as an + // ArrayBuffer). Returns 1 and sets *pbytes and *psize if value is one of them (*pbytes may be +@@ -434,7 +447,9 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo + return sqlite3_bind_int(vm, index, num); + } else { + double num; ++ sqlite3_int64 inum; + JS_ToFloat64(ctx, &num, val); ++ if (js_number_to_int64(num, &inum)) return sqlite3_bind_int64(vm, index, inum); + return sqlite3_bind_double(vm, index, num); + } + } +@@ -660,8 +675,10 @@ static void js_value_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV + sqlite3_result_int(context, num); + } else { + double num; ++ sqlite3_int64 inum; + JS_ToFloat64(js_ctx, &num, value); +- sqlite3_result_double(context, num); ++ if (js_number_to_int64(num, &inum)) sqlite3_result_int64(context, inum); ++ else sqlite3_result_double(context, num); + } + return; + } +diff --git a/test/main.c b/test/main.c +index b6c6a8a..cb2f899 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -748,6 +748,48 @@ abort_test: + return rc; + } + ++// MARK: - Numbers - ++ ++int test_numbers (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "SELECT js_create_scalar('identity', '(function(args){ return args[0]; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // integers keep their type and value through JavaScript, beyond the 32-bit range too ++ rc = check_query(db, "WITH v(x) AS (VALUES (0), (42), (-7), (2147483647), (2147483648), (-2147483649), (9007199254740991), (-9007199254740991)) SELECT group_concat(typeof(identity(x)) || ' ' || (identity(x) = x), ',') FROM v;", "integer 1,integer 1,integer 1,integer 1,integer 1,integer 1,integer 1,integer 1"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // REALs that are not whole numbers stay REAL; a whole number is an INTEGER, as JavaScript cannot tell 3.0 from 3 ++ rc = check_query_v2(db, "SELECT quote(identity(3.5)), quote(identity(-0.25)), quote(identity(1e300)), quote(identity(3.0));", (const char*[]){"3.5", "-0.25", "1.0e+300", "3"}, 4); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // beyond 2^53 - 1 a double cannot hold every integer, so the result is a REAL ++ rc = check_query(db, "SELECT typeof(identity(9007199254740993));", "real"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // results of arithmetic ++ rc = check_query_v2(db, "SELECT quote(js_eval('2.5 * 2')), quote(js_eval('1e10')), typeof(js_eval('0.1 + 0.2')), typeof(js_eval('NaN'));", (const char*[]){"5", "10000000000", "real", "null"}, 4); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // an aggregate whose result is past the 32-bit range ++ rc = db_exec(db, "SELECT js_create_aggregate('js_sum', 'total = 0;', '(function(args){ total += args[0]; })', '(function(){ return total; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "WITH v(x) AS (VALUES (3000000000), (1)) SELECT typeof(js_sum(x)) || ' ' || js_sum(x) FROM v;", "integer 3000000001"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // db.exec() binds numbers the same way ++ rc = check_query(db, "SELECT js_eval('(function () { const rs = db.exec(\"SELECT typeof(?), typeof(?), typeof(?)\", 2147483648, 2.5 * 2, 2.5); rs.next(); return [rs.get(0), rs.get(1), rs.get(2)].join(); })()');", "integer,integer,real"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -768,6 +810,7 @@ int main (void) { + result += test_report("Memory limit", test_memory_limit()); + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); ++ result += test_report("Numbers", test_numbers()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch b/subprojects/sqlite-js/patches/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch new file mode 100644 index 0000000000..1d8fa43048 --- /dev/null +++ b/subprojects/sqlite-js/patches/0006-Report-exceptions-thrown-by-aggregate-and-window-ste.patch @@ -0,0 +1,96 @@ +From 76cc3a2ad153d623f71a9a5a251340f5c41a3f41 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Tue, 10 Nov 2026 21:16:06 -0800 +Subject: [PATCH 06/10] Report exceptions thrown by aggregate and window steps + +js_execute_common() turned the result of a function into an SQL result +only when the caller wanted the value. The step function of an aggregate +or window function, and the inverse function of a window function, +return nothing, so their result was dropped, and with it any exception +they threw: the aggregate went on as if the row had been added or +removed. A step that threw, or ran out of memory, gave a wrong result +with no error. + +Report an exception thrown by a step or inverse function as an SQL error. +Reported from xStep or xInverse, it makes SQLite abort the statement, +which still calls xFinal, so the aggregate context is released as before. + +Add an Aggregate errors test: an exception in an aggregate step and in a +window inverse function each fail the statement with its message, and the +connection stays usable. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + src/sqlitejs.c | 3 +++ + test/main.c | 33 +++++++++++++++++++++++++++++++++ + 2 files changed, 36 insertions(+) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index c56b241..790dc82 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -896,6 +896,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, + JS_FreeValue(js_context, args); + + if (return_value) js_value_to_sqlite(context, js_context, result); ++ // step and inverse functions return nothing, but an exception they throw is still an error: ++ // reported from xStep or xInverse, it makes SQLite abort the statement ++ else if (JS_IsException(result)) js_error_to_sqlite(context, js_context, result, NULL); + JS_FreeValue(js_context, result); + } + +diff --git a/test/main.c b/test/main.c +index cb2f899..0af4d22 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -790,6 +790,38 @@ abort_test: + return rc; + } + ++// MARK: - Aggregate errors - ++ ++int test_aggregate_errors (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "CREATE TABLE t (x); INSERT INTO t VALUES (1), (2), (3);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // an exception thrown by an aggregate's step function fails the statement ++ rc = db_exec(db, "SELECT js_create_aggregate('step_fails', 'n = 0;', '(function(args){ if (args[0] == 2) throw new Error(\"step boom\"); n++; })', '(function(){ return n; })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT step_fails(x) FROM t;", "step boom"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // so does one thrown by a window function's inverse function ++ rc = db_exec(db, "SELECT js_create_window('inverse_fails', 'total = 0;', '(function(args){ total += args[0]; })', '(function(){ return total; })', '(function(){ return total; })', '(function(args){ throw new Error(\"inverse boom\"); })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT inverse_fails(x) OVER (ORDER BY x ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM t;", "inverse boom"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // and the connection stays usable ++ rc = check_query(db, "SELECT js_eval('[1, 2, 3].join()');", "1,2,3"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - + + int test_report(const char *description, int rc){ +@@ -811,6 +843,7 @@ int main (void) { + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); ++ result += test_report("Aggregate errors", test_aggregate_errors()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch b/subprojects/sqlite-js/patches/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch new file mode 100644 index 0000000000..5bf33015dd --- /dev/null +++ b/subprojects/sqlite-js/patches/0007-Keep-the-JavaScript-stack-size-within-the-thread-s-s.patch @@ -0,0 +1,276 @@ +From b373edbd9fed351c558fbc27da2c5a774c6ae889 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Wed, 11 Nov 2026 11:47:56 -0800 +Subject: [PATCH 07/10] Keep the JavaScript stack size within the thread's + stack + +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 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 5 ++- + src/sqlitejs.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++++-- + test/main.c | 58 ++++++++++++++++++++++++++++++++++ + 3 files changed, 144 insertions(+), 3 deletions(-) + +diff --git a/README.md b/README.md +index d2cf41b..8ef6804 100644 +--- a/README.md ++++ b/README.md +@@ -419,10 +419,13 @@ SELECT js_load_blob('/path/to/file.bin'); -- Returns file contents as a blob + + ### js_set_max_stack_size + +-Configures the maximum stack size (in bytes) for the JavaScript engine. ++Sets the most stack, in bytes, that JavaScript may use, which limits how deeply functions can call themselves; code that goes deeper fails with "Maximum call stack size exceeded". The default is 1 MB, or less when the thread that loads the extension has less stack. The size must be an integer no larger than the calling thread's stack allows, less a margin for the native code that runs between QuickJS's checks (`SQLITE_JS_STACK_MARGIN`, 256 KB); the error message gives the largest size allowed. A larger size, or text, which would read as 0, is an error, because QuickJS's check would never trip and code that calls itself without end would crash the process. ++ ++`0` turns the check off, for a connection used from several threads: the check measures from the stack of the thread that loaded the extension. With the check off, code that calls itself without end crashes the process. + + ```sql + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB ++SELECT js_set_max_stack_size(0); -- No check, for use from several threads + ``` + + ### js_set_memory_limit +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 790dc82..e5562f4 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -5,6 +5,11 @@ + // Created by Marco Bambini on 31/03/25. + // + ++// glibc declares pthread_getattr_np() (see js_stack_room) only for _GNU_SOURCE ++#if defined(__linux__) && !defined(_GNU_SOURCE) ++#define _GNU_SOURCE ++#endif ++ + #include + #include + #include +@@ -16,6 +21,15 @@ + #include "quickjs.h" + #include "quickjs-libc.h" + ++#if defined(_WIN32) ++#include ++#if defined(_MSC_VER) ++#include ++#endif ++#elif defined(__APPLE__) || defined(__linux__) ++#include ++#endif ++ + #ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 + #endif +@@ -197,6 +211,53 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + #define SQLITE_JS_DEFAULT_MEMORY_LIMIT (64 * 1024 * 1024) + #endif + ++// Stack, in bytes, kept free below the JavaScript stack limit for the native code that runs ++// between two of QuickJS's stack checks: QuickJS's own C functions, and SQLite when JavaScript ++// runs SQL through db.exec. ++#ifndef SQLITE_JS_STACK_MARGIN ++#define SQLITE_JS_STACK_MARGIN (256 * 1024) ++#endif ++ ++// The stack, in bytes, that the calling thread has left below this function, less the margin. ++// QuickJS trusts its stack size: one larger than the thread has never trips its check, and code ++// that calls itself without end then crashes the process. Returns false where the thread's stack ++// cannot be found. ++static bool js_stack_room (size_t *room) { ++ // where the stack is now, found the way QuickJS finds it: the address of a local variable ++ // can be elsewhere, for example on AddressSanitizer's separate stack ++#if defined(__clang__) || defined(__GNUC__) ++ uintptr_t sp = (uintptr_t)__builtin_frame_address(0); ++#elif defined(_MSC_VER) ++ uintptr_t sp = (uintptr_t)_AddressOfReturnAddress(); ++#else ++ volatile char here = 0; ++ uintptr_t sp = (uintptr_t)&here; ++#endif ++ uintptr_t low = 0; ++#if defined(_WIN32) ++ // the stack is one allocation, reserved from its lowest address ++ MEMORY_BASIC_INFORMATION mbi; ++ if (VirtualQuery((LPCVOID)sp, &mbi, sizeof(mbi)) == 0) return false; ++ low = (uintptr_t)mbi.AllocationBase; ++#elif defined(__APPLE__) ++ pthread_t self = pthread_self(); ++ low = (uintptr_t)pthread_get_stackaddr_np(self) - pthread_get_stacksize_np(self); ++#elif defined(__linux__) ++ pthread_attr_t attr; ++ void *addr = NULL; ++ size_t size = 0; ++ if (pthread_getattr_np(pthread_self(), &attr) != 0) return false; ++ int rc = pthread_attr_getstack(&attr, &addr, &size); ++ pthread_attr_destroy(&attr); ++ if (rc != 0) return false; ++ low = (uintptr_t)addr; ++#else ++ return false; ++#endif ++ *room = (sp > low + SQLITE_JS_STACK_MARGIN) ? (size_t)(sp - low - SQLITE_JS_STACK_MARGIN) : 0; ++ return true; ++} ++ + // QuickJS calls this from time to time while it runs code. A non-zero result stops the code + // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, + // a cancelled query in an app) also stops JavaScript that never returns to SQLite. +@@ -224,6 +285,11 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + // in its sqlite3_api_routines, so JavaScript cannot be interrupted there + if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); + ++ // the default stack size must fit in the stack of the thread that loads the extension: Windows ++ // gives a main thread 1 MB, and apps often give their threads no more ++ size_t room = 0; ++ if (js_stack_room(&room) && (room < JS_DEFAULT_STACK_SIZE)) JS_SetMaxStackSize(rt, (room > 0) ? room : 1); ++ + js_std_init_handlers(rt); + JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader, js_module_check_attributes, NULL); + +@@ -1409,8 +1475,22 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + UNUSED(argc); + globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); + +- int stack_size = sqlite3_value_int(argv[0]); +- JS_SetMaxStackSize(js->runtime, stack_size); ++ // 0 turns QuickJS's check off, for a connection used from several threads (the check measures ++ // from the stack of the thread that loaded the extension). Text would read as 0, and a size ++ // larger than the thread's stack is no limit either: code that calls itself without end ++ // would crash the process. Where the stack cannot be measured, allow up to the default. ++ size_t most = JS_DEFAULT_STACK_SIZE; ++ js_stack_room(&most); ++ sqlite3_int64 size = sqlite3_value_int64(argv[0]); ++ if ((sqlite3_value_type(argv[0]) != SQLITE_INTEGER) || (size < 0) || ((sqlite3_uint64)size > most)) { ++ char *msg = sqlite3_mprintf("The stack size must be an integer number of bytes from 1 to %llu, which this thread's stack allows, or 0 for no check", (unsigned long long)most); ++ if (msg) sqlite3_result_error(context, msg, -1); ++ else sqlite3_result_error_nomem(context); ++ sqlite3_free(msg); ++ return; ++ } ++ ++ JS_SetMaxStackSize(js->runtime, (size_t)size); + } + + void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **argv) { +diff --git a/test/main.c b/test/main.c +index 0af4d22..ff1c0e7 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -10,6 +10,7 @@ + #include "sqlitejs.h" + #include + #include ++#include + #include + #include + +@@ -647,6 +648,62 @@ abort_test: + return rc; + } + ++// MARK: - Stack size - ++ ++int test_stack_size (void) { ++ sqlite3 *db = NULL; ++ char sql[256]; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // code that calls itself without end fails, and the connection stays usable ++ const char *recurse = "SELECT js_eval('(function f(n) { return f(n + 1); })(0)');"; ++ rc = check_error(db, recurse, "Maximum call stack size exceeded"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db, "SELECT js_eval('1 + 1');", "2"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a size is an integer no larger than the thread's stack, or 0 for no check: text would read ++ // as 0, and a size larger than the stack never trips the check, so the code above would ++ // crash the process ++ const char *invalid[] = {"'abc'", "-1", "1.5", "'1048576'", "NULL", "x'00'", "1073741824"}; ++ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { ++ snprintf(sql, sizeof(sql), "SELECT js_set_max_stack_size(%s);", invalid[i]); ++ rc = check_error(db, sql, "The stack size must be an integer number of bytes from 1 to "); ++ if (rc != SQLITE_OK) goto abort_test; ++ } ++ ++ // close to the largest size allowed, the code still stops, also when it calls itself ++ // through SQL, which puts SQLite's frames between QuickJS's stack checks ++ const char *most_text = strstr(sqlite3_errmsg(db), "from 1 to "); ++ long long most = most_text ? strtoll(most_text + strlen("from 1 to "), NULL, 10) : 0; ++ if (most <= 64 * 1024) { printf("FAIL: no stack size range in: %s\n", sqlite3_errmsg(db)); rc = SQLITE_ERROR; goto abort_test; } ++ snprintf(sql, sizeof(sql), "SELECT js_set_max_stack_size(%lld);", most - 4096); ++ rc = db_exec(db, sql); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, recurse, "Maximum call stack size exceeded"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_create_scalar('recurse_sql', '(function (args) { try { const rs = db.exec(\"SELECT recurse_sql(?)\", args[0] + 1); if (rs.next()) return rs.get(0); } catch (e) {} throw new Error(\"stopped\"); })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT recurse_sql(0);", "stopped"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // a smaller size ++ rc = db_exec(db, "SELECT js_set_max_stack_size(256 * 1024);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, recurse, "Maximum call stack size exceeded"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // 0 is still allowed, for connections used from several threads (see test_thread) ++ rc = check_query(db, "SELECT quote(js_set_max_stack_size(0));", "NULL"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ + // MARK: - Direct only - + + int test_direct_only (void) { +@@ -840,6 +897,7 @@ int main (void) { + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); ++ result += test_report("Stack size", test_stack_size()); + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0008-Report-SQL-errors-from-db.exec-result-sets.patch b/subprojects/sqlite-js/patches/0008-Report-SQL-errors-from-db.exec-result-sets.patch new file mode 100644 index 0000000000..f6cb8afbb7 --- /dev/null +++ b/subprojects/sqlite-js/patches/0008-Report-SQL-errors-from-db.exec-result-sets.patch @@ -0,0 +1,161 @@ +From f2516ac9a2d0bff479d2286f604796ecd88187b5 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Wed, 11 Nov 2026 12:24:04 -0800 +Subject: [PATCH 08/10] Report SQL errors from db.exec result sets + +db.exec() prepares a statement and returns a result set; the statement +runs as next() or toArray() steps it. Both treated any sqlite3_step() +result other than SQLITE_ROW as the end of the rows, so an error while +the statement runs was dropped: next() returned false, as at the end of +the rows, and toArray() returned the rows read before the error. A +failed UNIQUE constraint on an INSERT, or an integer overflow, looked +like success, and JavaScript that writes through db.exec() could not +tell. An error found when the statement is prepared, such as an unknown +function, was already thrown by db.exec(). + +Throw an InternalError with the connection's error message when +sqlite3_step() returns neither SQLITE_ROW nor SQLITE_DONE, from next() +and from toArray(). The statement is finalized as before. The end of +the rows is still false. The README now documents db.exec(), including +that a statement runs only when next() or toArray() steps it. + +Add an Exec errors test: a failed constraint and an overflow throw from +next(), an overflow on the second row throws from toArray(), JavaScript +can catch the error, and the end of the rows and a successful INSERT +are unchanged. It fails without this change. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw +--- + README.md | 12 ++++++++++++ + src/sqlitejs.c | 19 +++++++++++++++---- + test/main.c | 35 +++++++++++++++++++++++++++++++++++ + 3 files changed, 62 insertions(+), 4 deletions(-) + +diff --git a/README.md b/README.md +index 8ef6804..abec56b 100644 +--- a/README.md ++++ b/README.md +@@ -397,6 +397,18 @@ SELECT js_eval('Math.PI * Math.pow(5, 2)'); + SELECT js_eval('new Date(1629381600000).toLocaleDateString()'); + ``` + ++### Running SQL from JavaScript ++ ++JavaScript can run SQL on the same connection through the global `db` object. `db.exec(sql, ...parameters)` prepares one statement, binds the parameters to its `?` placeholders, and returns a result set. The statement runs as you step through it: `next()` moves to the next row and returns `true`, or `false` after the last; `get(i)` and `name(i)` give a column's value and name; `columnCount` is the number of columns; and `toArray()` returns the remaining rows as arrays. A statement that returns no rows, such as an `INSERT`, also runs only when you call `next()` or `toArray()`. ++ ++An error while the statement runs, such as a failed constraint, is thrown from `next()` or `toArray()`, as an error in the SQL itself is thrown from `db.exec()`. ++ ++```sql ++CREATE TABLE t(a UNIQUE); ++SELECT js_eval('db.exec("INSERT INTO t VALUES (?)", 1).next()'); -- 0: the row is inserted, and next() is false, as there are no rows ++SELECT js_eval('(function () { try { db.exec("INSERT INTO t VALUES (?)", 1).next(); } catch (e) { return e.message; } })()'); -- UNIQUE constraint failed: t.a ++``` ++ + ## Utility Functions + + ### js_version +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index e5562f4..8f6e3a9 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -115,11 +115,16 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J + if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); + + if (!rs->vm) return JS_FALSE; +- if (sqlite3_step(rs->vm) == SQLITE_ROW) return JS_TRUE; ++ int rc = sqlite3_step(rs->vm); ++ if (rc == SQLITE_ROW) return JS_TRUE; + ++ // an error while the statement runs (a constraint, an overflow, an interrupt) is an ++ // exception, as an error while it is prepared is in js_sqlite_exec; only the end of the ++ // rows is false ++ JSValue result = (rc == SQLITE_DONE) ? JS_FALSE : JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); + sqlite3_finalize(rs->vm); + rs->vm = NULL; +- return JS_FALSE; ++ return result; + } + + static JSValue js_rowset_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { +@@ -168,8 +173,9 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg + + int ncols = rs->ncols; + int nrows = 0; ++ int rc; + while (true) { +- int rc = sqlite3_step(rs->vm); ++ rc = sqlite3_step(rs->vm); + if (rc != SQLITE_ROW) break; + + JSValue row = JS_NewArray(ctx); +@@ -186,7 +192,12 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg + + JS_SetPropertyUint32(ctx, result, nrows++, row); + } +- ++ ++ // as in js_rowset_next: an error is an exception, not a shorter array ++ if (rc != SQLITE_DONE) { ++ JS_FreeValue(ctx, result); ++ result = JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); ++ } + sqlite3_finalize(rs->vm); + rs->vm = NULL; + return result; +diff --git a/test/main.c b/test/main.c +index ff1c0e7..3b562dd 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -881,6 +881,40 @@ abort_test: + + // MARK: - + ++// MARK: - Exec errors - ++ ++int test_exec_errors (void) { ++ sqlite3 *db = NULL; ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ rc = db_exec(db, "CREATE TABLE u(a UNIQUE); INSERT INTO u VALUES (1);"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // an error while the statement runs is an exception, from next() and from toArray() ++ rc = check_error(db, "SELECT js_eval('db.exec(\"INSERT INTO u VALUES (1)\").next()');", "UNIQUE constraint failed"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('db.exec(\"SELECT abs(-9223372036854775808)\").next()');", "integer overflow"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_error(db, "SELECT js_eval('db.exec(\"SELECT 1 UNION ALL SELECT abs(-9223372036854775808) UNION ALL SELECT 3\").toArray()');", "integer overflow"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // JavaScript can catch it ++ rc = check_query(db, "SELECT js_eval('(function () { try { db.exec(\"INSERT INTO u VALUES (1)\").next(); return \"no error\"; } catch (e) { return e.message; } })()');", "UNIQUE constraint failed: u.a"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // the end of the rows is still false, and a statement that succeeds still runs ++ rc = check_query(db, "SELECT js_eval('[db.exec(\"SELECT 1 WHERE 0\").next(), db.exec(\"INSERT INTO u VALUES (2)\").next(), JSON.stringify(db.exec(\"SELECT a FROM u ORDER BY a\").toArray())].join(\" \")');", "false false [[1],[2]]"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++abort_test: ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ return rc; ++} ++ ++// MARK: - ++ + int test_report(const char *description, int rc){ + printf("%s%-30s %s\n", VERBOSE ? "********** " : "", description, (rc == SQLITE_OK) ? "OK" : "FAILED"); + return (rc == SQLITE_OK) ? 0 : 1; +@@ -902,6 +936,7 @@ int main (void) { + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); + result += test_report("Aggregate errors", test_aggregate_errors()); ++ result += test_report("Exec errors", test_exec_errors()); + + sqlite3_int64 current = 0; + sqlite3_int64 highwater = 0; +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0009-Measure-the-stack-of-the-thread-each-call-runs-on.patch b/subprojects/sqlite-js/patches/0009-Measure-the-stack-of-the-thread-each-call-runs-on.patch new file mode 100644 index 0000000000..25d4282c4b --- /dev/null +++ b/subprojects/sqlite-js/patches/0009-Measure-the-stack-of-the-thread-each-call-runs-on.patch @@ -0,0 +1,411 @@ +From 734b4e1e76476714ec3c51950309dd16a39ca019 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Wed, 11 Nov 2026 16:13:38 -0800 +Subject: [PATCH 09/10] Measure the stack of the thread each call runs on + +QuickJS measures the stack from the top it recorded on the thread that +created the runtime. A connection used on another thread, as in an +app's connection pool, failed at once with "Maximum call stack size +exceeded", or code that called itself without end was never stopped and +crashed the process; js_set_max_stack_size(0) was the workaround. + +Each call into JavaScript from SQLite now calls JS_UpdateStackTop() for +its thread and keeps the size within what that thread's stack has left. +Nested calls (JavaScript running SQL that runs JavaScript) keep the +outer limit. Each thread's stack bounds are found once and cached in a +thread-local variable, since on Linux finding the main thread's stack +reads /proc/self/maps. +--- + README.md | 6 +-- + src/sqlitejs.c | 128 +++++++++++++++++++++++++++++++++++++------------ + test/main.c | 85 ++++++++++++++++++++++++++++++++ + 3 files changed, 186 insertions(+), 33 deletions(-) + +diff --git a/README.md b/README.md +index abec56b..9e58b81 100644 +--- a/README.md ++++ b/README.md +@@ -431,13 +431,13 @@ SELECT js_load_blob('/path/to/file.bin'); -- Returns file contents as a blob + + ### js_set_max_stack_size + +-Sets the most stack, in bytes, that JavaScript may use, which limits how deeply functions can call themselves; code that goes deeper fails with "Maximum call stack size exceeded". The default is 1 MB, or less when the thread that loads the extension has less stack. The size must be an integer no larger than the calling thread's stack allows, less a margin for the native code that runs between QuickJS's checks (`SQLITE_JS_STACK_MARGIN`, 256 KB); the error message gives the largest size allowed. A larger size, or text, which would read as 0, is an error, because QuickJS's check would never trip and code that calls itself without end would crash the process. ++Sets the most stack, in bytes, that JavaScript may use, which limits how deeply functions can call themselves; code that goes deeper fails with "Maximum call stack size exceeded". The default is 1 MB. Each call into JavaScript measures the stack of the thread it runs on, so a connection can be used from several threads, and the size is lowered for a call on a thread with less stack. The size must be an integer no larger than the calling thread's stack allows, less a margin for the native code that runs between QuickJS's checks (`SQLITE_JS_STACK_MARGIN`, 256 KB); the error message gives the largest size allowed. A larger size, or text, which would read as 0, is an error, because QuickJS's check would never trip and code that calls itself without end would crash the process. + +-`0` turns the check off, for a connection used from several threads: the check measures from the stack of the thread that loaded the extension. With the check off, code that calls itself without end crashes the process. ++`0` turns the check off. Code that calls itself without end then crashes the process. + + ```sql + SELECT js_set_max_stack_size(1048576); -- Set max stack size to 1 MB +-SELECT js_set_max_stack_size(0); -- No check, for use from several threads ++SELECT js_set_max_stack_size(0); -- No check + ``` + + ### js_set_memory_limit +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 8f6e3a9..5abf713 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -34,6 +34,12 @@ + SQLITE_EXTENSION_INIT1 + #endif + ++#if defined(_MSC_VER) && !defined(__clang__) ++#define JS_THREAD_LOCAL __declspec(thread) ++#else ++#define JS_THREAD_LOCAL _Thread_local ++#endif ++ + #ifdef _WIN32 + #define APIEXPORT __declspec(dllexport) + #else +@@ -47,6 +53,8 @@ typedef struct { + JSClassID rowSetClassID; + int ref_count; + size_t memory_limit; // in bytes, 0 for none: see js_set_memory_limit() ++ size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() ++ int depth; // calls into JavaScript in progress: see js_enter() + } globaljs_context; + + typedef struct { +@@ -229,6 +237,41 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + #define SQLITE_JS_STACK_MARGIN (256 * 1024) + #endif + ++// The lowest address of the calling thread's stack, found once per thread: on Linux, finding the ++// main thread's stack reads /proc/self/maps. Returns false where the stack cannot be found. ++static bool js_stack_low (uintptr_t sp, uintptr_t *low) { ++ static JS_THREAD_LOCAL uintptr_t thread_low; ++ static JS_THREAD_LOCAL bool thread_unknown; ++ if (thread_low != 0) { *low = thread_low; return true; } ++ if (thread_unknown) return false; ++#if defined(_WIN32) ++ // the stack is one allocation, reserved from its lowest address ++ MEMORY_BASIC_INFORMATION mbi; ++ if (VirtualQuery((LPCVOID)sp, &mbi, sizeof(mbi)) == 0) { thread_unknown = true; return false; } ++ thread_low = (uintptr_t)mbi.AllocationBase; ++#elif defined(__APPLE__) ++ UNUSED(sp); ++ pthread_t self = pthread_self(); ++ thread_low = (uintptr_t)pthread_get_stackaddr_np(self) - pthread_get_stacksize_np(self); ++#elif defined(__linux__) ++ UNUSED(sp); ++ pthread_attr_t attr; ++ void *addr = NULL; ++ size_t size = 0; ++ if (pthread_getattr_np(pthread_self(), &attr) != 0) { thread_unknown = true; return false; } ++ int rc = pthread_attr_getstack(&attr, &addr, &size); ++ pthread_attr_destroy(&attr); ++ if (rc != 0) { thread_unknown = true; return false; } ++ thread_low = (uintptr_t)addr; ++#else ++ UNUSED(sp); ++ thread_unknown = true; ++ return false; ++#endif ++ *low = thread_low; ++ return true; ++} ++ + // The stack, in bytes, that the calling thread has left below this function, less the margin. + // QuickJS trusts its stack size: one larger than the thread has never trips its check, and code + // that calls itself without end then crashes the process. Returns false where the thread's stack +@@ -245,30 +288,30 @@ static bool js_stack_room (size_t *room) { + uintptr_t sp = (uintptr_t)&here; + #endif + uintptr_t low = 0; +-#if defined(_WIN32) +- // the stack is one allocation, reserved from its lowest address +- MEMORY_BASIC_INFORMATION mbi; +- if (VirtualQuery((LPCVOID)sp, &mbi, sizeof(mbi)) == 0) return false; +- low = (uintptr_t)mbi.AllocationBase; +-#elif defined(__APPLE__) +- pthread_t self = pthread_self(); +- low = (uintptr_t)pthread_get_stackaddr_np(self) - pthread_get_stacksize_np(self); +-#elif defined(__linux__) +- pthread_attr_t attr; +- void *addr = NULL; +- size_t size = 0; +- if (pthread_getattr_np(pthread_self(), &attr) != 0) return false; +- int rc = pthread_attr_getstack(&attr, &addr, &size); +- pthread_attr_destroy(&attr); +- if (rc != 0) return false; +- low = (uintptr_t)addr; +-#else +- return false; +-#endif ++ if (!js_stack_low(sp, &low)) return false; + *room = (sp > low + SQLITE_JS_STACK_MARGIN) ? (size_t)(sp - low - SQLITE_JS_STACK_MARGIN) : 0; + return true; + } + ++// Points QuickJS's stack check at the calling thread before JavaScript runs on a connection. ++// QuickJS measures the stack from the top it recorded on the thread that created the runtime, ++// so on any other thread its check is wrong: code fails at once with "Maximum call stack size ++// exceeded", or code that calls itself without end is never stopped and crashes the process. ++// An app's connection pool runs a connection on many threads. The size is also kept within ++// what this thread's stack has left. A call nested in another (JavaScript running SQL that ++// runs JavaScript) is on the same thread and keeps the outer call's limit. ++static void js_enter (globaljs_context *js) { ++ if (js->depth++ > 0) return; ++ JS_UpdateStackTop(js->runtime); ++ size_t size = js->stack_size, room = 0; ++ if ((size > 0) && js_stack_room(&room) && (room < size)) size = (room > 0) ? room : 1; ++ JS_SetMaxStackSize(js->runtime, size); ++} ++ ++static void js_leave (globaljs_context *js) { ++ js->depth--; ++} ++ + // QuickJS calls this from time to time while it runs code. A non-zero result stops the code + // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, + // a cancelled query in an app) also stops JavaScript that never returns to SQLite. +@@ -311,6 +354,7 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + js->runtime = rt; + js->context = ctx; + js->ref_count = 0; ++ js->stack_size = JS_DEFAULT_STACK_SIZE; + + JS_SetContextOpaque(ctx, js); + JS_SetRuntimeOpaque(rt, js); +@@ -981,7 +1025,9 @@ static void js_execute_common (sqlite3_context *context, JSContext *js_context, + + static void js_execute_scalar (sqlite3_context *context, int nvalues, sqlite3_value **values) { + functionjs_context *fctx = (functionjs_context *)sqlite3_user_data(context); ++ js_enter(fctx->js_ctx); + js_execute_common(context, fctx->js_ctx->context, nvalues, values, fctx->func, JS_UNDEFINED, true); ++ js_leave(fctx->js_ctx); + } + + static void js_execute_step (sqlite3_context *context, int nvalues, sqlite3_value **values) { +@@ -996,12 +1042,11 @@ static void js_execute_step (sqlite3_context *context, int nvalues, sqlite3_valu + + // if there is an init code then create a separate aggregate context + // to avoid shared state corruption across parallel aggregates +- if (!agg_ctx->context) { +- // set up a new isolated environment for this aggregation +- if (js_setup_aggregate(context, js, agg_ctx, fctx->init_code, fctx->step_code, fctx->final_code, fctx->value_code, fctx->inverse_code) == false) return; ++ js_enter(js); ++ if (agg_ctx->context || js_setup_aggregate(context, js, agg_ctx, fctx->init_code, fctx->step_code, fctx->final_code, fctx->value_code, fctx->inverse_code)) { ++ js_execute_common(context, agg_ctx->context, nvalues, values, agg_ctx->step_func, JS_UNDEFINED, false); + } +- +- js_execute_common(context, agg_ctx->context, nvalues, values, agg_ctx->step_func, JS_UNDEFINED, false); ++ js_leave(js); + } + + static void js_execute_value (sqlite3_context *context) { +@@ -1009,21 +1054,30 @@ static void js_execute_value (sqlite3_context *context) { + // new allocation here could only fail and there would be nothing to report anyway + functionjs_aggregate_context *agg_ctx = sqlite3_aggregate_context(context, 0); + if (!agg_ctx || !agg_ctx->context) { sqlite3_result_null(context); return; } ++ globaljs_context *js = ((functionjs_context *)sqlite3_user_data(context))->js_ctx; ++ js_enter(js); + js_execute_common(context, agg_ctx->context, 0, NULL, agg_ctx->value_func, JS_UNDEFINED, true); ++ js_leave(js); + } + + static void js_execute_inverse (sqlite3_context *context, int nvalues, sqlite3_value **values) { + functionjs_aggregate_context *agg_ctx = sqlite3_aggregate_context(context, 0); + if (!agg_ctx || !agg_ctx->context) return; ++ globaljs_context *js = ((functionjs_context *)sqlite3_user_data(context))->js_ctx; ++ js_enter(js); + js_execute_common(context, agg_ctx->context, nvalues, values, agg_ctx->inverse_func, JS_UNDEFINED, false); ++ js_leave(js); + } + + static void js_execute_final (sqlite3_context *context) { + functionjs_aggregate_context *agg_ctx = sqlite3_aggregate_context(context, 0); + + if (agg_ctx && agg_ctx->context) { ++ globaljs_context *js = ((functionjs_context *)sqlite3_user_data(context))->js_ctx; ++ js_enter(js); + js_execute_common(context, agg_ctx->context, 0, NULL, agg_ctx->final_func, JS_UNDEFINED, true); + functionjs_aggregate_free(agg_ctx); ++ js_leave(js); + } else { + sqlite3_result_null(context); + } +@@ -1032,6 +1086,7 @@ static void js_execute_final (sqlite3_context *context) { + static int js_execute_collation (void *xdata, int len1, const void *v1, int len2, const void *v2) { + functionjs_context *fctx = (functionjs_context *)xdata; + globaljs_context *js = fctx->js_ctx; ++ js_enter(js); + + // create arguments + JSValue val1 = (v1) ? JS_NewStringLen(js->context, (const char *)v1, (size_t)len1) : JS_NULL; +@@ -1056,6 +1111,7 @@ static int js_execute_collation (void *xdata, int len1, const void *v1, int len2 + if (JS_ToFloat64(js->context, &num, result) == 0) nresult = (num < 0.0) ? -1 : ((num > 0.0) ? 1 : 0); + } + JS_FreeValue(js->context, result); ++ js_leave(js); + + return nresult; + } +@@ -1159,7 +1215,7 @@ insert_function: + return (rc == SQLITE_DONE); + } + +-bool js_create_common (sqlite3_context *context, const char *type, const char *name, const char *init_code, const char *step_code, const char *final_code, const char *value_code, const char *inverse_code, bool is_load) { ++static bool js_create_function (sqlite3_context *context, const char *type, const char *name, const char *init_code, const char *step_code, const char *final_code, const char *value_code, const char *inverse_code, bool is_load) { + + globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); + +@@ -1254,6 +1310,14 @@ bool js_create_common (sqlite3_context *context, const char *type, const char *n + return (rc == SQLITE_OK); + } + ++bool js_create_common (sqlite3_context *context, const char *type, const char *name, const char *init_code, const char *step_code, const char *final_code, const char *value_code, const char *inverse_code, bool is_load) { ++ globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); ++ js_enter(js); ++ bool ok = js_create_function(context, type, name, init_code, step_code, final_code, value_code, inverse_code, is_load); ++ js_leave(js); ++ return ok; ++} ++ + void js_create_scalar (sqlite3_context *context, int argc, sqlite3_value **argv) { + UNUSED(argc); + // get/check parameters first +@@ -1326,9 +1390,11 @@ void js_eval (sqlite3_context *context, int argc, sqlite3_value **argv) { + return; + } + ++ js_enter(data); + JSValue value = JS_Eval(data->context, code, strlen(code), NULL, JS_EVAL_TYPE_GLOBAL); + js_value_to_sqlite(context, data->context, value); + JS_FreeValue(data->context, value); ++ js_leave(data); + } + + static void js_load_fromfile (sqlite3_context *context, int argc, sqlite3_value **argv, bool is_blob) { +@@ -1486,10 +1552,11 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + UNUSED(argc); + globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); + +- // 0 turns QuickJS's check off, for a connection used from several threads (the check measures +- // from the stack of the thread that loaded the extension). Text would read as 0, and a size +- // larger than the thread's stack is no limit either: code that calls itself without end +- // would crash the process. Where the stack cannot be measured, allow up to the default. ++ // 0 turns QuickJS's check off. It was needed for a connection used from several threads, ++ // before each call into JavaScript measured its own thread's stack (see js_enter). Text would ++ // read as 0, and a size larger than the thread's stack is no limit either: code that calls ++ // itself without end would crash the process. Where the stack cannot be measured, allow up ++ // to the default. + size_t most = JS_DEFAULT_STACK_SIZE; + js_stack_room(&most); + sqlite3_int64 size = sqlite3_value_int64(argv[0]); +@@ -1501,6 +1568,7 @@ void js_set_max_stack_size (sqlite3_context *context, int argc, sqlite3_value ** + return; + } + ++ js->stack_size = (size_t)size; + JS_SetMaxStackSize(js->runtime, (size_t)size); + } + +diff --git a/test/main.c b/test/main.c +index 3b562dd..53f77de 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -704,6 +704,90 @@ abort_test: + return rc; + } + ++// MARK: - Stack on other threads - ++ ++typedef struct { ++ sqlite3 *db; ++ int depth; // how deep deep() is asked to go ++ int rc; ++} stack_thread_args; ++ ++// Creates deep(n), which calls itself n levels deep, and forever(), which calls itself without end. ++static int stack_thread_functions (sqlite3 *db) { ++ int rc = db_exec(db, "SELECT js_create_scalar('deep', '(function (args) { return (function f(n) { return (n === 0) ? 0 : 1 + f(n - 1); })(args[0]); })');"); ++ if (rc != SQLITE_OK) return rc; ++ return db_exec(db, "SELECT js_create_scalar('forever', '(function (args) { return (function f(n) { return f(n + 1); })(0); })');"); ++} ++ ++// Runs deep() and forever() on the calling thread: deep() returns its depth, and forever() stops ++// with an error instead of crashing. ++static void *stack_thread_run (void *ptr) { ++ stack_thread_args *args = (stack_thread_args *)ptr; ++ char sql[64], expected[16]; ++ snprintf(sql, sizeof(sql), "SELECT deep(%d);", args->depth); ++ snprintf(expected, sizeof(expected), "%d", args->depth); ++ args->rc = check_query(args->db, sql, expected); ++ if (args->rc == SQLITE_OK) args->rc = check_error(args->db, "SELECT forever();", "Maximum call stack size exceeded"); ++ return NULL; ++} ++ ++static void *stack_thread_open (void *ptr) { ++ stack_thread_args *args = (stack_thread_args *)ptr; ++ args->rc = test_open(&args->db); ++ if (args->rc == SQLITE_OK) args->rc = stack_thread_functions(args->db); ++ return NULL; ++} ++ ++// Runs fn(args) on a new thread with a stack of stack_size bytes, or the default if 0. ++static int stack_thread (void *(*fn)(void *), stack_thread_args *args, size_t stack_size) { ++ pthread_attr_t attr; ++ pthread_t thread; ++ if (pthread_attr_init(&attr) != 0) return SQLITE_ERROR; ++ if (stack_size > 0 && pthread_attr_setstacksize(&attr, stack_size) != 0) { pthread_attr_destroy(&attr); return SQLITE_ERROR; } ++ int rc = pthread_create(&thread, &attr, fn, args); ++ pthread_attr_destroy(&attr); ++ if (rc != 0) return SQLITE_ERROR; ++ pthread_join(thread, NULL); ++ return args->rc; ++} ++ ++// A connection runs on whichever thread calls it, as in an app's connection pool. QuickJS measured ++// the stack from the thread that opened the connection, so on another thread JavaScript failed at ++// once with "Maximum call stack size exceeded", or code that called itself without end crashed. ++int test_stack_threads (void) { ++ // each level of JavaScript recursion takes about 1.5 KB of native stack, and the small stack ++ // below leaves about 250 KB after SQLITE_JS_STACK_MARGIN ++ stack_thread_args args = {NULL, 100, SQLITE_OK}; ++ ++ // opened on this thread, used on another ++ int rc = test_open(&args.db); ++ if (rc == SQLITE_OK) rc = stack_thread_functions(args.db); ++ if (rc == SQLITE_OK) rc = stack_thread(stack_thread_run, &args, 0); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // and on another thread with a small stack, where the size is lowered to fit ++ rc = stack_thread(stack_thread_run, &args, 512 * 1024); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // and back on this thread ++ stack_thread_run(&args); ++ rc = args.rc; ++ if (rc != SQLITE_OK) goto abort_test; ++ sqlite3_close(args.db); ++ args.db = NULL; ++ ++ // opened on another thread, used on this one ++ rc = stack_thread(stack_thread_open, &args, 0); ++ if (rc != SQLITE_OK) goto abort_test; ++ stack_thread_run(&args); ++ rc = args.rc; ++ ++abort_test: ++ if (rc != SQLITE_OK && args.db) printf("Error: %s\n", sqlite3_errmsg(args.db)); ++ if (args.db) sqlite3_close(args.db); ++ return rc; ++} ++ + // MARK: - Direct only - + + int test_direct_only (void) { +@@ -932,6 +1016,7 @@ int main (void) { + result += test_report("Interrupt", test_interrupt()); + result += test_report("Memory limit", test_memory_limit()); + result += test_report("Stack size", test_stack_size()); ++ result += test_report("Stack on other threads", test_stack_threads()); + result += test_report("Direct only", test_direct_only()); + result += test_report("Blobs", test_blobs()); + result += test_report("Numbers", test_numbers()); +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0010-Let-the-host-cancel-all-running-JavaScript.patch b/subprojects/sqlite-js/patches/0010-Let-the-host-cancel-all-running-JavaScript.patch new file mode 100644 index 0000000000..81762884ba --- /dev/null +++ b/subprojects/sqlite-js/patches/0010-Let-the-host-cancel-all-running-JavaScript.patch @@ -0,0 +1,183 @@ +From ef4e501a7a691d38fbd1ca46454d921d1e30cd9f Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Wed, 11 Nov 2026 16:43:39 -0800 +Subject: [PATCH 10/10] Let the host cancel all running JavaScript + +sqlitejs_cancel_all() stops the JavaScript running in every connection: +each call fails with an "interrupted" error, even code that catches +every exception. JavaScript that begins afterwards runs normally. + +Android cannot otherwise stop a runaway function: it cancels a query +with a progress handler, which SQLite never calls while a function runs, +and Room 2.7 and later pass no cancellation signal at all. A global +epoch, read when the outermost call into JavaScript begins and compared +by the existing interrupt handler, makes the cancel reach every runtime +without a list of connections. The interrupt handler is now installed +even when sqlite3_is_interrupted() is unavailable (SQLite before 3.41), +so cancelling still works there. +--- + src/sqlitejs.c | 36 +++++++++++++++++++++++++++++++++--- + src/sqlitejs.h | 1 + + test/main.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ + 3 files changed, 80 insertions(+), 3 deletions(-) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index 5abf713..e853b0e 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -55,6 +55,8 @@ typedef struct { + size_t memory_limit; // in bytes, 0 for none: see js_set_memory_limit() + size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() + int depth; // calls into JavaScript in progress: see js_enter() ++ unsigned cancel_epoch; // js_cancel_epoch when the outermost call began ++ bool check_interrupted; // sqlite3_is_interrupted() is available + } globaljs_context; + + typedef struct { +@@ -237,6 +239,29 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + #define SQLITE_JS_STACK_MARGIN (256 * 1024) + #endif + ++// Bumped by sqlitejs_cancel_all(): JavaScript that began before stops, as if interrupted. ++static unsigned js_cancel_epoch; ++ ++static unsigned js_cancel_epoch_load (void) { ++#if defined(__clang__) || defined(__GNUC__) ++ return __atomic_load_n(&js_cancel_epoch, __ATOMIC_ACQUIRE); ++#else ++ return *(volatile unsigned *)&js_cancel_epoch; ++#endif ++} ++ ++// Stops all JavaScript that is running now, in every connection: each call fails with an ++// "interrupted" error. JavaScript that begins afterwards runs normally. Safe from any thread. ++// For hosts whose own cancelling cannot reach JavaScript: Android cancels a query with a ++// progress handler, which SQLite never calls while a JavaScript function runs. ++void sqlitejs_cancel_all (void) { ++#if defined(__clang__) || defined(__GNUC__) ++ __atomic_add_fetch(&js_cancel_epoch, 1, __ATOMIC_RELEASE); ++#else ++ (*(volatile unsigned *)&js_cancel_epoch)++; ++#endif ++} ++ + // The lowest address of the calling thread's stack, found once per thread: on Linux, finding the + // main thread's stack reads /proc/self/maps. Returns false where the stack cannot be found. + static bool js_stack_low (uintptr_t sp, uintptr_t *low) { +@@ -302,6 +327,7 @@ static bool js_stack_room (size_t *room) { + // runs JavaScript) is on the same thread and keeps the outer call's limit. + static void js_enter (globaljs_context *js) { + if (js->depth++ > 0) return; ++ js->cancel_epoch = js_cancel_epoch_load(); + JS_UpdateStackTop(js->runtime); + size_t size = js->stack_size, room = 0; + if ((size > 0) && js_stack_room(&room) && (room < size)) size = (room > 0) ? room : 1; +@@ -318,7 +344,8 @@ static void js_leave (globaljs_context *js) { + static int js_interrupt_handler (JSRuntime *rt, void *opaque) { + UNUSED(rt); + globaljs_context *js = (globaljs_context *)opaque; +- return (js->db != NULL) && sqlite3_is_interrupted(js->db); ++ if (js->cancel_epoch != js_cancel_epoch_load()) return 1; ++ return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); + } + + static globaljs_context *globaljs_init (sqlite3 *db) { +@@ -328,6 +355,8 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + globaljs_context *js = (globaljs_context *)sqlite3_malloc(sizeof(globaljs_context)); + if (!js) return NULL; + memset(js, 0, sizeof(globaljs_context)); ++ // JavaScript that runs while the connection is set up must not count as begun before a cancel ++ js->cancel_epoch = js_cancel_epoch_load(); + + rt = JS_NewRuntime(); + if (!rt) goto abort_init; +@@ -336,8 +365,9 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + //JS_SetMaxStackSize(rt, 10 * 1024); + + // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry +- // in its sqlite3_api_routines, so JavaScript cannot be interrupted there +- if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); ++ // in its sqlite3_api_routines, so JavaScript cannot be interrupted there, only cancelled ++ js->check_interrupted = (sqlite3_libversion_number() >= 3041000); ++ JS_SetInterruptHandler(rt, js_interrupt_handler, js); + + // the default stack size must fit in the stack of the thread that loads the extension: Windows + // gives a main thread 1 MB, and apps often give their threads no more +diff --git a/src/sqlitejs.h b/src/sqlitejs.h +index 80fe49d..fea0870 100644 +--- a/src/sqlitejs.h ++++ b/src/sqlitejs.h +@@ -21,5 +21,6 @@ + int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); + const char *sqlitejs_version (void); + const char *quickjs_version (void); ++void sqlitejs_cancel_all (void); + + #endif +diff --git a/test/main.c b/test/main.c +index 53f77de..49ac377 100644 +--- a/test/main.c ++++ b/test/main.c +@@ -648,6 +648,51 @@ abort_test: + return rc; + } + ++// MARK: - Cancel all - ++ ++static void *test_cancel_all_worker (void *ptr) { ++ (void)ptr; ++ // give the statement time to start running JavaScript ++ usleep(200 * 1000); ++ sqlitejs_cancel_all(); ++ return NULL; ++} ++ ++// sqlitejs_cancel_all() stops the JavaScript running in every connection, as Android's own ++// cancelling (a progress handler, which SQLite never calls while a function runs) cannot. ++int test_cancel_all (void) { ++ sqlite3 *db = NULL, *db2 = NULL; ++ pthread_t thread; ++ ++ // if the code cannot be cancelled, end the test program instead of hanging forever ++ alarm(30); ++ ++ int rc = test_open(&db); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = db_exec(db, "SELECT js_create_scalar('spin', '(function (args) { for (;;) { try { while (true) {} } catch (e) {} } })');"); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // JavaScript running now stops, even code that catches every exception ++ if (pthread_create(&thread, NULL, test_cancel_all_worker, NULL) != 0) { rc = SQLITE_ERROR; goto abort_test; } ++ rc = check_error(db, "SELECT spin();", "interrupted"); ++ pthread_join(thread, NULL); ++ if (rc != SQLITE_OK) goto abort_test; ++ ++ // JavaScript that begins afterwards runs normally, on this connection and on a new one ++ rc = check_query(db, "SELECT js_eval('1 + 1');", "2"); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = test_open(&db2); ++ if (rc != SQLITE_OK) goto abort_test; ++ rc = check_query(db2, "SELECT js_eval('2 + 2');", "4"); ++ ++abort_test: ++ alarm(0); ++ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); ++ if (db) sqlite3_close(db); ++ if (db2) sqlite3_close(db2); ++ return rc; ++} ++ + // MARK: - Stack size - + + int test_stack_size (void) { +@@ -1014,6 +1059,7 @@ int main (void) { + result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations + result += test_report("Thread", test_thread()); + result += test_report("Interrupt", test_interrupt()); ++ result += test_report("Cancel all", test_cancel_all()); + result += test_report("Memory limit", test_memory_limit()); + result += test_report("Stack size", test_stack_size()); + result += test_report("Stack on other threads", test_stack_threads()); +-- +2.53.0 + diff --git a/subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-quickjs.txt b/subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-quickjs.txt new file mode 100644 index 0000000000..0490250e04 --- /dev/null +++ b/subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-quickjs.txt @@ -0,0 +1,33 @@ +Copyright (c) 2016-2017 Fabrice Bellard +Copyright (c) 2017-2018 Charlie Gordon +Copyright (c) 2017-2018 Fabrice Bellard +Copyright (c) 2017-2021 Charlie Gordon +Copyright (c) 2017-2021 Fabrice Bellard +Copyright (c) 2017-2024 Charlie Gordon +Copyright (c) 2017-2024 Fabrice Bellard +Copyright (c) 2017-2025 Charlie Gordon +Copyright (c) 2017-2025 Fabrice Bellard +Copyright (c) 2017 Fabrice Bellard +Copyright (c) 2018 Charlie Gordon +Copyright (c) 2023-2025 Ben Noordhuis +Copyright (c) 2023-2025 Saúl Ibarra Corretgé +Copyright (c) 2023 Marcin Kolny +Copyright (c) 2024 Fabrice Bellard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-sqlite-js.txt b/subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-sqlite-js.txt new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/subprojects/sqlite-js/src/main/resources/META-INF/LICENSE-sqlite-js.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/subprojects/sqlite-js/upstream/LICENSE b/subprojects/sqlite-js/upstream/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/subprojects/sqlite-js/upstream/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/subprojects/sqlite-js/upstream/LICENSE.quickjs b/subprojects/sqlite-js/upstream/LICENSE.quickjs new file mode 100644 index 0000000000..0490250e04 --- /dev/null +++ b/subprojects/sqlite-js/upstream/LICENSE.quickjs @@ -0,0 +1,33 @@ +Copyright (c) 2016-2017 Fabrice Bellard +Copyright (c) 2017-2018 Charlie Gordon +Copyright (c) 2017-2018 Fabrice Bellard +Copyright (c) 2017-2021 Charlie Gordon +Copyright (c) 2017-2021 Fabrice Bellard +Copyright (c) 2017-2024 Charlie Gordon +Copyright (c) 2017-2024 Fabrice Bellard +Copyright (c) 2017-2025 Charlie Gordon +Copyright (c) 2017-2025 Fabrice Bellard +Copyright (c) 2017 Fabrice Bellard +Copyright (c) 2018 Charlie Gordon +Copyright (c) 2023-2025 Ben Noordhuis +Copyright (c) 2023-2025 Saúl Ibarra Corretgé +Copyright (c) 2023 Marcin Kolny +Copyright (c) 2024 Fabrice Bellard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/subprojects/sqlite-js/upstream/libs/quickjs-libc.h b/subprojects/sqlite-js/upstream/libs/quickjs-libc.h new file mode 100644 index 0000000000..6cded280f8 --- /dev/null +++ b/subprojects/sqlite-js/upstream/libs/quickjs-libc.h @@ -0,0 +1,79 @@ +/* + * QuickJS C library + * + * Copyright (c) 2017-2018 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef QUICKJS_LIBC_H +#define QUICKJS_LIBC_H + +#include +#include +#include + +#include "quickjs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +JS_LIBC_EXTERN JSModuleDef *js_init_module_std(JSContext *ctx, + const char *module_name); +JS_LIBC_EXTERN JSModuleDef *js_init_module_os(JSContext *ctx, + const char *module_name); +JS_LIBC_EXTERN JSModuleDef *js_init_module_bjson(JSContext *ctx, + const char *module_name); +JS_LIBC_EXTERN void js_std_add_helpers(JSContext *ctx, int argc, char **argv); +JS_LIBC_EXTERN int js_std_loop(JSContext *ctx); +JS_LIBC_EXTERN int js_std_loop_once(JSContext *ctx); +JS_LIBC_EXTERN int js_std_poll_io(JSContext *ctx, int timeout_ms); +JS_LIBC_EXTERN JSValue js_std_await(JSContext *ctx, JSValue obj); +JS_LIBC_EXTERN void js_std_init_handlers(JSRuntime *rt); +JS_LIBC_EXTERN void js_std_free_handlers(JSRuntime *rt); +JS_LIBC_EXTERN void js_std_dump_error(JSContext *ctx); +JS_LIBC_EXTERN uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, + const char *filename); +JS_LIBC_EXTERN int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val, + bool use_realpath, bool is_main); +JS_LIBC_EXTERN JSModuleDef *js_module_loader(JSContext *ctx, + const char *module_name, void *opaque, + JSValueConst attributes); +JS_LIBC_EXTERN int js_module_check_attributes(JSContext *ctx, void *opaque, + JSValueConst attributes); +JS_LIBC_EXTERN int js_module_test_json(JSContext *ctx, JSValueConst attributes); +JS_LIBC_EXTERN void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, + size_t buf_len, int flags); +JS_LIBC_EXTERN void js_std_promise_rejection_tracker(JSContext *ctx, + JSValueConst promise, + JSValueConst reason, + bool is_handled, + void *opaque); +// Defaults to JS_NewRuntime, no-op if compiled without worker support. +// Call before creating the first worker thread. +JS_LIBC_EXTERN void js_std_set_worker_new_runtime_func(JSRuntime *(*func)(void)); +// Defaults to JS_NewContext, no-op if compiled without worker support. +// Call before creating the first worker thread. +JS_LIBC_EXTERN void js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt)); + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* QUICKJS_LIBC_H */ diff --git a/subprojects/sqlite-js/upstream/libs/quickjs.c b/subprojects/sqlite-js/upstream/libs/quickjs.c new file mode 100644 index 0000000000..6f9fdd51f3 --- /dev/null +++ b/subprojects/sqlite-js/upstream/libs/quickjs.c @@ -0,0 +1,82922 @@ +#if defined(QJS_BUILD_LIBC) && defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +/* + * QuickJS C atomics definitions + * + * Copyright (c) 2023 Marcin Kolny + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#if (defined(__GNUC__) || defined(__GNUG__)) && !defined(__clang__) + // Use GCC builtins for version < 4.9 +# if((__GNUC__ << 16) + __GNUC_MINOR__ < ((4) << 16) + 9) +# define GCC_BUILTIN_ATOMICS +# endif +#endif + +#ifdef GCC_BUILTIN_ATOMICS +#define atomic_fetch_add(obj, arg) \ + __atomic_fetch_add(obj, arg, __ATOMIC_SEQ_CST) +#define atomic_compare_exchange_strong(obj, expected, desired) \ + __atomic_compare_exchange_n(obj, expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) +#define atomic_exchange(obj, desired) \ + __atomic_exchange_n (obj, desired, __ATOMIC_SEQ_CST) +#define atomic_load(obj) \ + __atomic_load_n(obj, __ATOMIC_SEQ_CST) +#define atomic_store(obj, desired) \ + __atomic_store_n(obj, desired, __ATOMIC_SEQ_CST) +#define atomic_fetch_or(obj, arg) \ + __atomic_fetch_or(obj, arg, __ATOMIC_SEQ_CST) +#define atomic_fetch_xor(obj, arg) \ + __atomic_fetch_xor(obj, arg, __ATOMIC_SEQ_CST) +#define atomic_fetch_and(obj, arg) \ + __atomic_fetch_and(obj, arg, __ATOMIC_SEQ_CST) +#define atomic_fetch_sub(obj, arg) \ + __atomic_fetch_sub(obj, arg, __ATOMIC_SEQ_CST) +#define _Atomic +#else +#include +#endif +/* + * C utilities + * + * Copyright (c) 2017 Fabrice Bellard + * Copyright (c) 2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef CUTILS_H +#define CUTILS_H + +#include +#include +#include +#include +#if !defined(_MSC_VER) +#include +#endif +#if defined(__APPLE__) +#include +#endif +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(_MSC_VER) +#include +#define alloca _alloca +#define ssize_t ptrdiff_t +#endif +#if defined(__APPLE__) +#include +#elif defined(__linux__) || defined(__ANDROID__) || defined(__CYGWIN__) || defined(__GLIBC__) +#include +#elif defined(__FreeBSD__) +#include +#elif defined(_WIN32) +#include +#include +#include // _beginthread +#endif +#if !defined(_WIN32) && !defined(EMSCRIPTEN) && !defined(__wasi__) && !defined(__DJGPP) +#include +#include +#endif +#if !defined(_WIN32) +#include +#include +#endif + +#if defined(__sun) +#undef __maybe_unused +#endif + +#if defined(_MSC_VER) && !defined(__clang__) +# define likely(x) (x) +# define unlikely(x) (x) +# define no_inline __declspec(noinline) +# define __maybe_unused +# define __attribute__(x) +# define __attribute(x) +#else +# define likely(x) __builtin_expect(!!(x), 1) +# define unlikely(x) __builtin_expect(!!(x), 0) +# define no_inline __attribute__((noinline)) +# define __maybe_unused __attribute__((unused)) +#endif + +#ifndef offsetof +#define offsetof(type, field) ((size_t) &((type *)0)->field) +#endif +#ifndef countof +#define countof(x) (sizeof(x) / sizeof((x)[0])) +#ifndef endof +#define endof(x) ((x) + countof(x)) +#endif +#endif +#ifndef container_of +/* return the pointer of type 'type *' containing 'ptr' as field 'member' */ +#define container_of(ptr, type, member) ((type *)((uint8_t *)(ptr) - offsetof(type, member))) +#endif + +#if defined(_MSC_VER) || defined(__cplusplus) +#define minimum_length(n) n +#else +#define minimum_length(n) static n +#endif + +/* Borrowed from Folly */ +#ifndef JS_PRINTF_FORMAT +#ifdef _MSC_VER +#include +#define JS_PRINTF_FORMAT _Printf_format_string_ +#define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) +#else +#define JS_PRINTF_FORMAT +#if !defined(__clang__) && defined(__GNUC__) +#define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \ + __attribute__((format(gnu_printf, format_param, dots_param))) +#else +#define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \ + __attribute__((format(printf, format_param, dots_param))) +#endif +#endif +#endif + +#if defined(PATH_MAX) +# define JS__PATH_MAX PATH_MAX +#elif defined(_WIN32) +# define JS__PATH_MAX 32767 +#else +# define JS__PATH_MAX 8192 +#endif + +static inline void js__pstrcpy(char *buf, int buf_size, const char *str); +static inline char *js__pstrcat(char *buf, int buf_size, const char *s); +static inline int js__strstart(const char *str, const char *val, const char **ptr); +static inline int js__has_suffix(const char *str, const char *suffix); + +static inline uint8_t is_be(void) { + union { + uint16_t a; + uint8_t b; + } u = { 0x100 }; + return u.b; +} + +static inline int max_int(int a, int b) +{ + if (a > b) + return a; + else + return b; +} + +static inline int min_int(int a, int b) +{ + if (a < b) + return a; + else + return b; +} + +static inline uint32_t max_uint32(uint32_t a, uint32_t b) +{ + if (a > b) + return a; + else + return b; +} + +static inline uint32_t min_uint32(uint32_t a, uint32_t b) +{ + if (a < b) + return a; + else + return b; +} + +static inline int64_t max_int64(int64_t a, int64_t b) +{ + if (a > b) + return a; + else + return b; +} + +static inline int64_t min_int64(int64_t a, int64_t b) +{ + if (a < b) + return a; + else + return b; +} + +/* WARNING: undefined if a = 0 */ +static inline int clz32(unsigned int a) +{ +#if defined(_MSC_VER) && !defined(__clang__) + unsigned long index; + _BitScanReverse(&index, a); + return 31 - index; +#else + return __builtin_clz(a); +#endif +} + +/* WARNING: undefined if a = 0 */ +static inline int clz64(uint64_t a) +{ +#if defined(_MSC_VER) && !defined(__clang__) +#if INTPTR_MAX == INT64_MAX + unsigned long index; + _BitScanReverse64(&index, a); + return 63 - index; +#else + if (a >> 32) + return clz32((unsigned)(a >> 32)); + else + return clz32((unsigned)a) + 32; +#endif +#else + return __builtin_clzll(a); +#endif +} + +/* WARNING: undefined if a = 0 */ +static inline int ctz32(unsigned int a) +{ +#if defined(_MSC_VER) && !defined(__clang__) + unsigned long index; + _BitScanForward(&index, a); + return index; +#else + return __builtin_ctz(a); +#endif +} + +/* WARNING: undefined if a = 0 */ +static inline int ctz64(uint64_t a) +{ +#if defined(_MSC_VER) && !defined(__clang__) + unsigned long index; + _BitScanForward64(&index, a); + return index; +#else + return __builtin_ctzll(a); +#endif +} + +static inline uint64_t get_u64(const uint8_t *tab) +{ + uint64_t v; + memcpy(&v, tab, sizeof(v)); + return v; +} + +static inline int64_t get_i64(const uint8_t *tab) +{ + int64_t v; + memcpy(&v, tab, sizeof(v)); + return v; +} + +static inline void put_u64(uint8_t *tab, uint64_t val) +{ + memcpy(tab, &val, sizeof(val)); +} + +static inline uint32_t get_u32(const uint8_t *tab) +{ + uint32_t v; + memcpy(&v, tab, sizeof(v)); + return v; +} + +static inline int32_t get_i32(const uint8_t *tab) +{ + int32_t v; + memcpy(&v, tab, sizeof(v)); + return v; +} + +static inline void put_u32(uint8_t *tab, uint32_t val) +{ + memcpy(tab, &val, sizeof(val)); +} + +static inline uint32_t get_u16(const uint8_t *tab) +{ + uint16_t v; + memcpy(&v, tab, sizeof(v)); + return v; +} + +static inline int32_t get_i16(const uint8_t *tab) +{ + int16_t v; + memcpy(&v, tab, sizeof(v)); + return v; +} + +static inline void put_u16(uint8_t *tab, uint16_t val) +{ + memcpy(tab, &val, sizeof(val)); +} + +static inline uint32_t get_u8(const uint8_t *tab) +{ + return *tab; +} + +static inline int32_t get_i8(const uint8_t *tab) +{ + return (int8_t)*tab; +} + +static inline void put_u8(uint8_t *tab, uint8_t val) +{ + *tab = val; +} + +#ifndef bswap16 +static inline uint16_t bswap16(uint16_t x) +{ + return (x >> 8) | (x << 8); +} +#endif + +#ifndef bswap32 +static inline uint32_t bswap32(uint32_t v) +{ + return ((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >> 8) | + ((v & 0x0000ff00) << 8) | ((v & 0x000000ff) << 24); +} +#endif + +#ifndef bswap64 +static inline uint64_t bswap64(uint64_t v) +{ + return ((v & ((uint64_t)0xff << (7 * 8))) >> (7 * 8)) | + ((v & ((uint64_t)0xff << (6 * 8))) >> (5 * 8)) | + ((v & ((uint64_t)0xff << (5 * 8))) >> (3 * 8)) | + ((v & ((uint64_t)0xff << (4 * 8))) >> (1 * 8)) | + ((v & ((uint64_t)0xff << (3 * 8))) << (1 * 8)) | + ((v & ((uint64_t)0xff << (2 * 8))) << (3 * 8)) | + ((v & ((uint64_t)0xff << (1 * 8))) << (5 * 8)) | + ((v & ((uint64_t)0xff << (0 * 8))) << (7 * 8)); +} +#endif + +static inline void inplace_bswap16(uint8_t *tab) { + put_u16(tab, bswap16(get_u16(tab))); +} + +static inline void inplace_bswap32(uint8_t *tab) { + put_u32(tab, bswap32(get_u32(tab))); +} + +static inline double fromfp16(uint16_t v) { + double d, s; + int e; + if ((v & 0x7C00) == 0x7C00) { + d = (v & 0x3FF) ? NAN : INFINITY; + } else { + d = (v & 0x3FF) / 1024.; + e = (v & 0x7C00) >> 10; + if (e == 0) { + e = -14; + } else { + d += 1; + e -= 15; + } + d = scalbn(d, e); + } + s = (v & 0x8000) ? -1.0 : 1.0; + return d * s; +} + +static inline uint16_t tofp16(double d) { + uint16_t f, s; + double t; + int e; + s = 0; + if (copysign(1, d) < 0) { // preserve sign when |d| is negative zero + d = -d; + s = 0x8000; + } + if (isinf(d)) + return s | 0x7C00; + if (isnan(d)) + return s | 0x7C01; + if (d == 0) + return s | 0; + d = 2 * frexp(d, &e); + e--; + if (e > 15) + return s | 0x7C00; // out of range, return +/-infinity + if (e < -25) { + d = 0; + e = 0; + } else if (e < -14) { + d = scalbn(d, e + 14); + e = 0; + } else { + d -= 1; + e += 15; + } + d *= 1024.; + f = (uint16_t)d; + t = d - f; + if (t < 0.5) + goto done; + if (t == 0.5) + if ((f & 1) == 0) + goto done; + // adjust for rounding + if (++f == 1024) { + f = 0; + if (++e == 31) + return s | 0x7C00; // out of range, return +/-infinity + } +done: + return s | (e << 10) | f; +} + +static inline int isfp16nan(uint16_t v) { + return (v & 0x7FFF) > 0x7C00; +} + +static inline int isfp16zero(uint16_t v) { + return (v & 0x7FFF) == 0; +} + +/* XXX: should take an extra argument to pass slack information to the caller */ +typedef void *DynBufReallocFunc(void *opaque, void *ptr, size_t size); + +typedef struct DynBuf { + uint8_t *buf; + size_t size; + size_t allocated_size; + bool error; /* true if a memory allocation error occurred */ + DynBufReallocFunc *realloc_func; + void *opaque; /* for realloc_func */ +} DynBuf; + +static inline void dbuf_init(DynBuf *s); +static inline void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func); +static inline int dbuf_claim(DynBuf *s, size_t len); +static inline int dbuf_put(DynBuf *s, const void *data, size_t len); +static inline int dbuf_put_self(DynBuf *s, size_t offset, size_t len); +static inline int __dbuf_putc(DynBuf *s, uint8_t c); +static inline int __dbuf_put_u16(DynBuf *s, uint16_t val); +static inline int __dbuf_put_u32(DynBuf *s, uint32_t val); +static inline int __dbuf_put_u64(DynBuf *s, uint64_t val); +static inline int dbuf_putstr(DynBuf *s, const char *str); +static inline int dbuf_putc(DynBuf *s, uint8_t val) +{ + if (unlikely((s->allocated_size - s->size) < 1)) + return __dbuf_putc(s, val); + s->buf[s->size++] = val; + return 0; +} +static inline int dbuf_put_u16(DynBuf *s, uint16_t val) +{ + if (unlikely((s->allocated_size - s->size) < 2)) + return __dbuf_put_u16(s, val); + put_u16(s->buf + s->size, val); + s->size += 2; + return 0; +} +static inline int dbuf_put_u32(DynBuf *s, uint32_t val) +{ + if (unlikely((s->allocated_size - s->size) < 4)) + return __dbuf_put_u32(s, val); + put_u32(s->buf + s->size, val); + s->size += 4; + return 0; +} +static inline int dbuf_put_u64(DynBuf *s, uint64_t val) +{ + if (unlikely((s->allocated_size - s->size) < 8)) + return __dbuf_put_u64(s, val); + put_u64(s->buf + s->size, val); + s->size += 8; + return 0; +} +static inline int JS_PRINTF_FORMAT_ATTR(2, 3) dbuf_printf(DynBuf *s, JS_PRINTF_FORMAT const char *fmt, ...); +static inline void dbuf_free(DynBuf *s); +static inline bool dbuf_error(DynBuf *s) { + return s->error; +} +static inline void dbuf_set_error(DynBuf *s) +{ + s->error = true; +} + +/*---- UTF-8 and UTF-16 handling ----*/ + +#define UTF8_CHAR_LEN_MAX 4 + +enum { + UTF8_PLAIN_ASCII = 0, // 7-bit ASCII plain text + UTF8_NON_ASCII = 1, // has non ASCII code points (8-bit or more) + UTF8_HAS_16BIT = 2, // has 16-bit code points + UTF8_HAS_NON_BMP1 = 4, // has non-BMP1 code points, needs UTF-16 surrogate pairs + UTF8_HAS_ERRORS = 8, // has encoding errors +}; +static inline int utf8_scan(const char *buf, size_t len, size_t *plen); +static inline size_t utf8_encode_len(uint32_t c); +static inline size_t utf8_encode(uint8_t buf[minimum_length(UTF8_CHAR_LEN_MAX)], uint32_t c); +static inline uint32_t utf8_decode_len(const uint8_t *p, size_t max_len, const uint8_t **pp); +static inline uint32_t utf8_decode(const uint8_t *p, const uint8_t **pp); +static inline size_t utf8_decode_buf8(uint8_t *dest, size_t dest_len, const char *src, size_t src_len); +static inline size_t utf8_decode_buf16(uint16_t *dest, size_t dest_len, const char *src, size_t src_len); +static inline size_t utf8_encode_buf8(char *dest, size_t dest_len, const uint8_t *src, size_t src_len); +static inline size_t utf8_encode_buf16(char *dest, size_t dest_len, const uint16_t *src, size_t src_len); + +static inline bool is_surrogate(uint32_t c) +{ + return (c >> 11) == (0xD800 >> 11); // 0xD800-0xDFFF +} + +static inline bool is_hi_surrogate(uint32_t c) +{ + return (c >> 10) == (0xD800 >> 10); // 0xD800-0xDBFF +} + +static inline bool is_lo_surrogate(uint32_t c) +{ + return (c >> 10) == (0xDC00 >> 10); // 0xDC00-0xDFFF +} + +static inline uint32_t get_hi_surrogate(uint32_t c) +{ + return (c >> 10) - (0x10000 >> 10) + 0xD800; +} + +static inline uint32_t get_lo_surrogate(uint32_t c) +{ + return (c & 0x3FF) | 0xDC00; +} + +static inline uint32_t from_surrogate(uint32_t hi, uint32_t lo) +{ + return 65536 + 1024 * (hi & 1023) + (lo & 1023); +} + +static inline int from_hex(int c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + else if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + else if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + else + return -1; +} + +static inline uint8_t is_upper_ascii(uint8_t c) { + return c >= 'A' && c <= 'Z'; +} + +static inline uint8_t to_upper_ascii(uint8_t c) { + return c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; +} + +static inline void rqsort(void *base, size_t nmemb, size_t size, + int (*cmp)(const void *, const void *, void *), + void *arg); + +static inline uint64_t float64_as_uint64(double d) +{ + union { + double d; + uint64_t u64; + } u; + u.d = d; + return u.u64; +} + +static inline double uint64_as_float64(uint64_t u64) +{ + union { + double d; + uint64_t u64; + } u; + u.u64 = u64; + return u.d; +} + +static inline int64_t js__gettimeofday_us(void); +static inline uint64_t js__hrtime_ns(void); + +static inline size_t js__malloc_usable_size(const void *ptr) +{ +#if defined(__APPLE__) + return malloc_size(ptr); +#elif defined(_WIN32) + return _msize((void *)ptr); +#elif defined(__linux__) || defined(__ANDROID__) || defined(__CYGWIN__) || defined(__FreeBSD__) || defined(__GLIBC__) + return malloc_usable_size((void *)ptr); +#else + return 0; +#endif +} + +static inline int js_exepath(char* buffer, size_t* size); + +/* Cross-platform threading APIs. */ + +#if defined(EMSCRIPTEN) || defined(__wasi__) || defined(__DJGPP) + +#define JS_HAVE_THREADS 0 + +#else + +#define JS_HAVE_THREADS 1 + +#if defined(_WIN32) +#define JS_ONCE_INIT INIT_ONCE_STATIC_INIT +typedef INIT_ONCE js_once_t; +typedef CRITICAL_SECTION js_mutex_t; +typedef CONDITION_VARIABLE js_cond_t; +typedef HANDLE js_thread_t; +#else +#define JS_ONCE_INIT PTHREAD_ONCE_INIT +typedef pthread_once_t js_once_t; +typedef pthread_mutex_t js_mutex_t; +typedef pthread_cond_t js_cond_t; +typedef pthread_t js_thread_t; +#endif + +static inline void js_once(js_once_t *guard, void (*callback)(void)); + +static inline void js_mutex_init(js_mutex_t *mutex); +static inline void js_mutex_destroy(js_mutex_t *mutex); +static inline void js_mutex_lock(js_mutex_t *mutex); +static inline void js_mutex_unlock(js_mutex_t *mutex); + +static inline void js_cond_init(js_cond_t *cond); +static inline void js_cond_destroy(js_cond_t *cond); +static inline void js_cond_signal(js_cond_t *cond); +static inline void js_cond_broadcast(js_cond_t *cond); +static inline void js_cond_wait(js_cond_t *cond, js_mutex_t *mutex); +static inline int js_cond_timedwait(js_cond_t *cond, js_mutex_t *mutex, uint64_t timeout); + +enum { + JS_THREAD_CREATE_DETACHED = 1, +}; + +// creates threads with 2 MB stacks (glibc default) +static inline int js_thread_create(js_thread_t *thrd, void (*start)(void *), void *arg, + int flags); +static inline int js_thread_join(js_thread_t thrd); + +#endif /* !defined(EMSCRIPTEN) && !defined(__wasi__) */ + +// JS requires strict rounding behavior. Turn on 64-bits double precision +// and disable x87 80-bits extended precision for intermediate floating-point +// results. 0x300 is extended precision, 0x200 is double precision. +// Note that `*&cw` in the asm constraints looks redundant but isn't. +#if defined(__i386__) && !defined(_MSC_VER) +#define JS_X87_FPCW_SAVE_AND_ADJUST(cw) \ + unsigned short cw; \ + __asm__ __volatile__("fnstcw %0" : "=m"(*&cw)); \ + do { \ + unsigned short t = 0x200 | (cw & ~0x300); \ + __asm__ __volatile__("fldcw %0" : /*empty*/ : "m"(*&t)); \ + } while (0) +#define JS_X87_FPCW_RESTORE(cw) \ + __asm__ __volatile__("fldcw %0" : /*empty*/ : "m"(*&cw)) +#else +#define JS_X87_FPCW_SAVE_AND_ADJUST(cw) +#define JS_X87_FPCW_RESTORE(cw) +#endif + +#undef NANOSEC +#define NANOSEC ((uint64_t) 1e9) + +static inline void js__pstrcpy(char *buf, int buf_size, const char *str) +{ + int c; + char *q = buf; + + if (buf_size <= 0) + return; + + for(;;) { + c = *str++; + if (c == 0 || q >= buf + buf_size - 1) + break; + *q++ = c; + } + *q = '\0'; +} + +/* strcat and truncate. */ +static inline char *js__pstrcat(char *buf, int buf_size, const char *s) +{ + int len; + len = strlen(buf); + if (len < buf_size) + js__pstrcpy(buf + len, buf_size - len, s); + return buf; +} + +static inline int js__strstart(const char *str, const char *val, const char **ptr) +{ + const char *p, *q; + p = str; + q = val; + while (*q != '\0') { + if (*p != *q) + return 0; + p++; + q++; + } + if (ptr) + *ptr = p; + return 1; +} + +static inline int js__has_suffix(const char *str, const char *suffix) +{ + size_t len = strlen(str); + size_t slen = strlen(suffix); + return (len >= slen && !memcmp(str + len - slen, suffix, slen)); +} + +/* Dynamic buffer package */ + +static void *dbuf_default_realloc(void *opaque, void *ptr, size_t size) +{ + if (unlikely(size == 0)) { + free(ptr); + return NULL; + } + return realloc(ptr, size); +} + +static inline void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func) +{ + memset(s, 0, sizeof(*s)); + if (!realloc_func) + realloc_func = dbuf_default_realloc; + s->opaque = opaque; + s->realloc_func = realloc_func; +} + +static inline void dbuf_init(DynBuf *s) +{ + dbuf_init2(s, NULL, NULL); +} + +/* Try to allocate 'len' more bytes. return < 0 if error */ +static inline int dbuf_claim(DynBuf *s, size_t len) +{ + size_t new_size, size, new_allocated_size; + uint8_t *new_buf; + new_size = s->size + len; + if (new_size < len) + return -1; /* overflow */ + if (new_size > s->allocated_size) { + if (s->error) + return -1; + size = s->allocated_size + (s->allocated_size / 2); + if (size < new_size || size < s->allocated_size) /* overflow test */ + new_allocated_size = new_size; + else + new_allocated_size = size; + new_buf = s->realloc_func(s->opaque, s->buf, new_allocated_size); + if (!new_buf) { + s->error = true; + return -1; + } + s->buf = new_buf; + s->allocated_size = new_allocated_size; + } + return 0; +} + +static inline int dbuf_put(DynBuf *s, const void *data, size_t len) +{ + if (unlikely((s->size + len) > s->allocated_size)) { + if (dbuf_claim(s, len)) + return -1; + } + if (len > 0) { + memcpy(s->buf + s->size, data, len); + s->size += len; + } + return 0; +} + +static inline int dbuf_put_self(DynBuf *s, size_t offset, size_t len) +{ + if (unlikely((s->size + len) > s->allocated_size)) { + if (dbuf_claim(s, len)) + return -1; + } + if (len > 0) { + memcpy(s->buf + s->size, s->buf + offset, len); + s->size += len; + } + return 0; +} + +static inline int __dbuf_putc(DynBuf *s, uint8_t c) +{ + return dbuf_put(s, &c, 1); +} + +static inline int __dbuf_put_u16(DynBuf *s, uint16_t val) +{ + return dbuf_put(s, (uint8_t *)&val, 2); +} + +static inline int __dbuf_put_u32(DynBuf *s, uint32_t val) +{ + return dbuf_put(s, (uint8_t *)&val, 4); +} + +static inline int __dbuf_put_u64(DynBuf *s, uint64_t val) +{ + return dbuf_put(s, (uint8_t *)&val, 8); +} + +static inline int dbuf_putstr(DynBuf *s, const char *str) +{ + return dbuf_put(s, (const uint8_t *)str, strlen(str)); +} + +static inline int JS_PRINTF_FORMAT_ATTR(2, 3) dbuf_printf(DynBuf *s, JS_PRINTF_FORMAT const char *fmt, ...) +{ + va_list ap; + char buf[128]; + int len; + + va_start(ap, fmt); + len = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + if (len < (int)sizeof(buf)) { + /* fast case */ + return dbuf_put(s, (uint8_t *)buf, len); + } else { + if (dbuf_claim(s, len + 1)) + return -1; + va_start(ap, fmt); + vsnprintf((char *)(s->buf + s->size), s->allocated_size - s->size, + fmt, ap); + va_end(ap); + s->size += len; + } + return 0; +} + +static inline void dbuf_free(DynBuf *s) +{ + /* we test s->buf as a fail safe to avoid crashing if dbuf_free() + is called twice */ + if (s->buf) { + s->realloc_func(s->opaque, s->buf, 0); + } + memset(s, 0, sizeof(*s)); +} + +/*--- UTF-8 utility functions --*/ + +/* Note: only encode valid codepoints (0x0000..0x10FFFF). + At most UTF8_CHAR_LEN_MAX bytes are output. */ + +/* Compute the number of bytes of the UTF-8 encoding for a codepoint + `c` is a code-point. + Returns the number of bytes. If a codepoint is beyond 0x10FFFF the + return value is 3 as the codepoint would be encoded as 0xFFFD. + */ +static inline size_t utf8_encode_len(uint32_t c) +{ + if (c < 0x80) + return 1; + if (c < 0x800) + return 2; + if (c < 0x10000) + return 3; + if (c < 0x110000) + return 4; + return 3; +} + +/* Encode a codepoint in UTF-8 + `buf` points to an array of at least `UTF8_CHAR_LEN_MAX` bytes + `c` is a code-point. + Returns the number of bytes. If a codepoint is beyond 0x10FFFF the + return value is 3 and the codepoint is encoded as 0xFFFD. + No null byte is stored after the encoded bytes. + Return value is in range 1..4 + */ +static inline size_t utf8_encode(uint8_t buf[minimum_length(UTF8_CHAR_LEN_MAX)], uint32_t c) +{ + if (c < 0x80) { + buf[0] = c; + return 1; + } + if (c < 0x800) { + buf[0] = (c >> 6) | 0xC0; + buf[1] = (c & 0x3F) | 0x80; + return 2; + } + if (c < 0x10000) { + buf[0] = (c >> 12) | 0xE0; + buf[1] = ((c >> 6) & 0x3F) | 0x80; + buf[2] = (c & 0x3F) | 0x80; + return 3; + } + if (c < 0x110000) { + buf[0] = (c >> 18) | 0xF0; + buf[1] = ((c >> 12) & 0x3F) | 0x80; + buf[2] = ((c >> 6) & 0x3F) | 0x80; + buf[3] = (c & 0x3F) | 0x80; + return 4; + } + buf[0] = (0xFFFD >> 12) | 0xE0; + buf[1] = ((0xFFFD >> 6) & 0x3F) | 0x80; + buf[2] = (0xFFFD & 0x3F) | 0x80; + return 3; +} + +/* Decode a single code point from a UTF-8 encoded array of bytes + `p` is a valid pointer to an array of bytes + `pp` is a valid pointer to a `const uint8_t *` to store a pointer + to the byte following the current sequence. + Return the code point at `p`, in the range `0..0x10FFFF` + Return 0xFFFD on error. Only a single byte is consumed in this case + The maximum length for a UTF-8 byte sequence is 4 bytes. + This implements the algorithm specified in whatwg.org, except it accepts + UTF-8 encoded surrogates as JavaScript allows them in strings. + The source string is assumed to have at least UTF8_CHAR_LEN_MAX bytes + or be null terminated. + If `p[0]` is '\0', the return value is `0` and the byte is consumed. + cf: https://encoding.spec.whatwg.org/#utf-8-encoder + */ +static inline uint32_t utf8_decode(const uint8_t *p, const uint8_t **pp) +{ + uint32_t c; + uint8_t lower, upper; + + c = *p++; + if (c < 0x80) { + *pp = p; + return c; + } + switch(c) { + case 0xC2: case 0xC3: + case 0xC4: case 0xC5: case 0xC6: case 0xC7: + case 0xC8: case 0xC9: case 0xCA: case 0xCB: + case 0xCC: case 0xCD: case 0xCE: case 0xCF: + case 0xD0: case 0xD1: case 0xD2: case 0xD3: + case 0xD4: case 0xD5: case 0xD6: case 0xD7: + case 0xD8: case 0xD9: case 0xDA: case 0xDB: + case 0xDC: case 0xDD: case 0xDE: case 0xDF: + if (*p >= 0x80 && *p <= 0xBF) { + *pp = p + 1; + return ((c - 0xC0) << 6) + (*p - 0x80); + } + // otherwise encoding error + break; + case 0xE0: + lower = 0xA0; /* reject invalid encoding */ + goto need2; + case 0xE1: case 0xE2: case 0xE3: + case 0xE4: case 0xE5: case 0xE6: case 0xE7: + case 0xE8: case 0xE9: case 0xEA: case 0xEB: + case 0xEC: case 0xED: case 0xEE: case 0xEF: + lower = 0x80; + need2: + if (*p >= lower && *p <= 0xBF && p[1] >= 0x80 && p[1] <= 0xBF) { + *pp = p + 2; + return ((c - 0xE0) << 12) + ((*p - 0x80) << 6) + (p[1] - 0x80); + } + // otherwise encoding error + break; + case 0xF0: + lower = 0x90; /* reject invalid encoding */ + upper = 0xBF; + goto need3; + case 0xF4: + lower = 0x80; + upper = 0x8F; /* reject values above 0x10FFFF */ + goto need3; + case 0xF1: case 0xF2: case 0xF3: + lower = 0x80; + upper = 0xBF; + need3: + if (*p >= lower && *p <= upper && p[1] >= 0x80 && p[1] <= 0xBF + && p[2] >= 0x80 && p[2] <= 0xBF) { + *pp = p + 3; + return ((c - 0xF0) << 18) + ((*p - 0x80) << 12) + + ((p[1] - 0x80) << 6) + (p[2] - 0x80); + } + // otherwise encoding error + break; + default: + // invalid lead byte + break; + } + *pp = p; + return 0xFFFD; +} + +static inline uint32_t utf8_decode_len(const uint8_t *p, size_t max_len, const uint8_t **pp) { + switch (max_len) { + case 0: + *pp = p; + return 0xFFFD; + case 1: + if (*p < 0x80) + goto good; + break; + case 2: + if (*p < 0xE0) + goto good; + break; + case 3: + if (*p < 0xF0) + goto good; + break; + default: + good: + return utf8_decode(p, pp); + } + *pp = p + 1; + return 0xFFFD; +} + +/* Scan a UTF-8 encoded buffer for content type + `buf` is a valid pointer to a UTF-8 encoded string + `len` is the number of bytes to scan + `plen` points to a `size_t` variable to receive the number of units + Return value is a mask of bits. + - `UTF8_PLAIN_ASCII`: return value for 7-bit ASCII plain text + - `UTF8_NON_ASCII`: bit for non ASCII code points (8-bit or more) + - `UTF8_HAS_16BIT`: bit for 16-bit code points + - `UTF8_HAS_NON_BMP1`: bit for non-BMP1 code points, needs UTF-16 surrogate pairs + - `UTF8_HAS_ERRORS`: bit for encoding errors + */ +static inline int utf8_scan(const char *buf, size_t buf_len, size_t *plen) +{ + const uint8_t *p, *p_end, *p_next; + size_t i, len; + int kind; + uint8_t cbits; + + kind = UTF8_PLAIN_ASCII; + cbits = 0; + len = buf_len; + // TODO: handle more than 1 byte at a time + for (i = 0; i < buf_len; i++) + cbits |= buf[i]; + if (cbits >= 0x80) { + p = (const uint8_t *)buf; + p_end = p + buf_len; + kind = UTF8_NON_ASCII; + len = 0; + while (p < p_end) { + len++; + if (*p++ >= 0x80) { + /* parse UTF-8 sequence, check for encoding error */ + uint32_t c = utf8_decode_len(p - 1, p_end - (p - 1), &p_next); + if (p_next == p) + kind |= UTF8_HAS_ERRORS; + p = p_next; + if (c > 0xFF) { + kind |= UTF8_HAS_16BIT; + if (c > 0xFFFF) { + len++; + kind |= UTF8_HAS_NON_BMP1; + } + } + } + } + } + *plen = len; + return kind; +} + +/* Decode a string encoded in UTF-8 into an array of bytes + `src` points to the source string. It is assumed to be correctly encoded + and only contains code points below 0x800 + `src_len` is the length of the source string + `dest` points to the destination array, it can be null if `dest_len` is `0` + `dest_len` is the length of the destination array. A null + terminator is stored at the end of the array unless `dest_len` is `0`. + */ +static inline size_t utf8_decode_buf8(uint8_t *dest, size_t dest_len, const char *src, size_t src_len) +{ + const uint8_t *p, *p_end; + size_t i; + + p = (const uint8_t *)src; + p_end = p + src_len; + for (i = 0; p < p_end; i++) { + uint32_t c = *p++; + if (c >= 0xC0) + c = (c << 6) + *p++ - ((0xC0 << 6) + 0x80); + if (i < dest_len) + dest[i] = c; + } + if (i < dest_len) + dest[i] = '\0'; + else if (dest_len > 0) + dest[dest_len - 1] = '\0'; + return i; +} + +/* Decode a string encoded in UTF-8 into an array of 16-bit words + `src` points to the source string. It is assumed to be correctly encoded. + `src_len` is the length of the source string + `dest` points to the destination array, it can be null if `dest_len` is `0` + `dest_len` is the length of the destination array. No null terminator is + stored at the end of the array. + */ +static inline size_t utf8_decode_buf16(uint16_t *dest, size_t dest_len, const char *src, size_t src_len) +{ + const uint8_t *p, *p_end; + size_t i; + + p = (const uint8_t *)src; + p_end = p + src_len; + for (i = 0; p < p_end; i++) { + uint32_t c = *p++; + if (c >= 0x80) { + /* parse utf-8 sequence */ + c = utf8_decode_len(p - 1, p_end - (p - 1), &p); + /* encoding errors are converted as 0xFFFD and use a single byte */ + if (c > 0xFFFF) { + if (i < dest_len) + dest[i] = get_hi_surrogate(c); + i++; + c = get_lo_surrogate(c); + } + } + if (i < dest_len) + dest[i] = c; + } + return i; +} + +/* Encode a buffer of 8-bit bytes as a UTF-8 encoded string + `src` points to the source buffer. + `src_len` is the length of the source buffer + `dest` points to the destination array, it can be null if `dest_len` is `0` + `dest_len` is the length in bytes of the destination array. A null + terminator is stored at the end of the array unless `dest_len` is `0`. + */ +static inline size_t utf8_encode_buf8(char *dest, size_t dest_len, const uint8_t *src, size_t src_len) +{ + size_t i, j; + uint32_t c; + + for (i = j = 0; i < src_len; i++) { + c = src[i]; + if (c < 0x80) { + if (j + 1 >= dest_len) + goto overflow; + dest[j++] = c; + } else { + if (j + 2 >= dest_len) + goto overflow; + dest[j++] = (c >> 6) | 0xC0; + dest[j++] = (c & 0x3F) | 0x80; + } + } + if (j < dest_len) + dest[j] = '\0'; + return j; + +overflow: + if (j < dest_len) + dest[j] = '\0'; + while (i < src_len) + j += 1 + (src[i++] >= 0x80); + return j; +} + +/* Encode a buffer of 16-bit code points as a UTF-8 encoded string + `src` points to the source buffer. + `src_len` is the length of the source buffer + `dest` points to the destination array, it can be null if `dest_len` is `0` + `dest_len` is the length in bytes of the destination array. A null + terminator is stored at the end of the array unless `dest_len` is `0`. + */ +static inline size_t utf8_encode_buf16(char *dest, size_t dest_len, const uint16_t *src, size_t src_len) +{ + size_t i, j; + uint32_t c; + + for (i = j = 0; i < src_len;) { + c = src[i++]; + if (c < 0x80) { + if (j + 1 >= dest_len) + goto overflow; + dest[j++] = c; + } else { + if (is_hi_surrogate(c) && i < src_len && is_lo_surrogate(src[i])) + c = from_surrogate(c, src[i++]); + if (j + utf8_encode_len(c) >= dest_len) + goto overflow; + j += utf8_encode((uint8_t *)dest + j, c); + } + } + if (j < dest_len) + dest[j] = '\0'; + return j; + +overflow: + i -= 1 + (c > 0xFFFF); + if (j < dest_len) + dest[j] = '\0'; + while (i < src_len) { + c = src[i++]; + if (c < 0x80) { + j++; + } else { + if (is_hi_surrogate(c) && i < src_len && is_lo_surrogate(src[i])) + c = from_surrogate(c, src[i++]); + j += utf8_encode_len(c); + } + } + return j; +} + +/*---- sorting with opaque argument ----*/ + +typedef void (*exchange_f)(void *a, void *b, size_t size); +typedef int (*cmp_f)(const void *, const void *, void *opaque); + +static void exchange_bytes(void *a, void *b, size_t size) { + uint8_t *ap = (uint8_t *)a; + uint8_t *bp = (uint8_t *)b; + + while (size-- != 0) { + uint8_t t = *ap; + *ap++ = *bp; + *bp++ = t; + } +} + +static void exchange_one_byte(void *a, void *b, size_t size) { + uint8_t *ap = (uint8_t *)a; + uint8_t *bp = (uint8_t *)b; + uint8_t t = *ap; + *ap = *bp; + *bp = t; +} + +static void exchange_int16s(void *a, void *b, size_t size) { + uint16_t *ap = (uint16_t *)a; + uint16_t *bp = (uint16_t *)b; + + for (size /= sizeof(uint16_t); size-- != 0;) { + uint16_t t = *ap; + *ap++ = *bp; + *bp++ = t; + } +} + +static void exchange_one_int16(void *a, void *b, size_t size) { + uint16_t *ap = (uint16_t *)a; + uint16_t *bp = (uint16_t *)b; + uint16_t t = *ap; + *ap = *bp; + *bp = t; +} + +static void exchange_int32s(void *a, void *b, size_t size) { + uint32_t *ap = (uint32_t *)a; + uint32_t *bp = (uint32_t *)b; + + for (size /= sizeof(uint32_t); size-- != 0;) { + uint32_t t = *ap; + *ap++ = *bp; + *bp++ = t; + } +} + +static void exchange_one_int32(void *a, void *b, size_t size) { + uint32_t *ap = (uint32_t *)a; + uint32_t *bp = (uint32_t *)b; + uint32_t t = *ap; + *ap = *bp; + *bp = t; +} + +static void exchange_int64s(void *a, void *b, size_t size) { + uint64_t *ap = (uint64_t *)a; + uint64_t *bp = (uint64_t *)b; + + for (size /= sizeof(uint64_t); size-- != 0;) { + uint64_t t = *ap; + *ap++ = *bp; + *bp++ = t; + } +} + +static void exchange_one_int64(void *a, void *b, size_t size) { + uint64_t *ap = (uint64_t *)a; + uint64_t *bp = (uint64_t *)b; + uint64_t t = *ap; + *ap = *bp; + *bp = t; +} + +static void exchange_int128s(void *a, void *b, size_t size) { + uint64_t *ap = (uint64_t *)a; + uint64_t *bp = (uint64_t *)b; + + for (size /= sizeof(uint64_t) * 2; size-- != 0; ap += 2, bp += 2) { + uint64_t t = ap[0]; + uint64_t u = ap[1]; + ap[0] = bp[0]; + ap[1] = bp[1]; + bp[0] = t; + bp[1] = u; + } +} + +static void exchange_one_int128(void *a, void *b, size_t size) { + uint64_t *ap = (uint64_t *)a; + uint64_t *bp = (uint64_t *)b; + uint64_t t = ap[0]; + uint64_t u = ap[1]; + ap[0] = bp[0]; + ap[1] = bp[1]; + bp[0] = t; + bp[1] = u; +} + +static inline exchange_f exchange_func(const void *base, size_t size) { + switch (((uintptr_t)base | (uintptr_t)size) & 15) { + case 0: + if (size == sizeof(uint64_t) * 2) + return exchange_one_int128; + else + return exchange_int128s; + case 8: + if (size == sizeof(uint64_t)) + return exchange_one_int64; + else + return exchange_int64s; + case 4: + case 12: + if (size == sizeof(uint32_t)) + return exchange_one_int32; + else + return exchange_int32s; + case 2: + case 6: + case 10: + case 14: + if (size == sizeof(uint16_t)) + return exchange_one_int16; + else + return exchange_int16s; + default: + if (size == 1) + return exchange_one_byte; + else + return exchange_bytes; + } +} + +static void heapsortx(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque) +{ + uint8_t *basep = (uint8_t *)base; + size_t i, n, c, r; + exchange_f swap = exchange_func(base, size); + + if (nmemb > 1) { + i = (nmemb / 2) * size; + n = nmemb * size; + + while (i > 0) { + i -= size; + for (r = i; (c = r * 2 + size) < n; r = c) { + if (c < n - size && cmp(basep + c, basep + c + size, opaque) <= 0) + c += size; + if (cmp(basep + r, basep + c, opaque) > 0) + break; + swap(basep + r, basep + c, size); + } + } + for (i = n - size; i > 0; i -= size) { + swap(basep, basep + i, size); + + for (r = 0; (c = r * 2 + size) < i; r = c) { + if (c < i - size && cmp(basep + c, basep + c + size, opaque) <= 0) + c += size; + if (cmp(basep + r, basep + c, opaque) > 0) + break; + swap(basep + r, basep + c, size); + } + } + } +} + +static inline void *med3(void *a, void *b, void *c, cmp_f cmp, void *opaque) +{ + return cmp(a, b, opaque) < 0 ? + (cmp(b, c, opaque) < 0 ? b : (cmp(a, c, opaque) < 0 ? c : a )) : + (cmp(b, c, opaque) > 0 ? b : (cmp(a, c, opaque) < 0 ? a : c )); +} + +/* pointer based version with local stack and insertion sort threshhold */ +static inline void rqsort(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque) +{ + struct { uint8_t *base; size_t count; int depth; } stack[50], *sp = stack; + uint8_t *ptr, *pi, *pj, *plt, *pgt, *top, *m; + size_t m4, i, lt, gt, span, span2; + int c, depth; + exchange_f swap = exchange_func(base, size); + exchange_f swap_block = exchange_func(base, size | 128); + + if (nmemb < 2 || size <= 0) + return; + + sp->base = (uint8_t *)base; + sp->count = nmemb; + sp->depth = 0; + sp++; + + while (sp > stack) { + sp--; + ptr = sp->base; + nmemb = sp->count; + depth = sp->depth; + + while (nmemb > 6) { + if (++depth > 50) { + /* depth check to ensure worst case logarithmic time */ + heapsortx(ptr, nmemb, size, cmp, opaque); + nmemb = 0; + break; + } + /* select median of 3 from 1/4, 1/2, 3/4 positions */ + /* should use median of 5 or 9? */ + m4 = (nmemb >> 2) * size; + m = med3(ptr + m4, ptr + 2 * m4, ptr + 3 * m4, cmp, opaque); + swap(ptr, m, size); /* move the pivot to the start or the array */ + i = lt = 1; + pi = plt = ptr + size; + gt = nmemb; + pj = pgt = top = ptr + nmemb * size; + for (;;) { + while (pi < pj && (c = cmp(ptr, pi, opaque)) >= 0) { + if (c == 0) { + swap(plt, pi, size); + lt++; + plt += size; + } + i++; + pi += size; + } + while (pi < (pj -= size) && (c = cmp(ptr, pj, opaque)) <= 0) { + if (c == 0) { + gt--; + pgt -= size; + swap(pgt, pj, size); + } + } + if (pi >= pj) + break; + swap(pi, pj, size); + i++; + pi += size; + } + /* array has 4 parts: + * from 0 to lt excluded: elements identical to pivot + * from lt to pi excluded: elements smaller than pivot + * from pi to gt excluded: elements greater than pivot + * from gt to n excluded: elements identical to pivot + */ + /* move elements identical to pivot in the middle of the array: */ + /* swap values in ranges [0..lt[ and [i-lt..i[ + swapping the smallest span between lt and i-lt is sufficient + */ + span = plt - ptr; + span2 = pi - plt; + lt = i - lt; + if (span > span2) + span = span2; + swap_block(ptr, pi - span, span); + /* swap values in ranges [gt..top[ and [i..top-(top-gt)[ + swapping the smallest span between top-gt and gt-i is sufficient + */ + span = top - pgt; + span2 = pgt - pi; + pgt = top - span2; + gt = nmemb - (gt - i); + if (span > span2) + span = span2; + swap_block(pi, top - span, span); + + /* now array has 3 parts: + * from 0 to lt excluded: elements smaller than pivot + * from lt to gt excluded: elements identical to pivot + * from gt to n excluded: elements greater than pivot + */ + /* stack the larger segment and keep processing the smaller one + to minimize stack use for pathological distributions */ + if (lt > nmemb - gt) { + sp->base = ptr; + sp->count = lt; + sp->depth = depth; + sp++; + ptr = pgt; + nmemb -= gt; + } else { + sp->base = pgt; + sp->count = nmemb - gt; + sp->depth = depth; + sp++; + nmemb = lt; + } + } + /* Use insertion sort for small fragments */ + for (pi = ptr + size, top = ptr + nmemb * size; pi < top; pi += size) { + for (pj = pi; pj > ptr && cmp(pj - size, pj, opaque) > 0; pj -= size) + swap(pj, pj - size, size); + } + } +} + +/*---- Portable time functions ----*/ + +#ifdef _WIN32 + // From: https://stackoverflow.com/a/26085827 +static int gettimeofday_msvc(struct timeval *tp) +{ + static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); + + SYSTEMTIME system_time; + FILETIME file_time; + uint64_t time; + + GetSystemTime(&system_time); + SystemTimeToFileTime(&system_time, &file_time); + time = ((uint64_t)file_time.dwLowDateTime); + time += ((uint64_t)file_time.dwHighDateTime) << 32; + + tp->tv_sec = (long)((time - EPOCH) / 10000000L); + tp->tv_usec = (long)(system_time.wMilliseconds * 1000); + + return 0; +} + +static inline uint64_t js__hrtime_ns(void) { + LARGE_INTEGER counter, frequency; + double scaled_freq; + double result; + + if (!QueryPerformanceFrequency(&frequency)) + abort(); + assert(frequency.QuadPart != 0); + + if (!QueryPerformanceCounter(&counter)) + abort(); + assert(counter.QuadPart != 0); + + /* Because we have no guarantee about the order of magnitude of the + * performance counter interval, integer math could cause this computation + * to overflow. Therefore we resort to floating point math. + */ + scaled_freq = (double) frequency.QuadPart / NANOSEC; + result = (double) counter.QuadPart / scaled_freq; + return (uint64_t) result; +} +#else +static inline uint64_t js__hrtime_ns(void) { +#ifdef __DJGPP + struct timeval tv; + if (gettimeofday(&tv, NULL)) + abort(); + return tv.tv_sec * NANOSEC + tv.tv_usec * 1000; +#else + struct timespec t; + + if (clock_gettime(CLOCK_MONOTONIC, &t)) + abort(); + + return t.tv_sec * NANOSEC + t.tv_nsec; +#endif +} +#endif + +static inline int64_t js__gettimeofday_us(void) { + struct timeval tv; +#ifdef _WIN32 + gettimeofday_msvc(&tv); +#else + gettimeofday(&tv, NULL); +#endif + return ((int64_t)tv.tv_sec * 1000000) + tv.tv_usec; +} + +#if defined(_WIN32) +static inline int js_exepath(char *buffer, size_t *size_ptr) { + int utf8_len, utf16_buffer_len, utf16_len; + WCHAR* utf16_buffer; + + if (buffer == NULL || size_ptr == NULL || *size_ptr == 0) + return -1; + + if (*size_ptr > 32768) { + /* Windows paths can never be longer than this. */ + utf16_buffer_len = 32768; + } else { + utf16_buffer_len = (int)*size_ptr; + } + + utf16_buffer = malloc(sizeof(WCHAR) * utf16_buffer_len); + if (!utf16_buffer) + return -1; + + /* Get the path as UTF-16. */ + utf16_len = GetModuleFileNameW(NULL, utf16_buffer, utf16_buffer_len); + if (utf16_len <= 0) + goto error; + + /* Convert to UTF-8 */ + utf8_len = WideCharToMultiByte(CP_UTF8, + 0, + utf16_buffer, + -1, + buffer, + (int)*size_ptr, + NULL, + NULL); + if (utf8_len == 0) + goto error; + + free(utf16_buffer); + + /* utf8_len *does* include the terminating null at this point, but the + * returned size shouldn't. */ + *size_ptr = utf8_len - 1; + return 0; + +error: + free(utf16_buffer); + return -1; +} +#elif defined(__APPLE__) +static inline int js_exepath(char *buffer, size_t *size) { + /* realpath(exepath) may be > PATH_MAX so double it to be on the safe side. */ + char abspath[PATH_MAX * 2 + 1]; + char exepath[PATH_MAX + 1]; + uint32_t exepath_size; + size_t abspath_size; + + if (buffer == NULL || size == NULL || *size == 0) + return -1; + + exepath_size = sizeof(exepath); + if (_NSGetExecutablePath(exepath, &exepath_size)) + return -1; + + if (realpath(exepath, abspath) != abspath) + return -1; + + abspath_size = strlen(abspath); + if (abspath_size == 0) + return -1; + + *size -= 1; + if (*size > abspath_size) + *size = abspath_size; + + memcpy(buffer, abspath, *size); + buffer[*size] = '\0'; + + return 0; +} +#elif defined(__linux__) || defined(__GNU__) +static inline int js_exepath(char *buffer, size_t *size) { + ssize_t n; + + if (buffer == NULL || size == NULL || *size == 0) + return -1; + + n = *size - 1; + if (n > 0) + n = readlink("/proc/self/exe", buffer, n); + + if (n == -1) + return n; + + buffer[n] = '\0'; + *size = n; + + return 0; +} +#else +static inline int js_exepath(char* buffer, size_t* size_ptr) { + return -1; +} +#endif + +/*--- Cross-platform threading APIs. ----*/ + +#if JS_HAVE_THREADS +#if defined(_WIN32) +typedef void (*js__once_cb)(void); + +typedef struct { + js__once_cb callback; +} js__once_data_t; + +static int WINAPI js__once_inner(INIT_ONCE *once, void *param, void **context) { + js__once_data_t *data = param; + + data->callback(); + + return 1; +} + +static inline void js_once(js_once_t *guard, js__once_cb callback) { + js__once_data_t data = { .callback = callback }; + InitOnceExecuteOnce(guard, js__once_inner, (void*) &data, NULL); +} + +static inline void js_mutex_init(js_mutex_t *mutex) { + InitializeCriticalSection(mutex); +} + +static inline void js_mutex_destroy(js_mutex_t *mutex) { + DeleteCriticalSection(mutex); +} + +static inline void js_mutex_lock(js_mutex_t *mutex) { + EnterCriticalSection(mutex); +} + +static inline void js_mutex_unlock(js_mutex_t *mutex) { + LeaveCriticalSection(mutex); +} + +static inline void js_cond_init(js_cond_t *cond) { + InitializeConditionVariable(cond); +} + +static inline void js_cond_destroy(js_cond_t *cond) { + /* nothing to do */ + (void) cond; +} + +static inline void js_cond_signal(js_cond_t *cond) { + WakeConditionVariable(cond); +} + +static inline void js_cond_broadcast(js_cond_t *cond) { + WakeAllConditionVariable(cond); +} + +static inline void js_cond_wait(js_cond_t *cond, js_mutex_t *mutex) { + if (!SleepConditionVariableCS(cond, mutex, INFINITE)) + abort(); +} + +static inline int js_cond_timedwait(js_cond_t *cond, js_mutex_t *mutex, uint64_t timeout) { + if (SleepConditionVariableCS(cond, mutex, (DWORD)(timeout / 1e6))) + return 0; + if (GetLastError() != ERROR_TIMEOUT) + abort(); + return -1; +} + +static inline int js_thread_create(js_thread_t *thrd, void (*start)(void *), void *arg, + int flags) +{ + HANDLE h, cp; + + *thrd = INVALID_HANDLE_VALUE; + if (flags & ~JS_THREAD_CREATE_DETACHED) + return -1; + h = (HANDLE)_beginthread(start, /*stacksize*/2<<20, arg); + if (!h) + return -1; + if (flags & JS_THREAD_CREATE_DETACHED) + return 0; + // _endthread() automatically closes the handle but we want to wait on + // it so make a copy. Race-y for very short-lived threads. Can be solved + // by switching to _beginthreadex(CREATE_SUSPENDED) but means changing + // |start| from __cdecl to __stdcall. + cp = GetCurrentProcess(); + if (DuplicateHandle(cp, h, cp, thrd, 0, FALSE, DUPLICATE_SAME_ACCESS)) + return 0; + return -1; +} + +static inline int js_thread_join(js_thread_t thrd) +{ + if (WaitForSingleObject(thrd, INFINITE)) + return -1; + CloseHandle(thrd); + return 0; +} + +#else /* !defined(_WIN32) */ + +static inline void js_once(js_once_t *guard, void (*callback)(void)) { + if (pthread_once(guard, callback)) + abort(); +} + +static inline void js_mutex_init(js_mutex_t *mutex) { + if (pthread_mutex_init(mutex, NULL)) + abort(); +} + +static inline void js_mutex_destroy(js_mutex_t *mutex) { + if (pthread_mutex_destroy(mutex)) + abort(); +} + +static inline void js_mutex_lock(js_mutex_t *mutex) { + if (pthread_mutex_lock(mutex)) + abort(); +} + +static inline void js_mutex_unlock(js_mutex_t *mutex) { + if (pthread_mutex_unlock(mutex)) + abort(); +} + +static inline void js_cond_init(js_cond_t *cond) { +#if defined(__APPLE__) && defined(__MACH__) + if (pthread_cond_init(cond, NULL)) + abort(); +#else + pthread_condattr_t attr; + + if (pthread_condattr_init(&attr)) + abort(); + + if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)) + abort(); + + if (pthread_cond_init(cond, &attr)) + abort(); + + if (pthread_condattr_destroy(&attr)) + abort(); +#endif +} + +static inline void js_cond_destroy(js_cond_t *cond) { +#if defined(__APPLE__) && defined(__MACH__) + /* It has been reported that destroying condition variables that have been + * signalled but not waited on can sometimes result in application crashes. + * See https://codereview.chromium.org/1323293005. + */ + pthread_mutex_t mutex; + struct timespec ts; + int err; + + if (pthread_mutex_init(&mutex, NULL)) + abort(); + + if (pthread_mutex_lock(&mutex)) + abort(); + + ts.tv_sec = 0; + ts.tv_nsec = 1; + + err = pthread_cond_timedwait_relative_np(cond, &mutex, &ts); + if (err != 0 && err != ETIMEDOUT) + abort(); + + if (pthread_mutex_unlock(&mutex)) + abort(); + + if (pthread_mutex_destroy(&mutex)) + abort(); +#endif /* defined(__APPLE__) && defined(__MACH__) */ + + if (pthread_cond_destroy(cond)) + abort(); +} + +static inline void js_cond_signal(js_cond_t *cond) { + if (pthread_cond_signal(cond)) + abort(); +} + +static inline void js_cond_broadcast(js_cond_t *cond) { + if (pthread_cond_broadcast(cond)) + abort(); +} + +static inline void js_cond_wait(js_cond_t *cond, js_mutex_t *mutex) { +#if defined(__APPLE__) && defined(__MACH__) + int r; + + errno = 0; + r = pthread_cond_wait(cond, mutex); + + /* Workaround for a bug in OS X at least up to 13.6 + * See https://github.com/libuv/libuv/issues/4165 + */ + if (r == EINVAL && errno == EBUSY) + return; + if (r) + abort(); +#else + if (pthread_cond_wait(cond, mutex)) + abort(); +#endif +} + +static inline int js_cond_timedwait(js_cond_t *cond, js_mutex_t *mutex, uint64_t timeout) { + int r; + struct timespec ts; + +#if !defined(__APPLE__) + timeout += js__hrtime_ns(); +#endif + + ts.tv_sec = timeout / NANOSEC; + ts.tv_nsec = timeout % NANOSEC; +#if defined(__APPLE__) && defined(__MACH__) + r = pthread_cond_timedwait_relative_np(cond, mutex, &ts); +#else + r = pthread_cond_timedwait(cond, mutex, &ts); +#endif + + if (r == 0) + return 0; + + if (r == ETIMEDOUT) + return -1; + + abort(); + + /* Pacify some compilers. */ + return -1; +} + +static inline int js_thread_create(js_thread_t *thrd, void (*start)(void *), void *arg, + int flags) +{ + union { + void (*x)(void *); + void *(*f)(void *); + } u = {start}; + pthread_attr_t attr; + int ret; + + if (flags & ~JS_THREAD_CREATE_DETACHED) + return -1; + if (pthread_attr_init(&attr)) + return -1; + ret = -1; + if (pthread_attr_setstacksize(&attr, 2<<20)) + goto fail; + if (flags & JS_THREAD_CREATE_DETACHED) + if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) + goto fail; + if (pthread_create(thrd, &attr, u.f, arg)) + goto fail; + ret = 0; +fail: + pthread_attr_destroy(&attr); + return ret; +} + +static inline int js_thread_join(js_thread_t thrd) +{ + if (pthread_join(thrd, NULL)) + return -1; + return 0; +} + +#endif /* !defined(_WIN32) */ +#endif /* JS_HAVE_THREADS */ + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* CUTILS_H */ +/* + * Tiny float64 printing and parsing library + * + * Copyright (c) 2024 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef DTOA_H +#define DTOA_H + +//#define JS_DTOA_DUMP_STATS + +/* maximum number of digits for fixed and frac formats */ +#define JS_DTOA_MAX_DIGITS 101 + +/* radix != 10 is only supported with flags = JS_DTOA_FORMAT_FREE */ +/* use as many digits as necessary */ +#define JS_DTOA_FORMAT_FREE (0 << 0) +/* use n_digits significant digits (1 <= n_digits <= JS_DTOA_MAX_DIGITS) */ +#define JS_DTOA_FORMAT_FIXED (1 << 0) +/* force fractional format: [-]dd.dd with n_digits fractional digits. + 0 <= n_digits <= JS_DTOA_MAX_DIGITS */ +#define JS_DTOA_FORMAT_FRAC (2 << 0) +#define JS_DTOA_FORMAT_MASK (3 << 0) + +/* select exponential notation either in fixed or free format */ +#define JS_DTOA_EXP_AUTO (0 << 2) +#define JS_DTOA_EXP_ENABLED (1 << 2) +#define JS_DTOA_EXP_DISABLED (2 << 2) +#define JS_DTOA_EXP_MASK (3 << 2) + +#define JS_DTOA_MINUS_ZERO (1 << 4) /* show the minus sign for -0 */ + +/* only accepts integers (no dot, no exponent) */ +#define JS_ATOD_INT_ONLY (1 << 0) +/* accept Oo and Ob prefixes in addition to 0x prefix if radix = 0 */ +#define JS_ATOD_ACCEPT_BIN_OCT (1 << 1) +/* accept O prefix as octal if radix == 0 and properly formed (Annex B) */ +#define JS_ATOD_ACCEPT_LEGACY_OCTAL (1 << 2) +/* accept _ between digits as a digit separator */ +#define JS_ATOD_ACCEPT_UNDERSCORES (1 << 3) + +typedef struct { + uint64_t mem[37]; +} JSDTOATempMem; + +typedef struct { + uint64_t mem[27]; +} JSATODTempMem; + +/* return a maximum bound of the string length */ +int js_dtoa_max_len(double d, int radix, int n_digits, int flags); +/* return the string length */ +int js_dtoa(char *buf, double d, int radix, int n_digits, int flags, + JSDTOATempMem *tmp_mem); +double js_atod(const char *str, const char **pnext, int radix, int flags, + JSATODTempMem *tmp_mem); + +#ifdef JS_DTOA_DUMP_STATS +void js_dtoa_dump_stats(void); +#endif + +/* additional exported functions */ +size_t u32toa(char *buf, uint32_t n); +size_t i32toa(char *buf, int32_t n); +size_t u64toa(char *buf, uint64_t n); +size_t i64toa(char *buf, int64_t n); +size_t u64toa_radix(char *buf, uint64_t n, unsigned int radix); +size_t i64toa_radix(char *buf, int64_t n, unsigned int radix); + +#endif /* DTOA_H */ +/* + * Linux klist like system + * + * Copyright (c) 2016-2017 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef LIST_H +#define LIST_H + +#ifndef NULL +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +struct list_head { + struct list_head *prev; + struct list_head *next; +}; + +#define LIST_HEAD_INIT(el) { &(el), &(el) } + +/* return the pointer of type 'type *' containing 'el' as field 'member' */ +#define list_entry(el, type, member) container_of(el, type, member) + +static inline void init_list_head(struct list_head *head) +{ + head->prev = head; + head->next = head; +} + +/* insert 'el' between 'prev' and 'next' */ +static inline void __list_add(struct list_head *el, + struct list_head *prev, struct list_head *next) +{ + prev->next = el; + el->prev = prev; + el->next = next; + next->prev = el; +} + +/* add 'el' at the head of the list 'head' (= after element head) */ +static inline void list_add(struct list_head *el, struct list_head *head) +{ + __list_add(el, head, head->next); +} + +/* add 'el' at the end of the list 'head' (= before element head) */ +static inline void list_add_tail(struct list_head *el, struct list_head *head) +{ + __list_add(el, head->prev, head); +} + +static inline void list_del(struct list_head *el) +{ + struct list_head *prev, *next; + prev = el->prev; + next = el->next; + prev->next = next; + next->prev = prev; + el->prev = NULL; /* fail safe */ + el->next = NULL; /* fail safe */ +} + +static inline int list_empty(struct list_head *el) +{ + return el->next == el; +} + +#define list_for_each(el, head) \ + for(el = (head)->next; el != (head); el = el->next) + +#define list_for_each_safe(el, el1, head) \ + for(el = (head)->next, el1 = el->next; el != (head); \ + el = el1, el1 = el->next) + +#define list_for_each_prev(el, head) \ + for(el = (head)->prev; el != (head); el = el->prev) + +#define list_for_each_prev_safe(el, el1, head) \ + for(el = (head)->prev, el1 = el->prev; el != (head); \ + el = el1, el1 = el->prev) + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* LIST_H */ +/* + * Unicode utilities + * + * Copyright (c) 2017-2018 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef LIBUNICODE_H +#define LIBUNICODE_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define LRE_CC_RES_LEN_MAX 3 + +typedef enum { + UNICODE_NFC, + UNICODE_NFD, + UNICODE_NFKC, + UNICODE_NFKD, +} UnicodeNormalizationEnum; + +int lre_case_conv(uint32_t *res, uint32_t c, int conv_type); +int lre_canonicalize(uint32_t c, bool is_unicode); +bool lre_is_cased(uint32_t c); +bool lre_is_case_ignorable(uint32_t c); + +/* char ranges */ + +typedef struct { + int len; /* in points, always even */ + int size; + uint32_t *points; /* points sorted by increasing value */ + void *mem_opaque; + void *(*realloc_func)(void *opaque, void *ptr, size_t size); +} CharRange; + +typedef enum { + CR_OP_UNION, + CR_OP_INTER, + CR_OP_XOR, +} CharRangeOpEnum; + +void cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); +void cr_free(CharRange *cr); +int cr_realloc(CharRange *cr, int size); +int cr_copy(CharRange *cr, const CharRange *cr1); + +static inline int cr_add_point(CharRange *cr, uint32_t v) +{ + if (cr->len >= cr->size) { + if (cr_realloc(cr, cr->len + 1)) + return -1; + } + cr->points[cr->len++] = v; + return 0; +} + +static inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2) +{ + if ((cr->len + 2) > cr->size) { + if (cr_realloc(cr, cr->len + 2)) + return -1; + } + cr->points[cr->len++] = c1; + cr->points[cr->len++] = c2; + return 0; +} + +int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len); + +static inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2) +{ + uint32_t b_pt[2]; + b_pt[0] = c1; + b_pt[1] = c2 + 1; + return cr_union1(cr, b_pt, 2); +} + +int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len, + const uint32_t *b_pt, int b_len, int op); + +int cr_invert(CharRange *cr); +int cr_regexp_canonicalize(CharRange *cr, bool is_unicode); + +bool lre_is_id_start(uint32_t c); +bool lre_is_id_continue(uint32_t c); +bool lre_is_white_space(uint32_t c); + +int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len, + UnicodeNormalizationEnum n_type, + void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); + +/* Unicode character range functions */ + +int unicode_script(CharRange *cr, + const char *script_name, bool is_ext); +int unicode_general_category(CharRange *cr, const char *gc_name); +int unicode_prop(CharRange *cr, const char *prop_name); + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* LIBUNICODE_H */ +/* + * Regular Expression Engine + * + * Copyright (c) 2017-2018 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef LIBREGEXP_H +#define LIBREGEXP_H + +#include +#include + + + +#ifdef __cplusplus +extern "C" { +#endif + +#define LRE_FLAG_GLOBAL (1 << 0) +#define LRE_FLAG_IGNORECASE (1 << 1) +#define LRE_FLAG_MULTILINE (1 << 2) +#define LRE_FLAG_DOTALL (1 << 3) +#define LRE_FLAG_UNICODE (1 << 4) +#define LRE_FLAG_STICKY (1 << 5) +#define LRE_FLAG_INDICES (1 << 6) /* Unused by libregexp, just recorded. */ +#define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */ +#define LRE_FLAG_UNICODE_SETS (1 << 8) + +#define LRE_RET_MEMORY_ERROR (-1) +#define LRE_RET_TIMEOUT (-2) + +uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size, + const char *buf, size_t buf_len, int re_flags, + void *opaque); +int lre_get_capture_count(const uint8_t *bc_buf); +int lre_get_flags(const uint8_t *bc_buf); +const char *lre_get_groupnames(const uint8_t *bc_buf); +int lre_exec(uint8_t **capture, + const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen, + int cbuf_type, void *opaque); + +int lre_parse_escape(const uint8_t **pp, int allow_utf16); +bool lre_is_space(int c); + +void lre_byte_swap(uint8_t *buf, size_t len, bool is_byte_swapped); + +/* must be provided by the user */ +bool lre_check_stack_overflow(void *opaque, size_t alloca_size); +/* must be provided by the user, return non zero if time out */ +int lre_check_timeout(void *opaque); +void *lre_realloc(void *opaque, void *ptr, size_t size); + +/* JS identifier test */ +extern uint32_t const lre_id_start_table_ascii[4]; +extern uint32_t const lre_id_continue_table_ascii[4]; + +static inline int lre_js_is_ident_first(int c) +{ + if ((uint32_t)c < 128) { + return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1; + } else { + return lre_is_id_start(c); + } +} + +static inline int lre_js_is_ident_next(int c) +{ + if ((uint32_t)c < 128) { + return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1; + } else { + /* ZWNJ and ZWJ are accepted in identifiers */ + return lre_is_id_continue(c) || c == 0x200C || c == 0x200D; + } +} + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* LIBREGEXP_H */ +/* Compressed unicode tables */ +/* Automatically generated file - do not edit */ + +#include + +static const uint32_t case_conv_table1[378] = { + 0x00209a30, 0x00309a00, 0x005a8173, 0x00601730, + 0x006c0730, 0x006f81b3, 0x00701700, 0x007c0700, + 0x007f8100, 0x00803040, 0x009801c3, 0x00988190, + 0x00990640, 0x009c9040, 0x00a481b4, 0x00a52e40, + 0x00bc0130, 0x00bc8640, 0x00bf8170, 0x00c00100, + 0x00c08130, 0x00c10440, 0x00c30130, 0x00c38240, + 0x00c48230, 0x00c58240, 0x00c70130, 0x00c78130, + 0x00c80130, 0x00c88240, 0x00c98130, 0x00ca0130, + 0x00ca8100, 0x00cb0130, 0x00cb8130, 0x00cc0240, + 0x00cd0100, 0x00cd8101, 0x00ce0130, 0x00ce8130, + 0x00cf0100, 0x00cf8130, 0x00d00640, 0x00d30130, + 0x00d38240, 0x00d48130, 0x00d60240, 0x00d70130, + 0x00d78240, 0x00d88230, 0x00d98440, 0x00db8130, + 0x00dc0240, 0x00de0240, 0x00df8100, 0x00e20350, + 0x00e38350, 0x00e50350, 0x00e69040, 0x00ee8100, + 0x00ef1240, 0x00f801b4, 0x00f88350, 0x00fa0240, + 0x00fb0130, 0x00fb8130, 0x00fc2840, 0x01100130, + 0x01111240, 0x011d0131, 0x011d8240, 0x011e8130, + 0x011f0131, 0x011f8201, 0x01208240, 0x01218130, + 0x01220130, 0x01228130, 0x01230a40, 0x01280101, + 0x01288101, 0x01290101, 0x01298100, 0x012a0100, + 0x012b0200, 0x012c8100, 0x012d8100, 0x012e0101, + 0x01300100, 0x01308101, 0x01318100, 0x01320101, + 0x01328101, 0x01330101, 0x01340100, 0x01348100, + 0x01350101, 0x01358101, 0x01360101, 0x01378100, + 0x01388101, 0x01390100, 0x013a8100, 0x013e8101, + 0x01400100, 0x01410101, 0x01418100, 0x01438101, + 0x01440100, 0x01448100, 0x01450200, 0x01460100, + 0x01490100, 0x014e8101, 0x014f0101, 0x01a28173, + 0x01b80440, 0x01bb0240, 0x01bd8300, 0x01bf8130, + 0x01c30130, 0x01c40330, 0x01c60130, 0x01c70230, + 0x01c801d0, 0x01c89130, 0x01d18930, 0x01d60100, + 0x01d68300, 0x01d801d3, 0x01d89100, 0x01e10173, + 0x01e18900, 0x01e60100, 0x01e68200, 0x01e78130, + 0x01e80173, 0x01e88173, 0x01ea8173, 0x01eb0173, + 0x01eb8100, 0x01ec1840, 0x01f80173, 0x01f88173, + 0x01f90100, 0x01f98100, 0x01fa01a0, 0x01fa8173, + 0x01fb8240, 0x01fc8130, 0x01fd0240, 0x01fe8330, + 0x02001030, 0x02082030, 0x02182000, 0x02281000, + 0x02302240, 0x02453640, 0x02600130, 0x02608e40, + 0x02678100, 0x02686040, 0x0298a630, 0x02b0a600, + 0x02c381b5, 0x08502631, 0x08638131, 0x08668131, + 0x08682b00, 0x087e8300, 0x09d05011, 0x09f80610, + 0x09fc0620, 0x0e400174, 0x0e408174, 0x0e410174, + 0x0e418174, 0x0e420174, 0x0e428174, 0x0e430174, + 0x0e438180, 0x0e440180, 0x0e448240, 0x0e482b30, + 0x0e5e8330, 0x0ebc8101, 0x0ebe8101, 0x0ec70101, + 0x0f007e40, 0x0f3f1840, 0x0f4b01b5, 0x0f4b81b6, + 0x0f4c01b6, 0x0f4c81b6, 0x0f4d01b7, 0x0f4d8180, + 0x0f4f0130, 0x0f506040, 0x0f800800, 0x0f840830, + 0x0f880600, 0x0f8c0630, 0x0f900800, 0x0f940830, + 0x0f980800, 0x0f9c0830, 0x0fa00600, 0x0fa40630, + 0x0fa801b0, 0x0fa88100, 0x0fa901d3, 0x0fa98100, + 0x0faa01d3, 0x0faa8100, 0x0fab01d3, 0x0fab8100, + 0x0fac8130, 0x0fad8130, 0x0fae8130, 0x0faf8130, + 0x0fb00800, 0x0fb40830, 0x0fb80200, 0x0fb90400, + 0x0fbb0201, 0x0fbc0201, 0x0fbd0201, 0x0fbe0201, + 0x0fc008b7, 0x0fc40867, 0x0fc808b8, 0x0fcc0868, + 0x0fd008b8, 0x0fd40868, 0x0fd80200, 0x0fd901b9, + 0x0fd981b1, 0x0fda01b9, 0x0fdb01b1, 0x0fdb81d7, + 0x0fdc0230, 0x0fdd0230, 0x0fde0161, 0x0fdf0173, + 0x0fe101b9, 0x0fe181b2, 0x0fe201ba, 0x0fe301b2, + 0x0fe381d8, 0x0fe40430, 0x0fe60162, 0x0fe80201, + 0x0fe901d0, 0x0fe981d0, 0x0feb01b0, 0x0feb81d0, + 0x0fec0230, 0x0fed0230, 0x0ff00201, 0x0ff101d3, + 0x0ff181d3, 0x0ff201ba, 0x0ff28101, 0x0ff301b0, + 0x0ff381d3, 0x0ff40231, 0x0ff50230, 0x0ff60131, + 0x0ff901ba, 0x0ff981b2, 0x0ffa01bb, 0x0ffb01b2, + 0x0ffb81d9, 0x0ffc0230, 0x0ffd0230, 0x0ffe0162, + 0x109301a0, 0x109501a0, 0x109581a0, 0x10990131, + 0x10a70101, 0x10b01031, 0x10b81001, 0x10c18240, + 0x125b1a31, 0x12681a01, 0x16003031, 0x16183001, + 0x16300240, 0x16310130, 0x16318130, 0x16320130, + 0x16328100, 0x16330100, 0x16338640, 0x16368130, + 0x16370130, 0x16378130, 0x16380130, 0x16390240, + 0x163a8240, 0x163f0230, 0x16406440, 0x16758440, + 0x16790240, 0x16802600, 0x16938100, 0x16968100, + 0x53202e40, 0x53401c40, 0x53910e40, 0x53993e40, + 0x53bc8440, 0x53be8130, 0x53bf0a40, 0x53c58240, + 0x53c68130, 0x53c80440, 0x53ca0101, 0x53cb1440, + 0x53d50130, 0x53d58130, 0x53d60130, 0x53d68130, + 0x53d70130, 0x53d80130, 0x53d88130, 0x53d90130, + 0x53d98131, 0x53da1040, 0x53e20131, 0x53e28130, + 0x53e30130, 0x53e38440, 0x53e58130, 0x53e61040, + 0x53ee0130, 0x53fa8240, 0x55a98101, 0x55b85020, + 0x7d8001b2, 0x7d8081b2, 0x7d8101b2, 0x7d8181da, + 0x7d8201da, 0x7d8281b3, 0x7d8301b3, 0x7d8981bb, + 0x7d8a01bb, 0x7d8a81bb, 0x7d8b01bc, 0x7d8b81bb, + 0x7f909a31, 0x7fa09a01, 0x82002831, 0x82142801, + 0x82582431, 0x826c2401, 0x82b80b31, 0x82be0f31, + 0x82c60731, 0x82ca0231, 0x82cb8b01, 0x82d18f01, + 0x82d98701, 0x82dd8201, 0x86403331, 0x86603301, + 0x86a81631, 0x86b81601, 0x8c502031, 0x8c602001, + 0xb7202031, 0xb7302001, 0xb7501931, 0xb75d9901, + 0xf4802231, 0xf4912201, +}; + +static const uint8_t case_conv_table2[378] = { + 0x01, 0x00, 0x9c, 0x06, 0x07, 0x4d, 0x03, 0x04, + 0x10, 0x00, 0x8f, 0x0b, 0x00, 0x00, 0x11, 0x00, + 0x08, 0x00, 0x53, 0x4b, 0x52, 0x00, 0x53, 0x00, + 0x54, 0x00, 0x3b, 0x55, 0x56, 0x00, 0x58, 0x5a, + 0x40, 0x5f, 0x5e, 0x00, 0x47, 0x50, 0x63, 0x65, + 0x43, 0x66, 0x00, 0x68, 0x00, 0x6a, 0x00, 0x6c, + 0x00, 0x6e, 0x00, 0x70, 0x00, 0x00, 0x41, 0x00, + 0x00, 0x00, 0x00, 0x1a, 0x00, 0x93, 0x00, 0x00, + 0x20, 0x36, 0x00, 0x28, 0x00, 0x24, 0x00, 0x24, + 0x25, 0x2d, 0x00, 0x13, 0x6d, 0x6f, 0x00, 0x29, + 0x27, 0x2a, 0x14, 0x16, 0x18, 0x1b, 0x1c, 0x41, + 0x1e, 0x42, 0x1f, 0x4e, 0x3c, 0x40, 0x22, 0x21, + 0x44, 0x21, 0x43, 0x26, 0x28, 0x27, 0x29, 0x23, + 0x2b, 0x4b, 0x2d, 0x46, 0x2f, 0x4c, 0x31, 0x4d, + 0x33, 0x47, 0x45, 0x99, 0x00, 0x00, 0x97, 0x91, + 0x7f, 0x80, 0x85, 0x86, 0x12, 0x82, 0x84, 0x78, + 0x79, 0x12, 0x7d, 0xa3, 0x7e, 0x7a, 0x7b, 0x8c, + 0x92, 0x98, 0xa6, 0xa0, 0x87, 0x00, 0x9a, 0xa1, + 0x95, 0x77, 0x33, 0x95, 0x00, 0x90, 0x00, 0x76, + 0x9b, 0x9a, 0x99, 0x98, 0x00, 0x00, 0xa0, 0x00, + 0x9e, 0x00, 0xa3, 0xa2, 0x15, 0x31, 0x32, 0x33, + 0xb7, 0xb8, 0x53, 0xac, 0xab, 0x12, 0x14, 0x1e, + 0x21, 0x22, 0x22, 0x2a, 0x34, 0x35, 0x00, 0xa8, + 0xa9, 0x39, 0x22, 0x4c, 0x00, 0x00, 0x97, 0x01, + 0x5a, 0xda, 0x1d, 0x36, 0x05, 0x00, 0xc7, 0xc6, + 0xc9, 0xc8, 0xcb, 0xca, 0xcd, 0xcc, 0xcf, 0xce, + 0xc4, 0xd8, 0x45, 0xd9, 0x42, 0xda, 0x46, 0xdb, + 0xd1, 0xd3, 0xd5, 0xd7, 0xdd, 0xdc, 0xf1, 0xf9, + 0x01, 0x11, 0x0a, 0x12, 0x80, 0x9f, 0x00, 0x21, + 0x80, 0xa3, 0xf0, 0x00, 0xc0, 0x40, 0xc6, 0x60, + 0xea, 0xde, 0xe6, 0x99, 0xc0, 0x00, 0x00, 0x06, + 0x60, 0xdf, 0x29, 0x00, 0x15, 0x12, 0x06, 0x16, + 0xfb, 0xe0, 0x09, 0x15, 0x12, 0x84, 0x0b, 0xc6, + 0x16, 0x02, 0xe2, 0x06, 0xc0, 0x40, 0x00, 0x46, + 0x60, 0xe1, 0xe3, 0x6d, 0x37, 0x38, 0x39, 0x18, + 0x17, 0x1a, 0x19, 0x00, 0x1d, 0x1c, 0x1f, 0x1e, + 0x00, 0x61, 0xba, 0x67, 0x45, 0x48, 0x00, 0x50, + 0x64, 0x4f, 0x51, 0x00, 0x00, 0x49, 0x00, 0x00, + 0x00, 0xa5, 0xa6, 0xa7, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xb9, 0x00, 0x00, 0x5c, 0x00, 0x4a, 0x00, + 0x5d, 0x57, 0x59, 0x62, 0x60, 0x72, 0x6b, 0x71, + 0x52, 0x00, 0x3e, 0x69, 0xbb, 0x00, 0x5b, 0x00, + 0x25, 0x00, 0x48, 0xaa, 0x8a, 0x8b, 0x8c, 0xab, + 0xac, 0x58, 0x58, 0xaf, 0x94, 0xb0, 0x6f, 0xb2, + 0x61, 0x60, 0x63, 0x62, 0x65, 0x64, 0x6a, 0x6b, + 0x6c, 0x6d, 0x66, 0x67, 0x68, 0x69, 0x6f, 0x6e, + 0x71, 0x70, 0x73, 0x72, 0x75, 0x74, 0x77, 0x76, + 0x79, 0x78, +}; + +static const uint16_t case_conv_ext[58] = { + 0x0399, 0x0308, 0x0301, 0x03a5, 0x0313, 0x0300, 0x0342, 0x0391, + 0x0397, 0x03a9, 0x0046, 0x0049, 0x004c, 0x0053, 0x0069, 0x0307, + 0x02bc, 0x004e, 0x004a, 0x030c, 0x0535, 0x0552, 0x0048, 0x0331, + 0x0054, 0x0057, 0x030a, 0x0059, 0x0041, 0x02be, 0x1f08, 0x1f80, + 0x1f28, 0x1f90, 0x1f68, 0x1fa0, 0x1fba, 0x0386, 0x1fb3, 0x1fca, + 0x0389, 0x1fc3, 0x03a1, 0x1ffa, 0x038f, 0x1ff3, 0x0544, 0x0546, + 0x053b, 0x054e, 0x053d, 0x03b8, 0x0462, 0xa64a, 0x1e60, 0x03c9, + 0x006b, 0x00e5, +}; + +static const uint8_t unicode_prop_Cased1_table[190] = { + 0x40, 0xa9, 0x80, 0x8e, 0x80, 0xfc, 0x80, 0xd3, + 0x80, 0x9b, 0x81, 0x8d, 0x02, 0x80, 0xe1, 0x80, + 0x91, 0x85, 0x9a, 0x01, 0x00, 0x01, 0x11, 0x03, + 0x04, 0x08, 0x01, 0x08, 0x30, 0x08, 0x01, 0x15, + 0x20, 0x01, 0x31, 0x99, 0x31, 0x9d, 0x84, 0x40, + 0x94, 0x80, 0xd6, 0x82, 0xa6, 0x80, 0x41, 0x62, + 0x80, 0xa6, 0x80, 0x4b, 0x72, 0x80, 0x4c, 0x02, + 0xf8, 0x02, 0x80, 0x8f, 0x80, 0xb0, 0x40, 0xdb, + 0x08, 0x80, 0x41, 0xd0, 0x80, 0x8c, 0x80, 0x8f, + 0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, 0x14, 0x28, + 0x10, 0x11, 0x02, 0x01, 0x18, 0x0b, 0x24, 0x4b, + 0x26, 0x01, 0x01, 0x86, 0xe5, 0x80, 0x60, 0x79, + 0xb6, 0x81, 0x40, 0x91, 0x81, 0xbd, 0x88, 0x94, + 0x05, 0x80, 0x98, 0x80, 0xc0, 0x1a, 0x82, 0x43, + 0x34, 0xa2, 0x06, 0x80, 0x8d, 0x60, 0x5c, 0x15, + 0x01, 0x10, 0xa9, 0x80, 0x88, 0x60, 0xcc, 0x44, + 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b, 0x80, + 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f, 0x06, + 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, 0x80, 0x41, + 0x53, 0x81, 0x98, 0x80, 0x98, 0x80, 0x9e, 0x80, + 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, + 0x98, 0x80, 0x9e, 0x80, 0x98, 0x07, 0x47, 0x33, + 0x89, 0x80, 0x93, 0x2d, 0x41, 0x04, 0xbd, 0x50, + 0xc1, 0x99, 0x85, 0x99, 0x85, 0x99, +}; + +static const uint8_t unicode_prop_Cased1_index[18] = { + 0xb9, 0x02, 0x80, 0xa0, 0x1e, 0x40, 0x9e, 0xa6, + 0x40, 0x55, 0xd4, 0x21, 0x15, 0xd7, 0x21, 0x8a, + 0xf1, 0x01, +}; + +static const uint8_t unicode_prop_Case_Ignorable_table[785] = { + 0xa6, 0x05, 0x80, 0x8a, 0x80, 0xa2, 0x00, 0x80, + 0xc6, 0x03, 0x00, 0x03, 0x01, 0x81, 0x41, 0xf6, + 0x40, 0xbf, 0x19, 0x18, 0x88, 0x08, 0x80, 0x40, + 0xfa, 0x86, 0x40, 0xce, 0x04, 0x80, 0xb0, 0xac, + 0x00, 0x01, 0x01, 0x00, 0xab, 0x80, 0x8a, 0x85, + 0x89, 0x8a, 0x00, 0xa2, 0x80, 0x89, 0x94, 0x8f, + 0x80, 0xe4, 0x38, 0x89, 0x03, 0xa0, 0x00, 0x80, + 0x9d, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0x18, 0x08, + 0x97, 0x97, 0xaa, 0x82, 0xab, 0x06, 0x0c, 0x88, + 0xa8, 0xb9, 0xb6, 0x00, 0x03, 0x3b, 0x02, 0x86, + 0x89, 0x81, 0x8c, 0x80, 0x8e, 0x80, 0xb9, 0x03, + 0x1f, 0x80, 0x93, 0x81, 0x99, 0x01, 0x81, 0xb8, + 0x03, 0x0b, 0x09, 0x12, 0x80, 0x9d, 0x0a, 0x80, + 0x8a, 0x81, 0xb8, 0x03, 0x20, 0x0b, 0x80, 0x93, + 0x81, 0x95, 0x28, 0x80, 0xb9, 0x01, 0x00, 0x1f, + 0x06, 0x81, 0x8a, 0x81, 0x9d, 0x80, 0xbc, 0x80, + 0x8b, 0x80, 0xb1, 0x02, 0x80, 0xb6, 0x00, 0x14, + 0x10, 0x1e, 0x81, 0x8a, 0x81, 0x9c, 0x80, 0xb9, + 0x01, 0x05, 0x04, 0x81, 0x93, 0x81, 0x9b, 0x81, + 0xb8, 0x0b, 0x1f, 0x80, 0x93, 0x81, 0x9c, 0x80, + 0xc7, 0x06, 0x10, 0x80, 0xd9, 0x01, 0x86, 0x8a, + 0x88, 0xe1, 0x01, 0x88, 0x88, 0x00, 0x86, 0xc8, + 0x81, 0x9a, 0x00, 0x00, 0x80, 0xb6, 0x8d, 0x04, + 0x01, 0x84, 0x8a, 0x80, 0xa3, 0x88, 0x80, 0xe5, + 0x18, 0x28, 0x09, 0x81, 0x98, 0x0b, 0x82, 0x8f, + 0x83, 0x8c, 0x01, 0x0d, 0x80, 0x8e, 0x80, 0xdd, + 0x80, 0x42, 0x5f, 0x82, 0x43, 0xb1, 0x82, 0x9c, + 0x81, 0x9d, 0x81, 0x9d, 0x81, 0xbf, 0x08, 0x37, + 0x01, 0x8a, 0x10, 0x20, 0xac, 0x84, 0xb2, 0x80, + 0xc0, 0x81, 0xa1, 0x80, 0xf5, 0x13, 0x81, 0x88, + 0x05, 0x82, 0x40, 0xda, 0x09, 0x80, 0xb9, 0x00, + 0x30, 0x00, 0x01, 0x3d, 0x89, 0x08, 0xa6, 0x07, + 0xad, 0x81, 0x8b, 0x93, 0x83, 0xaf, 0x00, 0x20, + 0x04, 0x80, 0xa7, 0x88, 0x8b, 0x81, 0x9f, 0x19, + 0x08, 0x82, 0xb7, 0x00, 0x0a, 0x00, 0x82, 0xb9, + 0x39, 0x81, 0xbf, 0x85, 0xd1, 0x10, 0x8c, 0x06, + 0x18, 0x28, 0x11, 0xb1, 0xbe, 0x8c, 0x80, 0xa1, + 0xe4, 0x41, 0xbc, 0x00, 0x82, 0x8a, 0x82, 0x8c, + 0x82, 0x8c, 0x82, 0x8c, 0x81, 0x8b, 0x27, 0x81, + 0x89, 0x01, 0x01, 0x84, 0xb0, 0x20, 0x89, 0x00, + 0x8c, 0x80, 0x8f, 0x8c, 0xb2, 0xa0, 0x4b, 0x8a, + 0x81, 0xf0, 0x82, 0xfc, 0x80, 0x8e, 0x80, 0xdf, + 0x9f, 0xae, 0x80, 0x41, 0xd4, 0x80, 0xa3, 0x1a, + 0x24, 0x80, 0xdc, 0x85, 0xdc, 0x82, 0x60, 0x6f, + 0x15, 0x80, 0x44, 0xe1, 0x85, 0x41, 0x0d, 0x80, + 0xe1, 0x18, 0x89, 0x00, 0x9b, 0x83, 0xcf, 0x81, + 0x8d, 0xa1, 0xcd, 0x80, 0x96, 0x82, 0xe5, 0x1a, + 0x0f, 0x02, 0x03, 0x80, 0x98, 0x0c, 0x80, 0x40, + 0x96, 0x81, 0x99, 0x91, 0x8c, 0x80, 0xa5, 0x87, + 0x98, 0x8a, 0xad, 0x82, 0xaf, 0x01, 0x19, 0x81, + 0x90, 0x80, 0x94, 0x81, 0xc1, 0x29, 0x09, 0x81, + 0x8b, 0x07, 0x80, 0xa2, 0x80, 0x8a, 0x80, 0xb2, + 0x00, 0x11, 0x0c, 0x08, 0x80, 0x9a, 0x80, 0x8d, + 0x0c, 0x08, 0x80, 0xe3, 0x84, 0x88, 0x82, 0xf8, + 0x01, 0x03, 0x80, 0x60, 0x4f, 0x2f, 0x80, 0x40, + 0x92, 0x90, 0x42, 0x3c, 0x8f, 0x10, 0x8b, 0x8f, + 0xa1, 0x01, 0x80, 0x40, 0xa8, 0x06, 0x05, 0x80, + 0x8a, 0x80, 0xa2, 0x00, 0x80, 0xae, 0x80, 0xac, + 0x81, 0xc2, 0x80, 0x94, 0x82, 0x42, 0x00, 0x80, + 0x40, 0xe1, 0x80, 0x40, 0x94, 0x84, 0x44, 0x04, + 0x28, 0xa9, 0x80, 0x88, 0x42, 0x45, 0x10, 0x0c, + 0x83, 0xa7, 0x13, 0x80, 0x40, 0xa4, 0x81, 0x42, + 0x3c, 0x83, 0xa5, 0x80, 0x99, 0x20, 0x80, 0x41, + 0x3a, 0x81, 0x97, 0x80, 0xb3, 0x85, 0xc5, 0x8a, + 0xb0, 0x83, 0xfa, 0x80, 0xb5, 0x8e, 0xa8, 0x01, + 0x81, 0x89, 0x82, 0xb0, 0x19, 0x09, 0x03, 0x80, + 0x89, 0x80, 0xb1, 0x82, 0xa3, 0x20, 0x87, 0xbd, + 0x80, 0x8b, 0x81, 0xb3, 0x88, 0x89, 0x19, 0x80, + 0xde, 0x11, 0x00, 0x0d, 0x01, 0x80, 0x40, 0x9c, + 0x02, 0x87, 0x94, 0x81, 0xb8, 0x0a, 0x80, 0xa4, + 0x32, 0x84, 0xc5, 0x85, 0x8c, 0x00, 0x00, 0x80, + 0x8d, 0x81, 0xd4, 0x39, 0x10, 0x80, 0x96, 0x80, + 0xd3, 0x28, 0x03, 0x08, 0x81, 0x40, 0xed, 0x1d, + 0x08, 0x81, 0x9a, 0x81, 0xd4, 0x39, 0x00, 0x81, + 0xe9, 0x00, 0x01, 0x28, 0x80, 0xe4, 0x00, 0x01, + 0x18, 0x84, 0x41, 0x02, 0x88, 0x01, 0x40, 0xff, + 0x08, 0x03, 0x80, 0x40, 0x8f, 0x19, 0x0b, 0x80, + 0x9f, 0x89, 0xa7, 0x29, 0x1f, 0x80, 0x88, 0x29, + 0x82, 0xad, 0x8c, 0x01, 0x40, 0xc5, 0x00, 0x10, + 0x80, 0x40, 0xc8, 0x30, 0x28, 0x80, 0xd1, 0x95, + 0x0e, 0x01, 0x01, 0xf9, 0x2a, 0x00, 0x08, 0x30, + 0x80, 0xc7, 0x0a, 0x00, 0x80, 0xc0, 0x80, 0x41, + 0x18, 0x81, 0x8a, 0x81, 0xb3, 0x24, 0x00, 0x80, + 0x96, 0x80, 0x54, 0xd4, 0x90, 0x85, 0x8e, 0x60, + 0x2c, 0xc7, 0x8b, 0x12, 0x49, 0xbf, 0x84, 0xba, + 0x86, 0x88, 0x83, 0x41, 0xfb, 0x82, 0xa7, 0x81, + 0x41, 0xe1, 0x80, 0xbe, 0x90, 0xbf, 0x08, 0x81, + 0x8c, 0x81, 0x60, 0x3f, 0xfb, 0x18, 0x30, 0x81, + 0x4c, 0x9d, 0x08, 0x83, 0x52, 0x5b, 0xad, 0x81, + 0x96, 0x42, 0x1f, 0x82, 0x88, 0x8f, 0x0e, 0x9d, + 0x83, 0x40, 0x93, 0x82, 0x47, 0xba, 0xb6, 0x83, + 0xb1, 0x38, 0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45, + 0x4f, 0x30, 0x90, 0x0e, 0x01, 0x04, 0x84, 0xbd, + 0xa0, 0x80, 0x40, 0x9f, 0x8d, 0x41, 0x6f, 0x80, + 0xbc, 0x83, 0x41, 0xfa, 0x84, 0x40, 0xfd, 0x81, + 0x40, 0xf2, 0x01, 0x06, 0x0c, 0x80, 0x88, 0x80, + 0x41, 0xcf, 0x86, 0xec, 0x87, 0x4a, 0xae, 0x84, + 0x6c, 0x0c, 0x00, 0x80, 0x9d, 0xdf, 0xff, 0x40, + 0xef, +}; + +static const uint8_t unicode_prop_Case_Ignorable_index[75] = { + 0xbe, 0x05, 0x00, 0xfe, 0x07, 0x00, 0x52, 0x0a, + 0xa0, 0xc1, 0x0b, 0x00, 0x82, 0x0d, 0x00, 0x3f, + 0x10, 0x80, 0xd4, 0x17, 0x40, 0xde, 0x1a, 0x20, + 0xe9, 0x1c, 0x00, 0x72, 0x20, 0x00, 0x16, 0xa0, + 0x40, 0xc6, 0xa8, 0x40, 0xc2, 0xaa, 0xa0, 0x30, + 0xfe, 0x00, 0xb1, 0x07, 0x41, 0x51, 0x0f, 0x01, + 0xd0, 0x11, 0x01, 0x5f, 0x14, 0x01, 0x44, 0x19, + 0x61, 0xa8, 0x1c, 0x01, 0x2a, 0x61, 0x61, 0xff, + 0xaf, 0x01, 0x19, 0xe0, 0x61, 0x00, 0xe7, 0x01, + 0xf0, 0x01, 0x0e, +}; + +static const uint8_t unicode_prop_ID_Start_table[1146] = { + 0xc0, 0x99, 0x85, 0x99, 0xae, 0x80, 0x89, 0x03, + 0x04, 0x96, 0x80, 0x9e, 0x80, 0x41, 0xc9, 0x83, + 0x8b, 0x8d, 0x26, 0x00, 0x80, 0x40, 0x80, 0x20, + 0x09, 0x18, 0x05, 0x00, 0x10, 0x00, 0x93, 0x80, + 0xd2, 0x80, 0x40, 0x8a, 0x87, 0x40, 0xa5, 0x80, + 0xa5, 0x08, 0x85, 0xa8, 0xc6, 0x9a, 0x1b, 0xac, + 0xaa, 0xa2, 0x08, 0xe2, 0x00, 0x8e, 0x0e, 0x81, + 0x89, 0x11, 0x80, 0x8f, 0x00, 0x9d, 0x9c, 0xd8, + 0x8a, 0x80, 0x97, 0xa0, 0x88, 0x0b, 0x04, 0x95, + 0x18, 0x88, 0x02, 0x80, 0x96, 0x98, 0x86, 0x8a, + 0x84, 0x97, 0x06, 0x8f, 0xa9, 0xb9, 0xb5, 0x10, + 0x91, 0x06, 0x89, 0x8e, 0x8f, 0x1f, 0x09, 0x81, + 0x95, 0x06, 0x00, 0x13, 0x10, 0x8f, 0x80, 0x8c, + 0x08, 0x82, 0x8d, 0x81, 0x89, 0x07, 0x2b, 0x09, + 0x95, 0x06, 0x01, 0x01, 0x01, 0x9e, 0x18, 0x80, + 0x92, 0x82, 0x8f, 0x88, 0x02, 0x80, 0x95, 0x06, + 0x01, 0x04, 0x10, 0x91, 0x80, 0x8e, 0x81, 0x96, + 0x80, 0x8a, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04, + 0x10, 0x9d, 0x08, 0x82, 0x8e, 0x80, 0x90, 0x00, + 0x2a, 0x10, 0x1a, 0x08, 0x00, 0x0a, 0x0a, 0x12, + 0x8b, 0x95, 0x80, 0xb3, 0x38, 0x10, 0x96, 0x80, + 0x8f, 0x10, 0x99, 0x10, 0x09, 0x81, 0x9d, 0x03, + 0x38, 0x10, 0x96, 0x80, 0x89, 0x04, 0x10, 0x9d, + 0x10, 0x81, 0x8e, 0x81, 0x90, 0x88, 0x02, 0x80, + 0xa8, 0x08, 0x8f, 0x04, 0x17, 0x82, 0x97, 0x2c, + 0x91, 0x82, 0x97, 0x80, 0x88, 0x00, 0x0e, 0xb9, + 0xaf, 0x01, 0x8b, 0x86, 0xb9, 0x08, 0x00, 0x20, + 0x97, 0x00, 0x80, 0x89, 0x01, 0x88, 0x01, 0x20, + 0x80, 0x94, 0x83, 0x9f, 0x80, 0xbe, 0x38, 0xa3, + 0x9a, 0x84, 0xf2, 0xaa, 0x93, 0x80, 0x8f, 0x2b, + 0x1a, 0x02, 0x0e, 0x13, 0x8c, 0x8b, 0x80, 0x90, + 0xa5, 0x00, 0x20, 0x81, 0xaa, 0x80, 0x41, 0x4c, + 0x03, 0x0e, 0x00, 0x03, 0x81, 0xa8, 0x03, 0x81, + 0xa0, 0x03, 0x0e, 0x00, 0x03, 0x81, 0x8e, 0x80, + 0xb8, 0x03, 0x81, 0xc2, 0xa4, 0x8f, 0x8f, 0xd5, + 0x0d, 0x82, 0x42, 0x6b, 0x81, 0x90, 0x80, 0x99, + 0x84, 0xca, 0x82, 0x8a, 0x86, 0x91, 0x8c, 0x92, + 0x8d, 0x91, 0x8d, 0x8c, 0x02, 0x8e, 0xb3, 0xa2, + 0x03, 0x80, 0xc2, 0xd8, 0x86, 0xa8, 0x00, 0x84, + 0xc5, 0x89, 0x9e, 0xb0, 0x9d, 0x0c, 0x8a, 0xab, + 0x83, 0x99, 0xb5, 0x96, 0x88, 0xb4, 0xd1, 0x80, + 0xdc, 0xae, 0x90, 0x87, 0xb5, 0x9d, 0x8c, 0x81, + 0x89, 0xab, 0x99, 0xa3, 0xa8, 0x82, 0x89, 0xa3, + 0x81, 0x8a, 0x84, 0xaa, 0x0a, 0xa8, 0x18, 0x28, + 0x0a, 0x04, 0x40, 0xbf, 0xbf, 0x41, 0x15, 0x0d, + 0x81, 0xa5, 0x0d, 0x0f, 0x00, 0x00, 0x00, 0x80, + 0x9e, 0x81, 0xb4, 0x06, 0x00, 0x12, 0x06, 0x13, + 0x0d, 0x83, 0x8c, 0x22, 0x06, 0xf3, 0x80, 0x8c, + 0x80, 0x8f, 0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, + 0x0d, 0x28, 0x00, 0x00, 0x80, 0x8f, 0x0b, 0x24, + 0x18, 0x90, 0xa8, 0x4a, 0x76, 0x40, 0xe4, 0x2b, + 0x11, 0x8b, 0xa5, 0x00, 0x20, 0x81, 0xb7, 0x30, + 0x8f, 0x96, 0x88, 0x30, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x86, 0x42, 0x25, 0x82, 0x98, 0x88, + 0x34, 0x0c, 0x83, 0xd5, 0x1c, 0x80, 0xd9, 0x03, + 0x84, 0xaa, 0x80, 0xdd, 0x90, 0x9f, 0xaf, 0x8f, + 0x41, 0xff, 0x59, 0xbf, 0xbf, 0x60, 0x56, 0x8c, + 0xc2, 0xad, 0x81, 0x41, 0x0c, 0x82, 0x8f, 0x89, + 0x81, 0x93, 0xae, 0x8f, 0x9e, 0x81, 0xcf, 0xa6, + 0x88, 0x81, 0xe6, 0x81, 0xd1, 0x93, 0x90, 0x02, + 0x03, 0x80, 0x96, 0x9c, 0xb3, 0x8d, 0xb1, 0xbd, + 0x2a, 0x00, 0x81, 0x8a, 0x9b, 0x89, 0x96, 0x98, + 0x9c, 0x86, 0xae, 0x9b, 0x80, 0x8f, 0x20, 0x89, + 0x89, 0x20, 0xa8, 0x96, 0x10, 0x87, 0x93, 0x96, + 0x10, 0x82, 0xb1, 0x00, 0x11, 0x0c, 0x08, 0x00, + 0x97, 0x11, 0x8a, 0x32, 0x8b, 0x29, 0x29, 0x85, + 0x88, 0x30, 0x30, 0xaa, 0x80, 0x8d, 0x85, 0xf2, + 0x9c, 0x60, 0x2b, 0xa3, 0x8b, 0x96, 0x83, 0xb0, + 0x60, 0x21, 0x03, 0x41, 0x6d, 0x81, 0xe9, 0xa5, + 0x86, 0x8b, 0x24, 0x00, 0x89, 0x80, 0x8c, 0x04, + 0x00, 0x01, 0x01, 0x80, 0xeb, 0xa0, 0x41, 0x6a, + 0x91, 0xbf, 0x81, 0xb5, 0xa7, 0x8b, 0xf3, 0x20, + 0x40, 0x86, 0xa3, 0x99, 0x85, 0x99, 0x8a, 0xd8, + 0x15, 0x0d, 0x0d, 0x0a, 0xa2, 0x8b, 0x80, 0x99, + 0x80, 0x92, 0x01, 0x80, 0x8e, 0x81, 0x8d, 0xa1, + 0xfa, 0xc4, 0xb4, 0x41, 0x0a, 0x9c, 0x82, 0xb0, + 0xae, 0x9f, 0x8c, 0x9d, 0x84, 0xa5, 0x89, 0x9d, + 0x81, 0xa3, 0x1f, 0x04, 0xa9, 0x40, 0x9d, 0x91, + 0xa3, 0x83, 0xa3, 0x83, 0xa7, 0x87, 0xb3, 0x8b, + 0x8a, 0x80, 0x8e, 0x06, 0x01, 0x80, 0x8a, 0x80, + 0x8e, 0x06, 0x01, 0x82, 0xb3, 0x8b, 0x41, 0x36, + 0x88, 0x95, 0x89, 0x87, 0x97, 0x28, 0xa9, 0x80, + 0x88, 0xc4, 0x29, 0x00, 0xab, 0x01, 0x10, 0x81, + 0x96, 0x89, 0x96, 0x88, 0x9e, 0xc0, 0x92, 0x01, + 0x89, 0x95, 0x89, 0x99, 0x85, 0x99, 0xa5, 0xb7, + 0x29, 0xbf, 0x80, 0x8e, 0x18, 0x10, 0x9c, 0xa9, + 0x9c, 0x82, 0x9c, 0xa2, 0x38, 0x9b, 0x9a, 0xb5, + 0x89, 0x95, 0x89, 0x92, 0x8c, 0x91, 0xed, 0xc8, + 0xb6, 0xb2, 0x8c, 0xb2, 0x8c, 0xa3, 0xa5, 0x9b, + 0x88, 0x96, 0x40, 0xf9, 0xa9, 0x29, 0x8f, 0x85, + 0xb7, 0x9c, 0x89, 0x07, 0x95, 0xa9, 0x91, 0xad, + 0x94, 0x9a, 0x96, 0x8b, 0xb4, 0xb8, 0x09, 0x80, + 0x8c, 0xac, 0x9f, 0x98, 0x99, 0xa3, 0x9c, 0x01, + 0x07, 0xa2, 0x10, 0x8b, 0xaf, 0x8d, 0x83, 0x94, + 0x00, 0x80, 0xa2, 0x91, 0x80, 0x98, 0x92, 0x81, + 0xbe, 0x30, 0x00, 0x18, 0x8e, 0x80, 0x89, 0x86, + 0xae, 0xa5, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04, + 0x10, 0x91, 0x80, 0x8b, 0x84, 0x9d, 0x89, 0x00, + 0x08, 0x80, 0xa5, 0x00, 0x98, 0x00, 0x80, 0xab, + 0xb4, 0x91, 0x83, 0x93, 0x82, 0x9d, 0xaf, 0x93, + 0x08, 0x80, 0x40, 0xb7, 0xae, 0xa8, 0x83, 0xa3, + 0xaf, 0x93, 0x80, 0xba, 0xaa, 0x8c, 0x80, 0xc6, + 0x9a, 0xa4, 0x86, 0x40, 0xb8, 0xab, 0xf3, 0xbf, + 0x9e, 0x39, 0x01, 0x38, 0x08, 0x97, 0x8e, 0x00, + 0x80, 0xdd, 0x39, 0xa6, 0x8f, 0x00, 0x80, 0x9b, + 0x80, 0x89, 0xa7, 0x30, 0x94, 0x80, 0x8a, 0xad, + 0x92, 0x80, 0x91, 0xc8, 0x40, 0xc6, 0xa0, 0x9e, + 0x88, 0x80, 0xa4, 0x90, 0x80, 0xb0, 0x9d, 0xef, + 0x30, 0x08, 0xa5, 0x94, 0x80, 0x98, 0x28, 0x08, + 0x9f, 0x8d, 0x80, 0x96, 0xab, 0x41, 0x03, 0x92, + 0x8e, 0x00, 0x8c, 0x80, 0xa1, 0xfb, 0x80, 0xce, + 0x43, 0x99, 0xe5, 0xee, 0x90, 0x40, 0xc3, 0x4a, + 0x4b, 0xe0, 0x8e, 0x44, 0x2f, 0x90, 0x85, 0x98, + 0x4f, 0x9a, 0x84, 0x42, 0x46, 0x5a, 0xb8, 0x9d, + 0x46, 0xe1, 0x42, 0x38, 0x86, 0x9e, 0x90, 0xce, + 0x90, 0x9d, 0x91, 0xaf, 0x8f, 0x83, 0x9e, 0x94, + 0x84, 0x92, 0x41, 0xaf, 0xac, 0x40, 0xd2, 0xbf, + 0x9f, 0x98, 0x81, 0x98, 0xab, 0xca, 0x20, 0xc1, + 0x8c, 0xbf, 0x08, 0x80, 0x8d, 0x84, 0x88, 0x5c, + 0xd5, 0xa8, 0x9f, 0xe0, 0xf2, 0x60, 0x21, 0xfc, + 0x18, 0x30, 0x08, 0x41, 0x22, 0x8e, 0x80, 0x9c, + 0x11, 0x80, 0x8d, 0x1f, 0x41, 0x8b, 0x49, 0x03, + 0xea, 0x84, 0x8c, 0x82, 0x88, 0x86, 0x89, 0x57, + 0x65, 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b, + 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f, + 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, 0x80, + 0x41, 0x53, 0x81, 0x98, 0x80, 0x98, 0x80, 0x9e, + 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, + 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x07, 0x47, + 0x33, 0x9e, 0x2d, 0x41, 0x04, 0xbd, 0x40, 0x91, + 0xac, 0x89, 0x86, 0x8f, 0x80, 0x41, 0x40, 0x9d, + 0x91, 0xab, 0x41, 0xe3, 0x9b, 0x40, 0xe3, 0x9d, + 0x08, 0x40, 0xce, 0x9e, 0x02, 0x01, 0x06, 0x0c, + 0x88, 0x81, 0x40, 0xdf, 0x30, 0x18, 0x08, 0x8e, + 0x80, 0x40, 0xc4, 0xba, 0xc3, 0x30, 0x44, 0xb3, + 0x18, 0x9a, 0x01, 0x00, 0x08, 0x80, 0x89, 0x03, + 0x00, 0x00, 0x28, 0x18, 0x00, 0x00, 0x02, 0x01, + 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x0b, 0x06, 0x03, 0x03, 0x00, 0x80, 0x89, 0x80, + 0x90, 0x22, 0x04, 0x80, 0x90, 0x51, 0x43, 0x60, + 0xa6, 0xdf, 0x9f, 0x51, 0x1d, 0x81, 0x56, 0x8d, + 0x81, 0x5d, 0x30, 0x8e, 0x42, 0x6d, 0x49, 0xa1, + 0x42, 0x1d, 0x45, 0xe1, 0x53, 0x4a, 0x84, 0x60, + 0x21, 0x29, +}; + +static const uint8_t unicode_prop_ID_Start_index[108] = { + 0xf6, 0x03, 0x20, 0xa6, 0x07, 0x00, 0xa9, 0x09, + 0x20, 0xb1, 0x0a, 0x00, 0xba, 0x0b, 0x20, 0x3b, + 0x0d, 0x20, 0xc7, 0x0e, 0x20, 0x49, 0x12, 0x00, + 0x9b, 0x16, 0x00, 0xac, 0x19, 0x00, 0xc0, 0x1d, + 0x80, 0x80, 0x20, 0x20, 0x70, 0x2d, 0x00, 0x00, + 0x32, 0x00, 0x06, 0xa8, 0x00, 0x77, 0xaa, 0x00, + 0xfc, 0xd7, 0x00, 0xfd, 0xfe, 0x40, 0xd1, 0x02, + 0x01, 0xb2, 0x05, 0x21, 0xf6, 0x08, 0x01, 0x49, + 0x0c, 0x01, 0x76, 0x10, 0x01, 0xdf, 0x12, 0x21, + 0xc8, 0x14, 0x41, 0x42, 0x19, 0x21, 0x31, 0x1d, + 0x61, 0xf1, 0x2f, 0x41, 0x78, 0x6b, 0x01, 0x23, + 0xb1, 0xa1, 0xad, 0xd4, 0x01, 0x6f, 0xd7, 0x01, + 0xee, 0xe5, 0x01, 0x38, 0xee, 0x01, 0xe0, 0xa6, + 0x42, 0x7a, 0x34, 0x03, +}; + +static const uint8_t unicode_prop_ID_Continue1_table[708] = { + 0xaf, 0x89, 0xa4, 0x80, 0xd6, 0x80, 0x42, 0x47, + 0xef, 0x96, 0x80, 0x40, 0xfa, 0x84, 0x41, 0x08, + 0xac, 0x00, 0x01, 0x01, 0x00, 0xc7, 0x8a, 0xaf, + 0x9e, 0x28, 0xe4, 0x31, 0x29, 0x08, 0x19, 0x89, + 0x96, 0x80, 0x9d, 0x9a, 0xda, 0x8a, 0x8e, 0x89, + 0xa0, 0x88, 0x88, 0x80, 0x97, 0x18, 0x88, 0x02, + 0x04, 0xaa, 0x82, 0xba, 0x88, 0xa9, 0x97, 0x80, + 0xa0, 0xb5, 0x10, 0x91, 0x06, 0x89, 0x09, 0x89, + 0x90, 0x82, 0xb7, 0x00, 0x31, 0x09, 0x82, 0x88, + 0x80, 0x89, 0x09, 0x89, 0x8d, 0x01, 0x82, 0xb7, + 0x00, 0x23, 0x09, 0x12, 0x80, 0x93, 0x8b, 0x10, + 0x8a, 0x82, 0xb7, 0x00, 0x38, 0x10, 0x82, 0x93, + 0x09, 0x89, 0x89, 0x28, 0x82, 0xb7, 0x00, 0x31, + 0x09, 0x16, 0x82, 0x89, 0x09, 0x89, 0x91, 0x80, + 0xba, 0x22, 0x10, 0x83, 0x88, 0x80, 0x8d, 0x89, + 0x8f, 0x84, 0xb6, 0x00, 0x30, 0x10, 0x1e, 0x81, + 0x8a, 0x09, 0x89, 0x90, 0x82, 0xb7, 0x00, 0x30, + 0x10, 0x1e, 0x81, 0x8a, 0x09, 0x89, 0x10, 0x8b, + 0x83, 0xb6, 0x08, 0x30, 0x10, 0x83, 0x88, 0x80, + 0x89, 0x09, 0x89, 0x90, 0x82, 0xc5, 0x03, 0x28, + 0x00, 0x3d, 0x89, 0x09, 0xbc, 0x01, 0x86, 0x8b, + 0x38, 0x89, 0xd6, 0x01, 0x88, 0x8a, 0x30, 0x89, + 0xbd, 0x0d, 0x89, 0x8a, 0x00, 0x00, 0x03, 0x81, + 0xb0, 0x93, 0x01, 0x84, 0x8a, 0x80, 0xa3, 0x88, + 0x80, 0xe3, 0x93, 0x80, 0x89, 0x8b, 0x1b, 0x10, + 0x11, 0x32, 0x83, 0x8c, 0x8b, 0x80, 0x8e, 0x42, + 0xbe, 0x82, 0x88, 0x88, 0x43, 0x9f, 0x83, 0x9b, + 0x82, 0x9c, 0x81, 0x9d, 0x81, 0xbf, 0x9f, 0x88, + 0x01, 0x89, 0xa0, 0x10, 0x8a, 0x40, 0x8e, 0x80, + 0xf5, 0x8b, 0x83, 0x8b, 0x89, 0x89, 0xff, 0x8a, + 0xbb, 0x84, 0xb8, 0x89, 0x80, 0x9c, 0x81, 0x8a, + 0x85, 0x89, 0x95, 0x8d, 0x80, 0x9e, 0x81, 0x8b, + 0x93, 0x84, 0xae, 0x90, 0x8a, 0x89, 0x90, 0x88, + 0x8b, 0x82, 0x9d, 0x8c, 0x81, 0x89, 0xab, 0x8d, + 0xaf, 0x93, 0x87, 0x89, 0x85, 0x89, 0xf5, 0x10, + 0x94, 0x18, 0x28, 0x0a, 0x40, 0xc5, 0xbf, 0x42, + 0x0b, 0x81, 0xb0, 0x81, 0x92, 0x80, 0xfa, 0x8c, + 0x18, 0x82, 0x8b, 0x4b, 0xfd, 0x82, 0x40, 0x8c, + 0x80, 0xdf, 0x9f, 0x42, 0x29, 0x85, 0xe8, 0x81, + 0xdf, 0x80, 0x60, 0x75, 0x23, 0x89, 0xc4, 0x03, + 0x89, 0x9f, 0x81, 0xcf, 0x81, 0x41, 0x0f, 0x02, + 0x03, 0x80, 0x96, 0x23, 0x80, 0xd2, 0x81, 0xb1, + 0x91, 0x89, 0x89, 0x85, 0x91, 0x8c, 0x8a, 0x9b, + 0x87, 0x98, 0x8c, 0xab, 0x83, 0xae, 0x8d, 0x8e, + 0x89, 0x8a, 0x80, 0x89, 0x89, 0xae, 0x8d, 0x8b, + 0x07, 0x09, 0x89, 0xa0, 0x82, 0xb1, 0x00, 0x11, + 0x0c, 0x08, 0x80, 0xa8, 0x24, 0x81, 0x40, 0xeb, + 0x38, 0x09, 0x89, 0x60, 0x4f, 0x23, 0x80, 0x42, + 0xe0, 0x8f, 0x8f, 0x8f, 0x11, 0x97, 0x82, 0x40, + 0xbf, 0x89, 0xa4, 0x80, 0xa4, 0x80, 0x42, 0x96, + 0x80, 0x40, 0xe1, 0x80, 0x40, 0x94, 0x84, 0x41, + 0x24, 0x89, 0x45, 0x56, 0x10, 0x0c, 0x83, 0xa7, + 0x13, 0x80, 0x40, 0xa4, 0x81, 0x42, 0x3c, 0x1f, + 0x89, 0x85, 0x89, 0x9e, 0x84, 0x41, 0x3c, 0x81, + 0xcc, 0x85, 0xc5, 0x8a, 0xb0, 0x83, 0xf9, 0x82, + 0xb4, 0x8e, 0x9e, 0x8a, 0x09, 0x89, 0x83, 0xac, + 0x8a, 0x30, 0xac, 0x89, 0x2a, 0xa3, 0x8d, 0x80, + 0x89, 0x21, 0xab, 0x80, 0x8b, 0x82, 0xaf, 0x8d, + 0x3b, 0x80, 0x8b, 0xd1, 0x8b, 0x28, 0x08, 0x40, + 0x9c, 0x8b, 0x84, 0x89, 0x2b, 0xb6, 0x08, 0x31, + 0x09, 0x82, 0x88, 0x80, 0x89, 0x09, 0x32, 0x84, + 0xc2, 0x88, 0x00, 0x08, 0x03, 0x04, 0x00, 0x8d, + 0x81, 0xd1, 0x91, 0x88, 0x89, 0x18, 0xd0, 0x93, + 0x8b, 0x89, 0x40, 0xd4, 0x31, 0x88, 0x9a, 0x81, + 0xd1, 0x90, 0x8e, 0x89, 0xd0, 0x8c, 0x87, 0x89, + 0x85, 0x93, 0xb8, 0x8e, 0x83, 0x89, 0x40, 0xf1, + 0x8e, 0x40, 0xa4, 0x89, 0xc5, 0x28, 0x09, 0x18, + 0x00, 0x81, 0x8b, 0x89, 0xf6, 0x31, 0x32, 0x80, + 0x9b, 0x89, 0xa7, 0x30, 0x1f, 0x80, 0x88, 0x8a, + 0xad, 0x8f, 0x40, 0xc5, 0x87, 0x40, 0x87, 0x89, + 0xb4, 0x38, 0x87, 0x8f, 0x89, 0xb7, 0x95, 0x80, + 0x8d, 0xf9, 0x2a, 0x00, 0x08, 0x30, 0x07, 0x89, + 0xaf, 0x20, 0x08, 0x27, 0x89, 0xb5, 0x89, 0x41, + 0x08, 0x83, 0x88, 0x08, 0x80, 0xaf, 0x32, 0x84, + 0x8c, 0x8a, 0x54, 0xe4, 0x05, 0x8e, 0x60, 0x2c, + 0xc7, 0x9b, 0x49, 0x25, 0x89, 0xd5, 0x89, 0xa5, + 0x84, 0xba, 0x86, 0x98, 0x89, 0x42, 0x15, 0x89, + 0x41, 0xd4, 0x00, 0xb6, 0x33, 0xd0, 0x80, 0x8a, + 0x81, 0x60, 0x4c, 0xaa, 0x81, 0x50, 0x50, 0x89, + 0x42, 0x05, 0xad, 0x81, 0x96, 0x42, 0x1d, 0x22, + 0x2f, 0x39, 0x86, 0x9d, 0x83, 0x40, 0x93, 0x82, + 0x45, 0x88, 0xb1, 0x41, 0xff, 0xb6, 0x83, 0xb1, + 0x38, 0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45, 0x4f, + 0x30, 0x90, 0x0e, 0x01, 0x04, 0xe3, 0x80, 0x40, + 0x9f, 0x86, 0x88, 0x89, 0x41, 0x63, 0x80, 0xbc, + 0x8d, 0x41, 0xf1, 0x8d, 0x40, 0xf3, 0x08, 0x89, + 0x40, 0xe7, 0x01, 0x06, 0x0c, 0x80, 0x41, 0xd9, + 0x86, 0xec, 0x34, 0x89, 0x52, 0x95, 0x89, 0x6c, + 0x05, 0x05, 0x40, 0xef, +}; + +static const uint8_t unicode_prop_ID_Continue1_index[66] = { + 0xfa, 0x06, 0x00, 0x70, 0x09, 0x00, 0xf0, 0x0a, + 0x40, 0x57, 0x0c, 0x00, 0xf0, 0x0d, 0x60, 0xc7, + 0x0f, 0x20, 0xea, 0x17, 0x40, 0xec, 0x1a, 0x00, + 0x0e, 0x20, 0x40, 0x7e, 0xa6, 0x20, 0xda, 0xa9, + 0x20, 0x10, 0xfe, 0x40, 0x40, 0x0a, 0x41, 0xbb, + 0x10, 0x21, 0x4e, 0x13, 0x41, 0xde, 0x15, 0x01, + 0xe5, 0x19, 0x01, 0x5a, 0x1d, 0x01, 0xf5, 0x6a, + 0x21, 0x8c, 0xd1, 0x61, 0x37, 0xe1, 0x41, 0xf0, + 0x01, 0x0e, +}; + +static const uint8_t unicode_prop_White_Space_table[22] = { + 0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x99, 0x80, + 0x55, 0xde, 0x80, 0x49, 0x7e, 0x8a, 0x9c, 0x0c, + 0x80, 0xae, 0x80, 0x4f, 0x9f, 0x80, +}; + +static const uint8_t unicode_prop_White_Space_index[3] = { + 0x01, 0x30, 0x00, +}; + +static const uint8_t unicode_cc_table[937] = { + 0xb2, 0xcf, 0xd4, 0x00, 0xe8, 0x03, 0xdc, 0x00, + 0xe8, 0x00, 0xd8, 0x04, 0xdc, 0x01, 0xca, 0x03, + 0xdc, 0x01, 0xca, 0x0a, 0xdc, 0x04, 0x01, 0x03, + 0xdc, 0xc7, 0x00, 0xf0, 0xc0, 0x02, 0xdc, 0xc2, + 0x01, 0xdc, 0x80, 0xc2, 0x03, 0xdc, 0xc0, 0x00, + 0xe8, 0x01, 0xdc, 0xc0, 0x41, 0xe9, 0x00, 0xea, + 0x41, 0xe9, 0x00, 0xea, 0x00, 0xe9, 0xcc, 0xb0, + 0xe2, 0xc4, 0xb0, 0xd8, 0x00, 0xdc, 0xc3, 0x00, + 0xdc, 0xc2, 0x00, 0xde, 0x00, 0xdc, 0xc5, 0x05, + 0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00, 0xde, 0x00, + 0xe4, 0xc0, 0x49, 0x0a, 0x43, 0x13, 0x80, 0x00, + 0x17, 0x80, 0x41, 0x18, 0x80, 0xc0, 0x00, 0xdc, + 0x80, 0x00, 0x12, 0xb0, 0x17, 0xc7, 0x42, 0x1e, + 0xaf, 0x47, 0x1b, 0xc1, 0x01, 0xdc, 0xc4, 0x00, + 0xdc, 0xc1, 0x00, 0xdc, 0x8f, 0x00, 0x23, 0xb0, + 0x34, 0xc6, 0x81, 0xc3, 0x00, 0xdc, 0xc0, 0x81, + 0xc1, 0x80, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xa2, + 0x00, 0x24, 0x9d, 0xc0, 0x00, 0xdc, 0xc1, 0x00, + 0xdc, 0xc1, 0x02, 0xdc, 0xc0, 0x01, 0xdc, 0xc0, + 0x00, 0xdc, 0xc2, 0x00, 0xdc, 0xc0, 0x00, 0xdc, + 0xc0, 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xc1, 0xb0, + 0x6f, 0xc6, 0x00, 0xdc, 0xc0, 0x88, 0x00, 0xdc, + 0x97, 0xc3, 0x80, 0xc8, 0x80, 0xc2, 0x80, 0xc4, + 0xaa, 0x02, 0xdc, 0xb0, 0x0a, 0xc1, 0x02, 0xdc, + 0xc3, 0xa9, 0xc4, 0x04, 0xdc, 0xcd, 0x80, 0x00, + 0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xc2, + 0x02, 0xdc, 0x42, 0x1b, 0xc2, 0x00, 0xdc, 0xc1, + 0x01, 0xdc, 0xc4, 0xb0, 0x0b, 0x00, 0x07, 0x8f, + 0x00, 0x09, 0x82, 0xc0, 0x00, 0xdc, 0xc1, 0xb0, + 0x36, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xaf, 0xc0, + 0xb0, 0x0c, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0, + 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0, 0x3d, + 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0, 0x4e, 0x00, + 0x09, 0xb0, 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09, + 0x86, 0x00, 0x54, 0x00, 0x5b, 0xb0, 0x34, 0x00, + 0x07, 0x8f, 0x00, 0x09, 0xb0, 0x3c, 0x01, 0x09, + 0x8f, 0x00, 0x09, 0xb0, 0x4b, 0x00, 0x09, 0xb0, + 0x3c, 0x01, 0x67, 0x00, 0x09, 0x8c, 0x03, 0x6b, + 0xb0, 0x3b, 0x01, 0x76, 0x00, 0x09, 0x8c, 0x03, + 0x7a, 0xb0, 0x1b, 0x01, 0xdc, 0x9a, 0x00, 0xdc, + 0x80, 0x00, 0xdc, 0x80, 0x00, 0xd8, 0xb0, 0x06, + 0x41, 0x81, 0x80, 0x00, 0x84, 0x84, 0x03, 0x82, + 0x81, 0x00, 0x82, 0x80, 0xc1, 0x00, 0x09, 0x80, + 0xc1, 0xb0, 0x0d, 0x00, 0xdc, 0xb0, 0x3f, 0x00, + 0x07, 0x80, 0x01, 0x09, 0xb0, 0x21, 0x00, 0xdc, + 0xb2, 0x9e, 0xc2, 0xb3, 0x83, 0x01, 0x09, 0x9d, + 0x00, 0x09, 0xb0, 0x6c, 0x00, 0x09, 0x89, 0xc0, + 0xb0, 0x9a, 0x00, 0xe4, 0xb0, 0x5e, 0x00, 0xde, + 0xc0, 0x00, 0xdc, 0xb0, 0xaa, 0xc0, 0x00, 0xdc, + 0xb0, 0x16, 0x00, 0x09, 0x93, 0xc7, 0x81, 0x00, + 0xdc, 0xaf, 0xc4, 0x05, 0xdc, 0xc1, 0x00, 0xdc, + 0x80, 0x01, 0xdc, 0xc1, 0x01, 0xdc, 0xc4, 0x00, + 0xdc, 0xd1, 0x00, 0xdc, 0x81, 0xc5, 0x00, 0xdc, + 0xc3, 0x00, 0xea, 0xb0, 0x17, 0x00, 0x07, 0x8e, + 0x00, 0x09, 0xa5, 0xc0, 0x00, 0xdc, 0xc6, 0xb0, + 0x05, 0x01, 0x09, 0xb0, 0x09, 0x00, 0x07, 0x8a, + 0x01, 0x09, 0xb0, 0x12, 0x00, 0x07, 0xb0, 0x67, + 0xc2, 0x41, 0x00, 0x04, 0xdc, 0xc1, 0x03, 0xdc, + 0xc0, 0x41, 0x00, 0x05, 0x01, 0x83, 0x00, 0xdc, + 0x85, 0xc0, 0x82, 0xc1, 0xb0, 0x95, 0xc1, 0x00, + 0xdc, 0xc6, 0x00, 0xdc, 0xc1, 0x00, 0xea, 0x00, + 0xd6, 0x00, 0xdc, 0x00, 0xca, 0xe4, 0x00, 0xe8, + 0x01, 0xe4, 0x00, 0xdc, 0x00, 0xda, 0xc0, 0x00, + 0xe9, 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xb2, 0x9f, + 0xc1, 0x01, 0x01, 0xc3, 0x02, 0x01, 0xc1, 0x83, + 0xc0, 0x82, 0x01, 0x01, 0xc0, 0x00, 0xdc, 0xc0, + 0x01, 0x01, 0x03, 0xdc, 0xc0, 0xb8, 0x03, 0xcd, + 0xc2, 0xb0, 0x5c, 0x00, 0x09, 0xb0, 0x2f, 0xdf, + 0xb1, 0xf9, 0x00, 0xda, 0x00, 0xe4, 0x00, 0xe8, + 0x00, 0xde, 0x01, 0xe0, 0xb0, 0x38, 0x01, 0x08, + 0xb8, 0x6d, 0xa3, 0xc0, 0x83, 0xc9, 0x9f, 0xc1, + 0xb0, 0x1f, 0xc1, 0xb0, 0xe3, 0x00, 0x09, 0xa4, + 0x00, 0x09, 0xb0, 0x66, 0x00, 0x09, 0x9a, 0xd1, + 0xb0, 0x08, 0x02, 0xdc, 0xa4, 0x00, 0x09, 0xb0, + 0x2e, 0x00, 0x07, 0x8b, 0x00, 0x09, 0xb0, 0xbe, + 0xc0, 0x80, 0xc1, 0x00, 0xdc, 0x81, 0xc1, 0x84, + 0xc1, 0x80, 0xc0, 0xb0, 0x03, 0x00, 0x09, 0xb0, + 0xc5, 0x00, 0x09, 0xb8, 0x46, 0xff, 0x00, 0x1a, + 0xb2, 0xd0, 0xc6, 0x06, 0xdc, 0xc1, 0xb3, 0x9c, + 0x00, 0xdc, 0xb0, 0xb1, 0x00, 0xdc, 0xb0, 0x64, + 0xc4, 0xb6, 0x61, 0x00, 0xdc, 0x80, 0xc0, 0xa7, + 0xc0, 0x00, 0x01, 0x00, 0xdc, 0x83, 0x00, 0x09, + 0xb0, 0x74, 0xc0, 0x00, 0xdc, 0xb2, 0x0c, 0xc3, + 0xb0, 0x10, 0xc4, 0xb1, 0x0c, 0xc1, 0xb0, 0x1c, + 0x01, 0xdc, 0x80, 0x02, 0xdc, 0xb0, 0x15, 0x01, + 0xdc, 0xc2, 0x00, 0xdc, 0xc0, 0x03, 0xdc, 0xb0, + 0x00, 0xc0, 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xb0, + 0x8f, 0x00, 0x09, 0xa8, 0x00, 0x09, 0x8d, 0x00, + 0x09, 0xb0, 0x08, 0x00, 0x09, 0x00, 0x07, 0xb0, + 0x14, 0xc2, 0xaf, 0x01, 0x09, 0xb0, 0x0d, 0x00, + 0x07, 0xb0, 0x1b, 0x00, 0x09, 0x88, 0x00, 0x07, + 0xb0, 0x39, 0x00, 0x09, 0x00, 0x07, 0xb0, 0x81, + 0x00, 0x07, 0x00, 0x09, 0xb0, 0x1f, 0x01, 0x07, + 0x8f, 0x00, 0x09, 0x97, 0xc6, 0x82, 0xc4, 0xb0, + 0x28, 0x02, 0x09, 0xb0, 0x40, 0x00, 0x09, 0x82, + 0x00, 0x07, 0x96, 0xc0, 0xb0, 0x32, 0x00, 0x09, + 0x00, 0x07, 0xb0, 0xca, 0x00, 0x09, 0x00, 0x07, + 0xb0, 0x4d, 0x00, 0x09, 0xb0, 0x45, 0x00, 0x09, + 0x00, 0x07, 0xb0, 0x42, 0x00, 0x09, 0xb0, 0xdc, + 0x00, 0x09, 0x00, 0x07, 0xb0, 0xd1, 0x01, 0x09, + 0x83, 0x00, 0x07, 0xb0, 0x6b, 0x00, 0x09, 0xb0, + 0x22, 0x00, 0x09, 0x91, 0x00, 0x09, 0xb0, 0x20, + 0x00, 0x09, 0xb1, 0x74, 0x00, 0x09, 0xb0, 0xd1, + 0x00, 0x07, 0x80, 0x01, 0x09, 0xb0, 0x20, 0x00, + 0x09, 0xb1, 0x78, 0x01, 0x09, 0xb8, 0x39, 0xbb, + 0x00, 0x09, 0xb8, 0x01, 0x8f, 0x04, 0x01, 0xb0, + 0x0a, 0xc6, 0xb4, 0x88, 0x01, 0x06, 0xb8, 0x44, + 0x7b, 0x00, 0x01, 0xb8, 0x0c, 0x95, 0x01, 0xd8, + 0x02, 0x01, 0x82, 0x00, 0xe2, 0x04, 0xd8, 0x87, + 0x07, 0xdc, 0x81, 0xc4, 0x01, 0xdc, 0x9d, 0xc3, + 0xb0, 0x63, 0xc2, 0xb8, 0x05, 0x8a, 0xc6, 0x80, + 0xd0, 0x81, 0xc6, 0x80, 0xc1, 0x80, 0xc4, 0xb0, + 0x33, 0xc0, 0xb0, 0x6f, 0xc6, 0xb1, 0x46, 0xc0, + 0xb0, 0x0c, 0xc3, 0xb1, 0xcb, 0x01, 0xe8, 0x00, + 0xdc, 0xc0, 0xb0, 0xcd, 0xc0, 0x00, 0xdc, 0xb0, + 0xc2, 0xc0, 0x81, 0xc0, 0x86, 0xc1, 0x84, 0xc0, + 0xb1, 0xa9, 0x06, 0xdc, 0xb0, 0x3c, 0xc5, 0x00, + 0x07, +}; + +static const uint8_t unicode_cc_index[90] = { + 0x4d, 0x03, 0x00, 0x97, 0x05, 0x20, 0xc6, 0x05, + 0x00, 0xe7, 0x06, 0x00, 0x45, 0x07, 0x00, 0x9c, + 0x08, 0x00, 0x4d, 0x09, 0x00, 0x3c, 0x0b, 0x00, + 0x3d, 0x0d, 0x00, 0x36, 0x0f, 0x00, 0x38, 0x10, + 0x20, 0x3a, 0x19, 0x00, 0xcb, 0x1a, 0x20, 0xf2, + 0x1b, 0x00, 0xc3, 0x1d, 0x20, 0xd0, 0x20, 0x00, + 0x00, 0x2e, 0x00, 0x2c, 0xa8, 0x00, 0xbe, 0xaa, + 0x00, 0x76, 0x03, 0x01, 0xfa, 0x0e, 0x01, 0x80, + 0x10, 0x21, 0xe9, 0x12, 0x01, 0xc3, 0x14, 0x01, + 0x3f, 0x19, 0x01, 0x98, 0x1d, 0x21, 0x67, 0xd1, + 0x01, 0x8f, 0xe0, 0x21, 0xf6, 0xe6, 0x01, 0x4b, + 0xe9, 0x01, +}; + +static const uint32_t unicode_decomp_table1[709] = { + 0x00280081, 0x002a0097, 0x002a8081, 0x002bc097, + 0x002c8115, 0x002d0097, 0x002d4081, 0x002e0097, + 0x002e4115, 0x002f0199, 0x00302016, 0x00400842, + 0x00448a42, 0x004a0442, 0x004c0096, 0x004c8117, + 0x004d0242, 0x004e4342, 0x004fc12f, 0x0050c342, + 0x005240bf, 0x00530342, 0x00550942, 0x005a0842, + 0x005e0096, 0x005e4342, 0x005fc081, 0x00680142, + 0x006bc142, 0x00710185, 0x0071c317, 0x00734844, + 0x00778344, 0x00798342, 0x007b02be, 0x007c4197, + 0x007d0142, 0x007e0444, 0x00800e42, 0x00878142, + 0x00898744, 0x00ac0483, 0x00b60317, 0x00b80283, + 0x00d00214, 0x00d10096, 0x00dd0080, 0x00de8097, + 0x00df8080, 0x00e10097, 0x00e1413e, 0x00e1c080, + 0x00e204be, 0x00ea83ae, 0x00f282ae, 0x00f401ad, + 0x00f4c12e, 0x00f54103, 0x00fc0303, 0x00fe4081, + 0x0100023e, 0x0101c0be, 0x010301be, 0x010640be, + 0x010e40be, 0x0114023e, 0x0115c0be, 0x011701be, + 0x011d8144, 0x01304144, 0x01340244, 0x01358144, + 0x01368344, 0x01388344, 0x013a8644, 0x013e0144, + 0x0161c085, 0x018882ae, 0x019d422f, 0x01b00184, + 0x01b4c084, 0x024a4084, 0x024c4084, 0x024d0084, + 0x0256042e, 0x0272c12e, 0x02770120, 0x0277c084, + 0x028cc084, 0x028d8084, 0x029641ae, 0x02978084, + 0x02d20084, 0x02d2c12e, 0x02d70120, 0x02e50084, + 0x02f281ae, 0x03120084, 0x03300084, 0x0331c122, + 0x0332812e, 0x035281ae, 0x03768084, 0x037701ae, + 0x038cc085, 0x03acc085, 0x03b7012f, 0x03c30081, + 0x03d0c084, 0x03d34084, 0x03d48084, 0x03d5c084, + 0x03d70084, 0x03da4084, 0x03dcc084, 0x03dd412e, + 0x03ddc085, 0x03de0084, 0x03de4085, 0x03e04084, + 0x03e4c084, 0x03e74084, 0x03e88084, 0x03e9c084, + 0x03eb0084, 0x03ee4084, 0x04098084, 0x043f0081, + 0x06c18484, 0x06c48084, 0x06cec184, 0x06d00120, + 0x06d0c084, 0x074b0383, 0x074cc41f, 0x074f1783, + 0x075e0081, 0x0766d283, 0x07801d44, 0x078e8942, + 0x07931844, 0x079f0d42, 0x07a58216, 0x07a68085, + 0x07a6c0be, 0x07a80d44, 0x07aea044, 0x07c00122, + 0x07c08344, 0x07c20122, 0x07c28344, 0x07c40122, + 0x07c48244, 0x07c60122, 0x07c68244, 0x07c8113e, + 0x07d08244, 0x07d20122, 0x07d28244, 0x07d40122, + 0x07d48344, 0x07d64c3e, 0x07dc4080, 0x07dc80be, + 0x07dcc080, 0x07dd00be, 0x07dd4080, 0x07dd80be, + 0x07ddc080, 0x07de00be, 0x07de4080, 0x07de80be, + 0x07dec080, 0x07df00be, 0x07df4080, 0x07e00820, + 0x07e40820, 0x07e80820, 0x07ec05be, 0x07eec080, + 0x07ef00be, 0x07ef4097, 0x07ef8080, 0x07efc117, + 0x07f0443e, 0x07f24080, 0x07f280be, 0x07f2c080, + 0x07f303be, 0x07f4c080, 0x07f582ae, 0x07f6c080, + 0x07f7433e, 0x07f8c080, 0x07f903ae, 0x07fac080, + 0x07fb013e, 0x07fb8102, 0x07fc83be, 0x07fe4080, + 0x07fe80be, 0x07fec080, 0x07ff00be, 0x07ff4080, + 0x07ff8097, 0x0800011e, 0x08008495, 0x08044081, + 0x0805c097, 0x08090081, 0x08094097, 0x08098099, + 0x080bc081, 0x080cc085, 0x080d00b1, 0x080d8085, + 0x080dc0b1, 0x080f0197, 0x0811c197, 0x0815c0b3, + 0x0817c081, 0x081c0595, 0x081ec081, 0x081f0215, + 0x0820051f, 0x08228583, 0x08254415, 0x082a0097, + 0x08400119, 0x08408081, 0x0840c0bf, 0x08414119, + 0x0841c081, 0x084240bf, 0x0842852d, 0x08454081, + 0x08458097, 0x08464295, 0x08480097, 0x08484099, + 0x08488097, 0x08490081, 0x08498080, 0x084a0081, + 0x084a8102, 0x084b0495, 0x084d421f, 0x084e4081, + 0x084ec099, 0x084f0283, 0x08514295, 0x08540119, + 0x0854809b, 0x0854c619, 0x0857c097, 0x08580081, + 0x08584097, 0x08588099, 0x0858c097, 0x08590081, + 0x08594097, 0x08598099, 0x0859c09b, 0x085a0097, + 0x085a4081, 0x085a8097, 0x085ac099, 0x085b0295, + 0x085c4097, 0x085c8099, 0x085cc097, 0x085d0081, + 0x085d4097, 0x085d8099, 0x085dc09b, 0x085e0097, + 0x085e4081, 0x085e8097, 0x085ec099, 0x085f0215, + 0x08624099, 0x0866813e, 0x086b80be, 0x087341be, + 0x088100be, 0x088240be, 0x088300be, 0x088901be, + 0x088b0085, 0x088b40b1, 0x088bc085, 0x088c00b1, + 0x089040be, 0x089100be, 0x0891c1be, 0x089801be, + 0x089b42be, 0x089d0144, 0x089e0144, 0x08a00144, + 0x08a10144, 0x08a20144, 0x08ab023e, 0x08b80244, + 0x08ba8220, 0x08ca411e, 0x0918049f, 0x091a4523, + 0x091cc097, 0x091d04a5, 0x091f452b, 0x0921c09b, + 0x092204a1, 0x09244525, 0x0926c099, 0x09270d25, + 0x092d8d1f, 0x09340d1f, 0x093a8081, 0x0a8300b3, + 0x0a9d0099, 0x0a9d4097, 0x0a9d8099, 0x0ab700be, + 0x0b1f0115, 0x0b5bc081, 0x0ba7c081, 0x0bbcc081, + 0x0bc004ad, 0x0bc244ad, 0x0bc484ad, 0x0bc6f383, + 0x0be0852d, 0x0be31d03, 0x0bf1882d, 0x0c000081, + 0x0c0d8283, 0x0c130b84, 0x0c194284, 0x0c1c0122, + 0x0c1cc122, 0x0c1d8122, 0x0c1e4122, 0x0c1f0122, + 0x0c250084, 0x0c26c123, 0x0c278084, 0x0c27c085, + 0x0c2b0b84, 0x0c314284, 0x0c340122, 0x0c34c122, + 0x0c358122, 0x0c364122, 0x0c370122, 0x0c3d0084, + 0x0c3dc220, 0x0c3f8084, 0x0c3fc085, 0x0c4c4a2d, + 0x0c51451f, 0x0c53ca9f, 0x0c5915ad, 0x0c648703, + 0x0c800741, 0x0c838089, 0x0c83c129, 0x0c8441a9, + 0x0c850089, 0x0c854129, 0x0c85c2a9, 0x0c870089, + 0x0c87408f, 0x0c87808d, 0x0c881241, 0x0c910203, + 0x0c940099, 0x0c9444a3, 0x0c968323, 0x0c98072d, + 0x0c9b84af, 0x0c9dc2a1, 0x0c9f00b5, 0x0c9f40b3, + 0x0c9f8085, 0x0ca01883, 0x0cac4223, 0x0cad4523, + 0x0cafc097, 0x0cb004a1, 0x0cb241a5, 0x0cb30097, + 0x0cb34099, 0x0cb38097, 0x0cb3c099, 0x0cb417ad, + 0x0cbfc085, 0x0cc001b3, 0x0cc0c0b1, 0x0cc100b3, + 0x0cc14131, 0x0cc1c0b5, 0x0cc200b3, 0x0cc241b1, + 0x0cc30133, 0x0cc38131, 0x0cc40085, 0x0cc440b1, + 0x0cc48133, 0x0cc50085, 0x0cc540b5, 0x0cc580b7, + 0x0cc5c0b5, 0x0cc600b1, 0x0cc64135, 0x0cc6c0b3, + 0x0cc701b1, 0x0cc7c0b3, 0x0cc800b5, 0x0cc840b3, + 0x0cc881b1, 0x0cc9422f, 0x0cca4131, 0x0ccac0b5, + 0x0ccb00b1, 0x0ccb40b3, 0x0ccb80b5, 0x0ccbc0b1, + 0x0ccc012f, 0x0ccc80b5, 0x0cccc0b3, 0x0ccd00b5, + 0x0ccd40b1, 0x0ccd80b5, 0x0ccdc085, 0x0cce02b1, + 0x0ccf40b3, 0x0ccf80b1, 0x0ccfc085, 0x0cd001b1, + 0x0cd0c0b3, 0x0cd101b1, 0x0cd1c0b5, 0x0cd200b3, + 0x0cd24085, 0x0cd280b5, 0x0cd2c085, 0x0cd30133, + 0x0cd381b1, 0x0cd440b3, 0x0cd48085, 0x0cd4c0b1, + 0x0cd500b3, 0x0cd54085, 0x0cd580b5, 0x0cd5c0b1, + 0x0cd60521, 0x0cd88525, 0x0cdb02a5, 0x0cdc4099, + 0x0cdc8117, 0x0cdd0099, 0x0cdd4197, 0x0cde0127, + 0x0cde8285, 0x0cdfc089, 0x0ce0043f, 0x0ce20099, + 0x0ce2409b, 0x0ce283bf, 0x0ce44219, 0x0ce54205, + 0x0ce6433f, 0x0ce7c131, 0x0ce84085, 0x0ce881b1, + 0x0ce94085, 0x0ce98107, 0x0cea0089, 0x0cea4097, + 0x0cea8219, 0x0ceb809d, 0x0cebc08d, 0x0cec083f, + 0x0cf00105, 0x0cf0809b, 0x0cf0c197, 0x0cf1809b, + 0x0cf1c099, 0x0cf20517, 0x0cf48099, 0x0cf4c117, + 0x0cf54119, 0x0cf5c097, 0x0cf6009b, 0x0cf64099, + 0x0cf68217, 0x0cf78119, 0x0cf804a1, 0x0cfa4525, + 0x0cfcc525, 0x0cff4125, 0x0cffc099, 0x29a70103, + 0x29dc0081, 0x29fc4215, 0x29fe0103, 0x2ad70203, + 0x2ada4081, 0x3e401482, 0x3e4a7f82, 0x3e6a3f82, + 0x3e8aa102, 0x3e9b0110, 0x3e9c2f82, 0x3eb3c590, + 0x3ec00197, 0x3ec0c119, 0x3ec1413f, 0x3ec4c2af, + 0x3ec74184, 0x3ec804ad, 0x3eca4081, 0x3eca8304, + 0x3ecc03a0, 0x3ece02a0, 0x3ecf8084, 0x3ed00120, + 0x3ed0c120, 0x3ed184ae, 0x3ed3c085, 0x3ed4312d, + 0x3ef4cbad, 0x3efa892f, 0x3eff022d, 0x3f002f2f, + 0x3f1782a5, 0x3f18c0b1, 0x3f1907af, 0x3f1cffaf, + 0x3f3c81a5, 0x3f3d64af, 0x3f542031, 0x3f649b31, + 0x3f7c0131, 0x3f7c83b3, 0x3f7e40b1, 0x3f7e80bd, + 0x3f7ec0bb, 0x3f7f00b3, 0x3f840503, 0x3f8c01ad, + 0x3f8cc315, 0x3f8e462d, 0x3f91cc03, 0x3f97c695, + 0x3f9c01af, 0x3f9d0085, 0x3f9d852f, 0x3fa03aad, + 0x3fbd442f, 0x3fc06f1f, 0x3fd7c11f, 0x3fd85fad, + 0x3fe80081, 0x3fe84f1f, 0x3ff0831f, 0x3ff2831f, + 0x3ff4831f, 0x3ff6819f, 0x3ff80783, 0x41724092, + 0x41790092, 0x41e04d83, 0x41e70f91, 0x44268192, + 0x442ac092, 0x444b8112, 0x44d2c112, 0x44e0c192, + 0x44e38092, 0x44e44092, 0x44f14212, 0x452ec212, + 0x456e8112, 0x464e0092, 0x58484412, 0x5b5a0192, + 0x73358d1f, 0x733c051f, 0x74578392, 0x746ec312, + 0x75000d1f, 0x75068d1f, 0x750d0d1f, 0x7513839f, + 0x7515891f, 0x751a0d1f, 0x75208d1f, 0x75271015, + 0x752f439f, 0x7531459f, 0x75340d1f, 0x753a8d1f, + 0x75410395, 0x7543441f, 0x7545839f, 0x75478d1f, + 0x754e0795, 0x7552839f, 0x75548d1f, 0x755b0d1f, + 0x75618d1f, 0x75680d1f, 0x756e8d1f, 0x75750d1f, + 0x757b8d1f, 0x75820d1f, 0x75888d1f, 0x758f0d1f, + 0x75958d1f, 0x759c0d1f, 0x75a28d1f, 0x75a90103, + 0x75aa089f, 0x75ae4081, 0x75ae839f, 0x75b04081, + 0x75b08c9f, 0x75b6c081, 0x75b7032d, 0x75b8889f, + 0x75bcc081, 0x75bd039f, 0x75bec081, 0x75bf0c9f, + 0x75c54081, 0x75c5832d, 0x75c7089f, 0x75cb4081, + 0x75cb839f, 0x75cd4081, 0x75cd8c9f, 0x75d3c081, + 0x75d4032d, 0x75d5889f, 0x75d9c081, 0x75da039f, + 0x75dbc081, 0x75dc0c9f, 0x75e24081, 0x75e2832d, + 0x75e4089f, 0x75e84081, 0x75e8839f, 0x75ea4081, + 0x75ea8c9f, 0x75f0c081, 0x75f1042d, 0x75f3851f, + 0x75f6051f, 0x75f8851f, 0x75fb051f, 0x75fd851f, + 0x780c049f, 0x780e419f, 0x780f059f, 0x7811c203, + 0x7812d0ad, 0x781b0103, 0x7b80022d, 0x7b814dad, + 0x7b884203, 0x7b89c081, 0x7b8a452d, 0x7b8d0403, + 0x7b908081, 0x7b91dc03, 0x7ba0052d, 0x7ba2c8ad, + 0x7ba84483, 0x7baac8ad, 0x7c400097, 0x7c404521, + 0x7c440d25, 0x7c4a8087, 0x7c4ac115, 0x7c4b4117, + 0x7c4c0d1f, 0x7c528217, 0x7c538099, 0x7c53c097, + 0x7c5a8197, 0x7c640097, 0x7c80012f, 0x7c808081, + 0x7c841603, 0x7c9004c1, 0x7c940103, 0x7efc051f, + 0xbe0001ac, 0xbe00d110, 0xbe0947ac, 0xbe0d3910, + 0xbe29872c, 0xbe2d022c, 0xbe2e3790, 0xbe49ff90, + 0xbe69bc10, +}; + +static const uint16_t unicode_decomp_table2[709] = { + 0x0020, 0x0000, 0x0061, 0x0002, 0x0004, 0x0006, 0x03bc, 0x0008, + 0x000a, 0x000c, 0x0015, 0x0095, 0x00a5, 0x00b9, 0x00c1, 0x00c3, + 0x00c7, 0x00cb, 0x00d1, 0x00d7, 0x00dd, 0x00e0, 0x00e6, 0x00f8, + 0x0108, 0x010a, 0x0073, 0x0110, 0x0112, 0x0114, 0x0120, 0x012c, + 0x0144, 0x014d, 0x0153, 0x0162, 0x0168, 0x016a, 0x0176, 0x0192, + 0x0194, 0x01a9, 0x01bb, 0x01c7, 0x01d1, 0x01d5, 0x02b9, 0x01d7, + 0x003b, 0x01d9, 0x01db, 0x00b7, 0x01e1, 0x01fc, 0x020c, 0x0218, + 0x021d, 0x0223, 0x0227, 0x03a3, 0x0233, 0x023f, 0x0242, 0x024b, + 0x024e, 0x0251, 0x025d, 0x0260, 0x0269, 0x026c, 0x026f, 0x0275, + 0x0278, 0x0281, 0x028a, 0x029c, 0x029f, 0x02a3, 0x02af, 0x02b9, + 0x02c5, 0x02c9, 0x02cd, 0x02d1, 0x02d5, 0x02e7, 0x02ed, 0x02f1, + 0x02f5, 0x02f9, 0x02fd, 0x0305, 0x0309, 0x030d, 0x0313, 0x0317, + 0x031b, 0x0323, 0x0327, 0x032b, 0x032f, 0x0335, 0x033d, 0x0341, + 0x0349, 0x034d, 0x0351, 0x0f0b, 0x0357, 0x035b, 0x035f, 0x0363, + 0x0367, 0x036b, 0x036f, 0x0373, 0x0379, 0x037d, 0x0381, 0x0385, + 0x0389, 0x038d, 0x0391, 0x0395, 0x0399, 0x039d, 0x03a1, 0x10dc, + 0x03a5, 0x03c9, 0x03cd, 0x03d9, 0x03dd, 0x03e1, 0x03ef, 0x03f1, + 0x043d, 0x044f, 0x0499, 0x04f0, 0x0502, 0x054a, 0x0564, 0x056c, + 0x0570, 0x0573, 0x059a, 0x05fa, 0x05fe, 0x0607, 0x060b, 0x0614, + 0x0618, 0x061e, 0x0622, 0x0628, 0x068e, 0x0694, 0x0698, 0x069e, + 0x06a2, 0x06ab, 0x03ac, 0x06f3, 0x03ad, 0x06f6, 0x03ae, 0x06f9, + 0x03af, 0x06fc, 0x03cc, 0x06ff, 0x03cd, 0x0702, 0x03ce, 0x0705, + 0x0709, 0x070d, 0x0711, 0x0386, 0x0732, 0x0735, 0x03b9, 0x0737, + 0x073b, 0x0388, 0x0753, 0x0389, 0x0756, 0x0390, 0x076b, 0x038a, + 0x0777, 0x03b0, 0x0789, 0x038e, 0x0799, 0x079f, 0x07a3, 0x038c, + 0x07b8, 0x038f, 0x07bb, 0x00b4, 0x07be, 0x07c0, 0x07c2, 0x2010, + 0x07cb, 0x002e, 0x07cd, 0x07cf, 0x0020, 0x07d2, 0x07d6, 0x07db, + 0x07df, 0x07e4, 0x07ea, 0x07f0, 0x0020, 0x07f6, 0x2212, 0x0801, + 0x0805, 0x0807, 0x081d, 0x0825, 0x0827, 0x0043, 0x082d, 0x0830, + 0x0190, 0x0836, 0x0839, 0x004e, 0x0845, 0x0847, 0x084c, 0x084e, + 0x0851, 0x005a, 0x03a9, 0x005a, 0x0853, 0x0857, 0x0860, 0x0069, + 0x0862, 0x0865, 0x086f, 0x0874, 0x087a, 0x087e, 0x08a2, 0x0049, + 0x08a4, 0x08a6, 0x08a9, 0x0056, 0x08ab, 0x08ad, 0x08b0, 0x08b4, + 0x0058, 0x08b6, 0x08b8, 0x08bb, 0x08c0, 0x08c2, 0x08c5, 0x0076, + 0x08c7, 0x08c9, 0x08cc, 0x08d0, 0x0078, 0x08d2, 0x08d4, 0x08d7, + 0x08db, 0x08de, 0x08e4, 0x08e7, 0x08f0, 0x08f3, 0x08f6, 0x08f9, + 0x0902, 0x0906, 0x090b, 0x090f, 0x0914, 0x0917, 0x091a, 0x0923, + 0x092c, 0x093b, 0x093e, 0x0941, 0x0944, 0x0947, 0x094a, 0x0956, + 0x095c, 0x0960, 0x0962, 0x0964, 0x0968, 0x096a, 0x0970, 0x0978, + 0x097c, 0x0980, 0x0986, 0x0989, 0x098f, 0x0991, 0x0030, 0x0993, + 0x0999, 0x099c, 0x099e, 0x09a1, 0x09a4, 0x2d61, 0x6bcd, 0x9f9f, + 0x09a6, 0x09b1, 0x09bc, 0x09c7, 0x0a95, 0x0aa1, 0x0b15, 0x0020, + 0x0b27, 0x0b31, 0x0b8d, 0x0ba1, 0x0ba5, 0x0ba9, 0x0bad, 0x0bb1, + 0x0bb5, 0x0bb9, 0x0bbd, 0x0bc1, 0x0bc5, 0x0c21, 0x0c35, 0x0c39, + 0x0c3d, 0x0c41, 0x0c45, 0x0c49, 0x0c4d, 0x0c51, 0x0c55, 0x0c59, + 0x0c6f, 0x0c71, 0x0c73, 0x0ca0, 0x0cbc, 0x0cdc, 0x0ce4, 0x0cec, + 0x0cf4, 0x0cfc, 0x0d04, 0x0d0c, 0x0d14, 0x0d22, 0x0d2e, 0x0d7a, + 0x0d82, 0x0d85, 0x0d89, 0x0d8d, 0x0d9d, 0x0db1, 0x0db5, 0x0dbc, + 0x0dc2, 0x0dc6, 0x0e28, 0x0e2c, 0x0e30, 0x0e32, 0x0e36, 0x0e3c, + 0x0e3e, 0x0e41, 0x0e43, 0x0e46, 0x0e77, 0x0e7b, 0x0e89, 0x0e8e, + 0x0e94, 0x0e9c, 0x0ea3, 0x0ea9, 0x0eb4, 0x0ebe, 0x0ec6, 0x0eca, + 0x0ecf, 0x0ed9, 0x0edd, 0x0ee4, 0x0eec, 0x0ef3, 0x0ef8, 0x0f04, + 0x0f0a, 0x0f15, 0x0f1b, 0x0f22, 0x0f28, 0x0f33, 0x0f3d, 0x0f45, + 0x0f4c, 0x0f51, 0x0f57, 0x0f5e, 0x0f63, 0x0f69, 0x0f70, 0x0f76, + 0x0f7d, 0x0f82, 0x0f89, 0x0f8d, 0x0f9e, 0x0fa4, 0x0fa9, 0x0fad, + 0x0fb8, 0x0fbe, 0x0fc9, 0x0fd0, 0x0fd6, 0x0fda, 0x0fe1, 0x0fe5, + 0x0fef, 0x0ffa, 0x1000, 0x1004, 0x1009, 0x100f, 0x1013, 0x101a, + 0x101f, 0x1023, 0x1029, 0x102f, 0x1032, 0x1036, 0x1039, 0x103f, + 0x1045, 0x1059, 0x1061, 0x1079, 0x107c, 0x1080, 0x1095, 0x10a1, + 0x10b1, 0x10c3, 0x10cb, 0x10cf, 0x10da, 0x10de, 0x10ea, 0x10f2, + 0x10f4, 0x1100, 0x1105, 0x1111, 0x1141, 0x1149, 0x114d, 0x1153, + 0x1157, 0x115a, 0x116e, 0x1171, 0x1175, 0x117b, 0x117d, 0x1181, + 0x1184, 0x118c, 0x1192, 0x1196, 0x119c, 0x11a2, 0x11a8, 0x11ab, + 0xa76f, 0x11af, 0x11b3, 0x11b7, 0x028d, 0x11bf, 0x1211, 0x130f, + 0x140d, 0x1491, 0x1496, 0x1554, 0x156d, 0x1573, 0x1579, 0x157f, + 0x158b, 0x1597, 0x002b, 0x15a2, 0x15ba, 0x15be, 0x15c2, 0x15c6, + 0x15ca, 0x15ce, 0x15e2, 0x15e6, 0x164a, 0x1663, 0x1689, 0x168f, + 0x174d, 0x1753, 0x1758, 0x1778, 0x1878, 0x187e, 0x1912, 0x19d4, + 0x1a78, 0x1a80, 0x1a9e, 0x1aa3, 0x1ab7, 0x1ac1, 0x1ac7, 0x1adb, + 0x1ae0, 0x1ae6, 0x1af4, 0x1b24, 0x1b31, 0x1b39, 0x1b3d, 0x1b53, + 0x1bca, 0x1bdc, 0x1bde, 0x1be0, 0x3164, 0x1c21, 0x1c23, 0x1c25, + 0x1c27, 0x1c29, 0x1c2b, 0x1c49, 0x1c4e, 0x1c53, 0x1c89, 0x1ccf, + 0x1cdd, 0x1ce2, 0x1ceb, 0x1cf4, 0x1d02, 0x1d07, 0x1d0c, 0x1d1e, + 0x1d30, 0x1d39, 0x1d3e, 0x1d62, 0x1d70, 0x1d72, 0x1d74, 0x1d94, + 0x1daf, 0x1db1, 0x1db3, 0x1db5, 0x1db7, 0x1db9, 0x1dbb, 0x1dbd, + 0x1ddd, 0x1ddf, 0x1de1, 0x1de3, 0x1de5, 0x1dec, 0x1dee, 0x1df0, + 0x1df2, 0x1e01, 0x1e03, 0x1e05, 0x1e07, 0x1e09, 0x1e0b, 0x1e0d, + 0x1e0f, 0x1e11, 0x1e13, 0x1e15, 0x1e17, 0x1e19, 0x1e1b, 0x1e1d, + 0x1e21, 0x03f4, 0x1e23, 0x2207, 0x1e25, 0x2202, 0x1e27, 0x1e2f, + 0x03f4, 0x1e31, 0x2207, 0x1e33, 0x2202, 0x1e35, 0x1e3d, 0x03f4, + 0x1e3f, 0x2207, 0x1e41, 0x2202, 0x1e43, 0x1e4b, 0x03f4, 0x1e4d, + 0x2207, 0x1e4f, 0x2202, 0x1e51, 0x1e59, 0x03f4, 0x1e5b, 0x2207, + 0x1e5d, 0x2202, 0x1e5f, 0x1e69, 0x1e6b, 0x1e6d, 0x1e6f, 0x1e71, + 0x1e73, 0x1e75, 0x1e77, 0x1e79, 0x1e81, 0x1ea4, 0x1ea8, 0x1eae, + 0x1ecb, 0x062d, 0x1ed3, 0x1edf, 0x062c, 0x1eef, 0x1f5f, 0x1f6b, + 0x1f7e, 0x1f90, 0x1fa3, 0x1fa5, 0x1fa9, 0x1faf, 0x1fb5, 0x1fb7, + 0x1fbb, 0x1fbd, 0x1fc5, 0x1fc8, 0x1fca, 0x1fd0, 0x1fd2, 0x30b5, + 0x1fd8, 0x2030, 0x2046, 0x204a, 0x204c, 0x2051, 0x209e, 0x20af, + 0x21b0, 0x21c0, 0x21c6, 0x22c0, 0x23de, +}; + +static const uint8_t unicode_decomp_data[9452] = { + 0x20, 0x88, 0x20, 0x84, 0x32, 0x33, 0x20, 0x81, + 0x20, 0xa7, 0x31, 0x6f, 0x31, 0xd0, 0x34, 0x31, + 0xd0, 0x32, 0x33, 0xd0, 0x34, 0x41, 0x80, 0x41, + 0x81, 0x41, 0x82, 0x41, 0x83, 0x41, 0x88, 0x41, + 0x8a, 0x00, 0x00, 0x43, 0xa7, 0x45, 0x80, 0x45, + 0x81, 0x45, 0x82, 0x45, 0x88, 0x49, 0x80, 0x49, + 0x81, 0x49, 0x82, 0x49, 0x88, 0x00, 0x00, 0x4e, + 0x83, 0x4f, 0x80, 0x4f, 0x81, 0x4f, 0x82, 0x4f, + 0x83, 0x4f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x55, + 0x80, 0x55, 0x81, 0x55, 0x82, 0x55, 0x88, 0x59, + 0x81, 0x00, 0x00, 0x00, 0x00, 0x61, 0x80, 0x61, + 0x81, 0x61, 0x82, 0x61, 0x83, 0x61, 0x88, 0x61, + 0x8a, 0x00, 0x00, 0x63, 0xa7, 0x65, 0x80, 0x65, + 0x81, 0x65, 0x82, 0x65, 0x88, 0x69, 0x80, 0x69, + 0x81, 0x69, 0x82, 0x69, 0x88, 0x00, 0x00, 0x6e, + 0x83, 0x6f, 0x80, 0x6f, 0x81, 0x6f, 0x82, 0x6f, + 0x83, 0x6f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x75, + 0x80, 0x75, 0x81, 0x75, 0x82, 0x75, 0x88, 0x79, + 0x81, 0x00, 0x00, 0x79, 0x88, 0x41, 0x84, 0x41, + 0x86, 0x41, 0xa8, 0x43, 0x81, 0x43, 0x82, 0x43, + 0x87, 0x43, 0x8c, 0x44, 0x8c, 0x45, 0x84, 0x45, + 0x86, 0x45, 0x87, 0x45, 0xa8, 0x45, 0x8c, 0x47, + 0x82, 0x47, 0x86, 0x47, 0x87, 0x47, 0xa7, 0x48, + 0x82, 0x49, 0x83, 0x49, 0x84, 0x49, 0x86, 0x49, + 0xa8, 0x49, 0x87, 0x49, 0x4a, 0x69, 0x6a, 0x4a, + 0x82, 0x4b, 0xa7, 0x4c, 0x81, 0x4c, 0xa7, 0x4c, + 0x8c, 0x4c, 0x00, 0x00, 0x6b, 0x20, 0x6b, 0x4e, + 0x81, 0x4e, 0xa7, 0x4e, 0x8c, 0xbc, 0x02, 0x6e, + 0x4f, 0x84, 0x4f, 0x86, 0x4f, 0x8b, 0x52, 0x81, + 0x52, 0xa7, 0x52, 0x8c, 0x53, 0x81, 0x53, 0x82, + 0x53, 0xa7, 0x53, 0x8c, 0x54, 0xa7, 0x54, 0x8c, + 0x55, 0x83, 0x55, 0x84, 0x55, 0x86, 0x55, 0x8a, + 0x55, 0x8b, 0x55, 0xa8, 0x57, 0x82, 0x59, 0x82, + 0x59, 0x88, 0x5a, 0x81, 0x5a, 0x87, 0x5a, 0x8c, + 0x4f, 0x9b, 0x55, 0x9b, 0x44, 0x00, 0x7d, 0x01, + 0x44, 0x00, 0x7e, 0x01, 0x64, 0x00, 0x7e, 0x01, + 0x4c, 0x4a, 0x4c, 0x6a, 0x6c, 0x6a, 0x4e, 0x4a, + 0x4e, 0x6a, 0x6e, 0x6a, 0x41, 0x00, 0x8c, 0x49, + 0x00, 0x8c, 0x4f, 0x00, 0x8c, 0x55, 0x00, 0x8c, + 0xdc, 0x00, 0x84, 0xdc, 0x00, 0x81, 0xdc, 0x00, + 0x8c, 0xdc, 0x00, 0x80, 0xc4, 0x00, 0x84, 0x26, + 0x02, 0x84, 0xc6, 0x00, 0x84, 0x47, 0x8c, 0x4b, + 0x8c, 0x4f, 0xa8, 0xea, 0x01, 0x84, 0xeb, 0x01, + 0x84, 0xb7, 0x01, 0x8c, 0x92, 0x02, 0x8c, 0x6a, + 0x00, 0x8c, 0x44, 0x5a, 0x44, 0x7a, 0x64, 0x7a, + 0x47, 0x81, 0x4e, 0x00, 0x80, 0xc5, 0x00, 0x81, + 0xc6, 0x00, 0x81, 0xd8, 0x00, 0x81, 0x41, 0x8f, + 0x41, 0x91, 0x45, 0x8f, 0x45, 0x91, 0x49, 0x8f, + 0x49, 0x91, 0x4f, 0x8f, 0x4f, 0x91, 0x52, 0x8f, + 0x52, 0x91, 0x55, 0x8f, 0x55, 0x91, 0x53, 0xa6, + 0x54, 0xa6, 0x48, 0x8c, 0x41, 0x00, 0x87, 0x45, + 0x00, 0xa7, 0xd6, 0x00, 0x84, 0xd5, 0x00, 0x84, + 0x4f, 0x00, 0x87, 0x2e, 0x02, 0x84, 0x59, 0x00, + 0x84, 0x68, 0x00, 0x66, 0x02, 0x6a, 0x00, 0x72, + 0x00, 0x79, 0x02, 0x7b, 0x02, 0x81, 0x02, 0x77, + 0x00, 0x79, 0x00, 0x20, 0x86, 0x20, 0x87, 0x20, + 0x8a, 0x20, 0xa8, 0x20, 0x83, 0x20, 0x8b, 0x63, + 0x02, 0x6c, 0x00, 0x73, 0x00, 0x78, 0x00, 0x95, + 0x02, 0x80, 0x81, 0x00, 0x93, 0x88, 0x81, 0x20, + 0xc5, 0x20, 0x81, 0xa8, 0x00, 0x81, 0x91, 0x03, + 0x81, 0x95, 0x03, 0x81, 0x97, 0x03, 0x81, 0x99, + 0x03, 0x81, 0x00, 0x00, 0x00, 0x9f, 0x03, 0x81, + 0x00, 0x00, 0x00, 0xa5, 0x03, 0x81, 0xa9, 0x03, + 0x81, 0xca, 0x03, 0x81, 0x01, 0x03, 0x98, 0x07, + 0xa4, 0x07, 0xb0, 0x00, 0xb4, 0x00, 0xb6, 0x00, + 0xb8, 0x00, 0xca, 0x00, 0x01, 0x03, 0xb8, 0x07, + 0xc4, 0x07, 0xbe, 0x00, 0xc4, 0x00, 0xc8, 0x00, + 0xa5, 0x03, 0x0d, 0x13, 0x00, 0x01, 0x03, 0xd1, + 0x00, 0xd1, 0x07, 0xc6, 0x03, 0xc0, 0x03, 0xba, + 0x03, 0xc1, 0x03, 0xc2, 0x03, 0x00, 0x00, 0x98, + 0x03, 0xb5, 0x03, 0x15, 0x04, 0x80, 0x15, 0x04, + 0x88, 0x00, 0x00, 0x00, 0x13, 0x04, 0x81, 0x06, + 0x04, 0x88, 0x1a, 0x04, 0x81, 0x18, 0x04, 0x80, + 0x23, 0x04, 0x86, 0x18, 0x04, 0x86, 0x38, 0x04, + 0x86, 0x35, 0x04, 0x80, 0x35, 0x04, 0x88, 0x00, + 0x00, 0x00, 0x33, 0x04, 0x81, 0x56, 0x04, 0x88, + 0x3a, 0x04, 0x81, 0x38, 0x04, 0x80, 0x43, 0x04, + 0x86, 0x74, 0x04, 0x8f, 0x16, 0x04, 0x86, 0x10, + 0x04, 0x86, 0x10, 0x04, 0x88, 0x15, 0x04, 0x86, + 0xd8, 0x04, 0x88, 0x16, 0x04, 0x88, 0x17, 0x04, + 0x88, 0x18, 0x04, 0x84, 0x18, 0x04, 0x88, 0x1e, + 0x04, 0x88, 0xe8, 0x04, 0x88, 0x2d, 0x04, 0x88, + 0x23, 0x04, 0x84, 0x23, 0x04, 0x88, 0x23, 0x04, + 0x8b, 0x27, 0x04, 0x88, 0x2b, 0x04, 0x88, 0x65, + 0x05, 0x82, 0x05, 0x27, 0x06, 0x00, 0x2c, 0x00, + 0x2d, 0x21, 0x2d, 0x00, 0x2e, 0x23, 0x2d, 0x27, + 0x06, 0x00, 0x4d, 0x21, 0x4d, 0xa0, 0x4d, 0x23, + 0x4d, 0xd5, 0x06, 0x54, 0x06, 0x00, 0x00, 0x00, + 0x00, 0xc1, 0x06, 0x54, 0x06, 0xd2, 0x06, 0x54, + 0x06, 0x28, 0x09, 0x3c, 0x09, 0x30, 0x09, 0x3c, + 0x09, 0x33, 0x09, 0x3c, 0x09, 0x15, 0x09, 0x00, + 0x27, 0x01, 0x27, 0x02, 0x27, 0x07, 0x27, 0x0c, + 0x27, 0x0d, 0x27, 0x16, 0x27, 0x1a, 0x27, 0xbe, + 0x09, 0x09, 0x00, 0x09, 0x19, 0xa1, 0x09, 0xbc, + 0x09, 0xaf, 0x09, 0xbc, 0x09, 0x32, 0x0a, 0x3c, + 0x0a, 0x38, 0x0a, 0x3c, 0x0a, 0x16, 0x0a, 0x00, + 0x26, 0x01, 0x26, 0x06, 0x26, 0x2b, 0x0a, 0x3c, + 0x0a, 0x47, 0x0b, 0x56, 0x0b, 0x3e, 0x0b, 0x09, + 0x00, 0x09, 0x19, 0x21, 0x0b, 0x3c, 0x0b, 0x92, + 0x0b, 0xd7, 0x0b, 0xbe, 0x0b, 0x08, 0x00, 0x09, + 0x00, 0x08, 0x19, 0x46, 0x0c, 0x56, 0x0c, 0xbf, + 0x0c, 0xd5, 0x0c, 0xc6, 0x0c, 0xd5, 0x0c, 0xc2, + 0x0c, 0x04, 0x00, 0x08, 0x13, 0x3e, 0x0d, 0x08, + 0x00, 0x09, 0x00, 0x08, 0x19, 0xd9, 0x0d, 0xca, + 0x0d, 0xca, 0x0d, 0x0f, 0x05, 0x12, 0x00, 0x0f, + 0x15, 0x4d, 0x0e, 0x32, 0x0e, 0xcd, 0x0e, 0xb2, + 0x0e, 0x99, 0x0e, 0x12, 0x00, 0x12, 0x08, 0x42, + 0x0f, 0xb7, 0x0f, 0x4c, 0x0f, 0xb7, 0x0f, 0x51, + 0x0f, 0xb7, 0x0f, 0x56, 0x0f, 0xb7, 0x0f, 0x5b, + 0x0f, 0xb7, 0x0f, 0x40, 0x0f, 0xb5, 0x0f, 0x71, + 0x0f, 0x72, 0x0f, 0x71, 0x0f, 0x00, 0x03, 0x41, + 0x0f, 0xb2, 0x0f, 0x81, 0x0f, 0xb3, 0x0f, 0x80, + 0x0f, 0xb3, 0x0f, 0x81, 0x0f, 0x71, 0x0f, 0x80, + 0x0f, 0x92, 0x0f, 0xb7, 0x0f, 0x9c, 0x0f, 0xb7, + 0x0f, 0xa1, 0x0f, 0xb7, 0x0f, 0xa6, 0x0f, 0xb7, + 0x0f, 0xab, 0x0f, 0xb7, 0x0f, 0x90, 0x0f, 0xb5, + 0x0f, 0x25, 0x10, 0x2e, 0x10, 0x05, 0x1b, 0x35, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1b, 0x35, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x09, 0x1b, 0x35, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x1b, 0x35, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x1b, 0x35, + 0x1b, 0x11, 0x1b, 0x35, 0x1b, 0x3a, 0x1b, 0x35, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x1b, 0x35, + 0x1b, 0x3e, 0x1b, 0x35, 0x1b, 0x42, 0x1b, 0x35, + 0x1b, 0x41, 0x00, 0xc6, 0x00, 0x42, 0x00, 0x00, + 0x00, 0x44, 0x00, 0x45, 0x00, 0x8e, 0x01, 0x47, + 0x00, 0x4f, 0x00, 0x22, 0x02, 0x50, 0x00, 0x52, + 0x00, 0x54, 0x00, 0x55, 0x00, 0x57, 0x00, 0x61, + 0x00, 0x50, 0x02, 0x51, 0x02, 0x02, 0x1d, 0x62, + 0x00, 0x64, 0x00, 0x65, 0x00, 0x59, 0x02, 0x5b, + 0x02, 0x5c, 0x02, 0x67, 0x00, 0x00, 0x00, 0x6b, + 0x00, 0x6d, 0x00, 0x4b, 0x01, 0x6f, 0x00, 0x54, + 0x02, 0x16, 0x1d, 0x17, 0x1d, 0x70, 0x00, 0x74, + 0x00, 0x75, 0x00, 0x1d, 0x1d, 0x6f, 0x02, 0x76, + 0x00, 0x25, 0x1d, 0xb2, 0x03, 0xb3, 0x03, 0xb4, + 0x03, 0xc6, 0x03, 0xc7, 0x03, 0x69, 0x00, 0x72, + 0x00, 0x75, 0x00, 0x76, 0x00, 0xb2, 0x03, 0xb3, + 0x03, 0xc1, 0x03, 0xc6, 0x03, 0xc7, 0x03, 0x52, + 0x02, 0x63, 0x00, 0x55, 0x02, 0xf0, 0x00, 0x5c, + 0x02, 0x66, 0x00, 0x5f, 0x02, 0x61, 0x02, 0x65, + 0x02, 0x68, 0x02, 0x69, 0x02, 0x6a, 0x02, 0x7b, + 0x1d, 0x9d, 0x02, 0x6d, 0x02, 0x85, 0x1d, 0x9f, + 0x02, 0x71, 0x02, 0x70, 0x02, 0x72, 0x02, 0x73, + 0x02, 0x74, 0x02, 0x75, 0x02, 0x78, 0x02, 0x82, + 0x02, 0x83, 0x02, 0xab, 0x01, 0x89, 0x02, 0x8a, + 0x02, 0x1c, 0x1d, 0x8b, 0x02, 0x8c, 0x02, 0x7a, + 0x00, 0x90, 0x02, 0x91, 0x02, 0x92, 0x02, 0xb8, + 0x03, 0x41, 0x00, 0xa5, 0x42, 0x00, 0x87, 0x42, + 0x00, 0xa3, 0x42, 0x00, 0xb1, 0xc7, 0x00, 0x81, + 0x44, 0x00, 0x87, 0x44, 0x00, 0xa3, 0x44, 0x00, + 0xb1, 0x44, 0x00, 0xa7, 0x44, 0x00, 0xad, 0x12, + 0x01, 0x80, 0x12, 0x01, 0x81, 0x45, 0x00, 0xad, + 0x45, 0x00, 0xb0, 0x28, 0x02, 0x86, 0x46, 0x00, + 0x87, 0x47, 0x00, 0x84, 0x48, 0x00, 0x87, 0x48, + 0x00, 0xa3, 0x48, 0x00, 0x88, 0x48, 0x00, 0xa7, + 0x48, 0x00, 0xae, 0x49, 0x00, 0xb0, 0xcf, 0x00, + 0x81, 0x4b, 0x00, 0x81, 0x4b, 0x00, 0xa3, 0x4b, + 0x00, 0xb1, 0x4c, 0x00, 0xa3, 0x36, 0x1e, 0x84, + 0x4c, 0xb1, 0x4c, 0xad, 0x4d, 0x81, 0x4d, 0x87, + 0x4d, 0xa3, 0x4e, 0x87, 0x4e, 0xa3, 0x4e, 0xb1, + 0x4e, 0xad, 0xd5, 0x00, 0x81, 0xd5, 0x00, 0x88, + 0x4c, 0x01, 0x80, 0x4c, 0x01, 0x81, 0x50, 0x00, + 0x81, 0x50, 0x00, 0x87, 0x52, 0x00, 0x87, 0x52, + 0x00, 0xa3, 0x5a, 0x1e, 0x84, 0x52, 0x00, 0xb1, + 0x53, 0x00, 0x87, 0x53, 0x00, 0xa3, 0x5a, 0x01, + 0x87, 0x60, 0x01, 0x87, 0x62, 0x1e, 0x87, 0x54, + 0x00, 0x87, 0x54, 0x00, 0xa3, 0x54, 0x00, 0xb1, + 0x54, 0x00, 0xad, 0x55, 0x00, 0xa4, 0x55, 0x00, + 0xb0, 0x55, 0x00, 0xad, 0x68, 0x01, 0x81, 0x6a, + 0x01, 0x88, 0x56, 0x83, 0x56, 0xa3, 0x57, 0x80, + 0x57, 0x81, 0x57, 0x88, 0x57, 0x87, 0x57, 0xa3, + 0x58, 0x87, 0x58, 0x88, 0x59, 0x87, 0x5a, 0x82, + 0x5a, 0xa3, 0x5a, 0xb1, 0x68, 0xb1, 0x74, 0x88, + 0x77, 0x8a, 0x79, 0x8a, 0x61, 0x00, 0xbe, 0x02, + 0x7f, 0x01, 0x87, 0x41, 0x00, 0xa3, 0x41, 0x00, + 0x89, 0xc2, 0x00, 0x81, 0xc2, 0x00, 0x80, 0xc2, + 0x00, 0x89, 0xc2, 0x00, 0x83, 0xa0, 0x1e, 0x82, + 0x02, 0x01, 0x81, 0x02, 0x01, 0x80, 0x02, 0x01, + 0x89, 0x02, 0x01, 0x83, 0xa0, 0x1e, 0x86, 0x45, + 0x00, 0xa3, 0x45, 0x00, 0x89, 0x45, 0x00, 0x83, + 0xca, 0x00, 0x81, 0xca, 0x00, 0x80, 0xca, 0x00, + 0x89, 0xca, 0x00, 0x83, 0xb8, 0x1e, 0x82, 0x49, + 0x00, 0x89, 0x49, 0x00, 0xa3, 0x4f, 0x00, 0xa3, + 0x4f, 0x00, 0x89, 0xd4, 0x00, 0x81, 0xd4, 0x00, + 0x80, 0xd4, 0x00, 0x89, 0xd4, 0x00, 0x83, 0xcc, + 0x1e, 0x82, 0xa0, 0x01, 0x81, 0xa0, 0x01, 0x80, + 0xa0, 0x01, 0x89, 0xa0, 0x01, 0x83, 0xa0, 0x01, + 0xa3, 0x55, 0x00, 0xa3, 0x55, 0x00, 0x89, 0xaf, + 0x01, 0x81, 0xaf, 0x01, 0x80, 0xaf, 0x01, 0x89, + 0xaf, 0x01, 0x83, 0xaf, 0x01, 0xa3, 0x59, 0x00, + 0x80, 0x59, 0x00, 0xa3, 0x59, 0x00, 0x89, 0x59, + 0x00, 0x83, 0xb1, 0x03, 0x13, 0x03, 0x00, 0x1f, + 0x80, 0x00, 0x1f, 0x81, 0x00, 0x1f, 0xc2, 0x91, + 0x03, 0x13, 0x03, 0x08, 0x1f, 0x80, 0x08, 0x1f, + 0x81, 0x08, 0x1f, 0xc2, 0xb5, 0x03, 0x13, 0x03, + 0x10, 0x1f, 0x80, 0x10, 0x1f, 0x81, 0x95, 0x03, + 0x13, 0x03, 0x18, 0x1f, 0x80, 0x18, 0x1f, 0x81, + 0xb7, 0x03, 0x93, 0xb7, 0x03, 0x94, 0x20, 0x1f, + 0x80, 0x21, 0x1f, 0x80, 0x20, 0x1f, 0x81, 0x21, + 0x1f, 0x81, 0x20, 0x1f, 0xc2, 0x21, 0x1f, 0xc2, + 0x97, 0x03, 0x93, 0x97, 0x03, 0x94, 0x28, 0x1f, + 0x80, 0x29, 0x1f, 0x80, 0x28, 0x1f, 0x81, 0x29, + 0x1f, 0x81, 0x28, 0x1f, 0xc2, 0x29, 0x1f, 0xc2, + 0xb9, 0x03, 0x93, 0xb9, 0x03, 0x94, 0x30, 0x1f, + 0x80, 0x31, 0x1f, 0x80, 0x30, 0x1f, 0x81, 0x31, + 0x1f, 0x81, 0x30, 0x1f, 0xc2, 0x31, 0x1f, 0xc2, + 0x99, 0x03, 0x93, 0x99, 0x03, 0x94, 0x38, 0x1f, + 0x80, 0x39, 0x1f, 0x80, 0x38, 0x1f, 0x81, 0x39, + 0x1f, 0x81, 0x38, 0x1f, 0xc2, 0x39, 0x1f, 0xc2, + 0xbf, 0x03, 0x93, 0xbf, 0x03, 0x94, 0x40, 0x1f, + 0x80, 0x40, 0x1f, 0x81, 0x9f, 0x03, 0x13, 0x03, + 0x48, 0x1f, 0x80, 0x48, 0x1f, 0x81, 0xc5, 0x03, + 0x13, 0x03, 0x50, 0x1f, 0x80, 0x50, 0x1f, 0x81, + 0x50, 0x1f, 0xc2, 0xa5, 0x03, 0x94, 0x00, 0x00, + 0x00, 0x59, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x59, + 0x1f, 0x81, 0x00, 0x00, 0x00, 0x59, 0x1f, 0xc2, + 0xc9, 0x03, 0x93, 0xc9, 0x03, 0x94, 0x60, 0x1f, + 0x80, 0x61, 0x1f, 0x80, 0x60, 0x1f, 0x81, 0x61, + 0x1f, 0x81, 0x60, 0x1f, 0xc2, 0x61, 0x1f, 0xc2, + 0xa9, 0x03, 0x93, 0xa9, 0x03, 0x94, 0x68, 0x1f, + 0x80, 0x69, 0x1f, 0x80, 0x68, 0x1f, 0x81, 0x69, + 0x1f, 0x81, 0x68, 0x1f, 0xc2, 0x69, 0x1f, 0xc2, + 0xb1, 0x03, 0x80, 0xb5, 0x03, 0x80, 0xb7, 0x03, + 0x80, 0xb9, 0x03, 0x80, 0xbf, 0x03, 0x80, 0xc5, + 0x03, 0x80, 0xc9, 0x03, 0x80, 0x00, 0x1f, 0x45, + 0x03, 0x20, 0x1f, 0x45, 0x03, 0x60, 0x1f, 0x45, + 0x03, 0xb1, 0x03, 0x86, 0xb1, 0x03, 0x84, 0x70, + 0x1f, 0xc5, 0xb1, 0x03, 0xc5, 0xac, 0x03, 0xc5, + 0x00, 0x00, 0x00, 0xb1, 0x03, 0xc2, 0xb6, 0x1f, + 0xc5, 0x91, 0x03, 0x86, 0x91, 0x03, 0x84, 0x91, + 0x03, 0x80, 0x91, 0x03, 0xc5, 0x20, 0x93, 0x20, + 0x93, 0x20, 0xc2, 0xa8, 0x00, 0xc2, 0x74, 0x1f, + 0xc5, 0xb7, 0x03, 0xc5, 0xae, 0x03, 0xc5, 0x00, + 0x00, 0x00, 0xb7, 0x03, 0xc2, 0xc6, 0x1f, 0xc5, + 0x95, 0x03, 0x80, 0x97, 0x03, 0x80, 0x97, 0x03, + 0xc5, 0xbf, 0x1f, 0x80, 0xbf, 0x1f, 0x81, 0xbf, + 0x1f, 0xc2, 0xb9, 0x03, 0x86, 0xb9, 0x03, 0x84, + 0xca, 0x03, 0x80, 0x00, 0x03, 0xb9, 0x42, 0xca, + 0x42, 0x99, 0x06, 0x99, 0x04, 0x99, 0x00, 0xfe, + 0x1f, 0x80, 0xfe, 0x1f, 0x81, 0xfe, 0x1f, 0xc2, + 0xc5, 0x03, 0x86, 0xc5, 0x03, 0x84, 0xcb, 0x03, + 0x80, 0x00, 0x03, 0xc1, 0x13, 0xc1, 0x14, 0xc5, + 0x42, 0xcb, 0x42, 0xa5, 0x06, 0xa5, 0x04, 0xa5, + 0x00, 0xa1, 0x03, 0x94, 0xa8, 0x00, 0x80, 0x85, + 0x03, 0x60, 0x00, 0x7c, 0x1f, 0xc5, 0xc9, 0x03, + 0xc5, 0xce, 0x03, 0xc5, 0x00, 0x00, 0x00, 0xc9, + 0x03, 0xc2, 0xf6, 0x1f, 0xc5, 0x9f, 0x03, 0x80, + 0xa9, 0x03, 0x80, 0xa9, 0x03, 0xc5, 0x20, 0x94, + 0x02, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0xb3, 0x2e, 0x2e, 0x2e, + 0x2e, 0x2e, 0x32, 0x20, 0x32, 0x20, 0x32, 0x20, + 0x00, 0x00, 0x00, 0x35, 0x20, 0x35, 0x20, 0x35, + 0x20, 0x00, 0x00, 0x00, 0x21, 0x21, 0x00, 0x00, + 0x20, 0x85, 0x3f, 0x3f, 0x3f, 0x21, 0x21, 0x3f, + 0x32, 0x20, 0x00, 0x00, 0x00, 0x00, 0x30, 0x69, + 0x00, 0x00, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x2b, 0x3d, 0x28, 0x29, 0x6e, 0x30, 0x00, 0x2b, + 0x00, 0x12, 0x22, 0x3d, 0x00, 0x28, 0x00, 0x29, + 0x00, 0x00, 0x00, 0x61, 0x00, 0x65, 0x00, 0x6f, + 0x00, 0x78, 0x00, 0x59, 0x02, 0x68, 0x6b, 0x6c, + 0x6d, 0x6e, 0x70, 0x73, 0x74, 0x52, 0x73, 0x61, + 0x2f, 0x63, 0x61, 0x2f, 0x73, 0xb0, 0x00, 0x43, + 0x63, 0x2f, 0x6f, 0x63, 0x2f, 0x75, 0xb0, 0x00, + 0x46, 0x48, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x20, + 0xdf, 0x01, 0x01, 0x04, 0x24, 0x4e, 0x6f, 0x50, + 0x51, 0x52, 0x52, 0x52, 0x53, 0x4d, 0x54, 0x45, + 0x4c, 0x54, 0x4d, 0x4b, 0x00, 0xc5, 0x00, 0x42, + 0x43, 0x00, 0x65, 0x45, 0x46, 0x00, 0x4d, 0x6f, + 0xd0, 0x05, 0x46, 0x41, 0x58, 0xc0, 0x03, 0xb3, + 0x03, 0x93, 0x03, 0xa0, 0x03, 0x11, 0x22, 0x44, + 0x64, 0x65, 0x69, 0x6a, 0x31, 0xd0, 0x37, 0x31, + 0xd0, 0x39, 0x31, 0xd0, 0x31, 0x30, 0x31, 0xd0, + 0x33, 0x32, 0xd0, 0x33, 0x31, 0xd0, 0x35, 0x32, + 0xd0, 0x35, 0x33, 0xd0, 0x35, 0x34, 0xd0, 0x35, + 0x31, 0xd0, 0x36, 0x35, 0xd0, 0x36, 0x31, 0xd0, + 0x38, 0x33, 0xd0, 0x38, 0x35, 0xd0, 0x38, 0x37, + 0xd0, 0x38, 0x31, 0xd0, 0x49, 0x49, 0x49, 0x49, + 0x49, 0x49, 0x56, 0x56, 0x49, 0x56, 0x49, 0x49, + 0x56, 0x49, 0x49, 0x49, 0x49, 0x58, 0x58, 0x49, + 0x58, 0x49, 0x49, 0x4c, 0x43, 0x44, 0x4d, 0x69, + 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x76, 0x76, + 0x69, 0x76, 0x69, 0x69, 0x76, 0x69, 0x69, 0x69, + 0x69, 0x78, 0x78, 0x69, 0x78, 0x69, 0x69, 0x6c, + 0x63, 0x64, 0x6d, 0x30, 0xd0, 0x33, 0x90, 0x21, + 0xb8, 0x92, 0x21, 0xb8, 0x94, 0x21, 0xb8, 0xd0, + 0x21, 0xb8, 0xd4, 0x21, 0xb8, 0xd2, 0x21, 0xb8, + 0x03, 0x22, 0xb8, 0x08, 0x22, 0xb8, 0x0b, 0x22, + 0xb8, 0x23, 0x22, 0xb8, 0x00, 0x00, 0x00, 0x25, + 0x22, 0xb8, 0x2b, 0x22, 0x2b, 0x22, 0x2b, 0x22, + 0x00, 0x00, 0x00, 0x2e, 0x22, 0x2e, 0x22, 0x2e, + 0x22, 0x00, 0x00, 0x00, 0x3c, 0x22, 0xb8, 0x43, + 0x22, 0xb8, 0x45, 0x22, 0xb8, 0x00, 0x00, 0x00, + 0x48, 0x22, 0xb8, 0x3d, 0x00, 0xb8, 0x00, 0x00, + 0x00, 0x61, 0x22, 0xb8, 0x4d, 0x22, 0xb8, 0x3c, + 0x00, 0xb8, 0x3e, 0x00, 0xb8, 0x64, 0x22, 0xb8, + 0x65, 0x22, 0xb8, 0x72, 0x22, 0xb8, 0x76, 0x22, + 0xb8, 0x7a, 0x22, 0xb8, 0x82, 0x22, 0xb8, 0x86, + 0x22, 0xb8, 0xa2, 0x22, 0xb8, 0xa8, 0x22, 0xb8, + 0xa9, 0x22, 0xb8, 0xab, 0x22, 0xb8, 0x7c, 0x22, + 0xb8, 0x91, 0x22, 0xb8, 0xb2, 0x22, 0x38, 0x03, + 0x08, 0x30, 0x31, 0x00, 0x31, 0x00, 0x30, 0x00, + 0x32, 0x30, 0x28, 0x00, 0x31, 0x00, 0x29, 0x00, + 0x28, 0x00, 0x31, 0x00, 0x30, 0x00, 0x29, 0x00, + 0x28, 0x32, 0x30, 0x29, 0x31, 0x00, 0x2e, 0x00, + 0x31, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x32, 0x30, + 0x2e, 0x28, 0x00, 0x61, 0x00, 0x29, 0x00, 0x41, + 0x00, 0x61, 0x00, 0x2b, 0x22, 0x00, 0x00, 0x00, + 0x00, 0x3a, 0x3a, 0x3d, 0x3d, 0x3d, 0x3d, 0x3d, + 0x3d, 0xdd, 0x2a, 0xb8, 0x6a, 0x56, 0x00, 0x4e, + 0x00, 0x28, 0x36, 0x3f, 0x59, 0x85, 0x8c, 0xa0, + 0xba, 0x3f, 0x51, 0x00, 0x26, 0x2c, 0x43, 0x57, + 0x6c, 0xa1, 0xb6, 0xc1, 0x9b, 0x52, 0x00, 0x5e, + 0x7a, 0x7f, 0x9d, 0xa6, 0xc1, 0xce, 0xe7, 0xb6, + 0x53, 0xc8, 0x53, 0xe3, 0x53, 0xd7, 0x56, 0x1f, + 0x57, 0xeb, 0x58, 0x02, 0x59, 0x0a, 0x59, 0x15, + 0x59, 0x27, 0x59, 0x73, 0x59, 0x50, 0x5b, 0x80, + 0x5b, 0xf8, 0x5b, 0x0f, 0x5c, 0x22, 0x5c, 0x38, + 0x5c, 0x6e, 0x5c, 0x71, 0x5c, 0xdb, 0x5d, 0xe5, + 0x5d, 0xf1, 0x5d, 0xfe, 0x5d, 0x72, 0x5e, 0x7a, + 0x5e, 0x7f, 0x5e, 0xf4, 0x5e, 0xfe, 0x5e, 0x0b, + 0x5f, 0x13, 0x5f, 0x50, 0x5f, 0x61, 0x5f, 0x73, + 0x5f, 0xc3, 0x5f, 0x08, 0x62, 0x36, 0x62, 0x4b, + 0x62, 0x2f, 0x65, 0x34, 0x65, 0x87, 0x65, 0x97, + 0x65, 0xa4, 0x65, 0xb9, 0x65, 0xe0, 0x65, 0xe5, + 0x65, 0xf0, 0x66, 0x08, 0x67, 0x28, 0x67, 0x20, + 0x6b, 0x62, 0x6b, 0x79, 0x6b, 0xb3, 0x6b, 0xcb, + 0x6b, 0xd4, 0x6b, 0xdb, 0x6b, 0x0f, 0x6c, 0x14, + 0x6c, 0x34, 0x6c, 0x6b, 0x70, 0x2a, 0x72, 0x36, + 0x72, 0x3b, 0x72, 0x3f, 0x72, 0x47, 0x72, 0x59, + 0x72, 0x5b, 0x72, 0xac, 0x72, 0x84, 0x73, 0x89, + 0x73, 0xdc, 0x74, 0xe6, 0x74, 0x18, 0x75, 0x1f, + 0x75, 0x28, 0x75, 0x30, 0x75, 0x8b, 0x75, 0x92, + 0x75, 0x76, 0x76, 0x7d, 0x76, 0xae, 0x76, 0xbf, + 0x76, 0xee, 0x76, 0xdb, 0x77, 0xe2, 0x77, 0xf3, + 0x77, 0x3a, 0x79, 0xb8, 0x79, 0xbe, 0x79, 0x74, + 0x7a, 0xcb, 0x7a, 0xf9, 0x7a, 0x73, 0x7c, 0xf8, + 0x7c, 0x36, 0x7f, 0x51, 0x7f, 0x8a, 0x7f, 0xbd, + 0x7f, 0x01, 0x80, 0x0c, 0x80, 0x12, 0x80, 0x33, + 0x80, 0x7f, 0x80, 0x89, 0x80, 0xe3, 0x81, 0x00, + 0x07, 0x10, 0x19, 0x29, 0x38, 0x3c, 0x8b, 0x8f, + 0x95, 0x4d, 0x86, 0x6b, 0x86, 0x40, 0x88, 0x4c, + 0x88, 0x63, 0x88, 0x7e, 0x89, 0x8b, 0x89, 0xd2, + 0x89, 0x00, 0x8a, 0x37, 0x8c, 0x46, 0x8c, 0x55, + 0x8c, 0x78, 0x8c, 0x9d, 0x8c, 0x64, 0x8d, 0x70, + 0x8d, 0xb3, 0x8d, 0xab, 0x8e, 0xca, 0x8e, 0x9b, + 0x8f, 0xb0, 0x8f, 0xb5, 0x8f, 0x91, 0x90, 0x49, + 0x91, 0xc6, 0x91, 0xcc, 0x91, 0xd1, 0x91, 0x77, + 0x95, 0x80, 0x95, 0x1c, 0x96, 0xb6, 0x96, 0xb9, + 0x96, 0xe8, 0x96, 0x51, 0x97, 0x5e, 0x97, 0x62, + 0x97, 0x69, 0x97, 0xcb, 0x97, 0xed, 0x97, 0xf3, + 0x97, 0x01, 0x98, 0xa8, 0x98, 0xdb, 0x98, 0xdf, + 0x98, 0x96, 0x99, 0x99, 0x99, 0xac, 0x99, 0xa8, + 0x9a, 0xd8, 0x9a, 0xdf, 0x9a, 0x25, 0x9b, 0x2f, + 0x9b, 0x32, 0x9b, 0x3c, 0x9b, 0x5a, 0x9b, 0xe5, + 0x9c, 0x75, 0x9e, 0x7f, 0x9e, 0xa5, 0x9e, 0x00, + 0x16, 0x1e, 0x28, 0x2c, 0x54, 0x58, 0x69, 0x6e, + 0x7b, 0x96, 0xa5, 0xad, 0xe8, 0xf7, 0xfb, 0x12, + 0x30, 0x00, 0x00, 0x41, 0x53, 0x44, 0x53, 0x45, + 0x53, 0x4b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x4d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x4f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x51, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x53, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x55, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x59, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x5b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x5d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x5f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x61, 0x30, 0x99, 0x30, 0x64, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0x66, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0x68, 0x30, 0x99, + 0x30, 0x6f, 0x30, 0x99, 0x30, 0x72, 0x30, 0x99, + 0x30, 0x75, 0x30, 0x99, 0x30, 0x78, 0x30, 0x99, + 0x30, 0x7b, 0x30, 0x99, 0x30, 0x46, 0x30, 0x99, + 0x30, 0x20, 0x00, 0x99, 0x30, 0x9d, 0x30, 0x99, + 0x30, 0x88, 0x30, 0x8a, 0x30, 0xab, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xad, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xaf, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xb1, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xb3, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xb5, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xb7, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xbb, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xbd, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xbf, 0x30, 0x99, + 0x30, 0x00, 0x00, 0x00, 0x00, 0xc1, 0x30, 0x99, + 0x30, 0xc4, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0xc6, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00, + 0x00, 0xc8, 0x30, 0x99, 0x30, 0xcf, 0x30, 0x99, + 0x30, 0xd2, 0x30, 0x99, 0x30, 0xd5, 0x30, 0x99, + 0x30, 0xd8, 0x30, 0x99, 0x30, 0xdb, 0x30, 0x99, + 0x30, 0xa6, 0x30, 0x99, 0x30, 0xef, 0x30, 0x99, + 0x30, 0xfd, 0x30, 0x99, 0x30, 0xb3, 0x30, 0xc8, + 0x30, 0x00, 0x11, 0x00, 0x01, 0xaa, 0x02, 0xac, + 0xad, 0x03, 0x04, 0x05, 0xb0, 0xb1, 0xb2, 0xb3, + 0xb4, 0xb5, 0x1a, 0x06, 0x07, 0x08, 0x21, 0x09, + 0x11, 0x61, 0x11, 0x14, 0x11, 0x4c, 0x00, 0x01, + 0xb3, 0xb4, 0xb8, 0xba, 0xbf, 0xc3, 0xc5, 0x08, + 0xc9, 0xcb, 0x09, 0x0a, 0x0c, 0x0e, 0x0f, 0x13, + 0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1e, 0x22, + 0x2c, 0x33, 0x38, 0xdd, 0xde, 0x43, 0x44, 0x45, + 0x70, 0x71, 0x74, 0x7d, 0x7e, 0x80, 0x8a, 0x8d, + 0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56, + 0x0a, 0x4e, 0x2d, 0x4e, 0x0b, 0x4e, 0x32, 0x75, + 0x59, 0x4e, 0x19, 0x4e, 0x01, 0x4e, 0x29, 0x59, + 0x30, 0x57, 0xba, 0x4e, 0x28, 0x00, 0x29, 0x00, + 0x00, 0x11, 0x02, 0x11, 0x03, 0x11, 0x05, 0x11, + 0x06, 0x11, 0x07, 0x11, 0x09, 0x11, 0x0b, 0x11, + 0x0c, 0x11, 0x0e, 0x11, 0x0f, 0x11, 0x10, 0x11, + 0x11, 0x11, 0x12, 0x11, 0x28, 0x00, 0x00, 0x11, + 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x02, 0x11, + 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x05, 0x11, + 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x09, 0x11, + 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11, + 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0e, 0x11, + 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0c, 0x11, + 0x6e, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11, + 0x69, 0x11, 0x0c, 0x11, 0x65, 0x11, 0xab, 0x11, + 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11, 0x69, 0x11, + 0x12, 0x11, 0x6e, 0x11, 0x29, 0x00, 0x28, 0x00, + 0x29, 0x00, 0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e, + 0xdb, 0x56, 0x94, 0x4e, 0x6d, 0x51, 0x03, 0x4e, + 0x6b, 0x51, 0x5d, 0x4e, 0x41, 0x53, 0x08, 0x67, + 0x6b, 0x70, 0x34, 0x6c, 0x28, 0x67, 0xd1, 0x91, + 0x1f, 0x57, 0xe5, 0x65, 0x2a, 0x68, 0x09, 0x67, + 0x3e, 0x79, 0x0d, 0x54, 0x79, 0x72, 0xa1, 0x8c, + 0x5d, 0x79, 0xb4, 0x52, 0xe3, 0x4e, 0x7c, 0x54, + 0x66, 0x5b, 0xe3, 0x76, 0x01, 0x4f, 0xc7, 0x8c, + 0x54, 0x53, 0x6d, 0x79, 0x11, 0x4f, 0xea, 0x81, + 0xf3, 0x81, 0x4f, 0x55, 0x7c, 0x5e, 0x87, 0x65, + 0x8f, 0x7b, 0x50, 0x54, 0x45, 0x32, 0x00, 0x31, + 0x00, 0x33, 0x00, 0x30, 0x00, 0x00, 0x11, 0x00, + 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0b, 0x0c, + 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x00, 0x11, 0x00, + 0x61, 0x02, 0x61, 0x03, 0x61, 0x05, 0x61, 0x06, + 0x61, 0x07, 0x61, 0x09, 0x61, 0x0b, 0x61, 0x0c, + 0x61, 0x0e, 0x11, 0x61, 0x11, 0x00, 0x11, 0x0e, + 0x61, 0xb7, 0x00, 0x69, 0x0b, 0x11, 0x01, 0x63, + 0x00, 0x69, 0x0b, 0x11, 0x6e, 0x11, 0x00, 0x4e, + 0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56, 0x94, 0x4e, + 0x6d, 0x51, 0x03, 0x4e, 0x6b, 0x51, 0x5d, 0x4e, + 0x41, 0x53, 0x08, 0x67, 0x6b, 0x70, 0x34, 0x6c, + 0x28, 0x67, 0xd1, 0x91, 0x1f, 0x57, 0xe5, 0x65, + 0x2a, 0x68, 0x09, 0x67, 0x3e, 0x79, 0x0d, 0x54, + 0x79, 0x72, 0xa1, 0x8c, 0x5d, 0x79, 0xb4, 0x52, + 0xd8, 0x79, 0x37, 0x75, 0x73, 0x59, 0x69, 0x90, + 0x2a, 0x51, 0x70, 0x53, 0xe8, 0x6c, 0x05, 0x98, + 0x11, 0x4f, 0x99, 0x51, 0x63, 0x6b, 0x0a, 0x4e, + 0x2d, 0x4e, 0x0b, 0x4e, 0xe6, 0x5d, 0xf3, 0x53, + 0x3b, 0x53, 0x97, 0x5b, 0x66, 0x5b, 0xe3, 0x76, + 0x01, 0x4f, 0xc7, 0x8c, 0x54, 0x53, 0x1c, 0x59, + 0x33, 0x00, 0x36, 0x00, 0x34, 0x00, 0x30, 0x00, + 0x35, 0x30, 0x31, 0x00, 0x08, 0x67, 0x31, 0x00, + 0x30, 0x00, 0x08, 0x67, 0x48, 0x67, 0x65, 0x72, + 0x67, 0x65, 0x56, 0x4c, 0x54, 0x44, 0xa2, 0x30, + 0x00, 0x02, 0x04, 0x06, 0x08, 0x09, 0x0b, 0x0d, + 0x0f, 0x11, 0x13, 0x15, 0x17, 0x19, 0x1b, 0x1d, + 0x1f, 0x22, 0x24, 0x26, 0x28, 0x29, 0x2a, 0x2b, + 0x2c, 0x2d, 0x30, 0x33, 0x36, 0x39, 0x3c, 0x3d, + 0x3e, 0x3f, 0x40, 0x42, 0x44, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0xe4, + 0x4e, 0x8c, 0x54, 0xa1, 0x30, 0x01, 0x30, 0x5b, + 0x27, 0x01, 0x4a, 0x34, 0x00, 0x01, 0x52, 0x39, + 0x01, 0xa2, 0x30, 0x00, 0x5a, 0x49, 0xa4, 0x30, + 0x00, 0x27, 0x4f, 0x0c, 0xa4, 0x30, 0x00, 0x4f, + 0x1d, 0x02, 0x05, 0x4f, 0xa8, 0x30, 0x00, 0x11, + 0x07, 0x54, 0x21, 0xa8, 0x30, 0x00, 0x54, 0x03, + 0x54, 0xa4, 0x30, 0x06, 0x4f, 0x15, 0x06, 0x58, + 0x3c, 0x07, 0x00, 0x46, 0xab, 0x30, 0x00, 0x3e, + 0x18, 0x1d, 0x00, 0x42, 0x3f, 0x51, 0xac, 0x30, + 0x00, 0x41, 0x47, 0x00, 0x47, 0x32, 0xae, 0x30, + 0xac, 0x30, 0xae, 0x30, 0x00, 0x1d, 0x4e, 0xad, + 0x30, 0x00, 0x38, 0x3d, 0x4f, 0x01, 0x3e, 0x13, + 0x4f, 0xad, 0x30, 0xed, 0x30, 0xad, 0x30, 0x00, + 0x40, 0x03, 0x3c, 0x33, 0xad, 0x30, 0x00, 0x40, + 0x34, 0x4f, 0x1b, 0x3e, 0xad, 0x30, 0x00, 0x40, + 0x42, 0x16, 0x1b, 0xb0, 0x30, 0x00, 0x39, 0x30, + 0xa4, 0x30, 0x0c, 0x45, 0x3c, 0x24, 0x4f, 0x0b, + 0x47, 0x18, 0x00, 0x49, 0xaf, 0x30, 0x00, 0x3e, + 0x4d, 0x1e, 0xb1, 0x30, 0x00, 0x4b, 0x08, 0x02, + 0x3a, 0x19, 0x02, 0x4b, 0x2c, 0xa4, 0x30, 0x11, + 0x00, 0x0b, 0x47, 0xb5, 0x30, 0x00, 0x3e, 0x0c, + 0x47, 0x2b, 0xb0, 0x30, 0x07, 0x3a, 0x43, 0x00, + 0xb9, 0x30, 0x02, 0x3a, 0x08, 0x02, 0x3a, 0x0f, + 0x07, 0x43, 0x00, 0xb7, 0x30, 0x10, 0x00, 0x12, + 0x34, 0x11, 0x3c, 0x13, 0x17, 0xa4, 0x30, 0x2a, + 0x1f, 0x24, 0x2b, 0x00, 0x20, 0xbb, 0x30, 0x16, + 0x41, 0x00, 0x38, 0x0d, 0xc4, 0x30, 0x0d, 0x38, + 0x00, 0xd0, 0x30, 0x00, 0x2c, 0x1c, 0x1b, 0xa2, + 0x30, 0x32, 0x00, 0x17, 0x26, 0x49, 0xaf, 0x30, + 0x25, 0x00, 0x3c, 0xb3, 0x30, 0x21, 0x00, 0x20, + 0x38, 0xa1, 0x30, 0x34, 0x00, 0x48, 0x22, 0x28, + 0xa3, 0x30, 0x32, 0x00, 0x59, 0x25, 0xa7, 0x30, + 0x2f, 0x1c, 0x10, 0x00, 0x44, 0xd5, 0x30, 0x00, + 0x14, 0x1e, 0xaf, 0x30, 0x29, 0x00, 0x10, 0x4d, + 0x3c, 0xda, 0x30, 0xbd, 0x30, 0xb8, 0x30, 0x22, + 0x13, 0x1a, 0x20, 0x33, 0x0c, 0x22, 0x3b, 0x01, + 0x22, 0x44, 0x00, 0x21, 0x44, 0x07, 0xa4, 0x30, + 0x39, 0x00, 0x4f, 0x24, 0xc8, 0x30, 0x14, 0x23, + 0x00, 0xdb, 0x30, 0xf3, 0x30, 0xc9, 0x30, 0x14, + 0x2a, 0x00, 0x12, 0x33, 0x22, 0x12, 0x33, 0x2a, + 0xa4, 0x30, 0x3a, 0x00, 0x0b, 0x49, 0xa4, 0x30, + 0x3a, 0x00, 0x47, 0x3a, 0x1f, 0x2b, 0x3a, 0x47, + 0x0b, 0xb7, 0x30, 0x27, 0x3c, 0x00, 0x30, 0x3c, + 0xaf, 0x30, 0x30, 0x00, 0x3e, 0x44, 0xdf, 0x30, + 0xea, 0x30, 0xd0, 0x30, 0x0f, 0x1a, 0x00, 0x2c, + 0x1b, 0xe1, 0x30, 0xac, 0x30, 0xac, 0x30, 0x35, + 0x00, 0x1c, 0x47, 0x35, 0x50, 0x1c, 0x3f, 0xa2, + 0x30, 0x42, 0x5a, 0x27, 0x42, 0x5a, 0x49, 0x44, + 0x00, 0x51, 0xc3, 0x30, 0x27, 0x00, 0x05, 0x28, + 0xea, 0x30, 0xe9, 0x30, 0xd4, 0x30, 0x17, 0x00, + 0x28, 0xd6, 0x30, 0x15, 0x26, 0x00, 0x15, 0xec, + 0x30, 0xe0, 0x30, 0xb2, 0x30, 0x3a, 0x41, 0x16, + 0x00, 0x41, 0xc3, 0x30, 0x2c, 0x00, 0x05, 0x30, + 0x00, 0xb9, 0x70, 0x31, 0x00, 0x30, 0x00, 0xb9, + 0x70, 0x32, 0x00, 0x30, 0x00, 0xb9, 0x70, 0x68, + 0x50, 0x61, 0x64, 0x61, 0x41, 0x55, 0x62, 0x61, + 0x72, 0x6f, 0x56, 0x70, 0x63, 0x64, 0x6d, 0x64, + 0x00, 0x6d, 0x00, 0xb2, 0x00, 0x49, 0x00, 0x55, + 0x00, 0x73, 0x5e, 0x10, 0x62, 0x2d, 0x66, 0x8c, + 0x54, 0x27, 0x59, 0x63, 0x6b, 0x0e, 0x66, 0xbb, + 0x6c, 0x2a, 0x68, 0x0f, 0x5f, 0x1a, 0x4f, 0x3e, + 0x79, 0x70, 0x00, 0x41, 0x6e, 0x00, 0x41, 0xbc, + 0x03, 0x41, 0x6d, 0x00, 0x41, 0x6b, 0x00, 0x41, + 0x4b, 0x00, 0x42, 0x4d, 0x00, 0x42, 0x47, 0x00, + 0x42, 0x63, 0x61, 0x6c, 0x6b, 0x63, 0x61, 0x6c, + 0x70, 0x00, 0x46, 0x6e, 0x00, 0x46, 0xbc, 0x03, + 0x46, 0xbc, 0x03, 0x67, 0x6d, 0x00, 0x67, 0x6b, + 0x00, 0x67, 0x48, 0x00, 0x7a, 0x6b, 0x48, 0x7a, + 0x4d, 0x48, 0x7a, 0x47, 0x48, 0x7a, 0x54, 0x48, + 0x7a, 0xbc, 0x03, 0x13, 0x21, 0x6d, 0x00, 0x13, + 0x21, 0x64, 0x00, 0x13, 0x21, 0x6b, 0x00, 0x13, + 0x21, 0x66, 0x00, 0x6d, 0x6e, 0x00, 0x6d, 0xbc, + 0x03, 0x6d, 0x6d, 0x00, 0x6d, 0x63, 0x00, 0x6d, + 0x6b, 0x00, 0x6d, 0x63, 0x00, 0x0a, 0x0a, 0x4f, + 0x00, 0x0a, 0x4f, 0x6d, 0x00, 0xb2, 0x00, 0x63, + 0x00, 0x08, 0x0a, 0x4f, 0x0a, 0x0a, 0x50, 0x00, + 0x0a, 0x50, 0x6d, 0x00, 0xb3, 0x00, 0x6b, 0x00, + 0x6d, 0x00, 0xb3, 0x00, 0x6d, 0x00, 0x15, 0x22, + 0x73, 0x00, 0x6d, 0x00, 0x15, 0x22, 0x73, 0x00, + 0xb2, 0x00, 0x50, 0x61, 0x6b, 0x50, 0x61, 0x4d, + 0x50, 0x61, 0x47, 0x50, 0x61, 0x72, 0x61, 0x64, + 0x72, 0x61, 0x64, 0xd1, 0x73, 0x72, 0x00, 0x61, + 0x00, 0x64, 0x00, 0x15, 0x22, 0x73, 0x00, 0xb2, + 0x00, 0x70, 0x00, 0x73, 0x6e, 0x00, 0x73, 0xbc, + 0x03, 0x73, 0x6d, 0x00, 0x73, 0x70, 0x00, 0x56, + 0x6e, 0x00, 0x56, 0xbc, 0x03, 0x56, 0x6d, 0x00, + 0x56, 0x6b, 0x00, 0x56, 0x4d, 0x00, 0x56, 0x70, + 0x00, 0x57, 0x6e, 0x00, 0x57, 0xbc, 0x03, 0x57, + 0x6d, 0x00, 0x57, 0x6b, 0x00, 0x57, 0x4d, 0x00, + 0x57, 0x6b, 0x00, 0xa9, 0x03, 0x4d, 0x00, 0xa9, + 0x03, 0x61, 0x2e, 0x6d, 0x2e, 0x42, 0x71, 0x63, + 0x63, 0x63, 0x64, 0x43, 0xd1, 0x6b, 0x67, 0x43, + 0x6f, 0x2e, 0x64, 0x42, 0x47, 0x79, 0x68, 0x61, + 0x48, 0x50, 0x69, 0x6e, 0x4b, 0x4b, 0x4b, 0x4d, + 0x6b, 0x74, 0x6c, 0x6d, 0x6c, 0x6e, 0x6c, 0x6f, + 0x67, 0x6c, 0x78, 0x6d, 0x62, 0x6d, 0x69, 0x6c, + 0x6d, 0x6f, 0x6c, 0x50, 0x48, 0x70, 0x2e, 0x6d, + 0x2e, 0x50, 0x50, 0x4d, 0x50, 0x52, 0x73, 0x72, + 0x53, 0x76, 0x57, 0x62, 0x56, 0xd1, 0x6d, 0x41, + 0xd1, 0x6d, 0x31, 0x00, 0xe5, 0x65, 0x31, 0x00, + 0x30, 0x00, 0xe5, 0x65, 0x32, 0x00, 0x30, 0x00, + 0xe5, 0x65, 0x33, 0x00, 0x30, 0x00, 0xe5, 0x65, + 0x67, 0x61, 0x6c, 0x4a, 0x04, 0x4c, 0x04, 0x53, + 0x43, 0x46, 0x51, 0x26, 0x01, 0x53, 0x01, 0x27, + 0xa7, 0x37, 0xab, 0x6b, 0x02, 0x52, 0xab, 0x48, + 0x8c, 0xf4, 0x66, 0xca, 0x8e, 0xc8, 0x8c, 0xd1, + 0x6e, 0x32, 0x4e, 0xe5, 0x53, 0x9c, 0x9f, 0x9c, + 0x9f, 0x51, 0x59, 0xd1, 0x91, 0x87, 0x55, 0x48, + 0x59, 0xf6, 0x61, 0x69, 0x76, 0x85, 0x7f, 0x3f, + 0x86, 0xba, 0x87, 0xf8, 0x88, 0x8f, 0x90, 0x02, + 0x6a, 0x1b, 0x6d, 0xd9, 0x70, 0xde, 0x73, 0x3d, + 0x84, 0x6a, 0x91, 0xf1, 0x99, 0x82, 0x4e, 0x75, + 0x53, 0x04, 0x6b, 0x1b, 0x72, 0x2d, 0x86, 0x1e, + 0x9e, 0x50, 0x5d, 0xeb, 0x6f, 0xcd, 0x85, 0x64, + 0x89, 0xc9, 0x62, 0xd8, 0x81, 0x1f, 0x88, 0xca, + 0x5e, 0x17, 0x67, 0x6a, 0x6d, 0xfc, 0x72, 0xce, + 0x90, 0x86, 0x4f, 0xb7, 0x51, 0xde, 0x52, 0xc4, + 0x64, 0xd3, 0x6a, 0x10, 0x72, 0xe7, 0x76, 0x01, + 0x80, 0x06, 0x86, 0x5c, 0x86, 0xef, 0x8d, 0x32, + 0x97, 0x6f, 0x9b, 0xfa, 0x9d, 0x8c, 0x78, 0x7f, + 0x79, 0xa0, 0x7d, 0xc9, 0x83, 0x04, 0x93, 0x7f, + 0x9e, 0xd6, 0x8a, 0xdf, 0x58, 0x04, 0x5f, 0x60, + 0x7c, 0x7e, 0x80, 0x62, 0x72, 0xca, 0x78, 0xc2, + 0x8c, 0xf7, 0x96, 0xd8, 0x58, 0x62, 0x5c, 0x13, + 0x6a, 0xda, 0x6d, 0x0f, 0x6f, 0x2f, 0x7d, 0x37, + 0x7e, 0x4b, 0x96, 0xd2, 0x52, 0x8b, 0x80, 0xdc, + 0x51, 0xcc, 0x51, 0x1c, 0x7a, 0xbe, 0x7d, 0xf1, + 0x83, 0x75, 0x96, 0x80, 0x8b, 0xcf, 0x62, 0x02, + 0x6a, 0xfe, 0x8a, 0x39, 0x4e, 0xe7, 0x5b, 0x12, + 0x60, 0x87, 0x73, 0x70, 0x75, 0x17, 0x53, 0xfb, + 0x78, 0xbf, 0x4f, 0xa9, 0x5f, 0x0d, 0x4e, 0xcc, + 0x6c, 0x78, 0x65, 0x22, 0x7d, 0xc3, 0x53, 0x5e, + 0x58, 0x01, 0x77, 0x49, 0x84, 0xaa, 0x8a, 0xba, + 0x6b, 0xb0, 0x8f, 0x88, 0x6c, 0xfe, 0x62, 0xe5, + 0x82, 0xa0, 0x63, 0x65, 0x75, 0xae, 0x4e, 0x69, + 0x51, 0xc9, 0x51, 0x81, 0x68, 0xe7, 0x7c, 0x6f, + 0x82, 0xd2, 0x8a, 0xcf, 0x91, 0xf5, 0x52, 0x42, + 0x54, 0x73, 0x59, 0xec, 0x5e, 0xc5, 0x65, 0xfe, + 0x6f, 0x2a, 0x79, 0xad, 0x95, 0x6a, 0x9a, 0x97, + 0x9e, 0xce, 0x9e, 0x9b, 0x52, 0xc6, 0x66, 0x77, + 0x6b, 0x62, 0x8f, 0x74, 0x5e, 0x90, 0x61, 0x00, + 0x62, 0x9a, 0x64, 0x23, 0x6f, 0x49, 0x71, 0x89, + 0x74, 0xca, 0x79, 0xf4, 0x7d, 0x6f, 0x80, 0x26, + 0x8f, 0xee, 0x84, 0x23, 0x90, 0x4a, 0x93, 0x17, + 0x52, 0xa3, 0x52, 0xbd, 0x54, 0xc8, 0x70, 0xc2, + 0x88, 0xaa, 0x8a, 0xc9, 0x5e, 0xf5, 0x5f, 0x7b, + 0x63, 0xae, 0x6b, 0x3e, 0x7c, 0x75, 0x73, 0xe4, + 0x4e, 0xf9, 0x56, 0xe7, 0x5b, 0xba, 0x5d, 0x1c, + 0x60, 0xb2, 0x73, 0x69, 0x74, 0x9a, 0x7f, 0x46, + 0x80, 0x34, 0x92, 0xf6, 0x96, 0x48, 0x97, 0x18, + 0x98, 0x8b, 0x4f, 0xae, 0x79, 0xb4, 0x91, 0xb8, + 0x96, 0xe1, 0x60, 0x86, 0x4e, 0xda, 0x50, 0xee, + 0x5b, 0x3f, 0x5c, 0x99, 0x65, 0x02, 0x6a, 0xce, + 0x71, 0x42, 0x76, 0xfc, 0x84, 0x7c, 0x90, 0x8d, + 0x9f, 0x88, 0x66, 0x2e, 0x96, 0x89, 0x52, 0x7b, + 0x67, 0xf3, 0x67, 0x41, 0x6d, 0x9c, 0x6e, 0x09, + 0x74, 0x59, 0x75, 0x6b, 0x78, 0x10, 0x7d, 0x5e, + 0x98, 0x6d, 0x51, 0x2e, 0x62, 0x78, 0x96, 0x2b, + 0x50, 0x19, 0x5d, 0xea, 0x6d, 0x2a, 0x8f, 0x8b, + 0x5f, 0x44, 0x61, 0x17, 0x68, 0x87, 0x73, 0x86, + 0x96, 0x29, 0x52, 0x0f, 0x54, 0x65, 0x5c, 0x13, + 0x66, 0x4e, 0x67, 0xa8, 0x68, 0xe5, 0x6c, 0x06, + 0x74, 0xe2, 0x75, 0x79, 0x7f, 0xcf, 0x88, 0xe1, + 0x88, 0xcc, 0x91, 0xe2, 0x96, 0x3f, 0x53, 0xba, + 0x6e, 0x1d, 0x54, 0xd0, 0x71, 0x98, 0x74, 0xfa, + 0x85, 0xa3, 0x96, 0x57, 0x9c, 0x9f, 0x9e, 0x97, + 0x67, 0xcb, 0x6d, 0xe8, 0x81, 0xcb, 0x7a, 0x20, + 0x7b, 0x92, 0x7c, 0xc0, 0x72, 0x99, 0x70, 0x58, + 0x8b, 0xc0, 0x4e, 0x36, 0x83, 0x3a, 0x52, 0x07, + 0x52, 0xa6, 0x5e, 0xd3, 0x62, 0xd6, 0x7c, 0x85, + 0x5b, 0x1e, 0x6d, 0xb4, 0x66, 0x3b, 0x8f, 0x4c, + 0x88, 0x4d, 0x96, 0x8b, 0x89, 0xd3, 0x5e, 0x40, + 0x51, 0xc0, 0x55, 0x00, 0x00, 0x00, 0x00, 0x5a, + 0x58, 0x00, 0x00, 0x74, 0x66, 0x00, 0x00, 0x00, + 0x00, 0xde, 0x51, 0x2a, 0x73, 0xca, 0x76, 0x3c, + 0x79, 0x5e, 0x79, 0x65, 0x79, 0x8f, 0x79, 0x56, + 0x97, 0xbe, 0x7c, 0xbd, 0x7f, 0x00, 0x00, 0x12, + 0x86, 0x00, 0x00, 0xf8, 0x8a, 0x00, 0x00, 0x00, + 0x00, 0x38, 0x90, 0xfd, 0x90, 0xef, 0x98, 0xfc, + 0x98, 0x28, 0x99, 0xb4, 0x9d, 0xde, 0x90, 0xb7, + 0x96, 0xae, 0x4f, 0xe7, 0x50, 0x4d, 0x51, 0xc9, + 0x52, 0xe4, 0x52, 0x51, 0x53, 0x9d, 0x55, 0x06, + 0x56, 0x68, 0x56, 0x40, 0x58, 0xa8, 0x58, 0x64, + 0x5c, 0x6e, 0x5c, 0x94, 0x60, 0x68, 0x61, 0x8e, + 0x61, 0xf2, 0x61, 0x4f, 0x65, 0xe2, 0x65, 0x91, + 0x66, 0x85, 0x68, 0x77, 0x6d, 0x1a, 0x6e, 0x22, + 0x6f, 0x6e, 0x71, 0x2b, 0x72, 0x22, 0x74, 0x91, + 0x78, 0x3e, 0x79, 0x49, 0x79, 0x48, 0x79, 0x50, + 0x79, 0x56, 0x79, 0x5d, 0x79, 0x8d, 0x79, 0x8e, + 0x79, 0x40, 0x7a, 0x81, 0x7a, 0xc0, 0x7b, 0xf4, + 0x7d, 0x09, 0x7e, 0x41, 0x7e, 0x72, 0x7f, 0x05, + 0x80, 0xed, 0x81, 0x79, 0x82, 0x79, 0x82, 0x57, + 0x84, 0x10, 0x89, 0x96, 0x89, 0x01, 0x8b, 0x39, + 0x8b, 0xd3, 0x8c, 0x08, 0x8d, 0xb6, 0x8f, 0x38, + 0x90, 0xe3, 0x96, 0xff, 0x97, 0x3b, 0x98, 0x75, + 0x60, 0xee, 0x42, 0x18, 0x82, 0x02, 0x26, 0x4e, + 0xb5, 0x51, 0x68, 0x51, 0x80, 0x4f, 0x45, 0x51, + 0x80, 0x51, 0xc7, 0x52, 0xfa, 0x52, 0x9d, 0x55, + 0x55, 0x55, 0x99, 0x55, 0xe2, 0x55, 0x5a, 0x58, + 0xb3, 0x58, 0x44, 0x59, 0x54, 0x59, 0x62, 0x5a, + 0x28, 0x5b, 0xd2, 0x5e, 0xd9, 0x5e, 0x69, 0x5f, + 0xad, 0x5f, 0xd8, 0x60, 0x4e, 0x61, 0x08, 0x61, + 0x8e, 0x61, 0x60, 0x61, 0xf2, 0x61, 0x34, 0x62, + 0xc4, 0x63, 0x1c, 0x64, 0x52, 0x64, 0x56, 0x65, + 0x74, 0x66, 0x17, 0x67, 0x1b, 0x67, 0x56, 0x67, + 0x79, 0x6b, 0xba, 0x6b, 0x41, 0x6d, 0xdb, 0x6e, + 0xcb, 0x6e, 0x22, 0x6f, 0x1e, 0x70, 0x6e, 0x71, + 0xa7, 0x77, 0x35, 0x72, 0xaf, 0x72, 0x2a, 0x73, + 0x71, 0x74, 0x06, 0x75, 0x3b, 0x75, 0x1d, 0x76, + 0x1f, 0x76, 0xca, 0x76, 0xdb, 0x76, 0xf4, 0x76, + 0x4a, 0x77, 0x40, 0x77, 0xcc, 0x78, 0xb1, 0x7a, + 0xc0, 0x7b, 0x7b, 0x7c, 0x5b, 0x7d, 0xf4, 0x7d, + 0x3e, 0x7f, 0x05, 0x80, 0x52, 0x83, 0xef, 0x83, + 0x79, 0x87, 0x41, 0x89, 0x86, 0x89, 0x96, 0x89, + 0xbf, 0x8a, 0xf8, 0x8a, 0xcb, 0x8a, 0x01, 0x8b, + 0xfe, 0x8a, 0xed, 0x8a, 0x39, 0x8b, 0x8a, 0x8b, + 0x08, 0x8d, 0x38, 0x8f, 0x72, 0x90, 0x99, 0x91, + 0x76, 0x92, 0x7c, 0x96, 0xe3, 0x96, 0x56, 0x97, + 0xdb, 0x97, 0xff, 0x97, 0x0b, 0x98, 0x3b, 0x98, + 0x12, 0x9b, 0x9c, 0x9f, 0x4a, 0x28, 0x44, 0x28, + 0xd5, 0x33, 0x9d, 0x3b, 0x18, 0x40, 0x39, 0x40, + 0x49, 0x52, 0xd0, 0x5c, 0xd3, 0x7e, 0x43, 0x9f, + 0x8e, 0x9f, 0x2a, 0xa0, 0x02, 0x66, 0x66, 0x66, + 0x69, 0x66, 0x6c, 0x66, 0x66, 0x69, 0x66, 0x66, + 0x6c, 0x7f, 0x01, 0x74, 0x73, 0x00, 0x74, 0x65, + 0x05, 0x0f, 0x11, 0x0f, 0x00, 0x0f, 0x06, 0x19, + 0x11, 0x0f, 0x08, 0xd9, 0x05, 0xb4, 0x05, 0x00, + 0x00, 0x00, 0x00, 0xf2, 0x05, 0xb7, 0x05, 0xd0, + 0x05, 0x12, 0x00, 0x03, 0x04, 0x0b, 0x0c, 0x0d, + 0x18, 0x1a, 0xe9, 0x05, 0xc1, 0x05, 0xe9, 0x05, + 0xc2, 0x05, 0x49, 0xfb, 0xc1, 0x05, 0x49, 0xfb, + 0xc2, 0x05, 0xd0, 0x05, 0xb7, 0x05, 0xd0, 0x05, + 0xb8, 0x05, 0xd0, 0x05, 0xbc, 0x05, 0xd8, 0x05, + 0xbc, 0x05, 0xde, 0x05, 0xbc, 0x05, 0xe0, 0x05, + 0xbc, 0x05, 0xe3, 0x05, 0xbc, 0x05, 0xb9, 0x05, + 0x2d, 0x03, 0x2e, 0x03, 0x2f, 0x03, 0x30, 0x03, + 0x31, 0x03, 0x1c, 0x00, 0x18, 0x06, 0x22, 0x06, + 0x2b, 0x06, 0xd0, 0x05, 0xdc, 0x05, 0x71, 0x06, + 0x00, 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0d, 0x0d, + 0x0d, 0x0d, 0x0f, 0x0f, 0x0f, 0x0f, 0x09, 0x09, + 0x09, 0x09, 0x0e, 0x0e, 0x0e, 0x0e, 0x08, 0x08, + 0x08, 0x08, 0x33, 0x33, 0x33, 0x33, 0x35, 0x35, + 0x35, 0x35, 0x13, 0x13, 0x13, 0x13, 0x12, 0x12, + 0x12, 0x12, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, + 0x16, 0x16, 0x1c, 0x1c, 0x1b, 0x1b, 0x1d, 0x1d, + 0x17, 0x17, 0x27, 0x27, 0x20, 0x20, 0x38, 0x38, + 0x38, 0x38, 0x3e, 0x3e, 0x3e, 0x3e, 0x42, 0x42, + 0x42, 0x42, 0x40, 0x40, 0x40, 0x40, 0x49, 0x49, + 0x4a, 0x4a, 0x4a, 0x4a, 0x4f, 0x4f, 0x50, 0x50, + 0x50, 0x50, 0x4d, 0x4d, 0x4d, 0x4d, 0x61, 0x61, + 0x62, 0x62, 0x49, 0x06, 0x64, 0x64, 0x64, 0x64, + 0x7e, 0x7e, 0x7d, 0x7d, 0x7f, 0x7f, 0x2e, 0x82, + 0x82, 0x7c, 0x7c, 0x80, 0x80, 0x87, 0x87, 0x87, + 0x87, 0x00, 0x00, 0x26, 0x06, 0x00, 0x01, 0x00, + 0x01, 0x00, 0xaf, 0x00, 0xaf, 0x00, 0x22, 0x00, + 0x22, 0x00, 0xa1, 0x00, 0xa1, 0x00, 0xa0, 0x00, + 0xa0, 0x00, 0xa2, 0x00, 0xa2, 0x00, 0xaa, 0x00, + 0xaa, 0x00, 0xaa, 0x00, 0x23, 0x00, 0x23, 0x00, + 0x23, 0xcc, 0x06, 0x00, 0x00, 0x00, 0x00, 0x26, + 0x06, 0x00, 0x06, 0x00, 0x07, 0x00, 0x1f, 0x00, + 0x23, 0x00, 0x24, 0x02, 0x06, 0x02, 0x07, 0x02, + 0x08, 0x02, 0x1f, 0x02, 0x23, 0x02, 0x24, 0x04, + 0x06, 0x04, 0x07, 0x04, 0x08, 0x04, 0x1f, 0x04, + 0x23, 0x04, 0x24, 0x05, 0x06, 0x05, 0x1f, 0x05, + 0x23, 0x05, 0x24, 0x06, 0x07, 0x06, 0x1f, 0x07, + 0x06, 0x07, 0x1f, 0x08, 0x06, 0x08, 0x07, 0x08, + 0x1f, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x08, 0x0d, + 0x1f, 0x0f, 0x07, 0x0f, 0x1f, 0x10, 0x06, 0x10, + 0x07, 0x10, 0x08, 0x10, 0x1f, 0x11, 0x07, 0x11, + 0x1f, 0x12, 0x1f, 0x13, 0x06, 0x13, 0x1f, 0x14, + 0x06, 0x14, 0x1f, 0x1b, 0x06, 0x1b, 0x07, 0x1b, + 0x08, 0x1b, 0x1f, 0x1b, 0x23, 0x1b, 0x24, 0x1c, + 0x07, 0x1c, 0x1f, 0x1c, 0x23, 0x1c, 0x24, 0x1d, + 0x01, 0x1d, 0x06, 0x1d, 0x07, 0x1d, 0x08, 0x1d, + 0x1e, 0x1d, 0x1f, 0x1d, 0x23, 0x1d, 0x24, 0x1e, + 0x06, 0x1e, 0x07, 0x1e, 0x08, 0x1e, 0x1f, 0x1e, + 0x23, 0x1e, 0x24, 0x1f, 0x06, 0x1f, 0x07, 0x1f, + 0x08, 0x1f, 0x1f, 0x1f, 0x23, 0x1f, 0x24, 0x20, + 0x06, 0x20, 0x07, 0x20, 0x08, 0x20, 0x1f, 0x20, + 0x23, 0x20, 0x24, 0x21, 0x06, 0x21, 0x1f, 0x21, + 0x23, 0x21, 0x24, 0x24, 0x06, 0x24, 0x07, 0x24, + 0x08, 0x24, 0x1f, 0x24, 0x23, 0x24, 0x24, 0x0a, + 0x4a, 0x0b, 0x4a, 0x23, 0x4a, 0x20, 0x00, 0x4c, + 0x06, 0x51, 0x06, 0x51, 0x06, 0xff, 0x00, 0x1f, + 0x26, 0x06, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x1f, + 0x00, 0x20, 0x00, 0x23, 0x00, 0x24, 0x02, 0x0b, + 0x02, 0x0c, 0x02, 0x1f, 0x02, 0x20, 0x02, 0x23, + 0x02, 0x24, 0x04, 0x0b, 0x04, 0x0c, 0x04, 0x1f, + 0x26, 0x06, 0x04, 0x20, 0x04, 0x23, 0x04, 0x24, + 0x05, 0x0b, 0x05, 0x0c, 0x05, 0x1f, 0x05, 0x20, + 0x05, 0x23, 0x05, 0x24, 0x1b, 0x23, 0x1b, 0x24, + 0x1c, 0x23, 0x1c, 0x24, 0x1d, 0x01, 0x1d, 0x1e, + 0x1d, 0x1f, 0x1d, 0x23, 0x1d, 0x24, 0x1e, 0x1f, + 0x1e, 0x23, 0x1e, 0x24, 0x1f, 0x01, 0x1f, 0x1f, + 0x20, 0x0b, 0x20, 0x0c, 0x20, 0x1f, 0x20, 0x20, + 0x20, 0x23, 0x20, 0x24, 0x23, 0x4a, 0x24, 0x0b, + 0x24, 0x0c, 0x24, 0x1f, 0x24, 0x20, 0x24, 0x23, + 0x24, 0x24, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, + 0x00, 0x1f, 0x00, 0x21, 0x02, 0x06, 0x02, 0x07, + 0x02, 0x08, 0x02, 0x1f, 0x02, 0x21, 0x04, 0x06, + 0x04, 0x07, 0x04, 0x08, 0x04, 0x1f, 0x04, 0x21, + 0x05, 0x1f, 0x06, 0x07, 0x06, 0x1f, 0x07, 0x06, + 0x07, 0x1f, 0x08, 0x06, 0x08, 0x1f, 0x0d, 0x06, + 0x0d, 0x07, 0x0d, 0x08, 0x0d, 0x1f, 0x0f, 0x07, + 0x0f, 0x08, 0x0f, 0x1f, 0x10, 0x06, 0x10, 0x07, + 0x10, 0x08, 0x10, 0x1f, 0x11, 0x07, 0x12, 0x1f, + 0x13, 0x06, 0x13, 0x1f, 0x14, 0x06, 0x14, 0x1f, + 0x1b, 0x06, 0x1b, 0x07, 0x1b, 0x08, 0x1b, 0x1f, + 0x1c, 0x07, 0x1c, 0x1f, 0x1d, 0x06, 0x1d, 0x07, + 0x1d, 0x08, 0x1d, 0x1e, 0x1d, 0x1f, 0x1e, 0x06, + 0x1e, 0x07, 0x1e, 0x08, 0x1e, 0x1f, 0x1e, 0x21, + 0x1f, 0x06, 0x1f, 0x07, 0x1f, 0x08, 0x1f, 0x1f, + 0x20, 0x06, 0x20, 0x07, 0x20, 0x08, 0x20, 0x1f, + 0x20, 0x21, 0x21, 0x06, 0x21, 0x1f, 0x21, 0x4a, + 0x24, 0x06, 0x24, 0x07, 0x24, 0x08, 0x24, 0x1f, + 0x24, 0x21, 0x00, 0x1f, 0x00, 0x21, 0x02, 0x1f, + 0x02, 0x21, 0x04, 0x1f, 0x04, 0x21, 0x05, 0x1f, + 0x05, 0x21, 0x0d, 0x1f, 0x0d, 0x21, 0x0e, 0x1f, + 0x0e, 0x21, 0x1d, 0x1e, 0x1d, 0x1f, 0x1e, 0x1f, + 0x20, 0x1f, 0x20, 0x21, 0x24, 0x1f, 0x24, 0x21, + 0x40, 0x06, 0x4e, 0x06, 0x51, 0x06, 0x27, 0x06, + 0x10, 0x22, 0x10, 0x23, 0x12, 0x22, 0x12, 0x23, + 0x13, 0x22, 0x13, 0x23, 0x0c, 0x22, 0x0c, 0x23, + 0x0d, 0x22, 0x0d, 0x23, 0x06, 0x22, 0x06, 0x23, + 0x05, 0x22, 0x05, 0x23, 0x07, 0x22, 0x07, 0x23, + 0x0e, 0x22, 0x0e, 0x23, 0x0f, 0x22, 0x0f, 0x23, + 0x0d, 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x1e, + 0x0d, 0x0a, 0x0c, 0x0a, 0x0e, 0x0a, 0x0f, 0x0a, + 0x10, 0x22, 0x10, 0x23, 0x12, 0x22, 0x12, 0x23, + 0x13, 0x22, 0x13, 0x23, 0x0c, 0x22, 0x0c, 0x23, + 0x0d, 0x22, 0x0d, 0x23, 0x06, 0x22, 0x06, 0x23, + 0x05, 0x22, 0x05, 0x23, 0x07, 0x22, 0x07, 0x23, + 0x0e, 0x22, 0x0e, 0x23, 0x0f, 0x22, 0x0f, 0x23, + 0x0d, 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x1e, + 0x0d, 0x0a, 0x0c, 0x0a, 0x0e, 0x0a, 0x0f, 0x0a, + 0x0d, 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x1e, + 0x0c, 0x20, 0x0d, 0x20, 0x10, 0x1e, 0x0c, 0x05, + 0x0c, 0x06, 0x0c, 0x07, 0x0d, 0x05, 0x0d, 0x06, + 0x0d, 0x07, 0x10, 0x1e, 0x11, 0x1e, 0x00, 0x24, + 0x00, 0x24, 0x2a, 0x06, 0x00, 0x02, 0x1b, 0x00, + 0x03, 0x02, 0x00, 0x03, 0x02, 0x00, 0x03, 0x1b, + 0x00, 0x04, 0x1b, 0x00, 0x1b, 0x02, 0x00, 0x1b, + 0x03, 0x00, 0x1b, 0x04, 0x02, 0x1b, 0x03, 0x02, + 0x1b, 0x03, 0x03, 0x1b, 0x20, 0x03, 0x1b, 0x1f, + 0x09, 0x03, 0x02, 0x09, 0x02, 0x03, 0x09, 0x02, + 0x1f, 0x09, 0x1b, 0x03, 0x09, 0x1b, 0x03, 0x09, + 0x1b, 0x02, 0x09, 0x1b, 0x1b, 0x09, 0x1b, 0x1b, + 0x0b, 0x03, 0x03, 0x0b, 0x03, 0x03, 0x0b, 0x1b, + 0x1b, 0x0a, 0x03, 0x1b, 0x0a, 0x03, 0x1b, 0x0a, + 0x02, 0x20, 0x0a, 0x1b, 0x04, 0x0a, 0x1b, 0x04, + 0x0a, 0x1b, 0x1b, 0x0a, 0x1b, 0x1b, 0x0c, 0x03, + 0x1f, 0x0c, 0x04, 0x1b, 0x0c, 0x04, 0x1b, 0x0d, + 0x1b, 0x03, 0x0d, 0x1b, 0x03, 0x0d, 0x1b, 0x1b, + 0x0d, 0x1b, 0x20, 0x0f, 0x02, 0x1b, 0x0f, 0x1b, + 0x1b, 0x0f, 0x1b, 0x1b, 0x0f, 0x1b, 0x1f, 0x10, + 0x1b, 0x1b, 0x10, 0x1b, 0x20, 0x10, 0x1b, 0x1f, + 0x17, 0x04, 0x1b, 0x17, 0x04, 0x1b, 0x18, 0x1b, + 0x03, 0x18, 0x1b, 0x1b, 0x1a, 0x03, 0x1b, 0x1a, + 0x03, 0x20, 0x1a, 0x03, 0x1f, 0x1a, 0x02, 0x02, + 0x1a, 0x02, 0x02, 0x1a, 0x04, 0x1b, 0x1a, 0x04, + 0x1b, 0x1a, 0x1b, 0x03, 0x1a, 0x1b, 0x03, 0x1b, + 0x03, 0x02, 0x1b, 0x03, 0x1b, 0x1b, 0x03, 0x20, + 0x1b, 0x02, 0x03, 0x1b, 0x02, 0x1b, 0x1b, 0x04, + 0x02, 0x1b, 0x04, 0x1b, 0x28, 0x06, 0x1d, 0x04, + 0x06, 0x1f, 0x1d, 0x04, 0x1f, 0x1d, 0x1d, 0x1e, + 0x05, 0x1d, 0x1e, 0x05, 0x21, 0x1e, 0x04, 0x1d, + 0x1e, 0x04, 0x1d, 0x1e, 0x04, 0x21, 0x1e, 0x1d, + 0x22, 0x1e, 0x1d, 0x21, 0x22, 0x1d, 0x1d, 0x22, + 0x1d, 0x1d, 0x00, 0x06, 0x22, 0x02, 0x04, 0x22, + 0x02, 0x04, 0x21, 0x02, 0x06, 0x22, 0x02, 0x06, + 0x21, 0x02, 0x1d, 0x22, 0x02, 0x1d, 0x21, 0x04, + 0x1d, 0x22, 0x04, 0x05, 0x21, 0x04, 0x1d, 0x21, + 0x0b, 0x06, 0x21, 0x0d, 0x05, 0x22, 0x0c, 0x05, + 0x22, 0x0e, 0x05, 0x22, 0x1c, 0x04, 0x22, 0x1c, + 0x1d, 0x22, 0x22, 0x05, 0x22, 0x22, 0x04, 0x22, + 0x22, 0x1d, 0x22, 0x1d, 0x1d, 0x22, 0x1a, 0x1d, + 0x22, 0x1e, 0x05, 0x22, 0x1a, 0x1d, 0x05, 0x1c, + 0x05, 0x1d, 0x11, 0x1d, 0x22, 0x1b, 0x1d, 0x22, + 0x1e, 0x04, 0x05, 0x1d, 0x06, 0x22, 0x1c, 0x04, + 0x1d, 0x1b, 0x1d, 0x1d, 0x1c, 0x04, 0x1d, 0x1e, + 0x04, 0x05, 0x04, 0x05, 0x22, 0x05, 0x04, 0x22, + 0x1d, 0x04, 0x22, 0x19, 0x1d, 0x22, 0x00, 0x05, + 0x22, 0x1b, 0x1d, 0x1d, 0x11, 0x04, 0x1d, 0x0d, + 0x1d, 0x1d, 0x0b, 0x06, 0x22, 0x1e, 0x04, 0x22, + 0x35, 0x06, 0x00, 0x0f, 0x9d, 0x0d, 0x0f, 0x9d, + 0x27, 0x06, 0x00, 0x1d, 0x1d, 0x20, 0x00, 0x1c, + 0x01, 0x0a, 0x1e, 0x06, 0x1e, 0x08, 0x0e, 0x1d, + 0x12, 0x1e, 0x0a, 0x0c, 0x21, 0x1d, 0x12, 0x1d, + 0x23, 0x20, 0x21, 0x0c, 0x1d, 0x1e, 0x35, 0x06, + 0x00, 0x0f, 0x14, 0x27, 0x06, 0x0e, 0x1d, 0x22, + 0xff, 0x00, 0x1d, 0x1d, 0x20, 0xff, 0x12, 0x1d, + 0x23, 0x20, 0xff, 0x21, 0x0c, 0x1d, 0x1e, 0x27, + 0x06, 0x05, 0x1d, 0xff, 0x05, 0x1d, 0x00, 0x1d, + 0x20, 0x27, 0x06, 0x0a, 0xa5, 0x00, 0x1d, 0x2c, + 0x00, 0x01, 0x30, 0x02, 0x30, 0x3a, 0x00, 0x3b, + 0x00, 0x21, 0x00, 0x3f, 0x00, 0x16, 0x30, 0x17, + 0x30, 0x26, 0x20, 0x13, 0x20, 0x12, 0x01, 0x00, + 0x5f, 0x5f, 0x28, 0x29, 0x7b, 0x7d, 0x08, 0x30, + 0x0c, 0x0d, 0x08, 0x09, 0x02, 0x03, 0x00, 0x01, + 0x04, 0x05, 0x06, 0x07, 0x5b, 0x00, 0x5d, 0x00, + 0x3e, 0x20, 0x3e, 0x20, 0x3e, 0x20, 0x3e, 0x20, + 0x5f, 0x00, 0x5f, 0x00, 0x5f, 0x00, 0x2c, 0x00, + 0x01, 0x30, 0x2e, 0x00, 0x00, 0x00, 0x3b, 0x00, + 0x3a, 0x00, 0x3f, 0x00, 0x21, 0x00, 0x14, 0x20, + 0x28, 0x00, 0x29, 0x00, 0x7b, 0x00, 0x7d, 0x00, + 0x14, 0x30, 0x15, 0x30, 0x23, 0x26, 0x2a, 0x2b, + 0x2d, 0x3c, 0x3e, 0x3d, 0x00, 0x5c, 0x24, 0x25, + 0x40, 0x40, 0x06, 0xff, 0x0b, 0x00, 0x0b, 0xff, + 0x0c, 0x20, 0x00, 0x4d, 0x06, 0x40, 0x06, 0xff, + 0x0e, 0x00, 0x0e, 0xff, 0x0f, 0x00, 0x0f, 0xff, + 0x10, 0x00, 0x10, 0xff, 0x11, 0x00, 0x11, 0xff, + 0x12, 0x00, 0x12, 0x21, 0x06, 0x00, 0x01, 0x01, + 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, + 0x05, 0x05, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, + 0x08, 0x08, 0x09, 0x09, 0x09, 0x09, 0x0a, 0x0a, + 0x0a, 0x0a, 0x0b, 0x0b, 0x0b, 0x0b, 0x0c, 0x0c, + 0x0c, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, + 0x0f, 0x0f, 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, + 0x12, 0x12, 0x13, 0x13, 0x13, 0x13, 0x14, 0x14, + 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, + 0x16, 0x16, 0x17, 0x17, 0x17, 0x17, 0x18, 0x18, + 0x18, 0x18, 0x19, 0x19, 0x19, 0x19, 0x20, 0x20, + 0x20, 0x20, 0x21, 0x21, 0x21, 0x21, 0x22, 0x22, + 0x22, 0x22, 0x23, 0x23, 0x23, 0x23, 0x24, 0x24, + 0x24, 0x24, 0x25, 0x25, 0x25, 0x25, 0x26, 0x26, + 0x26, 0x26, 0x27, 0x27, 0x28, 0x28, 0x29, 0x29, + 0x29, 0x29, 0x22, 0x06, 0x22, 0x00, 0x22, 0x00, + 0x22, 0x01, 0x22, 0x01, 0x22, 0x03, 0x22, 0x03, + 0x22, 0x05, 0x22, 0x05, 0x21, 0x00, 0x85, 0x29, + 0x01, 0x30, 0x01, 0x0b, 0x0c, 0x00, 0xfa, 0xf1, + 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xe2, 0xe4, 0xe6, + 0xc2, 0xfb, 0xa1, 0xa3, 0xa5, 0xa7, 0xa9, 0xaa, + 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, + 0xbc, 0xbe, 0xc0, 0xc3, 0xc5, 0xc7, 0xc9, 0xca, + 0xcb, 0xcc, 0xcd, 0xce, 0xd1, 0xd4, 0xd7, 0xda, + 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xee, 0xf2, 0x98, + 0x99, 0x31, 0x31, 0x4f, 0x31, 0x55, 0x31, 0x5b, + 0x31, 0x61, 0x31, 0xa2, 0x00, 0xa3, 0x00, 0xac, + 0x00, 0xaf, 0x00, 0xa6, 0x00, 0xa5, 0x00, 0xa9, + 0x20, 0x00, 0x00, 0x02, 0x25, 0x90, 0x21, 0x91, + 0x21, 0x92, 0x21, 0x93, 0x21, 0xa0, 0x25, 0xcb, + 0x25, 0xd2, 0x05, 0x07, 0x03, 0x01, 0xda, 0x05, + 0x07, 0x03, 0x01, 0xd0, 0x02, 0xd1, 0x02, 0xe6, + 0x00, 0x99, 0x02, 0x53, 0x02, 0x00, 0x00, 0xa3, + 0x02, 0x66, 0xab, 0xa5, 0x02, 0xa4, 0x02, 0x56, + 0x02, 0x57, 0x02, 0x91, 0x1d, 0x58, 0x02, 0x5e, + 0x02, 0xa9, 0x02, 0x64, 0x02, 0x62, 0x02, 0x60, + 0x02, 0x9b, 0x02, 0x27, 0x01, 0x9c, 0x02, 0x67, + 0x02, 0x84, 0x02, 0xaa, 0x02, 0xab, 0x02, 0x6c, + 0x02, 0x04, 0xdf, 0x8e, 0xa7, 0x6e, 0x02, 0x05, + 0xdf, 0x8e, 0x02, 0x06, 0xdf, 0xf8, 0x00, 0x76, + 0x02, 0x77, 0x02, 0x71, 0x00, 0x7a, 0x02, 0x08, + 0xdf, 0x7d, 0x02, 0x7e, 0x02, 0x80, 0x02, 0xa8, + 0x02, 0xa6, 0x02, 0x67, 0xab, 0xa7, 0x02, 0x88, + 0x02, 0x71, 0x2c, 0x00, 0x00, 0x8f, 0x02, 0xa1, + 0x02, 0xa2, 0x02, 0x98, 0x02, 0xc0, 0x01, 0xc1, + 0x01, 0xc2, 0x01, 0x0a, 0xdf, 0x1e, 0xdf, 0x41, + 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x14, 0x99, + 0x10, 0xba, 0x10, 0x00, 0x00, 0x00, 0x00, 0x9b, + 0x10, 0xba, 0x10, 0x05, 0x05, 0xa5, 0x10, 0xba, + 0x10, 0x05, 0x31, 0x11, 0x27, 0x11, 0x32, 0x11, + 0x27, 0x11, 0x55, 0x47, 0x13, 0x3e, 0x13, 0x47, + 0x13, 0x57, 0x13, 0x55, 0x82, 0x13, 0xc9, 0x13, + 0x00, 0x00, 0x00, 0x00, 0x84, 0x13, 0xbb, 0x13, + 0x05, 0x05, 0x8b, 0x13, 0xc2, 0x13, 0x05, 0x90, + 0x13, 0xc9, 0x13, 0x05, 0xc2, 0x13, 0xc2, 0x13, + 0x00, 0x00, 0x00, 0x00, 0xc2, 0x13, 0xb8, 0x13, + 0xc2, 0x13, 0xc9, 0x13, 0x05, 0x55, 0xb9, 0x14, + 0xba, 0x14, 0xb9, 0x14, 0xb0, 0x14, 0x00, 0x00, + 0x00, 0x00, 0xb9, 0x14, 0xbd, 0x14, 0x55, 0x50, + 0xb8, 0x15, 0xaf, 0x15, 0xb9, 0x15, 0xaf, 0x15, + 0x55, 0x35, 0x19, 0x30, 0x19, 0x05, 0x1e, 0x61, + 0x1e, 0x61, 0x1e, 0x61, 0x29, 0x61, 0x1e, 0x61, + 0x1f, 0x61, 0x29, 0x61, 0x1f, 0x61, 0x1e, 0x61, + 0x20, 0x61, 0x21, 0x61, 0x1f, 0x61, 0x22, 0x61, + 0x1f, 0x61, 0x21, 0x61, 0x20, 0x61, 0x55, 0x55, + 0x55, 0x55, 0x67, 0x6d, 0x67, 0x6d, 0x63, 0x6d, + 0x67, 0x6d, 0x69, 0x6d, 0x67, 0x6d, 0x55, 0x05, + 0x41, 0x00, 0x30, 0x00, 0x57, 0xd1, 0x65, 0xd1, + 0x58, 0xd1, 0x65, 0xd1, 0x5f, 0xd1, 0x6e, 0xd1, + 0x5f, 0xd1, 0x6f, 0xd1, 0x5f, 0xd1, 0x70, 0xd1, + 0x5f, 0xd1, 0x71, 0xd1, 0x5f, 0xd1, 0x72, 0xd1, + 0x55, 0x55, 0x55, 0x05, 0xb9, 0xd1, 0x65, 0xd1, + 0xba, 0xd1, 0x65, 0xd1, 0xbb, 0xd1, 0x6e, 0xd1, + 0xbc, 0xd1, 0x6e, 0xd1, 0xbb, 0xd1, 0x6f, 0xd1, + 0xbc, 0xd1, 0x6f, 0xd1, 0x55, 0x55, 0x55, 0x41, + 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x69, + 0x00, 0x41, 0x00, 0x61, 0x00, 0x41, 0x00, 0x43, + 0x44, 0x00, 0x00, 0x47, 0x00, 0x00, 0x4a, 0x4b, + 0x00, 0x00, 0x4e, 0x4f, 0x50, 0x51, 0x00, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, + 0x62, 0x63, 0x64, 0x00, 0x66, 0x68, 0x00, 0x70, + 0x00, 0x41, 0x00, 0x61, 0x00, 0x41, 0x42, 0x00, + 0x44, 0x45, 0x46, 0x47, 0x4a, 0x00, 0x53, 0x00, + 0x61, 0x00, 0x41, 0x42, 0x00, 0x44, 0x45, 0x46, + 0x47, 0x00, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x00, + 0x4f, 0x53, 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, + 0x00, 0x41, 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, + 0x00, 0x41, 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, + 0x00, 0x41, 0x00, 0x61, 0x00, 0x31, 0x01, 0x37, + 0x02, 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, + 0x03, 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05, 0x91, + 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24, + 0x00, 0x1f, 0x04, 0x20, 0x05, 0x91, 0x03, 0xa3, + 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f, + 0x04, 0x20, 0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1, + 0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f, 0x04, 0x20, + 0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, + 0x03, 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05, 0x0b, + 0x0c, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, + 0x00, 0x30, 0x00, 0x30, 0x04, 0x3a, 0x04, 0x3e, + 0x04, 0x4b, 0x04, 0x4d, 0x04, 0x4e, 0x04, 0x89, + 0xa6, 0x30, 0x04, 0xa9, 0x26, 0x28, 0xb9, 0x7f, + 0x9f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x08, 0x0a, 0x0b, 0x0e, 0x0f, 0x11, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x1a, 0x1b, 0x61, + 0x26, 0x25, 0x2f, 0x7b, 0x51, 0xa6, 0xb1, 0x04, + 0x27, 0x06, 0x00, 0x01, 0x05, 0x08, 0x2a, 0x06, + 0x1e, 0x08, 0x03, 0x0d, 0x20, 0x19, 0x1a, 0x1b, + 0x1c, 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07, 0x0a, + 0x00, 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10, 0x44, + 0x90, 0x77, 0x45, 0x28, 0x06, 0x2c, 0x06, 0x00, + 0x00, 0x47, 0x06, 0x33, 0x06, 0x17, 0x10, 0x11, + 0x12, 0x13, 0x00, 0x06, 0x0e, 0x02, 0x0f, 0x34, + 0x06, 0x2a, 0x06, 0x2b, 0x06, 0x2e, 0x06, 0x00, + 0x00, 0x36, 0x06, 0x00, 0x00, 0x3a, 0x06, 0x2d, + 0x06, 0x00, 0x00, 0x4a, 0x06, 0x00, 0x00, 0x44, + 0x06, 0x00, 0x00, 0x46, 0x06, 0x33, 0x06, 0x39, + 0x06, 0x00, 0x00, 0x35, 0x06, 0x42, 0x06, 0x00, + 0x00, 0x34, 0x06, 0x00, 0x00, 0x00, 0x00, 0x2e, + 0x06, 0x00, 0x00, 0x36, 0x06, 0x00, 0x00, 0x3a, + 0x06, 0x00, 0x00, 0xba, 0x06, 0x00, 0x00, 0x6f, + 0x06, 0x00, 0x00, 0x28, 0x06, 0x2c, 0x06, 0x00, + 0x00, 0x47, 0x06, 0x00, 0x00, 0x00, 0x00, 0x2d, + 0x06, 0x37, 0x06, 0x4a, 0x06, 0x43, 0x06, 0x00, + 0x00, 0x45, 0x06, 0x46, 0x06, 0x33, 0x06, 0x39, + 0x06, 0x41, 0x06, 0x35, 0x06, 0x42, 0x06, 0x00, + 0x00, 0x34, 0x06, 0x2a, 0x06, 0x2b, 0x06, 0x2e, + 0x06, 0x00, 0x00, 0x36, 0x06, 0x38, 0x06, 0x3a, + 0x06, 0x6e, 0x06, 0x00, 0x00, 0xa1, 0x06, 0x27, + 0x06, 0x00, 0x01, 0x05, 0x08, 0x20, 0x21, 0x0b, + 0x06, 0x10, 0x23, 0x2a, 0x06, 0x1a, 0x1b, 0x1c, + 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07, 0x0a, 0x00, + 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10, 0x28, 0x06, + 0x2c, 0x06, 0x2f, 0x06, 0x00, 0x00, 0x48, 0x06, + 0x32, 0x06, 0x2d, 0x06, 0x37, 0x06, 0x4a, 0x06, + 0x2a, 0x06, 0x1a, 0x1b, 0x1c, 0x09, 0x0f, 0x17, + 0x0b, 0x18, 0x07, 0x0a, 0x00, 0x01, 0x04, 0x06, + 0x0c, 0x0e, 0x10, 0x30, 0x2e, 0x30, 0x00, 0x2c, + 0x00, 0x28, 0x00, 0x41, 0x00, 0x29, 0x00, 0x14, + 0x30, 0x53, 0x00, 0x15, 0x30, 0x43, 0x52, 0x43, + 0x44, 0x57, 0x5a, 0x41, 0x00, 0x48, 0x56, 0x4d, + 0x56, 0x53, 0x44, 0x53, 0x53, 0x50, 0x50, 0x56, + 0x57, 0x43, 0x4d, 0x43, 0x4d, 0x44, 0x4d, 0x52, + 0x44, 0x4a, 0x4b, 0x30, 0x30, 0x00, 0x68, 0x68, + 0x4b, 0x62, 0x57, 0x5b, 0xcc, 0x53, 0xc7, 0x30, + 0x8c, 0x4e, 0x1a, 0x59, 0xe3, 0x89, 0x29, 0x59, + 0xa4, 0x4e, 0x20, 0x66, 0x21, 0x71, 0x99, 0x65, + 0x4d, 0x52, 0x8c, 0x5f, 0x8d, 0x51, 0xb0, 0x65, + 0x1d, 0x52, 0x42, 0x7d, 0x1f, 0x75, 0xa9, 0x8c, + 0xf0, 0x58, 0x39, 0x54, 0x14, 0x6f, 0x95, 0x62, + 0x55, 0x63, 0x00, 0x4e, 0x09, 0x4e, 0x4a, 0x90, + 0xe6, 0x5d, 0x2d, 0x4e, 0xf3, 0x53, 0x07, 0x63, + 0x70, 0x8d, 0x53, 0x62, 0x81, 0x79, 0x7a, 0x7a, + 0x08, 0x54, 0x80, 0x6e, 0x09, 0x67, 0x08, 0x67, + 0x33, 0x75, 0x72, 0x52, 0xb6, 0x55, 0x4d, 0x91, + 0x14, 0x30, 0x15, 0x30, 0x2c, 0x67, 0x09, 0x4e, + 0x8c, 0x4e, 0x89, 0x5b, 0xb9, 0x70, 0x53, 0x62, + 0xd7, 0x76, 0xdd, 0x52, 0x57, 0x65, 0x97, 0x5f, + 0xef, 0x53, 0x30, 0x00, 0x38, 0x4e, 0x05, 0x00, + 0x09, 0x22, 0x01, 0x60, 0x4f, 0xae, 0x4f, 0xbb, + 0x4f, 0x02, 0x50, 0x7a, 0x50, 0x99, 0x50, 0xe7, + 0x50, 0xcf, 0x50, 0x9e, 0x34, 0x3a, 0x06, 0x4d, + 0x51, 0x54, 0x51, 0x64, 0x51, 0x77, 0x51, 0x1c, + 0x05, 0xb9, 0x34, 0x67, 0x51, 0x8d, 0x51, 0x4b, + 0x05, 0x97, 0x51, 0xa4, 0x51, 0xcc, 0x4e, 0xac, + 0x51, 0xb5, 0x51, 0xdf, 0x91, 0xf5, 0x51, 0x03, + 0x52, 0xdf, 0x34, 0x3b, 0x52, 0x46, 0x52, 0x72, + 0x52, 0x77, 0x52, 0x15, 0x35, 0x02, 0x00, 0x20, + 0x80, 0x80, 0x00, 0x08, 0x00, 0x00, 0xc7, 0x52, + 0x00, 0x02, 0x1d, 0x33, 0x3e, 0x3f, 0x50, 0x82, + 0x8a, 0x93, 0xac, 0xb6, 0xb8, 0xb8, 0xb8, 0x2c, + 0x0a, 0x70, 0x70, 0xca, 0x53, 0xdf, 0x53, 0x63, + 0x0b, 0xeb, 0x53, 0xf1, 0x53, 0x06, 0x54, 0x9e, + 0x54, 0x38, 0x54, 0x48, 0x54, 0x68, 0x54, 0xa2, + 0x54, 0xf6, 0x54, 0x10, 0x55, 0x53, 0x55, 0x63, + 0x55, 0x84, 0x55, 0x84, 0x55, 0x99, 0x55, 0xab, + 0x55, 0xb3, 0x55, 0xc2, 0x55, 0x16, 0x57, 0x06, + 0x56, 0x17, 0x57, 0x51, 0x56, 0x74, 0x56, 0x07, + 0x52, 0xee, 0x58, 0xce, 0x57, 0xf4, 0x57, 0x0d, + 0x58, 0x8b, 0x57, 0x32, 0x58, 0x31, 0x58, 0xac, + 0x58, 0xe4, 0x14, 0xf2, 0x58, 0xf7, 0x58, 0x06, + 0x59, 0x1a, 0x59, 0x22, 0x59, 0x62, 0x59, 0xa8, + 0x16, 0xea, 0x16, 0xec, 0x59, 0x1b, 0x5a, 0x27, + 0x5a, 0xd8, 0x59, 0x66, 0x5a, 0xee, 0x36, 0xfc, + 0x36, 0x08, 0x5b, 0x3e, 0x5b, 0x3e, 0x5b, 0xc8, + 0x19, 0xc3, 0x5b, 0xd8, 0x5b, 0xe7, 0x5b, 0xf3, + 0x5b, 0x18, 0x1b, 0xff, 0x5b, 0x06, 0x5c, 0x53, + 0x5f, 0x22, 0x5c, 0x81, 0x37, 0x60, 0x5c, 0x6e, + 0x5c, 0xc0, 0x5c, 0x8d, 0x5c, 0xe4, 0x1d, 0x43, + 0x5d, 0xe6, 0x1d, 0x6e, 0x5d, 0x6b, 0x5d, 0x7c, + 0x5d, 0xe1, 0x5d, 0xe2, 0x5d, 0x2f, 0x38, 0xfd, + 0x5d, 0x28, 0x5e, 0x3d, 0x5e, 0x69, 0x5e, 0x62, + 0x38, 0x83, 0x21, 0x7c, 0x38, 0xb0, 0x5e, 0xb3, + 0x5e, 0xb6, 0x5e, 0xca, 0x5e, 0x92, 0xa3, 0xfe, + 0x5e, 0x31, 0x23, 0x31, 0x23, 0x01, 0x82, 0x22, + 0x5f, 0x22, 0x5f, 0xc7, 0x38, 0xb8, 0x32, 0xda, + 0x61, 0x62, 0x5f, 0x6b, 0x5f, 0xe3, 0x38, 0x9a, + 0x5f, 0xcd, 0x5f, 0xd7, 0x5f, 0xf9, 0x5f, 0x81, + 0x60, 0x3a, 0x39, 0x1c, 0x39, 0x94, 0x60, 0xd4, + 0x26, 0xc7, 0x60, 0x02, 0x02, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, + 0x00, 0x02, 0x08, 0x00, 0x80, 0x08, 0x00, 0x00, + 0x08, 0x80, 0x28, 0x80, 0x02, 0x00, 0x00, 0x02, + 0x48, 0x61, 0x00, 0x04, 0x06, 0x04, 0x32, 0x46, + 0x6a, 0x5c, 0x67, 0x96, 0xaa, 0xae, 0xc8, 0xd3, + 0x5d, 0x62, 0x00, 0x54, 0x77, 0xf3, 0x0c, 0x2b, + 0x3d, 0x63, 0xfc, 0x62, 0x68, 0x63, 0x83, 0x63, + 0xe4, 0x63, 0xf1, 0x2b, 0x22, 0x64, 0xc5, 0x63, + 0xa9, 0x63, 0x2e, 0x3a, 0x69, 0x64, 0x7e, 0x64, + 0x9d, 0x64, 0x77, 0x64, 0x6c, 0x3a, 0x4f, 0x65, + 0x6c, 0x65, 0x0a, 0x30, 0xe3, 0x65, 0xf8, 0x66, + 0x49, 0x66, 0x19, 0x3b, 0x91, 0x66, 0x08, 0x3b, + 0xe4, 0x3a, 0x92, 0x51, 0x95, 0x51, 0x00, 0x67, + 0x9c, 0x66, 0xad, 0x80, 0xd9, 0x43, 0x17, 0x67, + 0x1b, 0x67, 0x21, 0x67, 0x5e, 0x67, 0x53, 0x67, + 0xc3, 0x33, 0x49, 0x3b, 0xfa, 0x67, 0x85, 0x67, + 0x52, 0x68, 0x85, 0x68, 0x6d, 0x34, 0x8e, 0x68, + 0x1f, 0x68, 0x14, 0x69, 0x9d, 0x3b, 0x42, 0x69, + 0xa3, 0x69, 0xea, 0x69, 0xa8, 0x6a, 0xa3, 0x36, + 0xdb, 0x6a, 0x18, 0x3c, 0x21, 0x6b, 0xa7, 0x38, + 0x54, 0x6b, 0x4e, 0x3c, 0x72, 0x6b, 0x9f, 0x6b, + 0xba, 0x6b, 0xbb, 0x6b, 0x8d, 0x3a, 0x0b, 0x1d, + 0xfa, 0x3a, 0x4e, 0x6c, 0xbc, 0x3c, 0xbf, 0x6c, + 0xcd, 0x6c, 0x67, 0x6c, 0x16, 0x6d, 0x3e, 0x6d, + 0x77, 0x6d, 0x41, 0x6d, 0x69, 0x6d, 0x78, 0x6d, + 0x85, 0x6d, 0x1e, 0x3d, 0x34, 0x6d, 0x2f, 0x6e, + 0x6e, 0x6e, 0x33, 0x3d, 0xcb, 0x6e, 0xc7, 0x6e, + 0xd1, 0x3e, 0xf9, 0x6d, 0x6e, 0x6f, 0x5e, 0x3f, + 0x8e, 0x3f, 0xc6, 0x6f, 0x39, 0x70, 0x1e, 0x70, + 0x1b, 0x70, 0x96, 0x3d, 0x4a, 0x70, 0x7d, 0x70, + 0x77, 0x70, 0xad, 0x70, 0x25, 0x05, 0x45, 0x71, + 0x63, 0x42, 0x9c, 0x71, 0xab, 0x43, 0x28, 0x72, + 0x35, 0x72, 0x50, 0x72, 0x08, 0x46, 0x80, 0x72, + 0x95, 0x72, 0x35, 0x47, 0x02, 0x20, 0x00, 0x00, + 0x20, 0x00, 0x00, 0x00, 0x00, 0x08, 0x80, 0x00, + 0x00, 0x02, 0x02, 0x80, 0x8a, 0x00, 0x00, 0x20, + 0x00, 0x08, 0x0a, 0x00, 0x80, 0x88, 0x80, 0x20, + 0x14, 0x48, 0x7a, 0x73, 0x8b, 0x73, 0xac, 0x3e, + 0xa5, 0x73, 0xb8, 0x3e, 0xb8, 0x3e, 0x47, 0x74, + 0x5c, 0x74, 0x71, 0x74, 0x85, 0x74, 0xca, 0x74, + 0x1b, 0x3f, 0x24, 0x75, 0x36, 0x4c, 0x3e, 0x75, + 0x92, 0x4c, 0x70, 0x75, 0x9f, 0x21, 0x10, 0x76, + 0xa1, 0x4f, 0xb8, 0x4f, 0x44, 0x50, 0xfc, 0x3f, + 0x08, 0x40, 0xf4, 0x76, 0xf3, 0x50, 0xf2, 0x50, + 0x19, 0x51, 0x33, 0x51, 0x1e, 0x77, 0x1f, 0x77, + 0x1f, 0x77, 0x4a, 0x77, 0x39, 0x40, 0x8b, 0x77, + 0x46, 0x40, 0x96, 0x40, 0x1d, 0x54, 0x4e, 0x78, + 0x8c, 0x78, 0xcc, 0x78, 0xe3, 0x40, 0x26, 0x56, + 0x56, 0x79, 0x9a, 0x56, 0xc5, 0x56, 0x8f, 0x79, + 0xeb, 0x79, 0x2f, 0x41, 0x40, 0x7a, 0x4a, 0x7a, + 0x4f, 0x7a, 0x7c, 0x59, 0xa7, 0x5a, 0xa7, 0x5a, + 0xee, 0x7a, 0x02, 0x42, 0xab, 0x5b, 0xc6, 0x7b, + 0xc9, 0x7b, 0x27, 0x42, 0x80, 0x5c, 0xd2, 0x7c, + 0xa0, 0x42, 0xe8, 0x7c, 0xe3, 0x7c, 0x00, 0x7d, + 0x86, 0x5f, 0x63, 0x7d, 0x01, 0x43, 0xc7, 0x7d, + 0x02, 0x7e, 0x45, 0x7e, 0x34, 0x43, 0x28, 0x62, + 0x47, 0x62, 0x59, 0x43, 0xd9, 0x62, 0x7a, 0x7f, + 0x3e, 0x63, 0x95, 0x7f, 0xfa, 0x7f, 0x05, 0x80, + 0xda, 0x64, 0x23, 0x65, 0x60, 0x80, 0xa8, 0x65, + 0x70, 0x80, 0x5f, 0x33, 0xd5, 0x43, 0xb2, 0x80, + 0x03, 0x81, 0x0b, 0x44, 0x3e, 0x81, 0xb5, 0x5a, + 0xa7, 0x67, 0xb5, 0x67, 0x93, 0x33, 0x9c, 0x33, + 0x01, 0x82, 0x04, 0x82, 0x9e, 0x8f, 0x6b, 0x44, + 0x91, 0x82, 0x8b, 0x82, 0x9d, 0x82, 0xb3, 0x52, + 0xb1, 0x82, 0xb3, 0x82, 0xbd, 0x82, 0xe6, 0x82, + 0x3c, 0x6b, 0xe5, 0x82, 0x1d, 0x83, 0x63, 0x83, + 0xad, 0x83, 0x23, 0x83, 0xbd, 0x83, 0xe7, 0x83, + 0x57, 0x84, 0x53, 0x83, 0xca, 0x83, 0xcc, 0x83, + 0xdc, 0x83, 0x36, 0x6c, 0x6b, 0x6d, 0x02, 0x00, + 0x00, 0x20, 0x22, 0x2a, 0xa0, 0x0a, 0x00, 0x20, + 0x80, 0x28, 0x00, 0xa8, 0x20, 0x20, 0x00, 0x02, + 0x80, 0x22, 0x02, 0x8a, 0x08, 0x00, 0xaa, 0x00, + 0x00, 0x00, 0x02, 0x00, 0x00, 0x28, 0xd5, 0x6c, + 0x2b, 0x45, 0xf1, 0x84, 0xf3, 0x84, 0x16, 0x85, + 0xca, 0x73, 0x64, 0x85, 0x2c, 0x6f, 0x5d, 0x45, + 0x61, 0x45, 0xb1, 0x6f, 0xd2, 0x70, 0x6b, 0x45, + 0x50, 0x86, 0x5c, 0x86, 0x67, 0x86, 0x69, 0x86, + 0xa9, 0x86, 0x88, 0x86, 0x0e, 0x87, 0xe2, 0x86, + 0x79, 0x87, 0x28, 0x87, 0x6b, 0x87, 0x86, 0x87, + 0xd7, 0x45, 0xe1, 0x87, 0x01, 0x88, 0xf9, 0x45, + 0x60, 0x88, 0x63, 0x88, 0x67, 0x76, 0xd7, 0x88, + 0xde, 0x88, 0x35, 0x46, 0xfa, 0x88, 0xbb, 0x34, + 0xae, 0x78, 0x66, 0x79, 0xbe, 0x46, 0xc7, 0x46, + 0xa0, 0x8a, 0xed, 0x8a, 0x8a, 0x8b, 0x55, 0x8c, + 0xa8, 0x7c, 0xab, 0x8c, 0xc1, 0x8c, 0x1b, 0x8d, + 0x77, 0x8d, 0x2f, 0x7f, 0x04, 0x08, 0xcb, 0x8d, + 0xbc, 0x8d, 0xf0, 0x8d, 0xde, 0x08, 0xd4, 0x8e, + 0x38, 0x8f, 0xd2, 0x85, 0xed, 0x85, 0x94, 0x90, + 0xf1, 0x90, 0x11, 0x91, 0x2e, 0x87, 0x1b, 0x91, + 0x38, 0x92, 0xd7, 0x92, 0xd8, 0x92, 0x7c, 0x92, + 0xf9, 0x93, 0x15, 0x94, 0xfa, 0x8b, 0x8b, 0x95, + 0x95, 0x49, 0xb7, 0x95, 0x77, 0x8d, 0xe6, 0x49, + 0xc3, 0x96, 0xb2, 0x5d, 0x23, 0x97, 0x45, 0x91, + 0x1a, 0x92, 0x6e, 0x4a, 0x76, 0x4a, 0xe0, 0x97, + 0x0a, 0x94, 0xb2, 0x4a, 0x96, 0x94, 0x0b, 0x98, + 0x0b, 0x98, 0x29, 0x98, 0xb6, 0x95, 0xe2, 0x98, + 0x33, 0x4b, 0x29, 0x99, 0xa7, 0x99, 0xc2, 0x99, + 0xfe, 0x99, 0xce, 0x4b, 0x30, 0x9b, 0x12, 0x9b, + 0x40, 0x9c, 0xfd, 0x9c, 0xce, 0x4c, 0xed, 0x4c, + 0x67, 0x9d, 0xce, 0xa0, 0xf8, 0x4c, 0x05, 0xa1, + 0x0e, 0xa2, 0x91, 0xa2, 0xbb, 0x9e, 0x56, 0x4d, + 0xf9, 0x9e, 0xfe, 0x9e, 0x05, 0x9f, 0x0f, 0x9f, + 0x16, 0x9f, 0x3b, 0x9f, 0x00, 0xa6, 0x02, 0x88, + 0xa0, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x28, + 0x00, 0x08, 0xa0, 0x80, 0xa0, 0x80, 0x00, 0x80, + 0x80, 0x00, 0x0a, 0x88, 0x80, 0x00, 0x80, 0x00, + 0x20, 0x2a, 0x00, 0x80, +}; + +static const uint16_t unicode_comp_table[965] = { + 0x4a01, 0x49c0, 0x4a02, 0x0280, 0x0281, 0x0282, 0x0283, 0x02c0, + 0x02c2, 0x0a00, 0x0284, 0x2442, 0x0285, 0x07c0, 0x0980, 0x0982, + 0x2440, 0x2280, 0x02c4, 0x2282, 0x2284, 0x2286, 0x02c6, 0x02c8, + 0x02ca, 0x02cc, 0x0287, 0x228a, 0x02ce, 0x228c, 0x2290, 0x2292, + 0x228e, 0x0288, 0x0289, 0x028a, 0x2482, 0x0300, 0x0302, 0x0304, + 0x028b, 0x2480, 0x0308, 0x0984, 0x0986, 0x2458, 0x0a02, 0x0306, + 0x2298, 0x229a, 0x229e, 0x0900, 0x030a, 0x22a0, 0x030c, 0x030e, + 0x0840, 0x0310, 0x0312, 0x22a2, 0x22a6, 0x09c0, 0x22a4, 0x22a8, + 0x22aa, 0x028c, 0x028d, 0x028e, 0x0340, 0x0342, 0x0344, 0x0380, + 0x028f, 0x248e, 0x07c2, 0x0988, 0x098a, 0x2490, 0x0346, 0x22ac, + 0x0400, 0x22b0, 0x0842, 0x22b2, 0x0402, 0x22b4, 0x0440, 0x0444, + 0x22b6, 0x0442, 0x22c2, 0x22c0, 0x22c4, 0x22c6, 0x22c8, 0x0940, + 0x04c0, 0x0291, 0x22ca, 0x04c4, 0x22cc, 0x04c2, 0x22d0, 0x22ce, + 0x0292, 0x0293, 0x0294, 0x0295, 0x0540, 0x0542, 0x0a08, 0x0296, + 0x2494, 0x0544, 0x07c4, 0x098c, 0x098e, 0x06c0, 0x2492, 0x0844, + 0x2308, 0x230a, 0x0580, 0x230c, 0x0584, 0x0990, 0x0992, 0x230e, + 0x0582, 0x2312, 0x0586, 0x0588, 0x2314, 0x058c, 0x2316, 0x0998, + 0x058a, 0x231e, 0x0590, 0x2320, 0x099a, 0x058e, 0x2324, 0x2322, + 0x0299, 0x029a, 0x029b, 0x05c0, 0x05c2, 0x05c4, 0x029c, 0x24ac, + 0x05c6, 0x05c8, 0x07c6, 0x0994, 0x0996, 0x0700, 0x24aa, 0x2326, + 0x05ca, 0x232a, 0x2328, 0x2340, 0x2342, 0x2344, 0x2346, 0x05cc, + 0x234a, 0x2348, 0x234c, 0x234e, 0x2350, 0x24b8, 0x029d, 0x05ce, + 0x24be, 0x0a0c, 0x2352, 0x0600, 0x24bc, 0x24ba, 0x0640, 0x2354, + 0x0642, 0x0644, 0x2356, 0x2358, 0x02a0, 0x02a1, 0x02a2, 0x02a3, + 0x02c1, 0x02c3, 0x0a01, 0x02a4, 0x2443, 0x02a5, 0x07c1, 0x0981, + 0x0983, 0x2441, 0x2281, 0x02c5, 0x2283, 0x2285, 0x2287, 0x02c7, + 0x02c9, 0x02cb, 0x02cd, 0x02a7, 0x228b, 0x02cf, 0x228d, 0x2291, + 0x2293, 0x228f, 0x02a8, 0x02a9, 0x02aa, 0x2483, 0x0301, 0x0303, + 0x0305, 0x02ab, 0x2481, 0x0309, 0x0985, 0x0987, 0x2459, 0x0a03, + 0x0307, 0x2299, 0x229b, 0x229f, 0x0901, 0x030b, 0x22a1, 0x030d, + 0x030f, 0x0841, 0x0311, 0x0313, 0x22a3, 0x22a7, 0x09c1, 0x22a5, + 0x22a9, 0x22ab, 0x2380, 0x02ac, 0x02ad, 0x02ae, 0x0341, 0x0343, + 0x0345, 0x02af, 0x248f, 0x07c3, 0x0989, 0x098b, 0x2491, 0x0347, + 0x22ad, 0x0401, 0x0884, 0x22b1, 0x0843, 0x22b3, 0x0403, 0x22b5, + 0x0441, 0x0445, 0x22b7, 0x0443, 0x22c3, 0x22c1, 0x22c5, 0x22c7, + 0x22c9, 0x0941, 0x04c1, 0x02b1, 0x22cb, 0x04c5, 0x22cd, 0x04c3, + 0x22d1, 0x22cf, 0x02b2, 0x02b3, 0x02b4, 0x02b5, 0x0541, 0x0543, + 0x0a09, 0x02b6, 0x2495, 0x0545, 0x07c5, 0x098d, 0x098f, 0x06c1, + 0x2493, 0x0845, 0x2309, 0x230b, 0x0581, 0x230d, 0x0585, 0x0991, + 0x0993, 0x230f, 0x0583, 0x2313, 0x0587, 0x0589, 0x2315, 0x058d, + 0x2317, 0x0999, 0x058b, 0x231f, 0x2381, 0x0591, 0x2321, 0x099b, + 0x058f, 0x2325, 0x2323, 0x02b9, 0x02ba, 0x02bb, 0x05c1, 0x05c3, + 0x05c5, 0x02bc, 0x24ad, 0x05c7, 0x05c9, 0x07c7, 0x0995, 0x0997, + 0x0701, 0x24ab, 0x2327, 0x05cb, 0x232b, 0x2329, 0x2341, 0x2343, + 0x2345, 0x2347, 0x05cd, 0x234b, 0x2349, 0x2382, 0x234d, 0x234f, + 0x2351, 0x24b9, 0x02bd, 0x05cf, 0x24bf, 0x0a0d, 0x2353, 0x02bf, + 0x24bd, 0x2383, 0x24bb, 0x0641, 0x2355, 0x0643, 0x0645, 0x2357, + 0x2359, 0x3101, 0x0c80, 0x2e00, 0x2446, 0x2444, 0x244a, 0x2448, + 0x0800, 0x0942, 0x0944, 0x0804, 0x2288, 0x2486, 0x2484, 0x248a, + 0x2488, 0x22ae, 0x2498, 0x2496, 0x249c, 0x249a, 0x2300, 0x0a06, + 0x2302, 0x0a04, 0x0946, 0x07ce, 0x07ca, 0x07c8, 0x07cc, 0x2447, + 0x2445, 0x244b, 0x2449, 0x0801, 0x0943, 0x0945, 0x0805, 0x2289, + 0x2487, 0x2485, 0x248b, 0x2489, 0x22af, 0x2499, 0x2497, 0x249d, + 0x249b, 0x2301, 0x0a07, 0x2303, 0x0a05, 0x0947, 0x07cf, 0x07cb, + 0x07c9, 0x07cd, 0x2450, 0x244e, 0x2454, 0x2452, 0x2451, 0x244f, + 0x2455, 0x2453, 0x2294, 0x2296, 0x2295, 0x2297, 0x2304, 0x2306, + 0x2305, 0x2307, 0x2318, 0x2319, 0x231a, 0x231b, 0x232c, 0x232d, + 0x232e, 0x232f, 0x2400, 0x24a2, 0x24a0, 0x24a6, 0x24a4, 0x24a8, + 0x24a3, 0x24a1, 0x24a7, 0x24a5, 0x24a9, 0x24b0, 0x24ae, 0x24b4, + 0x24b2, 0x24b6, 0x24b1, 0x24af, 0x24b5, 0x24b3, 0x24b7, 0x0882, + 0x0880, 0x0881, 0x0802, 0x0803, 0x229c, 0x229d, 0x0a0a, 0x0a0b, + 0x0883, 0x0b40, 0x2c8a, 0x0c81, 0x2c89, 0x2c88, 0x2540, 0x2541, + 0x2d00, 0x2e07, 0x0d00, 0x2640, 0x2641, 0x2e80, 0x0d01, 0x26c8, + 0x26c9, 0x2f00, 0x2f84, 0x0d02, 0x2f83, 0x2f82, 0x0d40, 0x26d8, + 0x26d9, 0x3186, 0x0d04, 0x2740, 0x2741, 0x3100, 0x3086, 0x0d06, + 0x3085, 0x3084, 0x0d41, 0x2840, 0x3200, 0x0d07, 0x284f, 0x2850, + 0x3280, 0x2c84, 0x2e03, 0x2857, 0x0d42, 0x2c81, 0x2c80, 0x24c0, + 0x24c1, 0x2c86, 0x2c83, 0x28c0, 0x0d43, 0x25c0, 0x25c1, 0x2940, + 0x0d44, 0x26c0, 0x26c1, 0x2e05, 0x2e02, 0x29c0, 0x0d45, 0x2f05, + 0x2f04, 0x0d80, 0x26d0, 0x26d1, 0x2f80, 0x2a40, 0x0d82, 0x26e0, + 0x26e1, 0x3080, 0x3081, 0x2ac0, 0x0d83, 0x3004, 0x3003, 0x0d81, + 0x27c0, 0x27c1, 0x3082, 0x2b40, 0x0d84, 0x2847, 0x2848, 0x3184, + 0x3181, 0x2f06, 0x0d08, 0x2f81, 0x3005, 0x0d46, 0x3083, 0x3182, + 0x0e00, 0x0e01, 0x0f40, 0x1180, 0x1182, 0x0f03, 0x0f00, 0x11c0, + 0x0f01, 0x1140, 0x1202, 0x1204, 0x0f81, 0x1240, 0x0fc0, 0x1242, + 0x0f80, 0x1244, 0x1284, 0x0f82, 0x1286, 0x1288, 0x128a, 0x12c0, + 0x1282, 0x1181, 0x1183, 0x1043, 0x1040, 0x11c1, 0x1041, 0x1141, + 0x1203, 0x1205, 0x10c1, 0x1241, 0x1000, 0x1243, 0x10c0, 0x1245, + 0x1285, 0x10c2, 0x1287, 0x1289, 0x128b, 0x12c1, 0x1283, 0x1080, + 0x1100, 0x1101, 0x1200, 0x1201, 0x1280, 0x1281, 0x1340, 0x1341, + 0x1343, 0x1342, 0x1344, 0x13c2, 0x1400, 0x13c0, 0x1440, 0x1480, + 0x14c0, 0x1540, 0x1541, 0x1740, 0x1700, 0x1741, 0x17c0, 0x1800, + 0x1802, 0x1801, 0x1840, 0x1880, 0x1900, 0x18c0, 0x18c1, 0x1901, + 0x1940, 0x1942, 0x1941, 0x1980, 0x19c0, 0x19c2, 0x19c1, 0x1c80, + 0x1cc0, 0x1dc0, 0x1f80, 0x2000, 0x2002, 0x2004, 0x2006, 0x2008, + 0x2040, 0x2080, 0x2082, 0x20c0, 0x20c1, 0x2100, 0x22b8, 0x22b9, + 0x2310, 0x2311, 0x231c, 0x231d, 0x244c, 0x2456, 0x244d, 0x2457, + 0x248c, 0x248d, 0x249e, 0x249f, 0x2500, 0x2502, 0x2504, 0x2bc0, + 0x2501, 0x2503, 0x2505, 0x2bc1, 0x2bc2, 0x2bc3, 0x2bc4, 0x2bc5, + 0x2bc6, 0x2bc7, 0x2580, 0x2582, 0x2584, 0x2bc8, 0x2581, 0x2583, + 0x2585, 0x2bc9, 0x2bca, 0x2bcb, 0x2bcc, 0x2bcd, 0x2bce, 0x2bcf, + 0x2600, 0x2602, 0x2601, 0x2603, 0x2680, 0x2682, 0x2681, 0x2683, + 0x26c2, 0x26c4, 0x26c6, 0x2c00, 0x26c3, 0x26c5, 0x26c7, 0x2c01, + 0x2c02, 0x2c03, 0x2c04, 0x2c05, 0x2c06, 0x2c07, 0x26ca, 0x26cc, + 0x26ce, 0x2c08, 0x26cb, 0x26cd, 0x26cf, 0x2c09, 0x2c0a, 0x2c0b, + 0x2c0c, 0x2c0d, 0x2c0e, 0x2c0f, 0x26d2, 0x26d4, 0x26d6, 0x26d3, + 0x26d5, 0x26d7, 0x26da, 0x26dc, 0x26de, 0x26db, 0x26dd, 0x26df, + 0x2700, 0x2702, 0x2701, 0x2703, 0x2780, 0x2782, 0x2781, 0x2783, + 0x2800, 0x2802, 0x2804, 0x2801, 0x2803, 0x2805, 0x2842, 0x2844, + 0x2846, 0x2849, 0x284b, 0x284d, 0x2c40, 0x284a, 0x284c, 0x284e, + 0x2c41, 0x2c42, 0x2c43, 0x2c44, 0x2c45, 0x2c46, 0x2c47, 0x2851, + 0x2853, 0x2855, 0x2c48, 0x2852, 0x2854, 0x2856, 0x2c49, 0x2c4a, + 0x2c4b, 0x2c4c, 0x2c4d, 0x2c4e, 0x2c4f, 0x2c82, 0x2e01, 0x3180, + 0x2c87, 0x2f01, 0x2f02, 0x2f03, 0x2e06, 0x3185, 0x3000, 0x3001, + 0x3002, 0x4640, 0x4641, 0x4680, 0x46c0, 0x46c2, 0x46c1, 0x4700, + 0x4740, 0x4780, 0x47c0, 0x47c2, 0x4900, 0x4940, 0x4980, 0x4982, + 0x4a00, 0x49c2, 0x4a03, 0x4a04, 0x4a40, 0x4a41, 0x4a80, 0x4a81, + 0x4ac0, 0x4ac1, 0x4bc0, 0x4bc1, 0x4b00, 0x4b01, 0x4b40, 0x4b41, + 0x4bc2, 0x4bc3, 0x4b80, 0x4b81, 0x4b82, 0x4b83, 0x4c00, 0x4c01, + 0x4c02, 0x4c03, 0x5600, 0x5440, 0x5442, 0x5444, 0x5446, 0x5448, + 0x544a, 0x544c, 0x544e, 0x5450, 0x5452, 0x5454, 0x5456, 0x5480, + 0x5482, 0x5484, 0x54c0, 0x54c1, 0x5500, 0x5501, 0x5540, 0x5541, + 0x5580, 0x5581, 0x55c0, 0x55c1, 0x5680, 0x58c0, 0x5700, 0x5702, + 0x5704, 0x5706, 0x5708, 0x570a, 0x570c, 0x570e, 0x5710, 0x5712, + 0x5714, 0x5716, 0x5740, 0x5742, 0x5744, 0x5780, 0x5781, 0x57c0, + 0x57c1, 0x5800, 0x5801, 0x5840, 0x5841, 0x5880, 0x5881, 0x5900, + 0x5901, 0x5902, 0x5903, 0x5940, 0x8ec0, 0x8f00, 0x8fc0, 0x8fc2, + 0x9000, 0x9040, 0x9041, 0x9080, 0x9081, 0x90c0, 0x90c2, 0x9100, + 0x9140, 0x9182, 0x9180, 0x9183, 0x91c1, 0x91c0, 0x91c3, 0x9200, + 0x9201, 0x9240, 0x9280, 0x9282, 0x9284, 0x9281, 0x9285, 0x9287, + 0x9286, 0x9283, 0x92c1, 0x92c0, 0x92c2, +}; + +typedef enum { + UNICODE_GC_Cn, + UNICODE_GC_Lu, + UNICODE_GC_Ll, + UNICODE_GC_Lt, + UNICODE_GC_Lm, + UNICODE_GC_Lo, + UNICODE_GC_Mn, + UNICODE_GC_Mc, + UNICODE_GC_Me, + UNICODE_GC_Nd, + UNICODE_GC_Nl, + UNICODE_GC_No, + UNICODE_GC_Sm, + UNICODE_GC_Sc, + UNICODE_GC_Sk, + UNICODE_GC_So, + UNICODE_GC_Pc, + UNICODE_GC_Pd, + UNICODE_GC_Ps, + UNICODE_GC_Pe, + UNICODE_GC_Pi, + UNICODE_GC_Pf, + UNICODE_GC_Po, + UNICODE_GC_Zs, + UNICODE_GC_Zl, + UNICODE_GC_Zp, + UNICODE_GC_Cc, + UNICODE_GC_Cf, + UNICODE_GC_Cs, + UNICODE_GC_Co, + UNICODE_GC_LC, + UNICODE_GC_L, + UNICODE_GC_M, + UNICODE_GC_N, + UNICODE_GC_S, + UNICODE_GC_P, + UNICODE_GC_Z, + UNICODE_GC_C, + UNICODE_GC_COUNT, +} UnicodeGCEnum; + +static const char unicode_gc_name_table[] = + "Cn,Unassigned" "\0" + "Lu,Uppercase_Letter" "\0" + "Ll,Lowercase_Letter" "\0" + "Lt,Titlecase_Letter" "\0" + "Lm,Modifier_Letter" "\0" + "Lo,Other_Letter" "\0" + "Mn,Nonspacing_Mark" "\0" + "Mc,Spacing_Mark" "\0" + "Me,Enclosing_Mark" "\0" + "Nd,Decimal_Number,digit" "\0" + "Nl,Letter_Number" "\0" + "No,Other_Number" "\0" + "Sm,Math_Symbol" "\0" + "Sc,Currency_Symbol" "\0" + "Sk,Modifier_Symbol" "\0" + "So,Other_Symbol" "\0" + "Pc,Connector_Punctuation" "\0" + "Pd,Dash_Punctuation" "\0" + "Ps,Open_Punctuation" "\0" + "Pe,Close_Punctuation" "\0" + "Pi,Initial_Punctuation" "\0" + "Pf,Final_Punctuation" "\0" + "Po,Other_Punctuation" "\0" + "Zs,Space_Separator" "\0" + "Zl,Line_Separator" "\0" + "Zp,Paragraph_Separator" "\0" + "Cc,Control,cntrl" "\0" + "Cf,Format" "\0" + "Cs,Surrogate" "\0" + "Co,Private_Use" "\0" + "LC,Cased_Letter" "\0" + "L,Letter" "\0" + "M,Mark,Combining_Mark" "\0" + "N,Number" "\0" + "S,Symbol" "\0" + "P,Punctuation,punct" "\0" + "Z,Separator" "\0" + "C,Other" "\0" +; + +static const uint8_t unicode_gc_table[4122] = { + 0xfa, 0x18, 0x17, 0x56, 0x0d, 0x56, 0x12, 0x13, + 0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9, 0x02, 0x36, + 0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16, 0x13, 0x0e, + 0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c, 0x13, 0x0c, + 0xfa, 0x19, 0x17, 0x16, 0x6d, 0x0f, 0x16, 0x0e, + 0x0f, 0x05, 0x14, 0x0c, 0x1b, 0x0f, 0x0e, 0x0f, + 0x0c, 0x2b, 0x0e, 0x02, 0x36, 0x0e, 0x0b, 0x05, + 0x15, 0x4b, 0x16, 0xe1, 0x0f, 0x0c, 0xc1, 0xe2, + 0x10, 0x0c, 0xe2, 0x00, 0xff, 0x30, 0x02, 0xff, + 0x08, 0x02, 0xff, 0x27, 0xbf, 0x22, 0x21, 0x02, + 0x5f, 0x5f, 0x21, 0x22, 0x61, 0x02, 0x21, 0x02, + 0x41, 0x42, 0x21, 0x02, 0x21, 0x02, 0x9f, 0x7f, + 0x02, 0x5f, 0x5f, 0x21, 0x02, 0x5f, 0x3f, 0x02, + 0x05, 0x3f, 0x22, 0x65, 0x01, 0x03, 0x02, 0x01, + 0x03, 0x02, 0x01, 0x03, 0x02, 0xff, 0x08, 0x02, + 0xff, 0x0a, 0x02, 0x01, 0x03, 0x02, 0x5f, 0x21, + 0x02, 0xff, 0x32, 0xa2, 0x21, 0x02, 0x21, 0x22, + 0x5f, 0x41, 0x02, 0xff, 0x00, 0xe2, 0x3c, 0x25, + 0xe2, 0x12, 0xe4, 0x0a, 0x6e, 0xe4, 0x04, 0xee, + 0x06, 0x84, 0xce, 0x04, 0x0e, 0x04, 0xee, 0x09, + 0xe6, 0x68, 0x7f, 0x04, 0x0e, 0x3f, 0x20, 0x04, + 0x42, 0x16, 0x01, 0x60, 0x2e, 0x01, 0x16, 0x41, + 0x00, 0x01, 0x00, 0x21, 0x02, 0xe1, 0x09, 0x00, + 0xe1, 0x01, 0xe2, 0x1b, 0x3f, 0x02, 0x41, 0x42, + 0xff, 0x10, 0x62, 0x3f, 0x0c, 0x5f, 0x3f, 0x02, + 0xe1, 0x2b, 0xe2, 0x28, 0xff, 0x1a, 0x0f, 0x86, + 0x28, 0xff, 0x2f, 0xff, 0x06, 0x02, 0xff, 0x58, + 0x00, 0xe1, 0x1e, 0x20, 0x04, 0xb6, 0xe2, 0x21, + 0x16, 0x11, 0x20, 0x2f, 0x0d, 0x00, 0xe6, 0x25, + 0x11, 0x06, 0x16, 0x26, 0x16, 0x26, 0x16, 0x06, + 0xe0, 0x00, 0xe5, 0x13, 0x60, 0x65, 0x36, 0xe0, + 0x03, 0xbb, 0x4c, 0x36, 0x0d, 0x36, 0x2f, 0xe6, + 0x03, 0x16, 0x1b, 0x56, 0xe5, 0x18, 0x04, 0xe5, + 0x02, 0xe6, 0x0d, 0xe9, 0x02, 0x76, 0x25, 0x06, + 0xe5, 0x5b, 0x16, 0x05, 0xc6, 0x1b, 0x0f, 0xa6, + 0x24, 0x26, 0x0f, 0x66, 0x25, 0xe9, 0x02, 0x45, + 0x2f, 0x05, 0xf6, 0x06, 0x00, 0x1b, 0x05, 0x06, + 0xe5, 0x16, 0xe6, 0x13, 0x20, 0xe5, 0x51, 0xe6, + 0x03, 0x05, 0xe0, 0x06, 0xe9, 0x02, 0xe5, 0x19, + 0xe6, 0x01, 0x24, 0x0f, 0x56, 0x04, 0x20, 0x06, + 0x2d, 0xe5, 0x0e, 0x66, 0x04, 0xe6, 0x01, 0x04, + 0x46, 0x04, 0x86, 0x20, 0xf6, 0x07, 0x00, 0xe5, + 0x11, 0x46, 0x20, 0x16, 0x00, 0xe5, 0x03, 0x80, + 0xe5, 0x10, 0x0e, 0xc5, 0x3b, 0x80, 0xe6, 0x01, + 0xe5, 0x21, 0x04, 0xe6, 0x10, 0x1b, 0xe6, 0x18, + 0x07, 0xe5, 0x2e, 0x06, 0x07, 0x06, 0x05, 0x47, + 0xe6, 0x00, 0x67, 0x06, 0x27, 0x05, 0xc6, 0xe5, + 0x02, 0x26, 0x36, 0xe9, 0x02, 0x16, 0x04, 0xe5, + 0x07, 0x06, 0x27, 0x00, 0xe5, 0x00, 0x20, 0x25, + 0x20, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x05, 0x40, + 0x65, 0x20, 0x06, 0x05, 0x47, 0x66, 0x20, 0x27, + 0x20, 0x27, 0x06, 0x05, 0xe0, 0x00, 0x07, 0x60, + 0x25, 0x00, 0x45, 0x26, 0x20, 0xe9, 0x02, 0x25, + 0x2d, 0xab, 0x0f, 0x0d, 0x05, 0x16, 0x06, 0x20, + 0x26, 0x07, 0x00, 0xa5, 0x60, 0x25, 0x20, 0xe5, + 0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00, 0x25, 0x00, + 0x25, 0x20, 0x06, 0x00, 0x47, 0x26, 0x60, 0x26, + 0x20, 0x46, 0x40, 0x06, 0xc0, 0x65, 0x00, 0x05, + 0xc0, 0xe9, 0x02, 0x26, 0x45, 0x06, 0x16, 0xe0, + 0x02, 0x26, 0x07, 0x00, 0xe5, 0x01, 0x00, 0x45, + 0x00, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00, + 0x85, 0x20, 0x06, 0x05, 0x47, 0x86, 0x00, 0x26, + 0x07, 0x00, 0x27, 0x06, 0x20, 0x05, 0xe0, 0x07, + 0x25, 0x26, 0x20, 0xe9, 0x02, 0x16, 0x0d, 0xc0, + 0x05, 0xa6, 0x00, 0x06, 0x27, 0x00, 0xe5, 0x00, + 0x20, 0x25, 0x20, 0xe5, 0x0e, 0x00, 0xc5, 0x00, + 0x25, 0x00, 0x85, 0x20, 0x06, 0x05, 0x07, 0x06, + 0x07, 0x66, 0x20, 0x27, 0x20, 0x27, 0x06, 0xc0, + 0x26, 0x07, 0x60, 0x25, 0x00, 0x45, 0x26, 0x20, + 0xe9, 0x02, 0x0f, 0x05, 0xab, 0xe0, 0x02, 0x06, + 0x05, 0x00, 0xa5, 0x40, 0x45, 0x00, 0x65, 0x40, + 0x25, 0x00, 0x05, 0x00, 0x25, 0x40, 0x25, 0x40, + 0x45, 0x40, 0xe5, 0x04, 0x60, 0x27, 0x06, 0x27, + 0x40, 0x47, 0x00, 0x47, 0x06, 0x20, 0x05, 0xa0, + 0x07, 0xe0, 0x06, 0xe9, 0x02, 0x4b, 0xaf, 0x0d, + 0x0f, 0x80, 0x06, 0x47, 0x06, 0xe5, 0x00, 0x00, + 0x45, 0x00, 0xe5, 0x0f, 0x00, 0xe5, 0x08, 0x20, + 0x06, 0x05, 0x46, 0x67, 0x00, 0x46, 0x00, 0x66, + 0xc0, 0x26, 0x00, 0x45, 0x00, 0x25, 0x20, 0x25, + 0x26, 0x20, 0xe9, 0x02, 0xc0, 0x16, 0xcb, 0x0f, + 0x05, 0x06, 0x27, 0x16, 0xe5, 0x00, 0x00, 0x45, + 0x00, 0xe5, 0x0f, 0x00, 0xe5, 0x02, 0x00, 0x85, + 0x20, 0x06, 0x05, 0x07, 0x06, 0x87, 0x00, 0x06, + 0x27, 0x00, 0x27, 0x26, 0xc0, 0x27, 0x80, 0x45, + 0x00, 0x25, 0x26, 0x20, 0xe9, 0x02, 0x00, 0x25, + 0x07, 0xe0, 0x04, 0x26, 0x27, 0xe5, 0x01, 0x00, + 0x45, 0x00, 0xe5, 0x21, 0x26, 0x05, 0x47, 0x66, + 0x00, 0x47, 0x00, 0x47, 0x06, 0x05, 0x0f, 0x60, + 0x45, 0x07, 0xcb, 0x45, 0x26, 0x20, 0xe9, 0x02, + 0xeb, 0x01, 0x0f, 0xa5, 0x00, 0x06, 0x27, 0x00, + 0xe5, 0x0a, 0x40, 0xe5, 0x10, 0x00, 0xe5, 0x01, + 0x00, 0x05, 0x20, 0xc5, 0x40, 0x06, 0x60, 0x47, + 0x46, 0x00, 0x06, 0x00, 0xe7, 0x00, 0xa0, 0xe9, + 0x02, 0x20, 0x27, 0x16, 0xe0, 0x04, 0xe5, 0x28, + 0x06, 0x25, 0xc6, 0x60, 0x0d, 0xa5, 0x04, 0xe6, + 0x00, 0x16, 0xe9, 0x02, 0x36, 0xe0, 0x1d, 0x25, + 0x00, 0x05, 0x00, 0x85, 0x00, 0xe5, 0x10, 0x00, + 0x05, 0x00, 0xe5, 0x02, 0x06, 0x25, 0xe6, 0x01, + 0x05, 0x20, 0x85, 0x00, 0x04, 0x00, 0xc6, 0x00, + 0xe9, 0x02, 0x20, 0x65, 0xe0, 0x18, 0x05, 0x4f, + 0xf6, 0x07, 0x0f, 0x16, 0x4f, 0x26, 0xaf, 0xe9, + 0x02, 0xeb, 0x02, 0x0f, 0x06, 0x0f, 0x06, 0x0f, + 0x06, 0x12, 0x13, 0x12, 0x13, 0x27, 0xe5, 0x00, + 0x00, 0xe5, 0x1c, 0x60, 0xe6, 0x06, 0x07, 0x86, + 0x16, 0x26, 0x85, 0xe6, 0x03, 0x00, 0xe6, 0x1c, + 0x00, 0xef, 0x00, 0x06, 0xaf, 0x00, 0x2f, 0x96, + 0x6f, 0x36, 0xe0, 0x1d, 0xe5, 0x23, 0x27, 0x66, + 0x07, 0xa6, 0x07, 0x26, 0x27, 0x26, 0x05, 0xe9, + 0x02, 0xb6, 0xa5, 0x27, 0x26, 0x65, 0x46, 0x05, + 0x47, 0x25, 0xc7, 0x45, 0x66, 0xe5, 0x05, 0x06, + 0x27, 0x26, 0xa7, 0x06, 0x05, 0x07, 0xe9, 0x02, + 0x47, 0x06, 0x2f, 0xe1, 0x1e, 0x00, 0x01, 0x80, + 0x01, 0x20, 0xe2, 0x23, 0x16, 0x04, 0x42, 0xe5, + 0x80, 0xc1, 0x00, 0x65, 0x20, 0xc5, 0x00, 0x05, + 0x00, 0x65, 0x20, 0xe5, 0x21, 0x00, 0x65, 0x20, + 0xe5, 0x19, 0x00, 0x65, 0x20, 0xc5, 0x00, 0x05, + 0x00, 0x65, 0x20, 0xe5, 0x07, 0x00, 0xe5, 0x31, + 0x00, 0x65, 0x20, 0xe5, 0x3b, 0x20, 0x46, 0xf6, + 0x01, 0xeb, 0x0c, 0x40, 0xe5, 0x08, 0xef, 0x02, + 0xa0, 0xe1, 0x4e, 0x20, 0xa2, 0x20, 0x11, 0xe5, + 0x81, 0xe4, 0x0f, 0x16, 0xe5, 0x09, 0x17, 0xe5, + 0x12, 0x12, 0x13, 0x40, 0xe5, 0x43, 0x56, 0x4a, + 0xe5, 0x00, 0xc0, 0xe5, 0x0a, 0x46, 0x07, 0xe0, + 0x01, 0xe5, 0x0b, 0x26, 0x07, 0x36, 0xe0, 0x01, + 0xe5, 0x0a, 0x26, 0xe0, 0x04, 0xe5, 0x05, 0x00, + 0x45, 0x00, 0x26, 0xe0, 0x04, 0xe5, 0x2c, 0x26, + 0x07, 0xc6, 0xe7, 0x00, 0x06, 0x27, 0xe6, 0x03, + 0x56, 0x04, 0x56, 0x0d, 0x05, 0x06, 0x20, 0xe9, + 0x02, 0xa0, 0xeb, 0x02, 0xa0, 0xb6, 0x11, 0x76, + 0x46, 0x1b, 0x06, 0xe9, 0x02, 0xa0, 0xe5, 0x1b, + 0x04, 0xe5, 0x2d, 0xc0, 0x85, 0x26, 0xe5, 0x1a, + 0x06, 0x05, 0x80, 0xe5, 0x3e, 0xe0, 0x02, 0xe5, + 0x17, 0x00, 0x46, 0x67, 0x26, 0x47, 0x60, 0x27, + 0x06, 0xa7, 0x46, 0x60, 0x0f, 0x40, 0x36, 0xe9, + 0x02, 0xe5, 0x16, 0x20, 0x85, 0xe0, 0x03, 0xe5, + 0x24, 0x60, 0xe5, 0x12, 0xa0, 0xe9, 0x02, 0x0b, + 0x40, 0xef, 0x1a, 0xe5, 0x0f, 0x26, 0x27, 0x06, + 0x20, 0x36, 0xe5, 0x2d, 0x07, 0x06, 0x07, 0xc6, + 0x00, 0x06, 0x07, 0x06, 0x27, 0xe6, 0x00, 0xa7, + 0xe6, 0x02, 0x20, 0x06, 0xe9, 0x02, 0xa0, 0xe9, + 0x02, 0xa0, 0xd6, 0x04, 0xb6, 0x20, 0xe6, 0x06, + 0x08, 0xe6, 0x17, 0x20, 0xe6, 0x04, 0xe0, 0x0c, + 0x66, 0x07, 0xe5, 0x27, 0x06, 0x07, 0x86, 0x07, + 0x06, 0x87, 0x06, 0x27, 0xe5, 0x00, 0x00, 0x36, + 0xe9, 0x02, 0xd6, 0xef, 0x02, 0xe6, 0x01, 0xef, + 0x01, 0x56, 0x26, 0x07, 0xe5, 0x16, 0x07, 0x66, + 0x27, 0x26, 0x07, 0x46, 0x25, 0xe9, 0x02, 0xe5, + 0x24, 0x06, 0x07, 0x26, 0x47, 0x06, 0x07, 0x46, + 0x27, 0xe0, 0x00, 0x76, 0xe5, 0x1c, 0xe7, 0x00, + 0xe6, 0x00, 0x27, 0x26, 0x40, 0x96, 0xe9, 0x02, + 0x40, 0x45, 0xe9, 0x02, 0xe5, 0x16, 0xa4, 0x36, + 0xe2, 0x01, 0x3f, 0x80, 0xe1, 0x23, 0x20, 0x41, + 0xf6, 0x00, 0xe0, 0x00, 0x46, 0x16, 0xe6, 0x05, + 0x07, 0xc6, 0x65, 0x06, 0xa5, 0x06, 0x25, 0x07, + 0x26, 0x05, 0x80, 0xe2, 0x24, 0xe4, 0x37, 0xe2, + 0x05, 0x04, 0xe2, 0x1a, 0xe4, 0x1d, 0xe6, 0x38, + 0xff, 0x80, 0x0e, 0xe2, 0x00, 0xff, 0x5a, 0xe2, + 0x00, 0xe1, 0x00, 0xa2, 0x20, 0xa1, 0x20, 0xe2, + 0x00, 0xe1, 0x00, 0xe2, 0x00, 0xe1, 0x00, 0xa2, + 0x20, 0xa1, 0x20, 0xe2, 0x00, 0x00, 0x01, 0x00, + 0x01, 0x00, 0x01, 0x00, 0x3f, 0xc2, 0xe1, 0x00, + 0xe2, 0x06, 0x20, 0xe2, 0x00, 0xe3, 0x00, 0xe2, + 0x00, 0xe3, 0x00, 0xe2, 0x00, 0xe3, 0x00, 0x82, + 0x00, 0x22, 0x61, 0x03, 0x0e, 0x02, 0x4e, 0x42, + 0x00, 0x22, 0x61, 0x03, 0x4e, 0x62, 0x20, 0x22, + 0x61, 0x00, 0x4e, 0xe2, 0x00, 0x81, 0x4e, 0x20, + 0x42, 0x00, 0x22, 0x61, 0x03, 0x2e, 0x00, 0xf7, + 0x03, 0x9b, 0xb1, 0x36, 0x14, 0x15, 0x12, 0x34, + 0x15, 0x12, 0x14, 0xf6, 0x00, 0x18, 0x19, 0x9b, + 0x17, 0xf6, 0x01, 0x14, 0x15, 0x76, 0x30, 0x56, + 0x0c, 0x12, 0x13, 0xf6, 0x03, 0x0c, 0x16, 0x10, + 0xf6, 0x02, 0x17, 0x9b, 0x00, 0xfb, 0x02, 0x0b, + 0x04, 0x20, 0xab, 0x4c, 0x12, 0x13, 0x04, 0xeb, + 0x02, 0x4c, 0x12, 0x13, 0x00, 0xe4, 0x05, 0x40, + 0xed, 0x1a, 0xe0, 0x06, 0xe6, 0x05, 0x68, 0x06, + 0x48, 0xe6, 0x04, 0xe0, 0x07, 0x2f, 0x01, 0x6f, + 0x01, 0x2f, 0x02, 0x41, 0x22, 0x41, 0x02, 0x0f, + 0x01, 0x2f, 0x0c, 0x81, 0xaf, 0x01, 0x0f, 0x01, + 0x0f, 0x01, 0x0f, 0x61, 0x0f, 0x02, 0x61, 0x02, + 0x65, 0x02, 0x2f, 0x22, 0x21, 0x8c, 0x3f, 0x42, + 0x0f, 0x0c, 0x2f, 0x02, 0x0f, 0xeb, 0x08, 0xea, + 0x1b, 0x3f, 0x6a, 0x0b, 0x2f, 0x60, 0x8c, 0x8f, + 0x2c, 0x6f, 0x0c, 0x2f, 0x0c, 0x2f, 0x0c, 0xcf, + 0x0c, 0xef, 0x17, 0x2c, 0x2f, 0x0c, 0x0f, 0x0c, + 0xef, 0x17, 0xec, 0x80, 0x84, 0xef, 0x00, 0x12, + 0x13, 0x12, 0x13, 0xef, 0x0c, 0x2c, 0xcf, 0x12, + 0x13, 0xef, 0x49, 0x0c, 0xef, 0x16, 0xec, 0x11, + 0xef, 0x20, 0xac, 0xef, 0x40, 0xe0, 0x0e, 0xef, + 0x03, 0xe0, 0x0d, 0xeb, 0x34, 0xef, 0x46, 0xeb, + 0x0e, 0xef, 0x80, 0x2f, 0x0c, 0xef, 0x01, 0x0c, + 0xef, 0x2e, 0xec, 0x00, 0xef, 0x67, 0x0c, 0xef, + 0x80, 0x70, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, + 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, + 0xeb, 0x16, 0xef, 0x24, 0x8c, 0x12, 0x13, 0xec, + 0x17, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, + 0x13, 0x12, 0x13, 0xec, 0x08, 0xef, 0x80, 0x78, + 0xec, 0x7b, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, + 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, + 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, + 0xec, 0x37, 0x12, 0x13, 0x12, 0x13, 0xec, 0x18, + 0x12, 0x13, 0xec, 0x80, 0x7a, 0xef, 0x28, 0xec, + 0x0d, 0x2f, 0xac, 0xef, 0x1f, 0x20, 0xef, 0x80, + 0x02, 0xe1, 0x28, 0xe2, 0x28, 0x5f, 0x21, 0x22, + 0xdf, 0x41, 0x02, 0x3f, 0x02, 0x3f, 0x82, 0x24, + 0x41, 0x02, 0xff, 0x5a, 0x02, 0xaf, 0x7f, 0x46, + 0x3f, 0x80, 0x76, 0x0b, 0x36, 0xe2, 0x1e, 0x00, + 0x02, 0x80, 0x02, 0x20, 0xe5, 0x30, 0xc0, 0x04, + 0x16, 0xe0, 0x06, 0x06, 0xe5, 0x0f, 0xe0, 0x01, + 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, + 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, + 0xe6, 0x18, 0x36, 0x14, 0x15, 0x14, 0x15, 0x56, + 0x14, 0x15, 0x16, 0x14, 0x15, 0xf6, 0x01, 0x11, + 0x36, 0x11, 0x16, 0x14, 0x15, 0x36, 0x14, 0x15, + 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, + 0x96, 0x04, 0xf6, 0x02, 0x31, 0x76, 0x11, 0x16, + 0x12, 0xf6, 0x05, 0x2f, 0x56, 0x12, 0x13, 0x12, + 0x13, 0x12, 0x13, 0x12, 0x13, 0x11, 0xe0, 0x1a, + 0xef, 0x12, 0x00, 0xef, 0x51, 0xe0, 0x04, 0xef, + 0x80, 0x4e, 0xe0, 0x12, 0xef, 0x08, 0x17, 0x56, + 0x0f, 0x04, 0x05, 0x0a, 0x12, 0x13, 0x12, 0x13, + 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x2f, 0x12, + 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x11, + 0x12, 0x33, 0x0f, 0xea, 0x01, 0x66, 0x27, 0x11, + 0x84, 0x2f, 0x4a, 0x04, 0x05, 0x16, 0x2f, 0x00, + 0xe5, 0x4e, 0x20, 0x26, 0x2e, 0x24, 0x05, 0x11, + 0xe5, 0x52, 0x16, 0x44, 0x05, 0x80, 0xe5, 0x23, + 0x00, 0xe5, 0x56, 0x00, 0x2f, 0x6b, 0xef, 0x02, + 0xe5, 0x18, 0xef, 0x1e, 0xe0, 0x01, 0x0f, 0xe5, + 0x08, 0xef, 0x17, 0x00, 0xeb, 0x02, 0xef, 0x16, + 0xeb, 0x00, 0x0f, 0xeb, 0x07, 0xef, 0x18, 0xeb, + 0x02, 0xef, 0x1f, 0xeb, 0x07, 0xef, 0x80, 0xb8, + 0xe5, 0x99, 0x38, 0xef, 0x38, 0xe5, 0xc0, 0x11, + 0x8d, 0x04, 0xe5, 0x83, 0xef, 0x40, 0xef, 0x2f, + 0xe0, 0x01, 0xe5, 0x20, 0xa4, 0x36, 0xe5, 0x80, + 0x84, 0x04, 0x56, 0xe5, 0x08, 0xe9, 0x02, 0x25, + 0xe0, 0x0c, 0xff, 0x26, 0x05, 0x06, 0x48, 0x16, + 0xe6, 0x02, 0x16, 0x04, 0xff, 0x14, 0x24, 0x26, + 0xe5, 0x3e, 0xea, 0x02, 0x26, 0xb6, 0xe0, 0x00, + 0xee, 0x0f, 0xe4, 0x01, 0x2e, 0xff, 0x06, 0x22, + 0xff, 0x36, 0x04, 0xe2, 0x00, 0x9f, 0xff, 0x02, + 0x04, 0x2e, 0x7f, 0x05, 0x7f, 0x22, 0xff, 0x0d, + 0x61, 0x02, 0x81, 0x02, 0xff, 0x07, 0x41, 0x02, + 0x5f, 0xff, 0x09, 0xe0, 0x0c, 0x64, 0x3f, 0x05, + 0x24, 0x02, 0xc5, 0x06, 0x45, 0x06, 0x65, 0x06, + 0xe5, 0x0f, 0x27, 0x26, 0x07, 0x6f, 0x06, 0x40, + 0xab, 0x2f, 0x0d, 0x0f, 0xa0, 0xe5, 0x2c, 0x76, + 0xe0, 0x00, 0x27, 0xe5, 0x2a, 0xe7, 0x08, 0x26, + 0xe0, 0x00, 0x36, 0xe9, 0x02, 0xa0, 0xe6, 0x0a, + 0xa5, 0x56, 0x05, 0x16, 0x25, 0x06, 0xe9, 0x02, + 0xe5, 0x14, 0xe6, 0x00, 0x36, 0xe5, 0x0f, 0xe6, + 0x03, 0x27, 0xe0, 0x03, 0x16, 0xe5, 0x15, 0x40, + 0x46, 0x07, 0xe5, 0x27, 0x06, 0x27, 0x66, 0x27, + 0x26, 0x47, 0xf6, 0x05, 0x00, 0x04, 0xe9, 0x02, + 0x60, 0x36, 0x85, 0x06, 0x04, 0xe5, 0x01, 0xe9, + 0x02, 0x85, 0x00, 0xe5, 0x21, 0xa6, 0x27, 0x26, + 0x27, 0x26, 0xe0, 0x01, 0x45, 0x06, 0xe5, 0x00, + 0x06, 0x07, 0x20, 0xe9, 0x02, 0x20, 0x76, 0xe5, + 0x08, 0x04, 0xa5, 0x4f, 0x05, 0x07, 0x06, 0x07, + 0xe5, 0x2a, 0x06, 0x05, 0x46, 0x25, 0x26, 0x85, + 0x26, 0x05, 0x06, 0x05, 0xe0, 0x10, 0x25, 0x04, + 0x36, 0xe5, 0x03, 0x07, 0x26, 0x27, 0x36, 0x05, + 0x24, 0x07, 0x06, 0xe0, 0x02, 0xa5, 0x20, 0xa5, + 0x20, 0xa5, 0xe0, 0x01, 0xc5, 0x00, 0xc5, 0x00, + 0xe2, 0x23, 0x0e, 0x64, 0xe2, 0x01, 0x04, 0x2e, + 0x60, 0xe2, 0x48, 0xe5, 0x1b, 0x27, 0x06, 0x27, + 0x06, 0x27, 0x16, 0x07, 0x06, 0x20, 0xe9, 0x02, + 0xa0, 0xe5, 0xab, 0x1c, 0xe0, 0x04, 0xe5, 0x0f, + 0x60, 0xe5, 0x29, 0x60, 0xfc, 0x87, 0x78, 0xfd, + 0x98, 0x78, 0xe5, 0x80, 0xe6, 0x20, 0xe5, 0x62, + 0xe0, 0x1e, 0xc2, 0xe0, 0x04, 0x82, 0x80, 0x05, + 0x06, 0xe5, 0x02, 0x0c, 0xe5, 0x05, 0x00, 0x85, + 0x00, 0x05, 0x00, 0x25, 0x00, 0x25, 0x00, 0xe5, + 0x64, 0xee, 0x09, 0xef, 0x08, 0xe5, 0x80, 0xe3, + 0x13, 0x12, 0xef, 0x08, 0xe5, 0x38, 0x2f, 0xe5, + 0x2e, 0xef, 0x00, 0xe0, 0x18, 0xe5, 0x04, 0x0d, + 0x4f, 0xe6, 0x08, 0xd6, 0x12, 0x13, 0x16, 0xa0, + 0xe6, 0x08, 0x16, 0x31, 0x30, 0x12, 0x13, 0x12, + 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, + 0x13, 0x12, 0x13, 0x12, 0x13, 0x36, 0x12, 0x13, + 0x76, 0x50, 0x56, 0x00, 0x76, 0x11, 0x12, 0x13, + 0x12, 0x13, 0x12, 0x13, 0x56, 0x0c, 0x11, 0x4c, + 0x00, 0x16, 0x0d, 0x36, 0x60, 0x85, 0x00, 0xe5, + 0x7f, 0x20, 0x1b, 0x00, 0x56, 0x0d, 0x56, 0x12, + 0x13, 0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9, 0x02, + 0x36, 0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16, 0x13, + 0x0e, 0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c, 0x13, + 0x0c, 0x12, 0x13, 0x16, 0x12, 0x13, 0x36, 0xe5, + 0x02, 0x04, 0xe5, 0x25, 0x24, 0xe5, 0x17, 0x40, + 0xa5, 0x20, 0xa5, 0x20, 0xa5, 0x20, 0x45, 0x40, + 0x2d, 0x0c, 0x0e, 0x0f, 0x2d, 0x00, 0x0f, 0x6c, + 0x2f, 0xe0, 0x02, 0x5b, 0x2f, 0x20, 0xe5, 0x04, + 0x00, 0xe5, 0x12, 0x00, 0xe5, 0x0b, 0x00, 0x25, + 0x00, 0xe5, 0x07, 0x20, 0xe5, 0x06, 0xe0, 0x1a, + 0xe5, 0x73, 0x80, 0x56, 0x60, 0xeb, 0x25, 0x40, + 0xef, 0x01, 0xea, 0x2d, 0x6b, 0xef, 0x09, 0x2b, + 0x4f, 0x00, 0xef, 0x05, 0x40, 0x0f, 0xe0, 0x27, + 0xef, 0x25, 0x06, 0xe0, 0x7a, 0xe5, 0x15, 0x40, + 0xe5, 0x29, 0xe0, 0x07, 0x06, 0xeb, 0x13, 0x60, + 0xe5, 0x18, 0x6b, 0xe0, 0x01, 0xe5, 0x0c, 0x0a, + 0xe5, 0x00, 0x0a, 0x80, 0xe5, 0x1e, 0x86, 0x80, + 0xe5, 0x16, 0x00, 0x16, 0xe5, 0x1c, 0x60, 0xe5, + 0x00, 0x16, 0x8a, 0xe0, 0x22, 0xe1, 0x20, 0xe2, + 0x20, 0xe5, 0x46, 0x20, 0xe9, 0x02, 0xa0, 0xe1, + 0x1c, 0x60, 0xe2, 0x1c, 0x60, 0xe5, 0x20, 0xe0, + 0x00, 0xe5, 0x2c, 0xe0, 0x03, 0x16, 0xe1, 0x03, + 0x00, 0xe1, 0x07, 0x00, 0xc1, 0x00, 0x21, 0x00, + 0xe2, 0x03, 0x00, 0xe2, 0x07, 0x00, 0xc2, 0x00, + 0x22, 0x40, 0xe5, 0x2c, 0xe0, 0x04, 0xe5, 0x80, + 0xaf, 0xe0, 0x01, 0xe5, 0x0e, 0xe0, 0x02, 0xe5, + 0x00, 0xe0, 0x10, 0xa4, 0x00, 0xe4, 0x22, 0x00, + 0xe4, 0x01, 0xe0, 0x3d, 0xa5, 0x20, 0x05, 0x00, + 0xe5, 0x24, 0x00, 0x25, 0x40, 0x05, 0x20, 0xe5, + 0x0f, 0x00, 0x16, 0xeb, 0x00, 0xe5, 0x0f, 0x2f, + 0xcb, 0xe5, 0x17, 0xe0, 0x00, 0xeb, 0x01, 0xe0, + 0x28, 0xe5, 0x0b, 0x00, 0x25, 0x80, 0x8b, 0xe5, + 0x0e, 0xab, 0x40, 0x16, 0xe5, 0x12, 0x80, 0x16, + 0xe5, 0x12, 0xe0, 0x1e, 0xe5, 0x30, 0x60, 0x2b, + 0x25, 0xeb, 0x08, 0x20, 0xeb, 0x26, 0x05, 0x46, + 0x00, 0x26, 0x80, 0x66, 0x65, 0x00, 0x45, 0x00, + 0xe5, 0x15, 0x20, 0x46, 0x60, 0x06, 0xeb, 0x01, + 0xc0, 0xf6, 0x01, 0xc0, 0xe5, 0x15, 0x2b, 0x16, + 0xe5, 0x15, 0x4b, 0xe0, 0x18, 0xe5, 0x00, 0x0f, + 0xe5, 0x14, 0x26, 0x60, 0x8b, 0xd6, 0xe0, 0x01, + 0xe5, 0x2e, 0x40, 0xd6, 0xe5, 0x0e, 0x20, 0xeb, + 0x00, 0xe5, 0x0b, 0x80, 0xeb, 0x00, 0xe5, 0x0a, + 0xc0, 0x76, 0xe0, 0x04, 0xcb, 0xe0, 0x48, 0xe5, + 0x41, 0xe0, 0x2f, 0xe1, 0x2b, 0xe0, 0x05, 0xe2, + 0x2b, 0xc0, 0xab, 0xe5, 0x1c, 0x66, 0xe0, 0x00, + 0xe9, 0x02, 0xa0, 0xe9, 0x02, 0x65, 0x04, 0x05, + 0xe1, 0x0e, 0x40, 0x86, 0x11, 0x04, 0xe2, 0x0e, + 0xe0, 0x00, 0x2c, 0xe0, 0x80, 0x48, 0xeb, 0x17, + 0x00, 0xe5, 0x22, 0x00, 0x26, 0x11, 0x20, 0x25, + 0xe0, 0x08, 0x45, 0x04, 0x25, 0xe0, 0x00, 0x16, + 0xef, 0x00, 0xe0, 0x19, 0xa6, 0xe5, 0x15, 0xeb, + 0x02, 0x05, 0xe0, 0x00, 0xe5, 0x0e, 0xe6, 0x03, + 0x6b, 0x96, 0xe0, 0x0e, 0xe5, 0x0a, 0x66, 0x76, + 0xe0, 0x1e, 0xe5, 0x0d, 0xcb, 0xe0, 0x0c, 0xe5, + 0x0f, 0xe0, 0x01, 0x07, 0x06, 0x07, 0xe5, 0x2d, + 0xe6, 0x07, 0xd6, 0x60, 0xeb, 0x0c, 0xe9, 0x02, + 0x06, 0x25, 0x26, 0x05, 0xe0, 0x01, 0x46, 0x07, + 0xe5, 0x25, 0x47, 0x66, 0x27, 0x26, 0x36, 0x1b, + 0x76, 0x06, 0xe0, 0x02, 0x1b, 0x20, 0xe5, 0x11, + 0xc0, 0xe9, 0x02, 0xa0, 0x46, 0xe5, 0x1c, 0x86, + 0x07, 0xe6, 0x00, 0x00, 0xe9, 0x02, 0x76, 0x05, + 0x27, 0x05, 0xe0, 0x00, 0xe5, 0x1b, 0x06, 0x36, + 0x05, 0xe0, 0x01, 0x26, 0x07, 0xe5, 0x28, 0x47, + 0xe6, 0x01, 0x27, 0x65, 0x76, 0x66, 0x16, 0x07, + 0x06, 0xe9, 0x02, 0x05, 0x16, 0x05, 0x56, 0x00, + 0xeb, 0x0c, 0xe0, 0x03, 0xe5, 0x0a, 0x00, 0xe5, + 0x11, 0x47, 0x46, 0x27, 0x06, 0x07, 0x26, 0xb6, + 0x06, 0x25, 0x06, 0xe0, 0x36, 0xc5, 0x00, 0x05, + 0x00, 0x65, 0x00, 0xe5, 0x07, 0x00, 0xe5, 0x02, + 0x16, 0xa0, 0xe5, 0x27, 0x06, 0x47, 0xe6, 0x00, + 0x80, 0xe9, 0x02, 0xa0, 0x26, 0x27, 0x00, 0xe5, + 0x00, 0x20, 0x25, 0x20, 0xe5, 0x0e, 0x00, 0xc5, + 0x00, 0x25, 0x00, 0x85, 0x00, 0x26, 0x05, 0x27, + 0x06, 0x67, 0x20, 0x27, 0x20, 0x47, 0x20, 0x05, + 0xa0, 0x07, 0x80, 0x85, 0x27, 0x20, 0xc6, 0x40, + 0x86, 0xe0, 0x03, 0xe5, 0x02, 0x00, 0x05, 0x20, + 0x05, 0x00, 0xe5, 0x1e, 0x00, 0x05, 0x47, 0xa6, + 0x00, 0x07, 0x20, 0x07, 0x00, 0x67, 0x00, 0x27, + 0x06, 0x07, 0x06, 0x05, 0x06, 0x05, 0x36, 0x00, + 0x36, 0xe0, 0x00, 0x26, 0xe0, 0x15, 0xe5, 0x2d, + 0x47, 0xe6, 0x00, 0x27, 0x46, 0x07, 0x06, 0x65, + 0x96, 0xe9, 0x02, 0x36, 0x00, 0x16, 0x06, 0x45, + 0xe0, 0x16, 0xe5, 0x28, 0x47, 0xa6, 0x07, 0x06, + 0x67, 0x26, 0x07, 0x26, 0x25, 0x16, 0x05, 0xe0, + 0x00, 0xe9, 0x02, 0xe0, 0x80, 0x1e, 0xe5, 0x27, + 0x47, 0x66, 0x20, 0x67, 0x26, 0x07, 0x26, 0xf6, + 0x0f, 0x65, 0x26, 0xe0, 0x1a, 0xe5, 0x28, 0x47, + 0xe6, 0x00, 0x27, 0x06, 0x07, 0x26, 0x56, 0x05, + 0xe0, 0x03, 0xe9, 0x02, 0xa0, 0xf6, 0x05, 0xe0, + 0x0b, 0xe5, 0x23, 0x06, 0x07, 0x06, 0x27, 0xa6, + 0x07, 0x06, 0x05, 0x16, 0xa0, 0xe9, 0x02, 0xa0, + 0xe9, 0x0c, 0xe0, 0x14, 0xe5, 0x13, 0x20, 0x06, + 0x07, 0x06, 0x27, 0x66, 0x07, 0x86, 0x60, 0xe9, + 0x02, 0x2b, 0x56, 0x0f, 0xc5, 0xe0, 0x80, 0x31, + 0xe5, 0x24, 0x47, 0xe6, 0x01, 0x07, 0x26, 0x16, + 0xe0, 0x5c, 0xe1, 0x18, 0xe2, 0x18, 0xe9, 0x02, + 0xeb, 0x01, 0xe0, 0x04, 0xe5, 0x00, 0x20, 0x05, + 0x20, 0xe5, 0x00, 0x00, 0x25, 0x00, 0xe5, 0x10, + 0xa7, 0x00, 0x27, 0x20, 0x26, 0x07, 0x06, 0x05, + 0x07, 0x05, 0x07, 0x06, 0x56, 0xe0, 0x01, 0xe9, + 0x02, 0xe0, 0x3e, 0xe5, 0x00, 0x20, 0xe5, 0x1f, + 0x47, 0x66, 0x20, 0x26, 0x67, 0x06, 0x05, 0x16, + 0x05, 0x07, 0xe0, 0x13, 0x05, 0xe6, 0x02, 0xe5, + 0x20, 0xa6, 0x07, 0x05, 0x66, 0xf6, 0x00, 0x06, + 0xe0, 0x00, 0x05, 0xa6, 0x27, 0x46, 0xe5, 0x26, + 0xe6, 0x05, 0x07, 0x26, 0x56, 0x05, 0x96, 0xe0, + 0x05, 0xe5, 0x41, 0xc0, 0xf6, 0x02, 0xe0, 0x4e, + 0x06, 0x07, 0x46, 0x07, 0x06, 0x07, 0xe0, 0x50, + 0xe5, 0x19, 0x16, 0xe0, 0x06, 0xe9, 0x02, 0xa0, + 0xe5, 0x01, 0x00, 0xe5, 0x1d, 0x07, 0xc6, 0x00, + 0xa6, 0x07, 0x06, 0x05, 0x96, 0xe0, 0x02, 0xe9, + 0x02, 0xeb, 0x0b, 0x40, 0x36, 0xe5, 0x16, 0x20, + 0xe6, 0x0e, 0x00, 0x07, 0xc6, 0x07, 0x26, 0x07, + 0x26, 0xe0, 0x41, 0xc5, 0x00, 0x25, 0x00, 0xe5, + 0x1e, 0xa6, 0x40, 0x06, 0x00, 0x26, 0x00, 0xc6, + 0x05, 0x06, 0xe0, 0x00, 0xe9, 0x02, 0xa0, 0xa5, + 0x00, 0x25, 0x00, 0xe5, 0x18, 0x87, 0x00, 0x26, + 0x00, 0x27, 0x06, 0x07, 0x06, 0x05, 0xc0, 0xe9, + 0x02, 0xa0, 0xe5, 0x21, 0x04, 0x25, 0x60, 0xe9, + 0x02, 0xe0, 0x80, 0x6e, 0xe5, 0x0b, 0x26, 0x27, + 0x36, 0xc0, 0x26, 0x05, 0x07, 0xe5, 0x05, 0x00, + 0xe5, 0x1a, 0x27, 0x86, 0x40, 0x27, 0x06, 0x07, + 0x06, 0xf6, 0x05, 0xe9, 0x02, 0x06, 0xe0, 0x4d, + 0x05, 0xe0, 0x07, 0xeb, 0x0d, 0xef, 0x00, 0x6d, + 0xef, 0x09, 0xe0, 0x05, 0x16, 0xe5, 0x83, 0x12, + 0xe0, 0x5e, 0xea, 0x67, 0x00, 0x96, 0xe0, 0x03, + 0xe5, 0x80, 0x3c, 0xe0, 0x89, 0xc4, 0xe5, 0x59, + 0x36, 0xe0, 0x05, 0xe5, 0x83, 0xa8, 0xfb, 0x08, + 0x06, 0xa5, 0xe6, 0x07, 0xe0, 0x02, 0xe5, 0x8f, + 0x13, 0x80, 0xe5, 0x81, 0xbf, 0xe0, 0x9a, 0x31, + 0xe5, 0x16, 0xe6, 0x04, 0x47, 0x46, 0xe9, 0x02, + 0xe0, 0x86, 0x3e, 0xe5, 0x81, 0xb1, 0xc0, 0xe5, + 0x17, 0x00, 0xe9, 0x02, 0x60, 0x36, 0xe5, 0x47, + 0x00, 0xe9, 0x02, 0xa0, 0xe5, 0x16, 0x20, 0x86, + 0x16, 0xe0, 0x02, 0xe5, 0x28, 0xc6, 0x96, 0x6f, + 0x64, 0x16, 0x0f, 0xe0, 0x02, 0xe9, 0x02, 0x00, + 0xcb, 0x00, 0xe5, 0x0d, 0x80, 0xe5, 0x0b, 0xe0, + 0x81, 0x28, 0x44, 0xe5, 0x20, 0x24, 0x56, 0xe9, + 0x02, 0xe0, 0x80, 0x3e, 0xe1, 0x18, 0xe2, 0x18, + 0xeb, 0x0f, 0x76, 0x80, 0xe1, 0x11, 0x20, 0xe2, + 0x11, 0xe0, 0x24, 0xe5, 0x43, 0x60, 0x06, 0x05, + 0xe7, 0x2f, 0xc0, 0x66, 0xe4, 0x05, 0xe0, 0x38, + 0x24, 0x16, 0x04, 0x06, 0xe0, 0x03, 0x27, 0x24, + 0x4a, 0xe0, 0x01, 0xe5, 0x9c, 0x4e, 0xe0, 0x21, + 0xe5, 0x18, 0xe0, 0x59, 0xe5, 0x6b, 0xe0, 0xa1, + 0x75, 0x64, 0x00, 0xc4, 0x00, 0x24, 0x00, 0xe5, + 0x80, 0x9b, 0xe0, 0x07, 0x05, 0xe0, 0x15, 0x45, + 0x20, 0x05, 0xe0, 0x06, 0x65, 0xe0, 0x00, 0xe5, + 0x81, 0x04, 0xe0, 0x88, 0x7c, 0xe5, 0x63, 0x80, + 0xe5, 0x05, 0x40, 0xe5, 0x01, 0xc0, 0xe5, 0x02, + 0x20, 0x0f, 0x26, 0x16, 0x7b, 0xe0, 0x8e, 0xd4, + 0xef, 0x80, 0x68, 0xe9, 0x02, 0x4f, 0x40, 0xef, + 0x81, 0x2c, 0xa0, 0xef, 0x0f, 0xe0, 0x07, 0xef, + 0x08, 0x0c, 0xe0, 0x07, 0xe6, 0x26, 0x20, 0xe6, + 0x0f, 0xe0, 0x01, 0xef, 0x6c, 0xe0, 0x34, 0xef, + 0x80, 0x6e, 0xe0, 0x02, 0xef, 0x1f, 0x20, 0xef, + 0x34, 0x27, 0x46, 0x4f, 0xa7, 0xfb, 0x00, 0xe6, + 0x00, 0x2f, 0xc6, 0xef, 0x16, 0x66, 0xef, 0x35, + 0xe0, 0x0d, 0xef, 0x3a, 0x46, 0x0f, 0xe0, 0x72, + 0xeb, 0x0c, 0xe0, 0x04, 0xeb, 0x0c, 0xe0, 0x04, + 0xef, 0x4f, 0xe0, 0x01, 0xeb, 0x11, 0xe0, 0x7f, + 0xe1, 0x12, 0xe2, 0x12, 0xe1, 0x12, 0xc2, 0x00, + 0xe2, 0x0a, 0xe1, 0x12, 0xe2, 0x12, 0x01, 0x00, + 0x21, 0x20, 0x01, 0x20, 0x21, 0x20, 0x61, 0x00, + 0xe1, 0x00, 0x62, 0x00, 0x02, 0x00, 0xc2, 0x00, + 0xe2, 0x03, 0xe1, 0x12, 0xe2, 0x12, 0x21, 0x00, + 0x61, 0x20, 0xe1, 0x00, 0x00, 0xc1, 0x00, 0xe2, + 0x12, 0x21, 0x00, 0x61, 0x00, 0x81, 0x00, 0x01, + 0x40, 0xc1, 0x00, 0xe2, 0x12, 0xe1, 0x12, 0xe2, + 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, + 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, + 0x12, 0xe1, 0x12, 0xe2, 0x14, 0x20, 0xe1, 0x11, + 0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c, + 0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2, + 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2, 0x11, + 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2, 0x11, 0x0c, + 0xa2, 0x3f, 0x20, 0xe9, 0x2a, 0xef, 0x81, 0x78, + 0xe6, 0x2f, 0x6f, 0xe6, 0x2a, 0xef, 0x00, 0x06, + 0xef, 0x06, 0x06, 0x2f, 0x96, 0xe0, 0x07, 0x86, + 0x00, 0xe6, 0x07, 0xe0, 0x83, 0xc8, 0xe2, 0x02, + 0x05, 0xe2, 0x0c, 0xa0, 0xa2, 0xe0, 0x80, 0x4d, + 0xc6, 0x00, 0xe6, 0x09, 0x20, 0xc6, 0x00, 0x26, + 0x00, 0x86, 0x80, 0xe4, 0x36, 0xe0, 0x19, 0x06, + 0xe0, 0x68, 0xe5, 0x25, 0x40, 0xc6, 0xc4, 0x20, + 0xe9, 0x02, 0x60, 0x05, 0x0f, 0xe0, 0x80, 0xb8, + 0xe5, 0x16, 0x06, 0xe0, 0x09, 0xe5, 0x24, 0x66, + 0xe9, 0x02, 0x80, 0x0d, 0xe0, 0x81, 0x48, 0xe5, + 0x13, 0x04, 0x66, 0xe9, 0x02, 0xe0, 0x80, 0x4e, + 0xe5, 0x16, 0x26, 0x05, 0xe9, 0x02, 0x60, 0x16, + 0xe0, 0x80, 0x38, 0xe5, 0x17, 0x00, 0x45, 0x06, + 0x25, 0x06, 0xc5, 0x26, 0x85, 0x06, 0xe0, 0x00, + 0x05, 0x04, 0xe0, 0x80, 0x58, 0xc5, 0x00, 0x65, + 0x00, 0x25, 0x00, 0xe5, 0x07, 0x00, 0xe5, 0x80, + 0x3d, 0x20, 0xeb, 0x01, 0xc6, 0xe0, 0x21, 0xe1, + 0x1a, 0xe2, 0x1a, 0xc6, 0x04, 0x60, 0xe9, 0x02, + 0x60, 0x36, 0xe0, 0x82, 0x89, 0xeb, 0x33, 0x0f, + 0x4b, 0x0d, 0x6b, 0xe0, 0x44, 0xeb, 0x25, 0x0f, + 0xeb, 0x07, 0xe0, 0x80, 0x3a, 0x65, 0x00, 0xe5, + 0x13, 0x00, 0x25, 0x00, 0x05, 0x20, 0x05, 0x00, + 0xe5, 0x02, 0x00, 0x65, 0x00, 0x05, 0x00, 0x05, + 0xa0, 0x05, 0x60, 0x05, 0x00, 0x05, 0x00, 0x05, + 0x00, 0x45, 0x00, 0x25, 0x00, 0x05, 0x20, 0x05, + 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, + 0x00, 0x25, 0x00, 0x05, 0x20, 0x65, 0x00, 0xc5, + 0x00, 0x65, 0x00, 0x65, 0x00, 0x05, 0x00, 0xe5, + 0x02, 0x00, 0xe5, 0x09, 0x80, 0x45, 0x00, 0x85, + 0x00, 0xe5, 0x09, 0xe0, 0x2c, 0x2c, 0xe0, 0x80, + 0x86, 0xef, 0x24, 0x60, 0xef, 0x5c, 0xe0, 0x04, + 0xef, 0x07, 0x20, 0xef, 0x07, 0x00, 0xef, 0x07, + 0x00, 0xef, 0x1d, 0xe0, 0x02, 0xeb, 0x05, 0xef, + 0x80, 0x19, 0xe0, 0x30, 0xef, 0x15, 0xe0, 0x05, + 0xef, 0x24, 0x60, 0xef, 0x01, 0xc0, 0x2f, 0xe0, + 0x06, 0xaf, 0xe0, 0x80, 0x12, 0xef, 0x80, 0x73, + 0x8e, 0xef, 0x82, 0x51, 0x40, 0xef, 0x09, 0x40, + 0xef, 0x05, 0x40, 0xef, 0x80, 0x52, 0xa0, 0xef, + 0x04, 0x60, 0x0f, 0xe0, 0x07, 0xef, 0x04, 0x60, + 0xef, 0x30, 0xe0, 0x00, 0xef, 0x02, 0xa0, 0xef, + 0x20, 0xe0, 0x00, 0xef, 0x16, 0x20, 0xef, 0x04, + 0x60, 0x2f, 0xe0, 0x06, 0xec, 0x01, 0xe0, 0x1f, + 0xef, 0x80, 0xd0, 0xe0, 0x00, 0xef, 0x06, 0x20, + 0xef, 0x05, 0x40, 0xef, 0x03, 0x40, 0xef, 0x31, + 0x00, 0x0f, 0x60, 0xef, 0x08, 0x20, 0xef, 0x04, + 0x60, 0xef, 0x02, 0xc0, 0xef, 0x80, 0x0b, 0x00, + 0xef, 0x54, 0xe9, 0x02, 0x0f, 0xe0, 0x83, 0x7d, + 0xe5, 0xc0, 0x66, 0x58, 0xe0, 0x18, 0xe5, 0x90, + 0x96, 0x20, 0xe5, 0x96, 0x06, 0x20, 0xe5, 0x9c, + 0xa9, 0xe0, 0x07, 0xe5, 0x81, 0xe6, 0xe0, 0x89, + 0x1a, 0xe5, 0x81, 0x96, 0xe0, 0x85, 0x5a, 0xe5, + 0x92, 0xc3, 0x80, 0xe5, 0xa0, 0xa2, 0xe0, 0xca, + 0x8a, 0xff, 0x1b, 0xe0, 0x16, 0xfb, 0x58, 0xe0, + 0x78, 0xe6, 0x80, 0x68, 0xe0, 0xc0, 0xbd, 0x88, + 0xfd, 0xc0, 0xbf, 0x76, 0x20, 0xfd, 0xc0, 0xbf, + 0x76, 0x20, +}; + +typedef enum { + UNICODE_SCRIPT_Unknown, + UNICODE_SCRIPT_Adlam, + UNICODE_SCRIPT_Ahom, + UNICODE_SCRIPT_Anatolian_Hieroglyphs, + UNICODE_SCRIPT_Arabic, + UNICODE_SCRIPT_Armenian, + UNICODE_SCRIPT_Avestan, + UNICODE_SCRIPT_Balinese, + UNICODE_SCRIPT_Bamum, + UNICODE_SCRIPT_Bassa_Vah, + UNICODE_SCRIPT_Batak, + UNICODE_SCRIPT_Bengali, + UNICODE_SCRIPT_Beria_Erfe, + UNICODE_SCRIPT_Bhaiksuki, + UNICODE_SCRIPT_Bopomofo, + UNICODE_SCRIPT_Brahmi, + UNICODE_SCRIPT_Braille, + UNICODE_SCRIPT_Buginese, + UNICODE_SCRIPT_Buhid, + UNICODE_SCRIPT_Canadian_Aboriginal, + UNICODE_SCRIPT_Carian, + UNICODE_SCRIPT_Caucasian_Albanian, + UNICODE_SCRIPT_Chakma, + UNICODE_SCRIPT_Cham, + UNICODE_SCRIPT_Cherokee, + UNICODE_SCRIPT_Chorasmian, + UNICODE_SCRIPT_Common, + UNICODE_SCRIPT_Coptic, + UNICODE_SCRIPT_Cuneiform, + UNICODE_SCRIPT_Cypriot, + UNICODE_SCRIPT_Cyrillic, + UNICODE_SCRIPT_Cypro_Minoan, + UNICODE_SCRIPT_Deseret, + UNICODE_SCRIPT_Devanagari, + UNICODE_SCRIPT_Dives_Akuru, + UNICODE_SCRIPT_Dogra, + UNICODE_SCRIPT_Duployan, + UNICODE_SCRIPT_Egyptian_Hieroglyphs, + UNICODE_SCRIPT_Elbasan, + UNICODE_SCRIPT_Elymaic, + UNICODE_SCRIPT_Ethiopic, + UNICODE_SCRIPT_Georgian, + UNICODE_SCRIPT_Glagolitic, + UNICODE_SCRIPT_Gothic, + UNICODE_SCRIPT_Garay, + UNICODE_SCRIPT_Grantha, + UNICODE_SCRIPT_Greek, + UNICODE_SCRIPT_Gujarati, + UNICODE_SCRIPT_Gunjala_Gondi, + UNICODE_SCRIPT_Gurmukhi, + UNICODE_SCRIPT_Gurung_Khema, + UNICODE_SCRIPT_Han, + UNICODE_SCRIPT_Hangul, + UNICODE_SCRIPT_Hanifi_Rohingya, + UNICODE_SCRIPT_Hanunoo, + UNICODE_SCRIPT_Hatran, + UNICODE_SCRIPT_Hebrew, + UNICODE_SCRIPT_Hiragana, + UNICODE_SCRIPT_Imperial_Aramaic, + UNICODE_SCRIPT_Inherited, + UNICODE_SCRIPT_Inscriptional_Pahlavi, + UNICODE_SCRIPT_Inscriptional_Parthian, + UNICODE_SCRIPT_Javanese, + UNICODE_SCRIPT_Kaithi, + UNICODE_SCRIPT_Kannada, + UNICODE_SCRIPT_Katakana, + UNICODE_SCRIPT_Katakana_Or_Hiragana, + UNICODE_SCRIPT_Kawi, + UNICODE_SCRIPT_Kayah_Li, + UNICODE_SCRIPT_Kharoshthi, + UNICODE_SCRIPT_Khmer, + UNICODE_SCRIPT_Khojki, + UNICODE_SCRIPT_Khitan_Small_Script, + UNICODE_SCRIPT_Khudawadi, + UNICODE_SCRIPT_Kirat_Rai, + UNICODE_SCRIPT_Lao, + UNICODE_SCRIPT_Latin, + UNICODE_SCRIPT_Lepcha, + UNICODE_SCRIPT_Limbu, + UNICODE_SCRIPT_Linear_A, + UNICODE_SCRIPT_Linear_B, + UNICODE_SCRIPT_Lisu, + UNICODE_SCRIPT_Lycian, + UNICODE_SCRIPT_Lydian, + UNICODE_SCRIPT_Makasar, + UNICODE_SCRIPT_Mahajani, + UNICODE_SCRIPT_Malayalam, + UNICODE_SCRIPT_Mandaic, + UNICODE_SCRIPT_Manichaean, + UNICODE_SCRIPT_Marchen, + UNICODE_SCRIPT_Masaram_Gondi, + UNICODE_SCRIPT_Medefaidrin, + UNICODE_SCRIPT_Meetei_Mayek, + UNICODE_SCRIPT_Mende_Kikakui, + UNICODE_SCRIPT_Meroitic_Cursive, + UNICODE_SCRIPT_Meroitic_Hieroglyphs, + UNICODE_SCRIPT_Miao, + UNICODE_SCRIPT_Modi, + UNICODE_SCRIPT_Mongolian, + UNICODE_SCRIPT_Mro, + UNICODE_SCRIPT_Multani, + UNICODE_SCRIPT_Myanmar, + UNICODE_SCRIPT_Nabataean, + UNICODE_SCRIPT_Nag_Mundari, + UNICODE_SCRIPT_Nandinagari, + UNICODE_SCRIPT_New_Tai_Lue, + UNICODE_SCRIPT_Newa, + UNICODE_SCRIPT_Nko, + UNICODE_SCRIPT_Nushu, + UNICODE_SCRIPT_Nyiakeng_Puachue_Hmong, + UNICODE_SCRIPT_Ogham, + UNICODE_SCRIPT_Ol_Chiki, + UNICODE_SCRIPT_Ol_Onal, + UNICODE_SCRIPT_Old_Hungarian, + UNICODE_SCRIPT_Old_Italic, + UNICODE_SCRIPT_Old_North_Arabian, + UNICODE_SCRIPT_Old_Permic, + UNICODE_SCRIPT_Old_Persian, + UNICODE_SCRIPT_Old_Sogdian, + UNICODE_SCRIPT_Old_South_Arabian, + UNICODE_SCRIPT_Old_Turkic, + UNICODE_SCRIPT_Old_Uyghur, + UNICODE_SCRIPT_Oriya, + UNICODE_SCRIPT_Osage, + UNICODE_SCRIPT_Osmanya, + UNICODE_SCRIPT_Pahawh_Hmong, + UNICODE_SCRIPT_Palmyrene, + UNICODE_SCRIPT_Pau_Cin_Hau, + UNICODE_SCRIPT_Phags_Pa, + UNICODE_SCRIPT_Phoenician, + UNICODE_SCRIPT_Psalter_Pahlavi, + UNICODE_SCRIPT_Rejang, + UNICODE_SCRIPT_Runic, + UNICODE_SCRIPT_Samaritan, + UNICODE_SCRIPT_Saurashtra, + UNICODE_SCRIPT_Sharada, + UNICODE_SCRIPT_Shavian, + UNICODE_SCRIPT_Siddham, + UNICODE_SCRIPT_Sidetic, + UNICODE_SCRIPT_SignWriting, + UNICODE_SCRIPT_Sinhala, + UNICODE_SCRIPT_Sogdian, + UNICODE_SCRIPT_Sora_Sompeng, + UNICODE_SCRIPT_Soyombo, + UNICODE_SCRIPT_Sundanese, + UNICODE_SCRIPT_Sunuwar, + UNICODE_SCRIPT_Syloti_Nagri, + UNICODE_SCRIPT_Syriac, + UNICODE_SCRIPT_Tagalog, + UNICODE_SCRIPT_Tagbanwa, + UNICODE_SCRIPT_Tai_Le, + UNICODE_SCRIPT_Tai_Tham, + UNICODE_SCRIPT_Tai_Viet, + UNICODE_SCRIPT_Tai_Yo, + UNICODE_SCRIPT_Takri, + UNICODE_SCRIPT_Tamil, + UNICODE_SCRIPT_Tangut, + UNICODE_SCRIPT_Telugu, + UNICODE_SCRIPT_Thaana, + UNICODE_SCRIPT_Thai, + UNICODE_SCRIPT_Tibetan, + UNICODE_SCRIPT_Tifinagh, + UNICODE_SCRIPT_Tirhuta, + UNICODE_SCRIPT_Tangsa, + UNICODE_SCRIPT_Todhri, + UNICODE_SCRIPT_Tolong_Siki, + UNICODE_SCRIPT_Toto, + UNICODE_SCRIPT_Tulu_Tigalari, + UNICODE_SCRIPT_Ugaritic, + UNICODE_SCRIPT_Vai, + UNICODE_SCRIPT_Vithkuqi, + UNICODE_SCRIPT_Wancho, + UNICODE_SCRIPT_Warang_Citi, + UNICODE_SCRIPT_Yezidi, + UNICODE_SCRIPT_Yi, + UNICODE_SCRIPT_Zanabazar_Square, + UNICODE_SCRIPT_COUNT, +} UnicodeScriptEnum; + +static const char unicode_script_name_table[] = + "Adlam,Adlm" "\0" + "Ahom,Ahom" "\0" + "Anatolian_Hieroglyphs,Hluw" "\0" + "Arabic,Arab" "\0" + "Armenian,Armn" "\0" + "Avestan,Avst" "\0" + "Balinese,Bali" "\0" + "Bamum,Bamu" "\0" + "Bassa_Vah,Bass" "\0" + "Batak,Batk" "\0" + "Bengali,Beng" "\0" + "Beria_Erfe,Berf" "\0" + "Bhaiksuki,Bhks" "\0" + "Bopomofo,Bopo" "\0" + "Brahmi,Brah" "\0" + "Braille,Brai" "\0" + "Buginese,Bugi" "\0" + "Buhid,Buhd" "\0" + "Canadian_Aboriginal,Cans" "\0" + "Carian,Cari" "\0" + "Caucasian_Albanian,Aghb" "\0" + "Chakma,Cakm" "\0" + "Cham,Cham" "\0" + "Cherokee,Cher" "\0" + "Chorasmian,Chrs" "\0" + "Common,Zyyy" "\0" + "Coptic,Copt,Qaac" "\0" + "Cuneiform,Xsux" "\0" + "Cypriot,Cprt" "\0" + "Cyrillic,Cyrl" "\0" + "Cypro_Minoan,Cpmn" "\0" + "Deseret,Dsrt" "\0" + "Devanagari,Deva" "\0" + "Dives_Akuru,Diak" "\0" + "Dogra,Dogr" "\0" + "Duployan,Dupl" "\0" + "Egyptian_Hieroglyphs,Egyp" "\0" + "Elbasan,Elba" "\0" + "Elymaic,Elym" "\0" + "Ethiopic,Ethi" "\0" + "Georgian,Geor" "\0" + "Glagolitic,Glag" "\0" + "Gothic,Goth" "\0" + "Garay,Gara" "\0" + "Grantha,Gran" "\0" + "Greek,Grek" "\0" + "Gujarati,Gujr" "\0" + "Gunjala_Gondi,Gong" "\0" + "Gurmukhi,Guru" "\0" + "Gurung_Khema,Gukh" "\0" + "Han,Hani" "\0" + "Hangul,Hang" "\0" + "Hanifi_Rohingya,Rohg" "\0" + "Hanunoo,Hano" "\0" + "Hatran,Hatr" "\0" + "Hebrew,Hebr" "\0" + "Hiragana,Hira" "\0" + "Imperial_Aramaic,Armi" "\0" + "Inherited,Zinh,Qaai" "\0" + "Inscriptional_Pahlavi,Phli" "\0" + "Inscriptional_Parthian,Prti" "\0" + "Javanese,Java" "\0" + "Kaithi,Kthi" "\0" + "Kannada,Knda" "\0" + "Katakana,Kana" "\0" + "Katakana_Or_Hiragana,Hrkt" "\0" + "Kawi,Kawi" "\0" + "Kayah_Li,Kali" "\0" + "Kharoshthi,Khar" "\0" + "Khmer,Khmr" "\0" + "Khojki,Khoj" "\0" + "Khitan_Small_Script,Kits" "\0" + "Khudawadi,Sind" "\0" + "Kirat_Rai,Krai" "\0" + "Lao,Laoo" "\0" + "Latin,Latn" "\0" + "Lepcha,Lepc" "\0" + "Limbu,Limb" "\0" + "Linear_A,Lina" "\0" + "Linear_B,Linb" "\0" + "Lisu,Lisu" "\0" + "Lycian,Lyci" "\0" + "Lydian,Lydi" "\0" + "Makasar,Maka" "\0" + "Mahajani,Mahj" "\0" + "Malayalam,Mlym" "\0" + "Mandaic,Mand" "\0" + "Manichaean,Mani" "\0" + "Marchen,Marc" "\0" + "Masaram_Gondi,Gonm" "\0" + "Medefaidrin,Medf" "\0" + "Meetei_Mayek,Mtei" "\0" + "Mende_Kikakui,Mend" "\0" + "Meroitic_Cursive,Merc" "\0" + "Meroitic_Hieroglyphs,Mero" "\0" + "Miao,Plrd" "\0" + "Modi,Modi" "\0" + "Mongolian,Mong" "\0" + "Mro,Mroo" "\0" + "Multani,Mult" "\0" + "Myanmar,Mymr" "\0" + "Nabataean,Nbat" "\0" + "Nag_Mundari,Nagm" "\0" + "Nandinagari,Nand" "\0" + "New_Tai_Lue,Talu" "\0" + "Newa,Newa" "\0" + "Nko,Nkoo" "\0" + "Nushu,Nshu" "\0" + "Nyiakeng_Puachue_Hmong,Hmnp" "\0" + "Ogham,Ogam" "\0" + "Ol_Chiki,Olck" "\0" + "Ol_Onal,Onao" "\0" + "Old_Hungarian,Hung" "\0" + "Old_Italic,Ital" "\0" + "Old_North_Arabian,Narb" "\0" + "Old_Permic,Perm" "\0" + "Old_Persian,Xpeo" "\0" + "Old_Sogdian,Sogo" "\0" + "Old_South_Arabian,Sarb" "\0" + "Old_Turkic,Orkh" "\0" + "Old_Uyghur,Ougr" "\0" + "Oriya,Orya" "\0" + "Osage,Osge" "\0" + "Osmanya,Osma" "\0" + "Pahawh_Hmong,Hmng" "\0" + "Palmyrene,Palm" "\0" + "Pau_Cin_Hau,Pauc" "\0" + "Phags_Pa,Phag" "\0" + "Phoenician,Phnx" "\0" + "Psalter_Pahlavi,Phlp" "\0" + "Rejang,Rjng" "\0" + "Runic,Runr" "\0" + "Samaritan,Samr" "\0" + "Saurashtra,Saur" "\0" + "Sharada,Shrd" "\0" + "Shavian,Shaw" "\0" + "Siddham,Sidd" "\0" + "Sidetic,Sidt" "\0" + "SignWriting,Sgnw" "\0" + "Sinhala,Sinh" "\0" + "Sogdian,Sogd" "\0" + "Sora_Sompeng,Sora" "\0" + "Soyombo,Soyo" "\0" + "Sundanese,Sund" "\0" + "Sunuwar,Sunu" "\0" + "Syloti_Nagri,Sylo" "\0" + "Syriac,Syrc" "\0" + "Tagalog,Tglg" "\0" + "Tagbanwa,Tagb" "\0" + "Tai_Le,Tale" "\0" + "Tai_Tham,Lana" "\0" + "Tai_Viet,Tavt" "\0" + "Tai_Yo,Tayo" "\0" + "Takri,Takr" "\0" + "Tamil,Taml" "\0" + "Tangut,Tang" "\0" + "Telugu,Telu" "\0" + "Thaana,Thaa" "\0" + "Thai,Thai" "\0" + "Tibetan,Tibt" "\0" + "Tifinagh,Tfng" "\0" + "Tirhuta,Tirh" "\0" + "Tangsa,Tnsa" "\0" + "Todhri,Todr" "\0" + "Tolong_Siki,Tols" "\0" + "Toto,Toto" "\0" + "Tulu_Tigalari,Tutg" "\0" + "Ugaritic,Ugar" "\0" + "Vai,Vaii" "\0" + "Vithkuqi,Vith" "\0" + "Wancho,Wcho" "\0" + "Warang_Citi,Wara" "\0" + "Yezidi,Yezi" "\0" + "Yi,Yiii" "\0" + "Zanabazar_Square,Zanb" "\0" +; + +static const uint8_t unicode_script_table[2818] = { + 0xc0, 0x1a, 0x99, 0x4c, 0x85, 0x1a, 0x99, 0x4c, + 0xae, 0x1a, 0x80, 0x4c, 0x8e, 0x1a, 0x80, 0x4c, + 0x84, 0x1a, 0x96, 0x4c, 0x80, 0x1a, 0x9e, 0x4c, + 0x80, 0x1a, 0xe1, 0x60, 0x4c, 0xa6, 0x1a, 0x84, + 0x4c, 0x84, 0x1a, 0x81, 0x0e, 0x93, 0x1a, 0xe0, + 0x0f, 0x3b, 0x83, 0x2e, 0x80, 0x1a, 0x82, 0x2e, + 0x01, 0x83, 0x2e, 0x80, 0x1a, 0x80, 0x2e, 0x03, + 0x80, 0x2e, 0x80, 0x1a, 0x80, 0x2e, 0x80, 0x1a, + 0x82, 0x2e, 0x00, 0x80, 0x2e, 0x00, 0x93, 0x2e, + 0x00, 0xbe, 0x2e, 0x8d, 0x1b, 0x8f, 0x2e, 0xe0, + 0x24, 0x1e, 0x81, 0x3b, 0xe0, 0x48, 0x1e, 0x00, + 0xa5, 0x05, 0x01, 0xb1, 0x05, 0x01, 0x82, 0x05, + 0x00, 0xb6, 0x38, 0x07, 0x9a, 0x38, 0x03, 0x85, + 0x38, 0x0a, 0x84, 0x04, 0x80, 0x1a, 0x85, 0x04, + 0x80, 0x1a, 0x8d, 0x04, 0x80, 0x1a, 0x82, 0x04, + 0x80, 0x1a, 0x9f, 0x04, 0x80, 0x1a, 0x89, 0x04, + 0x8a, 0x3b, 0x99, 0x04, 0x80, 0x3b, 0xe0, 0x0b, + 0x04, 0x80, 0x1a, 0xa1, 0x04, 0x8d, 0x93, 0x00, + 0xbb, 0x93, 0x01, 0x82, 0x93, 0xaf, 0x04, 0xb1, + 0x9e, 0x0d, 0xba, 0x6b, 0x01, 0x82, 0x6b, 0xad, + 0x85, 0x01, 0x8e, 0x85, 0x00, 0x9b, 0x57, 0x01, + 0x80, 0x57, 0x00, 0x8a, 0x93, 0x04, 0xa1, 0x04, + 0x04, 0xca, 0x04, 0x80, 0x1a, 0x9c, 0x04, 0xd0, + 0x21, 0x83, 0x3b, 0x8e, 0x21, 0x81, 0x1a, 0x99, + 0x21, 0x83, 0x0b, 0x00, 0x87, 0x0b, 0x01, 0x81, + 0x0b, 0x01, 0x95, 0x0b, 0x00, 0x86, 0x0b, 0x00, + 0x80, 0x0b, 0x02, 0x83, 0x0b, 0x01, 0x88, 0x0b, + 0x01, 0x81, 0x0b, 0x01, 0x83, 0x0b, 0x07, 0x80, + 0x0b, 0x03, 0x81, 0x0b, 0x00, 0x84, 0x0b, 0x01, + 0x98, 0x0b, 0x01, 0x82, 0x31, 0x00, 0x85, 0x31, + 0x03, 0x81, 0x31, 0x01, 0x95, 0x31, 0x00, 0x86, + 0x31, 0x00, 0x81, 0x31, 0x00, 0x81, 0x31, 0x00, + 0x81, 0x31, 0x01, 0x80, 0x31, 0x00, 0x84, 0x31, + 0x03, 0x81, 0x31, 0x01, 0x82, 0x31, 0x02, 0x80, + 0x31, 0x06, 0x83, 0x31, 0x00, 0x80, 0x31, 0x06, + 0x90, 0x31, 0x09, 0x82, 0x2f, 0x00, 0x88, 0x2f, + 0x00, 0x82, 0x2f, 0x00, 0x95, 0x2f, 0x00, 0x86, + 0x2f, 0x00, 0x81, 0x2f, 0x00, 0x84, 0x2f, 0x01, + 0x89, 0x2f, 0x00, 0x82, 0x2f, 0x00, 0x82, 0x2f, + 0x01, 0x80, 0x2f, 0x0e, 0x83, 0x2f, 0x01, 0x8b, + 0x2f, 0x06, 0x86, 0x2f, 0x00, 0x82, 0x7a, 0x00, + 0x87, 0x7a, 0x01, 0x81, 0x7a, 0x01, 0x95, 0x7a, + 0x00, 0x86, 0x7a, 0x00, 0x81, 0x7a, 0x00, 0x84, + 0x7a, 0x01, 0x88, 0x7a, 0x01, 0x81, 0x7a, 0x01, + 0x82, 0x7a, 0x06, 0x82, 0x7a, 0x03, 0x81, 0x7a, + 0x00, 0x84, 0x7a, 0x01, 0x91, 0x7a, 0x09, 0x81, + 0x9b, 0x00, 0x85, 0x9b, 0x02, 0x82, 0x9b, 0x00, + 0x83, 0x9b, 0x02, 0x81, 0x9b, 0x00, 0x80, 0x9b, + 0x00, 0x81, 0x9b, 0x02, 0x81, 0x9b, 0x02, 0x82, + 0x9b, 0x02, 0x8b, 0x9b, 0x03, 0x84, 0x9b, 0x02, + 0x82, 0x9b, 0x00, 0x83, 0x9b, 0x01, 0x80, 0x9b, + 0x05, 0x80, 0x9b, 0x0d, 0x94, 0x9b, 0x04, 0x8c, + 0x9d, 0x00, 0x82, 0x9d, 0x00, 0x96, 0x9d, 0x00, + 0x8f, 0x9d, 0x01, 0x88, 0x9d, 0x00, 0x82, 0x9d, + 0x00, 0x83, 0x9d, 0x06, 0x81, 0x9d, 0x00, 0x82, + 0x9d, 0x00, 0x81, 0x9d, 0x01, 0x83, 0x9d, 0x01, + 0x89, 0x9d, 0x06, 0x88, 0x9d, 0x8c, 0x40, 0x00, + 0x82, 0x40, 0x00, 0x96, 0x40, 0x00, 0x89, 0x40, + 0x00, 0x84, 0x40, 0x01, 0x88, 0x40, 0x00, 0x82, + 0x40, 0x00, 0x83, 0x40, 0x06, 0x81, 0x40, 0x04, + 0x82, 0x40, 0x00, 0x83, 0x40, 0x01, 0x89, 0x40, + 0x00, 0x82, 0x40, 0x0b, 0x8c, 0x56, 0x00, 0x82, + 0x56, 0x00, 0xb2, 0x56, 0x00, 0x82, 0x56, 0x00, + 0x85, 0x56, 0x03, 0x8f, 0x56, 0x01, 0x99, 0x56, + 0x00, 0x82, 0x8c, 0x00, 0x91, 0x8c, 0x02, 0x97, + 0x8c, 0x00, 0x88, 0x8c, 0x00, 0x80, 0x8c, 0x01, + 0x86, 0x8c, 0x02, 0x80, 0x8c, 0x03, 0x85, 0x8c, + 0x00, 0x80, 0x8c, 0x00, 0x87, 0x8c, 0x05, 0x89, + 0x8c, 0x01, 0x82, 0x8c, 0x0b, 0xb9, 0x9f, 0x03, + 0x80, 0x1a, 0x9b, 0x9f, 0x24, 0x81, 0x4b, 0x00, + 0x80, 0x4b, 0x00, 0x84, 0x4b, 0x00, 0x97, 0x4b, + 0x00, 0x80, 0x4b, 0x00, 0x96, 0x4b, 0x01, 0x84, + 0x4b, 0x00, 0x80, 0x4b, 0x00, 0x86, 0x4b, 0x00, + 0x89, 0x4b, 0x01, 0x83, 0x4b, 0x1f, 0xc7, 0xa0, + 0x00, 0xa3, 0xa0, 0x03, 0xa6, 0xa0, 0x00, 0xa3, + 0xa0, 0x00, 0x8e, 0xa0, 0x00, 0x86, 0xa0, 0x83, + 0x1a, 0x81, 0xa0, 0x24, 0xe0, 0x3f, 0x65, 0xa5, + 0x29, 0x00, 0x80, 0x29, 0x04, 0x80, 0x29, 0x01, + 0xaa, 0x29, 0x80, 0x1a, 0x83, 0x29, 0xe0, 0x9f, + 0x34, 0xc8, 0x28, 0x00, 0x83, 0x28, 0x01, 0x86, + 0x28, 0x00, 0x80, 0x28, 0x00, 0x83, 0x28, 0x01, + 0xa8, 0x28, 0x00, 0x83, 0x28, 0x01, 0xa0, 0x28, + 0x00, 0x83, 0x28, 0x01, 0x86, 0x28, 0x00, 0x80, + 0x28, 0x00, 0x83, 0x28, 0x01, 0x8e, 0x28, 0x00, + 0xb8, 0x28, 0x00, 0x83, 0x28, 0x01, 0xc2, 0x28, + 0x01, 0x9f, 0x28, 0x02, 0x99, 0x28, 0x05, 0xd5, + 0x18, 0x01, 0x85, 0x18, 0x01, 0xe2, 0x1f, 0x13, + 0x9c, 0x6e, 0x02, 0xca, 0x84, 0x82, 0x1a, 0x8a, + 0x84, 0x06, 0x95, 0x94, 0x08, 0x80, 0x94, 0x94, + 0x36, 0x81, 0x1a, 0x08, 0x93, 0x12, 0x0b, 0x8c, + 0x95, 0x00, 0x82, 0x95, 0x00, 0x81, 0x95, 0x0b, + 0xdd, 0x46, 0x01, 0x89, 0x46, 0x05, 0x89, 0x46, + 0x05, 0x81, 0x62, 0x81, 0x1a, 0x80, 0x62, 0x80, + 0x1a, 0x93, 0x62, 0x05, 0xd8, 0x62, 0x06, 0xaa, + 0x62, 0x04, 0xc5, 0x13, 0x09, 0x9e, 0x4e, 0x00, + 0x8b, 0x4e, 0x03, 0x8b, 0x4e, 0x03, 0x80, 0x4e, + 0x02, 0x8b, 0x4e, 0x9d, 0x96, 0x01, 0x84, 0x96, + 0x0a, 0xab, 0x69, 0x03, 0x99, 0x69, 0x05, 0x8a, + 0x69, 0x02, 0x81, 0x69, 0x9f, 0x46, 0x9b, 0x11, + 0x01, 0x81, 0x11, 0xbe, 0x97, 0x00, 0x9c, 0x97, + 0x01, 0x8a, 0x97, 0x05, 0x89, 0x97, 0x05, 0x8d, + 0x97, 0x01, 0xad, 0x3b, 0x01, 0x8b, 0x3b, 0x13, + 0xcc, 0x07, 0x00, 0xb1, 0x07, 0xbf, 0x90, 0xb3, + 0x0a, 0x07, 0x83, 0x0a, 0xb7, 0x4d, 0x02, 0x8e, + 0x4d, 0x02, 0x82, 0x4d, 0xaf, 0x6f, 0x8a, 0x1e, + 0x04, 0xaa, 0x29, 0x01, 0x82, 0x29, 0x87, 0x90, + 0x07, 0x82, 0x3b, 0x80, 0x1a, 0x8c, 0x3b, 0x80, + 0x1a, 0x86, 0x3b, 0x83, 0x1a, 0x80, 0x3b, 0x85, + 0x1a, 0x80, 0x3b, 0x82, 0x1a, 0x81, 0x3b, 0x80, + 0x1a, 0x04, 0xa5, 0x4c, 0x84, 0x2e, 0x80, 0x1e, + 0xb0, 0x4c, 0x84, 0x2e, 0x83, 0x4c, 0x84, 0x2e, + 0x8c, 0x4c, 0x80, 0x1e, 0xc5, 0x4c, 0x80, 0x2e, + 0xbf, 0x3b, 0xe0, 0x9f, 0x4c, 0x95, 0x2e, 0x01, + 0x85, 0x2e, 0x01, 0xa5, 0x2e, 0x01, 0x85, 0x2e, + 0x01, 0x87, 0x2e, 0x00, 0x80, 0x2e, 0x00, 0x80, + 0x2e, 0x00, 0x80, 0x2e, 0x00, 0x9e, 0x2e, 0x01, + 0xb4, 0x2e, 0x00, 0x8e, 0x2e, 0x00, 0x8d, 0x2e, + 0x01, 0x85, 0x2e, 0x00, 0x92, 0x2e, 0x01, 0x82, + 0x2e, 0x00, 0x88, 0x2e, 0x00, 0x8b, 0x1a, 0x81, + 0x3b, 0xd6, 0x1a, 0x00, 0x8a, 0x1a, 0x80, 0x4c, + 0x01, 0x8a, 0x1a, 0x80, 0x4c, 0x8e, 0x1a, 0x00, + 0x8c, 0x4c, 0x02, 0xa1, 0x1a, 0x0d, 0xa0, 0x3b, + 0x0e, 0xa5, 0x1a, 0x80, 0x2e, 0x82, 0x1a, 0x81, + 0x4c, 0x85, 0x1a, 0x80, 0x4c, 0x9a, 0x1a, 0x80, + 0x4c, 0x90, 0x1a, 0xa8, 0x4c, 0x82, 0x1a, 0x03, + 0xe2, 0x39, 0x1a, 0x15, 0x8a, 0x1a, 0x14, 0xe3, + 0x3f, 0x1a, 0xe0, 0x9f, 0x10, 0xe2, 0x13, 0x1a, + 0x01, 0xe0, 0x29, 0x1a, 0xdf, 0x2a, 0x9f, 0x4c, + 0xe0, 0x13, 0x1b, 0x04, 0x86, 0x1b, 0xa5, 0x29, + 0x00, 0x80, 0x29, 0x04, 0x80, 0x29, 0x01, 0xb7, + 0xa1, 0x06, 0x81, 0xa1, 0x0d, 0x80, 0xa1, 0x96, + 0x28, 0x08, 0x86, 0x28, 0x00, 0x86, 0x28, 0x00, + 0x86, 0x28, 0x00, 0x86, 0x28, 0x00, 0x86, 0x28, + 0x00, 0x86, 0x28, 0x00, 0x86, 0x28, 0x00, 0x86, + 0x28, 0x00, 0x9f, 0x1e, 0xdd, 0x1a, 0x21, 0x99, + 0x33, 0x00, 0xd8, 0x33, 0x0b, 0xe0, 0x75, 0x33, + 0x19, 0x94, 0x1a, 0x80, 0x33, 0x80, 0x1a, 0x80, + 0x33, 0x98, 0x1a, 0x88, 0x33, 0x83, 0x3b, 0x81, + 0x34, 0x87, 0x1a, 0x83, 0x33, 0x83, 0x1a, 0x00, + 0xd5, 0x39, 0x01, 0x81, 0x3b, 0x81, 0x1a, 0x82, + 0x39, 0x80, 0x1a, 0xd9, 0x41, 0x81, 0x1a, 0x82, + 0x41, 0x04, 0xaa, 0x0e, 0x00, 0xdd, 0x34, 0x00, + 0x8f, 0x1a, 0x9f, 0x0e, 0xa5, 0x1a, 0x08, 0x80, + 0x1a, 0x8f, 0x41, 0x9e, 0x34, 0x00, 0xbf, 0x1a, + 0x9e, 0x34, 0xd0, 0x1a, 0xae, 0x41, 0x80, 0x1a, + 0xd7, 0x41, 0xe0, 0x47, 0x1a, 0xf0, 0x09, 0x5f, + 0x33, 0xbf, 0x1a, 0xf0, 0x41, 0x9f, 0x33, 0xe4, + 0x2c, 0xae, 0x02, 0xb6, 0xae, 0x08, 0xaf, 0x51, + 0xe0, 0xcb, 0xa9, 0x13, 0xdf, 0x1e, 0xd7, 0x08, + 0x07, 0xa1, 0x1a, 0xe0, 0x05, 0x4c, 0x82, 0x1a, + 0xd1, 0x4c, 0x13, 0x8e, 0x4c, 0xac, 0x92, 0x02, + 0x89, 0x1a, 0x05, 0xb7, 0x80, 0x07, 0xc5, 0x86, + 0x07, 0x8b, 0x86, 0x05, 0x9f, 0x21, 0xad, 0x44, + 0x80, 0x1a, 0x80, 0x44, 0xa3, 0x83, 0x0a, 0x80, + 0x83, 0x9c, 0x34, 0x02, 0xcd, 0x3e, 0x00, 0x80, + 0x1a, 0x89, 0x3e, 0x03, 0x81, 0x3e, 0x9e, 0x65, + 0x00, 0xb6, 0x17, 0x08, 0x8d, 0x17, 0x01, 0x89, + 0x17, 0x01, 0x83, 0x17, 0x9f, 0x65, 0xc2, 0x98, + 0x17, 0x84, 0x98, 0x96, 0x5c, 0x09, 0x85, 0x28, + 0x01, 0x85, 0x28, 0x01, 0x85, 0x28, 0x08, 0x86, + 0x28, 0x00, 0x86, 0x28, 0x00, 0xaa, 0x4c, 0x80, + 0x1a, 0x88, 0x4c, 0x80, 0x2e, 0x83, 0x4c, 0x81, + 0x1a, 0x03, 0xcf, 0x18, 0xad, 0x5c, 0x01, 0x89, + 0x5c, 0x05, 0xf0, 0x1b, 0x43, 0x34, 0x0b, 0x96, + 0x34, 0x03, 0xb0, 0x34, 0x70, 0x10, 0xa3, 0xe1, + 0x0d, 0x33, 0x01, 0xe0, 0x09, 0x33, 0x25, 0x86, + 0x4c, 0x0b, 0x84, 0x05, 0x04, 0x99, 0x38, 0x00, + 0x84, 0x38, 0x00, 0x80, 0x38, 0x00, 0x81, 0x38, + 0x00, 0x81, 0x38, 0x00, 0x89, 0x38, 0xe1, 0x8d, + 0x04, 0x81, 0x1a, 0xe0, 0x2f, 0x04, 0x1f, 0x8f, + 0x04, 0x8f, 0x3b, 0x89, 0x1a, 0x05, 0x8d, 0x3b, + 0x81, 0x1e, 0xa2, 0x1a, 0x00, 0x92, 0x1a, 0x00, + 0x83, 0x1a, 0x03, 0x84, 0x04, 0x00, 0xe0, 0x26, + 0x04, 0x01, 0x80, 0x1a, 0x00, 0x9f, 0x1a, 0x99, + 0x4c, 0x85, 0x1a, 0x99, 0x4c, 0x8a, 0x1a, 0x89, + 0x41, 0x80, 0x1a, 0xac, 0x41, 0x81, 0x1a, 0x9e, + 0x34, 0x02, 0x85, 0x34, 0x01, 0x85, 0x34, 0x01, + 0x85, 0x34, 0x01, 0x82, 0x34, 0x02, 0x86, 0x1a, + 0x00, 0x86, 0x1a, 0x09, 0x84, 0x1a, 0x01, 0x8b, + 0x50, 0x00, 0x99, 0x50, 0x00, 0x92, 0x50, 0x00, + 0x81, 0x50, 0x00, 0x8e, 0x50, 0x01, 0x8d, 0x50, + 0x21, 0xe0, 0x1a, 0x50, 0x04, 0x82, 0x1a, 0x03, + 0xac, 0x1a, 0x02, 0x88, 0x1a, 0xce, 0x2e, 0x00, + 0x8c, 0x1a, 0x02, 0x80, 0x2e, 0x2e, 0xac, 0x1a, + 0x80, 0x3b, 0x60, 0x21, 0x9c, 0x52, 0x02, 0xb0, + 0x14, 0x0e, 0x80, 0x3b, 0x9a, 0x1a, 0x03, 0xa3, + 0x72, 0x08, 0x82, 0x72, 0x9a, 0x2b, 0x04, 0xaa, + 0x74, 0x04, 0x9d, 0xa8, 0x00, 0x80, 0xa8, 0xa3, + 0x75, 0x03, 0x8d, 0x75, 0x29, 0xcf, 0x20, 0xaf, + 0x88, 0x9d, 0x7c, 0x01, 0x89, 0x7c, 0x05, 0xa3, + 0x7b, 0x03, 0xa3, 0x7b, 0x03, 0xa7, 0x26, 0x07, + 0xb3, 0x15, 0x0a, 0x80, 0x15, 0x8a, 0xaa, 0x00, + 0x8e, 0xaa, 0x00, 0x86, 0xaa, 0x00, 0x81, 0xaa, + 0x00, 0x8a, 0xaa, 0x00, 0x8e, 0xaa, 0x00, 0x86, + 0xaa, 0x00, 0x81, 0xaa, 0x02, 0xb3, 0xa4, 0x0b, + 0xe0, 0xd6, 0x4f, 0x08, 0x95, 0x4f, 0x09, 0x87, + 0x4f, 0x17, 0x85, 0x4c, 0x00, 0xa9, 0x4c, 0x00, + 0x88, 0x4c, 0x44, 0x85, 0x1d, 0x01, 0x80, 0x1d, + 0x00, 0xab, 0x1d, 0x00, 0x81, 0x1d, 0x02, 0x80, + 0x1d, 0x01, 0x80, 0x1d, 0x95, 0x3a, 0x00, 0x88, + 0x3a, 0x9f, 0x7e, 0x9e, 0x66, 0x07, 0x88, 0x66, + 0x2f, 0x92, 0x37, 0x00, 0x81, 0x37, 0x04, 0x84, + 0x37, 0x9b, 0x81, 0x02, 0x80, 0x81, 0x99, 0x53, + 0x04, 0x80, 0x53, 0x99, 0x8a, 0x25, 0x9f, 0x5f, + 0x97, 0x5e, 0x03, 0x93, 0x5e, 0x01, 0xad, 0x5e, + 0x83, 0x45, 0x00, 0x81, 0x45, 0x04, 0x87, 0x45, + 0x00, 0x82, 0x45, 0x00, 0x9c, 0x45, 0x01, 0x82, + 0x45, 0x03, 0x89, 0x45, 0x06, 0x88, 0x45, 0x06, + 0x9f, 0x77, 0x9f, 0x73, 0x1f, 0xa6, 0x58, 0x03, + 0x8b, 0x58, 0x08, 0xb5, 0x06, 0x02, 0x86, 0x06, + 0x95, 0x3d, 0x01, 0x87, 0x3d, 0x92, 0x3c, 0x04, + 0x87, 0x3c, 0x91, 0x82, 0x06, 0x83, 0x82, 0x0b, + 0x86, 0x82, 0x4f, 0xc8, 0x78, 0x36, 0xb2, 0x71, + 0x0c, 0xb2, 0x71, 0x06, 0x85, 0x71, 0xa7, 0x35, + 0x07, 0x89, 0x35, 0x05, 0xa5, 0x2c, 0x02, 0x9c, + 0x2c, 0x07, 0x81, 0x2c, 0x60, 0x6f, 0x9e, 0x04, + 0x00, 0xa9, 0xad, 0x00, 0x82, 0xad, 0x01, 0x81, + 0xad, 0x0f, 0x85, 0x04, 0x07, 0x88, 0x04, 0x20, + 0x85, 0x04, 0xa7, 0x76, 0x07, 0xa9, 0x8d, 0x15, + 0x99, 0x79, 0x25, 0x9b, 0x19, 0x13, 0x96, 0x27, + 0x08, 0xcd, 0x0f, 0x03, 0xa3, 0x0f, 0x08, 0x80, + 0x0f, 0xc2, 0x3f, 0x09, 0x80, 0x3f, 0x01, 0x98, + 0x8e, 0x06, 0x89, 0x8e, 0x05, 0xb4, 0x16, 0x00, + 0x91, 0x16, 0x07, 0xa6, 0x55, 0x08, 0xdf, 0x87, + 0x00, 0x93, 0x8c, 0x0a, 0x91, 0x47, 0x00, 0xae, + 0x47, 0x3d, 0x86, 0x64, 0x00, 0x80, 0x64, 0x00, + 0x83, 0x64, 0x00, 0x8e, 0x64, 0x00, 0x8a, 0x64, + 0x05, 0xba, 0x49, 0x04, 0x89, 0x49, 0x05, 0x83, + 0x2d, 0x00, 0x87, 0x2d, 0x01, 0x81, 0x2d, 0x01, + 0x95, 0x2d, 0x00, 0x86, 0x2d, 0x00, 0x81, 0x2d, + 0x00, 0x84, 0x2d, 0x00, 0x80, 0x3b, 0x88, 0x2d, + 0x01, 0x81, 0x2d, 0x01, 0x82, 0x2d, 0x01, 0x80, + 0x2d, 0x05, 0x80, 0x2d, 0x04, 0x86, 0x2d, 0x01, + 0x86, 0x2d, 0x02, 0x84, 0x2d, 0x0a, 0x89, 0xa7, + 0x00, 0x80, 0xa7, 0x01, 0x80, 0xa7, 0x00, 0xa5, + 0xa7, 0x00, 0x89, 0xa7, 0x00, 0x80, 0xa7, 0x01, + 0x80, 0xa7, 0x00, 0x83, 0xa7, 0x00, 0x89, 0xa7, + 0x00, 0x81, 0xa7, 0x07, 0x81, 0xa7, 0x1c, 0xdb, + 0x6a, 0x00, 0x84, 0x6a, 0x1d, 0xc7, 0xa2, 0x07, + 0x89, 0xa2, 0x60, 0x45, 0xb5, 0x89, 0x01, 0xa5, + 0x89, 0x21, 0xc4, 0x61, 0x0a, 0x89, 0x61, 0x05, + 0x8c, 0x62, 0x12, 0xb9, 0x9a, 0x05, 0x89, 0x9a, + 0x05, 0x93, 0x65, 0x1b, 0x9a, 0x02, 0x01, 0x8e, + 0x02, 0x03, 0x96, 0x02, 0x60, 0x58, 0xbb, 0x23, + 0x60, 0x03, 0xd2, 0xac, 0x0b, 0x80, 0xac, 0x86, + 0x22, 0x01, 0x80, 0x22, 0x01, 0x87, 0x22, 0x00, + 0x81, 0x22, 0x00, 0x9d, 0x22, 0x00, 0x81, 0x22, + 0x01, 0x8b, 0x22, 0x08, 0x89, 0x22, 0x45, 0x87, + 0x68, 0x01, 0xad, 0x68, 0x01, 0x8a, 0x68, 0x1a, + 0xc7, 0xaf, 0x07, 0xd2, 0x8f, 0x0c, 0x8f, 0x13, + 0xb8, 0x7f, 0x06, 0x89, 0x21, 0x55, 0x87, 0x87, + 0x57, 0xa1, 0x91, 0x0d, 0x89, 0x91, 0x05, 0x88, + 0x0d, 0x00, 0xac, 0x0d, 0x00, 0x8d, 0x0d, 0x09, + 0x9c, 0x0d, 0x02, 0x9f, 0x59, 0x01, 0x95, 0x59, + 0x00, 0x8d, 0x59, 0x48, 0x86, 0x5a, 0x00, 0x81, + 0x5a, 0x00, 0xab, 0x5a, 0x02, 0x80, 0x5a, 0x00, + 0x81, 0x5a, 0x00, 0x88, 0x5a, 0x07, 0x89, 0x5a, + 0x05, 0x85, 0x30, 0x00, 0x81, 0x30, 0x00, 0xa4, + 0x30, 0x00, 0x81, 0x30, 0x00, 0x85, 0x30, 0x06, + 0x89, 0x30, 0x05, 0xab, 0xa5, 0x03, 0x89, 0xa5, + 0x60, 0x95, 0x98, 0x54, 0x06, 0x90, 0x43, 0x00, + 0xa8, 0x43, 0x02, 0x9c, 0x43, 0x54, 0x80, 0x51, + 0x0e, 0xb1, 0x9b, 0x0c, 0x80, 0x9b, 0xe3, 0x39, + 0x1c, 0x60, 0x05, 0xe0, 0x0e, 0x1c, 0x00, 0x84, + 0x1c, 0x0a, 0xe0, 0x63, 0x1c, 0x69, 0xeb, 0xe0, + 0x02, 0x1f, 0x0c, 0xe3, 0xf5, 0x25, 0x09, 0xef, + 0x3a, 0x25, 0x04, 0xe1, 0xe6, 0x03, 0x70, 0x0a, + 0x58, 0xb9, 0x32, 0x66, 0x65, 0xe1, 0xd8, 0x08, + 0x06, 0x9e, 0x63, 0x00, 0x89, 0x63, 0x03, 0x81, + 0x63, 0xce, 0xa3, 0x00, 0x89, 0xa3, 0x05, 0x9d, + 0x09, 0x01, 0x85, 0x09, 0x09, 0xc5, 0x7d, 0x09, + 0x89, 0x7d, 0x00, 0x86, 0x7d, 0x00, 0x94, 0x7d, + 0x04, 0x92, 0x7d, 0x61, 0x4f, 0xb9, 0x4a, 0x60, + 0x65, 0xda, 0x5b, 0x04, 0x98, 0x0c, 0x01, 0x98, + 0x0c, 0x2b, 0xca, 0x60, 0x03, 0xb8, 0x60, 0x06, + 0x90, 0x60, 0x3f, 0x80, 0x9c, 0x80, 0x6c, 0x81, + 0x33, 0x80, 0x48, 0x0a, 0x86, 0x33, 0x08, 0xf0, + 0x0a, 0x9f, 0x9c, 0xe1, 0x75, 0x48, 0x28, 0x80, + 0x48, 0x9e, 0x9c, 0x60, 0x00, 0xe0, 0x12, 0x9c, + 0x70, 0x11, 0x9c, 0x83, 0x41, 0x00, 0x86, 0x41, + 0x00, 0x81, 0x41, 0x00, 0x80, 0x41, 0xe0, 0xbe, + 0x39, 0x82, 0x41, 0x0e, 0x80, 0x39, 0x1c, 0x82, + 0x39, 0x01, 0x80, 0x41, 0x0d, 0x83, 0x41, 0x07, + 0xe1, 0x2b, 0x6c, 0x68, 0xa3, 0xe0, 0x0a, 0x24, + 0x04, 0x8c, 0x24, 0x02, 0x88, 0x24, 0x06, 0x89, + 0x24, 0x01, 0x83, 0x24, 0x83, 0x1a, 0x6e, 0xfb, + 0xe0, 0x9c, 0x1a, 0x02, 0xe1, 0x53, 0x1a, 0x05, + 0x96, 0x1a, 0x0e, 0x90, 0x1a, 0x0e, 0xad, 0x3b, + 0x01, 0x96, 0x3b, 0x08, 0xe0, 0x13, 0x1a, 0x3b, + 0xe0, 0x95, 0x1a, 0x09, 0xa6, 0x1a, 0x01, 0xbd, + 0x1a, 0x82, 0x3b, 0x90, 0x1a, 0x87, 0x3b, 0x81, + 0x1a, 0x86, 0x3b, 0x9d, 0x1a, 0x83, 0x3b, 0xbc, + 0x1a, 0x14, 0xc5, 0x2e, 0x60, 0x19, 0x93, 0x1a, + 0x0b, 0x93, 0x1a, 0x0b, 0xd6, 0x1a, 0x08, 0x98, + 0x1a, 0x60, 0x26, 0xd4, 0x1a, 0x00, 0xc6, 0x1a, + 0x00, 0x81, 0x1a, 0x01, 0x80, 0x1a, 0x01, 0x81, + 0x1a, 0x01, 0x83, 0x1a, 0x00, 0x8b, 0x1a, 0x00, + 0x80, 0x1a, 0x00, 0x86, 0x1a, 0x00, 0xc0, 0x1a, + 0x00, 0x83, 0x1a, 0x01, 0x87, 0x1a, 0x00, 0x86, + 0x1a, 0x00, 0x9b, 0x1a, 0x00, 0x83, 0x1a, 0x00, + 0x84, 0x1a, 0x00, 0x80, 0x1a, 0x02, 0x86, 0x1a, + 0x00, 0xe0, 0xf3, 0x1a, 0x01, 0xe0, 0xc3, 0x1a, + 0x01, 0xb1, 0x1a, 0xe2, 0x2b, 0x8b, 0x0e, 0x84, + 0x8b, 0x00, 0x8e, 0x8b, 0x63, 0xef, 0x9e, 0x4c, + 0x05, 0x85, 0x4c, 0x60, 0x74, 0x86, 0x2a, 0x00, + 0x90, 0x2a, 0x01, 0x86, 0x2a, 0x00, 0x81, 0x2a, + 0x00, 0x84, 0x2a, 0x04, 0xbd, 0x1e, 0x20, 0x80, + 0x1e, 0x60, 0x0f, 0xac, 0x6d, 0x02, 0x8d, 0x6d, + 0x01, 0x89, 0x6d, 0x03, 0x81, 0x6d, 0x60, 0xdf, + 0x9e, 0xa6, 0x10, 0xb9, 0xab, 0x04, 0x80, 0xab, + 0x61, 0x6f, 0xa9, 0x67, 0x60, 0x75, 0xaa, 0x70, + 0x03, 0x80, 0x70, 0x60, 0x5f, 0x9e, 0x99, 0x00, + 0x95, 0x99, 0x07, 0x81, 0x99, 0x60, 0x7f, 0x86, + 0x28, 0x00, 0x83, 0x28, 0x00, 0x81, 0x28, 0x00, + 0x8e, 0x28, 0x00, 0xe0, 0x64, 0x5d, 0x01, 0x8f, + 0x5d, 0x28, 0xcb, 0x01, 0x03, 0x89, 0x01, 0x03, + 0x81, 0x01, 0x62, 0xb0, 0xc3, 0x1a, 0x4b, 0xbc, + 0x1a, 0x60, 0x61, 0x83, 0x04, 0x00, 0x9a, 0x04, + 0x00, 0x81, 0x04, 0x00, 0x80, 0x04, 0x01, 0x80, + 0x04, 0x00, 0x89, 0x04, 0x00, 0x83, 0x04, 0x00, + 0x80, 0x04, 0x00, 0x80, 0x04, 0x05, 0x80, 0x04, + 0x03, 0x80, 0x04, 0x00, 0x80, 0x04, 0x00, 0x80, + 0x04, 0x00, 0x82, 0x04, 0x00, 0x81, 0x04, 0x00, + 0x80, 0x04, 0x01, 0x80, 0x04, 0x00, 0x80, 0x04, + 0x00, 0x80, 0x04, 0x00, 0x80, 0x04, 0x00, 0x80, + 0x04, 0x00, 0x81, 0x04, 0x00, 0x80, 0x04, 0x01, + 0x83, 0x04, 0x00, 0x86, 0x04, 0x00, 0x83, 0x04, + 0x00, 0x83, 0x04, 0x00, 0x80, 0x04, 0x00, 0x89, + 0x04, 0x00, 0x90, 0x04, 0x04, 0x82, 0x04, 0x00, + 0x84, 0x04, 0x00, 0x90, 0x04, 0x33, 0x81, 0x04, + 0x60, 0xad, 0xab, 0x1a, 0x03, 0xe0, 0x03, 0x1a, + 0x0b, 0x8e, 0x1a, 0x01, 0x8e, 0x1a, 0x00, 0x8e, + 0x1a, 0x00, 0xa4, 0x1a, 0x09, 0xe0, 0x4d, 0x1a, + 0x37, 0x99, 0x1a, 0x80, 0x39, 0x81, 0x1a, 0x0c, + 0xab, 0x1a, 0x03, 0x88, 0x1a, 0x06, 0x81, 0x1a, + 0x0d, 0x85, 0x1a, 0x60, 0x39, 0xe3, 0x78, 0x1a, + 0x02, 0x90, 0x1a, 0x02, 0x8c, 0x1a, 0x02, 0xe0, + 0x79, 0x1a, 0x05, 0x8b, 0x1a, 0x03, 0x80, 0x1a, + 0x0e, 0x8b, 0x1a, 0x03, 0xb7, 0x1a, 0x07, 0x89, + 0x1a, 0x05, 0xa7, 0x1a, 0x07, 0x9d, 0x1a, 0x01, + 0x8b, 0x1a, 0x03, 0x81, 0x1a, 0x0d, 0x88, 0x1a, + 0x26, 0xe0, 0xf7, 0x1a, 0x07, 0x8d, 0x1a, 0x01, + 0x8c, 0x1a, 0x02, 0x8a, 0x1a, 0x02, 0xb8, 0x1a, + 0x00, 0x80, 0x1a, 0x03, 0x8f, 0x1a, 0x01, 0x8b, + 0x1a, 0x03, 0x89, 0x1a, 0x06, 0xe0, 0x32, 0x1a, + 0x00, 0xe0, 0x06, 0x1a, 0x63, 0xa4, 0xf0, 0x96, + 0x7f, 0x33, 0x1f, 0xf0, 0x00, 0xbd, 0x33, 0x01, + 0xf0, 0x06, 0x2d, 0x33, 0x01, 0xf0, 0x0c, 0xd0, + 0x33, 0x0e, 0xe2, 0x0d, 0x33, 0x69, 0x41, 0xe1, + 0xbd, 0x33, 0x65, 0x81, 0xf0, 0x02, 0xea, 0x33, + 0x04, 0xf0, 0x10, 0xc9, 0x33, 0x7a, 0xbb, 0x26, + 0x80, 0x1a, 0x1d, 0xdf, 0x1a, 0x60, 0x1f, 0xe0, + 0x8f, 0x3b, +}; + +static const uint8_t unicode_script_ext_table[1278] = { + 0x80, 0x36, 0x00, 0x00, 0x10, 0x06, 0x14, 0x1b, + 0x24, 0x26, 0x29, 0x2a, 0x30, 0x2b, 0x2e, 0x33, + 0x4c, 0x53, 0x55, 0x74, 0x88, 0x81, 0x83, 0x00, + 0x00, 0x07, 0x0b, 0x1e, 0x21, 0x4c, 0x51, 0x9f, + 0xa6, 0x09, 0x00, 0x00, 0x02, 0x0e, 0x4c, 0x00, + 0x00, 0x02, 0x02, 0x0e, 0x4c, 0x00, 0x00, 0x00, + 0x02, 0x4c, 0x51, 0x08, 0x00, 0x00, 0x02, 0x4c, + 0x9f, 0x00, 0x00, 0x00, 0x02, 0x0e, 0x4c, 0x25, + 0x00, 0x00, 0x08, 0x18, 0x1b, 0x1e, 0x2e, 0x4c, + 0x74, 0x91, 0x96, 0x00, 0x08, 0x18, 0x1e, 0x2e, + 0x4c, 0x7b, 0x91, 0x96, 0xa4, 0x00, 0x04, 0x18, + 0x1e, 0x4c, 0xa1, 0x00, 0x05, 0x2a, 0x4c, 0x91, + 0x93, 0x9f, 0x00, 0x0b, 0x15, 0x18, 0x1b, 0x1e, + 0x2b, 0x2e, 0x4c, 0x7b, 0x93, 0xa1, 0xa4, 0x00, + 0x06, 0x1b, 0x26, 0x2a, 0x2b, 0x41, 0x4c, 0x00, + 0x05, 0x1e, 0x2e, 0x4c, 0x74, 0xa1, 0x00, 0x09, + 0x1b, 0x24, 0x38, 0x4c, 0x74, 0x93, 0x96, 0xa1, + 0xa4, 0x00, 0x0b, 0x05, 0x1e, 0x24, 0x2b, 0x2e, + 0x38, 0x4c, 0x74, 0x93, 0x96, 0xa1, 0x00, 0x02, + 0x4c, 0xa1, 0x00, 0x03, 0x24, 0x4c, 0x93, 0x00, + 0x04, 0x18, 0x1e, 0x4c, 0x7b, 0x00, 0x03, 0x18, + 0x4c, 0x96, 0x00, 0x02, 0x4c, 0x91, 0x00, 0x02, + 0x28, 0x4c, 0x00, 0x00, 0x00, 0x02, 0x4c, 0x91, + 0x00, 0x03, 0x1e, 0x4c, 0xa4, 0x00, 0x00, 0x00, + 0x04, 0x2e, 0x4c, 0x74, 0xa4, 0x0e, 0x00, 0x00, + 0x06, 0x18, 0x24, 0x41, 0x4c, 0x93, 0xa1, 0x00, + 0x04, 0x18, 0x24, 0x4c, 0x93, 0x00, 0x02, 0x4c, + 0x93, 0x06, 0x00, 0x00, 0x03, 0x4c, 0x91, 0x93, + 0x00, 0x02, 0x4c, 0x93, 0x00, 0x00, 0x00, 0x03, + 0x18, 0x4c, 0x93, 0x00, 0x07, 0x15, 0x18, 0x2b, + 0x4c, 0x91, 0x93, 0x9f, 0x0f, 0x00, 0x00, 0x01, + 0x2e, 0x01, 0x00, 0x00, 0x01, 0x2e, 0x11, 0x00, + 0x00, 0x02, 0x4c, 0x7b, 0x04, 0x00, 0x00, 0x03, + 0x15, 0x4c, 0xa4, 0x03, 0x00, 0x0c, 0x01, 0x4c, + 0x03, 0x00, 0x01, 0x02, 0x1b, 0x2e, 0x80, 0x8c, + 0x00, 0x00, 0x02, 0x1e, 0x74, 0x00, 0x02, 0x1e, + 0x2a, 0x01, 0x02, 0x1e, 0x4c, 0x00, 0x02, 0x1e, + 0x2a, 0x80, 0x80, 0x00, 0x00, 0x03, 0x05, 0x29, + 0x2a, 0x80, 0x01, 0x00, 0x00, 0x07, 0x04, 0x2c, + 0x6b, 0x35, 0x93, 0x9e, 0xad, 0x0d, 0x00, 0x00, + 0x07, 0x04, 0x2c, 0x6b, 0x35, 0x93, 0x9e, 0xad, + 0x00, 0x03, 0x04, 0x93, 0x9e, 0x01, 0x00, 0x00, + 0x08, 0x01, 0x04, 0x2c, 0x6b, 0x35, 0x93, 0x9e, + 0xad, 0x1f, 0x00, 0x00, 0x09, 0x01, 0x04, 0x57, + 0x58, 0x79, 0x82, 0x35, 0x8d, 0x93, 0x09, 0x00, + 0x0a, 0x02, 0x04, 0x93, 0x09, 0x00, 0x09, 0x03, + 0x04, 0x9e, 0xad, 0x05, 0x00, 0x00, 0x02, 0x04, + 0x93, 0x62, 0x00, 0x00, 0x02, 0x04, 0x35, 0x81, + 0xfb, 0x00, 0x00, 0x0f, 0x0b, 0x21, 0x2d, 0x2f, + 0x31, 0x40, 0x4c, 0x56, 0x68, 0x6a, 0x7a, 0x87, + 0x9b, 0x9d, 0xa2, 0x00, 0x0d, 0x0b, 0x21, 0x2d, + 0x2f, 0x31, 0x40, 0x4c, 0x56, 0x6a, 0x7a, 0x9b, + 0x9d, 0xa2, 0x10, 0x00, 0x00, 0x15, 0x0b, 0x21, + 0x23, 0x30, 0x5a, 0x2d, 0x2f, 0x31, 0x40, 0x55, + 0x56, 0x68, 0x70, 0x7a, 0x49, 0x8c, 0x92, 0x9a, + 0x9b, 0x9d, 0xa2, 0x00, 0x17, 0x0b, 0x21, 0x23, + 0x30, 0x5a, 0x2d, 0x2f, 0x32, 0x31, 0x40, 0x4e, + 0x55, 0x56, 0x68, 0x70, 0x7a, 0x49, 0x8c, 0x92, + 0x9a, 0x9b, 0x9d, 0xa2, 0x09, 0x04, 0x21, 0x23, + 0x3f, 0x55, 0x75, 0x00, 0x09, 0x03, 0x0b, 0x16, + 0x92, 0x75, 0x00, 0x09, 0x02, 0x31, 0x64, 0x75, + 0x00, 0x09, 0x02, 0x2f, 0x47, 0x80, 0x75, 0x00, + 0x0d, 0x02, 0x2d, 0x9b, 0x80, 0x71, 0x00, 0x09, + 0x03, 0x40, 0x68, 0xa7, 0x82, 0xcf, 0x00, 0x09, + 0x03, 0x16, 0x65, 0x96, 0x80, 0x30, 0x00, 0x00, + 0x03, 0x29, 0x2a, 0x4c, 0x85, 0x6e, 0x00, 0x02, + 0x01, 0x84, 0x46, 0x00, 0x01, 0x04, 0x12, 0x36, + 0x95, 0x94, 0x80, 0x4a, 0x00, 0x01, 0x02, 0x62, + 0x80, 0x00, 0x00, 0x00, 0x02, 0x62, 0x80, 0x84, + 0x49, 0x00, 0x00, 0x04, 0x0b, 0x21, 0x2d, 0x40, + 0x00, 0x01, 0x21, 0x00, 0x04, 0x0b, 0x21, 0x2d, + 0x40, 0x00, 0x03, 0x21, 0x2d, 0x40, 0x00, 0x01, + 0x21, 0x00, 0x05, 0x0b, 0x21, 0x6a, 0x9d, 0xa2, + 0x00, 0x03, 0x0b, 0x21, 0x9d, 0x00, 0x03, 0x21, + 0x6a, 0x87, 0x00, 0x04, 0x0b, 0x21, 0x6a, 0x9d, + 0x00, 0x02, 0x21, 0x87, 0x00, 0x06, 0x21, 0x40, + 0x56, 0x7a, 0x9b, 0x9d, 0x00, 0x01, 0x21, 0x01, + 0x02, 0x21, 0x87, 0x01, 0x01, 0x21, 0x00, 0x02, + 0x21, 0x87, 0x00, 0x02, 0x0b, 0x21, 0x00, 0x03, + 0x21, 0x6a, 0xa2, 0x05, 0x01, 0x21, 0x00, 0x03, + 0x21, 0x68, 0x6a, 0x00, 0x03, 0x0b, 0x21, 0x87, + 0x00, 0x02, 0x21, 0x6a, 0x00, 0x01, 0x21, 0x00, + 0x04, 0x0b, 0x21, 0x6a, 0x87, 0x03, 0x01, 0x21, + 0x00, 0x0b, 0x0b, 0x21, 0x2d, 0x40, 0x56, 0x68, + 0x7a, 0x8c, 0x9d, 0xa2, 0xa7, 0x00, 0x02, 0x21, + 0x2d, 0x00, 0x04, 0x21, 0x2d, 0x40, 0xa7, 0x01, + 0x02, 0x0b, 0x21, 0x00, 0x01, 0x0b, 0x01, 0x02, + 0x21, 0x2d, 0x00, 0x01, 0x68, 0x80, 0x44, 0x00, + 0x01, 0x01, 0x2e, 0x35, 0x00, 0x00, 0x03, 0x1e, + 0x4c, 0x93, 0x00, 0x00, 0x00, 0x01, 0x93, 0x81, + 0xb3, 0x00, 0x00, 0x03, 0x4c, 0x62, 0x80, 0x1e, + 0x00, 0x00, 0x02, 0x01, 0x04, 0x09, 0x00, 0x00, + 0x06, 0x14, 0x29, 0x2a, 0x71, 0x52, 0x78, 0x01, + 0x00, 0x00, 0x04, 0x14, 0x2e, 0x71, 0x5f, 0x80, + 0x11, 0x00, 0x00, 0x03, 0x21, 0x2d, 0x4c, 0x8c, + 0xa5, 0x00, 0x00, 0x02, 0x1b, 0x4c, 0x17, 0x00, + 0x00, 0x02, 0x06, 0x78, 0x00, 0x07, 0x06, 0x14, + 0x29, 0x71, 0x3f, 0x53, 0x85, 0x09, 0x00, 0x00, + 0x01, 0x24, 0x03, 0x00, 0x00, 0x03, 0x01, 0x04, + 0x71, 0x00, 0x00, 0x00, 0x02, 0x1e, 0x2a, 0x81, + 0x2b, 0x00, 0x0f, 0x02, 0x33, 0x9c, 0x00, 0x00, + 0x00, 0x07, 0x0e, 0x34, 0x33, 0x39, 0x41, 0x62, + 0xae, 0x00, 0x08, 0x0e, 0x34, 0x33, 0x39, 0x41, + 0x62, 0x80, 0xae, 0x00, 0x05, 0x0e, 0x34, 0x33, + 0x39, 0x41, 0x01, 0x00, 0x00, 0x01, 0x33, 0x00, + 0x00, 0x01, 0x08, 0x0e, 0x34, 0x33, 0x39, 0x41, + 0x62, 0xa0, 0xae, 0x01, 0x09, 0x0e, 0x34, 0x33, + 0x39, 0x41, 0x51, 0x62, 0xa0, 0xae, 0x05, 0x06, + 0x0e, 0x34, 0x33, 0x39, 0x41, 0xae, 0x00, 0x00, + 0x00, 0x05, 0x0e, 0x34, 0x33, 0x39, 0x41, 0x07, + 0x06, 0x0e, 0x34, 0x33, 0x39, 0x41, 0xae, 0x03, + 0x05, 0x0e, 0x34, 0x33, 0x39, 0x41, 0x09, 0x00, + 0x03, 0x02, 0x0e, 0x33, 0x01, 0x00, 0x00, 0x05, + 0x0e, 0x34, 0x33, 0x39, 0x41, 0x04, 0x02, 0x39, + 0x41, 0x00, 0x00, 0x00, 0x05, 0x0e, 0x34, 0x33, + 0x39, 0x41, 0x03, 0x00, 0x01, 0x03, 0x33, 0x39, + 0x41, 0x01, 0x01, 0x33, 0x58, 0x00, 0x03, 0x02, + 0x39, 0x41, 0x02, 0x00, 0x00, 0x02, 0x39, 0x41, + 0x59, 0x00, 0x00, 0x06, 0x0e, 0x34, 0x33, 0x39, + 0x41, 0xae, 0x00, 0x02, 0x39, 0x41, 0x80, 0x12, + 0x00, 0x0f, 0x01, 0x33, 0x1f, 0x00, 0x25, 0x01, + 0x33, 0x08, 0x00, 0x00, 0x02, 0x33, 0x9c, 0x2f, + 0x00, 0x27, 0x01, 0x33, 0x37, 0x00, 0x30, 0x01, + 0x33, 0x0e, 0x00, 0x0b, 0x01, 0x33, 0x32, 0x00, + 0x00, 0x01, 0x33, 0x57, 0x00, 0x18, 0x01, 0x33, + 0x09, 0x00, 0x04, 0x01, 0x33, 0x5f, 0x00, 0x1e, + 0x01, 0x33, 0xc0, 0x31, 0xef, 0x00, 0x00, 0x02, + 0x1e, 0x2a, 0x80, 0x0f, 0x00, 0x07, 0x02, 0x33, + 0x4c, 0x80, 0xa7, 0x00, 0x02, 0x10, 0x21, 0x23, + 0x2f, 0x31, 0x47, 0x40, 0x3f, 0x55, 0x56, 0x61, + 0x68, 0x87, 0x49, 0x9a, 0xa2, 0xa7, 0x02, 0x0f, + 0x21, 0x23, 0x2f, 0x31, 0x47, 0x40, 0x3f, 0x55, + 0x61, 0x68, 0x87, 0x49, 0x9a, 0xa2, 0xa7, 0x01, + 0x0b, 0x21, 0x23, 0x2f, 0x31, 0x47, 0x3f, 0x55, + 0x61, 0x49, 0x9a, 0xa2, 0x00, 0x0c, 0x21, 0x23, + 0x2f, 0x31, 0x47, 0x3f, 0x55, 0x61, 0x87, 0x49, + 0x9a, 0xa2, 0x00, 0x0b, 0x21, 0x23, 0x2f, 0x31, + 0x47, 0x3f, 0x55, 0x61, 0x49, 0x9a, 0xa2, 0x80, + 0x36, 0x00, 0x00, 0x03, 0x0b, 0x21, 0xa7, 0x00, + 0x00, 0x00, 0x02, 0x21, 0x9b, 0x39, 0x00, 0x00, + 0x03, 0x44, 0x4c, 0x65, 0x80, 0x1f, 0x00, 0x00, + 0x02, 0x11, 0x3e, 0xc0, 0x12, 0xed, 0x00, 0x01, + 0x02, 0x04, 0x6b, 0x80, 0x31, 0x00, 0x00, 0x02, + 0x04, 0x9e, 0x09, 0x00, 0x00, 0x02, 0x04, 0x9e, + 0x46, 0x00, 0x01, 0x05, 0x0e, 0x34, 0x33, 0x39, + 0x41, 0x80, 0x99, 0x00, 0x04, 0x06, 0x0e, 0x34, + 0x33, 0x39, 0x41, 0xae, 0x09, 0x00, 0x00, 0x02, + 0x39, 0x41, 0x2c, 0x00, 0x01, 0x02, 0x39, 0x41, + 0x80, 0xdf, 0x00, 0x01, 0x03, 0x1f, 0x1d, 0x50, + 0x00, 0x02, 0x1d, 0x50, 0x03, 0x00, 0x2c, 0x03, + 0x1d, 0x4f, 0x50, 0x02, 0x00, 0x08, 0x02, 0x1d, + 0x50, 0x81, 0x1f, 0x00, 0x1b, 0x02, 0x04, 0x1b, + 0x87, 0x75, 0x00, 0x00, 0x02, 0x58, 0x79, 0x87, + 0x8d, 0x00, 0x00, 0x02, 0x2d, 0x9b, 0x00, 0x00, + 0x00, 0x02, 0x2d, 0x9b, 0x36, 0x00, 0x01, 0x02, + 0x2d, 0x9b, 0x8c, 0x12, 0x00, 0x01, 0x02, 0x2d, + 0x9b, 0x00, 0x00, 0x00, 0x02, 0x2d, 0x9b, 0xc0, + 0x5c, 0x4b, 0x00, 0x03, 0x01, 0x24, 0x96, 0x3b, + 0x00, 0x11, 0x01, 0x33, 0x9e, 0x5d, 0x00, 0x01, + 0x01, 0x33, 0xce, 0xcd, 0x2d, 0x00, +}; + +static const uint8_t unicode_prop_Hyphen_table[28] = { + 0xac, 0x80, 0xfe, 0x80, 0x44, 0xdb, 0x80, 0x52, + 0x7a, 0x80, 0x48, 0x08, 0x81, 0x4e, 0x04, 0x80, + 0x42, 0xe2, 0x80, 0x60, 0xcd, 0x66, 0x80, 0x40, + 0xa8, 0x80, 0xd6, 0x80, +}; + +static const uint8_t unicode_prop_Other_Math_table[200] = { + 0xdd, 0x80, 0x43, 0x70, 0x11, 0x80, 0x99, 0x09, + 0x81, 0x5c, 0x1f, 0x80, 0x9a, 0x82, 0x8a, 0x80, + 0x9f, 0x83, 0x97, 0x81, 0x8d, 0x81, 0xc0, 0x8c, + 0x18, 0x11, 0x1c, 0x91, 0x03, 0x01, 0x89, 0x00, + 0x14, 0x28, 0x11, 0x09, 0x02, 0x05, 0x13, 0x24, + 0xca, 0x21, 0x18, 0x08, 0x08, 0x00, 0x21, 0x0b, + 0x0b, 0x91, 0x09, 0x00, 0x06, 0x00, 0x29, 0x41, + 0x21, 0x83, 0x40, 0xa7, 0x08, 0x80, 0x97, 0x80, + 0x90, 0x80, 0x41, 0xbc, 0x81, 0x8b, 0x88, 0x24, + 0x21, 0x09, 0x14, 0x8d, 0x00, 0x01, 0x85, 0x97, + 0x81, 0xb8, 0x00, 0x80, 0x9c, 0x83, 0x88, 0x81, + 0x41, 0x55, 0x81, 0x9e, 0x89, 0x41, 0x92, 0x95, + 0xbe, 0x83, 0x9f, 0x81, 0x60, 0xd4, 0x62, 0x00, + 0x03, 0x80, 0x40, 0xd2, 0x00, 0x80, 0x60, 0xd4, + 0xc0, 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b, + 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f, + 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, 0x80, + 0x41, 0x53, 0x81, 0x98, 0x80, 0x98, 0x80, 0x9e, + 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, + 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x07, 0x81, + 0xb1, 0x55, 0xff, 0x18, 0x9a, 0x01, 0x00, 0x08, + 0x80, 0x89, 0x03, 0x00, 0x00, 0x28, 0x18, 0x00, + 0x00, 0x02, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x0b, 0x06, 0x03, 0x03, 0x00, + 0x80, 0x89, 0x80, 0x90, 0x22, 0x04, 0x80, 0x90, +}; + +static const uint8_t unicode_prop_Other_Alphabetic_table[452] = { + 0x43, 0x44, 0x80, 0x9c, 0x8c, 0x42, 0x3f, 0x8d, + 0x00, 0x01, 0x01, 0x00, 0xc7, 0x8a, 0xaf, 0x8c, + 0x06, 0x8f, 0x80, 0xe4, 0x33, 0x19, 0x0b, 0x80, + 0xa2, 0x80, 0x9d, 0x8f, 0xe5, 0x8a, 0xe4, 0x0a, + 0x88, 0x02, 0x03, 0xe9, 0x80, 0xbb, 0x8b, 0x16, + 0x85, 0x93, 0xb5, 0x09, 0x8e, 0x01, 0x22, 0x89, + 0x81, 0x9c, 0x82, 0xb9, 0x31, 0x09, 0x81, 0x89, + 0x80, 0x89, 0x81, 0x9c, 0x82, 0xb9, 0x23, 0x09, + 0x0b, 0x80, 0x9d, 0x0a, 0x80, 0x8a, 0x82, 0xb9, + 0x38, 0x10, 0x81, 0x94, 0x81, 0x95, 0x13, 0x82, + 0xb9, 0x31, 0x09, 0x81, 0x88, 0x81, 0x89, 0x81, + 0x9d, 0x80, 0xba, 0x22, 0x10, 0x82, 0x89, 0x80, + 0xa7, 0x84, 0xb8, 0x30, 0x10, 0x17, 0x81, 0x8a, + 0x81, 0x9c, 0x82, 0xb9, 0x30, 0x10, 0x17, 0x81, + 0x8a, 0x81, 0x8e, 0x80, 0x8b, 0x83, 0xb9, 0x30, + 0x10, 0x82, 0x89, 0x80, 0x89, 0x81, 0x9c, 0x82, + 0xca, 0x28, 0x00, 0x87, 0x91, 0x81, 0xbc, 0x01, + 0x86, 0x91, 0x80, 0xe2, 0x01, 0x28, 0x81, 0x8f, + 0x80, 0x40, 0xa2, 0x92, 0x88, 0x8a, 0x80, 0xa3, + 0xed, 0x8b, 0x00, 0x0b, 0x96, 0x1b, 0x10, 0x11, + 0x32, 0x83, 0x8c, 0x8b, 0x00, 0x89, 0x83, 0x46, + 0x73, 0x81, 0x9d, 0x81, 0x9d, 0x81, 0x9d, 0x81, + 0xc1, 0x92, 0x40, 0xbb, 0x81, 0xa1, 0x80, 0xf5, + 0x8b, 0x83, 0x88, 0x40, 0xdd, 0x84, 0xb8, 0x89, + 0x81, 0x93, 0xc9, 0x81, 0x8a, 0x82, 0xb0, 0x84, + 0xaf, 0x8e, 0xbb, 0x82, 0x9d, 0x88, 0x09, 0xb8, + 0x8a, 0xb1, 0x92, 0x41, 0x9b, 0xa1, 0x46, 0xc0, + 0xb3, 0x48, 0xf5, 0x9f, 0x60, 0x78, 0x73, 0x87, + 0xa1, 0x81, 0x41, 0x61, 0x07, 0x80, 0x96, 0x84, + 0xd7, 0x81, 0xb1, 0x8f, 0x00, 0xb8, 0x80, 0xa5, + 0x84, 0x9b, 0x8b, 0xac, 0x83, 0xaf, 0x8b, 0xa4, + 0x80, 0xc2, 0x8d, 0x8b, 0x07, 0x81, 0xac, 0x82, + 0xb1, 0x00, 0x11, 0x0c, 0x80, 0xab, 0x24, 0x80, + 0x40, 0xec, 0x87, 0x60, 0x4f, 0x32, 0x80, 0x48, + 0x56, 0x84, 0x46, 0x85, 0x10, 0x0c, 0x83, 0x43, + 0x13, 0x83, 0xc0, 0x80, 0x41, 0x40, 0x81, 0xcc, + 0x82, 0x41, 0x02, 0x82, 0xb4, 0x8d, 0xac, 0x81, + 0x8a, 0x82, 0xac, 0x88, 0x88, 0x80, 0xbc, 0x82, + 0xa3, 0x8b, 0x91, 0x81, 0xb8, 0x82, 0xaf, 0x8c, + 0x8d, 0x81, 0xdb, 0x88, 0x08, 0x28, 0x08, 0x40, + 0x9c, 0x89, 0x96, 0x83, 0xb9, 0x31, 0x09, 0x81, + 0x89, 0x80, 0x89, 0x81, 0xd3, 0x88, 0x00, 0x08, + 0x03, 0x01, 0xe6, 0x8c, 0x02, 0xe9, 0x91, 0x40, + 0xec, 0x31, 0x86, 0x9c, 0x81, 0xd1, 0x8e, 0x00, + 0xe9, 0x8a, 0xe6, 0x8d, 0x41, 0x00, 0x8c, 0x40, + 0xf6, 0x28, 0x09, 0x0a, 0x00, 0x80, 0x40, 0x8d, + 0x31, 0x2b, 0x80, 0x9b, 0x89, 0xa9, 0x20, 0x83, + 0x91, 0x8a, 0xad, 0x8d, 0x40, 0xc7, 0x87, 0x40, + 0xc6, 0x38, 0x86, 0xd2, 0x95, 0x80, 0x8d, 0xf9, + 0x2a, 0x00, 0x08, 0x10, 0x02, 0x80, 0xc1, 0x20, + 0x08, 0x83, 0x41, 0x5b, 0x83, 0x88, 0x08, 0x80, + 0xaf, 0x32, 0x82, 0x60, 0x41, 0xdc, 0x90, 0x4e, + 0x1f, 0x00, 0xb6, 0x33, 0xdc, 0x81, 0x60, 0x4c, + 0xab, 0x80, 0x60, 0x23, 0x60, 0x30, 0x90, 0x0e, + 0x01, 0x04, 0xe3, 0x80, 0x46, 0x52, 0x01, 0x06, + 0x0c, 0x80, 0x42, 0x50, 0x80, 0x47, 0xe7, 0x99, + 0x85, 0x99, 0x85, 0x99, +}; + +static const uint8_t unicode_prop_Other_Lowercase_table[68] = { + 0x40, 0xa9, 0x80, 0x8e, 0x80, 0x41, 0xf4, 0x88, + 0x31, 0x9d, 0x84, 0xdf, 0x80, 0xb3, 0x80, 0x4d, + 0x80, 0x80, 0x4c, 0x2e, 0xbe, 0x8c, 0x80, 0xa1, + 0xa4, 0x42, 0xb0, 0x80, 0x8c, 0x80, 0x8f, 0x8c, + 0x40, 0xd2, 0x8f, 0x43, 0x4f, 0x99, 0x47, 0x91, + 0x81, 0x60, 0x7a, 0x1d, 0x81, 0x40, 0xd1, 0x80, + 0xff, 0x1a, 0x81, 0x43, 0x61, 0x83, 0x88, 0x80, + 0x60, 0x5c, 0x15, 0x01, 0x10, 0xa9, 0x80, 0x88, + 0x60, 0xd8, 0x74, 0xbd, +}; + +static const uint8_t unicode_prop_Other_Uppercase_table[15] = { + 0x60, 0x21, 0x5f, 0x8f, 0x43, 0x45, 0x99, 0x61, + 0xcc, 0x5f, 0x99, 0x85, 0x99, 0x85, 0x99, +}; + +static const uint8_t unicode_prop_Other_Grapheme_Extend_table[112] = { + 0x49, 0xbd, 0x80, 0x97, 0x80, 0x41, 0x65, 0x80, + 0x97, 0x80, 0xe5, 0x80, 0x97, 0x80, 0x40, 0xe7, + 0x00, 0x03, 0x08, 0x81, 0x88, 0x81, 0xe6, 0x80, + 0x97, 0x80, 0xf6, 0x80, 0x8e, 0x80, 0x49, 0x34, + 0x80, 0x9d, 0x80, 0x43, 0xff, 0x04, 0x00, 0x04, + 0x81, 0xe4, 0x80, 0xc6, 0x81, 0x44, 0x17, 0x80, + 0x50, 0x20, 0x81, 0x60, 0x79, 0x22, 0x80, 0xeb, + 0x80, 0x60, 0x55, 0xdc, 0x81, 0x52, 0x1f, 0x80, + 0xf3, 0x80, 0x41, 0x07, 0x80, 0x8d, 0x80, 0x88, + 0x80, 0xdf, 0x80, 0x88, 0x01, 0x00, 0x14, 0x80, + 0x40, 0xdf, 0x80, 0x8b, 0x80, 0x40, 0xf0, 0x80, + 0x41, 0x05, 0x80, 0x42, 0x78, 0x80, 0x8b, 0x80, + 0x46, 0x02, 0x80, 0x60, 0x50, 0xad, 0x81, 0x60, + 0x61, 0x72, 0x0d, 0x85, 0x6c, 0x2e, 0xac, 0xdf, +}; + +static const uint8_t unicode_prop_Other_Default_Ignorable_Code_Point_table[32] = { + 0x43, 0x4e, 0x80, 0x4e, 0x0e, 0x81, 0x46, 0x52, + 0x81, 0x48, 0xae, 0x80, 0x50, 0xfd, 0x80, 0x60, + 0xce, 0x3a, 0x80, 0xce, 0x88, 0x6d, 0x00, 0x06, + 0x00, 0x9d, 0xdf, 0xff, 0x40, 0xef, 0x4e, 0x0f, +}; + +static const uint8_t unicode_prop_Other_ID_Start_table[11] = { + 0x58, 0x84, 0x81, 0x48, 0x90, 0x80, 0x94, 0x80, + 0x4f, 0x6b, 0x81, +}; + +static const uint8_t unicode_prop_Other_ID_Continue_table[22] = { + 0x40, 0xb6, 0x80, 0x42, 0xce, 0x80, 0x4f, 0xe0, + 0x88, 0x46, 0x67, 0x80, 0x46, 0x30, 0x81, 0x50, + 0xec, 0x80, 0x60, 0xce, 0x68, 0x80, +}; + +static const uint8_t unicode_prop_Prepended_Concatenation_Mark_table[19] = { + 0x45, 0xff, 0x85, 0x40, 0xd6, 0x80, 0xb0, 0x80, + 0x41, 0x7f, 0x81, 0xcf, 0x80, 0x61, 0x07, 0xd9, + 0x80, 0x8e, 0x80, +}; + +static const uint8_t unicode_prop_XID_Start1_table[31] = { + 0x43, 0x79, 0x80, 0x4a, 0xb7, 0x80, 0xfe, 0x80, + 0x60, 0x21, 0xe6, 0x81, 0x60, 0xcb, 0xc0, 0x85, + 0x41, 0x95, 0x81, 0xf3, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x80, 0x41, 0x1e, 0x81, +}; + +static const uint8_t unicode_prop_XID_Continue1_table[23] = { + 0x43, 0x79, 0x80, 0x60, 0x2d, 0x1f, 0x81, 0x60, + 0xcb, 0xc0, 0x85, 0x41, 0x95, 0x81, 0xf3, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, +}; + +static const uint8_t unicode_prop_Changes_When_Titlecased1_table[22] = { + 0x41, 0xc3, 0x08, 0x08, 0x81, 0xa4, 0x81, 0x4e, + 0xdc, 0xaa, 0x0a, 0x4e, 0x87, 0x3f, 0x3f, 0x87, + 0x8b, 0x80, 0x8e, 0x80, 0xae, 0x80, +}; + +static const uint8_t unicode_prop_Changes_When_Casefolded1_table[29] = { + 0x41, 0xef, 0x80, 0x41, 0x9e, 0x80, 0x9e, 0x80, + 0x5a, 0xe4, 0x83, 0x40, 0xb5, 0x00, 0x00, 0x00, + 0x80, 0xde, 0x06, 0x06, 0x80, 0x8a, 0x09, 0x81, + 0x89, 0x10, 0x81, 0x8d, 0x80, +}; + +static const uint8_t unicode_prop_Changes_When_NFKC_Casefolded1_table[449] = { + 0x40, 0x9f, 0x06, 0x00, 0x01, 0x00, 0x01, 0x12, + 0x10, 0x82, 0xf3, 0x80, 0x8b, 0x80, 0x40, 0x84, + 0x01, 0x01, 0x80, 0xa2, 0x01, 0x80, 0x40, 0xbb, + 0x88, 0x9e, 0x29, 0x84, 0xda, 0x08, 0x81, 0x89, + 0x80, 0xa3, 0x04, 0x02, 0x04, 0x08, 0x07, 0x80, + 0x9e, 0x80, 0xa0, 0x82, 0x9c, 0x80, 0x42, 0x28, + 0x80, 0xd7, 0x83, 0x42, 0xde, 0x87, 0xfb, 0x08, + 0x80, 0xd2, 0x01, 0x80, 0xa1, 0x11, 0x80, 0x40, + 0xfc, 0x81, 0x42, 0xd4, 0x80, 0xfe, 0x80, 0xa7, + 0x81, 0xad, 0x80, 0xb5, 0x80, 0x88, 0x03, 0x03, + 0x03, 0x80, 0x8b, 0x80, 0x88, 0x00, 0x26, 0x80, + 0x90, 0x80, 0x88, 0x03, 0x03, 0x03, 0x80, 0x8b, + 0x80, 0x41, 0x41, 0x80, 0xe1, 0x81, 0x46, 0x52, + 0x81, 0xd4, 0x84, 0x45, 0x1b, 0x10, 0x8a, 0x80, + 0x91, 0x80, 0x9b, 0x8c, 0x80, 0xa1, 0xa4, 0x40, + 0xd5, 0x83, 0x40, 0xb5, 0x00, 0x00, 0x00, 0x80, + 0x99, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, + 0xb7, 0x05, 0x00, 0x13, 0x05, 0x11, 0x02, 0x0c, + 0x11, 0x00, 0x00, 0x0c, 0x15, 0x05, 0x08, 0x8f, + 0x00, 0x20, 0x8b, 0x12, 0x2a, 0x08, 0x0b, 0x00, + 0x07, 0x82, 0x8c, 0x06, 0x92, 0x81, 0x9a, 0x80, + 0x8c, 0x8a, 0x80, 0xd6, 0x18, 0x10, 0x8a, 0x01, + 0x0c, 0x0a, 0x00, 0x10, 0x11, 0x02, 0x06, 0x05, + 0x1c, 0x85, 0x8f, 0x8f, 0x8f, 0x88, 0x80, 0x40, + 0xa1, 0x08, 0x81, 0x40, 0xf7, 0x81, 0x41, 0x34, + 0xd5, 0x99, 0x9a, 0x45, 0x20, 0x80, 0xe6, 0x82, + 0xe4, 0x80, 0x41, 0x9e, 0x81, 0x40, 0xf0, 0x80, + 0x41, 0x2e, 0x80, 0xd2, 0x80, 0x8b, 0x40, 0xd5, + 0xa9, 0x80, 0xb4, 0x00, 0x82, 0xdf, 0x09, 0x80, + 0xde, 0x80, 0xb0, 0xdd, 0x82, 0x8d, 0xdf, 0x9e, + 0x80, 0xa7, 0x87, 0xae, 0x80, 0x41, 0x7f, 0x60, + 0x72, 0x9b, 0x81, 0x40, 0xd1, 0x80, 0xff, 0x1a, + 0x81, 0x43, 0x61, 0x83, 0x88, 0x80, 0x60, 0x4d, + 0x95, 0x41, 0x0d, 0x08, 0x00, 0x81, 0x89, 0x00, + 0x00, 0x09, 0x82, 0xc3, 0x81, 0xe9, 0xc2, 0x00, + 0x97, 0x04, 0x00, 0x01, 0x01, 0x80, 0xeb, 0xa0, + 0x41, 0x6a, 0x91, 0xbf, 0x81, 0xb5, 0xa7, 0x8c, + 0x82, 0x99, 0x95, 0x94, 0x81, 0x8b, 0x80, 0x92, + 0x03, 0x1a, 0x00, 0x80, 0x40, 0x86, 0x08, 0x80, + 0x9f, 0x99, 0x40, 0x83, 0x15, 0x0d, 0x0d, 0x0a, + 0x16, 0x06, 0x80, 0x88, 0x47, 0x87, 0x20, 0xa9, + 0x80, 0x88, 0x60, 0xb4, 0xe4, 0x83, 0x50, 0x31, + 0xa3, 0x44, 0x63, 0x86, 0x8d, 0x87, 0xbf, 0x85, + 0x42, 0x3e, 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, + 0x0b, 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, + 0x0f, 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, + 0x80, 0x41, 0x53, 0x81, 0x41, 0x23, 0x81, 0xb1, + 0x48, 0x2f, 0xbd, 0x4d, 0x91, 0x18, 0x9a, 0x01, + 0x00, 0x08, 0x80, 0x89, 0x03, 0x00, 0x00, 0x28, + 0x18, 0x00, 0x00, 0x02, 0x01, 0x00, 0x08, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x06, 0x03, + 0x03, 0x00, 0x80, 0x89, 0x80, 0x90, 0x22, 0x04, + 0x80, 0x90, 0x42, 0x43, 0x8a, 0x84, 0x9e, 0x80, + 0x9f, 0x99, 0x82, 0xa2, 0x80, 0xee, 0x82, 0x8c, + 0xab, 0x83, 0x88, 0x31, 0x49, 0x9d, 0x89, 0x60, + 0xfc, 0x05, 0x42, 0x1d, 0x6b, 0x05, 0xe1, 0x4f, + 0xff, +}; + +static const uint8_t unicode_prop_ASCII_Hex_Digit_table[5] = { + 0xaf, 0x89, 0x35, 0x99, 0x85, +}; + +static const uint8_t unicode_prop_Bidi_Control_table[10] = { + 0x46, 0x1b, 0x80, 0x59, 0xf0, 0x81, 0x99, 0x84, + 0xb6, 0x83, +}; + +static const uint8_t unicode_prop_Dash_table[58] = { + 0xac, 0x80, 0x45, 0x5b, 0x80, 0xb2, 0x80, 0x4e, + 0x40, 0x80, 0x44, 0x04, 0x80, 0x48, 0x08, 0x85, + 0xbc, 0x80, 0xa6, 0x80, 0x8e, 0x80, 0x41, 0x85, + 0x80, 0x4c, 0x03, 0x01, 0x80, 0x9e, 0x0b, 0x80, + 0x9b, 0x80, 0x41, 0xbd, 0x80, 0x92, 0x80, 0xee, + 0x80, 0x60, 0xcd, 0x8f, 0x81, 0xa4, 0x80, 0x89, + 0x80, 0x40, 0xa8, 0x80, 0x4e, 0x5f, 0x80, 0x41, + 0x3d, 0x80, +}; + +static const uint8_t unicode_prop_Deprecated_table[23] = { + 0x41, 0x48, 0x80, 0x45, 0x28, 0x80, 0x49, 0x02, + 0x00, 0x80, 0x48, 0x28, 0x81, 0x48, 0xc4, 0x85, + 0x42, 0xb8, 0x81, 0x6d, 0xdc, 0xd5, 0x80, +}; + +static const uint8_t unicode_prop_Diacritic_table[447] = { + 0xdd, 0x00, 0x80, 0xc6, 0x05, 0x03, 0x01, 0x81, + 0x41, 0xf6, 0x40, 0x9e, 0x07, 0x25, 0x90, 0x0b, + 0x80, 0x88, 0x81, 0x40, 0xfc, 0x84, 0x40, 0xd0, + 0x80, 0xb6, 0xac, 0x00, 0x01, 0x01, 0x00, 0x40, + 0x82, 0x3b, 0x81, 0x40, 0x85, 0x0b, 0x0a, 0x82, + 0xc2, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0xa1, 0x81, + 0xfd, 0x87, 0xa8, 0x89, 0x8f, 0x9b, 0xbc, 0x80, + 0x8f, 0x02, 0x83, 0x9b, 0x80, 0xc9, 0x80, 0x8f, + 0x80, 0xed, 0x80, 0x8f, 0x80, 0xed, 0x80, 0x8f, + 0x80, 0xae, 0x82, 0xbb, 0x80, 0x8f, 0x06, 0x80, + 0xf6, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xed, 0x80, + 0x8f, 0x80, 0xec, 0x81, 0x8f, 0x80, 0xfb, 0x80, + 0xee, 0x80, 0x8b, 0x28, 0x80, 0xea, 0x80, 0x8c, + 0x84, 0xca, 0x81, 0x9a, 0x00, 0x00, 0x03, 0x81, + 0xc1, 0x10, 0x81, 0xbd, 0x80, 0xef, 0x00, 0x81, + 0xa7, 0x0b, 0x84, 0x98, 0x30, 0x80, 0x89, 0x81, + 0x42, 0xc0, 0x82, 0x43, 0xb3, 0x81, 0x9d, 0x80, + 0x40, 0x93, 0x8a, 0x88, 0x80, 0x41, 0x5a, 0x82, + 0x41, 0x23, 0x80, 0x93, 0x39, 0x80, 0xaf, 0x8e, + 0x81, 0x8a, 0x82, 0x8e, 0x81, 0x8b, 0xc7, 0x80, + 0x8e, 0x80, 0xa5, 0x88, 0xb5, 0x81, 0xb9, 0x80, + 0x8a, 0x81, 0xc1, 0x81, 0xbf, 0x85, 0xd1, 0x98, + 0x18, 0x28, 0x0a, 0xb1, 0xbe, 0xaf, 0xa3, 0x84, + 0x8b, 0xa4, 0x8a, 0x41, 0xbc, 0x00, 0x82, 0x8a, + 0x82, 0x8c, 0x82, 0x8c, 0x82, 0x8c, 0x81, 0x4c, + 0xef, 0x82, 0x41, 0x3c, 0x80, 0x41, 0xf9, 0x85, + 0xe8, 0x83, 0xde, 0x80, 0x60, 0x75, 0x71, 0x80, + 0x8b, 0x08, 0x80, 0x9b, 0x81, 0xd1, 0x81, 0x8d, + 0xa1, 0xe5, 0x82, 0xe5, 0x05, 0x81, 0x8b, 0x80, + 0xa4, 0x80, 0x40, 0x96, 0x80, 0x9a, 0x91, 0xb8, + 0x83, 0xa3, 0x80, 0xde, 0x80, 0x8b, 0x80, 0xa3, + 0x80, 0x40, 0x94, 0x82, 0xc0, 0x83, 0xb2, 0x80, + 0xe3, 0x84, 0x88, 0x82, 0xff, 0x81, 0x60, 0x4f, + 0x2f, 0x80, 0x43, 0x00, 0x8f, 0x41, 0x0d, 0x00, + 0x80, 0xae, 0x80, 0xac, 0x81, 0xc2, 0x80, 0x42, + 0xfb, 0x80, 0x44, 0x9e, 0x28, 0xa9, 0x80, 0x88, + 0x42, 0x7c, 0x13, 0x80, 0x40, 0xa4, 0x81, 0x42, + 0x3a, 0x85, 0xa5, 0x80, 0x99, 0x84, 0x41, 0x8b, + 0x01, 0x82, 0xc5, 0x8a, 0xb0, 0x83, 0x40, 0xbf, + 0x80, 0xa8, 0x80, 0xc7, 0x81, 0xf7, 0x81, 0xbd, + 0x80, 0xcb, 0x80, 0x88, 0x82, 0xe7, 0x81, 0x40, + 0xb1, 0x81, 0xcf, 0x81, 0x8f, 0x80, 0x97, 0x32, + 0x84, 0xd8, 0x10, 0x81, 0x8c, 0x81, 0xde, 0x02, + 0x80, 0xfa, 0x81, 0x40, 0xfa, 0x81, 0xfd, 0x80, + 0xf5, 0x81, 0xf2, 0x80, 0x41, 0x0c, 0x81, 0x41, + 0x01, 0x0b, 0x80, 0x40, 0x9b, 0x80, 0xd2, 0x80, + 0x91, 0x80, 0xd0, 0x80, 0x41, 0xa4, 0x80, 0x41, + 0x01, 0x00, 0x81, 0xd0, 0x80, 0xc0, 0x80, 0x41, + 0x66, 0x81, 0x96, 0x80, 0x54, 0xeb, 0x8e, 0x60, + 0x2c, 0xd8, 0x80, 0x49, 0xbf, 0x84, 0xba, 0x86, + 0x42, 0x33, 0x81, 0x42, 0x21, 0x90, 0xcf, 0x81, + 0x60, 0x3f, 0xfd, 0x18, 0x30, 0x81, 0x5f, 0x00, + 0xad, 0x81, 0x96, 0x42, 0x1f, 0x12, 0x2f, 0x39, + 0x86, 0x9d, 0x83, 0x4e, 0x81, 0xbd, 0x40, 0xc1, + 0x86, 0x41, 0x76, 0x80, 0xbc, 0x83, 0x42, 0xfd, + 0x81, 0x42, 0xdf, 0x86, 0xec, 0x10, 0x82, +}; + +static const uint8_t unicode_prop_Extender_table[116] = { + 0x40, 0xb6, 0x80, 0x42, 0x17, 0x81, 0x43, 0x6d, + 0x80, 0x41, 0xb8, 0x80, 0x42, 0x75, 0x80, 0x40, + 0x88, 0x80, 0xd8, 0x80, 0x42, 0xef, 0x80, 0xfe, + 0x80, 0x49, 0x42, 0x80, 0xb7, 0x80, 0x42, 0x62, + 0x80, 0x41, 0x8d, 0x80, 0xc3, 0x80, 0x53, 0x88, + 0x80, 0xaa, 0x84, 0xe6, 0x81, 0xdc, 0x82, 0x60, + 0x6f, 0x15, 0x80, 0x45, 0xf5, 0x80, 0x43, 0xc1, + 0x80, 0x95, 0x80, 0x40, 0x88, 0x80, 0xeb, 0x80, + 0x94, 0x81, 0x60, 0x54, 0x7a, 0x80, 0x48, 0x0f, + 0x81, 0x45, 0xca, 0x80, 0x9a, 0x03, 0x80, 0x44, + 0xc6, 0x80, 0x41, 0x24, 0x80, 0xf3, 0x81, 0x41, + 0xf1, 0x82, 0x44, 0xce, 0x80, 0x43, 0x3f, 0x80, + 0x60, 0x4d, 0x67, 0x81, 0x44, 0x9b, 0x08, 0x80, + 0x8d, 0x81, 0x60, 0x71, 0x47, 0x81, 0x44, 0xb0, + 0x80, 0x43, 0x53, 0x82, +}; + +static const uint8_t unicode_prop_Hex_Digit_table[12] = { + 0xaf, 0x89, 0x35, 0x99, 0x85, 0x60, 0xfe, 0xa8, + 0x89, 0x35, 0x99, 0x85, +}; + +static const uint8_t unicode_prop_IDS_Unary_Operator_table[4] = { + 0x60, 0x2f, 0xfd, 0x81, +}; + +static const uint8_t unicode_prop_IDS_Binary_Operator_table[8] = { + 0x60, 0x2f, 0xef, 0x09, 0x89, 0x41, 0xf0, 0x80, +}; + +static const uint8_t unicode_prop_IDS_Trinary_Operator_table[4] = { + 0x60, 0x2f, 0xf1, 0x81, +}; + +static const uint8_t unicode_prop_Ideographic_table[71] = { + 0x60, 0x30, 0x05, 0x81, 0x98, 0x88, 0x8d, 0x82, + 0x43, 0xc4, 0x59, 0xbf, 0xbf, 0x60, 0x51, 0xff, + 0x60, 0x58, 0xff, 0x41, 0x6d, 0x81, 0xe9, 0x60, + 0x75, 0x09, 0x80, 0x8c, 0x84, 0x88, 0x5c, 0xd5, + 0xa8, 0x9f, 0xe0, 0xf2, 0x60, 0x23, 0x7c, 0x41, + 0x8b, 0x60, 0x4d, 0x03, 0x60, 0xa6, 0xdf, 0x9f, + 0x51, 0x1d, 0x81, 0x56, 0x8d, 0x81, 0x5d, 0x30, + 0x8e, 0x42, 0x6d, 0x49, 0xa1, 0x42, 0x1d, 0x45, + 0xe1, 0x53, 0x4a, 0x84, 0x60, 0x21, 0x29, +}; + +static const uint8_t unicode_prop_Join_Control_table[4] = { + 0x60, 0x20, 0x0b, 0x81, +}; + +static const uint8_t unicode_prop_Logical_Order_Exception_table[15] = { + 0x4e, 0x3f, 0x84, 0xfa, 0x84, 0x4a, 0xef, 0x11, + 0x80, 0x60, 0x90, 0xf9, 0x09, 0x00, 0x81, +}; + +static const uint8_t unicode_prop_Modifier_Combining_Mark_table[16] = { + 0x46, 0x53, 0x09, 0x80, 0x40, 0x82, 0x05, 0x02, + 0x81, 0x41, 0xe0, 0x08, 0x12, 0x80, 0x9e, 0x80, +}; + +static const uint8_t unicode_prop_Noncharacter_Code_Point_table[71] = { + 0x60, 0xfd, 0xcf, 0x9f, 0x42, 0x0d, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60, + 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, +}; + +static const uint8_t unicode_prop_Pattern_Syntax_table[58] = { + 0xa0, 0x8e, 0x89, 0x86, 0x99, 0x18, 0x80, 0x99, + 0x83, 0xa1, 0x30, 0x00, 0x08, 0x00, 0x0b, 0x03, + 0x02, 0x80, 0x96, 0x80, 0x9e, 0x80, 0x5f, 0x17, + 0x97, 0x87, 0x8e, 0x81, 0x92, 0x80, 0x89, 0x41, + 0x30, 0x42, 0xcf, 0x40, 0x9f, 0x42, 0x75, 0x9d, + 0x44, 0x6b, 0x41, 0xff, 0xff, 0x41, 0x80, 0x13, + 0x98, 0x8e, 0x80, 0x60, 0xcd, 0x0c, 0x81, 0x41, + 0x04, 0x81, +}; + +static const uint8_t unicode_prop_Pattern_White_Space_table[11] = { + 0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x5f, 0x87, + 0x81, 0x97, 0x81, +}; + +static const uint8_t unicode_prop_Quotation_Mark_table[31] = { + 0xa1, 0x03, 0x80, 0x40, 0x82, 0x80, 0x8e, 0x80, + 0x5f, 0x5b, 0x87, 0x98, 0x81, 0x4e, 0x06, 0x80, + 0x41, 0xc8, 0x83, 0x8c, 0x82, 0x60, 0xce, 0x20, + 0x83, 0x40, 0xbc, 0x03, 0x80, 0xd9, 0x81, +}; + +static const uint8_t unicode_prop_Radical_table[9] = { + 0x60, 0x2e, 0x7f, 0x99, 0x80, 0xd8, 0x8b, 0x40, + 0xd5, +}; + +static const uint8_t unicode_prop_Regional_Indicator_table[4] = { + 0x61, 0xf1, 0xe5, 0x99, +}; + +static const uint8_t unicode_prop_Sentence_Terminal_table[213] = { + 0xa0, 0x80, 0x8b, 0x80, 0x8f, 0x80, 0x45, 0x48, + 0x80, 0x40, 0x92, 0x82, 0x40, 0xb3, 0x80, 0xaa, + 0x82, 0x40, 0xf5, 0x80, 0xbc, 0x00, 0x02, 0x81, + 0x41, 0x24, 0x81, 0x46, 0xe3, 0x81, 0x43, 0x15, + 0x03, 0x81, 0x43, 0x04, 0x80, 0x40, 0xc5, 0x81, + 0x40, 0x9c, 0x81, 0xac, 0x04, 0x80, 0x41, 0x39, + 0x81, 0x41, 0x61, 0x83, 0x40, 0xa1, 0x81, 0x89, + 0x09, 0x81, 0x9c, 0x82, 0x40, 0xba, 0x81, 0xc0, + 0x81, 0x43, 0xa3, 0x80, 0x96, 0x81, 0x88, 0x82, + 0x4c, 0xae, 0x82, 0x41, 0x31, 0x80, 0x8c, 0x80, + 0x95, 0x81, 0x41, 0xac, 0x80, 0x60, 0x74, 0xfb, + 0x80, 0x41, 0x0d, 0x81, 0x40, 0xe2, 0x02, 0x80, + 0x41, 0x7d, 0x81, 0xd5, 0x81, 0xde, 0x80, 0x40, + 0x97, 0x81, 0x40, 0x92, 0x82, 0x40, 0x8f, 0x81, + 0x40, 0xf8, 0x80, 0x60, 0x52, 0x25, 0x01, 0x81, + 0xba, 0x02, 0x81, 0x40, 0xa8, 0x80, 0x8b, 0x80, + 0x8f, 0x80, 0xc0, 0x80, 0x4a, 0xf3, 0x81, 0x44, + 0xfc, 0x84, 0xab, 0x83, 0x40, 0xbc, 0x81, 0xf4, + 0x83, 0xfe, 0x82, 0x40, 0x80, 0x0d, 0x80, 0x8f, + 0x81, 0xd7, 0x08, 0x81, 0xeb, 0x80, 0x41, 0x29, + 0x81, 0xf4, 0x81, 0x41, 0x74, 0x0c, 0x8e, 0xe8, + 0x81, 0x40, 0xf8, 0x82, 0x42, 0x04, 0x00, 0x80, + 0x40, 0xfa, 0x81, 0xd6, 0x81, 0x41, 0xa3, 0x81, + 0x42, 0xb3, 0x81, 0xc9, 0x81, 0x60, 0x4b, 0x28, + 0x81, 0x40, 0x84, 0x80, 0xc0, 0x81, 0x8a, 0x80, + 0x42, 0x28, 0x81, 0x41, 0x27, 0x80, 0x60, 0x4e, + 0x05, 0x80, 0x5d, 0xe7, 0x80, +}; + +static const uint8_t unicode_prop_Soft_Dotted_table[79] = { + 0xe8, 0x81, 0x40, 0xc3, 0x80, 0x41, 0x18, 0x80, + 0x9d, 0x80, 0xb3, 0x80, 0x93, 0x80, 0x41, 0x3f, + 0x80, 0xe1, 0x00, 0x80, 0x59, 0x08, 0x80, 0xb2, + 0x80, 0x8c, 0x02, 0x80, 0x40, 0x83, 0x80, 0x40, + 0x9c, 0x80, 0x41, 0xa4, 0x80, 0x40, 0xd5, 0x81, + 0x4b, 0x31, 0x80, 0x61, 0xa7, 0xa4, 0x81, 0xb1, + 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, + 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, + 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0x48, + 0x85, 0x80, 0x41, 0x30, 0x81, 0x99, 0x80, +}; + +static const uint8_t unicode_prop_Terminal_Punctuation_table[264] = { + 0xa0, 0x80, 0x89, 0x00, 0x80, 0x8a, 0x0a, 0x80, + 0x43, 0x3d, 0x07, 0x80, 0x42, 0x00, 0x80, 0xb8, + 0x80, 0xc7, 0x80, 0x8d, 0x00, 0x82, 0x40, 0xb3, + 0x80, 0xaa, 0x8a, 0x00, 0x40, 0xea, 0x81, 0xb5, + 0x28, 0x87, 0x9e, 0x80, 0x41, 0x04, 0x81, 0x44, + 0xf3, 0x81, 0x40, 0xab, 0x03, 0x85, 0x41, 0x36, + 0x81, 0x43, 0x14, 0x87, 0x43, 0x04, 0x80, 0xfb, + 0x82, 0xc6, 0x81, 0x40, 0x9c, 0x12, 0x80, 0xa6, + 0x19, 0x81, 0x41, 0x39, 0x81, 0x41, 0x61, 0x83, + 0x40, 0xa1, 0x81, 0x89, 0x08, 0x82, 0x9c, 0x82, + 0x40, 0xba, 0x84, 0xbd, 0x81, 0x43, 0xa3, 0x80, + 0x96, 0x81, 0x88, 0x82, 0x4c, 0xae, 0x82, 0x41, + 0x31, 0x80, 0x8c, 0x03, 0x80, 0x89, 0x00, 0x0a, + 0x81, 0x41, 0xab, 0x81, 0x60, 0x74, 0xfa, 0x81, + 0x41, 0x0c, 0x82, 0x40, 0xe2, 0x84, 0x41, 0x7d, + 0x81, 0xd5, 0x81, 0xde, 0x80, 0x40, 0x96, 0x82, + 0x40, 0x92, 0x82, 0xfe, 0x80, 0x8f, 0x81, 0x40, + 0xf8, 0x80, 0x60, 0x52, 0x25, 0x01, 0x81, 0xb8, + 0x10, 0x83, 0x40, 0xa8, 0x80, 0x89, 0x00, 0x80, + 0x8a, 0x0a, 0x80, 0xc0, 0x01, 0x80, 0x44, 0x39, + 0x80, 0xaf, 0x80, 0x44, 0x85, 0x80, 0x40, 0xc6, + 0x80, 0x41, 0x35, 0x81, 0x40, 0x97, 0x85, 0xc3, + 0x85, 0xd8, 0x83, 0x43, 0xb7, 0x84, 0xab, 0x83, + 0x40, 0xbc, 0x86, 0xef, 0x83, 0xfe, 0x82, 0x40, + 0x80, 0x0d, 0x80, 0x8f, 0x81, 0xd7, 0x84, 0xeb, + 0x80, 0x41, 0x29, 0x81, 0xf4, 0x82, 0x8b, 0x81, + 0x41, 0x65, 0x1a, 0x8e, 0xe8, 0x81, 0x40, 0xf8, + 0x82, 0x42, 0x04, 0x00, 0x80, 0x40, 0xfa, 0x81, + 0xd6, 0x0b, 0x81, 0x41, 0x9d, 0x82, 0xac, 0x80, + 0x42, 0x84, 0x81, 0xc9, 0x81, 0x45, 0x2a, 0x84, + 0x60, 0x45, 0xf8, 0x81, 0x40, 0x84, 0x80, 0xc0, + 0x82, 0x89, 0x80, 0x42, 0x28, 0x81, 0x41, 0x26, + 0x81, 0x60, 0x4e, 0x05, 0x80, 0x5d, 0xe6, 0x83, +}; + +static const uint8_t unicode_prop_Unified_Ideograph_table[46] = { + 0x60, 0x33, 0xff, 0x59, 0xbf, 0xbf, 0x60, 0x51, + 0xff, 0x60, 0x5a, 0x0d, 0x08, 0x00, 0x81, 0x89, + 0x00, 0x00, 0x09, 0x82, 0x61, 0x05, 0xd5, 0x60, + 0xa6, 0xdf, 0x9f, 0x51, 0x1d, 0x81, 0x56, 0x8d, + 0x81, 0x5d, 0x30, 0x8e, 0x42, 0x6d, 0x51, 0xa1, + 0x53, 0x4a, 0x84, 0x60, 0x21, 0x29, +}; + +static const uint8_t unicode_prop_Variation_Selector_table[13] = { + 0x58, 0x0a, 0x10, 0x80, 0x60, 0xe5, 0xef, 0x8f, + 0x6d, 0x02, 0xef, 0x40, 0xef, +}; + +static const uint8_t unicode_prop_Bidi_Mirrored_table[173] = { + 0xa7, 0x81, 0x91, 0x00, 0x80, 0x9b, 0x00, 0x80, + 0x9c, 0x00, 0x80, 0xac, 0x80, 0x8e, 0x80, 0x4e, + 0x7d, 0x83, 0x47, 0x5c, 0x81, 0x49, 0x9b, 0x81, + 0x89, 0x81, 0xb5, 0x81, 0x8d, 0x81, 0x40, 0xb0, + 0x80, 0x40, 0xbf, 0x1a, 0x2a, 0x02, 0x0a, 0x18, + 0x18, 0x00, 0x03, 0x88, 0x20, 0x80, 0x91, 0x23, + 0x88, 0x08, 0x00, 0x38, 0x9f, 0x0b, 0x20, 0x88, + 0x09, 0x92, 0x21, 0x88, 0x21, 0x0b, 0x97, 0x81, + 0x8f, 0x3b, 0x93, 0x0e, 0x81, 0x44, 0x3c, 0x8d, + 0xc9, 0x01, 0x18, 0x08, 0x14, 0x1c, 0x12, 0x8d, + 0x41, 0x92, 0x95, 0x0d, 0x80, 0x8d, 0x38, 0x35, + 0x10, 0x1c, 0x01, 0x0c, 0x18, 0x02, 0x09, 0x89, + 0x29, 0x81, 0x8b, 0x92, 0x03, 0x08, 0x00, 0x08, + 0x03, 0x21, 0x2a, 0x97, 0x81, 0x8a, 0x0b, 0x18, + 0x09, 0x0b, 0xaa, 0x0f, 0x80, 0xa7, 0x20, 0x00, + 0x14, 0x22, 0x18, 0x14, 0x00, 0x40, 0xff, 0x80, + 0x42, 0x02, 0x1a, 0x08, 0x81, 0x8d, 0x09, 0x89, + 0xaa, 0x87, 0x41, 0xaa, 0x89, 0x0f, 0x60, 0xce, + 0x3c, 0x2c, 0x81, 0x40, 0xa1, 0x81, 0x91, 0x00, + 0x80, 0x9b, 0x00, 0x80, 0x9c, 0x00, 0x00, 0x08, + 0x81, 0x60, 0xd7, 0x76, 0x80, 0xb8, 0x80, 0xb8, + 0x80, 0xb8, 0x80, 0xb8, 0x80, +}; + +static const uint8_t unicode_prop_Emoji_table[239] = { + 0xa2, 0x05, 0x04, 0x89, 0xee, 0x03, 0x80, 0x5f, + 0x8c, 0x80, 0x8b, 0x80, 0x40, 0xd7, 0x80, 0x95, + 0x80, 0xd9, 0x85, 0x8e, 0x81, 0x41, 0x6e, 0x81, + 0x8b, 0x80, 0x40, 0xa5, 0x80, 0x98, 0x8a, 0x1a, + 0x40, 0xc6, 0x80, 0x40, 0xe6, 0x81, 0x89, 0x80, + 0x88, 0x80, 0xb9, 0x18, 0x84, 0x88, 0x01, 0x01, + 0x09, 0x03, 0x01, 0x00, 0x09, 0x02, 0x02, 0x0f, + 0x14, 0x00, 0x04, 0x8b, 0x8a, 0x09, 0x00, 0x08, + 0x80, 0x91, 0x01, 0x81, 0x91, 0x28, 0x00, 0x0a, + 0x0c, 0x01, 0x0b, 0x81, 0x8a, 0x0c, 0x09, 0x04, + 0x08, 0x00, 0x81, 0x93, 0x0c, 0x28, 0x19, 0x03, + 0x01, 0x01, 0x28, 0x01, 0x00, 0x00, 0x05, 0x02, + 0x05, 0x80, 0x89, 0x81, 0x8e, 0x01, 0x03, 0x00, + 0x03, 0x10, 0x80, 0x8a, 0x81, 0xaf, 0x82, 0x88, + 0x80, 0x8d, 0x80, 0x8d, 0x80, 0x41, 0x73, 0x81, + 0x41, 0xce, 0x82, 0x92, 0x81, 0xb2, 0x03, 0x80, + 0x44, 0xd9, 0x80, 0x8b, 0x80, 0x42, 0x58, 0x00, + 0x80, 0x61, 0xbd, 0x69, 0x80, 0x40, 0xc9, 0x80, + 0x40, 0x9f, 0x81, 0x8b, 0x81, 0x8d, 0x01, 0x89, + 0xca, 0x99, 0x01, 0x96, 0x80, 0x93, 0x01, 0x88, + 0x94, 0x81, 0x40, 0xad, 0xa1, 0x81, 0xef, 0x09, + 0x02, 0x81, 0xd2, 0x0a, 0x80, 0x41, 0x06, 0x80, + 0xbe, 0x8a, 0x28, 0x97, 0x31, 0x0f, 0x8b, 0x01, + 0x19, 0x03, 0x81, 0x8c, 0x09, 0x07, 0x81, 0x88, + 0x04, 0x82, 0x8b, 0x17, 0x11, 0x00, 0x03, 0x05, + 0x02, 0x05, 0xd5, 0xaf, 0xc5, 0x27, 0x0b, 0x82, + 0x89, 0x10, 0x01, 0x10, 0x81, 0x89, 0x40, 0xe2, + 0x8b, 0x18, 0x41, 0x1a, 0xae, 0x80, 0x89, 0x80, + 0x40, 0xb8, 0xef, 0x8c, 0x82, 0x8a, 0x82, 0xb8, + 0x00, 0x83, 0x8f, 0x81, 0x8b, 0x83, 0x89, +}; + +static const uint8_t unicode_prop_Emoji_Component_table[28] = { + 0xa2, 0x05, 0x04, 0x89, 0x5f, 0xd2, 0x80, 0x40, + 0xd4, 0x80, 0x60, 0xdd, 0x2a, 0x80, 0x60, 0xf3, + 0xd5, 0x99, 0x41, 0xfa, 0x84, 0x45, 0xaf, 0x83, + 0x6c, 0x06, 0x6b, 0xdf, +}; + +static const uint8_t unicode_prop_Emoji_Modifier_table[4] = { + 0x61, 0xf3, 0xfa, 0x84, +}; + +static const uint8_t unicode_prop_Emoji_Modifier_Base_table[71] = { + 0x60, 0x26, 0x1c, 0x80, 0x40, 0xda, 0x80, 0x8f, + 0x83, 0x61, 0xcc, 0x76, 0x80, 0xbb, 0x11, 0x01, + 0x82, 0xf4, 0x09, 0x8a, 0x94, 0x92, 0x10, 0x1a, + 0x02, 0x30, 0x00, 0x97, 0x80, 0x40, 0xc8, 0x0b, + 0x80, 0x94, 0x03, 0x81, 0x40, 0xad, 0x12, 0x84, + 0xd2, 0x80, 0x8f, 0x82, 0x88, 0x80, 0x8a, 0x80, + 0x42, 0x3e, 0x01, 0x07, 0x3d, 0x80, 0x88, 0x89, + 0x0a, 0xb7, 0x80, 0xbc, 0x08, 0x08, 0x80, 0x90, + 0x10, 0x8c, 0x40, 0xe4, 0x82, 0xa9, 0x88, +}; + +static const uint8_t unicode_prop_Emoji_Presentation_table[145] = { + 0x60, 0x23, 0x19, 0x81, 0x40, 0xcc, 0x1a, 0x01, + 0x80, 0x42, 0x08, 0x81, 0x94, 0x81, 0xb1, 0x8b, + 0xaa, 0x80, 0x92, 0x80, 0x8c, 0x07, 0x81, 0x90, + 0x0c, 0x0f, 0x04, 0x80, 0x94, 0x06, 0x08, 0x03, + 0x01, 0x06, 0x03, 0x81, 0x9b, 0x80, 0xa2, 0x00, + 0x03, 0x10, 0x80, 0xbc, 0x82, 0x97, 0x80, 0x8d, + 0x80, 0x43, 0x5a, 0x81, 0xb2, 0x03, 0x80, 0x61, + 0xc4, 0xad, 0x80, 0x40, 0xc9, 0x80, 0x40, 0xbd, + 0x01, 0x89, 0xca, 0x99, 0x00, 0x97, 0x80, 0x93, + 0x01, 0x20, 0x82, 0x94, 0x81, 0x40, 0xad, 0xa0, + 0x8b, 0x88, 0x80, 0xc5, 0x80, 0x95, 0x8b, 0xaa, + 0x1c, 0x8b, 0x90, 0x10, 0x82, 0xc6, 0x00, 0x80, + 0x40, 0xba, 0x81, 0xbe, 0x8c, 0x18, 0x97, 0x91, + 0x80, 0x99, 0x81, 0x8c, 0x80, 0xd5, 0xd4, 0xaf, + 0xc5, 0x28, 0x12, 0x0b, 0x13, 0x8a, 0x0e, 0x88, + 0x40, 0xe2, 0x8b, 0x18, 0x41, 0x1a, 0xae, 0x80, + 0x89, 0x80, 0x40, 0xb8, 0xef, 0x8c, 0x82, 0x8a, + 0x82, 0xb8, 0x00, 0x83, 0x8f, 0x81, 0x8b, 0x83, + 0x89, +}; + +static const uint8_t unicode_prop_Extended_Pictographic_table[254] = { + 0x40, 0xa8, 0x03, 0x80, 0x5f, 0x8c, 0x80, 0x8b, + 0x80, 0x40, 0xd7, 0x80, 0x95, 0x80, 0xd9, 0x85, + 0x8e, 0x81, 0x41, 0x6e, 0x81, 0x8b, 0x80, 0x40, + 0xa5, 0x80, 0x98, 0x8a, 0x1a, 0x40, 0xc6, 0x80, + 0x40, 0xe6, 0x81, 0x89, 0x80, 0x88, 0x80, 0xb9, + 0x18, 0x84, 0x88, 0x01, 0x01, 0x09, 0x03, 0x01, + 0x00, 0x09, 0x02, 0x02, 0x0f, 0x14, 0x00, 0x04, + 0x8b, 0x8a, 0x09, 0x00, 0x08, 0x80, 0x91, 0x01, + 0x81, 0x91, 0x28, 0x00, 0x0a, 0x0c, 0x01, 0x0b, + 0x81, 0x8a, 0x0c, 0x09, 0x04, 0x08, 0x00, 0x81, + 0x93, 0x0c, 0x28, 0x19, 0x03, 0x01, 0x01, 0x28, + 0x01, 0x00, 0x00, 0x05, 0x02, 0x05, 0x80, 0x89, + 0x81, 0x8e, 0x01, 0x03, 0x00, 0x03, 0x10, 0x80, + 0x8a, 0x81, 0xaf, 0x82, 0x88, 0x80, 0x8d, 0x80, + 0x8d, 0x80, 0x41, 0x73, 0x81, 0x41, 0xce, 0x82, + 0x92, 0x81, 0xb2, 0x03, 0x80, 0x44, 0xd9, 0x80, + 0x8b, 0x80, 0x42, 0x58, 0x00, 0x80, 0x61, 0xbd, + 0x69, 0x80, 0xa6, 0x83, 0xe3, 0x8b, 0x8e, 0x81, + 0x8e, 0x80, 0x8d, 0x81, 0xa4, 0x89, 0xef, 0x81, + 0x8b, 0x81, 0x8d, 0x01, 0x89, 0x92, 0xb7, 0x9a, + 0x8e, 0x89, 0x80, 0x93, 0x01, 0x88, 0x03, 0x88, + 0x96, 0x85, 0x40, 0xbb, 0x81, 0xef, 0x09, 0x02, + 0x81, 0xd2, 0x0a, 0x03, 0x84, 0x40, 0xfd, 0x80, + 0xbe, 0x8a, 0x28, 0x97, 0x31, 0x0f, 0x8b, 0x01, + 0x19, 0x03, 0x81, 0x8c, 0x09, 0x07, 0x81, 0x88, + 0x04, 0x82, 0x8b, 0x17, 0x11, 0x00, 0x03, 0x05, + 0x02, 0x05, 0xd5, 0xaf, 0xc5, 0x27, 0x81, 0x90, + 0x10, 0x05, 0x81, 0x8c, 0x40, 0xd9, 0xa5, 0x8b, + 0x83, 0xb7, 0x87, 0x89, 0x85, 0xa7, 0x87, 0x9d, + 0x81, 0x8b, 0x19, 0x8d, 0x88, 0xa6, 0x8b, 0xae, + 0x80, 0x89, 0x80, 0x40, 0xb8, 0xd7, 0x87, 0x8d, + 0x40, 0x91, 0x40, 0xff, 0x43, 0xfd, +}; + +static const uint8_t unicode_prop_Default_Ignorable_Code_Point_table[51] = { + 0x40, 0xac, 0x80, 0x42, 0xa0, 0x80, 0x42, 0xcb, + 0x80, 0x4b, 0x41, 0x81, 0x46, 0x52, 0x81, 0xd4, + 0x84, 0x47, 0xfa, 0x84, 0x99, 0x84, 0xb0, 0x8f, + 0x50, 0xf3, 0x80, 0x60, 0xcc, 0x9a, 0x8f, 0x40, + 0xee, 0x80, 0x40, 0x9f, 0x80, 0xce, 0x88, 0x60, + 0xbc, 0xa6, 0x83, 0x54, 0xce, 0x87, 0x6c, 0x2e, + 0x84, 0x4f, 0xff, +}; + +typedef enum { + UNICODE_PROP_Hyphen, + UNICODE_PROP_Other_Math, + UNICODE_PROP_Other_Alphabetic, + UNICODE_PROP_Other_Lowercase, + UNICODE_PROP_Other_Uppercase, + UNICODE_PROP_Other_Grapheme_Extend, + UNICODE_PROP_Other_Default_Ignorable_Code_Point, + UNICODE_PROP_Other_ID_Start, + UNICODE_PROP_Other_ID_Continue, + UNICODE_PROP_Prepended_Concatenation_Mark, + UNICODE_PROP_ID_Continue1, + UNICODE_PROP_XID_Start1, + UNICODE_PROP_XID_Continue1, + UNICODE_PROP_Changes_When_Titlecased1, + UNICODE_PROP_Changes_When_Casefolded1, + UNICODE_PROP_Changes_When_NFKC_Casefolded1, + UNICODE_PROP_ASCII_Hex_Digit, + UNICODE_PROP_Bidi_Control, + UNICODE_PROP_Dash, + UNICODE_PROP_Deprecated, + UNICODE_PROP_Diacritic, + UNICODE_PROP_Extender, + UNICODE_PROP_Hex_Digit, + UNICODE_PROP_IDS_Unary_Operator, + UNICODE_PROP_IDS_Binary_Operator, + UNICODE_PROP_IDS_Trinary_Operator, + UNICODE_PROP_Ideographic, + UNICODE_PROP_Join_Control, + UNICODE_PROP_Logical_Order_Exception, + UNICODE_PROP_Modifier_Combining_Mark, + UNICODE_PROP_Noncharacter_Code_Point, + UNICODE_PROP_Pattern_Syntax, + UNICODE_PROP_Pattern_White_Space, + UNICODE_PROP_Quotation_Mark, + UNICODE_PROP_Radical, + UNICODE_PROP_Regional_Indicator, + UNICODE_PROP_Sentence_Terminal, + UNICODE_PROP_Soft_Dotted, + UNICODE_PROP_Terminal_Punctuation, + UNICODE_PROP_Unified_Ideograph, + UNICODE_PROP_Variation_Selector, + UNICODE_PROP_White_Space, + UNICODE_PROP_Bidi_Mirrored, + UNICODE_PROP_Emoji, + UNICODE_PROP_Emoji_Component, + UNICODE_PROP_Emoji_Modifier, + UNICODE_PROP_Emoji_Modifier_Base, + UNICODE_PROP_Emoji_Presentation, + UNICODE_PROP_Extended_Pictographic, + UNICODE_PROP_Default_Ignorable_Code_Point, + UNICODE_PROP_ID_Start, + UNICODE_PROP_Case_Ignorable, + UNICODE_PROP_ASCII, + UNICODE_PROP_Alphabetic, + UNICODE_PROP_Any, + UNICODE_PROP_Assigned, + UNICODE_PROP_Cased, + UNICODE_PROP_Changes_When_Casefolded, + UNICODE_PROP_Changes_When_Casemapped, + UNICODE_PROP_Changes_When_Lowercased, + UNICODE_PROP_Changes_When_NFKC_Casefolded, + UNICODE_PROP_Changes_When_Titlecased, + UNICODE_PROP_Changes_When_Uppercased, + UNICODE_PROP_Grapheme_Base, + UNICODE_PROP_Grapheme_Extend, + UNICODE_PROP_ID_Continue, + UNICODE_PROP_ID_Compat_Math_Start, + UNICODE_PROP_ID_Compat_Math_Continue, + UNICODE_PROP_Lowercase, + UNICODE_PROP_Math, + UNICODE_PROP_Uppercase, + UNICODE_PROP_XID_Continue, + UNICODE_PROP_XID_Start, + UNICODE_PROP_Cased1, + UNICODE_PROP_InCB, + UNICODE_PROP_COUNT, +} UnicodePropertyEnum; + +static const char unicode_prop_name_table[] = + "ASCII_Hex_Digit,AHex" "\0" + "Bidi_Control,Bidi_C" "\0" + "Dash" "\0" + "Deprecated,Dep" "\0" + "Diacritic,Dia" "\0" + "Extender,Ext" "\0" + "Hex_Digit,Hex" "\0" + "IDS_Unary_Operator,IDSU" "\0" + "IDS_Binary_Operator,IDSB" "\0" + "IDS_Trinary_Operator,IDST" "\0" + "Ideographic,Ideo" "\0" + "Join_Control,Join_C" "\0" + "Logical_Order_Exception,LOE" "\0" + "Modifier_Combining_Mark,MCM" "\0" + "Noncharacter_Code_Point,NChar" "\0" + "Pattern_Syntax,Pat_Syn" "\0" + "Pattern_White_Space,Pat_WS" "\0" + "Quotation_Mark,QMark" "\0" + "Radical" "\0" + "Regional_Indicator,RI" "\0" + "Sentence_Terminal,STerm" "\0" + "Soft_Dotted,SD" "\0" + "Terminal_Punctuation,Term" "\0" + "Unified_Ideograph,UIdeo" "\0" + "Variation_Selector,VS" "\0" + "White_Space,space" "\0" + "Bidi_Mirrored,Bidi_M" "\0" + "Emoji" "\0" + "Emoji_Component,EComp" "\0" + "Emoji_Modifier,EMod" "\0" + "Emoji_Modifier_Base,EBase" "\0" + "Emoji_Presentation,EPres" "\0" + "Extended_Pictographic,ExtPict" "\0" + "Default_Ignorable_Code_Point,DI" "\0" + "ID_Start,IDS" "\0" + "Case_Ignorable,CI" "\0" + "ASCII" "\0" + "Alphabetic,Alpha" "\0" + "Any" "\0" + "Assigned" "\0" + "Cased" "\0" + "Changes_When_Casefolded,CWCF" "\0" + "Changes_When_Casemapped,CWCM" "\0" + "Changes_When_Lowercased,CWL" "\0" + "Changes_When_NFKC_Casefolded,CWKCF" "\0" + "Changes_When_Titlecased,CWT" "\0" + "Changes_When_Uppercased,CWU" "\0" + "Grapheme_Base,Gr_Base" "\0" + "Grapheme_Extend,Gr_Ext" "\0" + "ID_Continue,IDC" "\0" + "ID_Compat_Math_Start" "\0" + "ID_Compat_Math_Continue" "\0" + "Lowercase,Lower" "\0" + "Math" "\0" + "Uppercase,Upper" "\0" + "XID_Continue,XIDC" "\0" + "XID_Start,XIDS" "\0" +; + +static const uint8_t * const unicode_prop_table[] = { + unicode_prop_Hyphen_table, + unicode_prop_Other_Math_table, + unicode_prop_Other_Alphabetic_table, + unicode_prop_Other_Lowercase_table, + unicode_prop_Other_Uppercase_table, + unicode_prop_Other_Grapheme_Extend_table, + unicode_prop_Other_Default_Ignorable_Code_Point_table, + unicode_prop_Other_ID_Start_table, + unicode_prop_Other_ID_Continue_table, + unicode_prop_Prepended_Concatenation_Mark_table, + unicode_prop_ID_Continue1_table, + unicode_prop_XID_Start1_table, + unicode_prop_XID_Continue1_table, + unicode_prop_Changes_When_Titlecased1_table, + unicode_prop_Changes_When_Casefolded1_table, + unicode_prop_Changes_When_NFKC_Casefolded1_table, + unicode_prop_ASCII_Hex_Digit_table, + unicode_prop_Bidi_Control_table, + unicode_prop_Dash_table, + unicode_prop_Deprecated_table, + unicode_prop_Diacritic_table, + unicode_prop_Extender_table, + unicode_prop_Hex_Digit_table, + unicode_prop_IDS_Unary_Operator_table, + unicode_prop_IDS_Binary_Operator_table, + unicode_prop_IDS_Trinary_Operator_table, + unicode_prop_Ideographic_table, + unicode_prop_Join_Control_table, + unicode_prop_Logical_Order_Exception_table, + unicode_prop_Modifier_Combining_Mark_table, + unicode_prop_Noncharacter_Code_Point_table, + unicode_prop_Pattern_Syntax_table, + unicode_prop_Pattern_White_Space_table, + unicode_prop_Quotation_Mark_table, + unicode_prop_Radical_table, + unicode_prop_Regional_Indicator_table, + unicode_prop_Sentence_Terminal_table, + unicode_prop_Soft_Dotted_table, + unicode_prop_Terminal_Punctuation_table, + unicode_prop_Unified_Ideograph_table, + unicode_prop_Variation_Selector_table, + unicode_prop_White_Space_table, + unicode_prop_Bidi_Mirrored_table, + unicode_prop_Emoji_table, + unicode_prop_Emoji_Component_table, + unicode_prop_Emoji_Modifier_table, + unicode_prop_Emoji_Modifier_Base_table, + unicode_prop_Emoji_Presentation_table, + unicode_prop_Extended_Pictographic_table, + unicode_prop_Default_Ignorable_Code_Point_table, + unicode_prop_ID_Start_table, + unicode_prop_Case_Ignorable_table, +}; + +static const uint16_t unicode_prop_len_table[] = { + countof(unicode_prop_Hyphen_table), + countof(unicode_prop_Other_Math_table), + countof(unicode_prop_Other_Alphabetic_table), + countof(unicode_prop_Other_Lowercase_table), + countof(unicode_prop_Other_Uppercase_table), + countof(unicode_prop_Other_Grapheme_Extend_table), + countof(unicode_prop_Other_Default_Ignorable_Code_Point_table), + countof(unicode_prop_Other_ID_Start_table), + countof(unicode_prop_Other_ID_Continue_table), + countof(unicode_prop_Prepended_Concatenation_Mark_table), + countof(unicode_prop_ID_Continue1_table), + countof(unicode_prop_XID_Start1_table), + countof(unicode_prop_XID_Continue1_table), + countof(unicode_prop_Changes_When_Titlecased1_table), + countof(unicode_prop_Changes_When_Casefolded1_table), + countof(unicode_prop_Changes_When_NFKC_Casefolded1_table), + countof(unicode_prop_ASCII_Hex_Digit_table), + countof(unicode_prop_Bidi_Control_table), + countof(unicode_prop_Dash_table), + countof(unicode_prop_Deprecated_table), + countof(unicode_prop_Diacritic_table), + countof(unicode_prop_Extender_table), + countof(unicode_prop_Hex_Digit_table), + countof(unicode_prop_IDS_Unary_Operator_table), + countof(unicode_prop_IDS_Binary_Operator_table), + countof(unicode_prop_IDS_Trinary_Operator_table), + countof(unicode_prop_Ideographic_table), + countof(unicode_prop_Join_Control_table), + countof(unicode_prop_Logical_Order_Exception_table), + countof(unicode_prop_Modifier_Combining_Mark_table), + countof(unicode_prop_Noncharacter_Code_Point_table), + countof(unicode_prop_Pattern_Syntax_table), + countof(unicode_prop_Pattern_White_Space_table), + countof(unicode_prop_Quotation_Mark_table), + countof(unicode_prop_Radical_table), + countof(unicode_prop_Regional_Indicator_table), + countof(unicode_prop_Sentence_Terminal_table), + countof(unicode_prop_Soft_Dotted_table), + countof(unicode_prop_Terminal_Punctuation_table), + countof(unicode_prop_Unified_Ideograph_table), + countof(unicode_prop_Variation_Selector_table), + countof(unicode_prop_White_Space_table), + countof(unicode_prop_Bidi_Mirrored_table), + countof(unicode_prop_Emoji_table), + countof(unicode_prop_Emoji_Component_table), + countof(unicode_prop_Emoji_Modifier_table), + countof(unicode_prop_Emoji_Modifier_Base_table), + countof(unicode_prop_Emoji_Presentation_table), + countof(unicode_prop_Extended_Pictographic_table), + countof(unicode_prop_Default_Ignorable_Code_Point_table), + countof(unicode_prop_ID_Start_table), + countof(unicode_prop_Case_Ignorable_table), +}; + +/* + * QuickJS Javascript Engine + * + * Copyright (c) 2017-2024 Fabrice Bellard + * Copyright (c) 2017-2024 Charlie Gordon + * Copyright (c) 2023-2025 Ben Noordhuis + * Copyright (c) 2023-2025 Saúl Ibarra Corretgé + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef QUICKJS_H +#define QUICKJS_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define QUICKJS_NG 1 + +/* Helpers. */ +#if defined(_WIN32) || defined(__CYGWIN__) +# define QUICKJS_NG_PLAT_WIN32 1 +#endif /* defined(_WIN32) || defined(__CYGWIN__) */ + +#if defined(__GNUC__) || defined(__clang__) +# define QUICKJS_NG_CC_GNULIKE 1 +#endif /* defined(__GNUC__) || defined(__clang__) */ + +/* + * `JS_EXTERN` -- helper macro that must be used to mark the external + * interfaces of libqjs. + * + * Define BUILDING_QJS_SHARED when building and USING_QJS_SHARED when using + * shared libqjs. + * + * Windows note: The `__declspec` syntax is supported by both Clang and GCC. + * If building qjs, the BUILDING_QJS_SHARED macro must be defined for libqjs + * (and only for it) to properly export symbols. + */ +#ifdef QUICKJS_NG_PLAT_WIN32 +# if defined(BUILDING_QJS_SHARED) +# define JS_EXTERN __declspec(dllexport) +# elif defined(USING_QJS_SHARED) +# define JS_EXTERN __declspec(dllimport) +# else +# define JS_EXTERN /* nothing */ +# endif +#else +# ifdef QUICKJS_NG_CC_GNULIKE +# define JS_EXTERN __attribute__((visibility("default"))) +# else +# define JS_EXTERN /* nothing */ +# endif +#endif /* QUICKJS_NG_PLAT_WIN32 */ + +/* + * `JS_LIBC_EXTERN` -- helper macro that must be used to mark the extern + * interfaces of quickjs-libc specifically. + */ +#if defined(QUICKJS_NG_BUILD) && !defined(QJS_BUILD_LIBC) && defined(QUICKJS_NG_PLAT_WIN32) +/* + * We are building QuickJS-NG, quickjs-libc is a static library and we are on + * Windows. Then, make sure to not export any interfaces. + */ +# define JS_LIBC_EXTERN /* nothing */ +#else +/* + * Otherwise, if we are either (1) not building QuickJS-NG, (2) libc is built as + * a part of libqjs, or (3) we are not on Windows, define JS_LIBC_EXTERN to + * JS_EXTERN. + */ +# define JS_LIBC_EXTERN JS_EXTERN +#endif + +/* + * `JS_MODULE_EXTERN` -- helper macro that must be used to mark `js_init_module` + * and other public functions of the binary modules. See examples/ for examples + * of the usage. + * + * Windows note: -DQUICKJS_NG_MODULE_BUILD must be set when building a binary + * module to properly set __declspec. + */ +#ifdef QUICKJS_NG_PLAT_WIN32 +# ifdef QUICKJS_NG_MODULE_BUILD +# define JS_MODULE_EXTERN __declspec(dllexport) +# else +# define JS_MODULE_EXTERN __declspec(dllimport) +# endif +#else +# ifdef QUICKJS_NG_CC_GNULIKE +# define JS_MODULE_EXTERN __attribute__((visibility("default"))) +# else +# define JS_MODULE_EXTERN /* nothing */ +# endif +#endif /* QUICKJS_NG_PLAT_WIN32 */ + +/* Borrowed from Folly */ +#ifndef JS_PRINTF_FORMAT +#ifdef _MSC_VER +#include +#define JS_PRINTF_FORMAT _Printf_format_string_ +#define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) +#else +#define JS_PRINTF_FORMAT +#if !defined(__clang__) && defined(__GNUC__) +#define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \ + __attribute__((format(gnu_printf, format_param, dots_param))) +#else +#define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \ + __attribute__((format(printf, format_param, dots_param))) +#endif +#endif +#endif + +#undef QUICKJS_NG_CC_GNULIKE +#undef QUICKJS_NG_PLAT_WIN32 + +typedef struct JSRuntime JSRuntime; +typedef struct JSContext JSContext; +typedef struct JSObject JSObject; +typedef struct JSClass JSClass; +typedef uint32_t JSClassID; +typedef uint32_t JSAtom; + +/* Unless documented otherwise, C string pointers (`char *` or `const char *`) + are assumed to verify these constraints: + - unless a length is passed separately, the string has a null terminator + - string contents is either pure ASCII or is UTF-8 encoded. + */ + +/* Overridable purely for testing purposes; don't touch. */ +#ifndef JS_NAN_BOXING +#if INTPTR_MAX < INT64_MAX +#define JS_NAN_BOXING 1 /* Use NAN boxing for 32bit builds. */ +#endif +#endif + +enum { + /* all tags with a reference count are negative */ + JS_TAG_FIRST = -9, /* first negative tag */ + JS_TAG_BIG_INT = -9, + JS_TAG_SYMBOL = -8, + JS_TAG_STRING = -7, + JS_TAG_STRING_ROPE = -6, + JS_TAG_MODULE = -3, /* used internally */ + JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */ + JS_TAG_OBJECT = -1, + + JS_TAG_INT = 0, + JS_TAG_BOOL = 1, + JS_TAG_NULL = 2, + JS_TAG_UNDEFINED = 3, + JS_TAG_UNINITIALIZED = 4, + JS_TAG_CATCH_OFFSET = 5, + JS_TAG_EXCEPTION = 6, + JS_TAG_SHORT_BIG_INT = 7, + JS_TAG_FLOAT64 = 8, + /* any larger tag is FLOAT64 if JS_NAN_BOXING */ +}; + +#if !defined(JS_CHECK_JSVALUE) +#define JSValueConst JSValue +#endif + +// JS_CHECK_JSVALUE build mode does not produce working code but is here to +// help catch reference counting bugs at compile time, by making it harder +// to mix up JSValue and JSValueConst +// +// rules: +// +// - a function with a JSValue parameter takes ownership; +// caller must *not* call JS_FreeValue +// +// - a function with a JSValueConst parameter does not take ownership; +// caller *must* call JS_FreeValue +// +// - a function returning a JSValue transfers ownership to caller; +// caller *must* call JS_FreeValue +// +// - a function returning a JSValueConst does *not* transfer ownership; +// caller must *not* call JS_FreeValue +#if defined(JS_CHECK_JSVALUE) + +typedef struct JSValue *JSValue; +typedef const struct JSValue *JSValueConst; + +#define JS_MKVAL(tag, val) ((JSValue)((tag) | (intptr_t)(val) << 4)) +#define JS_MKPTR(tag, ptr) ((JSValue)((tag) | (intptr_t)(ptr))) +#define JS_VALUE_GET_NORM_TAG(v) ((int)((intptr_t)(v) & 15)) +#define JS_VALUE_GET_TAG(v) ((int)((intptr_t)(v) & 15)) +#define JS_VALUE_GET_SHORT_BIG_INT(v) JS_VALUE_GET_INT(v) +#define JS_VALUE_GET_PTR(v) ((void *)((intptr_t)(v) & ~15)) +#define JS_VALUE_GET_INT(v) ((int)((intptr_t)(v) >> 4)) +#define JS_VALUE_GET_BOOL(v) ((int)((intptr_t)(v) >> 4)) +#define JS_VALUE_GET_FLOAT64(v) ((double)((intptr_t)(v) >> 4)) +#define JS_TAG_IS_FLOAT64(tag) ((int)(tag) == JS_TAG_FLOAT64) +#define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 0) + +static inline JSValue __JS_NewFloat64(double d) +{ + return JS_MKVAL(JS_TAG_FLOAT64, (int)d); +} + +static inline JSValue __JS_NewShortBigInt(JSContext *ctx, int32_t d) +{ + (void)&ctx; + return JS_MKVAL(JS_TAG_SHORT_BIG_INT, d); +} + +static inline bool JS_VALUE_IS_NAN(JSValue v) +{ + (void)&v; + return false; +} + +#elif defined(JS_NAN_BOXING) && JS_NAN_BOXING + +typedef uint64_t JSValue; + +#define JS_VALUE_GET_TAG(v) (int)((v) >> 32) +#define JS_VALUE_GET_INT(v) (int)(v) +#define JS_VALUE_GET_BOOL(v) (int)(v) +#define JS_VALUE_GET_SHORT_BIG_INT(v) (int)(v) +#define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v) + +#define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val)) +#define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr)) + +#define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */ + +static inline double JS_VALUE_GET_FLOAT64(JSValue v) +{ + union { + JSValue v; + double d; + } u; + u.v = v; + u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32; + return u.d; +} + +#define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32)) + +static inline JSValue __JS_NewFloat64(double d) +{ + union { + double d; + uint64_t u64; + } u; + JSValue v; + u.d = d; + /* normalize NaN */ + if ((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000) + v = JS_NAN; + else + v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32); + return v; +} + +static inline JSValue __JS_NewShortBigInt(JSContext *ctx, int32_t d) +{ + (void)&ctx; + return JS_MKVAL(JS_TAG_SHORT_BIG_INT, d); +} + +#define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST)) + +/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ +static inline int JS_VALUE_GET_NORM_TAG(JSValue v) +{ + uint32_t tag; + tag = JS_VALUE_GET_TAG(v); + if (JS_TAG_IS_FLOAT64(tag)) + return JS_TAG_FLOAT64; + else + return tag; +} + +static inline bool JS_VALUE_IS_NAN(JSValue v) +{ + uint32_t tag; + tag = JS_VALUE_GET_TAG(v); + return tag == (JS_NAN >> 32); +} + +#else /* !JS_NAN_BOXING */ + +typedef union JSValueUnion { + int32_t int32; + double float64; + void *ptr; + int32_t short_big_int; +} JSValueUnion; + +typedef struct JSValue { + JSValueUnion u; + int64_t tag; +} JSValue; + +#define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag) +/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ +#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) +#define JS_VALUE_GET_INT(v) ((v).u.int32) +#define JS_VALUE_GET_BOOL(v) ((v).u.int32) +#define JS_VALUE_GET_FLOAT64(v) ((v).u.float64) +#define JS_VALUE_GET_SHORT_BIG_INT(v) ((v).u.short_big_int) +#define JS_VALUE_GET_PTR(v) ((v).u.ptr) + +/* msvc doesn't understand designated initializers without /std:c++20 */ +#ifdef __cplusplus +static inline JSValue JS_MKPTR(int64_t tag, void *ptr) +{ + JSValue v; + v.u.ptr = ptr; + v.tag = tag; + return v; +} +static inline JSValue JS_MKVAL(int64_t tag, int32_t int32) +{ + JSValue v; + v.u.int32 = int32; + v.tag = tag; + return v; +} +static inline JSValue JS_MKNAN(void) +{ + JSValue v; + v.u.float64 = NAN; + v.tag = JS_TAG_FLOAT64; + return v; +} +/* provide as macros for consistency and backward compat reasons */ +#define JS_MKPTR(tag, ptr) JS_MKPTR(tag, ptr) +#define JS_MKVAL(tag, val) JS_MKVAL(tag, val) +#define JS_NAN JS_MKNAN() /* alas, not a constant expression */ +#else +#define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag } +#define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag } +#define JS_NAN (JSValue){ (JSValueUnion){ .float64 = NAN }, JS_TAG_FLOAT64 } +#endif + +#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) + +static inline JSValue __JS_NewFloat64(double d) +{ + JSValue v; + v.tag = JS_TAG_FLOAT64; + v.u.float64 = d; + return v; +} + +static inline JSValue __JS_NewShortBigInt(JSContext *ctx, int64_t d) +{ + (void)&ctx; + JSValue v; + v.tag = JS_TAG_SHORT_BIG_INT; + v.u.short_big_int = d; + return v; +} + +static inline bool JS_VALUE_IS_NAN(JSValue v) +{ + union { + double d; + uint64_t u64; + } u; + if (v.tag != JS_TAG_FLOAT64) + return 0; + u.d = v.u.float64; + return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000; +} + +#endif /* !JS_NAN_BOXING */ + +#define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0) +#define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2))) + +#define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST) + +/* special values */ +#define JS_NULL JS_MKVAL(JS_TAG_NULL, 0) +#define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0) +#define JS_FALSE JS_MKVAL(JS_TAG_BOOL, 0) +#define JS_TRUE JS_MKVAL(JS_TAG_BOOL, 1) +#define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0) +#define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0) + +/* flags for object properties */ +#define JS_PROP_CONFIGURABLE (1 << 0) +#define JS_PROP_WRITABLE (1 << 1) +#define JS_PROP_ENUMERABLE (1 << 2) +#define JS_PROP_C_W_E (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE) +#define JS_PROP_LENGTH (1 << 3) /* used internally in Arrays */ +#define JS_PROP_TMASK (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */ +#define JS_PROP_NORMAL (0 << 4) +#define JS_PROP_GETSET (1 << 4) +#define JS_PROP_VARREF (2 << 4) /* used internally */ +#define JS_PROP_AUTOINIT (3 << 4) /* used internally */ + +/* flags for JS_DefineProperty */ +#define JS_PROP_HAS_SHIFT 8 +#define JS_PROP_HAS_CONFIGURABLE (1 << 8) +#define JS_PROP_HAS_WRITABLE (1 << 9) +#define JS_PROP_HAS_ENUMERABLE (1 << 10) +#define JS_PROP_HAS_GET (1 << 11) +#define JS_PROP_HAS_SET (1 << 12) +#define JS_PROP_HAS_VALUE (1 << 13) + +/* throw an exception if false would be returned + (JS_DefineProperty/JS_SetProperty) */ +#define JS_PROP_THROW (1 << 14) +/* throw an exception if false would be returned in strict mode + (JS_SetProperty) */ +#define JS_PROP_THROW_STRICT (1 << 15) + +#define JS_PROP_NO_ADD (1 << 16) /* internal use */ +#define JS_PROP_NO_EXOTIC (1 << 17) /* internal use */ +#define JS_PROP_DEFINE_PROPERTY (1 << 18) /* internal use */ +#define JS_PROP_REFLECT_DEFINE_PROPERTY (1 << 19) /* internal use */ + +#ifndef JS_DEFAULT_STACK_SIZE +#define JS_DEFAULT_STACK_SIZE (1024 * 1024) +#endif + +/* JS_Eval() flags */ +#define JS_EVAL_TYPE_GLOBAL (0 << 0) /* global code (default) */ +#define JS_EVAL_TYPE_MODULE (1 << 0) /* module code */ +#define JS_EVAL_TYPE_DIRECT (2 << 0) /* direct call (internal use) */ +#define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */ +#define JS_EVAL_TYPE_MASK (3 << 0) + +#define JS_EVAL_FLAG_STRICT (1 << 3) /* force 'strict' mode */ +#define JS_EVAL_FLAG_UNUSED (1 << 4) /* unused */ +/* compile but do not run. The result is an object with a + JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed + with JS_EvalFunction(). */ +#define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5) +/* don't include the stack frames before this eval in the Error() backtraces */ +#define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6) +/* allow top-level await in normal script. JS_Eval() returns a + promise. Only allowed with JS_EVAL_TYPE_GLOBAL */ +#define JS_EVAL_FLAG_ASYNC (1 << 7) + +typedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); +typedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); +typedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValueConst *func_data); +typedef JSValue JSCClosure(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, void *opaque); + +typedef struct JSMallocFunctions { + void *(*js_calloc)(void *opaque, size_t count, size_t size); + void *(*js_malloc)(void *opaque, size_t size); + void (*js_free)(void *opaque, void *ptr); + void *(*js_realloc)(void *opaque, void *ptr, size_t size); + size_t (*js_malloc_usable_size)(const void *ptr); +} JSMallocFunctions; + +// Debug trace system: the debug output will be produced to the dump stream (currently +// stdout) if dumps are enabled and JS_SetDumpFlags is invoked with the corresponding +// bit set. +#define JS_DUMP_BYTECODE_FINAL 0x01 /* dump pass 3 final byte code */ +#define JS_DUMP_BYTECODE_PASS2 0x02 /* dump pass 2 code */ +#define JS_DUMP_BYTECODE_PASS1 0x04 /* dump pass 1 code */ +#define JS_DUMP_BYTECODE_HEX 0x10 /* dump bytecode in hex */ +#define JS_DUMP_BYTECODE_PC2LINE 0x20 /* dump line number table */ +#define JS_DUMP_BYTECODE_STACK 0x40 /* dump compute_stack_size */ +#define JS_DUMP_BYTECODE_STEP 0x80 /* dump executed bytecode */ +#define JS_DUMP_READ_OBJECT 0x100 /* dump the marshalled objects at load time */ +#define JS_DUMP_FREE 0x200 /* dump every object free */ +#define JS_DUMP_GC 0x400 /* dump the occurrence of the automatic GC */ +#define JS_DUMP_GC_FREE 0x800 /* dump objects freed by the GC */ +#define JS_DUMP_MODULE_RESOLVE 0x1000 /* dump module resolution steps */ +#define JS_DUMP_PROMISE 0x2000 /* dump promise steps */ +#define JS_DUMP_LEAKS 0x4000 /* dump leaked objects and strings in JS_FreeRuntime */ +#define JS_DUMP_ATOM_LEAKS 0x8000 /* dump leaked atoms in JS_FreeRuntime */ +#define JS_DUMP_MEM 0x10000 /* dump memory usage in JS_FreeRuntime */ +#define JS_DUMP_OBJECTS 0x20000 /* dump objects in JS_FreeRuntime */ +#define JS_DUMP_ATOMS 0x40000 /* dump atoms in JS_FreeRuntime */ +#define JS_DUMP_SHAPES 0x80000 /* dump shapes in JS_FreeRuntime */ + +// Finalizers run in LIFO order at the very end of JS_FreeRuntime. +// Intended for cleanup of associated resources; the runtime itself +// is no longer usable. +typedef void JSRuntimeFinalizer(JSRuntime *rt, void *arg); + +typedef struct JSGCObjectHeader JSGCObjectHeader; + +JS_EXTERN JSRuntime *JS_NewRuntime(void); +/* info lifetime must exceed that of rt */ +JS_EXTERN void JS_SetRuntimeInfo(JSRuntime *rt, const char *info); +/* use 0 to disable memory limit */ +JS_EXTERN void JS_SetMemoryLimit(JSRuntime *rt, size_t limit); +JS_EXTERN void JS_SetDumpFlags(JSRuntime *rt, uint64_t flags); +JS_EXTERN uint64_t JS_GetDumpFlags(JSRuntime *rt); +JS_EXTERN size_t JS_GetGCThreshold(JSRuntime *rt); +JS_EXTERN void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold); +/* use 0 to disable maximum stack size check */ +JS_EXTERN void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size); +/* should be called when changing thread to update the stack top value + used to check stack overflow. */ +JS_EXTERN void JS_UpdateStackTop(JSRuntime *rt); +JS_EXTERN JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque); +JS_EXTERN void JS_FreeRuntime(JSRuntime *rt); +JS_EXTERN void *JS_GetRuntimeOpaque(JSRuntime *rt); +JS_EXTERN void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque); +JS_EXTERN int JS_AddRuntimeFinalizer(JSRuntime *rt, + JSRuntimeFinalizer *finalizer, void *arg); +typedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp); +JS_EXTERN void JS_MarkValue(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +JS_EXTERN void JS_RunGC(JSRuntime *rt); +JS_EXTERN bool JS_IsLiveObject(JSRuntime *rt, JSValueConst obj); + +JS_EXTERN JSContext *JS_NewContext(JSRuntime *rt); +JS_EXTERN void JS_FreeContext(JSContext *s); +JS_EXTERN JSContext *JS_DupContext(JSContext *ctx); +JS_EXTERN void *JS_GetContextOpaque(JSContext *ctx); +JS_EXTERN void JS_SetContextOpaque(JSContext *ctx, void *opaque); +JS_EXTERN JSRuntime *JS_GetRuntime(JSContext *ctx); +JS_EXTERN void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj); +JS_EXTERN JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id); +JS_EXTERN JSValue JS_GetFunctionProto(JSContext *ctx); + +/* the following functions are used to select the intrinsic object to + save memory */ +JS_EXTERN JSContext *JS_NewContextRaw(JSRuntime *rt); +JS_EXTERN void JS_AddIntrinsicBaseObjects(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicDate(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicEval(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicRegExpCompiler(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicRegExp(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicJSON(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicProxy(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicMapSet(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicTypedArrays(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicPromise(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicBigInt(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicWeakRef(JSContext *ctx); +JS_EXTERN void JS_AddPerformance(JSContext *ctx); +JS_EXTERN void JS_AddIntrinsicDOMException(JSContext *ctx); + +/* for equality comparisons and sameness */ +JS_EXTERN int JS_IsEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2); +JS_EXTERN bool JS_IsStrictEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2); +JS_EXTERN bool JS_IsSameValue(JSContext *ctx, JSValueConst op1, JSValueConst op2); +/* Similar to same-value equality, but +0 and -0 are considered equal. */ +JS_EXTERN bool JS_IsSameValueZero(JSContext *ctx, JSValueConst op1, JSValueConst op2); + +/* Only used for running 262 tests. TODO(saghul) add build time flag. */ +JS_EXTERN JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv); + +JS_EXTERN void *js_calloc_rt(JSRuntime *rt, size_t count, size_t size); +JS_EXTERN void *js_malloc_rt(JSRuntime *rt, size_t size); +JS_EXTERN void js_free_rt(JSRuntime *rt, void *ptr); +JS_EXTERN void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size); +JS_EXTERN size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr); +JS_EXTERN void *js_mallocz_rt(JSRuntime *rt, size_t size); + +JS_EXTERN void *js_calloc(JSContext *ctx, size_t count, size_t size); +JS_EXTERN void *js_malloc(JSContext *ctx, size_t size); +JS_EXTERN void js_free(JSContext *ctx, void *ptr); +JS_EXTERN void *js_realloc(JSContext *ctx, void *ptr, size_t size); +JS_EXTERN size_t js_malloc_usable_size(JSContext *ctx, const void *ptr); +JS_EXTERN void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack); +JS_EXTERN void *js_mallocz(JSContext *ctx, size_t size); +JS_EXTERN char *js_strdup(JSContext *ctx, const char *str); +JS_EXTERN char *js_strndup(JSContext *ctx, const char *s, size_t n); + +typedef struct JSMemoryUsage { + int64_t malloc_size, malloc_limit, memory_used_size; + int64_t malloc_count; + int64_t memory_used_count; + int64_t atom_count, atom_size; + int64_t str_count, str_size; + int64_t obj_count, obj_size; + int64_t prop_count, prop_size; + int64_t shape_count, shape_size; + int64_t js_func_count, js_func_size, js_func_code_size; + int64_t js_func_pc2line_count, js_func_pc2line_size; + int64_t c_func_count, array_count; + int64_t fast_array_count, fast_array_elements; + int64_t binary_object_count, binary_object_size; +} JSMemoryUsage; + +JS_EXTERN void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s); +JS_EXTERN void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt); + +/* atom support */ +#define JS_ATOM_NULL 0 + +JS_EXTERN JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len); +JS_EXTERN JSAtom JS_NewAtom(JSContext *ctx, const char *str); +JS_EXTERN JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n); +JS_EXTERN JSAtom JS_DupAtom(JSContext *ctx, JSAtom v); +JS_EXTERN JSAtom JS_DupAtomRT(JSRuntime *rt, JSAtom v); +JS_EXTERN void JS_FreeAtom(JSContext *ctx, JSAtom v); +JS_EXTERN void JS_FreeAtomRT(JSRuntime *rt, JSAtom v); +JS_EXTERN JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom); +JS_EXTERN JSValue JS_AtomToString(JSContext *ctx, JSAtom atom); +JS_EXTERN const char *JS_AtomToCStringLen(JSContext *ctx, size_t *plen, JSAtom atom); +static inline const char *JS_AtomToCString(JSContext *ctx, JSAtom atom) +{ + return JS_AtomToCStringLen(ctx, NULL, atom); +} +JS_EXTERN JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val); + +/* object class support */ + +typedef struct JSPropertyEnum { + bool is_enumerable; + JSAtom atom; +} JSPropertyEnum; + +typedef struct JSPropertyDescriptor { + int flags; + JSValue value; + JSValue getter; + JSValue setter; +} JSPropertyDescriptor; + +typedef struct JSClassExoticMethods { + /* Return -1 if exception (can only happen in case of Proxy object), + false if the property does not exists, true if it exists. If 1 is + returned, the property descriptor 'desc' is filled if != NULL. */ + int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc, + JSValueConst obj, JSAtom prop); + /* '*ptab' should hold the '*plen' property keys. Return 0 if OK, + -1 if exception. The 'is_enumerable' field is ignored. + */ + int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab, + uint32_t *plen, JSValueConst obj); + /* return < 0 if exception, or true/false */ + int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop); + /* return < 0 if exception or true/false */ + int (*define_own_property)(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, + int flags); + /* The following methods can be emulated with the previous ones, + so they are usually not needed */ + /* return < 0 if exception or true/false */ + int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom); + JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, + JSValueConst receiver); + /* return < 0 if exception or true/false */ + int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, + JSValueConst value, JSValueConst receiver, int flags); +} JSClassExoticMethods; + +typedef void JSClassFinalizer(JSRuntime *rt, JSValueConst val); +typedef void JSClassGCMark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +#define JS_CALL_FLAG_CONSTRUCTOR (1 << 0) +typedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_val, int argc, + JSValueConst *argv, int flags); + +typedef struct JSClassDef { + const char *class_name; /* pure ASCII only! */ + JSClassFinalizer *finalizer; + JSClassGCMark *gc_mark; + /* if call != NULL, the object is a function. If (flags & + JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a + constructor. In this case, 'this_val' is new.target. A + constructor call only happens if the object constructor bit is + set (see JS_SetConstructorBit()). */ + JSClassCall *call; + /* XXX: suppress this indirection ? It is here only to save memory + because only a few classes need these methods */ + JSClassExoticMethods *exotic; +} JSClassDef; + +#define JS_EVAL_OPTIONS_VERSION 1 + +typedef struct JSEvalOptions { + int version; + int eval_flags; + const char *filename; + int line_num; + // can add new fields in ABI-compatible manner by incrementing JS_EVAL_OPTIONS_VERSION +} JSEvalOptions; + +#define JS_INVALID_CLASS_ID 0 +JS_EXTERN JSClassID JS_NewClassID(JSRuntime *rt, JSClassID *pclass_id); +/* Returns the class ID if `v` is an object, otherwise returns JS_INVALID_CLASS_ID. */ +JS_EXTERN JSClassID JS_GetClassID(JSValueConst v); +JS_EXTERN int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def); +JS_EXTERN bool JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id); +/* Returns the class name or JS_ATOM_NULL if `id` is not a registered class. Must be freed with JS_FreeAtom. */ +JS_EXTERN JSAtom JS_GetClassName(JSRuntime *rt, JSClassID class_id); + +/* value handling */ + +static inline JSValue JS_NewBool(JSContext *ctx, bool val) +{ + (void)&ctx; + return JS_MKVAL(JS_TAG_BOOL, (val != 0)); +} + +static inline JSValue JS_NewInt32(JSContext *ctx, int32_t val) +{ + (void)&ctx; + return JS_MKVAL(JS_TAG_INT, val); +} + +static inline JSValue JS_NewFloat64(JSContext *ctx, double val) +{ + (void)&ctx; + return __JS_NewFloat64(val); +} + +static inline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val) +{ + (void)&ctx; + return JS_MKVAL(JS_TAG_CATCH_OFFSET, val); +} + +static inline JSValue JS_NewInt64(JSContext *ctx, int64_t val) +{ + JSValue v; + if (val >= INT32_MIN && val <= INT32_MAX) { + v = JS_NewInt32(ctx, (int32_t)val); + } else { + v = JS_NewFloat64(ctx, (double)val); + } + return v; +} + +static inline JSValue JS_NewUint32(JSContext *ctx, uint32_t val) +{ + JSValue v; + if (val <= INT32_MAX) { + v = JS_NewInt32(ctx, (int32_t)val); + } else { + v = JS_NewFloat64(ctx, (double)val); + } + return v; +} + +JS_EXTERN JSValue JS_NewNumber(JSContext *ctx, double d); +JS_EXTERN JSValue JS_NewBigInt64(JSContext *ctx, int64_t v); +JS_EXTERN JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v); + +static inline bool JS_IsNumber(JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag); +} + +static inline bool JS_IsBigInt(JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_BIG_INT || tag == JS_TAG_SHORT_BIG_INT; +} + +static inline bool JS_IsBool(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL; +} + +static inline bool JS_IsNull(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_NULL; +} + +static inline bool JS_IsUndefined(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED; +} + +static inline bool JS_IsException(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION; +} + +static inline bool JS_IsUninitialized(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED; +} + +static inline bool JS_IsString(JSValueConst v) +{ + int tag = JS_VALUE_GET_TAG(v); + return tag == JS_TAG_STRING || tag == JS_TAG_STRING_ROPE; +} + +static inline bool JS_IsSymbol(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL; +} + +static inline bool JS_IsObject(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT; +} + +static inline bool JS_IsModule(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_MODULE; +} + +JS_EXTERN JSValue JS_Throw(JSContext *ctx, JSValue obj); +JS_EXTERN JSValue JS_GetException(JSContext *ctx); +JS_EXTERN bool JS_HasException(JSContext *ctx); +JS_EXTERN bool JS_IsError(JSValueConst val); +JS_EXTERN bool JS_IsUncatchableError(JSValueConst val); +JS_EXTERN void JS_SetUncatchableError(JSContext *ctx, JSValueConst val); +JS_EXTERN void JS_ClearUncatchableError(JSContext *ctx, JSValueConst val); +// Shorthand for: +// JSValue exc = JS_GetException(ctx); +// JS_ClearUncatchableError(ctx, exc); +// JS_Throw(ctx, exc); +JS_EXTERN void JS_ResetUncatchableError(JSContext *ctx); +JS_EXTERN JSValue JS_NewError(JSContext *ctx); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_NewInternalError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_NewPlainError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_NewRangeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_NewReferenceError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_NewSyntaxError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_NewTypeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowInternalError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowPlainError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowRangeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowReferenceError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowSyntaxError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowTypeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(3, 4) JS_ThrowDOMException(JSContext *ctx, const char *name, JS_PRINTF_FORMAT const char *fmt, ...); +JS_EXTERN JSValue JS_ThrowOutOfMemory(JSContext *ctx); +JS_EXTERN void JS_FreeValue(JSContext *ctx, JSValue v); +JS_EXTERN void JS_FreeValueRT(JSRuntime *rt, JSValue v); +JS_EXTERN JSValue JS_DupValue(JSContext *ctx, JSValueConst v); +JS_EXTERN JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v); +JS_EXTERN int JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */ +static inline JSValue JS_ToBoolean(JSContext *ctx, JSValueConst val) +{ + return JS_NewBool(ctx, JS_ToBool(ctx, val)); +} +JS_EXTERN JSValue JS_ToNumber(JSContext *ctx, JSValueConst val); +JS_EXTERN int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val); +static inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val) +{ + return JS_ToInt32(ctx, (int32_t*)pres, val); +} +JS_EXTERN int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val); +JS_EXTERN int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val); +JS_EXTERN int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val); +/* return an exception if 'val' is a Number */ +JS_EXTERN int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val); +JS_EXTERN int JS_ToBigUint64(JSContext *ctx, uint64_t *pres, JSValueConst val); +/* same as JS_ToInt64() but allow BigInt */ +JS_EXTERN int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val); + +JS_EXTERN JSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1); +static inline JSValue JS_NewString(JSContext *ctx, const char *str) { + return JS_NewStringLen(ctx, str, strlen(str)); +} +// makes a copy of the input; does not check if the input is valid UTF-16, +// that is the responsibility of the caller +JS_EXTERN JSValue JS_NewStringUTF16(JSContext *ctx, const uint16_t *buf, + size_t len); +JS_EXTERN JSValue JS_NewAtomString(JSContext *ctx, const char *str); +JS_EXTERN JSValue JS_ToString(JSContext *ctx, JSValueConst val); +JS_EXTERN JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val); +JS_EXTERN const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, bool cesu8); +static inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1) +{ + return JS_ToCStringLen2(ctx, plen, val1, 0); +} +static inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1) +{ + return JS_ToCStringLen2(ctx, NULL, val1, 0); +} +// returns a utf-16 version of the string in native endianness; the +// string is not nul terminated and can contain unmatched surrogates +// |*plen| is in uint16s, not code points; a surrogate pair such as +// U+D834 U+DF06 has len=2; an unmatched surrogate has len=1 +JS_EXTERN const uint16_t *JS_ToCStringLenUTF16(JSContext *ctx, size_t *plen, + JSValueConst val1); +static inline const uint16_t *JS_ToCStringUTF16(JSContext *ctx, + JSValueConst val1) +{ + return JS_ToCStringLenUTF16(ctx, NULL, val1); +} +JS_EXTERN void JS_FreeCString(JSContext *ctx, const char *ptr); +JS_EXTERN void JS_FreeCStringRT(JSRuntime *rt, const char *ptr); +JS_EXTERN void JS_FreeCStringUTF16(JSContext *ctx, const uint16_t *ptr); +JS_EXTERN void JS_FreeCStringRT_UTF16(JSRuntime *rt, const uint16_t *ptr); + +JS_EXTERN JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto, + JSClassID class_id); +JS_EXTERN JSValue JS_NewObjectClass(JSContext *ctx, JSClassID class_id); +JS_EXTERN JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto); +JS_EXTERN JSValue JS_NewObject(JSContext *ctx); +// takes ownership of the values +JS_EXTERN JSValue JS_NewObjectFrom(JSContext *ctx, int count, + const JSAtom *props, + const JSValue *values); +// takes ownership of the values +JS_EXTERN JSValue JS_NewObjectFromStr(JSContext *ctx, int count, + const char **props, + const JSValue *values); +JS_EXTERN JSValue JS_ToObject(JSContext *ctx, JSValueConst val); +JS_EXTERN JSValue JS_ToObjectString(JSContext *ctx, JSValueConst val); + +JS_EXTERN bool JS_IsFunction(JSContext* ctx, JSValueConst val); +JS_EXTERN bool JS_IsConstructor(JSContext* ctx, JSValueConst val); +JS_EXTERN bool JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, bool val); + +JS_EXTERN bool JS_IsRegExp(JSValueConst val); +JS_EXTERN bool JS_IsMap(JSValueConst val); +JS_EXTERN bool JS_IsSet(JSValueConst val); +JS_EXTERN bool JS_IsWeakRef(JSValueConst val); +JS_EXTERN bool JS_IsWeakSet(JSValueConst val); +JS_EXTERN bool JS_IsWeakMap(JSValueConst val); +JS_EXTERN bool JS_IsDataView(JSValueConst val); + +JS_EXTERN JSValue JS_NewArray(JSContext *ctx); +// takes ownership of the values +JS_EXTERN JSValue JS_NewArrayFrom(JSContext *ctx, int count, + const JSValue *values); +// reader beware: JS_IsArray used to "punch" through proxies and check +// if the target object is an array but it no longer does; use JS_IsProxy +// and JS_GetProxyTarget instead, and remember that the target itself can +// also be a proxy, ad infinitum +JS_EXTERN bool JS_IsArray(JSValueConst val); + +JS_EXTERN bool JS_IsProxy(JSValueConst val); +JS_EXTERN JSValue JS_GetProxyTarget(JSContext *ctx, JSValueConst proxy); +JS_EXTERN JSValue JS_GetProxyHandler(JSContext *ctx, JSValueConst proxy); +JS_EXTERN JSValue JS_NewProxy(JSContext *ctx, JSValueConst target, + JSValueConst handler); + +JS_EXTERN JSValue JS_NewDate(JSContext *ctx, double epoch_ms); +JS_EXTERN bool JS_IsDate(JSValueConst v); + +JS_EXTERN JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop); +JS_EXTERN JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx); +JS_EXTERN JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst this_obj, + int64_t idx); +JS_EXTERN JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj, + const char *prop); + +JS_EXTERN int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue val); +JS_EXTERN int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx, JSValue val); +JS_EXTERN int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj, + int64_t idx, JSValue val); +JS_EXTERN int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj, + const char *prop, JSValue val); +JS_EXTERN int JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop); +JS_EXTERN int JS_IsExtensible(JSContext *ctx, JSValueConst obj); +JS_EXTERN int JS_PreventExtensions(JSContext *ctx, JSValueConst obj); +JS_EXTERN int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags); +JS_EXTERN int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val); +JS_EXTERN JSValue JS_GetPrototype(JSContext *ctx, JSValueConst val); +JS_EXTERN int JS_GetLength(JSContext *ctx, JSValueConst obj, int64_t *pres); +JS_EXTERN int JS_SetLength(JSContext *ctx, JSValueConst obj, int64_t len); +JS_EXTERN int JS_SealObject(JSContext *ctx, JSValueConst obj); +JS_EXTERN int JS_FreezeObject(JSContext *ctx, JSValueConst obj); + +#define JS_GPN_STRING_MASK (1 << 0) +#define JS_GPN_SYMBOL_MASK (1 << 1) +#define JS_GPN_PRIVATE_MASK (1 << 2) +/* only include the enumerable properties */ +#define JS_GPN_ENUM_ONLY (1 << 4) +/* set theJSPropertyEnum.is_enumerable field */ +#define JS_GPN_SET_ENUM (1 << 5) + +JS_EXTERN int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, + uint32_t *plen, JSValueConst obj, + int flags); +JS_EXTERN int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc, + JSValueConst obj, JSAtom prop); +JS_EXTERN void JS_FreePropertyEnum(JSContext *ctx, JSPropertyEnum *tab, + uint32_t len); + +JS_EXTERN JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, int argc, JSValueConst *argv); +JS_EXTERN JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom, + int argc, JSValueConst *argv); +JS_EXTERN JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj, + int argc, JSValueConst *argv); +JS_EXTERN JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj, + JSValueConst new_target, + int argc, JSValueConst *argv); +/* Try to detect if the input is a module. Returns true if parsing the input + * as a module produces no syntax errors. It's a naive approach that is not + * wholly infallible: non-strict classic scripts may _parse_ okay as a module + * but not _execute_ as one (different runtime semantics.) Use with caution. + * |input| can be either ASCII or UTF-8 encoded source code. + * Returns false if QuickJS was built with -DQJS_DISABLE_PARSER. + */ +JS_EXTERN bool JS_DetectModule(const char *input, size_t input_len); +/* 'input' must be zero terminated i.e. input[input_len] = '\0'. */ +JS_EXTERN JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len, + const char *filename, int eval_flags); +JS_EXTERN JSValue JS_Eval2(JSContext *ctx, const char *input, size_t input_len, + JSEvalOptions *options); +JS_EXTERN JSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj, + const char *input, size_t input_len, + const char *filename, int eval_flags); +JS_EXTERN JSValue JS_EvalThis2(JSContext *ctx, JSValueConst this_obj, + const char *input, size_t input_len, + JSEvalOptions *options); +JS_EXTERN JSValue JS_GetGlobalObject(JSContext *ctx); +JS_EXTERN int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj); +JS_EXTERN int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, + int flags); +JS_EXTERN int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue val, int flags); +JS_EXTERN int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx, JSValue val, int flags); +JS_EXTERN int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj, + const char *prop, JSValue val, int flags); +JS_EXTERN int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue getter, JSValue setter, + int flags); +/* Only supported for custom classes, returns 0 on success < 0 otherwise. */ +JS_EXTERN int JS_SetOpaque(JSValueConst obj, void *opaque); +JS_EXTERN void *JS_GetOpaque(JSValueConst obj, JSClassID class_id); +JS_EXTERN void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id); +JS_EXTERN void *JS_GetAnyOpaque(JSValueConst obj, JSClassID *class_id); + +/* 'buf' must be zero terminated i.e. buf[buf_len] = '\0'. */ +JS_EXTERN JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len, + const char *filename); +JS_EXTERN JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj, + JSValueConst replacer, JSValueConst space0); + +typedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr); +JS_EXTERN JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len, + JSFreeArrayBufferDataFunc *free_func, void *opaque, + bool is_shared); +JS_EXTERN JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len); +JS_EXTERN void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj); +JS_EXTERN uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj); +JS_EXTERN bool JS_IsArrayBuffer(JSValueConst obj); +JS_EXTERN uint8_t *JS_GetUint8Array(JSContext *ctx, size_t *psize, JSValueConst obj); + +typedef enum JSTypedArrayEnum { + JS_TYPED_ARRAY_UINT8C = 0, + JS_TYPED_ARRAY_INT8, + JS_TYPED_ARRAY_UINT8, + JS_TYPED_ARRAY_INT16, + JS_TYPED_ARRAY_UINT16, + JS_TYPED_ARRAY_INT32, + JS_TYPED_ARRAY_UINT32, + JS_TYPED_ARRAY_BIG_INT64, + JS_TYPED_ARRAY_BIG_UINT64, + JS_TYPED_ARRAY_FLOAT16, + JS_TYPED_ARRAY_FLOAT32, + JS_TYPED_ARRAY_FLOAT64, +} JSTypedArrayEnum; + +JS_EXTERN JSValue JS_NewTypedArray(JSContext *ctx, int argc, JSValueConst *argv, + JSTypedArrayEnum array_type); +JS_EXTERN JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj, + size_t *pbyte_offset, + size_t *pbyte_length, + size_t *pbytes_per_element); +JS_EXTERN JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len, + JSFreeArrayBufferDataFunc *free_func, void *opaque, + bool is_shared); +/* returns -1 if not a typed array otherwise return a JSTypedArrayEnum value */ +JS_EXTERN int JS_GetTypedArrayType(JSValueConst obj); +JS_EXTERN JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len); +typedef struct { + void *(*sab_alloc)(void *opaque, size_t size); + void (*sab_free)(void *opaque, void *ptr); + void (*sab_dup)(void *opaque, void *ptr); + void *sab_opaque; +} JSSharedArrayBufferFunctions; +JS_EXTERN void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, const JSSharedArrayBufferFunctions *sf); + +typedef enum JSPromiseStateEnum { + // argument to JS_PromiseState() was not in fact a promise + JS_PROMISE_NOT_A_PROMISE = -1, + JS_PROMISE_PENDING = 0, + JS_PROMISE_FULFILLED, + JS_PROMISE_REJECTED, +} JSPromiseStateEnum; + +JS_EXTERN JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs); +JS_EXTERN JSPromiseStateEnum JS_PromiseState(JSContext *ctx, + JSValueConst promise); +JS_EXTERN JSValue JS_PromiseResult(JSContext *ctx, JSValueConst promise); +JS_EXTERN bool JS_IsPromise(JSValueConst val); + +JS_EXTERN JSValue JS_NewSymbol(JSContext *ctx, const char *description, bool is_global); + +typedef enum JSPromiseHookType { + JS_PROMISE_HOOK_INIT, // emitted when a new promise is created + JS_PROMISE_HOOK_BEFORE, // runs right before promise.then is invoked + JS_PROMISE_HOOK_AFTER, // runs right after promise.then is invoked + JS_PROMISE_HOOK_RESOLVE, // not emitted for rejected promises +} JSPromiseHookType; + +// parent_promise is only passed in when type == JS_PROMISE_HOOK_INIT and +// is then either a promise object or JS_UNDEFINED if the new promise does +// not have a parent promise; only promises created with promise.then have +// a parent promise +typedef void JSPromiseHook(JSContext *ctx, JSPromiseHookType type, + JSValueConst promise, JSValueConst parent_promise, + void *opaque); +JS_EXTERN void JS_SetPromiseHook(JSRuntime *rt, JSPromiseHook promise_hook, + void *opaque); + +/* is_handled = true means that the rejection is handled */ +typedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise, + JSValueConst reason, + bool is_handled, void *opaque); +JS_EXTERN void JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque); + +/* return != 0 if the JS code needs to be interrupted */ +typedef int JSInterruptHandler(JSRuntime *rt, void *opaque); +JS_EXTERN void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque); +/* if can_block is true, Atomics.wait() can be used */ +JS_EXTERN void JS_SetCanBlock(JSRuntime *rt, bool can_block); +/* set the [IsHTMLDDA] internal slot */ +JS_EXTERN void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj); + +typedef struct JSModuleDef JSModuleDef; + +/* return the module specifier (allocated with js_malloc()) or NULL if + exception */ +typedef char *JSModuleNormalizeFunc(JSContext *ctx, + const char *module_base_name, + const char *module_name, void *opaque); +typedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx, + const char *module_name, void *opaque); + +/* module loader with import attributes support */ +typedef JSModuleDef *JSModuleLoaderFunc2(JSContext *ctx, + const char *module_name, void *opaque, + JSValueConst attributes); + +/* return -1 if exception, 0 if OK */ +typedef int JSModuleCheckSupportedImportAttributes(JSContext *ctx, void *opaque, + JSValueConst attributes); + +/* module_normalize = NULL is allowed and invokes the default module + filename normalizer */ +JS_EXTERN void JS_SetModuleLoaderFunc(JSRuntime *rt, + JSModuleNormalizeFunc *module_normalize, + JSModuleLoaderFunc *module_loader, void *opaque); + +/* same as JS_SetModuleLoaderFunc but with import attributes support */ +JS_EXTERN void JS_SetModuleLoaderFunc2(JSRuntime *rt, + JSModuleNormalizeFunc *module_normalize, + JSModuleLoaderFunc2 *module_loader, + JSModuleCheckSupportedImportAttributes *module_check_attrs, + void *opaque); + +/* return the import.meta object of a module */ +JS_EXTERN JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m); +JS_EXTERN JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m); +JS_EXTERN JSValue JS_GetModuleNamespace(JSContext *ctx, JSModuleDef *m); + +/* associate a JSValue to a C module */ +JS_EXTERN int JS_SetModulePrivateValue(JSContext *ctx, JSModuleDef *m, JSValue val); +JS_EXTERN JSValue JS_GetModulePrivateValue(JSContext *ctx, JSModuleDef *m); + +/* JS Job support */ + +typedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv); +JS_EXTERN int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, + int argc, JSValueConst *argv); + +JS_EXTERN bool JS_IsJobPending(JSRuntime *rt); +JS_EXTERN int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx); + +/* Structure to retrieve (de)serialized SharedArrayBuffer objects. */ +typedef struct JSSABTab { + uint8_t **tab; + size_t len; +} JSSABTab; + +/* Object Writer/Reader (currently only used to handle precompiled code) */ +#define JS_WRITE_OBJ_BYTECODE (1 << 0) /* allow function/module */ +#define JS_WRITE_OBJ_BSWAP (0) /* byte swapped output (obsolete, handled transparently) */ +#define JS_WRITE_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ +#define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to encode arbitrary object graph */ +#define JS_WRITE_OBJ_STRIP_SOURCE (1 << 4) /* do not write source code information */ +#define JS_WRITE_OBJ_STRIP_DEBUG (1 << 5) /* do not write debug information */ +JS_EXTERN uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj, int flags); +JS_EXTERN uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj, + int flags, JSSABTab *psab_tab); + +#define JS_READ_OBJ_BYTECODE (1 << 0) /* allow function/module */ +#define JS_READ_OBJ_ROM_DATA (0) /* avoid duplicating 'buf' data (obsolete, broken by ICs) */ +#define JS_READ_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ +#define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */ +JS_EXTERN JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len, int flags); +JS_EXTERN JSValue JS_ReadObject2(JSContext *ctx, const uint8_t *buf, size_t buf_len, + int flags, JSSABTab *psab_tab); +/* instantiate and evaluate a bytecode function. Only used when + reading a script or module with JS_ReadObject() */ +JS_EXTERN JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj); +/* load the dependencies of the module 'obj'. Useful when JS_ReadObject() + returns a module. */ +JS_EXTERN int JS_ResolveModule(JSContext *ctx, JSValueConst obj); + +/* only exported for os.Worker() */ +JS_EXTERN JSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels); +/* only exported for os.Worker() */ +JS_EXTERN JSValue JS_LoadModule(JSContext *ctx, const char *basename, + const char *filename); + +/* C function definition */ +typedef enum JSCFunctionEnum { /* XXX: should rename for namespace isolation */ + JS_CFUNC_generic, + JS_CFUNC_generic_magic, + JS_CFUNC_constructor, + JS_CFUNC_constructor_magic, + JS_CFUNC_constructor_or_func, + JS_CFUNC_constructor_or_func_magic, + JS_CFUNC_f_f, + JS_CFUNC_f_f_f, + JS_CFUNC_getter, + JS_CFUNC_setter, + JS_CFUNC_getter_magic, + JS_CFUNC_setter_magic, + JS_CFUNC_iterator_next, +} JSCFunctionEnum; + +typedef union JSCFunctionType { + JSCFunction *generic; + JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); + JSCFunction *constructor; + JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic); + JSCFunction *constructor_or_func; + double (*f_f)(double); + double (*f_f_f)(double, double); + JSValue (*getter)(JSContext *ctx, JSValueConst this_val); + JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val); + JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic); + JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic); + JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int *pdone, int magic); +} JSCFunctionType; + +JS_EXTERN JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func, + const char *name, + int length, JSCFunctionEnum cproto, int magic); +JS_EXTERN JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func, + const char *name, + int length, JSCFunctionEnum cproto, int magic, + JSValueConst proto_val); +JS_EXTERN JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func, + int length, int magic, int data_len, + JSValueConst *data); +JS_EXTERN JSValue JS_NewCFunctionData2(JSContext *ctx, JSCFunctionData *func, + const char *name, + int length, int magic, int data_len, + JSValueConst *data); +typedef void JSCClosureFinalizerFunc(void*); +JS_EXTERN JSValue JS_NewCClosure(JSContext *ctx, JSCClosure *func, + const char *name, + JSCClosureFinalizerFunc *opaque_finalize, + int length, int magic, void *opaque); + +static inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func, + const char *name, int length) +{ + return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0); +} + +static inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func, + const char *name, int length, + JSCFunctionEnum cproto, int magic) +{ + /* Used to squelch a -Wcast-function-type warning. */ + JSCFunctionType ft; + ft.generic_magic = func; + return JS_NewCFunction2(ctx, ft.generic, name, length, cproto, magic); +} +JS_EXTERN void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, + JSValueConst proto); + +/* C property definition */ + +typedef struct JSCFunctionListEntry { + const char *name; /* pure ASCII or UTF-8 encoded */ + uint8_t prop_flags; + uint8_t def_type; + int16_t magic; + union { + struct { + uint8_t length; /* XXX: should move outside union */ + uint8_t cproto; /* XXX: should move outside union */ + JSCFunctionType cfunc; + } func; + struct { + JSCFunctionType get; + JSCFunctionType set; + } getset; + struct { + const char *name; + int base; + } alias; + struct { + const struct JSCFunctionListEntry *tab; + int len; + } prop_list; + const char *str; /* pure ASCII or UTF-8 encoded */ + int32_t i32; + int64_t i64; + uint64_t u64; + double f64; + } u; +} JSCFunctionListEntry; + +#define JS_DEF_CFUNC 0 +#define JS_DEF_CGETSET 1 +#define JS_DEF_CGETSET_MAGIC 2 +#define JS_DEF_PROP_STRING 3 +#define JS_DEF_PROP_INT32 4 +#define JS_DEF_PROP_INT64 5 +#define JS_DEF_PROP_DOUBLE 6 +#define JS_DEF_PROP_UNDEFINED 7 +#define JS_DEF_OBJECT 8 +#define JS_DEF_ALIAS 9 + +/* Note: c++ does not like nested designators */ +#define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } } +#define JS_CFUNC_DEF2(name, length, func1, prop_flags) { name, prop_flags, JS_DEF_CFUNC, 0, { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } } +#define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } } +#define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } } +#define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } } +#define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } } +#define JS_CGETSET_DEF2(name, fgetter, fsetter, prop_flags) { name, prop_flags, JS_DEF_CGETSET, 0, { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } } +#define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } } +#define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, { .str = cstr } } +#define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, { .i32 = val } } +#define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, { .i64 = val } } +#define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, { .f64 = val } } +#define JS_PROP_U2D_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, { .u64 = val } } +#define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, { .i32 = 0 } } +#define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, { .prop_list = { tab, len } } } +#define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, { .alias = { from, -1 } } } +#define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, { .alias = { from, base } } } + +JS_EXTERN int JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj, + const JSCFunctionListEntry *tab, + int len); + +/* C module definition */ + +typedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m); + +JS_EXTERN JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str, + JSModuleInitFunc *func); +/* can only be called before the module is instantiated */ +JS_EXTERN int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str); +JS_EXTERN int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m, + const JSCFunctionListEntry *tab, int len); +/* can only be called after the module is instantiated */ +JS_EXTERN int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name, + JSValue val); +JS_EXTERN int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m, + const JSCFunctionListEntry *tab, int len); + +/* Version */ + +#define QJS_VERSION_MAJOR 0 +#define QJS_VERSION_MINOR 12 +#define QJS_VERSION_PATCH 1 +#define QJS_VERSION_SUFFIX "" + +JS_EXTERN const char* JS_GetVersion(void); + +/* Integration point for quickjs-libc.c, not for public use. */ +JS_EXTERN uintptr_t js_std_cmd(int cmd, ...); + +#ifdef __cplusplus +} /* extern "C" { */ +#endif + +#endif /* QUICKJS_H */ +/* + * QuickJS Javascript Engine + * + * Copyright (c) 2017-2025 Fabrice Bellard + * Copyright (c) 2017-2025 Charlie Gordon + * Copyright (c) 2023-2025 Ben Noordhuis + * Copyright (c) 2023-2025 Saúl Ibarra Corretgé + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include +#include +#include +#include +#include +#include +#if !defined(_MSC_VER) +#include +#if defined(_WIN32) +#include +#endif +#endif +#if defined(_WIN32) +#include +#endif +#include +#include + + + + + + + +#if defined(EMSCRIPTEN) || defined(_MSC_VER) +#define DIRECT_DISPATCH 0 +#else +#define DIRECT_DISPATCH 1 +#endif + +#if defined(__APPLE__) +#define MALLOC_OVERHEAD 0 +#else +#define MALLOC_OVERHEAD 8 +#endif + +#if defined(__NEWLIB__) +#define NO_TM_GMTOFF +#endif + +#if defined(__sun) +#include +#define NO_TM_GMTOFF +#endif + +// atomic_store etc. are completely busted in recent versions of tcc; +// somehow the compiler forgets to load |ptr| into %rdi when calling +// the __atomic_*() helpers in its lib/stdatomic.c and lib/atomic.S +#if !defined(__TINYC__) && !defined(EMSCRIPTEN) && !defined(__wasi__) && !__STDC_NO_ATOMICS__ && !defined(__DJGPP) + +#define CONFIG_ATOMICS +#endif + +#ifndef __GNUC__ +#define __extension__ +#endif + +#ifndef NDEBUG +#define ENABLE_DUMPS +#endif + +//#define FORCE_GC_AT_MALLOC /* test the GC by forcing it before each object allocation */ + +#define check_dump_flag(rt, flag) ((rt->dump_flags & (flag +0)) == (flag +0)) + +#define STRINGIFY_(x) #x +#define STRINGIFY(x) STRINGIFY_(x) + +#define QJS_VERSION_STRING \ + STRINGIFY(QJS_VERSION_MAJOR) "." STRINGIFY(QJS_VERSION_MINOR) "." STRINGIFY(QJS_VERSION_PATCH) QJS_VERSION_SUFFIX + +const char* JS_GetVersion(void) { + return QJS_VERSION_STRING; +} + +#undef STRINFIGY_ +#undef STRINGIFY + +static inline JSValueConst *vc(JSValue *vals) +{ + return (JSValueConst *)vals; +} + +static inline JSValue unsafe_unconst(JSValueConst v) +{ +#ifdef JS_CHECK_JSVALUE + return (JSValue)v; +#else + return v; +#endif +} + +static inline JSValueConst safe_const(JSValue v) +{ +#ifdef JS_CHECK_JSVALUE + return (JSValueConst)v; +#else + return v; +#endif +} + +enum { + /* classid tag */ /* union usage | properties */ + JS_CLASS_OBJECT = 1, /* must be first */ + JS_CLASS_ARRAY, /* u.array | length */ + JS_CLASS_ERROR, + JS_CLASS_NUMBER, /* u.object_data */ + JS_CLASS_STRING, /* u.object_data */ + JS_CLASS_BOOLEAN, /* u.object_data */ + JS_CLASS_SYMBOL, /* u.object_data */ + JS_CLASS_ARGUMENTS, /* u.array | length */ + JS_CLASS_MAPPED_ARGUMENTS, /* | length */ + JS_CLASS_DATE, /* u.object_data */ + JS_CLASS_MODULE_NS, + JS_CLASS_C_FUNCTION, /* u.cfunc */ + JS_CLASS_BYTECODE_FUNCTION, /* u.func */ + JS_CLASS_BOUND_FUNCTION, /* u.bound_function */ + JS_CLASS_C_FUNCTION_DATA, /* u.c_function_data_record */ + JS_CLASS_C_CLOSURE, /* u.c_closure_record */ + JS_CLASS_GENERATOR_FUNCTION, /* u.func */ + JS_CLASS_FOR_IN_ITERATOR, /* u.for_in_iterator */ + JS_CLASS_REGEXP, /* u.regexp */ + JS_CLASS_ARRAY_BUFFER, /* u.array_buffer */ + JS_CLASS_SHARED_ARRAY_BUFFER, /* u.array_buffer */ + JS_CLASS_UINT8C_ARRAY, /* u.array (typed_array) */ + JS_CLASS_INT8_ARRAY, /* u.array (typed_array) */ + JS_CLASS_UINT8_ARRAY, /* u.array (typed_array) */ + JS_CLASS_INT16_ARRAY, /* u.array (typed_array) */ + JS_CLASS_UINT16_ARRAY, /* u.array (typed_array) */ + JS_CLASS_INT32_ARRAY, /* u.array (typed_array) */ + JS_CLASS_UINT32_ARRAY, /* u.array (typed_array) */ + JS_CLASS_BIG_INT64_ARRAY, /* u.array (typed_array) */ + JS_CLASS_BIG_UINT64_ARRAY, /* u.array (typed_array) */ + JS_CLASS_FLOAT16_ARRAY, /* u.array (typed_array) */ + JS_CLASS_FLOAT32_ARRAY, /* u.array (typed_array) */ + JS_CLASS_FLOAT64_ARRAY, /* u.array (typed_array) */ + JS_CLASS_DATAVIEW, /* u.typed_array */ + JS_CLASS_BIG_INT, /* u.object_data */ + JS_CLASS_MAP, /* u.map_state */ + JS_CLASS_SET, /* u.map_state */ + JS_CLASS_WEAKMAP, /* u.map_state */ + JS_CLASS_WEAKSET, /* u.map_state */ + JS_CLASS_ITERATOR, + JS_CLASS_ITERATOR_CONCAT, /* u.iterator_concat_data */ + JS_CLASS_ITERATOR_HELPER, /* u.iterator_helper_data */ + JS_CLASS_ITERATOR_WRAP, /* u.iterator_wrap_data */ + JS_CLASS_MAP_ITERATOR, /* u.map_iterator_data */ + JS_CLASS_SET_ITERATOR, /* u.map_iterator_data */ + JS_CLASS_ARRAY_ITERATOR, /* u.array_iterator_data */ + JS_CLASS_STRING_ITERATOR, /* u.array_iterator_data */ + JS_CLASS_REGEXP_STRING_ITERATOR, /* u.regexp_string_iterator_data */ + JS_CLASS_GENERATOR, /* u.generator_data */ + JS_CLASS_PROXY, /* u.proxy_data */ + JS_CLASS_PROMISE, /* u.promise_data */ + JS_CLASS_PROMISE_RESOLVE_FUNCTION, /* u.promise_function_data */ + JS_CLASS_PROMISE_REJECT_FUNCTION, /* u.promise_function_data */ + JS_CLASS_ASYNC_FUNCTION, /* u.func */ + JS_CLASS_ASYNC_FUNCTION_RESOLVE, /* u.async_function_data */ + JS_CLASS_ASYNC_FUNCTION_REJECT, /* u.async_function_data */ + JS_CLASS_ASYNC_FROM_SYNC_ITERATOR, /* u.async_from_sync_iterator_data */ + JS_CLASS_ASYNC_GENERATOR_FUNCTION, /* u.func */ + JS_CLASS_ASYNC_GENERATOR, /* u.async_generator_data */ + JS_CLASS_WEAK_REF, + JS_CLASS_FINALIZATION_REGISTRY, + JS_CLASS_DOM_EXCEPTION, + JS_CLASS_CALL_SITE, + + JS_CLASS_INIT_COUNT, /* last entry for predefined classes */ +}; + +/* number of typed array types */ +#define JS_TYPED_ARRAY_COUNT (JS_CLASS_FLOAT64_ARRAY - JS_CLASS_UINT8C_ARRAY + 1) +static uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT]; +#define typed_array_size_log2(classid) (typed_array_size_log2[(classid)- JS_CLASS_UINT8C_ARRAY]) + +typedef enum JSErrorEnum { + JS_EVAL_ERROR, + JS_RANGE_ERROR, + JS_REFERENCE_ERROR, + JS_SYNTAX_ERROR, + JS_TYPE_ERROR, + JS_URI_ERROR, + JS_INTERNAL_ERROR, + JS_AGGREGATE_ERROR, + + JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */ + JS_PLAIN_ERROR = JS_NATIVE_ERROR_COUNT +} JSErrorEnum; + +#define JS_MAX_LOCAL_VARS 65535 +#define JS_STACK_SIZE_MAX 65534 +#define JS_STRING_LEN_MAX ((1 << 30) - 1) +// 1,024 bytes is about the cutoff point where it starts getting +// more profitable to ref slice than to copy +#define JS_STRING_SLICE_LEN_MAX 1024 // in bytes + +/* strings <= this length are not concatenated using ropes. if too + small, the rope memory overhead becomes high. */ +#define JS_STRING_ROPE_SHORT_LEN 512 +/* specific threshold for initial rope use */ +#define JS_STRING_ROPE_SHORT2_LEN 8192 +/* rope depth at which we rebalance */ +#define JS_STRING_ROPE_MAX_DEPTH 60 + +#define __exception __attribute__((warn_unused_result)) + +typedef struct JSShape JSShape; +typedef struct JSString JSString; +typedef struct JSString JSAtomStruct; +typedef struct JSStringRope JSStringRope; + +#define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v)) +#define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v)) +#define JS_VALUE_GET_STRING_ROPE(v) ((JSStringRope *)JS_VALUE_GET_PTR(v)) + +typedef enum { + JS_GC_PHASE_NONE, + JS_GC_PHASE_DECREF, + JS_GC_PHASE_REMOVE_CYCLES, +} JSGCPhaseEnum; + +typedef struct JSMallocState { + size_t malloc_count; + size_t malloc_size; + size_t malloc_limit; + void *opaque; /* user opaque */ +} JSMallocState; + +typedef struct JSRuntimeFinalizerState { + struct JSRuntimeFinalizerState *next; + JSRuntimeFinalizer *finalizer; + void *arg; +} JSRuntimeFinalizerState; + +typedef struct JSValueLink { + struct JSValueLink *next; + JSValueConst value; +} JSValueLink; + +struct JSRuntime { + JSMallocFunctions mf; + JSMallocState malloc_state; + const char *rt_info; + + int atom_hash_size; /* power of two */ + int atom_count; + int atom_size; + int atom_count_resize; /* resize hash table at this count */ + uint32_t *atom_hash; + JSAtomStruct **atom_array; + int atom_free_index; /* 0 = none */ + + JSClassID js_class_id_alloc; /* counter for user defined classes */ + int class_count; /* size of class_array */ + JSClass *class_array; + + struct list_head context_list; /* list of JSContext.link */ + /* list of JSGCObjectHeader.link. List of allocated GC objects (used + by the garbage collector) */ + struct list_head gc_obj_list; + /* list of JSGCObjectHeader.link. Used during JS_FreeValueRT() */ + struct list_head gc_zero_ref_count_list; + struct list_head tmp_obj_list; /* used during GC */ + JSGCPhaseEnum gc_phase : 8; + size_t malloc_gc_threshold; +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + struct list_head string_list; /* list of JSString.link */ +#endif + /* stack limitation */ + uintptr_t stack_size; /* in bytes, 0 if no limit */ + uintptr_t stack_top; + uintptr_t stack_limit; /* lower stack limit */ + + JSValue current_exception; + /* true if inside an out of memory error, to avoid recursing */ + bool in_out_of_memory; + /* true if inside build_backtrace, to avoid recursing */ + bool in_build_stack_trace; + /* true if inside JS_FreeRuntime */ + bool in_free; + + struct JSStackFrame *current_stack_frame; + + JSInterruptHandler *interrupt_handler; + void *interrupt_opaque; + + JSPromiseHook *promise_hook; + void *promise_hook_opaque; + // for smuggling the parent promise from js_promise_then + // to js_promise_constructor + JSValueLink *parent_promise; + + JSHostPromiseRejectionTracker *host_promise_rejection_tracker; + void *host_promise_rejection_tracker_opaque; + + struct list_head job_list; /* list of JSJobEntry.link */ + + JSModuleNormalizeFunc *module_normalize_func; + bool module_loader_has_attr; + union { + JSModuleLoaderFunc *module_loader_func; + JSModuleLoaderFunc2 *module_loader_func2; + } u; + JSModuleCheckSupportedImportAttributes *module_check_attrs; + void *module_loader_opaque; + /* timestamp for internal use in module evaluation */ + int64_t module_async_evaluation_next_timestamp; + + /* used to allocate, free and clone SharedArrayBuffers */ + JSSharedArrayBufferFunctions sab_funcs; + + bool can_block; /* true if Atomics.wait can block */ + uint32_t dump_flags : 24; + + /* Shape hash table */ + int shape_hash_bits; + int shape_hash_size; + int shape_hash_count; /* number of hashed shapes */ + JSShape **shape_hash; + void *user_opaque; + void *libc_opaque; + JSRuntimeFinalizerState *finalizers; +}; + +struct JSClass { + uint32_t class_id; /* 0 means free entry */ + JSAtom class_name; + JSClassFinalizer *finalizer; + JSClassGCMark *gc_mark; + JSClassCall *call; + /* pointers for exotic behavior, can be NULL if none are present */ + const JSClassExoticMethods *exotic; +}; + +typedef struct JSStackFrame { + struct JSStackFrame *prev_frame; /* NULL if first stack frame */ + JSValue cur_func; /* current function, JS_UNDEFINED if the frame is detached */ + JSValue *arg_buf; /* arguments */ + JSValue *var_buf; /* variables */ + struct JSVarRef **var_refs; /* references to arguments or local variables */ + uint8_t *cur_pc; /* only used in bytecode functions : PC of the + instruction after the call */ + uint16_t var_ref_count; /* number of var refs */ + uint16_t arg_count; + bool is_strict_mode; + /* only used in generators. Current stack pointer value. NULL if + the function is running. */ + JSValue *cur_sp; +} JSStackFrame; + +typedef enum { + JS_GC_OBJ_TYPE_JS_OBJECT, + JS_GC_OBJ_TYPE_FUNCTION_BYTECODE, + JS_GC_OBJ_TYPE_SHAPE, + JS_GC_OBJ_TYPE_VAR_REF, + JS_GC_OBJ_TYPE_ASYNC_FUNCTION, + JS_GC_OBJ_TYPE_JS_CONTEXT, +} JSGCObjectTypeEnum; + +/* header for GC objects. GC objects are C data structures with a + reference count that can reference other GC objects. JS Objects are + a particular type of GC object. */ +struct JSGCObjectHeader { + int ref_count; /* must come first, 32-bit */ + JSGCObjectTypeEnum gc_obj_type : 4; + uint8_t mark : 1; /* used by the GC */ + uint8_t dummy0 : 3; + uint8_t dummy1; /* not used by the GC */ + uint16_t dummy2; /* not used by the GC */ + struct list_head link; +}; + +typedef struct JSVarRef { + union { + JSGCObjectHeader header; /* must come first */ + struct { + int __gc_ref_count; /* corresponds to header.ref_count */ + uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */ + uint8_t is_detached; + uint8_t is_lexical; /* only used with global variables */ + uint8_t is_const; /* only used with global variables */ + }; + }; + JSValue *pvalue; /* pointer to the value, either on the stack or + to 'value' */ + union { + JSValue value; /* used when is_detached = true */ + struct { + uint16_t var_ref_idx; /* index in JSStackFrame.var_refs[] */ + JSStackFrame *stack_frame; + }; /* used when is_detached = false */ + }; +} JSVarRef; + +typedef struct JSRefCountHeader { + int ref_count; +} JSRefCountHeader; + +/* bigint */ +typedef int32_t js_slimb_t; +typedef uint32_t js_limb_t; +typedef int64_t js_sdlimb_t; +typedef uint64_t js_dlimb_t; + +#define JS_LIMB_DIGITS 9 + +/* Must match the size of short_big_int in JSValueUnion */ +#define JS_LIMB_BITS 32 +#define JS_SHORT_BIG_INT_BITS JS_LIMB_BITS +#define JS_BIGINT_MAX_SIZE ((1024 * 1024) / JS_LIMB_BITS) /* in limbs */ +#define JS_SHORT_BIG_INT_MIN INT32_MIN +#define JS_SHORT_BIG_INT_MAX INT32_MAX + + +typedef struct JSBigInt { + JSRefCountHeader header; /* must come first, 32-bit */ + uint32_t len; /* number of limbs, >= 1 */ + js_limb_t tab[]; /* two's complement representation, always + normalized so that 'len' is the minimum + possible length >= 1 */ +} JSBigInt; + +/* this bigint structure can hold a 64 bit integer */ +typedef struct { + js_limb_t big_int_buf[sizeof(JSBigInt) / sizeof(js_limb_t)]; /* for JSBigInt */ + /* must come just after */ + js_limb_t tab[(64 + JS_LIMB_BITS - 1) / JS_LIMB_BITS]; +} JSBigIntBuf; + +typedef enum { + JS_AUTOINIT_ID_PROTOTYPE, + JS_AUTOINIT_ID_MODULE_NS, + JS_AUTOINIT_ID_PROP, + JS_AUTOINIT_ID_BYTECODE, +} JSAutoInitIDEnum; + +enum { + JS_BUILTIN_ARRAY_FROMASYNC = 1, + JS_BUILTIN_ITERATOR_ZIP, + JS_BUILTIN_ITERATOR_ZIP_KEYED, +}; + +/* must be large enough to have a negligible runtime cost and small + enough to call the interrupt callback often. */ +#define JS_INTERRUPT_COUNTER_INIT 10000 + +struct JSContext { + JSGCObjectHeader header; /* must come first */ + JSRuntime *rt; + struct list_head link; + + uint16_t binary_object_count; + uint32_t binary_object_size : 31; + + /* true if the array prototype is "normal": + - no small index properties which are get/set or non writable + - its prototype is Object.prototype + - Object.prototype has no small index properties which are get/set or non writable + - the prototype of Object.prototype is null (always true as it is immutable) + */ + uint8_t std_array_prototype : 1; + + JSShape *array_shape; /* initial shape for Array objects */ + JSShape *arguments_shape; /* shape for arguments objects */ + JSShape *mapped_arguments_shape; /* shape for mapped arguments objects */ + JSShape *regexp_shape; /* shape for regexp objects */ + JSShape *regexp_result_shape; /* shape for regexp result objects */ + + JSValue *class_proto; + JSValue function_proto; + JSValue function_ctor; + JSValue array_ctor; + JSValue regexp_ctor; + JSValue promise_ctor; + JSValue native_error_proto[JS_NATIVE_ERROR_COUNT]; + JSValue error_ctor; + JSValue error_back_trace; + JSValue error_prepare_stack; + JSValue error_stack_trace_limit; + JSValue iterator_ctor; + JSValue iterator_ctor_getset; + JSValue iterator_proto; + JSValue async_iterator_proto; + JSValue array_proto_values; + JSValue throw_type_error; + JSValue eval_obj; + + JSValue global_obj; /* global object */ + JSValue global_var_obj; /* contains the global let/const definitions */ + + double time_origin; + + uint64_t random_state; + + /* when the counter reaches zero, JSRutime.interrupt_handler is called */ + int interrupt_counter; + + struct list_head loaded_modules; /* list of JSModuleDef.link */ + + /* if NULL, RegExp compilation is not supported */ + JSValue (*compile_regexp)(JSContext *ctx, JSValueConst pattern, + JSValueConst flags); + /* if NULL, eval is not supported */ + JSValue (*eval_internal)(JSContext *ctx, JSValueConst this_obj, + const char *input, size_t input_len, + const char *filename, int line, int flags, int scope_idx); + void *user_opaque; +}; + +typedef union JSFloat64Union { + double d; + uint64_t u64; + uint32_t u32[2]; +} JSFloat64Union; + +typedef enum { + JS_WEAK_REF_KIND_MAP, + JS_WEAK_REF_KIND_WEAK_REF, + JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY, +} JSWeakRefKindEnum; + +typedef struct JSWeakRefRecord { + JSWeakRefKindEnum kind; + struct JSWeakRefRecord *next_weak_ref; + union { + struct JSMapRecord *map_record; + struct JSWeakRefData *weak_ref_data; + struct JSFinRecEntry *fin_rec_entry; + } u; +} JSWeakRefRecord; + +typedef struct JSMapRecord { + int ref_count; /* used during enumeration to avoid freeing the record */ + bool empty; /* true if the record is deleted */ + struct JSMapState *map; + struct list_head link; + struct list_head hash_link; + JSValue key; + JSValue value; +} JSMapRecord; + +typedef struct JSMapState { + bool is_weak; /* true if WeakSet/WeakMap */ + struct list_head records; /* list of JSMapRecord.link */ + uint32_t record_count; + struct list_head *hash_table; + uint32_t hash_size; /* must be a power of two */ + uint32_t record_count_threshold; /* count at which a hash table + resize is needed */ +} JSMapState; + +enum +{ + JS_TO_STRING_IS_PROPERTY_KEY = 1 << 0, + JS_TO_STRING_NO_SIDE_EFFECTS = 1 << 1, +}; + +enum { + JS_ATOM_TYPE_STRING = 1, + JS_ATOM_TYPE_GLOBAL_SYMBOL, + JS_ATOM_TYPE_SYMBOL, + JS_ATOM_TYPE_PRIVATE, +}; + +enum { + JS_ATOM_HASH_SYMBOL, + JS_ATOM_HASH_PRIVATE, +}; + +typedef enum { + JS_ATOM_KIND_STRING, + JS_ATOM_KIND_SYMBOL, + JS_ATOM_KIND_PRIVATE, +} JSAtomKindEnum; + +typedef enum { + JS_STRING_KIND_NORMAL, + JS_STRING_KIND_SLICE, + JS_STRING_KIND_INDIRECT, +} JSStringKind; + +#define JS_ATOM_HASH_MASK ((1 << 28) - 1) + +struct JSString { + JSRefCountHeader header; /* must come first, 32-bit */ + uint32_t len : 31; + uint32_t is_wide_char : 1; /* 0 = 8 bits, 1 = 16 bits characters */ + /* for JS_ATOM_TYPE_SYMBOL: hash = 0, atom_type = 3, + for JS_ATOM_TYPE_PRIVATE: hash = 1, atom_type = 3 + XXX: could change encoding to have one more bit in hash */ + uint32_t hash : 28; + uint32_t kind : 2; + uint32_t atom_type : 2; /* != 0 if atom, JS_ATOM_TYPE_x */ + uint32_t hash_next; /* atom_index for JS_ATOM_TYPE_SYMBOL */ + JSWeakRefRecord *first_weak_ref; +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + struct list_head link; /* string list */ +#endif +}; + +typedef struct JSStringSlice { + JSString *parent; + uint32_t start; // in bytes, not characters +} JSStringSlice; + +struct JSStringRope { + JSRefCountHeader header; /* must come first, 32-bit */ + uint32_t len; + uint8_t is_wide_char; /* 0 = 8 bits, 1 = 16 bits characters */ + uint8_t depth; /* max depth of the rope tree */ + JSValue left; + JSValue right; /* might be the empty string */ +}; + +static inline void *strv(JSString *p) +{ + JSStringSlice *slice; + void **indirect; + + switch (p->kind) { + case JS_STRING_KIND_NORMAL: + return (void *)&p[1]; + case JS_STRING_KIND_SLICE: + slice = (void *)&p[1]; + return (char *)&slice->parent[1] + slice->start; + case JS_STRING_KIND_INDIRECT: + indirect = (void *)&p[1]; + return *indirect; + } + abort(); + return NULL; +} + +static inline uint8_t *str8(JSString *p) +{ + return strv(p); +} + +static inline uint16_t *str16(JSString *p) +{ + return strv(p); +} + +typedef enum { + JS_CLOSURE_LOCAL, /* 'var_idx' is the index of a local variable in the parent function */ + JS_CLOSURE_ARG, /* 'var_idx' is the index of an argument variable in the parent function */ + JS_CLOSURE_REF, /* 'var_idx' is the index of a closure variable in the parent function */ + JS_CLOSURE_GLOBAL_REF, /* 'var_idx' is the index of a closure variable in the parent + function referencing a global variable */ + JS_CLOSURE_GLOBAL_DECL, /* global variable declaration (eval code only) */ + JS_CLOSURE_GLOBAL, /* global variable (eval code only) */ + JS_CLOSURE_MODULE_DECL, /* definition of a module variable (eval code only) */ + JS_CLOSURE_MODULE_IMPORT, /* definition of a module import (eval code only) */ +} JSClosureTypeEnum; + +typedef struct JSClosureVar { + uint8_t closure_type : 3; /* see JSClosureTypeEnum */ + uint8_t is_lexical : 1; /* lexical variable */ + uint8_t is_const : 1; /* const variable (is_lexical = 1 if is_const = 1) */ + uint8_t var_kind : 4; /* see JSVarKindEnum */ + /* 7 bits available */ + uint16_t var_idx; /* JS_CLOSURE_LOCAL/JS_CLOSURE_ARG: index to a normal variable of the + parent function. otherwise: index to a closure + variable of the parent function */ + JSAtom var_name; +} JSClosureVar; + +#define ARG_SCOPE_INDEX 1 +#define ARG_SCOPE_END (-2) + +typedef struct JSVarScope { + int parent; /* index into fd->scopes of the enclosing scope */ + int first; /* index into fd->vars of the last variable in this scope */ +} JSVarScope; + +typedef enum { + /* XXX: add more variable kinds here instead of using bit fields */ + JS_VAR_NORMAL, + JS_VAR_FUNCTION_DECL, /* lexical var with function declaration */ + JS_VAR_NEW_FUNCTION_DECL, /* lexical var with async/generator + function declaration */ + JS_VAR_CATCH, + JS_VAR_FUNCTION_NAME, /* function expression name */ + JS_VAR_PRIVATE_FIELD, + JS_VAR_PRIVATE_METHOD, + JS_VAR_PRIVATE_GETTER, + JS_VAR_PRIVATE_SETTER, /* must come after JS_VAR_PRIVATE_GETTER */ + JS_VAR_PRIVATE_GETTER_SETTER, /* must come after JS_VAR_PRIVATE_SETTER */ +} JSVarKindEnum; + +/* XXX: could use a different structure in bytecode functions to save + memory */ +typedef struct JSVarDef { + JSAtom var_name; + /* index into fd->scopes of this variable lexical scope */ + int scope_level; + /* during compilation: + - if scope_level = 0: scope in which the variable is defined + - if scope_level != 0: index into fd->vars of the next + variable in the same or enclosing lexical scope + in a bytecode function: + index into fd->vars of the next + variable in the same or enclosing lexical scope + */ + int scope_next; + uint8_t is_const : 1; + uint8_t is_lexical : 1; + uint8_t is_captured : 1; + uint8_t is_static_private : 1; /* only used during private class field parsing */ + uint8_t var_kind : 4; /* see JSVarKindEnum */ + /* if is_captured = true, provides the index of the corresponding + JSVarRef on stack */ + uint16_t var_ref_idx; + /* only used during compilation: function pool index for lexical + variables with var_kind = + JS_VAR_FUNCTION_DECL/JS_VAR_NEW_FUNCTION_DECL or scope level of + the definition of the 'var' variables (they have scope_level = + 0) */ + int func_pool_idx; /* only used during compilation : index in + the constant pool for hoisted function + definition */ +} JSVarDef; + +/* for the encoding of the pc2line table */ +#define PC2LINE_BASE (-1) +#define PC2LINE_RANGE 5 +#define PC2LINE_OP_FIRST 1 +#define PC2LINE_DIFF_PC_MAX ((255 - PC2LINE_OP_FIRST) / PC2LINE_RANGE) + +typedef enum JSFunctionKindEnum { + JS_FUNC_NORMAL = 0, + JS_FUNC_GENERATOR = (1 << 0), + JS_FUNC_ASYNC = (1 << 1), + JS_FUNC_ASYNC_GENERATOR = (JS_FUNC_GENERATOR | JS_FUNC_ASYNC), +} JSFunctionKindEnum; + +typedef struct JSFunctionBytecode { + JSGCObjectHeader header; /* must come first */ + uint8_t is_strict_mode : 1; + uint8_t has_prototype : 1; /* true if a prototype field is necessary */ + uint8_t has_simple_parameter_list : 1; + uint8_t is_derived_class_constructor : 1; + /* true if home_object needs to be initialized */ + uint8_t need_home_object : 1; + uint8_t func_kind : 2; + uint8_t new_target_allowed : 1; + uint8_t super_call_allowed : 1; + uint8_t super_allowed : 1; + uint8_t arguments_allowed : 1; + uint8_t backtrace_barrier : 1; /* stop backtrace on this function */ + /* XXX: 5 bits available */ + uint8_t *byte_code_buf; /* (self pointer) */ + int byte_code_len; + JSAtom func_name; + JSVarDef *vardefs; /* arguments + local variables (arg_count + var_count) (self pointer) */ + JSClosureVar *closure_var; /* list of variables in the closure (self pointer) */ + uint16_t arg_count; + uint16_t var_count; + uint16_t defined_arg_count; /* for length function property */ + uint16_t stack_size; /* maximum stack size */ + uint16_t var_ref_count; /* number of local variable references */ + uint16_t closure_var_count; + int cpool_count; + JSContext *realm; /* function realm */ + JSValue *cpool; /* constant pool (self pointer) */ + JSAtom filename; + int line_num; + int col_num; + int source_len; + int pc2line_len; + uint8_t *pc2line_buf; + char *source; +} JSFunctionBytecode; + +typedef struct JSBoundFunction { + JSValue func_obj; + JSValue this_val; + int argc; + JSValue argv[]; +} JSBoundFunction; + +typedef enum JSIteratorKindEnum { + JS_ITERATOR_KIND_KEY, + JS_ITERATOR_KIND_VALUE, + JS_ITERATOR_KIND_KEY_AND_VALUE, +} JSIteratorKindEnum; + +typedef enum JSIteratorHelperKindEnum { + JS_ITERATOR_HELPER_KIND_DROP, + JS_ITERATOR_HELPER_KIND_EVERY, + JS_ITERATOR_HELPER_KIND_FILTER, + JS_ITERATOR_HELPER_KIND_FIND, + JS_ITERATOR_HELPER_KIND_FLAT_MAP, + JS_ITERATOR_HELPER_KIND_FOR_EACH, + JS_ITERATOR_HELPER_KIND_MAP, + JS_ITERATOR_HELPER_KIND_SOME, + JS_ITERATOR_HELPER_KIND_TAKE, +} JSIteratorHelperKindEnum; + +typedef struct JSForInIterator { + JSValue obj; + bool is_array; + uint32_t array_length; + uint32_t idx; +} JSForInIterator; + +typedef struct JSRegExp { + JSString *pattern; + JSString *bytecode; /* also contains the flags */ +} JSRegExp; + +typedef struct JSProxyData { + JSValue target; + JSValue handler; + uint8_t is_func; + uint8_t is_revoked; +} JSProxyData; + +typedef struct JSArrayBuffer { + int byte_length; /* 0 if detached */ + int max_byte_length; /* -1 if not resizable; >= byte_length otherwise */ + uint8_t detached; + uint8_t immutable; + uint8_t shared; /* if shared, the array buffer cannot be detached */ + uint8_t *data; /* NULL if detached */ + struct list_head array_list; + void *opaque; + JSFreeArrayBufferDataFunc *free_func; +} JSArrayBuffer; + +typedef struct JSTypedArray { + struct list_head link; /* link to arraybuffer */ + JSObject *obj; /* back pointer to the TypedArray/DataView object */ + JSObject *buffer; /* based array buffer */ + uint32_t offset; /* byte offset in the array buffer */ + uint32_t length; /* byte length in the array buffer */ + bool track_rab; /* auto-track length of backing array buffer */ +} JSTypedArray; + +typedef struct JSAsyncFunctionState { + JSValue this_val; /* 'this' generator argument */ + int argc; /* number of function arguments */ + bool throw_flag; /* used to throw an exception in JS_CallInternal() */ + JSStackFrame frame; +} JSAsyncFunctionState; + +/* XXX: could use an object instead to avoid the + JS_TAG_ASYNC_FUNCTION tag for the GC */ +typedef struct JSAsyncFunctionData { + JSGCObjectHeader header; /* must come first */ + JSValue resolving_funcs[2]; + bool is_active; /* true if the async function state is valid */ + JSAsyncFunctionState func_state; +} JSAsyncFunctionData; + +typedef struct JSReqModuleEntry { + JSAtom module_name; + JSModuleDef *module; /* used using resolution */ + JSValue attributes; /* JS_UNDEFINED or an object containing the attributes as key/value */ +} JSReqModuleEntry; + +typedef enum JSExportTypeEnum { + JS_EXPORT_TYPE_LOCAL, + JS_EXPORT_TYPE_INDIRECT, +} JSExportTypeEnum; + +typedef struct JSExportEntry { + union { + struct { + int var_idx; /* closure variable index */ + JSVarRef *var_ref; /* if != NULL, reference to the variable */ + } local; /* for local export */ + int req_module_idx; /* module for indirect export */ + } u; + JSExportTypeEnum export_type; + JSAtom local_name; /* '*' if export ns from. not used for local + export after compilation */ + JSAtom export_name; /* exported variable name */ +} JSExportEntry; + +typedef struct JSStarExportEntry { + int req_module_idx; /* in req_module_entries */ +} JSStarExportEntry; + +typedef struct JSImportEntry { + int var_idx; /* closure variable index */ + JSAtom import_name; + int req_module_idx; /* in req_module_entries */ +} JSImportEntry; + +typedef enum { + JS_MODULE_STATUS_UNLINKED, + JS_MODULE_STATUS_LINKING, + JS_MODULE_STATUS_LINKED, + JS_MODULE_STATUS_EVALUATING, + JS_MODULE_STATUS_EVALUATING_ASYNC, + JS_MODULE_STATUS_EVALUATED, +} JSModuleStatus; + +struct JSModuleDef { + JSRefCountHeader header; /* must come first, 32-bit */ + JSAtom module_name; + struct list_head link; + + JSReqModuleEntry *req_module_entries; + int req_module_entries_count; + int req_module_entries_size; + + JSExportEntry *export_entries; + int export_entries_count; + int export_entries_size; + + JSStarExportEntry *star_export_entries; + int star_export_entries_count; + int star_export_entries_size; + + JSImportEntry *import_entries; + int import_entries_count; + int import_entries_size; + + JSValue module_ns; + JSValue func_obj; /* only used for JS modules */ + JSModuleInitFunc *init_func; /* only used for C modules */ + bool has_tla; /* true if func_obj contains await */ + bool resolved; + bool func_created; + JSModuleStatus status : 8; + /* temp use during js_module_link() & js_module_evaluate() */ + int dfs_index, dfs_ancestor_index; + JSModuleDef *stack_prev; + /* temp use during js_module_evaluate() */ + JSModuleDef **async_parent_modules; + int async_parent_modules_count; + int async_parent_modules_size; + int pending_async_dependencies; + bool async_evaluation; + int64_t async_evaluation_timestamp; + JSModuleDef *cycle_root; + JSValue promise; /* corresponds to spec field: capability */ + JSValue resolving_funcs[2]; /* corresponds to spec field: capability */ + /* true if evaluation yielded an exception. It is saved in + eval_exception */ + bool eval_has_exception; + JSValue eval_exception; + JSValue meta_obj; /* for import.meta */ + JSValue private_value; /* private value for C modules */ +}; + +typedef struct JSJobEntry { + struct list_head link; + JSContext *ctx; + JSJobFunc *job_func; + int argc; + JSValue argv[]; +} JSJobEntry; + +typedef struct JSProperty { + union { + JSValue value; /* JS_PROP_NORMAL */ + struct { /* JS_PROP_GETSET */ + JSObject *getter; /* NULL if undefined */ + JSObject *setter; /* NULL if undefined */ + } getset; + JSVarRef *var_ref; /* JS_PROP_VARREF */ + struct { /* JS_PROP_AUTOINIT */ + /* in order to use only 2 pointers, we compress the realm + and the init function pointer */ + uintptr_t realm_and_id; /* realm and init_id (JS_AUTOINIT_ID_x) + in the 2 low bits */ + void *opaque; + } init; + } u; +} JSProperty; + +#define JS_PROP_INITIAL_SIZE 2 +#define JS_PROP_INITIAL_HASH_SIZE 4 /* must be a power of two */ +#define JS_ARRAY_INITIAL_SIZE 2 + +typedef struct JSShapeProperty { + uint32_t hash_next : 26; /* 0 if last in list */ + uint32_t flags : 6; /* JS_PROP_XXX */ + JSAtom atom; /* JS_ATOM_NULL = free property entry */ +} JSShapeProperty; + +struct JSShape { + /* hash table of size hash_mask + 1 before the start of the + structure (see prop_hash_end()). */ + JSGCObjectHeader header; + /* true if the shape is inserted in the shape hash table. If not, + JSShape.hash is not valid */ + uint8_t is_hashed; + uint32_t hash; /* current hash value */ + uint32_t prop_hash_mask; + int prop_size; /* allocated properties */ + int prop_count; /* include deleted properties */ + int deleted_prop_count; + JSShape *shape_hash_next; /* in JSRuntime.shape_hash[h] list */ + JSObject *proto; + JSShapeProperty prop[]; /* prop_size elements */ +}; + +struct JSObject { + union { + JSGCObjectHeader header; + struct { + int __gc_ref_count; /* corresponds to header.ref_count */ + uint8_t __gc_mark : 7; /* corresponds to header.mark/gc_obj_type */ + uint8_t is_prototype : 1; /* object may be used as prototype */ + + uint8_t extensible : 1; + uint8_t free_mark : 1; /* only used when freeing objects with cycles */ + uint8_t is_exotic : 1; /* true if object has exotic property handlers */ + uint8_t fast_array : 1; /* true if u.array is used for get/put (for JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_MAPPED_ARGUMENTS and typed arrays) */ + uint8_t is_constructor : 1; /* true if object is a constructor function */ + uint8_t is_uncatchable_error : 1; /* if true, error is not catchable */ + uint8_t tmp_mark : 1; /* used in JS_WriteObjectRec() */ + uint8_t is_HTMLDDA : 1; /* specific annex B IsHtmlDDA behavior */ + uint16_t class_id; /* see JS_CLASS_x */ + }; + }; + /* byte offsets: 16/24 */ + JSShape *shape; /* prototype and property names + flag */ + JSProperty *prop; /* array of properties */ + /* byte offsets: 24/40 */ + JSWeakRefRecord *first_weak_ref; + /* byte offsets: 28/48 */ + union { + void *opaque; + struct JSBoundFunction *bound_function; /* JS_CLASS_BOUND_FUNCTION */ + struct JSCFunctionDataRecord *c_function_data_record; /* JS_CLASS_C_FUNCTION_DATA */ + struct JSCClosureRecord *c_closure_record; /* JS_CLASS_C_CLOSURE */ + struct JSForInIterator *for_in_iterator; /* JS_CLASS_FOR_IN_ITERATOR */ + struct JSArrayBuffer *array_buffer; /* JS_CLASS_ARRAY_BUFFER, JS_CLASS_SHARED_ARRAY_BUFFER */ + struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_DATAVIEW */ + struct JSMapState *map_state; /* JS_CLASS_MAP..JS_CLASS_WEAKSET */ + struct JSMapIteratorData *map_iterator_data; /* JS_CLASS_MAP_ITERATOR, JS_CLASS_SET_ITERATOR */ + struct JSArrayIteratorData *array_iterator_data; /* JS_CLASS_ARRAY_ITERATOR, JS_CLASS_STRING_ITERATOR */ + struct JSRegExpStringIteratorData *regexp_string_iterator_data; /* JS_CLASS_REGEXP_STRING_ITERATOR */ + struct JSGeneratorData *generator_data; /* JS_CLASS_GENERATOR */ + struct JSIteratorConcatData *iterator_concat_data; /* JS_CLASS_ITERATOR_CONCAT */ + struct JSIteratorHelperData *iterator_helper_data; /* JS_CLASS_ITERATOR_HELPER */ + struct JSIteratorWrapData *iterator_wrap_data; /* JS_CLASS_ITERATOR_WRAP */ + struct JSProxyData *proxy_data; /* JS_CLASS_PROXY */ + struct JSPromiseData *promise_data; /* JS_CLASS_PROMISE */ + struct JSPromiseFunctionData *promise_function_data; /* JS_CLASS_PROMISE_RESOLVE_FUNCTION, JS_CLASS_PROMISE_REJECT_FUNCTION */ + struct JSAsyncFunctionData *async_function_data; /* JS_CLASS_ASYNC_FUNCTION_RESOLVE, JS_CLASS_ASYNC_FUNCTION_REJECT */ + struct JSAsyncFromSyncIteratorData *async_from_sync_iterator_data; /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */ + struct JSAsyncGeneratorData *async_generator_data; /* JS_CLASS_ASYNC_GENERATOR */ + struct { /* JS_CLASS_BYTECODE_FUNCTION: 12/24 bytes */ + /* also used by JS_CLASS_GENERATOR_FUNCTION, JS_CLASS_ASYNC_FUNCTION and JS_CLASS_ASYNC_GENERATOR_FUNCTION */ + struct JSFunctionBytecode *function_bytecode; + JSVarRef **var_refs; + JSObject *home_object; /* for 'super' access */ + } func; + struct { /* JS_CLASS_C_FUNCTION: 12/20 bytes */ + JSContext *realm; + JSCFunctionType c_function; + uint8_t length; + uint8_t cproto; + int16_t magic; + } cfunc; + /* array part for fast arrays and typed arrays */ + struct { /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_MAPPED_ARGUMENTS, JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */ + union { + uint32_t size; /* JS_CLASS_ARRAY */ + struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */ + } u1; + union { + JSValue *values; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */ + JSVarRef **var_refs; /* JS_CLASS_MAPPED_ARGUMENTS */ + void *ptr; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */ + int8_t *int8_ptr; /* JS_CLASS_INT8_ARRAY */ + uint8_t *uint8_ptr; /* JS_CLASS_UINT8_ARRAY, JS_CLASS_UINT8C_ARRAY */ + int16_t *int16_ptr; /* JS_CLASS_INT16_ARRAY */ + uint16_t *uint16_ptr; /* JS_CLASS_UINT16_ARRAY */ + int32_t *int32_ptr; /* JS_CLASS_INT32_ARRAY */ + uint32_t *uint32_ptr; /* JS_CLASS_UINT32_ARRAY */ + int64_t *int64_ptr; /* JS_CLASS_INT64_ARRAY */ + uint64_t *uint64_ptr; /* JS_CLASS_UINT64_ARRAY */ + uint16_t *fp16_ptr; /* JS_CLASS_FLOAT16_ARRAY */ + float *float_ptr; /* JS_CLASS_FLOAT32_ARRAY */ + double *double_ptr; /* JS_CLASS_FLOAT64_ARRAY */ + } u; + uint32_t count; /* <= 2^31-1. 0 for a detached typed array */ + } array; /* 12/20 bytes */ + JSRegExp regexp; /* JS_CLASS_REGEXP: 8/16 bytes */ + JSValue object_data; /* for JS_SetObjectData(): 8/16/16 bytes */ + } u; + /* byte sizes: 40/48/72 */ +}; + +typedef struct JSCallSiteData { + JSValue filename; + JSValue func; + JSValue func_name; + bool native; + int line_num; + int col_num; +} JSCallSiteData; + +enum { + __JS_ATOM_NULL = JS_ATOM_NULL, +#define DEF(name, str) JS_ATOM_ ## name, +/* + * QuickJS atom definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef DEF + +/* Note: first atoms are considered as keywords in the parser */ +DEF(null, "null") /* must be first */ +DEF(false, "false") +DEF(true, "true") +DEF(if, "if") +DEF(else, "else") +DEF(return, "return") +DEF(var, "var") +DEF(this, "this") +DEF(delete, "delete") +DEF(void, "void") +DEF(typeof, "typeof") +DEF(new, "new") +DEF(in, "in") +DEF(instanceof, "instanceof") +DEF(do, "do") +DEF(while, "while") +DEF(for, "for") +DEF(break, "break") +DEF(continue, "continue") +DEF(switch, "switch") +DEF(case, "case") +DEF(default, "default") +DEF(throw, "throw") +DEF(try, "try") +DEF(catch, "catch") +DEF(finally, "finally") +DEF(function, "function") +DEF(debugger, "debugger") +DEF(with, "with") +/* FutureReservedWord */ +DEF(class, "class") +DEF(const, "const") +DEF(enum, "enum") +DEF(export, "export") +DEF(extends, "extends") +DEF(import, "import") +DEF(super, "super") +/* FutureReservedWords when parsing strict mode code */ +DEF(implements, "implements") +DEF(interface, "interface") +DEF(let, "let") +DEF(package, "package") +DEF(private, "private") +DEF(protected, "protected") +DEF(public, "public") +DEF(static, "static") +DEF(yield, "yield") +DEF(await, "await") + +/* empty string */ +DEF(empty_string, "") +/* identifiers */ +DEF(keys, "keys") +DEF(size, "size") +DEF(length, "length") +DEF(message, "message") +DEF(cause, "cause") +DEF(errors, "errors") +DEF(stack, "stack") +DEF(name, "name") +DEF(toString, "toString") +DEF(toLocaleString, "toLocaleString") +DEF(valueOf, "valueOf") +DEF(eval, "eval") +DEF(prototype, "prototype") +DEF(constructor, "constructor") +DEF(configurable, "configurable") +DEF(writable, "writable") +DEF(enumerable, "enumerable") +DEF(value, "value") +DEF(get, "get") +DEF(set, "set") +DEF(of, "of") +DEF(__proto__, "__proto__") +DEF(undefined, "undefined") +DEF(number, "number") +DEF(boolean, "boolean") +DEF(string, "string") +DEF(object, "object") +DEF(symbol, "symbol") +DEF(integer, "integer") +DEF(unknown, "unknown") +DEF(arguments, "arguments") +DEF(callee, "callee") +DEF(caller, "caller") +DEF(_eval_, "") +DEF(_ret_, "") +DEF(_var_, "") +DEF(_arg_var_, "") +DEF(_with_, "") +DEF(lastIndex, "lastIndex") +DEF(target, "target") +DEF(index, "index") +DEF(input, "input") +DEF(defineProperties, "defineProperties") +DEF(apply, "apply") +DEF(join, "join") +DEF(concat, "concat") +DEF(split, "split") +DEF(construct, "construct") +DEF(getPrototypeOf, "getPrototypeOf") +DEF(setPrototypeOf, "setPrototypeOf") +DEF(isExtensible, "isExtensible") +DEF(preventExtensions, "preventExtensions") +DEF(has, "has") +DEF(deleteProperty, "deleteProperty") +DEF(defineProperty, "defineProperty") +DEF(getOwnPropertyDescriptor, "getOwnPropertyDescriptor") +DEF(ownKeys, "ownKeys") +DEF(add, "add") +DEF(done, "done") +DEF(next, "next") +DEF(values, "values") +DEF(source, "source") +DEF(flags, "flags") +DEF(global, "global") +DEF(unicode, "unicode") +DEF(raw, "raw") +DEF(new_target, "new.target") +DEF(this_active_func, "this.active_func") +DEF(home_object, "") +DEF(computed_field, "") +DEF(static_computed_field, "") /* must come after computed_fields */ +DEF(class_fields_init, "") +DEF(brand, "") +DEF(hash_constructor, "#constructor") +DEF(as, "as") +DEF(from, "from") +DEF(fromAsync, "fromAsync") +DEF(meta, "meta") +DEF(_default_, "*default*") +DEF(_star_, "*") +DEF(Module, "Module") +DEF(then, "then") +DEF(resolve, "resolve") +DEF(reject, "reject") +DEF(promise, "promise") +DEF(proxy, "proxy") +DEF(revoke, "revoke") +DEF(async, "async") +DEF(exec, "exec") +DEF(groups, "groups") +DEF(indices, "indices") +DEF(status, "status") +DEF(reason, "reason") +DEF(globalThis, "globalThis") +DEF(bigint, "bigint") +DEF(not_equal, "not-equal") +DEF(timed_out, "timed-out") +DEF(ok, "ok") +DEF(toJSON, "toJSON") +DEF(maxByteLength, "maxByteLength") +DEF(zip, "zip") +DEF(zipKeyed, "zipKeyed") +/* class names */ +DEF(Object, "Object") +DEF(Array, "Array") +DEF(Error, "Error") +DEF(Number, "Number") +DEF(String, "String") +DEF(Boolean, "Boolean") +DEF(Symbol, "Symbol") +DEF(Arguments, "Arguments") +DEF(Math, "Math") +DEF(JSON, "JSON") +DEF(Date, "Date") +DEF(Function, "Function") +DEF(GeneratorFunction, "GeneratorFunction") +DEF(ForInIterator, "ForInIterator") +DEF(RegExp, "RegExp") +DEF(ArrayBuffer, "ArrayBuffer") +DEF(SharedArrayBuffer, "SharedArrayBuffer") +/* must keep same order as class IDs for typed arrays */ +DEF(Uint8ClampedArray, "Uint8ClampedArray") +DEF(Int8Array, "Int8Array") +DEF(Uint8Array, "Uint8Array") +DEF(Int16Array, "Int16Array") +DEF(Uint16Array, "Uint16Array") +DEF(Int32Array, "Int32Array") +DEF(Uint32Array, "Uint32Array") +DEF(BigInt64Array, "BigInt64Array") +DEF(BigUint64Array, "BigUint64Array") +DEF(Float16Array, "Float16Array") +DEF(Float32Array, "Float32Array") +DEF(Float64Array, "Float64Array") +DEF(DataView, "DataView") +DEF(BigInt, "BigInt") +DEF(WeakRef, "WeakRef") +DEF(FinalizationRegistry, "FinalizationRegistry") +DEF(Map, "Map") +DEF(Set, "Set") /* Map + 1 */ +DEF(WeakMap, "WeakMap") /* Map + 2 */ +DEF(WeakSet, "WeakSet") /* Map + 3 */ +DEF(Iterator, "Iterator") +DEF(IteratorConcat, "Iterator Concat") +DEF(IteratorHelper, "Iterator Helper") +DEF(IteratorWrap, "Iterator Wrap") +DEF(Map_Iterator, "Map Iterator") +DEF(Set_Iterator, "Set Iterator") +DEF(Array_Iterator, "Array Iterator") +DEF(String_Iterator, "String Iterator") +DEF(RegExp_String_Iterator, "RegExp String Iterator") +DEF(Generator, "Generator") +DEF(Proxy, "Proxy") +DEF(Promise, "Promise") +DEF(PromiseResolveFunction, "PromiseResolveFunction") +DEF(PromiseRejectFunction, "PromiseRejectFunction") +DEF(AsyncFunction, "AsyncFunction") +DEF(AsyncFunctionResolve, "AsyncFunctionResolve") +DEF(AsyncFunctionReject, "AsyncFunctionReject") +DEF(AsyncGeneratorFunction, "AsyncGeneratorFunction") +DEF(AsyncGenerator, "AsyncGenerator") +DEF(EvalError, "EvalError") +DEF(RangeError, "RangeError") +DEF(ReferenceError, "ReferenceError") +DEF(SyntaxError, "SyntaxError") +DEF(TypeError, "TypeError") +DEF(URIError, "URIError") +DEF(InternalError, "InternalError") +DEF(DOMException, "DOMException") +DEF(CallSite, "CallSite") +/* private symbols */ +DEF(Private_brand, "") +/* symbols */ +DEF(Symbol_toPrimitive, "Symbol.toPrimitive") +DEF(Symbol_iterator, "Symbol.iterator") +DEF(Symbol_match, "Symbol.match") +DEF(Symbol_matchAll, "Symbol.matchAll") +DEF(Symbol_replace, "Symbol.replace") +DEF(Symbol_search, "Symbol.search") +DEF(Symbol_split, "Symbol.split") +DEF(Symbol_toStringTag, "Symbol.toStringTag") +DEF(Symbol_isConcatSpreadable, "Symbol.isConcatSpreadable") +DEF(Symbol_hasInstance, "Symbol.hasInstance") +DEF(Symbol_species, "Symbol.species") +DEF(Symbol_unscopables, "Symbol.unscopables") +DEF(Symbol_asyncIterator, "Symbol.asyncIterator") + +#endif /* DEF */ + +#undef DEF + JS_ATOM_END, +}; +#define JS_ATOM_LAST_KEYWORD JS_ATOM_super +#define JS_ATOM_LAST_STRICT_KEYWORD JS_ATOM_yield + +static const char js_atom_init[] = +#define DEF(name, str) str "\0" +/* + * QuickJS atom definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef DEF + +/* Note: first atoms are considered as keywords in the parser */ +DEF(null, "null") /* must be first */ +DEF(false, "false") +DEF(true, "true") +DEF(if, "if") +DEF(else, "else") +DEF(return, "return") +DEF(var, "var") +DEF(this, "this") +DEF(delete, "delete") +DEF(void, "void") +DEF(typeof, "typeof") +DEF(new, "new") +DEF(in, "in") +DEF(instanceof, "instanceof") +DEF(do, "do") +DEF(while, "while") +DEF(for, "for") +DEF(break, "break") +DEF(continue, "continue") +DEF(switch, "switch") +DEF(case, "case") +DEF(default, "default") +DEF(throw, "throw") +DEF(try, "try") +DEF(catch, "catch") +DEF(finally, "finally") +DEF(function, "function") +DEF(debugger, "debugger") +DEF(with, "with") +/* FutureReservedWord */ +DEF(class, "class") +DEF(const, "const") +DEF(enum, "enum") +DEF(export, "export") +DEF(extends, "extends") +DEF(import, "import") +DEF(super, "super") +/* FutureReservedWords when parsing strict mode code */ +DEF(implements, "implements") +DEF(interface, "interface") +DEF(let, "let") +DEF(package, "package") +DEF(private, "private") +DEF(protected, "protected") +DEF(public, "public") +DEF(static, "static") +DEF(yield, "yield") +DEF(await, "await") + +/* empty string */ +DEF(empty_string, "") +/* identifiers */ +DEF(keys, "keys") +DEF(size, "size") +DEF(length, "length") +DEF(message, "message") +DEF(cause, "cause") +DEF(errors, "errors") +DEF(stack, "stack") +DEF(name, "name") +DEF(toString, "toString") +DEF(toLocaleString, "toLocaleString") +DEF(valueOf, "valueOf") +DEF(eval, "eval") +DEF(prototype, "prototype") +DEF(constructor, "constructor") +DEF(configurable, "configurable") +DEF(writable, "writable") +DEF(enumerable, "enumerable") +DEF(value, "value") +DEF(get, "get") +DEF(set, "set") +DEF(of, "of") +DEF(__proto__, "__proto__") +DEF(undefined, "undefined") +DEF(number, "number") +DEF(boolean, "boolean") +DEF(string, "string") +DEF(object, "object") +DEF(symbol, "symbol") +DEF(integer, "integer") +DEF(unknown, "unknown") +DEF(arguments, "arguments") +DEF(callee, "callee") +DEF(caller, "caller") +DEF(_eval_, "") +DEF(_ret_, "") +DEF(_var_, "") +DEF(_arg_var_, "") +DEF(_with_, "") +DEF(lastIndex, "lastIndex") +DEF(target, "target") +DEF(index, "index") +DEF(input, "input") +DEF(defineProperties, "defineProperties") +DEF(apply, "apply") +DEF(join, "join") +DEF(concat, "concat") +DEF(split, "split") +DEF(construct, "construct") +DEF(getPrototypeOf, "getPrototypeOf") +DEF(setPrototypeOf, "setPrototypeOf") +DEF(isExtensible, "isExtensible") +DEF(preventExtensions, "preventExtensions") +DEF(has, "has") +DEF(deleteProperty, "deleteProperty") +DEF(defineProperty, "defineProperty") +DEF(getOwnPropertyDescriptor, "getOwnPropertyDescriptor") +DEF(ownKeys, "ownKeys") +DEF(add, "add") +DEF(done, "done") +DEF(next, "next") +DEF(values, "values") +DEF(source, "source") +DEF(flags, "flags") +DEF(global, "global") +DEF(unicode, "unicode") +DEF(raw, "raw") +DEF(new_target, "new.target") +DEF(this_active_func, "this.active_func") +DEF(home_object, "") +DEF(computed_field, "") +DEF(static_computed_field, "") /* must come after computed_fields */ +DEF(class_fields_init, "") +DEF(brand, "") +DEF(hash_constructor, "#constructor") +DEF(as, "as") +DEF(from, "from") +DEF(fromAsync, "fromAsync") +DEF(meta, "meta") +DEF(_default_, "*default*") +DEF(_star_, "*") +DEF(Module, "Module") +DEF(then, "then") +DEF(resolve, "resolve") +DEF(reject, "reject") +DEF(promise, "promise") +DEF(proxy, "proxy") +DEF(revoke, "revoke") +DEF(async, "async") +DEF(exec, "exec") +DEF(groups, "groups") +DEF(indices, "indices") +DEF(status, "status") +DEF(reason, "reason") +DEF(globalThis, "globalThis") +DEF(bigint, "bigint") +DEF(not_equal, "not-equal") +DEF(timed_out, "timed-out") +DEF(ok, "ok") +DEF(toJSON, "toJSON") +DEF(maxByteLength, "maxByteLength") +DEF(zip, "zip") +DEF(zipKeyed, "zipKeyed") +/* class names */ +DEF(Object, "Object") +DEF(Array, "Array") +DEF(Error, "Error") +DEF(Number, "Number") +DEF(String, "String") +DEF(Boolean, "Boolean") +DEF(Symbol, "Symbol") +DEF(Arguments, "Arguments") +DEF(Math, "Math") +DEF(JSON, "JSON") +DEF(Date, "Date") +DEF(Function, "Function") +DEF(GeneratorFunction, "GeneratorFunction") +DEF(ForInIterator, "ForInIterator") +DEF(RegExp, "RegExp") +DEF(ArrayBuffer, "ArrayBuffer") +DEF(SharedArrayBuffer, "SharedArrayBuffer") +/* must keep same order as class IDs for typed arrays */ +DEF(Uint8ClampedArray, "Uint8ClampedArray") +DEF(Int8Array, "Int8Array") +DEF(Uint8Array, "Uint8Array") +DEF(Int16Array, "Int16Array") +DEF(Uint16Array, "Uint16Array") +DEF(Int32Array, "Int32Array") +DEF(Uint32Array, "Uint32Array") +DEF(BigInt64Array, "BigInt64Array") +DEF(BigUint64Array, "BigUint64Array") +DEF(Float16Array, "Float16Array") +DEF(Float32Array, "Float32Array") +DEF(Float64Array, "Float64Array") +DEF(DataView, "DataView") +DEF(BigInt, "BigInt") +DEF(WeakRef, "WeakRef") +DEF(FinalizationRegistry, "FinalizationRegistry") +DEF(Map, "Map") +DEF(Set, "Set") /* Map + 1 */ +DEF(WeakMap, "WeakMap") /* Map + 2 */ +DEF(WeakSet, "WeakSet") /* Map + 3 */ +DEF(Iterator, "Iterator") +DEF(IteratorConcat, "Iterator Concat") +DEF(IteratorHelper, "Iterator Helper") +DEF(IteratorWrap, "Iterator Wrap") +DEF(Map_Iterator, "Map Iterator") +DEF(Set_Iterator, "Set Iterator") +DEF(Array_Iterator, "Array Iterator") +DEF(String_Iterator, "String Iterator") +DEF(RegExp_String_Iterator, "RegExp String Iterator") +DEF(Generator, "Generator") +DEF(Proxy, "Proxy") +DEF(Promise, "Promise") +DEF(PromiseResolveFunction, "PromiseResolveFunction") +DEF(PromiseRejectFunction, "PromiseRejectFunction") +DEF(AsyncFunction, "AsyncFunction") +DEF(AsyncFunctionResolve, "AsyncFunctionResolve") +DEF(AsyncFunctionReject, "AsyncFunctionReject") +DEF(AsyncGeneratorFunction, "AsyncGeneratorFunction") +DEF(AsyncGenerator, "AsyncGenerator") +DEF(EvalError, "EvalError") +DEF(RangeError, "RangeError") +DEF(ReferenceError, "ReferenceError") +DEF(SyntaxError, "SyntaxError") +DEF(TypeError, "TypeError") +DEF(URIError, "URIError") +DEF(InternalError, "InternalError") +DEF(DOMException, "DOMException") +DEF(CallSite, "CallSite") +/* private symbols */ +DEF(Private_brand, "") +/* symbols */ +DEF(Symbol_toPrimitive, "Symbol.toPrimitive") +DEF(Symbol_iterator, "Symbol.iterator") +DEF(Symbol_match, "Symbol.match") +DEF(Symbol_matchAll, "Symbol.matchAll") +DEF(Symbol_replace, "Symbol.replace") +DEF(Symbol_search, "Symbol.search") +DEF(Symbol_split, "Symbol.split") +DEF(Symbol_toStringTag, "Symbol.toStringTag") +DEF(Symbol_isConcatSpreadable, "Symbol.isConcatSpreadable") +DEF(Symbol_hasInstance, "Symbol.hasInstance") +DEF(Symbol_species, "Symbol.species") +DEF(Symbol_unscopables, "Symbol.unscopables") +DEF(Symbol_asyncIterator, "Symbol.asyncIterator") + +#endif /* DEF */ + +#undef DEF +; + +typedef enum OPCodeFormat { +#define FMT(f) OP_FMT_ ## f, +#define DEF(id, size, n_pop, n_push, f) +/* + * QuickJS opcode definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef FMT +FMT(none) +FMT(none_int) +FMT(none_loc) +FMT(none_arg) +FMT(none_var_ref) +FMT(u8) +FMT(i8) +FMT(loc8) +FMT(const8) +FMT(label8) +FMT(u16) +FMT(i16) +FMT(label16) +FMT(npop) +FMT(npopx) +FMT(npop_u16) +FMT(loc) +FMT(arg) +FMT(var_ref) +FMT(u32) +FMT(u32x2) +FMT(i32) +FMT(const) +FMT(label) +FMT(atom) +FMT(atom_u8) +FMT(atom_u16) +FMT(atom_label_u8) +FMT(atom_label_u16) +FMT(label_u16) +#undef FMT +#endif /* FMT */ + +#ifdef DEF + +#ifndef def +#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) +#endif + +DEF(invalid, 1, 0, 0, none) /* never emitted */ + +/* push values */ +DEF( push_i32, 5, 0, 1, i32) +DEF( push_const, 5, 0, 1, const) +DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ +DEF(push_atom_value, 5, 0, 1, atom) +DEF( private_symbol, 5, 0, 1, atom) +DEF( undefined, 1, 0, 1, none) +DEF( null, 1, 0, 1, none) +DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ +DEF( push_false, 1, 0, 1, none) +DEF( push_true, 1, 0, 1, none) +DEF( object, 1, 0, 1, none) +DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ +DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ + +DEF( drop, 1, 1, 0, none) /* a -> */ +DEF( nip, 1, 2, 1, none) /* a b -> b */ +DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ +DEF( dup, 1, 1, 2, none) /* a -> a a */ +DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ +DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ +DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ +DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ +DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ +DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ +DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ +DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ +DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ +DEF( swap, 1, 2, 2, none) /* a b -> b a */ +DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ +DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ +DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ +DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ +DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ + +DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ +DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ +DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ +DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ +DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ +DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ +DEF( apply, 3, 3, 1, u16) +DEF( return, 1, 1, 0, none) +DEF( return_undef, 1, 0, 0, none) +DEF(check_ctor_return, 1, 1, 2, none) +DEF( check_ctor, 1, 0, 0, none) +DEF( init_ctor, 1, 0, 1, none) +DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ +DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ +DEF( return_async, 1, 1, 0, none) +DEF( throw, 1, 1, 0, none) +DEF( throw_error, 6, 0, 0, atom_u8) +DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ +DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ +DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a + bytecode string */ +DEF( get_super, 1, 1, 1, none) +DEF( import, 1, 2, 1, none) /* dynamic module import */ + +DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ +DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ +DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ +DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ + +DEF( get_ref_value, 1, 2, 3, none) +DEF( put_ref_value, 1, 3, 0, none) + +DEF( define_var, 6, 0, 0, atom_u8) +DEF(check_define_var, 6, 0, 0, atom_u8) +DEF( define_func, 6, 1, 0, atom_u8) + +// order matters, see IC counterparts +DEF( get_field, 5, 1, 1, atom) +DEF( get_field2, 5, 1, 2, atom) +DEF( put_field, 5, 2, 0, atom) + +DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ +DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ +DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ +DEF( get_array_el, 1, 2, 1, none) +DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ +DEF( put_array_el, 1, 3, 0, none) +DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ +DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ +DEF( define_field, 5, 2, 1, atom) +DEF( set_name, 5, 1, 1, atom) +DEF(set_name_computed, 1, 2, 2, none) +DEF( set_proto, 1, 2, 1, none) +DEF(set_home_object, 1, 2, 2, none) +DEF(define_array_el, 1, 3, 2, none) +DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ +DEF(copy_data_properties, 2, 3, 3, u8) +DEF( define_method, 6, 2, 1, atom_u8) +DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ +DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ +DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ + +DEF( get_loc, 3, 0, 1, loc) +DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ +DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ +DEF( get_arg, 3, 0, 1, arg) +DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ +DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ +DEF( get_var_ref, 3, 0, 1, var_ref) +DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ +DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ +DEF(set_loc_uninitialized, 3, 0, 0, loc) +DEF( get_loc_check, 3, 0, 1, loc) +DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ +DEF( put_loc_check_init, 3, 1, 0, loc) +DEF(get_var_ref_check, 3, 0, 1, var_ref) +DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ +DEF(put_var_ref_check_init, 3, 1, 0, var_ref) +DEF( close_loc, 3, 0, 0, loc) +DEF( if_false, 5, 1, 0, label) +DEF( if_true, 5, 1, 0, label) /* must come after if_false */ +DEF( goto, 5, 0, 0, label) /* must come after if_true */ +DEF( catch, 5, 0, 1, label) +DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ +DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ +DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */ + +DEF( to_object, 1, 1, 1, none) +//DEF( to_string, 1, 1, 1, none) +DEF( to_propkey, 1, 1, 1, none) +DEF( to_propkey2, 1, 2, 2, none) + +DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) + +DEF( make_loc_ref, 7, 0, 2, atom_u16) +DEF( make_arg_ref, 7, 0, 2, atom_u16) +DEF(make_var_ref_ref, 7, 0, 2, atom_u16) +DEF( make_var_ref, 5, 0, 2, atom) + +DEF( for_in_start, 1, 1, 1, none) +DEF( for_of_start, 1, 1, 3, none) +DEF(for_await_of_start, 1, 1, 3, none) +DEF( for_in_next, 1, 1, 3, none) +DEF( for_of_next, 2, 3, 5, u8) +DEF(iterator_check_object, 1, 1, 1, none) +DEF(iterator_get_value_done, 1, 1, 2, none) +DEF( iterator_close, 1, 3, 0, none) +DEF( iterator_next, 1, 4, 4, none) +DEF( iterator_call, 2, 4, 5, u8) +DEF( initial_yield, 1, 0, 0, none) +DEF( yield, 1, 1, 2, none) +DEF( yield_star, 1, 1, 2, none) +DEF(async_yield_star, 1, 1, 2, none) +DEF( await, 1, 1, 1, none) + +/* arithmetic/logic operations */ +DEF( neg, 1, 1, 1, none) +DEF( plus, 1, 1, 1, none) +DEF( dec, 1, 1, 1, none) +DEF( inc, 1, 1, 1, none) +DEF( post_dec, 1, 1, 2, none) +DEF( post_inc, 1, 1, 2, none) +DEF( dec_loc, 2, 0, 0, loc8) +DEF( inc_loc, 2, 0, 0, loc8) +DEF( add_loc, 2, 1, 0, loc8) +DEF( not, 1, 1, 1, none) +DEF( lnot, 1, 1, 1, none) +DEF( typeof, 1, 1, 1, none) +DEF( delete, 1, 2, 1, none) +DEF( delete_var, 5, 0, 1, atom) + +/* warning: order matters (see js_parse_assign_expr) */ +DEF( mul, 1, 2, 1, none) +DEF( div, 1, 2, 1, none) +DEF( mod, 1, 2, 1, none) +DEF( add, 1, 2, 1, none) +DEF( sub, 1, 2, 1, none) +DEF( shl, 1, 2, 1, none) +DEF( sar, 1, 2, 1, none) +DEF( shr, 1, 2, 1, none) +DEF( and, 1, 2, 1, none) +DEF( xor, 1, 2, 1, none) +DEF( or, 1, 2, 1, none) +DEF( pow, 1, 2, 1, none) + +DEF( lt, 1, 2, 1, none) +DEF( lte, 1, 2, 1, none) +DEF( gt, 1, 2, 1, none) +DEF( gte, 1, 2, 1, none) +DEF( instanceof, 1, 2, 1, none) +DEF( in, 1, 2, 1, none) +DEF( eq, 1, 2, 1, none) +DEF( neq, 1, 2, 1, none) +DEF( strict_eq, 1, 2, 1, none) +DEF( strict_neq, 1, 2, 1, none) +DEF(is_undefined_or_null, 1, 1, 1, none) +DEF( private_in, 1, 2, 1, none) +DEF(push_bigint_i32, 5, 0, 1, i32) +/* must be the last non short and non temporary opcode */ +DEF( nop, 1, 0, 0, none) + +/* temporary opcodes: never emitted in the final bytecode */ + +def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ +def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ + +def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ + +def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ +def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ +def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */ +def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */ +def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */ +def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ + +def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */ + +DEF( push_minus1, 1, 0, 1, none_int) +DEF( push_0, 1, 0, 1, none_int) +DEF( push_1, 1, 0, 1, none_int) +DEF( push_2, 1, 0, 1, none_int) +DEF( push_3, 1, 0, 1, none_int) +DEF( push_4, 1, 0, 1, none_int) +DEF( push_5, 1, 0, 1, none_int) +DEF( push_6, 1, 0, 1, none_int) +DEF( push_7, 1, 0, 1, none_int) +DEF( push_i8, 2, 0, 1, i8) +DEF( push_i16, 3, 0, 1, i16) +DEF( push_const8, 2, 0, 1, const8) +DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ +DEF(push_empty_string, 1, 0, 1, none) + +DEF( get_loc8, 2, 0, 1, loc8) +DEF( put_loc8, 2, 1, 0, loc8) +DEF( set_loc8, 2, 1, 1, loc8) + +DEF( get_loc0_loc1, 1, 0, 2, none_loc) +DEF( get_loc0, 1, 0, 1, none_loc) +DEF( get_loc1, 1, 0, 1, none_loc) +DEF( get_loc2, 1, 0, 1, none_loc) +DEF( get_loc3, 1, 0, 1, none_loc) +DEF( put_loc0, 1, 1, 0, none_loc) +DEF( put_loc1, 1, 1, 0, none_loc) +DEF( put_loc2, 1, 1, 0, none_loc) +DEF( put_loc3, 1, 1, 0, none_loc) +DEF( set_loc0, 1, 1, 1, none_loc) +DEF( set_loc1, 1, 1, 1, none_loc) +DEF( set_loc2, 1, 1, 1, none_loc) +DEF( set_loc3, 1, 1, 1, none_loc) +DEF( get_arg0, 1, 0, 1, none_arg) +DEF( get_arg1, 1, 0, 1, none_arg) +DEF( get_arg2, 1, 0, 1, none_arg) +DEF( get_arg3, 1, 0, 1, none_arg) +DEF( put_arg0, 1, 1, 0, none_arg) +DEF( put_arg1, 1, 1, 0, none_arg) +DEF( put_arg2, 1, 1, 0, none_arg) +DEF( put_arg3, 1, 1, 0, none_arg) +DEF( set_arg0, 1, 1, 1, none_arg) +DEF( set_arg1, 1, 1, 1, none_arg) +DEF( set_arg2, 1, 1, 1, none_arg) +DEF( set_arg3, 1, 1, 1, none_arg) +DEF( get_var_ref0, 1, 0, 1, none_var_ref) +DEF( get_var_ref1, 1, 0, 1, none_var_ref) +DEF( get_var_ref2, 1, 0, 1, none_var_ref) +DEF( get_var_ref3, 1, 0, 1, none_var_ref) +DEF( put_var_ref0, 1, 1, 0, none_var_ref) +DEF( put_var_ref1, 1, 1, 0, none_var_ref) +DEF( put_var_ref2, 1, 1, 0, none_var_ref) +DEF( put_var_ref3, 1, 1, 0, none_var_ref) +DEF( set_var_ref0, 1, 1, 1, none_var_ref) +DEF( set_var_ref1, 1, 1, 1, none_var_ref) +DEF( set_var_ref2, 1, 1, 1, none_var_ref) +DEF( set_var_ref3, 1, 1, 1, none_var_ref) + +DEF( get_length, 1, 1, 1, none) + +DEF( if_false8, 2, 1, 0, label8) +DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ +DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ +DEF( goto16, 3, 0, 0, label16) + +DEF( call0, 1, 1, 1, npopx) +DEF( call1, 1, 1, 1, npopx) +DEF( call2, 1, 1, 1, npopx) +DEF( call3, 1, 1, 1, npopx) + +DEF( is_undefined, 1, 1, 1, none) +DEF( is_null, 1, 1, 1, none) +DEF(typeof_is_undefined, 1, 1, 1, none) +DEF( typeof_is_function, 1, 1, 1, none) + +#undef DEF +#undef def +#endif /* DEF */ + +#undef DEF +#undef FMT +} OPCodeFormat; + +typedef enum OPCodeEnum { +#define FMT(f) +#define DEF(id, size, n_pop, n_push, f) OP_ ## id, +#define def(id, size, n_pop, n_push, f) +/* + * QuickJS opcode definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef FMT +FMT(none) +FMT(none_int) +FMT(none_loc) +FMT(none_arg) +FMT(none_var_ref) +FMT(u8) +FMT(i8) +FMT(loc8) +FMT(const8) +FMT(label8) +FMT(u16) +FMT(i16) +FMT(label16) +FMT(npop) +FMT(npopx) +FMT(npop_u16) +FMT(loc) +FMT(arg) +FMT(var_ref) +FMT(u32) +FMT(u32x2) +FMT(i32) +FMT(const) +FMT(label) +FMT(atom) +FMT(atom_u8) +FMT(atom_u16) +FMT(atom_label_u8) +FMT(atom_label_u16) +FMT(label_u16) +#undef FMT +#endif /* FMT */ + +#ifdef DEF + +#ifndef def +#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) +#endif + +DEF(invalid, 1, 0, 0, none) /* never emitted */ + +/* push values */ +DEF( push_i32, 5, 0, 1, i32) +DEF( push_const, 5, 0, 1, const) +DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ +DEF(push_atom_value, 5, 0, 1, atom) +DEF( private_symbol, 5, 0, 1, atom) +DEF( undefined, 1, 0, 1, none) +DEF( null, 1, 0, 1, none) +DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ +DEF( push_false, 1, 0, 1, none) +DEF( push_true, 1, 0, 1, none) +DEF( object, 1, 0, 1, none) +DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ +DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ + +DEF( drop, 1, 1, 0, none) /* a -> */ +DEF( nip, 1, 2, 1, none) /* a b -> b */ +DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ +DEF( dup, 1, 1, 2, none) /* a -> a a */ +DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ +DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ +DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ +DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ +DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ +DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ +DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ +DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ +DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ +DEF( swap, 1, 2, 2, none) /* a b -> b a */ +DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ +DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ +DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ +DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ +DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ + +DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ +DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ +DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ +DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ +DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ +DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ +DEF( apply, 3, 3, 1, u16) +DEF( return, 1, 1, 0, none) +DEF( return_undef, 1, 0, 0, none) +DEF(check_ctor_return, 1, 1, 2, none) +DEF( check_ctor, 1, 0, 0, none) +DEF( init_ctor, 1, 0, 1, none) +DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ +DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ +DEF( return_async, 1, 1, 0, none) +DEF( throw, 1, 1, 0, none) +DEF( throw_error, 6, 0, 0, atom_u8) +DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ +DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ +DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a + bytecode string */ +DEF( get_super, 1, 1, 1, none) +DEF( import, 1, 2, 1, none) /* dynamic module import */ + +DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ +DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ +DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ +DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ + +DEF( get_ref_value, 1, 2, 3, none) +DEF( put_ref_value, 1, 3, 0, none) + +DEF( define_var, 6, 0, 0, atom_u8) +DEF(check_define_var, 6, 0, 0, atom_u8) +DEF( define_func, 6, 1, 0, atom_u8) + +// order matters, see IC counterparts +DEF( get_field, 5, 1, 1, atom) +DEF( get_field2, 5, 1, 2, atom) +DEF( put_field, 5, 2, 0, atom) + +DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ +DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ +DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ +DEF( get_array_el, 1, 2, 1, none) +DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ +DEF( put_array_el, 1, 3, 0, none) +DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ +DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ +DEF( define_field, 5, 2, 1, atom) +DEF( set_name, 5, 1, 1, atom) +DEF(set_name_computed, 1, 2, 2, none) +DEF( set_proto, 1, 2, 1, none) +DEF(set_home_object, 1, 2, 2, none) +DEF(define_array_el, 1, 3, 2, none) +DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ +DEF(copy_data_properties, 2, 3, 3, u8) +DEF( define_method, 6, 2, 1, atom_u8) +DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ +DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ +DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ + +DEF( get_loc, 3, 0, 1, loc) +DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ +DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ +DEF( get_arg, 3, 0, 1, arg) +DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ +DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ +DEF( get_var_ref, 3, 0, 1, var_ref) +DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ +DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ +DEF(set_loc_uninitialized, 3, 0, 0, loc) +DEF( get_loc_check, 3, 0, 1, loc) +DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ +DEF( put_loc_check_init, 3, 1, 0, loc) +DEF(get_var_ref_check, 3, 0, 1, var_ref) +DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ +DEF(put_var_ref_check_init, 3, 1, 0, var_ref) +DEF( close_loc, 3, 0, 0, loc) +DEF( if_false, 5, 1, 0, label) +DEF( if_true, 5, 1, 0, label) /* must come after if_false */ +DEF( goto, 5, 0, 0, label) /* must come after if_true */ +DEF( catch, 5, 0, 1, label) +DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ +DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ +DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */ + +DEF( to_object, 1, 1, 1, none) +//DEF( to_string, 1, 1, 1, none) +DEF( to_propkey, 1, 1, 1, none) +DEF( to_propkey2, 1, 2, 2, none) + +DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) + +DEF( make_loc_ref, 7, 0, 2, atom_u16) +DEF( make_arg_ref, 7, 0, 2, atom_u16) +DEF(make_var_ref_ref, 7, 0, 2, atom_u16) +DEF( make_var_ref, 5, 0, 2, atom) + +DEF( for_in_start, 1, 1, 1, none) +DEF( for_of_start, 1, 1, 3, none) +DEF(for_await_of_start, 1, 1, 3, none) +DEF( for_in_next, 1, 1, 3, none) +DEF( for_of_next, 2, 3, 5, u8) +DEF(iterator_check_object, 1, 1, 1, none) +DEF(iterator_get_value_done, 1, 1, 2, none) +DEF( iterator_close, 1, 3, 0, none) +DEF( iterator_next, 1, 4, 4, none) +DEF( iterator_call, 2, 4, 5, u8) +DEF( initial_yield, 1, 0, 0, none) +DEF( yield, 1, 1, 2, none) +DEF( yield_star, 1, 1, 2, none) +DEF(async_yield_star, 1, 1, 2, none) +DEF( await, 1, 1, 1, none) + +/* arithmetic/logic operations */ +DEF( neg, 1, 1, 1, none) +DEF( plus, 1, 1, 1, none) +DEF( dec, 1, 1, 1, none) +DEF( inc, 1, 1, 1, none) +DEF( post_dec, 1, 1, 2, none) +DEF( post_inc, 1, 1, 2, none) +DEF( dec_loc, 2, 0, 0, loc8) +DEF( inc_loc, 2, 0, 0, loc8) +DEF( add_loc, 2, 1, 0, loc8) +DEF( not, 1, 1, 1, none) +DEF( lnot, 1, 1, 1, none) +DEF( typeof, 1, 1, 1, none) +DEF( delete, 1, 2, 1, none) +DEF( delete_var, 5, 0, 1, atom) + +/* warning: order matters (see js_parse_assign_expr) */ +DEF( mul, 1, 2, 1, none) +DEF( div, 1, 2, 1, none) +DEF( mod, 1, 2, 1, none) +DEF( add, 1, 2, 1, none) +DEF( sub, 1, 2, 1, none) +DEF( shl, 1, 2, 1, none) +DEF( sar, 1, 2, 1, none) +DEF( shr, 1, 2, 1, none) +DEF( and, 1, 2, 1, none) +DEF( xor, 1, 2, 1, none) +DEF( or, 1, 2, 1, none) +DEF( pow, 1, 2, 1, none) + +DEF( lt, 1, 2, 1, none) +DEF( lte, 1, 2, 1, none) +DEF( gt, 1, 2, 1, none) +DEF( gte, 1, 2, 1, none) +DEF( instanceof, 1, 2, 1, none) +DEF( in, 1, 2, 1, none) +DEF( eq, 1, 2, 1, none) +DEF( neq, 1, 2, 1, none) +DEF( strict_eq, 1, 2, 1, none) +DEF( strict_neq, 1, 2, 1, none) +DEF(is_undefined_or_null, 1, 1, 1, none) +DEF( private_in, 1, 2, 1, none) +DEF(push_bigint_i32, 5, 0, 1, i32) +/* must be the last non short and non temporary opcode */ +DEF( nop, 1, 0, 0, none) + +/* temporary opcodes: never emitted in the final bytecode */ + +def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ +def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ + +def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ + +def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ +def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ +def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */ +def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */ +def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */ +def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ + +def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */ + +DEF( push_minus1, 1, 0, 1, none_int) +DEF( push_0, 1, 0, 1, none_int) +DEF( push_1, 1, 0, 1, none_int) +DEF( push_2, 1, 0, 1, none_int) +DEF( push_3, 1, 0, 1, none_int) +DEF( push_4, 1, 0, 1, none_int) +DEF( push_5, 1, 0, 1, none_int) +DEF( push_6, 1, 0, 1, none_int) +DEF( push_7, 1, 0, 1, none_int) +DEF( push_i8, 2, 0, 1, i8) +DEF( push_i16, 3, 0, 1, i16) +DEF( push_const8, 2, 0, 1, const8) +DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ +DEF(push_empty_string, 1, 0, 1, none) + +DEF( get_loc8, 2, 0, 1, loc8) +DEF( put_loc8, 2, 1, 0, loc8) +DEF( set_loc8, 2, 1, 1, loc8) + +DEF( get_loc0_loc1, 1, 0, 2, none_loc) +DEF( get_loc0, 1, 0, 1, none_loc) +DEF( get_loc1, 1, 0, 1, none_loc) +DEF( get_loc2, 1, 0, 1, none_loc) +DEF( get_loc3, 1, 0, 1, none_loc) +DEF( put_loc0, 1, 1, 0, none_loc) +DEF( put_loc1, 1, 1, 0, none_loc) +DEF( put_loc2, 1, 1, 0, none_loc) +DEF( put_loc3, 1, 1, 0, none_loc) +DEF( set_loc0, 1, 1, 1, none_loc) +DEF( set_loc1, 1, 1, 1, none_loc) +DEF( set_loc2, 1, 1, 1, none_loc) +DEF( set_loc3, 1, 1, 1, none_loc) +DEF( get_arg0, 1, 0, 1, none_arg) +DEF( get_arg1, 1, 0, 1, none_arg) +DEF( get_arg2, 1, 0, 1, none_arg) +DEF( get_arg3, 1, 0, 1, none_arg) +DEF( put_arg0, 1, 1, 0, none_arg) +DEF( put_arg1, 1, 1, 0, none_arg) +DEF( put_arg2, 1, 1, 0, none_arg) +DEF( put_arg3, 1, 1, 0, none_arg) +DEF( set_arg0, 1, 1, 1, none_arg) +DEF( set_arg1, 1, 1, 1, none_arg) +DEF( set_arg2, 1, 1, 1, none_arg) +DEF( set_arg3, 1, 1, 1, none_arg) +DEF( get_var_ref0, 1, 0, 1, none_var_ref) +DEF( get_var_ref1, 1, 0, 1, none_var_ref) +DEF( get_var_ref2, 1, 0, 1, none_var_ref) +DEF( get_var_ref3, 1, 0, 1, none_var_ref) +DEF( put_var_ref0, 1, 1, 0, none_var_ref) +DEF( put_var_ref1, 1, 1, 0, none_var_ref) +DEF( put_var_ref2, 1, 1, 0, none_var_ref) +DEF( put_var_ref3, 1, 1, 0, none_var_ref) +DEF( set_var_ref0, 1, 1, 1, none_var_ref) +DEF( set_var_ref1, 1, 1, 1, none_var_ref) +DEF( set_var_ref2, 1, 1, 1, none_var_ref) +DEF( set_var_ref3, 1, 1, 1, none_var_ref) + +DEF( get_length, 1, 1, 1, none) + +DEF( if_false8, 2, 1, 0, label8) +DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ +DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ +DEF( goto16, 3, 0, 0, label16) + +DEF( call0, 1, 1, 1, npopx) +DEF( call1, 1, 1, 1, npopx) +DEF( call2, 1, 1, 1, npopx) +DEF( call3, 1, 1, 1, npopx) + +DEF( is_undefined, 1, 1, 1, none) +DEF( is_null, 1, 1, 1, none) +DEF(typeof_is_undefined, 1, 1, 1, none) +DEF( typeof_is_function, 1, 1, 1, none) + +#undef DEF +#undef def +#endif /* DEF */ + +#undef def +#undef DEF +#undef FMT + OP_COUNT, /* excluding temporary opcodes */ + /* temporary opcodes : overlap with the short opcodes */ + OP_TEMP_START = OP_nop + 1, + OP___dummy = OP_TEMP_START - 1, +#define FMT(f) +#define DEF(id, size, n_pop, n_push, f) +#define def(id, size, n_pop, n_push, f) OP_ ## id, +/* + * QuickJS opcode definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef FMT +FMT(none) +FMT(none_int) +FMT(none_loc) +FMT(none_arg) +FMT(none_var_ref) +FMT(u8) +FMT(i8) +FMT(loc8) +FMT(const8) +FMT(label8) +FMT(u16) +FMT(i16) +FMT(label16) +FMT(npop) +FMT(npopx) +FMT(npop_u16) +FMT(loc) +FMT(arg) +FMT(var_ref) +FMT(u32) +FMT(u32x2) +FMT(i32) +FMT(const) +FMT(label) +FMT(atom) +FMT(atom_u8) +FMT(atom_u16) +FMT(atom_label_u8) +FMT(atom_label_u16) +FMT(label_u16) +#undef FMT +#endif /* FMT */ + +#ifdef DEF + +#ifndef def +#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) +#endif + +DEF(invalid, 1, 0, 0, none) /* never emitted */ + +/* push values */ +DEF( push_i32, 5, 0, 1, i32) +DEF( push_const, 5, 0, 1, const) +DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ +DEF(push_atom_value, 5, 0, 1, atom) +DEF( private_symbol, 5, 0, 1, atom) +DEF( undefined, 1, 0, 1, none) +DEF( null, 1, 0, 1, none) +DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ +DEF( push_false, 1, 0, 1, none) +DEF( push_true, 1, 0, 1, none) +DEF( object, 1, 0, 1, none) +DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ +DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ + +DEF( drop, 1, 1, 0, none) /* a -> */ +DEF( nip, 1, 2, 1, none) /* a b -> b */ +DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ +DEF( dup, 1, 1, 2, none) /* a -> a a */ +DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ +DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ +DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ +DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ +DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ +DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ +DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ +DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ +DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ +DEF( swap, 1, 2, 2, none) /* a b -> b a */ +DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ +DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ +DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ +DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ +DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ + +DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ +DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ +DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ +DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ +DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ +DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ +DEF( apply, 3, 3, 1, u16) +DEF( return, 1, 1, 0, none) +DEF( return_undef, 1, 0, 0, none) +DEF(check_ctor_return, 1, 1, 2, none) +DEF( check_ctor, 1, 0, 0, none) +DEF( init_ctor, 1, 0, 1, none) +DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ +DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ +DEF( return_async, 1, 1, 0, none) +DEF( throw, 1, 1, 0, none) +DEF( throw_error, 6, 0, 0, atom_u8) +DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ +DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ +DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a + bytecode string */ +DEF( get_super, 1, 1, 1, none) +DEF( import, 1, 2, 1, none) /* dynamic module import */ + +DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ +DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ +DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ +DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ + +DEF( get_ref_value, 1, 2, 3, none) +DEF( put_ref_value, 1, 3, 0, none) + +DEF( define_var, 6, 0, 0, atom_u8) +DEF(check_define_var, 6, 0, 0, atom_u8) +DEF( define_func, 6, 1, 0, atom_u8) + +// order matters, see IC counterparts +DEF( get_field, 5, 1, 1, atom) +DEF( get_field2, 5, 1, 2, atom) +DEF( put_field, 5, 2, 0, atom) + +DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ +DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ +DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ +DEF( get_array_el, 1, 2, 1, none) +DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ +DEF( put_array_el, 1, 3, 0, none) +DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ +DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ +DEF( define_field, 5, 2, 1, atom) +DEF( set_name, 5, 1, 1, atom) +DEF(set_name_computed, 1, 2, 2, none) +DEF( set_proto, 1, 2, 1, none) +DEF(set_home_object, 1, 2, 2, none) +DEF(define_array_el, 1, 3, 2, none) +DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ +DEF(copy_data_properties, 2, 3, 3, u8) +DEF( define_method, 6, 2, 1, atom_u8) +DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ +DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ +DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ + +DEF( get_loc, 3, 0, 1, loc) +DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ +DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ +DEF( get_arg, 3, 0, 1, arg) +DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ +DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ +DEF( get_var_ref, 3, 0, 1, var_ref) +DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ +DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ +DEF(set_loc_uninitialized, 3, 0, 0, loc) +DEF( get_loc_check, 3, 0, 1, loc) +DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ +DEF( put_loc_check_init, 3, 1, 0, loc) +DEF(get_var_ref_check, 3, 0, 1, var_ref) +DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ +DEF(put_var_ref_check_init, 3, 1, 0, var_ref) +DEF( close_loc, 3, 0, 0, loc) +DEF( if_false, 5, 1, 0, label) +DEF( if_true, 5, 1, 0, label) /* must come after if_false */ +DEF( goto, 5, 0, 0, label) /* must come after if_true */ +DEF( catch, 5, 0, 1, label) +DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ +DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ +DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */ + +DEF( to_object, 1, 1, 1, none) +//DEF( to_string, 1, 1, 1, none) +DEF( to_propkey, 1, 1, 1, none) +DEF( to_propkey2, 1, 2, 2, none) + +DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) + +DEF( make_loc_ref, 7, 0, 2, atom_u16) +DEF( make_arg_ref, 7, 0, 2, atom_u16) +DEF(make_var_ref_ref, 7, 0, 2, atom_u16) +DEF( make_var_ref, 5, 0, 2, atom) + +DEF( for_in_start, 1, 1, 1, none) +DEF( for_of_start, 1, 1, 3, none) +DEF(for_await_of_start, 1, 1, 3, none) +DEF( for_in_next, 1, 1, 3, none) +DEF( for_of_next, 2, 3, 5, u8) +DEF(iterator_check_object, 1, 1, 1, none) +DEF(iterator_get_value_done, 1, 1, 2, none) +DEF( iterator_close, 1, 3, 0, none) +DEF( iterator_next, 1, 4, 4, none) +DEF( iterator_call, 2, 4, 5, u8) +DEF( initial_yield, 1, 0, 0, none) +DEF( yield, 1, 1, 2, none) +DEF( yield_star, 1, 1, 2, none) +DEF(async_yield_star, 1, 1, 2, none) +DEF( await, 1, 1, 1, none) + +/* arithmetic/logic operations */ +DEF( neg, 1, 1, 1, none) +DEF( plus, 1, 1, 1, none) +DEF( dec, 1, 1, 1, none) +DEF( inc, 1, 1, 1, none) +DEF( post_dec, 1, 1, 2, none) +DEF( post_inc, 1, 1, 2, none) +DEF( dec_loc, 2, 0, 0, loc8) +DEF( inc_loc, 2, 0, 0, loc8) +DEF( add_loc, 2, 1, 0, loc8) +DEF( not, 1, 1, 1, none) +DEF( lnot, 1, 1, 1, none) +DEF( typeof, 1, 1, 1, none) +DEF( delete, 1, 2, 1, none) +DEF( delete_var, 5, 0, 1, atom) + +/* warning: order matters (see js_parse_assign_expr) */ +DEF( mul, 1, 2, 1, none) +DEF( div, 1, 2, 1, none) +DEF( mod, 1, 2, 1, none) +DEF( add, 1, 2, 1, none) +DEF( sub, 1, 2, 1, none) +DEF( shl, 1, 2, 1, none) +DEF( sar, 1, 2, 1, none) +DEF( shr, 1, 2, 1, none) +DEF( and, 1, 2, 1, none) +DEF( xor, 1, 2, 1, none) +DEF( or, 1, 2, 1, none) +DEF( pow, 1, 2, 1, none) + +DEF( lt, 1, 2, 1, none) +DEF( lte, 1, 2, 1, none) +DEF( gt, 1, 2, 1, none) +DEF( gte, 1, 2, 1, none) +DEF( instanceof, 1, 2, 1, none) +DEF( in, 1, 2, 1, none) +DEF( eq, 1, 2, 1, none) +DEF( neq, 1, 2, 1, none) +DEF( strict_eq, 1, 2, 1, none) +DEF( strict_neq, 1, 2, 1, none) +DEF(is_undefined_or_null, 1, 1, 1, none) +DEF( private_in, 1, 2, 1, none) +DEF(push_bigint_i32, 5, 0, 1, i32) +/* must be the last non short and non temporary opcode */ +DEF( nop, 1, 0, 0, none) + +/* temporary opcodes: never emitted in the final bytecode */ + +def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ +def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ + +def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ + +def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ +def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ +def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */ +def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */ +def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */ +def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ + +def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */ + +DEF( push_minus1, 1, 0, 1, none_int) +DEF( push_0, 1, 0, 1, none_int) +DEF( push_1, 1, 0, 1, none_int) +DEF( push_2, 1, 0, 1, none_int) +DEF( push_3, 1, 0, 1, none_int) +DEF( push_4, 1, 0, 1, none_int) +DEF( push_5, 1, 0, 1, none_int) +DEF( push_6, 1, 0, 1, none_int) +DEF( push_7, 1, 0, 1, none_int) +DEF( push_i8, 2, 0, 1, i8) +DEF( push_i16, 3, 0, 1, i16) +DEF( push_const8, 2, 0, 1, const8) +DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ +DEF(push_empty_string, 1, 0, 1, none) + +DEF( get_loc8, 2, 0, 1, loc8) +DEF( put_loc8, 2, 1, 0, loc8) +DEF( set_loc8, 2, 1, 1, loc8) + +DEF( get_loc0_loc1, 1, 0, 2, none_loc) +DEF( get_loc0, 1, 0, 1, none_loc) +DEF( get_loc1, 1, 0, 1, none_loc) +DEF( get_loc2, 1, 0, 1, none_loc) +DEF( get_loc3, 1, 0, 1, none_loc) +DEF( put_loc0, 1, 1, 0, none_loc) +DEF( put_loc1, 1, 1, 0, none_loc) +DEF( put_loc2, 1, 1, 0, none_loc) +DEF( put_loc3, 1, 1, 0, none_loc) +DEF( set_loc0, 1, 1, 1, none_loc) +DEF( set_loc1, 1, 1, 1, none_loc) +DEF( set_loc2, 1, 1, 1, none_loc) +DEF( set_loc3, 1, 1, 1, none_loc) +DEF( get_arg0, 1, 0, 1, none_arg) +DEF( get_arg1, 1, 0, 1, none_arg) +DEF( get_arg2, 1, 0, 1, none_arg) +DEF( get_arg3, 1, 0, 1, none_arg) +DEF( put_arg0, 1, 1, 0, none_arg) +DEF( put_arg1, 1, 1, 0, none_arg) +DEF( put_arg2, 1, 1, 0, none_arg) +DEF( put_arg3, 1, 1, 0, none_arg) +DEF( set_arg0, 1, 1, 1, none_arg) +DEF( set_arg1, 1, 1, 1, none_arg) +DEF( set_arg2, 1, 1, 1, none_arg) +DEF( set_arg3, 1, 1, 1, none_arg) +DEF( get_var_ref0, 1, 0, 1, none_var_ref) +DEF( get_var_ref1, 1, 0, 1, none_var_ref) +DEF( get_var_ref2, 1, 0, 1, none_var_ref) +DEF( get_var_ref3, 1, 0, 1, none_var_ref) +DEF( put_var_ref0, 1, 1, 0, none_var_ref) +DEF( put_var_ref1, 1, 1, 0, none_var_ref) +DEF( put_var_ref2, 1, 1, 0, none_var_ref) +DEF( put_var_ref3, 1, 1, 0, none_var_ref) +DEF( set_var_ref0, 1, 1, 1, none_var_ref) +DEF( set_var_ref1, 1, 1, 1, none_var_ref) +DEF( set_var_ref2, 1, 1, 1, none_var_ref) +DEF( set_var_ref3, 1, 1, 1, none_var_ref) + +DEF( get_length, 1, 1, 1, none) + +DEF( if_false8, 2, 1, 0, label8) +DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ +DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ +DEF( goto16, 3, 0, 0, label16) + +DEF( call0, 1, 1, 1, npopx) +DEF( call1, 1, 1, 1, npopx) +DEF( call2, 1, 1, 1, npopx) +DEF( call3, 1, 1, 1, npopx) + +DEF( is_undefined, 1, 1, 1, none) +DEF( is_null, 1, 1, 1, none) +DEF(typeof_is_undefined, 1, 1, 1, none) +DEF( typeof_is_function, 1, 1, 1, none) + +#undef DEF +#undef def +#endif /* DEF */ + +#undef def +#undef DEF +#undef FMT + OP_TEMP_END, +} OPCodeEnum; + +static int JS_InitAtoms(JSRuntime *rt); +static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len, + int atom_type); +static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p); +static void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b); +static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, int flags); +static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, int flags); +static JSValue JS_CallInternal(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, JSValueConst new_target, + int argc, JSValueConst *argv, int flags); +static JSValue JS_CallConstructorInternal(JSContext *ctx, + JSValueConst func_obj, + JSValueConst new_target, + int argc, JSValueConst *argv, int flags); +static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj, + int argc, JSValueConst *argv); +static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom, + int argc, JSValueConst *argv); +static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen, + JSValue val, bool is_array_ctor); +static JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj, + JSValueConst val, int flags, int scope_idx); +static __maybe_unused void JS_DumpString(JSRuntime *rt, JSString *p); +static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt); +static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p); +static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p); +static __maybe_unused void JS_DumpValue(JSRuntime *rt, JSValueConst val); +static __maybe_unused void JS_DumpAtoms(JSRuntime *rt); +static __maybe_unused void JS_DumpShapes(JSRuntime *rt); + +static JSValue js_function_apply(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int magic); +static void js_array_finalizer(JSRuntime *rt, JSValueConst val); +static void js_array_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_mapped_arguments_finalizer(JSRuntime *rt, JSValueConst val); +static void js_mapped_arguments_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_object_data_finalizer(JSRuntime *rt, JSValueConst val); +static void js_object_data_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_c_function_finalizer(JSRuntime *rt, JSValueConst val); +static void js_c_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_bytecode_function_finalizer(JSRuntime *rt, JSValueConst val); +static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_bound_function_finalizer(JSRuntime *rt, JSValueConst val); +static void js_bound_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValueConst val); +static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_regexp_finalizer(JSRuntime *rt, JSValueConst val); +static void js_array_buffer_finalizer(JSRuntime *rt, JSValueConst val); +static void js_typed_array_finalizer(JSRuntime *rt, JSValueConst val); +static void js_typed_array_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_proxy_finalizer(JSRuntime *rt, JSValueConst val); +static void js_proxy_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_map_finalizer(JSRuntime *rt, JSValueConst val); +static void js_map_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_map_iterator_finalizer(JSRuntime *rt, JSValueConst val); +static void js_map_iterator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_array_iterator_finalizer(JSRuntime *rt, JSValueConst val); +static void js_array_iterator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_iterator_concat_finalizer(JSRuntime *rt, JSValueConst val); +static void js_iterator_concat_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_iterator_helper_finalizer(JSRuntime *rt, JSValueConst val); +static void js_iterator_helper_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_iterator_wrap_finalizer(JSRuntime *rt, JSValueConst val); +static void js_iterator_wrap_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_regexp_string_iterator_finalizer(JSRuntime *rt, + JSValueConst val); +static void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_generator_finalizer(JSRuntime *rt, JSValueConst val); +static void js_generator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_promise_finalizer(JSRuntime *rt, JSValueConst val); +static void js_promise_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValueConst val); +static void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); + +#define HINT_STRING 0 +#define HINT_NUMBER 1 +#define HINT_NONE 2 +#define HINT_FORCE_ORDINARY (1 << 4) // don't try Symbol.toPrimitive +static JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint); +static JSValue JS_ToStringFree(JSContext *ctx, JSValue val); +static int JS_ToBoolFree(JSContext *ctx, JSValue val); +static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val); +static int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val); +static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val); +static JSValue JS_ToPropertyKeyInternal(JSContext *ctx, JSValueConst val, + int flags); +static JSValue js_new_string8_len(JSContext *ctx, const char *buf, int len); +static JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern, + JSValueConst flags); +static JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor, + JSValue pattern, JSValue bc); +static void gc_decref(JSRuntime *rt); +static int JS_NewClass1(JSRuntime *rt, JSClassID class_id, + const JSClassDef *class_def, JSAtom name); +static JSValue js_array_push(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int unshift); +static JSValue js_array_constructor(JSContext *ctx, JSValueConst new_target, + int argc, JSValueConst *argv); +static JSValue js_error_constructor(JSContext *ctx, JSValueConst new_target, + int argc, JSValueConst *argv, int magic); +static JSValue js_object_defineProperty(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int magic); + +typedef enum JSStrictEqModeEnum { + JS_EQ_STRICT, + JS_EQ_SAME_VALUE, + JS_EQ_SAME_VALUE_ZERO, +} JSStrictEqModeEnum; + +static bool js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2, + JSStrictEqModeEnum eq_mode); +static bool js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2); +static bool js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2); +static bool js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2); +static JSValue JS_ToObjectFree(JSContext *ctx, JSValue val); +static JSProperty *add_property(JSContext *ctx, + JSObject *p, JSAtom prop, int prop_flags); +static void free_property(JSRuntime *rt, JSProperty *pr, int prop_flags); +static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val); +static JSValue JS_ThrowStackOverflow(JSContext *ctx); +static JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx); +static JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj); +static int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj, + JSValueConst proto_val, bool throw_flag); +static int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj); +static int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj); +static int js_proxy_isArray(JSContext *ctx, JSValueConst obj); +static int JS_CreateProperty(JSContext *ctx, JSObject *p, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, + int flags); +static int js_string_memcmp(JSString *p1, JSString *p2, int len); +static void reset_weak_ref(JSRuntime *rt, JSWeakRefRecord **first_weak_ref); +static bool is_valid_weakref_target(JSValueConst val); +static void insert_weakref_record(JSValueConst target, + struct JSWeakRefRecord *wr); +static JSValue js_array_buffer_constructor3(JSContext *ctx, + JSValueConst new_target, + uint64_t len, uint64_t *max_len, + JSClassID class_id, + uint8_t *buf, + JSFreeArrayBufferDataFunc *free_func, + void *opaque, bool alloc_flag); +static void js_array_buffer_free(JSRuntime *rt, void *opaque, void *ptr); +static JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj); +static bool array_buffer_is_resizable(const JSArrayBuffer *abuf); +static JSValue js_typed_array_constructor(JSContext *ctx, + JSValueConst this_val, + int argc, JSValueConst *argv, + int classid); +static JSValue js_typed_array_constructor_ta(JSContext *ctx, + JSValueConst new_target, + JSValueConst src_obj, + int classid, uint32_t len); +static bool is_typed_array(JSClassID class_id); +static bool typed_array_is_immutable(JSObject *p); +static bool typed_array_is_oob(JSObject *p); +static uint32_t typed_array_length(JSObject *p); +static JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx); +static JSValue JS_ThrowTypeErrorImmutableArrayBuffer(JSContext *ctx); +static JSValue JS_ThrowTypeErrorArrayBufferOOB(JSContext *ctx); +static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx, + bool is_arg); +static JSVarRef *js_create_var_ref(JSContext *ctx, bool is_gc_object); +static JSValue js_call_generator_function(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, + int flags); +static void js_async_function_resolve_finalizer(JSRuntime *rt, + JSValueConst val); +static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj, + const char *input, size_t input_len, + const char *filename, int line, int flags, int scope_idx); +static void js_free_module_def(JSContext *ctx, JSModuleDef *m); +static void js_mark_module_def(JSRuntime *rt, JSModuleDef *m, + JS_MarkFunc *mark_func); +static JSValue js_import_meta(JSContext *ctx); +static JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier, + JSValueConst options); +static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref); +static JSValue js_new_promise_capability(JSContext *ctx, + JSValue *resolving_funcs, + JSValueConst ctor); +static __exception int perform_promise_then(JSContext *ctx, + JSValueConst promise, + JSValueConst *resolve_reject, + JSValueConst *cap_resolving_funcs); +static JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int magic); +static JSValue js_promise_then(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv); +static JSValue js_promise_resolve_thenable_job(JSContext *ctx, + int argc, JSValueConst *argv); +static bool js_string_eq(JSString *p1, JSString *p2); +static int js_string_compare(JSString *p1, JSString *p2); +static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj, + JSValue prop, JSValue val, int flags); +static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val); +static bool JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val); +static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val); +static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc, + JSObject *p, JSAtom prop); +static JSValue JS_GetOwnPropertyNames2(JSContext *ctx, JSValueConst obj1, + int flags, int kind); +static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc); +static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s, + JS_MarkFunc *mark_func); +static void JS_AddIntrinsicBasicObjects(JSContext *ctx); +static void js_free_shape(JSRuntime *rt, JSShape *sh); +static void js_free_shape_null(JSRuntime *rt, JSShape *sh); +static int js_shape_prepare_update(JSContext *ctx, JSObject *p, + JSShapeProperty **pprs); +static int init_shape_hash(JSRuntime *rt); +static __exception int js_get_length32(JSContext *ctx, uint32_t *pres, + JSValueConst obj); +static __exception int js_get_length64(JSContext *ctx, int64_t *pres, + JSValueConst obj); +static __exception int js_set_length64(JSContext *ctx, JSValueConst obj, + int64_t len); +static void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len); +static JSValue *build_arg_list(JSContext *ctx, uint32_t *plen, + JSValueConst array_arg); +static JSValue js_create_array(JSContext *ctx, int len, JSValueConst *tab); +static bool js_get_fast_array(JSContext *ctx, JSValue obj, + JSValue **arrpp, uint32_t *countp); +static int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len); +static JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx, + JSValue sync_iter); +static void js_c_function_data_finalizer(JSRuntime *rt, JSValueConst val); +static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func); +static JSValue js_call_c_function_data(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_val, + int argc, JSValueConst *argv, int flags); +static void js_c_closure_finalizer(JSRuntime *rt, JSValueConst val); +static JSValue js_call_c_closure(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_val, + int argc, JSValueConst *argv, int flags); +static JSAtom JS_ValueToAtomInternal(JSContext *ctx, JSValueConst val, + int flags); +static JSAtom js_symbol_to_atom(JSContext *ctx, JSValueConst val); +static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h, + JSGCObjectTypeEnum type); +static void remove_gc_object(JSGCObjectHeader *h); +static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s); +static JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); +static JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom, + void *opaque); +static JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p, + JSAtom atom, void *opaque); + +static void js_set_uncatchable_error(JSContext *ctx, JSValueConst val, + bool flag); + +static JSValue js_new_callsite(JSContext *ctx, JSCallSiteData *csd); +static void js_new_callsite_data(JSContext *ctx, JSCallSiteData *csd, JSStackFrame *sf); +static void js_new_callsite_data2(JSContext *ctx, JSCallSiteData *csd, const char *filename, int line_num, int col_num); +static void _JS_AddIntrinsicCallSite(JSContext *ctx); + +static void JS_SetOpaqueInternal(JSValueConst obj, void *opaque); + +static const JSClassExoticMethods js_arguments_exotic_methods; +static const JSClassExoticMethods js_string_exotic_methods; +static const JSClassExoticMethods js_proxy_exotic_methods; +static const JSClassExoticMethods js_module_ns_exotic_methods; + +static inline bool double_is_int32(double d) +{ + uint64_t u, e; + JSFloat64Union t; + + t.d = d; + u = t.u64; + + e = ((u >> 52) & 0x7FF) - 1023; + if (e > 30) { + // accept 0, INT32_MIN, reject too large, too small, nan, inf, -0 + return !u || (u == 0xc1e0000000000000); + } else { + // shift out sign, exponent and whole part bits + // value is fractional if remaining low bits are non-zero + return !(u << 12 << e); + } +} + +static JSValue js_float64(double d) +{ + return __JS_NewFloat64(d); +} + +static int compare_u32(uint32_t a, uint32_t b) +{ + return -(a < b) + (b < a); // -1, 0 or 1 +} + +static JSValue js_int32(int32_t v) +{ + return JS_MKVAL(JS_TAG_INT, v); +} + +static JSValue js_uint32(uint32_t v) +{ + if (v <= INT32_MAX) + return js_int32(v); + else + return js_float64(v); +} + +static JSValue js_int64(int64_t v) +{ + if (v >= INT32_MIN && v <= INT32_MAX) + return js_int32(v); + else + return js_float64(v); +} + +static JSValue js_number(double d) +{ + if (double_is_int32(d)) + return js_int32((int32_t)d); + else + return js_float64(d); +} + +JSValue JS_NewNumber(JSContext *ctx, double d) +{ + return js_number(d); +} + +static JSValue js_bool(bool v) +{ + return JS_MKVAL(JS_TAG_BOOL, (v != 0)); +} + +static JSValue js_dup(JSValueConst v) +{ + if (JS_VALUE_HAS_REF_COUNT(v)) { + JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); + p->ref_count++; + } + return unsafe_unconst(v); +} + +JSValue JS_DupValue(JSContext *ctx, JSValueConst v) +{ + return js_dup(v); +} + +JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v) +{ + return js_dup(v); +} + +static void js_trigger_gc(JSRuntime *rt, size_t size) +{ + bool force_gc; +#ifdef FORCE_GC_AT_MALLOC + force_gc = true; +#else + force_gc = ((rt->malloc_state.malloc_size + size) > + rt->malloc_gc_threshold); +#endif + if (force_gc) { +#ifdef ENABLE_DUMPS // JS_DUMP_GC + if (check_dump_flag(rt, JS_DUMP_GC)) { + printf("GC: size=%zd\n", rt->malloc_state.malloc_size); + } +#endif + JS_RunGC(rt); + rt->malloc_gc_threshold = rt->malloc_state.malloc_size + + (rt->malloc_state.malloc_size >> 1); + } +} + +static size_t js_malloc_usable_size_unknown(const void *ptr) +{ + return 0; +} + +void *js_calloc_rt(JSRuntime *rt, size_t count, size_t size) +{ + void *ptr; + JSMallocState *s; + + /* Do not allocate zero bytes: behavior is platform dependent */ + assert(count != 0 && size != 0); + + if (size > 0) + if (unlikely(count != (count * size) / size)) + return NULL; + + s = &rt->malloc_state; + /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */ + if (unlikely(s->malloc_size + (count * size) > s->malloc_limit - 1)) + return NULL; + + ptr = rt->mf.js_calloc(s->opaque, count, size); + if (!ptr) + return NULL; + + s->malloc_count++; + s->malloc_size += rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD; + return ptr; +} + +void *js_malloc_rt(JSRuntime *rt, size_t size) +{ + void *ptr; + JSMallocState *s; + + /* Do not allocate zero bytes: behavior is platform dependent */ + assert(size != 0); + + s = &rt->malloc_state; + /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */ + if (unlikely(s->malloc_size + size > s->malloc_limit - 1)) + return NULL; + + ptr = rt->mf.js_malloc(s->opaque, size); + if (!ptr) + return NULL; + + s->malloc_count++; + s->malloc_size += rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD; + return ptr; +} + +void js_free_rt(JSRuntime *rt, void *ptr) +{ + JSMallocState *s; + + if (!ptr) + return; + + s = &rt->malloc_state; + s->malloc_count--; + s->malloc_size -= rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD; + rt->mf.js_free(s->opaque, ptr); +} + +void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size) +{ + size_t old_size; + JSMallocState *s; + + if (!ptr) { + if (size == 0) + return NULL; + return js_malloc_rt(rt, size); + } + if (unlikely(size == 0)) { + js_free_rt(rt, ptr); + return NULL; + } + old_size = rt->mf.js_malloc_usable_size(ptr); + s = &rt->malloc_state; + /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */ + if (s->malloc_size + size - old_size > s->malloc_limit - 1) + return NULL; + + ptr = rt->mf.js_realloc(s->opaque, ptr, size); + if (!ptr) + return NULL; + + s->malloc_size += rt->mf.js_malloc_usable_size(ptr) - old_size; + return ptr; +} + +size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr) +{ + return rt->mf.js_malloc_usable_size(ptr); +} + +/** + * This used to be implemented as malloc + memset, but using calloc + * yields better performance in initial, bursty allocations, something useful + * for QuickJS. + * + * More information: https://github.com/quickjs-ng/quickjs/pull/519 + */ +void *js_mallocz_rt(JSRuntime *rt, size_t size) +{ + return js_calloc_rt(rt, 1, size); +} + +/* Throw out of memory in case of error */ +void *js_calloc(JSContext *ctx, size_t count, size_t size) +{ + void *ptr; + ptr = js_calloc_rt(ctx->rt, count, size); + if (unlikely(!ptr)) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + return ptr; +} + +/* Throw out of memory in case of error */ +void *js_malloc(JSContext *ctx, size_t size) +{ + void *ptr; + ptr = js_malloc_rt(ctx->rt, size); + if (unlikely(!ptr)) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + return ptr; +} + +/* Throw out of memory in case of error */ +void *js_mallocz(JSContext *ctx, size_t size) +{ + void *ptr; + ptr = js_mallocz_rt(ctx->rt, size); + if (unlikely(!ptr)) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + return ptr; +} + +void js_free(JSContext *ctx, void *ptr) +{ + js_free_rt(ctx->rt, ptr); +} + +/* Throw out of memory in case of error */ +void *js_realloc(JSContext *ctx, void *ptr, size_t size) +{ + void *ret; + ret = js_realloc_rt(ctx->rt, ptr, size); + if (unlikely(!ret && size != 0)) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + return ret; +} + +/* store extra allocated size in *pslack if successful */ +void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack) +{ + void *ret; + ret = js_realloc_rt(ctx->rt, ptr, size); + if (unlikely(!ret && size != 0)) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + if (pslack) { + size_t new_size = js_malloc_usable_size_rt(ctx->rt, ret); + *pslack = (new_size > size) ? new_size - size : 0; + } + return ret; +} + +size_t js_malloc_usable_size(JSContext *ctx, const void *ptr) +{ + return js_malloc_usable_size_rt(ctx->rt, ptr); +} + +/* Throw out of memory exception in case of error */ +char *js_strndup(JSContext *ctx, const char *s, size_t n) +{ + char *ptr; + ptr = js_malloc(ctx, n + 1); + if (ptr) { + memcpy(ptr, s, n); + ptr[n] = '\0'; + } + return ptr; +} + +char *js_strdup(JSContext *ctx, const char *str) +{ + return js_strndup(ctx, str, strlen(str)); +} + +static no_inline int js_realloc_array(JSContext *ctx, void **parray, + int elem_size, int *psize, int req_size) +{ + int new_size; + size_t slack; + void *new_array; + /* XXX: potential arithmetic overflow */ + new_size = max_int(req_size, *psize * 3 / 2); + new_array = js_realloc2(ctx, *parray, new_size * elem_size, &slack); + if (!new_array) + return -1; + new_size += slack / elem_size; + *psize = new_size; + *parray = new_array; + return 0; +} + +/* resize the array and update its size if req_size > *psize */ +static inline int js_resize_array(JSContext *ctx, void **parray, int elem_size, + int *psize, int req_size) +{ + if (unlikely(req_size > *psize)) + return js_realloc_array(ctx, parray, elem_size, psize, req_size); + else + return 0; +} + +static void *js_dbuf_realloc(void *ctx, void *ptr, size_t size) +{ + return js_realloc(ctx, ptr, size); +} + +static inline void js_dbuf_init(JSContext *ctx, DynBuf *s) +{ + dbuf_init2(s, ctx, js_dbuf_realloc); +} + +static inline int is_digit(int c) { + return c >= '0' && c <= '9'; +} + +static inline int string_get(JSString *p, int idx) { + return p->is_wide_char ? str16(p)[idx] : str8(p)[idx]; +} + +typedef struct JSClassShortDef { + JSAtom class_name; + JSClassFinalizer *finalizer; + JSClassGCMark *gc_mark; +} JSClassShortDef; + +static JSClassShortDef const js_std_class_def[] = { + { JS_ATOM_Object, NULL, NULL }, /* JS_CLASS_OBJECT */ + { JS_ATOM_Array, js_array_finalizer, js_array_mark }, /* JS_CLASS_ARRAY */ + { JS_ATOM_Error, NULL, NULL }, /* JS_CLASS_ERROR */ + { JS_ATOM_Number, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_NUMBER */ + { JS_ATOM_String, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_STRING */ + { JS_ATOM_Boolean, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BOOLEAN */ + { JS_ATOM_Symbol, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_SYMBOL */ + { JS_ATOM_Arguments, js_array_finalizer, js_array_mark }, /* JS_CLASS_ARGUMENTS */ + { JS_ATOM_Arguments, js_mapped_arguments_finalizer, js_mapped_arguments_mark }, /* JS_CLASS_MAPPED_ARGUMENTS */ + { JS_ATOM_Date, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_DATE */ + { JS_ATOM_Object, NULL, NULL }, /* JS_CLASS_MODULE_NS */ + { JS_ATOM_Function, js_c_function_finalizer, js_c_function_mark }, /* JS_CLASS_C_FUNCTION */ + { JS_ATOM_Function, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_BYTECODE_FUNCTION */ + { JS_ATOM_Function, js_bound_function_finalizer, js_bound_function_mark }, /* JS_CLASS_BOUND_FUNCTION */ + { JS_ATOM_Function, js_c_function_data_finalizer, js_c_function_data_mark }, /* JS_CLASS_C_FUNCTION_DATA */ + { JS_ATOM_Function, js_c_closure_finalizer, NULL}, /* JS_CLASS_C_CLOSURE */ + { JS_ATOM_GeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_GENERATOR_FUNCTION */ + { JS_ATOM_ForInIterator, js_for_in_iterator_finalizer, js_for_in_iterator_mark }, /* JS_CLASS_FOR_IN_ITERATOR */ + { JS_ATOM_RegExp, js_regexp_finalizer, NULL }, /* JS_CLASS_REGEXP */ + { JS_ATOM_ArrayBuffer, js_array_buffer_finalizer, NULL }, /* JS_CLASS_ARRAY_BUFFER */ + { JS_ATOM_SharedArrayBuffer, js_array_buffer_finalizer, NULL }, /* JS_CLASS_SHARED_ARRAY_BUFFER */ + { JS_ATOM_Uint8ClampedArray, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8C_ARRAY */ + { JS_ATOM_Int8Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT8_ARRAY */ + { JS_ATOM_Uint8Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8_ARRAY */ + { JS_ATOM_Int16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT16_ARRAY */ + { JS_ATOM_Uint16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT16_ARRAY */ + { JS_ATOM_Int32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT32_ARRAY */ + { JS_ATOM_Uint32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT32_ARRAY */ + { JS_ATOM_BigInt64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_BIG_INT64_ARRAY */ + { JS_ATOM_BigUint64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_BIG_UINT64_ARRAY */ + { JS_ATOM_Float16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT16_ARRAY */ + { JS_ATOM_Float32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT32_ARRAY */ + { JS_ATOM_Float64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT64_ARRAY */ + { JS_ATOM_DataView, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_DATAVIEW */ + { JS_ATOM_BigInt, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BIG_INT */ + { JS_ATOM_Map, js_map_finalizer, js_map_mark }, /* JS_CLASS_MAP */ + { JS_ATOM_Set, js_map_finalizer, js_map_mark }, /* JS_CLASS_SET */ + { JS_ATOM_WeakMap, js_map_finalizer, NULL }, /* JS_CLASS_WEAKMAP */ + { JS_ATOM_WeakSet, js_map_finalizer, NULL }, /* JS_CLASS_WEAKSET */ + { JS_ATOM_Iterator, NULL, NULL }, /* JS_CLASS_ITERATOR */ + { JS_ATOM_IteratorConcat, js_iterator_concat_finalizer, js_iterator_concat_mark }, /* JS_CLASS_ITERATOR_CONCAT */ + { JS_ATOM_IteratorHelper, js_iterator_helper_finalizer, js_iterator_helper_mark }, /* JS_CLASS_ITERATOR_HELPER */ + { JS_ATOM_IteratorWrap, js_iterator_wrap_finalizer, js_iterator_wrap_mark }, /* JS_CLASS_ITERATOR_WRAP */ + { JS_ATOM_Map_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_MAP_ITERATOR */ + { JS_ATOM_Set_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_SET_ITERATOR */ + { JS_ATOM_Array_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_ARRAY_ITERATOR */ + { JS_ATOM_String_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_STRING_ITERATOR */ + { JS_ATOM_RegExp_String_Iterator, js_regexp_string_iterator_finalizer, js_regexp_string_iterator_mark }, /* JS_CLASS_REGEXP_STRING_ITERATOR */ + { JS_ATOM_Generator, js_generator_finalizer, js_generator_mark }, /* JS_CLASS_GENERATOR */ +}; + +static int init_class_range(JSRuntime *rt, JSClassShortDef const *tab, + int start, int count) +{ + JSClassDef cm_s, *cm = &cm_s; + int i, class_id; + + for(i = 0; i < count; i++) { + class_id = i + start; + memset(cm, 0, sizeof(*cm)); + cm->finalizer = tab[i].finalizer; + cm->gc_mark = tab[i].gc_mark; + if (JS_NewClass1(rt, class_id, cm, tab[i].class_name) < 0) + return -1; + } + return 0; +} + +/* Uses code from LLVM project. */ +static inline uintptr_t js_get_stack_pointer(void) +{ +#if defined(__clang__) || defined(__GNUC__) + return (uintptr_t)__builtin_frame_address(0); +#elif defined(_MSC_VER) + return (uintptr_t)_AddressOfReturnAddress(); +#else + char CharOnStack = 0; + // The volatile store here is intended to escape the local variable, to + // prevent the compiler from optimizing CharOnStack into anything other + // than a char on the stack. + // + // Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19. + char *volatile Ptr = &CharOnStack; + return (uintptr_t) Ptr; +#endif +} + +static inline bool js_check_stack_overflow(JSRuntime *rt, size_t alloca_size) +{ + uintptr_t sp; + sp = js_get_stack_pointer() - alloca_size; + return unlikely(sp < rt->stack_limit); +} + +JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque) +{ + JSRuntime *rt; + JSMallocState ms; + + memset(&ms, 0, sizeof(ms)); + ms.opaque = opaque; + ms.malloc_limit = 0; + + rt = mf->js_calloc(opaque, 1, sizeof(JSRuntime)); + if (!rt) + return NULL; + rt->mf = *mf; + if (!rt->mf.js_malloc_usable_size) { + /* use dummy function if none provided */ + rt->mf.js_malloc_usable_size = js_malloc_usable_size_unknown; + } + /* Inline what js_malloc_rt does since we cannot use it here. */ + ms.malloc_count++; + ms.malloc_size += rt->mf.js_malloc_usable_size(rt) + MALLOC_OVERHEAD; + rt->malloc_state = ms; + rt->malloc_gc_threshold = 256 * 1024; + + init_list_head(&rt->context_list); + init_list_head(&rt->gc_obj_list); + init_list_head(&rt->gc_zero_ref_count_list); + rt->gc_phase = JS_GC_PHASE_NONE; + +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + init_list_head(&rt->string_list); +#endif + init_list_head(&rt->job_list); + + if (JS_InitAtoms(rt)) + goto fail; + + /* create the object, array and function classes */ + if (init_class_range(rt, js_std_class_def, JS_CLASS_OBJECT, + countof(js_std_class_def)) < 0) + goto fail; + rt->class_array[JS_CLASS_ARGUMENTS].exotic = &js_arguments_exotic_methods; + rt->class_array[JS_CLASS_MAPPED_ARGUMENTS].exotic = &js_arguments_exotic_methods; + rt->class_array[JS_CLASS_STRING].exotic = &js_string_exotic_methods; + rt->class_array[JS_CLASS_MODULE_NS].exotic = &js_module_ns_exotic_methods; + + rt->class_array[JS_CLASS_C_FUNCTION].call = js_call_c_function; + rt->class_array[JS_CLASS_C_FUNCTION_DATA].call = js_call_c_function_data; + rt->class_array[JS_CLASS_C_CLOSURE].call = js_call_c_closure; + rt->class_array[JS_CLASS_BOUND_FUNCTION].call = js_call_bound_function; + rt->class_array[JS_CLASS_GENERATOR_FUNCTION].call = js_call_generator_function; + if (init_shape_hash(rt)) + goto fail; + + rt->js_class_id_alloc = JS_CLASS_INIT_COUNT; + + rt->stack_size = JS_DEFAULT_STACK_SIZE; +#ifdef __wasi__ + rt->stack_size = 0; +#endif + + JS_UpdateStackTop(rt); + + rt->current_exception = JS_UNINITIALIZED; + + return rt; + fail: + JS_FreeRuntime(rt); + return NULL; +} + +void *JS_GetRuntimeOpaque(JSRuntime *rt) +{ + return rt->user_opaque; +} + +void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque) +{ + rt->user_opaque = opaque; +} + +int JS_AddRuntimeFinalizer(JSRuntime *rt, JSRuntimeFinalizer *finalizer, + void *arg) +{ + JSRuntimeFinalizerState *fs = js_malloc_rt(rt, sizeof(*fs)); + if (!fs) + return -1; + fs->next = rt->finalizers; + fs->finalizer = finalizer; + fs->arg = arg; + rt->finalizers = fs; + return 0; +} + +static void *js_def_calloc(void *opaque, size_t count, size_t size) +{ + return calloc(count, size); +} + +static void *js_def_malloc(void *opaque, size_t size) +{ + return malloc(size); +} + +static void js_def_free(void *opaque, void *ptr) +{ + free(ptr); +} + +static void *js_def_realloc(void *opaque, void *ptr, size_t size) +{ + return realloc(ptr, size); +} + +static const JSMallocFunctions def_malloc_funcs = { + js_def_calloc, + js_def_malloc, + js_def_free, + js_def_realloc, + js__malloc_usable_size +}; + +JSRuntime *JS_NewRuntime(void) +{ + return JS_NewRuntime2(&def_malloc_funcs, NULL); +} + +void JS_SetMemoryLimit(JSRuntime *rt, size_t limit) +{ + rt->malloc_state.malloc_limit = limit; +} + +void JS_SetDumpFlags(JSRuntime *rt, uint64_t flags) +{ +#ifdef ENABLE_DUMPS + rt->dump_flags = flags; +#endif +} + +uint64_t JS_GetDumpFlags(JSRuntime *rt) +{ +#ifdef ENABLE_DUMPS + return rt->dump_flags; +#else + return 0; +#endif +} + +size_t JS_GetGCThreshold(JSRuntime *rt) { + return rt->malloc_gc_threshold; +} + +/* use -1 to disable automatic GC */ +void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold) +{ + rt->malloc_gc_threshold = gc_threshold; +} + +#define malloc(s) malloc_is_forbidden(s) +#define free(p) free_is_forbidden(p) +#define realloc(p,s) realloc_is_forbidden(p,s) + +void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque) +{ + rt->interrupt_handler = cb; + rt->interrupt_opaque = opaque; +} + +void JS_SetCanBlock(JSRuntime *rt, bool can_block) +{ + rt->can_block = can_block; +} + +void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, + const JSSharedArrayBufferFunctions *sf) +{ + rt->sab_funcs = *sf; +} + +/* return 0 if OK, < 0 if exception */ +int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, + int argc, JSValueConst *argv) +{ + JSRuntime *rt = ctx->rt; + JSJobEntry *e; + int i; + + assert(!rt->in_free); + + e = js_malloc(ctx, sizeof(*e) + argc * sizeof(JSValue)); + if (!e) + return -1; + e->ctx = ctx; + e->job_func = job_func; + e->argc = argc; + for(i = 0; i < argc; i++) { + e->argv[i] = js_dup(argv[i]); + } + list_add_tail(&e->link, &rt->job_list); + return 0; +} + +bool JS_IsJobPending(JSRuntime *rt) +{ + return !list_empty(&rt->job_list); +} + +/* return < 0 if exception, 0 if no job pending, 1 if a job was + executed successfully. the context of the job is stored in '*pctx' */ +int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx) +{ + JSContext *ctx; + JSJobEntry *e; + JSValue res; + int i, ret; + + if (list_empty(&rt->job_list)) { + *pctx = NULL; + return 0; + } + + /* get the first pending job and execute it */ + e = list_entry(rt->job_list.next, JSJobEntry, link); + list_del(&e->link); + ctx = e->ctx; + res = e->job_func(e->ctx, e->argc, vc(e->argv)); + for(i = 0; i < e->argc; i++) + JS_FreeValue(ctx, e->argv[i]); + if (JS_IsException(res)) + ret = -1; + else + ret = 1; + JS_FreeValue(ctx, res); + js_free(ctx, e); + *pctx = ctx; + return ret; +} + +static inline uint32_t atom_get_free(const JSAtomStruct *p) +{ + return (uintptr_t)p >> 1; +} + +static inline bool atom_is_free(const JSAtomStruct *p) +{ + return (uintptr_t)p & 1; +} + +static inline JSAtomStruct *atom_set_free(uint32_t v) +{ + return (JSAtomStruct *)(((uintptr_t)v << 1) | 1); +} + +/* Note: the string contents are uninitialized */ +static JSString *js_alloc_string_rt(JSRuntime *rt, int max_len, int is_wide_char) +{ + JSString *str; + str = js_malloc_rt(rt, sizeof(JSString) + (max_len << is_wide_char) + 1 - is_wide_char); + if (unlikely(!str)) + return NULL; + str->header.ref_count = 1; + str->is_wide_char = is_wide_char; + str->len = max_len; + str->kind = JS_STRING_KIND_NORMAL; + str->atom_type = 0; + str->hash = 0; /* optional but costless */ + str->hash_next = 0; /* optional */ +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_add_tail(&str->link, &rt->string_list); +#endif + return str; +} + +static JSString *js_alloc_string(JSContext *ctx, int max_len, int is_wide_char) +{ + JSString *p; + p = js_alloc_string_rt(ctx->rt, max_len, is_wide_char); + if (unlikely(!p)) { + JS_ThrowOutOfMemory(ctx); + return NULL; + } + return p; +} + +static inline void js_free_string0(JSRuntime *rt, JSString *str); + +/* same as JS_FreeValueRT() but faster */ +static inline void js_free_string(JSRuntime *rt, JSString *str) +{ + if (--str->header.ref_count <= 0) + js_free_string0(rt, str); +} + +static inline void js_free_string0(JSRuntime *rt, JSString *str) +{ + JSStringSlice *slice; + + if (str->atom_type) { + JS_FreeAtomStruct(rt, str); + } else { +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_del(&str->link); +#endif + switch (str->kind) { + case JS_STRING_KIND_SLICE: + slice = (void *)&str[1]; + js_free_string(rt, slice->parent); // safe, recurses only 1 level + break; + case JS_STRING_KIND_INDIRECT: + js_free_rt(rt, strv(str)); + break; + } + js_free_rt(rt, str); + } +} + +void JS_SetRuntimeInfo(JSRuntime *rt, const char *s) +{ + if (rt) + rt->rt_info = s; +} + +void JS_FreeRuntime(JSRuntime *rt) +{ + struct list_head *el, *el1; + int i; + + rt->in_free = true; + JS_FreeValueRT(rt, rt->current_exception); + + list_for_each_safe(el, el1, &rt->job_list) { + JSJobEntry *e = list_entry(el, JSJobEntry, link); + for(i = 0; i < e->argc; i++) + JS_FreeValueRT(rt, e->argv[i]); + js_free_rt(rt, e); + } + init_list_head(&rt->job_list); + + JS_RunGC(rt); + +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + /* leaking objects */ + if (check_dump_flag(rt, JS_DUMP_LEAKS)) { + bool header_done; + JSGCObjectHeader *p; + int count; + + /* remove the internal refcounts to display only the object + referenced externally */ + list_for_each(el, &rt->gc_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + p->mark = 0; + } + gc_decref(rt); + + header_done = false; + list_for_each(el, &rt->gc_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + if (p->ref_count != 0) { + if (!header_done) { + printf("Object leaks:\n"); + JS_DumpObjectHeader(rt); + header_done = true; + } + JS_DumpGCObject(rt, p); + } + } + + count = 0; + list_for_each(el, &rt->gc_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + if (p->ref_count == 0) { + count++; + } + } + if (count != 0) + printf("Secondary object leaks: %d\n", count); + } +#endif + + assert(list_empty(&rt->gc_obj_list)); + + /* free the classes */ + for(i = 0; i < rt->class_count; i++) { + JSClass *cl = &rt->class_array[i]; + if (cl->class_id != 0) { + JS_FreeAtomRT(rt, cl->class_name); + } + } + js_free_rt(rt, rt->class_array); + +#ifdef ENABLE_DUMPS // JS_DUMP_ATOM_LEAKS + /* only the atoms defined in JS_InitAtoms() should be left */ + if (check_dump_flag(rt, JS_DUMP_ATOM_LEAKS)) { + bool header_done = false; + + for(i = 0; i < rt->atom_size; i++) { + JSAtomStruct *p = rt->atom_array[i]; + if (!atom_is_free(p) /* && p->str*/) { + if (i >= JS_ATOM_END || p->header.ref_count != 1) { + if (!header_done) { + header_done = true; + if (rt->rt_info) { + printf("%s:1: atom leakage:", rt->rt_info); + } else { + printf("Atom leaks:\n" + " %6s %6s %s\n", + "ID", "REFCNT", "NAME"); + } + } + if (rt->rt_info) { + printf(" "); + } else { + printf(" %6u %6u ", i, p->header.ref_count); + } + switch (p->atom_type) { + case JS_ATOM_TYPE_STRING: + JS_DumpString(rt, p); + break; + case JS_ATOM_TYPE_GLOBAL_SYMBOL: + printf("Symbol.for("); + JS_DumpString(rt, p); + printf(")"); + break; + case JS_ATOM_TYPE_SYMBOL: + if (p->hash == JS_ATOM_HASH_SYMBOL) { + printf("Symbol("); + JS_DumpString(rt, p); + printf(")"); + } else { + printf("Private("); + JS_DumpString(rt, p); + printf(")"); + } + break; + } + if (rt->rt_info) { + printf(":%u", p->header.ref_count); + } else { + printf("\n"); + } + } + } + } + if (rt->rt_info && header_done) + printf("\n"); + } +#endif + + /* free the atoms */ + for(i = 0; i < rt->atom_size; i++) { + JSAtomStruct *p = rt->atom_array[i]; + if (!atom_is_free(p)) { +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_del(&p->link); +#endif + js_free_rt(rt, p); + } + } + js_free_rt(rt, rt->atom_array); + js_free_rt(rt, rt->atom_hash); + js_free_rt(rt, rt->shape_hash); +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + if (check_dump_flag(rt, JS_DUMP_LEAKS) && !list_empty(&rt->string_list)) { + if (rt->rt_info) { + printf("%s:1: string leakage:", rt->rt_info); + } else { + printf("String leaks:\n" + " %6s %s\n", + "REFCNT", "VALUE"); + } + list_for_each_safe(el, el1, &rt->string_list) { + JSString *str = list_entry(el, JSString, link); + if (rt->rt_info) { + printf(" "); + } else { + printf(" %6u ", str->header.ref_count); + } + JS_DumpString(rt, str); + if (rt->rt_info) { + printf(":%u", str->header.ref_count); + } else { + printf("\n"); + } + list_del(&str->link); + js_free_rt(rt, str); + } + if (rt->rt_info) + printf("\n"); + } +#endif + + while (rt->finalizers) { + JSRuntimeFinalizerState *fs = rt->finalizers; + rt->finalizers = fs->next; + fs->finalizer(rt, fs->arg); + js_free_rt(rt, fs); + } + +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + if (check_dump_flag(rt, JS_DUMP_LEAKS)) { + JSMallocState *s = &rt->malloc_state; + if (s->malloc_count > 1) { + if (rt->rt_info) + printf("%s:1: ", rt->rt_info); + printf("Memory leak: %zd bytes lost in %zd block%s\n", + s->malloc_size - sizeof(JSRuntime), + s->malloc_count - 1, &"s"[s->malloc_count == 2]); + } + } +#endif + + { + JSMallocState *ms = &rt->malloc_state; + rt->mf.js_free(ms->opaque, rt); + } +} + +JSContext *JS_NewContextRaw(JSRuntime *rt) +{ + JSContext *ctx; + int i; + + ctx = js_mallocz_rt(rt, sizeof(JSContext)); + if (!ctx) + return NULL; + ctx->header.ref_count = 1; + add_gc_object(rt, &ctx->header, JS_GC_OBJ_TYPE_JS_CONTEXT); + + ctx->class_proto = js_malloc_rt(rt, sizeof(ctx->class_proto[0]) * + rt->class_count); + if (!ctx->class_proto) { + js_free_rt(rt, ctx); + return NULL; + } + ctx->rt = rt; + list_add_tail(&ctx->link, &rt->context_list); + for(i = 0; i < rt->class_count; i++) + ctx->class_proto[i] = JS_NULL; + ctx->array_ctor = JS_NULL; + ctx->iterator_ctor = JS_NULL; + ctx->iterator_ctor_getset = JS_NULL; + ctx->regexp_ctor = JS_NULL; + ctx->promise_ctor = JS_NULL; + ctx->error_ctor = JS_NULL; + ctx->error_back_trace = JS_UNDEFINED; + ctx->error_prepare_stack = JS_UNDEFINED; + ctx->error_stack_trace_limit = js_int32(10); + init_list_head(&ctx->loaded_modules); + + JS_AddIntrinsicBasicObjects(ctx); + return ctx; +} + +JSContext *JS_NewContext(JSRuntime *rt) +{ + JSContext *ctx; + + ctx = JS_NewContextRaw(rt); + if (!ctx) + return NULL; + + JS_AddIntrinsicBaseObjects(ctx); + JS_AddIntrinsicDate(ctx); + JS_AddIntrinsicEval(ctx); + JS_AddIntrinsicRegExp(ctx); + JS_AddIntrinsicJSON(ctx); + JS_AddIntrinsicProxy(ctx); + JS_AddIntrinsicMapSet(ctx); + JS_AddIntrinsicTypedArrays(ctx); + JS_AddIntrinsicPromise(ctx); + JS_AddIntrinsicBigInt(ctx); + JS_AddIntrinsicWeakRef(ctx); + JS_AddIntrinsicDOMException(ctx); + + JS_AddPerformance(ctx); + + return ctx; +} + +void *JS_GetContextOpaque(JSContext *ctx) +{ + return ctx->user_opaque; +} + +void JS_SetContextOpaque(JSContext *ctx, void *opaque) +{ + ctx->user_opaque = opaque; +} + +/* set the new value and free the old value after (freeing the value + can reallocate the object data) */ +static inline void set_value(JSContext *ctx, JSValue *pval, JSValue new_val) +{ + JSValue old_val; + old_val = *pval; + *pval = new_val; + JS_FreeValue(ctx, old_val); +} + +void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj) +{ + assert(class_id < ctx->rt->class_count); + set_value(ctx, &ctx->class_proto[class_id], obj); +} + +JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id) +{ + assert(class_id < ctx->rt->class_count); + return js_dup(ctx->class_proto[class_id]); +} + +JSValue JS_GetFunctionProto(JSContext *ctx) +{ + return js_dup(ctx->function_proto); +} + +typedef enum JSFreeModuleEnum { + JS_FREE_MODULE_ALL, + JS_FREE_MODULE_NOT_RESOLVED, +} JSFreeModuleEnum; + +/* XXX: would be more efficient with separate module lists */ +static void js_free_modules(JSContext *ctx, JSFreeModuleEnum flag) +{ + struct list_head *el, *el1; + list_for_each_safe(el, el1, &ctx->loaded_modules) { + JSModuleDef *m = list_entry(el, JSModuleDef, link); + if (flag == JS_FREE_MODULE_ALL || + (flag == JS_FREE_MODULE_NOT_RESOLVED && !m->resolved)) { + js_free_module_def(ctx, m); + } + } +} + +JSContext *JS_DupContext(JSContext *ctx) +{ + ctx->header.ref_count++; + return ctx; +} + +/* used by the GC */ +static void JS_MarkContext(JSRuntime *rt, JSContext *ctx, + JS_MarkFunc *mark_func) +{ + int i; + struct list_head *el; + + /* modules are not seen by the GC, so we directly mark the objects + referenced by each module */ + list_for_each(el, &ctx->loaded_modules) { + JSModuleDef *m = list_entry(el, JSModuleDef, link); + js_mark_module_def(rt, m, mark_func); + } + + JS_MarkValue(rt, ctx->global_obj, mark_func); + JS_MarkValue(rt, ctx->global_var_obj, mark_func); + + JS_MarkValue(rt, ctx->throw_type_error, mark_func); + JS_MarkValue(rt, ctx->eval_obj, mark_func); + + JS_MarkValue(rt, ctx->array_proto_values, mark_func); + for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) { + JS_MarkValue(rt, ctx->native_error_proto[i], mark_func); + } + JS_MarkValue(rt, ctx->error_ctor, mark_func); + JS_MarkValue(rt, ctx->error_back_trace, mark_func); + JS_MarkValue(rt, ctx->error_prepare_stack, mark_func); + JS_MarkValue(rt, ctx->error_stack_trace_limit, mark_func); + for(i = 0; i < rt->class_count; i++) { + JS_MarkValue(rt, ctx->class_proto[i], mark_func); + } + JS_MarkValue(rt, ctx->iterator_ctor, mark_func); + JS_MarkValue(rt, ctx->iterator_ctor_getset, mark_func); + JS_MarkValue(rt, ctx->async_iterator_proto, mark_func); + JS_MarkValue(rt, ctx->promise_ctor, mark_func); + JS_MarkValue(rt, ctx->array_ctor, mark_func); + JS_MarkValue(rt, ctx->regexp_ctor, mark_func); + JS_MarkValue(rt, ctx->function_ctor, mark_func); + JS_MarkValue(rt, ctx->function_proto, mark_func); + + if (ctx->array_shape) + mark_func(rt, &ctx->array_shape->header); + + if (ctx->arguments_shape) + mark_func(rt, &ctx->arguments_shape->header); + + if (ctx->mapped_arguments_shape) + mark_func(rt, &ctx->mapped_arguments_shape->header); + + if (ctx->regexp_shape) + mark_func(rt, &ctx->regexp_shape->header); + + if (ctx->regexp_result_shape) + mark_func(rt, &ctx->regexp_result_shape->header); +} + +void JS_FreeContext(JSContext *ctx) +{ + JSRuntime *rt = ctx->rt; + int i; + + if (--ctx->header.ref_count > 0) + return; + assert(ctx->header.ref_count == 0); + +#ifdef ENABLE_DUMPS // JS_DUMP_ATOMS + if (check_dump_flag(rt, JS_DUMP_ATOMS)) + JS_DumpAtoms(ctx->rt); +#endif +#ifdef ENABLE_DUMPS // JS_DUMP_SHAPES + if (check_dump_flag(rt, JS_DUMP_SHAPES)) + JS_DumpShapes(ctx->rt); +#endif +#ifdef ENABLE_DUMPS // JS_DUMP_OBJECTS + if (check_dump_flag(rt, JS_DUMP_OBJECTS)) { + struct list_head *el; + JSGCObjectHeader *p; + printf("JSObjects: {\n"); + JS_DumpObjectHeader(ctx->rt); + list_for_each(el, &rt->gc_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + JS_DumpGCObject(rt, p); + } + printf("}\n"); + } +#endif +#ifdef ENABLE_DUMPS // JS_DUMP_MEM + if (check_dump_flag(rt, JS_DUMP_MEM)) { + JSMemoryUsage stats; + JS_ComputeMemoryUsage(rt, &stats); + JS_DumpMemoryUsage(stdout, &stats, rt); + } +#endif + + js_free_modules(ctx, JS_FREE_MODULE_ALL); + + JS_FreeValue(ctx, ctx->global_obj); + JS_FreeValue(ctx, ctx->global_var_obj); + + JS_FreeValue(ctx, ctx->throw_type_error); + JS_FreeValue(ctx, ctx->eval_obj); + + JS_FreeValue(ctx, ctx->array_proto_values); + for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) { + JS_FreeValue(ctx, ctx->native_error_proto[i]); + } + JS_FreeValue(ctx, ctx->error_ctor); + JS_FreeValue(ctx, ctx->error_back_trace); + JS_FreeValue(ctx, ctx->error_prepare_stack); + JS_FreeValue(ctx, ctx->error_stack_trace_limit); + for(i = 0; i < rt->class_count; i++) { + JS_FreeValue(ctx, ctx->class_proto[i]); + } + js_free_rt(rt, ctx->class_proto); + JS_FreeValue(ctx, ctx->iterator_ctor); + JS_FreeValue(ctx, ctx->iterator_ctor_getset); + JS_FreeValue(ctx, ctx->async_iterator_proto); + JS_FreeValue(ctx, ctx->promise_ctor); + JS_FreeValue(ctx, ctx->array_ctor); + JS_FreeValue(ctx, ctx->regexp_ctor); + JS_FreeValue(ctx, ctx->function_ctor); + JS_FreeValue(ctx, ctx->function_proto); + + js_free_shape_null(ctx->rt, ctx->array_shape); + js_free_shape_null(ctx->rt, ctx->arguments_shape); + js_free_shape_null(ctx->rt, ctx->mapped_arguments_shape); + js_free_shape_null(ctx->rt, ctx->regexp_shape); + js_free_shape_null(ctx->rt, ctx->regexp_result_shape); + + list_del(&ctx->link); + remove_gc_object(&ctx->header); + js_free_rt(ctx->rt, ctx); +} + +JSRuntime *JS_GetRuntime(JSContext *ctx) +{ + return ctx->rt; +} + +static void update_stack_limit(JSRuntime *rt) +{ +#if defined(__wasi__) + rt->stack_limit = 0; /* no limit */ +#else + if (rt->stack_size == 0) { + rt->stack_limit = 0; /* no limit */ + } else { + rt->stack_limit = rt->stack_top - rt->stack_size; + } +#endif +} + +void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size) +{ + rt->stack_size = stack_size; + update_stack_limit(rt); +} + +void JS_UpdateStackTop(JSRuntime *rt) +{ + rt->stack_top = js_get_stack_pointer(); + update_stack_limit(rt); +} + +static inline bool is_strict_mode(JSContext *ctx) +{ + JSStackFrame *sf = ctx->rt->current_stack_frame; + return sf && sf->is_strict_mode; +} + +/* JSAtom support */ + +#define JS_ATOM_TAG_INT (1U << 31) +#define JS_ATOM_MAX_INT (JS_ATOM_TAG_INT - 1) +#define JS_ATOM_MAX ((1U << 30) - 1) + +/* return the max count from the hash size */ +#define JS_ATOM_COUNT_RESIZE(n) ((n) * 2) + +static inline bool __JS_AtomIsConst(JSAtom v) +{ + return (int32_t)v < JS_ATOM_END; +} + +static inline bool __JS_AtomIsTaggedInt(JSAtom v) +{ + return (v & JS_ATOM_TAG_INT) != 0; +} + +static inline JSAtom __JS_AtomFromUInt32(uint32_t v) +{ + return v | JS_ATOM_TAG_INT; +} + +static inline uint32_t __JS_AtomToUInt32(JSAtom atom) +{ + return atom & ~JS_ATOM_TAG_INT; +} + +static inline int is_num(int c) +{ + return c >= '0' && c <= '9'; +} + +/* return true if the string is a number n with 0 <= n <= 2^32-1 */ +static inline bool is_num_string(uint32_t *pval, JSString *p) +{ + uint32_t n; + uint64_t n64; + int c, i, len; + + len = p->len; + if (len == 0 || len > 10) + return false; + c = string_get(p, 0); + if (is_num(c)) { + if (c == '0') { + if (len != 1) + return false; + n = 0; + } else { + n = c - '0'; + for(i = 1; i < len; i++) { + c = string_get(p, i); + if (!is_num(c)) + return false; + n64 = (uint64_t)n * 10 + (c - '0'); + if ((n64 >> 32) != 0) + return false; + n = n64; + } + } + *pval = n; + return true; + } else { + return false; + } +} + +/* XXX: could use faster version ? */ +static inline uint32_t hash_string8(const uint8_t *str, size_t len, uint32_t h) +{ + size_t i; + + for(i = 0; i < len; i++) + h = h * 263 + str[i]; + return h; +} + +static inline uint32_t hash_string16(const uint16_t *str, + size_t len, uint32_t h) +{ + size_t i; + + for(i = 0; i < len; i++) + h = h * 263 + str[i]; + return h; +} + +static uint32_t hash_string(JSString *str, uint32_t h) +{ + if (str->is_wide_char) + h = hash_string16(str16(str), str->len, h); + else + h = hash_string8(str8(str), str->len, h); + return h; +} + +static uint32_t hash_string_rope(JSValueConst val, uint32_t h) +{ + if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING) { + return hash_string(JS_VALUE_GET_STRING(val), h); + } else { + JSStringRope *r = JS_VALUE_GET_STRING_ROPE(val); + h = hash_string_rope(r->left, h); + return hash_string_rope(r->right, h); + } +} + +static __maybe_unused void JS_DumpString(JSRuntime *rt, JSString *p) +{ + int i, c, sep; + + if (p == NULL) { + printf(""); + return; + } + if (p->header.ref_count != 1) + printf("%d", p->header.ref_count); + if (p->is_wide_char) + putchar('L'); + sep = '\"'; + putchar(sep); + for(i = 0; i < p->len; i++) { + c = string_get(p, i); + if (c == sep || c == '\\') { + putchar('\\'); + putchar(c); + } else if (c >= ' ' && c <= 126) { + putchar(c); + } else if (c == '\n') { + putchar('\\'); + putchar('n'); + } else { + printf("\\u%04x", c); + } + } + putchar(sep); +} + +static __maybe_unused void JS_DumpAtoms(JSRuntime *rt) +{ + JSAtomStruct *p; + int h, i; + /* This only dumps hashed atoms, not JS_ATOM_TYPE_SYMBOL atoms */ + printf("JSAtom count=%d size=%d hash_size=%d:\n", + rt->atom_count, rt->atom_size, rt->atom_hash_size); + printf("JSAtom hash table: {\n"); + for(i = 0; i < rt->atom_hash_size; i++) { + h = rt->atom_hash[i]; + if (h) { + printf(" %d:", i); + while (h) { + p = rt->atom_array[h]; + printf(" "); + JS_DumpString(rt, p); + h = p->hash_next; + } + printf("\n"); + } + } + printf("}\n"); + printf("JSAtom table: {\n"); + for(i = 0; i < rt->atom_size; i++) { + p = rt->atom_array[i]; + if (!atom_is_free(p)) { + printf(" %d: { %d %08x ", i, p->atom_type, p->hash); + if (!(p->len == 0 && p->is_wide_char != 0)) + JS_DumpString(rt, p); + printf(" %d }\n", p->hash_next); + } + } + printf("}\n"); +} + +static int JS_ResizeAtomHash(JSRuntime *rt, int new_hash_size) +{ + JSAtomStruct *p; + uint32_t new_hash_mask, h, i, hash_next1, j, *new_hash; + + assert((new_hash_size & (new_hash_size - 1)) == 0); /* power of two */ + new_hash_mask = new_hash_size - 1; + new_hash = js_mallocz_rt(rt, sizeof(rt->atom_hash[0]) * new_hash_size); + if (!new_hash) + return -1; + for(i = 0; i < rt->atom_hash_size; i++) { + h = rt->atom_hash[i]; + while (h != 0) { + p = rt->atom_array[h]; + hash_next1 = p->hash_next; + /* add in new hash table */ + j = p->hash & new_hash_mask; + p->hash_next = new_hash[j]; + new_hash[j] = h; + h = hash_next1; + } + } + js_free_rt(rt, rt->atom_hash); + rt->atom_hash = new_hash; + rt->atom_hash_size = new_hash_size; + rt->atom_count_resize = JS_ATOM_COUNT_RESIZE(new_hash_size); + // JS_DumpAtoms(rt); + return 0; +} + +static int JS_InitAtoms(JSRuntime *rt) +{ + int i, len, atom_type; + const char *p; + + rt->atom_hash_size = 0; + rt->atom_hash = NULL; + rt->atom_count = 0; + rt->atom_size = 0; + rt->atom_free_index = 0; + if (JS_ResizeAtomHash(rt, 256)) /* there are at least 195 predefined atoms */ + return -1; + + p = js_atom_init; + for(i = 1; i < JS_ATOM_END; i++) { + if (i == JS_ATOM_Private_brand) + atom_type = JS_ATOM_TYPE_PRIVATE; + else if (i >= JS_ATOM_Symbol_toPrimitive) + atom_type = JS_ATOM_TYPE_SYMBOL; + else + atom_type = JS_ATOM_TYPE_STRING; + len = strlen(p); + if (__JS_NewAtomInit(rt, p, len, atom_type) == JS_ATOM_NULL) + return -1; + p = p + len + 1; + } + return 0; +} + +JSAtom JS_DupAtomRT(JSRuntime *rt, JSAtom v) +{ + JSAtomStruct *p; + + if (!__JS_AtomIsConst(v)) { + p = rt->atom_array[v]; + p->header.ref_count++; + } + return v; +} + +JSAtom JS_DupAtom(JSContext *ctx, JSAtom v) +{ + JSRuntime *rt; + JSAtomStruct *p; + + if (!__JS_AtomIsConst(v)) { + rt = ctx->rt; + p = rt->atom_array[v]; + p->header.ref_count++; + } + return v; +} + +static JSAtomKindEnum JS_AtomGetKind(JSContext *ctx, JSAtom v) +{ + JSRuntime *rt; + JSAtomStruct *p; + + rt = ctx->rt; + if (__JS_AtomIsTaggedInt(v)) + return JS_ATOM_KIND_STRING; + p = rt->atom_array[v]; + switch(p->atom_type) { + case JS_ATOM_TYPE_STRING: + return JS_ATOM_KIND_STRING; + case JS_ATOM_TYPE_GLOBAL_SYMBOL: + return JS_ATOM_KIND_SYMBOL; + case JS_ATOM_TYPE_SYMBOL: + switch(p->hash) { + case JS_ATOM_HASH_SYMBOL: + return JS_ATOM_KIND_SYMBOL; + case JS_ATOM_HASH_PRIVATE: + return JS_ATOM_KIND_PRIVATE; + default: + abort(); + } + default: + abort(); + } + return (JSAtomKindEnum){-1}; // pacify compiler +} + +static JSAtom js_get_atom_index(JSRuntime *rt, JSAtomStruct *p) +{ + uint32_t i = p->hash_next; /* atom_index */ + if (p->atom_type != JS_ATOM_TYPE_SYMBOL) { + JSAtomStruct *p1; + + i = rt->atom_hash[p->hash & (rt->atom_hash_size - 1)]; + p1 = rt->atom_array[i]; + while (p1 != p) { + assert(i != 0); + i = p1->hash_next; + p1 = rt->atom_array[i]; + } + } + return i; +} + +/* string case (internal). Return JS_ATOM_NULL if error. 'str' is + freed. */ +static JSAtom __JS_NewAtom(JSRuntime *rt, JSString *str, int atom_type) +{ + uint32_t h, h1, i; + JSAtomStruct *p; + int len; + + if (atom_type < JS_ATOM_TYPE_SYMBOL) { + /* str is not NULL */ + if (str->atom_type == atom_type) { + /* str is the atom, return its index */ + i = js_get_atom_index(rt, str); + /* reduce string refcount and increase atom's unless constant */ + if (__JS_AtomIsConst(i)) + str->header.ref_count--; + return i; + } + /* try and locate an already registered atom */ + len = str->len; + h = hash_string(str, atom_type); + h &= JS_ATOM_HASH_MASK; + h1 = h & (rt->atom_hash_size - 1); + i = rt->atom_hash[h1]; + while (i != 0) { + p = rt->atom_array[i]; + if (p->hash == h && + p->atom_type == atom_type && + p->len == len && + js_string_memcmp(p, str, len) == 0) { + if (!__JS_AtomIsConst(i)) + p->header.ref_count++; + goto done; + } + i = p->hash_next; + } + } else { + h1 = 0; /* avoid warning */ + if (atom_type == JS_ATOM_TYPE_SYMBOL) { + h = JS_ATOM_HASH_SYMBOL; + } else { + h = JS_ATOM_HASH_PRIVATE; + atom_type = JS_ATOM_TYPE_SYMBOL; + } + } + + if (rt->atom_free_index == 0) { + /* allow new atom entries */ + uint32_t new_size, start; + JSAtomStruct **new_array; + + /* alloc new with size progression 3/2: + 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092 + preallocating space for predefined atoms (at least 195). + */ + new_size = max_int(211, rt->atom_size * 3 / 2); + if (new_size > JS_ATOM_MAX) + goto fail; + /* XXX: should use realloc2 to use slack space */ + new_array = js_realloc_rt(rt, rt->atom_array, sizeof(*new_array) * new_size); + if (!new_array) + goto fail; + /* Note: the atom 0 is not used */ + start = rt->atom_size; + if (start == 0) { + /* JS_ATOM_NULL entry */ + p = js_mallocz_rt(rt, sizeof(JSAtomStruct)); + if (!p) { + js_free_rt(rt, new_array); + goto fail; + } + p->header.ref_count = 1; /* not refcounted */ + p->atom_type = JS_ATOM_TYPE_SYMBOL; +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_add_tail(&p->link, &rt->string_list); +#endif + new_array[0] = p; + rt->atom_count++; + start = 1; + } + rt->atom_size = new_size; + rt->atom_array = new_array; + rt->atom_free_index = start; + for(i = start; i < new_size; i++) { + uint32_t next; + if (i == (new_size - 1)) + next = 0; + else + next = i + 1; + rt->atom_array[i] = atom_set_free(next); + } + } + + if (str) { + if (str->atom_type == 0) { + p = str; + p->atom_type = atom_type; + } else { + p = js_malloc_rt(rt, sizeof(JSString) + + (str->len << str->is_wide_char) + + 1 - str->is_wide_char); + if (unlikely(!p)) + goto fail; + p->header.ref_count = 1; + p->is_wide_char = str->is_wide_char; + p->len = str->len; + p->kind = JS_STRING_KIND_NORMAL; +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_add_tail(&p->link, &rt->string_list); +#endif + memcpy(str8(p), str8(str), (str->len << str->is_wide_char) + + 1 - str->is_wide_char); + js_free_string(rt, str); + } + } else { + p = js_malloc_rt(rt, sizeof(JSAtomStruct)); /* empty wide string */ + if (!p) + return JS_ATOM_NULL; + p->header.ref_count = 1; + p->is_wide_char = 1; /* Hack to represent NULL as a JSString */ + p->len = 0; + p->kind = JS_STRING_KIND_NORMAL; +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_add_tail(&p->link, &rt->string_list); +#endif + } + + /* use an already free entry */ + i = rt->atom_free_index; + rt->atom_free_index = atom_get_free(rt->atom_array[i]); + rt->atom_array[i] = p; + + p->hash = h; + p->hash_next = i; /* atom_index */ + p->atom_type = atom_type; + p->first_weak_ref = NULL; + + rt->atom_count++; + + if (atom_type != JS_ATOM_TYPE_SYMBOL) { + p->hash_next = rt->atom_hash[h1]; + rt->atom_hash[h1] = i; + if (unlikely(rt->atom_count >= rt->atom_count_resize)) + JS_ResizeAtomHash(rt, rt->atom_hash_size * 2); + } + + // JS_DumpAtoms(rt); + return i; + + fail: + i = JS_ATOM_NULL; + done: + if (str) + js_free_string(rt, str); + return i; +} + +// XXX: `str` must be pure ASCII. No UTF-8 encoded strings +// XXX: `str` must not be the string representation of a small integer +static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len, + int atom_type) +{ + JSString *p; + p = js_alloc_string_rt(rt, len, 0); + if (!p) + return JS_ATOM_NULL; + memcpy(str8(p), str, len); + str8(p)[len] = '\0'; + return __JS_NewAtom(rt, p, atom_type); +} + +// XXX: `str` must be raw 8-bit contents. No UTF-8 encoded strings +static JSAtom __JS_FindAtom(JSRuntime *rt, const char *str, size_t len, + int atom_type) +{ + uint32_t h, h1, i; + JSAtomStruct *p; + + h = hash_string8((const uint8_t *)str, len, JS_ATOM_TYPE_STRING); + h &= JS_ATOM_HASH_MASK; + h1 = h & (rt->atom_hash_size - 1); + i = rt->atom_hash[h1]; + while (i != 0) { + p = rt->atom_array[i]; + if (p->hash == h && + p->atom_type == JS_ATOM_TYPE_STRING && + p->len == len && + p->is_wide_char == 0 && + memcmp(str8(p), str, len) == 0) { + if (!__JS_AtomIsConst(i)) + p->header.ref_count++; + return i; + } + i = p->hash_next; + } + return JS_ATOM_NULL; +} + +static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p) +{ + uint32_t i = p->hash_next; /* atom_index */ + if (p->atom_type != JS_ATOM_TYPE_SYMBOL) { + JSAtomStruct *p0, *p1; + uint32_t h0; + + h0 = p->hash & (rt->atom_hash_size - 1); + i = rt->atom_hash[h0]; + p1 = rt->atom_array[i]; + if (p1 == p) { + rt->atom_hash[h0] = p1->hash_next; + } else { + for(;;) { + assert(i != 0); + p0 = p1; + i = p1->hash_next; + p1 = rt->atom_array[i]; + if (p1 == p) { + p0->hash_next = p1->hash_next; + break; + } + } + } + } + /* insert in free atom list */ + rt->atom_array[i] = atom_set_free(rt->atom_free_index); + rt->atom_free_index = i; + if (unlikely(p->first_weak_ref)) { + reset_weak_ref(rt, &p->first_weak_ref); + } + /* free the string structure */ +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_del(&p->link); +#endif + js_free_rt(rt, p); + rt->atom_count--; + assert(rt->atom_count >= 0); +} + +static void __JS_FreeAtom(JSRuntime *rt, uint32_t i) +{ + JSAtomStruct *p; + + p = rt->atom_array[i]; + if (--p->header.ref_count > 0) + return; + JS_FreeAtomStruct(rt, p); +} + +/* Warning: 'p' is freed */ +static JSAtom JS_NewAtomStr(JSContext *ctx, JSString *p) +{ + JSRuntime *rt = ctx->rt; + uint32_t n; + if (is_num_string(&n, p)) { + if (n <= JS_ATOM_MAX_INT) { + js_free_string(rt, p); + return __JS_AtomFromUInt32(n); + } + } + /* XXX: should generate an exception */ + return __JS_NewAtom(rt, p, JS_ATOM_TYPE_STRING); +} + +/* `str` may be pure ASCII or UTF-8 encoded */ +JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len) +{ + JSValue val; + + if (len == 0 || !is_digit(*str)) { + // TODO(chqrlie): this does not work if `str` has UTF-8 encoded contents + // bug example: `({ "\u00c3\u00a9": 1 }).\u00e9` evaluates to `1`. + JSAtom atom = __JS_FindAtom(ctx->rt, str, len, JS_ATOM_TYPE_STRING); + if (atom) + return atom; + } + val = JS_NewStringLen(ctx, str, len); + if (JS_IsException(val)) + return JS_ATOM_NULL; + return JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(val)); +} + +/* `str` may be pure ASCII or UTF-8 encoded */ +JSAtom JS_NewAtom(JSContext *ctx, const char *str) +{ + return JS_NewAtomLen(ctx, str, strlen(str)); +} + +JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n) +{ + if (n <= JS_ATOM_MAX_INT) { + return __JS_AtomFromUInt32(n); + } else { + char buf[16]; + size_t len = u32toa(buf, n); + JSValue val = js_new_string8_len(ctx, buf, len); + if (JS_IsException(val)) + return JS_ATOM_NULL; + return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val), + JS_ATOM_TYPE_STRING); + } +} + +static JSAtom JS_NewAtomInt64(JSContext *ctx, int64_t n) +{ + if ((uint64_t)n <= JS_ATOM_MAX_INT) { + return __JS_AtomFromUInt32((uint32_t)n); + } else { + char buf[24]; + size_t len = i64toa(buf, n); + JSValue val = js_new_string8_len(ctx, buf, len); + if (JS_IsException(val)) + return JS_ATOM_NULL; + return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val), + JS_ATOM_TYPE_STRING); + } +} + +/* 'p' is freed */ +static JSValue JS_NewSymbolInternal(JSContext *ctx, JSString *p, int atom_type) +{ + JSRuntime *rt = ctx->rt; + JSAtom atom; + atom = __JS_NewAtom(rt, p, atom_type); + if (atom == JS_ATOM_NULL) + return JS_ThrowOutOfMemory(ctx); + return JS_MKPTR(JS_TAG_SYMBOL, rt->atom_array[atom]); +} + +/* descr must be a non-numeric string atom */ +static JSValue JS_NewSymbolFromAtom(JSContext *ctx, JSAtom descr, + int atom_type) +{ + JSRuntime *rt = ctx->rt; + JSString *p; + + assert(!__JS_AtomIsTaggedInt(descr)); + assert(descr < rt->atom_size); + p = rt->atom_array[descr]; + js_dup(JS_MKPTR(JS_TAG_STRING, p)); + return JS_NewSymbolInternal(ctx, p, atom_type); +} + +/* `description` may be pure ASCII or UTF-8 encoded */ +JSValue JS_NewSymbol(JSContext *ctx, const char *description, bool is_global) +{ + JSAtom atom = JS_NewAtom(ctx, description); + if (atom == JS_ATOM_NULL) + return JS_EXCEPTION; + return JS_NewSymbolFromAtom(ctx, atom, is_global ? JS_ATOM_TYPE_GLOBAL_SYMBOL : JS_ATOM_TYPE_SYMBOL); +} + +#define ATOM_GET_STR_BUF_SIZE 64 + +static const char *JS_AtomGetStrRT(JSRuntime *rt, char *buf, int buf_size, + JSAtom atom) +{ + if (__JS_AtomIsTaggedInt(atom)) { + snprintf(buf, buf_size, "%u", __JS_AtomToUInt32(atom)); + } else if (atom == JS_ATOM_NULL) { + snprintf(buf, buf_size, ""); + } else if (atom >= rt->atom_size) { + assert(atom < rt->atom_size); + snprintf(buf, buf_size, "", atom); + } else { + JSAtomStruct *p = rt->atom_array[atom]; + *buf = '\0'; + if (atom_is_free(p)) { + snprintf(buf, buf_size, "", atom); + } else if (p != NULL) { + JSString *str = p; + if (str->is_wide_char) { + /* encode surrogates correctly */ + utf8_encode_buf16(buf, buf_size, str16(str), str->len); + } else { + utf8_encode_buf8(buf, buf_size, str8(str), str->len); + } + } + } + return buf; +} + +static const char *JS_AtomGetStr(JSContext *ctx, char *buf, int buf_size, JSAtom atom) +{ + return JS_AtomGetStrRT(ctx->rt, buf, buf_size, atom); +} + +static JSValue __JS_AtomToValue(JSContext *ctx, JSAtom atom, bool force_string) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + + if (__JS_AtomIsTaggedInt(atom)) { + size_t len = u32toa(buf, __JS_AtomToUInt32(atom)); + return js_new_string8_len(ctx, buf, len); + } else { + JSRuntime *rt = ctx->rt; + JSAtomStruct *p; + assert(atom < rt->atom_size); + p = rt->atom_array[atom]; + if (p->atom_type == JS_ATOM_TYPE_STRING) { + goto ret_string; + } else if (force_string) { + if (p->len == 0 && p->is_wide_char != 0) { + /* no description string */ + p = rt->atom_array[JS_ATOM_empty_string]; + } + ret_string: + return js_dup(JS_MKPTR(JS_TAG_STRING, p)); + } else { + return js_dup(JS_MKPTR(JS_TAG_SYMBOL, p)); + } + } +} + +JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom) +{ + return __JS_AtomToValue(ctx, atom, false); +} + +JSValue JS_AtomToString(JSContext *ctx, JSAtom atom) +{ + return __JS_AtomToValue(ctx, atom, true); +} + +/* return true if the atom is an array index (i.e. 0 <= index <= + 2^32-2 and return its value */ +static bool JS_AtomIsArrayIndex(JSContext *ctx, uint32_t *pval, JSAtom atom) +{ + if (__JS_AtomIsTaggedInt(atom)) { + *pval = __JS_AtomToUInt32(atom); + return true; + } else { + JSRuntime *rt = ctx->rt; + JSAtomStruct *p; + uint32_t val; + + assert(atom < rt->atom_size); + p = rt->atom_array[atom]; + if (p->atom_type == JS_ATOM_TYPE_STRING && + is_num_string(&val, p) && val != -1) { + *pval = val; + return true; + } else { + *pval = 0; + return false; + } + } +} + +/* This test must be fast if atom is not a numeric index (e.g. a + method name). Return JS_UNDEFINED if not a numeric + index. JS_EXCEPTION can also be returned. */ +static JSValue JS_AtomIsNumericIndex1(JSContext *ctx, JSAtom atom) +{ + JSRuntime *rt = ctx->rt; + JSAtomStruct *p1; + JSString *p; + int c, len, ret; + JSValue num, str; + + if (__JS_AtomIsTaggedInt(atom)) + return js_int32(__JS_AtomToUInt32(atom)); + assert(atom < rt->atom_size); + p1 = rt->atom_array[atom]; + if (p1->atom_type != JS_ATOM_TYPE_STRING) + return JS_UNDEFINED; + p = p1; + len = p->len; + if (p->is_wide_char) { + const uint16_t *r = str16(p), *r_end = str16(p) + len; + if (r >= r_end) + return JS_UNDEFINED; + c = *r; + if (c == '-') { + if (r >= r_end) + return JS_UNDEFINED; + r++; + c = *r; + /* -0 case is specific */ + if (c == '0' && len == 2) + goto minus_zero; + } + /* XXX: should test NaN, but the tests do not check it */ + if (!is_num(c)) { + /* XXX: String should be normalized, therefore 8-bit only */ + const uint16_t nfinity16[7] = { 'n', 'f', 'i', 'n', 'i', 't', 'y' }; + if (!(c =='I' && (r_end - r) == 8 && + !memcmp(r + 1, nfinity16, sizeof(nfinity16)))) + return JS_UNDEFINED; + } + } else { + const uint8_t *r = str8(p), *r_end = str8(p) + len; + if (r >= r_end) + return JS_UNDEFINED; + c = *r; + if (c == '-') { + if (r >= r_end) + return JS_UNDEFINED; + r++; + c = *r; + /* -0 case is specific */ + if (c == '0' && len == 2) { + minus_zero: + return js_float64(-0.0); + } + } + if (!is_num(c)) { + if (!(c =='I' && (r_end - r) == 8 && + !memcmp(r + 1, "nfinity", 7))) + return JS_UNDEFINED; + } + } + /* this is ECMA CanonicalNumericIndexString primitive */ + num = JS_ToNumber(ctx, JS_MKPTR(JS_TAG_STRING, p)); + if (JS_IsException(num)) + return num; + str = JS_ToString(ctx, num); + if (JS_IsException(str)) { + JS_FreeValue(ctx, num); + return str; + } + ret = js_string_eq(p, JS_VALUE_GET_STRING(str)); + JS_FreeValue(ctx, str); + if (ret) { + return num; + } else { + JS_FreeValue(ctx, num); + return JS_UNDEFINED; + } +} + +/* return -1 if exception or true/false */ +static int JS_AtomIsNumericIndex(JSContext *ctx, JSAtom atom) +{ + JSValue num; + num = JS_AtomIsNumericIndex1(ctx, atom); + if (likely(JS_IsUndefined(num))) + return false; + if (JS_IsException(num)) + return -1; + JS_FreeValue(ctx, num); + return true; +} + +void JS_FreeAtom(JSContext *ctx, JSAtom v) +{ + if (!__JS_AtomIsConst(v)) + __JS_FreeAtom(ctx->rt, v); +} + +void JS_FreeAtomRT(JSRuntime *rt, JSAtom v) +{ + if (!__JS_AtomIsConst(v)) + __JS_FreeAtom(rt, v); +} + +/* return true if 'v' is a symbol with a string description */ +static bool JS_AtomSymbolHasDescription(JSContext *ctx, JSAtom v) +{ + JSRuntime *rt; + JSAtomStruct *p; + + rt = ctx->rt; + if (__JS_AtomIsTaggedInt(v)) + return false; + p = rt->atom_array[v]; + return (((p->atom_type == JS_ATOM_TYPE_SYMBOL && + p->hash == JS_ATOM_HASH_SYMBOL) || + p->atom_type == JS_ATOM_TYPE_GLOBAL_SYMBOL) && + !(p->len == 0 && p->is_wide_char != 0)); +} + +static __maybe_unused void print_atom(JSContext *ctx, JSAtom atom) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + const char *p; + int i; + + /* XXX: should handle embedded null characters */ + /* XXX: should move encoding code to JS_AtomGetStr */ + p = JS_AtomGetStr(ctx, buf, sizeof(buf), atom); + for (i = 0; p[i]; i++) { + int c = (unsigned char)p[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c == '_' || c == '$') || (c >= '0' && c <= '9' && i > 0))) + break; + } + if (i > 0 && p[i] == '\0') { + printf("%s", p); + } else { + putchar('"'); + printf("%.*s", i, p); + for (; p[i]; i++) { + int c = (unsigned char)p[i]; + if (c == '\"' || c == '\\') { + putchar('\\'); + putchar(c); + } else if (c >= ' ' && c <= 126) { + putchar(c); + } else if (c == '\n') { + putchar('\\'); + putchar('n'); + } else { + printf("\\u%04x", c); + } + } + putchar('\"'); + } +} + +/* free with JS_FreeCString() */ +const char *JS_AtomToCStringLen(JSContext *ctx, size_t *plen, JSAtom atom) +{ + JSValue str; + const char *cstr; + + str = JS_AtomToString(ctx, atom); + if (JS_IsException(str)) { + if (plen) + *plen = 0; + return NULL; + } + cstr = JS_ToCStringLen(ctx, plen, str); + JS_FreeValue(ctx, str); + return cstr; +} + +#ifndef QJS_DISABLE_PARSER + +/* return a string atom containing name concatenated with str1 */ +/* `str1` may be pure ASCII or UTF-8 encoded */ +// TODO(chqrlie): use string concatenation instead of UTF-8 conversion +static JSAtom js_atom_concat_str(JSContext *ctx, JSAtom name, const char *str1) +{ + JSValue str; + JSAtom atom; + const char *cstr; + char *cstr2; + size_t len, len1; + + str = JS_AtomToString(ctx, name); + if (JS_IsException(str)) + return JS_ATOM_NULL; + cstr = JS_ToCStringLen(ctx, &len, str); + if (!cstr) + goto fail; + len1 = strlen(str1); + cstr2 = js_malloc(ctx, len + len1 + 1); + if (!cstr2) + goto fail; + memcpy(cstr2, cstr, len); + memcpy(cstr2 + len, str1, len1); + cstr2[len + len1] = '\0'; + atom = JS_NewAtomLen(ctx, cstr2, len + len1); + js_free(ctx, cstr2); + JS_FreeCString(ctx, cstr); + JS_FreeValue(ctx, str); + return atom; + fail: + JS_FreeCString(ctx, cstr); + JS_FreeValue(ctx, str); + return JS_ATOM_NULL; +} + +static JSAtom js_atom_concat_num(JSContext *ctx, JSAtom name, uint32_t n) +{ + char buf[16]; + size_t len; + + len = u32toa(buf, n); + buf[len] = '\0'; + return js_atom_concat_str(ctx, name, buf); +} + +#endif // QJS_DISABLE_PARSER + +static inline bool JS_IsEmptyString(JSValueConst v) +{ + return JS_VALUE_GET_TAG(v) == JS_TAG_STRING && JS_VALUE_GET_STRING(v)->len == 0; +} + +/* JSClass support */ + +/* a new class ID is allocated if *pclass_id == 0, otherwise *pclass_id is left unchanged */ +JSClassID JS_NewClassID(JSRuntime *rt, JSClassID *pclass_id) +{ + JSClassID class_id = *pclass_id; + if (class_id == 0) { + class_id = rt->js_class_id_alloc++; + *pclass_id = class_id; + } + return class_id; +} + +JSClassID JS_GetClassID(JSValueConst v) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(v) != JS_TAG_OBJECT) + return JS_INVALID_CLASS_ID; + p = JS_VALUE_GET_OBJ(v); + return p->class_id; +} + +bool JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id) +{ + return (class_id < rt->class_count && + rt->class_array[class_id].class_id != 0); +} + +JSAtom JS_GetClassName(JSRuntime *rt, JSClassID class_id) +{ + if (JS_IsRegisteredClass(rt, class_id)) { + return JS_DupAtomRT(rt, rt->class_array[class_id].class_id); + } else { + return JS_ATOM_NULL; + } +} + +/* create a new object internal class. Return -1 if error, 0 if + OK. The finalizer can be NULL if none is needed. */ +static int JS_NewClass1(JSRuntime *rt, JSClassID class_id, + const JSClassDef *class_def, JSAtom name) +{ + int new_size, i; + JSClass *cl, *new_class_array; + struct list_head *el; + + if (class_id >= (1 << 16)) + return -1; + if (class_id < rt->class_count && + rt->class_array[class_id].class_id != 0) + return -1; + + if (class_id >= rt->class_count) { + new_size = max_int(JS_CLASS_INIT_COUNT, + max_int(class_id + 1, rt->class_count * 3 / 2)); + + /* reallocate the context class prototype array, if any */ + list_for_each(el, &rt->context_list) { + JSContext *ctx = list_entry(el, JSContext, link); + JSValue *new_tab; + new_tab = js_realloc_rt(rt, ctx->class_proto, + sizeof(ctx->class_proto[0]) * new_size); + if (!new_tab) + return -1; + for(i = rt->class_count; i < new_size; i++) + new_tab[i] = JS_NULL; + ctx->class_proto = new_tab; + } + /* reallocate the class array */ + new_class_array = js_realloc_rt(rt, rt->class_array, + sizeof(JSClass) * new_size); + if (!new_class_array) + return -1; + memset(new_class_array + rt->class_count, 0, + (new_size - rt->class_count) * sizeof(JSClass)); + rt->class_array = new_class_array; + rt->class_count = new_size; + } + cl = &rt->class_array[class_id]; + cl->class_id = class_id; + cl->class_name = JS_DupAtomRT(rt, name); + cl->finalizer = class_def->finalizer; + cl->gc_mark = class_def->gc_mark; + cl->call = class_def->call; + cl->exotic = class_def->exotic; + return 0; +} + +int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def) +{ + int ret, len; + JSAtom name; + + // XXX: class_def->class_name must be raw 8-bit contents. No UTF-8 encoded strings + len = strlen(class_def->class_name); + name = __JS_FindAtom(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING); + if (name == JS_ATOM_NULL) { + name = __JS_NewAtomInit(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING); + if (name == JS_ATOM_NULL) + return -1; + } + ret = JS_NewClass1(rt, class_id, class_def, name); + JS_FreeAtomRT(rt, name); + return ret; +} + +static inline JSValue js_empty_string(JSRuntime *rt) +{ + JSAtomStruct *p = rt->atom_array[JS_ATOM_empty_string]; + return js_dup(JS_MKPTR(JS_TAG_STRING, p)); +} + +// XXX: `buf` contains raw 8-bit data, no UTF-8 decoding is performed +// XXX: no special case for len == 0 +static JSValue js_new_string8_len(JSContext *ctx, const char *buf, int len) +{ + JSString *str; + str = js_alloc_string(ctx, len, 0); + if (!str) + return JS_EXCEPTION; + memcpy(str8(str), buf, len); + str8(str)[len] = '\0'; + return JS_MKPTR(JS_TAG_STRING, str); +} + +// XXX: `buf` contains raw 8-bit data, no UTF-8 decoding is performed +// XXX: no special case for the empty string +static inline JSValue js_new_string8(JSContext *ctx, const char *str) +{ + return js_new_string8_len(ctx, str, strlen(str)); +} + +static JSValue js_new_string16_len(JSContext *ctx, const uint16_t *buf, int len) +{ + JSString *str; + str = js_alloc_string(ctx, len, 1); + if (!str) + return JS_EXCEPTION; + memcpy(str16(str), buf, len * 2); + return JS_MKPTR(JS_TAG_STRING, str); +} + +static JSValue js_new_string_char(JSContext *ctx, uint16_t c) +{ + if (c < 0x100) { + char ch8 = c; + return js_new_string8_len(ctx, &ch8, 1); + } else { + uint16_t ch16 = c; + return js_new_string16_len(ctx, &ch16, 1); + } +} + +static JSValue js_sub_string(JSContext *ctx, JSString *p, int start, int end) +{ + JSStringSlice *slice; + JSString *q; + int len; + + len = end - start; + if (start == 0 && end == p->len) { + return js_dup(JS_MKPTR(JS_TAG_STRING, p)); + } + if (len <= 0) { + return js_empty_string(ctx->rt); + } + if (len > (JS_STRING_SLICE_LEN_MAX >> p->is_wide_char)) { + if (p->kind == JS_STRING_KIND_SLICE) { + slice = (void *)&p[1]; + p = slice->parent; + start += slice->start >> p->is_wide_char; // bytes -> chars + } + // allocate as 16 bit wide string to avoid wastage; + // js_alloc_string allocates 1 byte extra for 8 bit strings; + q = js_alloc_string(ctx, sizeof(*slice)/2, /*is_wide_char*/true); + if (!q) + return JS_EXCEPTION; + q->is_wide_char = p->is_wide_char; + q->kind = JS_STRING_KIND_SLICE; + q->len = len; + slice = (void *)&q[1]; + slice->parent = p; + slice->start = start << p->is_wide_char; // chars -> bytes + p->header.ref_count++; + return JS_MKPTR(JS_TAG_STRING, q); + } + if (p->is_wide_char) { + JSString *str; + int i; + uint16_t c = 0; + for (i = start; i < end; i++) { + c |= str16(p)[i]; + } + if (c > 0xFF) + return js_new_string16_len(ctx, str16(p) + start, len); + + str = js_alloc_string(ctx, len, 0); + if (!str) + return JS_EXCEPTION; + for (i = 0; i < len; i++) { + str8(str)[i] = str16(p)[start + i]; + } + str8(str)[len] = '\0'; + return JS_MKPTR(JS_TAG_STRING, str); + } else { + return js_new_string8_len(ctx, (const char *)(str8(p) + start), len); + } +} + +typedef struct StringBuffer { + JSContext *ctx; + JSString *str; + int len; + int size; + int is_wide_char; + int error_status; +} StringBuffer; + +/* It is valid to call string_buffer_end() and all string_buffer functions even + if string_buffer_init() or another string_buffer function returns an error. + If the error_status is set, string_buffer_end() returns JS_EXCEPTION. + */ +static int string_buffer_init2(JSContext *ctx, StringBuffer *s, int size, + int is_wide) +{ + s->ctx = ctx; + s->size = size; + s->len = 0; + s->is_wide_char = is_wide; + s->error_status = 0; + s->str = js_alloc_string(ctx, size, is_wide); + if (unlikely(!s->str)) { + s->size = 0; + return s->error_status = -1; + } +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + /* the StringBuffer may reallocate the JSString, only link it at the end */ + list_del(&s->str->link); +#endif + return 0; +} + +static inline int string_buffer_init(JSContext *ctx, StringBuffer *s, int size) +{ + return string_buffer_init2(ctx, s, size, 0); +} + +static void string_buffer_free(StringBuffer *s) +{ + js_free(s->ctx, s->str); + s->str = NULL; +} + +static int string_buffer_set_error(StringBuffer *s) +{ + js_free(s->ctx, s->str); + s->str = NULL; + s->size = 0; + s->len = 0; + return s->error_status = -1; +} + +static no_inline int string_buffer_widen(StringBuffer *s, int size) +{ + JSString *str; + size_t slack; + int i; + + if (s->error_status) + return -1; + + str = js_realloc2(s->ctx, s->str, sizeof(JSString) + (size << 1), &slack); + if (!str) + return string_buffer_set_error(s); + size += slack >> 1; + for(i = s->len; i-- > 0;) { + str16(str)[i] = str8(str)[i]; + } + s->is_wide_char = 1; + s->size = size; + s->str = str; + return 0; +} + +static no_inline int string_buffer_realloc(StringBuffer *s, int new_len, int c) +{ + JSString *new_str; + int new_size; + size_t new_size_bytes, slack; + + if (s->error_status) + return -1; + + if (new_len > JS_STRING_LEN_MAX) { + JS_ThrowRangeError(s->ctx, "invalid string length"); + return string_buffer_set_error(s); + } + new_size = min_int(max_int(new_len, s->size * 3 / 2), JS_STRING_LEN_MAX); + if (!s->is_wide_char && c >= 0x100) { + return string_buffer_widen(s, new_size); + } + new_size_bytes = sizeof(JSString) + (new_size << s->is_wide_char) + 1 - s->is_wide_char; + new_str = js_realloc2(s->ctx, s->str, new_size_bytes, &slack); + if (!new_str) + return string_buffer_set_error(s); + new_size = min_int(new_size + (slack >> s->is_wide_char), JS_STRING_LEN_MAX); + s->size = new_size; + s->str = new_str; + return 0; +} + +static no_inline int string_buffer_putc16_slow(StringBuffer *s, uint32_t c) +{ + if (unlikely(s->len >= s->size)) { + if (string_buffer_realloc(s, s->len + 1, c)) + return -1; + } + if (s->is_wide_char) { + str16(s->str)[s->len++] = c; + } else if (c < 0x100) { + str8(s->str)[s->len++] = c; + } else { + if (string_buffer_widen(s, s->size)) + return -1; + str16(s->str)[s->len++] = c; + } + return 0; +} + +/* 0 <= c <= 0xff */ +static int string_buffer_putc8(StringBuffer *s, uint32_t c) +{ + if (unlikely(s->len >= s->size)) { + if (string_buffer_realloc(s, s->len + 1, c)) + return -1; + } + if (s->is_wide_char) { + str16(s->str)[s->len++] = c; + } else { + str8(s->str)[s->len++] = c; + } + return 0; +} + +/* 0 <= c <= 0xffff */ +static int string_buffer_putc16(StringBuffer *s, uint32_t c) +{ + if (likely(s->len < s->size)) { + if (s->is_wide_char) { + str16(s->str)[s->len++] = c; + return 0; + } else if (c < 0x100) { + str8(s->str)[s->len++] = c; + return 0; + } + } + return string_buffer_putc16_slow(s, c); +} + +/* 0 <= c <= 0x10ffff */ +static no_inline int string_buffer_putc_slow(StringBuffer *s, uint32_t c) +{ + if (c >= 0x10000) { + /* surrogate pair */ + if (string_buffer_putc16(s, get_hi_surrogate(c))) + return -1; + c = get_lo_surrogate(c); + } + return string_buffer_putc16(s, c); +} + +/* 0 <= c <= 0x10ffff */ +static inline int string_buffer_putc(StringBuffer *s, uint32_t c) +{ + if (likely(s->len < s->size)) { + if (s->is_wide_char) { + if (c < 0x10000) { + str16(s->str)[s->len++] = c; + return 0; + } else if (s->len + 1 < s->size) { + /* surrogate pair */ + str16(s->str)[s->len++] = get_hi_surrogate(c); + str16(s->str)[s->len++] = get_lo_surrogate(c); + return 0; + } + } else if (c < 0x100) { + str8(s->str)[s->len++] = c; + return 0; + } + } + return string_buffer_putc_slow(s, c); +} + +static int string_getc(JSString *p, int *pidx) +{ + int idx, c, c1; + idx = *pidx; + if (p->is_wide_char) { + c = str16(p)[idx++]; + if (is_hi_surrogate(c) && idx < p->len) { + c1 = str16(p)[idx]; + if (is_lo_surrogate(c1)) { + c = from_surrogate(c, c1); + idx++; + } + } + } else { + c = str8(p)[idx++]; + } + *pidx = idx; + return c; +} + +static int string_buffer_write8(StringBuffer *s, const uint8_t *p, int len) +{ + int i; + + if (s->len + len > s->size) { + if (string_buffer_realloc(s, s->len + len, 0)) + return -1; + } + if (s->is_wide_char) { + for (i = 0; i < len; i++) { + str16(s->str)[s->len + i] = p[i]; + } + s->len += len; + } else { + memcpy(&str8(s->str)[s->len], p, len); + s->len += len; + } + return 0; +} + +static int string_buffer_write16(StringBuffer *s, const uint16_t *p, int len) +{ + int c = 0, i; + + for (i = 0; i < len; i++) { + c |= p[i]; + } + if (s->len + len > s->size) { + if (string_buffer_realloc(s, s->len + len, c)) + return -1; + } else if (!s->is_wide_char && c >= 0x100) { + if (string_buffer_widen(s, s->size)) + return -1; + } + if (s->is_wide_char) { + memcpy(&str16(s->str)[s->len], p, len << 1); + s->len += len; + } else { + for (i = 0; i < len; i++) { + str8(s->str)[s->len + i] = p[i]; + } + s->len += len; + } + return 0; +} + +/* appending an ASCII string */ +static int string_buffer_puts8(StringBuffer *s, const char *str) +{ + return string_buffer_write8(s, (const uint8_t *)str, strlen(str)); +} + +static int string_buffer_concat(StringBuffer *s, JSString *p, + uint32_t from, uint32_t to) +{ + if (to <= from) + return 0; + if (p->is_wide_char) + return string_buffer_write16(s, str16(p) + from, to - from); + else + return string_buffer_write8(s, str8(p) + from, to - from); +} + +static int string_buffer_concat_value(StringBuffer *s, JSValueConst v) +{ + JSString *p; + JSValue v1; + int res; + int tag; + + if (s->error_status) { + /* prevent exception overload */ + return -1; + } + tag = JS_VALUE_GET_TAG(v); + if (tag == JS_TAG_STRING_ROPE) { + /* recursively concatenate rope children */ + JSStringRope *r = JS_VALUE_GET_STRING_ROPE(v); + if (string_buffer_concat_value(s, r->left)) + return -1; + return string_buffer_concat_value(s, r->right); + } + if (unlikely(tag != JS_TAG_STRING)) { + v1 = JS_ToString(s->ctx, v); + if (JS_IsException(v1)) + return string_buffer_set_error(s); + p = JS_VALUE_GET_STRING(v1); + res = string_buffer_concat(s, p, 0, p->len); + JS_FreeValue(s->ctx, v1); + return res; + } + p = JS_VALUE_GET_STRING(v); + return string_buffer_concat(s, p, 0, p->len); +} + +static int string_buffer_concat_value_free(StringBuffer *s, JSValue v) +{ + JSString *p; + int res; + int tag; + + if (s->error_status) { + /* prevent exception overload */ + JS_FreeValue(s->ctx, v); + return -1; + } + tag = JS_VALUE_GET_TAG(v); + if (tag == JS_TAG_STRING_ROPE) { + /* concatenate rope (don't free since concat_value doesn't free) */ + res = string_buffer_concat_value(s, v); + JS_FreeValue(s->ctx, v); + return res; + } + if (unlikely(tag != JS_TAG_STRING)) { + v = JS_ToStringFree(s->ctx, v); + if (JS_IsException(v)) + return string_buffer_set_error(s); + } + p = JS_VALUE_GET_STRING(v); + res = string_buffer_concat(s, p, 0, p->len); + JS_FreeValue(s->ctx, v); + return res; +} + +static int string_buffer_fill(StringBuffer *s, int c, int count) +{ + /* XXX: optimize */ + if (s->len + count > s->size) { + if (string_buffer_realloc(s, s->len + count, c)) + return -1; + } + while (count-- > 0) { + if (string_buffer_putc16(s, c)) + return -1; + } + return 0; +} + +static JSValue string_buffer_end(StringBuffer *s) +{ + JSString *str; + str = s->str; + if (s->error_status) + return JS_EXCEPTION; + if (s->len == 0) { + js_free(s->ctx, str); + s->str = NULL; + return js_empty_string(s->ctx->rt); + } + if (s->len < s->size) { + /* smaller size so js_realloc should not fail, but OK if it does */ + /* XXX: should add some slack to avoid unnecessary calls */ + /* XXX: might need to use malloc+free to ensure smaller size */ + str = js_realloc_rt(s->ctx->rt, str, sizeof(JSString) + + (s->len << s->is_wide_char) + 1 - s->is_wide_char); + if (str == NULL) + str = s->str; + s->str = str; + } + if (!s->is_wide_char) + str8(str)[s->len] = 0; +#ifdef ENABLE_DUMPS // JS_DUMP_LEAKS + list_add_tail(&str->link, &s->ctx->rt->string_list); +#endif + str->is_wide_char = s->is_wide_char; + str->len = s->len; + s->str = NULL; + return JS_MKPTR(JS_TAG_STRING, str); +} + +/* create a string from a UTF-8 buffer */ +JSValue JS_NewStringLen(JSContext *ctx, const char *buf, size_t buf_len) +{ + JSString *str; + size_t len; + int kind; + + if (buf_len <= 0) { + return js_empty_string(ctx->rt); + } + /* Compute string kind and length: 7-bit, 8-bit, 16-bit, 16-bit UTF-16 */ + kind = utf8_scan(buf, buf_len, &len); + if (len > JS_STRING_LEN_MAX) + return JS_ThrowRangeError(ctx, "invalid string length"); + + switch (kind) { + case UTF8_PLAIN_ASCII: + str = js_alloc_string(ctx, len, 0); + if (!str) + return JS_EXCEPTION; + memcpy(str8(str), buf, len); + str8(str)[len] = '\0'; + break; + case UTF8_NON_ASCII: + /* buf contains non-ASCII code-points, but limited to 8-bit values */ + str = js_alloc_string(ctx, len, 0); + if (!str) + return JS_EXCEPTION; + utf8_decode_buf8(str8(str), len + 1, buf, buf_len); + break; + default: + // This causes a potential problem in JS_ThrowError if message is invalid + //if (kind & UTF8_HAS_ERRORS) + // return JS_ThrowRangeError(ctx, "invalid UTF-8 sequence"); + str = js_alloc_string(ctx, len, 1); + if (!str) + return JS_EXCEPTION; + utf8_decode_buf16(str16(str), len, buf, buf_len); + break; + } + return JS_MKPTR(JS_TAG_STRING, str); +} + +JSValue JS_NewStringUTF16(JSContext *ctx, const uint16_t *buf, size_t len) +{ + JSString *str; + + if (!len) + return js_empty_string(ctx->rt); + str = js_alloc_string(ctx, len, 1); + if (!str) + return JS_EXCEPTION; + memcpy(str16(str), buf, len * sizeof(*buf)); + return JS_MKPTR(JS_TAG_STRING, str); +} + +static JSValue JS_ConcatString3(JSContext *ctx, const char *str1, + JSValue str2, const char *str3) +{ + StringBuffer b_s, *b = &b_s; + int len1, len3; + JSString *p; + + if (unlikely(JS_VALUE_GET_TAG(str2) != JS_TAG_STRING)) { + str2 = JS_ToStringFree(ctx, str2); + if (JS_IsException(str2)) + goto fail; + } + p = JS_VALUE_GET_STRING(str2); + len1 = strlen(str1); + len3 = strlen(str3); + + if (string_buffer_init2(ctx, b, len1 + p->len + len3, p->is_wide_char)) + goto fail; + + string_buffer_write8(b, (const uint8_t *)str1, len1); + string_buffer_concat(b, p, 0, p->len); + string_buffer_write8(b, (const uint8_t *)str3, len3); + + JS_FreeValue(ctx, str2); + return string_buffer_end(b); + + fail: + JS_FreeValue(ctx, str2); + return JS_EXCEPTION; +} + +/* `str` may be pure ASCII or UTF-8 encoded */ +JSValue JS_NewAtomString(JSContext *ctx, const char *str) +{ + JSAtom atom = JS_NewAtom(ctx, str); + if (atom == JS_ATOM_NULL) + return JS_EXCEPTION; + JSValue val = JS_AtomToString(ctx, atom); + JS_FreeAtom(ctx, atom); + return val; +} + +static JSValue js_force_tostring(JSContext *ctx, JSValueConst val1) +{ + JSObject *p; + JSValue val; + + if (JS_VALUE_GET_TAG(val1) == JS_TAG_STRING) + return js_dup(val1); + val = JS_ToString(ctx, val1); + if (!JS_IsException(val)) + return val; + // Stringification can fail when there is an exception pending, + // e.g. a stack overflow InternalError. Special-case exception + // objects to make debugging easier, look up the .message property + // and stringify that. + if (JS_VALUE_GET_TAG(val1) != JS_TAG_OBJECT) + return JS_EXCEPTION; + p = JS_VALUE_GET_OBJ(val1); + if (p->class_id != JS_CLASS_ERROR) + return JS_EXCEPTION; + val = JS_GetProperty(ctx, val1, JS_ATOM_message); + if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) { + JS_FreeValue(ctx, val); + return JS_EXCEPTION; + } + return val; +} + +/* return (NULL, 0) if exception. */ +/* return pointer into a JSString with a live ref_count */ +/* cesu8 determines if non-BMP1 codepoints are encoded as 1 or 2 utf-8 sequences */ +const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, + bool cesu8) +{ + JSValue val; + JSString *str, *str_new; + int pos, len, c, c1; + uint8_t *q; + + val = js_force_tostring(ctx, val1); + if (JS_IsException(val)) + goto fail; + str = JS_VALUE_GET_STRING(val); + len = str->len; + if (!str->is_wide_char) { + const uint8_t *src = str8(str); + int count; + + /* count the number of non-ASCII characters */ + /* Scanning the whole string is required for ASCII strings, + and computing the number of non-ASCII bytes is less expensive + than testing each byte, hence this method is faster for ASCII + strings, which is the most common case. + */ + count = 0; + for (pos = 0; pos < len; pos++) { + count += src[pos] >> 7; + } + if (count == 0 && str->kind == JS_STRING_KIND_NORMAL) { + if (plen) + *plen = len; + return (const char *)src; + } + str_new = js_alloc_string(ctx, len + count, 0); + if (!str_new) + goto fail; + q = str8(str_new); + for (pos = 0; pos < len; pos++) { + c = src[pos]; + if (c < 0x80) { + *q++ = c; + } else { + *q++ = (c >> 6) | 0xc0; + *q++ = (c & 0x3f) | 0x80; + } + } + } else { + const uint16_t *src = str16(str); + /* Allocate 3 bytes per 16 bit code point. Surrogate pairs may + produce 4 bytes but use 2 code points. + */ + str_new = js_alloc_string(ctx, len * 3, 0); + if (!str_new) + goto fail; + q = str8(str_new); + pos = 0; + while (pos < len) { + c = src[pos++]; + if (c < 0x80) { + *q++ = c; + } else { + if (is_hi_surrogate(c)) { + if (pos < len && !cesu8) { + c1 = src[pos]; + if (is_lo_surrogate(c1)) { + pos++; + c = from_surrogate(c, c1); + } else { + /* Keep unmatched surrogate code points */ + /* c = 0xfffd; */ /* error */ + } + } else { + /* Keep unmatched surrogate code points */ + /* c = 0xfffd; */ /* error */ + } + } + q += utf8_encode(q, c); + } + } + } + + *q = '\0'; + str_new->len = q - str8(str_new); + JS_FreeValue(ctx, val); + if (plen) + *plen = str_new->len; + return (const char *)str8(str_new); +fail: + if (plen) + *plen = 0; + return NULL; +} + +const uint16_t *JS_ToCStringLenUTF16(JSContext *ctx, size_t *plen, + JSValueConst val1) +{ + JSString *p, *q; + uint32_t i; + JSValue v; + + v = js_force_tostring(ctx, val1); + if (JS_IsException(v)) + goto fail; + p = JS_VALUE_GET_STRING(v); + if (!p->is_wide_char) { + q = js_alloc_string(ctx, p->len, /*is_wide_char*/true); + if (!q) + goto fail; + for (i = 0; i < p->len; i++) + str16(q)[i] = str8(p)[i]; + JS_FreeValue(ctx, v); + p = q; + } + if (plen) + *plen = p->len; + return str16(p); +fail: + JS_FreeValue(ctx, v); + if (plen) + *plen = 0; + return NULL; +} + +static void js_free_cstring(JSRuntime *rt, const void *ptr) +{ + if (!ptr) + return; + /* purposely removing constness */ + JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, (JSString *)ptr - 1)); +} + +void JS_FreeCString(JSContext *ctx, const char *ptr) +{ + return js_free_cstring(ctx->rt, ptr); +} + +void JS_FreeCStringRT(JSRuntime *rt, const char *ptr) +{ + return js_free_cstring(rt, ptr); +} + +void JS_FreeCStringUTF16(JSContext *ctx, const uint16_t *ptr) +{ + return js_free_cstring(ctx->rt, ptr); +} + +void JS_FreeCStringRT_UTF16(JSRuntime *rt, const uint16_t *ptr) +{ + return js_free_cstring(rt, ptr); +} + +static int memcmp16_8(const uint16_t *src1, const uint8_t *src2, int len) +{ + int c, i; + for(i = 0; i < len; i++) { + c = src1[i] - src2[i]; + if (c != 0) + return c; + } + return 0; +} + +static int memcmp16(const uint16_t *src1, const uint16_t *src2, int len) +{ + int c, i; + for(i = 0; i < len; i++) { + c = src1[i] - src2[i]; + if (c != 0) + return c; + } + return 0; +} + +static int js_string_memcmp(JSString *p1, JSString *p2, int len) +{ + int res; + + if (likely(!p1->is_wide_char)) { + if (likely(!p2->is_wide_char)) + res = memcmp(str8(p1), str8(p2), len); + else + res = -memcmp16_8(str16(p2), str8(p1), len); + } else { + if (!p2->is_wide_char) + res = memcmp16_8(str16(p1), str8(p2), len); + else + res = memcmp16(str16(p1), str16(p2), len); + } + return res; +} + +static bool js_string_eq(JSString *p1, JSString *p2) { + if (p1->len != p2->len) + return false; + return js_string_memcmp(p1, p2, p1->len) == 0; +} + +/* return < 0, 0 or > 0 */ +static int js_string_compare(JSString *p1, JSString *p2) +{ + int res, len; + len = min_int(p1->len, p2->len); + res = js_string_memcmp(p1, p2, len); + if (res == 0) + res = compare_u32(p1->len, p2->len); + return res; +} + +/* Rope string support functions */ + +static inline bool tag_is_string(int tag) +{ + return tag == JS_TAG_STRING || tag == JS_TAG_STRING_ROPE; +} + +static uint32_t string_rope_get_len(JSValueConst val) +{ + if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING) + return JS_VALUE_GET_STRING(val)->len; + else + return JS_VALUE_GET_STRING_ROPE(val)->len; +} + +static int string_rope_get(JSValueConst val, uint32_t idx) +{ + if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING) { + return string_get(JS_VALUE_GET_STRING(val), idx); + } else { + JSStringRope *r = JS_VALUE_GET_STRING_ROPE(val); + uint32_t len; + if (JS_VALUE_GET_TAG(r->left) == JS_TAG_STRING) + len = JS_VALUE_GET_STRING(r->left)->len; + else + len = JS_VALUE_GET_STRING_ROPE(r->left)->len; + if (idx < len) + return string_rope_get(r->left, idx); + else + return string_rope_get(r->right, idx - len); + } +} + +typedef struct { + JSValueConst stack[JS_STRING_ROPE_MAX_DEPTH]; + int stack_len; +} JSStringRopeIter; + +static void string_rope_iter_init(JSStringRopeIter *s, JSValueConst val) +{ + s->stack_len = 0; + s->stack[s->stack_len++] = val; +} + +/* iterate thru a rope and return the strings in order */ +static JSString *string_rope_iter_next(JSStringRopeIter *s) +{ + JSValueConst val; + JSStringRope *r; + + if (s->stack_len == 0) + return NULL; + val = s->stack[--s->stack_len]; + for(;;) { + if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING) + return JS_VALUE_GET_STRING(val); + r = JS_VALUE_GET_STRING_ROPE(val); + assert(s->stack_len < JS_STRING_ROPE_MAX_DEPTH); + s->stack[s->stack_len++] = r->right; + val = r->left; + } +} + +/* compare two string values with position offsets */ +static int js_string_memcmp_pos(JSString *p1, uint32_t pos1, + JSString *p2, uint32_t pos2, uint32_t len) +{ + int res; + + if (likely(!p1->is_wide_char)) { + if (likely(!p2->is_wide_char)) + res = memcmp(str8(p1) + pos1, str8(p2) + pos2, len); + else + res = -memcmp16_8(str16(p2) + pos2, str8(p1) + pos1, len); + } else { + if (!p2->is_wide_char) + res = memcmp16_8(str16(p1) + pos1, str8(p2) + pos2, len); + else + res = memcmp16(str16(p1) + pos1, str16(p2) + pos2, len); + } + return res; +} + +static int js_string_rope_compare(JSValueConst op1, + JSValueConst op2, bool eq_only) +{ + uint32_t len1, len2, len, pos1, pos2, l; + int res; + JSStringRopeIter it1, it2; + JSString *p1, *p2; + + len1 = string_rope_get_len(op1); + len2 = string_rope_get_len(op2); + /* no need to go further for equality test if different length */ + if (eq_only && len1 != len2) + return 1; + len = min_uint32(len1, len2); + string_rope_iter_init(&it1, op1); + string_rope_iter_init(&it2, op2); + p1 = string_rope_iter_next(&it1); + p2 = string_rope_iter_next(&it2); + pos1 = 0; + pos2 = 0; + while (len != 0) { + l = min_uint32(p1->len - pos1, p2->len - pos2); + l = min_uint32(l, len); + res = js_string_memcmp_pos(p1, pos1, p2, pos2, l); + if (res != 0) + return res; + len -= l; + pos1 += l; + if (pos1 >= p1->len) { + p1 = string_rope_iter_next(&it1); + pos1 = 0; + } + pos2 += l; + if (pos2 >= p2->len) { + p2 = string_rope_iter_next(&it2); + pos2 = 0; + } + } + + if (len1 == len2) + res = 0; + else if (len1 < len2) + res = -1; + else + res = 1; + return res; +} + +/* forward declaration */ +static int string_buffer_concat_value(StringBuffer *s, JSValueConst v); +static JSValue js_rebalance_string_rope(JSContext *ctx, JSValueConst rope); + +/* op1 and op2 must be strings or string ropes */ +static JSValue js_new_string_rope(JSContext *ctx, JSValue op1, JSValue op2) +{ + uint32_t len; + int is_wide_char, depth; + JSStringRope *r; + JSValue res; + + if (JS_VALUE_GET_TAG(op1) == JS_TAG_STRING) { + JSString *p1 = JS_VALUE_GET_STRING(op1); + len = p1->len; + is_wide_char = p1->is_wide_char; + depth = 0; + } else { + JSStringRope *r1 = JS_VALUE_GET_STRING_ROPE(op1); + len = r1->len; + is_wide_char = r1->is_wide_char; + depth = r1->depth; + } + + if (JS_VALUE_GET_TAG(op2) == JS_TAG_STRING) { + JSString *p2 = JS_VALUE_GET_STRING(op2); + len += p2->len; + is_wide_char |= p2->is_wide_char; + } else { + JSStringRope *r2 = JS_VALUE_GET_STRING_ROPE(op2); + len += r2->len; + is_wide_char |= r2->is_wide_char; + depth = max_int(depth, r2->depth); + } + if (len > JS_STRING_LEN_MAX) { + JS_ThrowInternalError(ctx, "string too long"); + goto fail; + } + r = js_malloc(ctx, sizeof(*r)); + if (!r) + goto fail; + r->header.ref_count = 1; + r->len = len; + r->is_wide_char = is_wide_char; + r->depth = depth + 1; + r->left = op1; + r->right = op2; + res = JS_MKPTR(JS_TAG_STRING_ROPE, r); + if (r->depth > JS_STRING_ROPE_MAX_DEPTH) { + JSValue res2; +#ifdef DUMP_ROPE_REBALANCE + printf("rebalance: initial depth=%d\n", r->depth); +#endif + res2 = js_rebalance_string_rope(ctx, res); +#ifdef DUMP_ROPE_REBALANCE + if (JS_VALUE_GET_TAG(res2) == JS_TAG_STRING_ROPE) + printf("rebalance: final depth=%d\n", JS_VALUE_GET_STRING_ROPE(res2)->depth); +#endif + JS_FreeValue(ctx, res); + return res2; + } else { + return res; + } + fail: + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + return JS_EXCEPTION; +} + +#define ROPE_N_BUCKETS 44 + +/* Fibonacci numbers starting from F_2 */ +static const uint32_t rope_bucket_len[ROPE_N_BUCKETS] = { + 1, 2, 3, 5, + 8, 13, 21, 34, + 55, 89, 144, 233, + 377, 610, 987, 1597, + 2584, 4181, 6765, 10946, + 17711, 28657, 46368, 75025, + 121393, 196418, 317811, 514229, + 832040, 1346269, 2178309, 3524578, + 5702887, 9227465, 14930352, 24157817, + 39088169, 63245986, 102334155, 165580141, + 267914296, 433494437, 701408733, 1134903170, /* > JS_STRING_LEN_MAX */ +}; + +static int js_rebalance_string_rope_rec(JSContext *ctx, JSValue *buckets, + JSValueConst val) +{ + if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING) { + JSString *p = JS_VALUE_GET_STRING(val); + uint32_t len, i; + JSValue a, b; + + len = p->len; + if (len == 0) + return 0; /* nothing to do */ + /* find the bucket i so that rope_bucket_len[i] <= len < + rope_bucket_len[i + 1] and concatenate the ropes in the + buckets before */ + a = JS_NULL; + i = 0; + while (len >= rope_bucket_len[i + 1]) { + b = buckets[i]; + if (!JS_IsNull(b)) { + buckets[i] = JS_NULL; + if (JS_IsNull(a)) { + a = b; + } else { + a = js_new_string_rope(ctx, b, a); + if (JS_IsException(a)) + return -1; + } + } + i++; + } + if (!JS_IsNull(a)) { + a = js_new_string_rope(ctx, a, js_dup(val)); + if (JS_IsException(a)) + return -1; + } else { + a = js_dup(val); + } + while (!JS_IsNull(buckets[i])) { + a = js_new_string_rope(ctx, buckets[i], a); + buckets[i] = JS_NULL; + if (JS_IsException(a)) + return -1; + i++; + } + buckets[i] = a; + } else { + JSStringRope *r = JS_VALUE_GET_STRING_ROPE(val); + if (js_rebalance_string_rope_rec(ctx, buckets, r->left)) + return -1; + if (js_rebalance_string_rope_rec(ctx, buckets, r->right)) + return -1; + } + return 0; +} + +/* Return a new rope which is balanced. Algorithm from "Ropes: an + Alternative to Strings", Hans-J. Boehm, Russ Atkinson and Michael + Plass. */ +static JSValue js_rebalance_string_rope(JSContext *ctx, JSValueConst rope) +{ + JSValue buckets[ROPE_N_BUCKETS], a, b; + int i; + + for(i = 0; i < ROPE_N_BUCKETS; i++) + buckets[i] = JS_NULL; + if (js_rebalance_string_rope_rec(ctx, buckets, rope)) + goto fail; + a = JS_NULL; + for(i = 0; i < ROPE_N_BUCKETS; i++) { + b = buckets[i]; + if (!JS_IsNull(b)) { + buckets[i] = JS_NULL; + if (JS_IsNull(a)) { + a = b; + } else { + a = js_new_string_rope(ctx, b, a); + if (JS_IsException(a)) + goto fail; + } + } + } + /* fail safe */ + if (JS_IsNull(a)) + return JS_AtomToString(ctx, JS_ATOM_empty_string); + else + return a; + fail: + for(i = 0; i < ROPE_N_BUCKETS; i++) { + JS_FreeValue(ctx, buckets[i]); + } + return JS_EXCEPTION; +} + +/* 'rope' must be a rope. return a string and modify the rope so that + it won't need to be linearized again. */ +static JSValue js_linearize_string_rope(JSContext *ctx, JSValueConst rope) +{ + StringBuffer b_s, *b = &b_s; + JSStringRope *r; + JSValue ret; + + r = JS_VALUE_GET_STRING_ROPE(rope); + + /* check whether it is already linearized */ + if (JS_VALUE_GET_TAG(r->right) == JS_TAG_STRING && + JS_VALUE_GET_STRING(r->right)->len == 0) { + ret = js_dup(r->left); + return ret; + } + if (string_buffer_init2(ctx, b, r->len, r->is_wide_char)) + goto fail; + if (string_buffer_concat_value(b, rope)) + goto fail; + ret = string_buffer_end(b); + if (r->header.ref_count > 1) { + /* update the rope so that it won't need to be linearized again */ + JS_FreeValue(ctx, r->left); + JS_FreeValue(ctx, r->right); + r->left = js_dup(ret); + r->right = JS_AtomToString(ctx, JS_ATOM_empty_string); + } + return ret; + fail: + return JS_EXCEPTION; +} + +/* flat string concatenation - used by rope when concatenating short strings */ +static JSValue JS_ConcatString2(JSContext *ctx, JSValue op1, JSValue op2); + +static void copy_str16(uint16_t *dst, JSString *p, int offset, int len) +{ + if (p->is_wide_char) { + memcpy(dst, str16(p) + offset, len * 2); + } else { + const uint8_t *src1 = str8(p) + offset; + int i; + + for(i = 0; i < len; i++) + dst[i] = src1[i]; + } +} + +static JSValue JS_ConcatString1(JSContext *ctx, JSString *p1, JSString *p2) +{ + JSString *p; + uint32_t len; + int is_wide_char; + + len = p1->len + p2->len; + if (len > JS_STRING_LEN_MAX) + return JS_ThrowRangeError(ctx, "invalid string length"); + is_wide_char = p1->is_wide_char | p2->is_wide_char; + p = js_alloc_string(ctx, len, is_wide_char); + if (!p) + return JS_EXCEPTION; + if (!is_wide_char) { + memcpy(str8(p), str8(p1), p1->len); + memcpy(str8(p) + p1->len, str8(p2), p2->len); + str8(p)[len] = '\0'; + } else { + copy_str16(str16(p), p1, 0, p1->len); + copy_str16(str16(p) + p1->len, p2, 0, p2->len); + } + return JS_MKPTR(JS_TAG_STRING, p); +} + +/* flat string concatenation - op1 and op2 must be JS_TAG_STRING */ +static JSValue JS_ConcatString2(JSContext *ctx, JSValue op1, JSValue op2) +{ + JSValue ret; + JSString *p1, *p2; + + p1 = JS_VALUE_GET_STRING(op1); + p2 = JS_VALUE_GET_STRING(op2); + + /* XXX: could also check if p1 is empty */ + if (p2->len == 0) { + goto ret_op1; + } + if (p1->header.ref_count == 1 && p1->is_wide_char == p2->is_wide_char + && js_malloc_usable_size(ctx, p1) >= sizeof(*p1) + ((p1->len + p2->len) << p2->is_wide_char) + 1 - p1->is_wide_char) { + /* Concatenate in place in available space at the end of p1 */ + if (p1->is_wide_char) { + memcpy(str16(p1) + p1->len, str16(p2), p2->len << 1); + p1->len += p2->len; + } else { + memcpy(str8(p1) + p1->len, str8(p2), p2->len); + p1->len += p2->len; + str8(p1)[p1->len] = '\0'; + } + ret_op1: + JS_FreeValue(ctx, op2); + return op1; + } + ret = JS_ConcatString1(ctx, p1, p2); + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + return ret; +} + +/* op1 and op2 are converted to strings. For convenience, op1 or op2 = + JS_EXCEPTION are accepted and return JS_EXCEPTION. */ +static JSValue JS_ConcatString(JSContext *ctx, JSValue op1, JSValue op2) +{ + JSString *p1, *p2; + + if (unlikely(!tag_is_string(JS_VALUE_GET_TAG(op1)))) { + op1 = JS_ToStringFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + return JS_EXCEPTION; + } + } + if (unlikely(!tag_is_string(JS_VALUE_GET_TAG(op2)))) { + op2 = JS_ToStringFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + return JS_EXCEPTION; + } + } + + /* normal concatenation for short strings */ + if (JS_VALUE_GET_TAG(op2) == JS_TAG_STRING) { + p2 = JS_VALUE_GET_STRING(op2); + if (p2->len == 0) { + JS_FreeValue(ctx, op2); + return op1; + } + if (p2->len <= JS_STRING_ROPE_SHORT_LEN) { + if (JS_VALUE_GET_TAG(op1) == JS_TAG_STRING) { + p1 = JS_VALUE_GET_STRING(op1); + if (p1->len <= JS_STRING_ROPE_SHORT2_LEN) { + return JS_ConcatString2(ctx, op1, op2); + } else { + return js_new_string_rope(ctx, op1, op2); + } + } else { + JSStringRope *r1; + r1 = JS_VALUE_GET_STRING_ROPE(op1); + if (JS_VALUE_GET_TAG(r1->right) == JS_TAG_STRING && + JS_VALUE_GET_STRING(r1->right)->len <= JS_STRING_ROPE_SHORT_LEN) { + JSValue val, ret; + val = JS_ConcatString2(ctx, js_dup(r1->right), op2); + if (JS_IsException(val)) { + JS_FreeValue(ctx, op1); + return JS_EXCEPTION; + } + ret = js_new_string_rope(ctx, js_dup(r1->left), val); + JS_FreeValue(ctx, op1); + return ret; + } + } + } + } else if (JS_VALUE_GET_TAG(op1) == JS_TAG_STRING) { + JSStringRope *r2; + p1 = JS_VALUE_GET_STRING(op1); + if (p1->len == 0) { + JS_FreeValue(ctx, op1); + return op2; + } + r2 = JS_VALUE_GET_STRING_ROPE(op2); + if (JS_VALUE_GET_TAG(r2->left) == JS_TAG_STRING && + JS_VALUE_GET_STRING(r2->left)->len <= JS_STRING_ROPE_SHORT_LEN) { + JSValue val, ret; + val = JS_ConcatString2(ctx, op1, js_dup(r2->left)); + if (JS_IsException(val)) { + JS_FreeValue(ctx, op2); + return JS_EXCEPTION; + } + ret = js_new_string_rope(ctx, val, js_dup(r2->right)); + JS_FreeValue(ctx, op2); + return ret; + } + } + return js_new_string_rope(ctx, op1, op2); +} + +/* Shape support */ + +static inline size_t get_shape_size(size_t hash_size, size_t prop_size) +{ + return hash_size * sizeof(uint32_t) + sizeof(JSShape) + + prop_size * sizeof(JSShapeProperty); +} + +static inline JSShape *get_shape_from_alloc(void *sh_alloc, size_t hash_size) +{ + return (JSShape *)(void *)((uint32_t *)sh_alloc + hash_size); +} + +static inline uint32_t *prop_hash_end(JSShape *sh) +{ + return (uint32_t *)sh; +} + +static inline void *get_alloc_from_shape(JSShape *sh) +{ + return prop_hash_end(sh) - ((intptr_t)sh->prop_hash_mask + 1); +} + +static inline JSShapeProperty *get_shape_prop(JSShape *sh) +{ + return sh->prop; +} + +static int init_shape_hash(JSRuntime *rt) +{ + rt->shape_hash_bits = 6; /* 64 shapes */ + rt->shape_hash_size = 1 << rt->shape_hash_bits; + rt->shape_hash_count = 0; + rt->shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) * + rt->shape_hash_size); + if (!rt->shape_hash) + return -1; + return 0; +} + +/* same magic hash multiplier as the Linux kernel */ +static uint32_t shape_hash(uint32_t h, uint32_t val) +{ + return (h + val) * 0x9e370001; +} + +/* truncate the shape hash to 'hash_bits' bits */ +static uint32_t get_shape_hash(uint32_t h, int hash_bits) +{ + return h >> (32 - hash_bits); +} + +static uint32_t shape_initial_hash(JSObject *proto) +{ + uint32_t h; + h = shape_hash(1, (uintptr_t)proto); + if (sizeof(proto) > 4) + h = shape_hash(h, (uint64_t)(uintptr_t)proto >> 32); + return h; +} + +static int resize_shape_hash(JSRuntime *rt, int new_shape_hash_bits) +{ + int new_shape_hash_size, i; + uint32_t h; + JSShape **new_shape_hash, *sh, *sh_next; + + new_shape_hash_size = 1 << new_shape_hash_bits; + new_shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) * + new_shape_hash_size); + if (!new_shape_hash) + return -1; + for(i = 0; i < rt->shape_hash_size; i++) { + for(sh = rt->shape_hash[i]; sh != NULL; sh = sh_next) { + sh_next = sh->shape_hash_next; + h = get_shape_hash(sh->hash, new_shape_hash_bits); + sh->shape_hash_next = new_shape_hash[h]; + new_shape_hash[h] = sh; + } + } + js_free_rt(rt, rt->shape_hash); + rt->shape_hash_bits = new_shape_hash_bits; + rt->shape_hash_size = new_shape_hash_size; + rt->shape_hash = new_shape_hash; + return 0; +} + +static void js_shape_hash_link(JSRuntime *rt, JSShape *sh) +{ + uint32_t h; + h = get_shape_hash(sh->hash, rt->shape_hash_bits); + sh->shape_hash_next = rt->shape_hash[h]; + rt->shape_hash[h] = sh; + rt->shape_hash_count++; +} + +static void js_shape_hash_unlink(JSRuntime *rt, JSShape *sh) +{ + uint32_t h; + JSShape **psh; + + h = get_shape_hash(sh->hash, rt->shape_hash_bits); + psh = &rt->shape_hash[h]; + while (*psh != sh) + psh = &(*psh)->shape_hash_next; + *psh = sh->shape_hash_next; + rt->shape_hash_count--; +} + +/* create a new empty shape with prototype 'proto' */ +static no_inline JSShape *js_new_shape2(JSContext *ctx, JSObject *proto, + int hash_size, int prop_size) +{ + JSRuntime *rt = ctx->rt; + void *sh_alloc; + JSShape *sh; + + /* resize the shape hash table if necessary */ + if (2 * (rt->shape_hash_count + 1) > rt->shape_hash_size) { + resize_shape_hash(rt, rt->shape_hash_bits + 1); + } + + sh_alloc = js_malloc(ctx, get_shape_size(hash_size, prop_size)); + if (!sh_alloc) + return NULL; + sh = get_shape_from_alloc(sh_alloc, hash_size); + sh->header.ref_count = 1; + add_gc_object(rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE); + if (proto) + js_dup(JS_MKPTR(JS_TAG_OBJECT, proto)); + sh->proto = proto; + memset(prop_hash_end(sh) - hash_size, 0, sizeof(prop_hash_end(sh)[0]) * + hash_size); + sh->prop_hash_mask = hash_size - 1; + sh->prop_size = prop_size; + sh->prop_count = 0; + sh->deleted_prop_count = 0; + + /* insert in the hash table */ + sh->hash = shape_initial_hash(proto); + sh->is_hashed = true; + js_shape_hash_link(ctx->rt, sh); + return sh; +} + +static JSShape *js_new_shape(JSContext *ctx, JSObject *proto) +{ + return js_new_shape2(ctx, proto, JS_PROP_INITIAL_HASH_SIZE, + JS_PROP_INITIAL_SIZE); +} + +/* The shape is cloned. The new shape is not inserted in the shape + hash table */ +static JSShape *js_clone_shape(JSContext *ctx, JSShape *sh1) +{ + JSShape *sh; + void *sh_alloc, *sh_alloc1; + size_t size; + JSShapeProperty *pr; + uint32_t i, hash_size; + + hash_size = sh1->prop_hash_mask + 1; + size = get_shape_size(hash_size, sh1->prop_size); + sh_alloc = js_malloc(ctx, size); + if (!sh_alloc) + return NULL; + sh_alloc1 = get_alloc_from_shape(sh1); + memcpy(sh_alloc, sh_alloc1, size); + sh = get_shape_from_alloc(sh_alloc, hash_size); + sh->header.ref_count = 1; + add_gc_object(ctx->rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE); + sh->is_hashed = false; + if (sh->proto) { + js_dup(JS_MKPTR(JS_TAG_OBJECT, sh->proto)); + } + for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) { + JS_DupAtom(ctx, pr->atom); + } + return sh; +} + +static JSShape *js_dup_shape(JSShape *sh) +{ + sh->header.ref_count++; + return sh; +} + +static void js_free_shape0(JSRuntime *rt, JSShape *sh) +{ + uint32_t i; + JSShapeProperty *pr; + + assert(sh->header.ref_count == 0); + if (sh->is_hashed) + js_shape_hash_unlink(rt, sh); + if (sh->proto != NULL) { + JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, sh->proto)); + } + pr = get_shape_prop(sh); + for(i = 0; i < sh->prop_count; i++) { + JS_FreeAtomRT(rt, pr->atom); + pr++; + } + remove_gc_object(&sh->header); + js_free_rt(rt, get_alloc_from_shape(sh)); +} + +static void js_free_shape(JSRuntime *rt, JSShape *sh) +{ + if (unlikely(--sh->header.ref_count <= 0)) { + js_free_shape0(rt, sh); + } +} + +static void js_free_shape_null(JSRuntime *rt, JSShape *sh) +{ + if (sh) + js_free_shape(rt, sh); +} + +/* make space to hold at least 'count' properties */ +static no_inline int resize_properties(JSContext *ctx, JSShape **psh, + JSObject *p, uint32_t count) +{ + JSShape *sh; + uint32_t new_size, new_hash_size, new_hash_mask, i; + JSShapeProperty *pr; + void *sh_alloc; + intptr_t h; + + sh = *psh; + new_size = max_int(count, sh->prop_size * 3 / 2); + /* Reallocate prop array first to avoid crash or size inconsistency + in case of memory allocation failure */ + if (p) { + JSProperty *new_prop; + new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size); + if (unlikely(!new_prop)) + return -1; + p->prop = new_prop; + } + new_hash_size = sh->prop_hash_mask + 1; + while (new_hash_size < new_size) + new_hash_size = 2 * new_hash_size; + if (new_hash_size != (sh->prop_hash_mask + 1)) { + JSShape *old_sh; + /* resize the hash table and the properties */ + old_sh = sh; + sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size)); + if (!sh_alloc) + return -1; + sh = get_shape_from_alloc(sh_alloc, new_hash_size); + list_del(&old_sh->header.link); + /* copy all the fields and the properties */ + memcpy(sh, old_sh, + sizeof(JSShape) + sizeof(sh->prop[0]) * old_sh->prop_count); + list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); + new_hash_mask = new_hash_size - 1; + sh->prop_hash_mask = new_hash_mask; + memset(prop_hash_end(sh) - new_hash_size, 0, + sizeof(prop_hash_end(sh)[0]) * new_hash_size); + for(i = 0, pr = sh->prop; i < sh->prop_count; i++, pr++) { + if (pr->atom != JS_ATOM_NULL) { + h = ((uintptr_t)pr->atom & new_hash_mask); + pr->hash_next = prop_hash_end(sh)[-h - 1]; + prop_hash_end(sh)[-h - 1] = i + 1; + } + } + js_free(ctx, get_alloc_from_shape(old_sh)); + } else { + /* only resize the properties */ + list_del(&sh->header.link); + sh_alloc = js_realloc(ctx, get_alloc_from_shape(sh), + get_shape_size(new_hash_size, new_size)); + if (unlikely(!sh_alloc)) { + /* insert again in the GC list */ + list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); + return -1; + } + sh = get_shape_from_alloc(sh_alloc, new_hash_size); + list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); + } + *psh = sh; + sh->prop_size = new_size; + return 0; +} + +/* remove the deleted properties. */ +static int compact_properties(JSContext *ctx, JSObject *p) +{ + JSShape *sh, *old_sh; + void *sh_alloc; + intptr_t h; + uint32_t new_hash_size, i, j, new_hash_mask, new_size; + JSShapeProperty *old_pr, *pr; + JSProperty *prop, *new_prop; + + sh = p->shape; + assert(!sh->is_hashed); + + new_size = max_int(JS_PROP_INITIAL_SIZE, + sh->prop_count - sh->deleted_prop_count); + assert(new_size <= sh->prop_size); + + new_hash_size = sh->prop_hash_mask + 1; + while ((new_hash_size / 2) >= new_size) + new_hash_size = new_hash_size / 2; + new_hash_mask = new_hash_size - 1; + + /* resize the hash table and the properties */ + old_sh = sh; + sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size)); + if (!sh_alloc) + return -1; + sh = get_shape_from_alloc(sh_alloc, new_hash_size); + list_del(&old_sh->header.link); + memcpy(sh, old_sh, sizeof(JSShape)); + list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); + + memset(prop_hash_end(sh) - new_hash_size, 0, + sizeof(prop_hash_end(sh)[0]) * new_hash_size); + + j = 0; + old_pr = old_sh->prop; + pr = sh->prop; + prop = p->prop; + for(i = 0; i < sh->prop_count; i++) { + if (old_pr->atom != JS_ATOM_NULL) { + pr->atom = old_pr->atom; + pr->flags = old_pr->flags; + h = ((uintptr_t)old_pr->atom & new_hash_mask); + pr->hash_next = prop_hash_end(sh)[-h - 1]; + prop_hash_end(sh)[-h - 1] = j + 1; + prop[j] = prop[i]; + j++; + pr++; + } + old_pr++; + } + assert(j == (sh->prop_count - sh->deleted_prop_count)); + sh->prop_hash_mask = new_hash_mask; + sh->prop_size = new_size; + sh->deleted_prop_count = 0; + sh->prop_count = j; + + p->shape = sh; + js_free(ctx, get_alloc_from_shape(old_sh)); + + /* reduce the size of the object properties */ + new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size); + if (new_prop) + p->prop = new_prop; + return 0; +} + +static int add_shape_property(JSContext *ctx, JSShape **psh, + JSObject *p, JSAtom atom, int prop_flags) +{ + JSRuntime *rt = ctx->rt; + JSShape *sh = *psh; + JSShapeProperty *pr, *prop; + uint32_t hash_mask, new_shape_hash = 0; + intptr_t h; + + /* update the shape hash */ + if (sh->is_hashed) { + js_shape_hash_unlink(rt, sh); + new_shape_hash = shape_hash(shape_hash(sh->hash, atom), prop_flags); + } + + if (unlikely(sh->prop_count >= sh->prop_size)) { + if (resize_properties(ctx, psh, p, sh->prop_count + 1)) { + /* in case of error, reinsert in the hash table. + sh is still valid if resize_properties() failed */ + if (sh->is_hashed) + js_shape_hash_link(rt, sh); + return -1; + } + sh = *psh; + } + if (sh->is_hashed) { + sh->hash = new_shape_hash; + js_shape_hash_link(rt, sh); + } + /* Initialize the new shape property. + The object property at p->prop[sh->prop_count] is uninitialized */ + prop = get_shape_prop(sh); + pr = &prop[sh->prop_count++]; + pr->atom = JS_DupAtom(ctx, atom); + pr->flags = prop_flags; + /* add in hash table */ + hash_mask = sh->prop_hash_mask; + h = atom & hash_mask; + pr->hash_next = prop_hash_end(sh)[-h - 1]; + prop_hash_end(sh)[-h - 1] = sh->prop_count; + return 0; +} + +/* find a hashed empty shape matching the prototype. Return NULL if + not found */ +static JSShape *find_hashed_shape_proto(JSRuntime *rt, JSObject *proto) +{ + JSShape *sh1; + uint32_t h, h1; + + h = shape_initial_hash(proto); + h1 = get_shape_hash(h, rt->shape_hash_bits); + for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) { + if (sh1->hash == h && + sh1->proto == proto && + sh1->prop_count == 0) { + return sh1; + } + } + return NULL; +} + +/* find a hashed shape matching sh + (prop, prop_flags). Return NULL if + not found */ +static JSShape *find_hashed_shape_prop(JSRuntime *rt, JSShape *sh, + JSAtom atom, int prop_flags) +{ + JSShape *sh1; + uint32_t h, h1, i, n; + + h = sh->hash; + h = shape_hash(h, atom); + h = shape_hash(h, prop_flags); + h1 = get_shape_hash(h, rt->shape_hash_bits); + for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) { + /* we test the hash first so that the rest is done only if the + shapes really match */ + if (sh1->hash == h && + sh1->proto == sh->proto && + sh1->prop_count == ((n = sh->prop_count) + 1)) { + for(i = 0; i < n; i++) { + if (unlikely(sh1->prop[i].atom != sh->prop[i].atom) || + unlikely(sh1->prop[i].flags != sh->prop[i].flags)) + goto next; + } + if (unlikely(sh1->prop[n].atom != atom) || + unlikely(sh1->prop[n].flags != prop_flags)) + goto next; + return sh1; + } + next: ; + } + return NULL; +} + +static __maybe_unused void JS_DumpShape(JSRuntime *rt, int i, JSShape *sh) +{ + char atom_buf[ATOM_GET_STR_BUF_SIZE]; + int j; + + /* XXX: should output readable class prototype */ + printf("%5d %3d%c %14p %5d %5d", i, + sh->header.ref_count, " *"[sh->is_hashed], + (void *)sh->proto, sh->prop_size, sh->prop_count); + for(j = 0; j < sh->prop_count; j++) { + printf(" %s", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), + sh->prop[j].atom)); + } + printf("\n"); +} + +static __maybe_unused void JS_DumpShapes(JSRuntime *rt) +{ + int i; + JSShape *sh; + struct list_head *el; + JSObject *p; + JSGCObjectHeader *gp; + + printf("JSShapes: {\n"); + printf("%5s %4s %14s %5s %5s %s\n", "SLOT", "REFS", "PROTO", "SIZE", "COUNT", "PROPS"); + for(i = 0; i < rt->shape_hash_size; i++) { + for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) { + JS_DumpShape(rt, i, sh); + assert(sh->is_hashed); + } + } + /* dump non-hashed shapes */ + list_for_each(el, &rt->gc_obj_list) { + gp = list_entry(el, JSGCObjectHeader, link); + if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) { + p = (JSObject *)gp; + if (!p->shape->is_hashed) { + JS_DumpShape(rt, -1, p->shape); + } + } + } + printf("}\n"); +} + +/* 'props[]' is used to initialized the object properties. The number + of elements depends on the shape. */ +static JSValue JS_NewObjectFromShape(JSContext *ctx, JSShape *sh, JSClassID class_id, + JSProperty *props) +{ + JSObject *p; + int i; + + js_trigger_gc(ctx->rt, sizeof(JSObject)); + p = js_malloc(ctx, sizeof(JSObject)); + if (unlikely(!p)) + goto fail; + p->class_id = class_id; + p->extensible = true; + p->free_mark = 0; + p->is_exotic = 0; + p->fast_array = 0; + p->is_constructor = 0; + p->is_uncatchable_error = 0; + p->tmp_mark = 0; + p->is_HTMLDDA = 0; + p->is_prototype = 0; + p->first_weak_ref = NULL; + p->u.opaque = NULL; + p->shape = sh; + p->prop = js_malloc(ctx, sizeof(JSProperty) * sh->prop_size); + if (unlikely(!p->prop)) { + js_free(ctx, p); + fail: + if (props) { + JSShapeProperty *prs = get_shape_prop(sh); + for(i = 0; i < sh->prop_count; i++) { + free_property(ctx->rt, &props[i], prs->flags); + prs++; + } + } + js_free_shape(ctx->rt, sh); + return JS_EXCEPTION; + } + + switch(class_id) { + case JS_CLASS_OBJECT: + break; + case JS_CLASS_ARRAY: + { + JSProperty *pr; + p->is_exotic = 1; + p->fast_array = 1; + p->u.array.u.values = NULL; + p->u.array.count = 0; + p->u.array.u1.size = 0; + if (!props) { + /* XXX: remove */ + /* the length property is always the first one */ + if (likely(sh == ctx->array_shape)) { + pr = &p->prop[0]; + } else { + /* only used for the first array */ + /* cannot fail */ + pr = add_property(ctx, p, JS_ATOM_length, + JS_PROP_WRITABLE | JS_PROP_LENGTH); + } + pr->u.value = js_int32(0); + } + } + break; + case JS_CLASS_C_FUNCTION: + p->prop[0].u.value = JS_UNDEFINED; + break; + case JS_CLASS_ARGUMENTS: + case JS_CLASS_MAPPED_ARGUMENTS: + case JS_CLASS_UINT8C_ARRAY: + case JS_CLASS_INT8_ARRAY: + case JS_CLASS_UINT8_ARRAY: + case JS_CLASS_INT16_ARRAY: + case JS_CLASS_UINT16_ARRAY: + case JS_CLASS_INT32_ARRAY: + case JS_CLASS_UINT32_ARRAY: + case JS_CLASS_BIG_INT64_ARRAY: + case JS_CLASS_BIG_UINT64_ARRAY: + case JS_CLASS_FLOAT16_ARRAY: + case JS_CLASS_FLOAT32_ARRAY: + case JS_CLASS_FLOAT64_ARRAY: + p->is_exotic = 1; + p->fast_array = 1; + p->u.array.u.ptr = NULL; + p->u.array.count = 0; + break; + case JS_CLASS_DATAVIEW: + p->u.array.u.ptr = NULL; + p->u.array.count = 0; + break; + case JS_CLASS_NUMBER: + case JS_CLASS_STRING: + case JS_CLASS_BOOLEAN: + case JS_CLASS_SYMBOL: + case JS_CLASS_DATE: + case JS_CLASS_BIG_INT: + p->u.object_data = JS_UNDEFINED; + goto set_exotic; + case JS_CLASS_REGEXP: + p->u.regexp.pattern = NULL; + p->u.regexp.bytecode = NULL; + goto set_exotic; + default: + set_exotic: + if (ctx->rt->class_array[class_id].exotic) { + p->is_exotic = 1; + } + break; + } + p->header.ref_count = 1; + add_gc_object(ctx->rt, &p->header, JS_GC_OBJ_TYPE_JS_OBJECT); + if (props) { + for(i = 0; i < sh->prop_count; i++) + p->prop[i] = props[i]; + } + return JS_MKPTR(JS_TAG_OBJECT, p); +} + +static JSObject *get_proto_obj(JSValueConst proto_val) +{ + if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) + return NULL; + else + return JS_VALUE_GET_OBJ(proto_val); +} + +/* WARNING: proto must be an object or JS_NULL */ +JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto_val, + JSClassID class_id) +{ + JSShape *sh; + JSObject *proto; + + proto = get_proto_obj(proto_val); + sh = find_hashed_shape_proto(ctx->rt, proto); + if (likely(sh)) { + sh = js_dup_shape(sh); + } else { + sh = js_new_shape(ctx, proto); + if (!sh) + return JS_EXCEPTION; + } + return JS_NewObjectFromShape(ctx, sh, class_id, NULL); +} + +static int JS_SetObjectData(JSContext *ctx, JSValueConst obj, JSValue val) +{ + JSObject *p; + + if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { + p = JS_VALUE_GET_OBJ(obj); + switch(p->class_id) { + case JS_CLASS_NUMBER: + case JS_CLASS_STRING: + case JS_CLASS_BOOLEAN: + case JS_CLASS_SYMBOL: + case JS_CLASS_DATE: + case JS_CLASS_BIG_INT: + JS_FreeValue(ctx, p->u.object_data); + p->u.object_data = val; /* for JS_CLASS_STRING, 'val' must + be JS_TAG_STRING (and not a rope) */ + return 0; + } + } + JS_FreeValue(ctx, val); + if (!JS_IsException(obj)) + JS_ThrowTypeError(ctx, "invalid object type"); + return -1; +} + +JSValue JS_NewObjectClass(JSContext *ctx, JSClassID class_id) +{ + return JS_NewObjectProtoClass(ctx, ctx->class_proto[class_id], class_id); +} + +JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto) +{ + return JS_NewObjectProtoClass(ctx, proto, JS_CLASS_OBJECT); +} + +JSValue JS_NewObjectFrom(JSContext *ctx, int count, const JSAtom *props, + const JSValue *values) +{ + JSShapeProperty *pr; + uint32_t *hash; + JSRuntime *rt; + JSObject *p; + JSShape *sh; + JSValue obj; + JSAtom atom; + intptr_t h; + int i; + + rt = ctx->rt; + obj = JS_NewObject(ctx); + if (JS_IsException(obj)) + return JS_EXCEPTION; + if (count > 0) { + p = JS_VALUE_GET_OBJ(obj); + sh = p->shape; + assert(sh->is_hashed); + assert(sh->header.ref_count == 1); + js_shape_hash_unlink(rt, sh); + if (resize_properties(ctx, &sh, p, count)) { + js_shape_hash_link(rt, sh); + JS_FreeValue(ctx, obj); + return JS_EXCEPTION; + } + p->shape = sh; + for (i = 0; i < count; i++) { + atom = props[i]; + pr = &sh->prop[i]; + sh->hash = shape_hash(shape_hash(sh->hash, atom), JS_PROP_C_W_E); + h = atom & sh->prop_hash_mask; + hash = &prop_hash_end(sh)[-h - 1]; + pr->hash_next = *hash; + *hash = i + 1; + pr->atom = JS_DupAtom(ctx, atom); + pr->flags = JS_PROP_C_W_E; + p->prop[i].u.value = values[i]; + } + js_shape_hash_link(rt, sh); + sh->prop_count = count; + } + return obj; +} + +JSValue JS_NewObjectFromStr(JSContext *ctx, int count, const char **props, + const JSValue *values) +{ + JSAtom atoms_s[16], *atoms = atoms_s; + JSValue ret; + int i; + + i = 0; + ret = JS_EXCEPTION; + if (count < 1) + goto out; + if (count > (int)countof(atoms_s)) { + atoms = js_malloc(ctx, count * sizeof(*atoms)); + if (!atoms) + return JS_EXCEPTION; + } + for (i = 0; i < count; i++) { + atoms[i] = JS_NewAtom(ctx, props[i]); + if (atoms[i] == JS_ATOM_NULL) + goto out; + } + ret = JS_NewObjectFrom(ctx, count, atoms, values); +out: + while (i-- > 0) + JS_FreeAtom(ctx, atoms[i]); + if (atoms != atoms_s) + js_free(ctx, atoms); + return ret; +} + +JSValue JS_NewArray(JSContext *ctx) +{ + return JS_NewObjectFromShape(ctx, js_dup_shape(ctx->array_shape), + JS_CLASS_ARRAY, NULL); +} + +// note: takes ownership of |values|, unlike js_create_array +JSValue JS_NewArrayFrom(JSContext *ctx, int count, const JSValue *values) +{ + JSObject *p; + JSValue obj; + int i; + + obj = JS_NewArray(ctx); + if (JS_IsException(obj)) + goto exception; + if (count > 0) { + p = JS_VALUE_GET_OBJ(obj); + if (expand_fast_array(ctx, p, count)) { + JS_FreeValue(ctx, obj); + goto exception; + } + p->u.array.count = count; + p->prop[0].u.value = js_int32(count); + memcpy(p->u.array.u.values, values, count * sizeof(*values)); + } + return obj; +exception: + for (i = 0; i < count; i++) + JS_FreeValue(ctx, values[i]); + return JS_EXCEPTION; +} + +JSValue JS_NewObject(JSContext *ctx) +{ + /* inline JS_NewObjectClass(ctx, JS_CLASS_OBJECT); */ + return JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_OBJECT); +} + +static void js_function_set_properties(JSContext *ctx, JSValue func_obj, + JSAtom name, int len) +{ + /* ES6 feature non compatible with ES5.1: length is configurable */ + JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length, js_int32(len), + JS_PROP_CONFIGURABLE); + JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, + JS_AtomToString(ctx, name), JS_PROP_CONFIGURABLE); +} + +static bool js_class_has_bytecode(JSClassID class_id) +{ + return (class_id == JS_CLASS_BYTECODE_FUNCTION || + class_id == JS_CLASS_GENERATOR_FUNCTION || + class_id == JS_CLASS_ASYNC_FUNCTION || + class_id == JS_CLASS_ASYNC_GENERATOR_FUNCTION); +} + +/* return NULL without exception if not a function or no bytecode */ +static JSFunctionBytecode *JS_GetFunctionBytecode(JSValueConst val) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return NULL; + p = JS_VALUE_GET_OBJ(val); + if (!js_class_has_bytecode(p->class_id)) + return NULL; + return p->u.func.function_bytecode; +} + +static void js_method_set_home_object(JSContext *ctx, JSValue func_obj, + JSValue home_obj) +{ + JSObject *p, *p1; + JSFunctionBytecode *b; + + if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT) + return; + p = JS_VALUE_GET_OBJ(func_obj); + if (!js_class_has_bytecode(p->class_id)) + return; + b = p->u.func.function_bytecode; + if (b->need_home_object) { + p1 = p->u.func.home_object; + if (p1) { + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1)); + } + if (JS_VALUE_GET_TAG(home_obj) == JS_TAG_OBJECT) + p1 = JS_VALUE_GET_OBJ(js_dup(home_obj)); + else + p1 = NULL; + p->u.func.home_object = p1; + } +} + +static JSValue js_get_function_name(JSContext *ctx, JSAtom name) +{ + JSValue name_str; + + name_str = JS_AtomToString(ctx, name); + if (JS_AtomSymbolHasDescription(ctx, name)) { + name_str = JS_ConcatString3(ctx, "[", name_str, "]"); + } + return name_str; +} + +/* Modify the name of a method according to the atom and + 'flags'. 'flags' is a bitmask of JS_PROP_HAS_GET and + JS_PROP_HAS_SET. Also set the home object of the method. + Return < 0 if exception. */ +static int js_method_set_properties(JSContext *ctx, JSValue func_obj, + JSAtom name, int flags, JSValue home_obj) +{ + JSValue name_str; + + name_str = js_get_function_name(ctx, name); + if (flags & JS_PROP_HAS_GET) { + name_str = JS_ConcatString3(ctx, "get ", name_str, ""); + } else if (flags & JS_PROP_HAS_SET) { + name_str = JS_ConcatString3(ctx, "set ", name_str, ""); + } + if (JS_IsException(name_str)) + return -1; + if (JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name_str, + JS_PROP_CONFIGURABLE) < 0) + return -1; + js_method_set_home_object(ctx, func_obj, home_obj); + return 0; +} + +/* Note: at least 'length' arguments will be readable in 'argv' */ +/* `name` may be NULL, pure ASCII or UTF-8 encoded */ +JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func, + const char *name, + int length, JSCFunctionEnum cproto, int magic, + JSValueConst proto_val) +{ + JSValue func_obj; + JSObject *p; + JSAtom name_atom; + + func_obj = JS_NewObjectProtoClass(ctx, proto_val, JS_CLASS_C_FUNCTION); + if (JS_IsException(func_obj)) + return func_obj; + p = JS_VALUE_GET_OBJ(func_obj); + p->u.cfunc.realm = JS_DupContext(ctx); + p->u.cfunc.c_function.generic = func; + p->u.cfunc.length = length; + p->u.cfunc.cproto = cproto; + p->u.cfunc.magic = magic; + p->is_constructor = (cproto == JS_CFUNC_constructor || + cproto == JS_CFUNC_constructor_magic || + cproto == JS_CFUNC_constructor_or_func || + cproto == JS_CFUNC_constructor_or_func_magic); + name_atom = JS_ATOM_empty_string; + if (name && *name) { + name_atom = JS_NewAtom(ctx, name); + if (name_atom == JS_ATOM_NULL) { + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; + } + } + js_function_set_properties(ctx, func_obj, name_atom, length); + JS_FreeAtom(ctx, name_atom); + return func_obj; +} + +/* Note: at least 'length' arguments will be readable in 'argv' */ +JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func, + const char *name, + int length, JSCFunctionEnum cproto, int magic) +{ + return JS_NewCFunction3(ctx, func, name, length, cproto, magic, + ctx->function_proto); +} + +typedef struct JSCFunctionDataRecord { + JSCFunctionData *func; + uint8_t length; + uint8_t data_len; + uint16_t magic; + JSValue data[]; +} JSCFunctionDataRecord; + +static void js_c_function_data_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA); + int i; + + if (s) { + for(i = 0; i < s->data_len; i++) { + JS_FreeValueRT(rt, s->data[i]); + } + js_free_rt(rt, s); + } +} + +static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA); + int i; + + if (s) { + for(i = 0; i < s->data_len; i++) { + JS_MarkValue(rt, s->data[i], mark_func); + } + } +} + +static JSValue js_call_c_function_data(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_val, + int argc, JSValueConst *argv, int flags) +{ + JSRuntime *rt = ctx->rt; + JSStackFrame sf_s, *sf = &sf_s, *prev_sf; + JSCFunctionDataRecord *s; + JSValueConst *arg_buf; + JSValue ret; + size_t stack_size; + int arg_count; + int i; + + s = JS_GetOpaque(func_obj, JS_CLASS_C_FUNCTION_DATA); + if (!s) + return JS_EXCEPTION; // can't really happen + arg_buf = argv; + arg_count = s->length; + if (unlikely(argc < arg_count)) { + stack_size = arg_count * sizeof(arg_buf[0]); + if (js_check_stack_overflow(rt, stack_size)) + return JS_ThrowStackOverflow(ctx); + arg_buf = alloca(stack_size); + for(i = 0; i < argc; i++) + arg_buf[i] = argv[i]; + for(i = argc; i < arg_count; i++) + arg_buf[i] = JS_UNDEFINED; + } + prev_sf = rt->current_stack_frame; + sf->prev_frame = prev_sf; + rt->current_stack_frame = sf; + // TODO(bnoordhuis) switch realms like js_call_c_function does + sf->is_strict_mode = false; + sf->cur_func = unsafe_unconst(func_obj); + sf->arg_count = argc; + ret = s->func(ctx, this_val, argc, arg_buf, s->magic, vc(s->data)); + rt->current_stack_frame = sf->prev_frame; + return ret; +} + +JSValue JS_NewCFunctionData2(JSContext *ctx, JSCFunctionData *func, + const char *name, + int length, int magic, int data_len, + JSValueConst *data) +{ + JSCFunctionDataRecord *s; + JSAtom name_atom; + JSValue func_obj; + int i; + + func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto, + JS_CLASS_C_FUNCTION_DATA); + if (JS_IsException(func_obj)) + return func_obj; + s = js_malloc(ctx, sizeof(*s) + data_len * sizeof(JSValue)); + if (!s) { + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; + } + s->func = func; + s->length = length; + s->data_len = data_len; + s->magic = magic; + for(i = 0; i < data_len; i++) + s->data[i] = js_dup(data[i]); + JS_SetOpaqueInternal(func_obj, s); + name_atom = JS_ATOM_empty_string; + if (name && *name) { + name_atom = JS_NewAtom(ctx, name); + if (name_atom == JS_ATOM_NULL) { + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; + } + } + js_function_set_properties(ctx, func_obj, name_atom, length); + JS_FreeAtom(ctx, name_atom); + return func_obj; +} + +JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func, + int length, int magic, int data_len, + JSValueConst *data) +{ + return JS_NewCFunctionData2(ctx, func, NULL, length, magic, data_len, data); +} + +static JSContext *js_autoinit_get_realm(JSProperty *pr) +{ + return (JSContext *)(pr->u.init.realm_and_id & ~3); +} + +static JSAutoInitIDEnum js_autoinit_get_id(JSProperty *pr) +{ + return pr->u.init.realm_and_id & 3; +} + +static void js_autoinit_free(JSRuntime *rt, JSProperty *pr) +{ + JS_FreeContext(js_autoinit_get_realm(pr)); +} + +static void js_autoinit_mark(JSRuntime *rt, JSProperty *pr, + JS_MarkFunc *mark_func) +{ + mark_func(rt, &js_autoinit_get_realm(pr)->header); +} + +typedef struct JSCClosureRecord { + JSCClosure *func; + uint16_t length; + uint16_t magic; + void *opaque; + void (*opaque_finalize)(void *opaque); +} JSCClosureRecord; + +static void js_c_closure_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSCClosureRecord *s = JS_GetOpaque(val, JS_CLASS_C_CLOSURE); + + if (s) { + if (s->opaque_finalize) + s->opaque_finalize(s->opaque); + + js_free_rt(rt, s); + } +} + +static JSValue js_call_c_closure(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_val, + int argc, JSValueConst *argv, int flags) +{ + JSRuntime *rt = ctx->rt; + JSStackFrame sf_s, *sf = &sf_s, *prev_sf; + JSCClosureRecord *s = JS_GetOpaque(func_obj, JS_CLASS_C_CLOSURE); + JSValueConst *arg_buf; + JSValue ret; + int arg_count; + int i; + size_t stack_size; + + arg_buf = argv; + arg_count = s->length; + if (unlikely(argc < arg_count)) { + stack_size = arg_count * sizeof(arg_buf[0]); + if (js_check_stack_overflow(rt, stack_size)) + return JS_ThrowStackOverflow(ctx); + arg_buf = alloca(stack_size); + for (i = 0; i < argc; i++) + arg_buf[i] = argv[i]; + for (i = argc; i < arg_count; i++) + arg_buf[i] = JS_UNDEFINED; + } + + prev_sf = rt->current_stack_frame; + sf->prev_frame = prev_sf; + rt->current_stack_frame = sf; + // TODO(bnoordhuis) switch realms like js_call_c_function does + sf->is_strict_mode = false; + sf->cur_func = unsafe_unconst(func_obj); + sf->arg_count = argc; + ret = s->func(ctx, this_val, argc, arg_buf, s->magic, s->opaque); + rt->current_stack_frame = sf->prev_frame; + + return ret; +} + +JSValue JS_NewCClosure(JSContext *ctx, JSCClosure *func, const char *name, + JSCClosureFinalizerFunc *opaque_finalize, + int length, int magic, void *opaque) +{ + JSCClosureRecord *s; + JSAtom name_atom; + JSValue func_obj; + + func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto, + JS_CLASS_C_CLOSURE); + if (JS_IsException(func_obj)) + return func_obj; + s = js_malloc(ctx, sizeof(*s)); + if (!s) { + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; + } + s->func = func; + s->length = length; + s->magic = magic; + s->opaque = opaque; + s->opaque_finalize = opaque_finalize; + JS_SetOpaqueInternal(func_obj, s); + name_atom = JS_ATOM_empty_string; + if (name && *name) { + name_atom = JS_NewAtom(ctx, name); + if (name_atom == JS_ATOM_NULL) { + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; + } + } + js_function_set_properties(ctx, func_obj, name_atom, length); + JS_FreeAtom(ctx, name_atom); + return func_obj; +} + +static void free_property(JSRuntime *rt, JSProperty *pr, int prop_flags) +{ + if (unlikely(prop_flags & JS_PROP_TMASK)) { + if ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + if (pr->u.getset.getter) + JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); + if (pr->u.getset.setter) + JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); + } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + free_var_ref(rt, pr->u.var_ref); + } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + js_autoinit_free(rt, pr); + } + } else { + JS_FreeValueRT(rt, pr->u.value); + } +} + +static inline JSShapeProperty *find_own_property1(JSObject *p, JSAtom atom) +{ + JSShape *sh; + JSShapeProperty *pr, *prop; + intptr_t h; + sh = p->shape; + h = (uintptr_t)atom & sh->prop_hash_mask; + h = prop_hash_end(sh)[-h - 1]; + prop = get_shape_prop(sh); + while (h) { + pr = &prop[h - 1]; + if (likely(pr->atom == atom)) { + return pr; + } + h = pr->hash_next; + } + return NULL; +} + +static inline JSShapeProperty *find_own_property(JSProperty **ppr, + JSObject *p, + JSAtom atom) +{ + JSShape *sh; + JSShapeProperty *pr, *prop; + intptr_t h; + sh = p->shape; + h = (uintptr_t)atom & sh->prop_hash_mask; + h = prop_hash_end(sh)[-h - 1]; + prop = get_shape_prop(sh); + while (h) { + pr = &prop[h - 1]; + if (likely(pr->atom == atom)) { + *ppr = &p->prop[h - 1]; + /* the compiler should be able to assume that pr != NULL here */ + return pr; + } + h = pr->hash_next; + } + *ppr = NULL; + return NULL; +} + +static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref) +{ + if (var_ref) { + assert(var_ref->header.ref_count > 0); + if (--var_ref->header.ref_count == 0) { + if (var_ref->is_detached) { + JS_FreeValueRT(rt, var_ref->value); + remove_gc_object(&var_ref->header); + } else { + JSStackFrame *sf = var_ref->stack_frame; + assert(sf->var_refs[var_ref->var_ref_idx] == var_ref); + sf->var_refs[var_ref->var_ref_idx] = NULL; + } + js_free_rt(rt, var_ref); + } + } +} + +static void js_array_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + int i; + + for(i = 0; i < p->u.array.count; i++) { + JS_FreeValueRT(rt, p->u.array.u.values[i]); + } + js_free_rt(rt, p->u.array.u.values); +} + +static void js_array_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + int i; + + for(i = 0; i < p->u.array.count; i++) { + JS_MarkValue(rt, p->u.array.u.values[i], mark_func); + } +} + +static void js_object_data_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JS_FreeValueRT(rt, p->u.object_data); + p->u.object_data = JS_UNDEFINED; +} + +static void js_object_data_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JS_MarkValue(rt, p->u.object_data, mark_func); +} + +static void js_c_function_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + + if (p->u.cfunc.realm) + JS_FreeContext(p->u.cfunc.realm); +} + +static void js_c_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + + if (p->u.cfunc.realm) + mark_func(rt, &p->u.cfunc.realm->header); +} + +static void js_bytecode_function_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p1, *p = JS_VALUE_GET_OBJ(val); + JSFunctionBytecode *b; + JSVarRef **var_refs; + int i; + + p1 = p->u.func.home_object; + if (p1) { + JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, p1)); + } + b = p->u.func.function_bytecode; + if (b) { + var_refs = p->u.func.var_refs; + if (var_refs) { + for(i = 0; i < b->closure_var_count; i++) + free_var_ref(rt, var_refs[i]); + js_free_rt(rt, var_refs); + } + JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b)); + } +} + +static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSVarRef **var_refs = p->u.func.var_refs; + JSFunctionBytecode *b = p->u.func.function_bytecode; + int i; + + if (p->u.func.home_object) { + JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object), + mark_func); + } + if (b) { + if (var_refs) { + for(i = 0; i < b->closure_var_count; i++) { + JSVarRef *var_ref = var_refs[i]; + if (var_ref && var_ref->is_detached) { + mark_func(rt, &var_ref->header); + } + } + } + /* must mark the function bytecode because template objects may be + part of a cycle */ + JS_MarkValue(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b), mark_func); + } +} + +static void js_bound_function_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSBoundFunction *bf = p->u.bound_function; + int i; + + JS_FreeValueRT(rt, bf->func_obj); + JS_FreeValueRT(rt, bf->this_val); + for(i = 0; i < bf->argc; i++) { + JS_FreeValueRT(rt, bf->argv[i]); + } + js_free_rt(rt, bf); +} + +static void js_bound_function_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSBoundFunction *bf = p->u.bound_function; + int i; + + JS_MarkValue(rt, bf->func_obj, mark_func); + JS_MarkValue(rt, bf->this_val, mark_func); + for(i = 0; i < bf->argc; i++) + JS_MarkValue(rt, bf->argv[i], mark_func); +} + +static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSForInIterator *it = p->u.for_in_iterator; + JS_FreeValueRT(rt, it->obj); + js_free_rt(rt, it); +} + +static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSForInIterator *it = p->u.for_in_iterator; + JS_MarkValue(rt, it->obj, mark_func); +} + +static void free_object(JSRuntime *rt, JSObject *p) +{ + int i; + JSClassFinalizer *finalizer; + JSShape *sh; + JSShapeProperty *pr; + + p->free_mark = 1; /* used to tell the object is invalid when + freeing cycles */ + /* free all the fields */ + sh = p->shape; + pr = get_shape_prop(sh); + for(i = 0; i < sh->prop_count; i++) { + free_property(rt, &p->prop[i], pr->flags); + pr++; + } + js_free_rt(rt, p->prop); + /* as an optimization we destroy the shape immediately without + putting it in gc_zero_ref_count_list */ + js_free_shape(rt, sh); + + /* fail safe */ + p->shape = NULL; + p->prop = NULL; + + if (unlikely(p->first_weak_ref)) { + reset_weak_ref(rt, &p->first_weak_ref); + } + + finalizer = rt->class_array[p->class_id].finalizer; + if (finalizer) + (*finalizer)(rt, JS_MKPTR(JS_TAG_OBJECT, p)); + + /* fail safe */ + p->class_id = 0; + p->u.opaque = NULL; + p->u.func.var_refs = NULL; + p->u.func.home_object = NULL; + + remove_gc_object(&p->header); + if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && p->header.ref_count != 0) { + list_add_tail(&p->header.link, &rt->gc_zero_ref_count_list); + } else { + js_free_rt(rt, p); + } +} + +static void free_gc_object(JSRuntime *rt, JSGCObjectHeader *gp) +{ + switch(gp->gc_obj_type) { + case JS_GC_OBJ_TYPE_JS_OBJECT: + free_object(rt, (JSObject *)gp); + break; + case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: + free_function_bytecode(rt, (JSFunctionBytecode *)gp); + break; + default: + abort(); + } +} + +static void free_zero_refcount(JSRuntime *rt) +{ + struct list_head *el; + JSGCObjectHeader *p; + + rt->gc_phase = JS_GC_PHASE_DECREF; + for(;;) { + el = rt->gc_zero_ref_count_list.next; + if (el == &rt->gc_zero_ref_count_list) + break; + p = list_entry(el, JSGCObjectHeader, link); + assert(p->ref_count == 0); + free_gc_object(rt, p); + } + rt->gc_phase = JS_GC_PHASE_NONE; +} + +/* called with the ref_count of 'v' reaches zero. */ +static void js_free_value_rt(JSRuntime *rt, JSValue v) +{ + uint32_t tag = JS_VALUE_GET_TAG(v); + +#ifdef ENABLE_DUMPS // JS_DUMP_FREE + if (check_dump_flag(rt, JS_DUMP_FREE)) { + /* Prevent invalid object access during GC */ + if ((rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) + || (tag != JS_TAG_OBJECT && tag != JS_TAG_FUNCTION_BYTECODE)) { + printf("Freeing "); + if (tag == JS_TAG_OBJECT) { + JS_DumpObject(rt, JS_VALUE_GET_OBJ(v)); + } else { + JS_DumpValue(rt, v); + printf("\n"); + } + } + } +#endif + + switch(tag) { + case JS_TAG_STRING: + js_free_string0(rt, JS_VALUE_GET_STRING(v)); + break; + case JS_TAG_STRING_ROPE: + { + JSStringRope *p = JS_VALUE_GET_STRING_ROPE(v); + JS_FreeValueRT(rt, p->left); + JS_FreeValueRT(rt, p->right); + js_free_rt(rt, p); + } + break; + case JS_TAG_OBJECT: + case JS_TAG_FUNCTION_BYTECODE: + { + JSGCObjectHeader *p = JS_VALUE_GET_PTR(v); + if (rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) { + list_del(&p->link); + list_add(&p->link, &rt->gc_zero_ref_count_list); + if (rt->gc_phase == JS_GC_PHASE_NONE) { + free_zero_refcount(rt); + } + } + } + break; + case JS_TAG_MODULE: + abort(); /* never freed here */ + break; + case JS_TAG_BIG_INT: + { + JSBigInt *p = JS_VALUE_GET_PTR(v); + js_free_rt(rt, p); + } + break; + case JS_TAG_SYMBOL: + { + JSAtomStruct *p = JS_VALUE_GET_PTR(v); + JS_FreeAtomStruct(rt, p); + } + break; + default: + printf("js_free_value_rt: unknown tag=%d\n", tag); + abort(); + } +} + +void JS_FreeValueRT(JSRuntime *rt, JSValue v) +{ + if (JS_VALUE_HAS_REF_COUNT(v)) { + JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); + if (--p->ref_count <= 0) { + js_free_value_rt(rt, v); + } + } +} + +void JS_FreeValue(JSContext *ctx, JSValue v) +{ + JS_FreeValueRT(ctx->rt, v); +} + +/* garbage collection */ + +static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h, + JSGCObjectTypeEnum type) +{ + h->mark = 0; + h->gc_obj_type = type; + list_add_tail(&h->link, &rt->gc_obj_list); +} + +static void remove_gc_object(JSGCObjectHeader *h) +{ + list_del(&h->link); +} + +void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) +{ + if (JS_VALUE_HAS_REF_COUNT(val)) { + switch(JS_VALUE_GET_TAG(val)) { + case JS_TAG_OBJECT: + case JS_TAG_FUNCTION_BYTECODE: + mark_func(rt, JS_VALUE_GET_PTR(val)); + break; + default: + break; + } + } +} + +static void mark_weak_map_value(JSRuntime *rt, JSWeakRefRecord *first_weak_ref, JS_MarkFunc *mark_func) { + JSWeakRefRecord *wr; + JSMapRecord *mr; + JSMapState *s; + + for (wr = first_weak_ref; wr != NULL; wr = wr->next_weak_ref) { + if (wr->kind == JS_WEAK_REF_KIND_MAP) { + mr = wr->u.map_record; + s = mr->map; + assert(s->is_weak); + assert(!mr->empty); /* no iterator on WeakMap/WeakSet */ + JS_MarkValue(rt, mr->value, mark_func); + } + } +} + +static void mark_children(JSRuntime *rt, JSGCObjectHeader *gp, + JS_MarkFunc *mark_func) +{ + switch(gp->gc_obj_type) { + case JS_GC_OBJ_TYPE_JS_OBJECT: + { + JSObject *p = (JSObject *)gp; + JSShapeProperty *prs; + JSShape *sh; + int i; + sh = p->shape; + mark_func(rt, &sh->header); + /* mark all the fields */ + prs = get_shape_prop(sh); + for(i = 0; i < sh->prop_count; i++) { + JSProperty *pr = &p->prop[i]; + if (prs->atom != JS_ATOM_NULL) { + if (prs->flags & JS_PROP_TMASK) { + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + if (pr->u.getset.getter) + mark_func(rt, &pr->u.getset.getter->header); + if (pr->u.getset.setter) + mark_func(rt, &pr->u.getset.setter->header); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + if (pr->u.var_ref->is_detached) { + /* Note: the tag does not matter + provided it is a GC object */ + mark_func(rt, &pr->u.var_ref->header); + } + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + js_autoinit_mark(rt, pr, mark_func); + } + } else { + JS_MarkValue(rt, pr->u.value, mark_func); + } + } + prs++; + } + + if (unlikely(p->first_weak_ref)) { + mark_weak_map_value(rt, p->first_weak_ref, mark_func); + } + + if (p->class_id != JS_CLASS_OBJECT) { + JSClassGCMark *gc_mark; + gc_mark = rt->class_array[p->class_id].gc_mark; + if (gc_mark) + gc_mark(rt, JS_MKPTR(JS_TAG_OBJECT, p), mark_func); + } + } + break; + case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: + /* the template objects can be part of a cycle */ + { + JSFunctionBytecode *b = (JSFunctionBytecode *)gp; + int i; + for(i = 0; i < b->cpool_count; i++) { + JS_MarkValue(rt, b->cpool[i], mark_func); + } + if (b->realm) + mark_func(rt, &b->realm->header); + } + break; + case JS_GC_OBJ_TYPE_VAR_REF: + { + JSVarRef *var_ref = (JSVarRef *)gp; + /* only detached variable referenced are taken into account */ + assert(var_ref->is_detached); + JS_MarkValue(rt, *var_ref->pvalue, mark_func); + } + break; + case JS_GC_OBJ_TYPE_ASYNC_FUNCTION: + { + JSAsyncFunctionData *s = (JSAsyncFunctionData *)gp; + if (s->is_active) + async_func_mark(rt, &s->func_state, mark_func); + JS_MarkValue(rt, s->resolving_funcs[0], mark_func); + JS_MarkValue(rt, s->resolving_funcs[1], mark_func); + } + break; + case JS_GC_OBJ_TYPE_SHAPE: + { + JSShape *sh = (JSShape *)gp; + if (sh->proto != NULL) { + mark_func(rt, &sh->proto->header); + } + } + break; + case JS_GC_OBJ_TYPE_JS_CONTEXT: + { + JSContext *ctx = (JSContext *)gp; + JS_MarkContext(rt, ctx, mark_func); + } + break; + default: + abort(); + } +} + +static void gc_decref_child(JSRuntime *rt, JSGCObjectHeader *p) +{ + assert(p->ref_count > 0); + p->ref_count--; + if (p->ref_count == 0 && p->mark == 1) { + list_del(&p->link); + list_add_tail(&p->link, &rt->tmp_obj_list); + } +} + +static void gc_decref(JSRuntime *rt) +{ + struct list_head *el, *el1; + JSGCObjectHeader *p; + + init_list_head(&rt->tmp_obj_list); + + /* decrement the refcount of all the children of all the GC + objects and move the GC objects with zero refcount to + tmp_obj_list */ + list_for_each_safe(el, el1, &rt->gc_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + assert(p->mark == 0); + mark_children(rt, p, gc_decref_child); + p->mark = 1; + if (p->ref_count == 0) { + list_del(&p->link); + list_add_tail(&p->link, &rt->tmp_obj_list); + } + } +} + +static void gc_scan_incref_child(JSRuntime *rt, JSGCObjectHeader *p) +{ + p->ref_count++; + if (p->ref_count == 1) { + /* ref_count was 0: remove from tmp_obj_list and add at the + end of gc_obj_list */ + list_del(&p->link); + list_add_tail(&p->link, &rt->gc_obj_list); + p->mark = 0; /* reset the mark for the next GC call */ + } +} + +static void gc_scan_incref_child2(JSRuntime *rt, JSGCObjectHeader *p) +{ + p->ref_count++; +} + +static void gc_scan(JSRuntime *rt) +{ + struct list_head *el; + JSGCObjectHeader *p; + + /* keep the objects with a refcount > 0 and their children. */ + list_for_each(el, &rt->gc_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + assert(p->ref_count > 0); + p->mark = 0; /* reset the mark for the next GC call */ + mark_children(rt, p, gc_scan_incref_child); + } + + /* restore the refcount of the objects to be deleted. */ + list_for_each(el, &rt->tmp_obj_list) { + p = list_entry(el, JSGCObjectHeader, link); + mark_children(rt, p, gc_scan_incref_child2); + } +} + +static void gc_free_cycles(JSRuntime *rt) +{ + struct list_head *el, *el1; + JSGCObjectHeader *p; +#ifdef ENABLE_DUMPS // JS_DUMP_GC_FREE + bool header_done = false; +#endif + + rt->gc_phase = JS_GC_PHASE_REMOVE_CYCLES; + + for(;;) { + el = rt->tmp_obj_list.next; + if (el == &rt->tmp_obj_list) + break; + p = list_entry(el, JSGCObjectHeader, link); + /* Only need to free the GC object associated with JS + values. The rest will be automatically removed because they + must be referenced by them. */ + switch(p->gc_obj_type) { + case JS_GC_OBJ_TYPE_JS_OBJECT: + case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: +#ifdef ENABLE_DUMPS // JS_DUMP_GC_FREE + if (check_dump_flag(rt, JS_DUMP_GC_FREE)) { + if (!header_done) { + printf("Freeing cycles:\n"); + JS_DumpObjectHeader(rt); + header_done = true; + } + JS_DumpGCObject(rt, p); + } +#endif + free_gc_object(rt, p); + break; + default: + list_del(&p->link); + list_add_tail(&p->link, &rt->gc_zero_ref_count_list); + break; + } + } + rt->gc_phase = JS_GC_PHASE_NONE; + + list_for_each_safe(el, el1, &rt->gc_zero_ref_count_list) { + p = list_entry(el, JSGCObjectHeader, link); + assert(p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT || + p->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE); + js_free_rt(rt, p); + } + + init_list_head(&rt->gc_zero_ref_count_list); +} + +void JS_RunGC(JSRuntime *rt) +{ + /* decrement the reference of the children of each object. mark = + 1 after this pass. */ + gc_decref(rt); + + /* keep the GC objects with a non zero refcount and their childs */ + gc_scan(rt); + + /* free the GC objects in a cycle */ + gc_free_cycles(rt); +} + +/* Return false if not an object or if the object has already been + freed (zombie objects are visible in finalizers when freeing + cycles). */ +bool JS_IsLiveObject(JSRuntime *rt, JSValueConst obj) +{ + JSObject *p; + if (!JS_IsObject(obj)) + return false; + p = JS_VALUE_GET_OBJ(obj); + return !p->free_mark; +} + +/* Compute memory used by various object types */ +/* XXX: poor man's approach to handling multiply referenced objects */ +typedef struct JSMemoryUsage_helper { + double memory_used_count; + double str_count; + double str_size; + int64_t js_func_count; + double js_func_size; + int64_t js_func_code_size; + int64_t js_func_pc2line_count; + int64_t js_func_pc2line_size; +} JSMemoryUsage_helper; + +static void compute_value_size(JSValue val, JSMemoryUsage_helper *hp); + +static void compute_jsstring_size(JSString *str, JSMemoryUsage_helper *hp) +{ + if (!str->atom_type) { /* atoms are handled separately */ + double s_ref_count = str->header.ref_count; + hp->str_count += 1 / s_ref_count; + hp->str_size += ((sizeof(*str) + (str->len << str->is_wide_char) + + 1 - str->is_wide_char) / s_ref_count); + } +} + +static void compute_bytecode_size(JSFunctionBytecode *b, JSMemoryUsage_helper *hp) +{ + int memory_used_count, js_func_size, i; + + memory_used_count = 0; + js_func_size = sizeof(*b); + if (b->vardefs) { + js_func_size += (b->arg_count + b->var_count) * sizeof(*b->vardefs); + } + if (b->cpool) { + js_func_size += b->cpool_count * sizeof(*b->cpool); + for (i = 0; i < b->cpool_count; i++) { + JSValue val = b->cpool[i]; + compute_value_size(val, hp); + } + } + if (b->closure_var) { + js_func_size += b->closure_var_count * sizeof(*b->closure_var); + } + if (b->byte_code_buf) { + hp->js_func_code_size += b->byte_code_len; + } + memory_used_count++; + js_func_size += b->source_len + 1; + if (b->pc2line_len) { + memory_used_count++; + hp->js_func_pc2line_count += 1; + hp->js_func_pc2line_size += b->pc2line_len; + } + hp->js_func_size += js_func_size; + hp->js_func_count += 1; + hp->memory_used_count += memory_used_count; +} + +static void compute_value_size(JSValue val, JSMemoryUsage_helper *hp) +{ + switch(JS_VALUE_GET_TAG(val)) { + case JS_TAG_STRING: + compute_jsstring_size(JS_VALUE_GET_STRING(val), hp); + break; + case JS_TAG_BIG_INT: + /* should track JSBigInt usage */ + break; + } +} + +void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s) +{ + struct list_head *el, *el1; + int i; + JSMemoryUsage_helper mem = { 0 }, *hp = &mem; + + memset(s, 0, sizeof(*s)); + s->malloc_count = rt->malloc_state.malloc_count; + s->malloc_size = rt->malloc_state.malloc_size; + s->malloc_limit = rt->malloc_state.malloc_limit; + + s->memory_used_count = 2; /* rt + rt->class_array */ + s->memory_used_size = sizeof(JSRuntime) + sizeof(JSClass) * rt->class_count; + + list_for_each(el, &rt->context_list) { + JSContext *ctx = list_entry(el, JSContext, link); + JSShape *sh = ctx->array_shape; + s->memory_used_count += 2; /* ctx + ctx->class_proto */ + s->memory_used_size += sizeof(JSContext) + + sizeof(JSValue) * rt->class_count; + s->binary_object_count += ctx->binary_object_count; + s->binary_object_size += ctx->binary_object_size; + + /* the hashed shapes are counted separately */ + if (sh && !sh->is_hashed) { + int hash_size = sh->prop_hash_mask + 1; + s->shape_count++; + s->shape_size += get_shape_size(hash_size, sh->prop_size); + } + list_for_each(el1, &ctx->loaded_modules) { + JSModuleDef *m = list_entry(el1, JSModuleDef, link); + s->memory_used_count += 1; + s->memory_used_size += sizeof(*m); + if (m->req_module_entries) { + s->memory_used_count += 1; + s->memory_used_size += m->req_module_entries_count * sizeof(*m->req_module_entries); + } + if (m->export_entries) { + s->memory_used_count += 1; + s->memory_used_size += m->export_entries_count * sizeof(*m->export_entries); + for (i = 0; i < m->export_entries_count; i++) { + JSExportEntry *me = &m->export_entries[i]; + if (me->export_type == JS_EXPORT_TYPE_LOCAL && me->u.local.var_ref) { + /* potential multiple count */ + s->memory_used_count += 1; + compute_value_size(me->u.local.var_ref->value, hp); + } + } + } + if (m->star_export_entries) { + s->memory_used_count += 1; + s->memory_used_size += m->star_export_entries_count * sizeof(*m->star_export_entries); + } + if (m->import_entries) { + s->memory_used_count += 1; + s->memory_used_size += m->import_entries_count * sizeof(*m->import_entries); + } + compute_value_size(m->module_ns, hp); + compute_value_size(m->func_obj, hp); + } + } + + list_for_each(el, &rt->gc_obj_list) { + JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link); + JSObject *p; + JSShape *sh; + JSShapeProperty *prs; + + /* XXX: could count the other GC object types too */ + if (gp->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE) { + compute_bytecode_size((JSFunctionBytecode *)gp, hp); + continue; + } else if (gp->gc_obj_type != JS_GC_OBJ_TYPE_JS_OBJECT) { + continue; + } + p = (JSObject *)gp; + sh = p->shape; + s->obj_count++; + if (p->prop) { + s->memory_used_count++; + s->prop_size += sh->prop_size * sizeof(*p->prop); + s->prop_count += sh->prop_count; + prs = get_shape_prop(sh); + for(i = 0; i < sh->prop_count; i++) { + JSProperty *pr = &p->prop[i]; + if (prs->atom != JS_ATOM_NULL && !(prs->flags & JS_PROP_TMASK)) { + compute_value_size(pr->u.value, hp); + } + prs++; + } + } + /* the hashed shapes are counted separately */ + if (!sh->is_hashed) { + int hash_size = sh->prop_hash_mask + 1; + s->shape_count++; + s->shape_size += get_shape_size(hash_size, sh->prop_size); + } + + switch(p->class_id) { + case JS_CLASS_ARRAY: /* u.array | length */ + case JS_CLASS_ARGUMENTS: /* u.array | length */ + s->array_count++; + if (p->fast_array) { + s->fast_array_count++; + if (p->u.array.u.values) { + s->memory_used_count++; + s->memory_used_size += p->u.array.count * + sizeof(*p->u.array.u.values); + s->fast_array_elements += p->u.array.count; + for (i = 0; i < p->u.array.count; i++) { + compute_value_size(p->u.array.u.values[i], hp); + } + } + } + break; + case JS_CLASS_NUMBER: /* u.object_data */ + case JS_CLASS_STRING: /* u.object_data */ + case JS_CLASS_BOOLEAN: /* u.object_data */ + case JS_CLASS_SYMBOL: /* u.object_data */ + case JS_CLASS_DATE: /* u.object_data */ + case JS_CLASS_BIG_INT: /* u.object_data */ + compute_value_size(p->u.object_data, hp); + break; + case JS_CLASS_C_FUNCTION: /* u.cfunc */ + s->c_func_count++; + break; + case JS_CLASS_BYTECODE_FUNCTION: /* u.func */ + { + JSFunctionBytecode *b = p->u.func.function_bytecode; + JSVarRef **var_refs = p->u.func.var_refs; + /* home_object: object will be accounted for in list scan */ + if (var_refs) { + s->memory_used_count++; + s->js_func_size += b->closure_var_count * sizeof(*var_refs); + for (i = 0; i < b->closure_var_count; i++) { + if (var_refs[i]) { + double ref_count = var_refs[i]->header.ref_count; + s->memory_used_count += 1 / ref_count; + s->js_func_size += sizeof(*var_refs[i]) / ref_count; + /* handle non object closed values */ + if (var_refs[i]->pvalue == &var_refs[i]->value) { + /* potential multiple count */ + compute_value_size(var_refs[i]->value, hp); + } + } + } + } + } + break; + case JS_CLASS_BOUND_FUNCTION: /* u.bound_function */ + { + JSBoundFunction *bf = p->u.bound_function; + /* func_obj and this_val are objects */ + for (i = 0; i < bf->argc; i++) { + compute_value_size(bf->argv[i], hp); + } + s->memory_used_count += 1; + s->memory_used_size += sizeof(*bf) + bf->argc * sizeof(*bf->argv); + } + break; + case JS_CLASS_C_FUNCTION_DATA: /* u.c_function_data_record */ + { + JSCFunctionDataRecord *fd = p->u.c_function_data_record; + if (fd) { + for (i = 0; i < fd->data_len; i++) { + compute_value_size(fd->data[i], hp); + } + s->memory_used_count += 1; + s->memory_used_size += sizeof(*fd) + fd->data_len * sizeof(*fd->data); + } + } + break; + case JS_CLASS_C_CLOSURE: /* u.c_closure_record */ + { + JSCClosureRecord *c = p->u.c_closure_record; + if (c) { + s->memory_used_count += 1; + s->memory_used_size += sizeof(*c); + } + } + break; + case JS_CLASS_REGEXP: /* u.regexp */ + compute_jsstring_size(p->u.regexp.pattern, hp); + compute_jsstring_size(p->u.regexp.bytecode, hp); + break; + + case JS_CLASS_FOR_IN_ITERATOR: /* u.for_in_iterator */ + { + JSForInIterator *it = p->u.for_in_iterator; + if (it) { + compute_value_size(it->obj, hp); + s->memory_used_count += 1; + s->memory_used_size += sizeof(*it); + } + } + break; + case JS_CLASS_ARRAY_BUFFER: /* u.array_buffer */ + case JS_CLASS_SHARED_ARRAY_BUFFER: /* u.array_buffer */ + { + JSArrayBuffer *abuf = p->u.array_buffer; + if (abuf) { + s->memory_used_count += 1; + s->memory_used_size += sizeof(*abuf); + if (abuf->data) { + s->memory_used_count += 1; + s->memory_used_size += abuf->byte_length; + } + } + } + break; + case JS_CLASS_GENERATOR: /* u.generator_data */ + case JS_CLASS_UINT8C_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_INT8_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_UINT8_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_INT16_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_UINT16_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_INT32_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_UINT32_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_BIG_INT64_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_BIG_UINT64_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_FLOAT16_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_FLOAT32_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_FLOAT64_ARRAY: /* u.typed_array / u.array */ + case JS_CLASS_DATAVIEW: /* u.typed_array */ + case JS_CLASS_MAP: /* u.map_state */ + case JS_CLASS_SET: /* u.map_state */ + case JS_CLASS_WEAKMAP: /* u.map_state */ + case JS_CLASS_WEAKSET: /* u.map_state */ + case JS_CLASS_MAP_ITERATOR: /* u.map_iterator_data */ + case JS_CLASS_SET_ITERATOR: /* u.map_iterator_data */ + case JS_CLASS_ARRAY_ITERATOR: /* u.array_iterator_data */ + case JS_CLASS_STRING_ITERATOR: /* u.array_iterator_data */ + case JS_CLASS_PROXY: /* u.proxy_data */ + case JS_CLASS_PROMISE: /* u.promise_data */ + case JS_CLASS_PROMISE_RESOLVE_FUNCTION: /* u.promise_function_data */ + case JS_CLASS_PROMISE_REJECT_FUNCTION: /* u.promise_function_data */ + case JS_CLASS_ASYNC_FUNCTION_RESOLVE: /* u.async_function_data */ + case JS_CLASS_ASYNC_FUNCTION_REJECT: /* u.async_function_data */ + case JS_CLASS_ASYNC_FROM_SYNC_ITERATOR: /* u.async_from_sync_iterator_data */ + case JS_CLASS_ASYNC_GENERATOR: /* u.async_generator_data */ + /* TODO */ + default: + /* XXX: class definition should have an opaque block size */ + if (p->u.opaque) { + s->memory_used_count += 1; + } + break; + } + } + s->obj_size += s->obj_count * sizeof(JSObject); + + /* hashed shapes */ + s->memory_used_count++; /* rt->shape_hash */ + s->memory_used_size += sizeof(rt->shape_hash[0]) * rt->shape_hash_size; + for(i = 0; i < rt->shape_hash_size; i++) { + JSShape *sh; + for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) { + int hash_size = sh->prop_hash_mask + 1; + s->shape_count++; + s->shape_size += get_shape_size(hash_size, sh->prop_size); + } + } + + /* atoms */ + s->memory_used_count += 2; /* rt->atom_array, rt->atom_hash */ + s->atom_count = rt->atom_count; + s->atom_size = sizeof(rt->atom_array[0]) * rt->atom_size + + sizeof(rt->atom_hash[0]) * rt->atom_hash_size; + for(i = 0; i < rt->atom_size; i++) { + JSAtomStruct *p = rt->atom_array[i]; + if (!atom_is_free(p)) { + s->atom_size += (sizeof(*p) + (p->len << p->is_wide_char) + + 1 - p->is_wide_char); + } + } + s->str_count = round(mem.str_count); + s->str_size = round(mem.str_size); + s->js_func_count = mem.js_func_count; + s->js_func_size = round(mem.js_func_size); + s->js_func_code_size = mem.js_func_code_size; + s->js_func_pc2line_count = mem.js_func_pc2line_count; + s->js_func_pc2line_size = mem.js_func_pc2line_size; + s->memory_used_count += round(mem.memory_used_count) + + s->atom_count + s->str_count + + s->obj_count + s->shape_count + + s->js_func_count + s->js_func_pc2line_count; + s->memory_used_size += s->atom_size + s->str_size + + s->obj_size + s->prop_size + s->shape_size + + s->js_func_size + s->js_func_code_size + s->js_func_pc2line_size; +} + +void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt) +{ + fprintf(fp, "QuickJS-ng memory usage -- %s version, %d-bit, %s Endian, malloc limit: %"PRId64"\n\n", + JS_GetVersion(), (int)sizeof(void *) * 8, is_be() ? "Big" : "Little", s->malloc_limit); + if (rt) { + static const struct { + const char *name; + size_t size; + } object_types[] = { + { "JSRuntime", sizeof(JSRuntime) }, + { "JSContext", sizeof(JSContext) }, + { "JSObject", sizeof(JSObject) }, + { "JSString", sizeof(JSString) }, + { "JSFunctionBytecode", sizeof(JSFunctionBytecode) }, + }; + int i, usage_size_ok = 0; + for(i = 0; i < countof(object_types); i++) { + unsigned int size = object_types[i].size; + void *p = js_malloc_rt(rt, size); + if (p) { + unsigned int size1 = js_malloc_usable_size_rt(rt, p); + if (size1 >= size) { + usage_size_ok = 1; + fprintf(fp, " %3u + %-2u %s\n", + size, size1 - size, object_types[i].name); + } + js_free_rt(rt, p); + } + } + if (!usage_size_ok) { + fprintf(fp, " malloc_usable_size unavailable\n"); + } + { + int obj_classes[JS_CLASS_INIT_COUNT + 1] = { 0 }; + int class_id; + struct list_head *el; + list_for_each(el, &rt->gc_obj_list) { + JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link); + JSObject *p; + if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) { + p = (JSObject *)gp; + obj_classes[min_uint32(p->class_id, JS_CLASS_INIT_COUNT)]++; + } + } + fprintf(fp, "\n" "JSObject classes\n"); + if (obj_classes[0]) + fprintf(fp, " %5d %2.0d %s\n", obj_classes[0], 0, "none"); + for (class_id = 1; class_id < JS_CLASS_INIT_COUNT; class_id++) { + if (obj_classes[class_id] && class_id < rt->class_count) { + char buf[ATOM_GET_STR_BUF_SIZE]; + fprintf(fp, " %5d %2.0d %s\n", obj_classes[class_id], class_id, + JS_AtomGetStrRT(rt, buf, sizeof(buf), rt->class_array[class_id].class_name)); + } + } + if (obj_classes[JS_CLASS_INIT_COUNT]) + fprintf(fp, " %5d %2.0d %s\n", obj_classes[JS_CLASS_INIT_COUNT], 0, "other"); + } + fprintf(fp, "\n"); + } + fprintf(fp, "%-20s %8s %8s\n", "NAME", "COUNT", "SIZE"); + + if (s->malloc_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per block)\n", + "memory allocated", s->malloc_count, s->malloc_size, + (double)s->malloc_size / s->malloc_count); + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%d overhead, %0.1f average slack)\n", + "memory used", s->memory_used_count, s->memory_used_size, + MALLOC_OVERHEAD, ((double)(s->malloc_size - s->memory_used_size) / + s->memory_used_count)); + } + if (s->atom_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per atom)\n", + "atoms", s->atom_count, s->atom_size, + (double)s->atom_size / s->atom_count); + } + if (s->str_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per string)\n", + "strings", s->str_count, s->str_size, + (double)s->str_size / s->str_count); + } + if (s->obj_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per object)\n", + "objects", s->obj_count, s->obj_size, + (double)s->obj_size / s->obj_count); + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per object)\n", + " properties", s->prop_count, s->prop_size, + (double)s->prop_count / s->obj_count); + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per shape)\n", + " shapes", s->shape_count, s->shape_size, + (double)s->shape_size / s->shape_count); + } + if (s->js_func_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64"\n", + "bytecode functions", s->js_func_count, s->js_func_size); + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per function)\n", + " bytecode", s->js_func_count, s->js_func_code_size, + (double)s->js_func_code_size / s->js_func_count); + if (s->js_func_pc2line_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per function)\n", + " pc2line", s->js_func_pc2line_count, + s->js_func_pc2line_size, + (double)s->js_func_pc2line_size / s->js_func_pc2line_count); + } + } + if (s->c_func_count) { + fprintf(fp, "%-20s %8"PRId64"\n", "C functions", s->c_func_count); + } + if (s->array_count) { + fprintf(fp, "%-20s %8"PRId64"\n", "arrays", s->array_count); + if (s->fast_array_count) { + fprintf(fp, "%-20s %8"PRId64"\n", " fast arrays", s->fast_array_count); + fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per fast array)\n", + " elements", s->fast_array_elements, + s->fast_array_elements * (int)sizeof(JSValue), + (double)s->fast_array_elements / s->fast_array_count); + } + } + if (s->binary_object_count) { + fprintf(fp, "%-20s %8"PRId64" %8"PRId64"\n", + "binary objects", s->binary_object_count, s->binary_object_size); + } +} + +JSValue JS_GetGlobalObject(JSContext *ctx) +{ + return js_dup(ctx->global_obj); +} + +/* WARNING: obj is freed */ +JSValue JS_Throw(JSContext *ctx, JSValue obj) +{ + JSRuntime *rt = ctx->rt; + JS_FreeValue(ctx, rt->current_exception); + rt->current_exception = obj; + return JS_EXCEPTION; +} + +/* return the pending exception (cannot be called twice). */ +JSValue JS_GetException(JSContext *ctx) +{ + JSValue val; + JSRuntime *rt = ctx->rt; + val = rt->current_exception; + rt->current_exception = JS_UNINITIALIZED; + return val; +} + +bool JS_HasException(JSContext *ctx) +{ + return !JS_IsUninitialized(ctx->rt->current_exception); +} + +static void dbuf_put_leb128(DynBuf *s, uint32_t v) +{ + uint32_t a; + for(;;) { + a = v & 0x7f; + v >>= 7; + if (v != 0) { + dbuf_putc(s, a | 0x80); + } else { + dbuf_putc(s, a); + break; + } + } +} + +static void dbuf_put_sleb128(DynBuf *s, int32_t v1) +{ + uint32_t v = v1; + dbuf_put_leb128(s, (2 * v) ^ -(v >> 31)); +} + +static int get_leb128(uint32_t *pval, const uint8_t *buf, + const uint8_t *buf_end) +{ + const uint8_t *ptr = buf; + uint32_t v, a, i; + v = 0; + for(i = 0; i < 5; i++) { + if (unlikely(ptr >= buf_end)) + break; + a = *ptr++; + v |= (a & 0x7f) << (i * 7); + if (!(a & 0x80)) { + *pval = v; + return ptr - buf; + } + } + *pval = 0; + return -1; +} + +static int get_sleb128(int32_t *pval, const uint8_t *buf, + const uint8_t *buf_end) +{ + int ret; + uint32_t val; + ret = get_leb128(&val, buf, buf_end); + if (ret < 0) { + *pval = 0; + return -1; + } + *pval = (val >> 1) ^ -(val & 1); + return ret; +} + +static int find_line_num(JSContext *ctx, JSFunctionBytecode *b, + uint32_t pc_value, int *col) +{ + const uint8_t *p_end, *p; + int new_line_num, new_col_num, line_num, col_num, pc, v, ret; + unsigned int op; + + *col = 1; + p = b->pc2line_buf; + if (!p) + goto fail; + p_end = p + b->pc2line_len; + pc = 0; + line_num = b->line_num; + col_num = b->col_num; + while (p < p_end) { + op = *p++; + if (op == 0) { + uint32_t val; + ret = get_leb128(&val, p, p_end); + if (ret < 0) + goto fail; + pc += val; + p += ret; + ret = get_sleb128(&v, p, p_end); + if (ret < 0) + goto fail; + p += ret; + new_line_num = line_num + v; + } else { + op -= PC2LINE_OP_FIRST; + pc += (op / PC2LINE_RANGE); + new_line_num = line_num + (op % PC2LINE_RANGE) + PC2LINE_BASE; + } + ret = get_sleb128(&v, p, p_end); + if (ret < 0) + goto fail; + p += ret; + new_col_num = col_num + v; + if (pc_value < pc) + break; + line_num = new_line_num; + col_num = new_col_num; + } + *col = col_num; + return line_num; +fail: + /* should never happen */ + return b->line_num; +} + +/* in order to avoid executing arbitrary code during the stack trace + generation, we only look at simple 'name' properties containing a + string. */ +static const char *get_func_name(JSContext *ctx, JSValueConst func) +{ + JSProperty *pr; + JSShapeProperty *prs; + JSValue val; + + if (JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT) + return NULL; + prs = find_own_property(&pr, JS_VALUE_GET_OBJ(func), JS_ATOM_name); + if (!prs) + return NULL; + if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL) + return NULL; + val = pr->u.value; + if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) + return NULL; + return JS_ToCString(ctx, val); +} + +/* Note: it is important that no exception is returned by this function */ +static bool can_add_backtrace(JSValueConst obj) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(obj); + if (p->class_id != JS_CLASS_ERROR && p->class_id != JS_CLASS_DOM_EXCEPTION) + return false; + if (find_own_property1(p, JS_ATOM_stack)) + return false; + return true; +} + +#define JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL (1 << 0) +/* only taken into account if filename is provided */ +#define JS_BACKTRACE_FLAG_SINGLE_LEVEL (1 << 1) +#define JS_BACKTRACE_FLAG_FILTER_FUNC (1 << 2) + +/* if filename != NULL, an additional level is added with the filename + and line number information (used for parse error). */ +static void build_backtrace(JSContext *ctx, JSValueConst error_val, + JSValueConst filter_func, const char *filename, + int line_num, int col_num, int backtrace_flags) +{ + JSStackFrame *sf, *sf_start; + JSValue stack, prepare, saved_exception; + DynBuf dbuf; + const char *func_name_str; + const char *str1; + JSObject *p; + JSFunctionBytecode *b; + bool backtrace_barrier, has_prepare, has_filter_func; + JSRuntime *rt; + JSCallSiteData csd[64]; + uint32_t i; + double d; + int stack_trace_limit; + + rt = ctx->rt; + if (rt->in_build_stack_trace) + return; + rt->in_build_stack_trace = true; + + // Save exception because conversion to double may fail. + saved_exception = JS_GetException(ctx); + + // Extract stack trace limit. + // Ignore error since it sets d to NAN anyway. + // coverity[check_return] + JS_ToFloat64(ctx, &d, ctx->error_stack_trace_limit); + if (isnan(d) || d < 0.0) + stack_trace_limit = 0; + else if (d > INT32_MAX) + stack_trace_limit = INT32_MAX; + else + stack_trace_limit = fabs(d); + + // Restore current exception. + JS_Throw(ctx, saved_exception); + saved_exception = JS_UNINITIALIZED; + + stack_trace_limit = min_int(stack_trace_limit, countof(csd)); + stack_trace_limit = max_int(stack_trace_limit, 0); + has_prepare = false; + has_filter_func = backtrace_flags & JS_BACKTRACE_FLAG_FILTER_FUNC; + i = 0; + + if (!JS_IsNull(ctx->error_ctor)) { + prepare = js_dup(ctx->error_prepare_stack); + has_prepare = JS_IsFunction(ctx, prepare); + } + + if (has_prepare) { + saved_exception = JS_GetException(ctx); + if (stack_trace_limit == 0) + goto done; + if (filename) + js_new_callsite_data2(ctx, &csd[i++], filename, line_num, col_num); + } else { + js_dbuf_init(ctx, &dbuf); + if (stack_trace_limit == 0) + goto done; + if (filename) { + i++; + dbuf_printf(&dbuf, " at %s", filename); + if (line_num != -1) + dbuf_printf(&dbuf, ":%d:%d", line_num, col_num); + dbuf_putc(&dbuf, '\n'); + } + } + + if (filename && (backtrace_flags & JS_BACKTRACE_FLAG_SINGLE_LEVEL)) + goto done; + + sf_start = rt->current_stack_frame; + + /* Find the frame we want to start from. Note that when a filter is used the filter + function will be the first, but we also specify we want to skip the first one. */ + if (has_filter_func) { + for (sf = sf_start; sf != NULL && i < stack_trace_limit; sf = sf->prev_frame) { + if (js_same_value(ctx, sf->cur_func, filter_func)) { + sf_start = sf; + break; + } + } + } + + for (sf = sf_start; sf != NULL && i < stack_trace_limit; sf = sf->prev_frame) { + if (backtrace_flags & JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL) { + backtrace_flags &= ~JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL; + continue; + } + + p = JS_VALUE_GET_OBJ(sf->cur_func); + b = NULL; + backtrace_barrier = false; + + if (js_class_has_bytecode(p->class_id)) { + b = p->u.func.function_bytecode; + backtrace_barrier = b->backtrace_barrier; + } + + if (has_prepare) { + js_new_callsite_data(ctx, &csd[i], sf); + } else { + /* func_name_str is UTF-8 encoded if needed */ + func_name_str = get_func_name(ctx, sf->cur_func); + if (!func_name_str || func_name_str[0] == '\0') + str1 = ""; + else + str1 = func_name_str; + dbuf_printf(&dbuf, " at %s", str1); + JS_FreeCString(ctx, func_name_str); + + if (b && sf->cur_pc) { + const char *atom_str; + int line_num1, col_num1; + uint32_t pc; + + pc = sf->cur_pc - b->byte_code_buf - 1; + line_num1 = find_line_num(ctx, b, pc, &col_num1); + atom_str = b->filename ? JS_AtomToCString(ctx, b->filename) : NULL; + dbuf_printf(&dbuf, " (%s", atom_str ? atom_str : ""); + JS_FreeCString(ctx, atom_str); + if (line_num1 != -1) + dbuf_printf(&dbuf, ":%d:%d", line_num1, col_num1); + dbuf_putc(&dbuf, ')'); + } else if (b) { + // FIXME(bnoordhuis) Missing `sf->cur_pc = pc` in bytecode + // handler in JS_CallInternal. Almost never user observable + // except with intercepting JS proxies that throw exceptions. + dbuf_printf(&dbuf, " (missing)"); + } else { + dbuf_printf(&dbuf, " (native)"); + } + dbuf_putc(&dbuf, '\n'); + } + i++; + + /* stop backtrace if JS_EVAL_FLAG_BACKTRACE_BARRIER was used */ + if (backtrace_barrier) + break; + } + done: + if (has_prepare) { + int j = 0, k; + stack = JS_NewArray(ctx); + if (JS_IsException(stack)) { + stack = JS_NULL; + } else { + for (; j < i; j++) { + JSValue v = js_new_callsite(ctx, &csd[j]); + if (JS_IsException(v)) + break; + if (JS_DefinePropertyValueUint32(ctx, stack, j, v, JS_PROP_C_W_E) < 0) { + JS_FreeValue(ctx, v); + break; + } + } + } + // Clear the csd's we didn't use in case of error. + for (k = j; k < i; k++) { + JS_FreeValue(ctx, csd[k].filename); + JS_FreeValue(ctx, csd[k].func); + JS_FreeValue(ctx, csd[k].func_name); + } + JSValueConst args[] = { + error_val, + stack, + }; + JSValue stack2 = JS_Call(ctx, prepare, ctx->error_ctor, countof(args), args); + JS_FreeValue(ctx, stack); + if (JS_IsException(stack2)) + stack = JS_NULL; + else + stack = stack2; + JS_FreeValue(ctx, prepare); + JS_Throw(ctx, saved_exception); + } else { + if (dbuf_error(&dbuf)) + stack = JS_NULL; + else + stack = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size); + dbuf_free(&dbuf); + } + + if (JS_IsUndefined(ctx->error_back_trace)) + ctx->error_back_trace = js_dup(stack); + if (has_filter_func || can_add_backtrace(error_val)) { + JS_DefinePropertyValue(ctx, error_val, JS_ATOM_stack, stack, + JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); + } else { + JS_FreeValue(ctx, stack); + } + + rt->in_build_stack_trace = false; +} + +JSValue JS_NewError(JSContext *ctx) +{ + JSValue obj = JS_NewObjectClass(ctx, JS_CLASS_ERROR); + if (JS_IsException(obj)) + return JS_EXCEPTION; + build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, 0); + return obj; +} + +static JSValue JS_MakeError2(JSContext *ctx, JSErrorEnum error_num, + bool add_backtrace, const char *message) +{ + JSValue obj, msg; + + if (error_num == JS_PLAIN_ERROR) { + obj = JS_NewObjectClass(ctx, JS_CLASS_ERROR); + } else { + obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num], + JS_CLASS_ERROR); + } + if (JS_IsException(obj)) + return JS_EXCEPTION; + msg = JS_NewString(ctx, message); + if (JS_IsException(msg)) + msg = JS_NewString(ctx, "Invalid error message"); + if (!JS_IsException(msg)) { + JS_DefinePropertyValue(ctx, obj, JS_ATOM_message, msg, + JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); + } + if (add_backtrace) + build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, 0); + return obj; +} + +static JSValue JS_PRINTF_FORMAT_ATTR(4, 0) +JS_MakeError(JSContext *ctx, JSErrorEnum error_num, bool add_backtrace, + JS_PRINTF_FORMAT const char *fmt, va_list ap) +{ + char buf[256]; + + vsnprintf(buf, sizeof(buf), fmt, ap); + return JS_MakeError2(ctx, error_num, add_backtrace, buf); +} + +/* fmt and arguments may be pure ASCII or UTF-8 encoded contents */ +static JSValue JS_PRINTF_FORMAT_ATTR(4, 0) +JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num, bool add_backtrace, + JS_PRINTF_FORMAT const char *fmt, va_list ap) +{ + JSValue obj; + + obj = JS_MakeError(ctx, error_num, add_backtrace, fmt, ap); + if (unlikely(JS_IsException(obj))) { + /* out of memory: throw JS_NULL to avoid recursing */ + obj = JS_NULL; + } + return JS_Throw(ctx, obj); +} + +static JSValue JS_PRINTF_FORMAT_ATTR(3, 0) +JS_ThrowError(JSContext *ctx, JSErrorEnum error_num, + JS_PRINTF_FORMAT const char *fmt, va_list ap) +{ + JSRuntime *rt = ctx->rt; + JSStackFrame *sf; + bool add_backtrace; + + /* the backtrace is added later if called from a bytecode function */ + sf = rt->current_stack_frame; + add_backtrace = !rt->in_out_of_memory && + (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL)); + return JS_ThrowError2(ctx, error_num, add_backtrace, fmt, ap); +} + +#define JS_ERROR_MAP(X) \ + X(Internal, INTERNAL) \ + X(Plain, PLAIN) \ + X(Range, RANGE) \ + X(Reference, REFERENCE) \ + X(Syntax, SYNTAX) \ + X(Type, TYPE) \ + +#define X(lc, uc) \ + JSValue JS_PRINTF_FORMAT_ATTR(2, 3) \ + JS_New##lc##Error(JSContext *ctx, \ + JS_PRINTF_FORMAT const char *fmt, ...) \ + { \ + JSValue val; \ + va_list ap; \ + \ + va_start(ap, fmt); \ + val = JS_MakeError(ctx, JS_##uc##_ERROR, \ + /*add_backtrace*/true, fmt, ap); \ + va_end(ap); \ + return val; \ + } \ + JSValue JS_PRINTF_FORMAT_ATTR(2, 3) \ + JS_Throw##lc##Error(JSContext *ctx, \ + JS_PRINTF_FORMAT const char *fmt, ...) \ + { \ + JSValue val; \ + va_list ap; \ + \ + va_start(ap, fmt); \ + val = JS_ThrowError(ctx, JS_##uc##_ERROR, fmt, ap); \ + va_end(ap); \ + return val; \ + } \ + +JS_ERROR_MAP(X) + +#undef X +#undef JS_ERROR_MAP + +static int JS_PRINTF_FORMAT_ATTR(3, 4) JS_ThrowTypeErrorOrFalse(JSContext *ctx, int flags, JS_PRINTF_FORMAT const char *fmt, ...) +{ + va_list ap; + + if ((flags & JS_PROP_THROW) || + ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { + va_start(ap, fmt); + JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap); + va_end(ap); + return -1; + } else { + return false; + } +} + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif // __GNUC__ +static JSValue JS_ThrowTypeErrorAtom(JSContext *ctx, const char *fmt, JSAtom atom) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + JS_AtomGetStr(ctx, buf, sizeof(buf), atom); + return JS_ThrowTypeError(ctx, fmt, buf); +} + +static JSValue JS_ThrowSyntaxErrorAtom(JSContext *ctx, const char *fmt, JSAtom atom) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + JS_AtomGetStr(ctx, buf, sizeof(buf), atom); + return JS_ThrowSyntaxError(ctx, fmt, buf); +} +#ifdef __GNUC__ +#pragma GCC diagnostic pop // ignored "-Wformat-nonliteral" +#endif // __GNUC__ + +static int JS_ThrowTypeErrorReadOnly(JSContext *ctx, int flags, JSAtom atom) +{ + if ((flags & JS_PROP_THROW) || + ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { + JS_ThrowTypeErrorAtom(ctx, "'%s' is read-only", atom); + return -1; + } else { + return false; + } +} + +JSValue JS_ThrowOutOfMemory(JSContext *ctx) +{ + JSRuntime *rt = ctx->rt; + if (!rt->in_out_of_memory) { + rt->in_out_of_memory = true; + JS_ThrowInternalError(ctx, "out of memory"); + rt->in_out_of_memory = false; + } + return JS_EXCEPTION; +} + +static JSValue JS_ThrowStackOverflow(JSContext *ctx) +{ + return JS_ThrowRangeError(ctx, "Maximum call stack size exceeded"); +} + +static JSValue JS_ThrowTypeErrorNotAConstructor(JSContext *ctx, + JSValueConst func_obj) +{ + JSObject *p; + JSAtom name; + + if (JS_TAG_OBJECT != JS_VALUE_GET_TAG(func_obj)) + goto fini; + p = JS_VALUE_GET_OBJ(func_obj); + if (!js_class_has_bytecode(p->class_id)) + goto fini; + name = p->u.func.function_bytecode->func_name; + if (name == JS_ATOM_NULL) + goto fini; + return JS_ThrowTypeErrorAtom(ctx, "%s is not a constructor", name); +fini: + return JS_ThrowTypeError(ctx, "not a constructor"); +} + +static JSValue JS_ThrowTypeErrorNotAFunction(JSContext *ctx) +{ + return JS_ThrowTypeError(ctx, "not a function"); +} + +static JSValue JS_ThrowTypeErrorNotAnObject(JSContext *ctx) +{ + return JS_ThrowTypeError(ctx, "not an object"); +} + +static JSValue JS_ThrowTypeErrorNotASymbol(JSContext *ctx) +{ + return JS_ThrowTypeError(ctx, "not a symbol"); +} + +static JSValue JS_ThrowReferenceErrorNotDefined(JSContext *ctx, JSAtom name) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + return JS_ThrowReferenceError(ctx, "%s is not defined", + JS_AtomGetStr(ctx, buf, sizeof(buf), name)); +} + +static JSValue JS_ThrowReferenceErrorUninitialized(JSContext *ctx, JSAtom name) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + return JS_ThrowReferenceError(ctx, "%s is not initialized", + name == JS_ATOM_NULL ? "lexical variable" : + JS_AtomGetStr(ctx, buf, sizeof(buf), name)); +} + +static JSValue JS_ThrowReferenceErrorUninitialized2(JSContext *ctx, + JSFunctionBytecode *b, + int idx, bool is_ref) +{ + JSAtom atom = JS_ATOM_NULL; + if (is_ref) { + atom = b->closure_var[idx].var_name; + } else { + /* not present if the function is stripped and contains no eval() */ + if (b->vardefs) + atom = b->vardefs[b->arg_count + idx].var_name; + } + return JS_ThrowReferenceErrorUninitialized(ctx, atom); +} + +static JSValue JS_ThrowTypeErrorInvalidClass(JSContext *ctx, int class_id) +{ + JSRuntime *rt = ctx->rt; + JSAtom name; + name = rt->class_array[class_id].class_name; + return JS_ThrowTypeErrorAtom(ctx, "%s object expected", name); +} + +static void JS_ThrowInterrupted(JSContext *ctx) +{ + JS_ThrowInternalError(ctx, "interrupted"); + JS_SetUncatchableError(ctx, ctx->rt->current_exception); +} + +static no_inline __exception int __js_poll_interrupts(JSContext *ctx) +{ + JSRuntime *rt = ctx->rt; + ctx->interrupt_counter = JS_INTERRUPT_COUNTER_INIT; + if (rt->interrupt_handler) { + if (rt->interrupt_handler(rt, rt->interrupt_opaque)) { + JS_ThrowInterrupted(ctx); + return -1; + } + } + return 0; +} + +static inline __exception int js_poll_interrupts(JSContext *ctx) +{ + if (unlikely(--ctx->interrupt_counter <= 0)) { + return __js_poll_interrupts(ctx); + } else { + return 0; + } +} + +/* return -1 (exception) or true/false */ +static int JS_SetPrototypeInternal(JSContext *ctx, JSValueConst obj, + JSValueConst proto_val, bool throw_flag) +{ + JSObject *proto, *p, *p1; + JSShape *sh; + + if (throw_flag) { + if (JS_VALUE_GET_TAG(obj) == JS_TAG_NULL || + JS_VALUE_GET_TAG(obj) == JS_TAG_UNDEFINED) + goto not_obj; + } else { + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + goto not_obj; + } + p = JS_VALUE_GET_OBJ(obj); + if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) { + if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_NULL) { + not_obj: + JS_ThrowTypeErrorNotAnObject(ctx); + return -1; + } + proto = NULL; + } else { + proto = JS_VALUE_GET_OBJ(proto_val); + } + + if (throw_flag && JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + return true; + + if (unlikely(p->class_id == JS_CLASS_PROXY)) + return js_proxy_setPrototypeOf(ctx, obj, proto_val, throw_flag); + sh = p->shape; + if (sh->proto == proto) + return true; + if (p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_OBJECT])) { + if (throw_flag) { + JS_ThrowTypeError(ctx, "'Immutable prototype object \'Object.prototype\' cannot have their prototype set'"); + return -1; + } + return false; + } + if (!p->extensible) { + if (throw_flag) { + JS_ThrowTypeError(ctx, "object is not extensible"); + return -1; + } else { + return false; + } + } + if (proto) { + /* check if there is a cycle */ + p1 = proto; + do { + if (p1 == p) { + if (throw_flag) { + JS_ThrowTypeError(ctx, "circular prototype chain"); + return -1; + } else { + return false; + } + } + /* Note: for Proxy objects, proto is NULL */ + p1 = p1->shape->proto; + } while (p1 != NULL); + js_dup(proto_val); + } + + if (js_shape_prepare_update(ctx, p, NULL)) + return -1; + sh = p->shape; + if (sh->proto) + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto)); + sh->proto = proto; + if (proto) + proto->is_prototype = true; + if (p->is_prototype) { + /* track modification of Array.prototype */ + if (unlikely(p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_ARRAY]))) { + ctx->std_array_prototype = false; + } + } + return true; +} + +/* return -1 (exception) or true/false */ +int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val) +{ + return JS_SetPrototypeInternal(ctx, obj, proto_val, true); +} + +/* Only works for primitive types, otherwise return JS_NULL. */ +static JSValueConst JS_GetPrototypePrimitive(JSContext *ctx, JSValueConst val) +{ + JSValue ret; + switch(JS_VALUE_GET_NORM_TAG(val)) { + case JS_TAG_SHORT_BIG_INT: + case JS_TAG_BIG_INT: + ret = ctx->class_proto[JS_CLASS_BIG_INT]; + break; + case JS_TAG_INT: + case JS_TAG_FLOAT64: + ret = ctx->class_proto[JS_CLASS_NUMBER]; + break; + case JS_TAG_BOOL: + ret = ctx->class_proto[JS_CLASS_BOOLEAN]; + break; + case JS_TAG_STRING: + case JS_TAG_STRING_ROPE: + ret = ctx->class_proto[JS_CLASS_STRING]; + break; + case JS_TAG_SYMBOL: + ret = ctx->class_proto[JS_CLASS_SYMBOL]; + break; + case JS_TAG_OBJECT: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + default: + ret = JS_NULL; + break; + } + return ret; +} + +/* Return an Object, JS_NULL or JS_EXCEPTION in case of Proxy object. */ +JSValue JS_GetPrototype(JSContext *ctx, JSValueConst obj) +{ + JSValue val; + if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { + JSObject *p; + p = JS_VALUE_GET_OBJ(obj); + if (unlikely(p->class_id == JS_CLASS_PROXY)) { + val = js_proxy_getPrototypeOf(ctx, obj); + } else { + p = p->shape->proto; + if (!p) + val = JS_NULL; + else + val = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); + } + } else { + val = js_dup(JS_GetPrototypePrimitive(ctx, obj)); + } + return val; +} + +static JSValue JS_GetPrototypeFree(JSContext *ctx, JSValue obj) +{ + JSValue obj1; + obj1 = JS_GetPrototype(ctx, obj); + JS_FreeValue(ctx, obj); + return obj1; +} + +int JS_GetLength(JSContext *ctx, JSValueConst obj, int64_t *pres) { + return js_get_length64(ctx, pres, obj); +} + +int JS_SetLength(JSContext *ctx, JSValueConst obj, int64_t len) { + return js_set_length64(ctx, obj, len); +} + +/* return true, false or (-1) in case of exception */ +static int JS_OrdinaryIsInstanceOf(JSContext *ctx, JSValueConst val, + JSValueConst obj) +{ + JSValue obj_proto; + JSObject *proto; + const JSObject *p, *proto1; + int ret; + + if (!JS_IsFunction(ctx, obj)) + return false; + p = JS_VALUE_GET_OBJ(obj); + if (p->class_id == JS_CLASS_BOUND_FUNCTION) { + JSBoundFunction *s = p->u.bound_function; + return JS_IsInstanceOf(ctx, val, s->func_obj); + } + + /* Only explicitly boxed values are instances of constructors */ + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return false; + obj_proto = JS_GetProperty(ctx, obj, JS_ATOM_prototype); + if (JS_VALUE_GET_TAG(obj_proto) != JS_TAG_OBJECT) { + if (!JS_IsException(obj_proto)) + JS_ThrowTypeError(ctx, "operand 'prototype' property is not an object"); + ret = -1; + goto done; + } + proto = JS_VALUE_GET_OBJ(obj_proto); + p = JS_VALUE_GET_OBJ(val); + for(;;) { + proto1 = p->shape->proto; + if (!proto1) { + /* slow case if proxy in the prototype chain */ + if (unlikely(p->class_id == JS_CLASS_PROXY)) { + JSValue obj1; + obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, (JSObject *)p)); + for(;;) { + obj1 = JS_GetPrototypeFree(ctx, obj1); + if (JS_IsException(obj1)) { + ret = -1; + break; + } + if (JS_IsNull(obj1)) { + ret = false; + break; + } + if (proto == JS_VALUE_GET_OBJ(obj1)) { + JS_FreeValue(ctx, obj1); + ret = true; + break; + } + /* must check for timeout to avoid infinite loop */ + if (js_poll_interrupts(ctx)) { + JS_FreeValue(ctx, obj1); + ret = -1; + break; + } + } + } else { + ret = false; + } + break; + } + p = proto1; + if (proto == p) { + ret = true; + break; + } + } +done: + JS_FreeValue(ctx, obj_proto); + return ret; +} + +/* return true, false or (-1) in case of exception */ +int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj) +{ + JSValue method; + + if (!JS_IsObject(obj)) + goto fail; + method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_hasInstance); + if (JS_IsException(method)) + return -1; + if (!JS_IsNull(method) && !JS_IsUndefined(method)) { + JSValue ret; + ret = JS_CallFree(ctx, method, obj, 1, &val); + return JS_ToBoolFree(ctx, ret); + } + + /* legacy case */ + if (!JS_IsFunction(ctx, obj)) { + fail: + JS_ThrowTypeError(ctx, "invalid 'instanceof' right operand"); + return -1; + } + return JS_OrdinaryIsInstanceOf(ctx, val, obj); +} + +/* File generated automatically by the QuickJS-ng compiler. */ + +#include + +const uint32_t qjsc_builtin_array_fromasync_size = 871; + +const uint8_t qjsc_builtin_array_fromasync[871] = { + 0x17, 0x0e, 0x01, 0x28, 0x53, 0x79, 0x6d, 0x62, + 0x6f, 0x6c, 0xb7, 0x61, 0x73, 0x79, 0x6e, 0x63, + 0x49, 0x74, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, + 0x01, 0x2a, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, + 0xb7, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x50, + 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x79, 0x01, + 0x1e, 0x53, 0x79, 0x6d, 0x62, 0x6f, 0x6c, 0xb7, + 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, + 0x01, 0x12, 0x61, 0x72, 0x72, 0x61, 0x79, 0x4c, + 0x69, 0x6b, 0x65, 0x01, 0x0a, 0x6d, 0x61, 0x70, + 0x46, 0x6e, 0x01, 0x0e, 0x74, 0x68, 0x69, 0x73, + 0x41, 0x72, 0x67, 0x01, 0x0c, 0x72, 0x65, 0x73, + 0x75, 0x6c, 0x74, 0x01, 0x02, 0x69, 0x01, 0x1a, + 0x69, 0x73, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x72, + 0x75, 0x63, 0x74, 0x6f, 0x72, 0x01, 0x08, 0x73, + 0x79, 0x6e, 0x63, 0x01, 0x0c, 0x6d, 0x65, 0x74, + 0x68, 0x6f, 0x64, 0x01, 0x08, 0x69, 0x74, 0x65, + 0x72, 0x01, 0x1c, 0x6e, 0x6f, 0x74, 0x20, 0x61, + 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, + 0x6e, 0x01, 0x08, 0x63, 0x61, 0x6c, 0x6c, 0x0c, + 0x00, 0x02, 0x00, 0xa2, 0x01, 0x00, 0x01, 0x00, + 0x01, 0x00, 0x00, 0x01, 0x04, 0x01, 0xa4, 0x01, + 0x00, 0x00, 0x00, 0x0c, 0x43, 0x02, 0x01, 0x00, + 0x05, 0x00, 0x05, 0x01, 0x05, 0x00, 0x01, 0x03, + 0x05, 0xae, 0x02, 0x00, 0x01, 0x40, 0x03, 0xa4, + 0x03, 0x00, 0x01, 0x40, 0x00, 0xca, 0x03, 0x00, + 0x01, 0x40, 0x01, 0xcc, 0x03, 0x00, 0x01, 0x40, + 0x04, 0xce, 0x03, 0x00, 0x01, 0x40, 0x02, 0x0c, + 0x60, 0x02, 0x01, 0xf8, 0x01, 0x03, 0x0e, 0x01, + 0x06, 0x00, 0x05, 0x00, 0x86, 0x04, 0x11, 0xd0, + 0x03, 0x00, 0x01, 0x00, 0xd2, 0x03, 0x00, 0x01, + 0x00, 0xd4, 0x03, 0x00, 0x01, 0x00, 0xd0, 0x03, + 0x01, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x20, 0xd2, + 0x03, 0x01, 0x01, 0x20, 0xd4, 0x03, 0x01, 0x02, + 0x20, 0xd6, 0x03, 0x02, 0x00, 0x20, 0xd8, 0x03, + 0x02, 0x04, 0x20, 0xda, 0x03, 0x02, 0x05, 0x20, + 0xdc, 0x03, 0x02, 0x06, 0x20, 0xde, 0x03, 0x02, + 0x07, 0x20, 0x64, 0x06, 0x08, 0x20, 0x82, 0x01, + 0x07, 0x09, 0x20, 0xe0, 0x03, 0x0a, 0x08, 0x30, + 0x82, 0x01, 0x0d, 0x0b, 0x20, 0xd4, 0x01, 0x0d, + 0x0c, 0x20, 0x10, 0x00, 0x01, 0x00, 0xa4, 0x03, + 0x01, 0x01, 0xca, 0x03, 0x02, 0x01, 0xce, 0x03, + 0x04, 0x01, 0xae, 0x02, 0x00, 0x01, 0xcc, 0x03, + 0x03, 0x01, 0x08, 0xc2, 0x0d, 0x60, 0x02, 0x00, + 0x60, 0x01, 0x00, 0x60, 0x00, 0x00, 0xd1, 0xc9, + 0xd2, 0x11, 0xf2, 0xea, 0x08, 0x0e, 0x38, 0x46, + 0x00, 0x00, 0x00, 0xda, 0xca, 0xd3, 0x11, 0xf2, + 0xea, 0x08, 0x0e, 0x38, 0x46, 0x00, 0x00, 0x00, + 0xdb, 0xcb, 0x60, 0x07, 0x00, 0x60, 0x06, 0x00, + 0x60, 0x05, 0x00, 0x60, 0x04, 0x00, 0x60, 0x03, + 0x00, 0xd2, 0x38, 0x46, 0x00, 0x00, 0x00, 0xae, + 0xea, 0x16, 0xd2, 0x96, 0x04, 0x1b, 0x00, 0x00, + 0x00, 0xae, 0xea, 0x0c, 0xdd, 0x11, 0x04, 0xf1, + 0x00, 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, 0x06, + 0xcc, 0xb4, 0xc2, 0x04, 0xc1, 0x0d, 0xf5, 0xc2, + 0x05, 0x09, 0xc2, 0x06, 0xd1, 0xde, 0x46, 0xc2, + 0x07, 0x61, 0x07, 0x00, 0x07, 0xab, 0xea, 0x0f, + 0x0a, 0x11, 0x62, 0x06, 0x00, 0x0e, 0xd1, 0xdf, + 0x46, 0x11, 0x62, 0x07, 0x00, 0x0e, 0x61, 0x07, + 0x00, 0x07, 0xab, 0x68, 0xa6, 0x00, 0x00, 0x00, + 0x60, 0x08, 0x00, 0x06, 0x11, 0xf2, 0xeb, 0x0c, + 0x6f, 0x41, 0x32, 0x00, 0x00, 0x00, 0xc2, 0x08, + 0x0e, 0xec, 0x05, 0x0e, 0xd1, 0xec, 0xf2, 0x61, + 0x08, 0x00, 0x8c, 0x11, 0xeb, 0x03, 0x0e, 0xb4, + 0x11, 0x62, 0x08, 0x00, 0x0e, 0x61, 0x05, 0x00, + 0xea, 0x0c, 0xc1, 0x0d, 0x11, 0x61, 0x08, 0x00, + 0x21, 0x01, 0x00, 0xec, 0x06, 0xe0, 0x61, 0x08, + 0x00, 0xef, 0x11, 0x62, 0x03, 0x00, 0x0e, 0x61, + 0x04, 0x00, 0x61, 0x08, 0x00, 0xa5, 0x68, 0x2a, + 0x01, 0x00, 0x00, 0x60, 0x09, 0x00, 0xd1, 0x61, + 0x04, 0x00, 0x46, 0xc2, 0x09, 0x61, 0x06, 0x00, + 0xea, 0x0a, 0x61, 0x09, 0x00, 0x8a, 0x11, 0x62, + 0x09, 0x00, 0x0e, 0xd2, 0xea, 0x17, 0xd2, 0x41, + 0xf2, 0x00, 0x00, 0x00, 0xd3, 0x61, 0x09, 0x00, + 0x61, 0x04, 0x00, 0x24, 0x03, 0x00, 0x8a, 0x11, + 0x62, 0x09, 0x00, 0x0e, 0x5d, 0x04, 0x00, 0x61, + 0x03, 0x00, 0x61, 0x04, 0x00, 0x90, 0x62, 0x04, + 0x00, 0x0b, 0x61, 0x09, 0x00, 0x4b, 0x41, 0x00, + 0x00, 0x00, 0x0a, 0x4b, 0x3e, 0x00, 0x00, 0x00, + 0x0a, 0x4b, 0x3f, 0x00, 0x00, 0x00, 0xf1, 0x0e, + 0xec, 0x9e, 0x60, 0x0a, 0x00, 0x61, 0x07, 0x00, + 0x41, 0xf2, 0x00, 0x00, 0x00, 0xd1, 0x24, 0x01, + 0x00, 0xc2, 0x0a, 0x61, 0x05, 0x00, 0xea, 0x09, + 0xc1, 0x0d, 0x11, 0x21, 0x00, 0x00, 0xec, 0x03, + 0xe0, 0xee, 0x11, 0x62, 0x03, 0x00, 0x0e, 0x6b, + 0x8c, 0x00, 0x00, 0x00, 0x60, 0x0c, 0x00, 0x60, + 0x0b, 0x00, 0x06, 0x11, 0xf2, 0xeb, 0x13, 0x6f, + 0x41, 0x41, 0x00, 0x00, 0x00, 0xc2, 0x0b, 0x41, + 0x6a, 0x00, 0x00, 0x00, 0xc2, 0x0c, 0x0e, 0xec, + 0x10, 0x0e, 0x61, 0x0a, 0x00, 0x41, 0x6b, 0x00, + 0x00, 0x00, 0x24, 0x00, 0x00, 0x8a, 0xec, 0xe0, + 0x61, 0x0c, 0x00, 0xeb, 0x4e, 0x61, 0x06, 0x00, + 0xea, 0x0a, 0x61, 0x0b, 0x00, 0x8a, 0x11, 0x62, + 0x0b, 0x00, 0x0e, 0xd2, 0xea, 0x17, 0xd2, 0x41, + 0xf2, 0x00, 0x00, 0x00, 0xd3, 0x61, 0x0b, 0x00, + 0x61, 0x04, 0x00, 0x24, 0x03, 0x00, 0x8a, 0x11, + 0x62, 0x0b, 0x00, 0x0e, 0x5d, 0x04, 0x00, 0x61, + 0x03, 0x00, 0x61, 0x04, 0x00, 0x90, 0x62, 0x04, + 0x00, 0x0b, 0x61, 0x0b, 0x00, 0x4b, 0x41, 0x00, + 0x00, 0x00, 0x0a, 0x4b, 0x3e, 0x00, 0x00, 0x00, + 0x0a, 0x4b, 0x3f, 0x00, 0x00, 0x00, 0xf1, 0x0e, + 0xec, 0x83, 0x0e, 0x06, 0x6c, 0x0d, 0x00, 0x00, + 0x00, 0x0e, 0xec, 0x1e, 0x6c, 0x05, 0x00, 0x00, + 0x00, 0x30, 0x61, 0x0a, 0x00, 0x40, 0x06, 0x00, + 0x00, 0x00, 0xea, 0x0d, 0x61, 0x0a, 0x00, 0x41, + 0x06, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x0e, + 0x6d, 0x61, 0x03, 0x00, 0x61, 0x04, 0x00, 0x42, + 0x32, 0x00, 0x00, 0x00, 0x61, 0x03, 0x00, 0x2f, + 0xbf, 0x00, 0x28, 0xbf, 0x00, 0xcd, 0x28, +}; + + +/* File generated automatically by the QuickJS-ng compiler. */ + +#include + +const uint32_t qjsc_builtin_iterator_zip_keyed_size = 2578; + +const uint8_t qjsc_builtin_iterator_zip_keyed[2578] = { + 0x17, 0x2b, 0x01, 0x1c, 0x49, 0x74, 0x65, 0x72, + 0x61, 0x74, 0x6f, 0x72, 0x48, 0x65, 0x6c, 0x70, + 0x65, 0x72, 0x01, 0x08, 0x63, 0x61, 0x6c, 0x6c, + 0x01, 0x24, 0x68, 0x61, 0x73, 0x4f, 0x77, 0x6e, + 0x45, 0x6e, 0x75, 0x6d, 0x50, 0x72, 0x6f, 0x70, + 0x65, 0x72, 0x74, 0x79, 0x01, 0x24, 0x67, 0x65, + 0x74, 0x4f, 0x77, 0x6e, 0x50, 0x72, 0x6f, 0x70, + 0x65, 0x72, 0x74, 0x79, 0x4b, 0x65, 0x79, 0x73, + 0x01, 0x1e, 0x53, 0x79, 0x6d, 0x62, 0x6f, 0x6c, + 0xb7, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x6f, + 0x72, 0x01, 0x0a, 0x63, 0x68, 0x65, 0x63, 0x6b, + 0x01, 0x0a, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x01, + 0x10, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x61, 0x6c, + 0x6c, 0x01, 0x02, 0x76, 0x01, 0x02, 0x73, 0x01, + 0x08, 0x69, 0x74, 0x65, 0x72, 0x01, 0x0c, 0x6d, + 0x65, 0x74, 0x68, 0x6f, 0x64, 0x01, 0x02, 0x65, + 0x01, 0x0a, 0x69, 0x74, 0x65, 0x72, 0x73, 0x01, + 0x0a, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x01, 0x04, + 0x65, 0x78, 0x01, 0x02, 0x69, 0x01, 0x12, 0x69, + 0x74, 0x65, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, + 0x01, 0x0e, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x01, 0x08, 0x6d, 0x6f, 0x64, 0x65, 0x01, + 0x0e, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, + 0x01, 0x0a, 0x6e, 0x65, 0x78, 0x74, 0x73, 0x01, + 0x08, 0x70, 0x61, 0x64, 0x73, 0x01, 0x06, 0x6b, + 0x65, 0x79, 0x01, 0x06, 0x64, 0x65, 0x6c, 0x01, + 0x02, 0x6a, 0x01, 0x0a, 0x73, 0x74, 0x61, 0x74, + 0x65, 0x01, 0x0a, 0x61, 0x6c, 0x69, 0x76, 0x65, + 0x01, 0x0a, 0x64, 0x6f, 0x6e, 0x65, 0x73, 0x01, + 0x0e, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, + 0x01, 0x0c, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x01, 0x1c, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, + 0x67, 0x20, 0x7a, 0x69, 0x70, 0x70, 0x65, 0x72, + 0x01, 0x06, 0x62, 0x75, 0x67, 0x01, 0x0e, 0x6c, + 0x6f, 0x6e, 0x67, 0x65, 0x73, 0x74, 0x01, 0x0c, + 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x01, 0x22, + 0x6d, 0x69, 0x73, 0x6d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x64, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, + 0x73, 0x01, 0x10, 0x73, 0x68, 0x6f, 0x72, 0x74, + 0x65, 0x73, 0x74, 0x01, 0x16, 0x62, 0x75, 0x67, + 0x3a, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x3d, + 0x01, 0x1a, 0x62, 0x61, 0x64, 0x20, 0x69, 0x74, + 0x65, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x01, + 0x16, 0x62, 0x61, 0x64, 0x20, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x01, 0x10, 0x62, 0x61, + 0x64, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x01, 0x16, + 0x62, 0x61, 0x64, 0x20, 0x70, 0x61, 0x64, 0x64, + 0x69, 0x6e, 0x67, 0x01, 0x18, 0x62, 0x61, 0x64, + 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x6f, + 0x72, 0x0c, 0x00, 0x02, 0x00, 0xa2, 0x01, 0x00, + 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x04, 0x01, + 0xa4, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x43, 0x02, + 0x00, 0x00, 0x07, 0x03, 0x07, 0x01, 0x0a, 0x00, + 0x04, 0x0c, 0x0a, 0xca, 0x03, 0x00, 0x01, 0x40, + 0x09, 0xa8, 0x03, 0x00, 0x01, 0x40, 0x03, 0xa4, + 0x03, 0x00, 0x01, 0x40, 0x00, 0xcc, 0x03, 0x00, + 0x01, 0x40, 0x01, 0xce, 0x03, 0x00, 0x01, 0x40, + 0x07, 0xd0, 0x03, 0x00, 0x01, 0x40, 0x06, 0xd2, + 0x03, 0x00, 0x01, 0x40, 0x08, 0xd4, 0x03, 0x00, + 0x00, 0x40, 0x05, 0xd6, 0x03, 0x00, 0x01, 0x40, + 0x02, 0xd8, 0x03, 0x00, 0x02, 0x40, 0x04, 0x0c, + 0x43, 0x02, 0x00, 0xd4, 0x03, 0x02, 0x00, 0x02, + 0x03, 0x00, 0x01, 0x00, 0x17, 0x02, 0xda, 0x03, + 0x00, 0x01, 0x00, 0xdc, 0x03, 0x00, 0x01, 0x00, + 0xa4, 0x03, 0x02, 0x01, 0xd1, 0x96, 0x04, 0x4a, + 0x00, 0x00, 0x00, 0xad, 0xea, 0x07, 0xd1, 0x07, + 0xae, 0xea, 0x02, 0x29, 0xdd, 0x11, 0xd2, 0x21, + 0x01, 0x00, 0x30, 0x0c, 0x43, 0x02, 0x00, 0xd6, + 0x03, 0x01, 0x02, 0x01, 0x04, 0x00, 0x01, 0x00, + 0x2e, 0x03, 0xde, 0x03, 0x00, 0x01, 0x00, 0xe0, + 0x03, 0x02, 0x00, 0x20, 0xe2, 0x03, 0x05, 0x00, + 0x03, 0xcc, 0x03, 0x03, 0x01, 0x6b, 0x23, 0x00, + 0x00, 0x00, 0x60, 0x00, 0x00, 0xd1, 0x95, 0xea, + 0x04, 0x06, 0x6e, 0x28, 0xd1, 0x40, 0x06, 0x00, + 0x00, 0x00, 0xc9, 0x61, 0x00, 0x00, 0xea, 0x08, + 0xdd, 0xd1, 0x61, 0x00, 0x00, 0xf0, 0x0e, 0x0e, + 0x29, 0xca, 0x6b, 0x07, 0x00, 0x00, 0x00, 0xc6, + 0x6e, 0x28, 0x30, 0x0c, 0x43, 0x02, 0x00, 0xd8, + 0x03, 0x02, 0x04, 0x02, 0x03, 0x00, 0x01, 0x00, + 0x55, 0x06, 0xe4, 0x03, 0x00, 0x01, 0x00, 0xe6, + 0x03, 0x00, 0x01, 0x00, 0xe8, 0x03, 0x01, 0x00, + 0x20, 0xea, 0x03, 0x02, 0x01, 0x20, 0xde, 0x03, + 0x03, 0x02, 0x20, 0xe2, 0x03, 0x03, 0x03, 0x20, + 0xd6, 0x03, 0x01, 0x00, 0x60, 0x00, 0x00, 0x38, + 0x46, 0x00, 0x00, 0x00, 0xc9, 0x60, 0x01, 0x00, + 0xd2, 0xca, 0x61, 0x01, 0x00, 0x8f, 0x62, 0x01, + 0x00, 0xb4, 0xa7, 0xea, 0x39, 0x60, 0x03, 0x00, + 0x60, 0x02, 0x00, 0xd1, 0x61, 0x01, 0x00, 0x46, + 0xcb, 0xd1, 0x61, 0x01, 0x00, 0x1b, 0x11, 0xaf, + 0xeb, 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x38, 0x46, + 0x00, 0x00, 0x00, 0x1b, 0x70, 0x1b, 0x48, 0xdd, + 0x61, 0x02, 0x00, 0xef, 0xcc, 0x61, 0x00, 0x00, + 0x95, 0xea, 0xc8, 0x61, 0x03, 0x00, 0x11, 0x62, + 0x00, 0x00, 0x0e, 0xec, 0xbe, 0x61, 0x00, 0x00, + 0x28, 0x0c, 0x41, 0x02, 0x00, 0xaa, 0x02, 0x02, + 0x15, 0x01, 0x06, 0x08, 0x09, 0x02, 0xc9, 0x05, + 0x17, 0xec, 0x03, 0x00, 0x01, 0x00, 0xee, 0x03, + 0x00, 0x01, 0x00, 0xec, 0x03, 0x01, 0xff, 0xff, + 0xff, 0xff, 0x0f, 0x20, 0xee, 0x03, 0x01, 0x01, + 0x20, 0xf0, 0x03, 0x02, 0x00, 0x60, 0x04, 0xf2, + 0x03, 0x02, 0x03, 0x20, 0x60, 0x02, 0x04, 0x60, + 0x02, 0xe6, 0x03, 0x02, 0x05, 0x60, 0x01, 0xe4, + 0x03, 0x02, 0x06, 0x60, 0x03, 0xf4, 0x03, 0x02, + 0x07, 0x60, 0x06, 0xf6, 0x03, 0x02, 0x08, 0x60, + 0x05, 0xf8, 0x03, 0x09, 0x15, 0x20, 0xea, 0x03, + 0x0b, 0x15, 0x20, 0xfa, 0x03, 0x0c, 0x0b, 0x20, + 0xf8, 0x03, 0x0c, 0x0c, 0x20, 0xde, 0x03, 0x0e, + 0x0d, 0x20, 0xe0, 0x03, 0x10, 0x0e, 0x20, 0xfc, + 0x03, 0x14, 0x0d, 0x20, 0xea, 0x03, 0x19, 0x15, + 0x20, 0xea, 0x03, 0x1b, 0x15, 0x20, 0xe2, 0x03, + 0x1c, 0x15, 0x03, 0xfe, 0x03, 0x02, 0x09, 0x60, + 0x00, 0x80, 0x04, 0x02, 0x14, 0x60, 0x07, 0xa4, + 0x03, 0x02, 0x01, 0xa8, 0x03, 0x01, 0x01, 0xcc, + 0x03, 0x03, 0x01, 0xd8, 0x03, 0x02, 0x00, 0xd4, + 0x03, 0x00, 0x00, 0xd0, 0x03, 0x05, 0x01, 0xce, + 0x03, 0x04, 0x01, 0xd2, 0x03, 0x06, 0x01, 0xca, + 0x03, 0x00, 0x01, 0x0c, 0x42, 0x03, 0x00, 0x00, + 0x00, 0x09, 0x00, 0x05, 0x00, 0x0c, 0x00, 0xf7, + 0x04, 0x09, 0x82, 0x04, 0x01, 0x00, 0x20, 0xd8, + 0x01, 0x01, 0x01, 0x20, 0x84, 0x04, 0x01, 0x02, + 0x20, 0xea, 0x03, 0x03, 0x03, 0x20, 0xf8, 0x03, + 0x04, 0x04, 0x20, 0xde, 0x03, 0x04, 0x05, 0x20, + 0x86, 0x04, 0x04, 0x06, 0x20, 0xe2, 0x03, 0x09, + 0x07, 0x03, 0xe8, 0x03, 0x10, 0x07, 0x20, 0xfe, + 0x03, 0x13, 0x10, 0xa4, 0x03, 0x00, 0x02, 0xa8, + 0x03, 0x01, 0x02, 0xe6, 0x03, 0x05, 0x10, 0x60, + 0x04, 0x10, 0xe4, 0x03, 0x06, 0x10, 0xf0, 0x03, + 0x02, 0x10, 0xf6, 0x03, 0x08, 0x10, 0xcc, 0x03, + 0x02, 0x02, 0xf4, 0x03, 0x07, 0x10, 0x80, 0x04, + 0x14, 0x10, 0xd8, 0x03, 0x03, 0x02, 0x60, 0x02, + 0x00, 0x60, 0x01, 0x00, 0x60, 0x00, 0x00, 0x64, + 0x00, 0x00, 0x11, 0xb4, 0xad, 0xeb, 0x06, 0x11, + 0xb5, 0xad, 0xea, 0x09, 0xb6, 0x11, 0x65, 0x00, + 0x00, 0x0e, 0xec, 0x33, 0x11, 0xb6, 0xad, 0xea, + 0x0c, 0xde, 0x11, 0x04, 0x04, 0x01, 0x00, 0x00, + 0x21, 0x01, 0x00, 0x30, 0x11, 0xb7, 0xad, 0xea, + 0x13, 0x0b, 0x38, 0x46, 0x00, 0x00, 0x00, 0x4b, + 0x41, 0x00, 0x00, 0x00, 0x0a, 0x4b, 0x6a, 0x00, + 0x00, 0x00, 0x28, 0xdf, 0x11, 0x04, 0x05, 0x01, + 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, 0x0e, 0xb4, + 0xc9, 0xb4, 0xca, 0x0c, 0x07, 0xcb, 0x60, 0x03, + 0x00, 0xb4, 0xcc, 0x61, 0x03, 0x00, 0x64, 0x03, + 0x00, 0xa5, 0x68, 0xdd, 0x01, 0x00, 0x00, 0x60, + 0x06, 0x00, 0x60, 0x05, 0x00, 0x60, 0x04, 0x00, + 0x64, 0x04, 0x00, 0x61, 0x03, 0x00, 0x46, 0xc2, + 0x04, 0x64, 0x05, 0x00, 0x61, 0x03, 0x00, 0x46, + 0xc2, 0x05, 0x61, 0x05, 0x00, 0x95, 0xea, 0x34, + 0x64, 0x06, 0x00, 0x04, 0x06, 0x01, 0x00, 0x00, + 0xae, 0xea, 0x0c, 0xdf, 0x11, 0x04, 0x05, 0x01, + 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, 0x61, 0x02, + 0x00, 0x61, 0x04, 0x00, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x64, 0x07, 0x00, + 0x61, 0x03, 0x00, 0x46, 0x1b, 0x70, 0x1b, 0x48, + 0xed, 0x7c, 0x01, 0x06, 0xc2, 0x06, 0x6b, 0x1a, + 0x00, 0x00, 0x00, 0x5d, 0x08, 0x00, 0x61, 0x05, + 0x00, 0x64, 0x09, 0x00, 0x61, 0x03, 0x00, 0x46, + 0xf0, 0x11, 0x62, 0x06, 0x00, 0x0e, 0x0e, 0xec, + 0x35, 0xc2, 0x07, 0x6b, 0x30, 0x00, 0x00, 0x00, + 0xb4, 0x11, 0x65, 0x0a, 0x00, 0x0e, 0x64, 0x05, + 0x00, 0x61, 0x03, 0x00, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x38, 0x46, 0x00, + 0x00, 0x00, 0x1b, 0x70, 0x1b, 0x48, 0x5d, 0x0b, + 0x00, 0x64, 0x05, 0x00, 0x64, 0x03, 0x00, 0xf0, + 0x0e, 0xc1, 0x07, 0x30, 0x30, 0x61, 0x06, 0x00, + 0x40, 0x6a, 0x00, 0x00, 0x00, 0x95, 0xea, 0x4f, + 0x64, 0x06, 0x00, 0x04, 0x07, 0x01, 0x00, 0x00, + 0xad, 0xea, 0x1e, 0x61, 0x00, 0x00, 0xb4, 0xa7, + 0xea, 0x17, 0x5d, 0x0b, 0x00, 0x64, 0x05, 0x00, + 0x64, 0x03, 0x00, 0xf0, 0x0e, 0xde, 0x11, 0x04, + 0x08, 0x01, 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, + 0x61, 0x02, 0x00, 0x61, 0x04, 0x00, 0x1b, 0x11, + 0xaf, 0xeb, 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x61, + 0x06, 0x00, 0x40, 0x41, 0x00, 0x00, 0x00, 0x1b, + 0x70, 0x1b, 0x48, 0x61, 0x01, 0x00, 0x90, 0x62, + 0x01, 0x00, 0x0e, 0xed, 0xd1, 0x00, 0x64, 0x0a, + 0x00, 0x8f, 0x65, 0x0a, 0x00, 0x0e, 0x61, 0x00, + 0x00, 0x90, 0x62, 0x00, 0x00, 0x0e, 0x64, 0x05, + 0x00, 0x61, 0x03, 0x00, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x38, 0x46, 0x00, + 0x00, 0x00, 0x1b, 0x70, 0x1b, 0x48, 0x64, 0x06, + 0x00, 0x60, 0x08, 0x00, 0x11, 0x04, 0x09, 0x01, + 0x00, 0x00, 0xad, 0xea, 0x2e, 0x5d, 0x0b, 0x00, + 0x64, 0x05, 0x00, 0x64, 0x03, 0x00, 0xf0, 0xc2, + 0x08, 0x61, 0x08, 0x00, 0xea, 0x05, 0x61, 0x08, + 0x00, 0x30, 0xb7, 0x11, 0x65, 0x00, 0x00, 0x0e, + 0x0b, 0x38, 0x46, 0x00, 0x00, 0x00, 0x4b, 0x41, + 0x00, 0x00, 0x00, 0x0a, 0x4b, 0x6a, 0x00, 0x00, + 0x00, 0x28, 0x11, 0x04, 0x06, 0x01, 0x00, 0x00, + 0xad, 0xea, 0x3c, 0x64, 0x0a, 0x00, 0xb5, 0xa5, + 0xea, 0x19, 0xb7, 0x11, 0x65, 0x00, 0x00, 0x0e, + 0x0b, 0x38, 0x46, 0x00, 0x00, 0x00, 0x4b, 0x41, + 0x00, 0x00, 0x00, 0x0a, 0x4b, 0x6a, 0x00, 0x00, + 0x00, 0x28, 0x61, 0x02, 0x00, 0x61, 0x04, 0x00, + 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, 0x70, 0x1b, + 0x1b, 0x64, 0x07, 0x00, 0x61, 0x03, 0x00, 0x46, + 0x1b, 0x70, 0x1b, 0x48, 0xec, 0x27, 0x11, 0x04, + 0x07, 0x01, 0x00, 0x00, 0xad, 0xea, 0x1e, 0x61, + 0x01, 0x00, 0xb4, 0xa7, 0xea, 0x17, 0x5d, 0x0b, + 0x00, 0x64, 0x05, 0x00, 0x64, 0x03, 0x00, 0xf0, + 0x0e, 0xde, 0x11, 0x04, 0x08, 0x01, 0x00, 0x00, + 0x21, 0x01, 0x00, 0x30, 0x0e, 0x61, 0x03, 0x00, + 0x90, 0x62, 0x03, 0x00, 0x0e, 0xed, 0x1d, 0xfe, + 0x61, 0x01, 0x00, 0xb4, 0xad, 0xea, 0x19, 0xb7, + 0x11, 0x65, 0x00, 0x00, 0x0e, 0x0b, 0x38, 0x46, + 0x00, 0x00, 0x00, 0x4b, 0x41, 0x00, 0x00, 0x00, + 0x0a, 0x4b, 0x6a, 0x00, 0x00, 0x00, 0x28, 0xb5, + 0x11, 0x65, 0x00, 0x00, 0x0e, 0x0b, 0x61, 0x02, + 0x00, 0x4b, 0x41, 0x00, 0x00, 0x00, 0x09, 0x4b, + 0x6a, 0x00, 0x00, 0x00, 0x28, 0x0c, 0x42, 0x03, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x06, + 0x00, 0x88, 0x01, 0x01, 0xe8, 0x03, 0x01, 0x00, + 0x20, 0xfe, 0x03, 0x13, 0x10, 0xa4, 0x03, 0x00, + 0x02, 0xa8, 0x03, 0x01, 0x02, 0xd8, 0x03, 0x03, + 0x02, 0xe4, 0x03, 0x06, 0x10, 0xe6, 0x03, 0x05, + 0x10, 0x60, 0x00, 0x00, 0x64, 0x00, 0x00, 0x11, + 0xb4, 0xad, 0xea, 0x09, 0xb7, 0x11, 0x65, 0x00, + 0x00, 0x0e, 0xec, 0x4b, 0x11, 0xb5, 0xad, 0xea, + 0x09, 0xb6, 0x11, 0x65, 0x00, 0x00, 0x0e, 0xec, + 0x3e, 0x11, 0xb6, 0xad, 0xea, 0x0c, 0xde, 0x11, + 0x04, 0x04, 0x01, 0x00, 0x00, 0x21, 0x01, 0x00, + 0x30, 0x11, 0xb7, 0xad, 0xea, 0x13, 0x0b, 0x38, + 0x46, 0x00, 0x00, 0x00, 0x4b, 0x41, 0x00, 0x00, + 0x00, 0x0a, 0x4b, 0x6a, 0x00, 0x00, 0x00, 0x28, + 0xdf, 0x11, 0x04, 0x0a, 0x01, 0x00, 0x00, 0x41, + 0x5d, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x24, + 0x01, 0x00, 0x21, 0x01, 0x00, 0x30, 0x0e, 0xe0, + 0x64, 0x04, 0x00, 0x64, 0x05, 0x00, 0xf0, 0xc9, + 0x61, 0x00, 0x00, 0xea, 0x05, 0x61, 0x00, 0x00, + 0x30, 0xb7, 0x11, 0x65, 0x00, 0x00, 0x0e, 0x0b, + 0x38, 0x46, 0x00, 0x00, 0x00, 0x4b, 0x41, 0x00, + 0x00, 0x00, 0x0a, 0x4b, 0x6a, 0x00, 0x00, 0x00, + 0x28, 0x60, 0x01, 0x00, 0x60, 0x00, 0x00, 0xd1, + 0xc9, 0xd2, 0x11, 0xf2, 0xea, 0x08, 0x0e, 0x38, + 0x46, 0x00, 0x00, 0x00, 0xda, 0xca, 0x60, 0x14, + 0x00, 0x60, 0x13, 0x00, 0x60, 0x08, 0x00, 0x60, + 0x07, 0x00, 0x60, 0x06, 0x00, 0x60, 0x05, 0x00, + 0x60, 0x04, 0x00, 0x60, 0x03, 0x00, 0x60, 0x02, + 0x00, 0x5d, 0x04, 0x00, 0xd1, 0x04, 0x0b, 0x01, + 0x00, 0x00, 0xf0, 0x0e, 0xd2, 0x38, 0x46, 0x00, + 0x00, 0x00, 0xad, 0xea, 0x06, 0x0c, 0x07, 0xd6, + 0xec, 0x0c, 0x5d, 0x04, 0x00, 0xd2, 0x04, 0x0c, + 0x01, 0x00, 0x00, 0xf0, 0x0e, 0xd2, 0x40, 0xf8, + 0x00, 0x00, 0x00, 0xcb, 0x61, 0x02, 0x00, 0x38, + 0x46, 0x00, 0x00, 0x00, 0xad, 0xea, 0x0b, 0x04, + 0x09, 0x01, 0x00, 0x00, 0x11, 0x62, 0x02, 0x00, + 0x0e, 0x61, 0x02, 0x00, 0x04, 0x07, 0x01, 0x00, + 0x00, 0xad, 0x11, 0xeb, 0x18, 0x0e, 0x61, 0x02, + 0x00, 0x04, 0x06, 0x01, 0x00, 0x00, 0xad, 0x11, + 0xeb, 0x0b, 0x0e, 0x61, 0x02, 0x00, 0x04, 0x09, + 0x01, 0x00, 0x00, 0xad, 0x95, 0xea, 0x0c, 0xdd, + 0x11, 0x04, 0x0d, 0x01, 0x00, 0x00, 0x21, 0x01, + 0x00, 0x30, 0x38, 0x46, 0x00, 0x00, 0x00, 0xcc, + 0x61, 0x02, 0x00, 0x04, 0x06, 0x01, 0x00, 0x00, + 0xad, 0xea, 0x24, 0xd2, 0x40, 0xf9, 0x00, 0x00, + 0x00, 0x11, 0x62, 0x03, 0x00, 0x0e, 0x61, 0x03, + 0x00, 0x38, 0x46, 0x00, 0x00, 0x00, 0xae, 0xea, + 0x0e, 0x5d, 0x04, 0x00, 0x61, 0x03, 0x00, 0x04, + 0x0e, 0x01, 0x00, 0x00, 0xf0, 0x0e, 0x26, 0x00, + 0x00, 0xc2, 0x04, 0xb4, 0xc2, 0x05, 0x26, 0x00, + 0x00, 0xc2, 0x06, 0x26, 0x00, 0x00, 0xc2, 0x07, + 0x26, 0x00, 0x00, 0xc2, 0x08, 0x60, 0x09, 0x00, + 0x5d, 0x05, 0x00, 0xd1, 0xef, 0x7d, 0xec, 0x1d, + 0xc2, 0x09, 0x61, 0x04, 0x00, 0x61, 0x05, 0x00, + 0x90, 0x62, 0x05, 0x00, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x61, 0x09, 0x00, + 0x1b, 0x70, 0x1b, 0x48, 0x80, 0x00, 0xea, 0xe1, + 0x0e, 0x83, 0x6b, 0x7d, 0x01, 0x00, 0x00, 0x60, + 0x0a, 0x00, 0xb4, 0xc2, 0x0a, 0x61, 0x0a, 0x00, + 0x61, 0x05, 0x00, 0xa5, 0x68, 0xf0, 0x00, 0x00, + 0x00, 0x60, 0x0c, 0x00, 0x60, 0x0b, 0x00, 0x0a, + 0xc2, 0x0b, 0x61, 0x04, 0x00, 0x61, 0x0a, 0x00, + 0x46, 0xc2, 0x0c, 0x5d, 0x06, 0x00, 0xd1, 0x61, + 0x0c, 0x00, 0xf0, 0xea, 0x78, 0x60, 0x0d, 0x00, + 0xd1, 0x61, 0x0c, 0x00, 0x46, 0xc2, 0x0d, 0x61, + 0x0d, 0x00, 0x38, 0x46, 0x00, 0x00, 0x00, 0xae, + 0xea, 0x63, 0x60, 0x0e, 0x00, 0x5d, 0x04, 0x00, + 0x61, 0x0d, 0x00, 0x04, 0x0f, 0x01, 0x00, 0x00, + 0xf0, 0x0e, 0x61, 0x0d, 0x00, 0x5d, 0x07, 0x00, + 0x46, 0xc2, 0x0e, 0x61, 0x0e, 0x00, 0xea, 0x0e, + 0xdf, 0x61, 0x0d, 0x00, 0x61, 0x0e, 0x00, 0xf0, + 0x11, 0x62, 0x0d, 0x00, 0x0e, 0x61, 0x06, 0x00, + 0x61, 0x0a, 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, + 0x1b, 0x70, 0x1b, 0x1b, 0x61, 0x0d, 0x00, 0x1b, + 0x70, 0x1b, 0x48, 0x61, 0x07, 0x00, 0x61, 0x0a, + 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, 0x70, + 0x1b, 0x1b, 0x61, 0x0d, 0x00, 0x40, 0x6b, 0x00, + 0x00, 0x00, 0x1b, 0x70, 0x1b, 0x48, 0x09, 0x11, + 0x62, 0x0b, 0x00, 0x0e, 0x61, 0x0b, 0x00, 0xea, + 0x4a, 0x60, 0x0f, 0x00, 0x61, 0x0a, 0x00, 0xb5, + 0x9c, 0xc2, 0x0f, 0x61, 0x0f, 0x00, 0x61, 0x05, + 0x00, 0xa5, 0xea, 0x27, 0x61, 0x04, 0x00, 0x61, + 0x0f, 0x00, 0xb5, 0x9d, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x61, 0x04, 0x00, + 0x61, 0x0f, 0x00, 0x46, 0x1b, 0x70, 0x1b, 0x48, + 0x61, 0x0f, 0x00, 0x90, 0x62, 0x0f, 0x00, 0x0e, + 0xec, 0xd2, 0x61, 0x05, 0x00, 0x8f, 0x62, 0x05, + 0x00, 0x0e, 0x61, 0x0a, 0x00, 0x8f, 0x62, 0x0a, + 0x00, 0x0e, 0x61, 0x0a, 0x00, 0x90, 0x62, 0x0a, + 0x00, 0x0e, 0xed, 0x0a, 0xff, 0x61, 0x02, 0x00, + 0x04, 0x06, 0x01, 0x00, 0x00, 0xad, 0xea, 0x6e, + 0x61, 0x03, 0x00, 0xea, 0x38, 0x60, 0x10, 0x00, + 0xb4, 0xc2, 0x10, 0x61, 0x10, 0x00, 0x61, 0x05, + 0x00, 0xa5, 0xea, 0x5a, 0x61, 0x08, 0x00, 0x61, + 0x10, 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, + 0x70, 0x1b, 0x1b, 0x61, 0x03, 0x00, 0x61, 0x04, + 0x00, 0x61, 0x10, 0x00, 0x46, 0x46, 0x1b, 0x70, + 0x1b, 0x48, 0x61, 0x10, 0x00, 0x90, 0x62, 0x10, + 0x00, 0x0e, 0xec, 0xd0, 0x60, 0x11, 0x00, 0xb4, + 0xc2, 0x11, 0x61, 0x11, 0x00, 0x61, 0x05, 0x00, + 0xa5, 0xea, 0x23, 0x61, 0x08, 0x00, 0x61, 0x11, + 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, 0x70, + 0x1b, 0x1b, 0x38, 0x46, 0x00, 0x00, 0x00, 0x1b, + 0x70, 0x1b, 0x48, 0x61, 0x11, 0x00, 0x90, 0x62, + 0x11, 0x00, 0x0e, 0xec, 0xd6, 0x0e, 0xec, 0x15, + 0xc2, 0x12, 0x6b, 0x10, 0x00, 0x00, 0x00, 0xe0, + 0x61, 0x06, 0x00, 0x61, 0x05, 0x00, 0xf0, 0x0e, + 0xc1, 0x12, 0x30, 0x30, 0xb4, 0xc2, 0x13, 0x61, + 0x05, 0x00, 0xc2, 0x14, 0x0b, 0x5d, 0x08, 0x00, + 0x4e, 0xbf, 0x00, 0x53, 0x6b, 0x00, 0x00, 0x00, + 0x04, 0xbf, 0x01, 0x53, 0x06, 0x00, 0x00, 0x00, + 0x04, 0x28, 0xbf, 0x00, 0xc9, 0xbf, 0x01, 0xca, + 0xbf, 0x02, 0xcb, 0xbf, 0x03, 0x28, 0xbf, 0x00, + 0xcd, 0x28, +}; + + +/* File generated automatically by the QuickJS-ng compiler. */ + +#include + +const uint32_t qjsc_builtin_iterator_zip_size = 2617; + +const uint8_t qjsc_builtin_iterator_zip[2617] = { + 0x17, 0x2a, 0x01, 0x1c, 0x49, 0x74, 0x65, 0x72, + 0x61, 0x74, 0x6f, 0x72, 0x48, 0x65, 0x6c, 0x70, + 0x65, 0x72, 0x01, 0x08, 0x63, 0x61, 0x6c, 0x6c, + 0x01, 0x1e, 0x53, 0x79, 0x6d, 0x62, 0x6f, 0x6c, + 0xb7, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x6f, + 0x72, 0x01, 0x0a, 0x63, 0x68, 0x65, 0x63, 0x6b, + 0x01, 0x0a, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x01, + 0x10, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x61, 0x6c, + 0x6c, 0x01, 0x02, 0x76, 0x01, 0x02, 0x73, 0x01, + 0x08, 0x69, 0x74, 0x65, 0x72, 0x01, 0x0c, 0x6d, + 0x65, 0x74, 0x68, 0x6f, 0x64, 0x01, 0x02, 0x65, + 0x01, 0x0a, 0x69, 0x74, 0x65, 0x72, 0x73, 0x01, + 0x0a, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x01, 0x04, + 0x65, 0x78, 0x01, 0x02, 0x69, 0x01, 0x12, 0x69, + 0x74, 0x65, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, + 0x01, 0x0e, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x01, 0x08, 0x6d, 0x6f, 0x64, 0x65, 0x01, + 0x0e, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, + 0x01, 0x08, 0x70, 0x61, 0x64, 0x73, 0x01, 0x0a, + 0x6e, 0x65, 0x78, 0x74, 0x73, 0x01, 0x16, 0x70, + 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x69, 0x74, + 0x65, 0x72, 0x01, 0x1a, 0x69, 0x74, 0x65, 0x72, + 0x61, 0x62, 0x6c, 0x65, 0x73, 0x69, 0x74, 0x65, + 0x72, 0x01, 0x08, 0x69, 0x74, 0x65, 0x6d, 0x01, + 0x02, 0x74, 0x01, 0x0a, 0x73, 0x74, 0x61, 0x74, + 0x65, 0x01, 0x0a, 0x61, 0x6c, 0x69, 0x76, 0x65, + 0x01, 0x0a, 0x64, 0x6f, 0x6e, 0x65, 0x73, 0x01, + 0x0e, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, + 0x01, 0x0c, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x01, 0x1c, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, + 0x67, 0x20, 0x7a, 0x69, 0x70, 0x70, 0x65, 0x72, + 0x01, 0x06, 0x62, 0x75, 0x67, 0x01, 0x0e, 0x6c, + 0x6f, 0x6e, 0x67, 0x65, 0x73, 0x74, 0x01, 0x0c, + 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x01, 0x22, + 0x6d, 0x69, 0x73, 0x6d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x64, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, + 0x73, 0x01, 0x10, 0x73, 0x68, 0x6f, 0x72, 0x74, + 0x65, 0x73, 0x74, 0x01, 0x16, 0x62, 0x75, 0x67, + 0x3a, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x3d, + 0x01, 0x1a, 0x62, 0x61, 0x64, 0x20, 0x69, 0x74, + 0x65, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x01, + 0x16, 0x62, 0x61, 0x64, 0x20, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x01, 0x10, 0x62, 0x61, + 0x64, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x01, 0x16, + 0x62, 0x61, 0x64, 0x20, 0x70, 0x61, 0x64, 0x64, + 0x69, 0x6e, 0x67, 0x01, 0x18, 0x62, 0x61, 0x64, + 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x6f, + 0x72, 0x0c, 0x00, 0x02, 0x00, 0xa2, 0x01, 0x00, + 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x04, 0x01, + 0xa4, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x43, 0x02, + 0x00, 0x00, 0x05, 0x03, 0x05, 0x01, 0x08, 0x00, + 0x04, 0x0c, 0x08, 0xca, 0x03, 0x00, 0x01, 0x40, + 0x07, 0xa8, 0x03, 0x00, 0x01, 0x40, 0x03, 0xa4, + 0x03, 0x00, 0x01, 0x40, 0x00, 0xcc, 0x03, 0x00, + 0x01, 0x40, 0x01, 0xce, 0x03, 0x00, 0x01, 0x40, + 0x06, 0xd0, 0x03, 0x00, 0x00, 0x40, 0x05, 0xd2, + 0x03, 0x00, 0x01, 0x40, 0x02, 0xd4, 0x03, 0x00, + 0x02, 0x40, 0x04, 0x0c, 0x43, 0x02, 0x00, 0xd0, + 0x03, 0x02, 0x00, 0x02, 0x03, 0x00, 0x01, 0x00, + 0x17, 0x02, 0xd6, 0x03, 0x00, 0x01, 0x00, 0xd8, + 0x03, 0x00, 0x01, 0x00, 0xa4, 0x03, 0x02, 0x01, + 0xd1, 0x96, 0x04, 0x4a, 0x00, 0x00, 0x00, 0xad, + 0xea, 0x07, 0xd1, 0x07, 0xae, 0xea, 0x02, 0x29, + 0xdd, 0x11, 0xd2, 0x21, 0x01, 0x00, 0x30, 0x0c, + 0x43, 0x02, 0x00, 0xd2, 0x03, 0x01, 0x02, 0x01, + 0x04, 0x00, 0x01, 0x00, 0x2e, 0x03, 0xda, 0x03, + 0x00, 0x01, 0x00, 0xdc, 0x03, 0x02, 0x00, 0x20, + 0xde, 0x03, 0x05, 0x00, 0x03, 0xcc, 0x03, 0x03, + 0x01, 0x6b, 0x23, 0x00, 0x00, 0x00, 0x60, 0x00, + 0x00, 0xd1, 0x95, 0xea, 0x04, 0x06, 0x6e, 0x28, + 0xd1, 0x40, 0x06, 0x00, 0x00, 0x00, 0xc9, 0x61, + 0x00, 0x00, 0xea, 0x08, 0xdd, 0xd1, 0x61, 0x00, + 0x00, 0xf0, 0x0e, 0x0e, 0x29, 0xca, 0x6b, 0x07, + 0x00, 0x00, 0x00, 0xc6, 0x6e, 0x28, 0x30, 0x0c, + 0x43, 0x02, 0x00, 0xd4, 0x03, 0x02, 0x04, 0x02, + 0x03, 0x00, 0x01, 0x00, 0x55, 0x06, 0xe0, 0x03, + 0x00, 0x01, 0x00, 0xe2, 0x03, 0x00, 0x01, 0x00, + 0xe4, 0x03, 0x01, 0x00, 0x20, 0xe6, 0x03, 0x02, + 0x01, 0x20, 0xda, 0x03, 0x03, 0x02, 0x20, 0xde, + 0x03, 0x03, 0x03, 0x20, 0xd2, 0x03, 0x01, 0x00, + 0x60, 0x00, 0x00, 0x38, 0x46, 0x00, 0x00, 0x00, + 0xc9, 0x60, 0x01, 0x00, 0xd2, 0xca, 0x61, 0x01, + 0x00, 0x8f, 0x62, 0x01, 0x00, 0xb4, 0xa7, 0xea, + 0x39, 0x60, 0x03, 0x00, 0x60, 0x02, 0x00, 0xd1, + 0x61, 0x01, 0x00, 0x46, 0xcb, 0xd1, 0x61, 0x01, + 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, 0x70, + 0x1b, 0x1b, 0x38, 0x46, 0x00, 0x00, 0x00, 0x1b, + 0x70, 0x1b, 0x48, 0xdd, 0x61, 0x02, 0x00, 0xef, + 0xcc, 0x61, 0x00, 0x00, 0x95, 0xea, 0xc8, 0x61, + 0x03, 0x00, 0x11, 0x62, 0x00, 0x00, 0x0e, 0xec, + 0xbe, 0x61, 0x00, 0x00, 0x28, 0x0c, 0x41, 0x02, + 0x00, 0xa8, 0x02, 0x02, 0x1a, 0x01, 0x05, 0x07, + 0x08, 0x02, 0x8a, 0x06, 0x1c, 0xe8, 0x03, 0x00, + 0x01, 0x00, 0xea, 0x03, 0x00, 0x01, 0x00, 0xe8, + 0x03, 0x01, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x20, + 0xea, 0x03, 0x01, 0x01, 0x20, 0xec, 0x03, 0x02, + 0x00, 0x60, 0x03, 0xee, 0x03, 0x02, 0x03, 0x20, + 0xf0, 0x03, 0x02, 0x04, 0x60, 0x04, 0xe0, 0x03, + 0x02, 0x05, 0x60, 0x02, 0xf2, 0x03, 0x02, 0x06, + 0x60, 0x05, 0xe2, 0x03, 0x02, 0x07, 0x60, 0x01, + 0xf4, 0x03, 0x02, 0x08, 0x20, 0xf6, 0x03, 0x02, + 0x09, 0x20, 0xd6, 0x01, 0x09, 0x1a, 0x20, 0xf8, + 0x03, 0x0b, 0x0b, 0x20, 0xde, 0x03, 0x0d, 0x0f, + 0x03, 0xda, 0x03, 0x0b, 0x0c, 0x20, 0xdc, 0x03, + 0x0b, 0x0e, 0x20, 0xd6, 0x01, 0x13, 0x0b, 0x20, + 0xe6, 0x03, 0x13, 0x10, 0x20, 0xd4, 0x01, 0x13, + 0x11, 0x20, 0x82, 0x01, 0x15, 0x16, 0x20, 0xf8, + 0x03, 0x16, 0x13, 0x20, 0xde, 0x03, 0x17, 0x13, + 0x03, 0xfa, 0x03, 0x13, 0x12, 0x20, 0xe4, 0x03, + 0x1c, 0x16, 0x20, 0xde, 0x03, 0x1f, 0x1a, 0x03, + 0xfc, 0x03, 0x02, 0x0a, 0x60, 0x00, 0xfe, 0x03, + 0x02, 0x19, 0x60, 0x06, 0xa4, 0x03, 0x02, 0x01, + 0xa8, 0x03, 0x01, 0x01, 0xcc, 0x03, 0x03, 0x01, + 0xd4, 0x03, 0x02, 0x00, 0xd0, 0x03, 0x00, 0x00, + 0xce, 0x03, 0x04, 0x01, 0xd2, 0x03, 0x01, 0x00, + 0xca, 0x03, 0x00, 0x01, 0x0c, 0x42, 0x03, 0x00, + 0x00, 0x00, 0x08, 0x00, 0x05, 0x00, 0x0b, 0x00, + 0xec, 0x04, 0x08, 0x80, 0x04, 0x01, 0x00, 0x20, + 0xd8, 0x01, 0x01, 0x01, 0x20, 0x82, 0x04, 0x01, + 0x02, 0x20, 0xe6, 0x03, 0x03, 0x03, 0x20, 0xda, + 0x03, 0x04, 0x04, 0x20, 0x84, 0x04, 0x04, 0x05, + 0x20, 0xde, 0x03, 0x09, 0x06, 0x03, 0xe4, 0x03, + 0x10, 0x06, 0x20, 0xfc, 0x03, 0x18, 0x10, 0xa4, + 0x03, 0x00, 0x02, 0xa8, 0x03, 0x01, 0x02, 0xe2, + 0x03, 0x07, 0x10, 0xe0, 0x03, 0x05, 0x10, 0xec, + 0x03, 0x02, 0x10, 0xf0, 0x03, 0x04, 0x10, 0xcc, + 0x03, 0x02, 0x02, 0xf2, 0x03, 0x06, 0x10, 0xfe, + 0x03, 0x19, 0x10, 0xd4, 0x03, 0x03, 0x02, 0x60, + 0x02, 0x00, 0x60, 0x01, 0x00, 0x60, 0x00, 0x00, + 0x64, 0x00, 0x00, 0x11, 0xb4, 0xad, 0xeb, 0x06, + 0x11, 0xb5, 0xad, 0xea, 0x09, 0xb6, 0x11, 0x65, + 0x00, 0x00, 0x0e, 0xec, 0x33, 0x11, 0xb6, 0xad, + 0xea, 0x0c, 0xde, 0x11, 0x04, 0x03, 0x01, 0x00, + 0x00, 0x21, 0x01, 0x00, 0x30, 0x11, 0xb7, 0xad, + 0xea, 0x13, 0x0b, 0x38, 0x46, 0x00, 0x00, 0x00, + 0x4b, 0x41, 0x00, 0x00, 0x00, 0x0a, 0x4b, 0x6a, + 0x00, 0x00, 0x00, 0x28, 0xdf, 0x11, 0x04, 0x04, + 0x01, 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, 0x0e, + 0xb4, 0xc9, 0xb4, 0xca, 0x26, 0x00, 0x00, 0xcb, + 0x60, 0x03, 0x00, 0xb4, 0xcc, 0x61, 0x03, 0x00, + 0x64, 0x03, 0x00, 0xa5, 0x68, 0xd1, 0x01, 0x00, + 0x00, 0x60, 0x05, 0x00, 0x60, 0x04, 0x00, 0x64, + 0x04, 0x00, 0x61, 0x03, 0x00, 0x46, 0xc2, 0x04, + 0x61, 0x04, 0x00, 0x95, 0xea, 0x34, 0x64, 0x05, + 0x00, 0x04, 0x05, 0x01, 0x00, 0x00, 0xae, 0xea, + 0x0c, 0xdf, 0x11, 0x04, 0x04, 0x01, 0x00, 0x00, + 0x21, 0x01, 0x00, 0x30, 0x61, 0x02, 0x00, 0x61, + 0x03, 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, + 0x70, 0x1b, 0x1b, 0x64, 0x06, 0x00, 0x61, 0x03, + 0x00, 0x46, 0x1b, 0x70, 0x1b, 0x48, 0xed, 0x7c, + 0x01, 0x06, 0xc2, 0x05, 0x6b, 0x1a, 0x00, 0x00, + 0x00, 0x5d, 0x07, 0x00, 0x61, 0x04, 0x00, 0x64, + 0x08, 0x00, 0x61, 0x03, 0x00, 0x46, 0xf0, 0x11, + 0x62, 0x05, 0x00, 0x0e, 0x0e, 0xec, 0x35, 0xc2, + 0x06, 0x6b, 0x30, 0x00, 0x00, 0x00, 0xb4, 0x11, + 0x65, 0x09, 0x00, 0x0e, 0x64, 0x04, 0x00, 0x61, + 0x03, 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, + 0x70, 0x1b, 0x1b, 0x38, 0x46, 0x00, 0x00, 0x00, + 0x1b, 0x70, 0x1b, 0x48, 0x5d, 0x0a, 0x00, 0x64, + 0x04, 0x00, 0x64, 0x03, 0x00, 0xf0, 0x0e, 0xc1, + 0x06, 0x30, 0x30, 0x61, 0x05, 0x00, 0x40, 0x6a, + 0x00, 0x00, 0x00, 0x95, 0xea, 0x4f, 0x64, 0x05, + 0x00, 0x04, 0x06, 0x01, 0x00, 0x00, 0xad, 0xea, + 0x1e, 0x61, 0x00, 0x00, 0xb4, 0xa7, 0xea, 0x17, + 0x5d, 0x0a, 0x00, 0x64, 0x04, 0x00, 0x64, 0x03, + 0x00, 0xf0, 0x0e, 0xde, 0x11, 0x04, 0x07, 0x01, + 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, 0x61, 0x02, + 0x00, 0x61, 0x03, 0x00, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x61, 0x05, 0x00, + 0x40, 0x41, 0x00, 0x00, 0x00, 0x1b, 0x70, 0x1b, + 0x48, 0x61, 0x01, 0x00, 0x90, 0x62, 0x01, 0x00, + 0x0e, 0xed, 0xd1, 0x00, 0x64, 0x09, 0x00, 0x8f, + 0x65, 0x09, 0x00, 0x0e, 0x61, 0x00, 0x00, 0x90, + 0x62, 0x00, 0x00, 0x0e, 0x64, 0x04, 0x00, 0x61, + 0x03, 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, + 0x70, 0x1b, 0x1b, 0x38, 0x46, 0x00, 0x00, 0x00, + 0x1b, 0x70, 0x1b, 0x48, 0x64, 0x05, 0x00, 0x60, + 0x07, 0x00, 0x11, 0x04, 0x08, 0x01, 0x00, 0x00, + 0xad, 0xea, 0x2e, 0x5d, 0x0a, 0x00, 0x64, 0x04, + 0x00, 0x64, 0x03, 0x00, 0xf0, 0xc2, 0x07, 0x61, + 0x07, 0x00, 0xea, 0x05, 0x61, 0x07, 0x00, 0x30, + 0xb7, 0x11, 0x65, 0x00, 0x00, 0x0e, 0x0b, 0x38, + 0x46, 0x00, 0x00, 0x00, 0x4b, 0x41, 0x00, 0x00, + 0x00, 0x0a, 0x4b, 0x6a, 0x00, 0x00, 0x00, 0x28, + 0x11, 0x04, 0x05, 0x01, 0x00, 0x00, 0xad, 0xea, + 0x3c, 0x64, 0x09, 0x00, 0xb5, 0xa5, 0xea, 0x19, + 0xb7, 0x11, 0x65, 0x00, 0x00, 0x0e, 0x0b, 0x38, + 0x46, 0x00, 0x00, 0x00, 0x4b, 0x41, 0x00, 0x00, + 0x00, 0x0a, 0x4b, 0x6a, 0x00, 0x00, 0x00, 0x28, + 0x61, 0x02, 0x00, 0x61, 0x03, 0x00, 0x1b, 0x11, + 0xaf, 0xeb, 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x64, + 0x06, 0x00, 0x61, 0x03, 0x00, 0x46, 0x1b, 0x70, + 0x1b, 0x48, 0xec, 0x27, 0x11, 0x04, 0x06, 0x01, + 0x00, 0x00, 0xad, 0xea, 0x1e, 0x61, 0x01, 0x00, + 0xb4, 0xa7, 0xea, 0x17, 0x5d, 0x0a, 0x00, 0x64, + 0x04, 0x00, 0x64, 0x03, 0x00, 0xf0, 0x0e, 0xde, + 0x11, 0x04, 0x07, 0x01, 0x00, 0x00, 0x21, 0x01, + 0x00, 0x30, 0x0e, 0x61, 0x03, 0x00, 0x90, 0x62, + 0x03, 0x00, 0x0e, 0xed, 0x29, 0xfe, 0x61, 0x01, + 0x00, 0xb4, 0xad, 0xea, 0x19, 0xb7, 0x11, 0x65, + 0x00, 0x00, 0x0e, 0x0b, 0x38, 0x46, 0x00, 0x00, + 0x00, 0x4b, 0x41, 0x00, 0x00, 0x00, 0x0a, 0x4b, + 0x6a, 0x00, 0x00, 0x00, 0x28, 0xb5, 0x11, 0x65, + 0x00, 0x00, 0x0e, 0x0b, 0x61, 0x02, 0x00, 0x4b, + 0x41, 0x00, 0x00, 0x00, 0x09, 0x4b, 0x6a, 0x00, + 0x00, 0x00, 0x28, 0x0c, 0x42, 0x03, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x06, 0x00, 0x06, 0x00, 0x88, + 0x01, 0x01, 0xe4, 0x03, 0x01, 0x00, 0x20, 0xfc, + 0x03, 0x18, 0x10, 0xa4, 0x03, 0x00, 0x02, 0xa8, + 0x03, 0x01, 0x02, 0xd4, 0x03, 0x03, 0x02, 0xe0, + 0x03, 0x05, 0x10, 0xe2, 0x03, 0x07, 0x10, 0x60, + 0x00, 0x00, 0x64, 0x00, 0x00, 0x11, 0xb4, 0xad, + 0xea, 0x09, 0xb7, 0x11, 0x65, 0x00, 0x00, 0x0e, + 0xec, 0x4b, 0x11, 0xb5, 0xad, 0xea, 0x09, 0xb6, + 0x11, 0x65, 0x00, 0x00, 0x0e, 0xec, 0x3e, 0x11, + 0xb6, 0xad, 0xea, 0x0c, 0xde, 0x11, 0x04, 0x03, + 0x01, 0x00, 0x00, 0x21, 0x01, 0x00, 0x30, 0x11, + 0xb7, 0xad, 0xea, 0x13, 0x0b, 0x38, 0x46, 0x00, + 0x00, 0x00, 0x4b, 0x41, 0x00, 0x00, 0x00, 0x0a, + 0x4b, 0x6a, 0x00, 0x00, 0x00, 0x28, 0xdf, 0x11, + 0x04, 0x09, 0x01, 0x00, 0x00, 0x41, 0x5d, 0x00, + 0x00, 0x00, 0x64, 0x00, 0x00, 0x24, 0x01, 0x00, + 0x21, 0x01, 0x00, 0x30, 0x0e, 0xe0, 0x64, 0x04, + 0x00, 0x64, 0x05, 0x00, 0xf0, 0xc9, 0x61, 0x00, + 0x00, 0xea, 0x05, 0x61, 0x00, 0x00, 0x30, 0xb7, + 0x11, 0x65, 0x00, 0x00, 0x0e, 0x0b, 0x38, 0x46, + 0x00, 0x00, 0x00, 0x4b, 0x41, 0x00, 0x00, 0x00, + 0x0a, 0x4b, 0x6a, 0x00, 0x00, 0x00, 0x28, 0x60, + 0x01, 0x00, 0x60, 0x00, 0x00, 0xd1, 0xc9, 0xd2, + 0x11, 0xf2, 0xea, 0x08, 0x0e, 0x38, 0x46, 0x00, + 0x00, 0x00, 0xda, 0xca, 0x60, 0x19, 0x00, 0x60, + 0x18, 0x00, 0x60, 0x09, 0x00, 0x60, 0x08, 0x00, + 0x60, 0x07, 0x00, 0x60, 0x06, 0x00, 0x60, 0x05, + 0x00, 0x60, 0x04, 0x00, 0x60, 0x03, 0x00, 0x60, + 0x02, 0x00, 0x5d, 0x04, 0x00, 0xd1, 0x04, 0x0a, + 0x01, 0x00, 0x00, 0xf0, 0x0e, 0xd2, 0x38, 0x46, + 0x00, 0x00, 0x00, 0xad, 0xea, 0x06, 0x0c, 0x07, + 0xd6, 0xec, 0x0c, 0x5d, 0x04, 0x00, 0xd2, 0x04, + 0x0b, 0x01, 0x00, 0x00, 0xf0, 0x0e, 0xd2, 0x40, + 0xf6, 0x00, 0x00, 0x00, 0xcb, 0x61, 0x02, 0x00, + 0x38, 0x46, 0x00, 0x00, 0x00, 0xad, 0xea, 0x0b, + 0x04, 0x08, 0x01, 0x00, 0x00, 0x11, 0x62, 0x02, + 0x00, 0x0e, 0x61, 0x02, 0x00, 0x04, 0x06, 0x01, + 0x00, 0x00, 0xad, 0x11, 0xeb, 0x18, 0x0e, 0x61, + 0x02, 0x00, 0x04, 0x05, 0x01, 0x00, 0x00, 0xad, + 0x11, 0xeb, 0x0b, 0x0e, 0x61, 0x02, 0x00, 0x04, + 0x08, 0x01, 0x00, 0x00, 0xad, 0x95, 0xea, 0x0c, + 0xdd, 0x11, 0x04, 0x0c, 0x01, 0x00, 0x00, 0x21, + 0x01, 0x00, 0x30, 0x38, 0x46, 0x00, 0x00, 0x00, + 0xcc, 0x61, 0x02, 0x00, 0x04, 0x05, 0x01, 0x00, + 0x00, 0xad, 0xea, 0x24, 0xd2, 0x40, 0xf7, 0x00, + 0x00, 0x00, 0x11, 0x62, 0x03, 0x00, 0x0e, 0x61, + 0x03, 0x00, 0x38, 0x46, 0x00, 0x00, 0x00, 0xae, + 0xea, 0x0e, 0x5d, 0x04, 0x00, 0x61, 0x03, 0x00, + 0x04, 0x0d, 0x01, 0x00, 0x00, 0xf0, 0x0e, 0x26, + 0x00, 0x00, 0xc2, 0x04, 0x26, 0x00, 0x00, 0xc2, + 0x05, 0x26, 0x00, 0x00, 0xc2, 0x06, 0xb4, 0xc2, + 0x07, 0x38, 0x46, 0x00, 0x00, 0x00, 0xc2, 0x08, + 0xd1, 0x5d, 0x05, 0x00, 0x47, 0x24, 0x00, 0x00, + 0xc2, 0x09, 0x6b, 0xcc, 0x01, 0x00, 0x00, 0x60, + 0x0a, 0x00, 0x61, 0x09, 0x00, 0x40, 0x6b, 0x00, + 0x00, 0x00, 0xc2, 0x0a, 0x60, 0x0e, 0x00, 0x60, + 0x0d, 0x00, 0x60, 0x0b, 0x00, 0x06, 0xc2, 0x0b, + 0x6b, 0x14, 0x00, 0x00, 0x00, 0xdf, 0x61, 0x09, + 0x00, 0x61, 0x0a, 0x00, 0xf0, 0x11, 0x62, 0x0b, + 0x00, 0x0e, 0x0e, 0xec, 0x16, 0xc2, 0x0c, 0x6b, + 0x11, 0x00, 0x00, 0x00, 0x38, 0x46, 0x00, 0x00, + 0x00, 0x11, 0x62, 0x09, 0x00, 0x0e, 0xc1, 0x0c, + 0x30, 0x30, 0x61, 0x0b, 0x00, 0x40, 0x6a, 0x00, + 0x00, 0x00, 0xeb, 0x6f, 0x61, 0x0b, 0x00, 0x40, + 0x41, 0x00, 0x00, 0x00, 0xc2, 0x0d, 0x5d, 0x04, + 0x00, 0x61, 0x0d, 0x00, 0x04, 0x0e, 0x01, 0x00, + 0x00, 0xf0, 0x0e, 0x61, 0x0d, 0x00, 0x5d, 0x05, + 0x00, 0x46, 0xc2, 0x0e, 0x61, 0x0e, 0x00, 0xea, + 0x0e, 0xdf, 0x61, 0x0d, 0x00, 0x61, 0x0e, 0x00, + 0xf0, 0x11, 0x62, 0x0d, 0x00, 0x0e, 0x61, 0x05, + 0x00, 0x61, 0x07, 0x00, 0x1b, 0x11, 0xaf, 0xeb, + 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x61, 0x0d, 0x00, + 0x1b, 0x70, 0x1b, 0x48, 0x61, 0x06, 0x00, 0x61, + 0x07, 0x00, 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, + 0x70, 0x1b, 0x1b, 0x61, 0x0d, 0x00, 0x40, 0x6b, + 0x00, 0x00, 0x00, 0x1b, 0x70, 0x1b, 0x48, 0x61, + 0x07, 0x00, 0x90, 0x62, 0x07, 0x00, 0x0e, 0xed, + 0x54, 0xff, 0x38, 0x46, 0x00, 0x00, 0x00, 0x11, + 0x62, 0x09, 0x00, 0x0e, 0x61, 0x03, 0x00, 0x68, + 0xfc, 0x00, 0x00, 0x00, 0x60, 0x15, 0x00, 0x60, + 0x11, 0x00, 0x60, 0x10, 0x00, 0x60, 0x0f, 0x00, + 0x61, 0x03, 0x00, 0x5d, 0x05, 0x00, 0x47, 0x24, + 0x00, 0x00, 0x11, 0x62, 0x08, 0x00, 0x0e, 0x61, + 0x08, 0x00, 0x40, 0x6b, 0x00, 0x00, 0x00, 0xc2, + 0x0f, 0xb4, 0xc2, 0x10, 0x09, 0xc2, 0x11, 0x61, + 0x10, 0x00, 0x61, 0x07, 0x00, 0xa5, 0xea, 0x70, + 0x60, 0x12, 0x00, 0x06, 0xc2, 0x12, 0x6b, 0x2e, + 0x00, 0x00, 0x00, 0x60, 0x13, 0x00, 0xdf, 0x61, + 0x08, 0x00, 0x61, 0x0f, 0x00, 0xf0, 0xc2, 0x13, + 0x61, 0x13, 0x00, 0x40, 0x6a, 0x00, 0x00, 0x00, + 0x11, 0x62, 0x11, 0x00, 0x0e, 0x61, 0x13, 0x00, + 0x40, 0x41, 0x00, 0x00, 0x00, 0x11, 0x62, 0x12, + 0x00, 0x0e, 0x0e, 0xec, 0x16, 0xc2, 0x14, 0x6b, + 0x11, 0x00, 0x00, 0x00, 0x38, 0x46, 0x00, 0x00, + 0x00, 0x11, 0x62, 0x08, 0x00, 0x0e, 0xc1, 0x14, + 0x30, 0x30, 0x61, 0x11, 0x00, 0xeb, 0x21, 0x61, + 0x04, 0x00, 0x61, 0x10, 0x00, 0x1b, 0x11, 0xaf, + 0xeb, 0x04, 0x1b, 0x70, 0x1b, 0x1b, 0x61, 0x12, + 0x00, 0x1b, 0x70, 0x1b, 0x48, 0x61, 0x10, 0x00, + 0x90, 0x62, 0x10, 0x00, 0x0e, 0xec, 0x89, 0x61, + 0x08, 0x00, 0xc2, 0x15, 0x38, 0x46, 0x00, 0x00, + 0x00, 0x11, 0x62, 0x08, 0x00, 0x0e, 0x61, 0x11, + 0x00, 0x95, 0xea, 0x16, 0x60, 0x16, 0x00, 0x5d, + 0x06, 0x00, 0x61, 0x15, 0x00, 0xef, 0xc2, 0x16, + 0x61, 0x16, 0x00, 0xea, 0x05, 0x61, 0x16, 0x00, + 0x30, 0x61, 0x10, 0x00, 0x61, 0x07, 0x00, 0xa5, + 0xea, 0x23, 0x61, 0x04, 0x00, 0x61, 0x10, 0x00, + 0x1b, 0x11, 0xaf, 0xeb, 0x04, 0x1b, 0x70, 0x1b, + 0x1b, 0x38, 0x46, 0x00, 0x00, 0x00, 0x1b, 0x70, + 0x1b, 0x48, 0x61, 0x10, 0x00, 0x90, 0x62, 0x10, + 0x00, 0x0e, 0xec, 0xd6, 0x0e, 0xec, 0x25, 0xc2, + 0x17, 0x6b, 0x20, 0x00, 0x00, 0x00, 0xe0, 0x61, + 0x05, 0x00, 0x61, 0x07, 0x00, 0xf0, 0x0e, 0x5d, + 0x06, 0x00, 0x61, 0x09, 0x00, 0xef, 0x0e, 0x5d, + 0x06, 0x00, 0x61, 0x08, 0x00, 0xef, 0x0e, 0xc1, + 0x17, 0x30, 0x30, 0xb4, 0xc2, 0x18, 0x61, 0x07, + 0x00, 0xc2, 0x19, 0x0b, 0x5d, 0x07, 0x00, 0x4e, + 0xbf, 0x00, 0x53, 0x6b, 0x00, 0x00, 0x00, 0x04, + 0xbf, 0x01, 0x53, 0x06, 0x00, 0x00, 0x00, 0x04, + 0x28, 0xbf, 0x00, 0xc9, 0xbf, 0x01, 0xca, 0xbf, + 0x02, 0xcb, 0xbf, 0x03, 0x28, 0xbf, 0x00, 0xcd, + 0x28, +}; + + + +// like Function.prototype.call but monkey patch-proof +static JSValue js_call_function(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) +{ + return JS_Call(ctx, argv[1], argv[0], argc-2, argv+2); +} + +// returns enumerable and non-enumerable strings *and* symbols +static JSValue js_getOwnPropertyKeys(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) +{ + int flags = JS_GPN_STRING_MASK|JS_GPN_SYMBOL_MASK; + return JS_GetOwnPropertyNames2(ctx, argv[0], flags, JS_ITERATOR_KIND_KEY); +} + +static JSValue js_hasOwnEnumProperty(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) +{ + JSPropertyDescriptor d; + JSObject *p; + JSAtom key; + int flags, res; + + if (JS_TAG_OBJECT != JS_VALUE_GET_TAG(argv[0])) + return JS_ThrowTypeErrorNotAnObject(ctx); + p = JS_VALUE_GET_OBJ(argv[0]); + key = JS_ValueToAtomInternal(ctx, argv[1], JS_TO_STRING_NO_SIDE_EFFECTS); + if (key == JS_ATOM_NULL) + return JS_EXCEPTION; + res = JS_GetOwnPropertyInternal(ctx, &d, p, key); + JS_FreeAtom(ctx, key); + if (res < 0) + return JS_EXCEPTION; + flags = 0; + if (res > 0) { + flags = d.flags; + js_free_desc(ctx, &d); + } + if (flags & JS_PROP_ENUMERABLE) + return JS_TRUE; + return JS_FALSE; +} + +// note: takes ownership of |argv| +static JSValue js_bytecode_eval(JSContext *ctx, const uint8_t *bytecode, + size_t len, int argc, JSValue *argv) +{ + JSValue obj, fun, result; + int i; + + obj = JS_ReadObject(ctx, bytecode, len, JS_READ_OBJ_BYTECODE); + if (JS_IsException(obj)) + return JS_EXCEPTION; + fun = JS_EvalFunction(ctx, obj); + if (JS_IsException(fun)) + return JS_EXCEPTION; + assert(JS_IsFunction(ctx, fun)); + result = JS_Call(ctx, fun, JS_UNDEFINED, argc, vc(argv)); + for (i = 0; i < argc; i++) + JS_FreeValue(ctx, argv[i]); + JS_FreeValue(ctx, fun); + if (JS_SetPrototypeInternal(ctx, result, ctx->function_proto, + /*throw_flag*/true) < 0) { + JS_FreeValue(ctx, result); + return JS_EXCEPTION; + } + return result; +} + +static JSValue js_bytecode_autoinit(JSContext *ctx, JSObject *p, JSAtom atom, + void *opaque) +{ + switch ((uintptr_t)opaque) { + default: + abort(); + case JS_BUILTIN_ARRAY_FROMASYNC: + { + JSValue argv[] = { + JS_NewCFunction(ctx, js_array_constructor, "Array", 0), + JS_NewCFunctionMagic(ctx, js_error_constructor, "TypeError", + 1, JS_CFUNC_constructor_or_func_magic, + JS_TYPE_ERROR), + JS_AtomToValue(ctx, JS_ATOM_Symbol_asyncIterator), + JS_NewCFunctionMagic(ctx, js_object_defineProperty, + "Object.defineProperty", 3, + JS_CFUNC_generic_magic, 0), + JS_AtomToValue(ctx, JS_ATOM_Symbol_iterator), + }; + return js_bytecode_eval(ctx, qjsc_builtin_array_fromasync, + sizeof(qjsc_builtin_array_fromasync), + countof(argv), argv); + } + case JS_BUILTIN_ITERATOR_ZIP: + { + JSValue argv[] = { + js_dup(ctx->class_proto[JS_CLASS_ITERATOR_HELPER]), + JS_NewCFunctionMagic(ctx, js_error_constructor, "InternalError", + 1, JS_CFUNC_constructor_or_func_magic, + JS_INTERNAL_ERROR), + JS_NewCFunctionMagic(ctx, js_error_constructor, "TypeError", + 1, JS_CFUNC_constructor_or_func_magic, + JS_TYPE_ERROR), + JS_NewCFunction(ctx, js_call_function, "call", 2), + JS_AtomToValue(ctx, JS_ATOM_Symbol_iterator), + }; + JSValue result = js_bytecode_eval(ctx, qjsc_builtin_iterator_zip, + sizeof(qjsc_builtin_iterator_zip), + countof(argv), argv); + JS_SetConstructorBit(ctx, result, false); + return result; + } + case JS_BUILTIN_ITERATOR_ZIP_KEYED: + { + JSValue argv[] = { + js_dup(ctx->class_proto[JS_CLASS_ITERATOR_HELPER]), + JS_NewCFunctionMagic(ctx, js_error_constructor, "InternalError", + 1, JS_CFUNC_constructor_or_func_magic, + JS_INTERNAL_ERROR), + JS_NewCFunctionMagic(ctx, js_error_constructor, "TypeError", + 1, JS_CFUNC_constructor_or_func_magic, + JS_TYPE_ERROR), + JS_NewCFunction(ctx, js_call_function, "call", 2), + JS_NewCFunction(ctx, js_hasOwnEnumProperty, + "hasOwnEnumProperty", 2), + JS_NewCFunction(ctx, js_getOwnPropertyKeys, + "getOwnPropertyKeys", 1), + JS_AtomToValue(ctx, JS_ATOM_Symbol_iterator), + }; + JSValue result = js_bytecode_eval(ctx, qjsc_builtin_iterator_zip_keyed, + sizeof(qjsc_builtin_iterator_zip_keyed), + countof(argv), argv); + JS_SetConstructorBit(ctx, result, false); + return result; + } + } + return JS_UNDEFINED; +} + +/* return the value associated to the autoinit property or an exception */ +typedef JSValue JSAutoInitFunc(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); + +static JSAutoInitFunc *const js_autoinit_func_table[] = { + js_instantiate_prototype, /* JS_AUTOINIT_ID_PROTOTYPE */ + js_module_ns_autoinit, /* JS_AUTOINIT_ID_MODULE_NS */ + JS_InstantiateFunctionListItem2, /* JS_AUTOINIT_ID_PROP */ + js_bytecode_autoinit, /* JS_AUTOINIT_ID_BYTECODE */ +}; + +/* warning: 'prs' is reallocated after it */ +static int JS_AutoInitProperty(JSContext *ctx, JSObject *p, JSAtom prop, + JSProperty *pr, JSShapeProperty *prs) +{ + JSValue val; + JSContext *realm; + JSAutoInitFunc *func; + + if (js_shape_prepare_update(ctx, p, &prs)) + return -1; + + realm = js_autoinit_get_realm(pr); + func = js_autoinit_func_table[js_autoinit_get_id(pr)]; + /* 'func' shall not modify the object properties 'pr' */ + val = func(realm, p, prop, pr->u.init.opaque); + js_autoinit_free(ctx->rt, pr); + prs->flags &= ~JS_PROP_TMASK; + pr->u.value = JS_UNDEFINED; + if (JS_IsException(val)) + return -1; + pr->u.value = val; + return 0; +} + +static JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj, + JSAtom prop, JSValueConst this_obj, + bool throw_ref_error) +{ + JSObject *p; + JSProperty *pr; + JSShapeProperty *prs; + uint32_t tag; + + tag = JS_VALUE_GET_TAG(obj); + if (unlikely(tag != JS_TAG_OBJECT)) { + switch(tag) { + case JS_TAG_NULL: + return JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of null", prop); + case JS_TAG_UNDEFINED: + return JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of undefined", prop); + case JS_TAG_EXCEPTION: + return JS_EXCEPTION; + case JS_TAG_STRING: + { + JSString *p1 = JS_VALUE_GET_STRING(obj); + if (__JS_AtomIsTaggedInt(prop)) { + uint32_t idx, ch; + idx = __JS_AtomToUInt32(prop); + if (idx < p1->len) { + ch = string_get(p1, idx); + return js_new_string_char(ctx, ch); + } + } else if (prop == JS_ATOM_length) { + return js_int32(p1->len); + } + } + break; + case JS_TAG_STRING_ROPE: + { + JSStringRope *r = JS_VALUE_GET_STRING_ROPE(obj); + if (__JS_AtomIsTaggedInt(prop)) { + uint32_t idx, ch; + idx = __JS_AtomToUInt32(prop); + if (idx < r->len) { + ch = string_rope_get(obj, idx); + return js_new_string_char(ctx, ch); + } + } else if (prop == JS_ATOM_length) { + return js_int32(r->len); + } + } + break; + default: + break; + } + /* cannot raise an exception */ + p = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, obj)); + if (!p) + return JS_UNDEFINED; + } else { + p = JS_VALUE_GET_OBJ(obj); + } + + for(;;) { + prs = find_own_property(&pr, p, prop); + if (prs) { + /* found */ + if (unlikely(prs->flags & JS_PROP_TMASK)) { + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + if (unlikely(!pr->u.getset.getter)) { + return JS_UNDEFINED; + } else { + JSValue func = JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter); + /* Note: the field could be removed in the getter */ + func = js_dup(func); + return JS_CallFree(ctx, func, this_obj, 0, NULL); + } + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + JSValue val = *pr->u.var_ref->pvalue; + if (unlikely(JS_IsUninitialized(val))) + return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return js_dup(val); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + /* Instantiate property and retry */ + if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) + return JS_EXCEPTION; + continue; + } + } else { + return js_dup(pr->u.value); + } + } + if (unlikely(p->is_exotic)) { + /* exotic behaviors */ + if (p->fast_array) { + if (__JS_AtomIsTaggedInt(prop)) { + uint32_t idx = __JS_AtomToUInt32(prop); + if (idx < p->u.array.count) { + /* we avoid duplicating the code */ + return JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx); + } else if (is_typed_array(p->class_id)) { + return JS_UNDEFINED; + } + } else if (is_typed_array(p->class_id)) { + int ret; + ret = JS_AtomIsNumericIndex(ctx, prop); + if (ret != 0) { + if (ret < 0) + return JS_EXCEPTION; + return JS_UNDEFINED; + } + } + } else { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + if (em) { + if (em->get_property) { + JSValue obj1, retval; + /* XXX: should pass throw_ref_error */ + /* Note: if 'p' is a prototype, it can be + freed in the called function */ + obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); + retval = em->get_property(ctx, obj1, prop, this_obj); + JS_FreeValue(ctx, obj1); + return retval; + } + if (em->get_own_property) { + JSPropertyDescriptor desc; + int ret; + JSValue obj1; + + /* Note: if 'p' is a prototype, it can be + freed in the called function */ + obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); + ret = em->get_own_property(ctx, &desc, obj1, prop); + JS_FreeValue(ctx, obj1); + if (ret < 0) + return JS_EXCEPTION; + if (ret) { + if (desc.flags & JS_PROP_GETSET) { + JS_FreeValue(ctx, desc.setter); + return JS_CallFree(ctx, desc.getter, this_obj, 0, NULL); + } else { + return desc.value; + } + } + } + } + } + } + p = p->shape->proto; + if (!p) + break; + } + if (unlikely(throw_ref_error)) { + return JS_ThrowReferenceErrorNotDefined(ctx, prop); + } else { + return JS_UNDEFINED; + } +} + +JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop) +{ + return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, false); +} + +static JSValue JS_ThrowTypeErrorPrivateNotFound(JSContext *ctx, JSAtom atom) +{ + return JS_ThrowTypeErrorAtom(ctx, "private class field '%s' does not exist", + atom); +} + +/* Private fields can be added even on non extensible objects or + Proxies */ +static int JS_DefinePrivateField(JSContext *ctx, JSValueConst obj, + JSValue name, JSValue val) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + JSAtom prop; + + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) { + JS_ThrowTypeErrorNotAnObject(ctx); + goto fail; + } + /* safety check */ + if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) { + JS_ThrowTypeErrorNotASymbol(ctx); + goto fail; + } + prop = js_symbol_to_atom(ctx, name); + p = JS_VALUE_GET_OBJ(obj); + prs = find_own_property(&pr, p, prop); + if (prs) { + JS_ThrowTypeErrorAtom(ctx, "private class field '%s' already exists", + prop); + goto fail; + } + pr = add_property(ctx, p, prop, JS_PROP_C_W_E); + if (unlikely(!pr)) { + fail: + JS_FreeValue(ctx, val); + return -1; + } + pr->u.value = val; + return 0; +} + +static JSValue JS_GetPrivateField(JSContext *ctx, JSValueConst obj, + JSValueConst name) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + JSAtom prop; + + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) + return JS_ThrowTypeErrorNotAnObject(ctx); + /* safety check */ + if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) + return JS_ThrowTypeErrorNotASymbol(ctx); + prop = js_symbol_to_atom(ctx, name); + p = JS_VALUE_GET_OBJ(obj); + prs = find_own_property(&pr, p, prop); + if (!prs) { + JS_ThrowTypeErrorPrivateNotFound(ctx, prop); + return JS_EXCEPTION; + } + return js_dup(pr->u.value); +} + +static int JS_SetPrivateField(JSContext *ctx, JSValueConst obj, + JSValueConst name, JSValue val) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + JSAtom prop; + + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) { + JS_ThrowTypeErrorNotAnObject(ctx); + goto fail; + } + /* safety check */ + if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) { + JS_ThrowTypeErrorNotASymbol(ctx); + goto fail; + } + prop = js_symbol_to_atom(ctx, name); + p = JS_VALUE_GET_OBJ(obj); + prs = find_own_property(&pr, p, prop); + if (!prs) { + JS_ThrowTypeErrorPrivateNotFound(ctx, prop); + fail: + JS_FreeValue(ctx, val); + return -1; + } + set_value(ctx, &pr->u.value, val); + return 0; +} + +/* add a private brand field to 'home_obj' if not already present and + if obj is != null add a private brand to it */ +static int JS_AddBrand(JSContext *ctx, JSValueConst obj, JSValueConst home_obj) +{ + JSObject *p, *p1; + JSShapeProperty *prs; + JSProperty *pr; + JSValue brand; + JSAtom brand_atom; + + if (unlikely(JS_VALUE_GET_TAG(home_obj) != JS_TAG_OBJECT)) { + JS_ThrowTypeErrorNotAnObject(ctx); + return -1; + } + p = JS_VALUE_GET_OBJ(home_obj); + prs = find_own_property(&pr, p, JS_ATOM_Private_brand); + if (!prs) { + /* if the brand is not present, add it */ + brand = JS_NewSymbolFromAtom(ctx, JS_ATOM_brand, JS_ATOM_TYPE_PRIVATE); + if (JS_IsException(brand)) + return -1; + pr = add_property(ctx, p, JS_ATOM_Private_brand, JS_PROP_C_W_E); + if (!pr) { + JS_FreeValue(ctx, brand); + return -1; + } + pr->u.value = js_dup(brand); + } else { + brand = js_dup(pr->u.value); + } + brand_atom = js_symbol_to_atom(ctx, brand); + + if (JS_IsObject(obj)) { + p1 = JS_VALUE_GET_OBJ(obj); + prs = find_own_property(&pr, p1, brand_atom); + if (unlikely(prs)) { + JS_FreeAtom(ctx, brand_atom); + JS_ThrowTypeError(ctx, "private method is already present"); + return -1; + } + pr = add_property(ctx, p1, brand_atom, JS_PROP_C_W_E); + JS_FreeAtom(ctx, brand_atom); + if (!pr) + return -1; + pr->u.value = JS_UNDEFINED; + } else { + JS_FreeAtom(ctx, brand_atom); + } + + return 0; +} + +/* return a boolean telling if the brand of the home object of 'func' + is present on 'obj' or -1 in case of exception */ +static int JS_CheckBrand(JSContext *ctx, JSValue obj, JSValue func) +{ + JSObject *p, *p1, *home_obj; + JSShapeProperty *prs; + JSProperty *pr; + JSValue brand; + + /* get the home object of 'func' */ + if (unlikely(JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)) + goto not_obj; + p1 = JS_VALUE_GET_OBJ(func); + if (!js_class_has_bytecode(p1->class_id)) + goto not_obj; + home_obj = p1->u.func.home_object; + if (!home_obj) + goto not_obj; + prs = find_own_property(&pr, home_obj, JS_ATOM_Private_brand); + if (!prs) { + JS_ThrowTypeError(ctx, "expecting private field"); + return -1; + } + brand = pr->u.value; + /* safety check */ + if (unlikely(JS_VALUE_GET_TAG(brand) != JS_TAG_SYMBOL)) + goto not_obj; + + /* get the brand array of 'obj' */ + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) { + not_obj: + JS_ThrowTypeErrorNotAnObject(ctx); + return -1; + } + p = JS_VALUE_GET_OBJ(obj); + prs = find_own_property(&pr, p, js_symbol_to_atom(ctx, brand)); + return (prs != NULL); +} + +static uint32_t js_string_obj_get_length(JSContext *ctx, JSValueConst obj) +{ + JSObject *p; + JSString *p1; + uint32_t len = 0; + + /* This is a class exotic method: obj class_id is JS_CLASS_STRING */ + p = JS_VALUE_GET_OBJ(obj); + if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) { + p1 = JS_VALUE_GET_STRING(p->u.object_data); + len = p1->len; + } + return len; +} + +static int num_keys_cmp(const void *p1, const void *p2, void *opaque) +{ + JSContext *ctx = opaque; + JSAtom atom1 = ((const JSPropertyEnum *)p1)->atom; + JSAtom atom2 = ((const JSPropertyEnum *)p2)->atom; + uint32_t v1, v2; + bool atom1_is_integer, atom2_is_integer; + + atom1_is_integer = JS_AtomIsArrayIndex(ctx, &v1, atom1); + atom2_is_integer = JS_AtomIsArrayIndex(ctx, &v2, atom2); + assert(atom1_is_integer && atom2_is_integer); + if (v1 < v2) + return -1; + else if (v1 == v2) + return 0; + else + return 1; +} + +static void js_free_prop_enum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len) +{ + uint32_t i; + if (tab) { + for(i = 0; i < len; i++) + JS_FreeAtom(ctx, tab[i].atom); + js_free(ctx, tab); + } +} + +/* return < 0 in case if exception, 0 if OK. ptab and its atoms must + be freed by the user. */ +static int __exception JS_GetOwnPropertyNamesInternal(JSContext *ctx, + JSPropertyEnum **ptab, + uint32_t *plen, + JSObject *p, int flags) +{ + int i, j; + JSShape *sh; + JSShapeProperty *prs; + JSPropertyEnum *tab_atom, *tab_exotic; + JSAtom atom; + uint32_t num_keys_count, str_keys_count, sym_keys_count, atom_count; + uint32_t num_index, str_index, sym_index, exotic_count, exotic_keys_count; + bool is_enumerable, num_sorted; + uint32_t num_key; + JSAtomKindEnum kind; + + /* clear pointer for consistency in case of failure */ + *ptab = NULL; + *plen = 0; + + /* compute the number of returned properties */ + num_keys_count = 0; + str_keys_count = 0; + sym_keys_count = 0; + exotic_keys_count = 0; + exotic_count = 0; + tab_exotic = NULL; + sh = p->shape; + for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { + atom = prs->atom; + if (atom != JS_ATOM_NULL) { + is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0); + kind = JS_AtomGetKind(ctx, atom); + if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) && + ((flags >> kind) & 1) != 0) { + /* need to raise an exception in case of the module + name space (implicit GetOwnProperty) */ + if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) && + (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY))) { + JSVarRef *var_ref = p->prop[i].u.var_ref; + if (unlikely(JS_IsUninitialized(*var_ref->pvalue))) { + JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return -1; + } + } + if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) { + num_keys_count++; + } else if (kind == JS_ATOM_KIND_STRING) { + str_keys_count++; + } else { + sym_keys_count++; + } + } + } + } + + if (p->is_exotic) { + if (p->fast_array) { + if (flags & JS_GPN_STRING_MASK) { + num_keys_count += p->u.array.count; + } + } else if (p->class_id == JS_CLASS_STRING) { + if (flags & JS_GPN_STRING_MASK) { + num_keys_count += js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); + } + } else { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + if (em && em->get_own_property_names) { + if (em->get_own_property_names(ctx, &tab_exotic, &exotic_count, + JS_MKPTR(JS_TAG_OBJECT, p))) + return -1; + for(i = 0; i < exotic_count; i++) { + atom = tab_exotic[i].atom; + kind = JS_AtomGetKind(ctx, atom); + if (((flags >> kind) & 1) != 0) { + is_enumerable = false; + if (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY)) { + JSPropertyDescriptor desc; + int res; + /* set the "is_enumerable" field if necessary */ + res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom); + if (res < 0) { + js_free_prop_enum(ctx, tab_exotic, exotic_count); + return -1; + } + if (res) { + is_enumerable = + ((desc.flags & JS_PROP_ENUMERABLE) != 0); + js_free_desc(ctx, &desc); + } + tab_exotic[i].is_enumerable = is_enumerable; + } + if (!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) { + exotic_keys_count++; + } + } + } + } + } + } + + /* fill them */ + + atom_count = num_keys_count + str_keys_count + sym_keys_count + exotic_keys_count; + /* avoid allocating 0 bytes */ + tab_atom = js_malloc(ctx, sizeof(tab_atom[0]) * max_int(atom_count, 1)); + if (!tab_atom) { + js_free_prop_enum(ctx, tab_exotic, exotic_count); + return -1; + } + + num_index = 0; + str_index = num_keys_count; + sym_index = str_index + str_keys_count; + + num_sorted = true; + sh = p->shape; + for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { + atom = prs->atom; + if (atom != JS_ATOM_NULL) { + is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0); + kind = JS_AtomGetKind(ctx, atom); + if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) && + ((flags >> kind) & 1) != 0) { + if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) { + j = num_index++; + num_sorted = false; + } else if (kind == JS_ATOM_KIND_STRING) { + j = str_index++; + } else { + j = sym_index++; + } + tab_atom[j].atom = JS_DupAtom(ctx, atom); + tab_atom[j].is_enumerable = is_enumerable; + } + } + } + + if (p->is_exotic) { + int len; + if (p->fast_array) { + if (flags & JS_GPN_STRING_MASK) { + len = p->u.array.count; + goto add_array_keys; + } + } else if (p->class_id == JS_CLASS_STRING) { + if (flags & JS_GPN_STRING_MASK) { + len = js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); + add_array_keys: + for(i = 0; i < len; i++) { + tab_atom[num_index].atom = __JS_AtomFromUInt32(i); + if (tab_atom[num_index].atom == JS_ATOM_NULL) { + js_free_prop_enum(ctx, tab_atom, num_index); + return -1; + } + tab_atom[num_index].is_enumerable = true; + num_index++; + } + } + } else { + /* Note: exotic keys are not reordered and comes after the object own properties. */ + for(i = 0; i < exotic_count; i++) { + atom = tab_exotic[i].atom; + is_enumerable = tab_exotic[i].is_enumerable; + kind = JS_AtomGetKind(ctx, atom); + if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) && + ((flags >> kind) & 1) != 0) { + tab_atom[sym_index].atom = atom; + tab_atom[sym_index].is_enumerable = is_enumerable; + sym_index++; + } else { + JS_FreeAtom(ctx, atom); + } + } + js_free(ctx, tab_exotic); + } + } + + assert(num_index == num_keys_count); + assert(str_index == num_keys_count + str_keys_count); + assert(sym_index == atom_count); + + if (num_keys_count != 0 && !num_sorted) { + rqsort(tab_atom, num_keys_count, sizeof(tab_atom[0]), num_keys_cmp, + ctx); + } + *ptab = tab_atom; + *plen = atom_count; + return 0; +} + +int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, + uint32_t *plen, JSValueConst obj, int flags) +{ + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) { + JS_ThrowTypeErrorNotAnObject(ctx); + return -1; + } + return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen, + JS_VALUE_GET_OBJ(obj), flags); +} + +/* Return -1 if exception, + false if the property does not exist, true if it exists. If true is + returned, the property descriptor 'desc' is filled present. */ +static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc, + JSObject *p, JSAtom prop) +{ + JSShapeProperty *prs; + JSProperty *pr; + +retry: + prs = find_own_property(&pr, p, prop); + if (prs) { + if (desc) { + desc->flags = prs->flags & JS_PROP_C_W_E; + desc->getter = JS_UNDEFINED; + desc->setter = JS_UNDEFINED; + desc->value = JS_UNDEFINED; + if (unlikely(prs->flags & JS_PROP_TMASK)) { + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + desc->flags |= JS_PROP_GETSET; + if (pr->u.getset.getter) + desc->getter = js_dup(JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); + if (pr->u.getset.setter) + desc->setter = js_dup(JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + JSValue val = *pr->u.var_ref->pvalue; + if (unlikely(JS_IsUninitialized(val))) { + JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return -1; + } + desc->value = js_dup(val); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + /* Instantiate property and retry */ + if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) + return -1; + goto retry; + } + } else { + desc->value = js_dup(pr->u.value); + } + } else { + /* for consistency, send the exception even if desc is NULL */ + if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF)) { + if (unlikely(JS_IsUninitialized(*pr->u.var_ref->pvalue))) { + JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return -1; + } + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + /* nothing to do: delay instantiation until actual value and/or attributes are read */ + } + } + return true; + } + if (p->is_exotic) { + if (p->fast_array) { + /* specific case for fast arrays */ + if (__JS_AtomIsTaggedInt(prop)) { + uint32_t idx; + idx = __JS_AtomToUInt32(prop); + if (idx < p->u.array.count) { + if (desc) { + desc->flags = JS_PROP_WRITABLE | JS_PROP_ENUMERABLE | + JS_PROP_CONFIGURABLE; + if (is_typed_array(p->class_id) && typed_array_is_immutable(p)) { + desc->flags &= ~JS_PROP_WRITABLE; + desc->flags &= ~JS_PROP_CONFIGURABLE; + } + desc->getter = JS_UNDEFINED; + desc->setter = JS_UNDEFINED; + desc->value = JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx); + } + return true; + } + } + } else { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + if (em && em->get_own_property) { + return em->get_own_property(ctx, desc, + JS_MKPTR(JS_TAG_OBJECT, p), prop); + } + } + } + return false; +} + +int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc, + JSValueConst obj, JSAtom prop) +{ + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) { + JS_ThrowTypeErrorNotAnObject(ctx); + return -1; + } + return JS_GetOwnPropertyInternal(ctx, desc, JS_VALUE_GET_OBJ(obj), prop); +} + +void JS_FreePropertyEnum(JSContext *ctx, JSPropertyEnum *tab, + uint32_t len) +{ + js_free_prop_enum(ctx, tab, len); +} + +/* return -1 if exception (Proxy object only) or true/false */ +int JS_IsExtensible(JSContext *ctx, JSValueConst obj) +{ + JSObject *p; + + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) + return false; + p = JS_VALUE_GET_OBJ(obj); + if (unlikely(p->class_id == JS_CLASS_PROXY)) + return js_proxy_isExtensible(ctx, obj); + else + return p->extensible; +} + +/* return -1 if exception (Proxy object only) or true/false */ +int JS_PreventExtensions(JSContext *ctx, JSValueConst obj) +{ + JSObject *p; + + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) + return false; + p = JS_VALUE_GET_OBJ(obj); + if (unlikely(p->class_id == JS_CLASS_PROXY)) + return js_proxy_preventExtensions(ctx, obj); + p->extensible = false; + return true; +} + +/* return -1 if exception otherwise true or false */ +int JS_HasProperty(JSContext *ctx, JSValueConst obj, JSAtom prop) +{ + JSObject *p; + int ret; + JSValue obj1; + + if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) + return false; + p = JS_VALUE_GET_OBJ(obj); + for(;;) { + if (p->is_exotic) { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + if (em && em->has_property) { + /* has_property can free the prototype */ + obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); + ret = em->has_property(ctx, obj1, prop); + JS_FreeValue(ctx, obj1); + return ret; + } + } + /* JS_GetOwnPropertyInternal can free the prototype */ + js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); + ret = JS_GetOwnPropertyInternal(ctx, NULL, p, prop); + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); + if (ret != 0) + return ret; + if (is_typed_array(p->class_id)) { + ret = JS_AtomIsNumericIndex(ctx, prop); + if (ret != 0) { + if (ret < 0) + return -1; + return false; + } + } + p = p->shape->proto; + if (!p) + break; + } + return false; +} + +/* val must be a symbol */ +static JSAtom js_symbol_to_atom(JSContext *ctx, JSValueConst val) +{ + JSAtomStruct *p = JS_VALUE_GET_PTR(val); + return js_get_atom_index(ctx->rt, p); +} + +/* return JS_ATOM_NULL in case of exception */ +static JSAtom JS_ValueToAtomInternal(JSContext *ctx, JSValueConst val, + int flags) +{ + JSAtom atom; + uint32_t tag; + tag = JS_VALUE_GET_TAG(val); + if (tag == JS_TAG_INT && + (uint32_t)JS_VALUE_GET_INT(val) <= JS_ATOM_MAX_INT) { + /* fast path for integer values */ + atom = __JS_AtomFromUInt32(JS_VALUE_GET_INT(val)); + } else if (tag == JS_TAG_SYMBOL) { + JSAtomStruct *p = JS_VALUE_GET_PTR(val); + atom = JS_DupAtom(ctx, js_get_atom_index(ctx->rt, p)); + } else { + JSValue str; + str = JS_ToPropertyKeyInternal(ctx, val, flags); + if (JS_IsException(str)) + return JS_ATOM_NULL; + if (JS_VALUE_GET_TAG(str) == JS_TAG_SYMBOL) { + atom = js_symbol_to_atom(ctx, str); + } else { + atom = JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(str)); + } + } + return atom; +} + +JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val) +{ + return JS_ValueToAtomInternal(ctx, val, /*flags*/0); +} + +static bool js_get_fast_array_element(JSContext *ctx, JSObject *p, + uint32_t idx, JSValue *pval) +{ + switch(p->class_id) { + case JS_CLASS_ARRAY: + case JS_CLASS_ARGUMENTS: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_dup(p->u.array.u.values[idx]); + return true; + case JS_CLASS_MAPPED_ARGUMENTS: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_dup(*p->u.array.u.var_refs[idx]->pvalue); + return true; + case JS_CLASS_INT8_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_int32(p->u.array.u.int8_ptr[idx]); + return true; + case JS_CLASS_UINT8C_ARRAY: + case JS_CLASS_UINT8_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_int32(p->u.array.u.uint8_ptr[idx]); + return true; + case JS_CLASS_INT16_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_int32(p->u.array.u.int16_ptr[idx]); + return true; + case JS_CLASS_UINT16_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_int32(p->u.array.u.uint16_ptr[idx]); + return true; + case JS_CLASS_INT32_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_int32(p->u.array.u.int32_ptr[idx]); + return true; + case JS_CLASS_UINT32_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_uint32(p->u.array.u.uint32_ptr[idx]); + return true; + case JS_CLASS_BIG_INT64_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = JS_NewBigInt64(ctx, p->u.array.u.int64_ptr[idx]); + return true; + case JS_CLASS_BIG_UINT64_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = JS_NewBigUint64(ctx, p->u.array.u.uint64_ptr[idx]); + return true; + case JS_CLASS_FLOAT16_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_float64(fromfp16(p->u.array.u.fp16_ptr[idx])); + return true; + case JS_CLASS_FLOAT32_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_float64(p->u.array.u.float_ptr[idx]); + return true; + case JS_CLASS_FLOAT64_ARRAY: + if (unlikely(idx >= p->u.array.count)) return false; + *pval = js_float64(p->u.array.u.double_ptr[idx]); + return true; + default: + return false; + } +} + +static JSValue JS_GetPropertyValue(JSContext *ctx, JSValueConst this_obj, + JSValue prop) +{ + JSAtom atom; + JSValue ret; + uint32_t tag; + + tag = JS_VALUE_GET_TAG(this_obj); + if (likely(tag == JS_TAG_OBJECT)) { + if (JS_VALUE_GET_TAG(prop) == JS_TAG_INT) { + JSObject *p = JS_VALUE_GET_OBJ(this_obj); + uint32_t idx = JS_VALUE_GET_INT(prop); + JSValue val; + /* fast path for array and typed array access */ + if (js_get_fast_array_element(ctx, p, idx, &val)) + return val; + } + } else if (unlikely(tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)) { + // per spec: not allowed to call ToPropertyKey before ToObject + // so we must ensure to not invoke JS anything that's observable + // from JS code + atom = JS_ValueToAtomInternal(ctx, prop, JS_TO_STRING_NO_SIDE_EFFECTS); + JS_FreeValue(ctx, prop); + if (unlikely(atom == JS_ATOM_NULL)) + return JS_EXCEPTION; + if (tag == JS_TAG_NULL) { + JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of null", atom); + } else { + JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of undefined", atom); + } + JS_FreeAtom(ctx, atom); + return JS_EXCEPTION; + } + atom = JS_ValueToAtom(ctx, prop); + JS_FreeValue(ctx, prop); + if (unlikely(atom == JS_ATOM_NULL)) + return JS_EXCEPTION; + ret = JS_GetProperty(ctx, this_obj, atom); + JS_FreeAtom(ctx, atom); + return ret; +} + +JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx) +{ + return JS_GetPropertyInt64(ctx, this_obj, idx); +} + +/* Check if an object has a generalized numeric property. Return value: + -1 for exception, *pval set to JS_EXCEPTION + true if property exists, stored into *pval, + false if property does not exist. *pval set to JS_UNDEFINED. + */ +static int JS_TryGetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, JSValue *pval) +{ + JSValue val; + JSAtom prop; + int present; + + if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT && + (uint64_t)idx <= INT32_MAX)) { + /* fast path for array and typed array access */ + JSObject *p = JS_VALUE_GET_OBJ(obj); + if (js_get_fast_array_element(ctx, p, idx, pval)) + return true; + } + val = JS_EXCEPTION; + present = -1; + prop = JS_NewAtomInt64(ctx, idx); + if (likely(prop != JS_ATOM_NULL)) { + present = JS_HasProperty(ctx, obj, prop); + if (present > 0) { + val = JS_GetProperty(ctx, obj, prop); + if (unlikely(JS_IsException(val))) + present = -1; + } else if (present == false) { + val = JS_UNDEFINED; + } + JS_FreeAtom(ctx, prop); + } + *pval = val; + return present; +} + +JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx) +{ + JSAtom prop; + JSValue val; + + if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT && + (uint64_t)idx <= INT32_MAX)) { + /* fast path for array and typed array access */ + JSObject *p = JS_VALUE_GET_OBJ(obj); + if (js_get_fast_array_element(ctx, p, idx, &val)) + return val; + } + prop = JS_NewAtomInt64(ctx, idx); + if (prop == JS_ATOM_NULL) + return JS_EXCEPTION; + + val = JS_GetProperty(ctx, obj, prop); + JS_FreeAtom(ctx, prop); + return val; +} + +/* `prop` may be pure ASCII or UTF-8 encoded */ +JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj, + const char *prop) +{ + JSAtom atom; + JSValue ret; + atom = JS_NewAtom(ctx, prop); + if (atom == JS_ATOM_NULL) + return JS_EXCEPTION; + ret = JS_GetProperty(ctx, this_obj, atom); + JS_FreeAtom(ctx, atom); + return ret; +} + +/* Note: the property value is not initialized. Return NULL if memory + error. */ +static JSProperty *add_property(JSContext *ctx, + JSObject *p, JSAtom prop, int prop_flags) +{ + JSShape *sh, *new_sh; + + if (unlikely(p->is_prototype)) { + /* track addition of small integer properties to + Array.prototype and Object.prototype */ + if (unlikely((p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_ARRAY]) || + p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_OBJECT])) && + __JS_AtomIsTaggedInt(prop))) { + ctx->std_array_prototype = false; + } + } + sh = p->shape; + if (sh->is_hashed) { + /* try to find an existing shape */ + new_sh = find_hashed_shape_prop(ctx->rt, sh, prop, prop_flags); + if (new_sh) { + /* matching shape found: use it */ + /* the property array may need to be resized */ + if (new_sh->prop_size != sh->prop_size) { + JSProperty *new_prop; + new_prop = js_realloc(ctx, p->prop, sizeof(p->prop[0]) * + new_sh->prop_size); + if (!new_prop) + return NULL; + p->prop = new_prop; + } + p->shape = js_dup_shape(new_sh); + js_free_shape(ctx->rt, sh); + return &p->prop[new_sh->prop_count - 1]; + } else if (sh->header.ref_count != 1) { + /* if the shape is shared, clone it */ + new_sh = js_clone_shape(ctx, sh); + if (!new_sh) + return NULL; + /* hash the cloned shape */ + new_sh->is_hashed = true; + js_shape_hash_link(ctx->rt, new_sh); + js_free_shape(ctx->rt, p->shape); + p->shape = new_sh; + } + } + assert(p->shape->header.ref_count == 1); + if (add_shape_property(ctx, &p->shape, p, prop, prop_flags)) + return NULL; + return &p->prop[p->shape->prop_count - 1]; +} + +/* can be called on JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS or + JS_CLASS_MAPPED_ARGUMENTS objects. return < 0 if memory alloc + error. */ +static no_inline __exception int convert_fast_array_to_array(JSContext *ctx, + JSObject *p) +{ + JSProperty *pr; + JSShape *sh; + uint32_t i, len, new_count; + + /* track modification of Array.prototype */ + if (unlikely(p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_ARRAY]))) { + ctx->std_array_prototype = false; + } + if (js_shape_prepare_update(ctx, p, NULL)) + return -1; + len = p->u.array.count; + /* resize the properties once to simplify the error handling */ + sh = p->shape; + new_count = sh->prop_count + len; + if (new_count > sh->prop_size) { + if (resize_properties(ctx, &p->shape, p, new_count)) + return -1; + } + + if (p->class_id == JS_CLASS_MAPPED_ARGUMENTS) { + JSVarRef **tab = p->u.array.u.var_refs; + for(i = 0; i < len; i++) { + /* add_property cannot fail here but + __JS_AtomFromUInt32(i) fails for i > INT32_MAX */ + pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E | JS_PROP_VARREF); + pr->u.var_ref = *tab++; + } + } else { + JSValue *tab = p->u.array.u.values; + for(i = 0; i < len; i++) { + /* add_property cannot fail here but + __JS_AtomFromUInt32(i) fails for i > INT32_MAX */ + pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E); + pr->u.value = *tab++; + } + } + js_free(ctx, p->u.array.u.values); + p->u.array.count = 0; + p->u.array.u.values = NULL; /* fail safe */ + p->u.array.u1.size = 0; + p->fast_array = 0; + return 0; +} + +static int delete_property(JSContext *ctx, JSObject *p, JSAtom atom) +{ + JSShape *sh; + JSShapeProperty *pr, *lpr, *prop; + JSProperty *pr1; + uint32_t lpr_idx; + intptr_t h, h1; + + redo: + sh = p->shape; + h1 = atom & sh->prop_hash_mask; + h = prop_hash_end(sh)[-h1 - 1]; + prop = get_shape_prop(sh); + lpr = NULL; + lpr_idx = 0; /* prevent warning */ + while (h != 0) { + pr = &prop[h - 1]; + if (likely(pr->atom == atom)) { + /* found ! */ + if (!(pr->flags & JS_PROP_CONFIGURABLE)) + return false; + /* realloc the shape if needed */ + if (lpr) + lpr_idx = lpr - get_shape_prop(sh); + if (js_shape_prepare_update(ctx, p, &pr)) + return -1; + sh = p->shape; + /* remove property */ + if (lpr) { + lpr = get_shape_prop(sh) + lpr_idx; + lpr->hash_next = pr->hash_next; + } else { + prop_hash_end(sh)[-h1 - 1] = pr->hash_next; + } + sh->deleted_prop_count++; + /* free the entry */ + pr1 = &p->prop[h - 1]; + free_property(ctx->rt, pr1, pr->flags); + JS_FreeAtom(ctx, pr->atom); + /* put default values */ + pr->flags = 0; + pr->atom = JS_ATOM_NULL; + pr1->u.value = JS_UNDEFINED; + + /* compact the properties if too many deleted properties */ + if (sh->deleted_prop_count >= 8 && + sh->deleted_prop_count >= ((unsigned)sh->prop_count / 2)) { + compact_properties(ctx, p); + } + return true; + } + lpr = pr; + h = pr->hash_next; + } + + if (p->is_exotic) { + if (p->fast_array) { + uint32_t idx; + if (JS_AtomIsArrayIndex(ctx, &idx, atom) && + idx < p->u.array.count) { + if (p->class_id == JS_CLASS_ARRAY || + p->class_id == JS_CLASS_ARGUMENTS || + p->class_id == JS_CLASS_MAPPED_ARGUMENTS) { + /* Special case deleting the last element of a fast Array */ + if (idx == p->u.array.count - 1) { + if (p->class_id == JS_CLASS_MAPPED_ARGUMENTS) { + free_var_ref(ctx->rt, p->u.array.u.var_refs[idx]); + } else { + JS_FreeValue(ctx, p->u.array.u.values[idx]); + } + p->u.array.count = idx; + return true; + } + if (convert_fast_array_to_array(ctx, p)) + return -1; + goto redo; + } else { + return false; + } + } + } else { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + if (em && em->delete_property) { + return em->delete_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), atom); + } + } + } + /* not found */ + return true; +} + +static int call_setter(JSContext *ctx, JSObject *setter, + JSValueConst this_obj, JSValue val, int flags) +{ + JSValue ret, func; + if (likely(setter)) { + func = JS_MKPTR(JS_TAG_OBJECT, setter); + /* Note: the field could be removed in the setter */ + func = js_dup(func); + ret = JS_CallFree(ctx, func, this_obj, 1, vc(&val)); + JS_FreeValue(ctx, val); + if (JS_IsException(ret)) + return -1; + JS_FreeValue(ctx, ret); + return true; + } else { + JS_FreeValue(ctx, val); + if ((flags & JS_PROP_THROW) || + ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { + JS_ThrowTypeError(ctx, "no setter for property"); + return -1; + } + return false; + } +} + +/* set the array length and remove the array elements if necessary. */ +static int set_array_length(JSContext *ctx, JSObject *p, JSValue val, + int flags) +{ + uint32_t len, idx, cur_len; + int i, ret; + + /* Note: this call can reallocate the properties of 'p' */ + ret = JS_ToArrayLengthFree(ctx, &len, val, false); + if (ret) + return -1; + /* JS_ToArrayLengthFree() must be done before the read-only test */ + if (unlikely(!(p->shape->prop[0].flags & JS_PROP_WRITABLE))) + return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length); + + if (likely(p->fast_array)) { + uint32_t old_len = p->u.array.count; + if (len < old_len) { + for(i = len; i < old_len; i++) { + JS_FreeValue(ctx, p->u.array.u.values[i]); + } + p->u.array.count = len; + } + p->prop[0].u.value = js_uint32(len); + } else { + /* Note: length is always a uint32 because the object is an + array */ + JS_ToUint32(ctx, &cur_len, p->prop[0].u.value); + if (len < cur_len) { + uint32_t d; + JSShape *sh; + JSShapeProperty *pr; + + d = cur_len - len; + sh = p->shape; + if (d <= sh->prop_count) { + JSAtom atom; + + /* faster to iterate */ + while (cur_len > len) { + atom = JS_NewAtomUInt32(ctx, cur_len - 1); + ret = delete_property(ctx, p, atom); + JS_FreeAtom(ctx, atom); + if (unlikely(!ret)) { + /* unlikely case: property is not + configurable */ + break; + } + cur_len--; + } + } else { + /* faster to iterate thru all the properties. Need two + passes in case one of the property is not + configurable */ + cur_len = len; + for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; + i++, pr++) { + if (pr->atom != JS_ATOM_NULL && + JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) { + if (idx >= cur_len && + !(pr->flags & JS_PROP_CONFIGURABLE)) { + cur_len = idx + 1; + } + } + } + + for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; + i++, pr++) { + if (pr->atom != JS_ATOM_NULL && + JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) { + if (idx >= cur_len) { + /* remove the property */ + delete_property(ctx, p, pr->atom); + /* WARNING: the shape may have been modified */ + sh = p->shape; + pr = get_shape_prop(sh) + i; + } + } + } + } + } else { + cur_len = len; + } + set_value(ctx, &p->prop[0].u.value, js_uint32(cur_len)); + if (unlikely(cur_len > len)) { + return JS_ThrowTypeErrorOrFalse(ctx, flags, "not configurable"); + } + } + return true; +} + +/* return -1 if exception */ +static int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len) +{ + uint32_t new_size; + size_t slack; + JSValue *new_array_prop; + /* XXX: potential arithmetic overflow */ + new_size = max_int(new_len, p->u.array.u1.size * 3 / 2); + new_array_prop = js_realloc2(ctx, p->u.array.u.values, sizeof(JSValue) * new_size, &slack); + if (!new_array_prop) + return -1; + new_size += slack / sizeof(*new_array_prop); + p->u.array.u.values = new_array_prop; + p->u.array.u1.size = new_size; + return 0; +} + +/* Preconditions: 'p' must be of class JS_CLASS_ARRAY, p->fast_array = + true and p->extensible = true */ +static int add_fast_array_element(JSContext *ctx, JSObject *p, + JSValue val, int flags) +{ + uint32_t new_len, array_len; + /* extend the array by one */ + /* XXX: convert to slow array if new_len > 2^31-1 elements */ + new_len = p->u.array.count + 1; + /* update the length if necessary. We assume that if the length is + not an integer, then if it >= 2^31. */ + if (likely(JS_VALUE_GET_TAG(p->prop[0].u.value) == JS_TAG_INT)) { + array_len = JS_VALUE_GET_INT(p->prop[0].u.value); + if (new_len > array_len) { + if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE))) { + JS_FreeValue(ctx, val); + return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length); + } + p->prop[0].u.value = js_int32(new_len); + } + } + if (unlikely(new_len > p->u.array.u1.size)) { + if (expand_fast_array(ctx, p, new_len)) { + JS_FreeValue(ctx, val); + return -1; + } + } + p->u.array.u.values[new_len - 1] = val; + p->u.array.count = new_len; + return true; +} + +static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc) +{ + JS_FreeValue(ctx, desc->getter); + JS_FreeValue(ctx, desc->setter); + JS_FreeValue(ctx, desc->value); +} + +/* return -1 in case of exception or true or false. Warning: 'val' is + freed by the function. 'flags' is a bitmask of JS_PROP_NO_ADD, + JS_PROP_THROW or JS_PROP_THROW_STRICT. If JS_PROP_NO_ADD is set, + the new property is not added and an error is raised. + 'obj' must be an object when obj != this_obj. + */ +static int JS_SetPropertyInternal2(JSContext *ctx, JSValueConst obj, JSAtom prop, + JSValue val, JSValueConst this_obj, int flags) +{ + JSObject *p, *p1; + JSShapeProperty *prs; + JSProperty *pr; + JSPropertyDescriptor desc; + int ret; + + switch(JS_VALUE_GET_TAG(this_obj)) { + case JS_TAG_NULL: + JS_ThrowTypeErrorAtom(ctx, "cannot set property '%s' of null", prop); + goto fail; + case JS_TAG_UNDEFINED: + JS_ThrowTypeErrorAtom(ctx, "cannot set property '%s' of undefined", prop); + goto fail; + case JS_TAG_OBJECT: + p = JS_VALUE_GET_OBJ(this_obj); + p1 = JS_VALUE_GET_OBJ(obj); + if (p == p1) + break; + goto retry2; + default: + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + obj = JS_GetPrototypePrimitive(ctx, obj); + p = NULL; + p1 = JS_VALUE_GET_OBJ(obj); + goto prototype_lookup; + } + +retry: + prs = find_own_property(&pr, p1, prop); + if (prs) { + if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE | + JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) { + /* fast case */ + set_value(ctx, &pr->u.value, val); + return true; + } else if (prs->flags & JS_PROP_LENGTH) { + assert(p->class_id == JS_CLASS_ARRAY); + assert(prop == JS_ATOM_length); + return set_array_length(ctx, p, val, flags); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + /* JS_PROP_WRITABLE is always true for variable + references, but they are write protected in module name + spaces. */ + if (p->class_id == JS_CLASS_MODULE_NS) + goto read_only_prop; + set_value(ctx, pr->u.var_ref->pvalue, val); + return true; + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + /* Instantiate property and retry (potentially useless) */ + if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) + goto fail; + goto retry; + } else { + goto read_only_prop; + } + } + + for(;;) { + if (p1->is_exotic) { + if (p1->fast_array) { + if (__JS_AtomIsTaggedInt(prop)) { + uint32_t idx = __JS_AtomToUInt32(prop); + if (idx < p1->u.array.count) { + if (unlikely(p == p1)) + return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), val, flags); + else + break; + } else if (is_typed_array(p1->class_id)) { + goto typed_array_oob; + } + } else if (is_typed_array(p1->class_id)) { + ret = JS_AtomIsNumericIndex(ctx, prop); + if (ret != 0) { + if (ret < 0) + goto fail; + typed_array_oob: + // per spec: evaluate value for side effects + if (p1->class_id == JS_CLASS_BIG_INT64_ARRAY || + p1->class_id == JS_CLASS_BIG_UINT64_ARRAY) { + int64_t v; + if (JS_ToBigInt64Free(ctx, &v, val)) + return -1; + } else { + val = JS_ToNumberFree(ctx, val); + JS_FreeValue(ctx, val); + if (JS_IsException(val)) + return -1; + } + return true; + } + } + } else { + const JSClassExoticMethods *em = ctx->rt->class_array[p1->class_id].exotic; + if (em) { + JSValue obj1; + if (em->set_property) { + /* set_property can free the prototype */ + obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1)); + ret = em->set_property(ctx, obj1, prop, + val, this_obj, flags); + JS_FreeValue(ctx, obj1); + JS_FreeValue(ctx, val); + return ret; + } + if (em->get_own_property) { + /* get_own_property can free the prototype */ + obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1)); + ret = em->get_own_property(ctx, &desc, + obj1, prop); + JS_FreeValue(ctx, obj1); + if (ret < 0) + goto fail; + if (ret) { + if (desc.flags & JS_PROP_GETSET) { + JSObject *setter; + if (JS_IsUndefined(desc.setter)) + setter = NULL; + else + setter = JS_VALUE_GET_OBJ(desc.setter); + ret = call_setter(ctx, setter, this_obj, val, flags); + JS_FreeValue(ctx, desc.getter); + JS_FreeValue(ctx, desc.setter); + return ret; + } else { + JS_FreeValue(ctx, desc.value); + if (!(desc.flags & JS_PROP_WRITABLE)) + goto read_only_prop; + if (likely(p == p1)) { + ret = JS_DefineProperty(ctx, this_obj, prop, val, + JS_UNDEFINED, JS_UNDEFINED, + JS_PROP_HAS_VALUE); + JS_FreeValue(ctx, val); + return ret; + } else { + break; + } + } + } + } + } + } + } + p1 = p1->shape->proto; + prototype_lookup: + if (!p1) + break; + + retry2: + prs = find_own_property(&pr, p1, prop); + if (prs) { + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + /* Instantiate property and retry (potentially useless) */ + if (JS_AutoInitProperty(ctx, p1, prop, pr, prs)) + return -1; + goto retry2; + } else if (!(prs->flags & JS_PROP_WRITABLE)) { + goto read_only_prop; + } else { + break; + } + } + } + + if (unlikely(flags & JS_PROP_NO_ADD)) { + JS_ThrowReferenceErrorNotDefined(ctx, prop); + goto fail; + } + + if (unlikely(!p)) { + ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "not an object"); + goto done; + } + + if (unlikely(!p->extensible)) { + ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "object is not extensible"); + goto done; + } + + if (p == JS_VALUE_GET_OBJ(obj)) { + if (p->is_exotic) { + if (p->class_id == JS_CLASS_ARRAY && p->fast_array && + __JS_AtomIsTaggedInt(prop)) { + uint32_t idx = __JS_AtomToUInt32(prop); + if (idx == p->u.array.count) { + /* fast case */ + return add_fast_array_element(ctx, p, val, flags); + } + } + goto generic_create_prop; + } else { + pr = add_property(ctx, p, prop, JS_PROP_C_W_E); + if (!pr) + goto fail; + pr->u.value = val; + return true; + } + } + + // TODO(bnoordhuis) return JSProperty slot and update in place + // when plain property (not is_exotic/setter/etc.) to avoid + // calling find_own_property() thrice? + ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop); + if (ret < 0) + goto fail; + + if (ret) { + JS_FreeValue(ctx, desc.value); + if (desc.flags & JS_PROP_GETSET) { + JS_FreeValue(ctx, desc.getter); + JS_FreeValue(ctx, desc.setter); + ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "setter is forbidden"); + goto done; + } else if (!(desc.flags & JS_PROP_WRITABLE) || + p->class_id == JS_CLASS_MODULE_NS) { + read_only_prop: + ret = JS_ThrowTypeErrorReadOnly(ctx, flags, prop); + goto done; + } + ret = JS_DefineProperty(ctx, this_obj, prop, val, + JS_UNDEFINED, JS_UNDEFINED, + JS_PROP_HAS_VALUE); + } else { + generic_create_prop: + ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED, + flags | + JS_PROP_HAS_VALUE | + JS_PROP_HAS_ENUMERABLE | + JS_PROP_HAS_WRITABLE | + JS_PROP_HAS_CONFIGURABLE | + JS_PROP_C_W_E); + } + +done: + JS_FreeValue(ctx, val); + return ret; +fail: + JS_FreeValue(ctx, val); + return -1; +} + +static int JS_SetPropertyInternal(JSContext *ctx, JSValueConst obj, JSAtom prop, + JSValue val, int flags) +{ + return JS_SetPropertyInternal2(ctx, obj, prop, val, obj, flags); +} + +int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val) +{ + return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW); +} + +/* flags can be JS_PROP_THROW or JS_PROP_THROW_STRICT */ +static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj, + JSValue prop, JSValue val, int flags) +{ + if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT && + JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) { + JSObject *p; + uint32_t idx; + double d; + int32_t v; + + /* fast path for array access */ + p = JS_VALUE_GET_OBJ(this_obj); + idx = JS_VALUE_GET_INT(prop); + switch(p->class_id) { + case JS_CLASS_ARRAY: + if (unlikely(idx >= (uint32_t)p->u.array.count)) { + /* fast path to add an element to the array */ + if (unlikely(idx != (uint32_t)p->u.array.count || + !p->fast_array || + !p->extensible || + p->shape->proto != JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_ARRAY]) || + !ctx->std_array_prototype)) { + goto slow_path; + } + /* add element */ + return add_fast_array_element(ctx, p, val, flags); + } + set_value(ctx, &p->u.array.u.values[idx], val); + break; + case JS_CLASS_ARGUMENTS: + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto slow_path; + set_value(ctx, &p->u.array.u.values[idx], val); + break; + case JS_CLASS_MAPPED_ARGUMENTS: + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto slow_path; + set_value(ctx, p->u.array.u.var_refs[idx]->pvalue, val); + break; + case JS_CLASS_UINT8C_ARRAY: + if (JS_ToUint8ClampFree(ctx, &v, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + /* Note: the conversion can detach the typed array, so the + array bound check must be done after */ + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.uint8_ptr[idx] = v; + break; + case JS_CLASS_INT8_ARRAY: + case JS_CLASS_UINT8_ARRAY: + if (JS_ToInt32Free(ctx, &v, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.uint8_ptr[idx] = v; + break; + case JS_CLASS_INT16_ARRAY: + case JS_CLASS_UINT16_ARRAY: + if (JS_ToInt32Free(ctx, &v, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.uint16_ptr[idx] = v; + break; + case JS_CLASS_INT32_ARRAY: + case JS_CLASS_UINT32_ARRAY: + if (JS_ToInt32Free(ctx, &v, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.uint32_ptr[idx] = v; + break; + case JS_CLASS_BIG_INT64_ARRAY: + case JS_CLASS_BIG_UINT64_ARRAY: + /* XXX: need specific conversion function */ + { + int64_t v; + if (JS_ToBigInt64Free(ctx, &v, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.uint64_ptr[idx] = v; + } + break; + case JS_CLASS_FLOAT16_ARRAY: + if (JS_ToFloat64Free(ctx, &d, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.fp16_ptr[idx] = tofp16(d); + break; + case JS_CLASS_FLOAT32_ARRAY: + if (JS_ToFloat64Free(ctx, &d, val)) + goto ta_cvt_fail; + if (typed_array_is_immutable(p)) + goto ta_immutable; + if (unlikely(idx >= (uint32_t)p->u.array.count)) + goto ta_out_of_bound; + p->u.array.u.float_ptr[idx] = d; + break; + case JS_CLASS_FLOAT64_ARRAY: + if (JS_ToFloat64Free(ctx, &d, val)) { + ta_cvt_fail: + if (flags & JS_PROP_REFLECT_DEFINE_PROPERTY) { + JS_FreeValue(ctx, JS_GetException(ctx)); + return false; + } + return -1; + } + if (typed_array_is_immutable(p)) { + ta_immutable: + return false; + } + if (unlikely(idx >= (uint32_t)p->u.array.count)) { + ta_out_of_bound: + if (typed_array_is_oob(p)) + if (flags & JS_PROP_DEFINE_PROPERTY) + return JS_ThrowTypeErrorOrFalse(ctx, flags, "out-of-bound numeric index"); + return true; // per spec: no OOB exception + } + p->u.array.u.double_ptr[idx] = d; + break; + default: + goto slow_path; + } + return true; + } else { + JSAtom atom; + int ret; + slow_path: + atom = JS_ValueToAtom(ctx, prop); + JS_FreeValue(ctx, prop); + if (unlikely(atom == JS_ATOM_NULL)) { + JS_FreeValue(ctx, val); + return -1; + } + ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, flags); + JS_FreeAtom(ctx, atom); + return ret; + } +} + +int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx, JSValue val) +{ + return JS_SetPropertyValue(ctx, this_obj, js_uint32(idx), val, + JS_PROP_THROW); +} + +int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj, + int64_t idx, JSValue val) +{ + JSAtom prop; + int res; + + if ((uint64_t)idx <= INT32_MAX) { + /* fast path for fast arrays */ + return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), val, + JS_PROP_THROW); + } + prop = JS_NewAtomInt64(ctx, idx); + if (prop == JS_ATOM_NULL) { + JS_FreeValue(ctx, val); + return -1; + } + res = JS_SetProperty(ctx, this_obj, prop, val); + JS_FreeAtom(ctx, prop); + return res; +} + +/* `prop` may be pure ASCII or UTF-8 encoded */ +int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj, + const char *prop, JSValue val) +{ + JSAtom atom; + int ret; + atom = JS_NewAtom(ctx, prop); + if (atom == JS_ATOM_NULL) { + JS_FreeValue(ctx, val); + return -1; + } + ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, JS_PROP_THROW); + JS_FreeAtom(ctx, atom); + return ret; +} + +/* compute the property flags. For each flag: (JS_PROP_HAS_x forces + it, otherwise def_flags is used) + Note: makes assumption about the bit pattern of the flags +*/ +static int get_prop_flags(int flags, int def_flags) +{ + int mask; + mask = (flags >> JS_PROP_HAS_SHIFT) & JS_PROP_C_W_E; + return (flags & mask) | (def_flags & ~mask); +} + +static int JS_CreateProperty(JSContext *ctx, JSObject *p, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, + int flags) +{ + JSProperty *pr; + int ret, prop_flags; + + /* add a new property or modify an existing exotic one */ + if (p->is_exotic) { + if (p->class_id == JS_CLASS_ARRAY) { + uint32_t idx, len; + + if (p->fast_array) { + if (__JS_AtomIsTaggedInt(prop)) { + idx = __JS_AtomToUInt32(prop); + if (idx == p->u.array.count) { + if (!p->extensible) + goto not_extensible; + if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) + goto convert_to_array; + prop_flags = get_prop_flags(flags, 0); + if (prop_flags != JS_PROP_C_W_E) + goto convert_to_array; + return add_fast_array_element(ctx, p, + js_dup(val), flags); + } else { + goto convert_to_array; + } + } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) { + /* convert the fast array to normal array */ + convert_to_array: + if (convert_fast_array_to_array(ctx, p)) + return -1; + goto generic_array; + } + } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) { + JSProperty *plen; + JSShapeProperty *pslen; + generic_array: + /* update the length field */ + plen = &p->prop[0]; + JS_ToUint32(ctx, &len, plen->u.value); + if ((idx + 1) > len) { + pslen = get_shape_prop(p->shape); + if (unlikely(!(pslen->flags & JS_PROP_WRITABLE))) + return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length); + /* XXX: should update the length after defining + the property */ + len = idx + 1; + set_value(ctx, &plen->u.value, js_uint32(len)); + } + } + } else if (is_typed_array(p->class_id)) { + ret = JS_AtomIsNumericIndex(ctx, prop); + if (ret != 0) { + if (ret < 0) + return -1; + return JS_ThrowTypeErrorOrFalse(ctx, flags, "cannot create numeric index in typed array"); + } + } else if (!(flags & JS_PROP_NO_EXOTIC)) { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + if (em) { + if (em->define_own_property) { + return em->define_own_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), + prop, val, getter, setter, flags); + } + ret = JS_IsExtensible(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); + if (ret < 0) + return -1; + if (!ret) + goto not_extensible; + } + } + } + + if (!p->extensible) { + not_extensible: + return JS_ThrowTypeErrorOrFalse(ctx, flags, "object is not extensible"); + } + + if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { + prop_flags = (flags & (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) | + JS_PROP_GETSET; + } else { + prop_flags = flags & JS_PROP_C_W_E; + } + pr = add_property(ctx, p, prop, prop_flags); + if (unlikely(!pr)) + return -1; + if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { + pr->u.getset.getter = NULL; + if ((flags & JS_PROP_HAS_GET) && JS_IsFunction(ctx, getter)) { + pr->u.getset.getter = + JS_VALUE_GET_OBJ(js_dup(getter)); + } + pr->u.getset.setter = NULL; + if ((flags & JS_PROP_HAS_SET) && JS_IsFunction(ctx, setter)) { + pr->u.getset.setter = + JS_VALUE_GET_OBJ(js_dup(setter)); + } + } else { + if (flags & JS_PROP_HAS_VALUE) { + pr->u.value = js_dup(val); + } else { + pr->u.value = JS_UNDEFINED; + } + } + return true; +} + +/* return false if not OK */ +static bool check_define_prop_flags(int prop_flags, int flags) +{ + bool has_accessor, is_getset; + + if (!(prop_flags & JS_PROP_CONFIGURABLE)) { + if ((flags & (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) == + (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) { + return false; + } + if ((flags & JS_PROP_HAS_ENUMERABLE) && + (flags & JS_PROP_ENUMERABLE) != (prop_flags & JS_PROP_ENUMERABLE)) + return false; + } + if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | + JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { + if (!(prop_flags & JS_PROP_CONFIGURABLE)) { + has_accessor = ((flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) != 0); + is_getset = ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET); + if (has_accessor != is_getset) + return false; + if (!has_accessor && !is_getset && !(prop_flags & JS_PROP_WRITABLE)) { + /* not writable: cannot set the writable bit */ + if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == + (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) + return false; + } + } + } + return true; +} + +/* ensure that the shape can be safely modified */ +static int js_shape_prepare_update(JSContext *ctx, JSObject *p, + JSShapeProperty **pprs) +{ + JSShape *sh; + uint32_t idx = 0; /* prevent warning */ + + sh = p->shape; + if (sh->is_hashed) { + if (sh->header.ref_count != 1) { + if (pprs) + idx = *pprs - get_shape_prop(sh); + /* clone the shape (the resulting one is no longer hashed) */ + sh = js_clone_shape(ctx, sh); + if (!sh) + return -1; + js_free_shape(ctx->rt, p->shape); + p->shape = sh; + if (pprs) + *pprs = get_shape_prop(sh) + idx; + } else { + js_shape_hash_unlink(ctx->rt, sh); + sh->is_hashed = false; + } + } + return 0; +} + +static int js_update_property_flags(JSContext *ctx, JSObject *p, + JSShapeProperty **pprs, int flags) +{ + if (flags != (*pprs)->flags) { + if (js_shape_prepare_update(ctx, p, pprs)) + return -1; + (*pprs)->flags = flags; + } + return 0; +} + +/* allowed flags: + JS_PROP_CONFIGURABLE, JS_PROP_WRITABLE, JS_PROP_ENUMERABLE + JS_PROP_HAS_GET, JS_PROP_HAS_SET, JS_PROP_HAS_VALUE, + JS_PROP_HAS_CONFIGURABLE, JS_PROP_HAS_WRITABLE, JS_PROP_HAS_ENUMERABLE, + JS_PROP_THROW, JS_PROP_NO_EXOTIC. + If JS_PROP_THROW is set, return an exception instead of false. + if JS_PROP_NO_EXOTIC is set, do not call the exotic + define_own_property callback. + return -1 (exception), false or true. +*/ +int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValueConst val, + JSValueConst getter, JSValueConst setter, int flags) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + int mask, res; + + if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) { + JS_ThrowTypeErrorNotAnObject(ctx); + return -1; + } + p = JS_VALUE_GET_OBJ(this_obj); + + redo_prop_update: + prs = find_own_property(&pr, p, prop); + if (prs) { + /* the range of the Array length property is always tested before */ + if ((prs->flags & JS_PROP_LENGTH) && (flags & JS_PROP_HAS_VALUE)) { + uint32_t array_length; + if (JS_ToArrayLengthFree(ctx, &array_length, + js_dup(val), false)) { + return -1; + } + /* this code relies on the fact that Uint32 are never allocated */ + val = js_uint32(array_length); + /* prs may have been modified */ + prs = find_own_property(&pr, p, prop); + assert(prs != NULL); + } + /* property already exists */ + if (!check_define_prop_flags(prs->flags, flags)) { + not_configurable: + return JS_ThrowTypeErrorOrFalse(ctx, flags, "property is not configurable"); + } + + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + /* Instantiate property and retry */ + if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) + return -1; + goto redo_prop_update; + } + + if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | + JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { + if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { + JSObject *new_getter, *new_setter; + + if (JS_IsFunction(ctx, getter)) { + new_getter = JS_VALUE_GET_OBJ(getter); + } else { + new_getter = NULL; + } + if (JS_IsFunction(ctx, setter)) { + new_setter = JS_VALUE_GET_OBJ(setter); + } else { + new_setter = NULL; + } + + if ((prs->flags & JS_PROP_TMASK) != JS_PROP_GETSET) { + if (js_shape_prepare_update(ctx, p, &prs)) + return -1; + /* convert to getset */ + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + free_var_ref(ctx->rt, pr->u.var_ref); + } else { + JS_FreeValue(ctx, pr->u.value); + } + prs->flags = (prs->flags & + (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) | + JS_PROP_GETSET; + pr->u.getset.getter = NULL; + pr->u.getset.setter = NULL; + } else { + if (!(prs->flags & JS_PROP_CONFIGURABLE)) { + if ((flags & JS_PROP_HAS_GET) && + new_getter != pr->u.getset.getter) { + goto not_configurable; + } + if ((flags & JS_PROP_HAS_SET) && + new_setter != pr->u.getset.setter) { + goto not_configurable; + } + } + } + if (flags & JS_PROP_HAS_GET) { + if (pr->u.getset.getter) + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); + if (new_getter) + js_dup(getter); + pr->u.getset.getter = new_getter; + } + if (flags & JS_PROP_HAS_SET) { + if (pr->u.getset.setter) + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); + if (new_setter) + js_dup(setter); + pr->u.getset.setter = new_setter; + } + } else { + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + /* convert to data descriptor */ + if (js_shape_prepare_update(ctx, p, &prs)) + return -1; + if (pr->u.getset.getter) + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); + if (pr->u.getset.setter) + JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); + prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE); + pr->u.value = JS_UNDEFINED; + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + /* Note: JS_PROP_VARREF is always writable */ + } else { + if ((prs->flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 && + (flags & JS_PROP_HAS_VALUE)) { + if (!js_same_value(ctx, val, pr->u.value)) { + goto not_configurable; + } else { + return true; + } + } + } + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + if (flags & JS_PROP_HAS_VALUE) { + if (p->class_id == JS_CLASS_MODULE_NS) { + /* JS_PROP_WRITABLE is always true for variable + references, but they are write protected in module name + spaces. */ + if (!js_same_value(ctx, val, *pr->u.var_ref->pvalue)) + goto not_configurable; + } + /* update the reference */ + set_value(ctx, pr->u.var_ref->pvalue, js_dup(val)); + } + /* if writable is set to false, no longer a + reference (for mapped arguments) */ + if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == JS_PROP_HAS_WRITABLE) { + JSValue val1; + if (js_shape_prepare_update(ctx, p, &prs)) + return -1; + val1 = js_dup(*pr->u.var_ref->pvalue); + free_var_ref(ctx->rt, pr->u.var_ref); + pr->u.value = val1; + prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE); + } + } else if (prs->flags & JS_PROP_LENGTH) { + if (flags & JS_PROP_HAS_VALUE) { + /* Note: no JS code is executable because + 'val' is guaranted to be a Uint32 */ + res = set_array_length(ctx, p, js_dup(val), flags); + } else { + res = true; + } + /* still need to reset the writable flag if + needed. The JS_PROP_LENGTH is kept because the + Uint32 test is still done if the length + property is read-only. */ + if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == + JS_PROP_HAS_WRITABLE) { + prs = get_shape_prop(p->shape); + if (js_update_property_flags(ctx, p, &prs, + prs->flags & ~JS_PROP_WRITABLE)) + return -1; + } + return res; + } else { + if (flags & JS_PROP_HAS_VALUE) { + JS_FreeValue(ctx, pr->u.value); + pr->u.value = js_dup(val); + } + if (flags & JS_PROP_HAS_WRITABLE) { + if (js_update_property_flags(ctx, p, &prs, + (prs->flags & ~JS_PROP_WRITABLE) | + (flags & JS_PROP_WRITABLE))) + return -1; + } + } + } + } + mask = 0; + if (flags & JS_PROP_HAS_CONFIGURABLE) + mask |= JS_PROP_CONFIGURABLE; + if (flags & JS_PROP_HAS_ENUMERABLE) + mask |= JS_PROP_ENUMERABLE; + if (js_update_property_flags(ctx, p, &prs, + (prs->flags & ~mask) | (flags & mask))) + return -1; + return true; + } + + /* handle modification of fast array elements */ + if (p->fast_array) { + uint32_t idx; + uint32_t prop_flags; + if (p->class_id == JS_CLASS_ARRAY) { + if (__JS_AtomIsTaggedInt(prop)) { + idx = __JS_AtomToUInt32(prop); + if (idx < p->u.array.count) { + prop_flags = get_prop_flags(flags, JS_PROP_C_W_E); + if (prop_flags != JS_PROP_C_W_E) + goto convert_to_slow_array; + if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { + convert_to_slow_array: + if (convert_fast_array_to_array(ctx, p)) + return -1; + else + goto redo_prop_update; + } + if (flags & JS_PROP_HAS_VALUE) { + set_value(ctx, &p->u.array.u.values[idx], js_dup(val)); + } + return true; + } + } + } else if (is_typed_array(p->class_id)) { + JSValue num; + int ret; + + if (!__JS_AtomIsTaggedInt(prop)) { + /* slow path with to handle all numeric indexes */ + num = JS_AtomIsNumericIndex1(ctx, prop); + if (JS_IsUndefined(num)) + goto typed_array_done; + if (JS_IsException(num)) + return -1; + ret = JS_NumberIsInteger(ctx, num); + if (ret < 0) { + JS_FreeValue(ctx, num); + return -1; + } + if (!ret) { + JS_FreeValue(ctx, num); + return JS_ThrowTypeErrorOrFalse(ctx, flags, "non integer index in typed array"); + } + ret = JS_NumberIsNegativeOrMinusZero(ctx, num); + JS_FreeValue(ctx, num); + if (ret) { + return JS_ThrowTypeErrorOrFalse(ctx, flags, "negative index in typed array"); + } + if (!__JS_AtomIsTaggedInt(prop)) + goto typed_array_oob; + } + idx = __JS_AtomToUInt32(prop); + /* if the typed array is detached, p->u.array.count = 0 */ + if (idx >= p->u.array.count) { + typed_array_oob: + return JS_ThrowTypeErrorOrFalse(ctx, flags, "out-of-bound index in typed array"); + } + prop_flags = get_prop_flags(flags, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); + if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET) || + prop_flags != (JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE)) { + return JS_ThrowTypeErrorOrFalse(ctx, flags, "invalid descriptor flags"); + } + if (flags & JS_PROP_HAS_VALUE) { + return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), js_dup(val), flags); + } + return true; + typed_array_done: ; + } + } + + return JS_CreateProperty(ctx, p, prop, val, getter, setter, flags); +} + +static int JS_DefineAutoInitProperty(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSAutoInitIDEnum id, + void *opaque, int flags) +{ + JSObject *p; + JSProperty *pr; + + if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) + return false; + + p = JS_VALUE_GET_OBJ(this_obj); + + if (find_own_property(&pr, p, prop)) { + /* property already exists */ + abort(); + return false; + } + + /* Specialized CreateProperty */ + pr = add_property(ctx, p, prop, (flags & JS_PROP_C_W_E) | JS_PROP_AUTOINIT); + if (unlikely(!pr)) + return -1; + pr->u.init.realm_and_id = (uintptr_t)JS_DupContext(ctx); + assert((pr->u.init.realm_and_id & 3) == 0); + assert(id <= 3); + pr->u.init.realm_and_id |= id; + pr->u.init.opaque = opaque; + return true; +} + +/* shortcut to add or redefine a new property value */ +int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue val, int flags) +{ + int ret; + ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED, + flags | JS_PROP_HAS_VALUE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE); + JS_FreeValue(ctx, val); + return ret; +} + +int JS_DefinePropertyValueValue(JSContext *ctx, JSValueConst this_obj, + JSValue prop, JSValue val, int flags) +{ + JSAtom atom; + int ret; + atom = JS_ValueToAtom(ctx, prop); + JS_FreeValue(ctx, prop); + if (unlikely(atom == JS_ATOM_NULL)) { + JS_FreeValue(ctx, val); + return -1; + } + ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags); + JS_FreeAtom(ctx, atom); + return ret; +} + +int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj, + uint32_t idx, JSValue val, int flags) +{ + return JS_DefinePropertyValueValue(ctx, this_obj, js_uint32(idx), + val, flags); +} + +int JS_DefinePropertyValueInt64(JSContext *ctx, JSValueConst this_obj, + int64_t idx, JSValue val, int flags) +{ + return JS_DefinePropertyValueValue(ctx, this_obj, js_int64(idx), + val, flags); +} + +/* `prop` may be pure ASCII or UTF-8 encoded */ +int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj, + const char *prop, JSValue val, int flags) +{ + JSAtom atom; + int ret; + atom = JS_NewAtom(ctx, prop); + if (atom == JS_ATOM_NULL) { + JS_FreeValue(ctx, val); + return -1; + } + ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags); + JS_FreeAtom(ctx, atom); + return ret; +} + +/* shortcut to add getter & setter */ +int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj, + JSAtom prop, JSValue getter, JSValue setter, + int flags) +{ + int ret; + ret = JS_DefineProperty(ctx, this_obj, prop, JS_UNDEFINED, getter, setter, + flags | JS_PROP_HAS_GET | JS_PROP_HAS_SET | + JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE); + JS_FreeValue(ctx, getter); + JS_FreeValue(ctx, setter); + return ret; +} + +static int JS_CreateDataPropertyUint32(JSContext *ctx, JSValueConst this_obj, + int64_t idx, JSValue val, int flags) +{ + return JS_DefinePropertyValueValue(ctx, this_obj, js_int64(idx), + val, flags | JS_PROP_CONFIGURABLE | + JS_PROP_ENUMERABLE | JS_PROP_WRITABLE); +} + + +/* return true if 'obj' has a non empty 'name' string */ +static bool js_object_has_name(JSContext *ctx, JSValue obj) +{ + JSProperty *pr; + JSShapeProperty *prs; + JSValue val; + JSString *p; + + prs = find_own_property(&pr, JS_VALUE_GET_OBJ(obj), JS_ATOM_name); + if (!prs) + return false; + if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL) + return true; + val = pr->u.value; + if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) + return true; + p = JS_VALUE_GET_STRING(val); + return (p->len != 0); +} + +static int JS_DefineObjectName(JSContext *ctx, JSValue obj, + JSAtom name, int flags) +{ + if (name != JS_ATOM_NULL + && JS_IsObject(obj) + && !js_object_has_name(ctx, obj) + && JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, JS_AtomToString(ctx, name), flags) < 0) { + return -1; + } + return 0; +} + +static int JS_DefineObjectNameComputed(JSContext *ctx, JSValue obj, + JSValue str, int flags) +{ + if (JS_IsObject(obj) && + !js_object_has_name(ctx, obj)) { + JSAtom prop; + JSValue name_str; + prop = JS_ValueToAtom(ctx, str); + if (prop == JS_ATOM_NULL) + return -1; + name_str = js_get_function_name(ctx, prop); + JS_FreeAtom(ctx, prop); + if (JS_IsException(name_str)) + return -1; + if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, name_str, flags) < 0) + return -1; + } + return 0; +} + +#define DEFINE_GLOBAL_LEX_VAR (1 << 7) +#define DEFINE_GLOBAL_FUNC_VAR (1 << 6) + +static JSValue JS_ThrowSyntaxErrorVarRedeclaration(JSContext *ctx, JSAtom prop) +{ + return JS_ThrowSyntaxErrorAtom(ctx, "redeclaration of '%s'", prop); +} + +/* flags is 0, DEFINE_GLOBAL_LEX_VAR or DEFINE_GLOBAL_FUNC_VAR */ +/* XXX: could support exotic global object. */ +static int JS_CheckDefineGlobalVar(JSContext *ctx, JSAtom prop, int flags) +{ + JSObject *p; + JSShapeProperty *prs; + + p = JS_VALUE_GET_OBJ(ctx->global_obj); + prs = find_own_property1(p, prop); + /* XXX: should handle JS_PROP_AUTOINIT */ + if (flags & DEFINE_GLOBAL_LEX_VAR) { + if (prs && !(prs->flags & JS_PROP_CONFIGURABLE)) + goto fail_redeclaration; + } else { + if (!prs && !p->extensible) + goto define_error; + if (flags & DEFINE_GLOBAL_FUNC_VAR) { + if (prs) { + if (!(prs->flags & JS_PROP_CONFIGURABLE) && + ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET || + ((prs->flags & (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)) != + (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)))) { + define_error: + JS_ThrowTypeErrorAtom(ctx, "cannot define variable '%s'", + prop); + return -1; + } + } + } + } + /* check if there already is a lexical declaration */ + p = JS_VALUE_GET_OBJ(ctx->global_var_obj); + prs = find_own_property1(p, prop); + if (prs) { + fail_redeclaration: + JS_ThrowSyntaxErrorVarRedeclaration(ctx, prop); + return -1; + } + return 0; +} + +/* def_flags is (0, DEFINE_GLOBAL_LEX_VAR) | + JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE */ +/* XXX: could support exotic global object. */ +static int JS_DefineGlobalVar(JSContext *ctx, JSAtom prop, int def_flags) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + JSValue val; + int flags; + + if (def_flags & DEFINE_GLOBAL_LEX_VAR) { + p = JS_VALUE_GET_OBJ(ctx->global_var_obj); + flags = JS_PROP_ENUMERABLE | (def_flags & JS_PROP_WRITABLE) | + JS_PROP_CONFIGURABLE; + val = JS_UNINITIALIZED; + } else { + p = JS_VALUE_GET_OBJ(ctx->global_obj); + flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | + (def_flags & JS_PROP_CONFIGURABLE); + val = JS_UNDEFINED; + } + prs = find_own_property1(p, prop); + if (prs) + return 0; + if (!p->extensible) + return 0; + pr = add_property(ctx, p, prop, flags); + if (unlikely(!pr)) + return -1; + pr->u.value = val; + return 0; +} + +/* 'def_flags' is 0 or JS_PROP_CONFIGURABLE. */ +/* XXX: could support exotic global object. */ +static int JS_DefineGlobalFunction(JSContext *ctx, JSAtom prop, + JSValue func, int def_flags) +{ + + JSObject *p; + JSShapeProperty *prs; + int flags; + + p = JS_VALUE_GET_OBJ(ctx->global_obj); + prs = find_own_property1(p, prop); + flags = JS_PROP_HAS_VALUE | JS_PROP_THROW; + if (!prs || (prs->flags & JS_PROP_CONFIGURABLE)) { + flags |= JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | def_flags | + JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE; + } + if (JS_DefineProperty(ctx, ctx->global_obj, prop, func, + JS_UNDEFINED, JS_UNDEFINED, flags) < 0) + return -1; + return 0; +} + +static JSValue JS_GetGlobalVar(JSContext *ctx, JSAtom prop, + bool throw_ref_error) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + + /* no exotic behavior is possible in global_var_obj */ + p = JS_VALUE_GET_OBJ(ctx->global_var_obj); + prs = find_own_property(&pr, p, prop); + if (prs) { + /* XXX: should handle JS_PROP_TMASK properties */ + if (unlikely(JS_IsUninitialized(pr->u.value))) + return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return js_dup(pr->u.value); + } + + /* fast path */ + p = JS_VALUE_GET_OBJ(ctx->global_obj); + prs = find_own_property(&pr, p, prop); + if (prs) { + if (likely((prs->flags & JS_PROP_TMASK) == 0)) + return js_dup(pr->u.value); + } + return JS_GetPropertyInternal(ctx, ctx->global_obj, prop, + ctx->global_obj, throw_ref_error); +} + +/* construct a reference to a global variable */ +static int JS_GetGlobalVarRef(JSContext *ctx, JSAtom prop, JSValue *sp) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + + /* no exotic behavior is possible in global_var_obj */ + p = JS_VALUE_GET_OBJ(ctx->global_var_obj); + prs = find_own_property(&pr, p, prop); + if (prs) { + /* XXX: should handle JS_PROP_AUTOINIT properties? */ + /* XXX: conformance: do these tests in + OP_put_var_ref/OP_get_var_ref ? */ + if (unlikely(JS_IsUninitialized(pr->u.value))) { + JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return -1; + } + if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) { + return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop); + } + sp[0] = js_dup(ctx->global_var_obj); + } else { + int ret; + ret = JS_HasProperty(ctx, ctx->global_obj, prop); + if (ret < 0) + return -1; + if (ret) { + sp[0] = js_dup(ctx->global_obj); + } else { + sp[0] = JS_UNDEFINED; + } + } + sp[1] = JS_AtomToValue(ctx, prop); + return 0; +} + +/* flag = 0: normal variable write + flag = 1: initialize lexical variable +*/ +static inline int JS_SetGlobalVar(JSContext *ctx, JSAtom prop, JSValue val, + int flag) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + int ret; + + /* no exotic behavior is possible in global_var_obj */ + p = JS_VALUE_GET_OBJ(ctx->global_var_obj); + prs = find_own_property(&pr, p, prop); + if (prs) { + /* XXX: should handle JS_PROP_AUTOINIT properties? */ + if (flag != 1) { + if (unlikely(JS_IsUninitialized(pr->u.value))) { + JS_FreeValue(ctx, val); + JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); + return -1; + } + if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) { + JS_FreeValue(ctx, val); + return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop); + } + } + set_value(ctx, &pr->u.value, val); + return 0; + } + + p = JS_VALUE_GET_OBJ(ctx->global_obj); + prs = find_own_property(&pr, p, prop); + if (prs) { + if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE | + JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) { + /* fast path */ + set_value(ctx, &pr->u.value, val); + return 0; + } + } + /* slow path */ + ret = JS_HasProperty(ctx, ctx->global_obj, prop); + if (ret < 0) { + JS_FreeValue(ctx, val); + return -1; + } + if (ret == 0 && is_strict_mode(ctx)) { + JS_FreeValue(ctx, val); + JS_ThrowReferenceErrorNotDefined(ctx, prop); + return -1; + } + return JS_SetPropertyInternal(ctx, ctx->global_obj, prop, val, + JS_PROP_THROW_STRICT); +} + +/* return -1, false or true */ +static int JS_DeleteGlobalVar(JSContext *ctx, JSAtom prop) +{ + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + int ret; + + /* 9.1.1.4.7 DeleteBinding ( N ) */ + p = JS_VALUE_GET_OBJ(ctx->global_var_obj); + prs = find_own_property(&pr, p, prop); + if (prs) + return false; /* lexical variables cannot be deleted */ + ret = JS_HasProperty(ctx, ctx->global_obj, prop); + if (ret < 0) + return -1; + if (ret) { + return JS_DeleteProperty(ctx, ctx->global_obj, prop, 0); + } else { + return true; + } +} + +/* return -1, false or true. return false if not configurable or + invalid object. return -1 in case of exception. + flags can be 0, JS_PROP_THROW or JS_PROP_THROW_STRICT */ +int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags) +{ + JSValue obj1; + JSObject *p; + int res; + + obj1 = JS_ToObject(ctx, obj); + if (JS_IsException(obj1)) + return -1; + p = JS_VALUE_GET_OBJ(obj1); + res = delete_property(ctx, p, prop); + JS_FreeValue(ctx, obj1); + if (res != false) + return res; + if ((flags & JS_PROP_THROW) || + ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { + JS_ThrowTypeError(ctx, "could not delete property"); + return -1; + } + return false; +} + +int JS_DeletePropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, int flags) +{ + JSAtom prop; + int res; + + if ((uint64_t)idx <= JS_ATOM_MAX_INT) { + /* fast path for fast arrays */ + return JS_DeleteProperty(ctx, obj, __JS_AtomFromUInt32(idx), flags); + } + prop = JS_NewAtomInt64(ctx, idx); + if (prop == JS_ATOM_NULL) + return -1; + res = JS_DeleteProperty(ctx, obj, prop, flags); + JS_FreeAtom(ctx, prop); + return res; +} + +bool JS_IsFunction(JSContext *ctx, JSValueConst val) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(val); + switch(p->class_id) { + case JS_CLASS_BYTECODE_FUNCTION: + return true; + case JS_CLASS_PROXY: + return p->u.proxy_data->is_func; + default: + return (ctx->rt->class_array[p->class_id].call != NULL); + } +} + +static bool JS_IsCFunction(JSContext *ctx, JSValueConst val, JSCFunction *func, + int magic) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(val); + if (p->class_id == JS_CLASS_C_FUNCTION) + return (p->u.cfunc.c_function.generic == func && p->u.cfunc.magic == magic); + else + return false; +} + +bool JS_IsConstructor(JSContext *ctx, JSValueConst val) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(val); + return p->is_constructor; +} + +bool JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, bool val) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(func_obj); + p->is_constructor = val; + return true; +} + +bool JS_IsRegExp(JSValueConst val) +{ + return JS_CLASS_REGEXP == JS_GetClassID(val); +} + +bool JS_IsMap(JSValueConst val) +{ + return JS_CLASS_MAP == JS_GetClassID(val); +} + +bool JS_IsSet(JSValueConst val) +{ + return JS_CLASS_SET == JS_GetClassID(val); +} + +bool JS_IsWeakRef(JSValueConst val) +{ + return JS_CLASS_WEAK_REF == JS_GetClassID(val); +} + +bool JS_IsWeakSet(JSValueConst val) +{ + return JS_CLASS_WEAKSET == JS_GetClassID(val); +} + +bool JS_IsWeakMap(JSValueConst val) +{ + return JS_CLASS_WEAKMAP == JS_GetClassID(val); +} + +bool JS_IsDataView(JSValueConst val) +{ + return JS_CLASS_DATAVIEW == JS_GetClassID(val); +} + +bool JS_IsError(JSValueConst val) +{ + return JS_CLASS_ERROR == JS_GetClassID(val); +} + +/* used to avoid catching interrupt exceptions */ +bool JS_IsUncatchableError(JSValueConst val) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(val); + return p->class_id == JS_CLASS_ERROR && p->is_uncatchable_error; +} + +static void js_set_uncatchable_error(JSContext *ctx, JSValueConst val, bool flag) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return; + p = JS_VALUE_GET_OBJ(val); + if (p->class_id == JS_CLASS_ERROR) + p->is_uncatchable_error = flag; +} + +void JS_SetUncatchableError(JSContext *ctx, JSValueConst val) +{ + js_set_uncatchable_error(ctx, val, true); +} + +void JS_ClearUncatchableError(JSContext *ctx, JSValueConst val) +{ + js_set_uncatchable_error(ctx, val, false); +} + +void JS_ResetUncatchableError(JSContext *ctx) +{ + js_set_uncatchable_error(ctx, ctx->rt->current_exception, false); +} + +int JS_SetOpaque(JSValueConst obj, void *opaque) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { + p = JS_VALUE_GET_OBJ(obj); + // User code can't set the opaque of internal objects. + if (p->class_id >= JS_CLASS_INIT_COUNT) { + p->u.opaque = opaque; + return 0; + } + } + + return -1; +} + +/* |obj| must be a JSObject of an internal class. */ +static void JS_SetOpaqueInternal(JSValueConst obj, void *opaque) +{ + JSObject *p; + assert(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT); + p = JS_VALUE_GET_OBJ(obj); + assert(p->class_id < JS_CLASS_INIT_COUNT); + p->u.opaque = opaque; +} + +/* return NULL if not an object of class class_id */ +void *JS_GetOpaque(JSValueConst obj, JSClassID class_id) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + return NULL; + p = JS_VALUE_GET_OBJ(obj); + if (p->class_id != class_id) + return NULL; + return p->u.opaque; +} + +void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id) +{ + void *p = JS_GetOpaque(obj, class_id); + if (unlikely(!p)) { + JS_ThrowTypeErrorInvalidClass(ctx, class_id); + } + return p; +} + +void *JS_GetAnyOpaque(JSValueConst obj, JSClassID *class_id) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) { + *class_id = 0; + return NULL; + } + p = JS_VALUE_GET_OBJ(obj); + *class_id = p->class_id; + return p->u.opaque; +} + +static JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint) +{ + int i; + bool force_ordinary; + + JSAtom method_name; + JSValue method, ret; + if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) + return val; + force_ordinary = hint & HINT_FORCE_ORDINARY; + hint &= ~HINT_FORCE_ORDINARY; + if (!force_ordinary) { + method = JS_GetProperty(ctx, val, JS_ATOM_Symbol_toPrimitive); + if (JS_IsException(method)) + goto exception; + /* ECMA says *If exoticToPrim is not undefined* but tests in + test262 use null as a non callable converter */ + if (!JS_IsUndefined(method) && !JS_IsNull(method)) { + JSAtom atom; + JSValue arg; + switch(hint) { + case HINT_STRING: + atom = JS_ATOM_string; + break; + case HINT_NUMBER: + atom = JS_ATOM_number; + break; + default: + case HINT_NONE: + atom = JS_ATOM_default; + break; + } + arg = JS_AtomToString(ctx, atom); + ret = JS_CallFree(ctx, method, val, 1, vc(&arg)); + JS_FreeValue(ctx, arg); + if (JS_IsException(ret)) + goto exception; + JS_FreeValue(ctx, val); + if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) + return ret; + JS_FreeValue(ctx, ret); + return JS_ThrowTypeError(ctx, "toPrimitive"); + } + } + if (hint != HINT_STRING) + hint = HINT_NUMBER; + for(i = 0; i < 2; i++) { + if ((i ^ hint) == 0) { + method_name = JS_ATOM_toString; + } else { + method_name = JS_ATOM_valueOf; + } + method = JS_GetProperty(ctx, val, method_name); + if (JS_IsException(method)) + goto exception; + if (JS_IsFunction(ctx, method)) { + ret = JS_CallFree(ctx, method, val, 0, NULL); + if (JS_IsException(ret)) + goto exception; + if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) { + JS_FreeValue(ctx, val); + return ret; + } + JS_FreeValue(ctx, ret); + } else { + JS_FreeValue(ctx, method); + } + } + JS_ThrowTypeError(ctx, "toPrimitive"); +exception: + JS_FreeValue(ctx, val); + return JS_EXCEPTION; +} + +static JSValue JS_ToPrimitive(JSContext *ctx, JSValueConst val, int hint) +{ + return JS_ToPrimitiveFree(ctx, js_dup(val), hint); +} + +void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + return; + p = JS_VALUE_GET_OBJ(obj); + p->is_HTMLDDA = true; +} + +static inline bool JS_IsHTMLDDA(JSContext *ctx, JSValueConst obj) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(obj); + return p->is_HTMLDDA; +} + +static int JS_ToBoolFree(JSContext *ctx, JSValue val) +{ + uint32_t tag = JS_VALUE_GET_TAG(val); + switch(tag) { + case JS_TAG_INT: + return JS_VALUE_GET_INT(val) != 0; + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + return JS_VALUE_GET_INT(val); + case JS_TAG_EXCEPTION: + return -1; + case JS_TAG_STRING: + { + bool ret = JS_VALUE_GET_STRING(val)->len != 0; + JS_FreeValue(ctx, val); + return ret; + } + case JS_TAG_STRING_ROPE: + { + bool ret = JS_VALUE_GET_STRING_ROPE(val)->len != 0; + JS_FreeValue(ctx, val); + return ret; + } + case JS_TAG_SHORT_BIG_INT: + return JS_VALUE_GET_SHORT_BIG_INT(val) != 0; + case JS_TAG_BIG_INT: + { + JSBigInt *p = JS_VALUE_GET_PTR(val); + bool ret; + int i; + + /* fail safe: we assume it is not necessarily + normalized. Beginning from the MSB ensures that the + test is fast. */ + ret = false; + for(i = p->len - 1; i >= 0; i--) { + if (p->tab[i] != 0) { + ret = true; + break; + } + } + JS_FreeValue(ctx, val); + return ret; + } + case JS_TAG_OBJECT: + { + JSObject *p = JS_VALUE_GET_OBJ(val); + bool ret = !p->is_HTMLDDA; + JS_FreeValue(ctx, val); + return ret; + } + break; + default: + if (JS_TAG_IS_FLOAT64(tag)) { + double d = JS_VALUE_GET_FLOAT64(val); + return !isnan(d) && d != 0; + } else { + JS_FreeValue(ctx, val); + return true; + } + } +} + +int JS_ToBool(JSContext *ctx, JSValueConst val) +{ + return JS_ToBoolFree(ctx, js_dup(val)); +} + +/* pc points to pure ASCII or UTF-8, null terminated contents */ +static int skip_spaces(const char *pc) +{ + const uint8_t *p, *p_next, *p_start; + uint32_t c; + + p = p_start = (const uint8_t *)pc; + for (;;) { + c = *p++; + if (c < 0x80) { + if (!((c >= 0x09 && c <= 0x0d) || (c == 0x20))) + break; + } else { + c = utf8_decode(p - 1, &p_next); + /* no need to test for invalid UTF-8, 0xFFFD is not a space */ + if (!lre_is_space(c)) + break; + p = p_next; + } + } + return p - 1 - p_start; +} + +static inline int js_to_digit(int c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + else if (c >= 'A' && c <= 'Z') + return c - 'A' + 10; + else if (c >= 'a' && c <= 'z') + return c - 'a' + 10; + else + return 36; +} + +/* bigint support */ + +#define ADDC(res, carry_out, op1, op2, carry_in) \ +do { \ + js_limb_t __v, __a, __k, __k1; \ + __v = (op1); \ + __a = __v + (op2); \ + __k1 = __a < __v; \ + __k = (carry_in); \ + __a = __a + __k; \ + carry_out = (__a < __k) | __k1; \ + res = __a; \ +} while (0) + +/* a != 0 */ +static inline js_limb_t js_limb_clz(js_limb_t a) +{ + if (!a) + return JS_LIMB_BITS; + return clz32(a); +} + +static js_limb_t js_mp_add(js_limb_t *res, const js_limb_t *op1, const js_limb_t *op2, + js_limb_t n, js_limb_t carry) +{ + int i; + for(i = 0;i < n; i++) { + ADDC(res[i], carry, op1[i], op2[i], carry); + } + return carry; +} + +static js_limb_t js_mp_sub(js_limb_t *res, const js_limb_t *op1, const js_limb_t *op2, + int n, js_limb_t carry) +{ + int i; + js_limb_t k, a, v, k1; + + k = carry; + for(i=0;i v; + v = a - k; + k = (v > a) | k1; + res[i] = v; + } + return k; +} + +/* compute 0 - op2. carry = 0 or 1. */ +static js_limb_t js_mp_neg(js_limb_t *res, const js_limb_t *op2, int n) +{ + int i; + js_limb_t v, carry; + + carry = 1; + for(i=0;i> JS_LIMB_BITS; + } + return l; +} + +static js_limb_t js_mp_div1(js_limb_t *tabr, const js_limb_t *taba, js_limb_t n, + js_limb_t b, js_limb_t r) +{ + js_slimb_t i; + js_dlimb_t a1; + for(i = n - 1; i >= 0; i--) { + a1 = ((js_dlimb_t)r << JS_LIMB_BITS) | taba[i]; + tabr[i] = a1 / b; + r = a1 % b; + } + return r; +} + +/* tabr[] += taba[] * b, return the high word. */ +static js_limb_t js_mp_add_mul1(js_limb_t *tabr, const js_limb_t *taba, js_limb_t n, + js_limb_t b) +{ + js_limb_t i, l; + js_dlimb_t t; + + l = 0; + for(i = 0; i < n; i++) { + t = (js_dlimb_t)taba[i] * (js_dlimb_t)b + l + tabr[i]; + tabr[i] = t; + l = t >> JS_LIMB_BITS; + } + return l; +} + +/* size of the result : op1_size + op2_size. */ +static void js_mp_mul_basecase(js_limb_t *result, + const js_limb_t *op1, js_limb_t op1_size, + const js_limb_t *op2, js_limb_t op2_size) +{ + int i; + js_limb_t r; + + result[op1_size] = js_mp_mul1(result, op1, op1_size, op2[0], 0); + for(i=1;i> JS_LIMB_BITS); + } + return l; +} + +/* WARNING: d must be >= 2^(JS_LIMB_BITS-1) */ +static inline js_limb_t js_udiv1norm_init(js_limb_t d) +{ + js_limb_t a0, a1; + a1 = -d - 1; + a0 = -1; + return (((js_dlimb_t)a1 << JS_LIMB_BITS) | a0) / d; +} + +/* return the quotient and the remainder in '*pr'of 'a1*2^JS_LIMB_BITS+a0 + / d' with 0 <= a1 < d. */ +static inline js_limb_t js_udiv1norm(js_limb_t *pr, js_limb_t a1, js_limb_t a0, + js_limb_t d, js_limb_t d_inv) +{ + js_limb_t n1m, n_adj, q, r, ah; + js_dlimb_t a; + n1m = ((js_slimb_t)a0 >> (JS_LIMB_BITS - 1)); + n_adj = a0 + (n1m & d); + a = (js_dlimb_t)d_inv * (a1 - n1m) + n_adj; + q = (a >> JS_LIMB_BITS) + a1; + /* compute a - q * r and update q so that the remainder is\ + between 0 and d - 1 */ + a = ((js_dlimb_t)a1 << JS_LIMB_BITS) | a0; + a = a - (js_dlimb_t)q * d - d; + ah = a >> JS_LIMB_BITS; + q += 1 + ah; + r = (js_limb_t)a + (ah & d); + *pr = r; + return q; +} + +#define UDIV1NORM_THRESHOLD 3 + +/* b must be >= 1 << (JS_LIMB_BITS - 1) */ +static js_limb_t js_mp_div1norm(js_limb_t *tabr, const js_limb_t *taba, js_limb_t n, + js_limb_t b, js_limb_t r) +{ + js_slimb_t i; + + if (n >= UDIV1NORM_THRESHOLD) { + js_limb_t b_inv; + b_inv = js_udiv1norm_init(b); + for(i = n - 1; i >= 0; i--) { + tabr[i] = js_udiv1norm(&r, r, taba[i], b, b_inv); + } + } else { + js_dlimb_t a1; + for(i = n - 1; i >= 0; i--) { + a1 = ((js_dlimb_t)r << JS_LIMB_BITS) | taba[i]; + tabr[i] = a1 / b; + r = a1 % b; + } + } + return r; +} + +/* base case division: divides taba[0..na-1] by tabb[0..nb-1]. tabb[nb + - 1] must be >= 1 << (JS_LIMB_BITS - 1). na - nb must be >= 0. 'taba' + is modified and contains the remainder (nb limbs). tabq[0..na-nb] + contains the quotient with tabq[na - nb] <= 1. */ +static void js_mp_divnorm(js_limb_t *tabq, js_limb_t *taba, js_limb_t na, + const js_limb_t *tabb, js_limb_t nb) +{ + js_limb_t r, a, c, q, v, b1, b1_inv, n, dummy_r; + int i, j; + + b1 = tabb[nb - 1]; + if (nb == 1) { + taba[0] = js_mp_div1norm(tabq, taba, na, b1, 0); + return; + } + n = na - nb; + + if (n >= UDIV1NORM_THRESHOLD) + b1_inv = js_udiv1norm_init(b1); + else + b1_inv = 0; + + /* first iteration: the quotient is only 0 or 1 */ + q = 1; + for(j = nb - 1; j >= 0; j--) { + if (taba[n + j] != tabb[j]) { + if (taba[n + j] < tabb[j]) + q = 0; + break; + } + } + tabq[n] = q; + if (q) { + js_mp_sub(taba + n, taba + n, tabb, nb, 0); + } + + for(i = n - 1; i >= 0; i--) { + if (unlikely(taba[i + nb] >= b1)) { + q = -1; + } else if (b1_inv) { + q = js_udiv1norm(&dummy_r, taba[i + nb], taba[i + nb - 1], b1, b1_inv); + } else { + js_dlimb_t al; + al = ((js_dlimb_t)taba[i + nb] << JS_LIMB_BITS) | taba[i + nb - 1]; + q = al / b1; + r = al % b1; + } + r = js_mp_sub_mul1(taba + i, tabb, nb, q); + + v = taba[i + nb]; + a = v - r; + c = (a > v); + taba[i + nb] = a; + + if (c != 0) { + /* negative result */ + for(;;) { + q--; + c = js_mp_add(taba + i, taba + i, tabb, nb, 0); + /* propagate carry and test if positive result */ + if (c != 0) { + if (++taba[i + nb] == 0) { + break; + } + } + } + } + tabq[i] = q; + } +} + +/* 1 <= shift <= JS_LIMB_BITS - 1 */ +static js_limb_t js_mp_shl(js_limb_t *tabr, const js_limb_t *taba, int n, + int shift) +{ + int i; + js_limb_t l, v; + l = 0; + for(i = 0; i < n; i++) { + v = taba[i]; + tabr[i] = (v << shift) | l; + l = v >> (JS_LIMB_BITS - shift); + } + return l; +} + +/* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift). + 1 <= shift <= LIMB_BITS - 1 */ +static js_limb_t js_mp_shr(js_limb_t *tab_r, const js_limb_t *tab, int n, + int shift, js_limb_t high) +{ + int i; + js_limb_t l, a; + + l = high; + for(i = n - 1; i >= 0; i--) { + a = tab[i]; + tab_r[i] = (a >> shift) | (l << (JS_LIMB_BITS - shift)); + l = a; + } + return l & (((js_limb_t)1 << shift) - 1); +} + +static JSBigInt *js_bigint_new(JSContext *ctx, int len) +{ + JSBigInt *r; + if (len > JS_BIGINT_MAX_SIZE) { + JS_ThrowRangeError(ctx, "BigInt is too large to allocate"); + return NULL; + } + r = js_malloc(ctx, sizeof(JSBigInt) + len * sizeof(js_limb_t)); + if (!r) + return NULL; + r->header.ref_count = 1; + r->len = len; + return r; +} + +static JSBigInt *js_bigint_set_si(JSBigIntBuf *buf, js_slimb_t a) +{ + JSBigInt *r = (JSBigInt *)buf->big_int_buf; + r->header.ref_count = 0; /* fail safe */ + r->len = 1; + r->tab[0] = a; + return r; +} + +static JSBigInt *js_bigint_set_si64(JSBigIntBuf *buf, int64_t a) +{ + JSBigInt *r = (JSBigInt *)buf->big_int_buf; + r->header.ref_count = 0; /* fail safe */ + if (a >= INT32_MIN && a <= INT32_MAX) { + r->len = 1; + r->tab[0] = a; + } else { + r->len = 2; + r->tab[0] = a; + r->tab[1] = a >> JS_LIMB_BITS; + } + return r; +} + +/* val must be a short big int */ +static JSBigInt *js_bigint_set_short(JSBigIntBuf *buf, JSValueConst val) +{ + return js_bigint_set_si(buf, JS_VALUE_GET_SHORT_BIG_INT(val)); +} + +static __maybe_unused void js_bigint_dump1(JSContext *ctx, const char *str, + const js_limb_t *tab, int len) +{ + int i; + printf("%s: ", str); + for(i = len - 1; i >= 0; i--) { + printf(" %08x", tab[i]); + } + printf("\n"); +} + +static __maybe_unused void js_bigint_dump(JSContext *ctx, const char *str, + const JSBigInt *p) +{ + js_bigint_dump1(ctx, str, p->tab, p->len); +} + +static JSBigInt *js_bigint_new_si(JSContext *ctx, js_slimb_t a) +{ + JSBigInt *r; + r = js_bigint_new(ctx, 1); + if (!r) + return NULL; + r->tab[0] = a; + return r; +} + +static JSBigInt *js_bigint_new_si64(JSContext *ctx, int64_t a) +{ + if (a >= INT32_MIN && a <= INT32_MAX) { + return js_bigint_new_si(ctx, a); + } else { + JSBigInt *r; + r = js_bigint_new(ctx, 2); + if (!r) + return NULL; + r->tab[0] = a; + r->tab[1] = a >> 32; + return r; + } +} + +static JSBigInt *js_bigint_new_ui64(JSContext *ctx, uint64_t a) +{ + if (a <= INT64_MAX) { + return js_bigint_new_si64(ctx, a); + } else { + JSBigInt *r; + r = js_bigint_new(ctx, (65 + JS_LIMB_BITS - 1) / JS_LIMB_BITS); + if (!r) + return NULL; + r->tab[0] = a; + r->tab[1] = a >> 32; + r->tab[2] = 0; + return r; + } +} + +static JSBigInt *js_bigint_new_di(JSContext *ctx, js_sdlimb_t a) +{ + JSBigInt *r; + if (a == (js_slimb_t)a) { + r = js_bigint_new(ctx, 1); + if (!r) + return NULL; + r->tab[0] = a; + } else { + r = js_bigint_new(ctx, 2); + if (!r) + return NULL; + r->tab[0] = a; + r->tab[1] = a >> JS_LIMB_BITS; + } + return r; +} + +/* Remove redundant high order limbs. Warning: 'a' may be + reallocated. Can never fail. +*/ +static JSBigInt *js_bigint_normalize1(JSContext *ctx, JSBigInt *a, int l) +{ + js_limb_t v; + + assert(a->header.ref_count == 1); + while (l > 1) { + v = a->tab[l - 1]; + if ((v != 0 && v != -1) || + (v & 1) != (a->tab[l - 2] >> (JS_LIMB_BITS - 1))) { + break; + } + l--; + } + if (l != a->len) { + JSBigInt *a1; + /* realloc to reduce the size */ + a->len = l; + a1 = js_realloc(ctx, a, sizeof(JSBigInt) + l * sizeof(js_limb_t)); + if (a1) + a = a1; + } + return a; +} + +static JSBigInt *js_bigint_normalize(JSContext *ctx, JSBigInt *a) +{ + return js_bigint_normalize1(ctx, a, a->len); +} + +/* return 0 or 1 depending on the sign */ +static inline int js_bigint_sign(const JSBigInt *a) +{ + return a->tab[a->len - 1] >> (JS_LIMB_BITS - 1); +} + +static js_slimb_t js_bigint_get_si_sat(const JSBigInt *a) +{ + if (a->len == 1) { + return a->tab[0]; + } else { + if (js_bigint_sign(a)) + return INT32_MIN; + else + return INT32_MAX; + } +} + +/* add the op1 limb */ +static JSBigInt *js_bigint_extend(JSContext *ctx, JSBigInt *r, + js_limb_t op1) +{ + int n2 = r->len; + if ((op1 != 0 && op1 != -1) || + (op1 & 1) != r->tab[n2 - 1] >> (JS_LIMB_BITS - 1)) { + JSBigInt *r1; + r1 = js_realloc(ctx, r, + sizeof(JSBigInt) + (n2 + 1) * sizeof(js_limb_t)); + if (!r1) { + js_free(ctx, r); + return NULL; + } + r = r1; + r->len = n2 + 1; + r->tab[n2] = op1; + } else { + /* otherwise still need to normalize the result */ + r = js_bigint_normalize(ctx, r); + } + return r; +} + +/* return NULL in case of error. Compute a + b (b_neg = 0) or a - b + (b_neg = 1) */ +/* XXX: optimize */ +static JSBigInt *js_bigint_add(JSContext *ctx, const JSBigInt *a, + const JSBigInt *b, int b_neg) +{ + JSBigInt *r; + int n1, n2, i; + js_limb_t carry, op1, op2, a_sign, b_sign; + + n2 = max_int(a->len, b->len); + n1 = min_int(a->len, b->len); + r = js_bigint_new(ctx, n2); + if (!r) + return NULL; + /* XXX: optimize */ + /* common part */ + carry = b_neg; + for(i = 0; i < n1; i++) { + op1 = a->tab[i]; + op2 = b->tab[i] ^ (-b_neg); + ADDC(r->tab[i], carry, op1, op2, carry); + } + a_sign = -js_bigint_sign(a); + b_sign = (-js_bigint_sign(b)) ^ (-b_neg); + /* part with sign extension of one operand */ + if (a->len > b->len) { + for(i = n1; i < n2; i++) { + op1 = a->tab[i]; + ADDC(r->tab[i], carry, op1, b_sign, carry); + } + } else if (a->len < b->len) { + for(i = n1; i < n2; i++) { + op2 = b->tab[i] ^ (-b_neg); + ADDC(r->tab[i], carry, a_sign, op2, carry); + } + } + + /* part with sign extension for both operands. Extend the result + if necessary */ + return js_bigint_extend(ctx, r, a_sign + b_sign + carry); +} + +/* XXX: optimize */ +static JSBigInt *js_bigint_neg(JSContext *ctx, const JSBigInt *a) +{ + JSBigIntBuf buf; + JSBigInt *b; + b = js_bigint_set_si(&buf, 0); + return js_bigint_add(ctx, b, a, 1); +} + +static JSBigInt *js_bigint_mul(JSContext *ctx, const JSBigInt *a, + const JSBigInt *b) +{ + JSBigInt *r; + + r = js_bigint_new(ctx, a->len + b->len); + if (!r) + return NULL; + js_mp_mul_basecase(r->tab, a->tab, a->len, b->tab, b->len); + /* correct the result if negative operands (no overflow is + possible) */ + if (js_bigint_sign(a)) + js_mp_sub(r->tab + a->len, r->tab + a->len, b->tab, b->len, 0); + if (js_bigint_sign(b)) + js_mp_sub(r->tab + b->len, r->tab + b->len, a->tab, a->len, 0); + return js_bigint_normalize(ctx, r); +} + +/* return the division or the remainder. 'b' must be != 0. return NULL + in case of exception (division by zero or memory error) */ +static JSBigInt *js_bigint_divrem(JSContext *ctx, const JSBigInt *a, + const JSBigInt *b, bool is_rem) +{ + JSBigInt *r, *q; + js_limb_t *tabb, h; + int na, nb, a_sign, b_sign, shift; + + if (b->len == 1 && b->tab[0] == 0) { + JS_ThrowRangeError(ctx, "BigInt division by zero"); + return NULL; + } + + a_sign = js_bigint_sign(a); + b_sign = js_bigint_sign(b); + na = a->len; + nb = b->len; + + r = js_bigint_new(ctx, na + 2); + if (!r) + return NULL; + if (a_sign) { + js_mp_neg(r->tab, a->tab, na); + } else { + memcpy(r->tab, a->tab, na * sizeof(a->tab[0])); + } + /* normalize */ + while (na > 1 && r->tab[na - 1] == 0) + na--; + + tabb = js_malloc(ctx, nb * sizeof(tabb[0])); + if (!tabb) { + js_free(ctx, r); + return NULL; + } + if (b_sign) { + js_mp_neg(tabb, b->tab, nb); + } else { + memcpy(tabb, b->tab, nb * sizeof(tabb[0])); + } + /* normalize */ + while (nb > 1 && tabb[nb - 1] == 0) + nb--; + + /* trivial case if 'a' is small */ + if (na < nb) { + js_free(ctx, r); + js_free(ctx, tabb); + if (is_rem) { + /* r = a */ + r = js_bigint_new(ctx, a->len); + if (!r) + return NULL; + memcpy(r->tab, a->tab, a->len * sizeof(a->tab[0])); + return r; + } else { + /* q = 0 */ + return js_bigint_new_si(ctx, 0); + } + } + + /* normalize 'b' */ + shift = js_limb_clz(tabb[nb - 1]); + if (shift != 0) { + js_mp_shl(tabb, tabb, nb, shift); + h = js_mp_shl(r->tab, r->tab, na, shift); + if (h != 0) + r->tab[na++] = h; + } + + q = js_bigint_new(ctx, na - nb + 2); /* one more limb for the sign */ + if (!q) { + js_free(ctx, r); + js_free(ctx, tabb); + return NULL; + } + + // js_bigint_dump1(ctx, "a", r->tab, na); + // js_bigint_dump1(ctx, "b", tabb, nb); + js_mp_divnorm(q->tab, r->tab, na, tabb, nb); + js_free(ctx, tabb); + + if (is_rem) { + js_free(ctx, q); + if (shift != 0) + js_mp_shr(r->tab, r->tab, nb, shift, 0); + r->tab[nb++] = 0; + if (a_sign) + js_mp_neg(r->tab, r->tab, nb); + r = js_bigint_normalize1(ctx, r, nb); + return r; + } else { + js_free(ctx, r); + q->tab[na - nb + 1] = 0; + if (a_sign ^ b_sign) { + js_mp_neg(q->tab, q->tab, q->len); + } + q = js_bigint_normalize(ctx, q); + return q; + } +} + +/* and, or, xor */ +static JSBigInt *js_bigint_logic(JSContext *ctx, const JSBigInt *a, + const JSBigInt *b, OPCodeEnum op) +{ + JSBigInt *r; + js_limb_t b_sign; + int a_len, b_len, i; + + if (a->len < b->len) { + const JSBigInt *tmp; + tmp = a; + a = b; + b = tmp; + } + /* a_len >= b_len */ + a_len = a->len; + b_len = b->len; + b_sign = -js_bigint_sign(b); + + r = js_bigint_new(ctx, a_len); + if (!r) + return NULL; + switch(op) { + case OP_or: + for(i = 0; i < b_len; i++) { + r->tab[i] = a->tab[i] | b->tab[i]; + } + for(i = b_len; i < a_len; i++) { + r->tab[i] = a->tab[i] | b_sign; + } + break; + case OP_and: + for(i = 0; i < b_len; i++) { + r->tab[i] = a->tab[i] & b->tab[i]; + } + for(i = b_len; i < a_len; i++) { + r->tab[i] = a->tab[i] & b_sign; + } + break; + case OP_xor: + for(i = 0; i < b_len; i++) { + r->tab[i] = a->tab[i] ^ b->tab[i]; + } + for(i = b_len; i < a_len; i++) { + r->tab[i] = a->tab[i] ^ b_sign; + } + break; + default: + abort(); + } + return js_bigint_normalize(ctx, r); +} + +static JSBigInt *js_bigint_not(JSContext *ctx, const JSBigInt *a) +{ + JSBigInt *r; + int i; + + r = js_bigint_new(ctx, a->len); + if (!r) + return NULL; + for(i = 0; i < a->len; i++) { + r->tab[i] = ~a->tab[i]; + } + /* no normalization is needed */ + return r; +} + +static JSBigInt *js_bigint_shl(JSContext *ctx, const JSBigInt *a, + unsigned int shift1) +{ + int d, i, shift; + JSBigInt *r; + js_limb_t l; + + if (a->len == 1 && a->tab[0] == 0) + return js_bigint_new_si(ctx, 0); /* zero case */ + d = shift1 / JS_LIMB_BITS; + shift = shift1 % JS_LIMB_BITS; + r = js_bigint_new(ctx, a->len + d); + if (!r) + return NULL; + for(i = 0; i < d; i++) + r->tab[i] = 0; + if (shift == 0) { + for(i = 0; i < a->len; i++) { + r->tab[i + d] = a->tab[i]; + } + } else { + l = js_mp_shl(r->tab + d, a->tab, a->len, shift); + if (js_bigint_sign(a)) + l |= (js_limb_t)(-1) << shift; + r = js_bigint_extend(ctx, r, l); + } + return r; +} + +static JSBigInt *js_bigint_shr(JSContext *ctx, const JSBigInt *a, + unsigned int shift1) +{ + int d, i, shift, a_sign, n1; + JSBigInt *r; + + d = shift1 / JS_LIMB_BITS; + shift = shift1 % JS_LIMB_BITS; + a_sign = js_bigint_sign(a); + if (d >= a->len) + return js_bigint_new_si(ctx, -a_sign); + n1 = a->len - d; + r = js_bigint_new(ctx, n1); + if (!r) + return NULL; + if (shift == 0) { + for(i = 0; i < n1; i++) { + r->tab[i] = a->tab[i + d]; + } + /* no normalization is needed */ + } else { + js_mp_shr(r->tab, a->tab + d, n1, shift, -a_sign); + r = js_bigint_normalize(ctx, r); + } + return r; +} + +static JSBigInt *js_bigint_pow(JSContext *ctx, const JSBigInt *a, JSBigInt *b) +{ + uint32_t e; + int n_bits, i; + JSBigInt *r, *r1; + + /* b must be >= 0 */ + if (js_bigint_sign(b)) { + JS_ThrowRangeError(ctx, "BigInt negative exponent"); + return NULL; + } + if (b->len == 1 && b->tab[0] == 0) { + /* a^0 = 1 */ + return js_bigint_new_si(ctx, 1); + } else if (a->len == 1) { + js_limb_t v; + bool is_neg; + + v = a->tab[0]; + if (v <= 1) + return js_bigint_new_si(ctx, v); + else if (v == -1) + return js_bigint_new_si(ctx, 1 - 2 * (b->tab[0] & 1)); + is_neg = (js_slimb_t)v < 0; + if (is_neg) + v = -v; + if ((v & (v - 1)) == 0) { + uint64_t e1; + int n; + /* v = 2^n */ + n = JS_LIMB_BITS - 1 - js_limb_clz(v); + if (b->len > 1) + goto overflow; + if (b->tab[0] > INT32_MAX) + goto overflow; + e = b->tab[0]; + e1 = (uint64_t)e * n; + if (e1 > JS_BIGINT_MAX_SIZE * JS_LIMB_BITS) + goto overflow; + e = e1; + if (is_neg) + is_neg = b->tab[0] & 1; + r = js_bigint_new(ctx, + (e + JS_LIMB_BITS + 1 - is_neg) / JS_LIMB_BITS); + if (!r) + return NULL; + memset(r->tab, 0, sizeof(r->tab[0]) * r->len); + r->tab[e / JS_LIMB_BITS] = + (js_limb_t)(1 - 2 * is_neg) << (e % JS_LIMB_BITS); + return r; + } + } + if (b->len > 1) + goto overflow; + if (b->tab[0] > INT32_MAX) + goto overflow; + e = b->tab[0]; + n_bits = 32 - clz32(e); + + r = js_bigint_new(ctx, a->len); + if (!r) + return NULL; + memcpy(r->tab, a->tab, a->len * sizeof(a->tab[0])); + for(i = n_bits - 2; i >= 0; i--) { + r1 = js_bigint_mul(ctx, r, r); + if (!r1) + return NULL; + js_free(ctx, r); + r = r1; + if ((e >> i) & 1) { + r1 = js_bigint_mul(ctx, r, a); + if (!r1) + return NULL; + js_free(ctx, r); + r = r1; + } + } + return r; + overflow: + JS_ThrowRangeError(ctx, "BigInt is too large"); + return NULL; +} + +/* return (mant, exp) so that abs(a) ~ mant*2^(exp - (limb_bits - + 1). a must be != 0. */ +static uint64_t js_bigint_get_mant_exp(JSContext *ctx, + int *pexp, const JSBigInt *a) +{ + js_limb_t t[4 - JS_LIMB_BITS / 32], carry, v, low_bits; + int n1, n2, sgn, shift, i, j, e; + uint64_t a1, a0; + + n2 = 4 - JS_LIMB_BITS / 32; + n1 = a->len - n2; + sgn = js_bigint_sign(a); + + /* low_bits != 0 if there are a non zero low bit in abs(a) */ + low_bits = 0; + carry = sgn; + for(i = 0; i < n1; i++) { + v = (a->tab[i] ^ (-sgn)) + carry; + carry = v < carry; + low_bits |= v; + } + /* get the n2 high limbs of abs(a) */ + for(j = 0; j < n2; j++) { + i = j + n1; + if (i < 0) { + v = 0; + } else { + v = (a->tab[i] ^ (-sgn)) + carry; + carry = v < carry; + } + t[j] = v; + } + + a1 = ((uint64_t)t[2] << 32) | t[1]; + a0 = (uint64_t)t[0] << 32; + a0 |= (low_bits != 0); + /* normalize */ + { + shift = clz64(a1); + if (shift != 0) { + a1 = (a1 << shift) | (a0 >> (64 - shift)); + a0 <<= shift; + } + } + a1 |= (a0 != 0); /* keep the bits for the final rounding */ + /* compute the exponent */ + e = a->len * JS_LIMB_BITS - shift - 1; + *pexp = e; + return a1; +} + +/* shift left with round to nearest, ties to even. n >= 1 */ +static uint64_t shr_rndn(uint64_t a, int n) +{ + uint64_t addend = ((a >> n) & 1) + ((1 << (n - 1)) - 1); + return (a + addend) >> n; +} + +/* convert to float64 with round to nearest, ties to even. Return + +/-infinity if too large. */ +static double js_bigint_to_float64(JSContext *ctx, const JSBigInt *a) +{ + int sgn, e; + uint64_t mant; + + if (a->len == 1) { + /* fast case, including zero */ + return (double)(js_slimb_t)a->tab[0]; + } + + sgn = js_bigint_sign(a); + mant = js_bigint_get_mant_exp(ctx, &e, a); + if (e > 1023) { + /* overflow: return infinity */ + mant = 0; + e = 1024; + } else { + mant = (mant >> 1) | (mant & 1); /* avoid overflow in rounding */ + mant = shr_rndn(mant, 10); + /* rounding can cause an overflow */ + if (mant >= ((uint64_t)1 << 53)) { + mant >>= 1; + e++; + } + mant &= (((uint64_t)1 << 52) - 1); + } + return uint64_as_float64(((uint64_t)sgn << 63) | + ((uint64_t)(e + 1023) << 52) | + mant); +} + +/* return (1, NULL) if not an integer, (2, NULL) if NaN or Infinity, + (0, n) if an integer, (0, NULL) in case of memory error */ +static JSBigInt *js_bigint_from_float64(JSContext *ctx, int *pres, double a1) +{ + uint64_t a = float64_as_uint64(a1); + int sgn, e, shift; + uint64_t mant; + JSBigIntBuf buf; + JSBigInt *r; + + sgn = a >> 63; + e = (a >> 52) & ((1 << 11) - 1); + mant = a & (((uint64_t)1 << 52) - 1); + if (e == 2047) { + /* NaN, Infinity */ + *pres = 2; + return NULL; + } + if (e == 0 && mant == 0) { + /* zero */ + *pres = 0; + return js_bigint_new_si(ctx, 0); + } + e -= 1023; + /* 0 < a < 1 : not an integer */ + if (e < 0) + goto not_an_integer; + mant |= (uint64_t)1 << 52; + if (e < 52) { + shift = 52 - e; + /* check that there is no fractional part */ + if (mant & (((uint64_t)1 << shift) - 1)) { + not_an_integer: + *pres = 1; + return NULL; + } + mant >>= shift; + e = 0; + } else { + e -= 52; + } + if (sgn) + mant = -mant; + /* the integer is mant*2^e */ + r = js_bigint_set_si64(&buf, (int64_t)mant); + *pres = 0; + return js_bigint_shl(ctx, r, e); +} + +/* return -1, 0, 1 or (2) (unordered) */ +static int js_bigint_float64_cmp(JSContext *ctx, const JSBigInt *a, + double b) +{ + int b_sign, a_sign, e, f; + uint64_t mant, b1, a_mant; + + b1 = float64_as_uint64(b); + b_sign = b1 >> 63; + e = (b1 >> 52) & ((1 << 11) - 1); + mant = b1 & (((uint64_t)1 << 52) - 1); + a_sign = js_bigint_sign(a); + if (e == 2047) { + if (mant != 0) { + /* NaN */ + return 2; + } else { + /* +/- infinity */ + return 2 * b_sign - 1; + } + } else if (e == 0 && mant == 0) { + /* b = +/-0 */ + if (a->len == 1 && a->tab[0] == 0) + return 0; + else + return 1 - 2 * a_sign; + } else if (a->len == 1 && a->tab[0] == 0) { + /* a = 0, b != 0 */ + return 2 * b_sign - 1; + } else if (a_sign != b_sign) { + return 1 - 2 * a_sign; + } else { + e -= 1023; + /* Note: handling denormals is not necessary because we + compare to integers hence f >= 0 */ + /* compute f so that 2^f <= abs(a) < 2^(f+1) */ + a_mant = js_bigint_get_mant_exp(ctx, &f, a); + if (f != e) { + if (f < e) + return -1; + else + return 1; + } else { + mant = (mant | ((uint64_t)1 << 52)) << 11; /* align to a_mant */ + if (a_mant < mant) + return 2 * a_sign - 1; + else if (a_mant > mant) + return 1 - 2 * a_sign; + else + return 0; + } + } +} + +/* return -1, 0 or 1 */ +static int js_bigint_cmp(JSContext *ctx, const JSBigInt *a, + const JSBigInt *b) +{ + int a_sign, b_sign, res, i; + a_sign = js_bigint_sign(a); + b_sign = js_bigint_sign(b); + if (a_sign != b_sign) { + res = 1 - 2 * a_sign; + } else { + /* we assume the numbers are normalized */ + if (a->len != b->len) { + if (a->len < b->len) + res = 2 * a_sign - 1; + else + res = 1 - 2 * a_sign; + } else { + res = 0; + for(i = a->len -1; i >= 0; i--) { + if (a->tab[i] != b->tab[i]) { + if (a->tab[i] < b->tab[i]) + res = -1; + else + res = 1; + break; + } + } + } + } + return res; +} + +/* contains 10^i */ +static const js_limb_t js_pow_dec[JS_LIMB_DIGITS + 1] = { + 1U, + 10U, + 100U, + 1000U, + 10000U, + 100000U, + 1000000U, + 10000000U, + 100000000U, + 1000000000U, +}; + +/* syntax: [-]digits in base radix. Return NULL if memory error. radix + = 10, 2, 8 or 16. */ +static JSBigInt *js_bigint_from_string(JSContext *ctx, + const char *str, int radix) +{ + const char *p = str; + size_t n_digits1; + int is_neg, n_digits, n_limbs, len, log2_radix, n_bits, i; + JSBigInt *r; + js_limb_t v, c, h; + + is_neg = 0; + if (*p == '-') { + is_neg = 1; + p++; + } + while (*p == '0') + p++; + n_digits1 = strlen(p); + /* the real check for overflox is done js_bigint_new(). Here + we just avoid integer overflow */ + if (n_digits1 > JS_BIGINT_MAX_SIZE * JS_LIMB_BITS) { + JS_ThrowRangeError(ctx, "BigInt is too large to allocate"); + return NULL; + } + n_digits = n_digits1; + log2_radix = 32 - clz32(radix - 1); /* ceil(log2(radix)) */ + /* compute the maximum number of limbs */ + if (radix == 10) { + n_bits = (n_digits * 27 + 7) / 8; /* >= ceil(n_digits * log2(10)) */ + } else { + n_bits = n_digits * log2_radix; + } + /* we add one extra bit for the sign */ + n_limbs = max_int(1, n_bits / JS_LIMB_BITS + 1); + r = js_bigint_new(ctx, n_limbs); + if (!r) + return NULL; + if (radix == 10) { + int digits_per_limb = JS_LIMB_DIGITS; + len = 1; + r->tab[0] = 0; + for(;;) { + /* XXX: slow */ + v = 0; + for(i = 0; i < digits_per_limb; i++) { + c = js_to_digit(*p); + if (c >= radix) + break; + p++; + v = v * 10 + c; + } + if (i == 0) + break; + if (len == 1 && r->tab[0] == 0) { + r->tab[0] = v; + } else { + h = js_mp_mul1(r->tab, r->tab, len, js_pow_dec[i], v); + if (h != 0) { + r->tab[len++] = h; + } + } + } + /* add one extra limb to have the correct sign*/ + if ((r->tab[len - 1] >> (JS_LIMB_BITS - 1)) != 0) + r->tab[len++] = 0; + r->len = len; + } else { + unsigned int bit_pos, shift, pos; + + /* power of two base: no multiplication is needed */ + r->len = n_limbs; + memset(r->tab, 0, sizeof(r->tab[0]) * n_limbs); + for(i = 0; i < n_digits; i++) { + c = js_to_digit(p[n_digits - 1 - i]); + assert(c < radix); + bit_pos = i * log2_radix; + shift = bit_pos & (JS_LIMB_BITS - 1); + pos = bit_pos / JS_LIMB_BITS; + r->tab[pos] |= c << shift; + /* if log2_radix does not divide JS_LIMB_BITS, needed an + additional op */ + if (shift + log2_radix > JS_LIMB_BITS) { + r->tab[pos + 1] |= c >> (JS_LIMB_BITS - shift); + } + } + } + r = js_bigint_normalize(ctx, r); + /* XXX: could do it in place */ + if (is_neg) { + JSBigInt *r1; + r1 = js_bigint_neg(ctx, r); + js_free(ctx, r); + r = r1; + } + return r; +} + +/* 2 <= base <= 36 */ +static char const digits[36] = { + '0','1','2','3','4','5','6','7','8','9', + 'a','b','c','d','e','f','g','h','i','j', + 'k','l','m','n','o','p','q','r','s','t', + 'u','v','w','x','y','z' +}; + +/* special version going backwards */ +/* XXX: use dtoa.c */ +static char *js_u64toa(char *q, int64_t n, unsigned int base) +{ + int digit; + if (base == 10) { + /* division by known base uses multiplication */ + do { + digit = (uint64_t)n % 10; + n = (uint64_t)n / 10; + *--q = '0' + digit; + } while (n != 0); + } else { + do { + digit = (uint64_t)n % base; + n = (uint64_t)n / base; + *--q = digits[digit]; + } while (n != 0); + } + return q; +} + +/* len >= 1. 2 <= radix <= 36 */ +static char *js_limb_to_a(char *q, js_limb_t n, unsigned int radix, int len) +{ + int digit, i; + + if (radix == 10) { + /* specific case with constant divisor */ + /* XXX: optimize */ + for(i = 0; i < len; i++) { + digit = (js_limb_t)n % 10; + n = (js_limb_t)n / 10; + *--q = digit + '0'; + } + } else { + for(i = 0; i < len; i++) { + digit = (js_limb_t)n % radix; + n = (js_limb_t)n / radix; + *--q = digits[digit]; + } + } + return q; +} + +#define JS_RADIX_MAX 36 + +static const uint8_t js_digits_per_limb_table[JS_RADIX_MAX - 1] = { +32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, +}; + +static const js_limb_t js_radix_base_table[JS_RADIX_MAX - 1] = { + 0x00000000, 0xcfd41b91, 0x00000000, 0x48c27395, + 0x81bf1000, 0x75db9c97, 0x40000000, 0xcfd41b91, + 0x3b9aca00, 0x8c8b6d2b, 0x19a10000, 0x309f1021, + 0x57f6c100, 0x98c29b81, 0x00000000, 0x18754571, + 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, + 0x94ace180, 0xcaf18367, 0x0b640000, 0x0e8d4a51, + 0x1269ae40, 0x17179149, 0x1cb91000, 0x23744899, + 0x2b73a840, 0x34e63b41, 0x40000000, 0x4cfa3cc1, + 0x5c13d840, 0x6d91b519, 0x81bf1000, +}; + +static JSValue js_bigint_to_string1(JSContext *ctx, JSValueConst val, int radix) +{ + if (JS_VALUE_GET_TAG(val) == JS_TAG_SHORT_BIG_INT) { + char buf[66]; + int len; + len = i64toa_radix(buf, JS_VALUE_GET_SHORT_BIG_INT(val), radix); + return js_new_string8_len(ctx, buf, len); + } else { + JSBigInt *r, *tmp = NULL; + char *buf, *q, *buf_end; + int is_neg, n_bits, log2_radix, n_digits; + bool is_binary_radix; + JSValue res; + + assert(JS_VALUE_GET_TAG(val) == JS_TAG_BIG_INT); + r = JS_VALUE_GET_PTR(val); + if (r->len == 1 && r->tab[0] == 0) { + /* '0' case */ + return js_new_string8_len(ctx, "0", 1); + } + is_binary_radix = ((radix & (radix - 1)) == 0); + is_neg = js_bigint_sign(r); + if (is_neg) { + tmp = js_bigint_neg(ctx, r); + if (!tmp) + return JS_EXCEPTION; + r = tmp; + } else if (!is_binary_radix) { + /* need to modify 'r' */ + tmp = js_bigint_new(ctx, r->len); + if (!tmp) + return JS_EXCEPTION; + memcpy(tmp->tab, r->tab, r->len * sizeof(r->tab[0])); + r = tmp; + } + log2_radix = 31 - clz32(radix); /* floor(log2(radix)) */ + n_bits = r->len * JS_LIMB_BITS - js_limb_clz(r->tab[r->len - 1]); + /* n_digits is exact only if radix is a power of + two. Otherwise it is >= the exact number of digits */ + n_digits = (n_bits + log2_radix - 1) / log2_radix; + /* XXX: could directly build the JSString */ + buf = js_malloc(ctx, n_digits + is_neg + 1); + if (!buf) { + js_free(ctx, tmp); + return JS_EXCEPTION; + } + q = buf + n_digits + is_neg + 1; + *--q = '\0'; + buf_end = q; + if (!is_binary_radix) { + int len; + js_limb_t radix_base, v; + radix_base = js_radix_base_table[radix - 2]; + len = r->len; + for(;;) { + /* remove leading zero limbs */ + while (len > 1 && r->tab[len - 1] == 0) + len--; + if (len == 1 && r->tab[0] < radix_base) { + v = r->tab[0]; + if (v != 0) { + q = js_u64toa(q, v, radix); + } + break; + } else { + v = js_mp_div1(r->tab, r->tab, len, radix_base, 0); + q = js_limb_to_a(q, v, radix, js_digits_per_limb_table[radix - 2]); + } + } + } else { + int i, shift; + unsigned int bit_pos, pos, c; + + /* radix is a power of two */ + for(i = 0; i < n_digits; i++) { + bit_pos = i * log2_radix; + pos = bit_pos / JS_LIMB_BITS; + shift = bit_pos % JS_LIMB_BITS; + c = r->tab[pos] >> shift; + if ((shift + log2_radix) > JS_LIMB_BITS && + (pos + 1) < r->len) { + c |= r->tab[pos + 1] << (JS_LIMB_BITS - shift); + } + c &= (radix - 1); + *--q = digits[c]; + } + } + if (is_neg) + *--q = '-'; + js_free(ctx, tmp); + res = js_new_string8_len(ctx, q, buf_end - q); + js_free(ctx, buf); + return res; + } +} + +/* if possible transform a BigInt to short big and free it, otherwise + return a normal bigint */ +static JSValue JS_CompactBigInt(JSContext *ctx, JSBigInt *p) +{ + JSValue res; + if (p->len == 1) { + res = __JS_NewShortBigInt(ctx, (js_slimb_t)p->tab[0]); + js_free(ctx, p); + return res; + } else { + return JS_MKPTR(JS_TAG_BIG_INT, p); + } +} + +#define ATOD_INT_ONLY (1 << 0) +/* accept Oo and Ob prefixes in addition to 0x prefix if radix = 0 */ +#define ATOD_ACCEPT_BIN_OCT (1 << 2) +/* accept O prefix as octal if radix == 0 and properly formed (Annex B) */ +#define ATOD_ACCEPT_LEGACY_OCTAL (1 << 4) +/* accept _ between digits as a digit separator */ +#define ATOD_ACCEPT_UNDERSCORES (1 << 5) +/* allow a suffix to override the type */ +#define ATOD_ACCEPT_SUFFIX (1 << 6) +/* default type */ +#define ATOD_TYPE_MASK (3 << 7) +#define ATOD_TYPE_FLOAT64 (0 << 7) +#define ATOD_TYPE_BIG_INT (1 << 7) +/* accept -0x1 */ +#define ATOD_ACCEPT_PREFIX_AFTER_SIGN (1 << 10) + +/* return an exception in case of memory error. Return JS_NAN if + invalid syntax */ +/* XXX: directly use js_atod() */ +static JSValue js_atof(JSContext *ctx, const char *str, const char **pp, + int radix, int flags) +{ + const char *p, *p_start; + int sep, is_neg; + bool is_float, has_legacy_octal; + int atod_type = flags & ATOD_TYPE_MASK; + char buf1[64], *buf; + int i, j, len; + bool buf_allocated = false; + JSValue val; + JSATODTempMem atod_mem; + + /* optional separator between digits */ + sep = (flags & ATOD_ACCEPT_UNDERSCORES) ? '_' : 256; + has_legacy_octal = false; + + p = str; + p_start = p; + is_neg = 0; + if (p[0] == '+') { + p++; + p_start++; + if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN)) + goto no_radix_prefix; + } else if (p[0] == '-') { + p++; + p_start++; + is_neg = 1; + if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN)) + goto no_radix_prefix; + } + if (p[0] == '0') { + if ((p[1] == 'x' || p[1] == 'X') && + (radix == 0 || radix == 16)) { + p += 2; + radix = 16; + } else if ((p[1] == 'o' || p[1] == 'O') && + radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) { + p += 2; + radix = 8; + } else if ((p[1] == 'b' || p[1] == 'B') && + radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) { + p += 2; + radix = 2; + } else if ((p[1] >= '0' && p[1] <= '9') && + radix == 0 && (flags & ATOD_ACCEPT_LEGACY_OCTAL)) { + int i; + has_legacy_octal = true; + sep = 256; + for (i = 1; (p[i] >= '0' && p[i] <= '7'); i++) + continue; + if (p[i] == '8' || p[i] == '9') + goto no_prefix; + p += 1; + radix = 8; + } else { + goto no_prefix; + } + /* there must be a digit after the prefix */ + if (js_to_digit((uint8_t)*p) >= radix) + goto fail; + no_prefix: ; + } else { + no_radix_prefix: + if (!(flags & ATOD_INT_ONLY) && + (atod_type == ATOD_TYPE_FLOAT64) && + js__strstart(p, "Infinity", &p)) { + double d = INFINITY; + if (is_neg) + d = -d; + val = js_float64(d); + goto done; + } + } + if (radix == 0) + radix = 10; + is_float = false; + p_start = p; + while (js_to_digit((uint8_t)*p) < radix + || (*p == sep && (radix != 10 || + p != p_start + 1 || p[-1] != '0') && + js_to_digit((uint8_t)p[1]) < radix)) { + p++; + } + if (!(flags & ATOD_INT_ONLY) && radix == 10) { + if (*p == '.' && (p > p_start || js_to_digit((uint8_t)p[1]) < radix)) { + is_float = true; + p++; + if (*p == sep) + goto fail; + while (js_to_digit((uint8_t)*p) < radix || + (*p == sep && js_to_digit((uint8_t)p[1]) < radix)) + p++; + } + if (p > p_start && (*p == 'e' || *p == 'E')) { + const char *p1 = p + 1; + is_float = true; + if (*p1 == '+') { + p1++; + } else if (*p1 == '-') { + p1++; + } + if (is_digit((uint8_t)*p1)) { + p = p1 + 1; + while (is_digit((uint8_t)*p) || (*p == sep && is_digit((uint8_t)p[1]))) + p++; + } + } + } + if (p == p_start) + goto fail; + + buf = buf1; + buf_allocated = false; + len = p - p_start; + if (unlikely((len + 2) > sizeof(buf1))) { + buf = js_malloc_rt(ctx->rt, len + 2); /* no exception raised */ + if (!buf) + goto mem_error; + buf_allocated = true; + } + /* remove the separators and the radix prefixes */ + j = 0; + if (is_neg) + buf[j++] = '-'; + for (i = 0; i < len; i++) { + if (p_start[i] != '_') + buf[j++] = p_start[i]; + } + buf[j] = '\0'; + + if (flags & ATOD_ACCEPT_SUFFIX) { + if (*p == 'n') { + p++; + atod_type = ATOD_TYPE_BIG_INT; + } + } + + switch(atod_type) { + case ATOD_TYPE_FLOAT64: + { + double d; + d = js_atod(buf, NULL, radix, is_float ? 0 : JS_ATOD_INT_ONLY, + &atod_mem); + /* return int or float64 */ + val = js_number(d); + } + break; + case ATOD_TYPE_BIG_INT: + { + JSBigInt *r; + if (has_legacy_octal || is_float) + goto fail; + r = js_bigint_from_string(ctx, buf, radix); + if (!r) { + val = JS_EXCEPTION; + goto done; + } + val = JS_CompactBigInt(ctx, r); + } + break; + default: + abort(); + } + +done: + if (buf_allocated) + js_free_rt(ctx->rt, buf); + if (pp) + *pp = p; + return val; + fail: + val = JS_NAN; + goto done; + mem_error: + val = JS_ThrowOutOfMemory(ctx); + goto done; +} + +typedef enum JSToNumberHintEnum { + TON_FLAG_NUMBER, + TON_FLAG_NUMERIC, +} JSToNumberHintEnum; + +static JSValue JS_ToNumberHintFree(JSContext *ctx, JSValue val, + JSToNumberHintEnum flag) +{ + uint32_t tag; + JSValue ret; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_BIG_INT: + case JS_TAG_SHORT_BIG_INT: + if (flag != TON_FLAG_NUMERIC) { + JS_FreeValue(ctx, val); + return JS_ThrowTypeError(ctx, "cannot convert BigInt to number"); + } + ret = val; + break; + case JS_TAG_FLOAT64: + case JS_TAG_INT: + case JS_TAG_EXCEPTION: + ret = val; + break; + case JS_TAG_BOOL: + case JS_TAG_NULL: + ret = js_int32(JS_VALUE_GET_INT(val)); + break; + case JS_TAG_UNDEFINED: + ret = JS_NAN; + break; + case JS_TAG_OBJECT: + val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER); + if (JS_IsException(val)) + return JS_EXCEPTION; + goto redo; + case JS_TAG_STRING: + case JS_TAG_STRING_ROPE: + { + const char *str; + const char *p; + size_t len; + + str = JS_ToCStringLen(ctx, &len, val); + JS_FreeValue(ctx, val); + if (!str) + return JS_EXCEPTION; + p = str; + p += skip_spaces(p); + if ((p - str) == len) { + ret = JS_NewInt32(ctx, 0); + } else { + int flags = ATOD_ACCEPT_BIN_OCT; + ret = js_atof(ctx, p, &p, 0, flags); + if (!JS_IsException(ret)) { + p += skip_spaces(p); + if ((p - str) != len) { + JS_FreeValue(ctx, ret); + ret = JS_NAN; + } + } + } + JS_FreeCString(ctx, str); + } + break; + case JS_TAG_SYMBOL: + JS_FreeValue(ctx, val); + return JS_ThrowTypeError(ctx, "cannot convert symbol to number"); + default: + JS_FreeValue(ctx, val); + ret = JS_NAN; + break; + } + return ret; +} + +static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val) +{ + return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMBER); +} + +static JSValue JS_ToNumericFree(JSContext *ctx, JSValue val) +{ + return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMERIC); +} + +static JSValue JS_ToNumeric(JSContext *ctx, JSValueConst val) +{ + return JS_ToNumericFree(ctx, js_dup(val)); +} + +static __exception int __JS_ToFloat64Free(JSContext *ctx, double *pres, + JSValue val) +{ + double d; + uint32_t tag; + + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) + goto fail; + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + d = JS_VALUE_GET_INT(val); + break; + case JS_TAG_FLOAT64: + d = JS_VALUE_GET_FLOAT64(val); + break; + default: + abort(); + } + *pres = d; + return 0; +fail: + *pres = NAN; + return -1; +} + +static inline int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val) +{ + uint32_t tag; + + tag = JS_VALUE_GET_TAG(val); + if (tag <= JS_TAG_NULL) { + *pres = JS_VALUE_GET_INT(val); + return 0; + } else if (JS_TAG_IS_FLOAT64(tag)) { + *pres = JS_VALUE_GET_FLOAT64(val); + return 0; + } else { + return __JS_ToFloat64Free(ctx, pres, val); + } +} + +int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val) +{ + return JS_ToFloat64Free(ctx, pres, js_dup(val)); +} + +JSValue JS_ToNumber(JSContext *ctx, JSValueConst val) +{ + return JS_ToNumberFree(ctx, js_dup(val)); +} + +/* same as JS_ToNumber() but return 0 in case of NaN/Undefined */ +static __maybe_unused JSValue JS_ToIntegerFree(JSContext *ctx, JSValue val) +{ + uint32_t tag; + JSValue ret; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + ret = js_int32(JS_VALUE_GET_INT(val)); + break; + case JS_TAG_FLOAT64: + { + double d = JS_VALUE_GET_FLOAT64(val); + if (isnan(d)) { + ret = js_int32(0); + } else { + /* convert -0 to +0 */ + d = trunc(d) + 0.0; + ret = js_number(d); + } + } + break; + default: + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) + return val; + goto redo; + } + return ret; +} + +/* Note: the integer value is satured to 32 bits */ +static int JS_ToInt32SatFree(JSContext *ctx, int *pres, JSValue val) +{ + uint32_t tag; + int ret; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + ret = JS_VALUE_GET_INT(val); + break; + case JS_TAG_EXCEPTION: + *pres = 0; + return -1; + case JS_TAG_FLOAT64: + { + double d = JS_VALUE_GET_FLOAT64(val); + if (isnan(d)) { + ret = 0; + } else { + if (d < INT32_MIN) + ret = INT32_MIN; + else if (d > INT32_MAX) + ret = INT32_MAX; + else + ret = (int)d; + } + } + break; + default: + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) { + *pres = 0; + return -1; + } + goto redo; + } + *pres = ret; + return 0; +} + +static int JS_ToInt32Sat(JSContext *ctx, int *pres, JSValueConst val) +{ + return JS_ToInt32SatFree(ctx, pres, js_dup(val)); +} + +static int JS_ToInt32Clamp(JSContext *ctx, int *pres, JSValueConst val, + int min, int max, int min_offset) +{ + int res = JS_ToInt32SatFree(ctx, pres, js_dup(val)); + if (res == 0) { + if (*pres < min) { + *pres += min_offset; + if (*pres < min) + *pres = min; + } else { + if (*pres > max) + *pres = max; + } + } + return res; +} + +static int JS_ToInt64SatFree(JSContext *ctx, int64_t *pres, JSValue val) +{ + uint32_t tag; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + *pres = JS_VALUE_GET_INT(val); + return 0; + case JS_TAG_EXCEPTION: + *pres = 0; + return -1; + case JS_TAG_FLOAT64: + { + double d = JS_VALUE_GET_FLOAT64(val); + if (isnan(d)) { + *pres = 0; + } else { + if (d < INT64_MIN) + *pres = INT64_MIN; + else if (d >= 0x1p63) + *pres = INT64_MAX; + else + *pres = (int64_t)d; + } + } + return 0; + default: + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) { + *pres = 0; + return -1; + } + goto redo; + } +} + +int JS_ToInt64Sat(JSContext *ctx, int64_t *pres, JSValueConst val) +{ + return JS_ToInt64SatFree(ctx, pres, js_dup(val)); +} + +int JS_ToInt64Clamp(JSContext *ctx, int64_t *pres, JSValueConst val, + int64_t min, int64_t max, int64_t neg_offset) +{ + int res = JS_ToInt64SatFree(ctx, pres, js_dup(val)); + if (res == 0) { + if (*pres < 0) + *pres += neg_offset; + if (*pres < min) + *pres = min; + else if (*pres > max) + *pres = max; + } + return res; +} + +/* Same as JS_ToInt32Free() but with a 64 bit result. Return (<0, 0) + in case of exception */ +static int JS_ToInt64Free(JSContext *ctx, int64_t *pres, JSValue val) +{ + uint32_t tag; + int64_t ret; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + ret = JS_VALUE_GET_INT(val); + break; + case JS_TAG_FLOAT64: + { + JSFloat64Union u; + double d; + int e; + d = JS_VALUE_GET_FLOAT64(val); + u.d = d; + /* we avoid doing fmod(x, 2^64) */ + e = (u.u64 >> 52) & 0x7ff; + if (likely(e <= (1023 + 62))) { + /* fast case */ + ret = (int64_t)d; + } else if (e <= (1023 + 62 + 53)) { + uint64_t v; + /* remainder modulo 2^64 */ + v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52); + ret = v << ((e - 1023) - 52); + /* take the sign into account */ + if (u.u64 >> 63) + if (ret != INT64_MIN) + ret = -ret; + } else { + ret = 0; /* also handles NaN and +inf */ + } + } + break; + default: + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) { + *pres = 0; + return -1; + } + goto redo; + } + *pres = ret; + return 0; +} + +int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val) +{ + return JS_ToInt64Free(ctx, pres, js_dup(val)); +} + +int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val) +{ + if (JS_IsBigInt(val)) + return JS_ToBigInt64(ctx, pres, val); + else + return JS_ToInt64(ctx, pres, val); +} + +/* return (<0, 0) in case of exception */ +static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val) +{ + uint32_t tag; + int32_t ret; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + ret = JS_VALUE_GET_INT(val); + break; + case JS_TAG_FLOAT64: + { + JSFloat64Union u; + double d; + int e; + d = JS_VALUE_GET_FLOAT64(val); + u.d = d; + /* we avoid doing fmod(x, 2^32) */ + e = (u.u64 >> 52) & 0x7ff; + if (likely(e <= (1023 + 30))) { + /* fast case */ + ret = (int32_t)d; + } else if (e <= (1023 + 30 + 53)) { + uint64_t v; + /* remainder modulo 2^32 */ + v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52); + v = v << ((e - 1023) - 52 + 32); + ret = v >> 32; + /* take the sign into account */ + if (u.u64 >> 63) + if (ret != INT32_MIN) + ret = -ret; + } else { + ret = 0; /* also handles NaN and +inf */ + } + } + break; + default: + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) { + *pres = 0; + return -1; + } + goto redo; + } + *pres = ret; + return 0; +} + +int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val) +{ + return JS_ToInt32Free(ctx, pres, js_dup(val)); +} + +static inline int JS_ToUint32Free(JSContext *ctx, uint32_t *pres, JSValue val) +{ + return JS_ToInt32Free(ctx, (int32_t *)pres, val); +} + +static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val) +{ + uint32_t tag; + int res; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + res = JS_VALUE_GET_INT(val); + res = max_int(0, min_int(255, res)); + break; + case JS_TAG_FLOAT64: + { + double d = JS_VALUE_GET_FLOAT64(val); + if (isnan(d)) { + res = 0; + } else { + if (d < 0) + res = 0; + else if (d > 255) + res = 255; + else + res = lrint(d); + } + } + break; + default: + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) { + *pres = 0; + return -1; + } + goto redo; + } + *pres = res; + return 0; +} + +static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen, + JSValue val, bool is_array_ctor) +{ + uint32_t tag, len; + + tag = JS_VALUE_GET_TAG(val); + switch(tag) { + case JS_TAG_INT: + case JS_TAG_BOOL: + case JS_TAG_NULL: + { + int v; + v = JS_VALUE_GET_INT(val); + if (v < 0) + goto fail; + len = v; + } + break; + default: + if (JS_TAG_IS_FLOAT64(tag)) { + double d; + d = JS_VALUE_GET_FLOAT64(val); + if (!(d >= 0 && d <= UINT32_MAX)) + goto fail; + len = (uint32_t)d; + if (len != d) + goto fail; + } else { + uint32_t len1; + + if (is_array_ctor) { + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) + return -1; + /* cannot recurse because val is a number */ + if (JS_ToArrayLengthFree(ctx, &len, val, true)) + return -1; + } else { + /* legacy behavior: must do the conversion twice and compare */ + if (JS_ToUint32(ctx, &len, val)) { + JS_FreeValue(ctx, val); + return -1; + } + val = JS_ToNumberFree(ctx, val); + if (JS_IsException(val)) + return -1; + /* cannot recurse because val is a number */ + if (JS_ToArrayLengthFree(ctx, &len1, val, false)) + return -1; + if (len1 != len) { + fail: + JS_ThrowRangeError(ctx, "invalid array length"); + return -1; + } + } + } + break; + } + *plen = len; + return 0; +} + +#define MAX_SAFE_INTEGER (((int64_t)1 << 53) - 1) + +static bool is_safe_integer(double d) +{ + return isfinite(d) && floor(d) == d && + fabs(d) <= (double)MAX_SAFE_INTEGER; +} + +int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val) +{ + int64_t v; + if (JS_ToInt64Sat(ctx, &v, val)) + return -1; + if (v < 0 || v > MAX_SAFE_INTEGER) { + JS_ThrowRangeError(ctx, "invalid array index"); + *plen = 0; + return -1; + } + *plen = v; + return 0; +} + +/* convert a value to a length between 0 and MAX_SAFE_INTEGER. + return -1 for exception */ +static __exception int JS_ToLengthFree(JSContext *ctx, int64_t *plen, + JSValue val) +{ + int res = JS_ToInt64Clamp(ctx, plen, val, 0, MAX_SAFE_INTEGER, 0); + JS_FreeValue(ctx, val); + return res; +} + +/* Note: can return an exception */ +static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val) +{ + double d; + if (!JS_IsNumber(val)) + return false; + if (unlikely(JS_ToFloat64(ctx, &d, val))) + return -1; + return isfinite(d) && floor(d) == d; +} + +static bool JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val) +{ + uint32_t tag; + + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_INT: + { + int v; + v = JS_VALUE_GET_INT(val); + return (v < 0); + } + case JS_TAG_FLOAT64: + { + JSFloat64Union u; + u.d = JS_VALUE_GET_FLOAT64(val); + return (u.u64 >> 63); + } + case JS_TAG_SHORT_BIG_INT: + return (JS_VALUE_GET_SHORT_BIG_INT(val) < 0); + case JS_TAG_BIG_INT: + { + JSBigInt *p = JS_VALUE_GET_PTR(val); + return js_bigint_sign(p); + } + default: + return false; + } +} + +static JSValue js_bigint_to_string(JSContext *ctx, JSValueConst val) +{ + return js_bigint_to_string1(ctx, val, 10); +} + +/*---- floating point number to string conversions ----*/ + +static JSValue js_dtoa2(JSContext *ctx, + double d, int radix, int n_digits, int flags) +{ + char static_buf[128], *buf, *tmp_buf; + int len, len_max; + JSValue res; + JSDTOATempMem dtoa_mem; + len_max = js_dtoa_max_len(d, radix, n_digits, flags); + + /* longer buffer may be used if radix != 10 */ + if (len_max > sizeof(static_buf) - 1) { + tmp_buf = js_malloc(ctx, len_max + 1); + if (!tmp_buf) + return JS_EXCEPTION; + buf = tmp_buf; + } else { + tmp_buf = NULL; + buf = static_buf; + } + len = js_dtoa(buf, d, radix, n_digits, flags, &dtoa_mem); + res = js_new_string8_len(ctx, buf, len); + js_free(ctx, tmp_buf); + return res; +} + +static JSValue JS_ToStringInternal(JSContext *ctx, JSValueConst val, + int flags) +{ + uint32_t tag; + char buf[32]; + size_t len; + + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_STRING: + return js_dup(val); + case JS_TAG_STRING_ROPE: + return js_linearize_string_rope(ctx, val); + case JS_TAG_INT: + len = i32toa(buf, JS_VALUE_GET_INT(val)); + return js_new_string8_len(ctx, buf, len); + case JS_TAG_BOOL: + return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ? + JS_ATOM_true : JS_ATOM_false); + case JS_TAG_NULL: + return JS_AtomToString(ctx, JS_ATOM_null); + case JS_TAG_UNDEFINED: + return JS_AtomToString(ctx, JS_ATOM_undefined); + case JS_TAG_EXCEPTION: + return JS_EXCEPTION; + case JS_TAG_OBJECT: + if (flags & JS_TO_STRING_NO_SIDE_EFFECTS) { + return js_new_string8(ctx, "{}"); + } else { + JSValue val1, ret; + val1 = JS_ToPrimitive(ctx, val, HINT_STRING); + if (JS_IsException(val1)) + return val1; + ret = JS_ToStringInternal(ctx, val1, flags); + JS_FreeValue(ctx, val1); + return ret; + } + break; + case JS_TAG_FUNCTION_BYTECODE: + return js_new_string8(ctx, "[function bytecode]"); + case JS_TAG_SYMBOL: + if (flags & JS_TO_STRING_IS_PROPERTY_KEY) { + return js_dup(val); + } else { + return JS_ThrowTypeError(ctx, "cannot convert symbol to string"); + } + case JS_TAG_FLOAT64: + return js_dtoa2(ctx, JS_VALUE_GET_FLOAT64(val), 10, 0, + JS_DTOA_FORMAT_FREE); + case JS_TAG_SHORT_BIG_INT: + case JS_TAG_BIG_INT: + return js_bigint_to_string(ctx, val); + case JS_TAG_UNINITIALIZED: + return js_new_string8(ctx, "[uninitialized]"); + default: + return js_new_string8(ctx, "[unsupported type]"); + } +} + +JSValue JS_ToString(JSContext *ctx, JSValueConst val) +{ + return JS_ToStringInternal(ctx, val, /*flags*/0); +} + +static JSValue JS_ToStringFree(JSContext *ctx, JSValue val) +{ + JSValue ret; + ret = JS_ToString(ctx, val); + JS_FreeValue(ctx, val); + return ret; +} + +static JSValue JS_ToLocaleStringFree(JSContext *ctx, JSValue val) +{ + if (JS_IsUndefined(val) || JS_IsNull(val)) + return JS_ToStringFree(ctx, val); + return JS_InvokeFree(ctx, val, JS_ATOM_toLocaleString, 0, NULL); +} + +static JSValue JS_ToPropertyKeyInternal(JSContext *ctx, JSValueConst val, + int flags) +{ + return JS_ToStringInternal(ctx, val, flags | JS_TO_STRING_IS_PROPERTY_KEY); +} + +JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val) +{ + return JS_ToPropertyKeyInternal(ctx, val, /*flags*/0); +} + +static JSValue JS_ToStringCheckObject(JSContext *ctx, JSValueConst val) +{ + uint32_t tag = JS_VALUE_GET_TAG(val); + if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) + return JS_ThrowTypeError(ctx, "null or undefined are forbidden"); + return JS_ToString(ctx, val); +} + +static JSValue JS_ToQuotedString(JSContext *ctx, JSValueConst val1) +{ + JSValue val; + JSString *p; + int i; + uint32_t c; + StringBuffer b_s, *b = &b_s; + char buf[16]; + + val = JS_ToStringCheckObject(ctx, val1); + if (JS_IsException(val)) + return val; + p = JS_VALUE_GET_STRING(val); + + if (string_buffer_init(ctx, b, p->len + 2)) + goto fail; + + if (string_buffer_putc8(b, '\"')) + goto fail; + for(i = 0; i < p->len; ) { + c = string_getc(p, &i); + switch(c) { + case '\t': + c = 't'; + goto quote; + case '\r': + c = 'r'; + goto quote; + case '\n': + c = 'n'; + goto quote; + case '\b': + c = 'b'; + goto quote; + case '\f': + c = 'f'; + goto quote; + case '\"': + case '\\': + quote: + if (string_buffer_putc8(b, '\\')) + goto fail; + if (string_buffer_putc8(b, c)) + goto fail; + break; + default: + if (c < 32 || is_surrogate(c)) { + snprintf(buf, sizeof(buf), "\\u%04x", c); + if (string_buffer_write8(b, (uint8_t*)buf, 6)) + goto fail; + } else { + if (string_buffer_putc(b, c)) + goto fail; + } + break; + } + } + if (string_buffer_putc8(b, '\"')) + goto fail; + JS_FreeValue(ctx, val); + return string_buffer_end(b); + fail: + JS_FreeValue(ctx, val); + string_buffer_free(b); + return JS_EXCEPTION; +} + +static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt) +{ + printf("%14s %4s %4s %14s %10s %s\n", + "ADDRESS", "REFS", "SHRF", "PROTO", "CLASS", "PROPS"); +} + +/* for debug only: dump an object without side effect */ +static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p) +{ + uint32_t i; + char atom_buf[ATOM_GET_STR_BUF_SIZE]; + JSShape *sh; + JSShapeProperty *prs; + JSProperty *pr; + bool is_first = true; + + /* XXX: should encode atoms with special characters */ + sh = p->shape; /* the shape can be NULL while freeing an object */ + printf("%14p %4d ", + (void *)p, + p->header.ref_count); + if (sh) { + printf("%3d%c %14p ", + sh->header.ref_count, + " *"[sh->is_hashed], + (void *)sh->proto); + } else { + printf("%3s %14s ", "-", "-"); + } + printf("%10s ", + JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), rt->class_array[p->class_id].class_name)); + if (p->is_exotic && p->fast_array) { + printf("[ "); + for(i = 0; i < p->u.array.count; i++) { + if (i != 0) + printf(", "); + switch (p->class_id) { + case JS_CLASS_ARRAY: + case JS_CLASS_ARGUMENTS: + JS_DumpValue(rt, p->u.array.u.values[i]); + break; + case JS_CLASS_UINT8C_ARRAY: + case JS_CLASS_INT8_ARRAY: + case JS_CLASS_UINT8_ARRAY: + case JS_CLASS_INT16_ARRAY: + case JS_CLASS_UINT16_ARRAY: + case JS_CLASS_INT32_ARRAY: + case JS_CLASS_UINT32_ARRAY: + case JS_CLASS_BIG_INT64_ARRAY: + case JS_CLASS_BIG_UINT64_ARRAY: + case JS_CLASS_FLOAT16_ARRAY: + case JS_CLASS_FLOAT32_ARRAY: + case JS_CLASS_FLOAT64_ARRAY: + { + int size = 1 << typed_array_size_log2(p->class_id); + const uint8_t *b = p->u.array.u.uint8_ptr + i * size; + while (size-- > 0) + printf("%02X", *b++); + } + break; + } + } + printf(" ] "); + } + + if (sh) { + printf("{ "); + for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { + if (prs->atom != JS_ATOM_NULL) { + pr = &p->prop[i]; + if (!is_first) + printf(", "); + printf("%s: ", + JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), prs->atom)); + if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { + printf("[getset %p %p]", (void *)pr->u.getset.getter, + (void *)pr->u.getset.setter); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { + printf("[varref %p]", (void *)pr->u.var_ref); + } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { + printf("[autoinit %p %d %p]", + (void *)js_autoinit_get_realm(pr), + js_autoinit_get_id(pr), + (void *)pr->u.init.opaque); + } else { + JS_DumpValue(rt, pr->u.value); + } + is_first = false; + } + } + printf(" }"); + } + + if (js_class_has_bytecode(p->class_id)) { + JSFunctionBytecode *b = p->u.func.function_bytecode; + JSVarRef **var_refs; + if (b->closure_var_count) { + var_refs = p->u.func.var_refs; + printf(" Closure:"); + for(i = 0; i < b->closure_var_count; i++) { + printf(" "); + JS_DumpValue(rt, var_refs[i]->value); + } + if (p->u.func.home_object) { + printf(" HomeObject: "); + JS_DumpValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object)); + } + } + } + printf("\n"); +} + +static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p) +{ + if (p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) { + JS_DumpObject(rt, (JSObject *)p); + } else { + printf("%14p %4d ", + (void *)p, + p->ref_count); + switch(p->gc_obj_type) { + case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: + printf("[function bytecode]"); + break; + case JS_GC_OBJ_TYPE_SHAPE: + printf("[shape]"); + break; + case JS_GC_OBJ_TYPE_VAR_REF: + printf("[var_ref]"); + break; + case JS_GC_OBJ_TYPE_ASYNC_FUNCTION: + printf("[async_function]"); + break; + case JS_GC_OBJ_TYPE_JS_CONTEXT: + printf("[js_context]"); + break; + default: + printf("[unknown %d]", p->gc_obj_type); + break; + } + printf("\n"); + } +} + +static __maybe_unused void JS_DumpValue(JSRuntime *rt, JSValueConst val) +{ + uint32_t tag = JS_VALUE_GET_NORM_TAG(val); + const char *str; + + switch(tag) { + case JS_TAG_INT: + printf("%d", JS_VALUE_GET_INT(val)); + break; + case JS_TAG_BOOL: + if (JS_VALUE_GET_BOOL(val)) + str = "true"; + else + str = "false"; + goto print_str; + case JS_TAG_NULL: + str = "null"; + goto print_str; + case JS_TAG_EXCEPTION: + str = "exception"; + goto print_str; + case JS_TAG_UNINITIALIZED: + str = "uninitialized"; + goto print_str; + case JS_TAG_UNDEFINED: + str = "undefined"; + print_str: + printf("%s", str); + break; + case JS_TAG_FLOAT64: + printf("%.14g", JS_VALUE_GET_FLOAT64(val)); + break; + case JS_TAG_SHORT_BIG_INT: + printf("%" PRId64 "n", (int64_t)JS_VALUE_GET_SHORT_BIG_INT(val)); + break; + case JS_TAG_BIG_INT: + { + JSBigInt *p = JS_VALUE_GET_PTR(val); + int sgn, i; + /* In order to avoid allocations we just dump the limbs */ + sgn = js_bigint_sign(p); + if (sgn) + printf("BigInt.asIntN(%d,", p->len * JS_LIMB_BITS); + printf("0x"); + for(i = p->len - 1; i >= 0; i--) { + if (i != p->len - 1) + printf("_"); + printf("%08x", p->tab[i]); + } + printf("n"); + if (sgn) + printf(")"); + } + break; + case JS_TAG_STRING: + { + JSString *p; + p = JS_VALUE_GET_STRING(val); + JS_DumpString(rt, p); + } + break; + case JS_TAG_STRING_ROPE: + { + JSStringRope *r = JS_VALUE_GET_STRING_ROPE(val); + printf("[rope len=%d depth=%d]", r->len, r->depth); + } + break; + case JS_TAG_FUNCTION_BYTECODE: + { + JSFunctionBytecode *b = JS_VALUE_GET_PTR(val); + char buf[ATOM_GET_STR_BUF_SIZE]; + if (b->func_name) { + printf("[bytecode %s]", JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name)); + } else { + printf("[bytecode (anonymous)]"); + } + } + break; + case JS_TAG_OBJECT: + { + JSObject *p = JS_VALUE_GET_OBJ(val); + JSAtom atom = rt->class_array[p->class_id].class_name; + char atom_buf[ATOM_GET_STR_BUF_SIZE]; + printf("[%s %p]", + JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), atom), (void *)p); + } + break; + case JS_TAG_SYMBOL: + { + JSAtomStruct *p = JS_VALUE_GET_PTR(val); + char atom_buf[ATOM_GET_STR_BUF_SIZE]; + printf("Symbol(%s)", + JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), js_get_atom_index(rt, p))); + } + break; + case JS_TAG_MODULE: + printf("[module]"); + break; + default: + printf("[unknown tag %d]", tag); + break; + } +} + +bool JS_IsArray(JSValueConst val) +{ + if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) { + JSObject *p = JS_VALUE_GET_OBJ(val); + return p->class_id == JS_CLASS_ARRAY; + } + return false; +} + +/* return -1 if exception (proxy case) or true/false */ +static int js_is_array(JSContext *ctx, JSValueConst val) +{ + JSObject *p; + if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) { + p = JS_VALUE_GET_OBJ(val); + if (unlikely(p->class_id == JS_CLASS_PROXY)) + return js_proxy_isArray(ctx, val); + else + return p->class_id == JS_CLASS_ARRAY; + } else { + return false; + } +} + +static double js_math_pow(double a, double b) +{ + double d; + + if (unlikely(!isfinite(b)) && fabs(a) == 1) { + /* not compatible with IEEE 754 */ + d = NAN; + } else { + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + d = pow(a, b); + JS_X87_FPCW_RESTORE(fpcw); + } + return d; +} + +JSValue JS_NewBigInt64(JSContext *ctx, int64_t v) +{ + if (v >= JS_SHORT_BIG_INT_MIN && v <= JS_SHORT_BIG_INT_MAX) { + return __JS_NewShortBigInt(ctx, v); + } else { + JSBigInt *p; + p = js_bigint_new_si64(ctx, v); + if (!p) + return JS_EXCEPTION; + return JS_MKPTR(JS_TAG_BIG_INT, p); + } +} + +JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v) +{ + if (v <= JS_SHORT_BIG_INT_MAX) { + return __JS_NewShortBigInt(ctx, v); + } else { + JSBigInt *p; + p = js_bigint_new_ui64(ctx, v); + if (!p) + return JS_EXCEPTION; + return JS_MKPTR(JS_TAG_BIG_INT, p); + } +} + +/* return NaN if bad bigint literal */ +static JSValue JS_StringToBigInt(JSContext *ctx, JSValue val) +{ + const char *str, *p; + size_t len; + int flags; + + str = JS_ToCStringLen(ctx, &len, val); + JS_FreeValue(ctx, val); + if (!str) + return JS_EXCEPTION; + p = str; + p += skip_spaces(p); + if ((p - str) == len) { + val = JS_NewBigInt64(ctx, 0); + } else { + flags = ATOD_INT_ONLY | ATOD_ACCEPT_BIN_OCT | ATOD_TYPE_BIG_INT; + val = js_atof(ctx, p, &p, 0, flags); + p += skip_spaces(p); + if (!JS_IsException(val)) { + if ((p - str) != len) { + JS_FreeValue(ctx, val); + val = JS_NAN; + } + } + } + JS_FreeCString(ctx, str); + return val; +} + +static JSValue JS_StringToBigIntErr(JSContext *ctx, JSValue val) +{ + val = JS_StringToBigInt(ctx, val); + if (JS_VALUE_IS_NAN(val)) + return JS_ThrowSyntaxError(ctx, "invalid BigInt literal"); + return val; +} + +/* JS Numbers are not allowed */ +static JSValue JS_ToBigIntFree(JSContext *ctx, JSValue val) +{ + uint32_t tag; + + redo: + tag = JS_VALUE_GET_NORM_TAG(val); + switch(tag) { + case JS_TAG_SHORT_BIG_INT: + case JS_TAG_BIG_INT: + break; + case JS_TAG_INT: + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + case JS_TAG_FLOAT64: + goto fail; + case JS_TAG_BOOL: + val = __JS_NewShortBigInt(ctx, JS_VALUE_GET_INT(val)); + break; + case JS_TAG_STRING: + case JS_TAG_STRING_ROPE: + val = JS_StringToBigIntErr(ctx, val); + if (JS_IsException(val)) + return val; + goto redo; + case JS_TAG_OBJECT: + val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER); + if (JS_IsException(val)) + return val; + goto redo; + default: + fail: + JS_FreeValue(ctx, val); + return JS_ThrowTypeError(ctx, "cannot convert to bigint"); + } + return val; +} + +static JSValue JS_ToBigInt(JSContext *ctx, JSValueConst val) +{ + return JS_ToBigIntFree(ctx, js_dup(val)); +} + +/* XXX: merge with JS_ToInt64Free with a specific flag */ +static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val) +{ + uint64_t res; + + val = JS_ToBigIntFree(ctx, val); + if (JS_IsException(val)) { + *pres = 0; + return -1; + } + if (JS_VALUE_GET_TAG(val) == JS_TAG_SHORT_BIG_INT) { + res = JS_VALUE_GET_SHORT_BIG_INT(val); + } else { + JSBigInt *p = JS_VALUE_GET_PTR(val); + /* return the value mod 2^64 */ + res = p->tab[0]; + if (p->len >= 2) + res |= (uint64_t)p->tab[1] << 32; + JS_FreeValue(ctx, val); + } + *pres = res; + return 0; +} + +int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val) +{ + return JS_ToBigInt64Free(ctx, pres, js_dup(val)); +} + +int JS_ToBigUint64(JSContext *ctx, uint64_t *pres, JSValueConst val) +{ + return JS_ToBigInt64Free(ctx, (int64_t *)pres, js_dup(val)); +} + +static no_inline __exception int js_unary_arith_slow(JSContext *ctx, + JSValue *sp, + OPCodeEnum op) +{ + JSValue op1; + int v; + uint32_t tag; + JSBigIntBuf buf1; + JSBigInt *p1; + + op1 = sp[-1]; + /* fast path for float64 */ + if (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(op1))) + goto handle_float64; + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) + goto exception; + tag = JS_VALUE_GET_TAG(op1); + switch(tag) { + case JS_TAG_INT: + { + int64_t v64; + v64 = JS_VALUE_GET_INT(op1); + switch(op) { + case OP_inc: + case OP_dec: + v = 2 * (op - OP_dec) - 1; + v64 += v; + break; + case OP_plus: + break; + case OP_neg: + if (v64 == 0) { + sp[-1] = js_float64(-0.0); + return 0; + } else { + v64 = -v64; + } + break; + default: + abort(); + } + sp[-1] = js_int64(v64); + } + break; + case JS_TAG_SHORT_BIG_INT: + { + int64_t v; + v = JS_VALUE_GET_SHORT_BIG_INT(op1); + switch(op) { + case OP_plus: + JS_ThrowTypeError(ctx, "bigint argument with unary +"); + goto exception; + case OP_inc: + if (v == JS_SHORT_BIG_INT_MAX) + goto bigint_slow_case; + sp[-1] = __JS_NewShortBigInt(ctx, v + 1); + break; + case OP_dec: + if (v == JS_SHORT_BIG_INT_MIN) + goto bigint_slow_case; + sp[-1] = __JS_NewShortBigInt(ctx, v - 1); + break; + case OP_neg: + v = JS_VALUE_GET_SHORT_BIG_INT(op1); + if (v == JS_SHORT_BIG_INT_MIN) { + bigint_slow_case: + p1 = js_bigint_set_short(&buf1, op1); + goto bigint_slow_case1; + } + sp[-1] = __JS_NewShortBigInt(ctx, -v); + break; + default: + abort(); + } + } + break; + case JS_TAG_BIG_INT: + { + JSBigInt *r; + p1 = JS_VALUE_GET_PTR(op1); + bigint_slow_case1: + switch(op) { + case OP_plus: + JS_ThrowTypeError(ctx, "bigint argument with unary +"); + JS_FreeValue(ctx, op1); + goto exception; + case OP_inc: + case OP_dec: + { + JSBigIntBuf buf2; + JSBigInt *p2; + p2 = js_bigint_set_si(&buf2, 2 * (op - OP_dec) - 1); + r = js_bigint_add(ctx, p1, p2, 0); + } + break; + case OP_neg: + r = js_bigint_neg(ctx, p1); + break; + case OP_not: + r = js_bigint_not(ctx, p1); + break; + default: + abort(); + } + JS_FreeValue(ctx, op1); + if (!r) + goto exception; + sp[-1] = JS_CompactBigInt(ctx, r); + } + break; + default: + handle_float64: + { + double d; + d = JS_VALUE_GET_FLOAT64(op1); + switch(op) { + case OP_inc: + case OP_dec: + v = 2 * (op - OP_dec) - 1; + d += v; + break; + case OP_plus: + break; + case OP_neg: + d = -d; + break; + default: + abort(); + } + sp[-1] = js_float64(d); + } + break; + } + return 0; + exception: + sp[-1] = JS_UNDEFINED; + return -1; +} + +static __exception int js_post_inc_slow(JSContext *ctx, + JSValue *sp, OPCodeEnum op) +{ + JSValue op1; + + /* XXX: allow custom operators */ + op1 = sp[-1]; + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + sp[-1] = JS_UNDEFINED; + return -1; + } + sp[-1] = op1; + sp[0] = js_dup(op1); + return js_unary_arith_slow(ctx, sp + 1, op - OP_post_dec + OP_dec); +} + +static no_inline int js_not_slow(JSContext *ctx, JSValue *sp) +{ + JSValue op1; + + op1 = sp[-1]; + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) + goto exception; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) { + sp[-1] = __JS_NewShortBigInt(ctx, ~JS_VALUE_GET_SHORT_BIG_INT(op1)); + } else if (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT) { + JSBigInt *r; + r = js_bigint_not(ctx, JS_VALUE_GET_PTR(op1)); + JS_FreeValue(ctx, op1); + if (!r) + goto exception; + sp[-1] = JS_CompactBigInt(ctx, r); + } else { + int32_t v1; + if (unlikely(JS_ToInt32Free(ctx, &v1, op1))) + goto exception; + sp[-1] = js_int32(~v1); + } + return 0; + exception: + sp[-1] = JS_UNDEFINED; + return -1; +} + +static no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp, + OPCodeEnum op) +{ + JSValue op1, op2; + uint32_t tag1, tag2; + double d1, d2; + + op1 = sp[-2]; + op2 = sp[-1]; + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + /* fast path for float operations */ + if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) { + d1 = JS_VALUE_GET_FLOAT64(op1); + d2 = JS_VALUE_GET_FLOAT64(op2); + goto handle_float64; + } + /* fast path for short big int operations */ + if (tag1 == JS_TAG_SHORT_BIG_INT && tag2 == JS_TAG_SHORT_BIG_INT) { + js_slimb_t v1, v2; + js_sdlimb_t v; + v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); + v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); + switch(op) { + case OP_sub: + v = (js_sdlimb_t)v1 - (js_sdlimb_t)v2; + break; + case OP_mul: + v = (js_sdlimb_t)v1 * (js_sdlimb_t)v2; + break; + case OP_div: + if (v2 == 0 || + ((js_limb_t)v1 == (js_limb_t)1 << (JS_LIMB_BITS - 1) && + v2 == -1)) { + goto slow_big_int; + } + sp[-2] = __JS_NewShortBigInt(ctx, v1 / v2); + return 0; + case OP_mod: + if (v2 == 0 || + ((js_limb_t)v1 == (js_limb_t)1 << (JS_LIMB_BITS - 1) && + v2 == -1)) { + goto slow_big_int; + } + sp[-2] = __JS_NewShortBigInt(ctx, v1 % v2); + return 0; + case OP_pow: + goto slow_big_int; + default: + abort(); + } + if (likely(v >= JS_SHORT_BIG_INT_MIN && v <= JS_SHORT_BIG_INT_MAX)) { + sp[-2] = __JS_NewShortBigInt(ctx, v); + } else { + JSBigInt *r = js_bigint_new_di(ctx, v); + if (!r) + goto exception; + sp[-2] = JS_MKPTR(JS_TAG_BIG_INT, r); + } + return 0; + } + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToNumericFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + + if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) { + int32_t v1, v2; + int64_t v; + v1 = JS_VALUE_GET_INT(op1); + v2 = JS_VALUE_GET_INT(op2); + switch(op) { + case OP_sub: + v = (int64_t)v1 - (int64_t)v2; + break; + case OP_mul: + v = (int64_t)v1 * (int64_t)v2; + if (v == 0 && (v1 | v2) < 0) { + sp[-2] = js_float64(-0.0); + return 0; + } + break; + case OP_div: + { + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + sp[-2] = js_number((double)v1 / (double)v2); + JS_X87_FPCW_RESTORE(fpcw); + } + return 0; + case OP_mod: + if (v1 < 0 || v2 <= 0) { + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + sp[-2] = js_number(fmod(v1, v2)); + JS_X87_FPCW_RESTORE(fpcw); + return 0; + } else { + v = (int64_t)v1 % (int64_t)v2; + } + break; + case OP_pow: + sp[-2] = js_number(js_math_pow(v1, v2)); + return 0; + default: + abort(); + } + sp[-2] = js_int64(v); + } else if ((tag1 == JS_TAG_SHORT_BIG_INT || tag1 == JS_TAG_BIG_INT) && + (tag2 == JS_TAG_SHORT_BIG_INT || tag2 == JS_TAG_BIG_INT)) { + JSBigInt *p1, *p2, *r; + JSBigIntBuf buf1, buf2; + slow_big_int: + /* bigint result */ + if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) + p1 = js_bigint_set_short(&buf1, op1); + else + p1 = JS_VALUE_GET_PTR(op1); + if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) + p2 = js_bigint_set_short(&buf2, op2); + else + p2 = JS_VALUE_GET_PTR(op2); + switch(op) { + case OP_add: + r = js_bigint_add(ctx, p1, p2, 0); + break; + case OP_sub: + r = js_bigint_add(ctx, p1, p2, 1); + break; + case OP_mul: + r = js_bigint_mul(ctx, p1, p2); + break; + case OP_div: + r = js_bigint_divrem(ctx, p1, p2, false); + break; + case OP_mod: + r = js_bigint_divrem(ctx, p1, p2, true); + break; + case OP_pow: + r = js_bigint_pow(ctx, p1, p2); + break; + default: + abort(); + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + if (!r) + goto exception; + sp[-2] = JS_CompactBigInt(ctx, r); + } else { + double dr; + /* float64 result */ + if (JS_ToFloat64Free(ctx, &d1, op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + if (JS_ToFloat64Free(ctx, &d2, op2)) + goto exception; + handle_float64: + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + switch(op) { + case OP_sub: + dr = d1 - d2; + break; + case OP_mul: + dr = d1 * d2; + break; + case OP_div: + dr = d1 / d2; + break; + case OP_mod: + dr = fmod(d1, d2); + break; + case OP_pow: + dr = js_math_pow(d1, d2); + break; + default: + abort(); + } + JS_X87_FPCW_RESTORE(fpcw); + sp[-2] = js_float64(dr); + } + return 0; + exception: + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +static no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp) +{ + JSValue op1, op2; + uint32_t tag1, tag2; + + op1 = sp[-2]; + op2 = sp[-1]; + + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + /* fast path for float64 */ + if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) { + double d1, d2; + d1 = JS_VALUE_GET_FLOAT64(op1); + d2 = JS_VALUE_GET_FLOAT64(op2); + sp[-2] = js_float64(d1 + d2); + return 0; + } + /* fast path for short bigint */ + if (tag1 == JS_TAG_SHORT_BIG_INT && tag2 == JS_TAG_SHORT_BIG_INT) { + js_slimb_t v1, v2; + js_sdlimb_t v; + v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); + v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); + v = (js_sdlimb_t)v1 + (js_sdlimb_t)v2; + if (likely(v >= JS_SHORT_BIG_INT_MIN && v <= JS_SHORT_BIG_INT_MAX)) { + sp[-2] = __JS_NewShortBigInt(ctx, v); + } else { + JSBigInt *r = js_bigint_new_di(ctx, v); + if (!r) + goto exception; + sp[-2] = JS_MKPTR(JS_TAG_BIG_INT, r); + } + return 0; + } + + if (tag1 == JS_TAG_OBJECT || tag2 == JS_TAG_OBJECT) { + op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + + op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + } + + if (tag_is_string(tag1) || tag_is_string(tag2)) { + sp[-2] = JS_ConcatString(ctx, op1, op2); + if (JS_IsException(sp[-2])) + goto exception; + return 0; + } + + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToNumericFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + + if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) { + int32_t v1, v2; + int64_t v; + v1 = JS_VALUE_GET_INT(op1); + v2 = JS_VALUE_GET_INT(op2); + v = (int64_t)v1 + (int64_t)v2; + sp[-2] = js_int64(v); + } else if ((tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT) && + (tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT)) { + JSBigInt *p1, *p2, *r; + JSBigIntBuf buf1, buf2; + /* bigint result */ + if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) + p1 = js_bigint_set_short(&buf1, op1); + else + p1 = JS_VALUE_GET_PTR(op1); + if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) + p2 = js_bigint_set_short(&buf2, op2); + else + p2 = JS_VALUE_GET_PTR(op2); + r = js_bigint_add(ctx, p1, p2, 0); + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + if (!r) + goto exception; + sp[-2] = JS_CompactBigInt(ctx, r); + } else { + double d1, d2; + /* float64 result */ + if (JS_ToFloat64Free(ctx, &d1, op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + if (JS_ToFloat64Free(ctx, &d2, op2)) + goto exception; + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + sp[-2] = js_float64(d1 + d2); + JS_X87_FPCW_RESTORE(fpcw); + } + return 0; + exception: + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +static no_inline __exception int js_binary_logic_slow(JSContext *ctx, + JSValue *sp, + OPCodeEnum op) +{ + JSValue op1, op2; + uint32_t tag1, tag2; + uint32_t v1, v2, r; + + op1 = sp[-2]; + op2 = sp[-1]; + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + + if (tag1 == JS_TAG_SHORT_BIG_INT && tag2 == JS_TAG_SHORT_BIG_INT) { + js_slimb_t v1, v2, v; + js_sdlimb_t vd; + v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); + v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); + /* bigint fast path */ + switch(op) { + case OP_and: + v = v1 & v2; + break; + case OP_or: + v = v1 | v2; + break; + case OP_xor: + v = v1 ^ v2; + break; + case OP_sar: + if (v2 > (JS_LIMB_BITS - 1)) { + goto slow_big_int; + } else if (v2 < 0) { + if (v2 < -(JS_LIMB_BITS - 1)) + goto slow_big_int; + v2 = -v2; + goto bigint_shl; + } + bigint_sar: + v = v1 >> v2; + break; + case OP_shl: + if (v2 > (JS_LIMB_BITS - 1)) { + goto slow_big_int; + } else if (v2 < 0) { + if (v2 < -(JS_LIMB_BITS - 1)) + goto slow_big_int; + v2 = -v2; + goto bigint_sar; + } + bigint_shl: + vd = (js_dlimb_t)v1 << v2; + if (likely(vd >= JS_SHORT_BIG_INT_MIN && + vd <= JS_SHORT_BIG_INT_MAX)) { + v = vd; + } else { + JSBigInt *r = js_bigint_new_di(ctx, vd); + if (!r) + goto exception; + sp[-2] = JS_MKPTR(JS_TAG_BIG_INT, r); + return 0; + } + break; + default: + abort(); + } + sp[-2] = __JS_NewShortBigInt(ctx, v); + return 0; + } + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToNumericFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + + tag1 = JS_VALUE_GET_TAG(op1); + tag2 = JS_VALUE_GET_TAG(op2); + if ((tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT) && + (tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT)) { + JSBigInt *p1, *p2, *r; + JSBigIntBuf buf1, buf2; + slow_big_int: + if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) + p1 = js_bigint_set_short(&buf1, op1); + else + p1 = JS_VALUE_GET_PTR(op1); + if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) + p2 = js_bigint_set_short(&buf2, op2); + else + p2 = JS_VALUE_GET_PTR(op2); + switch(op) { + case OP_and: + case OP_or: + case OP_xor: + r = js_bigint_logic(ctx, p1, p2, op); + break; + case OP_shl: + case OP_sar: + { + js_slimb_t shift; + shift = js_bigint_get_si_sat(p2); + if (shift > INT32_MAX) + shift = INT32_MAX; + else if (shift < -INT32_MAX) + shift = -INT32_MAX; + if (op == OP_sar) + shift = -shift; + if (shift >= 0) + r = js_bigint_shl(ctx, p1, shift); + else + r = js_bigint_shr(ctx, p1, -shift); + } + break; + default: + abort(); + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + if (!r) + goto exception; + sp[-2] = JS_CompactBigInt(ctx, r); + } else { + if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) { + JS_FreeValue(ctx, op2); + goto exception; + } + if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2))) + goto exception; + switch(op) { + case OP_shl: + r = v1 << (v2 & 0x1f); + break; + case OP_sar: + r = (int)v1 >> (v2 & 0x1f); + break; + case OP_and: + r = v1 & v2; + break; + case OP_or: + r = v1 | v2; + break; + case OP_xor: + r = v1 ^ v2; + break; + default: + abort(); + } + sp[-2] = js_int32(r); + } + return 0; + exception: + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +/* op1 must be a bigint or int. */ +static JSBigInt *JS_ToBigIntBuf(JSContext *ctx, JSBigIntBuf *buf1, + JSValue op1) +{ + JSBigInt *p1; + + switch(JS_VALUE_GET_TAG(op1)) { + case JS_TAG_INT: + p1 = js_bigint_set_si(buf1, JS_VALUE_GET_INT(op1)); + break; + case JS_TAG_SHORT_BIG_INT: + p1 = js_bigint_set_short(buf1, op1); + break; + case JS_TAG_BIG_INT: + p1 = JS_VALUE_GET_PTR(op1); + break; + default: + abort(); + } + return p1; +} + +/* op1 and op2 must be numeric types and at least one must be a + bigint. No exception is generated. */ +static int js_compare_bigint(JSContext *ctx, OPCodeEnum op, + JSValue op1, JSValue op2) +{ + int res, val, tag1, tag2; + JSBigIntBuf buf1, buf2; + JSBigInt *p1, *p2; + + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + if ((tag1 == JS_TAG_SHORT_BIG_INT || tag1 == JS_TAG_INT) && + (tag2 == JS_TAG_SHORT_BIG_INT || tag2 == JS_TAG_INT)) { + /* fast path */ + js_slimb_t v1, v2; + if (tag1 == JS_TAG_INT) + v1 = JS_VALUE_GET_INT(op1); + else + v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); + if (tag2 == JS_TAG_INT) + v2 = JS_VALUE_GET_INT(op2); + else + v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); + val = (v1 > v2) - (v1 < v2); + } else { + if (tag1 == JS_TAG_FLOAT64) { + p2 = JS_ToBigIntBuf(ctx, &buf2, op2); + val = js_bigint_float64_cmp(ctx, p2, JS_VALUE_GET_FLOAT64(op1)); + if (val == 2) + goto unordered; + val = -val; + } else if (tag2 == JS_TAG_FLOAT64) { + p1 = JS_ToBigIntBuf(ctx, &buf1, op1); + val = js_bigint_float64_cmp(ctx, p1, JS_VALUE_GET_FLOAT64(op2)); + if (val == 2) { + unordered: + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + return false; + } + } else { + p1 = JS_ToBigIntBuf(ctx, &buf1, op1); + p2 = JS_ToBigIntBuf(ctx, &buf2, op2); + val = js_bigint_cmp(ctx, p1, p2); + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + } + + switch(op) { + case OP_lt: + res = val < 0; + break; + case OP_lte: + res = val <= 0; + break; + case OP_gt: + res = val > 0; + break; + case OP_gte: + res = val >= 0; + break; + case OP_eq: + res = val == 0; + break; + default: + abort(); + } + return res; +} + +static no_inline int js_relational_slow(JSContext *ctx, JSValue *sp, + OPCodeEnum op) +{ + JSValue op1, op2; + int res; + uint32_t tag1, tag2; + + op1 = sp[-2]; + op2 = sp[-1]; + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + + op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + + if (tag_is_string(tag1) && tag_is_string(tag2)) { + if (tag1 == JS_TAG_STRING && tag2 == JS_TAG_STRING) { + res = js_string_compare(JS_VALUE_GET_STRING(op1), + JS_VALUE_GET_STRING(op2)); + } else { + res = js_string_rope_compare(op1, op2, false); + } + switch(op) { + case OP_lt: + res = (res < 0); + break; + case OP_lte: + res = (res <= 0); + break; + case OP_gt: + res = (res > 0); + break; + default: + case OP_gte: + res = (res >= 0); + break; + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + } else if ((tag1 <= JS_TAG_NULL || tag1 == JS_TAG_FLOAT64) && + (tag2 <= JS_TAG_NULL || tag2 == JS_TAG_FLOAT64)) { + /* fast path for float64/int */ + goto float64_compare; + } else { + if ((((tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT) && + tag2 == JS_TAG_STRING) || + ((tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT) && + tag1 == JS_TAG_STRING))) { + if (tag1 == JS_TAG_STRING) { + op1 = JS_StringToBigInt(ctx, op1); + if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT && + JS_VALUE_GET_TAG(op1) != JS_TAG_SHORT_BIG_INT) + goto invalid_bigint_string; + } + if (tag2 == JS_TAG_STRING) { + op2 = JS_StringToBigInt(ctx, op2); + if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT && + JS_VALUE_GET_TAG(op2) != JS_TAG_SHORT_BIG_INT) { + invalid_bigint_string: + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + res = false; + goto done; + } + } + } else { + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToNumericFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + } + + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + + if (tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT || + tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT) { + res = js_compare_bigint(ctx, op, op1, op2); + } else { + double d1, d2; + + float64_compare: + /* can use floating point comparison */ + if (tag1 == JS_TAG_FLOAT64) { + d1 = JS_VALUE_GET_FLOAT64(op1); + } else { + d1 = JS_VALUE_GET_INT(op1); + } + if (tag2 == JS_TAG_FLOAT64) { + d2 = JS_VALUE_GET_FLOAT64(op2); + } else { + d2 = JS_VALUE_GET_INT(op2); + } + switch(op) { + case OP_lt: + res = (d1 < d2); /* if NaN return false */ + break; + case OP_lte: + res = (d1 <= d2); /* if NaN return false */ + break; + case OP_gt: + res = (d1 > d2); /* if NaN return false */ + break; + default: + case OP_gte: + res = (d1 >= d2); /* if NaN return false */ + break; + } + } + } + done: + sp[-2] = js_bool(res); + return 0; + exception: + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +static bool tag_is_number(uint32_t tag) +{ + return (tag == JS_TAG_INT || + tag == JS_TAG_FLOAT64 || + tag == JS_TAG_BIG_INT || tag == JS_TAG_SHORT_BIG_INT); +} + +static no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp, + bool is_neq) +{ + JSValue op1, op2; + int res; + uint32_t tag1, tag2; + + op1 = sp[-2]; + op2 = sp[-1]; + redo: + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + if (tag_is_number(tag1) && tag_is_number(tag2)) { + if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) { + res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2); + } else if ((tag1 == JS_TAG_FLOAT64 && + (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64)) || + (tag2 == JS_TAG_FLOAT64 && + (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64))) { + double d1, d2; + if (tag1 == JS_TAG_FLOAT64) { + d1 = JS_VALUE_GET_FLOAT64(op1); + } else { + d1 = JS_VALUE_GET_INT(op1); + } + if (tag2 == JS_TAG_FLOAT64) { + d2 = JS_VALUE_GET_FLOAT64(op2); + } else { + d2 = JS_VALUE_GET_INT(op2); + } + res = (d1 == d2); + } else { + res = js_compare_bigint(ctx, OP_eq, op1, op2); + if (res < 0) + goto exception; + } + } else if (tag1 == tag2) { + res = js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT); + } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) || + (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) { + res = true; + } else if ((tag_is_string(tag1) && tag_is_number(tag2)) || + (tag_is_string(tag2) && tag_is_number(tag1))) { + + if (tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT || + tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT) { + if (tag_is_string(tag1)) { + op1 = JS_StringToBigInt(ctx, op1); + if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT && + JS_VALUE_GET_TAG(op1) != JS_TAG_SHORT_BIG_INT) + goto invalid_bigint_string; + } + if (tag_is_string(tag2)) { + op2 = JS_StringToBigInt(ctx, op2); + if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT && + JS_VALUE_GET_TAG(op2) != JS_TAG_SHORT_BIG_INT ) { + invalid_bigint_string: + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + res = false; + goto done; + } + } + } else { + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToNumericFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + } + res = js_strict_eq(ctx, op1, op2); + } else if (tag1 == JS_TAG_BOOL) { + op1 = js_int32(JS_VALUE_GET_INT(op1)); + goto redo; + } else if (tag2 == JS_TAG_BOOL) { + op2 = js_int32(JS_VALUE_GET_INT(op2)); + goto redo; + } else if ((tag1 == JS_TAG_OBJECT && + (tag_is_number(tag2) || tag_is_string(tag2) || tag2 == JS_TAG_SYMBOL)) || + (tag2 == JS_TAG_OBJECT && + (tag_is_number(tag1) || tag_is_string(tag1) || tag1 == JS_TAG_SYMBOL))) { + op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + goto redo; + } else { + /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */ + if ((JS_IsHTMLDDA(ctx, op1) && + (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) || + (JS_IsHTMLDDA(ctx, op2) && + (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) { + res = true; + } else { + res = false; + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + } + done: + sp[-2] = js_bool(res ^ is_neq); + return 0; + exception: + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +static no_inline int js_shr_slow(JSContext *ctx, JSValue *sp) +{ + JSValue op1, op2; + uint32_t v1, v2, r; + + op1 = sp[-2]; + op2 = sp[-1]; + op1 = JS_ToNumericFree(ctx, op1); + if (JS_IsException(op1)) { + JS_FreeValue(ctx, op2); + goto exception; + } + op2 = JS_ToNumericFree(ctx, op2); + if (JS_IsException(op2)) { + JS_FreeValue(ctx, op1); + goto exception; + } + + if (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT || + JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT || + JS_VALUE_GET_TAG(op2) == JS_TAG_BIG_INT || + JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) { + JS_ThrowTypeError(ctx, "BigInt operands are forbidden for >>>"); + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + goto exception; + } + /* cannot give an exception */ + JS_ToUint32Free(ctx, &v1, op1); + JS_ToUint32Free(ctx, &v2, op2); + r = v1 >> (v2 & 0x1f); + sp[-2] = js_uint32(r); + return 0; + exception: + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +static bool js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2, + JSStrictEqModeEnum eq_mode) +{ + bool res; + int tag1, tag2; + double d1, d2; + + tag1 = JS_VALUE_GET_NORM_TAG(op1); + tag2 = JS_VALUE_GET_NORM_TAG(op2); + switch(tag1) { + case JS_TAG_BOOL: + if (tag1 != tag2) { + res = false; + } else { + res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2); + goto done_no_free; + } + break; + case JS_TAG_NULL: + case JS_TAG_UNDEFINED: + res = (tag1 == tag2); + break; + case JS_TAG_STRING: + case JS_TAG_STRING_ROPE: + { + if (!tag_is_string(tag2)) { + res = false; + } else if (tag1 == JS_TAG_STRING && tag2 == JS_TAG_STRING) { + res = js_string_eq(JS_VALUE_GET_STRING(op1), + JS_VALUE_GET_STRING(op2)); + } else { + res = (js_string_rope_compare(op1, op2, true) == 0); + } + } + break; + case JS_TAG_SYMBOL: + { + JSAtomStruct *p1, *p2; + if (tag1 != tag2) { + res = false; + } else { + p1 = JS_VALUE_GET_PTR(op1); + p2 = JS_VALUE_GET_PTR(op2); + res = (p1 == p2); + } + } + break; + case JS_TAG_OBJECT: + if (tag1 != tag2) + res = false; + else + res = JS_VALUE_GET_OBJ(op1) == JS_VALUE_GET_OBJ(op2); + break; + case JS_TAG_INT: + d1 = JS_VALUE_GET_INT(op1); + if (tag2 == JS_TAG_INT) { + d2 = JS_VALUE_GET_INT(op2); + goto number_test; + } else if (tag2 == JS_TAG_FLOAT64) { + d2 = JS_VALUE_GET_FLOAT64(op2); + goto number_test; + } else { + res = false; + } + break; + case JS_TAG_FLOAT64: + d1 = JS_VALUE_GET_FLOAT64(op1); + if (tag2 == JS_TAG_FLOAT64) { + d2 = JS_VALUE_GET_FLOAT64(op2); + } else if (tag2 == JS_TAG_INT) { + d2 = JS_VALUE_GET_INT(op2); + } else { + res = false; + break; + } + number_test: + if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) { + JSFloat64Union u1, u2; + /* NaN is not always normalized, so this test is necessary */ + if (isnan(d1) || isnan(d2)) { + res = isnan(d1) == isnan(d2); + } else if (eq_mode == JS_EQ_SAME_VALUE_ZERO) { + res = (d1 == d2); /* +0 == -0 */ + } else { + u1.d = d1; + u2.d = d2; + res = (u1.u64 == u2.u64); /* +0 != -0 */ + } + } else { + res = (d1 == d2); /* if NaN return false and +0 == -0 */ + } + goto done_no_free; + case JS_TAG_SHORT_BIG_INT: + case JS_TAG_BIG_INT: + { + JSBigIntBuf buf1, buf2; + JSBigInt *p1, *p2; + + if (tag2 != JS_TAG_SHORT_BIG_INT && + tag2 != JS_TAG_BIG_INT) { + res = false; + break; + } + + if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) + p1 = js_bigint_set_short(&buf1, op1); + else + p1 = JS_VALUE_GET_PTR(op1); + if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) + p2 = js_bigint_set_short(&buf2, op2); + else + p2 = JS_VALUE_GET_PTR(op2); + res = (js_bigint_cmp(ctx, p1, p2) == 0); + } + break; + default: + res = false; + break; + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + done_no_free: + return res; +} + +static bool js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2) +{ + return js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT); +} + +static bool js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2) +{ + return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_SAME_VALUE); +} + +static bool js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2) +{ + return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_SAME_VALUE_ZERO); +} + +static no_inline int js_strict_eq_slow(JSContext *ctx, JSValue *sp, + bool is_neq) +{ + bool res; + res = js_strict_eq(ctx, sp[-2], sp[-1]); + sp[-2] = js_bool(res ^ is_neq); + return 0; +} + +static __exception int js_operator_in(JSContext *ctx, JSValue *sp) +{ + JSValue op1, op2; + JSAtom atom; + int ret; + + op1 = sp[-2]; + op2 = sp[-1]; + + if (JS_VALUE_GET_TAG(op2) != JS_TAG_OBJECT) { + JS_ThrowTypeError(ctx, "invalid 'in' operand"); + return -1; + } + atom = JS_ValueToAtom(ctx, op1); + if (unlikely(atom == JS_ATOM_NULL)) + return -1; + ret = JS_HasProperty(ctx, op2, atom); + JS_FreeAtom(ctx, atom); + if (ret < 0) + return -1; + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + sp[-2] = js_bool(ret); + return 0; +} + +static __exception int js_operator_private_in(JSContext *ctx, JSValue *sp) +{ + JSValue op1, op2; + int ret; + op1 = sp[-2]; /* object */ + op2 = sp[-1]; /* field name or method function */ + if (JS_VALUE_GET_TAG(op1) != JS_TAG_OBJECT) { + JS_ThrowTypeError(ctx, "invalid 'in' operand"); + return -1; + } + if (JS_IsObject(op2)) { + /* method: use the brand */ + ret = JS_CheckBrand(ctx, op1, op2); + if (ret < 0) + return -1; + } else { + JSAtom atom; + JSObject *p; + JSShapeProperty *prs; + JSProperty *pr; + /* field */ + atom = JS_ValueToAtom(ctx, op2); + if (unlikely(atom == JS_ATOM_NULL)) + return -1; + p = JS_VALUE_GET_OBJ(op1); + prs = find_own_property(&pr, p, atom); + JS_FreeAtom(ctx, atom); + ret = (prs != NULL); + } + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + sp[-2] = js_bool(ret); + return 0; +} + +static __exception int js_has_unscopable(JSContext *ctx, JSValue obj, + JSAtom atom) +{ + JSValue arr, val; + int ret; + + arr = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_unscopables); + if (JS_IsException(arr)) + return -1; + ret = 0; + if (JS_IsObject(arr)) { + val = JS_GetProperty(ctx, arr, atom); + ret = JS_ToBoolFree(ctx, val); + } + JS_FreeValue(ctx, arr); + return ret; +} + +static __exception int js_operator_instanceof(JSContext *ctx, JSValue *sp) +{ + JSValue op1, op2; + int ret; + + op1 = sp[-2]; + op2 = sp[-1]; + ret = JS_IsInstanceOf(ctx, op1, op2); + if (ret < 0) + return ret; + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + sp[-2] = js_bool(ret); + return 0; +} + +static __exception int js_operator_typeof(JSContext *ctx, JSValue op1) +{ + JSAtom atom; + uint32_t tag; + + tag = JS_VALUE_GET_NORM_TAG(op1); + switch(tag) { + case JS_TAG_SHORT_BIG_INT: + case JS_TAG_BIG_INT: + atom = JS_ATOM_bigint; + break; + case JS_TAG_INT: + case JS_TAG_FLOAT64: + atom = JS_ATOM_number; + break; + case JS_TAG_UNDEFINED: + atom = JS_ATOM_undefined; + break; + case JS_TAG_BOOL: + atom = JS_ATOM_boolean; + break; + case JS_TAG_STRING: + case JS_TAG_STRING_ROPE: + atom = JS_ATOM_string; + break; + case JS_TAG_OBJECT: + { + JSObject *p; + p = JS_VALUE_GET_OBJ(op1); + if (unlikely(p->is_HTMLDDA)) + atom = JS_ATOM_undefined; + else if (JS_IsFunction(ctx, op1)) + atom = JS_ATOM_function; + else + goto obj_type; + } + break; + case JS_TAG_NULL: + obj_type: + atom = JS_ATOM_object; + break; + case JS_TAG_SYMBOL: + atom = JS_ATOM_symbol; + break; + default: + atom = JS_ATOM_unknown; + break; + } + return atom; +} + +static __exception int js_operator_delete(JSContext *ctx, JSValue *sp) +{ + JSValue op1, op2; + JSAtom atom; + int ret; + + op1 = sp[-2]; + op2 = sp[-1]; + atom = JS_ValueToAtom(ctx, op2); + if (unlikely(atom == JS_ATOM_NULL)) + return -1; + ret = JS_DeleteProperty(ctx, op1, atom, JS_PROP_THROW_STRICT); + JS_FreeAtom(ctx, atom); + if (unlikely(ret < 0)) + return -1; + JS_FreeValue(ctx, op1); + JS_FreeValue(ctx, op2); + sp[-2] = js_bool(ret); + return 0; +} + +static JSValue js_throw_type_error(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) +{ + JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val); + if (!b || b->is_strict_mode || !b->has_prototype) { + return JS_ThrowTypeError(ctx, "invalid property access"); + } + return JS_UNDEFINED; +} + +static JSValue js_function_proto_fileName(JSContext *ctx, + JSValueConst this_val) +{ + JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val); + if (b) { + return JS_AtomToString(ctx, b->filename); + } + return JS_UNDEFINED; +} + +static JSValue js_function_proto_int32(JSContext *ctx, + JSValueConst this_val, + int magic) +{ + JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val); + if (b) { + int *field = (int *) ((char *)b + magic); + return js_int32(*field); + } + return JS_UNDEFINED; +} + +static int js_arguments_define_own_property(JSContext *ctx, + JSValueConst this_obj, + JSAtom prop, JSValueConst val, + JSValueConst getter, + JSValueConst setter, int flags) +{ + JSObject *p; + uint32_t idx; + p = JS_VALUE_GET_OBJ(this_obj); + /* convert to normal array when redefining an existing numeric field */ + if (p->fast_array && JS_AtomIsArrayIndex(ctx, &idx, prop) && + idx < p->u.array.count) { + if (convert_fast_array_to_array(ctx, p)) + return -1; + } + /* run the default define own property */ + return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter, + flags | JS_PROP_NO_EXOTIC); +} + +static const JSClassExoticMethods js_arguments_exotic_methods = { + .define_own_property = js_arguments_define_own_property, +}; + +static JSValue js_build_arguments(JSContext *ctx, int argc, JSValueConst *argv) +{ + JSValue val, *tab; + JSProperty props[3]; + JSObject *p; + int i; + + props[0].u.value = js_int32(argc); /* length */ + props[1].u.value = js_dup(ctx->array_proto_values); /* Symbol.iterator */ + props[2].u.getset.getter = JS_VALUE_GET_OBJ(js_dup(ctx->throw_type_error)); /* callee */ + props[2].u.getset.setter = JS_VALUE_GET_OBJ(js_dup(ctx->throw_type_error)); /* callee */ + + val = JS_NewObjectFromShape(ctx, js_dup_shape(ctx->arguments_shape), + JS_CLASS_ARGUMENTS, props); + if (JS_IsException(val)) + return val; + p = JS_VALUE_GET_OBJ(val); + + /* initialize the fast array part */ + tab = NULL; + if (argc > 0) { + tab = js_malloc(ctx, sizeof(tab[0]) * argc); + if (!tab) + goto fail; + for(i = 0; i < argc; i++) { + tab[i] = js_dup(argv[i]); + } + } + p->u.array.u.values = tab; + p->u.array.count = argc; + + return val; + fail: + JS_FreeValue(ctx, val); + return JS_EXCEPTION; +} + +#define GLOBAL_VAR_OFFSET 0x40000000 +#define ARGUMENT_VAR_OFFSET 0x20000000 + +static void js_mapped_arguments_finalizer(JSRuntime *rt, JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + if (p->fast_array) { + JSVarRef **var_refs = p->u.array.u.var_refs; + int i; + if (var_refs) { + for(i = 0; i < p->u.array.count; i++) { + if (var_refs[i]) + free_var_ref(rt, var_refs[i]); + } + js_free_rt(rt, var_refs); + } + } +} + +static void js_mapped_arguments_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + if (p->fast_array) { + JSVarRef **var_refs = p->u.array.u.var_refs; + int i; + if (var_refs) { + for(i = 0; i < p->u.array.count; i++) { + if (var_refs[i]) + mark_func(rt, &var_refs[i]->header); + } + } + } +} + +/* legacy arguments object: add references to the function arguments */ +static JSValue js_build_mapped_arguments(JSContext *ctx, int argc, + JSValueConst *argv, + JSStackFrame *sf, int arg_count) +{ + JSValue val; + JSProperty props[3]; + JSVarRef **tab, *var_ref; + JSObject *p; + int i, j; + + props[0].u.value = js_int32(argc); /* length */ + props[1].u.value = js_dup(ctx->array_proto_values); /* Symbol.iterator */ + props[2].u.value = js_dup(ctx->rt->current_stack_frame->cur_func); /* callee */ + + val = JS_NewObjectFromShape(ctx, js_dup_shape(ctx->mapped_arguments_shape), + JS_CLASS_MAPPED_ARGUMENTS, props); + if (JS_IsException(val)) + return val; + p = JS_VALUE_GET_OBJ(val); + + /* initialize the fast array part */ + tab = NULL; + if (argc > 0) { + tab = js_malloc(ctx, sizeof(tab[0]) * argc); + if (!tab) + goto fail; + for(i = 0; i < arg_count; i++) { + var_ref = get_var_ref(ctx, sf, i, true); + if (!var_ref) + goto fail1; + tab[i] = var_ref; + } + for(i = arg_count; i < argc; i++) { + var_ref = js_create_var_ref(ctx, true); + if (!var_ref) { + fail1: + for(j = 0; j < i; j++) + free_var_ref(ctx->rt, tab[j]); + js_free(ctx, tab); + goto fail; + } + var_ref->value = js_dup(argv[i]); + tab[i] = var_ref; + } + } + p->u.array.u.var_refs = tab; + p->u.array.count = argc; + return val; + fail: + JS_FreeValue(ctx, val); + return JS_EXCEPTION; +} + +static JSValue build_for_in_iterator(JSContext *ctx, JSValue obj) +{ + JSObject *p; + JSPropertyEnum *tab_atom; + int i; + JSValue enum_obj, obj1; + JSForInIterator *it; + uint32_t tag, tab_atom_count; + + tag = JS_VALUE_GET_TAG(obj); + if (tag != JS_TAG_OBJECT && tag != JS_TAG_NULL && tag != JS_TAG_UNDEFINED) { + obj = JS_ToObjectFree(ctx, obj); + } + + it = js_malloc(ctx, sizeof(*it)); + if (!it) { + JS_FreeValue(ctx, obj); + return JS_EXCEPTION; + } + enum_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_FOR_IN_ITERATOR); + if (JS_IsException(enum_obj)) { + js_free(ctx, it); + JS_FreeValue(ctx, obj); + return JS_EXCEPTION; + } + it->is_array = false; + it->obj = obj; + it->idx = 0; + p = JS_VALUE_GET_OBJ(enum_obj); + p->u.for_in_iterator = it; + + if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) + return enum_obj; + + /* fast path: assume no enumerable properties in the prototype chain */ + obj1 = js_dup(obj); + for(;;) { + obj1 = JS_GetPrototypeFree(ctx, obj1); + if (JS_IsNull(obj1)) + break; + if (JS_IsException(obj1)) + goto fail; + if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, + JS_VALUE_GET_OBJ(obj1), + JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) { + JS_FreeValue(ctx, obj1); + goto fail; + } + js_free_prop_enum(ctx, tab_atom, tab_atom_count); + if (tab_atom_count != 0) { + JS_FreeValue(ctx, obj1); + goto slow_path; + } + /* must check for timeout to avoid infinite loop */ + if (js_poll_interrupts(ctx)) { + JS_FreeValue(ctx, obj1); + goto fail; + } + } + + p = JS_VALUE_GET_OBJ(obj); + + if (p->fast_array) { + JSShape *sh; + JSShapeProperty *prs; + /* check that there are no enumerable normal fields */ + sh = p->shape; + for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { + if (prs->flags & JS_PROP_ENUMERABLE) + goto normal_case; + } + /* for fast arrays, we only store the number of elements */ + it->is_array = true; + it->array_length = p->u.array.count; + } else { + normal_case: + if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p, + JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) + goto fail; + for(i = 0; i < tab_atom_count; i++) { + JS_SetPropertyInternal(ctx, enum_obj, tab_atom[i].atom, JS_NULL, 0); + } + js_free_prop_enum(ctx, tab_atom, tab_atom_count); + } + return enum_obj; + + slow_path: + /* non enumerable properties hide the enumerables ones in the + prototype chain */ + obj1 = js_dup(obj); + for(;;) { + if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, + JS_VALUE_GET_OBJ(obj1), + JS_GPN_STRING_MASK | JS_GPN_SET_ENUM)) { + JS_FreeValue(ctx, obj1); + goto fail; + } + for(i = 0; i < tab_atom_count; i++) { + JS_DefinePropertyValue(ctx, enum_obj, tab_atom[i].atom, JS_NULL, + (tab_atom[i].is_enumerable ? + JS_PROP_ENUMERABLE : 0)); + } + js_free_prop_enum(ctx, tab_atom, tab_atom_count); + obj1 = JS_GetPrototypeFree(ctx, obj1); + if (JS_IsNull(obj1)) + break; + if (JS_IsException(obj1)) + goto fail; + /* must check for timeout to avoid infinite loop */ + if (js_poll_interrupts(ctx)) { + JS_FreeValue(ctx, obj1); + goto fail; + } + } + return enum_obj; + + fail: + JS_FreeValue(ctx, enum_obj); + return JS_EXCEPTION; +} + +/* obj -> enum_obj */ +static __exception int js_for_in_start(JSContext *ctx, JSValue *sp) +{ + sp[-1] = build_for_in_iterator(ctx, sp[-1]); + if (JS_IsException(sp[-1])) + return -1; + return 0; +} + +/* enum_obj -> enum_obj value done */ +static __exception int js_for_in_next(JSContext *ctx, JSValue *sp) +{ + JSValue enum_obj; + JSObject *p; + JSAtom prop; + JSForInIterator *it; + int ret; + + enum_obj = sp[-1]; + /* fail safe */ + if (JS_VALUE_GET_TAG(enum_obj) != JS_TAG_OBJECT) + goto done; + p = JS_VALUE_GET_OBJ(enum_obj); + if (p->class_id != JS_CLASS_FOR_IN_ITERATOR) + goto done; + it = p->u.for_in_iterator; + + for(;;) { + if (it->is_array) { + if (it->idx >= it->array_length) + goto done; + prop = __JS_AtomFromUInt32(it->idx); + it->idx++; + } else { + JSShape *sh = p->shape; + JSShapeProperty *prs; + if (it->idx >= sh->prop_count) + goto done; + prs = get_shape_prop(sh) + it->idx; + prop = prs->atom; + it->idx++; + if (prop == JS_ATOM_NULL || !(prs->flags & JS_PROP_ENUMERABLE)) + continue; + } + // check if the property was deleted unless we're dealing with a proxy + JSValue obj = it->obj; + if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { + JSObject *p = JS_VALUE_GET_OBJ(obj); + if (p->class_id == JS_CLASS_PROXY) + break; + } + ret = JS_HasProperty(ctx, obj, prop); + if (ret < 0) + return ret; + if (ret) + break; + } + /* return the property */ + sp[0] = JS_AtomToValue(ctx, prop); + sp[1] = JS_FALSE; + return 0; + done: + /* return the end */ + sp[0] = JS_UNDEFINED; + sp[1] = JS_TRUE; + return 0; +} + +static JSValue JS_GetIterator2(JSContext *ctx, JSValueConst obj, + JSValueConst method) +{ + JSValue enum_obj; + + enum_obj = JS_Call(ctx, method, obj, 0, NULL); + if (JS_IsException(enum_obj)) + return enum_obj; + if (!JS_IsObject(enum_obj)) { + JS_FreeValue(ctx, enum_obj); + return JS_ThrowTypeErrorNotAnObject(ctx); + } + return enum_obj; +} + +static JSValue JS_GetIterator(JSContext *ctx, JSValueConst obj, bool is_async) +{ + JSValue method, ret, sync_iter; + + if (is_async) { + method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_asyncIterator); + if (JS_IsException(method)) + return method; + if (JS_IsUndefined(method) || JS_IsNull(method)) { + method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator); + if (JS_IsException(method)) + return method; + sync_iter = JS_GetIterator2(ctx, obj, method); + JS_FreeValue(ctx, method); + if (JS_IsException(sync_iter)) + return sync_iter; + ret = JS_CreateAsyncFromSyncIterator(ctx, sync_iter); + JS_FreeValue(ctx, sync_iter); + return ret; + } + } else { + method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator); + if (JS_IsException(method)) + return method; + } + if (!JS_IsFunction(ctx, method)) { + JS_FreeValue(ctx, method); + return JS_ThrowTypeError(ctx, "value is not iterable"); + } + ret = JS_GetIterator2(ctx, obj, method); + JS_FreeValue(ctx, method); + return ret; +} + +/* return *pdone = 2 if the iterator object is not parsed */ +static JSValue JS_IteratorNext2(JSContext *ctx, JSValueConst enum_obj, + JSValueConst method, + int argc, JSValueConst *argv, int *pdone) +{ + JSValue obj; + + /* fast path for the built-in iterators (avoid creating the + intermediate result object) */ + if (JS_IsObject(method)) { + JSObject *p = JS_VALUE_GET_OBJ(method); + if (p->class_id == JS_CLASS_C_FUNCTION && + p->u.cfunc.cproto == JS_CFUNC_iterator_next) { + JSCFunctionType func; + JSValueConst args[1]; + + /* in case the function expects one argument */ + if (argc == 0) { + args[0] = JS_UNDEFINED; + argv = args; + } + func = p->u.cfunc.c_function; + return func.iterator_next(ctx, enum_obj, argc, argv, + pdone, p->u.cfunc.magic); + } + } + obj = JS_Call(ctx, method, enum_obj, argc, argv); + if (JS_IsException(obj)) + goto fail; + if (!JS_IsObject(obj)) { + JS_FreeValue(ctx, obj); + JS_ThrowTypeError(ctx, "iterator must return an object"); + goto fail; + } + *pdone = 2; + return obj; + fail: + *pdone = false; + return JS_EXCEPTION; +} + +static JSValue JS_IteratorNext(JSContext *ctx, JSValueConst enum_obj, + JSValueConst method, + int argc, JSValueConst *argv, int *pdone) +{ + JSValue obj, value, done_val; + int done; + + obj = JS_IteratorNext2(ctx, enum_obj, method, argc, argv, &done); + if (JS_IsException(obj)) + goto fail; + if (likely(done == 0)) { + *pdone = false; + return obj; + } else if (done != 2) { + JS_FreeValue(ctx, obj); + *pdone = true; + return JS_UNDEFINED; + } else { + done_val = JS_GetProperty(ctx, obj, JS_ATOM_done); + if (JS_IsException(done_val)) + goto fail; + *pdone = JS_ToBoolFree(ctx, done_val); + value = JS_UNDEFINED; + if (!*pdone) { + value = JS_GetProperty(ctx, obj, JS_ATOM_value); + } + JS_FreeValue(ctx, obj); + return value; + } + fail: + JS_FreeValue(ctx, obj); + *pdone = false; + return JS_EXCEPTION; +} + +/* return < 0 in case of exception */ +static int JS_IteratorClose(JSContext *ctx, JSValueConst enum_obj, + bool is_exception_pending) +{ + JSValue method, ret, ex_obj; + int res; + + if (is_exception_pending) { + ex_obj = ctx->rt->current_exception; + ctx->rt->current_exception = JS_UNINITIALIZED; + res = -1; + } else { + ex_obj = JS_UNDEFINED; + res = 0; + } + method = JS_GetProperty(ctx, enum_obj, JS_ATOM_return); + if (JS_IsException(method)) { + res = -1; + goto done; + } + if (JS_IsUndefined(method) || JS_IsNull(method)) { + goto done; + } + ret = JS_CallFree(ctx, method, enum_obj, 0, NULL); + if (!is_exception_pending) { + if (JS_IsException(ret)) { + res = -1; + } else if (!JS_IsObject(ret)) { + JS_ThrowTypeErrorNotAnObject(ctx); + res = -1; + } + } + JS_FreeValue(ctx, ret); + done: + if (is_exception_pending) { + JS_Throw(ctx, ex_obj); + } + return res; +} + +/* obj -> enum_rec (3 slots) */ +static __exception int js_for_of_start(JSContext *ctx, JSValue *sp, + bool is_async) +{ + JSValue op1, obj, method; + op1 = sp[-1]; + obj = JS_GetIterator(ctx, op1, is_async); + if (JS_IsException(obj)) + return -1; + JS_FreeValue(ctx, op1); + sp[-1] = obj; + method = JS_GetProperty(ctx, obj, JS_ATOM_next); + if (JS_IsException(method)) + return -1; + sp[0] = method; + return 0; +} + +/* enum_rec [objs] -> enum_rec [objs] value done. There are 'offset' + objs. If 'done' is true or in case of exception, 'enum_rec' is set + to undefined. If 'done' is true, 'value' is always set to + undefined. */ +static __exception int js_for_of_next(JSContext *ctx, JSValue *sp, int offset) +{ + JSValue value = JS_UNDEFINED; + int done = 1; + + if (likely(!JS_IsUndefined(sp[offset]))) { + value = JS_IteratorNext(ctx, sp[offset], sp[offset + 1], 0, NULL, &done); + if (JS_IsException(value)) + done = -1; + if (done) { + /* value is JS_UNDEFINED or JS_EXCEPTION */ + /* replace the iteration object with undefined */ + JS_FreeValue(ctx, sp[offset]); + sp[offset] = JS_UNDEFINED; + if (done < 0) { + return -1; + } else { + JS_FreeValue(ctx, value); + value = JS_UNDEFINED; + } + } + } + sp[0] = value; + sp[1] = js_bool(done); + return 0; +} + +static JSValue JS_IteratorGetCompleteValue(JSContext *ctx, JSValue obj, + int *pdone) +{ + JSValue done_val, value; + int done; + done_val = JS_GetProperty(ctx, obj, JS_ATOM_done); + if (JS_IsException(done_val)) + goto fail; + done = JS_ToBoolFree(ctx, done_val); + value = JS_GetProperty(ctx, obj, JS_ATOM_value); + if (JS_IsException(value)) + goto fail; + *pdone = done; + return value; + fail: + *pdone = false; + return JS_EXCEPTION; +} + +static __exception int js_iterator_get_value_done(JSContext *ctx, JSValue *sp) +{ + JSValue obj, value; + int done; + obj = sp[-1]; + if (!JS_IsObject(obj)) { + JS_ThrowTypeError(ctx, "iterator must return an object"); + return -1; + } + value = JS_IteratorGetCompleteValue(ctx, obj, &done); + if (JS_IsException(value)) + return -1; + JS_FreeValue(ctx, obj); + sp[-1] = value; + sp[0] = js_bool(done); + return 0; +} + +static JSValue js_create_iterator_result(JSContext *ctx, + JSValue val, + bool done) +{ + JSValue obj; + obj = JS_NewObject(ctx); + if (JS_IsException(obj)) { + JS_FreeValue(ctx, val); + return obj; + } + if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_value, + val, JS_PROP_C_W_E) < 0) { + goto fail; + } + if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_done, + js_bool(done), JS_PROP_C_W_E) < 0) { + fail: + JS_FreeValue(ctx, obj); + return JS_EXCEPTION; + } + return obj; +} + +static JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, + int *pdone, int magic); + +static JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, int magic); + +static bool js_is_fast_array(JSContext *ctx, JSValue obj) +{ + /* Try and handle fast arrays explicitly */ + if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { + JSObject *p = JS_VALUE_GET_OBJ(obj); + if (p->class_id == JS_CLASS_ARRAY && p->fast_array) { + return true; + } + } + return false; +} + +/* Access an Array's internal JSValue array if available */ +static bool js_get_fast_array(JSContext *ctx, JSValue obj, + JSValue **arrpp, uint32_t *countp) +{ + /* Try and handle fast arrays explicitly */ + if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { + JSObject *p = JS_VALUE_GET_OBJ(obj); + if (p->class_id == JS_CLASS_ARRAY && p->fast_array) { + *countp = p->u.array.count; + *arrpp = p->u.array.u.values; + return true; + } + } + return false; +} + +static __exception int js_append_enumerate(JSContext *ctx, JSValue *sp) +{ + JSValue iterator, enumobj, method, value; + int is_array_iterator; + JSValue *arrp; + uint32_t i, count32, pos; + + if (JS_VALUE_GET_TAG(sp[-2]) != JS_TAG_INT) { + JS_ThrowInternalError(ctx, "invalid index for append"); + return -1; + } + + pos = JS_VALUE_GET_INT(sp[-2]); + + /* XXX: further optimisations: + - use ctx->array_proto_values? + - check if array_iterator_prototype next method is built-in and + avoid constructing actual iterator object? + - build this into js_for_of_start and use in all `for (x of o)` loops + */ + iterator = JS_GetProperty(ctx, sp[-1], JS_ATOM_Symbol_iterator); + if (JS_IsException(iterator)) + return -1; + /* Used to squelch a -Wcast-function-type warning. */ + JSCFunctionType ft = { .generic_magic = js_create_array_iterator }; + is_array_iterator = JS_IsCFunction(ctx, iterator, + ft.generic, + JS_ITERATOR_KIND_VALUE); + JS_FreeValue(ctx, iterator); + + enumobj = JS_GetIterator(ctx, sp[-1], false); + if (JS_IsException(enumobj)) + return -1; + method = JS_GetProperty(ctx, enumobj, JS_ATOM_next); + if (JS_IsException(method)) { + JS_FreeValue(ctx, enumobj); + return -1; + } + /* Used to squelch a -Wcast-function-type warning. */ + JSCFunctionType ft2 = { .iterator_next = js_array_iterator_next }; + if (is_array_iterator + && JS_IsCFunction(ctx, method, ft2.generic, 0) + && js_get_fast_array(ctx, sp[-1], &arrp, &count32)) { + uint32_t len; + if (js_get_length32(ctx, &len, sp[-1])) + goto exception; + /* if len > count32, the elements >= count32 might be read in + the prototypes and might have side effects */ + if (len != count32) + goto general_case; + /* Handle fast arrays explicitly */ + for (i = 0; i < count32; i++) { + if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, + js_dup(arrp[i]), JS_PROP_C_W_E) < 0) + goto exception; + } + } else { + general_case: + for (;;) { + int done; + value = JS_IteratorNext(ctx, enumobj, method, 0, NULL, &done); + if (JS_IsException(value)) + goto exception; + if (done) { + /* value is JS_UNDEFINED */ + break; + } + if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, value, JS_PROP_C_W_E) < 0) + goto exception; + } + } + /* Note: could raise an error if too many elements */ + sp[-2] = js_int32(pos); + JS_FreeValue(ctx, enumobj); + JS_FreeValue(ctx, method); + return 0; + +exception: + JS_IteratorClose(ctx, enumobj, true); + JS_FreeValue(ctx, enumobj); + JS_FreeValue(ctx, method); + return -1; +} + +static __exception int JS_CopyDataProperties(JSContext *ctx, + JSValue target, + JSValue source, + JSValue excluded, + bool setprop) +{ + JSPropertyEnum *tab_atom; + JSValue val; + uint32_t i, tab_atom_count; + JSObject *p; + JSObject *pexcl = NULL; + int ret, gpn_flags; + JSPropertyDescriptor desc; + bool is_enumerable; + + if (JS_VALUE_GET_TAG(source) != JS_TAG_OBJECT) + return 0; + + if (JS_VALUE_GET_TAG(excluded) == JS_TAG_OBJECT) + pexcl = JS_VALUE_GET_OBJ(excluded); + + p = JS_VALUE_GET_OBJ(source); + + gpn_flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY; + if (p->is_exotic) { + const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; + /* cannot use JS_GPN_ENUM_ONLY with e.g. proxies because it + introduces a visible change */ + if (em && em->get_own_property_names) { + gpn_flags &= ~JS_GPN_ENUM_ONLY; + } + } + if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p, + gpn_flags)) + return -1; + + for (i = 0; i < tab_atom_count; i++) { + if (pexcl) { + ret = JS_GetOwnPropertyInternal(ctx, NULL, pexcl, tab_atom[i].atom); + if (ret) { + if (ret < 0) + goto exception; + continue; + } + } + if (!(gpn_flags & JS_GPN_ENUM_ONLY)) { + /* test if the property is enumerable */ + ret = JS_GetOwnPropertyInternal(ctx, &desc, p, tab_atom[i].atom); + if (ret < 0) + goto exception; + if (!ret) + continue; + is_enumerable = (desc.flags & JS_PROP_ENUMERABLE) != 0; + js_free_desc(ctx, &desc); + if (!is_enumerable) + continue; + } + val = JS_GetProperty(ctx, source, tab_atom[i].atom); + if (JS_IsException(val)) + goto exception; + if (setprop) + ret = JS_SetProperty(ctx, target, tab_atom[i].atom, val); + else + ret = JS_DefinePropertyValue(ctx, target, tab_atom[i].atom, val, + JS_PROP_C_W_E); + if (ret < 0) + goto exception; + } + js_free_prop_enum(ctx, tab_atom, tab_atom_count); + return 0; + exception: + js_free_prop_enum(ctx, tab_atom, tab_atom_count); + return -1; +} + +/* only valid inside C functions */ +static JSValueConst JS_GetActiveFunction(JSContext *ctx) +{ + return ctx->rt->current_stack_frame->cur_func; +} + +/* create a detached var ref */ +static JSVarRef *js_create_var_ref(JSContext *ctx, bool is_gc_object) +{ + JSVarRef *var_ref; + var_ref = js_malloc(ctx, sizeof(JSVarRef)); + if (!var_ref) + return NULL; + var_ref->header.ref_count = 1; + var_ref->is_detached = true; + var_ref->value = JS_UNDEFINED; + var_ref->pvalue = &var_ref->value; + if (is_gc_object) + add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF); + return var_ref; +} + +static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx, + bool is_arg) +{ + JSObject *p; + JSFunctionBytecode *b; + JSVarRef *var_ref; + JSValue *pvalue; + int var_ref_idx; + JSVarDef *vd; + + p = JS_VALUE_GET_OBJ(sf->cur_func); + b = p->u.func.function_bytecode; + + if (is_arg) { + vd = &b->vardefs[var_idx]; + pvalue = &sf->arg_buf[var_idx]; + } else { + vd = &b->vardefs[b->arg_count + var_idx]; + pvalue = &sf->var_buf[var_idx]; + } + + /* If the variable is captured, use the pre-computed index for O(1) lookup */ + if (vd->is_captured) { + var_ref_idx = vd->var_ref_idx; + var_ref = sf->var_refs[var_ref_idx]; + if (var_ref) { + /* reference to the already created local variable */ + var_ref->header.ref_count++; + return var_ref; + } + + /* create a new one */ + var_ref = js_malloc(ctx, sizeof(JSVarRef)); + if (!var_ref) + return NULL; + var_ref->header.ref_count = 1; + var_ref->is_detached = false; + var_ref->is_lexical = false; + var_ref->is_const = false; + var_ref->var_ref_idx = var_ref_idx; + var_ref->stack_frame = sf; + sf->var_refs[var_ref_idx] = var_ref; + var_ref->pvalue = pvalue; + return var_ref; + } else { + /* Variable is not captured (e.g., from eval closures on uncaptured vars). + Create a detached var_ref that holds a copy of the value. */ + var_ref = js_malloc(ctx, sizeof(JSVarRef)); + if (!var_ref) + return NULL; + var_ref->header.ref_count = 1; + var_ref->is_detached = true; + var_ref->value = js_dup(*pvalue); + var_ref->pvalue = &var_ref->value; + add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF); + return var_ref; + } +} + +static JSValue js_closure2(JSContext *ctx, JSValue func_obj, + JSFunctionBytecode *b, + JSVarRef **cur_var_refs, + JSStackFrame *sf) +{ + JSObject *p; + JSVarRef **var_refs; + int i; + + p = JS_VALUE_GET_OBJ(func_obj); + p->u.func.function_bytecode = b; + p->u.func.home_object = NULL; + p->u.func.var_refs = NULL; + if (b->closure_var_count) { + var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count); + if (!var_refs) + goto fail; + p->u.func.var_refs = var_refs; + for(i = 0; i < b->closure_var_count; i++) { + JSClosureVar *cv = &b->closure_var[i]; + JSVarRef *var_ref; + switch(cv->closure_type) { + case JS_CLOSURE_LOCAL: + /* reuse the existing variable reference if it already exists */ + var_ref = get_var_ref(ctx, sf, cv->var_idx, false); + break; + case JS_CLOSURE_ARG: + /* reuse the existing variable reference if it already exists */ + var_ref = get_var_ref(ctx, sf, cv->var_idx, true); + break; + case JS_CLOSURE_REF: + case JS_CLOSURE_GLOBAL_REF: + var_ref = cur_var_refs[cv->var_idx]; + var_ref->header.ref_count++; + break; + default: + abort(); + } + if (!var_ref) + goto fail; + var_refs[i] = var_ref; + } + } + return func_obj; + fail: + /* bfunc is freed when func_obj is freed */ + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; +} + +static JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque) +{ + JSValue obj, this_val; + int ret; + + this_val = JS_MKPTR(JS_TAG_OBJECT, p); + obj = JS_NewObject(ctx); + if (JS_IsException(obj)) + return JS_EXCEPTION; + ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_constructor, + js_dup(this_val), + JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); + if (ret < 0) { + JS_FreeValue(ctx, obj); + return JS_EXCEPTION; + } + return obj; +} + +static const uint16_t func_kind_to_class_id[] = { + [JS_FUNC_NORMAL] = JS_CLASS_BYTECODE_FUNCTION, + [JS_FUNC_GENERATOR] = JS_CLASS_GENERATOR_FUNCTION, + [JS_FUNC_ASYNC] = JS_CLASS_ASYNC_FUNCTION, + [JS_FUNC_ASYNC_GENERATOR] = JS_CLASS_ASYNC_GENERATOR_FUNCTION, +}; + +static JSValue js_closure(JSContext *ctx, JSValue bfunc, + JSVarRef **cur_var_refs, + JSStackFrame *sf) +{ + JSFunctionBytecode *b; + JSValue func_obj; + JSAtom name_atom; + + b = JS_VALUE_GET_PTR(bfunc); + func_obj = JS_NewObjectClass(ctx, func_kind_to_class_id[b->func_kind]); + if (JS_IsException(func_obj)) { + JS_FreeValue(ctx, bfunc); + return JS_EXCEPTION; + } + func_obj = js_closure2(ctx, func_obj, b, cur_var_refs, sf); + if (JS_IsException(func_obj)) { + /* bfunc has been freed */ + goto fail; + } + name_atom = b->func_name; + if (name_atom == JS_ATOM_NULL) + name_atom = JS_ATOM_empty_string; + js_function_set_properties(ctx, func_obj, name_atom, + b->defined_arg_count); + + if (b->func_kind & JS_FUNC_GENERATOR) { + JSValue proto; + int proto_class_id; + /* generators have a prototype field which is used as + prototype for the generator object */ + if (b->func_kind == JS_FUNC_ASYNC_GENERATOR) + proto_class_id = JS_CLASS_ASYNC_GENERATOR; + else + proto_class_id = JS_CLASS_GENERATOR; + proto = JS_NewObjectProto(ctx, ctx->class_proto[proto_class_id]); + if (JS_IsException(proto)) + goto fail; + JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype, proto, + JS_PROP_WRITABLE); + } else if (b->has_prototype) { + /* add the 'prototype' property: delay instantiation to avoid + creating cycles for every javascript function. The prototype + object is created on the fly when first accessed */ + JS_SetConstructorBit(ctx, func_obj, true); + JS_DefineAutoInitProperty(ctx, func_obj, JS_ATOM_prototype, + JS_AUTOINIT_ID_PROTOTYPE, NULL, + JS_PROP_WRITABLE); + } + return func_obj; + fail: + /* bfunc is freed when func_obj is freed */ + JS_FreeValue(ctx, func_obj); + return JS_EXCEPTION; +} + +#define JS_DEFINE_CLASS_HAS_HERITAGE (1 << 0) + +static int js_op_define_class(JSContext *ctx, JSValue *sp, + JSAtom class_name, int class_flags, + JSVarRef **cur_var_refs, + JSStackFrame *sf, bool is_computed_name) +{ + JSValue bfunc, parent_class, proto = JS_UNDEFINED; + JSValue ctor = JS_UNDEFINED, parent_proto = JS_UNDEFINED; + JSFunctionBytecode *b; + + parent_class = sp[-2]; + bfunc = sp[-1]; + + if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE) { + if (JS_IsNull(parent_class)) { + parent_proto = JS_NULL; + parent_class = js_dup(ctx->function_proto); + } else { + if (!JS_IsConstructor(ctx, parent_class)) { + JS_ThrowTypeError(ctx, "parent class must be constructor"); + goto fail; + } + parent_proto = JS_GetProperty(ctx, parent_class, JS_ATOM_prototype); + if (JS_IsException(parent_proto)) + goto fail; + if (!JS_IsNull(parent_proto) && !JS_IsObject(parent_proto)) { + JS_ThrowTypeError(ctx, "parent prototype must be an object or null"); + goto fail; + } + } + } else { + /* parent_class is JS_UNDEFINED in this case */ + parent_proto = js_dup(ctx->class_proto[JS_CLASS_OBJECT]); + parent_class = js_dup(ctx->function_proto); + } + proto = JS_NewObjectProto(ctx, parent_proto); + if (JS_IsException(proto)) + goto fail; + + b = JS_VALUE_GET_PTR(bfunc); + assert(b->func_kind == JS_FUNC_NORMAL); + ctor = JS_NewObjectProtoClass(ctx, parent_class, + JS_CLASS_BYTECODE_FUNCTION); + if (JS_IsException(ctor)) + goto fail; + ctor = js_closure2(ctx, ctor, b, cur_var_refs, sf); + bfunc = JS_UNDEFINED; + if (JS_IsException(ctor)) + goto fail; + js_method_set_home_object(ctx, ctor, proto); + JS_SetConstructorBit(ctx, ctor, true); + + JS_DefinePropertyValue(ctx, ctor, JS_ATOM_length, + js_int32(b->defined_arg_count), + JS_PROP_CONFIGURABLE); + + if (is_computed_name) { + if (JS_DefineObjectNameComputed(ctx, ctor, sp[-3], + JS_PROP_CONFIGURABLE) < 0) + goto fail; + } else { + if (JS_DefineObjectName(ctx, ctor, class_name, JS_PROP_CONFIGURABLE) < 0) + goto fail; + } + + /* the constructor property must be first. It can be overriden by + computed property names */ + if (JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor, + js_dup(ctor), + JS_PROP_CONFIGURABLE | + JS_PROP_WRITABLE | JS_PROP_THROW) < 0) + goto fail; + /* set the prototype property */ + if (JS_DefinePropertyValue(ctx, ctor, JS_ATOM_prototype, + js_dup(proto), JS_PROP_THROW) < 0) + goto fail; + + JS_FreeValue(ctx, parent_proto); + JS_FreeValue(ctx, parent_class); + + sp[-2] = ctor; + sp[-1] = proto; + return 0; + fail: + JS_FreeValue(ctx, parent_class); + JS_FreeValue(ctx, parent_proto); + JS_FreeValue(ctx, bfunc); + JS_FreeValue(ctx, proto); + JS_FreeValue(ctx, ctor); + sp[-2] = JS_UNDEFINED; + sp[-1] = JS_UNDEFINED; + return -1; +} + +static void close_var_ref(JSRuntime *rt, JSVarRef *var_ref) +{ + var_ref->value = js_dup(*var_ref->pvalue); + var_ref->pvalue = &var_ref->value; + /* the reference is no longer to a local variable */ + var_ref->is_detached = true; + add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF); +} + +static void close_var_refs(JSRuntime *rt, JSStackFrame *sf) +{ + JSVarRef *var_ref; + int i; + + for (i = 0; i < sf->var_ref_count; i++) { + var_ref = sf->var_refs[i]; + if (var_ref) + close_var_ref(rt, var_ref); + } +} + +static void close_lexical_var(JSContext *ctx, JSFunctionBytecode *b, + JSStackFrame *sf, int var_idx) +{ + JSVarRef *var_ref; + int var_ref_idx; + + var_ref_idx = b->vardefs[b->arg_count + var_idx].var_ref_idx; + var_ref = sf->var_refs[var_ref_idx]; + if (var_ref) { + close_var_ref(ctx->rt, var_ref); + sf->var_refs[var_ref_idx] = NULL; + } +} + +#define JS_CALL_FLAG_COPY_ARGV (1 << 1) +#define JS_CALL_FLAG_GENERATOR (1 << 2) + +static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, int flags) +{ + JSRuntime *rt = ctx->rt; + JSCFunctionType func; + JSObject *p; + JSStackFrame sf_s, *sf = &sf_s, *prev_sf; + JSValue ret_val; + JSValueConst *arg_buf; + int arg_count, i; + JSCFunctionEnum cproto; + + p = JS_VALUE_GET_OBJ(func_obj); + cproto = p->u.cfunc.cproto; + arg_count = p->u.cfunc.length; + + /* better to always check stack overflow */ + if (js_check_stack_overflow(rt, sizeof(arg_buf[0]) * arg_count)) + return JS_ThrowStackOverflow(ctx); + + prev_sf = rt->current_stack_frame; + sf->prev_frame = prev_sf; + rt->current_stack_frame = sf; + ctx = p->u.cfunc.realm; /* change the current realm */ + + sf->is_strict_mode = false; + sf->cur_func = unsafe_unconst(func_obj); + sf->arg_count = argc; + arg_buf = argv; + + if (unlikely(argc < arg_count)) { + /* ensure that at least argc_count arguments are readable */ + arg_buf = alloca(sizeof(arg_buf[0]) * arg_count); + for(i = 0; i < argc; i++) + arg_buf[i] = argv[i]; + for(i = argc; i < arg_count; i++) + arg_buf[i] = JS_UNDEFINED; + sf->arg_count = arg_count; + } + sf->arg_buf = (JSValue *)arg_buf; + + func = p->u.cfunc.c_function; + switch(cproto) { + case JS_CFUNC_constructor: + case JS_CFUNC_constructor_or_func: + if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) { + if (cproto == JS_CFUNC_constructor) { + not_a_constructor: + ret_val = JS_ThrowTypeError(ctx, "must be called with new"); + break; + } else { + this_obj = JS_UNDEFINED; + } + } + /* here this_obj is new_target */ + /* fall thru */ + case JS_CFUNC_generic: + ret_val = func.generic(ctx, this_obj, argc, arg_buf); + break; + case JS_CFUNC_constructor_magic: + case JS_CFUNC_constructor_or_func_magic: + if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) { + if (cproto == JS_CFUNC_constructor_magic) { + goto not_a_constructor; + } else { + this_obj = JS_UNDEFINED; + } + } + /* fall thru */ + case JS_CFUNC_generic_magic: + ret_val = func.generic_magic(ctx, this_obj, argc, arg_buf, + p->u.cfunc.magic); + break; + case JS_CFUNC_getter: + ret_val = func.getter(ctx, this_obj); + break; + case JS_CFUNC_setter: + ret_val = func.setter(ctx, this_obj, arg_buf[0]); + break; + case JS_CFUNC_getter_magic: + ret_val = func.getter_magic(ctx, this_obj, p->u.cfunc.magic); + break; + case JS_CFUNC_setter_magic: + ret_val = func.setter_magic(ctx, this_obj, arg_buf[0], p->u.cfunc.magic); + break; + case JS_CFUNC_f_f: + { + double d1; + + if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) { + ret_val = JS_EXCEPTION; + break; + } + ret_val = js_number(func.f_f(d1)); + } + break; + case JS_CFUNC_f_f_f: + { + double d1, d2; + + if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) { + ret_val = JS_EXCEPTION; + break; + } + if (unlikely(JS_ToFloat64(ctx, &d2, arg_buf[1]))) { + ret_val = JS_EXCEPTION; + break; + } + ret_val = js_number(func.f_f_f(d1, d2)); + } + break; + case JS_CFUNC_iterator_next: + { + int done; + ret_val = func.iterator_next(ctx, this_obj, argc, arg_buf, + &done, p->u.cfunc.magic); + if (!JS_IsException(ret_val) && done != 2) { + ret_val = js_create_iterator_result(ctx, ret_val, done); + } + } + break; + default: + abort(); + } + + rt->current_stack_frame = sf->prev_frame; + return ret_val; +} + +static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, int flags) +{ + JSObject *p; + JSBoundFunction *bf; + JSValueConst *arg_buf, new_target; + int arg_count, i; + + p = JS_VALUE_GET_OBJ(func_obj); + bf = p->u.bound_function; + arg_count = bf->argc + argc; + if (js_check_stack_overflow(ctx->rt, sizeof(JSValue) * arg_count)) + return JS_ThrowStackOverflow(ctx); + arg_buf = alloca(sizeof(JSValue) * arg_count); + for(i = 0; i < bf->argc; i++) { + arg_buf[i] = bf->argv[i]; + } + for(i = 0; i < argc; i++) { + arg_buf[bf->argc + i] = argv[i]; + } + if (flags & JS_CALL_FLAG_CONSTRUCTOR) { + new_target = this_obj; + if (js_same_value(ctx, func_obj, new_target)) + new_target = bf->func_obj; + return JS_CallConstructor2(ctx, bf->func_obj, new_target, + arg_count, arg_buf); + } else { + return JS_Call(ctx, bf->func_obj, bf->this_val, + arg_count, arg_buf); + } +} + +/* argument of OP_special_object */ +typedef enum { + OP_SPECIAL_OBJECT_ARGUMENTS, + OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS, + OP_SPECIAL_OBJECT_THIS_FUNC, + OP_SPECIAL_OBJECT_NEW_TARGET, + OP_SPECIAL_OBJECT_HOME_OBJECT, + OP_SPECIAL_OBJECT_VAR_OBJECT, + OP_SPECIAL_OBJECT_IMPORT_META, + OP_SPECIAL_OBJECT_NULL_PROTO, +} OPSpecialObjectEnum; + +#define FUNC_RET_AWAIT 0 +#define FUNC_RET_YIELD 1 +#define FUNC_RET_YIELD_STAR 2 + +#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_* +static void dump_single_byte_code(JSContext *ctx, const uint8_t *pc, + JSFunctionBytecode *b, int start_pos); +static void print_func_name(JSFunctionBytecode *b); +#endif + +static bool needs_backtrace(JSValue exc) +{ + JSObject *p; + + if (JS_VALUE_GET_TAG(exc) != JS_TAG_OBJECT) + return false; + p = JS_VALUE_GET_OBJ(exc); + if (p->class_id != JS_CLASS_ERROR) + return false; + return !find_own_property1(p, JS_ATOM_stack); +} + +/* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */ +static JSValue JS_CallInternal(JSContext *caller_ctx, JSValueConst func_obj, + JSValueConst this_obj, JSValueConst new_target, + int argc, JSValueConst *argv, int flags) +{ + JSRuntime *rt = caller_ctx->rt; + JSContext *ctx; + JSObject *p; + JSFunctionBytecode *b; + JSStackFrame sf_s, *sf = &sf_s; + uint8_t *pc; + int opcode, arg_allocated_size, i; + JSValue *local_buf, *stack_buf, *var_buf, *arg_buf, *sp, ret_val, *pval; + JSVarRef **var_refs; + size_t alloca_size; + +#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STEP +#define DUMP_BYTECODE_OR_DONT(pc) \ + if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STEP)) dump_single_byte_code(ctx, pc, b, 0); +#else +#define DUMP_BYTECODE_OR_DONT(pc) +#endif + +#if !DIRECT_DISPATCH +#define SWITCH(pc) DUMP_BYTECODE_OR_DONT(pc) switch (opcode = *pc++) +#define CASE(op) case op +#define DEFAULT default +#define BREAK break +#else + __extension__ static const void * const dispatch_table[256] = { +#define DEF(id, size, n_pop, n_push, f) && case_OP_ ## id, +#define def(id, size, n_pop, n_push, f) +/* + * QuickJS opcode definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef FMT +FMT(none) +FMT(none_int) +FMT(none_loc) +FMT(none_arg) +FMT(none_var_ref) +FMT(u8) +FMT(i8) +FMT(loc8) +FMT(const8) +FMT(label8) +FMT(u16) +FMT(i16) +FMT(label16) +FMT(npop) +FMT(npopx) +FMT(npop_u16) +FMT(loc) +FMT(arg) +FMT(var_ref) +FMT(u32) +FMT(u32x2) +FMT(i32) +FMT(const) +FMT(label) +FMT(atom) +FMT(atom_u8) +FMT(atom_u16) +FMT(atom_label_u8) +FMT(atom_label_u16) +FMT(label_u16) +#undef FMT +#endif /* FMT */ + +#ifdef DEF + +#ifndef def +#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) +#endif + +DEF(invalid, 1, 0, 0, none) /* never emitted */ + +/* push values */ +DEF( push_i32, 5, 0, 1, i32) +DEF( push_const, 5, 0, 1, const) +DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ +DEF(push_atom_value, 5, 0, 1, atom) +DEF( private_symbol, 5, 0, 1, atom) +DEF( undefined, 1, 0, 1, none) +DEF( null, 1, 0, 1, none) +DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ +DEF( push_false, 1, 0, 1, none) +DEF( push_true, 1, 0, 1, none) +DEF( object, 1, 0, 1, none) +DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ +DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ + +DEF( drop, 1, 1, 0, none) /* a -> */ +DEF( nip, 1, 2, 1, none) /* a b -> b */ +DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ +DEF( dup, 1, 1, 2, none) /* a -> a a */ +DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ +DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ +DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ +DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ +DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ +DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ +DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ +DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ +DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ +DEF( swap, 1, 2, 2, none) /* a b -> b a */ +DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ +DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ +DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ +DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ +DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ + +DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ +DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ +DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ +DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ +DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ +DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ +DEF( apply, 3, 3, 1, u16) +DEF( return, 1, 1, 0, none) +DEF( return_undef, 1, 0, 0, none) +DEF(check_ctor_return, 1, 1, 2, none) +DEF( check_ctor, 1, 0, 0, none) +DEF( init_ctor, 1, 0, 1, none) +DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ +DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ +DEF( return_async, 1, 1, 0, none) +DEF( throw, 1, 1, 0, none) +DEF( throw_error, 6, 0, 0, atom_u8) +DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ +DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ +DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a + bytecode string */ +DEF( get_super, 1, 1, 1, none) +DEF( import, 1, 2, 1, none) /* dynamic module import */ + +DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ +DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ +DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ +DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ + +DEF( get_ref_value, 1, 2, 3, none) +DEF( put_ref_value, 1, 3, 0, none) + +DEF( define_var, 6, 0, 0, atom_u8) +DEF(check_define_var, 6, 0, 0, atom_u8) +DEF( define_func, 6, 1, 0, atom_u8) + +// order matters, see IC counterparts +DEF( get_field, 5, 1, 1, atom) +DEF( get_field2, 5, 1, 2, atom) +DEF( put_field, 5, 2, 0, atom) + +DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ +DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ +DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ +DEF( get_array_el, 1, 2, 1, none) +DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ +DEF( put_array_el, 1, 3, 0, none) +DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ +DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ +DEF( define_field, 5, 2, 1, atom) +DEF( set_name, 5, 1, 1, atom) +DEF(set_name_computed, 1, 2, 2, none) +DEF( set_proto, 1, 2, 1, none) +DEF(set_home_object, 1, 2, 2, none) +DEF(define_array_el, 1, 3, 2, none) +DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ +DEF(copy_data_properties, 2, 3, 3, u8) +DEF( define_method, 6, 2, 1, atom_u8) +DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ +DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ +DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ + +DEF( get_loc, 3, 0, 1, loc) +DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ +DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ +DEF( get_arg, 3, 0, 1, arg) +DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ +DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ +DEF( get_var_ref, 3, 0, 1, var_ref) +DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ +DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ +DEF(set_loc_uninitialized, 3, 0, 0, loc) +DEF( get_loc_check, 3, 0, 1, loc) +DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ +DEF( put_loc_check_init, 3, 1, 0, loc) +DEF(get_var_ref_check, 3, 0, 1, var_ref) +DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ +DEF(put_var_ref_check_init, 3, 1, 0, var_ref) +DEF( close_loc, 3, 0, 0, loc) +DEF( if_false, 5, 1, 0, label) +DEF( if_true, 5, 1, 0, label) /* must come after if_false */ +DEF( goto, 5, 0, 0, label) /* must come after if_true */ +DEF( catch, 5, 0, 1, label) +DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ +DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ +DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */ + +DEF( to_object, 1, 1, 1, none) +//DEF( to_string, 1, 1, 1, none) +DEF( to_propkey, 1, 1, 1, none) +DEF( to_propkey2, 1, 2, 2, none) + +DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) + +DEF( make_loc_ref, 7, 0, 2, atom_u16) +DEF( make_arg_ref, 7, 0, 2, atom_u16) +DEF(make_var_ref_ref, 7, 0, 2, atom_u16) +DEF( make_var_ref, 5, 0, 2, atom) + +DEF( for_in_start, 1, 1, 1, none) +DEF( for_of_start, 1, 1, 3, none) +DEF(for_await_of_start, 1, 1, 3, none) +DEF( for_in_next, 1, 1, 3, none) +DEF( for_of_next, 2, 3, 5, u8) +DEF(iterator_check_object, 1, 1, 1, none) +DEF(iterator_get_value_done, 1, 1, 2, none) +DEF( iterator_close, 1, 3, 0, none) +DEF( iterator_next, 1, 4, 4, none) +DEF( iterator_call, 2, 4, 5, u8) +DEF( initial_yield, 1, 0, 0, none) +DEF( yield, 1, 1, 2, none) +DEF( yield_star, 1, 1, 2, none) +DEF(async_yield_star, 1, 1, 2, none) +DEF( await, 1, 1, 1, none) + +/* arithmetic/logic operations */ +DEF( neg, 1, 1, 1, none) +DEF( plus, 1, 1, 1, none) +DEF( dec, 1, 1, 1, none) +DEF( inc, 1, 1, 1, none) +DEF( post_dec, 1, 1, 2, none) +DEF( post_inc, 1, 1, 2, none) +DEF( dec_loc, 2, 0, 0, loc8) +DEF( inc_loc, 2, 0, 0, loc8) +DEF( add_loc, 2, 1, 0, loc8) +DEF( not, 1, 1, 1, none) +DEF( lnot, 1, 1, 1, none) +DEF( typeof, 1, 1, 1, none) +DEF( delete, 1, 2, 1, none) +DEF( delete_var, 5, 0, 1, atom) + +/* warning: order matters (see js_parse_assign_expr) */ +DEF( mul, 1, 2, 1, none) +DEF( div, 1, 2, 1, none) +DEF( mod, 1, 2, 1, none) +DEF( add, 1, 2, 1, none) +DEF( sub, 1, 2, 1, none) +DEF( shl, 1, 2, 1, none) +DEF( sar, 1, 2, 1, none) +DEF( shr, 1, 2, 1, none) +DEF( and, 1, 2, 1, none) +DEF( xor, 1, 2, 1, none) +DEF( or, 1, 2, 1, none) +DEF( pow, 1, 2, 1, none) + +DEF( lt, 1, 2, 1, none) +DEF( lte, 1, 2, 1, none) +DEF( gt, 1, 2, 1, none) +DEF( gte, 1, 2, 1, none) +DEF( instanceof, 1, 2, 1, none) +DEF( in, 1, 2, 1, none) +DEF( eq, 1, 2, 1, none) +DEF( neq, 1, 2, 1, none) +DEF( strict_eq, 1, 2, 1, none) +DEF( strict_neq, 1, 2, 1, none) +DEF(is_undefined_or_null, 1, 1, 1, none) +DEF( private_in, 1, 2, 1, none) +DEF(push_bigint_i32, 5, 0, 1, i32) +/* must be the last non short and non temporary opcode */ +DEF( nop, 1, 0, 0, none) + +/* temporary opcodes: never emitted in the final bytecode */ + +def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ +def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ + +def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ + +def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ +def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ +def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */ +def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */ +def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */ +def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ + +def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */ + +DEF( push_minus1, 1, 0, 1, none_int) +DEF( push_0, 1, 0, 1, none_int) +DEF( push_1, 1, 0, 1, none_int) +DEF( push_2, 1, 0, 1, none_int) +DEF( push_3, 1, 0, 1, none_int) +DEF( push_4, 1, 0, 1, none_int) +DEF( push_5, 1, 0, 1, none_int) +DEF( push_6, 1, 0, 1, none_int) +DEF( push_7, 1, 0, 1, none_int) +DEF( push_i8, 2, 0, 1, i8) +DEF( push_i16, 3, 0, 1, i16) +DEF( push_const8, 2, 0, 1, const8) +DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ +DEF(push_empty_string, 1, 0, 1, none) + +DEF( get_loc8, 2, 0, 1, loc8) +DEF( put_loc8, 2, 1, 0, loc8) +DEF( set_loc8, 2, 1, 1, loc8) + +DEF( get_loc0_loc1, 1, 0, 2, none_loc) +DEF( get_loc0, 1, 0, 1, none_loc) +DEF( get_loc1, 1, 0, 1, none_loc) +DEF( get_loc2, 1, 0, 1, none_loc) +DEF( get_loc3, 1, 0, 1, none_loc) +DEF( put_loc0, 1, 1, 0, none_loc) +DEF( put_loc1, 1, 1, 0, none_loc) +DEF( put_loc2, 1, 1, 0, none_loc) +DEF( put_loc3, 1, 1, 0, none_loc) +DEF( set_loc0, 1, 1, 1, none_loc) +DEF( set_loc1, 1, 1, 1, none_loc) +DEF( set_loc2, 1, 1, 1, none_loc) +DEF( set_loc3, 1, 1, 1, none_loc) +DEF( get_arg0, 1, 0, 1, none_arg) +DEF( get_arg1, 1, 0, 1, none_arg) +DEF( get_arg2, 1, 0, 1, none_arg) +DEF( get_arg3, 1, 0, 1, none_arg) +DEF( put_arg0, 1, 1, 0, none_arg) +DEF( put_arg1, 1, 1, 0, none_arg) +DEF( put_arg2, 1, 1, 0, none_arg) +DEF( put_arg3, 1, 1, 0, none_arg) +DEF( set_arg0, 1, 1, 1, none_arg) +DEF( set_arg1, 1, 1, 1, none_arg) +DEF( set_arg2, 1, 1, 1, none_arg) +DEF( set_arg3, 1, 1, 1, none_arg) +DEF( get_var_ref0, 1, 0, 1, none_var_ref) +DEF( get_var_ref1, 1, 0, 1, none_var_ref) +DEF( get_var_ref2, 1, 0, 1, none_var_ref) +DEF( get_var_ref3, 1, 0, 1, none_var_ref) +DEF( put_var_ref0, 1, 1, 0, none_var_ref) +DEF( put_var_ref1, 1, 1, 0, none_var_ref) +DEF( put_var_ref2, 1, 1, 0, none_var_ref) +DEF( put_var_ref3, 1, 1, 0, none_var_ref) +DEF( set_var_ref0, 1, 1, 1, none_var_ref) +DEF( set_var_ref1, 1, 1, 1, none_var_ref) +DEF( set_var_ref2, 1, 1, 1, none_var_ref) +DEF( set_var_ref3, 1, 1, 1, none_var_ref) + +DEF( get_length, 1, 1, 1, none) + +DEF( if_false8, 2, 1, 0, label8) +DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ +DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ +DEF( goto16, 3, 0, 0, label16) + +DEF( call0, 1, 1, 1, npopx) +DEF( call1, 1, 1, 1, npopx) +DEF( call2, 1, 1, 1, npopx) +DEF( call3, 1, 1, 1, npopx) + +DEF( is_undefined, 1, 1, 1, none) +DEF( is_null, 1, 1, 1, none) +DEF(typeof_is_undefined, 1, 1, 1, none) +DEF( typeof_is_function, 1, 1, 1, none) + +#undef DEF +#undef def +#endif /* DEF */ + + [ OP_COUNT ... 255 ] = &&case_default + }; +#define SWITCH(pc) DUMP_BYTECODE_OR_DONT(pc) __extension__ ({ goto *dispatch_table[opcode = *pc++]; }); +#define CASE(op) case_ ## op +#define DEFAULT case_default +#define BREAK SWITCH(pc) +#endif + + if (js_poll_interrupts(caller_ctx)) + return JS_EXCEPTION; + if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) { + if (flags & JS_CALL_FLAG_GENERATOR) { + JSAsyncFunctionState *s = JS_VALUE_GET_PTR(func_obj); + /* func_obj get contains a pointer to JSFuncAsyncState */ + /* the stack frame is already allocated */ + sf = &s->frame; + p = JS_VALUE_GET_OBJ(sf->cur_func); + b = p->u.func.function_bytecode; + ctx = b->realm; + var_refs = p->u.func.var_refs; + local_buf = arg_buf = sf->arg_buf; + var_buf = sf->var_buf; + stack_buf = sf->var_buf + b->var_count; + sp = sf->cur_sp; + sf->cur_sp = NULL; /* cur_sp is NULL if the function is running */ + pc = sf->cur_pc; + sf->prev_frame = rt->current_stack_frame; + rt->current_stack_frame = sf; + if (s->throw_flag) + goto exception; + else + goto restart; + } else { + goto not_a_function; + } + } + p = JS_VALUE_GET_OBJ(func_obj); + if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) { + JSClassCall *call_func; + call_func = rt->class_array[p->class_id].call; + if (!call_func) { + not_a_function: + return JS_ThrowTypeErrorNotAFunction(caller_ctx); + } + return call_func(caller_ctx, func_obj, this_obj, argc, + argv, flags); + } + b = p->u.func.function_bytecode; + + if (unlikely(argc < b->arg_count || (flags & JS_CALL_FLAG_COPY_ARGV))) { + arg_allocated_size = b->arg_count; + } else { + arg_allocated_size = 0; + } + + alloca_size = sizeof(JSValue) * (arg_allocated_size + b->var_count + + b->stack_size) + + sizeof(JSVarRef *) * b->var_ref_count; + if (js_check_stack_overflow(rt, alloca_size)) + return JS_ThrowStackOverflow(caller_ctx); + + sf->is_strict_mode = b->is_strict_mode; + arg_buf = (JSValue *)argv; + sf->arg_count = argc; + sf->cur_func = unsafe_unconst(func_obj); + var_refs = p->u.func.var_refs; + + local_buf = alloca(alloca_size); + if (unlikely(arg_allocated_size)) { + int n = min_int(argc, b->arg_count); + arg_buf = local_buf; + for(i = 0; i < n; i++) + arg_buf[i] = js_dup(argv[i]); + for(; i < b->arg_count; i++) + arg_buf[i] = JS_UNDEFINED; + sf->arg_count = b->arg_count; + } + var_buf = local_buf + arg_allocated_size; + sf->var_buf = var_buf; + sf->arg_buf = arg_buf; + + for(i = 0; i < b->var_count; i++) + var_buf[i] = JS_UNDEFINED; + + stack_buf = var_buf + b->var_count; + sf->var_refs = (JSVarRef **)(stack_buf + b->stack_size); + sf->var_ref_count = b->var_ref_count; + for(i = 0; i < b->var_ref_count; i++) + sf->var_refs[i] = NULL; + sp = stack_buf; + pc = b->byte_code_buf; + /* sf->cur_pc must we set to pc before any recursive calls to JS_CallInternal. */ + sf->cur_pc = NULL; + sf->prev_frame = rt->current_stack_frame; + rt->current_stack_frame = sf; + ctx = b->realm; /* set the current realm */ + +#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STEP + if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STEP)) + print_func_name(b); +#endif + + restart: + for(;;) { + int call_argc; + JSValue *call_argv; + + SWITCH(pc) { + CASE(OP_push_i32): + *sp++ = js_int32(get_u32(pc)); + pc += 4; + BREAK; + CASE(OP_push_bigint_i32): + *sp++ = __JS_NewShortBigInt(ctx, (int)get_u32(pc)); + pc += 4; + BREAK; + CASE(OP_push_const): + *sp++ = js_dup(b->cpool[get_u32(pc)]); + pc += 4; + BREAK; + CASE(OP_push_minus1): + CASE(OP_push_0): + CASE(OP_push_1): + CASE(OP_push_2): + CASE(OP_push_3): + CASE(OP_push_4): + CASE(OP_push_5): + CASE(OP_push_6): + CASE(OP_push_7): + *sp++ = js_int32(opcode - OP_push_0); + BREAK; + CASE(OP_push_i8): + *sp++ = js_int32(get_i8(pc)); + pc += 1; + BREAK; + CASE(OP_push_i16): + *sp++ = js_int32(get_i16(pc)); + pc += 2; + BREAK; + CASE(OP_push_const8): + *sp++ = js_dup(b->cpool[*pc++]); + BREAK; + CASE(OP_fclosure8): + *sp++ = js_closure(ctx, js_dup(b->cpool[*pc++]), var_refs, sf); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + BREAK; + CASE(OP_push_empty_string): + *sp++ = js_empty_string(rt); + BREAK; + CASE(OP_get_length): + { + JSValue val, obj; + JSAtom atom; + JSObject *p; + JSProperty *pr; + JSShapeProperty *prs; + + atom = JS_ATOM_length; + + obj = sp[-1]; + if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT)) { + p = JS_VALUE_GET_OBJ(obj); + for(;;) { + prs = find_own_property(&pr, p, atom); + if (prs) { + /* found */ + if (unlikely(prs->flags & JS_PROP_TMASK)) + goto get_length_slow_path; + val = js_dup(pr->u.value); + break; + } + if (unlikely(p->is_exotic)) { + obj = JS_MKPTR(JS_TAG_OBJECT, p); + goto get_length_slow_path; + } + p = p->shape->proto; + if (!p) { + val = JS_UNDEFINED; + break; + } + } + } else { + get_length_slow_path: + sf->cur_pc = pc; + val = JS_GetPropertyInternal(ctx, obj, atom, sp[-1], false); + if (unlikely(JS_IsException(val))) + goto exception; + } + JS_FreeValue(ctx, sp[-1]); + sp[-1] = val; + } + BREAK; + CASE(OP_push_atom_value): + *sp++ = JS_AtomToValue(ctx, get_u32(pc)); + pc += 4; + BREAK; + CASE(OP_undefined): + *sp++ = JS_UNDEFINED; + BREAK; + CASE(OP_null): + *sp++ = JS_NULL; + BREAK; + CASE(OP_push_this): + /* OP_push_this is only called at the start of a function */ + { + JSValue val; + if (!b->is_strict_mode) { + uint32_t tag = JS_VALUE_GET_TAG(this_obj); + if (likely(tag == JS_TAG_OBJECT)) + goto normal_this; + if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) { + val = js_dup(ctx->global_obj); + } else { + val = JS_ToObject(ctx, this_obj); + if (JS_IsException(val)) + goto exception; + } + } else { + normal_this: + val = js_dup(this_obj); + } + *sp++ = val; + } + BREAK; + CASE(OP_push_false): + *sp++ = JS_FALSE; + BREAK; + CASE(OP_push_true): + *sp++ = JS_TRUE; + BREAK; + CASE(OP_object): + *sp++ = JS_NewObject(ctx); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + BREAK; + CASE(OP_special_object): + { + int arg = *pc++; + switch(arg) { + case OP_SPECIAL_OBJECT_ARGUMENTS: + *sp++ = js_build_arguments(ctx, argc, argv); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + break; + case OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS: + *sp++ = js_build_mapped_arguments(ctx, argc, argv, + sf, min_int(argc, b->arg_count)); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + break; + case OP_SPECIAL_OBJECT_THIS_FUNC: + *sp++ = js_dup(sf->cur_func); + break; + case OP_SPECIAL_OBJECT_NEW_TARGET: + *sp++ = js_dup(new_target); + break; + case OP_SPECIAL_OBJECT_HOME_OBJECT: + { + JSObject *p1; + p1 = p->u.func.home_object; + if (unlikely(!p1)) + *sp++ = JS_UNDEFINED; + else + *sp++ = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1)); + } + break; + case OP_SPECIAL_OBJECT_VAR_OBJECT: + *sp++ = JS_NewObjectProto(ctx, JS_NULL); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + break; + case OP_SPECIAL_OBJECT_IMPORT_META: + *sp++ = js_import_meta(ctx); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + break; + case OP_SPECIAL_OBJECT_NULL_PROTO: + *sp++ = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_OBJECT); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + break; + default: + abort(); + } + } + BREAK; + CASE(OP_rest): + { + int i, n, first = get_u16(pc); + pc += 2; + i = min_int(first, argc); + n = argc - i; + *sp++ = js_create_array(ctx, n, &argv[i]); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + } + BREAK; + + CASE(OP_drop): + JS_FreeValue(ctx, sp[-1]); + sp--; + BREAK; + CASE(OP_nip): + JS_FreeValue(ctx, sp[-2]); + sp[-2] = sp[-1]; + sp--; + BREAK; + CASE(OP_nip1): /* a b c -> b c */ + JS_FreeValue(ctx, sp[-3]); + sp[-3] = sp[-2]; + sp[-2] = sp[-1]; + sp--; + BREAK; + CASE(OP_dup): + sp[0] = js_dup(sp[-1]); + sp++; + BREAK; + CASE(OP_dup2): /* a b -> a b a b */ + sp[0] = js_dup(sp[-2]); + sp[1] = js_dup(sp[-1]); + sp += 2; + BREAK; + CASE(OP_dup3): /* a b c -> a b c a b c */ + sp[0] = js_dup(sp[-3]); + sp[1] = js_dup(sp[-2]); + sp[2] = js_dup(sp[-1]); + sp += 3; + BREAK; + CASE(OP_dup1): /* a b -> a a b */ + sp[0] = sp[-1]; + sp[-1] = js_dup(sp[-2]); + sp++; + BREAK; + CASE(OP_insert2): /* obj a -> a obj a (dup_x1) */ + sp[0] = sp[-1]; + sp[-1] = sp[-2]; + sp[-2] = js_dup(sp[0]); + sp++; + BREAK; + CASE(OP_insert3): /* obj prop a -> a obj prop a (dup_x2) */ + sp[0] = sp[-1]; + sp[-1] = sp[-2]; + sp[-2] = sp[-3]; + sp[-3] = js_dup(sp[0]); + sp++; + BREAK; + CASE(OP_insert4): /* this obj prop a -> a this obj prop a */ + sp[0] = sp[-1]; + sp[-1] = sp[-2]; + sp[-2] = sp[-3]; + sp[-3] = sp[-4]; + sp[-4] = js_dup(sp[0]); + sp++; + BREAK; + CASE(OP_perm3): /* obj a b -> a obj b (213) */ + { + JSValue tmp; + tmp = sp[-2]; + sp[-2] = sp[-3]; + sp[-3] = tmp; + } + BREAK; + CASE(OP_rot3l): /* x a b -> a b x (231) */ + { + JSValue tmp; + tmp = sp[-3]; + sp[-3] = sp[-2]; + sp[-2] = sp[-1]; + sp[-1] = tmp; + } + BREAK; + CASE(OP_rot4l): /* x a b c -> a b c x */ + { + JSValue tmp; + tmp = sp[-4]; + sp[-4] = sp[-3]; + sp[-3] = sp[-2]; + sp[-2] = sp[-1]; + sp[-1] = tmp; + } + BREAK; + CASE(OP_rot5l): /* x a b c d -> a b c d x */ + { + JSValue tmp; + tmp = sp[-5]; + sp[-5] = sp[-4]; + sp[-4] = sp[-3]; + sp[-3] = sp[-2]; + sp[-2] = sp[-1]; + sp[-1] = tmp; + } + BREAK; + CASE(OP_rot3r): /* a b x -> x a b (312) */ + { + JSValue tmp; + tmp = sp[-1]; + sp[-1] = sp[-2]; + sp[-2] = sp[-3]; + sp[-3] = tmp; + } + BREAK; + CASE(OP_perm4): /* obj prop a b -> a obj prop b */ + { + JSValue tmp; + tmp = sp[-2]; + sp[-2] = sp[-3]; + sp[-3] = sp[-4]; + sp[-4] = tmp; + } + BREAK; + CASE(OP_perm5): /* this obj prop a b -> a this obj prop b */ + { + JSValue tmp; + tmp = sp[-2]; + sp[-2] = sp[-3]; + sp[-3] = sp[-4]; + sp[-4] = sp[-5]; + sp[-5] = tmp; + } + BREAK; + CASE(OP_swap): /* a b -> b a */ + { + JSValue tmp; + tmp = sp[-2]; + sp[-2] = sp[-1]; + sp[-1] = tmp; + } + BREAK; + CASE(OP_swap2): /* a b c d -> c d a b */ + { + JSValue tmp1, tmp2; + tmp1 = sp[-4]; + tmp2 = sp[-3]; + sp[-4] = sp[-2]; + sp[-3] = sp[-1]; + sp[-2] = tmp1; + sp[-1] = tmp2; + } + BREAK; + + CASE(OP_fclosure): + { + JSValue bfunc = js_dup(b->cpool[get_u32(pc)]); + pc += 4; + *sp++ = js_closure(ctx, bfunc, var_refs, sf); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + } + BREAK; + CASE(OP_call0): + CASE(OP_call1): + CASE(OP_call2): + CASE(OP_call3): + call_argc = opcode - OP_call0; + goto has_call_argc; + CASE(OP_call): + CASE(OP_tail_call): + { + call_argc = get_u16(pc); + pc += 2; + goto has_call_argc; + has_call_argc: + call_argv = sp - call_argc; + sf->cur_pc = pc; + ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED, + JS_UNDEFINED, call_argc, + vc(call_argv), 0); + if (unlikely(JS_IsException(ret_val))) + goto exception; + if (opcode == OP_tail_call) + goto done; + for(i = -1; i < call_argc; i++) + JS_FreeValue(ctx, call_argv[i]); + sp -= call_argc + 1; + *sp++ = ret_val; + } + BREAK; + CASE(OP_call_constructor): + { + call_argc = get_u16(pc); + pc += 2; + call_argv = sp - call_argc; + sf->cur_pc = pc; + ret_val = JS_CallConstructorInternal(ctx, call_argv[-2], + call_argv[-1], call_argc, + vc(call_argv), 0); + if (unlikely(JS_IsException(ret_val))) + goto exception; + for(i = -2; i < call_argc; i++) + JS_FreeValue(ctx, call_argv[i]); + sp -= call_argc + 2; + *sp++ = ret_val; + } + BREAK; + CASE(OP_call_method): + CASE(OP_tail_call_method): + { + call_argc = get_u16(pc); + pc += 2; + call_argv = sp - call_argc; + sf->cur_pc = pc; + ret_val = JS_CallInternal(ctx, call_argv[-1], call_argv[-2], + JS_UNDEFINED, call_argc, + vc(call_argv), 0); + if (unlikely(JS_IsException(ret_val))) + goto exception; + if (opcode == OP_tail_call_method) + goto done; + for(i = -2; i < call_argc; i++) + JS_FreeValue(ctx, call_argv[i]); + sp -= call_argc + 2; + *sp++ = ret_val; + } + BREAK; + CASE(OP_array_from): + { + call_argc = get_u16(pc); + pc += 2; + call_argv = sp - call_argc; + ret_val = JS_NewArrayFrom(ctx, call_argc, call_argv); + sp -= call_argc; + if (unlikely(JS_IsException(ret_val))) + goto exception; + *sp++ = ret_val; + } + BREAK; + + CASE(OP_apply): + { + int magic; + magic = get_u16(pc); + pc += 2; + sf->cur_pc = pc; + + ret_val = js_function_apply(ctx, sp[-3], 2, vc(&sp[-2]), magic); + if (unlikely(JS_IsException(ret_val))) + goto exception; + JS_FreeValue(ctx, sp[-3]); + JS_FreeValue(ctx, sp[-2]); + JS_FreeValue(ctx, sp[-1]); + sp -= 3; + *sp++ = ret_val; + } + BREAK; + CASE(OP_return): + ret_val = *--sp; + goto done; + CASE(OP_return_undef): + ret_val = JS_UNDEFINED; + goto done; + + CASE(OP_check_ctor_return): + /* return true if 'this' should be returned */ + if (!JS_IsObject(sp[-1])) { + if (!JS_IsUndefined(sp[-1])) { + JS_ThrowTypeError(caller_ctx, "derived class constructor must return an object or undefined"); + goto exception; + } + sp[0] = JS_TRUE; + } else { + sp[0] = JS_FALSE; + } + sp++; + BREAK; + CASE(OP_check_ctor): + if (JS_IsUndefined(new_target)) { + non_ctor_call: + JS_ThrowTypeError(ctx, "class constructors must be invoked with 'new'"); + goto exception; + } + BREAK; + CASE(OP_init_ctor): + { + JSValue super, ret; + sf->cur_pc = pc; + if (JS_IsUndefined(new_target)) + goto non_ctor_call; + super = JS_GetPrototype(ctx, func_obj); + if (JS_IsException(super)) + goto exception; + ret = JS_CallConstructor2(ctx, super, new_target, argc, argv); + JS_FreeValue(ctx, super); + if (JS_IsException(ret)) + goto exception; + *sp++ = ret; + } + BREAK; + CASE(OP_check_brand): + { + int ret = JS_CheckBrand(ctx, sp[-2], sp[-1]); + if (ret < 0) + goto exception; + if (!ret) { + JS_ThrowTypeError(ctx, "invalid brand on object"); + goto exception; + } + } + BREAK; + CASE(OP_add_brand): + if (JS_AddBrand(ctx, sp[-2], sp[-1]) < 0) + goto exception; + JS_FreeValue(ctx, sp[-2]); + JS_FreeValue(ctx, sp[-1]); + sp -= 2; + BREAK; + + CASE(OP_throw): + JS_Throw(ctx, *--sp); + goto exception; + + CASE(OP_throw_error): +#define JS_THROW_VAR_RO 0 +#define JS_THROW_VAR_REDECL 1 +#define JS_THROW_VAR_UNINITIALIZED 2 +#define JS_THROW_ERROR_DELETE_SUPER 3 +#define JS_THROW_ERROR_ITERATOR_THROW 4 + { + JSAtom atom; + int type; + atom = get_u32(pc); + type = pc[4]; + pc += 5; + if (type == JS_THROW_VAR_RO) + JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, atom); + else + if (type == JS_THROW_VAR_REDECL) + JS_ThrowSyntaxErrorVarRedeclaration(ctx, atom); + else + if (type == JS_THROW_VAR_UNINITIALIZED) + JS_ThrowReferenceErrorUninitialized(ctx, atom); + else + if (type == JS_THROW_ERROR_DELETE_SUPER) + JS_ThrowReferenceError(ctx, "unsupported reference to 'super'"); + else + if (type == JS_THROW_ERROR_ITERATOR_THROW) + JS_ThrowTypeError(ctx, "iterator does not have a throw method"); + else + JS_ThrowInternalError(ctx, "invalid throw var type %d", type); + } + goto exception; + + CASE(OP_eval): + { + JSValue obj; + int scope_idx; + call_argc = get_u16(pc); + scope_idx = get_u16(pc + 2) - 1; + pc += 4; + call_argv = sp - call_argc; + sf->cur_pc = pc; + if (js_same_value(ctx, call_argv[-1], ctx->eval_obj)) { + if (call_argc >= 1) + obj = call_argv[0]; + else + obj = JS_UNDEFINED; + ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj, + JS_EVAL_TYPE_DIRECT, scope_idx); + } else { + ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED, + JS_UNDEFINED, call_argc, + vc(call_argv), 0); + } + if (unlikely(JS_IsException(ret_val))) + goto exception; + for(i = -1; i < call_argc; i++) + JS_FreeValue(ctx, call_argv[i]); + sp -= call_argc + 1; + *sp++ = ret_val; + } + BREAK; + /* could merge with OP_apply */ + CASE(OP_apply_eval): + { + int scope_idx; + uint32_t len; + JSValue *tab; + JSValue obj; + + scope_idx = get_u16(pc) - 1; + pc += 2; + sf->cur_pc = pc; + tab = build_arg_list(ctx, &len, sp[-1]); + if (!tab) + goto exception; + if (js_same_value(ctx, sp[-2], ctx->eval_obj)) { + if (len >= 1) + obj = tab[0]; + else + obj = JS_UNDEFINED; + ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj, + JS_EVAL_TYPE_DIRECT, scope_idx); + } else { + ret_val = JS_Call(ctx, sp[-2], JS_UNDEFINED, len, vc(tab)); + } + free_arg_list(ctx, tab, len); + if (unlikely(JS_IsException(ret_val))) + goto exception; + JS_FreeValue(ctx, sp[-2]); + JS_FreeValue(ctx, sp[-1]); + sp -= 2; + *sp++ = ret_val; + } + BREAK; + + CASE(OP_regexp): + { + sp[-2] = js_regexp_constructor_internal(ctx, JS_UNDEFINED, + sp[-2], sp[-1]); + sp--; + } + BREAK; + + CASE(OP_get_super): + { + JSValue proto; + proto = JS_GetPrototype(ctx, sp[-1]); + if (JS_IsException(proto)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = proto; + } + BREAK; + + CASE(OP_import): + { + JSValue val; + sf->cur_pc = pc; + val = js_dynamic_import(ctx, sp[-2], sp[-1]); + if (JS_IsException(val)) + goto exception; + JS_FreeValue(ctx, sp[-2]); + JS_FreeValue(ctx, sp[-1]); + sp--; + sp[-1] = val; + } + BREAK; + + CASE(OP_get_var_undef): + CASE(OP_get_var): + { + JSValue val; + JSAtom atom; + atom = get_u32(pc); + pc += 4; + sf->cur_pc = pc; + + val = JS_GetGlobalVar(ctx, atom, opcode - OP_get_var_undef); + if (unlikely(JS_IsException(val))) + goto exception; + *sp++ = val; + } + BREAK; + + CASE(OP_put_var): + CASE(OP_put_var_init): + { + int ret; + JSAtom atom; + atom = get_u32(pc); + pc += 4; + sf->cur_pc = pc; + + ret = JS_SetGlobalVar(ctx, atom, sp[-1], opcode - OP_put_var); + sp--; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_check_define_var): + { + JSAtom atom; + int flags; + atom = get_u32(pc); + flags = pc[4]; + pc += 5; + if (JS_CheckDefineGlobalVar(ctx, atom, flags)) + goto exception; + } + BREAK; + CASE(OP_define_var): + { + JSAtom atom; + int flags; + atom = get_u32(pc); + flags = pc[4]; + pc += 5; + if (JS_DefineGlobalVar(ctx, atom, flags)) + goto exception; + } + BREAK; + CASE(OP_define_func): + { + JSAtom atom; + int flags; + atom = get_u32(pc); + flags = pc[4]; + pc += 5; + if (JS_DefineGlobalFunction(ctx, atom, sp[-1], flags)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp--; + } + BREAK; + + CASE(OP_get_loc): + { + int idx; + idx = get_u16(pc); + pc += 2; + sp[0] = js_dup(var_buf[idx]); + sp++; + } + BREAK; + CASE(OP_put_loc): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, &var_buf[idx], sp[-1]); + sp--; + } + BREAK; + CASE(OP_set_loc): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, &var_buf[idx], js_dup(sp[-1])); + } + BREAK; + CASE(OP_get_arg): + { + int idx; + idx = get_u16(pc); + pc += 2; + sp[0] = js_dup(arg_buf[idx]); + sp++; + } + BREAK; + CASE(OP_put_arg): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, &arg_buf[idx], sp[-1]); + sp--; + } + BREAK; + CASE(OP_set_arg): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, &arg_buf[idx], js_dup(sp[-1])); + } + BREAK; + + CASE(OP_get_loc8): *sp++ = js_dup(var_buf[*pc++]); BREAK; + CASE(OP_put_loc8): set_value(ctx, &var_buf[*pc++], *--sp); BREAK; + CASE(OP_set_loc8): set_value(ctx, &var_buf[*pc++], js_dup(sp[-1])); BREAK; + + // Observation: get_loc0 and get_loc1 are individually very + // frequent opcodes _and_ they are very often paired together, + // making them ideal candidates for opcode fusion. + CASE(OP_get_loc0_loc1): + *sp++ = js_dup(var_buf[0]); + *sp++ = js_dup(var_buf[1]); + BREAK; + + CASE(OP_get_loc0): *sp++ = js_dup(var_buf[0]); BREAK; + CASE(OP_get_loc1): *sp++ = js_dup(var_buf[1]); BREAK; + CASE(OP_get_loc2): *sp++ = js_dup(var_buf[2]); BREAK; + CASE(OP_get_loc3): *sp++ = js_dup(var_buf[3]); BREAK; + CASE(OP_put_loc0): set_value(ctx, &var_buf[0], *--sp); BREAK; + CASE(OP_put_loc1): set_value(ctx, &var_buf[1], *--sp); BREAK; + CASE(OP_put_loc2): set_value(ctx, &var_buf[2], *--sp); BREAK; + CASE(OP_put_loc3): set_value(ctx, &var_buf[3], *--sp); BREAK; + CASE(OP_set_loc0): set_value(ctx, &var_buf[0], js_dup(sp[-1])); BREAK; + CASE(OP_set_loc1): set_value(ctx, &var_buf[1], js_dup(sp[-1])); BREAK; + CASE(OP_set_loc2): set_value(ctx, &var_buf[2], js_dup(sp[-1])); BREAK; + CASE(OP_set_loc3): set_value(ctx, &var_buf[3], js_dup(sp[-1])); BREAK; + CASE(OP_get_arg0): *sp++ = js_dup(arg_buf[0]); BREAK; + CASE(OP_get_arg1): *sp++ = js_dup(arg_buf[1]); BREAK; + CASE(OP_get_arg2): *sp++ = js_dup(arg_buf[2]); BREAK; + CASE(OP_get_arg3): *sp++ = js_dup(arg_buf[3]); BREAK; + CASE(OP_put_arg0): set_value(ctx, &arg_buf[0], *--sp); BREAK; + CASE(OP_put_arg1): set_value(ctx, &arg_buf[1], *--sp); BREAK; + CASE(OP_put_arg2): set_value(ctx, &arg_buf[2], *--sp); BREAK; + CASE(OP_put_arg3): set_value(ctx, &arg_buf[3], *--sp); BREAK; + CASE(OP_set_arg0): set_value(ctx, &arg_buf[0], js_dup(sp[-1])); BREAK; + CASE(OP_set_arg1): set_value(ctx, &arg_buf[1], js_dup(sp[-1])); BREAK; + CASE(OP_set_arg2): set_value(ctx, &arg_buf[2], js_dup(sp[-1])); BREAK; + CASE(OP_set_arg3): set_value(ctx, &arg_buf[3], js_dup(sp[-1])); BREAK; + CASE(OP_get_var_ref0): *sp++ = js_dup(*var_refs[0]->pvalue); BREAK; + CASE(OP_get_var_ref1): *sp++ = js_dup(*var_refs[1]->pvalue); BREAK; + CASE(OP_get_var_ref2): *sp++ = js_dup(*var_refs[2]->pvalue); BREAK; + CASE(OP_get_var_ref3): *sp++ = js_dup(*var_refs[3]->pvalue); BREAK; + CASE(OP_put_var_ref0): set_value(ctx, var_refs[0]->pvalue, *--sp); BREAK; + CASE(OP_put_var_ref1): set_value(ctx, var_refs[1]->pvalue, *--sp); BREAK; + CASE(OP_put_var_ref2): set_value(ctx, var_refs[2]->pvalue, *--sp); BREAK; + CASE(OP_put_var_ref3): set_value(ctx, var_refs[3]->pvalue, *--sp); BREAK; + CASE(OP_set_var_ref0): set_value(ctx, var_refs[0]->pvalue, js_dup(sp[-1])); BREAK; + CASE(OP_set_var_ref1): set_value(ctx, var_refs[1]->pvalue, js_dup(sp[-1])); BREAK; + CASE(OP_set_var_ref2): set_value(ctx, var_refs[2]->pvalue, js_dup(sp[-1])); BREAK; + CASE(OP_set_var_ref3): set_value(ctx, var_refs[3]->pvalue, js_dup(sp[-1])); BREAK; + + CASE(OP_get_var_ref): + { + int idx; + JSValue val; + idx = get_u16(pc); + pc += 2; + val = *var_refs[idx]->pvalue; + sp[0] = js_dup(val); + sp++; + } + BREAK; + CASE(OP_put_var_ref): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, var_refs[idx]->pvalue, sp[-1]); + sp--; + } + BREAK; + CASE(OP_set_var_ref): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, var_refs[idx]->pvalue, js_dup(sp[-1])); + } + BREAK; + CASE(OP_get_var_ref_check): + { + int idx; + JSValue val; + idx = get_u16(pc); + pc += 2; + val = *var_refs[idx]->pvalue; + if (unlikely(JS_IsUninitialized(val))) { + JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true); + goto exception; + } + sp[0] = js_dup(val); + sp++; + } + BREAK; + CASE(OP_put_var_ref_check): + { + int idx; + idx = get_u16(pc); + pc += 2; + if (unlikely(JS_IsUninitialized(*var_refs[idx]->pvalue))) { + JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true); + goto exception; + } + set_value(ctx, var_refs[idx]->pvalue, sp[-1]); + sp--; + } + BREAK; + CASE(OP_put_var_ref_check_init): + { + int idx; + idx = get_u16(pc); + pc += 2; + if (unlikely(!JS_IsUninitialized(*var_refs[idx]->pvalue))) { + JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true); + goto exception; + } + set_value(ctx, var_refs[idx]->pvalue, sp[-1]); + sp--; + } + BREAK; + CASE(OP_set_loc_uninitialized): + { + int idx; + idx = get_u16(pc); + pc += 2; + set_value(ctx, &var_buf[idx], JS_UNINITIALIZED); + } + BREAK; + CASE(OP_get_loc_check): + { + int idx; + idx = get_u16(pc); + pc += 2; + if (unlikely(JS_IsUninitialized(var_buf[idx]))) { + JS_ThrowReferenceErrorUninitialized2(caller_ctx, b, idx, + false); + goto exception; + } + sp[0] = js_dup(var_buf[idx]); + sp++; + } + BREAK; + CASE(OP_put_loc_check): + { + int idx; + idx = get_u16(pc); + pc += 2; + if (unlikely(JS_IsUninitialized(var_buf[idx]))) { + JS_ThrowReferenceErrorUninitialized2(caller_ctx, b, idx, + false); + goto exception; + } + set_value(ctx, &var_buf[idx], sp[-1]); + sp--; + } + BREAK; + CASE(OP_put_loc_check_init): + { + int idx; + idx = get_u16(pc); + pc += 2; + if (unlikely(!JS_IsUninitialized(var_buf[idx]))) { + JS_ThrowReferenceError(caller_ctx, + "'this' can be initialized only once"); + goto exception; + } + set_value(ctx, &var_buf[idx], sp[-1]); + sp--; + } + BREAK; + CASE(OP_close_loc): + { + int idx; + idx = get_u16(pc); + pc += 2; + close_lexical_var(ctx, b, sf, idx); + } + BREAK; + + CASE(OP_make_loc_ref): + CASE(OP_make_arg_ref): + CASE(OP_make_var_ref_ref): + { + JSVarRef *var_ref; + JSProperty *pr; + JSAtom atom; + int idx; + atom = get_u32(pc); + idx = get_u16(pc + 4); + pc += 6; + *sp++ = JS_NewObjectProto(ctx, JS_NULL); + if (unlikely(JS_IsException(sp[-1]))) + goto exception; + if (opcode == OP_make_var_ref_ref) { + var_ref = var_refs[idx]; + var_ref->header.ref_count++; + } else { + var_ref = get_var_ref(ctx, sf, idx, opcode == OP_make_arg_ref); + if (!var_ref) + goto exception; + } + pr = add_property(ctx, JS_VALUE_GET_OBJ(sp[-1]), atom, + JS_PROP_WRITABLE | JS_PROP_VARREF); + if (!pr) { + free_var_ref(rt, var_ref); + goto exception; + } + pr->u.var_ref = var_ref; + *sp++ = JS_AtomToValue(ctx, atom); + } + BREAK; + CASE(OP_make_var_ref): + { + JSAtom atom; + atom = get_u32(pc); + pc += 4; + + if (JS_GetGlobalVarRef(ctx, atom, sp)) + goto exception; + sp += 2; + } + BREAK; + + CASE(OP_goto): + pc += (int32_t)get_u32(pc); + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + BREAK; + CASE(OP_goto16): + pc += (int16_t)get_u16(pc); + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + BREAK; + CASE(OP_goto8): + pc += (int8_t)pc[0]; + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + BREAK; + CASE(OP_if_true): + { + int res; + JSValue op1; + + op1 = sp[-1]; + pc += 4; + if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { + res = JS_VALUE_GET_INT(op1); + } else { + res = JS_ToBoolFree(ctx, op1); + } + sp--; + if (res) { + pc += (int32_t)get_u32(pc - 4) - 4; + } + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + } + BREAK; + CASE(OP_if_false): + { + int res; + JSValue op1; + + op1 = sp[-1]; + pc += 4; + if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { + res = JS_VALUE_GET_INT(op1); + } else { + res = JS_ToBoolFree(ctx, op1); + } + sp--; + if (!res) { + pc += (int32_t)get_u32(pc - 4) - 4; + } + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + } + BREAK; + CASE(OP_if_true8): + { + int res; + JSValue op1; + + op1 = sp[-1]; + pc += 1; + if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { + res = JS_VALUE_GET_INT(op1); + } else { + res = JS_ToBoolFree(ctx, op1); + } + sp--; + if (res) { + pc += (int8_t)pc[-1] - 1; + } + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + } + BREAK; + CASE(OP_if_false8): + { + int res; + JSValue op1; + + op1 = sp[-1]; + pc += 1; + if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { + res = JS_VALUE_GET_INT(op1); + } else { + res = JS_ToBoolFree(ctx, op1); + } + sp--; + if (!res) { + pc += (int8_t)pc[-1] - 1; + } + if (unlikely(js_poll_interrupts(ctx))) + goto exception; + } + BREAK; + CASE(OP_catch): + { + int32_t diff; + diff = get_u32(pc); + sp[0] = JS_NewCatchOffset(ctx, pc + diff - b->byte_code_buf); + sp++; + pc += 4; + } + BREAK; + CASE(OP_gosub): + { + int32_t diff; + diff = get_u32(pc); + /* XXX: should have a different tag to avoid security flaw */ + sp[0] = js_int32(pc + 4 - b->byte_code_buf); + sp++; + pc += diff; + } + BREAK; + CASE(OP_ret): + { + JSValue op1; + uint32_t pos; + op1 = sp[-1]; + if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_INT)) + goto ret_fail; + pos = JS_VALUE_GET_INT(op1); + if (unlikely(pos >= b->byte_code_len)) { + ret_fail: + JS_ThrowInternalError(ctx, "invalid ret value"); + goto exception; + } + sp--; + pc = b->byte_code_buf + pos; + } + BREAK; + + CASE(OP_for_in_start): + sf->cur_pc = pc; + if (js_for_in_start(ctx, sp)) + goto exception; + BREAK; + CASE(OP_for_in_next): + sf->cur_pc = pc; + if (js_for_in_next(ctx, sp)) + goto exception; + sp += 2; + BREAK; + CASE(OP_for_of_start): + sf->cur_pc = pc; + if (js_for_of_start(ctx, sp, false)) + goto exception; + sp += 1; + *sp++ = JS_NewCatchOffset(ctx, 0); + BREAK; + CASE(OP_for_of_next): + { + int offset = -3 - pc[0]; + pc += 1; + sf->cur_pc = pc; + if (js_for_of_next(ctx, sp, offset)) + goto exception; + sp += 2; + } + BREAK; + CASE(OP_for_await_of_start): + sf->cur_pc = pc; + if (js_for_of_start(ctx, sp, true)) + goto exception; + sp += 1; + *sp++ = JS_NewCatchOffset(ctx, 0); + BREAK; + CASE(OP_iterator_get_value_done): + sf->cur_pc = pc; + if (js_iterator_get_value_done(ctx, sp)) + goto exception; + sp += 1; + BREAK; + CASE(OP_iterator_check_object): + if (unlikely(!JS_IsObject(sp[-1]))) { + JS_ThrowTypeError(ctx, "iterator must return an object"); + goto exception; + } + BREAK; + + CASE(OP_iterator_close): + /* iter_obj next catch_offset -> */ + sp--; /* drop the catch offset to avoid getting caught by exception */ + JS_FreeValue(ctx, sp[-1]); /* drop the next method */ + sp--; + if (!JS_IsUndefined(sp[-1])) { + sf->cur_pc = pc; + if (JS_IteratorClose(ctx, sp[-1], false)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + } + sp--; + BREAK; + CASE(OP_nip_catch): + { + JSValue ret_val; + /* catch_offset ... ret_val -> ret_eval */ + ret_val = *--sp; + while (sp > stack_buf && + JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_CATCH_OFFSET) { + JS_FreeValue(ctx, *--sp); + } + if (unlikely(sp == stack_buf)) { + JS_ThrowInternalError(ctx, "nip_catch"); + JS_FreeValue(ctx, ret_val); + goto exception; + } + sp[-1] = ret_val; + } + BREAK; + + CASE(OP_iterator_next): + /* stack: iter_obj next catch_offset val */ + { + JSValue ret; + sf->cur_pc = pc; + ret = JS_Call(ctx, sp[-3], sp[-4], 1, vc(sp - 1)); + if (JS_IsException(ret)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = ret; + } + BREAK; + + CASE(OP_iterator_call): + /* stack: iter_obj next catch_offset val */ + { + JSValue method, ret; + bool ret_flag; + int flags; + flags = *pc++; + sf->cur_pc = pc; + method = JS_GetProperty(ctx, sp[-4], (flags & 1) ? + JS_ATOM_throw : JS_ATOM_return); + if (JS_IsException(method)) + goto exception; + if (JS_IsUndefined(method) || JS_IsNull(method)) { + ret_flag = true; + } else { + if (flags & 2) { + /* no argument */ + ret = JS_CallFree(ctx, method, sp[-4], + 0, NULL); + } else { + ret = JS_CallFree(ctx, method, sp[-4], + 1, vc(sp - 1)); + } + if (JS_IsException(ret)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = ret; + ret_flag = false; + } + sp[0] = js_bool(ret_flag); + sp += 1; + } + BREAK; + + CASE(OP_lnot): + { + int res; + JSValue op1; + + op1 = sp[-1]; + if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { + res = JS_VALUE_GET_INT(op1) != 0; + } else { + res = JS_ToBoolFree(ctx, op1); + } + sp[-1] = js_bool(!res); + } + BREAK; + + CASE(OP_get_field): + { + JSValue val, obj; + JSAtom atom; + JSObject *p; + JSProperty *pr; + JSShapeProperty *prs; + + atom = get_u32(pc); + pc += 4; + + obj = sp[-1]; + if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT)) { + p = JS_VALUE_GET_OBJ(obj); + for(;;) { + prs = find_own_property(&pr, p, atom); + if (prs) { + /* found */ + if (unlikely(prs->flags & JS_PROP_TMASK)) + goto get_field_slow_path; + val = js_dup(pr->u.value); + break; + } + if (unlikely(p->is_exotic)) { + /* XXX: should avoid the slow path for arrays + and typed arrays by ensuring that 'prop' is + not numeric */ + obj = JS_MKPTR(JS_TAG_OBJECT, p); + goto get_field_slow_path; + } + p = p->shape->proto; + if (!p) { + val = JS_UNDEFINED; + break; + } + } + } else { + get_field_slow_path: + sf->cur_pc = pc; + val = JS_GetPropertyInternal(ctx, obj, atom, sp[-1], false); + if (unlikely(JS_IsException(val))) + goto exception; + } + JS_FreeValue(ctx, sp[-1]); + sp[-1] = val; + } + BREAK; + + CASE(OP_get_field2): + { + JSValue val, obj; + JSAtom atom; + JSObject *p; + JSProperty *pr; + JSShapeProperty *prs; + + atom = get_u32(pc); + pc += 4; + + obj = sp[-1]; + if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT)) { + p = JS_VALUE_GET_OBJ(obj); + for(;;) { + prs = find_own_property(&pr, p, atom); + if (prs) { + /* found */ + if (unlikely(prs->flags & JS_PROP_TMASK)) + goto get_field2_slow_path; + val = js_dup(pr->u.value); + break; + } + if (unlikely(p->is_exotic)) { + /* XXX: should avoid the slow path for arrays + and typed arrays by ensuring that 'prop' is + not numeric */ + obj = JS_MKPTR(JS_TAG_OBJECT, p); + goto get_field2_slow_path; + } + p = p->shape->proto; + if (!p) { + val = JS_UNDEFINED; + break; + } + } + } else { + get_field2_slow_path: + sf->cur_pc = pc; + val = JS_GetPropertyInternal(ctx, obj, atom, sp[-1], false); + if (unlikely(JS_IsException(val))) + goto exception; + } + *sp++ = val; + } + BREAK; + + CASE(OP_put_field): + { + int ret; + JSValue obj; + JSAtom atom; + JSObject *p; + JSProperty *pr; + JSShapeProperty *prs; + + atom = get_u32(pc); + pc += 4; + + obj = sp[-2]; + if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT)) { + p = JS_VALUE_GET_OBJ(obj); + prs = find_own_property(&pr, p, atom); + if (!prs) + goto put_field_slow_path; + if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE | + JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) { + /* fast path */ + set_value(ctx, &pr->u.value, sp[-1]); + } else { + goto put_field_slow_path; + } + JS_FreeValue(ctx, obj); + sp -= 2; + } else { + put_field_slow_path: + sf->cur_pc = pc; + ret = JS_SetPropertyInternal2(ctx, obj, atom, sp[-1], obj, + JS_PROP_THROW_STRICT); + JS_FreeValue(ctx, obj); + sp -= 2; + if (unlikely(ret < 0)) + goto exception; + } + } + BREAK; + + CASE(OP_private_symbol): + { + JSAtom atom; + JSValue val; + + atom = get_u32(pc); + pc += 4; + val = JS_NewSymbolFromAtom(ctx, atom, JS_ATOM_TYPE_PRIVATE); + if (JS_IsException(val)) + goto exception; + *sp++ = val; + } + BREAK; + + CASE(OP_get_private_field): + { + JSValue val; + sf->cur_pc = pc; + val = JS_GetPrivateField(ctx, sp[-2], sp[-1]); + JS_FreeValue(ctx, sp[-1]); + JS_FreeValue(ctx, sp[-2]); + sp[-2] = val; + sp--; + if (unlikely(JS_IsException(val))) + goto exception; + } + BREAK; + + CASE(OP_put_private_field): + { + int ret; + sf->cur_pc = pc; + ret = JS_SetPrivateField(ctx, sp[-3], sp[-1], sp[-2]); + JS_FreeValue(ctx, sp[-3]); + JS_FreeValue(ctx, sp[-1]); + sp -= 3; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_define_private_field): + { + int ret; + ret = JS_DefinePrivateField(ctx, sp[-3], sp[-2], sp[-1]); + JS_FreeValue(ctx, sp[-2]); + sp -= 2; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_define_field): + { + int ret; + JSAtom atom; + atom = get_u32(pc); + pc += 4; + + ret = JS_DefinePropertyValue(ctx, sp[-2], atom, sp[-1], + JS_PROP_C_W_E | JS_PROP_THROW); + sp--; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_set_name): + { + int ret; + JSAtom atom; + atom = get_u32(pc); + pc += 4; + + ret = JS_DefineObjectName(ctx, sp[-1], atom, JS_PROP_CONFIGURABLE); + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + CASE(OP_set_name_computed): + { + int ret; + ret = JS_DefineObjectNameComputed(ctx, sp[-1], sp[-2], JS_PROP_CONFIGURABLE); + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + CASE(OP_set_proto): + { + JSValue proto; + proto = sp[-1]; + if (JS_IsObject(proto) || JS_IsNull(proto)) { + if (JS_SetPrototypeInternal(ctx, sp[-2], proto, true) < 0) + goto exception; + } + JS_FreeValue(ctx, proto); + sp--; + } + BREAK; + CASE(OP_set_home_object): + js_method_set_home_object(ctx, sp[-1], sp[-2]); + BREAK; + CASE(OP_define_method): + CASE(OP_define_method_computed): + { + JSValue getter, setter, value; + JSValue obj; + JSAtom atom; + int flags, ret, op_flags; + bool is_computed; +#define OP_DEFINE_METHOD_METHOD 0 +#define OP_DEFINE_METHOD_GETTER 1 +#define OP_DEFINE_METHOD_SETTER 2 +#define OP_DEFINE_METHOD_ENUMERABLE 4 + + is_computed = (opcode == OP_define_method_computed); + if (is_computed) { + atom = JS_ValueToAtom(ctx, sp[-2]); + if (unlikely(atom == JS_ATOM_NULL)) + goto exception; + opcode += OP_define_method - OP_define_method_computed; + } else { + atom = get_u32(pc); + pc += 4; + } + op_flags = *pc++; + + obj = sp[-2 - is_computed]; + flags = JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE | + JS_PROP_HAS_ENUMERABLE | JS_PROP_THROW; + if (op_flags & OP_DEFINE_METHOD_ENUMERABLE) + flags |= JS_PROP_ENUMERABLE; + op_flags &= 3; + value = JS_UNDEFINED; + getter = JS_UNDEFINED; + setter = JS_UNDEFINED; + if (op_flags == OP_DEFINE_METHOD_METHOD) { + value = sp[-1]; + flags |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE; + } else if (op_flags == OP_DEFINE_METHOD_GETTER) { + getter = sp[-1]; + flags |= JS_PROP_HAS_GET; + } else { + setter = sp[-1]; + flags |= JS_PROP_HAS_SET; + } + ret = js_method_set_properties(ctx, sp[-1], atom, flags, obj); + if (ret >= 0) { + ret = JS_DefineProperty(ctx, obj, atom, value, + getter, setter, flags); + } + JS_FreeValue(ctx, sp[-1]); + if (is_computed) { + JS_FreeAtom(ctx, atom); + JS_FreeValue(ctx, sp[-2]); + } + sp -= 1 + is_computed; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_define_class): + CASE(OP_define_class_computed): + { + int class_flags; + JSAtom atom; + + atom = get_u32(pc); + class_flags = pc[4]; + pc += 5; + if (js_op_define_class(ctx, sp, atom, class_flags, + var_refs, sf, + (opcode == OP_define_class_computed)) < 0) + goto exception; + } + BREAK; + + CASE(OP_get_array_el): + { + JSValue val; + + sf->cur_pc = pc; + val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]); + JS_FreeValue(ctx, sp[-2]); + sp[-2] = val; + sp--; + if (unlikely(JS_IsException(val))) + goto exception; + } + BREAK; + + CASE(OP_get_array_el2): + { + JSValue val; + + sf->cur_pc = pc; + val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]); + sp[-1] = val; + if (unlikely(JS_IsException(val))) + goto exception; + } + BREAK; + + CASE(OP_get_ref_value): + { + JSValue val; + sf->cur_pc = pc; + if (unlikely(JS_IsUndefined(sp[-2]))) { + JSAtom atom = JS_ValueToAtom(ctx, sp[-1]); + if (atom != JS_ATOM_NULL) { + JS_ThrowReferenceErrorNotDefined(ctx, atom); + JS_FreeAtom(ctx, atom); + } + goto exception; + } + val = JS_GetPropertyValue(ctx, sp[-2], + js_dup(sp[-1])); + if (unlikely(JS_IsException(val))) + goto exception; + sp[0] = val; + sp++; + } + BREAK; + + CASE(OP_get_super_value): + { + JSValue val; + JSAtom atom; + sf->cur_pc = pc; + atom = JS_ValueToAtom(ctx, sp[-1]); + if (unlikely(atom == JS_ATOM_NULL)) + goto exception; + val = JS_GetPropertyInternal(ctx, sp[-2], atom, sp[-3], false); + JS_FreeAtom(ctx, atom); + if (unlikely(JS_IsException(val))) + goto exception; + JS_FreeValue(ctx, sp[-1]); + JS_FreeValue(ctx, sp[-2]); + JS_FreeValue(ctx, sp[-3]); + sp[-3] = val; + sp -= 2; + } + BREAK; + + CASE(OP_put_array_el): + { + int ret; + JSValue val; + uint32_t idx; + JSObject *p; + + val = sp[-1]; + if (likely(JS_VALUE_GET_TAG(sp[-2]) == JS_TAG_INT)) { + idx = JS_VALUE_GET_INT(sp[-2]); + if (likely(JS_VALUE_GET_TAG(sp[-3]) == JS_TAG_OBJECT)) { + p = JS_VALUE_GET_OBJ(sp[-3]); + if (likely(p->class_id == JS_CLASS_ARRAY && + idx < (uint32_t)p->u.array.count)) { + set_value(ctx, &p->u.array.u.values[idx], val); + JS_FreeValue(ctx, sp[-3]); + sp -= 3; + BREAK; + } + if (likely(p->class_id == JS_CLASS_ARRAY && + idx == (uint32_t)p->u.array.count && + p->fast_array && + p->extensible && + p->shape->proto == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_ARRAY]) && + ctx->std_array_prototype)) { + /* fast path to add an element */ + uint32_t array_len; + if (likely(JS_VALUE_GET_TAG(p->prop[0].u.value) == JS_TAG_INT)) { + uint32_t new_len = idx + 1; + array_len = JS_VALUE_GET_INT(p->prop[0].u.value); + if (likely(new_len <= p->u.array.u1.size)) { + p->u.array.u.values[idx] = val; + p->u.array.count = new_len; + if (new_len > array_len) + p->prop[0].u.value = js_int32(new_len); + JS_FreeValue(ctx, sp[-3]); + sp -= 3; + BREAK; + } + } + } + } + } + sf->cur_pc = pc; + ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], JS_PROP_THROW_STRICT); + JS_FreeValue(ctx, sp[-3]); + sp -= 3; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_put_ref_value): + { + int ret, flags; + sf->cur_pc = pc; + flags = JS_PROP_THROW_STRICT; + if (unlikely(JS_IsUndefined(sp[-3]))) { + if (is_strict_mode(ctx)) { + JSAtom atom = JS_ValueToAtom(ctx, sp[-2]); + if (atom != JS_ATOM_NULL) { + JS_ThrowReferenceErrorNotDefined(ctx, atom); + JS_FreeAtom(ctx, atom); + } + goto exception; + } else { + sp[-3] = js_dup(ctx->global_obj); + } + } else { + if (is_strict_mode(ctx)) + flags |= JS_PROP_NO_ADD; + } + ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], flags); + JS_FreeValue(ctx, sp[-3]); + sp -= 3; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_put_super_value): + { + int ret; + JSAtom atom; + sf->cur_pc = pc; + if (JS_VALUE_GET_TAG(sp[-3]) != JS_TAG_OBJECT) { + JS_ThrowTypeErrorNotAnObject(ctx); + goto exception; + } + atom = JS_ValueToAtom(ctx, sp[-2]); + if (unlikely(atom == JS_ATOM_NULL)) + goto exception; + ret = JS_SetPropertyInternal2(ctx, + sp[-3], atom, + sp[-1], sp[-4], + JS_PROP_THROW_STRICT); + JS_FreeAtom(ctx, atom); + JS_FreeValue(ctx, sp[-4]); + JS_FreeValue(ctx, sp[-3]); + JS_FreeValue(ctx, sp[-2]); + sp -= 4; + if (ret < 0) + goto exception; + } + BREAK; + + CASE(OP_define_array_el): + { + int ret; + ret = JS_DefinePropertyValueValue(ctx, sp[-3], js_dup(sp[-2]), sp[-1], + JS_PROP_C_W_E | JS_PROP_THROW); + sp -= 1; + if (unlikely(ret < 0)) + goto exception; + } + BREAK; + + CASE(OP_append): /* array pos enumobj -- array pos */ + { + sf->cur_pc = pc; + if (js_append_enumerate(ctx, sp)) + goto exception; + JS_FreeValue(ctx, *--sp); + } + BREAK; + + CASE(OP_copy_data_properties): /* target source excludeList */ + { + /* stack offsets (-1 based): + 2 bits for target, + 3 bits for source, + 2 bits for exclusionList */ + int mask; + + mask = *pc++; + sf->cur_pc = pc; + if (JS_CopyDataProperties(ctx, sp[-1 - (mask & 3)], + sp[-1 - ((mask >> 2) & 7)], + sp[-1 - ((mask >> 5) & 7)], 0)) + goto exception; + } + BREAK; + + CASE(OP_add): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + int64_t r; + r = (int64_t)JS_VALUE_GET_INT(op1) + JS_VALUE_GET_INT(op2); + if (unlikely(r < INT32_MIN || r > INT32_MAX)) + sp[-2] = js_float64(r); + else + sp[-2] = js_int32(r); + sp--; + } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) { + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + sp[-2] = js_float64(JS_VALUE_GET_FLOAT64(op1) + + JS_VALUE_GET_FLOAT64(op2)); + JS_X87_FPCW_RESTORE(fpcw); + sp--; + } else { + sf->cur_pc = pc; + if (js_add_slow(ctx, sp)) + goto exception; + sp--; + } + } + BREAK; + CASE(OP_add_loc): + { + JSValue *pv; + int idx; + idx = *pc; + pc += 1; + + pv = &var_buf[idx]; + if (likely(JS_VALUE_IS_BOTH_INT(*pv, sp[-1]))) { + int64_t r; + r = (int64_t)JS_VALUE_GET_INT(*pv) + + JS_VALUE_GET_INT(sp[-1]); + if (unlikely((int)r != r)) + *pv = __JS_NewFloat64((double)r); + else + *pv = js_int32(r); + sp--; + } else if (JS_VALUE_GET_TAG(*pv) == JS_TAG_STRING) { + JSValue op1; + op1 = sp[-1]; + sp--; + sf->cur_pc = pc; + op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE); + if (JS_IsException(op1)) + goto exception; + op1 = JS_ConcatString(ctx, js_dup(*pv), op1); + if (JS_IsException(op1)) + goto exception; + set_value(ctx, pv, op1); + } else { + JSValue ops[2]; + /* In case of exception, js_add_slow frees ops[0] + and ops[1], so we must duplicate *pv */ + sf->cur_pc = pc; + ops[0] = js_dup(*pv); + ops[1] = sp[-1]; + sp--; + if (js_add_slow(ctx, ops + 2)) + goto exception; + set_value(ctx, pv, ops[0]); + } + } + BREAK; + CASE(OP_sub): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + int64_t r; + r = (int64_t)JS_VALUE_GET_INT(op1) - JS_VALUE_GET_INT(op2); + if (unlikely((int)r != r)) + sp[-2] = __JS_NewFloat64((double)r); + else + sp[-2] = js_int32(r); + sp--; + } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) { + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + sp[-2] = js_float64(JS_VALUE_GET_FLOAT64(op1) - + JS_VALUE_GET_FLOAT64(op2)); + JS_X87_FPCW_RESTORE(fpcw); + sp--; + } else { + goto binary_arith_slow; + } + } + BREAK; + CASE(OP_mul): + { + JSValue op1, op2; + double d; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + int32_t v1, v2; + int64_t r; + v1 = JS_VALUE_GET_INT(op1); + v2 = JS_VALUE_GET_INT(op2); + r = (int64_t)v1 * v2; + if (unlikely((int)r != r)) { + d = (double)r; + goto mul_fp_res; + } + /* need to test zero case for -0 result */ + if (unlikely(r == 0 && (v1 | v2) < 0)) { + d = -0.0; + goto mul_fp_res; + } + sp[-2] = js_int32(r); + sp--; + } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) { + JS_X87_FPCW_SAVE_AND_ADJUST(fpcw); + d = JS_VALUE_GET_FLOAT64(op1) * JS_VALUE_GET_FLOAT64(op2); + JS_X87_FPCW_RESTORE(fpcw); + mul_fp_res: + sp[-2] = js_float64(d); + sp--; + } else { + goto binary_arith_slow; + } + } + BREAK; + CASE(OP_div): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + int v1, v2; + v1 = JS_VALUE_GET_INT(op1); + v2 = JS_VALUE_GET_INT(op2); + sp[-2] = js_number((double)v1 / (double)v2); + sp--; + } else { + goto binary_arith_slow; + } + } + BREAK; + CASE(OP_mod): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + int v1, v2, r; + v1 = JS_VALUE_GET_INT(op1); + v2 = JS_VALUE_GET_INT(op2); + /* We must avoid v2 = 0, v1 = INT32_MIN and v2 = + -1 and the cases where the result is -0. */ + if (unlikely(v1 < 0 || v2 <= 0)) + goto binary_arith_slow; + r = v1 % v2; + sp[-2] = js_int32(r); + sp--; + } else { + goto binary_arith_slow; + } + } + BREAK; + CASE(OP_pow): + binary_arith_slow: + sf->cur_pc = pc; + if (js_binary_arith_slow(ctx, sp, opcode)) + goto exception; + sp--; + BREAK; + + CASE(OP_plus): + { + JSValue op1; + uint32_t tag; + op1 = sp[-1]; + tag = JS_VALUE_GET_TAG(op1); + if (tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag)) { + } else { + sf->cur_pc = pc; + if (js_unary_arith_slow(ctx, sp, opcode)) + goto exception; + } + } + BREAK; + CASE(OP_neg): + { + JSValue op1; + uint32_t tag; + int val; + double d; + op1 = sp[-1]; + tag = JS_VALUE_GET_TAG(op1); + if (tag == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + /* Note: -0 cannot be expressed as integer */ + if (unlikely(val == 0)) { + d = -0.0; + goto neg_fp_res; + } + if (unlikely(val == INT32_MIN)) { + d = -(double)val; + goto neg_fp_res; + } + sp[-1] = js_int32(-val); + } else if (JS_TAG_IS_FLOAT64(tag)) { + d = -JS_VALUE_GET_FLOAT64(op1); + neg_fp_res: + sp[-1] = js_float64(d); + } else { + sf->cur_pc = pc; + if (js_unary_arith_slow(ctx, sp, opcode)) + goto exception; + } + } + BREAK; + CASE(OP_inc): + { + JSValue op1; + int val; + op1 = sp[-1]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + if (unlikely(val == INT32_MAX)) + goto inc_slow; + sp[-1] = js_int32(val + 1); + } else { + inc_slow: + sf->cur_pc = pc; + if (js_unary_arith_slow(ctx, sp, opcode)) + goto exception; + } + } + BREAK; + CASE(OP_dec): + { + JSValue op1; + int val; + op1 = sp[-1]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + if (unlikely(val == INT32_MIN)) + goto dec_slow; + sp[-1] = js_int32(val - 1); + } else { + dec_slow: + sf->cur_pc = pc; + if (js_unary_arith_slow(ctx, sp, opcode)) + goto exception; + } + } + BREAK; + CASE(OP_post_inc): + { + JSValue op1; + int val; + op1 = sp[-1]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + if (unlikely(val == INT32_MAX)) + goto post_inc_slow; + sp[0] = js_int32(val + 1); + } else { + post_inc_slow: + sf->cur_pc = pc; + if (js_post_inc_slow(ctx, sp, opcode)) + goto exception; + } + sp++; + } + BREAK; + CASE(OP_post_dec): + { + JSValue op1; + int val; + op1 = sp[-1]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + if (unlikely(val == INT32_MIN)) + goto post_dec_slow; + sp[0] = js_int32(val - 1); + } else { + post_dec_slow: + sf->cur_pc = pc; + if (js_post_inc_slow(ctx, sp, opcode)) + goto exception; + } + sp++; + } + BREAK; + CASE(OP_inc_loc): + { + JSValue op1; + int val; + int idx; + idx = *pc; + pc += 1; + + op1 = var_buf[idx]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + if (unlikely(val == INT32_MAX)) + goto inc_loc_slow; + var_buf[idx] = js_int32(val + 1); + } else { + inc_loc_slow: + sf->cur_pc = pc; + /* must duplicate otherwise the variable value may + be destroyed before JS code accesses it */ + op1 = js_dup(op1); + if (js_unary_arith_slow(ctx, &op1 + 1, OP_inc)) + goto exception; + set_value(ctx, &var_buf[idx], op1); + } + } + BREAK; + CASE(OP_dec_loc): + { + JSValue op1; + int val; + int idx; + idx = *pc; + pc += 1; + + op1 = var_buf[idx]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + val = JS_VALUE_GET_INT(op1); + if (unlikely(val == INT32_MIN)) + goto dec_loc_slow; + var_buf[idx] = js_int32(val - 1); + } else { + dec_loc_slow: + sf->cur_pc = pc; + /* must duplicate otherwise the variable value may + be destroyed before JS code accesses it */ + op1 = js_dup(op1); + if (js_unary_arith_slow(ctx, &op1 + 1, OP_dec)) + goto exception; + set_value(ctx, &var_buf[idx], op1); + } + } + BREAK; + CASE(OP_not): + { + JSValue op1; + op1 = sp[-1]; + if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { + sp[-1] = js_int32(~JS_VALUE_GET_INT(op1)); + } else { + sf->cur_pc = pc; + if (js_not_slow(ctx, sp)) + goto exception; + } + } + BREAK; + + CASE(OP_shl): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + uint32_t v1, v2; + v1 = JS_VALUE_GET_INT(op1); + v2 = JS_VALUE_GET_INT(op2) & 0x1f; + sp[-2] = js_int32(v1 << v2); + sp--; + } else { + sf->cur_pc = pc; + if (js_binary_logic_slow(ctx, sp, opcode)) + goto exception; + sp--; + } + } + BREAK; + CASE(OP_shr): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + uint32_t v2; + v2 = JS_VALUE_GET_INT(op2); + v2 &= 0x1f; + sp[-2] = js_uint32((uint32_t)JS_VALUE_GET_INT(op1) >> v2); + sp--; + } else { + sf->cur_pc = pc; + if (js_shr_slow(ctx, sp)) + goto exception; + sp--; + } + } + BREAK; + CASE(OP_sar): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + uint32_t v2; + v2 = JS_VALUE_GET_INT(op2); + if (unlikely(v2 > 0x1f)) { + v2 &= 0x1f; + } + sp[-2] = js_int32((int)JS_VALUE_GET_INT(op1) >> v2); + sp--; + } else { + sf->cur_pc = pc; + if (js_binary_logic_slow(ctx, sp, opcode)) + goto exception; + sp--; + } + } + BREAK; + CASE(OP_and): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + sp[-2] = js_int32(JS_VALUE_GET_INT(op1) & JS_VALUE_GET_INT(op2)); + sp--; + } else { + sf->cur_pc = pc; + if (js_binary_logic_slow(ctx, sp, opcode)) + goto exception; + sp--; + } + } + BREAK; + CASE(OP_or): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + sp[-2] = js_int32(JS_VALUE_GET_INT(op1) | JS_VALUE_GET_INT(op2)); + sp--; + } else { + sf->cur_pc = pc; + if (js_binary_logic_slow(ctx, sp, opcode)) + goto exception; + sp--; + } + } + BREAK; + CASE(OP_xor): + { + JSValue op1, op2; + op1 = sp[-2]; + op2 = sp[-1]; + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { + sp[-2] = js_int32(JS_VALUE_GET_INT(op1) ^ JS_VALUE_GET_INT(op2)); + sp--; + } else { + sf->cur_pc = pc; + if (js_binary_logic_slow(ctx, sp, opcode)) + goto exception; + sp--; + } + } + BREAK; + + +#define OP_CMP(opcode, binary_op, slow_call) \ + CASE(opcode): \ + { \ + JSValue op1, op2; \ + op1 = sp[-2]; \ + op2 = sp[-1]; \ + if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { \ + sp[-2] = js_bool(JS_VALUE_GET_INT(op1) binary_op JS_VALUE_GET_INT(op2)); \ + sp--; \ + } else { \ + sf->cur_pc = pc; \ + if (slow_call) \ + goto exception; \ + sp--; \ + } \ + } \ + BREAK + + OP_CMP(OP_lt, <, js_relational_slow(ctx, sp, opcode)); + OP_CMP(OP_lte, <=, js_relational_slow(ctx, sp, opcode)); + OP_CMP(OP_gt, >, js_relational_slow(ctx, sp, opcode)); + OP_CMP(OP_gte, >=, js_relational_slow(ctx, sp, opcode)); + OP_CMP(OP_eq, ==, js_eq_slow(ctx, sp, 0)); + OP_CMP(OP_neq, !=, js_eq_slow(ctx, sp, 1)); + OP_CMP(OP_strict_eq, ==, js_strict_eq_slow(ctx, sp, 0)); + OP_CMP(OP_strict_neq, !=, js_strict_eq_slow(ctx, sp, 1)); + + CASE(OP_in): + sf->cur_pc = pc; + if (js_operator_in(ctx, sp)) + goto exception; + sp--; + BREAK; + CASE(OP_private_in): + if (js_operator_private_in(ctx, sp)) + goto exception; + sp--; + BREAK; + CASE(OP_instanceof): + sf->cur_pc = pc; + if (js_operator_instanceof(ctx, sp)) + goto exception; + sp--; + BREAK; + CASE(OP_typeof): + { + JSValue op1; + JSAtom atom; + + op1 = sp[-1]; + atom = js_operator_typeof(ctx, op1); + JS_FreeValue(ctx, op1); + sp[-1] = JS_AtomToString(ctx, atom); + } + BREAK; + CASE(OP_delete): + sf->cur_pc = pc; + if (js_operator_delete(ctx, sp)) + goto exception; + sp--; + BREAK; + CASE(OP_delete_var): + { + JSAtom atom; + int ret; + + atom = get_u32(pc); + pc += 4; + + sf->cur_pc = pc; + ret = JS_DeleteGlobalVar(ctx, atom); + if (unlikely(ret < 0)) + goto exception; + *sp++ = js_bool(ret); + } + BREAK; + + CASE(OP_to_object): + if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_OBJECT) { + sf->cur_pc = pc; + ret_val = JS_ToObject(ctx, sp[-1]); + if (JS_IsException(ret_val)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = ret_val; + } + BREAK; + + CASE(OP_to_propkey): + switch (JS_VALUE_GET_TAG(sp[-1])) { + case JS_TAG_INT: + case JS_TAG_STRING: + case JS_TAG_SYMBOL: + break; + default: + sf->cur_pc = pc; + ret_val = JS_ToPropertyKey(ctx, sp[-1]); + if (JS_IsException(ret_val)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = ret_val; + break; + } + BREAK; + + CASE(OP_to_propkey2): + /* must be tested first */ + if (unlikely(JS_IsUndefined(sp[-2]) || JS_IsNull(sp[-2]))) { + JS_ThrowTypeError(ctx, "value has no property"); + goto exception; + } + switch (JS_VALUE_GET_TAG(sp[-1])) { + case JS_TAG_INT: + case JS_TAG_STRING: + case JS_TAG_SYMBOL: + break; + default: + sf->cur_pc = pc; + ret_val = JS_ToPropertyKey(ctx, sp[-1]); + if (JS_IsException(ret_val)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = ret_val; + break; + } + BREAK; + CASE(OP_with_get_var): + CASE(OP_with_put_var): + CASE(OP_with_delete_var): + CASE(OP_with_make_ref): + CASE(OP_with_get_ref): + CASE(OP_with_get_ref_undef): + { + JSAtom atom; + int32_t diff; + JSValue obj, val; + int ret, is_with; + atom = get_u32(pc); + diff = get_u32(pc + 4); + is_with = pc[8]; + pc += 9; + sf->cur_pc = pc; + + obj = sp[-1]; + ret = JS_HasProperty(ctx, obj, atom); + if (unlikely(ret < 0)) + goto exception; + if (ret) { + if (is_with) { + ret = js_has_unscopable(ctx, obj, atom); + if (unlikely(ret < 0)) + goto exception; + if (ret) + goto no_with; + } + switch (opcode) { + case OP_with_get_var: + val = JS_GetProperty(ctx, obj, atom); + if (unlikely(JS_IsException(val))) + goto exception; + set_value(ctx, &sp[-1], val); + break; + case OP_with_put_var: + /* XXX: check if strict mode */ + ret = JS_SetPropertyInternal(ctx, obj, atom, sp[-2], + JS_PROP_THROW_STRICT); + JS_FreeValue(ctx, sp[-1]); + sp -= 2; + if (unlikely(ret < 0)) + goto exception; + break; + case OP_with_delete_var: + ret = JS_DeleteProperty(ctx, obj, atom, 0); + if (unlikely(ret < 0)) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = js_bool(ret); + break; + case OP_with_make_ref: + /* produce a pair object/propname on the stack */ + *sp++ = JS_AtomToValue(ctx, atom); + break; + case OP_with_get_ref: + /* produce a pair object/method on the stack */ + val = JS_GetProperty(ctx, obj, atom); + if (unlikely(JS_IsException(val))) + goto exception; + *sp++ = val; + break; + case OP_with_get_ref_undef: + /* produce a pair undefined/function on the stack */ + val = JS_GetProperty(ctx, obj, atom); + if (unlikely(JS_IsException(val))) + goto exception; + JS_FreeValue(ctx, sp[-1]); + sp[-1] = JS_UNDEFINED; + *sp++ = val; + break; + } + pc += diff - 5; + } else { + no_with: + /* if not jumping, drop the object argument */ + JS_FreeValue(ctx, sp[-1]); + sp--; + } + } + BREAK; + + CASE(OP_await): + ret_val = js_int32(FUNC_RET_AWAIT); + goto done_generator; + CASE(OP_yield): + ret_val = js_int32(FUNC_RET_YIELD); + goto done_generator; + CASE(OP_yield_star): + CASE(OP_async_yield_star): + ret_val = js_int32(FUNC_RET_YIELD_STAR); + goto done_generator; + CASE(OP_return_async): + CASE(OP_initial_yield): + ret_val = JS_UNDEFINED; + goto done_generator; + + CASE(OP_nop): + BREAK; + CASE(OP_is_undefined_or_null): + if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED || + JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) { + goto set_true; + } else { + goto free_and_set_false; + } + CASE(OP_is_undefined): + if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED) { + goto set_true; + } else { + goto free_and_set_false; + } + CASE(OP_is_null): + if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) { + goto set_true; + } else { + goto free_and_set_false; + } + /* XXX: could merge to a single opcode */ + CASE(OP_typeof_is_undefined): + /* different from OP_is_undefined because of isHTMLDDA */ + if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_undefined) { + goto free_and_set_true; + } else { + goto free_and_set_false; + } + CASE(OP_typeof_is_function): + if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_function) { + goto free_and_set_true; + } else { + goto free_and_set_false; + } + free_and_set_true: + JS_FreeValue(ctx, sp[-1]); + set_true: + sp[-1] = JS_TRUE; + BREAK; + free_and_set_false: + JS_FreeValue(ctx, sp[-1]); + sp[-1] = JS_FALSE; + BREAK; + CASE(OP_invalid): + DEFAULT: + JS_ThrowInternalError(ctx, "invalid opcode: pc=%u opcode=0x%02x", + (int)(pc - b->byte_code_buf - 1), opcode); + goto exception; + } + } + exception: + if (needs_backtrace(rt->current_exception) + || JS_IsUndefined(ctx->error_back_trace)) { + sf->cur_pc = pc; + build_backtrace(ctx, rt->current_exception, JS_UNDEFINED, + NULL, 0, 0, 0); + } + if (!JS_IsUncatchableError(rt->current_exception)) { + while (sp > stack_buf) { + JSValue val = *--sp; + JS_FreeValue(ctx, val); + if (JS_VALUE_GET_TAG(val) == JS_TAG_CATCH_OFFSET) { + int pos = JS_VALUE_GET_INT(val); + if (pos == 0) { + /* enumerator: close it with a throw */ + JS_FreeValue(ctx, sp[-1]); /* drop the next method */ + sp--; + JS_IteratorClose(ctx, sp[-1], true); + } else { + *sp++ = rt->current_exception; + rt->current_exception = JS_UNINITIALIZED; + JS_FreeValueRT(rt, ctx->error_back_trace); + ctx->error_back_trace = JS_UNDEFINED; + pc = b->byte_code_buf + pos; + goto restart; + } + } + } + } + ret_val = JS_EXCEPTION; + /* the local variables are freed by the caller in the generator + case. Hence the label 'done' should never be reached in a + generator function. */ + if (b->func_kind != JS_FUNC_NORMAL) { + done_generator: + sf->cur_pc = pc; + sf->cur_sp = sp; + } else { + done: + if (unlikely(sf->var_ref_count != 0)) { + /* variable references reference the stack: must close them */ + close_var_refs(rt, sf); + } + /* free the local variables and stack */ + for(pval = local_buf; pval < sp; pval++) { + JS_FreeValue(ctx, *pval); + } + } + rt->current_stack_frame = sf->prev_frame; + return ret_val; +} + +JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, + int argc, JSValueConst *argv) +{ + return JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED, + argc, argv, JS_CALL_FLAG_COPY_ARGV); +} + +static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj, + int argc, JSValueConst *argv) +{ + JSValue res = JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED, + argc, argv, JS_CALL_FLAG_COPY_ARGV); + JS_FreeValue(ctx, func_obj); + return res; +} + +/* warning: the refcount of the context is not incremented. Return + NULL in case of exception (case of revoked proxy only) */ +static JSContext *JS_GetFunctionRealm(JSContext *ctx, JSValueConst func_obj) +{ + JSObject *p; + JSContext *realm; + + if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT) + return ctx; + p = JS_VALUE_GET_OBJ(func_obj); + switch(p->class_id) { + case JS_CLASS_C_FUNCTION: + realm = p->u.cfunc.realm; + break; + case JS_CLASS_BYTECODE_FUNCTION: + case JS_CLASS_GENERATOR_FUNCTION: + case JS_CLASS_ASYNC_FUNCTION: + case JS_CLASS_ASYNC_GENERATOR_FUNCTION: + { + JSFunctionBytecode *b; + b = p->u.func.function_bytecode; + realm = b->realm; + } + break; + case JS_CLASS_PROXY: + { + JSProxyData *s = p->u.opaque; + if (!s) + return ctx; + if (s->is_revoked) { + JS_ThrowTypeErrorRevokedProxy(ctx); + return NULL; + } else { + realm = JS_GetFunctionRealm(ctx, s->target); + } + } + break; + case JS_CLASS_BOUND_FUNCTION: + { + JSBoundFunction *bf = p->u.bound_function; + realm = JS_GetFunctionRealm(ctx, bf->func_obj); + } + break; + default: + realm = ctx; + break; + } + return realm; +} + +static JSValue js_create_from_ctor(JSContext *ctx, JSValueConst ctor, + int class_id) +{ + JSValue proto, obj; + JSContext *realm; + + if (JS_IsUndefined(ctor)) { + proto = js_dup(ctx->class_proto[class_id]); + } else { + proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype); + if (JS_IsException(proto)) + return proto; + if (!JS_IsObject(proto)) { + JS_FreeValue(ctx, proto); + realm = JS_GetFunctionRealm(ctx, ctor); + if (!realm) + return JS_EXCEPTION; + proto = js_dup(realm->class_proto[class_id]); + } + } + obj = JS_NewObjectProtoClass(ctx, proto, class_id); + JS_FreeValue(ctx, proto); + return obj; +} + +/* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */ +static JSValue JS_CallConstructorInternal(JSContext *ctx, + JSValueConst func_obj, + JSValueConst new_target, + int argc, JSValueConst *argv, + int flags) +{ + JSObject *p; + JSFunctionBytecode *b; + + if (js_poll_interrupts(ctx)) + return JS_EXCEPTION; + flags |= JS_CALL_FLAG_CONSTRUCTOR; + if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) + goto not_a_function; + p = JS_VALUE_GET_OBJ(func_obj); + if (unlikely(!p->is_constructor)) + return JS_ThrowTypeErrorNotAConstructor(ctx, func_obj); + if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) { + JSClassCall *call_func; + call_func = ctx->rt->class_array[p->class_id].call; + if (!call_func) { + not_a_function: + return JS_ThrowTypeErrorNotAFunction(ctx); + } + return call_func(ctx, func_obj, new_target, argc, + argv, flags); + } + + b = p->u.func.function_bytecode; + if (b->is_derived_class_constructor) { + return JS_CallInternal(ctx, func_obj, JS_UNDEFINED, new_target, argc, argv, flags); + } else { + JSValue obj, ret; + /* legacy constructor behavior */ + obj = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT); + if (JS_IsException(obj)) + return JS_EXCEPTION; + ret = JS_CallInternal(ctx, func_obj, obj, new_target, argc, argv, flags); + if (JS_VALUE_GET_TAG(ret) == JS_TAG_OBJECT || + JS_IsException(ret)) { + JS_FreeValue(ctx, obj); + return ret; + } else { + JS_FreeValue(ctx, ret); + return obj; + } + } +} + +JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj, + JSValueConst new_target, + int argc, JSValueConst *argv) +{ + return JS_CallConstructorInternal(ctx, func_obj, new_target, + argc, argv, + JS_CALL_FLAG_COPY_ARGV); +} + +JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj, + int argc, JSValueConst *argv) +{ + return JS_CallConstructorInternal(ctx, func_obj, func_obj, + argc, argv, + JS_CALL_FLAG_COPY_ARGV); +} + +JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom, + int argc, JSValueConst *argv) +{ + JSValue func_obj; + func_obj = JS_GetProperty(ctx, this_val, atom); + if (JS_IsException(func_obj)) + return func_obj; + return JS_CallFree(ctx, func_obj, this_val, argc, argv); +} + +static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom, + int argc, JSValueConst *argv) +{ + JSValue res = JS_Invoke(ctx, this_val, atom, argc, argv); + JS_FreeValue(ctx, this_val); + return res; +} + +/* JSAsyncFunctionState (used by generator and async functions) */ +static __exception int async_func_init(JSContext *ctx, JSAsyncFunctionState *s, + JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv) +{ + JSObject *p; + JSFunctionBytecode *b; + JSStackFrame *sf; + int local_count, i, arg_buf_len, n; + size_t alloc_size; + + sf = &s->frame; + p = JS_VALUE_GET_OBJ(func_obj); + b = p->u.func.function_bytecode; + sf->is_strict_mode = b->is_strict_mode; + sf->cur_pc = b->byte_code_buf; + arg_buf_len = max_int(b->arg_count, argc); + local_count = arg_buf_len + b->var_count + b->stack_size; + alloc_size = sizeof(JSValue) * max_int(local_count, 1) + + sizeof(JSVarRef *) * b->var_ref_count; + sf->arg_buf = js_malloc(ctx, alloc_size); + if (!sf->arg_buf) + return -1; + sf->cur_func = js_dup(func_obj); + s->this_val = js_dup(this_obj); + s->argc = argc; + sf->arg_count = arg_buf_len; + sf->var_buf = sf->arg_buf + arg_buf_len; + sf->cur_sp = sf->var_buf + b->var_count; + sf->var_refs = (JSVarRef **)(sf->cur_sp + b->stack_size); + sf->var_ref_count = b->var_ref_count; + for(i = 0; i < b->var_ref_count; i++) + sf->var_refs[i] = NULL; + for(i = 0; i < argc; i++) + sf->arg_buf[i] = js_dup(argv[i]); + n = arg_buf_len + b->var_count; + for(i = argc; i < n; i++) + sf->arg_buf[i] = JS_UNDEFINED; + return 0; +} + +static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s, + JS_MarkFunc *mark_func) +{ + JSStackFrame *sf; + JSValue *sp; + + sf = &s->frame; + JS_MarkValue(rt, sf->cur_func, mark_func); + JS_MarkValue(rt, s->this_val, mark_func); + if (sf->cur_sp) { + /* if the function is running, cur_sp is not known so we + cannot mark the stack. Marking the variables is not needed + because a running function cannot be part of a removable + cycle */ + for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) + JS_MarkValue(rt, *sp, mark_func); + } +} + +static void async_func_free(JSRuntime *rt, JSAsyncFunctionState *s) +{ + JSStackFrame *sf; + JSValue *sp; + + sf = &s->frame; + + if (sf->arg_buf) { + /* close the closure variables. */ + if (sf->var_ref_count != 0) + close_var_refs(rt, sf); + + /* cannot free the function if it is running */ + assert(sf->cur_sp != NULL); + for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) { + JS_FreeValueRT(rt, *sp); + } + js_free_rt(rt, sf->arg_buf); + } + JS_FreeValueRT(rt, sf->cur_func); + JS_FreeValueRT(rt, s->this_val); +} + +static JSValue async_func_resume(JSContext *ctx, JSAsyncFunctionState *s) +{ + JSValue func_obj; + + if (js_check_stack_overflow(ctx->rt, 0)) + return JS_ThrowStackOverflow(ctx); + + /* the tag does not matter provided it is not an object */ + func_obj = JS_MKPTR(JS_TAG_INT, s); + return JS_CallInternal(ctx, func_obj, s->this_val, JS_UNDEFINED, + s->argc, vc(s->frame.arg_buf), + JS_CALL_FLAG_GENERATOR); +} + + +/* Generators */ + +typedef enum JSGeneratorStateEnum { + JS_GENERATOR_STATE_SUSPENDED_START, + JS_GENERATOR_STATE_SUSPENDED_YIELD, + JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR, + JS_GENERATOR_STATE_EXECUTING, + JS_GENERATOR_STATE_COMPLETED, +} JSGeneratorStateEnum; + +typedef struct JSGeneratorData { + JSGeneratorStateEnum state; + JSAsyncFunctionState func_state; +} JSGeneratorData; + +static void free_generator_stack_rt(JSRuntime *rt, JSGeneratorData *s) +{ + if (s->state == JS_GENERATOR_STATE_COMPLETED) + return; + async_func_free(rt, &s->func_state); + s->state = JS_GENERATOR_STATE_COMPLETED; +} + +static void js_generator_finalizer(JSRuntime *rt, JSValueConst obj) +{ + JSGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_GENERATOR); + + if (s) { + free_generator_stack_rt(rt, s); + js_free_rt(rt, s); + } +} + +static void free_generator_stack(JSContext *ctx, JSGeneratorData *s) +{ + free_generator_stack_rt(ctx->rt, s); +} + +static void js_generator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSGeneratorData *s = p->u.generator_data; + + if (!s || s->state == JS_GENERATOR_STATE_COMPLETED) + return; + async_func_mark(rt, &s->func_state, mark_func); +} + +/* XXX: use enum */ +#define GEN_MAGIC_NEXT 0 +#define GEN_MAGIC_RETURN 1 +#define GEN_MAGIC_THROW 2 + +static JSValue js_generator_next(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, + int *pdone, int magic) +{ + JSGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_GENERATOR); + JSStackFrame *sf; + JSValue ret, func_ret; + + *pdone = true; + if (!s) + return JS_ThrowTypeError(ctx, "not a generator"); + sf = &s->func_state.frame; + switch(s->state) { + default: + case JS_GENERATOR_STATE_SUSPENDED_START: + if (magic == GEN_MAGIC_NEXT) { + goto exec_no_arg; + } else { + free_generator_stack(ctx, s); + goto done; + } + break; + case JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR: + case JS_GENERATOR_STATE_SUSPENDED_YIELD: + /* cur_sp[-1] was set to JS_UNDEFINED in the previous call */ + ret = js_dup(argv[0]); + if (magic == GEN_MAGIC_THROW && + s->state == JS_GENERATOR_STATE_SUSPENDED_YIELD) { + JS_Throw(ctx, ret); + s->func_state.throw_flag = true; + } else { + sf->cur_sp[-1] = ret; + sf->cur_sp[0] = js_int32(magic); + sf->cur_sp++; + exec_no_arg: + s->func_state.throw_flag = false; + } + s->state = JS_GENERATOR_STATE_EXECUTING; + func_ret = async_func_resume(ctx, &s->func_state); + s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD; + if (JS_IsException(func_ret)) { + /* finalize the execution in case of exception */ + free_generator_stack(ctx, s); + return func_ret; + } + if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) { + /* get the returned yield value at the top of the stack */ + ret = sf->cur_sp[-1]; + sf->cur_sp[-1] = JS_UNDEFINED; + if (JS_VALUE_GET_INT(func_ret) == FUNC_RET_YIELD_STAR) { + s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR; + /* return (value, done) object */ + *pdone = 2; + } else { + *pdone = false; + } + } else { + /* end of iterator */ + ret = sf->cur_sp[-1]; + sf->cur_sp[-1] = JS_UNDEFINED; + JS_FreeValue(ctx, func_ret); + free_generator_stack(ctx, s); + } + break; + case JS_GENERATOR_STATE_COMPLETED: + done: + /* execution is finished */ + switch(magic) { + default: + case GEN_MAGIC_NEXT: + ret = JS_UNDEFINED; + break; + case GEN_MAGIC_RETURN: + ret = js_dup(argv[0]); + break; + case GEN_MAGIC_THROW: + ret = JS_Throw(ctx, js_dup(argv[0])); + break; + } + break; + case JS_GENERATOR_STATE_EXECUTING: + ret = JS_ThrowTypeError(ctx, "cannot invoke a running generator"); + break; + } + return ret; +} + +static JSValue js_call_generator_function(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, + int flags) +{ + JSValue obj, func_ret; + JSGeneratorData *s; + + s = js_mallocz(ctx, sizeof(*s)); + if (!s) + return JS_EXCEPTION; + s->state = JS_GENERATOR_STATE_SUSPENDED_START; + if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { + s->state = JS_GENERATOR_STATE_COMPLETED; + goto fail; + } + + /* execute the function up to 'OP_initial_yield' */ + func_ret = async_func_resume(ctx, &s->func_state); + if (JS_IsException(func_ret)) + goto fail; + JS_FreeValue(ctx, func_ret); + + obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_GENERATOR); + if (JS_IsException(obj)) + goto fail; + JS_SetOpaqueInternal(obj, s); + return obj; + fail: + free_generator_stack_rt(ctx->rt, s); + js_free(ctx, s); + return JS_EXCEPTION; +} + +/* AsyncFunction */ + +static void js_async_function_terminate(JSRuntime *rt, JSAsyncFunctionData *s) +{ + if (s->is_active) { + async_func_free(rt, &s->func_state); + s->is_active = false; + } +} + +static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s) +{ + js_async_function_terminate(rt, s); + JS_FreeValueRT(rt, s->resolving_funcs[0]); + JS_FreeValueRT(rt, s->resolving_funcs[1]); + remove_gc_object(&s->header); + js_free_rt(rt, s); +} + +static void js_async_function_free(JSRuntime *rt, JSAsyncFunctionData *s) +{ + if (--s->header.ref_count == 0) { + js_async_function_free0(rt, s); + } +} + +static void js_async_function_resolve_finalizer(JSRuntime *rt, + JSValueConst val) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSAsyncFunctionData *s = p->u.async_function_data; + if (s) { + js_async_function_free(rt, s); + } +} + +static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSObject *p = JS_VALUE_GET_OBJ(val); + JSAsyncFunctionData *s = p->u.async_function_data; + if (s) { + mark_func(rt, &s->header); + } +} + +static int js_async_function_resolve_create(JSContext *ctx, + JSAsyncFunctionData *s, + JSValue *resolving_funcs) +{ + int i; + JSObject *p; + + for(i = 0; i < 2; i++) { + resolving_funcs[i] = + JS_NewObjectProtoClass(ctx, ctx->function_proto, + JS_CLASS_ASYNC_FUNCTION_RESOLVE + i); + if (JS_IsException(resolving_funcs[i])) { + if (i == 1) + JS_FreeValue(ctx, resolving_funcs[0]); + return -1; + } + p = JS_VALUE_GET_OBJ(resolving_funcs[i]); + s->header.ref_count++; + p->u.async_function_data = s; + } + return 0; +} + +static bool js_async_function_resume(JSContext *ctx, JSAsyncFunctionData *s) +{ + bool is_success = true; + JSValue func_ret, ret2; + + func_ret = async_func_resume(ctx, &s->func_state); + if (JS_IsException(func_ret)) { + fail: + if (unlikely(JS_IsUncatchableError(ctx->rt->current_exception))) { + is_success = false; + } else { + JSValue error = JS_GetException(ctx); + ret2 = JS_Call(ctx, s->resolving_funcs[1], JS_UNDEFINED, + 1, vc(&error)); + JS_FreeValue(ctx, error); + resolved: + if (unlikely(JS_IsException(ret2))) { + if (JS_IsUncatchableError(ctx->rt->current_exception)) { + is_success = false; + } else { + abort(); /* BUG */ + } + } + JS_FreeValue(ctx, ret2); + } + js_async_function_terminate(ctx->rt, s); + } else { + JSValue value; + value = s->func_state.frame.cur_sp[-1]; + s->func_state.frame.cur_sp[-1] = JS_UNDEFINED; + if (JS_IsUndefined(func_ret)) { + /* function returned */ + ret2 = JS_Call(ctx, s->resolving_funcs[0], JS_UNDEFINED, + 1, vc(&value)); + JS_FreeValue(ctx, value); + goto resolved; + } else { + JSValue promise, resolving_funcs[2], resolving_funcs1[2]; + int i, res; + + /* await */ + JS_FreeValue(ctx, func_ret); /* not used */ + promise = js_promise_resolve(ctx, ctx->promise_ctor, + 1, vc(&value), 0); + JS_FreeValue(ctx, value); + if (JS_IsException(promise)) + goto fail; + if (js_async_function_resolve_create(ctx, s, resolving_funcs)) { + JS_FreeValue(ctx, promise); + goto fail; + } + + /* Note: no need to create 'thrownawayCapability' as in + the spec */ + for(i = 0; i < 2; i++) + resolving_funcs1[i] = JS_UNDEFINED; + res = perform_promise_then(ctx, promise, + vc(resolving_funcs), + vc(resolving_funcs1)); + JS_FreeValue(ctx, promise); + for(i = 0; i < 2; i++) + JS_FreeValue(ctx, resolving_funcs[i]); + if (res) + goto fail; + } + } + return is_success; +} + +static JSValue js_async_function_resolve_call(JSContext *ctx, + JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, + int flags) +{ + JSObject *p = JS_VALUE_GET_OBJ(func_obj); + JSAsyncFunctionData *s = p->u.async_function_data; + bool is_reject = p->class_id - JS_CLASS_ASYNC_FUNCTION_RESOLVE; + JSValueConst arg; + + if (argc > 0) + arg = argv[0]; + else + arg = JS_UNDEFINED; + s->func_state.throw_flag = is_reject; + if (is_reject) { + JS_Throw(ctx, js_dup(arg)); + } else { + /* return value of await */ + s->func_state.frame.cur_sp[-1] = js_dup(arg); + } + if (!js_async_function_resume(ctx, s)) + return JS_EXCEPTION; + return JS_UNDEFINED; +} + +static JSValue js_async_function_call(JSContext *ctx, JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, int flags) +{ + JSValue promise; + JSAsyncFunctionData *s; + + s = js_mallocz(ctx, sizeof(*s)); + if (!s) + return JS_EXCEPTION; + s->header.ref_count = 1; + add_gc_object(ctx->rt, &s->header, JS_GC_OBJ_TYPE_ASYNC_FUNCTION); + s->is_active = false; + s->resolving_funcs[0] = JS_UNDEFINED; + s->resolving_funcs[1] = JS_UNDEFINED; + + promise = JS_NewPromiseCapability(ctx, s->resolving_funcs); + if (JS_IsException(promise)) + goto fail; + + if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { + fail: + JS_FreeValue(ctx, promise); + js_async_function_free(ctx->rt, s); + return JS_EXCEPTION; + } + s->is_active = true; + + if (!js_async_function_resume(ctx, s)) + goto fail; + + js_async_function_free(ctx->rt, s); + + return promise; +} + +/* AsyncGenerator */ + +typedef enum JSAsyncGeneratorStateEnum { + JS_ASYNC_GENERATOR_STATE_SUSPENDED_START, + JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD, + JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR, + JS_ASYNC_GENERATOR_STATE_EXECUTING, + JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN, + JS_ASYNC_GENERATOR_STATE_COMPLETED, +} JSAsyncGeneratorStateEnum; + +typedef struct JSAsyncGeneratorRequest { + struct list_head link; + /* completion */ + int completion_type; /* GEN_MAGIC_x */ + JSValue result; + /* promise capability */ + JSValue promise; + JSValue resolving_funcs[2]; +} JSAsyncGeneratorRequest; + +typedef struct JSAsyncGeneratorData { + JSObject *generator; /* back pointer to the object (const) */ + JSAsyncGeneratorStateEnum state; + JSAsyncFunctionState func_state; + struct list_head queue; /* list of JSAsyncGeneratorRequest.link */ +} JSAsyncGeneratorData; + +static void js_async_generator_free(JSRuntime *rt, + JSAsyncGeneratorData *s) +{ + struct list_head *el, *el1; + JSAsyncGeneratorRequest *req; + + list_for_each_safe(el, el1, &s->queue) { + req = list_entry(el, JSAsyncGeneratorRequest, link); + JS_FreeValueRT(rt, req->result); + JS_FreeValueRT(rt, req->promise); + JS_FreeValueRT(rt, req->resolving_funcs[0]); + JS_FreeValueRT(rt, req->resolving_funcs[1]); + js_free_rt(rt, req); + } + if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED && + s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) { + async_func_free(rt, &s->func_state); + } + js_free_rt(rt, s); +} + +static void js_async_generator_finalizer(JSRuntime *rt, JSValueConst obj) +{ + JSAsyncGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_ASYNC_GENERATOR); + + if (s) { + js_async_generator_free(rt, s); + } +} + +static void js_async_generator_mark(JSRuntime *rt, JSValueConst val, + JS_MarkFunc *mark_func) +{ + JSAsyncGeneratorData *s = JS_GetOpaque(val, JS_CLASS_ASYNC_GENERATOR); + struct list_head *el; + JSAsyncGeneratorRequest *req; + if (s) { + list_for_each(el, &s->queue) { + req = list_entry(el, JSAsyncGeneratorRequest, link); + JS_MarkValue(rt, req->result, mark_func); + JS_MarkValue(rt, req->promise, mark_func); + JS_MarkValue(rt, req->resolving_funcs[0], mark_func); + JS_MarkValue(rt, req->resolving_funcs[1], mark_func); + } + if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED && + s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) { + async_func_mark(rt, &s->func_state, mark_func); + } + } +} + +static JSValue js_async_generator_resolve_function(JSContext *ctx, + JSValueConst this_obj, + int argc, JSValueConst *argv, + int magic, JSValueConst *func_data); + +static int js_async_generator_resolve_function_create(JSContext *ctx, + JSValue generator, + JSValue *resolving_funcs, + bool is_resume_next) +{ + int i; + JSValue func; + + for(i = 0; i < 2; i++) { + func = JS_NewCFunctionData(ctx, js_async_generator_resolve_function, 1, + i + is_resume_next * 2, 1, vc(&generator)); + if (JS_IsException(func)) { + if (i == 1) + JS_FreeValue(ctx, resolving_funcs[0]); + return -1; + } + resolving_funcs[i] = func; + } + return 0; +} + +static int js_async_generator_await(JSContext *ctx, + JSAsyncGeneratorData *s, + JSValue value) +{ + JSValue promise, resolving_funcs[2], resolving_funcs1[2]; + int i, res; + + promise = js_promise_resolve(ctx, ctx->promise_ctor, + 1, vc(&value), 0); + if (JS_IsException(promise)) + goto fail; + + if (js_async_generator_resolve_function_create(ctx, JS_MKPTR(JS_TAG_OBJECT, s->generator), + resolving_funcs, false)) { + JS_FreeValue(ctx, promise); + goto fail; + } + + /* Note: no need to create 'thrownawayCapability' as in + the spec */ + for(i = 0; i < 2; i++) + resolving_funcs1[i] = JS_UNDEFINED; + res = perform_promise_then(ctx, promise, + vc(resolving_funcs), + vc(resolving_funcs1)); + JS_FreeValue(ctx, promise); + for(i = 0; i < 2; i++) + JS_FreeValue(ctx, resolving_funcs[i]); + if (res) + goto fail; + return 0; + fail: + return -1; +} + +static void js_async_generator_resolve_or_reject(JSContext *ctx, + JSAsyncGeneratorData *s, + JSValueConst result, + int is_reject) +{ + JSAsyncGeneratorRequest *next; + JSValue ret; + + next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link); + list_del(&next->link); + ret = JS_Call(ctx, next->resolving_funcs[is_reject], JS_UNDEFINED, 1, + &result); + JS_FreeValue(ctx, ret); + JS_FreeValue(ctx, next->result); + JS_FreeValue(ctx, next->promise); + JS_FreeValue(ctx, next->resolving_funcs[0]); + JS_FreeValue(ctx, next->resolving_funcs[1]); + js_free(ctx, next); +} + +static void js_async_generator_resolve(JSContext *ctx, + JSAsyncGeneratorData *s, + JSValueConst value, + bool done) +{ + JSValue result; + result = js_create_iterator_result(ctx, js_dup(value), done); + /* XXX: better exception handling ? */ + js_async_generator_resolve_or_reject(ctx, s, result, 0); + JS_FreeValue(ctx, result); + } + +static void js_async_generator_reject(JSContext *ctx, + JSAsyncGeneratorData *s, + JSValueConst exception) +{ + js_async_generator_resolve_or_reject(ctx, s, exception, 1); +} + +static void js_async_generator_complete(JSContext *ctx, + JSAsyncGeneratorData *s) +{ + if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED) { + s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED; + async_func_free(ctx->rt, &s->func_state); + } +} + +static int js_async_generator_completed_return(JSContext *ctx, + JSAsyncGeneratorData *s, + JSValue value) +{ + JSValue promise, resolving_funcs[2], resolving_funcs1[2]; + int res; + + // Can fail looking up JS_ATOM_constructor when is_reject==0. + promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&value), + /*is_reject*/0); + // A poisoned .constructor property is observable and the resulting + // exception should be delivered to the catch handler. + if (JS_IsException(promise)) { + JSValue err = JS_GetException(ctx); + promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&err), + /*is_reject*/1); + JS_FreeValue(ctx, err); + if (JS_IsException(promise)) + return -1; + } + if (js_async_generator_resolve_function_create(ctx, + JS_MKPTR(JS_TAG_OBJECT, s->generator), + resolving_funcs1, + true)) { + JS_FreeValue(ctx, promise); + return -1; + } + resolving_funcs[0] = JS_UNDEFINED; + resolving_funcs[1] = JS_UNDEFINED; + res = perform_promise_then(ctx, promise, + vc(resolving_funcs1), + vc(resolving_funcs)); + JS_FreeValue(ctx, resolving_funcs1[0]); + JS_FreeValue(ctx, resolving_funcs1[1]); + JS_FreeValue(ctx, promise); + return res; +} + +static void js_async_generator_resume_next(JSContext *ctx, + JSAsyncGeneratorData *s) +{ + JSAsyncGeneratorRequest *next; + JSValue func_ret, value; + + for(;;) { + if (list_empty(&s->queue)) + break; + next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link); + switch(s->state) { + case JS_ASYNC_GENERATOR_STATE_EXECUTING: + /* only happens when restarting execution after await() */ + goto resume_exec; + case JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN: + goto done; + case JS_ASYNC_GENERATOR_STATE_SUSPENDED_START: + if (next->completion_type == GEN_MAGIC_NEXT) { + goto exec_no_arg; + } else { + js_async_generator_complete(ctx, s); + } + break; + case JS_ASYNC_GENERATOR_STATE_COMPLETED: + if (next->completion_type == GEN_MAGIC_NEXT) { + js_async_generator_resolve(ctx, s, JS_UNDEFINED, true); + } else if (next->completion_type == GEN_MAGIC_RETURN) { + s->state = JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN; + js_async_generator_completed_return(ctx, s, next->result); + } else { + js_async_generator_reject(ctx, s, next->result); + } + goto done; + case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD: + case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR: + value = js_dup(next->result); + if (next->completion_type == GEN_MAGIC_THROW && + s->state == JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD) { + JS_Throw(ctx, value); + s->func_state.throw_flag = true; + } else { + /* 'yield' returns a value. 'yield *' also returns a value + in case the 'throw' method is called */ + s->func_state.frame.cur_sp[-1] = value; + s->func_state.frame.cur_sp[0] = + js_int32(next->completion_type); + s->func_state.frame.cur_sp++; + exec_no_arg: + s->func_state.throw_flag = false; + } + s->state = JS_ASYNC_GENERATOR_STATE_EXECUTING; + resume_exec: + func_ret = async_func_resume(ctx, &s->func_state); + if (JS_IsException(func_ret)) { + value = JS_GetException(ctx); + js_async_generator_complete(ctx, s); + js_async_generator_reject(ctx, s, value); + JS_FreeValue(ctx, value); + } else if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) { + int func_ret_code, ret; + value = s->func_state.frame.cur_sp[-1]; + s->func_state.frame.cur_sp[-1] = JS_UNDEFINED; + func_ret_code = JS_VALUE_GET_INT(func_ret); + switch(func_ret_code) { + case FUNC_RET_YIELD: + case FUNC_RET_YIELD_STAR: + if (func_ret_code == FUNC_RET_YIELD_STAR) + s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR; + else + s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD; + js_async_generator_resolve(ctx, s, value, false); + JS_FreeValue(ctx, value); + break; + case FUNC_RET_AWAIT: + ret = js_async_generator_await(ctx, s, value); + JS_FreeValue(ctx, value); + if (ret < 0) { + /* exception: throw it */ + s->func_state.throw_flag = true; + goto resume_exec; + } + goto done; + default: + abort(); + } + } else { + assert(JS_IsUndefined(func_ret)); + /* end of function */ + value = s->func_state.frame.cur_sp[-1]; + s->func_state.frame.cur_sp[-1] = JS_UNDEFINED; + js_async_generator_complete(ctx, s); + js_async_generator_resolve(ctx, s, value, true); + JS_FreeValue(ctx, value); + } + break; + default: + abort(); + } + } + done: ; +} + +static JSValue js_async_generator_resolve_function(JSContext *ctx, + JSValueConst this_obj, + int argc, JSValueConst *argv, + int magic, JSValueConst *func_data) +{ + bool is_reject = magic & 1; + JSAsyncGeneratorData *s = JS_GetOpaque(func_data[0], JS_CLASS_ASYNC_GENERATOR); + JSValueConst arg = argv[0]; + + /* XXX: what if s == NULL */ + + if (magic >= 2) { + /* resume next case in AWAITING_RETURN state */ + assert(s->state == JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN || + s->state == JS_ASYNC_GENERATOR_STATE_COMPLETED); + s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED; + if (is_reject) { + js_async_generator_reject(ctx, s, arg); + } else { + js_async_generator_resolve(ctx, s, arg, true); + } + } else { + /* restart function execution after await() */ + assert(s->state == JS_ASYNC_GENERATOR_STATE_EXECUTING); + s->func_state.throw_flag = is_reject; + if (is_reject) { + JS_Throw(ctx, js_dup(arg)); + } else { + /* return value of await */ + s->func_state.frame.cur_sp[-1] = js_dup(arg); + } + js_async_generator_resume_next(ctx, s); + } + return JS_UNDEFINED; +} + +/* magic = GEN_MAGIC_x */ +static JSValue js_async_generator_next(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv, + int magic) +{ + JSAsyncGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_GENERATOR); + JSValue promise, resolving_funcs[2]; + JSAsyncGeneratorRequest *req; + + promise = JS_NewPromiseCapability(ctx, resolving_funcs); + if (JS_IsException(promise)) + return JS_EXCEPTION; + if (!s) { + JSValue err, res2; + JS_ThrowTypeError(ctx, "not an AsyncGenerator object"); + err = JS_GetException(ctx); + res2 = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, + 1, vc(&err)); + JS_FreeValue(ctx, err); + JS_FreeValue(ctx, res2); + JS_FreeValue(ctx, resolving_funcs[0]); + JS_FreeValue(ctx, resolving_funcs[1]); + return promise; + } + req = js_mallocz(ctx, sizeof(*req)); + if (!req) + goto fail; + req->completion_type = magic; + req->result = js_dup(argv[0]); + req->promise = js_dup(promise); + req->resolving_funcs[0] = resolving_funcs[0]; + req->resolving_funcs[1] = resolving_funcs[1]; + list_add_tail(&req->link, &s->queue); + if (s->state != JS_ASYNC_GENERATOR_STATE_EXECUTING) { + js_async_generator_resume_next(ctx, s); + } + return promise; + fail: + JS_FreeValue(ctx, resolving_funcs[0]); + JS_FreeValue(ctx, resolving_funcs[1]); + JS_FreeValue(ctx, promise); + return JS_EXCEPTION; +} + +static JSValue js_async_generator_function_call(JSContext *ctx, + JSValueConst func_obj, + JSValueConst this_obj, + int argc, JSValueConst *argv, + int flags) +{ + JSValue obj, func_ret; + JSAsyncGeneratorData *s; + + s = js_mallocz(ctx, sizeof(*s)); + if (!s) + return JS_EXCEPTION; + s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_START; + init_list_head(&s->queue); + if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { + s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED; + goto fail; + } + + /* execute the function up to 'OP_initial_yield' (no yield nor + await are possible) */ + func_ret = async_func_resume(ctx, &s->func_state); + if (JS_IsException(func_ret)) + goto fail; + JS_FreeValue(ctx, func_ret); + + obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_ASYNC_GENERATOR); + if (JS_IsException(obj)) + goto fail; + s->generator = JS_VALUE_GET_OBJ(obj); + JS_SetOpaqueInternal(obj, s); + return obj; + fail: + js_async_generator_free(ctx->rt, s); + return JS_EXCEPTION; +} + +/* JS parser */ + +enum { + TOK_NUMBER = -128, + TOK_STRING, + TOK_TEMPLATE, + TOK_IDENT, + TOK_REGEXP, + /* warning: order matters (see js_parse_assign_expr) */ + TOK_MUL_ASSIGN, + TOK_DIV_ASSIGN, + TOK_MOD_ASSIGN, + TOK_PLUS_ASSIGN, + TOK_MINUS_ASSIGN, + TOK_SHL_ASSIGN, + TOK_SAR_ASSIGN, + TOK_SHR_ASSIGN, + TOK_AND_ASSIGN, + TOK_XOR_ASSIGN, + TOK_OR_ASSIGN, + TOK_POW_ASSIGN, + TOK_LAND_ASSIGN, + TOK_LOR_ASSIGN, + TOK_DOUBLE_QUESTION_MARK_ASSIGN, + TOK_DEC, + TOK_INC, + TOK_SHL, + TOK_SAR, + TOK_SHR, + TOK_LT, + TOK_LTE, + TOK_GT, + TOK_GTE, + TOK_EQ, + TOK_STRICT_EQ, + TOK_NEQ, + TOK_STRICT_NEQ, + TOK_LAND, + TOK_LOR, + TOK_POW, + TOK_ARROW, + TOK_ELLIPSIS, + TOK_DOUBLE_QUESTION_MARK, + TOK_QUESTION_MARK_DOT, + TOK_ERROR, + TOK_PRIVATE_NAME, + TOK_EOF, + /* keywords: WARNING: same order as atoms */ + TOK_NULL, /* must be first */ + TOK_FALSE, + TOK_TRUE, + TOK_IF, + TOK_ELSE, + TOK_RETURN, + TOK_VAR, + TOK_THIS, + TOK_DELETE, + TOK_VOID, + TOK_TYPEOF, + TOK_NEW, + TOK_IN, + TOK_INSTANCEOF, + TOK_DO, + TOK_WHILE, + TOK_FOR, + TOK_BREAK, + TOK_CONTINUE, + TOK_SWITCH, + TOK_CASE, + TOK_DEFAULT, + TOK_THROW, + TOK_TRY, + TOK_CATCH, + TOK_FINALLY, + TOK_FUNCTION, + TOK_DEBUGGER, + TOK_WITH, + /* FutureReservedWord */ + TOK_CLASS, + TOK_CONST, + TOK_ENUM, + TOK_EXPORT, + TOK_EXTENDS, + TOK_IMPORT, + TOK_SUPER, + /* FutureReservedWords when parsing strict mode code */ + TOK_IMPLEMENTS, + TOK_INTERFACE, + TOK_LET, + TOK_PACKAGE, + TOK_PRIVATE, + TOK_PROTECTED, + TOK_PUBLIC, + TOK_STATIC, + TOK_YIELD, + TOK_AWAIT, /* must be last */ + TOK_OF, /* only used for js_parse_skip_parens_token() */ +}; + +#define TOK_FIRST_KEYWORD TOK_NULL +#define TOK_LAST_KEYWORD TOK_AWAIT + +/* unicode code points */ +#define CP_NBSP 0x00a0 +#define CP_BOM 0xfeff + +#define CP_LS 0x2028 +#define CP_PS 0x2029 + +typedef struct BlockEnv { + struct BlockEnv *prev; + JSAtom label_name; /* JS_ATOM_NULL if none */ + int label_break; /* -1 if none */ + int label_cont; /* -1 if none */ + int drop_count; /* number of stack elements to drop */ + int label_finally; /* -1 if none */ + int scope_level; + uint8_t has_iterator : 1; + uint8_t is_regular_stmt : 1; // i.e. not a loop statement +} BlockEnv; + +typedef struct JSGlobalVar { + int cpool_idx; /* if >= 0, index in the constant pool for hoisted + function defintion*/ + uint8_t force_init : 1; /* force initialization to undefined */ + uint8_t is_lexical : 1; /* global let/const definition */ + uint8_t is_const : 1; /* const definition */ + int scope_level; /* scope of definition */ + JSAtom var_name; /* variable name */ +} JSGlobalVar; + +typedef struct RelocEntry { + struct RelocEntry *next; + uint32_t addr; /* address to patch */ + int size; /* address size: 1, 2 or 4 bytes */ +} RelocEntry; + +typedef struct JumpSlot { + int op; + int size; + int pos; + int label; +} JumpSlot; + +typedef struct LabelSlot { + int ref_count; + int pos; /* phase 1 address, -1 means not resolved yet */ + int pos2; /* phase 2 address, -1 means not resolved yet */ + int addr; /* phase 3 address, -1 means not resolved yet */ + RelocEntry *first_reloc; +} LabelSlot; + +typedef struct SourceLocSlot { + uint32_t pc; + int line_num; + int col_num; +} SourceLocSlot; + +typedef enum JSParseFunctionEnum { + JS_PARSE_FUNC_STATEMENT, + JS_PARSE_FUNC_VAR, + JS_PARSE_FUNC_EXPR, + JS_PARSE_FUNC_ARROW, + JS_PARSE_FUNC_GETTER, + JS_PARSE_FUNC_SETTER, + JS_PARSE_FUNC_METHOD, + JS_PARSE_FUNC_CLASS_STATIC_INIT, + JS_PARSE_FUNC_CLASS_CONSTRUCTOR, + JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR, +} JSParseFunctionEnum; + +typedef enum JSParseExportEnum { + JS_PARSE_EXPORT_NONE, + JS_PARSE_EXPORT_NAMED, + JS_PARSE_EXPORT_DEFAULT, +} JSParseExportEnum; + +typedef struct JSFunctionDef { + JSContext *ctx; + struct JSFunctionDef *parent; + int parent_cpool_idx; /* index in the constant pool of the parent + or -1 if none */ + int parent_scope_level; /* scope level in parent at point of definition */ + struct list_head child_list; /* list of JSFunctionDef.link */ + struct list_head link; + + int eval_type; /* only valid if is_eval = true */ + + /* Pack all boolean flags together as 1-bit fields to reduce struct size + while avoiding padding and compiler deoptimization. */ + bool is_eval : 1; /* true if eval code */ + bool is_global_var : 1; /* true if variables are not defined locally: + eval global, eval module or non strict eval */ + bool is_func_expr : 1; /* true if function expression */ + bool has_home_object : 1; /* true if the home object is available */ + bool has_prototype : 1; /* true if a prototype field is necessary */ + bool has_simple_parameter_list : 1; + bool has_parameter_expressions : 1; /* if true, an argument scope is created */ + bool has_use_strict : 1; /* to reject directive in special cases */ + bool has_eval_call : 1; /* true if the function contains a call to eval() */ + bool has_arguments_binding : 1; /* true if the 'arguments' binding is + available in the function */ + bool has_this_binding : 1; /* true if the 'this' and new.target binding are + available in the function */ + bool new_target_allowed : 1; /* true if the 'new.target' does not + throw a syntax error */ + bool super_call_allowed : 1; /* true if super() is allowed */ + bool super_allowed : 1; /* true if super. or super[] is allowed */ + bool arguments_allowed : 1; /* true if the 'arguments' identifier is allowed */ + bool is_derived_class_constructor : 1; + bool in_function_body : 1; + bool backtrace_barrier : 1; + bool need_home_object : 1; + bool use_short_opcodes : 1; /* true if short opcodes are used in byte_code */ + bool has_await : 1; /* true if await is used (used in module eval) */ + + JSFunctionKindEnum func_kind : 8; + JSParseFunctionEnum func_type : 7; + uint8_t is_strict_mode : 1; + JSAtom func_name; /* JS_ATOM_NULL if no name */ + + JSVarDef *vars; + uint32_t *vars_htab; // indexes into vars[] + int var_size; /* allocated size for vars[] */ + int var_count; + JSVarDef *args; + int arg_size; /* allocated size for args[] */ + int arg_count; /* number of arguments */ + int defined_arg_count; + int var_ref_count; /* number of local/arg variable references */ + int var_object_idx; /* -1 if none */ + int arg_var_object_idx; /* -1 if none (var object for the argument scope) */ + int arguments_var_idx; /* -1 if none */ + int arguments_arg_idx; /* argument variable definition in argument scope, + -1 if none */ + int func_var_idx; /* variable containing the current function (-1 + if none, only used if is_func_expr is true) */ + int eval_ret_idx; /* variable containing the return value of the eval, -1 if none */ + int this_var_idx; /* variable containg the 'this' value, -1 if none */ + int new_target_var_idx; /* variable containg the 'new.target' value, -1 if none */ + int this_active_func_var_idx; /* variable containg the 'this.active_func' value, -1 if none */ + int home_object_var_idx; + + int scope_level; /* index into fd->scopes if the current lexical scope */ + int scope_first; /* index into vd->vars of first lexically scoped variable */ + int scope_size; /* allocated size of fd->scopes array */ + int scope_count; /* number of entries used in the fd->scopes array */ + JSVarScope *scopes; + JSVarScope def_scope_array[4]; + int body_scope; /* scope of the body of the function or eval */ + + int global_var_count; + int global_var_size; + JSGlobalVar *global_vars; + + DynBuf byte_code; + int last_opcode_pos; /* -1 if no last opcode */ + + LabelSlot *label_slots; + int label_size; /* allocated size for label_slots[] */ + int label_count; + BlockEnv *top_break; /* break/continue label stack */ + + /* constant pool (strings, functions, numbers) */ + JSValue *cpool; + int cpool_count; + int cpool_size; + + /* list of variables in the closure */ + int closure_var_count; + int closure_var_size; + JSClosureVar *closure_var; + + JumpSlot *jump_slots; + int jump_size; + int jump_count; + + SourceLocSlot *source_loc_slots; + int source_loc_size; + int source_loc_count; + int line_number_last; + int line_number_last_pc; + int col_number_last; + + /* pc2line table */ + JSAtom filename; + int line_num; + int col_num; + DynBuf pc2line; + + char *source; /* raw source, utf-8 encoded */ + int source_len; + + JSModuleDef *module; /* != NULL when parsing a module */ +} JSFunctionDef; + +typedef struct JSToken { + int val; + int line_num; /* line number of token start */ + int col_num; /* column number of token start */ + const uint8_t *ptr; + union { + struct { + JSValue str; + int sep; + } str; + struct { + JSValue val; + } num; + struct { + JSAtom atom; + bool has_escape; + bool is_reserved; + } ident; + struct { + JSValue body; + JSValue flags; + } regexp; + } u; +} JSToken; + +typedef struct JSParseState { + JSContext *ctx; + int last_line_num; /* line number of last token */ + int last_col_num; /* column number of last token */ + int line_num; /* line number of current offset */ + int col_num; /* column number of current offset */ + const char *filename; + JSToken token; + bool got_lf; /* true if got line feed before the current token */ + const uint8_t *last_ptr; + const uint8_t *buf_start; + const uint8_t *buf_ptr; + const uint8_t *buf_end; + const uint8_t *eol; // most recently seen end-of-line character + const uint8_t *mark; // first token character, invariant: eol < mark + + /* current function code */ + JSFunctionDef *cur_func; + bool is_module; /* parsing a module */ + bool allow_html_comments; +} JSParseState; + +typedef struct JSOpCode { +#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_* + const char *name; +#endif + uint8_t size; /* in bytes */ + /* the opcodes remove n_pop items from the top of the stack, then + pushes n_push items */ + uint8_t n_pop; + uint8_t n_push; + uint8_t fmt; +} JSOpCode; + +static const JSOpCode opcode_info[OP_COUNT + (OP_TEMP_END - OP_TEMP_START)] = { +#define FMT(f) +#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_* +#define DEF(id, size, n_pop, n_push, f) { #id, size, n_pop, n_push, OP_FMT_ ## f }, +#else +#define DEF(id, size, n_pop, n_push, f) { size, n_pop, n_push, OP_FMT_ ## f }, +#endif +/* + * QuickJS opcode definitions + * + * Copyright (c) 2017-2018 Fabrice Bellard + * Copyright (c) 2017-2018 Charlie Gordon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifdef FMT +FMT(none) +FMT(none_int) +FMT(none_loc) +FMT(none_arg) +FMT(none_var_ref) +FMT(u8) +FMT(i8) +FMT(loc8) +FMT(const8) +FMT(label8) +FMT(u16) +FMT(i16) +FMT(label16) +FMT(npop) +FMT(npopx) +FMT(npop_u16) +FMT(loc) +FMT(arg) +FMT(var_ref) +FMT(u32) +FMT(u32x2) +FMT(i32) +FMT(const) +FMT(label) +FMT(atom) +FMT(atom_u8) +FMT(atom_u16) +FMT(atom_label_u8) +FMT(atom_label_u16) +FMT(label_u16) +#undef FMT +#endif /* FMT */ + +#ifdef DEF + +#ifndef def +#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f) +#endif + +DEF(invalid, 1, 0, 0, none) /* never emitted */ + +/* push values */ +DEF( push_i32, 5, 0, 1, i32) +DEF( push_const, 5, 0, 1, const) +DEF( fclosure, 5, 0, 1, const) /* must follow push_const */ +DEF(push_atom_value, 5, 0, 1, atom) +DEF( private_symbol, 5, 0, 1, atom) +DEF( undefined, 1, 0, 1, none) +DEF( null, 1, 0, 1, none) +DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */ +DEF( push_false, 1, 0, 1, none) +DEF( push_true, 1, 0, 1, none) +DEF( object, 1, 0, 1, none) +DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */ +DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */ + +DEF( drop, 1, 1, 0, none) /* a -> */ +DEF( nip, 1, 2, 1, none) /* a b -> b */ +DEF( nip1, 1, 3, 2, none) /* a b c -> b c */ +DEF( dup, 1, 1, 2, none) /* a -> a a */ +DEF( dup1, 1, 2, 3, none) /* a b -> a a b */ +DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */ +DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */ +DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */ +DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */ +DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */ +DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */ +DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */ +DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */ +DEF( swap, 1, 2, 2, none) /* a b -> b a */ +DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */ +DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */ +DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */ +DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */ +DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */ + +DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */ +DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */ +DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */ +DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */ +DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */ +DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */ +DEF( apply, 3, 3, 1, u16) +DEF( return, 1, 1, 0, none) +DEF( return_undef, 1, 0, 0, none) +DEF(check_ctor_return, 1, 1, 2, none) +DEF( check_ctor, 1, 0, 0, none) +DEF( init_ctor, 1, 0, 1, none) +DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */ +DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */ +DEF( return_async, 1, 1, 0, none) +DEF( throw, 1, 1, 0, none) +DEF( throw_error, 6, 0, 0, atom_u8) +DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */ +DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */ +DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a + bytecode string */ +DEF( get_super, 1, 1, 1, none) +DEF( import, 1, 2, 1, none) /* dynamic module import */ + +DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */ +DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */ +DEF( put_var, 5, 1, 0, atom) /* must come after get_var */ +DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */ + +DEF( get_ref_value, 1, 2, 3, none) +DEF( put_ref_value, 1, 3, 0, none) + +DEF( define_var, 6, 0, 0, atom_u8) +DEF(check_define_var, 6, 0, 0, atom_u8) +DEF( define_func, 6, 1, 0, atom_u8) + +// order matters, see IC counterparts +DEF( get_field, 5, 1, 1, atom) +DEF( get_field2, 5, 1, 2, atom) +DEF( put_field, 5, 2, 0, atom) + +DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */ +DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */ +DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */ +DEF( get_array_el, 1, 2, 1, none) +DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */ +DEF( put_array_el, 1, 3, 0, none) +DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */ +DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */ +DEF( define_field, 5, 2, 1, atom) +DEF( set_name, 5, 1, 1, atom) +DEF(set_name_computed, 1, 2, 2, none) +DEF( set_proto, 1, 2, 1, none) +DEF(set_home_object, 1, 2, 2, none) +DEF(define_array_el, 1, 3, 2, none) +DEF( append, 1, 3, 2, none) /* append enumerated object, update length */ +DEF(copy_data_properties, 2, 3, 3, u8) +DEF( define_method, 6, 2, 1, atom_u8) +DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */ +DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */ +DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */ + +DEF( get_loc, 3, 0, 1, loc) +DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */ +DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */ +DEF( get_arg, 3, 0, 1, arg) +DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */ +DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */ +DEF( get_var_ref, 3, 0, 1, var_ref) +DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */ +DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */ +DEF(set_loc_uninitialized, 3, 0, 0, loc) +DEF( get_loc_check, 3, 0, 1, loc) +DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */ +DEF( put_loc_check_init, 3, 1, 0, loc) +DEF(get_var_ref_check, 3, 0, 1, var_ref) +DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */ +DEF(put_var_ref_check_init, 3, 1, 0, var_ref) +DEF( close_loc, 3, 0, 0, loc) +DEF( if_false, 5, 1, 0, label) +DEF( if_true, 5, 1, 0, label) /* must come after if_false */ +DEF( goto, 5, 0, 0, label) /* must come after if_true */ +DEF( catch, 5, 0, 1, label) +DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */ +DEF( ret, 1, 1, 0, none) /* used to return from the finally block */ +DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */ + +DEF( to_object, 1, 1, 1, none) +//DEF( to_string, 1, 1, 1, none) +DEF( to_propkey, 1, 1, 1, none) +DEF( to_propkey2, 1, 2, 2, none) + +DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */ +DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8) + +DEF( make_loc_ref, 7, 0, 2, atom_u16) +DEF( make_arg_ref, 7, 0, 2, atom_u16) +DEF(make_var_ref_ref, 7, 0, 2, atom_u16) +DEF( make_var_ref, 5, 0, 2, atom) + +DEF( for_in_start, 1, 1, 1, none) +DEF( for_of_start, 1, 1, 3, none) +DEF(for_await_of_start, 1, 1, 3, none) +DEF( for_in_next, 1, 1, 3, none) +DEF( for_of_next, 2, 3, 5, u8) +DEF(iterator_check_object, 1, 1, 1, none) +DEF(iterator_get_value_done, 1, 1, 2, none) +DEF( iterator_close, 1, 3, 0, none) +DEF( iterator_next, 1, 4, 4, none) +DEF( iterator_call, 2, 4, 5, u8) +DEF( initial_yield, 1, 0, 0, none) +DEF( yield, 1, 1, 2, none) +DEF( yield_star, 1, 1, 2, none) +DEF(async_yield_star, 1, 1, 2, none) +DEF( await, 1, 1, 1, none) + +/* arithmetic/logic operations */ +DEF( neg, 1, 1, 1, none) +DEF( plus, 1, 1, 1, none) +DEF( dec, 1, 1, 1, none) +DEF( inc, 1, 1, 1, none) +DEF( post_dec, 1, 1, 2, none) +DEF( post_inc, 1, 1, 2, none) +DEF( dec_loc, 2, 0, 0, loc8) +DEF( inc_loc, 2, 0, 0, loc8) +DEF( add_loc, 2, 1, 0, loc8) +DEF( not, 1, 1, 1, none) +DEF( lnot, 1, 1, 1, none) +DEF( typeof, 1, 1, 1, none) +DEF( delete, 1, 2, 1, none) +DEF( delete_var, 5, 0, 1, atom) + +/* warning: order matters (see js_parse_assign_expr) */ +DEF( mul, 1, 2, 1, none) +DEF( div, 1, 2, 1, none) +DEF( mod, 1, 2, 1, none) +DEF( add, 1, 2, 1, none) +DEF( sub, 1, 2, 1, none) +DEF( shl, 1, 2, 1, none) +DEF( sar, 1, 2, 1, none) +DEF( shr, 1, 2, 1, none) +DEF( and, 1, 2, 1, none) +DEF( xor, 1, 2, 1, none) +DEF( or, 1, 2, 1, none) +DEF( pow, 1, 2, 1, none) + +DEF( lt, 1, 2, 1, none) +DEF( lte, 1, 2, 1, none) +DEF( gt, 1, 2, 1, none) +DEF( gte, 1, 2, 1, none) +DEF( instanceof, 1, 2, 1, none) +DEF( in, 1, 2, 1, none) +DEF( eq, 1, 2, 1, none) +DEF( neq, 1, 2, 1, none) +DEF( strict_eq, 1, 2, 1, none) +DEF( strict_neq, 1, 2, 1, none) +DEF(is_undefined_or_null, 1, 1, 1, none) +DEF( private_in, 1, 2, 1, none) +DEF(push_bigint_i32, 5, 0, 1, i32) +/* must be the last non short and non temporary opcode */ +DEF( nop, 1, 0, 0, none) + +/* temporary opcodes: never emitted in the final bytecode */ + +def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ +def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */ + +def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */ + +def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */ +def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */ +def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */ +def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */ +def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */ +def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */ +def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */ +def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */ + +def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */ + +DEF( push_minus1, 1, 0, 1, none_int) +DEF( push_0, 1, 0, 1, none_int) +DEF( push_1, 1, 0, 1, none_int) +DEF( push_2, 1, 0, 1, none_int) +DEF( push_3, 1, 0, 1, none_int) +DEF( push_4, 1, 0, 1, none_int) +DEF( push_5, 1, 0, 1, none_int) +DEF( push_6, 1, 0, 1, none_int) +DEF( push_7, 1, 0, 1, none_int) +DEF( push_i8, 2, 0, 1, i8) +DEF( push_i16, 3, 0, 1, i16) +DEF( push_const8, 2, 0, 1, const8) +DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */ +DEF(push_empty_string, 1, 0, 1, none) + +DEF( get_loc8, 2, 0, 1, loc8) +DEF( put_loc8, 2, 1, 0, loc8) +DEF( set_loc8, 2, 1, 1, loc8) + +DEF( get_loc0_loc1, 1, 0, 2, none_loc) +DEF( get_loc0, 1, 0, 1, none_loc) +DEF( get_loc1, 1, 0, 1, none_loc) +DEF( get_loc2, 1, 0, 1, none_loc) +DEF( get_loc3, 1, 0, 1, none_loc) +DEF( put_loc0, 1, 1, 0, none_loc) +DEF( put_loc1, 1, 1, 0, none_loc) +DEF( put_loc2, 1, 1, 0, none_loc) +DEF( put_loc3, 1, 1, 0, none_loc) +DEF( set_loc0, 1, 1, 1, none_loc) +DEF( set_loc1, 1, 1, 1, none_loc) +DEF( set_loc2, 1, 1, 1, none_loc) +DEF( set_loc3, 1, 1, 1, none_loc) +DEF( get_arg0, 1, 0, 1, none_arg) +DEF( get_arg1, 1, 0, 1, none_arg) +DEF( get_arg2, 1, 0, 1, none_arg) +DEF( get_arg3, 1, 0, 1, none_arg) +DEF( put_arg0, 1, 1, 0, none_arg) +DEF( put_arg1, 1, 1, 0, none_arg) +DEF( put_arg2, 1, 1, 0, none_arg) +DEF( put_arg3, 1, 1, 0, none_arg) +DEF( set_arg0, 1, 1, 1, none_arg) +DEF( set_arg1, 1, 1, 1, none_arg) +DEF( set_arg2, 1, 1, 1, none_arg) +DEF( set_arg3, 1, 1, 1, none_arg) +DEF( get_var_ref0, 1, 0, 1, none_var_ref) +DEF( get_var_ref1, 1, 0, 1, none_var_ref) +DEF( get_var_ref2, 1, 0, 1, none_var_ref) +DEF( get_var_ref3, 1, 0, 1, none_var_ref) +DEF( put_var_ref0, 1, 1, 0, none_var_ref) +DEF( put_var_ref1, 1, 1, 0, none_var_ref) +DEF( put_var_ref2, 1, 1, 0, none_var_ref) +DEF( put_var_ref3, 1, 1, 0, none_var_ref) +DEF( set_var_ref0, 1, 1, 1, none_var_ref) +DEF( set_var_ref1, 1, 1, 1, none_var_ref) +DEF( set_var_ref2, 1, 1, 1, none_var_ref) +DEF( set_var_ref3, 1, 1, 1, none_var_ref) + +DEF( get_length, 1, 1, 1, none) + +DEF( if_false8, 2, 1, 0, label8) +DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */ +DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */ +DEF( goto16, 3, 0, 0, label16) + +DEF( call0, 1, 1, 1, npopx) +DEF( call1, 1, 1, 1, npopx) +DEF( call2, 1, 1, 1, npopx) +DEF( call3, 1, 1, 1, npopx) + +DEF( is_undefined, 1, 1, 1, none) +DEF( is_null, 1, 1, 1, none) +DEF(typeof_is_undefined, 1, 1, 1, none) +DEF( typeof_is_function, 1, 1, 1, none) + +#undef DEF +#undef def +#endif /* DEF */ + +#undef DEF +#undef FMT +}; + +/* After the final compilation pass, short opcodes are used. Their + opcodes overlap with the temporary opcodes which cannot appear in + the final bytecode. Their description is after the temporary + opcodes in opcode_info[]. */ +#define short_opcode_info(op) \ + opcode_info[(op) >= OP_TEMP_START ? \ + (op) + (OP_TEMP_END - OP_TEMP_START) : (op)] + +static void json_free_token(JSParseState *s, JSToken *token) { + // Only free actual allocated values + switch(token->val) { + case TOK_NUMBER: + JS_FreeValue(s->ctx, token->u.num.val); + break; + case TOK_STRING: + JS_FreeValue(s->ctx, token->u.str.str); + break; + case TOK_IDENT: + JS_FreeAtom(s->ctx, token->u.ident.atom); + break; + } +} + +static void free_token(JSParseState *s, JSToken *token) +{ + switch(token->val) { + case TOK_NUMBER: + JS_FreeValue(s->ctx, token->u.num.val); + break; + case TOK_STRING: + case TOK_TEMPLATE: + JS_FreeValue(s->ctx, token->u.str.str); + break; + case TOK_REGEXP: + JS_FreeValue(s->ctx, token->u.regexp.body); + JS_FreeValue(s->ctx, token->u.regexp.flags); + break; + case TOK_IDENT: + case TOK_PRIVATE_NAME: + JS_FreeAtom(s->ctx, token->u.ident.atom); + break; + default: + if (token->val >= TOK_FIRST_KEYWORD && + token->val <= TOK_LAST_KEYWORD) { + JS_FreeAtom(s->ctx, token->u.ident.atom); + } + break; + } +} + +static void __attribute((unused)) dump_token(JSParseState *s, + const JSToken *token) +{ + printf("%d:%d ", token->line_num, token->col_num); + switch(token->val) { + case TOK_NUMBER: + { + double d; + JS_ToFloat64(s->ctx, &d, token->u.num.val); /* no exception possible */ + printf("number: %.14g\n", d); + } + break; + case TOK_IDENT: + dump_atom: + { + char buf[ATOM_GET_STR_BUF_SIZE]; + printf("ident: '%s'\n", + JS_AtomGetStr(s->ctx, buf, sizeof(buf), token->u.ident.atom)); + } + break; + case TOK_STRING: + { + const char *str; + /* XXX: quote the string */ + str = JS_ToCString(s->ctx, token->u.str.str); + printf("string: '%s'\n", str); + JS_FreeCString(s->ctx, str); + } + break; + case TOK_TEMPLATE: + { + const char *str; + str = JS_ToCString(s->ctx, token->u.str.str); + printf("template: `%s`\n", str); + JS_FreeCString(s->ctx, str); + } + break; + case TOK_REGEXP: + { + const char *str, *str2; + str = JS_ToCString(s->ctx, token->u.regexp.body); + str2 = JS_ToCString(s->ctx, token->u.regexp.flags); + printf("regexp: '%s' '%s'\n", str, str2); + JS_FreeCString(s->ctx, str); + JS_FreeCString(s->ctx, str2); + } + break; + case TOK_EOF: + printf("eof\n"); + break; + default: + if (s->token.val >= TOK_NULL && s->token.val <= TOK_LAST_KEYWORD) { + goto dump_atom; + } else if (s->token.val >= 256) { + printf("token: %d\n", token->val); + } else { + printf("token: '%c'\n", token->val); + } + break; + } +} + +int JS_PRINTF_FORMAT_ATTR(2, 3) js_parse_error(JSParseState *s, JS_PRINTF_FORMAT const char *fmt, ...) +{ + JSContext *ctx = s->ctx; + va_list ap; + int backtrace_flags; + + va_start(ap, fmt); + JS_ThrowError2(ctx, JS_SYNTAX_ERROR, false, fmt, ap); + va_end(ap); + backtrace_flags = 0; + if (s->cur_func && s->cur_func->backtrace_barrier) + backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL; + build_backtrace(ctx, ctx->rt->current_exception, JS_UNDEFINED, s->filename, + s->line_num, s->col_num, backtrace_flags); + return -1; +} + +#ifndef QJS_DISABLE_PARSER + +static __exception int next_token(JSParseState *s); + +static int js_parse_expect(JSParseState *s, int tok) +{ + char buf[ATOM_GET_STR_BUF_SIZE]; + + if (s->token.val == tok) + return next_token(s); + + switch(s->token.val) { + case TOK_EOF: + return js_parse_error(s, "Unexpected end of input"); + case TOK_NUMBER: + return js_parse_error(s, "Unexpected number"); + case TOK_STRING: + return js_parse_error(s, "Unexpected string"); + case TOK_TEMPLATE: + return js_parse_error(s, "Unexpected string template"); + case TOK_REGEXP: + return js_parse_error(s, "Unexpected regexp"); + case TOK_IDENT: + return js_parse_error(s, "Unexpected identifier '%s'", + JS_AtomGetStr(s->ctx, buf, sizeof(buf), + s->token.u.ident.atom)); + case TOK_ERROR: + return js_parse_error(s, "Invalid or unexpected token"); + default: + return js_parse_error(s, "Unexpected token '%.*s'", + (int)(s->buf_ptr - s->token.ptr), + (const char *)s->token.ptr); + } +} + +static int js_parse_expect_semi(JSParseState *s) +{ + if (s->token.val != ';') { + /* automatic insertion of ';' */ + if (s->token.val == TOK_EOF || s->token.val == '}' || s->got_lf) { + return 0; + } + return js_parse_error(s, "expecting '%c'", ';'); + } + return next_token(s); +} + +static int js_parse_error_reserved_identifier(JSParseState *s) +{ + char buf1[ATOM_GET_STR_BUF_SIZE]; + return js_parse_error(s, "'%s' is a reserved identifier", + JS_AtomGetStr(s->ctx, buf1, sizeof(buf1), + s->token.u.ident.atom)); +} + +static __exception int js_parse_template_part(JSParseState *s, + const uint8_t *p) +{ + const uint8_t *p_next; + uint32_t c; + StringBuffer b_s, *b = &b_s; + JSValue str; + + /* p points to the first byte of the template part */ + if (string_buffer_init(s->ctx, b, 32)) + goto fail; + for(;;) { + if (p >= s->buf_end) + goto unexpected_eof; + c = *p++; + if (c == '`') { + /* template end part */ + break; + } + if (c == '$' && *p == '{') { + /* template start or middle part */ + p++; + break; + } + if (c == '\\') { + if (string_buffer_putc8(b, c)) + goto fail; + if (p >= s->buf_end) + goto unexpected_eof; + c = *p++; + } + /* newline sequences are normalized as single '\n' bytes */ + if (c == '\r') { + if (*p == '\n') + p++; + c = '\n'; + } + if (c == '\n') { + s->line_num++; + s->eol = &p[-1]; + s->mark = p; + } else if (c >= 0x80) { + c = utf8_decode(p - 1, &p_next); + if (p_next == p) { + js_parse_error(s, "invalid UTF-8 sequence"); + goto fail; + } + p = p_next; + } + if (string_buffer_putc(b, c)) + goto fail; + } + str = string_buffer_end(b); + if (JS_IsException(str)) + return -1; + s->token.val = TOK_TEMPLATE; + s->token.u.str.sep = c; + s->token.u.str.str = str; + s->buf_ptr = p; + return 0; + + unexpected_eof: + js_parse_error(s, "unexpected end of string"); + fail: + string_buffer_free(b); + return -1; +} + +static __exception int js_parse_string(JSParseState *s, int sep, + bool do_throw, const uint8_t *p, + JSToken *token, const uint8_t **pp) +{ + const uint8_t *p_next; + int ret; + uint32_t c; + StringBuffer b_s, *b = &b_s; + JSValue str; + + /* string */ + if (string_buffer_init(s->ctx, b, 32)) + goto fail; + for(;;) { + if (p >= s->buf_end) + goto invalid_char; + c = *p; + if (c < 0x20) { + if (sep == '`') { + if (c == '\r') { + if (p[1] == '\n') + p++; + c = '\n'; + } + /* do not update s->line_num */ + } else if (c == '\n' || c == '\r') + goto invalid_char; + } + p++; + if (c == sep) + break; + if (c == '$' && *p == '{' && sep == '`') { + /* template start or middle part */ + p++; + break; + } + if (c == '\\') { + c = *p; + switch(c) { + case '\0': + if (p >= s->buf_end) { + if (sep != '`') + goto invalid_char; + if (do_throw) + js_parse_error(s, "Unexpected end of input"); + goto fail; + } + p++; + break; + case '\'': + case '\"': + case '\\': + p++; + break; + case '\r': /* accept DOS and MAC newline sequences */ + if (p[1] == '\n') { + p++; + } + /* fall thru */ + case '\n': + /* ignore escaped newline sequence */ + p++; + if (sep != '`') { + s->line_num++; + s->eol = &p[-1]; + s->mark = p; + } + continue; + default: + if (c == '0' && !(p[1] >= '0' && p[1] <= '9')) { + /* accept isolated \0 */ + p++; + c = '\0'; + } else + if ((c >= '0' && c <= '9') + && (s->cur_func->is_strict_mode || sep == '`')) { + if (do_throw) { + js_parse_error(s, "%s are not allowed in %s", + (c >= '8') ? "\\8 and \\9" : "Octal escape sequences", + (sep == '`') ? "template strings" : "strict mode"); + } + goto fail; + } else if (c >= 0x80) { + c = utf8_decode(p, &p_next); + if (p_next == p + 1) { + goto invalid_utf8; + } + p = p_next; + /* LS or PS are skipped */ + if (c == CP_LS || c == CP_PS) + continue; + } else { + ret = lre_parse_escape(&p, true); + if (ret == -1) { + if (do_throw) { + js_parse_error(s, "Invalid %s escape sequence", + c == 'u' ? "Unicode" : "hexadecimal"); + } + goto fail; + } else if (ret < 0) { + /* ignore the '\' (could output a warning) */ + p++; + } else { + c = ret; + } + } + break; + } + } else if (c >= 0x80) { + c = utf8_decode(p - 1, &p_next); + if (p_next == p) + goto invalid_utf8; + p = p_next; + } + if (string_buffer_putc(b, c)) + goto fail; + } + str = string_buffer_end(b); + if (JS_IsException(str)) + return -1; + token->val = TOK_STRING; + token->u.str.sep = c; + token->u.str.str = str; + *pp = p; + return 0; + + invalid_utf8: + if (do_throw) + js_parse_error(s, "invalid UTF-8 sequence"); + goto fail; + invalid_char: + if (do_throw) + js_parse_error(s, "unexpected end of string"); + fail: + string_buffer_free(b); + return -1; +} + +static inline bool token_is_pseudo_keyword(JSParseState *s, JSAtom atom) { + return s->token.val == TOK_IDENT && s->token.u.ident.atom == atom && + !s->token.u.ident.has_escape; +} + +static __exception int js_parse_regexp(JSParseState *s) +{ + const uint8_t *p, *p_next; + bool in_class; + StringBuffer b_s, *b = &b_s; + StringBuffer b2_s, *b2 = &b2_s; + uint32_t c; + JSValue body_str, flags_str; + + p = s->buf_ptr; + p++; + in_class = false; + if (string_buffer_init(s->ctx, b, 32)) + return -1; + if (string_buffer_init(s->ctx, b2, 1)) + goto fail; + for(;;) { + if (p >= s->buf_end) { + eof_error: + js_parse_error(s, "unexpected end of regexp"); + goto fail; + } + c = *p++; + if (c == '\n' || c == '\r') { + goto eol_error; + } else if (c == '/') { + if (!in_class) + break; + } else if (c == '[') { + in_class = true; + } else if (c == ']') { + /* XXX: incorrect as the first character in a class */ + in_class = false; + } else if (c == '\\') { + if (string_buffer_putc8(b, c)) + goto fail; + c = *p++; + if (c == '\n' || c == '\r') + goto eol_error; + else if (c == '\0' && p >= s->buf_end) + goto eof_error; + else if (c >= 0x80) { + c = utf8_decode(p - 1, &p_next); + if (p_next == p) { + goto invalid_utf8; + } + p = p_next; + if (c == CP_LS || c == CP_PS) + goto eol_error; + } + } else if (c >= 0x80) { + c = utf8_decode(p - 1, &p_next); + if (p_next == p) { + invalid_utf8: + js_parse_error(s, "invalid UTF-8 sequence"); + goto fail; + } + p = p_next; + /* LS or PS are considered as line terminator */ + if (c == CP_LS || c == CP_PS) { + eol_error: + js_parse_error(s, "unexpected line terminator in regexp"); + goto fail; + } + } + if (string_buffer_putc(b, c)) + goto fail; + } + + /* flags */ + for(;;) { + c = utf8_decode(p, &p_next); + /* no need to test for invalid UTF-8, 0xFFFD is not ident_next */ + if (!lre_js_is_ident_next(c)) + break; + if (string_buffer_putc(b2, c)) + goto fail; + p = p_next; + } + + body_str = string_buffer_end(b); + flags_str = string_buffer_end(b2); + if (JS_IsException(body_str) || + JS_IsException(flags_str)) { + JS_FreeValue(s->ctx, body_str); + JS_FreeValue(s->ctx, flags_str); + return -1; + } + s->token.val = TOK_REGEXP; + s->token.u.regexp.body = body_str; + s->token.u.regexp.flags = flags_str; + s->buf_ptr = p; + return 0; + fail: + string_buffer_free(b); + string_buffer_free(b2); + return -1; +} + +#endif // QJS_DISABLE_PARSER + +static __exception int ident_realloc(JSContext *ctx, char **pbuf, size_t *psize, + char *static_buf) +{ + char *buf, *new_buf; + size_t size, new_size; + + buf = *pbuf; + size = *psize; + if (size >= (SIZE_MAX / 3) * 2) + new_size = SIZE_MAX; + else + new_size = size + (size >> 1); + if (buf == static_buf) { + new_buf = js_malloc(ctx, new_size); + if (!new_buf) + return -1; + memcpy(new_buf, buf, size); + } else { + new_buf = js_realloc(ctx, buf, new_size); + if (!new_buf) + return -1; + } + *pbuf = new_buf; + *psize = new_size; + return 0; +} + +#ifndef QJS_DISABLE_PARSER + +/* convert a TOK_IDENT to a keyword when needed */ +static void update_token_ident(JSParseState *s) +{ + if (s->token.u.ident.atom <= JS_ATOM_LAST_KEYWORD || + (s->token.u.ident.atom <= JS_ATOM_LAST_STRICT_KEYWORD && + s->cur_func->is_strict_mode) || + (s->token.u.ident.atom == JS_ATOM_yield && + ((s->cur_func->func_kind & JS_FUNC_GENERATOR) || + (s->cur_func->func_type == JS_PARSE_FUNC_ARROW && + !s->cur_func->in_function_body && s->cur_func->parent && + (s->cur_func->parent->func_kind & JS_FUNC_GENERATOR)))) || + (s->token.u.ident.atom == JS_ATOM_await && + (s->is_module || + (s->cur_func->func_kind & JS_FUNC_ASYNC) || + s->cur_func->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT || + (s->cur_func->func_type == JS_PARSE_FUNC_ARROW && + !s->cur_func->in_function_body && s->cur_func->parent && + ((s->cur_func->parent->func_kind & JS_FUNC_ASYNC) || + s->cur_func->parent->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT))))) { + if (s->token.u.ident.has_escape) { + s->token.u.ident.is_reserved = true; + s->token.val = TOK_IDENT; + } else { + /* The keywords atoms are pre allocated */ + s->token.val = s->token.u.ident.atom - 1 + TOK_FIRST_KEYWORD; + } + } +} + +/* if the current token is an identifier or keyword, reparse it + according to the current function type */ +static void reparse_ident_token(JSParseState *s) +{ + if (s->token.val == TOK_IDENT || + (s->token.val >= TOK_FIRST_KEYWORD && + s->token.val <= TOK_LAST_KEYWORD)) { + s->token.val = TOK_IDENT; + s->token.u.ident.is_reserved = false; + update_token_ident(s); + } +} + +/* 'c' is the first character. Return JS_ATOM_NULL in case of error */ +static JSAtom parse_ident(JSParseState *s, const uint8_t **pp, + bool *pident_has_escape, int c, bool is_private) +{ + const uint8_t *p, *p_next; + char ident_buf[128], *buf; + size_t ident_size, ident_pos; + JSAtom atom = JS_ATOM_NULL; + + p = *pp; + buf = ident_buf; + ident_size = sizeof(ident_buf); + ident_pos = 0; + if (is_private) + buf[ident_pos++] = '#'; + for(;;) { + if (c < 0x80) { + buf[ident_pos++] = c; + } else { + ident_pos += utf8_encode((uint8_t*)buf + ident_pos, c); + } + c = *p; + p_next = p + 1; + if (c == '\\' && *p_next == 'u') { + c = lre_parse_escape(&p_next, true); + *pident_has_escape = true; + } else if (c >= 0x80) { + c = utf8_decode(p, &p_next); + /* no need to test for invalid UTF-8, 0xFFFD is not ident_next */ + } + if (!lre_js_is_ident_next(c)) + break; + p = p_next; + if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) { + if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) + goto done; + } + } + /* buf is pure ASCII or UTF-8 encoded */ + atom = JS_NewAtomLen(s->ctx, buf, ident_pos); + done: + if (unlikely(buf != ident_buf)) + js_free(s->ctx, buf); + *pp = p; + return atom; +} + + +static __exception int next_token(JSParseState *s) +{ + const uint8_t *p, *p_next; + int c; + bool ident_has_escape; + JSAtom atom; + + if (js_check_stack_overflow(s->ctx->rt, 1000)) { + JS_ThrowStackOverflow(s->ctx); + return -1; + } + + free_token(s, &s->token); + + p = s->last_ptr = s->buf_ptr; + s->got_lf = false; + s->last_line_num = s->token.line_num; + s->last_col_num = s->token.col_num; + redo: + s->token.line_num = s->line_num; + s->token.col_num = s->col_num; + s->token.ptr = p; + c = *p; + switch(c) { + case 0: + if (p >= s->buf_end) { + s->token.val = TOK_EOF; + } else { + goto def_token; + } + break; + case '`': + if (js_parse_template_part(s, p + 1)) + goto fail; + p = s->buf_ptr; + break; + case '\'': + case '\"': + if (js_parse_string(s, c, true, p + 1, &s->token, &p)) + goto fail; + break; + case '\r': /* accept DOS and MAC newline sequences */ + if (p[1] == '\n') { + p++; + } + /* fall thru */ + case '\n': + p++; + line_terminator: + s->eol = &p[-1]; + s->mark = p; + s->got_lf = true; + s->line_num++; + goto redo; + case '\f': + case '\v': + case ' ': + case '\t': + s->mark = ++p; + goto redo; + case '/': + if (p[1] == '*') { + /* comment */ + p += 2; + for(;;) { + if (*p == '\0' && p >= s->buf_end) { + js_parse_error(s, "unexpected end of comment"); + goto fail; + } + if (p[0] == '*' && p[1] == '/') { + p += 2; + break; + } + if (*p == '\n') { + s->line_num++; + s->got_lf = true; /* considered as LF for ASI */ + s->eol = p++; + s->mark = p; + } else if (*p == '\r') { + s->got_lf = true; /* considered as LF for ASI */ + p++; + } else if (*p >= 0x80) { + c = utf8_decode(p, &p); + /* ignore invalid UTF-8 in comments */ + if (c == CP_LS || c == CP_PS) { + s->got_lf = true; /* considered as LF for ASI */ + } + } else { + p++; + } + } + s->mark = p; + goto redo; + } else if (p[1] == '/') { + /* line comment */ + p += 2; + skip_line_comment: + for(;;) { + if (*p == '\0' && p >= s->buf_end) + break; + if (*p == '\r' || *p == '\n') + break; + if (*p >= 0x80) { + c = utf8_decode(p, &p); + /* ignore invalid UTF-8 in comments */ + /* LS or PS are considered as line terminator */ + if (c == CP_LS || c == CP_PS) { + break; + } + } else { + p++; + } + } + s->mark = p; + goto redo; + } else if (p[1] == '=') { + p += 2; + s->token.val = TOK_DIV_ASSIGN; + } else { + p++; + s->token.val = c; + } + break; + case '\\': + if (p[1] == 'u') { + const uint8_t *p1 = p + 1; + int c1 = lre_parse_escape(&p1, true); + if (c1 >= 0 && lre_js_is_ident_first(c1)) { + c = c1; + p = p1; + ident_has_escape = true; + goto has_ident; + } else { + /* XXX: syntax error? */ + } + } + goto def_token; + case 'a': case 'b': case 'c': case 'd': + case 'e': case 'f': case 'g': case 'h': + case 'i': case 'j': case 'k': case 'l': + case 'm': case 'n': case 'o': case 'p': + case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': + case 'y': case 'z': + case 'A': case 'B': case 'C': case 'D': + case 'E': case 'F': case 'G': case 'H': + case 'I': case 'J': case 'K': case 'L': + case 'M': case 'N': case 'O': case 'P': + case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': + case 'Y': case 'Z': + case '_': + case '$': + /* identifier */ + s->mark = p; + p++; + ident_has_escape = false; + has_ident: + atom = parse_ident(s, &p, &ident_has_escape, c, false); + if (atom == JS_ATOM_NULL) + goto fail; + s->token.u.ident.atom = atom; + s->token.u.ident.has_escape = ident_has_escape; + s->token.u.ident.is_reserved = false; + s->token.val = TOK_IDENT; + update_token_ident(s); + break; + case '#': + /* private name */ + { + p++; + c = *p; + p_next = p + 1; + if (c == '\\' && *p_next == 'u') { + c = lre_parse_escape(&p_next, true); + } else if (c >= 0x80) { + c = utf8_decode(p, &p_next); + if (p_next == p + 1) + goto invalid_utf8; + } + if (!lre_js_is_ident_first(c)) { + js_parse_error(s, "invalid first character of private name"); + goto fail; + } + p = p_next; + ident_has_escape = false; /* not used */ + atom = parse_ident(s, &p, &ident_has_escape, c, true); + if (atom == JS_ATOM_NULL) + goto fail; + s->token.u.ident.atom = atom; + s->token.val = TOK_PRIVATE_NAME; + } + break; + case '.': + if (p[1] == '.' && p[2] == '.') { + p += 3; + s->token.val = TOK_ELLIPSIS; + break; + } + if (p[1] >= '0' && p[1] <= '9') { + goto parse_number; + } else { + goto def_token; + } + break; + case '0': + /* in strict mode, octal literals are not accepted */ + if (is_digit(p[1]) && (s->cur_func->is_strict_mode)) { + js_parse_error(s, "Octal literals are not allowed in strict mode"); + goto fail; + } + goto parse_number; + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': + case '9': + /* number */ + parse_number: + { + JSValue ret; + const uint8_t *p1; + int flags; + flags = ATOD_ACCEPT_BIN_OCT | ATOD_ACCEPT_LEGACY_OCTAL | + ATOD_ACCEPT_UNDERSCORES | ATOD_ACCEPT_SUFFIX; + ret = js_atof(s->ctx, (const char *)p, (const char **)&p, 0, + flags); + if (JS_IsException(ret)) + goto fail; + /* reject `10instanceof Number` */ + if (JS_VALUE_IS_NAN(ret) || + lre_js_is_ident_next(utf8_decode(p, &p1))) { + JS_FreeValue(s->ctx, ret); + js_parse_error(s, "invalid number literal"); + goto fail; + } + s->token.val = TOK_NUMBER; + s->token.u.num.val = ret; + } + break; + case '*': + if (p[1] == '=') { + p += 2; + s->token.val = TOK_MUL_ASSIGN; + } else if (p[1] == '*') { + if (p[2] == '=') { + p += 3; + s->token.val = TOK_POW_ASSIGN; + } else { + p += 2; + s->token.val = TOK_POW; + } + } else { + goto def_token; + } + break; + case '%': + if (p[1] == '=') { + p += 2; + s->token.val = TOK_MOD_ASSIGN; + } else { + goto def_token; + } + break; + case '+': + if (p[1] == '=') { + p += 2; + s->token.val = TOK_PLUS_ASSIGN; + } else if (p[1] == '+') { + p += 2; + s->token.val = TOK_INC; + } else { + goto def_token; + } + break; + case '-': + if (p[1] == '=') { + p += 2; + s->token.val = TOK_MINUS_ASSIGN; + } else if (p[1] == '-') { + if (s->allow_html_comments && p[2] == '>' && + (s->got_lf || s->last_ptr == s->buf_start)) { + /* Annex B: `-->` at beginning of line is an html comment end. + It extends to the end of the line. + */ + goto skip_line_comment; + } + p += 2; + s->token.val = TOK_DEC; + } else { + goto def_token; + } + break; + case '<': + if (p[1] == '=') { + p += 2; + s->token.val = TOK_LTE; + } else if (p[1] == '<') { + if (p[2] == '=') { + p += 3; + s->token.val = TOK_SHL_ASSIGN; + } else { + p += 2; + s->token.val = TOK_SHL; + } + } else if (s->allow_html_comments && + p[1] == '!' && p[2] == '-' && p[3] == '-') { + /* Annex B: handle ` + + + diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt new file mode 100644 index 0000000000..2328ca17d1 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt @@ -0,0 +1,68 @@ +package org.appdevforall.sqlitedebugger + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.pm.ApplicationInfo +import android.database.Cursor +import android.net.Uri +import android.util.Log +import java.io.File +import kotlin.concurrent.thread +import org.appdevforall.sqlitedebugger.engine.NativeDebugEngine +import org.appdevforall.sqlitedebugger.mcp.DatabaseTools +import org.appdevforall.sqlitedebugger.mcp.McpHttp +import org.appdevforall.sqlitedebugger.mcp.McpProtocol +import java.util.UUID + +/** + * Starts the debugger when the app's process starts. Refuses to run in a build that is not + * debuggable, so a release build that includes this library by mistake crashes at once instead of + * opening a local server. + */ +class DebuggerStartup : ContentProvider() { + override fun onCreate(): Boolean { + val context = context ?: return false + check(context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) { + "The SQLite debugger is in a build that is not debuggable. Remove it from release builds." + } + val databaseDir = File(context.applicationInfo.dataDir, "databases") + thread(name = "sqlite-debugger-start", isDaemon = true) { + try { + val engine = NativeDebugEngine() + engine.install() + val tools = DatabaseTools(engine, databaseDir) + val token = McpHttp.newToken() + val protocol = McpProtocol(tools.tools(), "1", { UUID.randomUUID().toString() }) + val http = McpHttp(protocol, { token }, log = { Log.w(TAG, it) }) + http.start() + port = http.boundPort + endpointToken = token + Log.i(TAG, "listening on 127.0.0.1:${http.boundPort}") + } catch (e: Exception) { + Log.e(TAG, "could not start", e) + } + } + return true + } + + override fun query(uri: Uri, projection: Array?, selection: String?, selectionArgs: Array?, sortOrder: String?): Cursor? = null + + override fun getType(uri: Uri): String? = null + + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + + override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int = 0 + + companion object { + private const val TAG = "SqliteDebugger" + + /** Set once the server listens; the broadcast to Code on the Go (ADFA-7137) reads them. */ + @Volatile var port: Int = 0 + private set + + @Volatile var endpointToken: String? = null + private set + } +} diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt new file mode 100644 index 0000000000..477b8d9d60 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -0,0 +1,382 @@ +package org.appdevforall.sqlitedebugger.mcp + +import java.io.File +import org.appdevforall.sqlitedebugger.engine.DebugEngine +import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.QueryLimits +import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.appdevforall.sqlitedebugger.engine.ServerConnection +import org.json.JSONArray +import org.json.JSONObject + +/** + * The debugger's MCP tools, all read-only: they open server connections through [engine] with + * `writable = false`, so SQLite's authorizer refuses a write whatever SQL a client sends. A tool + * names a database by the path one of the app's own connections has open; any other path is + * refused before the engine is called (opening a file Android's SQLite has open, with the + * extension's SQLite, can corrupt it). + */ +class DatabaseTools( + private val engine: DebugEngine, + /** The app's database folder, to list files no connection has opened; null on the JVM. */ + private val databaseDir: File? = null, + private val clock: () -> Long = System::currentTimeMillis, +) { + companion object { + const val DEFAULT_MAX_ROWS = 100 + const val MAX_ROWS = 1000 + const val MAX_TEXT_BYTES = 4096 + const val MAX_BLOB_BYTES = 1024 + + /** Below the client's 60 s limit on a tool call. */ + const val DEADLINE_MS = 50_000L + const val EVENT_BATCH_BYTES = 256 * 1024 + const val MAX_TABLES_FOR_COUNTS = 10 + + private const val MAX_SAFE_INTEGER = 9007199254740992L // 2^53 + private val SIDE_FILE_SUFFIXES = listOf("-wal", "-shm", "-journal") + + const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + + /** A SQLite value as JSON: org.json throws on NaN and infinities, and JSON numbers lose integers past 2^53. */ + fun encodeValue( + value: Any?, + maxBlobBytes: Int = MAX_BLOB_BYTES, + ): Any = + when (value) { + null -> JSONObject.NULL + is Long -> encodeLong(value) + is Int -> value.toLong() + is Double -> + when { + value.isNaN() -> "NaN" + value == Double.POSITIVE_INFINITY -> "Infinity" + value == Double.NEGATIVE_INFINITY -> "-Infinity" + else -> value + } + is String -> value + is ByteArray -> + JSONObject() + .put("base64", McpHttp.base64(value, urlSafe = false, pad = true)) + .put("bytes", value.size) + // the engine cuts at the limit without saying how long the BLOB was + .put("truncated", value.size >= maxBlobBytes) + else -> value.toString() + } + + fun encodeLong(value: Long): Any = if (value > MAX_SAFE_INTEGER || value < -MAX_SAFE_INTEGER) value.toString() else value + + fun quoteIdentifier(name: String) = "\"" + name.replace("\"", "\"\"") + "\"" + } + + private val lock = Any() + private val serverConnections = HashMap() + private var clientConnected = false + + /** Closes the server connections and tells the engine no client is watching. Call when the server stops. */ + fun onServerStopped() { + synchronized(lock) { + serverConnections.values.forEach { runCatching { it.close() } } + serverConnections.clear() + if (clientConnected) { + clientConnected = false + engine.setClientConnected(false) + } + } + } + + fun tools(): List = + listOf( + tool("list_databases", "List databases", "Lists the app's databases: each one an app connection has open (available), and the files in the app's database folder that none has opened (not available: not inspectable until the app opens them).") { listDatabases() }, + tool("list_connections", "List connections", "Lists the app's open SQLite connections (not yet freed by SQLite), oldest first.") { listConnections() }, + tool("get_schema", "Get schema", "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_schema.", databaseSchema()) { getSchema(it) }, + tool( + "query", + "Run a query", + "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. Use offset to page. $PAGING_NOTE Writes are refused.", + databaseSchema( + "sql" to prop("string", "The SQL statement."), + "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), + "offset" to prop("integer", "Rows to skip. Default 0."), + "max_rows" to prop("integer", "Rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), + required = listOf("sql"), + ), + ) { query(it) }, + tool( + "explain_query_plan", + "Explain a query plan", + "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run.", + databaseSchema( + "sql" to prop("string", "The SQL statement."), + "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), + required = listOf("sql"), + ), + ) { explain(it) }, + tool("get_stats", "Get statistics", "Returns page_count, page_size, freelist_count, and the row count of each table when the database has fewer than $MAX_TABLES_FOR_COUNTS tables.", databaseSchema()) { getStats(it) }, + tool( + "integrity_check", + "Check integrity", + "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. ok is true when SQLite reports no problem.", + databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), + ) { integrityCheck(it) }, + tool( + "get_events", + "Get SQL events", + "Returns the SQL the app ran, oldest first, after the cursor. Pass the returned next as after to continue; dropped counts events that left the buffer unread. The first call starts recording bound values into the SQL.", + JSONObject().put("type", "object").put("additionalProperties", false) + .put("properties", JSONObject().put("after", prop("integer", "Cursor: the next from the last call. Default 0."))) + .put("required", JSONArray()), + ) { getEvents(it) }, + ) + + private fun tool( + name: String, + title: String, + description: String, + inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), + run: (JSONObject) -> JSONObject, + ) = McpTool(name, title, description, inputSchema, readOnly = true, run = run) + + private fun prop( + type: String, + description: String, + ) = JSONObject().put("type", type).put("description", description) + + private fun databaseSchema( + vararg extra: Pair, + required: List = emptyList(), + ): JSONObject { + val props = JSONObject().put("database", prop("string", "The database path, as list_databases gives it.")) + extra.forEach { props.put(it.first, it.second) } + return JSONObject().put("type", "object").put("properties", props).put("additionalProperties", false) + .put("required", JSONArray(listOf("database") + required)) + } + + private fun listDatabases(): JSONObject { + val connections = engine.connections() + val byPath = LinkedHashMap>() + for (c in connections) if (c.path.isNotEmpty()) byPath.getOrPut(c.path) { mutableListOf() } += c.id + val list = JSONArray() + for ((path, ids) in byPath) { + list.put(JSONObject().put("path", path).put("available", true).put("connections", ids.size)) + } + databaseDir?.listFiles()?.sortedBy { it.name }?.forEach { f -> + if (!f.isFile || SIDE_FILE_SUFFIXES.any { f.name.endsWith(it) }) return@forEach + if (f.absolutePath in byPath || f.path in byPath) return@forEach + list.put(JSONObject().put("path", f.absolutePath).put("available", false).put("connections", 0)) + } + return JSONObject().put("databases", list) + } + + private fun listConnections(): JSONObject { + val list = JSONArray() + for (c in engine.connections()) { + list.put( + JSONObject().put("id", encodeLong(c.id)).put("path", c.path).put("read_only", c.readOnly).put("closing", c.closing) + .put("opened_at_epoch_nanos", encodeLong(c.openedAtEpochNanos)).put("open_thread_id", encodeLong(c.openThreadId)), + ) + } + return JSONObject().put("connections", list) + } + + private fun getSchema(args: JSONObject): JSONObject { + val result = run(args, "SELECT type, name, tbl_name, sql FROM sqlite_schema ORDER BY type, name", emptyList(), 0, QueryLimits(MAX_ROWS, 65536, MAX_BLOB_BYTES)) + val groups = linkedMapOf("table" to JSONArray(), "index" to JSONArray(), "view" to JSONArray(), "trigger" to JSONArray()) + for (row in result.rows) { + val item = JSONObject().put("name", encodeValue(row[1])).put("table", encodeValue(row[2])).put("sql", encodeValue(row[3])) + groups[row[0] as? String]?.put(item) + } + return JSONObject().put("tables", groups["table"]).put("indexes", groups["index"]).put("views", groups["view"]) + .put("triggers", groups["trigger"]).put("truncated", result.hasMore) + } + + private fun query(args: JSONObject): JSONObject { + val sql = stringArg(args, "sql") + val offset = intArg(args, "offset", 0, 0, Long.MAX_VALUE) + val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() + val result = run(args, sql, bindArgs(args), offset, QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) + val out = encodeResult(result, offset) + out.put("note", PAGING_NOTE) + return out + } + + private fun explain(args: JSONObject): JSONObject { + val result = run(args, "EXPLAIN QUERY PLAN " + stringArg(args, "sql"), bindArgs(args), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) + return JSONObject().put("plan", rowsAsObjects(result)) + } + + private fun getStats(args: JSONObject): JSONObject { + val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES) + val deadline = clock() + DEADLINE_MS + val path = checkedPath(args) + fun pragma(name: String) = runChecked(path, "PRAGMA $name", emptyList(), 0, limits, deadline).rows.firstOrNull()?.firstOrNull() + val pageCount = pragma("page_count") as? Long + val pageSize = pragma("page_size") as? Long + val out = JSONObject().put("page_count", encodeValue(pageCount)).put("page_size", encodeValue(pageSize)) + .put("freelist_count", encodeValue(pragma("freelist_count"))) + if (pageCount != null && pageSize != null) out.put("size_bytes", encodeLong(pageCount * pageSize)) + val tables = runChecked(path, "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", emptyList(), 0, limits, deadline) + .rows.map { it[0] as String } + if (tables.size < MAX_TABLES_FOR_COUNTS) { + val counts = JSONObject() + for (t in tables) { + val n = try { + runChecked(path, "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", emptyList(), 0, limits, deadline).rows.firstOrNull()?.firstOrNull() + } catch (e: McpToolError) { + e.message + } + counts.put(t, encodeValue(n)) + } + out.put("row_counts", counts) + } else { + out.put("row_counts_skipped", "The database has ${tables.size} tables; counts are given only under $MAX_TABLES_FOR_COUNTS.") + } + return out + } + + private fun integrityCheck(args: JSONObject): JSONObject { + val full = when (val v = args.opt("full")) { + null, JSONObject.NULL -> false + is Boolean -> v + else -> throw McpToolError("full must be true or false.") + } + val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" + val result = run(args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) + val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } + return JSONObject().put("check", if (full) "integrity_check" else "quick_check") + .put("ok", messages == listOf("ok")).put("messages", JSONArray(messages)) + } + + private fun getEvents(args: JSONObject): JSONObject { + val after = intArg(args, "after", 0, 0, Long.MAX_VALUE) + synchronized(lock) { + if (!clientConnected) { + engine.setClientConnected(true) + clientConnected = true + } + } + val batch = try { + engine.readEvents(after, EVENT_BATCH_BYTES) + } catch (e: DebugEngineException) { + throw engineError(e) + } + val events = JSONArray() + for (e in batch.events) { + events.put( + JSONObject().put("seq", encodeLong(e.seq)).put("kind", e.kind.name.lowercase()).put("connection_id", encodeLong(e.connectionId)) + .put("thread_id", encodeLong(e.threadId)).put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) + .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) + .put("sql", e.sql).put("truncated", e.truncated).put("expanded", e.expanded), + ) + } + return JSONObject().put("next", encodeLong(batch.next)).put("dropped", encodeLong(batch.dropped)).put("events", events) + } + + private fun encodeResult( + result: QueryResult, + offset: Long, + ): JSONObject { + val rows = JSONArray() + for (row in result.rows) rows.put(JSONArray().also { a -> row.forEach { a.put(encodeValue(it)) } }) + val out = JSONObject().put("columns", JSONArray(result.columns)).put("rows", rows).put("row_count", result.rows.size) + .put("offset", encodeLong(offset)).put("has_more", result.hasMore).put("truncated_cells", result.truncatedCells) + if (result.hasMore) out.put("next_offset", encodeLong(offset + result.rows.size)) + return out + } + + private fun rowsAsObjects(result: QueryResult): JSONArray { + val arr = JSONArray() + for (row in result.rows) { + val o = JSONObject() + result.columns.forEachIndexed { i, c -> o.put(c, encodeValue(row[i])) } + arr.put(o) + } + return arr + } + + private fun checkedPath(args: JSONObject): String { + val path = stringArg(args, "database") + val known = engine.connections().map { it.path }.filter { it.isNotEmpty() }.distinct() + if (path !in known) { + throw McpToolError( + "Unknown database \"$path\": use a path from list_databases that is available.", + JSONObject().put("available", JSONArray(known)), + ) + } + return path + } + + private fun run( + args: JSONObject, + sql: String, + bind: List, + offset: Long, + limits: QueryLimits, + ): QueryResult = runChecked(checkedPath(args), sql, bind, offset, limits, clock() + DEADLINE_MS) + + private fun runChecked( + path: String, + sql: String, + bind: List, + offset: Long, + limits: QueryLimits, + deadline: Long, + ): QueryResult = + synchronized(lock) { + try { + val conn = serverConnections.getOrPut(path) { engine.openServerConnection(path, writable = false) } + conn.query(sql, bind, offset, limits, deadline) + } catch (e: DebugEngineException) { + throw engineError(e) + } + } + + private fun engineError(e: DebugEngineException) = + McpToolError(e.message ?: "SQLite error ${e.sqliteCode}", JSONObject().put("sqlite_code", e.sqliteCode)) + + private fun stringArg( + args: JSONObject, + name: String, + ): String { + val v = args.opt(name) + if (v !is String || v.isEmpty()) throw McpToolError("$name is required and must be a non-empty string.") + return v + } + + private fun intArg( + args: JSONObject, + name: String, + default: Long, + min: Long, + max: Long, + ): Long { + val v = args.opt(name) + if (v == null || v == JSONObject.NULL) return default + val n = v as? Number ?: throw McpToolError("$name must be an integer.") + // org.json parses a decimal as BigDecimal, not Double + if (n !is Int && n !is Long && n !is Short && n !is Byte) { + val d = n.toDouble() + if (d != Math.floor(d) || d.isInfinite() || Math.abs(d) >= 9.2e18) throw McpToolError("$name must be an integer.") + } + val l = n.toLong() + if (l < min || l > max) throw McpToolError("$name must be between $min and ${if (max == Long.MAX_VALUE) "2^63-1" else max.toString()}.") + return l + } + + private fun bindArgs(args: JSONObject): List { + val raw = args.opt("args") + if (raw == null || raw == JSONObject.NULL) return emptyList() + val arr = raw as? JSONArray ?: throw McpToolError("args must be an array.") + return (0 until arr.length()).map { i -> + when (val v = arr.opt(i)) { + null, JSONObject.NULL -> null + is Int, is Long, is Short -> (v as Number).toLong() + is Number -> v.toDouble() + is String -> v + is Boolean -> if (v) 1L else 0L + else -> throw McpToolError("args[$i] must be null, a number or a string.") + } + } + } +} diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index c04c7fe6c3..7d58e73556 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -19,295 +19,318 @@ import kotlin.concurrent.thread import org.json.JSONObject /** - * The MCP endpoint's HTTP side: a small HTTP/1.1 listener on 127.0.0.1 only, apart from the store's - * own HttpServer, so it's never reachable from another device. Before [McpProtocol] sees a request, + * The MCP endpoint's HTTP side: a small HTTP/1.1 listener on 127.0.0.1 only, so it's never + * reachable from another device. Before [McpProtocol] sees a request, * it checks who's asking: * - the peer is a loopback address (it can't be otherwise, but it's checked anyway); * - Host names 127.0.0.1 or localhost, and Origin, if sent, does too, so a web page can't reach it * by DNS rebinding; - * - Authorization: Bearer , the token shown on the server screen, compared in constant time. + * - Authorization: Bearer , the token from [newToken], compared in constant time. * * POST /mcp carries JSON-RPC; DELETE /mcp ends a session; GET gets 405, since this server never * opens an event stream. Each connection has its own thread, as a tool may wait a while; at most * [MAX_CONNECTIONS] at once. Plain Kotlin, so unit tests can run it without Android. */ class McpHttp( - private val protocol: McpProtocol, - /** The current token: read on every request, so a new one takes effect at once. */ - private val token: () -> String, - private val port: Int = DEFAULT_PORT, - /** Problems worth a line in the log. Never given the token. */ - private val log: (String) -> Unit = {}, + private val protocol: McpProtocol, + /** The current token: read on every request, so a new one takes effect at once. */ + private val token: () -> String, + /** 0 lets the system pick a free port; read it from [boundPort] after [start]. */ + private val port: Int = 0, + /** Problems worth a line in the log. Never given the token. */ + private val log: (String) -> Unit = {}, ) { - companion object { - const val DEFAULT_PORT = 6176 - const val PATH = "/mcp" - const val MAX_CONNECTIONS = 8 - private const val MAX_HEADER_BYTES = 16 * 1024 - const val MAX_BODY_BYTES = 1024 * 1024 - /** A connection with no request for this long is closed. */ - const val IDLE_TIMEOUT_MS = 30_000 - private val STATUS = mapOf( - 200 to "OK", 202 to "Accepted", 204 to "No Content", 400 to "Bad Request", 401 to "Unauthorized", - 403 to "Forbidden", 404 to "Not Found", 405 to "Method Not Allowed", 413 to "Payload Too Large", - 415 to "Unsupported Media Type", 431 to "Request Header Fields Too Large", 500 to "Internal Server Error", - 501 to "Not Implemented", 503 to "Service Unavailable", - ) - private val LOOPBACK_NAMES = setOf("127.0.0.1", "localhost") - } + companion object { + private const val B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - private class Request(val method: String, val target: String, val version: String, val headers: Map, val body: ByteArray) - private class HttpError(val status: Int, message: String) : Exception(message) + /** 32 random bytes, URL-safe base64 without padding. A new one on every process start. */ + fun newToken(): String = base64(ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }, urlSafe = true, pad = false) - @Volatile private var socket: ServerSocket? = null - @Volatile private var running = false - private val open = AtomicInteger(0) - private val clients: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) + /** By hand: java.util.Base64 needs API 26 and this library's minSdk is 21. */ + fun base64(bytes: ByteArray, urlSafe: Boolean, pad: Boolean): String { + val out = StringBuilder() + var i = 0 + while (i < bytes.size) { + val n = minOf(3, bytes.size - i) + var v = 0 + for (k in 0 until 3) v = (v shl 8) or (if (k < n) bytes[i + k].toInt() and 0xff else 0) + for (k in 0..n) { + val idx = (v shr (18 - 6 * k)) and 63 + out.append(if (idx < 62) B64[idx] else if (idx == 62) (if (urlSafe) '-' else '+') else (if (urlSafe) '_' else '/')) + } + if (pad) repeat(3 - n) { out.append('=') } + i += 3 + } + return out.toString() + } - /** The port actually bound (useful when [port] is 0, as in tests). */ - val boundPort: Int get() = socket?.localPort ?: port + const val PATH = "/mcp" + const val MAX_CONNECTIONS = 8 + private const val MAX_HEADER_BYTES = 16 * 1024 + const val MAX_BODY_BYTES = 1024 * 1024 + /** A connection with no request for this long is closed. */ + const val IDLE_TIMEOUT_MS = 30_000 + private val STATUS = mapOf( + 200 to "OK", 202 to "Accepted", 204 to "No Content", 400 to "Bad Request", 401 to "Unauthorized", + 403 to "Forbidden", 404 to "Not Found", 405 to "Method Not Allowed", 413 to "Payload Too Large", + 415 to "Unsupported Media Type", 431 to "Request Header Fields Too Large", 500 to "Internal Server Error", + 501 to "Not Implemented", 503 to "Service Unavailable", + ) + private val LOOPBACK_NAMES = setOf("127.0.0.1", "localhost") + } - /** Binds 127.0.0.1:[port]. Throws IOException with a readable message if the port is taken. */ - fun start() { - val s = ServerSocket() - try { - s.reuseAddress = true - s.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), port), 16) - } catch (e: IOException) { - try { s.close() } catch (ignored: IOException) { } - throw IOException("Can't listen on 127.0.0.1:$port: ${e.message}", e) - } - socket = s - running = true - thread(name = "mcp-accept", isDaemon = true) { acceptLoop(s) } - } + private class Request(val method: String, val target: String, val version: String, val headers: Map, val body: ByteArray) + private class HttpError(val status: Int, message: String) : Exception(message) - /** Stops listening and closes every connection. */ - fun stop() { - running = false - try { socket?.close() } catch (ignored: IOException) { } - socket = null - clients.forEach { close(it) } - clients.clear() - } + @Volatile private var socket: ServerSocket? = null + @Volatile private var running = false + private val open = AtomicInteger(0) + private val clients: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) - private fun acceptLoop(s: ServerSocket) { - while (running && !s.isClosed) { - val c = try { s.accept() } catch (e: IOException) { - if (running && !s.isClosed) log("couldn't accept a connection: ${e.message}") - continue - } - if (!c.inetAddress.isLoopbackAddress) { close(c); continue } - if (open.incrementAndGet() > MAX_CONNECTIONS) { - open.decrementAndGet() - try { - c.soTimeout = 1000 - respond(c.getOutputStream(), 503, rpcError("Too many connections at once; try again."), emptyMap(), close = true) - } catch (ignored: IOException) { } - close(c) - continue - } - clients += c - thread(name = "mcp-connection", isDaemon = true) { - try { - serve(c) - } catch (ignored: IOException) { - // The client went away. - } catch (e: Exception) { - log("a connection failed: ${e.javaClass.simpleName}: ${e.message}") - } finally { - clients -= c - close(c) - open.decrementAndGet() - } - } - } - } + /** The port actually bound (useful when [port] is 0, as in tests). */ + val boundPort: Int get() = socket?.localPort ?: port - private fun serve(c: Socket) { - c.soTimeout = IDLE_TIMEOUT_MS - c.tcpNoDelay = true - val input = BufferedInputStream(c.getInputStream()) - val out = c.getOutputStream() - while (running) { - val req = try { - readRequest(input) ?: return - } catch (e: SocketTimeoutException) { - return - } catch (e: HttpError) { - respond(out, e.status, rpcError(e.message ?: "Bad request."), emptyMap(), close = true) - return - } - if (!handle(req, out)) return - } - } + /** Binds 127.0.0.1:[port]. Throws IOException with a readable message if the port is taken. */ + fun start() { + val s = ServerSocket() + try { + s.reuseAddress = true + s.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), port), 16) + } catch (e: IOException) { + try { s.close() } catch (ignored: IOException) { } + throw IOException("Can't listen on 127.0.0.1:$port: ${e.message}", e) + } + socket = s + running = true + thread(name = "mcp-accept", isDaemon = true) { acceptLoop(s) } + } - /** Answers one request. Returns whether the connection stays open for another. */ - private fun handle(r: Request, out: OutputStream): Boolean { - val close = r.version == "HTTP/1.0" || r.headers["connection"]?.lowercase()?.contains("close") == true - fun send(status: Int, body: String?, headers: Map = emptyMap()): Boolean { - respond(out, status, body, headers, close) - return !close - } - if (!hostAllowed(r.headers["host"])) return send(403, rpcError("The Host header must be 127.0.0.1 or localhost.")) - val origin = r.headers["origin"] - if (origin != null && !originAllowed(origin)) return send(403, rpcError("Requests from web pages aren't accepted.")) - if (r.target.substringBefore('?') != PATH) return send(404, rpcError("Not found: the MCP endpoint is $PATH.")) - if (!authorized(r.headers["authorization"])) { - return send(401, rpcError("Missing or wrong token. Code on the Go passes it to its Agent; send it as Authorization: Bearer ."), - mapOf("WWW-Authenticate" to "Bearer realm=\"SQLite debugger\"")) - } - val session = r.headers["mcp-session-id"] - val reply = when (r.method) { - "POST" -> { - val type = r.headers["content-type"]?.substringBefore(';')?.trim()?.lowercase() - if (type != null && type != "application/json") return send(415, rpcError("Send the request as application/json.")) - try { - protocol.post(String(r.body, Charsets.UTF_8), session, r.headers["mcp-protocol-version"]) - } catch (e: Exception) { - log("a request failed: ${e.javaClass.simpleName}: ${e.message}") - McpProtocol.Reply(500, rpcError("The server failed: ${e.message ?: e.javaClass.simpleName}")) - } - } - "DELETE" -> protocol.delete(session) - "GET" -> return send(405, rpcError("This server doesn't offer an event stream: use POST."), mapOf("Allow" to "POST, DELETE")) - else -> return send(405, rpcError("Use POST."), mapOf("Allow" to "POST, DELETE")) - } - return send(reply.status, reply.body, reply.headers) - } + /** Stops listening and closes every connection. */ + fun stop() { + running = false + try { socket?.close() } catch (ignored: IOException) { } + socket = null + clients.forEach { close(it) } + clients.clear() + } - // ---------------------------------------------------------------- checks + private fun acceptLoop(s: ServerSocket) { + while (running && !s.isClosed) { + val c = try { s.accept() } catch (e: IOException) { + if (running && !s.isClosed) log("couldn't accept a connection: ${e.message}") + continue + } + if (!c.inetAddress.isLoopbackAddress) { close(c); continue } + if (open.incrementAndGet() > MAX_CONNECTIONS) { + open.decrementAndGet() + try { + c.soTimeout = 1000 + respond(c.getOutputStream(), 503, rpcError("Too many connections at once; try again."), emptyMap(), close = true) + } catch (ignored: IOException) { } + close(c) + continue + } + clients += c + thread(name = "mcp-connection", isDaemon = true) { + try { + serve(c) + } catch (ignored: IOException) { + // The client went away. + } catch (e: Exception) { + log("a connection failed: ${e.javaClass.simpleName}: ${e.message}") + } finally { + clients -= c + close(c) + open.decrementAndGet() + } + } + } + } - /** 127.0.0.1 or localhost, on any port: adb forward may bring the request in from another port. */ - private fun hostAllowed(host: String?): Boolean { - val h = host?.trim()?.lowercase() ?: return false - val name = if (h.count { it == ':' } == 1) h.substringBefore(':') else h - if (h.count { it == ':' } == 1 && h.substringAfter(':').let { it.isEmpty() || it.any { ch -> !ch.isDigit() } }) return false - return name in LOOPBACK_NAMES - } + private fun serve(c: Socket) { + c.soTimeout = IDLE_TIMEOUT_MS + c.tcpNoDelay = true + val input = BufferedInputStream(c.getInputStream()) + val out = c.getOutputStream() + while (running) { + val req = try { + readRequest(input) ?: return + } catch (e: SocketTimeoutException) { + return + } catch (e: HttpError) { + respond(out, e.status, rpcError(e.message ?: "Bad request."), emptyMap(), close = true) + return + } + if (!handle(req, out)) return + } + } - private fun originAllowed(origin: String): Boolean = try { - val u = URI(origin.trim()) - (u.scheme == "http" || u.scheme == "https") && u.host?.lowercase() in LOOPBACK_NAMES - } catch (e: Exception) { false } + /** Answers one request. Returns whether the connection stays open for another. */ + private fun handle(r: Request, out: OutputStream): Boolean { + val close = r.version == "HTTP/1.0" || r.headers["connection"]?.lowercase()?.contains("close") == true + fun send(status: Int, body: String?, headers: Map = emptyMap()): Boolean { + respond(out, status, body, headers, close) + return !close + } + if (!hostAllowed(r.headers["host"])) return send(403, rpcError("The Host header must be 127.0.0.1 or localhost.")) + val origin = r.headers["origin"] + if (origin != null && !originAllowed(origin)) return send(403, rpcError("Requests from web pages aren't accepted.")) + if (r.target.substringBefore('?') != PATH) return send(404, rpcError("Not found: the MCP endpoint is $PATH.")) + if (!authorized(r.headers["authorization"])) { + return send(401, rpcError("Missing or wrong token. Code on the Go gives it to its Agent; send it as Authorization: Bearer ."), + mapOf("WWW-Authenticate" to "Bearer realm=\"SQLite debugger\"")) + } + val session = r.headers["mcp-session-id"] + val reply = when (r.method) { + "POST" -> { + val type = r.headers["content-type"]?.substringBefore(';')?.trim()?.lowercase() + if (type != null && type != "application/json") return send(415, rpcError("Send the request as application/json.")) + try { + protocol.post(String(r.body, Charsets.UTF_8), session, r.headers["mcp-protocol-version"]) + } catch (e: Exception) { + log("a request failed: ${e.javaClass.simpleName}: ${e.message}") + McpProtocol.Reply(500, rpcError("The server failed: ${e.message ?: e.javaClass.simpleName}")) + } + } + "DELETE" -> protocol.delete(session) + "GET" -> return send(405, rpcError("This server doesn't offer an event stream: use POST."), mapOf("Allow" to "POST, DELETE")) + else -> return send(405, rpcError("Use POST."), mapOf("Allow" to "POST, DELETE")) + } + return send(reply.status, reply.body, reply.headers) + } - private fun authorized(header: String?): Boolean { - val expected = token() - if (header == null || expected.isEmpty()) return false - val h = header.trim() - if (!h.regionMatches(0, "Bearer ", 0, 7, ignoreCase = true)) return false - return MessageDigest.isEqual(h.substring(7).trim().toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8)) - } + // ---------------------------------------------------------------- checks - // ---------------------------------------------------------------- reading and writing HTTP + /** 127.0.0.1 or localhost, on any port: adb forward may bring the request in from another port. */ + private fun hostAllowed(host: String?): Boolean { + val h = host?.trim()?.lowercase() ?: return false + val name = if (h.count { it == ':' } == 1) h.substringBefore(':') else h + if (h.count { it == ':' } == 1 && h.substringAfter(':').let { it.isEmpty() || it.any { ch -> !ch.isDigit() } }) return false + return name in LOOPBACK_NAMES + } - /** One request, or null if the connection closed before one began. */ - private fun readRequest(input: InputStream): Request? { - var budget = MAX_HEADER_BYTES - fun line(): String? { - val b = ByteArrayOutputStream() - while (true) { - val ch = input.read() - if (ch < 0) { if (b.size() == 0) return null else throw HttpError(400, "The request ended early.") } - if (--budget < 0) throw HttpError(431, "The request's headers are too long.") - if (ch == '\n'.code) break - b.write(ch) - } - return b.toString("ISO-8859-1").removeSuffix("\r") - } - var first = line() ?: return null - while (first.isEmpty()) first = line() ?: return null // stray line ends between requests - val parts = first.split(' ') - if (parts.size != 3 || !parts[2].startsWith("HTTP/1.")) throw HttpError(400, "That isn't an HTTP/1.x request.") - val headers = HashMap() - while (true) { - val l = line() ?: throw HttpError(400, "The request ended early.") - if (l.isEmpty()) break - val colon = l.indexOf(':') - if (colon <= 0) throw HttpError(400, "A header line without a colon.") - val name = l.substring(0, colon).trim().lowercase() - val value = l.substring(colon + 1).trim() - // A repeated header is joined, so two Host headers fail the Host check. - headers[name] = headers[name]?.let { "$it, $value" } ?: value - } - return Request(parts[0], parts[1], parts[2], headers, readBody(input, headers)) - } + private fun originAllowed(origin: String): Boolean = try { + val u = URI(origin.trim()) + (u.scheme == "http" || u.scheme == "https") && u.host?.lowercase() in LOOPBACK_NAMES + } catch (e: Exception) { false } - private fun readBody(input: InputStream, h: Map): ByteArray { - val te = h["transfer-encoding"] - if (te != null) { - if (!te.equals("chunked", ignoreCase = true)) throw HttpError(501, "Transfer-Encoding $te isn't supported.") - if (h.containsKey("content-length")) throw HttpError(400, "Both Content-Length and Transfer-Encoding were sent.") - return readChunked(input) - } - val len = h["content-length"] ?: return ByteArray(0) - val n = len.toLongOrNull()?.takeIf { it >= 0 } ?: throw HttpError(400, "Content-Length isn't a number.") - if (n > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") - return readExactly(input, n.toInt()) - } + private fun authorized(header: String?): Boolean { + val expected = token() + if (header == null || expected.isEmpty()) return false + val h = header.trim() + if (!h.regionMatches(0, "Bearer ", 0, 7, ignoreCase = true)) return false + return MessageDigest.isEqual(h.substring(7).trim().toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8)) + } - private fun readChunked(input: InputStream): ByteArray { - val out = ByteArrayOutputStream() - while (true) { - val sizeLine = shortLine(input, 1024) ?: throw HttpError(400, "The request ended early.") - val size = sizeLine.substringBefore(';').trim().toIntOrNull(16)?.takeIf { it >= 0 } ?: throw HttpError(400, "A bad chunk size.") - if (out.size().toLong() + size > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") - if (size == 0) { - // Trailers, if any, up to a blank line. - var lines = 0 - while (true) { - val t = shortLine(input, 1024) ?: break - if (t.isEmpty()) break - if (++lines > 32) throw HttpError(431, "Too many trailers.") - } - return out.toByteArray() - } - out.write(readExactly(input, size)) - if (shortLine(input, 2) != "") throw HttpError(400, "A chunk without its line end.") - } - } + // ---------------------------------------------------------------- reading and writing HTTP - private fun shortLine(input: InputStream, max: Int): String? { - val b = ByteArrayOutputStream() - var left = max - while (true) { - val ch = input.read() - if (ch < 0) return if (b.size() == 0) null else throw HttpError(400, "The request ended early.") - if (--left < 0) throw HttpError(400, "A line in the request is too long.") - if (ch == '\n'.code) break - b.write(ch) - } - return b.toString("ISO-8859-1").removeSuffix("\r") - } + /** One request, or null if the connection closed before one began. */ + private fun readRequest(input: InputStream): Request? { + var budget = MAX_HEADER_BYTES + fun line(): String? { + val b = ByteArrayOutputStream() + while (true) { + val ch = input.read() + if (ch < 0) { if (b.size() == 0) return null else throw HttpError(400, "The request ended early.") } + if (--budget < 0) throw HttpError(431, "The request's headers are too long.") + if (ch == '\n'.code) break + b.write(ch) + } + return b.toString("ISO-8859-1").removeSuffix("\r") + } + var first = line() ?: return null + while (first.isEmpty()) first = line() ?: return null // stray line ends between requests + val parts = first.split(' ') + if (parts.size != 3 || !parts[2].startsWith("HTTP/1.")) throw HttpError(400, "That isn't an HTTP/1.x request.") + val headers = HashMap() + while (true) { + val l = line() ?: throw HttpError(400, "The request ended early.") + if (l.isEmpty()) break + val colon = l.indexOf(':') + if (colon <= 0) throw HttpError(400, "A header line without a colon.") + val name = l.substring(0, colon).trim().lowercase() + val value = l.substring(colon + 1).trim() + // A repeated header is joined, so two Host headers fail the Host check. + headers[name] = headers[name]?.let { "$it, $value" } ?: value + } + return Request(parts[0], parts[1], parts[2], headers, readBody(input, headers)) + } - private fun readExactly(input: InputStream, n: Int): ByteArray { - val b = ByteArray(n) - var off = 0 - while (off < n) { - val r = input.read(b, off, n - off) - if (r < 0) throw HttpError(400, "The request ended early.") - off += r - } - return b - } + private fun readBody(input: InputStream, h: Map): ByteArray { + val te = h["transfer-encoding"] + if (te != null) { + if (!te.equals("chunked", ignoreCase = true)) throw HttpError(501, "Transfer-Encoding $te isn't supported.") + if (h.containsKey("content-length")) throw HttpError(400, "Both Content-Length and Transfer-Encoding were sent.") + return readChunked(input) + } + val len = h["content-length"] ?: return ByteArray(0) + val n = len.toLongOrNull()?.takeIf { it >= 0 } ?: throw HttpError(400, "Content-Length isn't a number.") + if (n > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") + return readExactly(input, n.toInt()) + } - private fun respond(out: OutputStream, status: Int, body: String?, headers: Map, close: Boolean) { - val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) - val head = StringBuilder("HTTP/1.1 $status ${STATUS[status] ?: "Status"}\r\n") - if (body != null) head.append("Content-Type: application/json; charset=utf-8\r\n") - if (status != 204) head.append("Content-Length: ${bytes.size}\r\n") - head.append("Cache-Control: no-store\r\n") - if (close) head.append("Connection: close\r\n") - for ((k, v) in headers) head.append(k).append(": ").append(v.replace("\r", "").replace("\n", "")).append("\r\n") - head.append("\r\n") - out.write(head.toString().toByteArray(Charsets.ISO_8859_1)) - if (status != 204) out.write(bytes) - out.flush() - } + private fun readChunked(input: InputStream): ByteArray { + val out = ByteArrayOutputStream() + while (true) { + val sizeLine = shortLine(input, 1024) ?: throw HttpError(400, "The request ended early.") + val size = sizeLine.substringBefore(';').trim().toIntOrNull(16)?.takeIf { it >= 0 } ?: throw HttpError(400, "A bad chunk size.") + if (out.size().toLong() + size > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") + if (size == 0) { + // Trailers, if any, up to a blank line. + var lines = 0 + while (true) { + val t = shortLine(input, 1024) ?: break + if (t.isEmpty()) break + if (++lines > 32) throw HttpError(431, "Too many trailers.") + } + return out.toByteArray() + } + out.write(readExactly(input, size)) + if (shortLine(input, 2) != "") throw HttpError(400, "A chunk without its line end.") + } + } - /** An HTTP-level refusal, as a JSON-RPC error with no id, which MCP clients know how to show. */ - private fun rpcError(message: String): String = JSONObject().put("jsonrpc", "2.0").put("id", JSONObject.NULL) - .put("error", JSONObject().put("code", McpProtocol.INVALID_REQUEST).put("message", message)).toString() + private fun shortLine(input: InputStream, max: Int): String? { + val b = ByteArrayOutputStream() + var left = max + while (true) { + val ch = input.read() + if (ch < 0) return if (b.size() == 0) null else throw HttpError(400, "The request ended early.") + if (--left < 0) throw HttpError(400, "A line in the request is too long.") + if (ch == '\n'.code) break + b.write(ch) + } + return b.toString("ISO-8859-1").removeSuffix("\r") + } - private fun close(s: Socket) { try { s.close() } catch (ignored: IOException) { } } + private fun readExactly(input: InputStream, n: Int): ByteArray { + val b = ByteArray(n) + var off = 0 + while (off < n) { + val r = input.read(b, off, n - off) + if (r < 0) throw HttpError(400, "The request ended early.") + off += r + } + return b + } + + private fun respond(out: OutputStream, status: Int, body: String?, headers: Map, close: Boolean) { + val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) + val head = StringBuilder("HTTP/1.1 $status ${STATUS[status] ?: "Status"}\r\n") + if (body != null) head.append("Content-Type: application/json; charset=utf-8\r\n") + if (status != 204) head.append("Content-Length: ${bytes.size}\r\n") + head.append("Cache-Control: no-store\r\n") + if (close) head.append("Connection: close\r\n") + for ((k, v) in headers) head.append(k).append(": ").append(v.replace("\r", "").replace("\n", "")).append("\r\n") + head.append("\r\n") + out.write(head.toString().toByteArray(Charsets.ISO_8859_1)) + if (status != 204) out.write(bytes) + out.flush() + } + + /** An HTTP-level refusal, as a JSON-RPC error with no id, which MCP clients know how to show. */ + private fun rpcError(message: String): String = JSONObject().put("jsonrpc", "2.0").put("id", JSONObject.NULL) + .put("error", JSONObject().put("code", McpProtocol.INVALID_REQUEST).put("message", message)).toString() + + private fun close(s: Socket) { try { s.close() } catch (ignored: IOException) { } } } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 273d27e5d3..01e0877b1d 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -10,19 +10,19 @@ import org.json.JSONTokener * should read, such as "a person is needed". */ class McpTool( - val name: String, - val title: String, - val description: String, - val inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), - /** Only reports; changes nothing. Shown to clients as a hint, not relied on. */ - val readOnly: Boolean = true, - val run: (JSONObject) -> JSONObject, + val name: String, + val title: String, + val description: String, + val inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), + /** Only reports; changes nothing. Shown to clients as a hint, not relied on. */ + val readOnly: Boolean = true, + val run: (JSONObject) -> JSONObject, ) { - fun describe(): JSONObject = JSONObject() - .put("name", name).put("title", title).put("description", description) - .put("inputSchema", inputSchema) - .put("annotations", JSONObject().put("title", title).put("readOnlyHint", readOnly) - .put("destructiveHint", false).put("openWorldHint", false)) + fun describe(): JSONObject = JSONObject() + .put("name", name).put("title", title).put("description", description) + .put("inputSchema", inputSchema) + .put("annotations", JSONObject().put("title", title).put("readOnlyHint", readOnly) + .put("destructiveHint", false).put("openWorldHint", false)) } /** A tool's failure, told to the client as a tool result with isError, with [details] when there are any. */ @@ -38,135 +38,135 @@ class McpToolError(message: String, val details: JSONObject? = null) : Exception * are accepted and need no answer (HTTP 202). */ class McpProtocol( - private val tools: List, - private val serverVersion: String, - private val newSessionId: () -> String, - private val maxSessions: Int = 16, + private val tools: List, + private val serverVersion: String, + private val newSessionId: () -> String, + private val maxSessions: Int = 16, ) { - companion object { - /** Newest first: offered when a client asks for a version this server doesn't know. */ - val VERSIONS = listOf("2025-06-18", "2025-03-26", "2024-11-05") - const val SERVER_NAME = "sqlite-debugger" - const val SESSION_HEADER = "Mcp-Session-Id" - const val PARSE_ERROR = -32700 - const val INVALID_REQUEST = -32600 - const val METHOD_NOT_FOUND = -32601 - const val INVALID_PARAMS = -32602 - const val INSTRUCTIONS = "Inspects and queries the SQLite databases of the app this server runs in, a debug " + - "build made with Code on the Go. Read-only unless the app's developer turned on read-write mode." - } - - /** What to send back: an HTTP status, a JSON body (or none), and extra headers. */ - class Reply(val status: Int, val body: String?, val headers: Map = emptyMap()) - - /** Live sessions, oldest first; the oldest is dropped when there are too many. */ - private val sessions = LinkedHashSet() - - /** A POST to the endpoint: one JSON-RPC message, or a batch of them. */ - fun post(body: String, sessionId: String?, versionHeader: String?): Reply { - val parsed = try { JSONTokener(body).nextValue() } catch (e: Exception) { null } - if (parsed !is JSONObject && parsed !is JSONArray) return Reply(400, error(null, PARSE_ERROR, "That isn't a JSON object or array.").toString()) - val messages: List = if (parsed is JSONArray) (0 until parsed.length()).map { parsed.opt(it) } else listOf(parsed) - if (messages.isEmpty()) return Reply(400, error(null, INVALID_REQUEST, "An empty batch.").toString()) - - if (messages.any { (it as? JSONObject)?.optString("method") == "initialize" }) { - if (messages.size != 1) return Reply(400, error(null, INVALID_REQUEST, "Send initialize on its own, not in a batch.").toString()) - return initialize(messages[0] as JSONObject) - } - if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header: send initialize first.").toString()) - if (!touch(sessionId)) return Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist: send initialize again.").toString()) - if (versionHeader != null && versionHeader !in VERSIONS) { - return Reply(400, error(null, INVALID_REQUEST, "Unsupported MCP-Protocol-Version $versionHeader; this server speaks ${VERSIONS.joinToString()}.").toString()) - } - val replies = messages.mapNotNull { handle(it) } - if (replies.isEmpty()) return Reply(202, null) - return Reply(200, if (parsed is JSONArray) JSONArray(replies).toString() else replies[0].toString()) - } - - /** A DELETE: the client is done with its session. */ - fun delete(sessionId: String?): Reply { - if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header.").toString()) - val removed = synchronized(sessions) { sessions.remove(sessionId) } - return if (removed) Reply(204, null) else Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist.").toString()) - } - - /** Ends every session, so clients must initialize again. */ - fun endAll() = synchronized(sessions) { sessions.clear() } - - fun sessionCount(): Int = synchronized(sessions) { sessions.size } - - private fun touch(id: String): Boolean = synchronized(sessions) { - if (!sessions.remove(id)) return false - sessions += id // most recently used goes last, so it's dropped last - true - } - - private fun initialize(m: JSONObject): Reply { - val id = m.opt("id") - if (!validId(id)) return Reply(400, error(null, INVALID_REQUEST, "initialize needs an id, a string or a number.").toString()) - if (m.optString("jsonrpc") != "2.0") return Reply(400, error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".").toString()) - val asked = m.optJSONObject("params")?.optString("protocolVersion", "") ?: "" - val version = if (asked in VERSIONS) asked else VERSIONS[0] - val session = newSessionId() - synchronized(sessions) { - sessions += session - while (sessions.size > maxSessions) sessions.remove(sessions.first()) - } - val result = JSONObject() - .put("protocolVersion", version) - .put("capabilities", JSONObject().put("tools", JSONObject().put("listChanged", false))) - .put("serverInfo", JSONObject().put("name", SERVER_NAME).put("title", "SQLite debugger").put("version", serverVersion)) - .put("instructions", INSTRUCTIONS) - return Reply(200, ok(id, result).toString(), mapOf(SESSION_HEADER to session)) - } - - /** One message of a POST; null when it needs no answer. */ - private fun handle(raw: Any?): JSONObject? { - val m = raw as? JSONObject ?: return error(null, INVALID_REQUEST, "Each message must be a JSON object.") - val hasId = m.has("id") - val id = m.opt("id") - val method = m.opt("method") as? String - if (method == null) { - // A response to something this server asked: it never asks, so there's nothing to do. - if (m.has("result") || m.has("error")) return null - return error(if (validId(id)) id else null, INVALID_REQUEST, "A request needs a method.") - } - if (!hasId) return null // a notification, such as notifications/initialized: no answer - if (!validId(id)) return error(null, INVALID_REQUEST, "id must be a string or a number.") - if (m.optString("jsonrpc") != "2.0") return error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".") - return when (method) { - "ping" -> ok(id, JSONObject()) - "tools/list" -> ok(id, JSONObject().put("tools", JSONArray().also { a -> tools.forEach { a.put(it.describe()) } })) - "tools/call" -> call(id, m.opt("params")) - else -> error(id, METHOD_NOT_FOUND, "Unknown method \"$method\".") - } - } - - private fun call(id: Any, rawParams: Any?): JSONObject { - val params = rawParams as? JSONObject ?: return error(id, INVALID_PARAMS, "tools/call needs params, with the tool's name.") - val name = params.opt("name") as? String ?: return error(id, INVALID_PARAMS, "tools/call needs the tool's name.") - val tool = tools.firstOrNull { it.name == name } ?: return error(id, INVALID_PARAMS, "Unknown tool \"$name\".") - val args = when (val a = params.opt("arguments")) { - null, JSONObject.NULL -> JSONObject() - is JSONObject -> a - else -> return error(id, INVALID_PARAMS, "arguments must be an object.") - } - val result = try { - val out = tool.run(args) - JSONObject().put("content", JSONArray().put(text(out.toString(2)))).put("structuredContent", out).put("isError", false) - } catch (e: McpToolError) { - JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> - e.details?.let { r.put("structuredContent", it) } - } - } catch (e: Exception) { - JSONObject().put("content", JSONArray().put(text("The tool failed: ${e.message ?: e.javaClass.simpleName}"))).put("isError", true) - } - return ok(id, result) - } - - private fun validId(id: Any?) = id is String || id is Number - private fun text(t: String) = JSONObject().put("type", "text").put("text", t) - private fun ok(id: Any, result: JSONObject) = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) - private fun error(id: Any?, code: Int, message: String) = JSONObject().put("jsonrpc", "2.0").put("id", id ?: JSONObject.NULL) - .put("error", JSONObject().put("code", code).put("message", message)) + companion object { + /** Newest first: offered when a client asks for a version this server doesn't know. */ + val VERSIONS = listOf("2025-06-18", "2025-03-26", "2024-11-05") + const val SERVER_NAME = "sqlite-debugger" + const val SESSION_HEADER = "Mcp-Session-Id" + const val PARSE_ERROR = -32700 + const val INVALID_REQUEST = -32600 + const val METHOD_NOT_FOUND = -32601 + const val INVALID_PARAMS = -32602 + const val INSTRUCTIONS = "Inspects and queries the SQLite databases of the app this server runs in, a debug " + + "build made with Code on the Go. Read-only unless the app's developer turned on read-write mode." + } + + /** What to send back: an HTTP status, a JSON body (or none), and extra headers. */ + class Reply(val status: Int, val body: String?, val headers: Map = emptyMap()) + + /** Live sessions, oldest first; the oldest is dropped when there are too many. */ + private val sessions = LinkedHashSet() + + /** A POST to the endpoint: one JSON-RPC message, or a batch of them. */ + fun post(body: String, sessionId: String?, versionHeader: String?): Reply { + val parsed = try { JSONTokener(body).nextValue() } catch (e: Exception) { null } + if (parsed !is JSONObject && parsed !is JSONArray) return Reply(400, error(null, PARSE_ERROR, "That isn't a JSON object or array.").toString()) + val messages: List = if (parsed is JSONArray) (0 until parsed.length()).map { parsed.opt(it) } else listOf(parsed) + if (messages.isEmpty()) return Reply(400, error(null, INVALID_REQUEST, "An empty batch.").toString()) + + if (messages.any { (it as? JSONObject)?.optString("method") == "initialize" }) { + if (messages.size != 1) return Reply(400, error(null, INVALID_REQUEST, "Send initialize on its own, not in a batch.").toString()) + return initialize(messages[0] as JSONObject) + } + if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header: send initialize first.").toString()) + if (!touch(sessionId)) return Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist: send initialize again.").toString()) + if (versionHeader != null && versionHeader !in VERSIONS) { + return Reply(400, error(null, INVALID_REQUEST, "Unsupported MCP-Protocol-Version $versionHeader; this server speaks ${VERSIONS.joinToString()}.").toString()) + } + val replies = messages.mapNotNull { handle(it) } + if (replies.isEmpty()) return Reply(202, null) + return Reply(200, if (parsed is JSONArray) JSONArray(replies).toString() else replies[0].toString()) + } + + /** A DELETE: the client is done with its session. */ + fun delete(sessionId: String?): Reply { + if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header.").toString()) + val removed = synchronized(sessions) { sessions.remove(sessionId) } + return if (removed) Reply(204, null) else Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist.").toString()) + } + + /** Ends every session, so clients must initialize again. */ + fun endAll() = synchronized(sessions) { sessions.clear() } + + fun sessionCount(): Int = synchronized(sessions) { sessions.size } + + private fun touch(id: String): Boolean = synchronized(sessions) { + if (!sessions.remove(id)) return false + sessions += id // most recently used goes last, so it's dropped last + true + } + + private fun initialize(m: JSONObject): Reply { + val id = m.opt("id") + if (!validId(id)) return Reply(400, error(null, INVALID_REQUEST, "initialize needs an id, a string or a number.").toString()) + if (m.optString("jsonrpc") != "2.0") return Reply(400, error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".").toString()) + val asked = m.optJSONObject("params")?.optString("protocolVersion", "") ?: "" + val version = if (asked in VERSIONS) asked else VERSIONS[0] + val session = newSessionId() + synchronized(sessions) { + sessions += session + while (sessions.size > maxSessions) sessions.remove(sessions.first()) + } + val result = JSONObject() + .put("protocolVersion", version) + .put("capabilities", JSONObject().put("tools", JSONObject().put("listChanged", false))) + .put("serverInfo", JSONObject().put("name", SERVER_NAME).put("title", "SQLite debugger").put("version", serverVersion)) + .put("instructions", INSTRUCTIONS) + return Reply(200, ok(id, result).toString(), mapOf(SESSION_HEADER to session)) + } + + /** One message of a POST; null when it needs no answer. */ + private fun handle(raw: Any?): JSONObject? { + val m = raw as? JSONObject ?: return error(null, INVALID_REQUEST, "Each message must be a JSON object.") + val hasId = m.has("id") + val id = m.opt("id") + val method = m.opt("method") as? String + if (method == null) { + // A response to something this server asked: it never asks, so there's nothing to do. + if (m.has("result") || m.has("error")) return null + return error(if (validId(id)) id else null, INVALID_REQUEST, "A request needs a method.") + } + if (!hasId) return null // a notification, such as notifications/initialized: no answer + if (!validId(id)) return error(null, INVALID_REQUEST, "id must be a string or a number.") + if (m.optString("jsonrpc") != "2.0") return error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".") + return when (method) { + "ping" -> ok(id, JSONObject()) + "tools/list" -> ok(id, JSONObject().put("tools", JSONArray().also { a -> tools.forEach { a.put(it.describe()) } })) + "tools/call" -> call(id, m.opt("params")) + else -> error(id, METHOD_NOT_FOUND, "Unknown method \"$method\".") + } + } + + private fun call(id: Any, rawParams: Any?): JSONObject { + val params = rawParams as? JSONObject ?: return error(id, INVALID_PARAMS, "tools/call needs params, with the tool's name.") + val name = params.opt("name") as? String ?: return error(id, INVALID_PARAMS, "tools/call needs the tool's name.") + val tool = tools.firstOrNull { it.name == name } ?: return error(id, INVALID_PARAMS, "Unknown tool \"$name\".") + val args = when (val a = params.opt("arguments")) { + null, JSONObject.NULL -> JSONObject() + is JSONObject -> a + else -> return error(id, INVALID_PARAMS, "arguments must be an object.") + } + val result = try { + val out = tool.run(args) + JSONObject().put("content", JSONArray().put(text(out.toString(2)))).put("structuredContent", out).put("isError", false) + } catch (e: McpToolError) { + JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> + e.details?.let { r.put("structuredContent", it) } + } + } catch (e: Exception) { + JSONObject().put("content", JSONArray().put(text("The tool failed: ${e.message ?: e.javaClass.simpleName}"))).put("isError", true) + } + return ok(id, result) + } + + private fun validId(id: Any?) = id is String || id is Number + private fun text(t: String) = JSONObject().put("type", "text").put("text", t) + private fun ok(id: Any, result: JSONObject) = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + private fun error(id: Any?, code: Int, message: String) = JSONObject().put("jsonrpc", "2.0").put("id", id ?: JSONObject.NULL) + .put("error", JSONObject().put("code", code).put("message", message)) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt new file mode 100644 index 0000000000..7e15669b14 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -0,0 +1,318 @@ +package org.appdevforall.sqlitedebugger.mcp + +import java.io.File +import org.appdevforall.sqlitedebugger.engine.AppConnection +import org.appdevforall.sqlitedebugger.engine.DebugEngineException +import org.appdevforall.sqlitedebugger.engine.EventKind +import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine +import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class DatabaseToolsTest { + private val engine = FakeDebugEngine() + private var now = 1_000_000L + private var dir: File? = null + private val tools get() = DatabaseTools(engine, dir, { now }) + private val seenSql = mutableListOf() + + private fun conn( + id: Long, + path: String, + closing: Boolean = false, + ) = AppConnection(id, path, false, closing, 1_700_000_000_000_000_000L + id, 5) + + private fun runTool( + t: DatabaseTools, + name: String, + args: JSONObject = JSONObject(), + ): JSONObject { + val protocol = McpProtocol(t.tools(), "test", { "s" }, 4) + val init = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize") + .put("params", JSONObject().put("protocolVersion", "2025-06-18")).toString() + val session = protocol.post(init, null, null).headers[McpProtocol.SESSION_HEADER]!! + val call = JSONObject().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call") + .put("params", JSONObject().put("name", name).put("arguments", args)).toString() + return JSONObject(protocol.post(call, session, null).body!!).getJSONObject("result") + } + + private fun ok( + name: String, + args: JSONObject = JSONObject(), + t: DatabaseTools = tools, + ): JSONObject { + val r = runTool(t, name, args) + assertFalse(r.toString(), r.getBoolean("isError")) + return r.getJSONObject("structuredContent") + } + + private fun db(path: String = "/data/a.db") = JSONObject().put("database", path) + + private fun answerWith(vararg byPrefix: Pair) { + engine.answer = { _, _, sql, _ -> + seenSql += sql + byPrefix.firstOrNull { sql.startsWith(it.first) }?.second ?: QueryResult(emptyList(), emptyList(), 0, false) + } + } + + @Test fun everyToolIsReadOnly() { + val list = tools.tools() + assertEquals( + listOf("list_databases", "list_connections", "get_schema", "query", "explain_query_plan", "get_stats", "integrity_check", "get_events"), + list.map { it.name }, + ) + list.forEach { assertTrue(it.name, it.describe().getJSONObject("annotations").getBoolean("readOnlyHint")) } + } + + @Test fun listDatabasesGroupsByPathAndSkipsEmpty() { + engine.appConnections += listOf(conn(1, "/data/a.db"), conn(2, "/data/a.db"), conn(3, ""), conn(4, "/data/b.db")) + val dbs = ok("list_databases").getJSONArray("databases") + assertEquals(2, dbs.length()) + assertEquals("/data/a.db", dbs.getJSONObject(0).getString("path")) + assertEquals(2, dbs.getJSONObject(0).getInt("connections")) + assertTrue(dbs.getJSONObject(1).getBoolean("available")) + } + + @Test fun listDatabasesAddsUnopenedFilesButNotSideFiles() { + val d = kotlin.io.path.createTempDirectory("dbs").toFile() + try { + listOf("open.db", "closed.db", "closed.db-wal", "closed.db-shm", "closed.db-journal").forEach { File(d, it).writeText("x") } + dir = d + engine.appConnections += conn(1, File(d, "open.db").absolutePath) + val dbs = ok("list_databases").getJSONArray("databases") + assertEquals(2, dbs.length()) + assertTrue(dbs.getJSONObject(0).getBoolean("available")) + val closed = dbs.getJSONObject(1) + assertEquals(File(d, "closed.db").absolutePath, closed.getString("path")) + assertFalse(closed.getBoolean("available")) + } finally { + d.deleteRecursively() + } + } + + @Test fun listConnectionsEncodesBigIntegersAsStrings() { + engine.appConnections += conn(1, "/data/a.db", closing = true) + val c = ok("list_connections").getJSONArray("connections").getJSONObject(0) + assertEquals(1, c.getInt("id")) + assertTrue(c.getBoolean("closing")) + assertEquals("1700000000000000001", c.getString("opened_at_epoch_nanos")) + } + + @Test fun everyDatabaseToolRefusesAnUnknownPathBeforeTheEngine() { + engine.appConnections += conn(1, "/data/a.db") + for ((name, extra) in listOf("get_schema" to JSONObject(), "query" to JSONObject().put("sql", "select 1"), "explain_query_plan" to JSONObject().put("sql", "select 1"), "get_stats" to JSONObject(), "integrity_check" to JSONObject())) { + for (bad in listOf("/data/other.db", "", "/data/a.db-wal")) { + val r = runTool(tools, name, db(bad).also { o -> extra.keys().forEach { k -> o.put(k, extra.get(k)) } }) + assertTrue("$name $bad", r.getBoolean("isError")) + } + val missing = runTool(tools, name, extra) + assertTrue(name, missing.getBoolean("isError")) + } + assertTrue(engine.openedServerConnections.isEmpty()) + } + + @Test fun emptyPathOfAnInMemoryConnectionIsNotOpenable() { + engine.appConnections += conn(1, "") + assertTrue(runTool(tools, "get_stats", db("")).getBoolean("isError")) + assertTrue(engine.openedServerConnections.isEmpty()) + } + + @Test fun queryOpensReadOnlyAndPages() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> QueryResult(listOf("n"), (1L..5L).map { listOf(it) }, 0, false) } + val r = ok("query", db().put("sql", "select n from t").put("max_rows", 2).put("offset", 1)) + assertEquals(listOf(listOf("/data/a.db", false)), engine.openedServerConnections.map { listOf(it.first, it.second) }) + assertEquals(2, r.getInt("row_count")) + assertEquals(2, r.getJSONArray("rows").getJSONArray(0).getInt(0)) + assertTrue(r.getBoolean("has_more")) + assertEquals(3, r.getInt("next_offset")) + assertTrue(r.getString("note").contains("re-runs")) + assertTrue(tools.tools().first { it.name == "query" }.description.contains("re-runs")) + } + + @Test fun queryChecksItsArguments() { + engine.appConnections += conn(1, "/data/a.db") + fun bad(vararg kv: Pair) = assertTrue(kv.toString(), runTool(tools, "query", db().also { o -> kv.forEach { o.put(it.first, it.second) } }).getBoolean("isError")) + bad() + bad("sql" to "x", "max_rows" to 1001) + bad("sql" to "x", "max_rows" to 0) + bad("sql" to "x", "offset" to -1) + bad("sql" to "x", "max_rows" to 1.5) + bad("sql" to "x", "args" to "nope") + bad("sql" to "x", "args" to JSONArray().put(JSONObject())) + assertTrue(engine.openedServerConnections.isEmpty()) + } + + @Test fun queryBindsArgsByType() { + engine.appConnections += conn(1, "/data/a.db") + var got: List = emptyList() + engine.answer = { _, _, _, a -> got = a; QueryResult(emptyList(), emptyList(), 0, false) } + ok("query", db().put("sql", "x").put("args", JSONArray().put(JSONObject.NULL).put(3).put(2.5).put("s").put(true))) + assertEquals(listOf(null, 3L, 2.5, "s", 1L), got) + } + + @Test fun queryErrorsCarryTheSqliteCode() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") } + val r = runTool(tools, "query", db().put("sql", "delete from t")) + assertTrue(r.getBoolean("isError")) + assertEquals(23, r.getJSONObject("structuredContent").getInt("sqlite_code")) + } + + @Test fun deadlineIsFiftySecondsAhead() { + engine.appConnections += conn(1, "/data/a.db") + var deadline = 0L + val real = engine + engine.answer = { _, _, _, _ -> QueryResult(emptyList(), emptyList(), 0, false) } + // the fake ignores the deadline, so check the arithmetic through the constant and a wrapper engine + val wrapper = object : org.appdevforall.sqlitedebugger.engine.DebugEngine by real { + override fun openServerConnection(path: String, writable: Boolean) = real.openServerConnection(path, writable).let { c -> + object : org.appdevforall.sqlitedebugger.engine.ServerConnection by c { + override fun query(sql: String, args: List, offset: Long, limits: org.appdevforall.sqlitedebugger.engine.QueryLimits, deadlineMillis: Long): QueryResult { + deadline = deadlineMillis + return c.query(sql, args, offset, limits, deadlineMillis) + } + } + } + } + ok("query", db().put("sql", "x"), DatabaseTools(wrapper, null, { now })) + assertEquals(now + 50_000, deadline) + } + + @Test fun jsonEncodesNonFiniteDoublesBigIntegersAndBlobs() { + engine.appConnections += conn(1, "/data/a.db") + val big = 9_007_199_254_740_993L + engine.answer = { _, _, _, _ -> + QueryResult( + listOf("a", "b", "c", "d", "e", "f", "g", "h"), + listOf(listOf(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, big, -big, 9_007_199_254_740_992L, byteArrayOf(1, 2, 3), null)), + 0, + false, + ) + } + val row = ok("query", db().put("sql", "x")).getJSONArray("rows").getJSONArray(0) + assertEquals("NaN", row.get(0)) + assertEquals("Infinity", row.get(1)) + assertEquals("-Infinity", row.get(2)) + assertEquals("9007199254740993", row.get(3)) + assertEquals("-9007199254740993", row.get(4)) + assertEquals(9_007_199_254_740_992L, row.getLong(5)) + val blob = row.getJSONObject(6) + assertEquals("AQID", blob.getString("base64")) + assertEquals(3, blob.getInt("bytes")) + assertFalse(blob.getBoolean("truncated")) + assertTrue(row.isNull(7)) + assertEquals(true, DatabaseTools.encodeValue(ByteArray(1024).also { }).let { (it as JSONObject).getBoolean("truncated") }) + assertEquals(1.5, DatabaseTools.encodeValue(1.5)) + } + + @Test fun getSchemaGroupsByType() { + engine.appConnections += conn(1, "/data/a.db") + answerWith( + "SELECT type" to QueryResult( + listOf("type", "name", "tbl_name", "sql"), + listOf( + listOf("index", "i1", "t", "CREATE INDEX i1 ON t(a)"), + listOf("table", "t", "t", "CREATE TABLE t(a)"), + listOf("trigger", "tr", "t", "CREATE TRIGGER tr ..."), + listOf("view", "v", "v", "CREATE VIEW v AS ..."), + ), + 0, + false, + ), + ) + val r = ok("get_schema", db()) + assertEquals("t", r.getJSONArray("tables").getJSONObject(0).getString("name")) + assertEquals("CREATE INDEX i1 ON t(a)", r.getJSONArray("indexes").getJSONObject(0).getString("sql")) + assertEquals(1, r.getJSONArray("views").length()) + assertEquals(1, r.getJSONArray("triggers").length()) + assertTrue(seenSql.single().contains("sqlite_schema")) + } + + @Test fun explainQueryPlanPrefixesTheSql() { + engine.appConnections += conn(1, "/data/a.db") + answerWith("EXPLAIN QUERY PLAN" to QueryResult(listOf("id", "parent", "notused", "detail"), listOf(listOf(3L, 0L, 0L, "SCAN t")), 0, false)) + val plan = ok("explain_query_plan", db().put("sql", "select * from t")).getJSONArray("plan") + assertEquals("SCAN t", plan.getJSONObject(0).getString("detail")) + assertEquals("EXPLAIN QUERY PLAN select * from t", seenSql.single()) + } + + @Test fun getStatsCountsRowsUnderTenTables() { + engine.appConnections += conn(1, "/data/a.db") + fun one(v: Long) = QueryResult(listOf("x"), listOf(listOf(v)), 0, false) + answerWith( + "PRAGMA page_count" to one(10), + "PRAGMA page_size" to one(4096), + "PRAGMA freelist_count" to one(2), + "SELECT name" to QueryResult(listOf("name"), listOf(listOf("a\"b"), listOf("c")), 0, false), + "SELECT COUNT" to one(7), + ) + val r = ok("get_stats", db()) + assertEquals(10, r.getInt("page_count")) + assertEquals(4096, r.getInt("page_size")) + assertEquals(2, r.getInt("freelist_count")) + assertEquals(40960, r.getInt("size_bytes")) + assertEquals(7, r.getJSONObject("row_counts").getInt("a\"b")) + assertTrue(seenSql.contains("SELECT COUNT(*) FROM \"a\"\"b\"")) + } + + @Test fun getStatsSkipsCountsFromTenTables() { + engine.appConnections += conn(1, "/data/a.db") + answerWith("SELECT name" to QueryResult(listOf("name"), (1..10).map { listOf("t$it") }, 0, false)) + val r = ok("get_stats", db()) + assertFalse(r.has("row_counts")) + assertTrue(r.has("row_counts_skipped")) + assertTrue(seenSql.none { it.startsWith("SELECT COUNT") }) + } + + @Test fun integrityCheckIsQuickUnlessAskedForFull() { + engine.appConnections += conn(1, "/data/a.db") + answerWith("PRAGMA" to QueryResult(listOf("quick_check"), listOf(listOf("ok")), 0, false)) + val quick = ok("integrity_check", db()) + assertTrue(quick.getBoolean("ok")) + assertEquals("quick_check", quick.getString("check")) + ok("integrity_check", db().put("full", true)) + assertEquals(listOf("PRAGMA quick_check", "PRAGMA integrity_check"), seenSql) + answerWith("PRAGMA" to QueryResult(listOf("c"), listOf(listOf("row 1 missing from index i1")), 0, false)) + assertFalse(ok("integrity_check", db()).getBoolean("ok")) + } + + @Test fun getEventsReturnsCursorDroppedAndTurnsOnExpansion() { + assertFalse(engine.clientConnected) + engine.addEvent(EventKind.STATEMENT, "select 1") + engine.addEvent(EventKind.PROFILE, "select 1", durationNanos = 99) + engine.addEvent(EventKind.STATEMENT, "select 2") + engine.dropOldest(1) + val t = tools + val first = ok("get_events", t = t) + assertTrue(engine.clientConnected) + assertEquals(1, first.getInt("dropped")) + assertEquals(3, first.getInt("next")) + val events = first.getJSONArray("events") + assertEquals(2, events.length()) + assertEquals("profile", events.getJSONObject(0).getString("kind")) + assertEquals(99, events.getJSONObject(0).getInt("duration_nanos")) + assertTrue(events.getJSONObject(1).isNull("duration_nanos")) + val second = ok("get_events", JSONObject().put("after", 3), t) + assertEquals(0, second.getJSONArray("events").length()) + assertEquals(0, second.getInt("dropped")) + assertEquals(3, second.getInt("next")) + t.onServerStopped() + assertFalse(engine.clientConnected) + } + + @Test fun stoppingTheServerClosesServerConnections() { + engine.appConnections += conn(1, "/data/a.db") + val t = tools + ok("get_stats", db(), t) + ok("get_stats", db(), t) + assertEquals(1, engine.openedServerConnections.size) + t.onServerStopped() + ok("get_stats", db(), t) + assertEquals(2, engine.openedServerConnections.size) + } +} diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index a1bf367dbd..9d705d3bda 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -1,10 +1,5 @@ package org.appdevforall.sqlitedebugger.mcp -import org.appdevforall.sqlitedebugger.mcp.McpHttp -import org.appdevforall.sqlitedebugger.mcp.McpProtocol -import org.appdevforall.sqlitedebugger.mcp.McpTool -import org.appdevforall.sqlitedebugger.mcp.McpToolError -import org.appdevforall.sqlitedebugger.mcp.McpTools import org.json.JSONArray import org.json.JSONObject import org.junit.After @@ -22,342 +17,317 @@ import java.net.Socket */ class McpProtocolTest { - private var sessionNumber = 0 - private val echo = McpTool("echo", "Echo", "Returns its arguments.") { args -> JSONObject().put("got", args) } - private val needsPerson = McpTool("needs_person", "Needs a person", "Always says a person is needed.", readOnly = false) { _ -> - throw McpToolError("A person is needed: tap Allow on the sharing phone.", JSONObject().put("person_needed", true)) - } - private val crashes = McpTool("crashes", "Crashes", "Throws an unexpected exception.") { _ -> throw IllegalStateException("boom") } - - private fun protocol(maxSessions: Int = 16) = - McpProtocol(listOf(echo, needsPerson, crashes), "test", { "s${++sessionNumber}" }, maxSessions) - - private fun initBody(version: String = "2025-06-18") = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize") - .put("params", JSONObject().put("protocolVersion", version).put("capabilities", JSONObject()) - .put("clientInfo", JSONObject().put("name", "test").put("version", "1"))).toString() - - private fun request(id: Any, method: String, params: JSONObject? = null) = JSONObject().put("jsonrpc", "2.0").put("id", id) - .put("method", method).also { if (params != null) it.put("params", params) } - - private fun session(p: McpProtocol): String { - val r = p.post(initBody(), null, null) - assertEquals(200, r.status) - return r.headers[McpProtocol.SESSION_HEADER]!! - } - - private fun call(p: McpProtocol, s: String, tool: String, args: JSONObject? = null): JSONObject { - val params = JSONObject().put("name", tool).also { if (args != null) it.put("arguments", args) } - val r = p.post(request(7, "tools/call", params).toString(), s, null) - assertEquals(200, r.status) - return JSONObject(r.body!!) - } - - // ---------------------------------------------------------------- the protocol - - @Test fun initializeAgreesVersionAndStartsSession() { - val p = protocol() - val r = p.post(initBody("2025-03-26"), null, null) - assertEquals(200, r.status) - assertEquals("s1", r.headers[McpProtocol.SESSION_HEADER]) - val result = JSONObject(r.body!!).getJSONObject("result") - assertEquals("2025-03-26", result.getString("protocolVersion")) - assertEquals(McpProtocol.SERVER_NAME, result.getJSONObject("serverInfo").getString("name")) - assertTrue(result.getJSONObject("capabilities").has("tools")) - assertEquals(1, p.sessionCount()) - } - - @Test fun unknownVersionGetsTheNewest() { - val r = protocol().post(initBody("1999-01-01"), null, null) - assertEquals(McpProtocol.VERSIONS[0], JSONObject(r.body!!).getJSONObject("result").getString("protocolVersion")) - } - - @Test fun requestsNeedALiveSession() { - val p = protocol() - assertEquals(400, p.post(request(1, "ping").toString(), null, null).status) - assertEquals(404, p.post(request(1, "ping").toString(), "nope", null).status) - val s = session(p) - assertEquals(200, p.post(request(1, "ping").toString(), s, null).status) - } - - @Test fun unsupportedVersionHeaderIsRefused() { - val p = protocol(); val s = session(p) - assertEquals(400, p.post(request(1, "ping").toString(), s, "1999-01-01").status) - assertEquals(200, p.post(request(1, "ping").toString(), s, "2025-06-18").status) - } - - @Test fun notificationsGetNoAnswer() { - val p = protocol(); val s = session(p) - val r = p.post(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized").toString(), s, null) - assertEquals(202, r.status) - assertNull(r.body) - } - - @Test fun pingAnswersEmptyResult() { - val p = protocol(); val s = session(p) - val r = JSONObject(p.post(request("a", "ping").toString(), s, null).body!!) - assertEquals("a", r.get("id")) - assertEquals(0, r.getJSONObject("result").length()) - } - - @Test fun toolsListDescribesEveryTool() { - val p = protocol(); val s = session(p) - val tools = JSONObject(p.post(request(2, "tools/list").toString(), s, null).body!!).getJSONObject("result").getJSONArray("tools") - val names = (0 until tools.length()).map { tools.getJSONObject(it).getString("name") } - assertEquals(listOf("echo", "needs_person", "crashes"), names) - val first = tools.getJSONObject(0) - assertEquals("object", first.getJSONObject("inputSchema").getString("type")) - assertTrue(first.getJSONObject("annotations").getBoolean("readOnlyHint")) - assertFalse(tools.getJSONObject(1).getJSONObject("annotations").getBoolean("readOnlyHint")) - } - - @Test fun toolCallReturnsStructuredContent() { - val p = protocol(); val s = session(p) - val result = call(p, s, "echo", JSONObject().put("x", 3)).getJSONObject("result") - assertFalse(result.getBoolean("isError")) - assertEquals(3, result.getJSONObject("structuredContent").getJSONObject("got").getInt("x")) - assertEquals("text", result.getJSONArray("content").getJSONObject(0).getString("type")) - } - - @Test fun toolCallWithoutArgumentsGetsEmptyObject() { - val p = protocol(); val s = session(p) - val got = call(p, s, "echo").getJSONObject("result").getJSONObject("structuredContent").getJSONObject("got") - assertEquals(0, got.length()) - } - - @Test fun toolErrorIsAResultWithIsError() { - val p = protocol(); val s = session(p) - val result = call(p, s, "needs_person").getJSONObject("result") - assertTrue(result.getBoolean("isError")) - assertTrue(result.getJSONArray("content").getJSONObject(0).getString("text").contains("person is needed")) - assertTrue(result.getJSONObject("structuredContent").getBoolean("person_needed")) - } - - @Test fun unexpectedExceptionIsAResultWithIsError() { - val p = protocol(); val s = session(p) - val result = call(p, s, "crashes").getJSONObject("result") - assertTrue(result.getBoolean("isError")) - assertTrue(result.getJSONArray("content").getJSONObject(0).getString("text").contains("boom")) - } - - @Test fun unknownToolAndBadArgumentsAreInvalidParams() { - val p = protocol(); val s = session(p) - assertEquals(McpProtocol.INVALID_PARAMS, call(p, s, "nope").getJSONObject("error").getInt("code")) - val bad = request(3, "tools/call", JSONObject().put("name", "echo").put("arguments", JSONArray())).toString() - assertEquals(McpProtocol.INVALID_PARAMS, JSONObject(p.post(bad, s, null).body!!).getJSONObject("error").getInt("code")) - } - - @Test fun unknownMethodIsMethodNotFound() { - val p = protocol(); val s = session(p) - val r = JSONObject(p.post(request(4, "resources/list").toString(), s, null).body!!) - assertEquals(McpProtocol.METHOD_NOT_FOUND, r.getJSONObject("error").getInt("code")) - } - - @Test fun badJsonIsAParseError() { - val r = protocol().post("{not json", null, null) - assertEquals(400, r.status) - assertEquals(McpProtocol.PARSE_ERROR, JSONObject(r.body!!).getJSONObject("error").getInt("code")) - } - - @Test fun batchGetsAnArrayOfReplies() { - val p = protocol(); val s = session(p) - val batch = JSONArray().put(request(1, "ping")).put(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/x")).put(request(2, "tools/list")) - val r = p.post(batch.toString(), s, null) - assertEquals(200, r.status) - val replies = JSONArray(r.body!!) - assertEquals(2, replies.length()) - assertEquals(1, replies.getJSONObject(0).getInt("id")) - assertEquals(2, replies.getJSONObject(1).getInt("id")) - } - - @Test fun initializeMustBeAlone() { - val batch = JSONArray().put(JSONObject(initBody())).put(request(2, "ping")) - assertEquals(400, protocol().post(batch.toString(), null, null).status) - } - - @Test fun deleteEndsTheSession() { - val p = protocol(); val s = session(p) - assertEquals(204, p.delete(s).status) - assertEquals(404, p.delete(s).status) - assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) - } - - @Test fun oldestSessionIsDroppedBeyondTheLimit() { - val p = protocol(maxSessions = 2) - val a = session(p); val b = session(p) - p.post(request(1, "ping").toString(), a, null) // a is now the most recently used - val c = session(p) // drops b - assertEquals(2, p.sessionCount()) - assertEquals(200, p.post(request(1, "ping").toString(), a, null).status) - assertEquals(404, p.post(request(1, "ping").toString(), b, null).status) - assertEquals(200, p.post(request(1, "ping").toString(), c, null).status) - } - - @Test fun endAllEndsEverySession() { - val p = protocol(); val s = session(p) - p.endAll() - assertEquals(0, p.sessionCount()) - assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) - } - - @Test fun statusLineBecomesOneWord() { - assertEquals("serving", McpTools.stateOf("Serving Store_12345678", "http://192.168.1.5:6175/")) - assertEquals("failed", McpTools.stateOf("Failed: storage access hasn't been granted", null)) - assertEquals("paused", McpTools.stateOf("Paused while the screen is off.", null)) - assertEquals("stopped", McpTools.stateOf("Stopped", null)) - assertEquals("starting", McpTools.stateOf("Starting…", null)) - assertEquals("starting", McpTools.stateOf("Restarting after the server stopped unexpectedly…", null)) - assertEquals("starting", McpTools.stateOf("Not on Wi-Fi — starting a hotspot…", null)) - } - - // ---------------------------------------------------------------- step 3: share and server tools - - private val share = org.appdevforall.localstore.server.ShareControl - - @Test fun shareStateBecomesOneWord() { - assertEquals("waiting_for_phone", share.stateWord("OPEN", 0, false)) - assertEquals("preparing", share.stateWord("PREPARING", 0, false)) - assertEquals("phone_connecting", share.stateWord("ASKED", 0, false)) - assertEquals("waiting_for_allow", share.stateWord("REVEALED", 0, false)) - assertEquals("sending", share.stateWord("ALLOWED", 0, false)) - assertEquals("transfer_failed", share.stateWord("ALLOWED", 2, false)) - assertEquals("done", share.stateWord("DONE", 0, false)) - assertEquals("denied", share.stateWord("DENIED", 0, false)) - assertEquals("expired", share.stateWord("CLOSED", 0, false)) - assertEquals("not_serving", share.stateWord("NONE", 0, false)) - assertEquals("not_serving", share.stateWord(null, 0, false)) - assertEquals("cant_share", share.stateWord("ERROR", 0, true)) - assertEquals("closed", share.stateWord("ERROR", 0, false)) - } - - /** The rule MCP control rests on: ShareControl may open, poll and close a share, and never allow or deny one. */ - @Test fun shareControlCanNeverAllowOrDeny() { - val ipc = org.appdevforall.localstore.server.Ipc - val field = share.javaClass.getDeclaredField("ALLOWED_MESSAGES").apply { isAccessible = true } - val allowed = field.get(null) as Set<*> - assertEquals(setOf(ipc.MSG_SHARE_OPEN, ipc.MSG_SHARE_POLL, ipc.MSG_SHARE_CLOSE), allowed) - assertFalse(ipc.MSG_SHARE_ALLOW in allowed) - assertFalse(ipc.MSG_SHARE_DENY in allowed) - } - - @Test fun waitSecondsIsCheckedAndCapped() { - assertEquals(10, McpTools.waitArg(JSONObject(), 10)) - assertEquals(10, McpTools.waitArg(JSONObject().put("wait_seconds", JSONObject.NULL), 10)) - assertEquals(5, McpTools.waitArg(JSONObject().put("wait_seconds", 5), 10)) - assertEquals(2, McpTools.waitArg(JSONObject().put("wait_seconds", 2.7), 10)) - assertEquals(share.MAX_WAIT_S, McpTools.waitArg(JSONObject().put("wait_seconds", 999), 10)) - assertEquals(0, McpTools.waitArg(JSONObject().put("wait_seconds", -3), 10)) - assertTrue(runCatching { McpTools.waitArg(JSONObject().put("wait_seconds", "5"), 10) }.exceptionOrNull() is McpToolError) - } - - @Test fun storeArgumentIsOwnOrCopy() { - assertNull(McpTools.storeArg(JSONObject())) - assertNull(McpTools.storeArg(JSONObject().put("store", JSONObject.NULL))) - assertEquals("own", McpTools.storeArg(JSONObject().put("store", "own"))) - assertEquals("copy", McpTools.storeArg(JSONObject().put("store", "copy"))) - assertTrue(runCatching { McpTools.storeArg(JSONObject().put("store", "both")) }.exceptionOrNull() is McpToolError) - assertTrue(runCatching { McpTools.storeArg(JSONObject().put("store", 1)) }.exceptionOrNull() is McpToolError) - } - - // ---------------------------------------------------------------- the HTTP side - - private val token = "secret-token" - private var server: McpHttp? = null - - @After fun stopServer() { server?.stop(); server = null } - - private fun startServer(): Int { - val s = McpHttp(protocol(), { token }, port = 0) - s.start() - server = s - return s.boundPort - } - - private class Answer(val status: Int, val headers: Map, val body: String) - - /** One request on its own connection; [headers] may replace Host. */ - private fun http(port: Int, method: String, path: String = McpHttp.PATH, headers: Map = emptyMap(), body: String? = null): Answer { - Socket("127.0.0.1", port).use { s -> - s.soTimeout = 5000 - val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) - val all = linkedMapOf("Host" to "127.0.0.1:$port", "Connection" to "close") - all.putAll(headers) - if (body != null) { all["Content-Type"] = "application/json"; all["Content-Length"] = bytes.size.toString() } - val head = StringBuilder("$method $path HTTP/1.1\r\n") - for ((k, v) in all) head.append(k).append(": ").append(v).append("\r\n") - head.append("\r\n") - s.getOutputStream().apply { write(head.toString().toByteArray(Charsets.ISO_8859_1)); write(bytes); flush() } - val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) - val lines = text.substringBefore("\r\n\r\n").split("\r\n") - val status = lines[0].split(' ')[1].toInt() - val h = lines.drop(1).associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() } - return Answer(status, h, text.substringAfter("\r\n\r\n", "")) - } - } - - private val auth get() = mapOf("Authorization" to "Bearer $token") - - @Test fun httpNeedsTheToken() { - val port = startServer() - val none = http(port, "POST", body = initBody()) - assertEquals(401, none.status) - assertNotNull(none.headers["www-authenticate"]) - assertEquals(401, http(port, "POST", headers = mapOf("Authorization" to "Bearer wrong"), body = initBody()).status) - assertFalse("the token never appears in a refusal", none.body.contains(token)) - } - - @Test fun httpInitializeWithTheToken() { - val port = startServer() - val r = http(port, "POST", headers = auth, body = initBody()) - assertEquals(200, r.status) - assertNotNull(r.headers["mcp-session-id"]) - assertEquals("2025-06-18", JSONObject(r.body).getJSONObject("result").getString("protocolVersion")) - } - - @Test fun httpLocalhostHostIsAccepted() { - val port = startServer() - assertEquals(200, http(port, "POST", headers = auth + ("Host" to "localhost:$port"), body = initBody()).status) - } - - @Test fun httpOtherHostIsRefused() { - val port = startServer() - assertEquals(403, http(port, "POST", headers = auth + ("Host" to "evil.example"), body = initBody()).status) - assertEquals(403, http(port, "POST", headers = auth + ("Host" to "127.0.0.1:x"), body = initBody()).status) - } - - @Test fun httpWebPageOriginIsRefused() { - val port = startServer() - assertEquals(403, http(port, "POST", headers = auth + ("Origin" to "https://evil.example"), body = initBody()).status) - assertEquals(200, http(port, "POST", headers = auth + ("Origin" to "http://localhost:3000"), body = initBody()).status) - } - - @Test fun httpGetIsNotAllowed() { - val port = startServer() - val r = http(port, "GET", headers = auth) - assertEquals(405, r.status) - assertEquals("POST, DELETE", r.headers["allow"]) - } - - @Test fun httpOtherPathIsNotFound() { - assertEquals(404, http(startServer(), "POST", path = "/other", headers = auth, body = initBody()).status) - } - - @Test fun httpWrongContentTypeIsRefused() { - val port = startServer() - Socket("127.0.0.1", port).use { s -> - val body = initBody().toByteArray() - s.getOutputStream().write(("POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer $token\r\nConnection: close\r\n" + - "Content-Type: text/plain\r\nContent-Length: ${body.size}\r\n\r\n").toByteArray() + body) - val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) - assertTrue(text.startsWith("HTTP/1.1 415")) - } - } - - @Test fun httpSessionThenDelete() { - val port = startServer() - val s = http(port, "POST", headers = auth, body = initBody()).headers["mcp-session-id"]!! - val ping = request(1, "ping").toString() - assertEquals(200, http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = ping).status) - assertEquals(204, http(port, "DELETE", headers = auth + ("Mcp-Session-Id" to s)).status) - assertEquals(404, http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = ping).status) - } + private var sessionNumber = 0 + private val echo = McpTool("echo", "Echo", "Returns its arguments.") { args -> JSONObject().put("got", args) } + private val needsPerson = McpTool("needs_person", "Needs a person", "Always says a person is needed.", readOnly = false) { _ -> + throw McpToolError("A person is needed: tap Allow on the sharing phone.", JSONObject().put("person_needed", true)) + } + private val crashes = McpTool("crashes", "Crashes", "Throws an unexpected exception.") { _ -> throw IllegalStateException("boom") } + + private fun protocol(maxSessions: Int = 16) = + McpProtocol(listOf(echo, needsPerson, crashes), "test", { "s${++sessionNumber}" }, maxSessions) + + private fun initBody(version: String = "2025-06-18") = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize") + .put("params", JSONObject().put("protocolVersion", version).put("capabilities", JSONObject()) + .put("clientInfo", JSONObject().put("name", "test").put("version", "1"))).toString() + + private fun request(id: Any, method: String, params: JSONObject? = null) = JSONObject().put("jsonrpc", "2.0").put("id", id) + .put("method", method).also { if (params != null) it.put("params", params) } + + private fun session(p: McpProtocol): String { + val r = p.post(initBody(), null, null) + assertEquals(200, r.status) + return r.headers[McpProtocol.SESSION_HEADER]!! + } + + private fun call(p: McpProtocol, s: String, tool: String, args: JSONObject? = null): JSONObject { + val params = JSONObject().put("name", tool).also { if (args != null) it.put("arguments", args) } + val r = p.post(request(7, "tools/call", params).toString(), s, null) + assertEquals(200, r.status) + return JSONObject(r.body!!) + } + + // ---------------------------------------------------------------- the protocol + + @Test fun initializeAgreesVersionAndStartsSession() { + val p = protocol() + val r = p.post(initBody("2025-03-26"), null, null) + assertEquals(200, r.status) + assertEquals("s1", r.headers[McpProtocol.SESSION_HEADER]) + val result = JSONObject(r.body!!).getJSONObject("result") + assertEquals("2025-03-26", result.getString("protocolVersion")) + assertEquals(McpProtocol.SERVER_NAME, result.getJSONObject("serverInfo").getString("name")) + assertTrue(result.getJSONObject("capabilities").has("tools")) + assertEquals(1, p.sessionCount()) + } + + @Test fun unknownVersionGetsTheNewest() { + val r = protocol().post(initBody("1999-01-01"), null, null) + assertEquals(McpProtocol.VERSIONS[0], JSONObject(r.body!!).getJSONObject("result").getString("protocolVersion")) + } + + @Test fun requestsNeedALiveSession() { + val p = protocol() + assertEquals(400, p.post(request(1, "ping").toString(), null, null).status) + assertEquals(404, p.post(request(1, "ping").toString(), "nope", null).status) + val s = session(p) + assertEquals(200, p.post(request(1, "ping").toString(), s, null).status) + } + + @Test fun unsupportedVersionHeaderIsRefused() { + val p = protocol(); val s = session(p) + assertEquals(400, p.post(request(1, "ping").toString(), s, "1999-01-01").status) + assertEquals(200, p.post(request(1, "ping").toString(), s, "2025-06-18").status) + } + + @Test fun notificationsGetNoAnswer() { + val p = protocol(); val s = session(p) + val r = p.post(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized").toString(), s, null) + assertEquals(202, r.status) + assertNull(r.body) + } + + @Test fun pingAnswersEmptyResult() { + val p = protocol(); val s = session(p) + val r = JSONObject(p.post(request("a", "ping").toString(), s, null).body!!) + assertEquals("a", r.get("id")) + assertEquals(0, r.getJSONObject("result").length()) + } + + @Test fun toolsListDescribesEveryTool() { + val p = protocol(); val s = session(p) + val tools = JSONObject(p.post(request(2, "tools/list").toString(), s, null).body!!).getJSONObject("result").getJSONArray("tools") + val names = (0 until tools.length()).map { tools.getJSONObject(it).getString("name") } + assertEquals(listOf("echo", "needs_person", "crashes"), names) + val first = tools.getJSONObject(0) + assertEquals("object", first.getJSONObject("inputSchema").getString("type")) + assertTrue(first.getJSONObject("annotations").getBoolean("readOnlyHint")) + assertFalse(tools.getJSONObject(1).getJSONObject("annotations").getBoolean("readOnlyHint")) + } + + @Test fun toolCallReturnsStructuredContent() { + val p = protocol(); val s = session(p) + val result = call(p, s, "echo", JSONObject().put("x", 3)).getJSONObject("result") + assertFalse(result.getBoolean("isError")) + assertEquals(3, result.getJSONObject("structuredContent").getJSONObject("got").getInt("x")) + assertEquals("text", result.getJSONArray("content").getJSONObject(0).getString("type")) + } + + @Test fun toolCallWithoutArgumentsGetsEmptyObject() { + val p = protocol(); val s = session(p) + val got = call(p, s, "echo").getJSONObject("result").getJSONObject("structuredContent").getJSONObject("got") + assertEquals(0, got.length()) + } + + @Test fun toolErrorIsAResultWithIsError() { + val p = protocol(); val s = session(p) + val result = call(p, s, "needs_person").getJSONObject("result") + assertTrue(result.getBoolean("isError")) + assertTrue(result.getJSONArray("content").getJSONObject(0).getString("text").contains("person is needed")) + assertTrue(result.getJSONObject("structuredContent").getBoolean("person_needed")) + } + + @Test fun unexpectedExceptionIsAResultWithIsError() { + val p = protocol(); val s = session(p) + val result = call(p, s, "crashes").getJSONObject("result") + assertTrue(result.getBoolean("isError")) + assertTrue(result.getJSONArray("content").getJSONObject(0).getString("text").contains("boom")) + } + + @Test fun unknownToolAndBadArgumentsAreInvalidParams() { + val p = protocol(); val s = session(p) + assertEquals(McpProtocol.INVALID_PARAMS, call(p, s, "nope").getJSONObject("error").getInt("code")) + val bad = request(3, "tools/call", JSONObject().put("name", "echo").put("arguments", JSONArray())).toString() + assertEquals(McpProtocol.INVALID_PARAMS, JSONObject(p.post(bad, s, null).body!!).getJSONObject("error").getInt("code")) + } + + @Test fun unknownMethodIsMethodNotFound() { + val p = protocol(); val s = session(p) + val r = JSONObject(p.post(request(4, "resources/list").toString(), s, null).body!!) + assertEquals(McpProtocol.METHOD_NOT_FOUND, r.getJSONObject("error").getInt("code")) + } + + @Test fun badJsonIsAParseError() { + val r = protocol().post("{not json", null, null) + assertEquals(400, r.status) + assertEquals(McpProtocol.PARSE_ERROR, JSONObject(r.body!!).getJSONObject("error").getInt("code")) + } + + @Test fun batchGetsAnArrayOfReplies() { + val p = protocol(); val s = session(p) + val batch = JSONArray().put(request(1, "ping")).put(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/x")).put(request(2, "tools/list")) + val r = p.post(batch.toString(), s, null) + assertEquals(200, r.status) + val replies = JSONArray(r.body!!) + assertEquals(2, replies.length()) + assertEquals(1, replies.getJSONObject(0).getInt("id")) + assertEquals(2, replies.getJSONObject(1).getInt("id")) + } + + @Test fun initializeMustBeAlone() { + val batch = JSONArray().put(JSONObject(initBody())).put(request(2, "ping")) + assertEquals(400, protocol().post(batch.toString(), null, null).status) + } + + @Test fun deleteEndsTheSession() { + val p = protocol(); val s = session(p) + assertEquals(204, p.delete(s).status) + assertEquals(404, p.delete(s).status) + assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) + } + + @Test fun oldestSessionIsDroppedBeyondTheLimit() { + val p = protocol(maxSessions = 2) + val a = session(p); val b = session(p) + p.post(request(1, "ping").toString(), a, null) // a is now the most recently used + val c = session(p) // drops b + assertEquals(2, p.sessionCount()) + assertEquals(200, p.post(request(1, "ping").toString(), a, null).status) + assertEquals(404, p.post(request(1, "ping").toString(), b, null).status) + assertEquals(200, p.post(request(1, "ping").toString(), c, null).status) + } + + @Test fun endAllEndsEverySession() { + val p = protocol(); val s = session(p) + p.endAll() + assertEquals(0, p.sessionCount()) + assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) + } + + // ---------------------------------------------------------------- the HTTP side + + private val token = "secret-token" + private var server: McpHttp? = null + + @After fun stopServer() { server?.stop(); server = null } + + private fun startServer(): Int { + val s = McpHttp(protocol(), { token }, port = 0) + s.start() + server = s + return s.boundPort + } + + private class Answer(val status: Int, val headers: Map, val body: String) + + /** One request on its own connection; [headers] may replace Host. */ + private fun http(port: Int, method: String, path: String = McpHttp.PATH, headers: Map = emptyMap(), body: String? = null): Answer { + Socket("127.0.0.1", port).use { s -> + s.soTimeout = 5000 + val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) + val all = linkedMapOf("Host" to "127.0.0.1:$port", "Connection" to "close") + all.putAll(headers) + if (body != null) { all["Content-Type"] = "application/json"; all["Content-Length"] = bytes.size.toString() } + val head = StringBuilder("$method $path HTTP/1.1\r\n") + for ((k, v) in all) head.append(k).append(": ").append(v).append("\r\n") + head.append("\r\n") + s.getOutputStream().apply { write(head.toString().toByteArray(Charsets.ISO_8859_1)); write(bytes); flush() } + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + val lines = text.substringBefore("\r\n\r\n").split("\r\n") + val status = lines[0].split(' ')[1].toInt() + val h = lines.drop(1).associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() } + return Answer(status, h, text.substringAfter("\r\n\r\n", "")) + } + } + + private val auth get() = mapOf("Authorization" to "Bearer $token") + + @Test fun tokenIs32BytesUrlSafeAndNew() { + val a = McpHttp.newToken() + assertEquals(43, a.length) + assertTrue(a.matches(Regex("[A-Za-z0-9_-]{43}"))) + assertTrue(a != McpHttp.newToken()) + } + + @Test fun base64MatchesTheJdkEncoder() { + for (n in 0..40) { + val bytes = ByteArray(n) { (it * 37 + 250).toByte() } + assertEquals(java.util.Base64.getEncoder().encodeToString(bytes), McpHttp.base64(bytes, urlSafe = false, pad = true)) + assertEquals(java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes), McpHttp.base64(bytes, urlSafe = true, pad = false)) + } + } + + @Test fun httpPortZeroBindsAFreePortOnLoopback() { + val port = startServer() + assertTrue(port in 1..65535) + assertEquals("127.0.0.1", java.net.Socket("127.0.0.1", port).use { it.inetAddress.hostAddress }) + } + + @Test fun httpNinthConnectionIsRefused() { + val port = startServer() + val held = (1..McpHttp.MAX_CONNECTIONS).map { Socket("127.0.0.1", port) } + try { + Thread.sleep(300) + Socket("127.0.0.1", port).use { s -> + s.soTimeout = 5000 + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text.startsWith("HTTP/1.1 503")) + } + } finally { held.forEach { it.close() } } + } + + @Test fun httpNeedsTheToken() { + val port = startServer() + val none = http(port, "POST", body = initBody()) + assertEquals(401, none.status) + assertNotNull(none.headers["www-authenticate"]) + assertEquals(401, http(port, "POST", headers = mapOf("Authorization" to "Bearer wrong"), body = initBody()).status) + assertFalse("the token never appears in a refusal", none.body.contains(token)) + } + + @Test fun httpInitializeWithTheToken() { + val port = startServer() + val r = http(port, "POST", headers = auth, body = initBody()) + assertEquals(200, r.status) + assertNotNull(r.headers["mcp-session-id"]) + assertEquals("2025-06-18", JSONObject(r.body).getJSONObject("result").getString("protocolVersion")) + } + + @Test fun httpLocalhostHostIsAccepted() { + val port = startServer() + assertEquals(200, http(port, "POST", headers = auth + ("Host" to "localhost:$port"), body = initBody()).status) + } + + @Test fun httpOtherHostIsRefused() { + val port = startServer() + assertEquals(403, http(port, "POST", headers = auth + ("Host" to "evil.example"), body = initBody()).status) + assertEquals(403, http(port, "POST", headers = auth + ("Host" to "127.0.0.1:x"), body = initBody()).status) + } + + @Test fun httpWebPageOriginIsRefused() { + val port = startServer() + assertEquals(403, http(port, "POST", headers = auth + ("Origin" to "https://evil.example"), body = initBody()).status) + assertEquals(200, http(port, "POST", headers = auth + ("Origin" to "http://localhost:3000"), body = initBody()).status) + } + + @Test fun httpGetIsNotAllowed() { + val port = startServer() + val r = http(port, "GET", headers = auth) + assertEquals(405, r.status) + assertEquals("POST, DELETE", r.headers["allow"]) + } + + @Test fun httpOtherPathIsNotFound() { + assertEquals(404, http(startServer(), "POST", path = "/other", headers = auth, body = initBody()).status) + } + + @Test fun httpWrongContentTypeIsRefused() { + val port = startServer() + Socket("127.0.0.1", port).use { s -> + val body = initBody().toByteArray() + s.getOutputStream().write(("POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer $token\r\nConnection: close\r\n" + + "Content-Type: text/plain\r\nContent-Length: ${body.size}\r\n\r\n").toByteArray() + body) + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text.startsWith("HTTP/1.1 415")) + } + } + + @Test fun httpSessionThenDelete() { + val port = startServer() + val s = http(port, "POST", headers = auth, body = initBody()).headers["mcp-session-id"]!! + val ping = request(1, "ping").toString() + assertEquals(200, http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = ping).status) + assertEquals(204, http(port, "DELETE", headers = auth + ("Mcp-Session-Id" to s)).status) + assertEquals(404, http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = ping).status) + } } From acddbd2586e2f1e91a2a240254af262df500055d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:54:59 +0000 Subject: [PATCH 028/203] ADFA-7135 Implement the SQLite debugger extension and its host tests sqlitedbg.c implements sqlitedbg.h as a loadable-extension client. Per-connection state is freed only from the xDestroy of sqlitedbg_connection_id; the trace CLOSE event only marks it closing. Events live in a ring of records in their exported layout. Server connections are recognised by a thread-local flag set around sqlitedbg_open_server's own open. test.sh builds SQLite 3.49.1 from the amalgamation (pinned) and runs sqlitedbg_test.c under ASan+UBSan and under TSan. The same run writes or checks the fixture the EventDecoder JVM test reads. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- .../src/main/cpp/CMakeLists.txt | 17 + .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 419 +++++++++ .../src/main/cpp/sqlitedbg.map | 6 + .../src/test/c/sqlitedbg_test.c | 841 ++++++++++++++++++ .../sqlitedebugger/engine/events.bin | Bin 0 -> 1792 bytes .../sqlitedebugger/engine/events.tsv | 21 + subprojects/sqlite-debugger/test.sh | 67 ++ 7 files changed, 1371 insertions(+) create mode 100644 subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt create mode 100644 subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c create mode 100644 subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.map create mode 100644 subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c create mode 100644 subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin create mode 100644 subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv create mode 100755 subprojects/sqlite-debugger/test.sh diff --git a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000..bbe9393af9 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.22.1) + +project(sqlitedbg C) + +# Only the headers: the extension runs inside requery's libsqlite3x.so and reaches SQLite through +# the api table it is given (sqlite3ext.h), so no SQLite is compiled or linked here. +set(SQLITE_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/../../../../sqlite-js/upstream/libs) + +add_library(sqlitedbg SHARED + sqlitedbg.c) + +target_include_directories(sqlitedbg PRIVATE ${SQLITE_HEADERS} ${CMAKE_CURRENT_SOURCE_DIR}) +target_compile_options(sqlitedbg PRIVATE -Wall -Wextra -fvisibility=hidden) +# Only JNI_OnLoad is exported, so sqlite3_api and our other symbols cannot bind to another library's. +target_link_options(sqlitedbg PRIVATE + -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/sqlitedbg.map + -Wl,-z,max-page-size=16384) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c new file mode 100644 index 0000000000..1442df0990 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -0,0 +1,419 @@ +// The SQLite debugger's extension (ADFA-7135). The contract is sqlitedbg.h. +// +// Built as a loadable-extension client (sqlite3ext.h): on a device every sqlite3_ call goes +// through the api table SQLite hands to the first sqlitedbg_extension_init, because libsqlitedbg.so +// links no SQLite of its own. Host tests define SQLITE_CORE, where the macros call SQLite directly. + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include +#include +#include +#include +#include +#include + +#include "sqlite3ext.h" +#include "sqlitedbg.h" + +SQLITE_EXTENSION_INIT1 + +#define DEFAULT_BUFFER_BYTES ((size_t)4 << 20) +#define DEFAULT_MAX_SQL_BYTES 4096u +#define RECORD_HEADER_BYTES 56u + +_Static_assert(sizeof(sqlitedbg_event_record) == RECORD_HEADER_BYTES, "event record layout"); + +// Padding record written where the next record would not fit before the end of the ring, so a +// record is always contiguous. kind 0 is never a real event. +#define KIND_PAD 0u + +typedef struct conn_state { + struct conn_state *prev, *next; + uint64_t id; + char *path; + int read_only; + int closing; + int64_t opened_at_ns; + int64_t open_thread_id; +} conn_state; + +// Taken only for the fields below; never while SQLite runs. +static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; +// Serialises sqlitedbg_install so a second caller does not return before the first registered. +static pthread_mutex_t g_install_lock = PTHREAD_MUTEX_INITIALIZER; + +static int g_installed; // g_install_lock +static int g_api_ready; // g_lock: sqlite3_api has been saved +static uint32_t g_max_sql; // set before g_installed, then read-only +static int g_client_connected; // atomic + +static conn_state *g_first, *g_last; +static uint64_t g_next_conn_id = 1; + +static unsigned char *g_ring; +static size_t g_cap; +static size_t g_head; // where the next record goes +static size_t g_tail; // the oldest record; never a padding record while g_used > 0 +static size_t g_used; // bytes between tail and head, padding included +static uint64_t g_next_seq = 1; + +// Set around the server's own sqlite3_open_v2: auto extensions run on the opening thread, inside it. +static __thread int tls_opening_server; + +static int64_t now_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; +} + +static int64_t this_thread_id(void) { +#ifdef __ANDROID__ + return (int64_t)gettid(); +#else + return (int64_t)syscall(SYS_gettid); +#endif +} + +static sqlitedbg_event_record *record_at(size_t offset) { + return (sqlitedbg_event_record *)(void *)(g_ring + offset); +} + +// Drops the oldest record, then any padding that is now the oldest. g_lock held. +static void evict_oldest(void) { + do { + uint32_t bytes = record_at(g_tail)->record_bytes; + g_used -= bytes; + g_tail += bytes; + if (g_tail >= g_cap) g_tail = 0; + } while (g_used > 0 && record_at(g_tail)->kind == KIND_PAD); +} + +// The seq of the oldest event still buffered, or the next one to be made if none is. g_lock held. +static uint64_t oldest_seq(void) { + return g_used > 0 ? record_at(g_tail)->seq : g_next_seq; +} + +// Makes room for one record of `need` bytes at g_head. g_lock held; need <= g_cap. +static void make_room(size_t need) { + for (;;) { + if (g_used == 0) { + g_head = g_tail = 0; + return; + } + if (g_head > g_tail) { + if (g_cap - g_head >= need) return; + if (g_tail >= need) { + sqlitedbg_event_record *pad = record_at(g_head); + pad->record_bytes = (uint32_t)(g_cap - g_head); + pad->kind = KIND_PAD; + g_used += g_cap - g_head; + g_head = 0; + return; + } + } else if (g_tail - g_head >= need) { + return; + } + evict_oldest(); + } +} + +// Longest prefix of sql, at most max bytes, that ends on a character boundary. +static size_t utf8_cut(const char *sql, size_t len, size_t max) { + if (len <= max) return len; + while (max > 0 && ((unsigned char)sql[max] & 0xC0) == 0x80) max--; + return max; +} + +static void add_event(uint32_t kind, uint64_t connection_id, int64_t duration_ns, uint32_t flags, + const char *sql, size_t sql_len) { + int64_t time = now_ns(); + int64_t tid = this_thread_id(); + size_t kept = utf8_cut(sql, sql_len, g_max_sql); + if (kept < sql_len) flags |= SQLITEDBG_EVENT_TRUNCATED; + size_t need = (RECORD_HEADER_BYTES + kept + 7) & ~(size_t)7; + + pthread_mutex_lock(&g_lock); + uint64_t seq = g_next_seq++; + if (need <= g_cap) { + make_room(need); + sqlitedbg_event_record *r = record_at(g_head); + r->record_bytes = (uint32_t)need; + r->kind = kind; + r->seq = seq; + r->connection_id = connection_id; + r->thread_id = tid; + r->time_ns = time; + r->duration_ns = duration_ns; + r->flags = flags; + r->sql_bytes = (uint32_t)kept; + memcpy((unsigned char *)r + RECORD_HEADER_BYTES, sql, kept); + memset((unsigned char *)r + RECORD_HEADER_BYTES + kept, 0, need - RECORD_HEADER_BYTES - kept); + g_head += need; + g_used += need; + if (g_head >= g_cap) g_head = 0; + } + pthread_mutex_unlock(&g_lock); +} + +// sqlite3_trace_v2 callback. C is the connection's conn_state, which lives until SQLite frees the +// connection, so it outlives every callback. +static int trace_cb(unsigned type, void *c, void *p, void *x) { + conn_state *cs = (conn_state *)c; + switch (type) { + case SQLITE_TRACE_STMT: + case SQLITE_TRACE_PROFILE: { + sqlite3_stmt *stmt = (sqlite3_stmt *)p; + const char *sql = NULL; + char *expanded = NULL; + uint32_t flags = 0; + int is_stmt = type == SQLITE_TRACE_STMT; + if (is_stmt) sql = (const char *)x; + else sql = sqlite3_sql(stmt); + if (!sql) sql = ""; + // A trigger's text starts with "--" and P is the outer statement, whose expansion would + // be the wrong text. + if (__atomic_load_n(&g_client_connected, __ATOMIC_RELAXED) && !(sql[0] == '-' && sql[1] == '-')) { + expanded = sqlite3_expanded_sql(stmt); + if (expanded) { + sql = expanded; + flags |= SQLITEDBG_EVENT_EXPANDED; + } + } + int64_t duration = is_stmt ? -1 : *(sqlite3_int64 *)x; + add_event(is_stmt ? SQLITEDBG_EVENT_STATEMENT : SQLITEDBG_EVENT_PROFILE, cs->id, duration, flags, sql, + strlen(sql)); + if (expanded) sqlite3_free(expanded); + break; + } + case SQLITE_TRACE_CLOSE: + // The close can still fail or leave a zombie, so only mark it: xDestroy frees. + pthread_mutex_lock(&g_lock); + cs->closing = 1; + pthread_mutex_unlock(&g_lock); + add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, 0, "", 0); + break; + } + return 0; +} + +// SQLite calls this when it really frees the connection (or if registering the function failed). +static void conn_destroy(void *p) { + conn_state *cs = (conn_state *)p; + pthread_mutex_lock(&g_lock); + if (cs->prev) cs->prev->next = cs->next; + else g_first = cs->next; + if (cs->next) cs->next->prev = cs->prev; + else g_last = cs->prev; + pthread_mutex_unlock(&g_lock); + free(cs->path); + free(cs); +} + +static void connection_id_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv) { + (void)argc; + (void)argv; + sqlite3_result_int64(ctx, (sqlite3_int64)((conn_state *)sqlite3_user_data(ctx))->id); +} + +int sqlitedbg_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines *api) { + (void)err; + if (tls_opening_server) return SQLITE_OK; + + pthread_mutex_lock(&g_lock); + if (!g_api_ready) { + SQLITE_EXTENSION_INIT2(api); + g_api_ready = 1; + } + pthread_mutex_unlock(&g_lock); + + conn_state *cs = (conn_state *)calloc(1, sizeof *cs); + if (!cs) return SQLITE_NOMEM; + const char *filename = sqlite3_db_filename(db, "main"); + cs->path = strdup(filename ? filename : ""); + if (!cs->path) { + free(cs); + return SQLITE_NOMEM; + } + cs->read_only = sqlite3_db_readonly(db, "main") == 1; + cs->opened_at_ns = now_ns(); + cs->open_thread_id = this_thread_id(); + + pthread_mutex_lock(&g_lock); + cs->id = g_next_conn_id++; + cs->prev = g_last; + if (g_last) g_last->next = cs; + else g_first = cs; + g_last = cs; + pthread_mutex_unlock(&g_lock); + + // On failure SQLite has already called conn_destroy, so cs is gone. + int rc = sqlite3_create_function_v2(db, "sqlitedbg_connection_id", 0, SQLITE_UTF8 | SQLITE_INNOCUOUS, cs, + connection_id_fn, NULL, NULL, conn_destroy); + if (rc != SQLITE_OK) return rc; + return sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_CLOSE, trace_cb, cs); +} + +int sqlitedbg_install(sqlitedbg_auto_extension_fn auto_extension, const sqlitedbg_config *config) { + if (!auto_extension) return SQLITE_MISUSE; + pthread_mutex_lock(&g_install_lock); + if (g_installed) { + pthread_mutex_unlock(&g_install_lock); + return SQLITE_OK; + } + size_t cap = config && config->buffer_bytes ? config->buffer_bytes : DEFAULT_BUFFER_BYTES; + uint32_t max_sql = config && config->max_sql_bytes ? config->max_sql_bytes : DEFAULT_MAX_SQL_BYTES; + // Room for two of the largest records, or the ring could never hold one beside a pad. + size_t min_cap = 2 * ((RECORD_HEADER_BYTES + (size_t)max_sql + 7) & ~(size_t)7); + if (cap < min_cap) cap = min_cap; + cap &= ~(size_t)7; + unsigned char *ring = (unsigned char *)calloc(1, cap); + if (!ring) { + pthread_mutex_unlock(&g_install_lock); + return SQLITE_NOMEM; + } + pthread_mutex_lock(&g_lock); + g_ring = ring; + g_cap = cap; + g_head = g_tail = g_used = 0; + g_max_sql = max_sql; + pthread_mutex_unlock(&g_lock); + + int rc = auto_extension((void (*)(void))sqlitedbg_extension_init); + if (rc == SQLITE_OK) { + g_installed = 1; + } else { + pthread_mutex_lock(&g_lock); + g_ring = NULL; + g_cap = 0; + pthread_mutex_unlock(&g_lock); + free(ring); + } + pthread_mutex_unlock(&g_install_lock); + return rc; +} + +size_t sqlitedbg_each_connection(void (*fn)(void *context, const sqlitedbg_connection *connection), + void *context) { + size_t n = 0; + pthread_mutex_lock(&g_lock); + for (conn_state *cs = g_first; cs; cs = cs->next) { + sqlitedbg_connection c; + c.id = cs->id; + c.path = cs->path; + c.read_only = cs->read_only; + c.closing = cs->closing; + c.opened_at_ns = cs->opened_at_ns; + c.open_thread_id = cs->open_thread_id; + fn(context, &c); + n++; + } + pthread_mutex_unlock(&g_lock); + return n; +} + +void sqlitedbg_read_events(uint64_t after, void *out, size_t out_bytes, sqlitedbg_read_result *result) { + result->next = after; + result->dropped = 0; + result->bytes = 0; + result->count = 0; + pthread_mutex_lock(&g_lock); + if (g_ring) { + uint64_t oldest = oldest_seq(); + if (oldest > after && oldest - after > 1) result->dropped = oldest - after - 1; + size_t offset = g_tail, left = g_used; + while (left > 0) { + const sqlitedbg_event_record *r = record_at(offset); + uint32_t bytes = r->record_bytes; + if (r->kind != KIND_PAD && r->seq > after) { + if (result->bytes + bytes > out_bytes) break; + memcpy((unsigned char *)out + result->bytes, r, bytes); + result->bytes += bytes; + result->count++; + result->next = r->seq; + } + left -= bytes; + offset += bytes; + if (offset >= g_cap) offset = 0; + } + } + pthread_mutex_unlock(&g_lock); +} + +void sqlitedbg_set_client_connected(int connected) { + __atomic_store_n(&g_client_connected, connected ? 1 : 0, __ATOMIC_RELAXED); +} + +static int server_authorizer(void *unused, int action, const char *a1, const char *a2, const char *db, + const char *trigger) { + (void)unused; + (void)a2; + (void)db; + (void)trigger; + switch (action) { + case SQLITE_INSERT: + case SQLITE_UPDATE: + case SQLITE_DELETE: + case SQLITE_CREATE_INDEX: + case SQLITE_CREATE_TABLE: + case SQLITE_CREATE_TEMP_INDEX: + case SQLITE_CREATE_TEMP_TABLE: + case SQLITE_CREATE_TEMP_TRIGGER: + case SQLITE_CREATE_TEMP_VIEW: + case SQLITE_CREATE_TRIGGER: + case SQLITE_CREATE_VIEW: + case SQLITE_CREATE_VTABLE: + case SQLITE_DROP_INDEX: + case SQLITE_DROP_TABLE: + case SQLITE_DROP_TEMP_INDEX: + case SQLITE_DROP_TEMP_TABLE: + case SQLITE_DROP_TEMP_TRIGGER: + case SQLITE_DROP_TEMP_VIEW: + case SQLITE_DROP_TRIGGER: + case SQLITE_DROP_VIEW: + case SQLITE_DROP_VTABLE: + case SQLITE_ALTER_TABLE: + case SQLITE_REINDEX: + case SQLITE_ANALYZE: + case SQLITE_ATTACH: + case SQLITE_DETACH: + return SQLITE_DENY; + case SQLITE_PRAGMA: + // PRAGMA query_only=0 would lift the guard, and a PRAGMA that stores a value writes. + // PRAGMA table_info(t) also has a second argument, so only these names are checked. + if (a1 && (sqlite3_stricmp(a1, "query_only") == 0 || sqlite3_stricmp(a1, "writable_schema") == 0 || + sqlite3_stricmp(a1, "wal_checkpoint") == 0 || + sqlite3_stricmp(a1, "incremental_vacuum") == 0 || sqlite3_stricmp(a1, "optimize") == 0)) + return SQLITE_DENY; + if (a1 && a2 && + (sqlite3_stricmp(a1, "journal_mode") == 0 || sqlite3_stricmp(a1, "user_version") == 0 || + sqlite3_stricmp(a1, "application_id") == 0 || sqlite3_stricmp(a1, "schema_version") == 0)) + return SQLITE_DENY; + return SQLITE_OK; + default: + return SQLITE_OK; + } +} + +int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db) { + *db = NULL; + pthread_mutex_lock(&g_lock); + int ready = g_api_ready; + pthread_mutex_unlock(&g_lock); + if (!ready) return SQLITE_MISUSE; + + tls_opening_server = 1; + int rc = sqlite3_open_v2(path, db, writable ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY, NULL); + tls_opening_server = 0; + if (rc == SQLITE_OK && !writable) { + rc = sqlite3_exec(*db, "PRAGMA query_only=1", NULL, NULL, NULL); + if (rc == SQLITE_OK) rc = sqlite3_set_authorizer(*db, server_authorizer, NULL); + } + if (rc != SQLITE_OK && *db) { + sqlite3_close_v2(*db); + *db = NULL; + } + return rc; +} diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.map b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.map new file mode 100644 index 0000000000..b6518f1c1d --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.map @@ -0,0 +1,6 @@ +{ + global: + JNI_OnLoad; + local: + *; +}; diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c new file mode 100644 index 0000000000..f2efe08d7a --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -0,0 +1,841 @@ +// Host tests of the SQLite debugger's extension (ADFA-7135), run by test.sh against SQLite built +// from the amalgamation as requery builds it (SQLITE_THREADSAFE=2). The extension keeps process +// state and installs once, so the tests share one install and run in order. +// +// Usage: sqlitedbg_test [--write-fixture BIN TSV | --check-fixture BIN TSV] +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sqlite3.h" +#include "sqlitedbg.h" + +static int g_failures; +static int g_checks; + +#define CHECK(cond) \ + do { \ + g_checks++; \ + if (!(cond)) { \ + g_failures++; \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + } \ + } while (0) + +#define CHECK_EQ(a, b) \ + do { \ + long long va_ = (long long)(a), vb_ = (long long)(b); \ + g_checks++; \ + if (va_ != vb_) { \ + g_failures++; \ + fprintf(stderr, "FAIL %s:%d: %s == %s (%lld vs %lld)\n", __FILE__, __LINE__, \ + #a, #b, va_, vb_); \ + } \ + } while (0) + +#define MAX_SQL 64 +#define BUFFER_BYTES 8192 + +static char g_dir[256]; +static char g_db_path[300]; + +static long long tid(void) { return (long long)syscall(SYS_gettid); } + +static void exec_ok(sqlite3 *db, const char *sql) { + char *err = NULL; + int rc = sqlite3_exec(db, sql, NULL, NULL, &err); + if (rc != SQLITE_OK) fprintf(stderr, "exec(%s): %s\n", sql, err ? err : "?"); + sqlite3_free(err); + CHECK_EQ(rc, SQLITE_OK); +} + +static sqlite3 *open_app(const char *path) { + sqlite3 *db = NULL; + int rc = sqlite3_open(path, &db); + CHECK_EQ(rc, SQLITE_OK); + return db; +} + +// Events + +typedef struct ev { + uint32_t kind, flags; + uint64_t seq, conn; + int64_t tid, time_ns, duration_ns; + char sql[MAX_SQL * 4 + 8]; + uint32_t sql_bytes; +} ev; + +typedef struct batch { + ev *events; + size_t count; + uint64_t next, dropped; +} batch; + +static void batch_free(batch *b) { free(b->events); } + +// Reads everything after `after`, checking the layout of each record on the way. +static void read_all(uint64_t after, batch *b) { + size_t cap = 1 << 20; + unsigned char *buf = malloc(cap); + sqlitedbg_read_result r; + sqlitedbg_read_events(after, buf, cap, &r); + CHECK_EQ(r.bytes % 8, 0); + b->events = calloc(r.count + 1, sizeof(ev)); + b->count = r.count; + b->next = r.next; + b->dropped = r.dropped; + size_t off = 0; + uint64_t prev = after; + for (size_t i = 0; i < r.count; i++) { + const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); + CHECK(rec->record_bytes >= sizeof *rec); + CHECK_EQ(rec->record_bytes % 8, 0); + CHECK(rec->sql_bytes <= MAX_SQL); + CHECK(rec->record_bytes >= sizeof *rec + rec->sql_bytes); + CHECK(rec->seq > prev); + prev = rec->seq; + ev *e = &b->events[i]; + e->kind = rec->kind; + e->flags = rec->flags; + e->seq = rec->seq; + e->conn = rec->connection_id; + e->tid = rec->thread_id; + e->time_ns = rec->time_ns; + e->duration_ns = rec->duration_ns; + e->sql_bytes = rec->sql_bytes; + memcpy(e->sql, (const char *)buf + off + sizeof *rec, rec->sql_bytes); + e->sql[rec->sql_bytes] = 0; + off += rec->record_bytes; + } + CHECK_EQ(off, r.bytes); + free(buf); +} + +static uint64_t cursor_now(void) { + batch b; + read_all(0, &b); + uint64_t n = b.next; + batch_free(&b); + return n; +} + +static int utf8_valid(const char *s, size_t n) { + size_t i = 0; + while (i < n) { + unsigned char c = (unsigned char)s[i]; + size_t len = c < 0x80 ? 1 : (c >> 5) == 6 ? 2 : (c >> 4) == 14 ? 3 : (c >> 3) == 30 ? 4 : 0; + if (!len || i + len > n) return 0; + for (size_t k = 1; k < len; k++) + if (((unsigned char)s[i + k] & 0xC0) != 0x80) return 0; + i += len; + } + return 1; +} + +// Connections + +typedef struct listing { + sqlitedbg_connection c[64]; + char path[64][300]; + size_t n; +} listing; + +static void list_cb(void *context, const sqlitedbg_connection *c) { + listing *l = context; + if (l->n < 64) { + l->c[l->n] = *c; + snprintf(l->path[l->n], sizeof l->path[l->n], "%s", c->path); + l->c[l->n].path = l->path[l->n]; + } + l->n++; +} + +static size_t list_conns(listing *l) { + l->n = 0; + return sqlitedbg_each_connection(list_cb, l); +} + +static const sqlitedbg_connection *find_conn(const listing *l, uint64_t id) { + for (size_t i = 0; i < l->n && i < 64; i++) + if (l->c[i].id == id) return &l->c[i]; + return NULL; +} + +static uint64_t conn_id_of(sqlite3 *db) { + sqlite3_stmt *st; + uint64_t id = 0; + CHECK_EQ(sqlite3_prepare_v2(db, "SELECT sqlitedbg_connection_id()", -1, &st, NULL), SQLITE_OK); + if (sqlite3_step(st) == SQLITE_ROW) id = (uint64_t)sqlite3_column_int64(st, 0); + sqlite3_finalize(st); + return id; +} + +// Tests + +static sqlitedbg_config g_config = {BUFFER_BYTES, MAX_SQL}; +static sqlite3 *g_main; + +static void test_install(void) { + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_MISUSE); + CHECK(srv == NULL); + CHECK_EQ(sqlitedbg_install(sqlite3_auto_extension, &g_config), SQLITE_OK); + sqlitedbg_config other = {1 << 20, 1000}; + CHECK_EQ(sqlitedbg_install(sqlite3_auto_extension, &other), SQLITE_OK); + CHECK_EQ(sqlitedbg_install(NULL, NULL), SQLITE_MISUSE); + // still no app connection: the extension has no SQLite API to call + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_MISUSE); + + listing l; + CHECK_EQ(list_conns(&l), 0); + g_main = open_app(g_db_path); + // a second install registered the entry point once: one connection, one listing, one id + CHECK_EQ(list_conns(&l), 1); + CHECK_EQ(l.c[0].id, 1); + CHECK(strcmp(l.c[0].path, g_db_path) == 0 || strstr(l.c[0].path, "app.db") != NULL); + CHECK_EQ(l.c[0].read_only, 0); + CHECK_EQ(l.c[0].closing, 0); + CHECK_EQ(l.c[0].open_thread_id, tid()); + CHECK(l.c[0].opened_at_ns > 0); + CHECK_EQ(conn_id_of(g_main), 1); + // the second config was ignored: the 64-byte limit still applies + uint64_t cur = cursor_now(); + char sql[200]; + snprintf(sql, sizeof sql, "SELECT '%0100d'", 0); + exec_ok(g_main, sql); + batch b; + read_all(cur, &b); + CHECK_EQ(b.count, 2); + CHECK(b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + batch_free(&b); +} + +static void test_events(void) { + exec_ok(g_main, "CREATE TABLE t(a)"); + exec_ok(g_main, "CREATE TABLE log(a)"); + exec_ok(g_main, "CREATE TRIGGER trg AFTER INSERT ON t BEGIN INSERT INTO log VALUES(new.a); END"); + uint64_t cur = cursor_now(); + + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO t VALUES(?)", -1, &st, NULL), SQLITE_OK); + sqlite3_bind_int(st, 1, 42); + CHECK_EQ(sqlite3_step(st), SQLITE_DONE); + sqlite3_finalize(st); + + batch b; + read_all(cur, &b); + // the insert, the trigger it fires (its header, then its one step), then the insert's profile + CHECK_EQ(b.count, 4); + CHECK_EQ(b.events[0].kind, SQLITEDBG_EVENT_STATEMENT); + CHECK(strcmp(b.events[0].sql, "INSERT INTO t VALUES(?)") == 0); + CHECK_EQ(b.events[0].duration_ns, -1); + CHECK_EQ(b.events[0].flags, 0); + CHECK_EQ(b.events[1].kind, SQLITEDBG_EVENT_STATEMENT); + CHECK(strcmp(b.events[1].sql, "-- TRIGGER trg") == 0); + CHECK_EQ(b.events[2].kind, SQLITEDBG_EVENT_STATEMENT); + CHECK(strcmp(b.events[2].sql, "-- INSERT INTO log VALUES(new.a)") == 0); + CHECK_EQ(b.events[3].kind, SQLITEDBG_EVENT_PROFILE); + CHECK(strcmp(b.events[3].sql, "INSERT INTO t VALUES(?)") == 0); + CHECK(b.events[3].duration_ns >= 0); + for (size_t i = 0; i < b.count; i++) { + CHECK_EQ(b.events[i].conn, 1); + CHECK_EQ(b.events[i].tid, tid()); + CHECK_EQ(b.events[i].seq, cur + 1 + i); + CHECK(b.events[i].time_ns > 0); + } + CHECK_EQ(b.next, cur + 4); + CHECK_EQ(b.dropped, 0); + batch_free(&b); + + // nothing new: the cursor stays + read_all(cur + 4, &b); + CHECK_EQ(b.count, 0); + CHECK_EQ(b.next, cur + 4); + batch_free(&b); + + // one buffer too small for a record returns none and does not split one + sqlitedbg_read_result r; + char tiny[8]; + sqlitedbg_read_events(cur, tiny, sizeof tiny, &r); + CHECK_EQ(r.count, 0); + CHECK_EQ(r.bytes, 0); + CHECK_EQ(r.next, cur); +} + +static void test_expanded(void) { + sqlite3_stmt *st; + uint64_t cur = cursor_now(); + sqlitedbg_set_client_connected(1); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO t VALUES(?)", -1, &st, NULL), SQLITE_OK); + sqlite3_bind_int(st, 1, 7); + CHECK_EQ(sqlite3_step(st), SQLITE_DONE); + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + batch b; + read_all(cur, &b); + CHECK_EQ(b.count, 4); + CHECK(strcmp(b.events[0].sql, "INSERT INTO t VALUES(7)") == 0); + CHECK(b.events[0].flags & SQLITEDBG_EVENT_EXPANDED); + // a trigger's text is not expanded: P is the outer statement + CHECK(strncmp(b.events[1].sql, "--", 2) == 0); + CHECK(strncmp(b.events[2].sql, "--", 2) == 0); + CHECK_EQ(b.events[1].flags & SQLITEDBG_EVENT_EXPANDED, 0); + CHECK_EQ(b.events[2].flags & SQLITEDBG_EVENT_EXPANDED, 0); + CHECK(strcmp(b.events[3].sql, "INSERT INTO t VALUES(7)") == 0); + CHECK(b.events[3].flags & SQLITEDBG_EVENT_EXPANDED); + batch_free(&b); + + // after the client leaves, the bound value is not written in again + cur = cursor_now(); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO t VALUES(?)", -1, &st, NULL), SQLITE_OK); + sqlite3_bind_int(st, 1, 8); + CHECK_EQ(sqlite3_step(st), SQLITE_DONE); + sqlite3_finalize(st); + read_all(cur, &b); + CHECK(strcmp(b.events[0].sql, "INSERT INTO t VALUES(?)") == 0); + CHECK_EQ(b.events[0].flags, 0); + batch_free(&b); + + // A long bound value does not outgrow the limit: expansion is cut like any other text + char big[300]; + memset(big, 'x', sizeof big - 1); + big[sizeof big - 1] = 0; + cur = cursor_now(); + sqlitedbg_set_client_connected(1); + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO t VALUES(?)", -1, &st, NULL), SQLITE_OK); + sqlite3_bind_text(st, 1, big, -1, SQLITE_STATIC); + CHECK_EQ(sqlite3_step(st), SQLITE_DONE); + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + read_all(cur, &b); + CHECK(b.events[0].flags & SQLITEDBG_EVENT_EXPANDED); + CHECK(b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + batch_free(&b); +} + +static void test_truncation(void) { + char sql[256]; + batch b; + uint64_t cur; + + // "SELECT '" is 8 bytes; each euro sign is 3, so byte 64 is the third byte of one + // that starts at 62: the cut must fall back to 62 + size_t n = (size_t)snprintf(sql, sizeof sql, "SELECT '"); + for (int i = 0; i < 25; i++) n += (size_t)snprintf(sql + n, sizeof sql - n, "\xE2\x82\xAC"); + snprintf(sql + n, sizeof sql - n, "'"); + cur = cursor_now(); + exec_ok(g_main, sql); + read_all(cur, &b); + CHECK_EQ(b.count, 2); + for (int i = 0; i < 2; i++) { + CHECK_EQ(b.events[i].sql_bytes, 62); + CHECK(b.events[i].flags & SQLITEDBG_EVENT_TRUNCATED); + CHECK(utf8_valid(b.events[i].sql, b.events[i].sql_bytes)); + } + batch_free(&b); + + // a 4-byte character straddling the limit: 11 bytes of prefix, then 4-byte characters, + // so byte 64 is the second byte of one that starts at 63 + n = (size_t)snprintf(sql, sizeof sql, "SELECT 1 /*"); + for (int i = 0; i < 20; i++) n += (size_t)snprintf(sql + n, sizeof sql - n, "\xF0\x9F\x98\x80"); + snprintf(sql + n, sizeof sql - n, "*/"); + cur = cursor_now(); + exec_ok(g_main, sql); + read_all(cur, &b); + CHECK_EQ(b.count, 2); + CHECK_EQ(b.events[0].sql_bytes, 63); + CHECK(utf8_valid(b.events[0].sql, b.events[0].sql_bytes)); + batch_free(&b); + + // exactly at the limit is whole, one byte over is cut + for (int over = 0; over < 2; over++) { + memset(sql, 0, sizeof sql); + n = (size_t)snprintf(sql, sizeof sql, "SELECT 1 /*"); + while (n < (size_t)(MAX_SQL - 2 + over)) sql[n++] = 'x'; + sql[n++] = '*'; + sql[n++] = '/'; + sql[n] = 0; + CHECK_EQ(strlen(sql), MAX_SQL + over); + cur = cursor_now(); + exec_ok(g_main, sql); + read_all(cur, &b); + CHECK_EQ(b.events[0].sql_bytes, MAX_SQL); + CHECK_EQ((b.events[0].flags & SQLITEDBG_EVENT_TRUNCATED) != 0, over); + batch_free(&b); + } +} + +static void test_burst(void) { + uint64_t cur = cursor_now(); + const int stmts = 2000; + for (int i = 0; i < stmts; i++) exec_ok(g_main, "SELECT 1"); + const uint64_t made = 2 * (uint64_t)stmts; + batch b; + read_all(cur, &b); + CHECK(b.count > 0); + CHECK(b.count < made); + CHECK_EQ(b.dropped, made - b.count); + CHECK_EQ(b.next, cur + made); + CHECK_EQ(b.events[0].seq, cur + made - b.count + 1); + CHECK_EQ(b.events[b.count - 1].seq, cur + made); + for (size_t i = 1; i < b.count; i++) CHECK_EQ(b.events[i].seq, b.events[i - 1].seq + 1); + batch_free(&b); + + // nothing is reported twice + uint64_t next = cur + made; + read_all(next, &b); + CHECK_EQ(b.count, 0); + CHECK_EQ(b.dropped, 0); + batch_free(&b); + + // a cursor from before the start counts everything that left + read_all(0, &b); + CHECK_EQ(b.dropped, b.events[0].seq - 1); + CHECK_EQ(b.dropped + b.count, next); + batch_free(&b); + + // a reader that kept up loses nothing: read after every 10 statements + uint64_t pos = next, lost = 0, got = 0; + for (int round = 0; round < 50; round++) { + for (int i = 0; i < 10; i++) exec_ok(g_main, "SELECT 2"); + read_all(pos, &b); + lost += b.dropped; + got += b.count; + pos = b.next; + batch_free(&b); + } + CHECK_EQ(lost, 0); + CHECK_EQ(got, 50 * 10 * 2); +} + +static void test_close_and_list(void) { + listing l; + size_t before = list_conns(&l); + sqlite3 *c = open_app(g_db_path); + uint64_t id = conn_id_of(c); + CHECK(id > 1); + CHECK_EQ(list_conns(&l), before + 1); + CHECK(find_conn(&l, id) != NULL); + CHECK_EQ(find_conn(&l, id)->closing, 0); + + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(c, "SELECT * FROM t", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + uint64_t cur = cursor_now(); + CHECK_EQ(sqlite3_close(c), SQLITE_BUSY); + // the close event fired, but the connection is still there: listed, marked closing + CHECK_EQ(list_conns(&l), before + 1); + CHECK_EQ(find_conn(&l, id)->closing, 1); + batch b; + read_all(cur, &b); + CHECK_EQ(b.count, 1); + CHECK_EQ(b.events[0].kind, SQLITEDBG_EVENT_CLOSE); + CHECK_EQ(b.events[0].conn, id); + CHECK_EQ(b.events[0].sql_bytes, 0); + batch_free(&b); + + // the app retries once the statement is gone + sqlite3_finalize(st); + CHECK_EQ(list_conns(&l), before + 1); + CHECK_EQ(sqlite3_close(c), SQLITE_OK); + CHECK_EQ(list_conns(&l), before); + CHECK(find_conn(&l, id) == NULL); + + // close_v2 with a statement open leaves a zombie, listed until it is finalized + c = open_app(g_db_path); + uint64_t id2 = conn_id_of(c); + CHECK(id2 > id); + CHECK_EQ(sqlite3_prepare_v2(c, "SELECT * FROM t", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_close_v2(c), SQLITE_OK); + CHECK_EQ(list_conns(&l), before + 1); + CHECK_EQ(find_conn(&l, id2)->closing, 1); + sqlite3_finalize(st); + CHECK_EQ(list_conns(&l), before); + + // ids are never reused + c = open_app(g_db_path); + CHECK(conn_id_of(c) > id2); + CHECK_EQ(sqlite3_close(c), SQLITE_OK); + + // an in-memory database lists with an empty path, a read-only one as read-only + c = open_app(":memory:"); + list_conns(&l); + CHECK(find_conn(&l, conn_id_of(c)) != NULL); + CHECK_EQ(find_conn(&l, conn_id_of(c))->path[0], 0); + CHECK_EQ(sqlite3_close(c), SQLITE_OK); + sqlite3 *ro = NULL; + CHECK_EQ(sqlite3_open_v2(g_db_path, &ro, SQLITE_OPEN_READONLY, NULL), SQLITE_OK); + list_conns(&l); + CHECK_EQ(find_conn(&l, conn_id_of(ro))->read_only, 1); + CHECK_EQ(sqlite3_close(ro), SQLITE_OK); + CHECK_EQ(list_conns(&l), before); +} + +static int step_all(sqlite3 *db, const char *sql) { + sqlite3_stmt *st; + int rc = sqlite3_prepare_v2(db, sql, -1, &st, NULL); + if (rc != SQLITE_OK) return rc; + while ((rc = sqlite3_step(st)) == SQLITE_ROW) {} + sqlite3_finalize(st); + return rc; +} + +static void test_server(void) { + listing l; + size_t before = list_conns(&l); + uint64_t cur = cursor_now(); + sqlite3 *srv = NULL; + + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_OK); + CHECK(srv != NULL); + CHECK_EQ(sqlite3_db_readonly(srv, "main"), 1); + // not listed, and it has no connection id function + CHECK_EQ(list_conns(&l), before); + CHECK(sqlite3_prepare_v2(srv, "SELECT sqlitedbg_connection_id()", -1, &(sqlite3_stmt *){NULL}, NULL) != SQLITE_OK); + + CHECK_EQ(step_all(srv, "SELECT 'server-marker', count(*) FROM t"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "SELECT name FROM sqlite_schema"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "PRAGMA table_info(t)"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "PRAGMA quick_check"), SQLITE_DONE); + // not traced + batch b; + read_all(cur, &b); + CHECK_EQ(b.count, 0); + batch_free(&b); + + // writes are refused, and so are the ways to lift the guard + CHECK_EQ(step_all(srv, "INSERT INTO t VALUES(99)"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "UPDATE t SET a=1"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "DELETE FROM t"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "CREATE TABLE x(a)"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "DROP TABLE t"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "PRAGMA query_only=0"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "PRAGMA user_version=5"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "ATTACH ':memory:' AS m"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "SELECT 'still works'"), SQLITE_DONE); + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(srv, "SELECT count(*) FROM t WHERE a=99", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 0); + sqlite3_finalize(st); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + CHECK_EQ(list_conns(&l), before); + + // a writable server connection writes, to what the app sees, and is still unlisted + CHECK_EQ(sqlitedbg_open_server(g_db_path, 1, &srv), SQLITE_OK); + CHECK_EQ(sqlite3_db_readonly(srv, "main"), 0); + CHECK_EQ(step_all(srv, "INSERT INTO t VALUES(1234)"), SQLITE_DONE); + CHECK_EQ(list_conns(&l), before); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT count(*) FROM t WHERE a=1234", -1, &st, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_step(st), SQLITE_ROW); + CHECK_EQ(sqlite3_column_int(st, 0), 1); + sqlite3_finalize(st); + + // a missing file is not created by a read-only open, and nothing leaks + char missing[320]; + snprintf(missing, sizeof missing, "%s/missing.db", g_dir); + CHECK_EQ(sqlitedbg_open_server(missing, 0, &srv), SQLITE_CANTOPEN); + CHECK(srv == NULL); + CHECK_EQ(sqlitedbg_open_server(missing, 1, &srv), SQLITE_CANTOPEN); + CHECK(srv == NULL); + + // the flag is per thread and per open: an app connection opened after is listed + sqlite3 *app = open_app(":memory:"); + CHECK_EQ(list_conns(&l), before + 1); + CHECK_EQ(sqlite3_close(app), SQLITE_OK); +} + +typedef struct worker { + int index; + atomic_int *stop; + long long stmts, closes; + int failed; +} worker; + +static void *worker_main(void *arg) { + worker *w = arg; + sqlite3 *db = NULL; + if (sqlite3_open(":memory:", &db) != SQLITE_OK) { + w->failed = 1; + return NULL; + } + sqlite3_stmt *st; + sqlite3_exec(db, "CREATE TABLE w(a, b)", NULL, NULL, NULL); + w->stmts++; + long long n = 0; + while (!atomic_load(w->stop)) { + if (sqlite3_prepare_v2(db, "INSERT INTO w VALUES(?, ?)", -1, &st, NULL) != SQLITE_OK) { + w->failed = 1; + break; + } + sqlite3_bind_int64(st, 1, n); + sqlite3_bind_text(st, 2, "value", -1, SQLITE_STATIC); + if (sqlite3_step(st) != SQLITE_DONE) w->failed = 1; + sqlite3_finalize(st); + w->stmts++; + if (n % 7 == 0) { + if (sqlite3_exec(db, "SELECT count(*) FROM w", NULL, NULL, NULL) != SQLITE_OK) w->failed = 1; + w->stmts++; + } + if (n % 50 == 0) { + // connection churn beside the other threads' statements + sqlite3 *extra = NULL; + if (sqlite3_open(":memory:", &extra) != SQLITE_OK) { + w->failed = 1; + break; + } + if (sqlite3_exec(extra, "SELECT 1", NULL, NULL, NULL) != SQLITE_OK) w->failed = 1; + w->stmts++; + if (sqlite3_close(extra) != SQLITE_OK) w->failed = 1; + w->closes++; + } + n++; + } + if (sqlite3_close(db) != SQLITE_OK) w->failed = 1; + w->closes++; + return NULL; +} + +typedef struct reader { + atomic_int *stop; + int failed; + long long reads; +} reader; + +static void list_noop(void *context, const sqlitedbg_connection *c) { + (void)context; + if (c->id == 0 || !c->path) *(int *)context = 1; +} + +static void *reader_main(void *arg) { + reader *r = arg; + static unsigned char buf[2048]; + uint64_t after = 0; + while (!atomic_load(r->stop)) { + sqlitedbg_read_result res; + sqlitedbg_read_events(after, buf, sizeof buf, &res); + size_t off = 0; + uint64_t prev = after; + for (size_t i = 0; i < res.count; i++) { + const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); + if (rec->seq <= prev || rec->record_bytes % 8 || rec->kind < 1 || rec->kind > 3 || + rec->record_bytes < sizeof *rec + rec->sql_bytes) + r->failed = 1; + prev = rec->seq; + off += rec->record_bytes; + } + if (off != res.bytes) r->failed = 1; + after = res.next; + int bad = 0; + sqlitedbg_each_connection(list_noop, &bad); + if (bad) r->failed = 1; + sqlitedbg_set_client_connected(r->reads++ % 3 == 0); + } + sqlitedbg_set_client_connected(0); + return NULL; +} + +static void test_threads(void) { + listing l; + size_t before = list_conns(&l); + uint64_t cur = cursor_now(); + enum { N = 8 }; + pthread_t th[N], rt; + worker w[N]; + reader rd; + atomic_int stop = 0; + memset(w, 0, sizeof w); + memset(&rd, 0, sizeof rd); + rd.stop = &stop; + pthread_create(&rt, NULL, reader_main, &rd); + for (int i = 0; i < N; i++) { + w[i].index = i; + w[i].stop = &stop; + pthread_create(&th[i], NULL, worker_main, &w[i]); + } + struct timespec two = {2, 0}; + nanosleep(&two, NULL); + atomic_store(&stop, 1); + for (int i = 0; i < N; i++) pthread_join(th[i], NULL); + pthread_join(rt, NULL); + + long long stmts = 0, closes = 0; + for (int i = 0; i < N; i++) { + CHECK_EQ(w[i].failed, 0); + stmts += w[i].stmts; + closes += w[i].closes; + } + CHECK_EQ(rd.failed, 0); + CHECK(stmts > 1000); + // every thread's connections are gone, and every event made was numbered + CHECK_EQ(list_conns(&l), before); + batch b; + read_all(0, &b); + CHECK_EQ(b.next - cur, 2 * (uint64_t)stmts + (uint64_t)closes); + batch_free(&b); + printf(" threads: %lld statements, %lld closes, %lld reads\n", stmts, closes, rd.reads); +} + +// Fixture for EventDecoder's JVM test: a known run, as bytes plus a table of what they hold. + +static void write_tsv_row(FILE *f, const sqlitedbg_event_record *r, const char *sql) { + fprintf(f, "%llu\t%u\t%llu\t%lld\t%lld\t%lld\t%u\t%.*s\n", (unsigned long long)r->seq, r->kind, + (unsigned long long)r->connection_id, (long long)r->thread_id, (long long)r->time_ns, + (long long)r->duration_ns, r->flags, (int)r->sql_bytes, sql); +} + +static void run_fixture_scenario(void) { + char sql[256]; + exec_ok(g_main, "CREATE TABLE fx(a)"); + sqlite3_stmt *st; + CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO fx VALUES(?)", -1, &st, NULL), SQLITE_OK); + sqlite3_bind_int(st, 1, 5); + sqlite3_step(st); + sqlite3_reset(st); + sqlitedbg_set_client_connected(1); + sqlite3_bind_int(st, 1, 6); + sqlite3_step(st); + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + exec_ok(g_main, "SELECT 'h\xC3\xA9llo \xE2\x82\xAC \xF0\x9F\x98\x80'"); + exec_ok(g_main, "CREATE TABLE fxlog(a)"); + exec_ok(g_main, "CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VALUES(new.a); END"); + exec_ok(g_main, "INSERT INTO fx VALUES(1)"); + size_t n = (size_t)snprintf(sql, sizeof sql, "SELECT '"); + for (int i = 0; i < 25; i++) n += (size_t)snprintf(sql + n, sizeof sql - n, "\xE2\x82\xAC"); + snprintf(sql + n, sizeof sql - n, "'"); + exec_ok(g_main, sql); + sqlite3 *c = open_app(":memory:"); + exec_ok(c, "SELECT 1"); + CHECK_EQ(sqlite3_close(c), SQLITE_OK); +} + +static unsigned char *slurp(const char *path, size_t *n) { + FILE *f = fopen(path, "rb"); + if (!f) { + perror(path); + return NULL; + } + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + unsigned char *buf = malloc((size_t)len + 1); + if (fread(buf, 1, (size_t)len, f) != (size_t)len) len = 0; + buf[len] = 0; + fclose(f); + *n = (size_t)len; + return buf; +} + +// Walks records in bin and rewrites them as the table; used both to write and to check the fixture. +static int bin_to_tsv(const unsigned char *bin, size_t n, char **out) { + size_t cap = 1 << 16; + char *s = malloc(cap); + FILE *f = fmemopen(s, cap, "w"); + size_t off = 0; + int ok = 1; + while (off < n) { + const sqlitedbg_event_record *r = (const sqlitedbg_event_record *)(const void *)(bin + off); + if (off + sizeof *r > n || r->record_bytes % 8 || off + r->record_bytes > n || + r->record_bytes < sizeof *r + r->sql_bytes) { + ok = 0; + break; + } + write_tsv_row(f, r, (const char *)bin + off + sizeof *r); + off += r->record_bytes; + } + fclose(f); + *out = s; + return ok; +} + +static void write_fixture(const char *bin_path, const char *tsv_path) { + uint64_t cur = cursor_now(); + run_fixture_scenario(); + size_t cap = 1 << 16; + unsigned char *buf = malloc(cap); + sqlitedbg_read_result r; + sqlitedbg_read_events(cur, buf, cap, &r); + CHECK_EQ(r.dropped, 0); + CHECK(r.count > 10); + FILE *f = fopen(bin_path, "wb"); + CHECK(f != NULL); + if (f) { + fwrite(buf, 1, r.bytes, f); + fclose(f); + } + char *tsv; + CHECK(bin_to_tsv(buf, r.bytes, &tsv)); + f = fopen(tsv_path, "wb"); + CHECK(f != NULL); + if (f) { + fputs(tsv, f); + fclose(f); + } + free(tsv); + free(buf); +} + +// The committed fixture still has the layout of the header: its table is what its bytes hold +static void check_fixture(const char *bin_path, const char *tsv_path) { + size_t bn, tn; + unsigned char *bin = slurp(bin_path, &bn); + unsigned char *tsv = slurp(tsv_path, &tn); + CHECK(bin && tsv); + if (!bin || !tsv) return; + char *again; + CHECK(bin_to_tsv(bin, bn, &again)); + CHECK(strcmp(again, (char *)tsv) == 0); + free(again); + free(bin); + free(tsv); +} + +int main(int argc, char **argv) { + snprintf(g_dir, sizeof g_dir, "/tmp/sqlitedbg-test-XXXXXX"); + if (!mkdtemp(g_dir)) { + perror("mkdtemp"); + return 2; + } + snprintf(g_db_path, sizeof g_db_path, "%s/app.db", g_dir); + + if (argc == 4 && strcmp(argv[1], "--check-fixture") == 0) { + check_fixture(argv[2], argv[3]); + } else { + printf("# install\n"); + test_install(); + printf("# events\n"); + test_events(); + test_expanded(); + printf("# truncation\n"); + test_truncation(); + printf("# burst\n"); + test_burst(); + printf("# close and list\n"); + test_close_and_list(); + printf("# server connections\n"); + test_server(); + printf("# threads\n"); + test_threads(); + if (argc == 4 && strcmp(argv[1], "--write-fixture") == 0) write_fixture(argv[2], argv[3]); + sqlite3_close(g_main); + } + + char cmd[300]; + snprintf(cmd, sizeof cmd, "rm -rf '%s'", g_dir); + if (system(cmd) != 0) fprintf(stderr, "could not remove %s\n", g_dir); + printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.bin new file mode 100644 index 0000000000000000000000000000000000000000..0441b915006ad5921acdf11c603ea101862533ed GIT binary patch literal 1792 zcmb`IIY|tT3Cpsjg5_kjkUhFvlFvfUKDZ2n=CVLzW2|Yx3gi!SRPm+SqQy+#($Rsd&Wxd zHD_w&wfxg;#u#+oh;ZwI>uyg_@WF(m*NHQXg~9T{W(eMXu*2YKo)UC7S}F9oc&Kld z;EkjtFH>JR_yziKwI5sr1beypOg%o4%iTsBfO&U5-hf(ucXB zd39-h3j}ZIb;6?WH$2q0NbtseleY6keNhn9?&n{<+$y+CQjqS&l{2{Lxtfq$R-??L~2gXp>2EiHcv~wyX$9fgW z^cuIp=)iPs_Pw=9@T6W>^0Y(eJ N_K5YKM|*q(eF53lvcUiV literal 0 HcmV?d00001 diff --git a/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv new file mode 100644 index 0000000000..4405849603 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/resources/org/appdevforall/sqlitedebugger/engine/events.tsv @@ -0,0 +1,21 @@ +426616 1 1 10289 1794545527187098386 -1 0 CREATE TABLE fx(a) +426617 2 1 10289 1794545527188573325 1000000 0 CREATE TABLE fx(a) +426618 1 1 10289 1794545527188596333 -1 0 INSERT INTO fx VALUES(?) +426619 2 1 10289 1794545527189296629 1000000 0 INSERT INTO fx VALUES(?) +426620 1 1 10289 1794545527189303467 -1 2 INSERT INTO fx VALUES(6) +426621 2 1 10289 1794545527190447975 1000000 2 INSERT INTO fx VALUES(6) +426622 1 1 10289 1794545527190472305 -1 0 SELECT 'héllo € 😀' +426623 2 1 10289 1794545527190474851 0 0 SELECT 'héllo € 😀' +426624 1 1 10289 1794545527190557276 -1 0 CREATE TABLE fxlog(a) +426625 2 1 10289 1794545527191607925 1000000 0 CREATE TABLE fxlog(a) +426626 1 1 10289 1794545527191694489 -1 1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +426627 2 1 10289 1794545527192759261 1000000 1 CREATE TRIGGER fxt AFTER INSERT ON fx BEGIN INSERT INTO fxlog VA +426628 1 1 10289 1794545527192791863 -1 0 INSERT INTO fx VALUES(1) +426629 1 1 10289 1794545527192835643 -1 0 -- TRIGGER fxt +426630 1 1 10289 1794545527192836209 -1 0 -- INSERT INTO fxlog VALUES(new.a) +426631 2 1 10289 1794545527193623084 1000000 0 INSERT INTO fx VALUES(1) +426632 1 1 10289 1794545527193646993 -1 1 SELECT '€€€€€€€€€€€€€€€€€€ +426633 2 1 10289 1794545527193649365 0 1 SELECT '€€€€€€€€€€€€€€€€€€ +426634 1 3616 10289 1794545527193782816 -1 0 SELECT 1 +426635 2 3616 10289 1794545527193784200 0 0 SELECT 1 +426636 3 3616 10289 1794545527193785154 -1 0 diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh new file mode 100755 index 0000000000..18b42811af --- /dev/null +++ b/subprojects/sqlite-debugger/test.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Host tests of the SQLite debugger's extension (ADFA-7135): src/test/c/sqlitedbg_test.c, with +# SQLite built from the amalgamation as requery builds it (SQLITE_THREADSAFE=2), under +# AddressSanitizer + UBSan and then ThreadSanitizer. +# Usage: test.sh [--update-fixture] [AMALGAMATION_TARBALL] (without the tarball, downloads it) +# --update-fixture rewrites src/test/resources/.../events.bin and events.tsv, which the JVM test +# of EventDecoder reads; without it the committed pair is checked against the +# current record layout instead. +# Needs gcc, curl, tar and sha256sum. +set -euo pipefail +HERE=$(cd "$(dirname "$0")" && pwd) + +# SQLite 3.49.1, the version of the vendored headers in ../sqlite-js/upstream/libs (the script +# checks they are the same). sqlite.org's own zip (sqlite-amalgamation-3490100.zip) is the usual +# source; this is the same amalgamation as bundled in the sqlean.py sdist, which PyPI serves where +# sqlite.org is not reachable. sqlean appends its own init code after SQLite's last line, which is +# cut off below. SHA256 is of the tarball, SQLITE3_C_SHA256 of the cut sqlite3.c. +VERSION=3.49.1 +SHA256=210d89989226b988d7d6391f837387d3b81e8cd608c997e0bd37826e395970e7 +URL=https://files.pythonhosted.org/packages/67/eb/ac95fab0bc4658124b4ec8fbc31fc494165ab4544606ae91b9a489907dad/sqlean_py-3.49.1.tar.gz +SQLITE3_C_SHA256=ff80c36ef1bb44eb357c7ff1d15be77540d41c28fb671088215a6cd12785c5d3 +SQLITE_SOURCE_ID="2025-02-18 13:38:58 873d4e274b4988d260ba8354a9718324a1c26187a4ab4c1cc0227c03d0f10e70" + +UPDATE=0 +if [ "${1:-}" = "--update-fixture" ]; then UPDATE=1; shift; fi + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +TARBALL=${1:-$WORK/sqlite-$VERSION.tar.gz} +[ -f "$TARBALL" ] || curl -fsSL -o "$TARBALL" "$URL" +echo "$SHA256 $TARBALL" | sha256sum -c --quiet - +mkdir "$WORK/src" +tar -xzf "$TARBALL" -C "$WORK/src" --strip-components=1 +AMAL=$WORK/src/sqlite +sed -i '/^\/\*.* End of sqlite3\.c \*/q' "$AMAL/sqlite3.c" +echo "$SQLITE3_C_SHA256 $AMAL/sqlite3.c" | sha256sum -c --quiet - +grep -q "SQLITE_SOURCE_ID \"$SQLITE_SOURCE_ID\"" "$AMAL/sqlite3.h" || { echo "unexpected SQLite source id"; exit 1; } + +LIBS=$HERE/../sqlite-js/upstream/libs +for h in sqlite3.h sqlite3ext.h; do + cmp -s "$AMAL/$h" "$LIBS/$h" || { echo "$h differs from $LIBS/$h"; exit 1; } +done + +build () { "$@" >"$WORK/build.log" 2>&1 || { cat "$WORK/build.log"; exit 1; }; } +CPP=$HERE/src/main/cpp +DEFS=(-DSQLITE_CORE -DSQLITE_THREADSAFE=2 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0) + +run_with () { + local name=$1 sanitize=$2 + echo "# $name" + mkdir "$WORK/$name" + build gcc -O1 -g -w -fsanitize="$sanitize" "${DEFS[@]}" -I"$AMAL" -c "$AMAL/sqlite3.c" -o "$WORK/$name/sqlite3.o" + build gcc -O1 -g -Wall -Wextra -Werror -fsanitize="$sanitize" -fno-sanitize-recover=all "${DEFS[@]}" \ + -I"$AMAL" -I"$CPP" "$CPP/sqlitedbg.c" "$HERE/src/test/c/sqlitedbg_test.c" "$WORK/$name/sqlite3.o" \ + -o "$WORK/$name/test" -lpthread -ldl -lm + TSAN_OPTIONS=halt_on_error=1 "$WORK/$name/test" ${3:+"${@:3}"} +} + +RES=$HERE/src/test/resources/org/appdevforall/sqlitedebugger/engine +if [ "$UPDATE" = 1 ]; then + mkdir -p "$RES" + run_with asan-ubsan address,undefined --write-fixture "$RES/events.bin" "$RES/events.tsv" +else + run_with asan-ubsan address,undefined + "$WORK/asan-ubsan/test" --check-fixture "$RES/events.bin" "$RES/events.tsv" +fi +run_with tsan thread From ff0312f85b8121d9e1ac867b279b33db63e4de25 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:00:25 +0000 Subject: [PATCH 029/203] ADFA-7135 Add the JNI layer and NativeDebugEngine sqlitedbg_jni.c registers NativeBridge's natives from JNI_OnLoad (the version script exports nothing else) and reaches SQLite only through the extension's api table. ServerConnection.query steps the statement in C, binds args by type, applies QueryLimits, and stops at the deadline through a progress handler on the server connection. EventDecoder mirrors the exported record layout and is tested against the fixture the host C test writes. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- .../sqlite-debugger/consumer-rules.pro | 3 + .../src/main/cpp/CMakeLists.txt | 5 +- .../src/main/cpp/sqlitedbg_jni.c | 420 ++++++++++++++++++ .../sqlitedebugger/engine/EventDecoder.kt | 69 +++ .../sqlitedebugger/engine/NativeBridge.kt | 52 +++ .../engine/NativeDebugEngine.kt | 127 ++++++ .../sqlitedebugger/engine/EventDecoderTest.kt | 92 ++++ 7 files changed, 767 insertions(+), 1 deletion(-) create mode 100644 subprojects/sqlite-debugger/consumer-rules.pro create mode 100644 subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c create mode 100644 subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt create mode 100644 subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt create mode 100644 subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt create mode 100644 subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt diff --git a/subprojects/sqlite-debugger/consumer-rules.pro b/subprojects/sqlite-debugger/consumer-rules.pro new file mode 100644 index 0000000000..4ba638bc89 --- /dev/null +++ b/subprojects/sqlite-debugger/consumer-rules.pro @@ -0,0 +1,3 @@ +# JNI_OnLoad registers these by name, and the native code builds this exception +-keep class org.appdevforall.sqlitedebugger.engine.NativeBridge { *; } +-keep class org.appdevforall.sqlitedebugger.engine.DebugEngineException { (int, java.lang.String); } diff --git a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt index bbe9393af9..779767a2bb 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt +++ b/subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt @@ -7,10 +7,13 @@ project(sqlitedbg C) set(SQLITE_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/../../../../sqlite-js/upstream/libs) add_library(sqlitedbg SHARED - sqlitedbg.c) + sqlitedbg.c + sqlitedbg_jni.c) target_include_directories(sqlitedbg PRIVATE ${SQLITE_HEADERS} ${CMAKE_CURRENT_SOURCE_DIR}) target_compile_options(sqlitedbg PRIVATE -Wall -Wextra -fvisibility=hidden) +# dlopen/dlsym to find sqlite3_auto_extension in requery's libsqlite3x.so +target_link_libraries(sqlitedbg dl) # Only JNI_OnLoad is exported, so sqlite3_api and our other symbols cannot bind to another library's. target_link_options(sqlitedbg PRIVATE -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/sqlitedbg.map diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c new file mode 100644 index 0000000000..d5fede7078 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -0,0 +1,420 @@ +// JNI layer of the SQLite debugger (ADFA-7135): NativeBridge.kt over sqlitedbg.h. Like the +// extension it calls SQLite only through the api table (sqlite3ext.h), which sqlitedbg.c saves. +// Every handle here comes from sqlitedbg_open_server, which refuses to open before that. + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include +#include +#include +#include +#include + +#include "sqlite3ext.h" +#include "sqlitedbg.h" + +SQLITE_EXTENSION_INIT3 + +#define BRIDGE_CLASS "org/appdevforall/sqlitedebugger/engine/NativeBridge" +#define EXCEPTION_CLASS "org/appdevforall/sqlitedebugger/engine/DebugEngineException" + +static jclass g_object, g_string, g_array_list, g_long, g_double, g_exception; +static jmethodID g_string_from_bytes, g_list_init, g_list_add, g_long_value_of, g_double_value_of, g_exception_init; +static jstring g_utf8_name; + +static jclass global_class(JNIEnv *env, const char *name) { + jclass local = (*env)->FindClass(env, name); + if (!local) return NULL; + jclass global = (jclass)(*env)->NewGlobalRef(env, local); + (*env)->DeleteLocalRef(env, local); + return global; +} + +// A Java String from UTF-8 bytes. NewStringUTF takes modified UTF-8, which differs for NUL and for +// characters outside the BMP, and SQLite text can hold both. +static jstring utf8_string(JNIEnv *env, const char *bytes, int n) { + jbyteArray array = (*env)->NewByteArray(env, n); + if (!array) return NULL; + (*env)->SetByteArrayRegion(env, array, 0, n, (const jbyte *)bytes); + jstring s = (jstring)(*env)->NewObject(env, g_string, g_string_from_bytes, array, g_utf8_name); + (*env)->DeleteLocalRef(env, array); + return s; +} + +static void throw_engine(JNIEnv *env, int code, const char *message) { + if ((*env)->ExceptionCheck(env)) return; + jstring text = utf8_string(env, message, (int)strlen(message)); + if (!text) return; + jobject ex = (*env)->NewObject(env, g_exception, g_exception_init, (jint)code, text); + if (ex) (*env)->Throw(env, (jthrowable)ex); +} + +static int64_t now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +// install + +static jint bridge_install(JNIEnv *env, jclass cls) { + (void)env; + (void)cls; + // requery's library is already loaded by System.loadLibrary; NOLOAD only finds it, and its + // sqlite3_ functions are all exported, so no separate handle to SQLite is needed + void *lib = dlopen("libsqlite3x.so", RTLD_NOW | RTLD_NOLOAD); + if (!lib) return -1; + sqlitedbg_auto_extension_fn auto_extension = (sqlitedbg_auto_extension_fn)dlsym(lib, "sqlite3_auto_extension"); + int rc = auto_extension ? sqlitedbg_install(auto_extension, NULL) : -1; + dlclose(lib); + return rc; +} + +// connections + +typedef struct conn_list { + jlong *meta; + char **paths; + size_t n, cap; + int oom; +} conn_list; + +static void collect_connection(void *context, const sqlitedbg_connection *c) { + conn_list *l = (conn_list *)context; + if (l->oom) return; + if (l->n == l->cap) { + size_t cap = l->cap ? l->cap * 2 : 16; + jlong *meta = realloc(l->meta, cap * 5 * sizeof(jlong)); + if (meta) l->meta = meta; + char **paths = realloc(l->paths, cap * sizeof(char *)); + if (paths) l->paths = paths; + if (!meta || !paths) { + l->oom = 1; + return; + } + l->cap = cap; + } + char *path = strdup(c->path); + if (!path) { + l->oom = 1; + return; + } + jlong *m = l->meta + l->n * 5; + m[0] = (jlong)c->id; + m[1] = c->read_only; + m[2] = c->closing; + m[3] = (jlong)c->opened_at_ns; + m[4] = (jlong)c->open_thread_id; + l->paths[l->n++] = path; +} + +static jobjectArray bridge_connections(JNIEnv *env, jclass cls) { + (void)cls; + conn_list l = {0}; + sqlitedbg_each_connection(collect_connection, &l); + jobjectArray result = NULL; + if (l.oom) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + goto done; + } + jlongArray meta = (*env)->NewLongArray(env, (jsize)(l.n * 5)); + jobjectArray paths = meta ? (*env)->NewObjectArray(env, (jsize)l.n, g_string, NULL) : NULL; + if (!paths) goto done; + (*env)->SetLongArrayRegion(env, meta, 0, (jsize)(l.n * 5), l.meta ? l.meta : (jlong[]){0}); + for (size_t i = 0; i < l.n; i++) { + jstring s = utf8_string(env, l.paths[i], (int)strlen(l.paths[i])); + if (!s) goto done; + (*env)->SetObjectArrayElement(env, paths, (jsize)i, s); + (*env)->DeleteLocalRef(env, s); + } + result = (*env)->NewObjectArray(env, 2, g_object, NULL); + if (result) { + (*env)->SetObjectArrayElement(env, result, 0, meta); + (*env)->SetObjectArrayElement(env, result, 1, paths); + } +done: + for (size_t i = 0; i < l.n; i++) free(l.paths[i]); + free(l.paths); + free(l.meta); + return result; +} + +// events + +static void bridge_read_events(JNIEnv *env, jclass cls, jlong after, jbyteArray buf, jlongArray out) { + (void)cls; + jsize cap = (*env)->GetArrayLength(env, buf); + void *tmp = malloc((size_t)cap); + if (!tmp) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return; + } + sqlitedbg_read_result r; + sqlitedbg_read_events((uint64_t)after, tmp, (size_t)cap, &r); + (*env)->SetByteArrayRegion(env, buf, 0, (jsize)r.bytes, (const jbyte *)tmp); + free(tmp); + jlong values[3] = {(jlong)r.next, (jlong)r.dropped, (jlong)r.bytes}; + (*env)->SetLongArrayRegion(env, out, 0, 3, values); +} + +static void bridge_set_client_connected(JNIEnv *env, jclass cls, jboolean connected) { + (void)env; + (void)cls; + sqlitedbg_set_client_connected(connected ? 1 : 0); +} + +// server connections + +static jlong bridge_open_server(JNIEnv *env, jclass cls, jbyteArray path, jboolean writable) { + (void)cls; + jsize n = (*env)->GetArrayLength(env, path); + char *c_path = malloc((size_t)n + 1); + if (!c_path) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return 0; + } + (*env)->GetByteArrayRegion(env, path, 0, n, (jbyte *)c_path); + c_path[n] = 0; + sqlite3 *db = NULL; + int rc = sqlitedbg_open_server(c_path, writable ? 1 : 0, &db); + free(c_path); + if (rc != SQLITE_OK) { + throw_engine(env, rc, rc == SQLITE_MISUSE ? "no app connection has opened yet" : sqlite3_errstr(rc)); + return 0; + } + return (jlong)(intptr_t)db; +} + +static void bridge_close(JNIEnv *env, jclass cls, jlong handle) { + (void)env; + (void)cls; + sqlite3_close_v2((sqlite3 *)(intptr_t)handle); +} + +typedef struct deadline { + int64_t at_ms; + int hit; +} deadline; + +static int progress_cb(void *p) { + deadline *d = (deadline *)p; + if (now_ms() < d->at_ms) return 0; + d->hit = 1; + return 1; +} + +// Binds args[i] to parameter i + 1. Returns SQLITE_OK or a code with *message set. +static int bind_args(JNIEnv *env, sqlite3 *db, sqlite3_stmt *st, jobjectArray args, const char **message) { + jsize count = (*env)->GetArrayLength(env, args); + for (jsize i = 0; i < count; i++) { + jobject v = (*env)->GetObjectArrayElement(env, args, i); + int rc; + if (!v) { + rc = sqlite3_bind_null(st, i + 1); + } else if ((*env)->IsInstanceOf(env, v, g_long)) { + jmethodID m = (*env)->GetMethodID(env, g_long, "longValue", "()J"); + rc = sqlite3_bind_int64(st, i + 1, (sqlite3_int64)(*env)->CallLongMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_double)) { + jmethodID m = (*env)->GetMethodID(env, g_double, "doubleValue", "()D"); + rc = sqlite3_bind_double(st, i + 1, (*env)->CallDoubleMethod(env, v, m)); + } else if ((*env)->IsInstanceOf(env, v, g_string)) { + jsize len = (*env)->GetStringLength(env, (jstring)v); + const jchar *chars = (*env)->GetStringChars(env, (jstring)v, NULL); + if (!chars) return SQLITE_NOMEM; + rc = sqlite3_bind_text16(st, i + 1, chars, len * 2, SQLITE_TRANSIENT); + (*env)->ReleaseStringChars(env, (jstring)v, chars); + } else { + jclass bytes_class = (*env)->FindClass(env, "[B"); + int is_bytes = bytes_class && (*env)->IsInstanceOf(env, v, bytes_class); + if (bytes_class) (*env)->DeleteLocalRef(env, bytes_class); + if (!is_bytes) { + *message = "unsupported argument type"; + return SQLITE_MISUSE; + } + jsize len = (*env)->GetArrayLength(env, (jbyteArray)v); + void *copy = malloc(len ? (size_t)len : 1); + if (!copy) return SQLITE_NOMEM; + (*env)->GetByteArrayRegion(env, (jbyteArray)v, 0, len, (jbyte *)copy); + rc = sqlite3_bind_blob64(st, i + 1, copy, (sqlite3_uint64)len, SQLITE_TRANSIENT); + free(copy); + } + if (v) (*env)->DeleteLocalRef(env, v); + if (rc != SQLITE_OK) { + *message = sqlite3_errmsg(db); + return rc; + } + if ((*env)->ExceptionCheck(env)) return SQLITE_ERROR; + } + return SQLITE_OK; +} + +// A UTF-8 prefix of at most max bytes ending on a character boundary. +static int utf8_prefix(const unsigned char *s, int len, int max) { + if (len <= max) return len; + while (max > 0 && (s[max] & 0xC0) == 0x80) max--; + return max; +} + +// One cell as a Java object, or NULL for SQL NULL (or on failure, with an exception pending). +static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, jint max_blob, int *truncated) { + switch (sqlite3_column_type(st, col)) { + case SQLITE_INTEGER: + return (*env)->CallStaticObjectMethod(env, g_long, g_long_value_of, (jlong)sqlite3_column_int64(st, col)); + case SQLITE_FLOAT: + return (*env)->CallStaticObjectMethod(env, g_double, g_double_value_of, (jdouble)sqlite3_column_double(st, col)); + case SQLITE_TEXT: { + const unsigned char *text = sqlite3_column_text(st, col); + int len = sqlite3_column_bytes(st, col); + int keep = utf8_prefix(text, len, max_text); + if (keep < len) (*truncated)++; + return utf8_string(env, (const char *)text, keep); + } + case SQLITE_BLOB: { + const void *blob = sqlite3_column_blob(st, col); + int len = sqlite3_column_bytes(st, col); + int keep = len > max_blob ? max_blob : len; + if (keep < len) (*truncated)++; + jbyteArray array = (*env)->NewByteArray(env, keep); + if (array && keep > 0) (*env)->SetByteArrayRegion(env, array, 0, keep, (const jbyte *)blob); + return array; + } + default: + return NULL; + } +} + +static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong offset, + jint max_rows, jint max_text, jint max_blob, jlong deadline_ms) { + (void)cls; + sqlite3 *db = (sqlite3 *)(intptr_t)handle; + sqlite3_stmt *st = NULL; + jobjectArray result = NULL; + deadline dl = {(int64_t)deadline_ms, 0}; + int handler_set = 0; + const char *message = NULL; + int rc; + + if (now_ms() >= dl.at_ms) { + throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); + return NULL; + } + jsize sql_len = (*env)->GetStringLength(env, sql); + const jchar *sql_chars = (*env)->GetStringChars(env, sql, NULL); + if (!sql_chars) return NULL; + rc = sqlite3_prepare16_v2(db, sql_chars, sql_len * 2, &st, NULL); + (*env)->ReleaseStringChars(env, sql, sql_chars); + if (rc != SQLITE_OK) { + throw_engine(env, rc, sqlite3_errmsg(db)); + return NULL; + } + + // SQLite checks the handler every 1000 virtual machine steps and stops the statement when it + // returns non-zero; it is cleared before this returns, so it never outlives `dl`. + sqlite3_progress_handler(db, 1000, progress_cb, &dl); + handler_set = 1; + + rc = st ? bind_args(env, db, st, args, &message) : SQLITE_OK; + if (rc != SQLITE_OK) { + if (!(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); + goto done; + } + + int ncols = st ? sqlite3_column_count(st) : 0; + jobjectArray names = (*env)->NewObjectArray(env, ncols, g_string, NULL); + jobject rows = names ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; + if (!rows) goto done; + for (int c = 0; c < ncols; c++) { + const char *name = sqlite3_column_name(st, c); + jstring s = utf8_string(env, name ? name : "", name ? (int)strlen(name) : 0); + if (!s) goto done; + (*env)->SetObjectArrayElement(env, names, c, s); + (*env)->DeleteLocalRef(env, s); + } + + int truncated = 0, has_more = 0, row_count = 0; + jlong skipped = 0; + while (st && (rc = sqlite3_step(st)) == SQLITE_ROW) { + if (skipped < offset) { + skipped++; + continue; + } + if (row_count >= max_rows) { + has_more = 1; + break; + } + jobjectArray row = (*env)->NewObjectArray(env, ncols, g_object, NULL); + if (!row) goto done; + for (int c = 0; c < ncols; c++) { + jobject cell = cell_value(env, st, c, max_text, max_blob, &truncated); + if ((*env)->ExceptionCheck(env)) goto done; + if (cell) { + (*env)->SetObjectArrayElement(env, row, c, cell); + (*env)->DeleteLocalRef(env, cell); + } + } + (*env)->CallBooleanMethod(env, rows, g_list_add, row); + (*env)->DeleteLocalRef(env, row); + if ((*env)->ExceptionCheck(env)) goto done; + row_count++; + } + if (st && !has_more && rc != SQLITE_DONE) { + if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); + else throw_engine(env, rc, sqlite3_errmsg(db)); + goto done; + } + + jlongArray counts = (*env)->NewLongArray(env, 2); + result = counts ? (*env)->NewObjectArray(env, 3, g_object, NULL) : NULL; + if (!result) goto done; + jlong values[2] = {truncated, has_more}; + (*env)->SetLongArrayRegion(env, counts, 0, 2, values); + (*env)->SetObjectArrayElement(env, result, 0, names); + (*env)->SetObjectArrayElement(env, result, 1, rows); + (*env)->SetObjectArrayElement(env, result, 2, counts); + +done: + if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); + sqlite3_finalize(st); + return result; +} + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { + (void)reserved; + JNIEnv *env; + if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; + + g_object = global_class(env, "java/lang/Object"); + g_string = global_class(env, "java/lang/String"); + g_array_list = global_class(env, "java/util/ArrayList"); + g_long = global_class(env, "java/lang/Long"); + g_double = global_class(env, "java/lang/Double"); + g_exception = global_class(env, EXCEPTION_CLASS); + jstring utf8 = (*env)->NewStringUTF(env, "UTF-8"); + if (!g_object || !g_string || !g_array_list || !g_long || !g_double || !g_exception || !utf8) return JNI_ERR; + g_utf8_name = (jstring)(*env)->NewGlobalRef(env, utf8); + + g_string_from_bytes = (*env)->GetMethodID(env, g_string, "", "([BLjava/lang/String;)V"); + g_list_init = (*env)->GetMethodID(env, g_array_list, "", "()V"); + g_list_add = (*env)->GetMethodID(env, g_array_list, "add", "(Ljava/lang/Object;)Z"); + g_long_value_of = (*env)->GetStaticMethodID(env, g_long, "valueOf", "(J)Ljava/lang/Long;"); + g_double_value_of = (*env)->GetStaticMethodID(env, g_double, "valueOf", "(D)Ljava/lang/Double;"); + g_exception_init = (*env)->GetMethodID(env, g_exception, "", "(ILjava/lang/String;)V"); + if (!g_string_from_bytes || !g_list_init || !g_list_add || !g_long_value_of || !g_double_value_of || !g_exception_init) + return JNI_ERR; + + static const JNINativeMethod methods[] = { + {"install", "()I", (void *)bridge_install}, + {"connections", "()[Ljava/lang/Object;", (void *)bridge_connections}, + {"readEvents", "(J[B[J)V", (void *)bridge_read_events}, + {"setClientConnected", "(Z)V", (void *)bridge_set_client_connected}, + {"openServer", "([BZ)J", (void *)bridge_open_server}, + {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"close", "(J)V", (void *)bridge_close}, + }; + jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); + if (!bridge || (*env)->RegisterNatives(env, bridge, methods, sizeof methods / sizeof methods[0]) != JNI_OK) + return JNI_ERR; + return JNI_VERSION_1_6; +} diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt new file mode 100644 index 0000000000..73af648598 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/EventDecoder.kt @@ -0,0 +1,69 @@ +package org.appdevforall.sqlitedebugger.engine + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * Decodes the records `sqlitedbg_read_events` copies out. Mirrors `sqlitedbg_event_record` in + * `sqlitedbg.h`: change both together. Little-endian, because the CPU is on every ABI we build. + */ +internal object EventDecoder { + /** `sizeof(sqlitedbg_event_record)`. */ + const val HEADER_BYTES = 56 + + private const val OFFSET_RECORD_BYTES = 0 + private const val OFFSET_KIND = 4 + private const val OFFSET_SEQ = 8 + private const val OFFSET_CONNECTION_ID = 16 + private const val OFFSET_THREAD_ID = 24 + private const val OFFSET_TIME_NS = 32 + private const val OFFSET_DURATION_NS = 40 + private const val OFFSET_FLAGS = 48 + private const val OFFSET_SQL_BYTES = 52 + + private const val FLAG_TRUNCATED = 1 + private const val FLAG_EXPANDED = 2 + + /** + * The records in the first [length] bytes of [bytes]. + * + * @throws IllegalArgumentException if they are not whole, well-formed records. + */ + fun decode( + bytes: ByteArray, + length: Int, + ): List { + require(length in 0..bytes.size) { "length $length outside 0..${bytes.size}" } + val buffer = ByteBuffer.wrap(bytes, 0, length).order(ByteOrder.LITTLE_ENDIAN) + val events = ArrayList() + var offset = 0 + while (offset < length) { + require(length - offset >= HEADER_BYTES) { "record at $offset is cut off by the end of the data" } + val recordBytes = buffer.getInt(offset + OFFSET_RECORD_BYTES) + val sqlBytes = buffer.getInt(offset + OFFSET_SQL_BYTES) + require(sqlBytes >= 0 && recordBytes >= 0 && recordBytes % 8 == 0 && sqlBytes <= recordBytes - HEADER_BYTES) { + "record at $offset has record_bytes=$recordBytes sql_bytes=$sqlBytes" + } + require(recordBytes <= length - offset) { "record at $offset runs past the end of the data" } + val kindValue = buffer.getInt(offset + OFFSET_KIND) + val kind = + EventKind.values().firstOrNull { it.nativeValue == kindValue } + ?: throw IllegalArgumentException("record at $offset has unknown kind $kindValue") + val flags = buffer.getInt(offset + OFFSET_FLAGS) + events += + Event( + seq = buffer.getLong(offset + OFFSET_SEQ), + kind = kind, + connectionId = buffer.getLong(offset + OFFSET_CONNECTION_ID), + threadId = buffer.getLong(offset + OFFSET_THREAD_ID), + timeEpochNanos = buffer.getLong(offset + OFFSET_TIME_NS), + durationNanos = if (kind == EventKind.PROFILE) buffer.getLong(offset + OFFSET_DURATION_NS) else null, + sql = String(bytes, offset + HEADER_BYTES, sqlBytes, Charsets.UTF_8), + truncated = flags and FLAG_TRUNCATED != 0, + expanded = flags and FLAG_EXPANDED != 0, + ) + offset += recordBytes + } + return events + } +} diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt new file mode 100644 index 0000000000..578ac83086 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -0,0 +1,52 @@ +package org.appdevforall.sqlitedebugger.engine + +/** + * The JNI entry points of libsqlitedbg.so, registered by name in its JNI_OnLoad (sqlitedbg_jni.c). + * Signatures there must match these. Only [NativeDebugEngine] calls them. + */ +internal object NativeBridge { + /** Registers the extension with requery's SQLite. 0 (SQLITE_OK) or the SQLite code; -1 if libsqlite3x.so is not loaded. */ + @JvmStatic + external fun install(): Int + + /** `[LongArray, Array]`: 5 longs per connection (id, readOnly, closing, openedAtNs, openThreadId), and the paths. */ + @JvmStatic + external fun connections(): Array + + /** Fills [buf] with records after [after]; [out] gets next, dropped and the bytes written. */ + @JvmStatic + external fun readEvents( + after: Long, + buf: ByteArray, + out: LongArray, + ) + + @JvmStatic + external fun setClientConnected(connected: Boolean) + + /** A handle for [query] and [close]. Throws [DebugEngineException]. */ + @JvmStatic + external fun openServer( + path: ByteArray, + writable: Boolean, + ): Long + + /** + * `[Array, ArrayList>, LongArray]`: the column names, the rows, and + * `{truncatedCells, hasMore}`. Throws [DebugEngineException]. + */ + @JvmStatic + external fun query( + handle: Long, + sql: String, + args: Array, + offset: Long, + maxRows: Int, + maxTextBytes: Int, + maxBlobBytes: Int, + deadlineMillis: Long, + ): Array + + @JvmStatic + external fun close(handle: Long) +} diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt new file mode 100644 index 0000000000..00e95c20d1 --- /dev/null +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -0,0 +1,127 @@ +package org.appdevforall.sqlitedebugger.engine + +/** + * [DebugEngine] over the JNI layer of libsqlitedbg.so. Needs requery's libsqlite3x.so in the process: + * the extension runs inside it, on connections it opens after [install]. Call [install] before + * anything else; the native state is per process, so every instance shares it. + */ +class NativeDebugEngine : DebugEngine { + /** + * Loads requery's SQLite and the debugger's library and registers the extension. Connections + * opened before this are never seen, so call it as early as the process allows. Calling it + * again, on any instance, does nothing. + * + * @throws DebugEngineException if SQLite refuses the extension. + * @throws UnsatisfiedLinkError if a library is missing. + */ + fun install() { + synchronized(lock) { + if (installed) return + System.loadLibrary("sqlite3x") + System.loadLibrary("sqlitedbg") + val rc = NativeBridge.install() + if (rc != 0) { + throw DebugEngineException( + if (rc < 0) DebugEngineException.SQLITE_MISUSE else rc, + if (rc < 0) "libsqlite3x.so is not loaded" else "sqlite3_auto_extension failed with $rc", + ) + } + installed = true + } + } + + override fun connections(): List { + val result = NativeBridge.connections() + + @Suppress("UNCHECKED_CAST") + val paths = result[1] as Array + val meta = result[0] as LongArray + return paths.indices.map { i -> + val m = i * META_PER_CONNECTION + AppConnection( + id = meta[m], + path = paths[i], + readOnly = meta[m + 1] != 0L, + closing = meta[m + 2] != 0L, + openedAtEpochNanos = meta[m + 3], + openThreadId = meta[m + 4], + ) + } + } + + override fun readEvents( + after: Long, + maxBytes: Int, + ): EventBatch { + val buffer = ByteArray(maxBytes.coerceIn(1, MAX_READ_BYTES)) + val out = LongArray(3) + NativeBridge.readEvents(after, buffer, out) + return EventBatch(events = EventDecoder.decode(buffer, out[2].toInt()), next = out[0], dropped = out[1]) + } + + override fun setClientConnected(connected: Boolean) = NativeBridge.setClientConnected(connected) + + override fun openServerConnection( + path: String, + writable: Boolean, + ): ServerConnection = NativeServerConnection(NativeBridge.openServer(path.toByteArray(Charsets.UTF_8), writable)) + + private class NativeServerConnection( + private var handle: Long, + ) : ServerConnection { + override fun query( + sql: String, + args: List, + offset: Long, + limits: QueryLimits, + deadlineMillis: Long, + ): QueryResult { + check(handle != 0L) { "the connection is closed" } + require(offset >= 0) { "offset $offset is negative" } + require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0) { "bad limits $limits" } + val result = + NativeBridge.query( + handle, + sql, + Array(args.size) { bindable(args[it]) }, + offset, + limits.maxRows, + limits.maxTextBytes, + limits.maxBlobBytes, + deadlineMillis, + ) + + @Suppress("UNCHECKED_CAST") + val columns = (result[0] as Array).asList() + + @Suppress("UNCHECKED_CAST") + val rows = (result[1] as List>).map { it.asList() } + val counts = result[2] as LongArray + return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L) + } + + override fun close() { + val h = handle + handle = 0 + if (h != 0L) NativeBridge.close(h) + } + + private fun bindable(value: Any?): Any? = + when (value) { + null, is Long, is Double, is String, is ByteArray -> value + is Int -> value.toLong() + is Short -> value.toLong() + is Byte -> value.toLong() + is Float -> value.toDouble() + else -> throw IllegalArgumentException("cannot bind a ${value.javaClass.name}") + } + } + + private companion object { + const val META_PER_CONNECTION = 5 + const val MAX_READ_BYTES = 16 shl 20 + + val lock = Any() + var installed = false + } +} diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt new file mode 100644 index 0000000000..555e566544 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/EventDecoderTest.kt @@ -0,0 +1,92 @@ +package org.appdevforall.sqlitedebugger.engine + +import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class EventDecoderTest { + // events.bin is what sqlitedbg_read_events copied out in sqlitedbg_test.c (test.sh --update-fixture); + // events.tsv is the same records as the C struct reads them: seq, kind, connection, thread, time, + // duration, flags, sql. + private val bytes = resource("events.bin") + private val table = + String(resource("events.tsv"), Charsets.UTF_8) + .trimEnd('\n') + .split('\n') + .map { it.split('\t', limit = 8) } + + private fun resource(name: String): ByteArray = + checkNotNull(javaClass.getResourceAsStream(name)) { "missing fixture $name" }.use { it.readBytes() } + + @Test + fun `decodes every field of the record the C layer wrote`() { + val events = EventDecoder.decode(bytes, bytes.size) + + assertThat(events).hasSize(table.size) + events.zip(table).forEach { (event, row) -> + assertThat(event.seq).isEqualTo(row[0].toLong()) + assertThat(event.kind.nativeValue).isEqualTo(row[1].toInt()) + assertThat(event.connectionId).isEqualTo(row[2].toLong()) + assertThat(event.threadId).isEqualTo(row[3].toLong()) + assertThat(event.timeEpochNanos).isEqualTo(row[4].toLong()) + assertThat(event.durationNanos).isEqualTo(if (event.kind == EventKind.PROFILE) row[5].toLong() else null) + assertThat(event.truncated).isEqualTo(row[6].toInt() and 1 != 0) + assertThat(event.expanded).isEqualTo(row[6].toInt() and 2 != 0) + assertThat(event.sql).isEqualTo(row[7]) + } + } + + @Test + fun `the fixture covers every kind and flag and a wide id`() { + val events = EventDecoder.decode(bytes, bytes.size) + + assertThat(events.map { it.kind }.toSet()).containsExactlyElementsIn(EventKind.values().toList()) + assertThat(events.any { it.truncated }).isTrue() + assertThat(events.any { it.expanded }).isTrue() + assertThat(events.any { it.sql.startsWith("--") }).isTrue() + // multi-byte text survives, including a character outside the BMP + assertThat(events.any { it.sql.contains("héllo € 😀") }).isTrue() + assertThat(events.map { it.seq }).isInOrder() + } + + @Test + fun `a prefix ending on a record boundary decodes to those records`() { + val firstRecordBytes = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(0) + + assertThat(EventDecoder.decode(bytes, firstRecordBytes)).hasSize(1) + assertThat(EventDecoder.decode(bytes, 0)).isEmpty() + } + + @Test + fun `a cut-off record is refused`() { + val firstRecordBytes = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(0) + + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(bytes, firstRecordBytes - 8) } + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(bytes, EventDecoder.HEADER_BYTES - 1) } + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(bytes, bytes.size + 1) } + } + + @Test + fun `a malformed header is refused`() { + fun patched( + offset: Int, + value: Int, + ): ByteArray { + val copy = bytes.copyOf() + ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN).putInt(offset, value) + return copy + } + + // record_bytes not a multiple of 8, smaller than the header, and an unknown kind + for (broken in listOf(patched(0, 60), patched(0, 48), patched(4, 9), patched(4, 0))) { + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(broken, broken.size) } + } + // sql_bytes longer than the record holds + val big = patched(52, 100000) + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(big, big.size) } + val negative = patched(52, -1) + assertThrows(IllegalArgumentException::class.java) { EventDecoder.decode(negative, negative.size) } + } +} From 31dc721e05c3871b68da8ebe909072a43897e08a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:06:19 +0000 Subject: [PATCH 030/203] style: spotless reformat of the SQLite debugger module, no functional change Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- .../sqlitedebugger/DebuggerStartup.kt | 30 ++- .../sqlitedebugger/mcp/DatabaseTools.kt | 213 ++++++++++++---- .../sqlitedebugger/mcp/McpHttp.kt | 232 +++++++++++++----- .../sqlitedebugger/mcp/McpProtocol.kt | 150 +++++++---- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 148 ++++++++--- .../sqlitedebugger/mcp/McpProtocolTest.kt | 176 +++++++++---- 6 files changed, 718 insertions(+), 231 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt index 2328ca17d1..30f7177dad 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt @@ -6,13 +6,13 @@ import android.content.pm.ApplicationInfo import android.database.Cursor import android.net.Uri import android.util.Log -import java.io.File -import kotlin.concurrent.thread import org.appdevforall.sqlitedebugger.engine.NativeDebugEngine import org.appdevforall.sqlitedebugger.mcp.DatabaseTools import org.appdevforall.sqlitedebugger.mcp.McpHttp import org.appdevforall.sqlitedebugger.mcp.McpProtocol +import java.io.File import java.util.UUID +import kotlin.concurrent.thread /** * Starts the debugger when the app's process starts. Refuses to run in a build that is not @@ -45,15 +45,33 @@ class DebuggerStartup : ContentProvider() { return true } - override fun query(uri: Uri, projection: Array?, selection: String?, selectionArgs: Array?, sortOrder: String?): Cursor? = null + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + ): Cursor? = null override fun getType(uri: Uri): String? = null - override fun insert(uri: Uri, values: ContentValues?): Uri? = null + override fun insert( + uri: Uri, + values: ContentValues?, + ): Uri? = null - override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + override fun delete( + uri: Uri, + selection: String?, + selectionArgs: Array?, + ): Int = 0 - override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int = 0 + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array?, + ): Int = 0 companion object { private const val TAG = "SqliteDebugger" diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 477b8d9d60..2ff44ec868 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -1,6 +1,5 @@ package org.appdevforall.sqlitedebugger.mcp -import java.io.File import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException import org.appdevforall.sqlitedebugger.engine.QueryLimits @@ -8,6 +7,7 @@ import org.appdevforall.sqlitedebugger.engine.QueryResult import org.appdevforall.sqlitedebugger.engine.ServerConnection import org.json.JSONArray import org.json.JSONObject +import java.io.File /** * The debugger's MCP tools, all read-only: they open server connections through [engine] with @@ -44,24 +44,42 @@ class DatabaseTools( maxBlobBytes: Int = MAX_BLOB_BYTES, ): Any = when (value) { - null -> JSONObject.NULL - is Long -> encodeLong(value) - is Int -> value.toLong() - is Double -> + null -> { + JSONObject.NULL + } + + is Long -> { + encodeLong(value) + } + + is Int -> { + value.toLong() + } + + is Double -> { when { value.isNaN() -> "NaN" value == Double.POSITIVE_INFINITY -> "Infinity" value == Double.NEGATIVE_INFINITY -> "-Infinity" else -> value } - is String -> value - is ByteArray -> + } + + is String -> { + value + } + + is ByteArray -> { JSONObject() .put("base64", McpHttp.base64(value, urlSafe = false, pad = true)) .put("bytes", value.size) // the engine cuts at the limit without saying how long the BLOB was .put("truncated", value.size >= maxBlobBytes) - else -> value.toString() + } + + else -> { + value.toString() + } } fun encodeLong(value: Long): Any = if (value > MAX_SAFE_INTEGER || value < -MAX_SAFE_INTEGER) value.toString() else value @@ -87,14 +105,29 @@ class DatabaseTools( fun tools(): List = listOf( - tool("list_databases", "List databases", "Lists the app's databases: each one an app connection has open (available), and the files in the app's database folder that none has opened (not available: not inspectable until the app opens them).") { listDatabases() }, - tool("list_connections", "List connections", "Lists the app's open SQLite connections (not yet freed by SQLite), oldest first.") { listConnections() }, - tool("get_schema", "Get schema", "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_schema.", databaseSchema()) { getSchema(it) }, + tool( + "list_databases", + "List databases", + "Lists the app's databases: each one an app connection has open (available), and the files in the app's database folder " + + "that none has opened (not available: not inspectable until the app opens them).", + ) { listDatabases() }, + tool( + "list_connections", + "List connections", + "Lists the app's open SQLite connections (not yet freed by SQLite), oldest first.", + ) { listConnections() }, + tool( + "get_schema", + "Get schema", + "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_schema.", + databaseSchema(), + ) { getSchema(it) }, tool( "query", "Run a query", "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + - "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. Use offset to page. $PAGING_NOTE Writes are refused.", + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. Use offset to page. " + + "$PAGING_NOTE Writes are refused.", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), @@ -113,18 +146,28 @@ class DatabaseTools( required = listOf("sql"), ), ) { explain(it) }, - tool("get_stats", "Get statistics", "Returns page_count, page_size, freelist_count, and the row count of each table when the database has fewer than $MAX_TABLES_FOR_COUNTS tables.", databaseSchema()) { getStats(it) }, + tool( + "get_stats", + "Get statistics", + "Returns page_count, page_size, freelist_count, and the row count of each table when the database has fewer than " + + "$MAX_TABLES_FOR_COUNTS tables.", + databaseSchema(), + ) { getStats(it) }, tool( "integrity_check", "Check integrity", - "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. ok is true when SQLite reports no problem.", + "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. " + + "ok is true when SQLite reports no problem.", databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), ) { integrityCheck(it) }, tool( "get_events", "Get SQL events", - "Returns the SQL the app ran, oldest first, after the cursor. Pass the returned next as after to continue; dropped counts events that left the buffer unread. The first call starts recording bound values into the SQL.", - JSONObject().put("type", "object").put("additionalProperties", false) + "Returns the SQL the app ran, oldest first, after the cursor. Pass the returned next as after to continue; " + + "dropped counts events that left the buffer unread. The first call starts recording bound values into the SQL.", + JSONObject() + .put("type", "object") + .put("additionalProperties", false) .put("properties", JSONObject().put("after", prop("integer", "Cursor: the next from the last call. Default 0."))) .put("required", JSONArray()), ) { getEvents(it) }, @@ -149,7 +192,10 @@ class DatabaseTools( ): JSONObject { val props = JSONObject().put("database", prop("string", "The database path, as list_databases gives it.")) extra.forEach { props.put(it.first, it.second) } - return JSONObject().put("type", "object").put("properties", props).put("additionalProperties", false) + return JSONObject() + .put("type", "object") + .put("properties", props) + .put("additionalProperties", false) .put("required", JSONArray(listOf("database") + required)) } @@ -173,22 +219,38 @@ class DatabaseTools( val list = JSONArray() for (c in engine.connections()) { list.put( - JSONObject().put("id", encodeLong(c.id)).put("path", c.path).put("read_only", c.readOnly).put("closing", c.closing) - .put("opened_at_epoch_nanos", encodeLong(c.openedAtEpochNanos)).put("open_thread_id", encodeLong(c.openThreadId)), + JSONObject() + .put("id", encodeLong(c.id)) + .put("path", c.path) + .put("read_only", c.readOnly) + .put("closing", c.closing) + .put("opened_at_epoch_nanos", encodeLong(c.openedAtEpochNanos)) + .put("open_thread_id", encodeLong(c.openThreadId)), ) } return JSONObject().put("connections", list) } private fun getSchema(args: JSONObject): JSONObject { - val result = run(args, "SELECT type, name, tbl_name, sql FROM sqlite_schema ORDER BY type, name", emptyList(), 0, QueryLimits(MAX_ROWS, 65536, MAX_BLOB_BYTES)) + val result = + run( + args, + "SELECT type, name, tbl_name, sql FROM sqlite_schema ORDER BY type, name", + emptyList(), + 0, + QueryLimits(MAX_ROWS, 65536, MAX_BLOB_BYTES), + ) val groups = linkedMapOf("table" to JSONArray(), "index" to JSONArray(), "view" to JSONArray(), "trigger" to JSONArray()) for (row in result.rows) { val item = JSONObject().put("name", encodeValue(row[1])).put("table", encodeValue(row[2])).put("sql", encodeValue(row[3])) groups[row[0] as? String]?.put(item) } - return JSONObject().put("tables", groups["table"]).put("indexes", groups["index"]).put("views", groups["view"]) - .put("triggers", groups["trigger"]).put("truncated", result.hasMore) + return JSONObject() + .put("tables", groups["table"]) + .put("indexes", groups["index"]) + .put("views", groups["view"]) + .put("triggers", groups["trigger"]) + .put("truncated", result.hasMore) } private fun query(args: JSONObject): JSONObject { @@ -202,7 +264,14 @@ class DatabaseTools( } private fun explain(args: JSONObject): JSONObject { - val result = run(args, "EXPLAIN QUERY PLAN " + stringArg(args, "sql"), bindArgs(args), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) + val result = + run( + args, + "EXPLAIN QUERY PLAN " + stringArg(args, "sql"), + bindArgs(args), + 0, + QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES), + ) return JSONObject().put("plan", rowsAsObjects(result)) } @@ -210,22 +279,42 @@ class DatabaseTools( val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES) val deadline = clock() + DEADLINE_MS val path = checkedPath(args) + fun pragma(name: String) = runChecked(path, "PRAGMA $name", emptyList(), 0, limits, deadline).rows.firstOrNull()?.firstOrNull() val pageCount = pragma("page_count") as? Long val pageSize = pragma("page_size") as? Long - val out = JSONObject().put("page_count", encodeValue(pageCount)).put("page_size", encodeValue(pageSize)) - .put("freelist_count", encodeValue(pragma("freelist_count"))) + val out = + JSONObject() + .put("page_count", encodeValue(pageCount)) + .put("page_size", encodeValue(pageSize)) + .put("freelist_count", encodeValue(pragma("freelist_count"))) if (pageCount != null && pageSize != null) out.put("size_bytes", encodeLong(pageCount * pageSize)) - val tables = runChecked(path, "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", emptyList(), 0, limits, deadline) - .rows.map { it[0] as String } + val tables = + runChecked( + path, + "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + emptyList(), + 0, + limits, + deadline, + ).rows + .map { it[0] as String } if (tables.size < MAX_TABLES_FOR_COUNTS) { val counts = JSONObject() for (t in tables) { - val n = try { - runChecked(path, "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", emptyList(), 0, limits, deadline).rows.firstOrNull()?.firstOrNull() - } catch (e: McpToolError) { - e.message - } + val n = + try { + runChecked( + path, + "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", + emptyList(), + 0, + limits, + deadline, + ).rows.firstOrNull()?.firstOrNull() + } catch (e: McpToolError) { + e.message + } counts.put(t, encodeValue(n)) } out.put("row_counts", counts) @@ -236,16 +325,19 @@ class DatabaseTools( } private fun integrityCheck(args: JSONObject): JSONObject { - val full = when (val v = args.opt("full")) { - null, JSONObject.NULL -> false - is Boolean -> v - else -> throw McpToolError("full must be true or false.") - } + val full = + when (val v = args.opt("full")) { + null, JSONObject.NULL -> false + is Boolean -> v + else -> throw McpToolError("full must be true or false.") + } val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" val result = run(args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } - return JSONObject().put("check", if (full) "integrity_check" else "quick_check") - .put("ok", messages == listOf("ok")).put("messages", JSONArray(messages)) + return JSONObject() + .put("check", if (full) "integrity_check" else "quick_check") + .put("ok", messages == listOf("ok")) + .put("messages", JSONArray(messages)) } private fun getEvents(args: JSONObject): JSONObject { @@ -256,18 +348,25 @@ class DatabaseTools( clientConnected = true } } - val batch = try { - engine.readEvents(after, EVENT_BATCH_BYTES) - } catch (e: DebugEngineException) { - throw engineError(e) - } + val batch = + try { + engine.readEvents(after, EVENT_BATCH_BYTES) + } catch (e: DebugEngineException) { + throw engineError(e) + } val events = JSONArray() for (e in batch.events) { events.put( - JSONObject().put("seq", encodeLong(e.seq)).put("kind", e.kind.name.lowercase()).put("connection_id", encodeLong(e.connectionId)) - .put("thread_id", encodeLong(e.threadId)).put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) + JSONObject() + .put("seq", encodeLong(e.seq)) + .put("kind", e.kind.name.lowercase()) + .put("connection_id", encodeLong(e.connectionId)) + .put("thread_id", encodeLong(e.threadId)) + .put("time_epoch_nanos", encodeLong(e.timeEpochNanos)) .put("duration_nanos", e.durationNanos?.let { encodeLong(it) } ?: JSONObject.NULL) - .put("sql", e.sql).put("truncated", e.truncated).put("expanded", e.expanded), + .put("sql", e.sql) + .put("truncated", e.truncated) + .put("expanded", e.expanded), ) } return JSONObject().put("next", encodeLong(batch.next)).put("dropped", encodeLong(batch.dropped)).put("events", events) @@ -279,8 +378,14 @@ class DatabaseTools( ): JSONObject { val rows = JSONArray() for (row in result.rows) rows.put(JSONArray().also { a -> row.forEach { a.put(encodeValue(it)) } }) - val out = JSONObject().put("columns", JSONArray(result.columns)).put("rows", rows).put("row_count", result.rows.size) - .put("offset", encodeLong(offset)).put("has_more", result.hasMore).put("truncated_cells", result.truncatedCells) + val out = + JSONObject() + .put("columns", JSONArray(result.columns)) + .put("rows", rows) + .put("row_count", result.rows.size) + .put("offset", encodeLong(offset)) + .put("has_more", result.hasMore) + .put("truncated_cells", result.truncatedCells) if (result.hasMore) out.put("next_offset", encodeLong(offset + result.rows.size)) return out } @@ -297,7 +402,12 @@ class DatabaseTools( private fun checkedPath(args: JSONObject): String { val path = stringArg(args, "database") - val known = engine.connections().map { it.path }.filter { it.isNotEmpty() }.distinct() + val known = + engine + .connections() + .map { it.path } + .filter { it.isNotEmpty() } + .distinct() if (path !in known) { throw McpToolError( "Unknown database \"$path\": use a path from list_databases that is available.", @@ -360,7 +470,8 @@ class DatabaseTools( if (d != Math.floor(d) || d.isInfinite() || Math.abs(d) >= 9.2e18) throw McpToolError("$name must be an integer.") } val l = n.toLong() - if (l < min || l > max) throw McpToolError("$name must be between $min and ${if (max == Long.MAX_VALUE) "2^63-1" else max.toString()}.") + val upper = if (max == Long.MAX_VALUE) "2^63-1" else max.toString() + if (l < min || l > max) throw McpToolError("$name must be between $min and $upper.") return l } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index 7d58e73556..f29b5acad3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -1,5 +1,6 @@ package org.appdevforall.sqlitedebugger.mcp +import org.json.JSONObject import java.io.BufferedInputStream import java.io.ByteArrayOutputStream import java.io.IOException @@ -16,7 +17,6 @@ import java.util.Collections import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger import kotlin.concurrent.thread -import org.json.JSONObject /** * The MCP endpoint's HTTP side: a small HTTP/1.1 listener on 127.0.0.1 only, so it's never @@ -47,7 +47,11 @@ class McpHttp( fun newToken(): String = base64(ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }, urlSafe = true, pad = false) /** By hand: java.util.Base64 needs API 26 and this library's minSdk is 21. */ - fun base64(bytes: ByteArray, urlSafe: Boolean, pad: Boolean): String { + fun base64( + bytes: ByteArray, + urlSafe: Boolean, + pad: Boolean, + ): String { val out = StringBuilder() var i = 0 while (i < bytes.size) { @@ -56,7 +60,15 @@ class McpHttp( for (k in 0 until 3) v = (v shl 8) or (if (k < n) bytes[i + k].toInt() and 0xff else 0) for (k in 0..n) { val idx = (v shr (18 - 6 * k)) and 63 - out.append(if (idx < 62) B64[idx] else if (idx == 62) (if (urlSafe) '-' else '+') else (if (urlSafe) '_' else '/')) + out.append( + if (idx < 62) { + B64[idx] + } else if (idx == 62) { + (if (urlSafe) '-' else '+') + } else { + (if (urlSafe) '_' else '/') + }, + ) } if (pad) repeat(3 - n) { out.append('=') } i += 3 @@ -68,21 +80,44 @@ class McpHttp( const val MAX_CONNECTIONS = 8 private const val MAX_HEADER_BYTES = 16 * 1024 const val MAX_BODY_BYTES = 1024 * 1024 + /** A connection with no request for this long is closed. */ const val IDLE_TIMEOUT_MS = 30_000 - private val STATUS = mapOf( - 200 to "OK", 202 to "Accepted", 204 to "No Content", 400 to "Bad Request", 401 to "Unauthorized", - 403 to "Forbidden", 404 to "Not Found", 405 to "Method Not Allowed", 413 to "Payload Too Large", - 415 to "Unsupported Media Type", 431 to "Request Header Fields Too Large", 500 to "Internal Server Error", - 501 to "Not Implemented", 503 to "Service Unavailable", - ) + private val STATUS = + mapOf( + 200 to "OK", + 202 to "Accepted", + 204 to "No Content", + 400 to "Bad Request", + 401 to "Unauthorized", + 403 to "Forbidden", + 404 to "Not Found", + 405 to "Method Not Allowed", + 413 to "Payload Too Large", + 415 to "Unsupported Media Type", + 431 to "Request Header Fields Too Large", + 500 to "Internal Server Error", + 501 to "Not Implemented", + 503 to "Service Unavailable", + ) private val LOOPBACK_NAMES = setOf("127.0.0.1", "localhost") } - private class Request(val method: String, val target: String, val version: String, val headers: Map, val body: ByteArray) - private class HttpError(val status: Int, message: String) : Exception(message) + private class Request( + val method: String, + val target: String, + val version: String, + val headers: Map, + val body: ByteArray, + ) + + private class HttpError( + val status: Int, + message: String, + ) : Exception(message) @Volatile private var socket: ServerSocket? = null + @Volatile private var running = false private val open = AtomicInteger(0) private val clients: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) @@ -97,7 +132,10 @@ class McpHttp( s.reuseAddress = true s.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), port), 16) } catch (e: IOException) { - try { s.close() } catch (ignored: IOException) { } + try { + s.close() + } catch (ignored: IOException) { + } throw IOException("Can't listen on 127.0.0.1:$port: ${e.message}", e) } socket = s @@ -108,7 +146,10 @@ class McpHttp( /** Stops listening and closes every connection. */ fun stop() { running = false - try { socket?.close() } catch (ignored: IOException) { } + try { + socket?.close() + } catch (ignored: IOException) { + } socket = null clients.forEach { close(it) } clients.clear() @@ -116,17 +157,24 @@ class McpHttp( private fun acceptLoop(s: ServerSocket) { while (running && !s.isClosed) { - val c = try { s.accept() } catch (e: IOException) { - if (running && !s.isClosed) log("couldn't accept a connection: ${e.message}") + val c = + try { + s.accept() + } catch (e: IOException) { + if (running && !s.isClosed) log("couldn't accept a connection: ${e.message}") + continue + } + if (!c.inetAddress.isLoopbackAddress) { + close(c) continue } - if (!c.inetAddress.isLoopbackAddress) { close(c); continue } if (open.incrementAndGet() > MAX_CONNECTIONS) { open.decrementAndGet() try { c.soTimeout = 1000 respond(c.getOutputStream(), 503, rpcError("Too many connections at once; try again."), emptyMap(), close = true) - } catch (ignored: IOException) { } + } catch (ignored: IOException) { + } close(c) continue } @@ -153,22 +201,31 @@ class McpHttp( val input = BufferedInputStream(c.getInputStream()) val out = c.getOutputStream() while (running) { - val req = try { - readRequest(input) ?: return - } catch (e: SocketTimeoutException) { - return - } catch (e: HttpError) { - respond(out, e.status, rpcError(e.message ?: "Bad request."), emptyMap(), close = true) - return - } + val req = + try { + readRequest(input) ?: return + } catch (e: SocketTimeoutException) { + return + } catch (e: HttpError) { + respond(out, e.status, rpcError(e.message ?: "Bad request."), emptyMap(), close = true) + return + } if (!handle(req, out)) return } } /** Answers one request. Returns whether the connection stays open for another. */ - private fun handle(r: Request, out: OutputStream): Boolean { + private fun handle( + r: Request, + out: OutputStream, + ): Boolean { val close = r.version == "HTTP/1.0" || r.headers["connection"]?.lowercase()?.contains("close") == true - fun send(status: Int, body: String?, headers: Map = emptyMap()): Boolean { + + fun send( + status: Int, + body: String?, + headers: Map = emptyMap(), + ): Boolean { respond(out, status, body, headers, close) return !close } @@ -177,25 +234,45 @@ class McpHttp( if (origin != null && !originAllowed(origin)) return send(403, rpcError("Requests from web pages aren't accepted.")) if (r.target.substringBefore('?') != PATH) return send(404, rpcError("Not found: the MCP endpoint is $PATH.")) if (!authorized(r.headers["authorization"])) { - return send(401, rpcError("Missing or wrong token. Code on the Go gives it to its Agent; send it as Authorization: Bearer ."), - mapOf("WWW-Authenticate" to "Bearer realm=\"SQLite debugger\"")) + return send( + 401, + rpcError( + "Missing or wrong token. Code on the Go gives it to its Agent; " + + "send it as Authorization: Bearer .", + ), + mapOf("WWW-Authenticate" to "Bearer realm=\"SQLite debugger\""), + ) } val session = r.headers["mcp-session-id"] - val reply = when (r.method) { - "POST" -> { - val type = r.headers["content-type"]?.substringBefore(';')?.trim()?.lowercase() - if (type != null && type != "application/json") return send(415, rpcError("Send the request as application/json.")) - try { - protocol.post(String(r.body, Charsets.UTF_8), session, r.headers["mcp-protocol-version"]) - } catch (e: Exception) { - log("a request failed: ${e.javaClass.simpleName}: ${e.message}") - McpProtocol.Reply(500, rpcError("The server failed: ${e.message ?: e.javaClass.simpleName}")) + val reply = + when (r.method) { + "POST" -> { + val type = + r.headers["content-type"] + ?.substringBefore(';') + ?.trim() + ?.lowercase() + if (type != null && type != "application/json") return send(415, rpcError("Send the request as application/json.")) + try { + protocol.post(String(r.body, Charsets.UTF_8), session, r.headers["mcp-protocol-version"]) + } catch (e: Exception) { + log("a request failed: ${e.javaClass.simpleName}: ${e.message}") + McpProtocol.Reply(500, rpcError("The server failed: ${e.message ?: e.javaClass.simpleName}")) + } + } + + "DELETE" -> { + protocol.delete(session) + } + + "GET" -> { + return send(405, rpcError("This server doesn't offer an event stream: use POST."), mapOf("Allow" to "POST, DELETE")) + } + + else -> { + return send(405, rpcError("Use POST."), mapOf("Allow" to "POST, DELETE")) } } - "DELETE" -> protocol.delete(session) - "GET" -> return send(405, rpcError("This server doesn't offer an event stream: use POST."), mapOf("Allow" to "POST, DELETE")) - else -> return send(405, rpcError("Use POST."), mapOf("Allow" to "POST, DELETE")) - } return send(reply.status, reply.body, reply.headers) } @@ -209,10 +286,13 @@ class McpHttp( return name in LOOPBACK_NAMES } - private fun originAllowed(origin: String): Boolean = try { - val u = URI(origin.trim()) - (u.scheme == "http" || u.scheme == "https") && u.host?.lowercase() in LOOPBACK_NAMES - } catch (e: Exception) { false } + private fun originAllowed(origin: String): Boolean = + try { + val u = URI(origin.trim()) + (u.scheme == "http" || u.scheme == "https") && u.host?.lowercase() in LOOPBACK_NAMES + } catch (e: Exception) { + false + } private fun authorized(header: String?): Boolean { val expected = token() @@ -227,11 +307,14 @@ class McpHttp( /** One request, or null if the connection closed before one began. */ private fun readRequest(input: InputStream): Request? { var budget = MAX_HEADER_BYTES + fun line(): String? { val b = ByteArrayOutputStream() while (true) { val ch = input.read() - if (ch < 0) { if (b.size() == 0) return null else throw HttpError(400, "The request ended early.") } + if (ch < 0) { + if (b.size() == 0) return null else throw HttpError(400, "The request ended early.") + } if (--budget < 0) throw HttpError(431, "The request's headers are too long.") if (ch == '\n'.code) break b.write(ch) @@ -239,7 +322,7 @@ class McpHttp( return b.toString("ISO-8859-1").removeSuffix("\r") } var first = line() ?: return null - while (first.isEmpty()) first = line() ?: return null // stray line ends between requests + while (first.isEmpty()) first = line() ?: return null // stray line ends between requests val parts = first.split(' ') if (parts.size != 3 || !parts[2].startsWith("HTTP/1.")) throw HttpError(400, "That isn't an HTTP/1.x request.") val headers = HashMap() @@ -256,7 +339,10 @@ class McpHttp( return Request(parts[0], parts[1], parts[2], headers, readBody(input, headers)) } - private fun readBody(input: InputStream, h: Map): ByteArray { + private fun readBody( + input: InputStream, + h: Map, + ): ByteArray { val te = h["transfer-encoding"] if (te != null) { if (!te.equals("chunked", ignoreCase = true)) throw HttpError(501, "Transfer-Encoding $te isn't supported.") @@ -273,7 +359,12 @@ class McpHttp( val out = ByteArrayOutputStream() while (true) { val sizeLine = shortLine(input, 1024) ?: throw HttpError(400, "The request ended early.") - val size = sizeLine.substringBefore(';').trim().toIntOrNull(16)?.takeIf { it >= 0 } ?: throw HttpError(400, "A bad chunk size.") + val size = + sizeLine + .substringBefore(';') + .trim() + .toIntOrNull(16) + ?.takeIf { it >= 0 } ?: throw HttpError(400, "A bad chunk size.") if (out.size().toLong() + size > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") if (size == 0) { // Trailers, if any, up to a blank line. @@ -290,7 +381,10 @@ class McpHttp( } } - private fun shortLine(input: InputStream, max: Int): String? { + private fun shortLine( + input: InputStream, + max: Int, + ): String? { val b = ByteArrayOutputStream() var left = max while (true) { @@ -303,7 +397,10 @@ class McpHttp( return b.toString("ISO-8859-1").removeSuffix("\r") } - private fun readExactly(input: InputStream, n: Int): ByteArray { + private fun readExactly( + input: InputStream, + n: Int, + ): ByteArray { val b = ByteArray(n) var off = 0 while (off < n) { @@ -314,14 +411,26 @@ class McpHttp( return b } - private fun respond(out: OutputStream, status: Int, body: String?, headers: Map, close: Boolean) { + private fun respond( + out: OutputStream, + status: Int, + body: String?, + headers: Map, + close: Boolean, + ) { val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) val head = StringBuilder("HTTP/1.1 $status ${STATUS[status] ?: "Status"}\r\n") if (body != null) head.append("Content-Type: application/json; charset=utf-8\r\n") if (status != 204) head.append("Content-Length: ${bytes.size}\r\n") head.append("Cache-Control: no-store\r\n") if (close) head.append("Connection: close\r\n") - for ((k, v) in headers) head.append(k).append(": ").append(v.replace("\r", "").replace("\n", "")).append("\r\n") + for ((k, v) in headers) { + head + .append(k) + .append(": ") + .append(v.replace("\r", "").replace("\n", "")) + .append("\r\n") + } head.append("\r\n") out.write(head.toString().toByteArray(Charsets.ISO_8859_1)) if (status != 204) out.write(bytes) @@ -329,8 +438,17 @@ class McpHttp( } /** An HTTP-level refusal, as a JSON-RPC error with no id, which MCP clients know how to show. */ - private fun rpcError(message: String): String = JSONObject().put("jsonrpc", "2.0").put("id", JSONObject.NULL) - .put("error", JSONObject().put("code", McpProtocol.INVALID_REQUEST).put("message", message)).toString() + private fun rpcError(message: String): String = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", JSONObject.NULL) + .put("error", JSONObject().put("code", McpProtocol.INVALID_REQUEST).put("message", message)) + .toString() - private fun close(s: Socket) { try { s.close() } catch (ignored: IOException) { } } + private fun close(s: Socket) { + try { + s.close() + } catch (ignored: IOException) { + } + } } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 01e0877b1d..6ee7c1b128 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -18,15 +18,27 @@ class McpTool( val readOnly: Boolean = true, val run: (JSONObject) -> JSONObject, ) { - fun describe(): JSONObject = JSONObject() - .put("name", name).put("title", title).put("description", description) - .put("inputSchema", inputSchema) - .put("annotations", JSONObject().put("title", title).put("readOnlyHint", readOnly) - .put("destructiveHint", false).put("openWorldHint", false)) + fun describe(): JSONObject = + JSONObject() + .put("name", name) + .put("title", title) + .put("description", description) + .put("inputSchema", inputSchema) + .put( + "annotations", + JSONObject() + .put("title", title) + .put("readOnlyHint", readOnly) + .put("destructiveHint", false) + .put("openWorldHint", false), + ) } /** A tool's failure, told to the client as a tool result with isError, with [details] when there are any. */ -class McpToolError(message: String, val details: JSONObject? = null) : Exception(message) +class McpToolError( + message: String, + val details: JSONObject? = null, +) : Exception(message) /** * The Model Context Protocol, as the SQLite debugger speaks it: JSON-RPC 2.0 over the Streamable HTTP @@ -52,31 +64,54 @@ class McpProtocol( const val INVALID_REQUEST = -32600 const val METHOD_NOT_FOUND = -32601 const val INVALID_PARAMS = -32602 - const val INSTRUCTIONS = "Inspects and queries the SQLite databases of the app this server runs in, a debug " + - "build made with Code on the Go. Read-only unless the app's developer turned on read-write mode." + const val INSTRUCTIONS = + "Inspects and queries the SQLite databases of the app this server runs in, a debug " + + "build made with Code on the Go. Read-only unless the app's developer turned on read-write mode." } /** What to send back: an HTTP status, a JSON body (or none), and extra headers. */ - class Reply(val status: Int, val body: String?, val headers: Map = emptyMap()) + class Reply( + val status: Int, + val body: String?, + val headers: Map = emptyMap(), + ) /** Live sessions, oldest first; the oldest is dropped when there are too many. */ private val sessions = LinkedHashSet() /** A POST to the endpoint: one JSON-RPC message, or a batch of them. */ - fun post(body: String, sessionId: String?, versionHeader: String?): Reply { - val parsed = try { JSONTokener(body).nextValue() } catch (e: Exception) { null } - if (parsed !is JSONObject && parsed !is JSONArray) return Reply(400, error(null, PARSE_ERROR, "That isn't a JSON object or array.").toString()) + fun post( + body: String, + sessionId: String?, + versionHeader: String?, + ): Reply { + val parsed = + try { + JSONTokener(body).nextValue() + } catch (e: Exception) { + null + } + if (parsed !is JSONObject && parsed !is JSONArray) { + return Reply(400, error(null, PARSE_ERROR, "That isn't a JSON object or array.").toString()) + } val messages: List = if (parsed is JSONArray) (0 until parsed.length()).map { parsed.opt(it) } else listOf(parsed) if (messages.isEmpty()) return Reply(400, error(null, INVALID_REQUEST, "An empty batch.").toString()) if (messages.any { (it as? JSONObject)?.optString("method") == "initialize" }) { - if (messages.size != 1) return Reply(400, error(null, INVALID_REQUEST, "Send initialize on its own, not in a batch.").toString()) + if (messages.size != 1) { + return Reply(400, error(null, INVALID_REQUEST, "Send initialize on its own, not in a batch.").toString()) + } return initialize(messages[0] as JSONObject) } - if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header: send initialize first.").toString()) - if (!touch(sessionId)) return Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist: send initialize again.").toString()) + if (sessionId.isNullOrEmpty()) { + return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header: send initialize first.").toString()) + } + if (!touch(sessionId)) { + return Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist: send initialize again.").toString()) + } if (versionHeader != null && versionHeader !in VERSIONS) { - return Reply(400, error(null, INVALID_REQUEST, "Unsupported MCP-Protocol-Version $versionHeader; this server speaks ${VERSIONS.joinToString()}.").toString()) + val detail = "Unsupported MCP-Protocol-Version $versionHeader; this server speaks ${VERSIONS.joinToString()}." + return Reply(400, error(null, INVALID_REQUEST, detail).toString()) } val replies = messages.mapNotNull { handle(it) } if (replies.isEmpty()) return Reply(202, null) @@ -87,7 +122,11 @@ class McpProtocol( fun delete(sessionId: String?): Reply { if (sessionId.isNullOrEmpty()) return Reply(400, error(null, INVALID_REQUEST, "No $SESSION_HEADER header.").toString()) val removed = synchronized(sessions) { sessions.remove(sessionId) } - return if (removed) Reply(204, null) else Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist.").toString()) + return if (removed) { + Reply(204, null) + } else { + Reply(404, error(null, INVALID_REQUEST, "That session has ended or doesn't exist.").toString()) + } } /** Ends every session, so clients must initialize again. */ @@ -95,11 +134,12 @@ class McpProtocol( fun sessionCount(): Int = synchronized(sessions) { sessions.size } - private fun touch(id: String): Boolean = synchronized(sessions) { - if (!sessions.remove(id)) return false - sessions += id // most recently used goes last, so it's dropped last - true - } + private fun touch(id: String): Boolean = + synchronized(sessions) { + if (!sessions.remove(id)) return false + sessions += id // most recently used goes last, so it's dropped last + true + } private fun initialize(m: JSONObject): Reply { val id = m.opt("id") @@ -112,11 +152,12 @@ class McpProtocol( sessions += session while (sessions.size > maxSessions) sessions.remove(sessions.first()) } - val result = JSONObject() - .put("protocolVersion", version) - .put("capabilities", JSONObject().put("tools", JSONObject().put("listChanged", false))) - .put("serverInfo", JSONObject().put("name", SERVER_NAME).put("title", "SQLite debugger").put("version", serverVersion)) - .put("instructions", INSTRUCTIONS) + val result = + JSONObject() + .put("protocolVersion", version) + .put("capabilities", JSONObject().put("tools", JSONObject().put("listChanged", false))) + .put("serverInfo", JSONObject().put("name", SERVER_NAME).put("title", "SQLite debugger").put("version", serverVersion)) + .put("instructions", INSTRUCTIONS) return Reply(200, ok(id, result).toString(), mapOf(SESSION_HEADER to session)) } @@ -131,7 +172,7 @@ class McpProtocol( if (m.has("result") || m.has("error")) return null return error(if (validId(id)) id else null, INVALID_REQUEST, "A request needs a method.") } - if (!hasId) return null // a notification, such as notifications/initialized: no answer + if (!hasId) return null // a notification, such as notifications/initialized: no answer if (!validId(id)) return error(null, INVALID_REQUEST, "id must be a string or a number.") if (m.optString("jsonrpc") != "2.0") return error(id, INVALID_REQUEST, "jsonrpc must be \"2.0\".") return when (method) { @@ -142,31 +183,50 @@ class McpProtocol( } } - private fun call(id: Any, rawParams: Any?): JSONObject { + private fun call( + id: Any, + rawParams: Any?, + ): JSONObject { val params = rawParams as? JSONObject ?: return error(id, INVALID_PARAMS, "tools/call needs params, with the tool's name.") val name = params.opt("name") as? String ?: return error(id, INVALID_PARAMS, "tools/call needs the tool's name.") val tool = tools.firstOrNull { it.name == name } ?: return error(id, INVALID_PARAMS, "Unknown tool \"$name\".") - val args = when (val a = params.opt("arguments")) { - null, JSONObject.NULL -> JSONObject() - is JSONObject -> a - else -> return error(id, INVALID_PARAMS, "arguments must be an object.") - } - val result = try { - val out = tool.run(args) - JSONObject().put("content", JSONArray().put(text(out.toString(2)))).put("structuredContent", out).put("isError", false) - } catch (e: McpToolError) { - JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> - e.details?.let { r.put("structuredContent", it) } + val args = + when (val a = params.opt("arguments")) { + null, JSONObject.NULL -> JSONObject() + is JSONObject -> a + else -> return error(id, INVALID_PARAMS, "arguments must be an object.") + } + val result = + try { + val out = tool.run(args) + JSONObject().put("content", JSONArray().put(text(out.toString(2)))).put("structuredContent", out).put("isError", false) + } catch (e: McpToolError) { + JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> + e.details?.let { r.put("structuredContent", it) } + } + } catch (e: Exception) { + JSONObject() + .put("content", JSONArray().put(text("The tool failed: ${e.message ?: e.javaClass.simpleName}"))) + .put("isError", true) } - } catch (e: Exception) { - JSONObject().put("content", JSONArray().put(text("The tool failed: ${e.message ?: e.javaClass.simpleName}"))).put("isError", true) - } return ok(id, result) } private fun validId(id: Any?) = id is String || id is Number + private fun text(t: String) = JSONObject().put("type", "text").put("text", t) - private fun ok(id: Any, result: JSONObject) = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) - private fun error(id: Any?, code: Int, message: String) = JSONObject().put("jsonrpc", "2.0").put("id", id ?: JSONObject.NULL) + + private fun ok( + id: Any, + result: JSONObject, + ) = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + + private fun error( + id: Any?, + code: Int, + message: String, + ) = JSONObject() + .put("jsonrpc", "2.0") + .put("id", id ?: JSONObject.NULL) .put("error", JSONObject().put("code", code).put("message", message)) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 7e15669b14..702bc4c75f 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -1,6 +1,5 @@ package org.appdevforall.sqlitedebugger.mcp -import java.io.File import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngineException import org.appdevforall.sqlitedebugger.engine.EventKind @@ -12,6 +11,7 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test +import java.io.File class DatabaseToolsTest { private val engine = FakeDebugEngine() @@ -32,11 +32,21 @@ class DatabaseToolsTest { args: JSONObject = JSONObject(), ): JSONObject { val protocol = McpProtocol(t.tools(), "test", { "s" }, 4) - val init = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize") - .put("params", JSONObject().put("protocolVersion", "2025-06-18")).toString() + val init = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 1) + .put("method", "initialize") + .put("params", JSONObject().put("protocolVersion", "2025-06-18")) + .toString() val session = protocol.post(init, null, null).headers[McpProtocol.SESSION_HEADER]!! - val call = JSONObject().put("jsonrpc", "2.0").put("id", 2).put("method", "tools/call") - .put("params", JSONObject().put("name", name).put("arguments", args)).toString() + val call = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 2) + .put("method", "tools/call") + .put("params", JSONObject().put("name", name).put("arguments", args)) + .toString() return JSONObject(protocol.post(call, session, null).body!!).getJSONObject("result") } @@ -62,7 +72,16 @@ class DatabaseToolsTest { @Test fun everyToolIsReadOnly() { val list = tools.tools() assertEquals( - listOf("list_databases", "list_connections", "get_schema", "query", "explain_query_plan", "get_stats", "integrity_check", "get_events"), + listOf( + "list_databases", + "list_connections", + "get_schema", + "query", + "explain_query_plan", + "get_stats", + "integrity_check", + "get_events", + ), list.map { it.name }, ) list.forEach { assertTrue(it.name, it.describe().getJSONObject("annotations").getBoolean("readOnlyHint")) } @@ -78,7 +97,10 @@ class DatabaseToolsTest { } @Test fun listDatabasesAddsUnopenedFilesButNotSideFiles() { - val d = kotlin.io.path.createTempDirectory("dbs").toFile() + val d = + kotlin.io.path + .createTempDirectory("dbs") + .toFile() try { listOf("open.db", "closed.db", "closed.db-wal", "closed.db-shm", "closed.db-journal").forEach { File(d, it).writeText("x") } dir = d @@ -104,7 +126,15 @@ class DatabaseToolsTest { @Test fun everyDatabaseToolRefusesAnUnknownPathBeforeTheEngine() { engine.appConnections += conn(1, "/data/a.db") - for ((name, extra) in listOf("get_schema" to JSONObject(), "query" to JSONObject().put("sql", "select 1"), "explain_query_plan" to JSONObject().put("sql", "select 1"), "get_stats" to JSONObject(), "integrity_check" to JSONObject())) { + val cases = + listOf( + "get_schema" to JSONObject(), + "query" to JSONObject().put("sql", "select 1"), + "explain_query_plan" to JSONObject().put("sql", "select 1"), + "get_stats" to JSONObject(), + "integrity_check" to JSONObject(), + ) + for ((name, extra) in cases) { for (bad in listOf("/data/other.db", "", "/data/a.db-wal")) { val r = runTool(tools, name, db(bad).also { o -> extra.keys().forEach { k -> o.put(k, extra.get(k)) } }) assertTrue("$name $bad", r.getBoolean("isError")) @@ -131,12 +161,23 @@ class DatabaseToolsTest { assertTrue(r.getBoolean("has_more")) assertEquals(3, r.getInt("next_offset")) assertTrue(r.getString("note").contains("re-runs")) - assertTrue(tools.tools().first { it.name == "query" }.description.contains("re-runs")) + assertTrue( + tools + .tools() + .first { it.name == "query" } + .description + .contains("re-runs"), + ) } @Test fun queryChecksItsArguments() { engine.appConnections += conn(1, "/data/a.db") - fun bad(vararg kv: Pair) = assertTrue(kv.toString(), runTool(tools, "query", db().also { o -> kv.forEach { o.put(it.first, it.second) } }).getBoolean("isError")) + + fun bad(vararg kv: Pair) = + assertTrue( + kv.toString(), + runTool(tools, "query", db().also { o -> kv.forEach { o.put(it.first, it.second) } }).getBoolean("isError"), + ) bad() bad("sql" to "x", "max_rows" to 1001) bad("sql" to "x", "max_rows" to 0) @@ -150,8 +191,22 @@ class DatabaseToolsTest { @Test fun queryBindsArgsByType() { engine.appConnections += conn(1, "/data/a.db") var got: List = emptyList() - engine.answer = { _, _, _, a -> got = a; QueryResult(emptyList(), emptyList(), 0, false) } - ok("query", db().put("sql", "x").put("args", JSONArray().put(JSONObject.NULL).put(3).put(2.5).put("s").put(true))) + engine.answer = { _, _, _, a -> + got = a + QueryResult(emptyList(), emptyList(), 0, false) + } + ok( + "query", + db().put("sql", "x").put( + "args", + JSONArray() + .put(JSONObject.NULL) + .put(3) + .put(2.5) + .put("s") + .put(true), + ), + ) assertEquals(listOf(null, 3L, 2.5, "s", 1L), got) } @@ -169,16 +224,26 @@ class DatabaseToolsTest { val real = engine engine.answer = { _, _, _, _ -> QueryResult(emptyList(), emptyList(), 0, false) } // the fake ignores the deadline, so check the arithmetic through the constant and a wrapper engine - val wrapper = object : org.appdevforall.sqlitedebugger.engine.DebugEngine by real { - override fun openServerConnection(path: String, writable: Boolean) = real.openServerConnection(path, writable).let { c -> - object : org.appdevforall.sqlitedebugger.engine.ServerConnection by c { - override fun query(sql: String, args: List, offset: Long, limits: org.appdevforall.sqlitedebugger.engine.QueryLimits, deadlineMillis: Long): QueryResult { - deadline = deadlineMillis - return c.query(sql, args, offset, limits, deadlineMillis) + val wrapper = + object : org.appdevforall.sqlitedebugger.engine.DebugEngine by real { + override fun openServerConnection( + path: String, + writable: Boolean, + ) = real.openServerConnection(path, writable).let { c -> + object : org.appdevforall.sqlitedebugger.engine.ServerConnection by c { + override fun query( + sql: String, + args: List, + offset: Long, + limits: org.appdevforall.sqlitedebugger.engine.QueryLimits, + deadlineMillis: Long, + ): QueryResult { + deadline = deadlineMillis + return c.query(sql, args, offset, limits, deadlineMillis) + } } } } - } ok("query", db().put("sql", "x"), DatabaseTools(wrapper, null, { now })) assertEquals(now + 50_000, deadline) } @@ -189,7 +254,18 @@ class DatabaseToolsTest { engine.answer = { _, _, _, _ -> QueryResult( listOf("a", "b", "c", "d", "e", "f", "g", "h"), - listOf(listOf(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, big, -big, 9_007_199_254_740_992L, byteArrayOf(1, 2, 3), null)), + listOf( + listOf( + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + big, + -big, + 9_007_199_254_740_992L, + byteArrayOf(1, 2, 3), + null, + ), + ), 0, false, ) @@ -213,17 +289,18 @@ class DatabaseToolsTest { @Test fun getSchemaGroupsByType() { engine.appConnections += conn(1, "/data/a.db") answerWith( - "SELECT type" to QueryResult( - listOf("type", "name", "tbl_name", "sql"), - listOf( - listOf("index", "i1", "t", "CREATE INDEX i1 ON t(a)"), - listOf("table", "t", "t", "CREATE TABLE t(a)"), - listOf("trigger", "tr", "t", "CREATE TRIGGER tr ..."), - listOf("view", "v", "v", "CREATE VIEW v AS ..."), + "SELECT type" to + QueryResult( + listOf("type", "name", "tbl_name", "sql"), + listOf( + listOf("index", "i1", "t", "CREATE INDEX i1 ON t(a)"), + listOf("table", "t", "t", "CREATE TABLE t(a)"), + listOf("trigger", "tr", "t", "CREATE TRIGGER tr ..."), + listOf("view", "v", "v", "CREATE VIEW v AS ..."), + ), + 0, + false, ), - 0, - false, - ), ) val r = ok("get_schema", db()) assertEquals("t", r.getJSONArray("tables").getJSONObject(0).getString("name")) @@ -235,7 +312,15 @@ class DatabaseToolsTest { @Test fun explainQueryPlanPrefixesTheSql() { engine.appConnections += conn(1, "/data/a.db") - answerWith("EXPLAIN QUERY PLAN" to QueryResult(listOf("id", "parent", "notused", "detail"), listOf(listOf(3L, 0L, 0L, "SCAN t")), 0, false)) + answerWith( + "EXPLAIN QUERY PLAN" to + QueryResult( + listOf("id", "parent", "notused", "detail"), + listOf(listOf(3L, 0L, 0L, "SCAN t")), + 0, + false, + ), + ) val plan = ok("explain_query_plan", db().put("sql", "select * from t")).getJSONArray("plan") assertEquals("SCAN t", plan.getJSONObject(0).getString("detail")) assertEquals("EXPLAIN QUERY PLAN select * from t", seenSql.single()) @@ -243,6 +328,7 @@ class DatabaseToolsTest { @Test fun getStatsCountsRowsUnderTenTables() { engine.appConnections += conn(1, "/data/a.db") + fun one(v: Long) = QueryResult(listOf("x"), listOf(listOf(v)), 0, false) answerWith( "PRAGMA page_count" to one(10), diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 9d705d3bda..ecad15a633 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -16,23 +16,39 @@ import java.net.Socket * HTTP side (token, Host and Origin checks, methods and paths), on a real loopback socket. */ class McpProtocolTest { - private var sessionNumber = 0 private val echo = McpTool("echo", "Echo", "Returns its arguments.") { args -> JSONObject().put("got", args) } - private val needsPerson = McpTool("needs_person", "Needs a person", "Always says a person is needed.", readOnly = false) { _ -> - throw McpToolError("A person is needed: tap Allow on the sharing phone.", JSONObject().put("person_needed", true)) - } + private val needsPerson = + McpTool("needs_person", "Needs a person", "Always says a person is needed.", readOnly = false) { _ -> + throw McpToolError("A person is needed: tap Allow on the sharing phone.", JSONObject().put("person_needed", true)) + } private val crashes = McpTool("crashes", "Crashes", "Throws an unexpected exception.") { _ -> throw IllegalStateException("boom") } private fun protocol(maxSessions: Int = 16) = McpProtocol(listOf(echo, needsPerson, crashes), "test", { "s${++sessionNumber}" }, maxSessions) - private fun initBody(version: String = "2025-06-18") = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "initialize") - .put("params", JSONObject().put("protocolVersion", version).put("capabilities", JSONObject()) - .put("clientInfo", JSONObject().put("name", "test").put("version", "1"))).toString() - - private fun request(id: Any, method: String, params: JSONObject? = null) = JSONObject().put("jsonrpc", "2.0").put("id", id) - .put("method", method).also { if (params != null) it.put("params", params) } + private fun initBody(version: String = "2025-06-18") = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 1) + .put("method", "initialize") + .put( + "params", + JSONObject() + .put("protocolVersion", version) + .put("capabilities", JSONObject()) + .put("clientInfo", JSONObject().put("name", "test").put("version", "1")), + ).toString() + + private fun request( + id: Any, + method: String, + params: JSONObject? = null, + ) = JSONObject() + .put("jsonrpc", "2.0") + .put("id", id) + .put("method", method) + .also { if (params != null) it.put("params", params) } private fun session(p: McpProtocol): String { val r = p.post(initBody(), null, null) @@ -40,7 +56,12 @@ class McpProtocolTest { return r.headers[McpProtocol.SESSION_HEADER]!! } - private fun call(p: McpProtocol, s: String, tool: String, args: JSONObject? = null): JSONObject { + private fun call( + p: McpProtocol, + s: String, + tool: String, + args: JSONObject? = null, + ): JSONObject { val params = JSONObject().put("name", tool).also { if (args != null) it.put("arguments", args) } val r = p.post(request(7, "tools/call", params).toString(), s, null) assertEquals(200, r.status) @@ -75,27 +96,31 @@ class McpProtocolTest { } @Test fun unsupportedVersionHeaderIsRefused() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) assertEquals(400, p.post(request(1, "ping").toString(), s, "1999-01-01").status) assertEquals(200, p.post(request(1, "ping").toString(), s, "2025-06-18").status) } @Test fun notificationsGetNoAnswer() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val r = p.post(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized").toString(), s, null) assertEquals(202, r.status) assertNull(r.body) } @Test fun pingAnswersEmptyResult() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val r = JSONObject(p.post(request("a", "ping").toString(), s, null).body!!) assertEquals("a", r.get("id")) assertEquals(0, r.getJSONObject("result").length()) } @Test fun toolsListDescribesEveryTool() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val tools = JSONObject(p.post(request(2, "tools/list").toString(), s, null).body!!).getJSONObject("result").getJSONArray("tools") val names = (0 until tools.length()).map { tools.getJSONObject(it).getString("name") } assertEquals(listOf("echo", "needs_person", "crashes"), names) @@ -106,7 +131,8 @@ class McpProtocolTest { } @Test fun toolCallReturnsStructuredContent() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val result = call(p, s, "echo", JSONObject().put("x", 3)).getJSONObject("result") assertFalse(result.getBoolean("isError")) assertEquals(3, result.getJSONObject("structuredContent").getJSONObject("got").getInt("x")) @@ -114,35 +140,52 @@ class McpProtocolTest { } @Test fun toolCallWithoutArgumentsGetsEmptyObject() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val got = call(p, s, "echo").getJSONObject("result").getJSONObject("structuredContent").getJSONObject("got") assertEquals(0, got.length()) } @Test fun toolErrorIsAResultWithIsError() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val result = call(p, s, "needs_person").getJSONObject("result") assertTrue(result.getBoolean("isError")) - assertTrue(result.getJSONArray("content").getJSONObject(0).getString("text").contains("person is needed")) + assertTrue( + result + .getJSONArray("content") + .getJSONObject(0) + .getString("text") + .contains("person is needed"), + ) assertTrue(result.getJSONObject("structuredContent").getBoolean("person_needed")) } @Test fun unexpectedExceptionIsAResultWithIsError() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val result = call(p, s, "crashes").getJSONObject("result") assertTrue(result.getBoolean("isError")) - assertTrue(result.getJSONArray("content").getJSONObject(0).getString("text").contains("boom")) + assertTrue( + result + .getJSONArray("content") + .getJSONObject(0) + .getString("text") + .contains("boom"), + ) } @Test fun unknownToolAndBadArgumentsAreInvalidParams() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) assertEquals(McpProtocol.INVALID_PARAMS, call(p, s, "nope").getJSONObject("error").getInt("code")) val bad = request(3, "tools/call", JSONObject().put("name", "echo").put("arguments", JSONArray())).toString() assertEquals(McpProtocol.INVALID_PARAMS, JSONObject(p.post(bad, s, null).body!!).getJSONObject("error").getInt("code")) } @Test fun unknownMethodIsMethodNotFound() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) val r = JSONObject(p.post(request(4, "resources/list").toString(), s, null).body!!) assertEquals(McpProtocol.METHOD_NOT_FOUND, r.getJSONObject("error").getInt("code")) } @@ -154,8 +197,13 @@ class McpProtocolTest { } @Test fun batchGetsAnArrayOfReplies() { - val p = protocol(); val s = session(p) - val batch = JSONArray().put(request(1, "ping")).put(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/x")).put(request(2, "tools/list")) + val p = protocol() + val s = session(p) + val batch = + JSONArray() + .put(request(1, "ping")) + .put(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/x")) + .put(request(2, "tools/list")) val r = p.post(batch.toString(), s, null) assertEquals(200, r.status) val replies = JSONArray(r.body!!) @@ -170,7 +218,8 @@ class McpProtocolTest { } @Test fun deleteEndsTheSession() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) assertEquals(204, p.delete(s).status) assertEquals(404, p.delete(s).status) assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) @@ -178,9 +227,10 @@ class McpProtocolTest { @Test fun oldestSessionIsDroppedBeyondTheLimit() { val p = protocol(maxSessions = 2) - val a = session(p); val b = session(p) - p.post(request(1, "ping").toString(), a, null) // a is now the most recently used - val c = session(p) // drops b + val a = session(p) + val b = session(p) + p.post(request(1, "ping").toString(), a, null) // a is now the most recently used + val c = session(p) // drops b assertEquals(2, p.sessionCount()) assertEquals(200, p.post(request(1, "ping").toString(), a, null).status) assertEquals(404, p.post(request(1, "ping").toString(), b, null).status) @@ -188,7 +238,8 @@ class McpProtocolTest { } @Test fun endAllEndsEverySession() { - val p = protocol(); val s = session(p) + val p = protocol() + val s = session(p) p.endAll() assertEquals(0, p.sessionCount()) assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) @@ -199,7 +250,10 @@ class McpProtocolTest { private val token = "secret-token" private var server: McpHttp? = null - @After fun stopServer() { server?.stop(); server = null } + @After fun stopServer() { + server?.stop() + server = null + } private fun startServer(): Int { val s = McpHttp(protocol(), { token }, port = 0) @@ -208,20 +262,43 @@ class McpProtocolTest { return s.boundPort } - private class Answer(val status: Int, val headers: Map, val body: String) + private class Answer( + val status: Int, + val headers: Map, + val body: String, + ) /** One request on its own connection; [headers] may replace Host. */ - private fun http(port: Int, method: String, path: String = McpHttp.PATH, headers: Map = emptyMap(), body: String? = null): Answer { + private fun http( + port: Int, + method: String, + path: String = McpHttp.PATH, + headers: Map = emptyMap(), + body: String? = null, + ): Answer { Socket("127.0.0.1", port).use { s -> s.soTimeout = 5000 val bytes = body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) val all = linkedMapOf("Host" to "127.0.0.1:$port", "Connection" to "close") all.putAll(headers) - if (body != null) { all["Content-Type"] = "application/json"; all["Content-Length"] = bytes.size.toString() } + if (body != null) { + all["Content-Type"] = "application/json" + all["Content-Length"] = bytes.size.toString() + } val head = StringBuilder("$method $path HTTP/1.1\r\n") - for ((k, v) in all) head.append(k).append(": ").append(v).append("\r\n") + for ((k, v) in all) { + head + .append(k) + .append(": ") + .append(v) + .append("\r\n") + } head.append("\r\n") - s.getOutputStream().apply { write(head.toString().toByteArray(Charsets.ISO_8859_1)); write(bytes); flush() } + s.getOutputStream().apply { + write(head.toString().toByteArray(Charsets.ISO_8859_1)) + write(bytes) + flush() + } val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) val lines = text.substringBefore("\r\n\r\n").split("\r\n") val status = lines[0].split(' ')[1].toInt() @@ -242,8 +319,19 @@ class McpProtocolTest { @Test fun base64MatchesTheJdkEncoder() { for (n in 0..40) { val bytes = ByteArray(n) { (it * 37 + 250).toByte() } - assertEquals(java.util.Base64.getEncoder().encodeToString(bytes), McpHttp.base64(bytes, urlSafe = false, pad = true)) - assertEquals(java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes), McpHttp.base64(bytes, urlSafe = true, pad = false)) + assertEquals( + java.util.Base64 + .getEncoder() + .encodeToString(bytes), + McpHttp.base64(bytes, urlSafe = false, pad = true), + ) + assertEquals( + java.util.Base64 + .getUrlEncoder() + .withoutPadding() + .encodeToString(bytes), + McpHttp.base64(bytes, urlSafe = true, pad = false), + ) } } @@ -263,7 +351,9 @@ class McpProtocolTest { val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) assertTrue(text.startsWith("HTTP/1.1 503")) } - } finally { held.forEach { it.close() } } + } finally { + held.forEach { it.close() } + } } @Test fun httpNeedsTheToken() { @@ -315,8 +405,12 @@ class McpProtocolTest { val port = startServer() Socket("127.0.0.1", port).use { s -> val body = initBody().toByteArray() - s.getOutputStream().write(("POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer $token\r\nConnection: close\r\n" + - "Content-Type: text/plain\r\nContent-Length: ${body.size}\r\n\r\n").toByteArray() + body) + s.getOutputStream().write( + ( + "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer $token\r\nConnection: close\r\n" + + "Content-Type: text/plain\r\nContent-Length: ${body.size}\r\n\r\n" + ).toByteArray() + body, + ) val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) assertTrue(text.startsWith("HTTP/1.1 415")) } From 16a006fe603e6f9d7a6d7a836ee5acf89b42fd18 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:07:48 +0000 Subject: [PATCH 031/203] ADFA-7135 Fix three review findings in the extension - read_events moves the cursor past dropped events when it copies nothing, so a drop is reported once. - An internal failure in sqlitedbg_extension_init is logged and the connection left untracked; the app's own sqlite3_open no longer fails because of it. - A trigger is told apart from app SQL by X differing from sqlite3_sql(P), not by a "--" prefix, so statements that start with a comment are expanded. test.sh builds the extension with SQLITEDBG_TEST for the failure hook. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 45 ++++++++++++++-- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 4 +- .../src/test/c/sqlitedbg_test.c | 53 +++++++++++++++++++ subprojects/sqlite-debugger/test.sh | 2 +- 4 files changed, 97 insertions(+), 7 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 1442df0990..6e3f0f78f8 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -173,9 +173,15 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { if (is_stmt) sql = (const char *)x; else sql = sqlite3_sql(stmt); if (!sql) sql = ""; - // A trigger's text starts with "--" and P is the outer statement, whose expansion would - // be the wrong text. - if (__atomic_load_n(&g_client_connected, __ATOMIC_RELAXED) && !(sql[0] == '-' && sql[1] == '-')) { + // For a trigger, X is its own "-- ..." text while P is the outer statement, whose expansion + // would be the wrong text. For the statement itself X is its SQL. Not a prefix test: app SQL + // may start with a comment. + int is_trigger = 0; + if (is_stmt) { + const char *own = sqlite3_sql(stmt); + is_trigger = !own || strcmp(own, sql) != 0; + } + if (__atomic_load_n(&g_client_connected, __ATOMIC_RELAXED) && !is_trigger) { expanded = sqlite3_expanded_sql(stmt); if (expanded) { sql = expanded; @@ -218,9 +224,24 @@ static void connection_id_fn(sqlite3_context *ctx, int argc, sqlite3_value **arg sqlite3_result_int64(ctx, (sqlite3_int64)((conn_state *)sqlite3_user_data(ctx))->id); } +#ifdef SQLITEDBG_TEST +// Host tests: 1 fails the allocation, 2 makes registering the function fail. +int sqlitedbg_test_fail_init; +#endif + +static int init_connection(sqlite3 *db, const sqlite3_api_routines *api); + +// An internal failure must never fail the app's own sqlite3_open: log it and leave the connection +// untracked. int sqlitedbg_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines *api) { (void)err; if (tls_opening_server) return SQLITE_OK; + int rc = init_connection(db, api); + if (rc != SQLITE_OK) sqlite3_log(rc, "sqlitedbg: connection not tracked (%d)", rc); + return SQLITE_OK; +} + +static int init_connection(sqlite3 *db, const sqlite3_api_routines *api) { pthread_mutex_lock(&g_lock); if (!g_api_ready) { @@ -230,6 +251,12 @@ int sqlitedbg_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines pthread_mutex_unlock(&g_lock); conn_state *cs = (conn_state *)calloc(1, sizeof *cs); +#ifdef SQLITEDBG_TEST + if (sqlitedbg_test_fail_init == 1) { + free(cs); + cs = NULL; + } +#endif if (!cs) return SQLITE_NOMEM; const char *filename = sqlite3_db_filename(db, "main"); cs->path = strdup(filename ? filename : ""); @@ -250,7 +277,11 @@ int sqlitedbg_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines pthread_mutex_unlock(&g_lock); // On failure SQLite has already called conn_destroy, so cs is gone. - int rc = sqlite3_create_function_v2(db, "sqlitedbg_connection_id", 0, SQLITE_UTF8 | SQLITE_INNOCUOUS, cs, + const char *fn_name = "sqlitedbg_connection_id"; +#ifdef SQLITEDBG_TEST + if (sqlitedbg_test_fail_init == 2) fn_name = NULL; // SQLite refuses a NULL name +#endif + int rc = sqlite3_create_function_v2(db, fn_name, 0, SQLITE_UTF8 | SQLITE_INNOCUOUS, cs, connection_id_fn, NULL, NULL, conn_destroy); if (rc != SQLITE_OK) return rc; return sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_CLOSE, trace_cb, cs); @@ -322,7 +353,11 @@ void sqlitedbg_read_events(uint64_t after, void *out, size_t out_bytes, sqlitedb pthread_mutex_lock(&g_lock); if (g_ring) { uint64_t oldest = oldest_seq(); - if (oldest > after && oldest - after > 1) result->dropped = oldest - after - 1; + if (oldest > after && oldest - after > 1) { + result->dropped = oldest - after - 1; + // Past the dropped events, so they are reported once even if nothing is copied below. + result->next = oldest - 1; + } size_t offset = g_tail, left = g_used; while (left > 0) { const sqlitedbg_event_record *r = record_at(offset); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 2153afaa05..5a40fd7877 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -109,7 +109,9 @@ typedef struct sqlitedbg_event_record { } sqlitedbg_event_record; // 56 bytes; the SQL text follows typedef struct sqlitedbg_read_result { - // The seq of the last event copied out, or `after` if none was: pass it as `after` next time. + // The seq of the last event copied out, or if none was, `after` moved past any dropped events + // (so they are reported once): pass it as `after` next time. A record too big for out is not + // passed. uint64_t next; // Events after `after` that left the buffer before they could be read. uint64_t dropped; diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index f2efe08d7a..d2606e6997 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -181,6 +181,8 @@ static uint64_t conn_id_of(sqlite3 *db) { // Tests +extern int sqlitedbg_test_fail_init; // sqlitedbg.c, built with SQLITEDBG_TEST + static sqlitedbg_config g_config = {BUFFER_BYTES, MAX_SQL}; static sqlite3 *g_main; @@ -295,6 +297,20 @@ static void test_expanded(void) { CHECK(b.events[3].flags & SQLITEDBG_EVENT_EXPANDED); batch_free(&b); + // app SQL that starts with a comment is not a trigger: it is expanded like any other + cur = cursor_now(); + sqlitedbg_set_client_connected(1); + CHECK_EQ(sqlite3_prepare_v2(g_main, "-- note\nINSERT INTO t VALUES(?)", -1, &st, NULL), SQLITE_OK); + sqlite3_bind_int(st, 1, 9); + CHECK_EQ(sqlite3_step(st), SQLITE_DONE); + sqlite3_finalize(st); + sqlitedbg_set_client_connected(0); + read_all(cur, &b); + CHECK(b.count >= 2); + CHECK(strstr(b.events[0].sql, "INSERT INTO t VALUES(9)") != NULL); + CHECK(b.events[0].flags & SQLITEDBG_EVENT_EXPANDED); + batch_free(&b); + // after the client leaves, the bound value is not written in again cur = cursor_now(); CHECK_EQ(sqlite3_prepare_v2(g_main, "INSERT INTO t VALUES(?)", -1, &st, NULL), SQLITE_OK); @@ -390,8 +406,25 @@ static void test_burst(void) { CHECK_EQ(b.events[0].seq, cur + made - b.count + 1); CHECK_EQ(b.events[b.count - 1].seq, cur + made); for (size_t i = 1; i < b.count; i++) CHECK_EQ(b.events[i].seq, b.events[i - 1].seq + 1); + const uint64_t first_seq = b.events[0].seq; + const size_t stored = b.count; batch_free(&b); + // drops are reported once even when nothing is copied: a record too big for out stays + // unpassed, and the cursor moves up to it + { + sqlitedbg_read_result r; + char tiny[8]; + sqlitedbg_read_events(cur, tiny, sizeof tiny, &r); + CHECK_EQ(r.count, 0); + CHECK_EQ(r.dropped, made - stored); + CHECK_EQ(r.next, first_seq - 1); + sqlitedbg_read_result again; + sqlitedbg_read_events(r.next, tiny, sizeof tiny, &again); + CHECK_EQ(again.dropped, 0); + CHECK_EQ(again.next, r.next); + } + // nothing is reported twice uint64_t next = cur + made; read_all(next, &b); @@ -482,6 +515,24 @@ static void test_close_and_list(void) { CHECK_EQ(list_conns(&l), before); } +static void test_init_failure(void) { + listing l; + size_t before = list_conns(&l); + for (int mode = 1; mode <= 2; mode++) { + sqlitedbg_test_fail_init = mode; + sqlite3 *db = NULL; + // the app's open must not fail because the debugger could not track the connection + CHECK_EQ(sqlite3_open(":memory:", &db), SQLITE_OK); + sqlitedbg_test_fail_init = 0; + CHECK(db != NULL); + if (!db) continue; + CHECK_EQ(list_conns(&l), before); + exec_ok(db, "CREATE TABLE u(a)"); + CHECK_EQ(sqlite3_close(db), SQLITE_OK); + } + CHECK_EQ(list_conns(&l), before); +} + static int step_all(sqlite3 *db, const char *sql) { sqlite3_stmt *st; int rc = sqlite3_prepare_v2(db, sql, -1, &st, NULL); @@ -825,6 +876,8 @@ int main(int argc, char **argv) { test_burst(); printf("# close and list\n"); test_close_and_list(); + printf("# init failure\n"); + test_init_failure(); printf("# server connections\n"); test_server(); printf("# threads\n"); diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh index 18b42811af..455dffa987 100755 --- a/subprojects/sqlite-debugger/test.sh +++ b/subprojects/sqlite-debugger/test.sh @@ -51,7 +51,7 @@ run_with () { mkdir "$WORK/$name" build gcc -O1 -g -w -fsanitize="$sanitize" "${DEFS[@]}" -I"$AMAL" -c "$AMAL/sqlite3.c" -o "$WORK/$name/sqlite3.o" build gcc -O1 -g -Wall -Wextra -Werror -fsanitize="$sanitize" -fno-sanitize-recover=all "${DEFS[@]}" \ - -I"$AMAL" -I"$CPP" "$CPP/sqlitedbg.c" "$HERE/src/test/c/sqlitedbg_test.c" "$WORK/$name/sqlite3.o" \ + -DSQLITEDBG_TEST -I"$AMAL" -I"$CPP" "$CPP/sqlitedbg.c" "$HERE/src/test/c/sqlitedbg_test.c" "$WORK/$name/sqlite3.o" \ -o "$WORK/$name/test" -lpthread -ldl -lm TSAN_OPTIONS=halt_on_error=1 "$WORK/$name/test" ${3:+"${@:3}"} } From f03521dc2a03b684333c89e37d7ee9510ea06e96 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:20:10 +0000 Subject: [PATCH 032/203] ADFA-7136: Document the SQLite debugger module Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- ARCHITECTURE.md | 1 + subprojects/sqlite-debugger/README.md | 53 +++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 subprojects/sqlite-debugger/README.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b4046e491d..b83d711c35 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -108,6 +108,7 @@ These structural facts shape every module. Day-to-day build *commands* live in ` - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: sqlite-js vendored with our patches (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. +- **SQLite debugger for apps built with CoGo** (ADFA-7131). `subprojects:sqlite-debugger` builds an AAR with a debug-only SQLite debugger and MCP server for apps built with CoGo: a native extension on requery's SQLite plus a loopback HTTP server. Like sqlite-js it has no ABI flavors, and nothing in CoGo depends on it; see its README. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). - **`app` package layout is by concern, not feature:** `activities`, `fragments`, `services`, `di`, `agent`, `viewmodel(s)`, `repositories`, `roomData`, `localWebServer`, `preferences`, `ui` (Compose screens live under `ui/compose`), `templates/manager` (the Manager screen's `.cgt`-parsing data layer, with direct filesystem access to `Environment.TEMPLATES_DIR` — distinct from the plugin-facing `IdeTemplateService` in `plugin-api`/`plugin-manager`), `utils`, …. diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md new file mode 100644 index 0000000000..406bcd17ab --- /dev/null +++ b/subprojects/sqlite-debugger/README.md @@ -0,0 +1,53 @@ +# SQLite debugger for apps + +A debug-only SQLite debugger and MCP server that runs inside apps built with Code on the Go (ADFA-7131). It lets an AI agent list an app's databases, read their schema and rows, see the SQL the app runs, and check integrity, all read-only. Phase 1 is the native extension (ADFA-7135) and the server (ADFA-7136). Nothing in CoGo itself depends on it: apps do, in debug builds. + +The module builds an AAR with `libsqlitedbg.so` for arm64-v8a and armeabi-v7a in one artifact, so it has no v7/v8 flavors (`AndroidModuleConf`). Its minSdk is 21, requery's, because the debugger runs on requery's SQLite. The unit test task is `:subprojects:sqlite-debugger:testDebugUnitTest`. + +## How it fits together + +``` +MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> DebugEngine + | + NativeDebugEngine -> NativeBridge (JNI) + | + sqlitedbg_jni.c -> sqlitedbg.c (sqlitedbg.h) + | + requery's libsqlite3x.so (the app's SQLite) +``` + +- `src/main/cpp/sqlitedbg.h` is the contract between the extension, its JNI layer and its host tests, with the semantics of each call. `SQLITEDBG_INTERFACE_VERSION` is raised when anything in it changes shape. +- `sqlitedbg.c` is a SQLite extension. `sqlitedbg_install` registers it with `sqlite3_auto_extension`, so it runs on every connection the app opens afterwards. It keeps the list of app connections and a ring buffer of statement events (trace: statement, profile, close), and opens connections for the server (`sqlitedbg_open_server`). +- `sqlitedbg_jni.c` finds `sqlite3_auto_extension` in requery's `libsqlite3x.so` with `dlopen(RTLD_NOLOAD)` and `dlsym`, so no SQLite is compiled or linked here (CMake takes only the headers from `../sqlite-js/upstream/libs`). Its version script exports only `JNI_OnLoad`; the functions of `NativeBridge` are registered there by name, and `consumer-rules.pro` keeps them. +- `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. +- `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. +- `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It starts the engine and the server on a background thread. + +### The event record + +The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer hands the bytes to Kotlin unchanged, so `EventDecoder.kt` mirrors the layout, field offsets included: change both together. A committed fixture pins them (see Testing). + +## Decisions that shape it + +- **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. +- **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. It opens no event stream: GET gets 405. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes. Anyone holding the token can still run SQL, so the token is the boundary. +- **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. +- **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. +- **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. + +## Testing + +- **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. +- **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. +- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol` and `DatabaseTools` (with `FakeDebugEngine`). + +No workflow in `.github/workflows` runs either yet. + +## Not done yet + +- Broadcasting the port and token to Code on the Go (ADFA-7137). `DebuggerStartup` only keeps them in `DebuggerStartup.port` and `endpointToken` and logs the port, never the token. +- Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138). +- The AI-Agent-MCP side that connects to the server (ADFA-7139). +- Verification on a device. The C tests run on the host and the Kotlin tests on the JVM; nothing has run in an app on a device or emulator. From e21aae35a83ac43c4d159b107ac8063bff9fe95c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:20:32 +0000 Subject: [PATCH 033/203] ADFA-7136: List sqlite-debugger among the modules without ABI flavors AndroidModuleConf.kt already excludes it; ARCHITECTURE.md and CLAUDE.md named only plugin-api and sqlite-js. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- ARCHITECTURE.md | 4 ++-- CLAUDE.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b83d711c35..e8247b2966 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -95,7 +95,7 @@ Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle buil - **`app` depends inward; libraries never depend on `app`.** Subsystems are consumed by `app`, not vice versa. - **Vendored forks are substituted, not imported ad hoc.** `composite-builds/build-deps` and `build-deps-common` provide forked `javac`/`jdt`/`layoutlib`/etc.; `settings.gradle.kts` substitutes them in for `com.itsaky.androidide.build:*`. Don't add a Maven coordinate for something already substituted. Pebble is likewise built from source, as `subprojects:pebble`, for a lexer fix Android needs (its `NOTICE` says what changed); depend on `projects.subprojects.pebble`, not `io.pebbletemplates:pebble`. -- **All module config flows through `composite-builds/build-logic`.** Every Android module gets the `v7`/`v8` ABI flavors centrally (`AndroidModuleConf.kt`) — there is no flavorless `assembleDebug`. `:plugin-api` and `:subprojects:sqlite-js`, libraries for other projects that need one artifact, are intentionally excluded from flavors. +- **All module config flows through `composite-builds/build-logic`.** Every Android module gets the `v7`/`v8` ABI flavors centrally (`AndroidModuleConf.kt`) — there is no flavorless `assembleDebug`. `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger`, libraries for other projects that need one artifact, are intentionally excluded from flavors. - **`RepositoriesMode.FAIL_ON_PROJECT_REPOS`** — repositories are declared once in `settings.gradle.kts`; modules must not declare their own. - **Avoid new dependencies.** Check `gradle/libs.versions.toml` first; the build almost certainly already has it. @@ -104,7 +104,7 @@ Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle buil These structural facts shape every module. Day-to-day build *commands* live in `CLAUDE.md`; the rules that produce them live here. - **Centralized convention logic.** All Android module setup flows through `composite-builds/build-logic` (`conf/AndroidModuleConf.kt`). Modules stay thin and share configuration, so understanding any module's setup starts here. -- **ABI product flavors.** Every Android module *except* `:plugin-api` and `:subprojects:sqlite-js` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. +- **ABI product flavors.** Every Android module *except* `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: sqlite-js vendored with our patches (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. diff --git a/CLAUDE.md b/CLAUDE.md index eaae5b3de6..7334588a8c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,7 +15,7 @@ flox activate -d flox/local -- ./gradlew ``` - **Debug APK (arm64, the usual target):** `flox activate -d flox/local -- ./gradlew :app:assembleV8Debug --parallel --max-workers=6` -- **Module unit tests:** `flox activate -d flox/local -- ./gradlew :editor:testV7DebugUnitTest` - unit tests are per-flavor, there is no plain `test` task. `:plugin-api` and `:subprojects:sqlite-js` are the modules without flavors: `:plugin-api:testDebugUnitTest`. +- **Module unit tests:** `flox activate -d flox/local -- ./gradlew :editor:testV7DebugUnitTest` - unit tests are per-flavor, there is no plain `test` task. `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger` are the modules without flavors: `:plugin-api:testDebugUnitTest`. - **Single unit test:** append `--tests "com.itsaky.androidide.SomeTest"` to the flavored task above. - **Fast iteration:** during multi-file/multi-module changes, verify with targeted `:module:compileV8DebugKotlin`/`compileV8DebugJavaWithJavac` invocations (batch several modules into one Gradle call) rather than a full assemble. Reserve `:app:assembleV8Debug` for final end-to-end verification — it's slow (multi-minute) in this multi-module project, and running it after every small change adds up. - **Long-running commands: narrate them, and background only the read-only ones.** Anything that can exceed ~60s — `assembleV8Debug`, a full test sweep, a cold Gradle invocation of any kind (daemon start plus configuring this many modules is ~20s before any task runs, and far worse under memory pressure), and `git push`, which runs Spotless through the hook — gets a line before it starts saying what is running and roughly how long it takes, and a status line every couple of minutes while it runs: elapsed time, the last output line, whether it is still progressing. A silent terminal is indistinguishable from a hang, and saying which it is is your job, not the user's to ask. @@ -26,7 +26,7 @@ When the user names a CI/CD job ("the sonar job", "the analyze workflow"), read ### ABI product flavors (v7 / v8) -Every module except `:plugin-api` and `:subprojects:sqlite-js` carries `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) flavors, so build tasks are `assembleV8Debug`, `assembleV7Release`, etc. — there is **no** flavorless `assembleDebug`. Those two build one artifact for other projects. See [ARCHITECTURE.md](ARCHITECTURE.md) (Build & Module Configuration) for flavors, native asset bundling, and SDK levels. +Every module except `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger` carries `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) flavors, so build tasks are `assembleV8Debug`, `assembleV7Release`, etc. — there is **no** flavorless `assembleDebug`. Those three build one artifact for other projects. See [ARCHITECTURE.md](ARCHITECTURE.md) (Build & Module Configuration) for flavors, native asset bundling, and SDK levels. ### Emulator / device From 8dd5efb4d9f4046461eedc2e2665618488f7b732 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:28:26 +0000 Subject: [PATCH 034/203] ADFA-7136 Never let the debugger crash or miss the host app's early connections - DebuggerStartup catches Throwable after the debuggable check, so a missing requery library (UnsatisfiedLinkError) disables the debugger instead of killing the app. The check itself still throws. - install() runs synchronously in onCreate; only the server start is on the thread, so connections opened in Application.onCreate are tracked. - McpHttp: connection and accept threads catch Throwable; an Error while handling a request is answered with a 500. - McpHttp: a failed accept sleeps 100 ms, doubling to 2 s while failures continue, and resets on success (no spin on EMFILE). Tests: an Error thrown by a tool gives HTTP 500 and the server keeps serving; a ServerSocket whose accept fails is retried with growing gaps, then serves. DebuggerStartup imports android.* and has no JVM test. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/DebuggerStartup.kt | 43 +++++++++++++------ .../sqlitedebugger/mcp/McpHttp.kt | 42 ++++++++++++++---- .../sqlitedebugger/mcp/McpProtocolTest.kt | 37 +++++++++++++++- 4 files changed, 99 insertions(+), 25 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 406bcd17ab..fbd8034fb4 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -21,7 +21,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `sqlitedbg_jni.c` finds `sqlite3_auto_extension` in requery's `libsqlite3x.so` with `dlopen(RTLD_NOLOAD)` and `dlsym`, so no SQLite is compiled or linked here (CMake takes only the headers from `../sqlite-js/upstream/libs`). Its version script exports only `JNI_OnLoad`; the functions of `NativeBridge` are registered there by name, and `consumer-rules.pro` keeps them. - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. -- `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It starts the engine and the server on a background thread. +- `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. ### The event record diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt index 30f7177dad..a2605df810 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt @@ -26,25 +26,40 @@ class DebuggerStartup : ContentProvider() { "The SQLite debugger is in a build that is not debuggable. Remove it from release builds." } val databaseDir = File(context.applicationInfo.dataDir, "databases") - thread(name = "sqlite-debugger-start", isDaemon = true) { - try { - val engine = NativeDebugEngine() - engine.install() - val tools = DatabaseTools(engine, databaseDir) - val token = McpHttp.newToken() - val protocol = McpProtocol(tools.tools(), "1", { UUID.randomUUID().toString() }) - val http = McpHttp(protocol, { token }, log = { Log.w(TAG, it) }) - http.start() - port = http.boundPort - endpointToken = token - Log.i(TAG, "listening on 127.0.0.1:${http.boundPort}") - } catch (e: Exception) { - Log.e(TAG, "could not start", e) + // Throwable, not Exception: a missing library is an UnsatisfiedLinkError, and an Error that + // escapes here kills the host app. A debugger that cannot start is disabled, never a crash. + try { + // Synchronous: an app that opens its database in Application.onCreate or another + // provider would otherwise be missed. + val engine = NativeDebugEngine() + engine.install() + thread(name = "sqlite-debugger-start", isDaemon = true) { + try { + startServer(engine, databaseDir) + } catch (t: Throwable) { + Log.e(TAG, "could not start the server", t) + } } + } catch (t: Throwable) { + Log.e(TAG, "the SQLite debugger is disabled", t) } return true } + private fun startServer( + engine: NativeDebugEngine, + databaseDir: File, + ) { + val tools = DatabaseTools(engine, databaseDir) + val token = McpHttp.newToken() + val protocol = McpProtocol(tools.tools(), "1", { UUID.randomUUID().toString() }) + val http = McpHttp(protocol, { token }, log = { Log.w(TAG, it) }) + http.start() + port = http.boundPort + endpointToken = token + Log.i(TAG, "listening on 127.0.0.1:${http.boundPort}") + } + override fun query( uri: Uri, projection: Array?, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index f29b5acad3..ef1028cc7f 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -39,6 +39,8 @@ class McpHttp( private val port: Int = 0, /** Problems worth a line in the log. Never given the token. */ private val log: (String) -> Unit = {}, + /** Creates the listening socket; tests pass one whose accept fails. */ + private val socketFactory: () -> ServerSocket = { ServerSocket() }, ) { companion object { private const val B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" @@ -83,6 +85,10 @@ class McpHttp( /** A connection with no request for this long is closed. */ const val IDLE_TIMEOUT_MS = 30_000 + + /** After a failed accept the loop sleeps this long, doubling up to the maximum while failures continue. */ + const val ACCEPT_BACKOFF_MIN_MS = 100L + const val ACCEPT_BACKOFF_MAX_MS = 2_000L private val STATUS = mapOf( 200 to "OK", @@ -127,7 +133,7 @@ class McpHttp( /** Binds 127.0.0.1:[port]. Throws IOException with a readable message if the port is taken. */ fun start() { - val s = ServerSocket() + val s = socketFactory() try { s.reuseAddress = true s.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), port), 16) @@ -156,12 +162,23 @@ class McpHttp( } private fun acceptLoop(s: ServerSocket) { + var backoffMs = 0L while (running && !s.isClosed) { val c = try { - s.accept() + s.accept().also { backoffMs = 0 } } catch (e: IOException) { - if (running && !s.isClosed) log("couldn't accept a connection: ${e.message}") + if (running && !s.isClosed) { + log("couldn't accept a connection: ${e.message}") + // A persistent failure (EMFILE) would otherwise spin; keep trying, slowly. + backoffMs = if (backoffMs == 0L) ACCEPT_BACKOFF_MIN_MS else minOf(backoffMs * 2, ACCEPT_BACKOFF_MAX_MS) + sleepQuietly(backoffMs) + } + continue + } catch (t: Throwable) { + log("accept failed: ${t.javaClass.simpleName}: ${t.message}") + backoffMs = if (backoffMs == 0L) ACCEPT_BACKOFF_MIN_MS else minOf(backoffMs * 2, ACCEPT_BACKOFF_MAX_MS) + sleepQuietly(backoffMs) continue } if (!c.inetAddress.isLoopbackAddress) { @@ -184,8 +201,9 @@ class McpHttp( serve(c) } catch (ignored: IOException) { // The client went away. - } catch (e: Exception) { - log("a connection failed: ${e.javaClass.simpleName}: ${e.message}") + } catch (t: Throwable) { + // An Error here would kill the host app: log it and drop the connection. + log("a connection failed: ${t.javaClass.simpleName}: ${t.message}") } finally { clients -= c close(c) @@ -255,9 +273,9 @@ class McpHttp( if (type != null && type != "application/json") return send(415, rpcError("Send the request as application/json.")) try { protocol.post(String(r.body, Charsets.UTF_8), session, r.headers["mcp-protocol-version"]) - } catch (e: Exception) { - log("a request failed: ${e.javaClass.simpleName}: ${e.message}") - McpProtocol.Reply(500, rpcError("The server failed: ${e.message ?: e.javaClass.simpleName}")) + } catch (t: Throwable) { + log("a request failed: ${t.javaClass.simpleName}: ${t.message}") + McpProtocol.Reply(500, rpcError("The server failed: ${t.message ?: t.javaClass.simpleName}")) } } @@ -445,6 +463,14 @@ class McpHttp( .put("error", JSONObject().put("code", McpProtocol.INVALID_REQUEST).put("message", message)) .toString() + private fun sleepQuietly(ms: Long) { + try { + Thread.sleep(ms) + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + } + } + private fun close(s: Socket) { try { s.close() diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index ecad15a633..b6db250247 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -23,9 +23,10 @@ class McpProtocolTest { throw McpToolError("A person is needed: tap Allow on the sharing phone.", JSONObject().put("person_needed", true)) } private val crashes = McpTool("crashes", "Crashes", "Throws an unexpected exception.") { _ -> throw IllegalStateException("boom") } + private val linkFails = McpTool("link_fails", "Link fails", "Throws an Error.") { _ -> throw UnsatisfiedLinkError("no library") } private fun protocol(maxSessions: Int = 16) = - McpProtocol(listOf(echo, needsPerson, crashes), "test", { "s${++sessionNumber}" }, maxSessions) + McpProtocol(listOf(echo, needsPerson, crashes, linkFails), "test", { "s${++sessionNumber}" }, maxSessions) private fun initBody(version: String = "2025-06-18") = JSONObject() @@ -123,7 +124,7 @@ class McpProtocolTest { val s = session(p) val tools = JSONObject(p.post(request(2, "tools/list").toString(), s, null).body!!).getJSONObject("result").getJSONArray("tools") val names = (0 until tools.length()).map { tools.getJSONObject(it).getString("name") } - assertEquals(listOf("echo", "needs_person", "crashes"), names) + assertEquals(listOf("echo", "needs_person", "crashes", "link_fails"), names) val first = tools.getJSONObject(0) assertEquals("object", first.getJSONObject("inputSchema").getString("type")) assertTrue(first.getJSONObject("annotations").getBoolean("readOnlyHint")) @@ -416,6 +417,38 @@ class McpProtocolTest { } } + @Test fun httpAnErrorInAToolIsA500AndTheServerKeepsServing() { + val port = startServer() + val s = http(port, "POST", headers = auth, body = initBody()).headers["mcp-session-id"]!! + val params = JSONObject().put("name", "link_fails") + val r = http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = request(3, "tools/call", params).toString()) + assertEquals(500, r.status) + assertTrue(r.body, r.body.contains("no library")) + assertEquals(200, http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = request(4, "ping").toString()).status) + } + + @Test fun httpAcceptBacksOffAfterFailuresAndKeepsServing() { + val attempts = java.util.Collections.synchronizedList(mutableListOf()) + val failures = 4 + val flaky = + object : java.net.ServerSocket() { + override fun accept(): Socket { + attempts += System.nanoTime() + if (attempts.size <= failures) throw java.io.IOException("Too many open files") + return super.accept() + } + } + val s = McpHttp(protocol(), { token }, port = 0, socketFactory = { flaky }) + s.start() + server = s + Thread.sleep(1_200) // 100 + 200 + 400 ms of sleeps, then the fourth failure sleeps 800 ms + // a spinning loop would have made thousands of attempts by now + assertTrue("attempts so far: ${attempts.size}", attempts.size in 4..6) + val gaps = attempts.zipWithNext { a, b -> (b - a) / 1_000_000 } + assertTrue("gaps $gaps", gaps[0] >= 90 && gaps[1] >= 190 && gaps[2] >= 390) + assertEquals(200, http(s.boundPort, "POST", headers = auth, body = initBody()).status) + } + @Test fun httpSessionThenDelete() { val port = startServer() val s = http(port, "POST", headers = auth, body = initBody()).headers["mcp-session-id"]!! From c862c5c2ae7dc090ca7469e9bba9ac5864c05c9a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:31:33 +0000 Subject: [PATCH 035/203] ADFA-7135 Keep read-only server connections from holding locks The read-only authorizer allowed BEGIN, SAVEPOINT and PRAGMA locking_mode, so a client could hold a lock on the app's database: BEGIN; SELECT left the app's INSERT failing with SQLITE_BUSY until ROLLBACK. - sqlitedbg.c: deny SQLITE_TRANSACTION, SQLITE_SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout (any form) on read-only server connections. - sqlitedbg_jni.c: bridge_query rolls back if the connection is not in autocommit when it returns (covers writable connections). - Host C test: each denied statement returns SQLITE_AUTH and the app can still write after a read on that connection. Without the authorizer change the test fails on all 8 statements (BEGIN and SAVEPOINT: "database is locked" for the app's INSERT). The backstop is tested with the JNI test. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 6 +++ .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 3 +- .../src/main/cpp/sqlitedbg_jni.c | 3 ++ .../src/test/c/sqlitedbg_test.c | 41 +++++++++++++++++++ 5 files changed, 53 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index fbd8034fb4..1cfc9e69f2 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -31,7 +31,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database; the JNI query path also rolls back any transaction left open. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 6e3f0f78f8..929be274a2 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -414,11 +414,17 @@ static int server_authorizer(void *unused, int action, const char *a1, const cha case SQLITE_ANALYZE: case SQLITE_ATTACH: case SQLITE_DETACH: + // A client could open a transaction or savepoint and hold a lock on the app's database. + case SQLITE_TRANSACTION: + case SQLITE_SAVEPOINT: return SQLITE_DENY; case SQLITE_PRAGMA: // PRAGMA query_only=0 would lift the guard, and a PRAGMA that stores a value writes. // PRAGMA table_info(t) also has a second argument, so only these names are checked. + // locking_mode=EXCLUSIVE keeps the lock after a read, and busy_timeout (any form) lets a + // statement wait on the app's lock for as long as the client likes. if (a1 && (sqlite3_stricmp(a1, "query_only") == 0 || sqlite3_stricmp(a1, "writable_schema") == 0 || + sqlite3_stricmp(a1, "locking_mode") == 0 || sqlite3_stricmp(a1, "busy_timeout") == 0 || sqlite3_stricmp(a1, "wal_checkpoint") == 0 || sqlite3_stricmp(a1, "incremental_vacuum") == 0 || sqlite3_stricmp(a1, "optimize") == 0)) return SQLITE_DENY; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 5a40fd7877..d87890daa0 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -135,7 +135,8 @@ void sqlitedbg_set_client_connected(int connected); // Opens path for the server with the same SQLite the app uses: SQLITE_OPEN_READONLY unless // writable, PRAGMA query_only when read-only, and an authorizer that refuses ordinary writes when -// read-only. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, +// read-only, and also BEGIN, SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout: a client must not +// be able to hold a lock on the app's database. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, // D11). Never traced and never listed. The caller owns *db and closes it with sqlite3_close_v2. // A server connection, unlike an app connection, may use a progress handler (for time limits). // Returns SQLITE_MISUSE before any app connection has opened (the extension then has no SQLite diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index d5fede7078..7793e2e277 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -377,6 +377,9 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); sqlite3_finalize(st); + // Backstop: a transaction left open (a writable connection, or a way past the authorizer) + // would hold a lock on the app's database until the next query. + if (sqlite3_get_autocommit(db) == 0) sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL); return result; } diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index d2606e6997..bcb1c8460d 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -608,6 +608,45 @@ static void test_server(void) { CHECK_EQ(sqlite3_close(app), SQLITE_OK); } +// Each of these would let a client keep a lock on the app's database (ADFA-7135 review, H3). +static void test_server_holds_no_locks(void) { + static const char *const denied[] = { + "BEGIN", + "BEGIN IMMEDIATE", + "BEGIN EXCLUSIVE", + "SAVEPOINT s", + "PRAGMA locking_mode=EXCLUSIVE", + "PRAGMA locking_mode", + "PRAGMA busy_timeout=60000", + "PRAGMA busy_timeout", + }; + for (size_t i = 0; i < sizeof denied / sizeof denied[0]; i++) { + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_OK); + int rc = step_all(srv, denied[i]); + if (rc != SQLITE_AUTH) fprintf(stderr, "not refused: %s (%d)\n", denied[i], rc); + CHECK_EQ(rc, SQLITE_AUTH); + // a read on the same connection, then the app must still be able to write + CHECK_EQ(step_all(srv, "SELECT count(*) FROM t"), SQLITE_DONE); + char *err = NULL; + rc = sqlite3_exec(g_main, "INSERT INTO t VALUES(4242)", NULL, NULL, &err); + if (rc != SQLITE_OK) fprintf(stderr, "app write after \"%s\": %s\n", denied[i], err ? err : "?"); + sqlite3_free(err); + CHECK_EQ(rc, SQLITE_OK); + exec_ok(g_main, "DELETE FROM t WHERE a=4242"); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + } + + // an ordinary read leaves the server connection with no lock and in autocommit + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_OK); + CHECK_EQ(step_all(srv, "SELECT * FROM t"), SQLITE_DONE); + CHECK_EQ(sqlite3_get_autocommit(srv), 1); + exec_ok(g_main, "INSERT INTO t VALUES(4243)"); + exec_ok(g_main, "DELETE FROM t WHERE a=4243"); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); +} + typedef struct worker { int index; atomic_int *stop; @@ -880,6 +919,8 @@ int main(int argc, char **argv) { test_init_failure(); printf("# server connections\n"); test_server(); + printf("# server holds no locks\n"); + test_server_holds_no_locks(); printf("# threads\n"); test_threads(); if (argc == 4 && strcmp(argv[1], "--write-fixture") == 0) write_fixture(argv[2], argv[3]); From 05c2a2b018b3c3123f5601ede147214658d0c498 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:34:42 +0000 Subject: [PATCH 036/203] ADFA-7136 Bound query results and report truncation per cell - M4: QueryLimits.maxTotalBytes (DatabaseTools passes 4 MiB). bridge_query counts the TEXT/BLOB bytes kept and 8 per number, and stops with hasMore before the row that would pass the budget; the first row always goes in so a page makes progress. The tool result text is serialised compact: it was sent twice, pretty and as structuredContent. - L11: the engine reports cut cells (QueryResult.truncatedCellIndexes, row * columns + column) instead of DatabaseTools guessing from size >= limit, so a BLOB of exactly maxBlobBytes is no longer flagged. - L12: get_schema and get_stats read sqlite_master (sqlite_schema needs 3.33). - L13: sqlite3_column_text/blob returning NULL (out of memory) is checked. JVM tests: blob at the limit vs one byte over, the budget pages a result of 3 MiB rows, sqlite_master in the SQL sent, compact result text. Each fails with its fix reverted. The native side (budget, cut cells) is tested by the JNI test in a later commit; L13 has no test (needs an allocation failure). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 2 +- .../src/main/cpp/sqlitedbg_jni.c | 67 ++++++++++++++++--- .../sqlitedebugger/engine/DebugEngine.kt | 20 +++++- .../sqlitedebugger/engine/NativeBridge.kt | 4 +- .../engine/NativeDebugEngine.kt | 9 ++- .../sqlitedebugger/mcp/DatabaseTools.kt | 35 +++++----- .../sqlitedebugger/mcp/McpProtocol.kt | 2 +- .../sqlitedebugger/engine/FakeDebugEngine.kt | 34 +++++++++- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 36 +++++++++- .../sqlitedebugger/mcp/McpProtocolTest.kt | 9 +++ 10 files changed, 182 insertions(+), 36 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 1cfc9e69f2..efdae621c8 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does. -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 7793e2e277..7033766bd6 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -258,24 +258,40 @@ static int utf8_prefix(const unsigned char *s, int len, int max) { } // One cell as a Java object, or NULL for SQL NULL (or on failure, with an exception pending). -static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, jint max_blob, int *truncated) { +// *cut is set when a TEXT or BLOB was cut at its limit, and *bytes grows by what the cell costs the +// result: the TEXT or BLOB bytes kept, 8 for a number. +static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, jint max_blob, int *cut, + int64_t *bytes) { + *cut = 0; switch (sqlite3_column_type(st, col)) { case SQLITE_INTEGER: + *bytes += 8; return (*env)->CallStaticObjectMethod(env, g_long, g_long_value_of, (jlong)sqlite3_column_int64(st, col)); case SQLITE_FLOAT: + *bytes += 8; return (*env)->CallStaticObjectMethod(env, g_double, g_double_value_of, (jdouble)sqlite3_column_double(st, col)); case SQLITE_TEXT: { const unsigned char *text = sqlite3_column_text(st, col); + if (!text) { // out of memory + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return NULL; + } int len = sqlite3_column_bytes(st, col); int keep = utf8_prefix(text, len, max_text); - if (keep < len) (*truncated)++; + if (keep < len) *cut = 1; + *bytes += keep; return utf8_string(env, (const char *)text, keep); } case SQLITE_BLOB: { const void *blob = sqlite3_column_blob(st, col); int len = sqlite3_column_bytes(st, col); + if (!blob && len > 0) { // out of memory + throw_engine(env, SQLITE_NOMEM, "out of memory"); + return NULL; + } int keep = len > max_blob ? max_blob : len; - if (keep < len) (*truncated)++; + if (keep < len) *cut = 1; + *bytes += keep; jbyteArray array = (*env)->NewByteArray(env, keep); if (array && keep > 0) (*env)->SetByteArrayRegion(env, array, 0, keep, (const jbyte *)blob); return array; @@ -286,11 +302,13 @@ static jobject cell_value(JNIEnv *env, sqlite3_stmt *st, int col, jint max_text, } static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong offset, - jint max_rows, jint max_text, jint max_blob, jlong deadline_ms) { + jint max_rows, jint max_text, jint max_blob, jint max_total, jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; sqlite3_stmt *st = NULL; jobjectArray result = NULL; + jlong *cut_cells = NULL; // row * columns + column of each cut cell + size_t cut_n = 0, cut_cap = 0; deadline dl = {(int64_t)deadline_ms, 0}; int handler_set = 0; const char *message = NULL; @@ -333,7 +351,8 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring (*env)->DeleteLocalRef(env, s); } - int truncated = 0, has_more = 0, row_count = 0; + int has_more = 0, row_count = 0; + int64_t total = 0; jlong skipped = 0; while (st && (rc = sqlite3_step(st)) == SQLITE_ROW) { if (skipped < offset) { @@ -346,14 +365,39 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring } jobjectArray row = (*env)->NewObjectArray(env, ncols, g_object, NULL); if (!row) goto done; + int64_t row_bytes = 0; + size_t cut_before = cut_n; for (int c = 0; c < ncols; c++) { - jobject cell = cell_value(env, st, c, max_text, max_blob, &truncated); + int cut; + jobject cell = cell_value(env, st, c, max_text, max_blob, &cut, &row_bytes); if ((*env)->ExceptionCheck(env)) goto done; + if (cut) { + if (cut_n == cut_cap) { + size_t cap = cut_cap ? cut_cap * 2 : 16; + jlong *grown = realloc(cut_cells, cap * sizeof(jlong)); + if (!grown) { + throw_engine(env, SQLITE_NOMEM, "out of memory"); + goto done; + } + cut_cells = grown; + cut_cap = cap; + } + cut_cells[cut_n++] = (jlong)row_count * ncols + c; + } if (cell) { (*env)->SetObjectArrayElement(env, row, c, cell); (*env)->DeleteLocalRef(env, cell); } } + // The total bounds the host app's heap. The first row always goes in, so a page makes + // progress; one row is bounded by the per-cell limits. + if (row_count > 0 && total + row_bytes > max_total) { + (*env)->DeleteLocalRef(env, row); + cut_n = cut_before; + has_more = 1; + break; + } + total += row_bytes; (*env)->CallBooleanMethod(env, rows, g_list_add, row); (*env)->DeleteLocalRef(env, row); if ((*env)->ExceptionCheck(env)) goto done; @@ -365,11 +409,13 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring goto done; } - jlongArray counts = (*env)->NewLongArray(env, 2); + // {cut cell count, hasMore, then the index of each cut cell} + jlongArray counts = (*env)->NewLongArray(env, (jsize)(2 + cut_n)); result = counts ? (*env)->NewObjectArray(env, 3, g_object, NULL) : NULL; if (!result) goto done; - jlong values[2] = {truncated, has_more}; - (*env)->SetLongArrayRegion(env, counts, 0, 2, values); + jlong head[2] = {(jlong)cut_n, has_more}; + (*env)->SetLongArrayRegion(env, counts, 0, 2, head); + if (cut_n) (*env)->SetLongArrayRegion(env, counts, 2, (jsize)cut_n, cut_cells); (*env)->SetObjectArrayElement(env, result, 0, names); (*env)->SetObjectArrayElement(env, result, 1, rows); (*env)->SetObjectArrayElement(env, result, 2, counts); @@ -377,6 +423,7 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); sqlite3_finalize(st); + free(cut_cells); // Backstop: a transaction left open (a writable connection, or a way past the authorizer) // would hold a lock on the app's database until the next query. if (sqlite3_get_autocommit(db) == 0) sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL); @@ -413,7 +460,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"readEvents", "(J[B[J)V", (void *)bridge_read_events}, {"setClientConnected", "(Z)V", (void *)bridge_set_client_connected}, {"openServer", "([BZ)J", (void *)bridge_open_server}, - {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 65e476ad52..7aeabc53fa 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -112,6 +112,12 @@ data class QueryLimits( val maxTextBytes: Int, /** Longer BLOB values are cut and counted in [QueryResult.truncatedCells]. */ val maxBlobBytes: Int, + /** + * A bound on the cell bytes of one result, so a wide SELECT cannot exhaust the app's heap: the + * TEXT and BLOB bytes kept, plus 8 for each number. Rows are added until the next one would pass + * it; the rest is [QueryResult.hasMore]. The first row is always returned. + */ + val maxTotalBytes: Int, ) data class QueryResult( @@ -119,9 +125,19 @@ data class QueryResult( /** Each value is null, [Long], [Double], [String] or [ByteArray]. Doubles may be NaN or infinite. */ val rows: List>, val truncatedCells: Int, - /** More rows follow the last one returned. */ + /** More rows follow the last one returned: the row limit or [QueryLimits.maxTotalBytes] was reached. */ val hasMore: Boolean, -) + /** + * Which cells were cut, as `row * columns.size + column`: a BLOB of exactly [QueryLimits.maxBlobBytes] + * is whole and not listed, one byte more is. [truncatedCells] is its size. + */ + val truncatedCellIndexes: Set = emptySet(), +) { + fun isTruncated( + row: Int, + column: Int, + ) = (row.toLong() * columns.size + column) in truncatedCellIndexes +} class DebugEngineException( /** The SQLite result code, or [SQLITE_MISUSE] when no app connection has opened yet. */ diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 578ac83086..fa95abee7b 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -33,7 +33,8 @@ internal object NativeBridge { /** * `[Array, ArrayList>, LongArray]`: the column names, the rows, and - * `{truncatedCells, hasMore}`. Throws [DebugEngineException]. + * `{truncatedCells, hasMore, then the index of each cut cell}` (row * columns + column). + * Throws [DebugEngineException]. */ @JvmStatic external fun query( @@ -44,6 +45,7 @@ internal object NativeBridge { maxRows: Int, maxTextBytes: Int, maxBlobBytes: Int, + maxTotalBytes: Int, deadlineMillis: Long, ): Array diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index 00e95c20d1..f020c2d1e7 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -78,7 +78,9 @@ class NativeDebugEngine : DebugEngine { ): QueryResult { check(handle != 0L) { "the connection is closed" } require(offset >= 0) { "offset $offset is negative" } - require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0) { "bad limits $limits" } + require(limits.maxRows > 0 && limits.maxTextBytes >= 0 && limits.maxBlobBytes >= 0 && limits.maxTotalBytes > 0) { + "bad limits $limits" + } val result = NativeBridge.query( handle, @@ -88,6 +90,7 @@ class NativeDebugEngine : DebugEngine { limits.maxRows, limits.maxTextBytes, limits.maxBlobBytes, + limits.maxTotalBytes, deadlineMillis, ) @@ -97,7 +100,9 @@ class NativeDebugEngine : DebugEngine { @Suppress("UNCHECKED_CAST") val rows = (result[1] as List>).map { it.asList() } val counts = result[2] as LongArray - return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L) + val cut = HashSet() + for (i in 2 until counts.size) cut += counts[i] + return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L, truncatedCellIndexes = cut) } override fun close() { diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 2ff44ec868..53ebf6419a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -28,6 +28,9 @@ class DatabaseTools( const val MAX_TEXT_BYTES = 4096 const val MAX_BLOB_BYTES = 1024 + /** The most cell bytes one tool result holds (the engine's `maxTotalBytes`); the rest is paged. */ + const val MAX_TOTAL_BYTES = 4 * 1024 * 1024 + /** Below the client's 60 s limit on a tool call. */ const val DEADLINE_MS = 50_000L const val EVENT_BATCH_BYTES = 256 * 1024 @@ -41,7 +44,7 @@ class DatabaseTools( /** A SQLite value as JSON: org.json throws on NaN and infinities, and JSON numbers lose integers past 2^53. */ fun encodeValue( value: Any?, - maxBlobBytes: Int = MAX_BLOB_BYTES, + truncated: Boolean = false, ): Any = when (value) { null -> { @@ -73,8 +76,7 @@ class DatabaseTools( JSONObject() .put("base64", McpHttp.base64(value, urlSafe = false, pad = true)) .put("bytes", value.size) - // the engine cuts at the limit without saying how long the BLOB was - .put("truncated", value.size >= maxBlobBytes) + .put("truncated", truncated) } else -> { @@ -119,14 +121,15 @@ class DatabaseTools( tool( "get_schema", "Get schema", - "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_schema.", + "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_master.", databaseSchema(), ) { getSchema(it) }, tool( "query", "Run a query", "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + - "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. Use offset to page. " + + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. A result also stops at about " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true). Use offset to page. " + "$PAGING_NOTE Writes are refused.", databaseSchema( "sql" to prop("string", "The SQL statement."), @@ -235,10 +238,10 @@ class DatabaseTools( val result = run( args, - "SELECT type, name, tbl_name, sql FROM sqlite_schema ORDER BY type, name", + "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", emptyList(), 0, - QueryLimits(MAX_ROWS, 65536, MAX_BLOB_BYTES), + QueryLimits(MAX_ROWS, 65536, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) val groups = linkedMapOf("table" to JSONArray(), "index" to JSONArray(), "view" to JSONArray(), "trigger" to JSONArray()) for (row in result.rows) { @@ -257,7 +260,7 @@ class DatabaseTools( val sql = stringArg(args, "sql") val offset = intArg(args, "offset", 0, 0, Long.MAX_VALUE) val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() - val result = run(args, sql, bindArgs(args), offset, QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) + val result = run(args, sql, bindArgs(args), offset, QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val out = encodeResult(result, offset) out.put("note", PAGING_NOTE) return out @@ -270,13 +273,13 @@ class DatabaseTools( "EXPLAIN QUERY PLAN " + stringArg(args, "sql"), bindArgs(args), 0, - QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES), + QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) return JSONObject().put("plan", rowsAsObjects(result)) } private fun getStats(args: JSONObject): JSONObject { - val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES) + val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) val deadline = clock() + DEADLINE_MS val path = checkedPath(args) @@ -292,7 +295,7 @@ class DatabaseTools( val tables = runChecked( path, - "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", emptyList(), 0, limits, @@ -332,7 +335,7 @@ class DatabaseTools( else -> throw McpToolError("full must be true or false.") } val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" - val result = run(args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES)) + val result = run(args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } return JSONObject() .put("check", if (full) "integrity_check" else "quick_check") @@ -377,7 +380,9 @@ class DatabaseTools( offset: Long, ): JSONObject { val rows = JSONArray() - for (row in result.rows) rows.put(JSONArray().also { a -> row.forEach { a.put(encodeValue(it)) } }) + result.rows.forEachIndexed { r, row -> + rows.put(JSONArray().also { a -> row.forEachIndexed { c, v -> a.put(encodeValue(v, result.isTruncated(r, c))) } }) + } val out = JSONObject() .put("columns", JSONArray(result.columns)) @@ -392,9 +397,9 @@ class DatabaseTools( private fun rowsAsObjects(result: QueryResult): JSONArray { val arr = JSONArray() - for (row in result.rows) { + result.rows.forEachIndexed { r, row -> val o = JSONObject() - result.columns.forEachIndexed { i, c -> o.put(c, encodeValue(row[i])) } + result.columns.forEachIndexed { i, c -> o.put(c, encodeValue(row[i], result.isTruncated(r, i))) } arr.put(o) } return arr diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 6ee7c1b128..21ca3deaa9 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -199,7 +199,7 @@ class McpProtocol( val result = try { val out = tool.run(args) - JSONObject().put("content", JSONArray().put(text(out.toString(2)))).put("structuredContent", out).put("isError", false) + JSONObject().put("content", JSONArray().put(text(out.toString()))).put("structuredContent", out).put("isError", false) } catch (e: McpToolError) { JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> e.details?.let { r.put("structuredContent", it) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index e0b61ce460..ea815dbc2b 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -34,6 +34,14 @@ class FakeDebugEngine( /** Drops the [count] oldest buffered events, as a full native buffer would. */ fun dropOldest(count: Int) = repeat(count) { buffered.removeFirstOrNull() } + private fun cellBytes(value: Any?): Long = + when (value) { + is String -> value.toByteArray().size.toLong() + is ByteArray -> value.size.toLong() + is Long, is Int, is Double -> 8 + else -> 0 + } + override fun connections() = appConnections.toList() override fun readEvents( @@ -82,8 +90,30 @@ class FakeDebugEngine( ): QueryResult { check(!closed) { "closed" } val all = answer(path, writable, sql, args) - val rows = all.rows.drop(offset.toInt()) - return all.copy(rows = rows.take(limits.maxRows), hasMore = rows.size > limits.maxRows) + val skip = offset.toInt().coerceAtMost(all.rows.size) + val rest = all.rows.drop(skip) + // the native rule: the first row always goes in, then rows while the total stays within the budget + var taken = 0 + var total = 0L + for (row in rest) { + if (taken >= limits.maxRows) break + val bytes = row.sumOf { cellBytes(it) } + if (taken > 0 && total + bytes > limits.maxTotalBytes) break + total += bytes + taken++ + } + val columns = all.columns.size + val cut = + all.truncatedCellIndexes + .map { it - skip.toLong() * columns } + .filter { it >= 0 && it < taken.toLong() * columns } + .toSet() + return all.copy( + rows = rest.take(taken), + hasMore = rest.size > taken, + truncatedCells = if (all.truncatedCellIndexes.isEmpty()) all.truncatedCells else cut.size, + truncatedCellIndexes = cut, + ) } override fun close() { diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 702bc4c75f..87c63b9f4b 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -282,10 +282,39 @@ class DatabaseToolsTest { assertEquals(3, blob.getInt("bytes")) assertFalse(blob.getBoolean("truncated")) assertTrue(row.isNull(7)) - assertEquals(true, DatabaseTools.encodeValue(ByteArray(1024).also { }).let { (it as JSONObject).getBoolean("truncated") }) + assertEquals(true, (DatabaseTools.encodeValue(ByteArray(8), truncated = true) as JSONObject).getBoolean("truncated")) + assertEquals(false, (DatabaseTools.encodeValue(ByteArray(1024)) as JSONObject).getBoolean("truncated")) assertEquals(1.5, DatabaseTools.encodeValue(1.5)) } + @Test fun aBlobExactlyAtTheLimitIsNotTruncatedButOneByteMoreIs() { + engine.appConnections += conn(1, "/data/a.db") + val whole = ByteArray(DatabaseTools.MAX_BLOB_BYTES) + val cut = ByteArray(DatabaseTools.MAX_BLOB_BYTES) // the engine kept maxBlobBytes of a longer value + engine.answer = { _, _, _, _ -> + QueryResult(listOf("a", "b"), listOf(listOf(whole, cut)), 1, false, setOf(1L)) + } + val r = ok("query", db().put("sql", "x")) + val row = r.getJSONArray("rows").getJSONArray(0) + assertFalse(row.getJSONObject(0).getBoolean("truncated")) + assertTrue(row.getJSONObject(1).getBoolean("truncated")) + assertEquals(1, r.getInt("truncated_cells")) + } + + @Test fun aResultStopsAtTheTotalBudgetAndPages() { + engine.appConnections += conn(1, "/data/a.db") + val big = "x".repeat(3 * 1024 * 1024) + engine.answer = { _, _, _, _ -> QueryResult(listOf("v"), listOf(listOf(big), listOf(big), listOf(big)), 0, false) } + val r = ok("query", db().put("sql", "x")) + assertEquals(1, r.getInt("row_count")) + assertTrue(r.getBoolean("has_more")) + assertEquals(1, r.getInt("next_offset")) + val next = ok("query", db().put("sql", "x").put("offset", 1)) + assertEquals(1, next.getInt("row_count")) + assertEquals(2, next.getInt("next_offset")) + assertEquals(4 * 1024 * 1024, DatabaseTools.MAX_TOTAL_BYTES) + } + @Test fun getSchemaGroupsByType() { engine.appConnections += conn(1, "/data/a.db") answerWith( @@ -307,7 +336,8 @@ class DatabaseToolsTest { assertEquals("CREATE INDEX i1 ON t(a)", r.getJSONArray("indexes").getJSONObject(0).getString("sql")) assertEquals(1, r.getJSONArray("views").length()) assertEquals(1, r.getJSONArray("triggers").length()) - assertTrue(seenSql.single().contains("sqlite_schema")) + assertTrue(seenSql.single().contains("FROM sqlite_master")) + assertFalse(seenSql.single().contains("sqlite_schema")) // an alias that needs SQLite 3.33 } @Test fun explainQueryPlanPrefixesTheSql() { @@ -344,6 +374,8 @@ class DatabaseToolsTest { assertEquals(40960, r.getInt("size_bytes")) assertEquals(7, r.getJSONObject("row_counts").getInt("a\"b")) assertTrue(seenSql.contains("SELECT COUNT(*) FROM \"a\"\"b\"")) + assertTrue(seenSql.any { it.contains("FROM sqlite_master") }) + assertTrue(seenSql.none { it.contains("sqlite_schema") }) } @Test fun getStatsSkipsCountsFromTenTables() { diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index b6db250247..bb7b2c1e53 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -140,6 +140,15 @@ class McpProtocolTest { assertEquals("text", result.getJSONArray("content").getJSONObject(0).getString("type")) } + @Test fun toolResultTextIsCompactSoTheResultIsNotSentTwiceInFull() { + val p = protocol() + val s = session(p) + val result = call(p, s, "echo", JSONObject().put("x", 3)).getJSONObject("result") + val text = result.getJSONArray("content").getJSONObject(0).getString("text") + assertFalse(text, text.contains("\n")) + assertEquals(result.getJSONObject("structuredContent").toString(), text) + } + @Test fun toolCallWithoutArgumentsGetsEmptyObject() { val p = protocol() val s = session(p) From d309d28af6462f86d0926ed06bb6070b7c548e3a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:36:17 +0000 Subject: [PATCH 037/203] ADFA-7136 Drop stale server connections and stop expanding SQL when idle - M7: DatabaseTools cached a server connection per path forever, so after the app deleted and recreated its database the server read the old file. Each cached connection remembers the ids of the app connections to its path when it opened. Before each tool call it is closed and dropped when no live app connection has the path, or none of those ids is left. - L14: the first get_events turned on bound-value expansion until the server stopped, so every app statement was expanded twice forever. It now goes off 60 s after the last get_events call, checked on every tool call and by a daemon timer; the tool description says so. - L10 (one lock for all tool calls) is documented in the class KDoc. Tests: recreated database reopens (opened 2, closed 1), a connection survives while a seen app connection remains, a vanished path closes the cached one, and expansion stops after 60 s. Each fails with its fix reverted (expected 2 but was 1; expected 1 but was 0; "60 s after the last get_events"). Limit accepted: a database replaced in place while the same app connections stay open is not detected. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 91 ++++++++++++++++++- .../sqlitedebugger/engine/FakeDebugEngine.kt | 5 + .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 57 ++++++++++++ 4 files changed, 149 insertions(+), 6 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index efdae621c8..bd33b17f4c 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,7 +34,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database; the JNI query path also rolls back any transaction left open. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. -- **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does. +- **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). - **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 53ebf6419a..5bbed62ebf 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -1,5 +1,6 @@ package org.appdevforall.sqlitedebugger.mcp +import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException import org.appdevforall.sqlitedebugger.engine.QueryLimits @@ -8,6 +9,8 @@ import org.appdevforall.sqlitedebugger.engine.ServerConnection import org.json.JSONArray import org.json.JSONObject import java.io.File +import java.util.Timer +import java.util.TimerTask /** * The debugger's MCP tools, all read-only: they open server connections through [engine] with @@ -15,6 +18,10 @@ import java.io.File * names a database by the path one of the app's own connections has open; any other path is * refused before the engine is called (opening a file Android's SQLite has open, with the * extension's SQLite, can corrupt it). + * + * One lock guards the cached server connections and every query, so tool calls run one at a time: + * a slow query (up to [DEADLINE_MS]) makes the others wait. That is accepted: the debugger serves + * one agent, and a connection per call would open the app's file many times over. */ class DatabaseTools( private val engine: DebugEngine, @@ -36,6 +43,9 @@ class DatabaseTools( const val EVENT_BATCH_BYTES = 256 * 1024 const val MAX_TABLES_FOR_COUNTS = 10 + /** Bound values stop being recorded this long after the last get_events call. */ + const val EVENTS_IDLE_MS = 60_000L + private const val MAX_SAFE_INTEGER = 9007199254740992L // 2^53 private val SIDE_FILE_SUFFIXES = listOf("-wal", "-shm", "-journal") @@ -90,14 +100,24 @@ class DatabaseTools( } private val lock = Any() - private val serverConnections = HashMap() + private val serverConnections = HashMap() private var clientConnected = false + private var lastEventsCallMs = 0L + private var idleTimer: Timer? = null + + /** A server connection and the ids of the app connections to its path when it was opened. */ + private class CachedConnection( + val connection: ServerConnection, + val appConnectionIds: Set, + ) /** Closes the server connections and tells the engine no client is watching. Call when the server stops. */ fun onServerStopped() { synchronized(lock) { - serverConnections.values.forEach { runCatching { it.close() } } + serverConnections.values.forEach { runCatching { it.connection.close() } } serverConnections.clear() + idleTimer?.cancel() + idleTimer = null if (clientConnected) { clientConnected = false engine.setClientConnected(false) @@ -105,6 +125,35 @@ class DatabaseTools( } } + /** + * Stops recording bound values once [EVENTS_IDLE_MS] have passed since the last get_events call: + * expanding every statement costs memory, and nobody is reading. Checked on every tool call and + * by a timer, so it also happens when no call comes. + */ + fun expireIdleClient() { + synchronized(lock) { + if (clientConnected && clock() - lastEventsCallMs >= EVENTS_IDLE_MS) { + clientConnected = false + engine.setClientConnected(false) + } + } + } + + private fun scheduleIdleCheck() { + val timer = idleTimer ?: Timer("sqlite-debugger-idle", true).also { idleTimer = it } + timer.schedule( + object : TimerTask() { + override fun run() { + expireIdleClient() + synchronized(lock) { + if (clientConnected && idleTimer === timer) scheduleIdleCheck() + } + } + }, + EVENTS_IDLE_MS / 4, + ) + } + fun tools(): List = listOf( tool( @@ -167,7 +216,8 @@ class DatabaseTools( "get_events", "Get SQL events", "Returns the SQL the app ran, oldest first, after the cursor. Pass the returned next as after to continue; " + - "dropped counts events that left the buffer unread. The first call starts recording bound values into the SQL.", + "dropped counts events that left the buffer unread. The first call starts recording bound values into the SQL; " + + "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while watching.", JSONObject() .put("type", "object") .put("additionalProperties", false) @@ -182,7 +232,10 @@ class DatabaseTools( description: String, inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), run: (JSONObject) -> JSONObject, - ) = McpTool(name, title, description, inputSchema, readOnly = true, run = run) + ) = McpTool(name, title, description, inputSchema, readOnly = true, run = { args -> + expireIdleClient() + run(args) + }) private fun prop( type: String, @@ -346,9 +399,11 @@ class DatabaseTools( private fun getEvents(args: JSONObject): JSONObject { val after = intArg(args, "after", 0, 0, Long.MAX_VALUE) synchronized(lock) { + lastEventsCallMs = clock() if (!clientConnected) { engine.setClientConnected(true) clientConnected = true + scheduleIdleCheck() } } val batch = @@ -413,6 +468,7 @@ class DatabaseTools( .map { it.path } .filter { it.isNotEmpty() } .distinct() + synchronized(lock) { dropStaleServerConnections(engine.connections()) } if (path !in known) { throw McpToolError( "Unknown database \"$path\": use a path from list_databases that is available.", @@ -440,13 +496,38 @@ class DatabaseTools( ): QueryResult = synchronized(lock) { try { - val conn = serverConnections.getOrPut(path) { engine.openServerConnection(path, writable = false) } + val live = engine.connections() + dropStaleServerConnections(live) + val conn = + serverConnections + .getOrPut(path) { + val ids = live.filter { it.path == path && !it.closing }.map { it.id }.toSet() + CachedConnection(engine.openServerConnection(path, writable = false), ids) + }.connection conn.query(sql, bind, offset, limits, deadline) } catch (e: DebugEngineException) { throw engineError(e) } } + /** + * Closes cached server connections whose file may be gone: after the app deletes and recreates a + * database, a connection opened before still reads the old file. A connection is kept while some + * app connection to its path that was there when it opened is still open; a path no app connection + * has any more, or only new ones, is stale. Call with [lock] held. + */ + private fun dropStaleServerConnections(live: List) { + val it = serverConnections.entries.iterator() + while (it.hasNext()) { + val (path, cached) = it.next() + val ids = live.filter { c -> c.path == path && !c.closing }.map { c -> c.id } + if (ids.none { id -> id in cached.appConnectionIds }) { + runCatching { cached.connection.close() } + it.remove() + } + } + } + private fun engineError(e: DebugEngineException) = McpToolError(e.message ?: "SQLite error ${e.sqliteCode}", JSONObject().put("sqlite_code", e.sqliteCode)) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index ea815dbc2b..b6d9a59484 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -21,6 +21,10 @@ class FakeDebugEngine( val openedServerConnections = mutableListOf>() + /** How many server connections were closed. */ + var closedServerConnections = 0 + private set + fun addEvent( kind: EventKind, sql: String, @@ -117,6 +121,7 @@ class FakeDebugEngine( } override fun close() { + if (!closed) closedServerConnections++ closed = true } } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 87c63b9f4b..21cae2b0a0 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -423,6 +423,63 @@ class DatabaseToolsTest { assertFalse(engine.clientConnected) } + @Test fun aServerConnectionIsDroppedWhenTheAppRecreatesTheDatabase() { + engine.appConnections += conn(1, "/data/a.db") + val t = tools + ok("get_stats", db(), t) + assertEquals(1, engine.openedServerConnections.size) + // the app closed connection 1, deleted the file and opened a new one: no overlap with {1} + engine.appConnections.clear() + engine.appConnections += conn(2, "/data/a.db") + ok("get_stats", db(), t) + assertEquals(2, engine.openedServerConnections.size) + assertEquals(1, engine.closedServerConnections) + } + + @Test fun aServerConnectionIsKeptWhileASeenAppConnectionRemains() { + engine.appConnections += conn(1, "/data/a.db") + val t = tools + ok("get_stats", db(), t) + engine.appConnections += conn(2, "/data/a.db") + ok("get_stats", db(), t) + engine.appConnections.removeAll { it.id == 2L } + ok("get_stats", db(), t) + assertEquals(1, engine.openedServerConnections.size) + assertEquals(0, engine.closedServerConnections) + } + + @Test fun aServerConnectionIsDroppedWhenNoAppConnectionHasThePathAnyMore() { + engine.appConnections += conn(1, "/data/a.db") + val t = tools + ok("get_stats", db(), t) + engine.appConnections.clear() + engine.appConnections += conn(3, "/data/b.db") + assertTrue(runTool(t, "get_stats", db()).getBoolean("isError")) // refused: no longer a known path + assertEquals(1, engine.closedServerConnections) + } + + @Test fun boundValuesStopBeingRecordedSixtySecondsAfterTheLastGetEvents() { + val t = tools + ok("get_events", t = t) + assertTrue(engine.clientConnected) + now += 59_000 + ok("list_connections", t = t) + assertTrue("still within 60 s", engine.clientConnected) + ok("get_events", t = t) // renews the 60 s + now += 59_000 + ok("list_connections", t = t) + assertTrue(engine.clientConnected) + now += 2_000 + ok("list_connections", t = t) + assertFalse("60 s after the last get_events", engine.clientConnected) + ok("get_events", t = t) + assertTrue("the next get_events turns it on again", engine.clientConnected) + now += 61_000 + t.expireIdleClient() // what the timer calls when no tool call comes + assertFalse(engine.clientConnected) + t.onServerStopped() + } + @Test fun stoppingTheServerClosesServerConnections() { engine.appConnections += conn(1, "/data/a.db") val t = tools From d1f0feb397fc7348603094006ae171a75dc0a638 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:54:35 +0000 Subject: [PATCH 038/203] ADFA-7136 Test the JNI query path test.sh now also builds the JNI layer as it ships (libsqlitedbg.so without SQLITE_CORE, with the version script) against a requery-like libsqlite3x.so (amalgamation, THREADSAFE=2, all symbols exported) and runs src/test/jni/JniQueryTest.java on the host JVM through NativeBridge. It is skipped with a message when no JDK is on PATH. It uses Java stubs of NativeBridge and DebugEngineException (same names and native signatures) rather than compiling the Kotlin, so only a JDK is needed; test.sh fails if the native names in NativeBridge.kt and the stub differ. A change of a Kotlin parameter type alone is not caught. Covers: value types, paging and hasMore, the total-bytes budget (including "first row always goes in" and the budget stopping on a row boundary), per-cell truncation at, over and under the limit with row * columns + column indexes and a budget-dropped row's cells, bound types, the deadline giving SQLITE_INTERRUPT, refused writes giving SQLITE_AUTH, BEGIN/SAVEPOINT/PRAGMA refusals leaving the app able to write, and the rollback backstop. Checked to fail with each native fix reverted: budget (50 rows vs 4), cut cell indexes ([] vs [1, 3]), rollback backstop (app INSERT 5 vs 0, SQLITE_BUSY), authorizer (BEGIN: 0 vs 23), dropped row's cut cells ([0, 1] vs [0]). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- .../sqlite-debugger/src/test/jni/Helper.java | 8 + .../src/test/jni/JniQueryTest.java | 255 ++++++++++++++++++ .../sqlite-debugger/src/test/jni/helper.c | 27 ++ .../engine/DebugEngineException.java | 11 + .../sqlitedebugger/engine/NativeBridge.java | 26 ++ subprojects/sqlite-debugger/test.sh | 36 +++ 6 files changed, 363 insertions(+) create mode 100644 subprojects/sqlite-debugger/src/test/jni/Helper.java create mode 100644 subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java create mode 100644 subprojects/sqlite-debugger/src/test/jni/helper.c create mode 100644 subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/DebugEngineException.java create mode 100644 subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java new file mode 100644 index 0000000000..e283c57768 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -0,0 +1,8 @@ +/** Opens and uses "app" connections with the same libsqlite3x.so the debugger runs in. */ +public class Helper { + static native long open(String path); + + static native int exec(long db, String sql); + + static native int close(long db); +} diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java new file mode 100644 index 0000000000..061d813ccb --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -0,0 +1,255 @@ +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import org.appdevforall.sqlitedebugger.engine.DebugEngineException; +import org.appdevforall.sqlitedebugger.engine.NativeBridge; + +/** + * The real JNI query path (sqlitedbg_jni.c over sqlitedbg.c) on a host JVM, against a SQLite built + * like requery's. test.sh builds libsqlite3x.so, libsqlitedbg.so (no SQLITE_CORE) and libhosthelper.so + * and runs this with them. It calls NativeBridge directly; the Kotlin above it is covered by the + * JVM unit tests with a fake engine. + */ +public class JniQueryTest { + static int failures, checks; + + static void check(boolean ok, String what) { + checks++; + if (!ok) { + failures++; + System.out.println("FAIL " + what); + } + } + + static void eq(Object a, Object b, String what) { + check(Objects.equals(a, b), what + ": " + show(a) + " vs " + show(b)); + } + + static String show(Object o) { + return o instanceof byte[] ? Arrays.toString((byte[]) o) : String.valueOf(o); + } + + static final long FAR = Long.MAX_VALUE / 2; + static final int MAX = 1 << 30; + + /** What NativeBridge.query returns, unpacked. */ + static class Result { + String[] columns; + List rows; + long truncated; + boolean hasMore; + Set cut = new HashSet<>(); + } + + @SuppressWarnings("unchecked") + static Result query(long h, String sql, Object[] args, long offset, int maxRows, int maxText, int maxBlob, int maxTotal, + long deadline) throws DebugEngineException { + Object[] r = NativeBridge.query(h, sql, args, offset, maxRows, maxText, maxBlob, maxTotal, deadline); + Result out = new Result(); + out.columns = (String[]) r[0]; + out.rows = (List) r[1]; + long[] counts = (long[]) r[2]; + out.truncated = counts[0]; + out.hasMore = counts[1] != 0; + eq(counts.length, 2 + (int) counts[0], "one index per cut cell"); + for (int i = 2; i < counts.length; i++) out.cut.add(counts[i]); + return out; + } + + static Result q(long h, String sql) throws DebugEngineException { + return query(h, sql, new Object[0], 0, 1000, 4096, 1024, MAX, FAR); + } + + static int codeOf(long h, String sql, Object[] args, long deadline) { + try { + query(h, sql, args, 0, 100, 4096, 1024, MAX, deadline); + return 0; + } catch (DebugEngineException e) { + return e.sqliteCode; + } + } + + static Set set(Long... v) { + return new HashSet<>(Arrays.asList(v)); + } + + public static void main(String[] a) throws Exception { + System.loadLibrary("sqlite3x"); + System.loadLibrary("sqlitedbg"); + System.loadLibrary("hosthelper"); + + try { + NativeBridge.openServer("/nonexistent/x.db".getBytes(StandardCharsets.UTF_8), false); + check(false, "open before install"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 21, "SQLITE_MISUSE before any app connection"); + } + eq(NativeBridge.install(), 0, "install"); + eq(NativeBridge.install(), 0, "install twice"); + + Path dir = Files.createTempDirectory("jniquery"); + String path = dir.resolve("app.db").toString(); + long app = Helper.open(path); + eq(Helper.exec(app, "CREATE TABLE t(id INTEGER, r REAL, s TEXT, b BLOB)"), 0, "create"); + eq(Helper.exec(app, "INSERT INTO t VALUES(1, 1.5, 'one', x'0102'),(2, NULL, 'héllo €', x''),(3, 3e999, NULL, NULL)"), 0, + "insert"); + eq(Helper.exec(app, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x<300) INSERT INTO t(id) SELECT x+10 FROM c"), + 0, "insert 300"); + + Object[] conns = NativeBridge.connections(); + eq(((String[]) conns[1]).length, 1, "one app connection"); + eq(((String[]) conns[1])[0], path, "its path"); + + byte[] bytes = path.getBytes(StandardCharsets.UTF_8); + long srv = NativeBridge.openServer(bytes, false); + check(srv != 0, "server handle"); + + // value types + Result r = q(srv, "SELECT id, r, s, b FROM t WHERE id < 10 ORDER BY id"); + eq(Arrays.asList(r.columns), Arrays.asList("id", "r", "s", "b"), "columns"); + eq(r.rows.size(), 3, "rows"); + eq(r.rows.get(0)[0], 1L, "long"); + eq(r.rows.get(0)[1], 1.5, "double"); + eq(r.rows.get(0)[2], "one", "text"); + check(Arrays.equals((byte[]) r.rows.get(0)[3], new byte[] {1, 2}), "blob"); + eq(r.rows.get(1)[1], null, "null"); + eq(r.rows.get(1)[2], "héllo €", "utf8 text"); + eq(((byte[]) r.rows.get(1)[3]).length, 0, "empty blob"); + eq(r.rows.get(2)[1], Double.POSITIVE_INFINITY, "infinity"); + eq(r.hasMore, false, "no more"); + eq(r.truncated, 0L, "nothing cut"); + + // paging: 300 rows with id >= 10 + String all = "SELECT id FROM t WHERE id >= 10 ORDER BY id"; + r = query(srv, all, new Object[0], 0, 100, 4096, 1024, MAX, FAR); + eq(r.rows.size(), 100, "page 1"); + eq(r.hasMore, true, "has more after a full page"); + r = query(srv, all, new Object[0], 100, 100, 4096, 1024, MAX, FAR); + eq(r.rows.get(0)[0], 111L, "page 2 starts after the offset"); + r = query(srv, all, new Object[0], 200, 100, 4096, 1024, MAX, FAR); + eq(r.rows.size(), 100, "page 3"); + eq(r.hasMore, false, "exactly the last row of the last page: no more"); + r = query(srv, all, new Object[0], 299, 100, 4096, 1024, MAX, FAR); + eq(r.rows.size(), 1, "last page"); + eq(r.rows.get(0)[0], 310L, "last id"); + r = query(srv, all, new Object[0], 5000, 100, 4096, 1024, MAX, FAR); + eq(r.rows.size(), 0, "past the end"); + eq(r.hasMore, false, "past the end has no more"); + + // M4: the total-bytes budget. 8 bytes per number: 3 numbers = 24 a row, 4 rows fit in 100. + String nums = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x<50) SELECT x, x, x FROM c"; + r = query(srv, nums, new Object[0], 0, 1000, 4096, 1024, 100, FAR); + eq(r.rows.size(), 4, "budget 100 holds 4 rows of 24"); + eq(r.hasMore, true, "budget reached: has more"); + r = query(srv, nums, new Object[0], 4, 1000, 4096, 1024, 100, FAR); + eq(r.rows.get(0)[0], 5L, "the next page starts where the budget stopped"); + r = query(srv, nums, new Object[0], 0, 1000, 4096, 1024, 24 * 50, FAR); + eq(r.rows.size(), 50, "a budget of exactly the whole result holds it"); + eq(r.hasMore, false, "and has no more"); + // text and blob count the bytes kept, not the bytes stored + String fat = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x<5) " + + "SELECT substr(hex(zeroblob(1000)), 1, 1000), zeroblob(500) FROM c"; + r = query(srv, fat, new Object[0], 0, 1000, 4096, 1024, 3200, FAR); + eq(r.rows.size(), 2, "1500 bytes a row: 2 rows in 3200"); + eq(r.hasMore, true, "fat rows: has more"); + r = query(srv, fat, new Object[0], 0, 1000, 100, 100, 3200, FAR); + eq(r.rows.size(), 5, "cells cut to 100 bytes cost 200 a row: all 5 fit"); + // the first row always goes in, so a page makes progress + r = query(srv, fat, new Object[0], 0, 1000, 4096, 1024, 10, FAR); + eq(r.rows.size(), 1, "one row over the budget is still returned"); + eq(r.hasMore, true, "and more follows"); + + // L11: per-cell truncation, exactly at the limit is whole + r = query(srv, "SELECT x'01020304', x'0102030405', 'abcd', 'abcde'", new Object[0], 0, 10, 4, 4, MAX, FAR); + eq(((byte[]) r.rows.get(0)[0]).length, 4, "blob at the limit"); + eq(((byte[]) r.rows.get(0)[1]).length, 4, "blob over the limit is cut"); + eq(r.rows.get(0)[2], "abcd", "text at the limit"); + eq(r.rows.get(0)[3], "abcd", "text over the limit is cut"); + eq(r.truncated, 2L, "two cells cut"); + eq(r.cut, set(1L, 3L), "cut cells are the over-limit blob and text, not the ones at the limit"); + r = query(srv, "SELECT x'01020304', x'0102030405', 'abcd', 'abcde' UNION ALL SELECT x'0102030405', x'01', 'abcde', 'a'", + new Object[0], 0, 10, 4, 4, MAX, FAR); + eq(r.cut, set(1L, 3L, 4L, 6L), "indexes are row * columns + column"); + eq(r.truncated, 4L, "four cells cut"); + // a character is never split: 'a' + 3 emoji of 4 bytes, 6 bytes allowed + r = query(srv, "SELECT 'a' || '😀😀😀', x'0102030405'", new Object[0], 0, 10, 6, 3, MAX, FAR); + eq(r.rows.get(0)[0], "a😀", "text cut at a character boundary"); + eq(((byte[]) r.rows.get(0)[1]).length, 3, "blob cut"); + eq(r.cut, set(0L, 1L), "both cut"); + // a row left out by the budget takes its cut cells with it + r = query(srv, "SELECT 'abcde' UNION ALL SELECT 'abcde'", new Object[0], 0, 10, 4, 4, 6, FAR); + eq(r.rows.size(), 1, "the second row would pass the budget"); + eq(r.cut, set(0L), "only the kept row's cut cell is reported"); + eq(r.truncated, 1L, "and counted"); + + // bound values of every type + r = query(srv, "SELECT ?, ?, ?, ?, ?", new Object[] {7L, 2.25, "a😀b", new byte[] {9, 8, 7}, null}, 0, 10, 4096, 1024, + MAX, FAR); + Object[] row = r.rows.get(0); + eq(row[0], 7L, "arg long"); + eq(row[1], 2.25, "arg double"); + eq(row[2], "a😀b", "arg text"); + check(Arrays.equals((byte[]) row[3], new byte[] {9, 8, 7}), "arg blob"); + eq(row[4], null, "arg null"); + eq(q(srv, "SELECT ?").rows.get(0)[0], null, "an unbound parameter is NULL"); + eq(codeOf(srv, "SELECT ?", new Object[] {1L, 2L}, FAR), 25, "too many args: SQLITE_RANGE"); + eq(codeOf(srv, "SELECT ?", new Object[] {new Object()}, FAR), 21, "unsupported arg type: SQLITE_MISUSE"); + eq(codeOf(srv, "SELEKT 1", new Object[0], FAR), 1, "syntax error: SQLITE_ERROR"); + + // a refused write is SQLITE_AUTH, and the data is untouched + eq(codeOf(srv, "INSERT INTO t(id) VALUES(5)", new Object[0], FAR), 23, "write refused: SQLITE_AUTH"); + eq(codeOf(srv, "DELETE FROM t", new Object[0], FAR), 23, "delete refused: SQLITE_AUTH"); + eq(q(srv, "SELECT count(*) FROM t WHERE id = 5").rows.get(0)[0], 0L, "nothing written"); + + // H3: a transaction cannot be opened, so the app is never locked out + for (String sql : new String[] {"BEGIN", "BEGIN IMMEDIATE", "SAVEPOINT s", "PRAGMA locking_mode=EXCLUSIVE", "PRAGMA busy_timeout=60000"}) { + eq(codeOf(srv, sql, new Object[0], FAR), 23, sql + " refused: SQLITE_AUTH"); + q(srv, "SELECT count(*) FROM t"); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4242)"), 0, "the app can write after " + sql); + Helper.exec(app, "DELETE FROM t WHERE id = 4242"); + } + + // the deadline stops a statement that never ends, and the connection stays usable + long t0 = System.currentTimeMillis(); + eq(codeOf(srv, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c) SELECT count(*) FROM c", new Object[0], t0 + 300), 9, + "deadline: SQLITE_INTERRUPT"); + long took = System.currentTimeMillis() - t0; + check(took >= 250 && took < 3000, "the deadline stopped it in " + took + " ms"); + eq(codeOf(srv, "SELECT 1", new Object[0], t0 - 1), 9, "a deadline already past: SQLITE_INTERRUPT"); + eq(q(srv, "SELECT 41 + 1").rows.get(0)[0], 42L, "usable after the deadline"); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4243)"), 0, "the app can write after an interrupted query"); + Helper.exec(app, "DELETE FROM t WHERE id = 4243"); + + // the server connection is not listed + eq(((String[]) NativeBridge.connections()[1]).length, 1, "server not listed"); + NativeBridge.close(srv); + + // the backstop: a writable connection that opens a transaction does not keep it + long w = NativeBridge.openServer(bytes, true); + q(w, "BEGIN IMMEDIATE"); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4244)"), 0, "the app can write after a writable BEGIN IMMEDIATE"); + Helper.exec(app, "DELETE FROM t WHERE id = 4244"); + q(w, "BEGIN"); + q(w, "INSERT INTO t(id) VALUES(4245)"); + eq(q(w, "SELECT count(*) FROM t WHERE id = 4245").rows.get(0)[0], 1L, "an autocommit insert on the writable connection stays"); + NativeBridge.close(w); + Helper.exec(app, "DELETE FROM t WHERE id = 4245"); + + try { + NativeBridge.openServer(dir.resolve("none.db").toString().getBytes(StandardCharsets.UTF_8), false); + check(false, "missing file"); + } catch (DebugEngineException e) { + eq(e.sqliteCode, 14, "SQLITE_CANTOPEN"); + } + + eq(Helper.close(app), 0, "close the app connection"); + eq(((String[]) NativeBridge.connections()[1]).length, 0, "all freed"); + System.out.println(checks + " checks, " + failures + " failures"); + System.exit(failures == 0 ? 0 : 1); + } +} diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c new file mode 100644 index 0000000000..9fe88d041a --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -0,0 +1,27 @@ +// The "app" side of the JNI test: plain sqlite3 calls into libsqlite3x.so, as requery's do. +#include +#include +#include "sqlite3.h" + +JNIEXPORT jlong JNICALL Java_Helper_open(JNIEnv *e, jclass c, jstring p) { + (void)c; + const char *s = (*e)->GetStringUTFChars(e, p, 0); + sqlite3 *db = 0; + sqlite3_open(s, &db); + (*e)->ReleaseStringUTFChars(e, p, s); + return (jlong)(intptr_t)db; +} + +JNIEXPORT jint JNICALL Java_Helper_exec(JNIEnv *e, jclass c, jlong db, jstring q) { + (void)c; + const char *s = (*e)->GetStringUTFChars(e, q, 0); + int rc = sqlite3_exec((sqlite3 *)(intptr_t)db, s, 0, 0, 0); + (*e)->ReleaseStringUTFChars(e, q, s); + return rc; +} + +JNIEXPORT jint JNICALL Java_Helper_close(JNIEnv *e, jclass c, jlong db) { + (void)e; + (void)c; + return sqlite3_close((sqlite3 *)(intptr_t)db); +} diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/DebugEngineException.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/DebugEngineException.java new file mode 100644 index 0000000000..bbdbdf276f --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/DebugEngineException.java @@ -0,0 +1,11 @@ +package org.appdevforall.sqlitedebugger.engine; + +/** Stands in for DebugEngineException in DebugEngine.kt: the JNI layer constructs it as (int, String). */ +public class DebugEngineException extends Exception { + public final int sqliteCode; + + public DebugEngineException(int sqliteCode, String message) { + super(message); + this.sqliteCode = sqliteCode; + } +} diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java new file mode 100644 index 0000000000..bc4ee25852 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -0,0 +1,26 @@ +package org.appdevforall.sqlitedebugger.engine; + +/** + * Stands in for NativeBridge.kt in the host JNI test (test.sh): the same class name and native + * signatures, which sqlitedbg_jni.c registers by name in JNI_OnLoad, so a Java-only toolchain can + * run the real C. test.sh checks that the native names here match the ones in NativeBridge.kt. + */ +public final class NativeBridge { + private NativeBridge() {} + + public static native int install(); + + public static native Object[] connections(); + + public static native void readEvents(long after, byte[] buf, long[] out); + + public static native void setClientConnected(boolean connected); + + public static native long openServer(byte[] path, boolean writable) throws DebugEngineException; + + public static native Object[] query(long handle, String sql, Object[] args, long offset, int maxRows, int maxTextBytes, + int maxBlobBytes, int maxTotalBytes, long deadlineMillis) + throws DebugEngineException; + + public static native void close(long handle); +} diff --git a/subprojects/sqlite-debugger/test.sh b/subprojects/sqlite-debugger/test.sh index 455dffa987..ce80e1702a 100755 --- a/subprojects/sqlite-debugger/test.sh +++ b/subprojects/sqlite-debugger/test.sh @@ -6,6 +6,8 @@ # --update-fixture rewrites src/test/resources/.../events.bin and events.tsv, which the JVM test # of EventDecoder reads; without it the committed pair is checked against the # current record layout instead. +# Then, if a JDK is on PATH (javac, java, jni.h), the JNI layer is built as on a device (no SQLITE_CORE, +# against a requery-like libsqlite3x.so) and src/test/jni/JniQueryTest.java runs the real query path. # Needs gcc, curl, tar and sha256sum. set -euo pipefail HERE=$(cd "$(dirname "$0")" && pwd) @@ -65,3 +67,37 @@ else "$WORK/asan-ubsan/test" --check-fixture "$RES/events.bin" "$RES/events.tsv" fi run_with tsan thread + +# The JNI query path on a host JVM. The Java stubs of NativeBridge and DebugEngineException under +# src/test/jni stand in for the Kotlin classes (no Kotlin compiler needed); the native names are +# checked against NativeBridge.kt below. +run_jni () { + local jdk + jdk=$(dirname "$(dirname "$(readlink -f "$(command -v javac)")")") + [ -f "$jdk/include/jni.h" ] || { echo "# jni: skipped, no jni.h under $jdk"; return 0; } + echo "# jni" + local jni=$HERE/src/test/jni out=$WORK/jni + mkdir -p "$out/lib" "$out/classes" + local kotlin_names java_names + kotlin_names=$(sed -n 's/.*external fun \([A-Za-z]*\)(.*/\1/p' "$HERE/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt" | sort | tr '\n' ' ') + java_names=$(sed -n 's/.*static native .* \([A-Za-z]*\)(.*/\1/p' "$jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java" | sort | tr '\n' ' ') + [ "$kotlin_names" = "$java_names" ] || { echo "NativeBridge.kt has ($kotlin_names) but the test stub has ($java_names)"; exit 1; } + local jinc=(-I"$jdk/include" -I"$jdk/include/linux") + # as requery builds it: everything exported, so dlsym finds sqlite3_auto_extension + build gcc -O1 -w -shared -fPIC -DSQLITE_THREADSAFE=2 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -I"$AMAL" \ + "$AMAL/sqlite3.c" -o "$out/lib/libsqlite3x.so" -lpthread -ldl -lm + build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -fvisibility=hidden -I"$AMAL" -I"$CPP" "${jinc[@]}" \ + "$CPP/sqlitedbg.c" "$CPP/sqlitedbg_jni.c" -Wl,--version-script="$CPP/sqlitedbg.map" \ + -o "$out/lib/libsqlitedbg.so" -lpthread -ldl + build gcc -O1 -Wall -Wextra -Werror -shared -fPIC -I"$AMAL" "${jinc[@]}" "$jni/helper.c" \ + -L"$out/lib" -lsqlite3x -Wl,-rpath,"$out/lib" -o "$out/lib/libhosthelper.so" + build javac -d "$out/classes" "$jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java" \ + "$jni/org/appdevforall/sqlitedebugger/engine/DebugEngineException.java" "$jni/Helper.java" "$jni/JniQueryTest.java" + LD_LIBRARY_PATH="$out/lib" java -Djava.library.path="$out/lib" -cp "$out/classes" JniQueryTest +} + +if command -v javac >/dev/null && command -v java >/dev/null; then + run_jni +else + echo "# jni: skipped, no JDK (javac and java) on PATH" +fi From 7684331c2bcb54a7ce21c4823fc8bbe4a81ad9d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:54:43 +0000 Subject: [PATCH 039/203] ADFA-7136 Document the JNI test and the requery trace limit README: the JNI test and how it stands in for the Kotlin, and that requery's own sqlite3_trace (log.tag.SQLiteStatements or SQLiteTime VERBOSE) replaces ours on a connection, so its events stop. No code change for that. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index bd33b17f4c..7421b66283 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,13 +35,14 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. ## Testing - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol` and `DatabaseTools` (with `FakeDebugEngine`). +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. +- **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). No workflow in `.github/workflows` runs either yet. From 3a5cb5356b9576aaf2996eda184dc02e1806a3f1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 13 Nov 2026 10:05:54 -0800 Subject: [PATCH 040/203] ADFA-7082: Vendor the sqlite-js 1.4.2 release Upstream released 1.4.2 with our stack, garbage-collection and result-set patches merged (sqliteai/sqlite-js #22, with two maintainer commits, #23 and #24) and with a fix for the use after free we reported (#25). That fix also changes behaviour: a db.exec result set no longer outlives the call into JavaScript that created it, and reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned". So patches 0002 to 0009 go: - 0002 to 0005 and 0008 are upstream, by patch-id identical except for 0002, which has the maintainer's two commits on top. - 0006, 0007 (its second half) and 0009 only told interrupts apart for result sets kept across calls, which 1.4.2 no longer allows. 0001 (sqlitejs_cancel_all, issue 20) is rebased: the same changes, with new context in the struct. A new 0002 keeps what 0006 and the first half of 0007 did for a cancel on SQLite before 3.41: ending a cancelled call's result sets runs the finals of the window and aggregate functions they were computing, each a call that begins after the cancel, which before 3.41 nothing else stops; and those result sets read on as "interrupted". It is narrowed to a cancelled call, since in 1.4.2 result sets are also ended on every normal return. The next commit updates the tests for 1.4.2. vendor.sh --check passes on the 1.4.2 archive (SHA-256 1aa4c566...cf24). The libs/ and license files are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...e-host-cancel-all-running-JavaScript.patch | 32 ++-- ...call-s-result-sets-as-interrupted-an.patch | 73 ++++++++ ...heck-within-the-stack-in-two-more-ca.patch | 110 ------------ ...after-any-out-of-memory-error-and-on.patch | 120 ------------- ...result-sets-an-interrupt-leaves-open.patch | 164 ------------------ ...ult-set-twice-when-finalizing-it-run.patch | 89 ---------- ...ets-a-cancel-leaves-open-on-SQLite-b.patch | 62 ------- ...-result-sets-runs-and-count-the-inte.patch | 76 -------- ...pt-test-s-garbage-result-set-a-cycle.patch | 33 ---- ...ERRUPT-as-an-interrupt-only-before-S.patch | 50 ------ subprojects/sqlite-js/upstream/src/sqlitejs.c | 150 +++++++++++----- subprojects/sqlite-js/upstream/src/sqlitejs.h | 2 +- subprojects/sqlite-js/vendor.sh | 4 +- 13 files changed, 203 insertions(+), 762 deletions(-) create mode 100644 subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch delete mode 100644 subprojects/sqlite-js/patches/0002-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch delete mode 100644 subprojects/sqlite-js/patches/0003-Collect-garbage-after-any-out-of-memory-error-and-on.patch delete mode 100644 subprojects/sqlite-js/patches/0004-End-the-result-sets-an-interrupt-leaves-open.patch delete mode 100644 subprojects/sqlite-js/patches/0005-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch delete mode 100644 subprojects/sqlite-js/patches/0006-End-the-result-sets-a-cancel-leaves-open-on-SQLite-b.patch delete mode 100644 subprojects/sqlite-js/patches/0007-Stop-what-ending-result-sets-runs-and-count-the-inte.patch delete mode 100644 subprojects/sqlite-js/patches/0008-Make-the-Interrupt-test-s-garbage-result-set-a-cycle.patch delete mode 100644 subprojects/sqlite-js/patches/0009-Count-SQLITE_INTERRUPT-as-an-interrupt-only-before-S.patch diff --git a/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch b/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch index c5973670a3..f45def7dd5 100644 --- a/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch +++ b/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch @@ -1,7 +1,7 @@ -From 45278f053210e570fad37d1ef2af7a6d4461064b Mon Sep 17 00:00:00 2001 +From 8ba5688b1cd9c9560345da31989288760049da8f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 00:05:58 -0800 -Subject: [PATCH 1/3] Let the host cancel all running JavaScript +Subject: [PATCH 1/2] Let the host cancel all running JavaScript sqlitejs_cancel_all() stops the JavaScript running in every connection: each call fails with an "interrupted" error, even code that catches @@ -45,7 +45,7 @@ Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw 3 files changed, 149 insertions(+), 3 deletions(-) diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 9137ca8..a0cacb0 100644 +index 26af849..e5fea55 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c @@ -70,6 +70,8 @@ typedef struct { @@ -54,10 +54,10 @@ index 9137ca8..a0cacb0 100644 int depth; // calls into JavaScript in progress: see js_enter() + unsigned cancel_epoch; // js_cancel_epoch when the outermost call began + bool check_interrupted; // sqlite3_is_interrupted() is available - } globaljs_context; - - typedef struct { -@@ -264,6 +266,30 @@ static void js_collect_below_limit (globaljs_context *js) { + struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() + int orphans; // of those, the ones whose JavaScript object is gone + bool ending_rowsets; // js_end_rowsets() is running +@@ -325,6 +327,30 @@ static void js_collect_below_limit (globaljs_context *js) { js_keep_gc_below_limit(js); } @@ -88,7 +88,7 @@ index 9137ca8..a0cacb0 100644 // QuickJS calls this from time to time while it runs code. A non-zero result stops the code // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, // a cancelled query in an app) also stops JavaScript that never returns to SQLite. -@@ -271,7 +297,15 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { +@@ -332,7 +358,15 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { UNUSED(rt); globaljs_context *js = (globaljs_context *)opaque; js_keep_gc_below_limit(js); @@ -105,15 +105,15 @@ index 9137ca8..a0cacb0 100644 } // The most memory, in bytes, the JavaScript runtime of a connection may allocate until -@@ -442,6 +476,7 @@ static bool js_stack_room (size_t *room) { +@@ -542,6 +576,7 @@ static bool js_stack_room (size_t *room) { // runs JavaScript) is on the same thread and keeps the outer call's limit. static void js_enter (globaljs_context *js) { if (js->depth++ > 0) return; + js->cancel_epoch = js_cancel_epoch_load(); JS_UpdateStackTop(js->runtime); - size_t size = js->stack_size, room = 0; - if ((size > 0) && js_stack_room(&room) && (room >= SQLITE_JS_STACK_MIN) && (room < size)) size = room; -@@ -469,8 +504,9 @@ static globaljs_context *globaljs_init (sqlite3 *db) { + // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails + // with "Maximum call stack size exceeded" rather than running past the end of the stack. A +@@ -577,8 +612,9 @@ static globaljs_context *globaljs_init (sqlite3 *db) { //JS_SetMaxStackSize(rt, 10 * 1024); // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry @@ -126,7 +126,7 @@ index 9137ca8..a0cacb0 100644 // the default stack size must fit in the stack of the thread that loads the extension: Windows // gives a main thread 1 MB, and apps often give their threads no more diff --git a/src/sqlitejs.h b/src/sqlitejs.h -index 048d62b..2d6bb3d 100644 +index fb0172d..ed6ce4e 100644 --- a/src/sqlitejs.h +++ b/src/sqlitejs.h @@ -21,5 +21,6 @@ @@ -137,10 +137,10 @@ index 048d62b..2d6bb3d 100644 #endif diff --git a/test/main.c b/test/main.c -index 0c8a47b..20e7764 100644 +index 8cc3706..d0930e6 100644 --- a/test/main.c +++ b/test/main.c -@@ -932,6 +932,114 @@ abort_test: +@@ -1047,6 +1047,114 @@ abort_test: return rc; } @@ -255,7 +255,7 @@ index 0c8a47b..20e7764 100644 // MARK: - Stack size - int test_stack_size (void) { -@@ -1114,6 +1222,7 @@ int main (void) { +@@ -1276,6 +1384,7 @@ int main (void) { result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations result += test_report("Thread", test_thread()); result += test_report("Interrupt", test_interrupt()); diff --git a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch new file mode 100644 index 0000000000..c0fcdce9d6 --- /dev/null +++ b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch @@ -0,0 +1,73 @@ +From 59370bd43a82eb8fcd56cb78002ccc7fc811bfb5 Mon Sep 17 00:00:00 2001 +From: David Schachter +Date: Fri, 13 Nov 2026 10:00:14 -0800 +Subject: [PATCH 2/2] End a cancelled call's result sets as interrupted, and + stop their finals + +Since 1.4.2 every result set still open when the outermost call into +JavaScript returns is ended there, which runs the final of each window +or aggregate function its statement was computing. After +sqlitejs_cancel_all() stopped the call, each such final is a new call +that begins after the cancel, so the cancel does not stop it. On SQLite +3.41 and later the interrupt the cancel left on the connection does. +Before 3.41, which has no sqlite3_is_interrupted(), nothing did, and a +final that never ends hung the statement for good. + +A call that a cancel stopped is now told apart in js_leave() by its +cancel epoch. The finals that ending its result sets runs are stopped, +and reading on from those result sets throws "interrupted", as after +sqlite3_interrupt() on 3.41 and later, rather than the message for a +result set that outlived its call. A final that ending them runs returns +through js_leave() itself, which now leaves the ending to the call that +started it. + +Before 3.41, an sqlite3_interrupt() that no cancel came with still reads +as the result set outliving its call: nothing shows it. +--- + src/sqlitejs.c | 15 +++++++++++++-- + 1 file changed, 13 insertions(+), 2 deletions(-) + +diff --git a/src/sqlitejs.c b/src/sqlitejs.c +index e5fea55..a0debe7 100644 +--- a/src/sqlitejs.c ++++ b/src/sqlitejs.c +@@ -75,6 +75,7 @@ typedef struct { + struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() + int orphans; // of those, the ones whose JavaScript object is gone + bool ending_rowsets; // js_end_rowsets() is running ++ bool ending_cancelled; // and a cancel stopped the call: see js_leave() + } globaljs_context; + + typedef struct { +@@ -366,6 +367,10 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { + if (js->db) sqlite3_interrupt(js->db); + return 1; + } ++ // Ending a cancelled call's result sets runs the finals of the window and aggregate functions ++ // they were computing, each a call that begins after the cancel: stopped too, since before ++ // SQLite 3.41 nothing else would stop one that never ends. ++ if (js->ending_cancelled) return 1; + return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); + } + +@@ -590,9 +595,15 @@ static void js_enter (globaljs_context *js) { + // ended here: see js_end_rowsets(). + static void js_leave (globaljs_context *js) { + if (--js->depth > 0) return; +- if (!js->rowsets) return; +- bool interrupted = (sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db); ++ // a final that ending them runs returns here: the call that is ending them goes on ++ if (!js->rowsets || js->ending_rowsets) return; ++ // A cancel (sqlitejs_cancel_all) during the call interrupted it, and before SQLite 3.41 is ++ // the only interrupt that shows: its result sets read on as interrupted. ++ bool cancelled = (js->cancel_epoch != js_cancel_epoch_load()); ++ bool interrupted = cancelled || ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)); ++ js->ending_cancelled = cancelled; + js_end_rowsets(js, true, interrupted); ++ js->ending_cancelled = false; + } + + static globaljs_context *globaljs_init (sqlite3 *db) { +-- +2.53.0 + diff --git a/subprojects/sqlite-js/patches/0002-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch b/subprojects/sqlite-js/patches/0002-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch deleted file mode 100644 index f6ac8003db..0000000000 --- a/subprojects/sqlite-js/patches/0002-Keep-the-stack-check-within-the-stack-in-two-more-ca.patch +++ /dev/null @@ -1,110 +0,0 @@ -From 81453cbd29634c00632d57337b08b581bee03d16 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 15:17:11 -0800 -Subject: [PATCH 2/3] Keep the stack check within the stack in two more cases - -On the initial thread on Linux, RLIMIT_STACK is now counted from the top -of the stack, as the kernel counts it, rather than from where the first -measurement was taken. Counted from there, a first measurement deep in -the stack put the bound below the real one by that depth: with the -extension loaded 2 MB deep on the main thread, js_set_max_stack_size() -allowed 10 MB of an 8 MB stack, and code that called itself without end -at that size crashed the process. - -A call into JavaScript on a thread with less room than -SQLITE_JS_STACK_MIN now keeps the measured room rather than the size -set for the connection, 1 MB by default: on a thread with a 64 KB stack, -code that called itself without end crashed. JavaScript there now fails -with "Maximum call stack size exceeded". The minimum still applies where -a runtime is created, since QuickJS cannot create a context in less. - -Stack on other threads now also runs forever() on a 64 KB thread. It -crashes without this change and passes with it, also under ASan and -UBSan, and the suite passes 16 of 16. The first case is checked by a -program that loads the extension deep in the main thread's stack: at 2 -and 6 MB deep, the largest size allowed was 10.2 and 14.4 MB of 8 MB -before, and about 7.75 MB after, where forever() stops with an error. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 17 ++++++++++++----- - test/main.c | 12 ++++++++++++ - 2 files changed, 24 insertions(+), 5 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index a0cacb0..afde928 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -389,9 +389,10 @@ static void js_mem_reset_peak (globaljs_context *js) { - #endif - - // The least stack worth giving JavaScript. QuickJS cannot even create a context below about --// 16 KB (measured: 4 KB fails, 16 KB works), and it reads 0 as "no check at all", so a smaller --// measurement is treated as no measurement and leaves the default alone. Failing to catch --// runaway recursion is the lesser evil next to an extension that cannot load. -+// 16 KB (measured: 4 KB fails, 16 KB works), and it reads 0 as "no check at all", so where a -+// runtime is created a smaller measurement is treated as no measurement and leaves the default -+// alone. Failing to catch runaway recursion is the lesser evil next to an extension that cannot -+// load. A call into JavaScript on an existing runtime keeps any measurement (see js_enter). - #ifndef SQLITE_JS_STACK_MIN - #define SQLITE_JS_STACK_MIN (32 * 1024) - #endif -@@ -429,7 +430,10 @@ static bool js_stack_low (uintptr_t sp, uintptr_t *low) { - if (syscall(SYS_gettid) == (long)getpid()) { - struct rlimit limit; - if ((getrlimit(RLIMIT_STACK, &limit) == 0) && (limit.rlim_cur != RLIM_INFINITY)) { -- uintptr_t grows_to = (sp > (uintptr_t)limit.rlim_cur) ? sp - (uintptr_t)limit.rlim_cur : 0; -+ // counted from the top of the stack, as the kernel counts it: counted from sp, a first -+ // measurement deep in the stack would put the bound below the real one -+ uintptr_t high = (uintptr_t)addr + size; -+ uintptr_t grows_to = (high > (uintptr_t)limit.rlim_cur) ? high - (uintptr_t)limit.rlim_cur : 0; - if (grows_to < thread_low) thread_low = grows_to; - } - } -@@ -478,8 +482,11 @@ static void js_enter (globaljs_context *js) { - if (js->depth++ > 0) return; - js->cancel_epoch = js_cancel_epoch_load(); - JS_UpdateStackTop(js->runtime); -+ // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails -+ // with "Maximum call stack size exceeded" rather than running past the end of the stack. A -+ // size of 1 rather than 0, which would turn the check off. - size_t size = js->stack_size, room = 0; -- if ((size > 0) && js_stack_room(&room) && (room >= SQLITE_JS_STACK_MIN) && (room < size)) size = room; -+ if ((size > 0) && js_stack_room(&room) && (room < size)) size = (room > 0) ? room : 1; - JS_SetMaxStackSize(js->runtime, size); - } - -diff --git a/test/main.c b/test/main.c -index 20e7764..7969419 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -1130,6 +1130,13 @@ static void *stack_thread_run (void *ptr) { - return NULL; - } - -+// Runs forever() on the calling thread, which must stop with an error instead of crashing. -+static void *stack_thread_forever (void *ptr) { -+ stack_thread_args *args = (stack_thread_args *)ptr; -+ args->rc = check_error(args->db, "SELECT forever();", "Maximum call stack size exceeded"); -+ return NULL; -+} -+ - static void *stack_thread_open (void *ptr) { - stack_thread_args *args = (stack_thread_args *)ptr; - args->rc = test_open(&args->db); -@@ -1203,6 +1210,11 @@ int test_stack_threads (void) { - rc = args.rc; - if (rc != SQLITE_OK) goto abort_test; - -+ // and on a thread with less stack left than SQLITE_JS_STACK_MIN: the size is still lowered to -+ // fit, since the default would let code that calls itself without end run past the stack -+ rc = stack_thread(stack_thread_forever, &args, 64 * 1024); -+ if (rc != SQLITE_OK) goto abort_test; -+ - // a thread whose whole stack is under twice the margin still gets a usable runtime - rc = stack_thread(stack_thread_tiny, &args, 256 * 1024); - --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0003-Collect-garbage-after-any-out-of-memory-error-and-on.patch b/subprojects/sqlite-js/patches/0003-Collect-garbage-after-any-out-of-memory-error-and-on.patch deleted file mode 100644 index 5c6e1dfae5..0000000000 --- a/subprojects/sqlite-js/patches/0003-Collect-garbage-after-any-out-of-memory-error-and-on.patch +++ /dev/null @@ -1,120 +0,0 @@ -From 2260b1174c223b8ecc7c4619a3573de0cce5441f Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 15:32:30 -0800 -Subject: [PATCH 3/3] Collect garbage after any out-of-memory error and on any - new limit - -Garbage could leave a connection unable to make an allocation that fits -in its memory limit, on every try: - -- After an allocation too large to fit fails. QuickJS refuses it before - making it, so the memory in use never came within 64 KB of the limit - and the collection after the error did not run. With 40 MB of cyclic - garbage under the 64 MB default, new ArrayBuffer(30 MB) failed with - "out of memory" every time. The collection now also runs whenever the - error is "out of memory": the next try succeeds. -- After a lower limit set above the memory in use. Only a limit within - 64 KB of the memory in use collected. With the garbage of 200,000 - cyclic objects and the limit lowered to 32 MB, new ArrayBuffer(16 MB) - failed. Setting a limit now always collects. - -The Memory limit test covers both, each on a connection of its own; each -case fails without its change. The suite passes 16 of 16, also under -ASan and UBSan. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 18 +++++++++++------- - test/main.c | 32 ++++++++++++++++++++++++++++++++ - 2 files changed, 43 insertions(+), 7 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index afde928..6c1183b 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -968,7 +968,9 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - default_error = "out of memory"; - } - } -- bool out_of_memory = js_reached_memory_limit(JS_GetContextOpaque(js_ctx)); -+ // An allocation too large to fit is refused before it is counted, so the memory in use need -+ // not have come near the limit: the error itself says so. -+ bool out_of_memory = js_reached_memory_limit(JS_GetContextOpaque(js_ctx)) || (err_msg && (strcmp(err_msg, "out of memory") == 0)); - js_mem_reset_peak(JS_GetContextOpaque(js_ctx)); - - // set a default error message and code -@@ -980,9 +982,9 @@ static void js_error_to_sqlite (sqlite3_context *context, JSContext *js_ctx, JSV - if (!JS_IsNull(exception)) JS_FreeValue(js_ctx, exception); - - // QuickJS refuses every allocation once the memory in use is over the limit, and it collects -- // only when it creates an object, which it cannot do without allocating: the connection -- // would stay out of memory for good. No JavaScript is running here, so collect now, while -- // the garbage that filled the limit is still reachable from nothing. -+ // only when it creates an object past its threshold, which the code that failed may never -+ // do: the connection would stay out of memory for good. No JavaScript is running here, so -+ // collect now, while the garbage that filled the limit is still reachable from nothing. - if (out_of_memory) js_collect_below_limit(JS_GetContextOpaque(js_ctx)); - } - -@@ -1804,9 +1806,11 @@ void js_set_memory_limit (sqlite3_context *context, int argc, sqlite3_value **ar - js->memory_limit = (limit > SIZE_MAX) ? 0 : (size_t)limit; - JS_SetMemoryLimit(js->runtime, js->memory_limit); - js->gc_threshold = 0; // check the GC threshold against the new limit -- // a limit at or under the memory in use leaves nothing to allocate from, and QuickJS cannot -- // collect without allocating, so collect here instead -- if ((js->memory_limit > 0) && (js->mem_used + 64 * 1024 >= js->memory_limit)) js_collect_below_limit(js); -+ // Garbage left from before counts against the new limit, and QuickJS collects only when it -+ // creates an object past its threshold: a limit at or under the memory in use leaves nothing -+ // to allocate from, and one above it can leave too little for a large allocation. So collect -+ // here, as no JavaScript is running. -+ if (js->memory_limit > 0) js_collect_below_limit(js); - else js_keep_gc_below_limit(js); - js_mem_reset_peak(js); - } -diff --git a/test/main.c b/test/main.c -index 7969419..dfb0079 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -900,6 +900,38 @@ int test_memory_limit (void) { - rc = check_query(db, "SELECT js_eval('[1, 2, 3].map(x => x * 2).join()');", "2,4,6"); - if (rc != SQLITE_OK) goto abort_test; - -+ // and so does a lower limit set above it: the garbage would fill the room left under the new -+ // limit, and an allocation that needs that room would fail -+ if (db) sqlite3_close(db); -+ db = NULL; -+ rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_set_memory_limit(0);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');", "200000"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_eval('delete globalThis.g; 0');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_set_memory_limit(32 * 1024 * 1024);"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(16 * 1024 * 1024).byteLength');", "16777216"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // garbage that leaves no room for a large allocation is collected after it fails, so the next -+ // try succeeds: QuickJS refuses an allocation that would pass the limit before making it, so -+ // the memory in use never comes near the limit, and nothing else would collect the garbage -+ if (db) sqlite3_close(db); -+ db = NULL; -+ rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT js_eval('globalThis.g = []; for (let i = 0; i < 40; i++) { const o = { b: new ArrayBuffer(1024 * 1024) }; o.o = o; g.push(o); } g.length');", "40"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_eval('delete globalThis.g; 0');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ sqlite3_exec(db, "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');", NULL, NULL, NULL); // may fail -+ rc = check_query(db, "SELECT js_eval('new ArrayBuffer(30 * 1024 * 1024).byteLength');", "31457280"); -+ if (rc != SQLITE_OK) goto abort_test; -+ - // running out of memory through many small allocations, which leaves no room for the error - // object, is reported as "out of memory" too - rc = check_error(db, "SELECT js_eval('(function () { let h = null; for (;;) h = {n: h}; })()');", "out of memory"); --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0004-End-the-result-sets-an-interrupt-leaves-open.patch b/subprojects/sqlite-js/patches/0004-End-the-result-sets-an-interrupt-leaves-open.patch deleted file mode 100644 index ff56c81848..0000000000 --- a/subprojects/sqlite-js/patches/0004-End-the-result-sets-an-interrupt-leaves-open.patch +++ /dev/null @@ -1,164 +0,0 @@ -From 2744be532cb469b7d44b6cb86082760105fd25a9 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 16:07:37 -0800 -Subject: [PATCH 4/4] End the result sets an interrupt leaves open - -SQLite keeps an interrupt in effect until no statement of the connection -is running, and a db.exec result set that JavaScript leaves open is a -running statement. One kept in a global, or garbage not yet collected, -made every later statement on the connection fail with "interrupted", -the JavaScript that could release it included, until the connection -closed. In the sqlite3 shell, Ctrl-C during - globalThis.held = db.exec("SELECT 1 UNION ALL SELECT 2"); held.next(); - while (true) {} -left the session unable to run anything. - -Each connection now lists its result sets. When the outermost call into -JavaScript returns on an interrupted connection, no result set is being -stepped, so the open ones are finalized there; one that JavaScript kept -then throws "interrupted" from next() and toArray(). The interrupt then -clears as usual once the interrupted statement ends. - -The Interrupt test now interrupts code that keeps a result set in a -global, and code whose result set is garbage, and checks that the -connection runs SQL afterwards and that the kept one throws. It fails -without this change. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 37 +++++++++++++++++++++++++++++++++---- - test/main.c | 14 ++++++++++++++ - 2 files changed, 47 insertions(+), 4 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 6c1183b..7f31883 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -72,6 +72,7 @@ typedef struct { - int depth; // calls into JavaScript in progress: see js_enter() - unsigned cancel_epoch; // js_cancel_epoch when the outermost call began - bool check_interrupted; // sqlite3_is_interrupted() is available -+ struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - } globaljs_context; - - typedef struct { -@@ -108,9 +109,11 @@ static JSValue sqlite_value_to_js (JSContext *ctx, sqlite3_value *value); - - // MARK: - RowSet - - --typedef struct { -+typedef struct rowset { - int ncols; - sqlite3_stmt *vm; -+ bool interrupted; // ended by js_end_rowsets(): reading on throws -+ struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() - } rowset; - - static void js_rowset_finalizer(JSRuntime *rt, JSValue val); -@@ -139,7 +142,7 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J - rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); - if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); - -- if (!rs->vm) return JS_FALSE; -+ if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_FALSE; - int rc = sqlite3_step(rs->vm); - if (rc == SQLITE_ROW) return JS_TRUE; - -@@ -191,7 +194,7 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg - globaljs_context *js = JS_GetContextOpaque(ctx); - rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); - if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); -- if (!rs->vm) return JS_NewArray(ctx); -+ if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_NewArray(ctx); - - JSValue result = JS_NewArray(ctx); - if (JS_IsException(result)) return JS_EXCEPTION; -@@ -233,10 +236,27 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - rowset *rs = (rowset *)JS_GetOpaque(val, js->rowSetClassID); - if (!rs) return; - -+ if (rs->prev) rs->prev->next = rs->next; -+ else if (js->rowsets == rs) js->rowsets = rs->next; -+ if (rs->next) rs->next->prev = rs->prev; - if (rs->vm) sqlite3_finalize(rs->vm); - sqlite3_free(rs); - } - -+// Ends every result set of the connection that is still open. SQLite keeps an interrupt in effect -+// until no statement of the connection is running, and an open result set is a running statement: -+// one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every -+// later statement fail with "interrupted" until the connection closed, the statements that could -+// release it included. Only to be called where none of them is being stepped: see js_leave(). -+static void js_end_rowsets (globaljs_context *js) { -+ for (rowset *rs = js->rowsets; rs; rs = rs->next) { -+ if (!rs->vm) continue; -+ sqlite3_finalize(rs->vm); -+ rs->vm = NULL; -+ rs->interrupted = true; -+ } -+} -+ - // MARK: - Initializer - - - // QuickJS collects cyclic garbage only when its memory use passes a threshold, which it resets -@@ -490,8 +510,11 @@ static void js_enter (globaljs_context *js) { - JS_SetMaxStackSize(js->runtime, size); - } - -+// Once the outermost call has returned, no result set is being stepped, so those an interrupt left -+// open are ended here: see js_end_rowsets(). - static void js_leave (globaljs_context *js) { -- js->depth--; -+ if (--js->depth > 0) return; -+ if ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)) js_end_rowsets(js); - } - - static globaljs_context *globaljs_init (sqlite3 *db) { -@@ -827,12 +850,18 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int - if (!rs) goto abort_with_dberror; - rs->vm = vm; - rs->ncols = sqlite3_column_count(vm); -+ rs->interrupted = false; -+ rs->prev = rs->next = NULL; - - // create Rowset JS object - globaljs_context *js = JS_GetContextOpaque(ctx); - JSValue obj = JS_NewObjectClass(ctx, js->rowSetClassID); - if (JS_IsException(obj)) goto abort_with_jserror; - JS_SetOpaque(obj, rs); -+ // listed once the object owns it, since its finalizer unlists it -+ rs->next = js->rowsets; -+ if (js->rowsets) js->rowsets->prev = rs; -+ js->rowsets = rs; - JS_SetPropertyStr(ctx, obj, "columnCount", JS_NewInt32(ctx, rs->ncols)); - - return obj; -diff --git a/test/main.c b/test/main.c -index dfb0079..63f9dab 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -577,6 +577,20 @@ int test_interrupt (void) { - rc = test_interrupt_sql(db, "SELECT js_eval('for (;;) { try { while (true) {} } catch (e) {} }');"); - if (rc != SQLITE_OK) goto abort_test; - -+ // A result set left open, kept in a global or garbage not yet collected, is a statement still -+ // running, and SQLite keeps an interrupt in effect until none is: every later statement on the -+ // connection failed. The interrupted call ends them, and the kept one then throws. -+ rc = test_interrupt_sql(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); while (true) {}');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT 1 + 2;", "3"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = test_interrupt_sql(db, "SELECT js_eval('(function () { const r = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); r.next(); while (true) {} })()');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db, "SELECT 1 + 2;", "3"); -+ if (rc != SQLITE_OK) goto abort_test; -+ - abort_test: - test_watchdog_stop = 1; - if (watching) pthread_join(watchdog, NULL); --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0005-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch b/subprojects/sqlite-js/patches/0005-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch deleted file mode 100644 index 9a79a711b8..0000000000 --- a/subprojects/sqlite-js/patches/0005-Do-not-end-a-result-set-twice-when-finalizing-it-run.patch +++ /dev/null @@ -1,89 +0,0 @@ -From ec5ba2c4092d85931c191df7d56664ee5579d3a3 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 16:29:13 -0800 -Subject: [PATCH 5/6] Do not end a result set twice when finalizing it runs - JavaScript - -Finalizing a statement that is computing a window or aggregate function -runs the function's final, which for a JavaScript function calls -js_enter() and js_leave(). On an interrupted connection that js_leave() -ended the result sets again, before the first finalize had returned: the -same statement was finalized twice, a use after free under ASan, found -by CodeRabbit. Garbage collection while that JavaScript runs can also -free result sets of the list being walked. - -js_end_rowsets() now takes each statement from its result set before it -finalizes it, walks the list again from its head after each one, and -does nothing when called from within itself. The Interrupt test now also -interrupts code that keeps a result set computing a JavaScript window -function; without this change it is a use after free under ASan. The -suite passes 15 of 15, also under ASan and UBSan. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 17 ++++++++++++++--- - test/main.c | 8 ++++++++ - 2 files changed, 22 insertions(+), 3 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 7f31883..a3d72c6 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -73,6 +73,7 @@ typedef struct { - unsigned cancel_epoch; // js_cancel_epoch when the outermost call began - bool check_interrupted; // sqlite3_is_interrupted() is available - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() -+ bool ending_rowsets; // js_end_rowsets() is running - } globaljs_context; - - typedef struct { -@@ -248,13 +249,23 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - // one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every - // later statement fail with "interrupted" until the connection closed, the statements that could - // release it included. Only to be called where none of them is being stepped: see js_leave(). -+// Finalizing a statement can run JavaScript, the final of a window or aggregate function it was -+// computing, whose js_leave() comes back here and whose garbage collection can free result sets -+// of the list. So each statement is taken from its result set before it is finalized, the list -+// is walked again from its head after each one, and a nested call does nothing. - static void js_end_rowsets (globaljs_context *js) { -- for (rowset *rs = js->rowsets; rs; rs = rs->next) { -- if (!rs->vm) continue; -- sqlite3_finalize(rs->vm); -+ if (js->ending_rowsets) return; -+ js->ending_rowsets = true; -+ for (;;) { -+ rowset *rs = js->rowsets; -+ while (rs && !rs->vm) rs = rs->next; -+ if (!rs) break; -+ sqlite3_stmt *vm = rs->vm; - rs->vm = NULL; - rs->interrupted = true; -+ sqlite3_finalize(vm); - } -+ js->ending_rowsets = false; - } - - // MARK: - Initializer - -diff --git a/test/main.c b/test/main.c -index 63f9dab..d7edb9e 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -590,6 +590,14 @@ int test_interrupt (void) { - if (rc != SQLITE_OK) goto abort_test; - rc = check_query(db, "SELECT 1 + 2;", "3"); - if (rc != SQLITE_OK) goto abort_test; -+ // ending a result set that is computing a window function runs the function's final, which -+ // is JavaScript too: its end must not end the same result set again -+ rc = db_exec(db, "SELECT js_create_window('running_sum', 'total = 0;', '(function (args) { total += args[0]; })', '(function () { return total; })', '(function () { return total; })', '(function (args) { total -= args[0]; })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = test_interrupt_sql(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT running_sum(column1) OVER (ORDER BY column1) FROM (VALUES (1), (2), (3))\"); held.next(); while (true) {}');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); -+ if (rc != SQLITE_OK) goto abort_test; - - abort_test: - test_watchdog_stop = 1; --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0006-End-the-result-sets-a-cancel-leaves-open-on-SQLite-b.patch b/subprojects/sqlite-js/patches/0006-End-the-result-sets-a-cancel-leaves-open-on-SQLite-b.patch deleted file mode 100644 index 127dbed515..0000000000 --- a/subprojects/sqlite-js/patches/0006-End-the-result-sets-a-cancel-leaves-open-on-SQLite-b.patch +++ /dev/null @@ -1,62 +0,0 @@ -From 7c2193937cb11b71f2a5d4435d5f7fad328f76a7 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 16:30:11 -0800 -Subject: [PATCH 6/6] End the result sets a cancel leaves open on SQLite before - 3.41 - -js_leave() ends the result sets an interrupt left open only when -sqlite3_is_interrupted() says the connection is interrupted, and SQLite -before 3.41 has no such function. A cancel still interrupts the -connection there, through sqlite3_interrupt() in the interrupt handler, -so a result set the cancelled JavaScript kept open left every later -statement failing (CodeRabbit). The handler now records that it sent the -interrupt, and js_leave() ends the result sets on that record too. - -Checked with this file built to report SQLite 3.40: after a cancel of -JavaScript that keeps a result set in a global, every later statement -failed before, and SELECT 1 and js_eval() run after. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 8 +++++++- - 1 file changed, 7 insertions(+), 1 deletion(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index a3d72c6..7d8bd3a 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -74,6 +74,7 @@ typedef struct { - bool check_interrupted; // sqlite3_is_interrupted() is available - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - bool ending_rowsets; // js_end_rowsets() is running -+ bool cancel_interrupted; // a cancel interrupted the connection: see js_leave() - } globaljs_context; - - typedef struct { -@@ -334,6 +335,7 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { - // The statement is interrupted too: a collation cannot report an error, so the - // statement would go on calling JavaScript, each call beginning after the cancel. - if (js->db) sqlite3_interrupt(js->db); -+ js->cancel_interrupted = true; - return 1; - } - return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); -@@ -523,9 +525,13 @@ static void js_enter (globaljs_context *js) { - - // Once the outermost call has returned, no result set is being stepped, so those an interrupt left - // open are ended here: see js_end_rowsets(). -+// A cancel's own interrupt counts even where sqlite3_is_interrupted() is missing (SQLite before 3.41). - static void js_leave (globaljs_context *js) { - if (--js->depth > 0) return; -- if ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)) js_end_rowsets(js); -+ if (js->cancel_interrupted || (js->check_interrupted && js->db && sqlite3_is_interrupted(js->db))) { -+ js->cancel_interrupted = false; -+ js_end_rowsets(js); -+ } - } - - static globaljs_context *globaljs_init (sqlite3 *db) { --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0007-Stop-what-ending-result-sets-runs-and-count-the-inte.patch b/subprojects/sqlite-js/patches/0007-Stop-what-ending-result-sets-runs-and-count-the-inte.patch deleted file mode 100644 index 22bcf1c3e4..0000000000 --- a/subprojects/sqlite-js/patches/0007-Stop-what-ending-result-sets-runs-and-count-the-inte.patch +++ /dev/null @@ -1,76 +0,0 @@ -From 1f1f9c0d3079fd6707f3ed5ee996fdade891211d Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 16:46:08 -0800 -Subject: [PATCH] Stop what ending result sets runs, and count the interrupts - db.exec sees - -Two more cases on SQLite before 3.41, which has no -sqlite3_is_interrupted() (CodeRabbit): -- Ending result sets after a cancel can run JavaScript: the final of a - window or aggregate function, as its statement is finalized. That - JavaScript begins after the cancel, so nothing stopped it, and a final - that never ended hung the cancelled query. The interrupt handler now - stops any JavaScript while result sets are being ended. -- A direct sqlite3_interrupt() that reached the SQL of a db.exec result - set, while JavaScript kept another one open, was not seen by - js_leave(), so that one kept the connection interrupted. A result set - whose step returns SQLITE_INTERRUPT now records it. - -Checked with this file built to report SQLite 3.40. A window function -whose final never ends, kept open by cancelled JavaScript, hung before -and ends after. A direct interrupt during db.exec's SQL, with another -result set kept, uncaught or caught, left later statements failing -before and not after. An interrupt that never reaches the SQL that -JavaScript runs remains unseen before 3.41; JavaScript cannot be -interrupted there at all, only cancelled. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 9 ++++++++- - 1 file changed, 8 insertions(+), 1 deletion(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 7d8bd3a..b8d4634 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -74,7 +74,7 @@ typedef struct { - bool check_interrupted; // sqlite3_is_interrupted() is available - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - bool ending_rowsets; // js_end_rowsets() is running -- bool cancel_interrupted; // a cancel interrupted the connection: see js_leave() -+ bool cancel_interrupted; // the connection is known to be interrupted: see js_leave() - } globaljs_context; - - typedef struct { -@@ -147,6 +147,8 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J - if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_FALSE; - int rc = sqlite3_step(rs->vm); - if (rc == SQLITE_ROW) return JS_TRUE; -+ // before SQLite 3.41, the only sign of an interrupt that js_leave() can see -+ if (rc == SQLITE_INTERRUPT) js->cancel_interrupted = true; - - // an error while the statement runs (a constraint, an overflow, an interrupt) is an - // exception, as an error while it is prepared is in js_sqlite_exec; only the end of the -@@ -224,6 +226,7 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg - } - - // as in js_rowset_next: an error is an exception, not a shorter array -+ if (rc == SQLITE_INTERRUPT) js->cancel_interrupted = true; - if (rc != SQLITE_DONE) { - JS_FreeValue(ctx, result); - result = JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); -@@ -329,6 +332,10 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { - UNUSED(rt); - globaljs_context *js = (globaljs_context *)opaque; - js_keep_gc_below_limit(js); -+ // JavaScript that ending result sets runs, the final of a window or aggregate function as its -+ // statement is finalized, belongs to a call already stopped. Before SQLite 3.41 nothing else -+ // would stop it: it begins after the cancel, and sqlite3_is_interrupted() is missing. -+ if (js->ending_rowsets) return 1; - // Only a call (see js_enter) is cancelled: the JavaScript a connection runs while it is set - // up is not one, and stopping it would make the connection fail to load the extension. - if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0008-Make-the-Interrupt-test-s-garbage-result-set-a-cycle.patch b/subprojects/sqlite-js/patches/0008-Make-the-Interrupt-test-s-garbage-result-set-a-cycle.patch deleted file mode 100644 index 0c17e7a3d0..0000000000 --- a/subprojects/sqlite-js/patches/0008-Make-the-Interrupt-test-s-garbage-result-set-a-cycle.patch +++ /dev/null @@ -1,33 +0,0 @@ -From 7c86bfb57d7018afaff9e90b72fb398f45dfa45b Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 19:04:33 -0800 -Subject: [PATCH 8/9] Make the Interrupt test's garbage result set a cycle - -The test's "garbage" result set was freed by reference counting as the -interrupt unwound the call, so the case passed without the change it -tests, found by an independent review. Referring to itself, it stays -until the collector runs, as garbage a cleanup has to reach: the case -now fails on 1.4.1 without the change and passes with it. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - test/main.c | 2 +- - 1 file changed, 1 insertion(+), 1 deletion(-) - -diff --git a/test/main.c b/test/main.c -index d7edb9e..3bd49a8 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -586,7 +586,7 @@ int test_interrupt (void) { - if (rc != SQLITE_OK) goto abort_test; - rc = check_error(db, "SELECT js_eval('held.next()');", "interrupted"); - if (rc != SQLITE_OK) goto abort_test; -- rc = test_interrupt_sql(db, "SELECT js_eval('(function () { const r = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); r.next(); while (true) {} })()');"); -+ rc = test_interrupt_sql(db, "SELECT js_eval('(function () { const r = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); r.self = r; r.next(); while (true) {} })()');"); - if (rc != SQLITE_OK) goto abort_test; - rc = check_query(db, "SELECT 1 + 2;", "3"); - if (rc != SQLITE_OK) goto abort_test; --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0009-Count-SQLITE_INTERRUPT-as-an-interrupt-only-before-S.patch b/subprojects/sqlite-js/patches/0009-Count-SQLITE_INTERRUPT-as-an-interrupt-only-before-S.patch deleted file mode 100644 index e592a0a3ea..0000000000 --- a/subprojects/sqlite-js/patches/0009-Count-SQLITE_INTERRUPT-as-an-interrupt-only-before-S.patch +++ /dev/null @@ -1,50 +0,0 @@ -From 06cdbf8d9147e8de3ac01c1dd256861cb17ff117 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 19:05:55 -0800 -Subject: [PATCH 9/9] Count SQLITE_INTERRUPT as an interrupt only before SQLite - 3.41 - -A result set's step that returned SQLITE_INTERRUPT marked the connection -as interrupted, so the next js_leave() ended every result set still -open. But a progress handler that stops a statement, which is how -Android cancels a query, gives SQLITE_INTERRUPT too, and leaves nothing -interrupted: result sets that earlier calls kept were ended for nothing, -on any SQLite (independent review). From 3.41, sqlite3_is_interrupted() -tells, so the step's code is used only before it. Before 3.41 the two -cannot be told apart, and kept result sets are still ended. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 8 +++++--- - 1 file changed, 5 insertions(+), 3 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index b8d4634..1f9e49f 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -147,8 +147,10 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J - if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_FALSE; - int rc = sqlite3_step(rs->vm); - if (rc == SQLITE_ROW) return JS_TRUE; -- // before SQLite 3.41, the only sign of an interrupt that js_leave() can see -- if (rc == SQLITE_INTERRUPT) js->cancel_interrupted = true; -+ // Before SQLite 3.41, the only sign of an interrupt that js_leave() can see. Not from 3.41, -+ // where sqlite3_is_interrupted() tells, since SQLITE_INTERRUPT is also what a progress handler -+ // that stops a statement gives (Android's cancelling), which leaves nothing interrupted. -+ if ((rc == SQLITE_INTERRUPT) && !js->check_interrupted) js->cancel_interrupted = true; - - // an error while the statement runs (a constraint, an overflow, an interrupt) is an - // exception, as an error while it is prepared is in js_sqlite_exec; only the end of the -@@ -226,7 +228,7 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg - } - - // as in js_rowset_next: an error is an exception, not a shorter array -- if (rc == SQLITE_INTERRUPT) js->cancel_interrupted = true; -+ if ((rc == SQLITE_INTERRUPT) && !js->check_interrupted) js->cancel_interrupted = true; - if (rc != SQLITE_DONE) { - JS_FreeValue(ctx, result); - result = JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); --- -2.53.0 - diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.c b/subprojects/sqlite-js/upstream/src/sqlitejs.c index 1f9e49f1fb..a0debe729e 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.c +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.c @@ -73,8 +73,9 @@ typedef struct { unsigned cancel_epoch; // js_cancel_epoch when the outermost call began bool check_interrupted; // sqlite3_is_interrupted() is available struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() + int orphans; // of those, the ones whose JavaScript object is gone bool ending_rowsets; // js_end_rowsets() is running - bool cancel_interrupted; // the connection is known to be interrupted: see js_leave() + bool ending_cancelled; // and a cancel stopped the call: see js_leave() } globaljs_context; typedef struct { @@ -114,10 +115,18 @@ static JSValue sqlite_value_to_js (JSContext *ctx, sqlite3_value *value); typedef struct rowset { int ncols; sqlite3_stmt *vm; - bool interrupted; // ended by js_end_rowsets(): reading on throws + bool ended; // ended by js_end_rowsets(): reading on throws + bool interrupted; // and an interrupt is why: reading on throws "interrupted" + bool orphaned; // its JavaScript object is gone: see js_rowset_finalizer() struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() } rowset; +// The error for reading a result set that js_end_rowsets() ended, which is not the end of its rows. +static JSValue js_rowset_ended (JSContext *ctx, const rowset *rs) { + if (rs->interrupted) return JS_ThrowInternalError(ctx, "interrupted"); + return JS_ThrowInternalError(ctx, "The result set was closed when the call into JavaScript that created it returned"); +} + static void js_rowset_finalizer(JSRuntime *rt, JSValue val); static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); static JSValue js_rowset_get(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); @@ -144,13 +153,9 @@ static JSValue js_rowset_next(JSContext *ctx, JSValueConst this_val, int argc, J rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); - if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_FALSE; + if (!rs->vm) return rs->ended ? js_rowset_ended(ctx, rs) : JS_FALSE; int rc = sqlite3_step(rs->vm); if (rc == SQLITE_ROW) return JS_TRUE; - // Before SQLite 3.41, the only sign of an interrupt that js_leave() can see. Not from 3.41, - // where sqlite3_is_interrupted() tells, since SQLITE_INTERRUPT is also what a progress handler - // that stops a statement gives (Android's cancelling), which leaves nothing interrupted. - if ((rc == SQLITE_INTERRUPT) && !js->check_interrupted) js->cancel_interrupted = true; // an error while the statement runs (a constraint, an overflow, an interrupt) is an // exception, as an error while it is prepared is in js_sqlite_exec; only the end of the @@ -169,7 +174,7 @@ static JSValue js_rowset_get(JSContext *ctx, JSValueConst this_val, int argc, JS // never return JS_EXCEPTION without throwing something: QuickJS would propagate a // null exception and the caller would only get a generic error message - if (!rs->vm) return JS_ThrowInternalError(ctx, "No row available, call next() first"); + if (!rs->vm) return rs->ended ? js_rowset_ended(ctx, rs) : JS_ThrowInternalError(ctx, "No row available, call next() first"); uint32_t index = 0; if (JS_ToUint32(ctx, &index, argv[0])) return JS_EXCEPTION; if (index >= (uint32_t)rs->ncols) return JS_ThrowRangeError(ctx, "Column index %u out of range, column count is %d", index, rs->ncols); @@ -184,7 +189,7 @@ static JSValue js_rowset_name(JSContext *ctx, JSValueConst this_val, int argc, J rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); - if (!rs->vm) return JS_ThrowInternalError(ctx, "Rowset statement is no longer available"); + if (!rs->vm) return rs->ended ? js_rowset_ended(ctx, rs) : JS_ThrowInternalError(ctx, "Rowset statement is no longer available"); uint32_t index = 0; if (JS_ToUint32(ctx, &index, argv[0])) return JS_EXCEPTION; if (index >= (uint32_t)rs->ncols) return JS_ThrowRangeError(ctx, "Column index %u out of range, column count is %d", index, rs->ncols); @@ -200,7 +205,7 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg globaljs_context *js = JS_GetContextOpaque(ctx); rowset *rs = JS_GetOpaque(this_val, js->rowSetClassID); if (!rs) return JS_ThrowTypeError(ctx, "Not a Rowset object"); - if (!rs->vm) return rs->interrupted ? JS_ThrowInternalError(ctx, "interrupted") : JS_NewArray(ctx); + if (!rs->vm) return rs->ended ? js_rowset_ended(ctx, rs) : JS_NewArray(ctx); JSValue result = JS_NewArray(ctx); if (JS_IsException(result)) return JS_EXCEPTION; @@ -228,7 +233,6 @@ static JSValue js_rowset_to_array(JSContext *ctx, JSValueConst this_val, int arg } // as in js_rowset_next: an error is an exception, not a shorter array - if ((rc == SQLITE_INTERRUPT) && !js->check_interrupted) js->cancel_interrupted = true; if (rc != SQLITE_DONE) { JS_FreeValue(ctx, result); result = JS_ThrowInternalError(ctx, "%s", sqlite3_errmsg(sqlite3_db_handle(rs->vm))); @@ -243,6 +247,15 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { rowset *rs = (rowset *)JS_GetOpaque(val, js->rowSetClassID); if (!rs) return; + // A statement that is mid-query holds the state of every aggregate and window function it is + // computing, and sqlite3_finalize() runs each one's final as it finalizes it. For a JavaScript + // function that runs JavaScript, which a QuickJS class finalizer must not do: this one runs + // inside free_object() or inside the cycle collector, and a collection that the JavaScript + // starts can free the very object being freed. So such a statement is left listed and ended + // from js_end_rowsets(), where JavaScript may run. One that is not busy holds no such state, + // so finalizing it here cannot come back into JavaScript. + if (rs->vm && sqlite3_stmt_busy(rs->vm)) { rs->orphaned = true; js->orphans++; return; } + if (rs->prev) rs->prev->next = rs->next; else if (js->rowsets == rs) js->rowsets = rs->next; if (rs->next) rs->next->prev = rs->prev; @@ -250,26 +263,38 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { sqlite3_free(rs); } -// Ends every result set of the connection that is still open. SQLite keeps an interrupt in effect -// until no statement of the connection is running, and an open result set is a running statement: -// one that JavaScript keeps, in a global say, or that is garbage not yet collected, would make every -// later statement fail with "interrupted" until the connection closed, the statements that could -// release it included. Only to be called where none of them is being stepped: see js_leave(). +// Ends the result sets of the connection: with all, every one still open, and otherwise only the +// ones whose JavaScript object is gone (see js_rowset_finalizer). An open result set is a statement +// still running, which keeps a read transaction open, keeps an interrupt in effect until it ends, +// and stops sqlite3_close() from closing the connection at all, so none outlives the call into +// JavaScript that created it: see js_leave(). Only to be called where none of them is being +// stepped, which holds wherever JavaScript is not running inside one. // Finalizing a statement can run JavaScript, the final of a window or aggregate function it was // computing, whose js_leave() comes back here and whose garbage collection can free result sets // of the list. So each statement is taken from its result set before it is finalized, the list // is walked again from its head after each one, and a nested call does nothing. -static void js_end_rowsets (globaljs_context *js) { +static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { if (js->ending_rowsets) return; js->ending_rowsets = true; for (;;) { rowset *rs = js->rowsets; - while (rs && !rs->vm) rs = rs->next; + while (rs && !(rs->orphaned || (all && rs->vm))) rs = rs->next; if (!rs) break; sqlite3_stmt *vm = rs->vm; - rs->vm = NULL; - rs->interrupted = true; - sqlite3_finalize(vm); + if (rs->orphaned) { + // nothing in JavaScript can reach it any more, so it is unlisted and freed here + // rather than left for another pass to find + if (rs->prev) rs->prev->next = rs->next; + else if (js->rowsets == rs) js->rowsets = rs->next; + if (rs->next) rs->next->prev = rs->prev; + sqlite3_free(rs); + js->orphans--; + } else { + rs->vm = NULL; + rs->ended = true; + if (interrupted) rs->interrupted = true; + } + if (vm) sqlite3_finalize(vm); } js->ending_rowsets = false; } @@ -334,19 +359,18 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { UNUSED(rt); globaljs_context *js = (globaljs_context *)opaque; js_keep_gc_below_limit(js); - // JavaScript that ending result sets runs, the final of a window or aggregate function as its - // statement is finalized, belongs to a call already stopped. Before SQLite 3.41 nothing else - // would stop it: it begins after the cancel, and sqlite3_is_interrupted() is missing. - if (js->ending_rowsets) return 1; // Only a call (see js_enter) is cancelled: the JavaScript a connection runs while it is set // up is not one, and stopping it would make the connection fail to load the extension. if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { // The statement is interrupted too: a collation cannot report an error, so the // statement would go on calling JavaScript, each call beginning after the cancel. if (js->db) sqlite3_interrupt(js->db); - js->cancel_interrupted = true; return 1; } + // Ending a cancelled call's result sets runs the finals of the window and aggregate functions + // they were computing, each a call that begins after the cancel: stopped too, since before + // SQLite 3.41 nothing else would stop one that never ends. + if (js->ending_cancelled) return 1; return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); } @@ -439,6 +463,30 @@ static void js_mem_reset_peak (globaljs_context *js) { #define SQLITE_JS_STACK_MIN (32 * 1024) #endif +#if defined(__linux__) +// The high address of the initial thread's stack, as the kernel sees it, read from +// /proc/self/maps, or 0 where it cannot be read. pthread_attr_getstack() reaches only to the top +// of what the program may use, which is below the block of argv, environment and auxiliary vector +// that the kernel puts at the top of the stack; RLIMIT_STACK is counted from above that block. A +// bound counted from pthread's top therefore lands below the real one by the size of the block, +// which Linux lets grow to a quarter of RLIMIT_STACK: 2 MB of an 8 MB stack. +static uintptr_t js_stack_kernel_top (void) { + FILE *maps = fopen("/proc/self/maps", "r"); + if (!maps) return 0; + char line[512]; + uintptr_t high = 0; + while (fgets(line, sizeof(line), maps)) { + if (strstr(line, "[stack]")) { + unsigned long long low = 0, hi = 0; + if (sscanf(line, "%llx-%llx", &low, &hi) == 2) high = (uintptr_t)hi; + break; + } + } + fclose(maps); + return high; +} +#endif + // The lowest address of the calling thread's stack, found once per thread: on Linux, finding the // main thread's stack reads /proc/self/maps. Returns false where the stack cannot be found. static bool js_stack_low (uintptr_t sp, uintptr_t *low) { @@ -471,13 +519,24 @@ static bool js_stack_low (uintptr_t sp, uintptr_t *low) { // RLIMIT_STACK is how far it may grow, so for that thread it is the bound that counts. if (syscall(SYS_gettid) == (long)getpid()) { struct rlimit limit; - if ((getrlimit(RLIMIT_STACK, &limit) == 0) && (limit.rlim_cur != RLIM_INFINITY)) { - // counted from the top of the stack, as the kernel counts it: counted from sp, a first - // measurement deep in the stack would put the bound below the real one - uintptr_t high = (uintptr_t)addr + size; - uintptr_t grows_to = (high > (uintptr_t)limit.rlim_cur) ? high - (uintptr_t)limit.rlim_cur : 0; - if (grows_to < thread_low) thread_low = grows_to; + if ((getrlimit(RLIMIT_STACK, &limit) != 0) || (limit.rlim_cur == RLIM_INFINITY)) { + // Without a finite RLIMIT_STACK there is no bound to measure, and glibc then reports + // a stack of nearly the whole address space: about 85 TB, which + // js_set_max_stack_size() would offer and accept, and code that calls itself without + // end would take the memory of the machine until it was killed. So the stack counts + // as unmeasurable, which allows up to the default the thread certainly has. + thread_low = 0; + thread_unknown = true; + return false; } + // counted from the top of the stack, as the kernel counts it: counted from sp, a first + // measurement deep in the stack would put the bound below the real one. The kernel's own + // top is above the argv and environment block, which pthread's does not reach, so that + // one is only the fallback: see js_stack_kernel_top(). + uintptr_t high = js_stack_kernel_top(); + if (high == 0) high = (uintptr_t)addr + size; + uintptr_t grows_to = (high > (uintptr_t)limit.rlim_cur) ? high - (uintptr_t)limit.rlim_cur : 0; + if (grows_to < thread_low) thread_low = grows_to; } #else UNUSED(sp); @@ -532,15 +591,19 @@ static void js_enter (globaljs_context *js) { JS_SetMaxStackSize(js->runtime, size); } -// Once the outermost call has returned, no result set is being stepped, so those an interrupt left -// open are ended here: see js_end_rowsets(). -// A cancel's own interrupt counts even where sqlite3_is_interrupted() is missing (SQLite before 3.41). +// Once the outermost call has returned, no result set is being stepped, so every one still open is +// ended here: see js_end_rowsets(). static void js_leave (globaljs_context *js) { if (--js->depth > 0) return; - if (js->cancel_interrupted || (js->check_interrupted && js->db && sqlite3_is_interrupted(js->db))) { - js->cancel_interrupted = false; - js_end_rowsets(js); - } + // a final that ending them runs returns here: the call that is ending them goes on + if (!js->rowsets || js->ending_rowsets) return; + // A cancel (sqlitejs_cancel_all) during the call interrupted it, and before SQLite 3.41 is + // the only interrupt that shows: its result sets read on as interrupted. + bool cancelled = (js->cancel_epoch != js_cancel_epoch_load()); + bool interrupted = cancelled || ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)); + js->ending_cancelled = cancelled; + js_end_rowsets(js, true, interrupted); + js->ending_cancelled = false; } static globaljs_context *globaljs_init (sqlite3 *db) { @@ -848,6 +911,13 @@ static int js_bind_value (JSContext *ctx, sqlite3_stmt *vm, int index, JSValueCo } static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int argc, JSValueConst *argv) { + // A result set dropped while its statement was mid-query waits for a point where JavaScript may + // run (see js_rowset_finalizer). Waiting for the call to return is too long for a loop that + // drops one on every turn: the statements would pile up until the loop ran out of memory. Here + // is such a point, and the one a loop like that passes through. + globaljs_context *waiting = JS_GetContextOpaque(ctx); + if (waiting && (waiting->orphans > 0)) js_end_rowsets(waiting, false, false); + sqlite3_stmt *vm = NULL; rowset *rs = NULL; @@ -876,7 +946,9 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int if (!rs) goto abort_with_dberror; rs->vm = vm; rs->ncols = sqlite3_column_count(vm); + rs->ended = false; rs->interrupted = false; + rs->orphaned = false; rs->prev = rs->next = NULL; // create Rowset JS object diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.h b/subprojects/sqlite-js/upstream/src/sqlitejs.h index 2d6bb3d16d..ed6ce4e200 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.h +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.h @@ -16,7 +16,7 @@ #include "sqlite3.h" #endif -#define SQLITE_JS_VERSION "1.4.1" +#define SQLITE_JS_VERSION "1.4.2" int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); const char *sqlitejs_version (void); diff --git a/subprojects/sqlite-js/vendor.sh b/subprojects/sqlite-js/vendor.sh index 2bc45c8943..124e3aad79 100755 --- a/subprojects/sqlite-js/vendor.sh +++ b/subprojects/sqlite-js/vendor.sh @@ -2,8 +2,8 @@ # Rebuilds upstream/ from the sqlite-js release VERSION and patches/, or checks that it matches. # Usage: vendor.sh [--check] [TARBALL] (without TARBALL, downloads it) set -euo pipefail -VERSION=1.4.1 -SHA256=d45d394fc7cb37070a64fa248994c7fef7c10cff31541eb57608405753fc3078 +VERSION=1.4.2 +SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 URL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/$VERSION.tar.gz HERE=$(cd "$(dirname "$0")" && pwd) CHECK=false From 464e6e7efee9be92ccf2af8a74755b2def9ec9a4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 13 Nov 2026 10:05:54 -0800 Subject: [PATCH 041/203] ADFA-7082: Test sqlite-js 1.4.2's result-set rule and patch 0002 glue_test.c, for 1.4.2: - The progress-handler case kept a result set across calls, which 1.4.2 no longer allows. It now checks, within one call, that a statement a progress handler stopped (as Android's cancelling does) leaves the call's other result set readable, on any SQLite, and that the connection runs SQL afterwards. - A direct sqlite3_interrupt() before SQLite 3.41 shows nowhere, so its kept result set reads as one that outlived its call; on 3.41 and later, as interrupted. - The cleanup that read a kept result set after its call is gone: it now throws. test.sh and the README name patch 0002 for the run as on SQLite 3.40, and the README lists the two patches, states the 1.4.2 rule, and says the 1.4.2 build has not been run on a phone yet. test.sh: upstream's suite 17 of 17 (its 16 and 0001's Cancel all), and glue_test 37 of 37 both normally and as on SQLite 3.40. Without patch 0002, the normal run still passes 37 of 37, and the 3.40 run fails as expected: the kept result set after a cancel reads "The result set was closed ..." rather than "interrupted", and the window function whose final never ends hangs until the 30 s alarm stops the test. Both ABIs build with NDK 29, and libsqlitejs.so exports only JNI_OnLoad and the three entry points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- subprojects/sqlite-js/README.md | 19 ++++----- subprojects/sqlite-js/src/test/c/glue_test.c | 43 ++++++++++---------- subprojects/sqlite-js/test.sh | 2 +- 3 files changed, 29 insertions(+), 35 deletions(-) diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index b7be38deb7..40a8e826cf 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -6,16 +6,11 @@ An AAR that lets apps built with Code on the Go define and call JavaScript funct ## Contents -- `upstream/`: the sqlite-js 1.4.1 release (Apache-2.0), the first with our earlier changes (upstream pull requests #11 to #19), with QuickJS amalgamated in `libs/quickjs.c` (MIT), and `patches/` applied. Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. -- `patches/`: our changes, none of them merged upstream yet: +- `upstream/`: the sqlite-js 1.4.2 release (Apache-2.0), which has our earlier changes (upstream pull requests #11 to #19, and #22 to #24), with QuickJS amalgamated in `libs/quickjs.c` (MIT), and `patches/` applied. Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. +- `patches/`: our changes not upstream: - 0001 adds `sqlitejs_cancel_all()`: Android cannot otherwise stop JavaScript that never returns. It is offered upstream in sqliteai/sqlite-js issue 20. - - 0002 keeps QuickJS's stack check within the thread's stack in two cases where code that called itself without end crashed the process: a thread with less than 64 KB of stack left, and a main thread first measured deep in its stack. - - 0003 collects garbage after any "out of memory" error and whenever a memory limit is set. Before, garbage could leave an allocation that fits in the limit failing on every try. - - 0004 ends the `db.exec` result sets that an interrupted call leaves open. SQLite keeps an interrupt in effect while any statement of the connection runs, so after `cancelAll()` stopped JavaScript that kept one open, every later statement on that connection failed. - - 0005 and 0006 complete 0004. Finalizing a result set can run JavaScript, the final of a window or aggregate function, which must not end the same result set again. And on SQLite before 3.41, which cannot report an interrupt, a cancel's own interrupt counts. - - 0007 stops the JavaScript that ending result sets runs, which before SQLite 3.41 nothing else stopped. Before 3.41 only, it also counts an interrupt that a result set's statement reports. 0009 limits that to before 3.41, because a progress handler that stops a statement, as Android's cancelling does, gives the same code and interrupts nothing else. - - 0008 makes the test of 0004's garbage case a reference cycle, so that it fails without 0004. 0004, 0005 and 0008 are offered upstream as sqliteai/sqlite-js#24. - - On any SQLite, an `sqlite3_interrupt()` that lands while no JavaScript runs still leaves the connection failing every statement as long as JavaScript keeps a result set open: no JavaScript runs to end it. Android's cancelling never calls `sqlite3_interrupt()`, and `cancelAll()` is covered, but finish each result set (`toArray()`, or `next()` until it returns false) before the call that made it returns. + - 0002 completes 0001 on SQLite before 3.41, which cannot report an interrupt. Ending a cancelled call's result sets runs the finals of the window and aggregate functions they were computing, each a call that begins after the cancel: 0002 stops them, as on 3.41 and later the cancel's interrupt does, and has those result sets read on as "interrupted". +- Since 1.4.2 a `db.exec` result set does not outlive the call into JavaScript that created it: every one still open is ended when the call returns, because its statement keeps a read transaction open, keeps an interrupt in effect and stops the connection from closing. Reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned", or "interrupted" when a cancel (or, on SQLite 3.41 and later, `sqlite3_interrupt()`) stopped the call. One read to its end still reports the end of its rows. - `src/main/cpp/`: the CMake build of `libsqlitejs.so`, and `sqlitejs_android.c`, which is ours: JNI for `SqliteJs`, and the two entry points it names. The version script exports only the entry points (and upstream's `sqlite3_js_init`) and `JNI_OnLoad`. - `src/test/c/glue_test.c` and `test.sh`: the tests the Android build cannot run. See Testing. - `src/main/java/`: `SqliteJs`. @@ -43,13 +38,13 @@ Room.databaseBuilder(context, AppDb::class.java, name).openHelperFactory(factory - A connection that opened before a function was stored does not have it. So store the functions before Room opens the database, on a connection opened with `ENTRY_POINT`, since a connection cannot redefine a function it has. - Room checks queries at build time with its own SQLite, which has no JavaScript functions: mark DAO methods that call them `@SkipQueryVerification`. - SQLite loads the extension from a file, so set `packaging.jniLibs.useLegacyPackaging = true`. -- Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its statement is interrupted too, so that one whose JavaScript cannot report an error (a collation) also stops. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted `INSERT`, `UPDATE` or `DELETE` inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a new connection. Every `db.exec` result set still open on the connection is ended, including ones that earlier calls kept, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. +- Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its statement is interrupted too, so that one whose JavaScript cannot report an error (a collation) also stops. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted `INSERT`, `UPDATE` or `DELETE` inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a new connection. The `db.exec` result sets of a call it stops are ended, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. -Built from 1.3.7 with our changes as patches, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 5 ms. +Built from 1.4.1 with our patches of the time, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 25 ms. The build from 1.4.2 has not been run on a phone yet. ## Testing -The Android build compiles but does not run sqlite-js. `test.sh` builds it on the host and runs upstream's test suite (`test/main.c`, which is not vendored) on its source with `patches/` applied, and `src/test/c/glue_test.c` on `upstream/` and `sqlitejs_android.c`: what each entry point loads and runs, that a stored function that fails to load is skipped, that one whose loading is cancelled loads on a second try, even when its code keeps a result set open, and that a cancel or a direct interrupt during `db.exec` ends kept result sets and a cancel stops a window function's final, but a progress handler does not end them. It runs `glue_test.c` twice, the second time with sqlite-js working as on SQLite before 3.41 (for patches 0006, 0007 and 0009). It needs gcc, make and a JDK (for `jni.h`). The `test-sqlite-js.yml` workflow runs `vendor.sh --check` and `test.sh` on every pull request that changes this module. +The Android build compiles but does not run sqlite-js. `test.sh` builds it on the host and runs upstream's test suite (`test/main.c`, which is not vendored) on its source with `patches/` applied, and `src/test/c/glue_test.c` on `upstream/` and `sqlitejs_android.c`: what each entry point loads and runs, that a stored function that fails to load is skipped, that one whose loading is cancelled loads on a second try, even when its code keeps a result set open, and that a cancel or a direct interrupt during `db.exec` ends kept result sets and a cancel stops a window function's final, but a statement a progress handler stops leaves the call's other result sets readable. It runs `glue_test.c` twice, the second time with sqlite-js working as on SQLite before 3.41 (for patch 0002). It needs gcc, make and a JDK (for `jni.h`). The `test-sqlite-js.yml` workflow runs `vendor.sh --check` and `test.sh` on every pull request that changes this module. ## Updating diff --git a/subprojects/sqlite-js/src/test/c/glue_test.c b/subprojects/sqlite-js/src/test/c/glue_test.c index 3eaaca7cb7..bd2a6f33f3 100644 --- a/subprojects/sqlite-js/src/test/c/glue_test.c +++ b/subprojects/sqlite-js/src/test/c/glue_test.c @@ -288,13 +288,13 @@ int main (void) { check(cancel_calls == 2, "the trusted entry point loads h again after the cancel stops it"); check(answers(db, "SELECT h()", "9"), "h is loaded"); check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL afterwards"); - exec(db, "SELECT js_eval('held.toArray(); 0')"); sqlite3_close(db); unlink(held); - // After a cancel, the result sets JavaScript keeps open are ended, as the interrupt would - // otherwise stay in effect: every later statement on the connection failed. Run as on SQLite - // before 3.41 too (GLUE_AS_SQLITE_3_40), where the cancel's own record shows it (0006). + // A result set JavaScript keeps is ended when the call that made it returns (sqlite-js 1.4.2), + // or the interrupt would stay in effect and every later statement on the connection fail. + // After a cancel, reading on throws "interrupted", also as on SQLite before 3.41 + // (GLUE_AS_SQLITE_3_40), where only the cancel itself shows it (patch 0002). signal(SIGALRM, on_alarm); char kept[512]; snprintf(kept, sizeof(kept), "%s/kept.db", dir); @@ -308,7 +308,7 @@ int main (void) { "the kept result set was ended"); // Ending a result set that is computing a window function runs the function's final, which - // begins after the cancel: the cancel must still stop it, also before SQLite 3.41 (0007). + // begins after the cancel: the cancel must still stop it, also before SQLite 3.41 (patch 0002). check(exec(db, "SELECT js_create_window('loop_final', 'total = 0;', '(function (args) { total += args[0]; })', " "'(function () { while (true) {} })', '(function () { return total; })', " "'(function (args) { total -= args[0]; })')") == SQLITE_OK, @@ -319,33 +319,32 @@ int main (void) { check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that cancel"); // A direct sqlite3_interrupt() that reaches the SQL of a db.exec, while another result set is - // kept: the kept one is ended, so the connection runs SQL afterwards. Before SQLite 3.41, the - // step's SQLITE_INTERRUPT is the only sign of it (0007), and that query never ends otherwise. + // kept: the kept one is ended, so the connection runs SQL afterwards. Before SQLite 3.41 no + // interrupt shows, so it reads as a result set that outlived its call. check(exec_interrupted(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); held.next(); " "db.exec(\"SELECT started()\").next(); " "db.exec(\"WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c\").next()')") != SQLITE_OK, "sqlite3_interrupt() stops db.exec SQL while another result set is kept"); check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that interrupt"); - check(answers(db, "SELECT js_eval('try { held.next(); \"open\" } catch (e) { \"ended: \" + e.message }')", "ended: interrupted"), +#ifdef GLUE_AS_SQLITE_3_40 + check(answers(db, "SELECT js_eval('try { held.next(); \"open\" } catch (e) { \"ended: \" + e.message }')", + "ended: The result set was closed when the call into JavaScript that created it returned"), "the kept result set was ended"); +#else + check(answers(db, "SELECT js_eval('try { held.next(); \"open\" } catch (e) { \"ended: \" + e.message }')", "ended: interrupted"), + "the kept result set was ended, as interrupted"); +#endif // A progress handler that stops a statement, as Android's cancelling does, interrupts nothing - // else, so it leaves result sets that earlier calls kept. Before 3.41, which cannot tell it - // from an interrupt, they are ended. - check(answers(db, "SELECT js_eval('globalThis.kept = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); kept.next()')", "1"), - "JavaScript keeps a result set open"); + // else: the call's other result sets read on, on any SQLite. sqlite3_progress_handler(db, 1000, stop_statement, NULL); - exec(db, "SELECT js_eval('try { db.exec(\"WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 100000000) " - "SELECT count(*) FROM c\").next(); } catch (e) {} 0')"); + check(answers(db, "SELECT js_eval('const kept = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); kept.next(); " + "try { db.exec(\"WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 100000000) " + "SELECT count(*) FROM c\").next(); } catch (e) {} kept.next() && kept.get(0)')", "2"), + "a statement a progress handler stopped leaves the call's other result set readable"); sqlite3_progress_handler(db, 0, NULL, NULL); -#ifdef GLUE_AS_SQLITE_3_40 - check(answers(db, "SELECT js_eval('kept.next()')", "interrupted"), - "before 3.41, a statement a progress handler stopped ends the kept result set"); -#else - check(answers(db, "SELECT js_eval('kept.next()')", "1"), - "a statement a progress handler stopped leaves the kept result set"); -#endif - exec(db, "SELECT js_eval('kept = null; held = null; 0')"); + check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after a progress handler stopped a statement"); + exec(db, "SELECT js_eval('held = null; 0')"); sqlite3_close_v2(db); unlink(kept); diff --git a/subprojects/sqlite-js/test.sh b/subprojects/sqlite-js/test.sh index 36e5d8d857..fc959acc20 100755 --- a/subprojects/sqlite-js/test.sh +++ b/subprojects/sqlite-js/test.sh @@ -39,7 +39,7 @@ build gcc -O1 -g -Wall -Wextra -Werror "${DEFS[@]}" "${INC[@]}" \ "$WORK/sqlitejs.o" "$WORK/quickjs.o" "$WORK/sqlite3.o" -o "$WORK/glue_test" -lm -lpthread -ldl "$WORK/glue_test" -# again with sqlite-js working as on SQLite before 3.41, which patches 0006 and 0007 are for +# again with sqlite-js working as on SQLite before 3.41, which patch 0002 is for echo "# sqlitejs_android.c, as on SQLite 3.40" build gcc -O1 -g -w "${DEFS[@]}" "${INC[@]}" -Dsqlite3_libversion_number=glue_sqlite3_libversion_number \ -c "$U/src/sqlitejs.c" -o "$WORK/sqlitejs-3.40.o" From 5b9b062eb33eaf3e7e243ce6fba837d0964149b9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 13 Nov 2026 17:05:48 -0800 Subject: [PATCH 042/203] ADFA-7082: Keep a call's cancel for the finals its result sets run From the independent review of 3a5cb5356 and 464e6e7ef (no critical, high or medium findings; F01 to F05 low or nits). Patch 0002 told a cancelled call apart only once, in js_leave(), and each final that ending its result sets ran entered JavaScript as a new call with a new cancel epoch. So, before SQLite 3.41: - a cancel that landed while the result sets were ended stopped only the final then running, and the next final that never ended hung the statement (F01); - a cancel that landed just before the call returned let the call succeed with its finals skipped, on any SQLite (F02). Patch 0002 now keeps the call's epoch while its result sets are ended (js_enter), so a cancel during the call or the ending stops every final, and a late cancel fails the statement with an interrupt. The ending_cancelled flag and its interrupt-handler check are gone; the patch is 8 lines. upstream/ is regenerated with vendor.sh. glue_test.c, 44 tests (was 37): - 31: a cancelled call that keeps two result sets whose window finals never end (F03's case); - 33-34: the cancel lands during the first final of a call that returned normally (F01); - 36-37: a cancel that lands as the call returns fails it (F02); - 43: after a progress handler's stop, the kept result set reads as outliving its call, not as interrupted (F04; it passes without the fix too, as a guard against counting such a stop as an interrupt). test.sh: upstream's suite 17 of 17; the glue test 44 of 44 normally and as on SQLite 3.40. With the previous 0002, test 37 fails in the normal run and the 3.40 run hangs at test 34; with 0001 alone, test 37 fails, and the 3.40 run fails test 29 and hangs at test 31. README: what 0002 does now, and what the glue test covers (F05). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- subprojects/sqlite-js/README.md | 4 +- ...call-s-result-sets-as-interrupted-an.patch | 81 ++++++++----------- subprojects/sqlite-js/src/test/c/glue_test.c | 49 +++++++++-- subprojects/sqlite-js/upstream/src/sqlitejs.c | 15 ++-- 4 files changed, 85 insertions(+), 64 deletions(-) diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index 40a8e826cf..c3a7cc55cc 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -9,7 +9,7 @@ An AAR that lets apps built with Code on the Go define and call JavaScript funct - `upstream/`: the sqlite-js 1.4.2 release (Apache-2.0), which has our earlier changes (upstream pull requests #11 to #19, and #22 to #24), with QuickJS amalgamated in `libs/quickjs.c` (MIT), and `patches/` applied. Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. - `patches/`: our changes not upstream: - 0001 adds `sqlitejs_cancel_all()`: Android cannot otherwise stop JavaScript that never returns. It is offered upstream in sqliteai/sqlite-js issue 20. - - 0002 completes 0001 on SQLite before 3.41, which cannot report an interrupt. Ending a cancelled call's result sets runs the finals of the window and aggregate functions they were computing, each a call that begins after the cancel: 0002 stops them, as on 3.41 and later the cancel's interrupt does, and has those result sets read on as "interrupted". + - 0002 completes 0001. Ending a call's result sets runs the finals of the window and aggregate functions they were computing, and each final entered JavaScript as a new call, which a cancel during the call no longer stopped; before SQLite 3.41 nothing else did. The finals now belong to the call: a cancel during the call or while its result sets are ended stops them, a cancel that lands just before the call returns fails it rather than skipping its finals, and those result sets read on as "interrupted". - Since 1.4.2 a `db.exec` result set does not outlive the call into JavaScript that created it: every one still open is ended when the call returns, because its statement keeps a read transaction open, keeps an interrupt in effect and stops the connection from closing. Reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned", or "interrupted" when a cancel (or, on SQLite 3.41 and later, `sqlite3_interrupt()`) stopped the call. One read to its end still reports the end of its rows. - `src/main/cpp/`: the CMake build of `libsqlitejs.so`, and `sqlitejs_android.c`, which is ours: JNI for `SqliteJs`, and the two entry points it names. The version script exports only the entry points (and upstream's `sqlite3_js_init`) and `JNI_OnLoad`. - `src/test/c/glue_test.c` and `test.sh`: the tests the Android build cannot run. See Testing. @@ -44,7 +44,7 @@ Built from 1.4.1 with our patches of the time, it was tested in a trial app (req ## Testing -The Android build compiles but does not run sqlite-js. `test.sh` builds it on the host and runs upstream's test suite (`test/main.c`, which is not vendored) on its source with `patches/` applied, and `src/test/c/glue_test.c` on `upstream/` and `sqlitejs_android.c`: what each entry point loads and runs, that a stored function that fails to load is skipped, that one whose loading is cancelled loads on a second try, even when its code keeps a result set open, and that a cancel or a direct interrupt during `db.exec` ends kept result sets and a cancel stops a window function's final, but a statement a progress handler stops leaves the call's other result sets readable. It runs `glue_test.c` twice, the second time with sqlite-js working as on SQLite before 3.41 (for patch 0002). It needs gcc, make and a JDK (for `jni.h`). The `test-sqlite-js.yml` workflow runs `vendor.sh --check` and `test.sh` on every pull request that changes this module. +The Android build compiles but does not run sqlite-js. `test.sh` builds it on the host and runs upstream's test suite (`test/main.c`, which is not vendored) on its source with `patches/` applied, and `src/test/c/glue_test.c` on `upstream/` and `sqlitejs_android.c`: what each entry point loads and runs, that a stored function that fails to load is skipped, that one whose loading is cancelled loads on a second try, even when its code keeps a result set open, what reading a kept result set throws after a cancel or a direct interrupt, that a cancel stops every window function's final that ending the call's result sets runs, also when it lands while they are ended or just before the call returns, and that a statement a progress handler stops is not an interrupt. It runs `glue_test.c` twice, the second time with sqlite-js working as on SQLite before 3.41 (for patch 0002). It needs gcc, make and a JDK (for `jni.h`). The `test-sqlite-js.yml` workflow runs `vendor.sh --check` and `test.sh` on every pull request that changes this module. ## Updating diff --git a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch index c0fcdce9d6..8032691624 100644 --- a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch +++ b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch @@ -1,73 +1,60 @@ -From 59370bd43a82eb8fcd56cb78002ccc7fc811bfb5 Mon Sep 17 00:00:00 2001 +From 0432e1e8dac47a8e54b2f4b812fabe20ea9e8be3 Mon Sep 17 00:00:00 2001 From: David Schachter -Date: Fri, 13 Nov 2026 10:00:14 -0800 -Subject: [PATCH 2/2] End a cancelled call's result sets as interrupted, and - stop their finals +Date: Fri, 13 Nov 2026 16:58:23 -0800 +Subject: [PATCH] End a cancelled call's result sets as interrupted, and stop + their finals Since 1.4.2 every result set still open when the outermost call into JavaScript returns is ended there, which runs the final of each window -or aggregate function its statement was computing. After -sqlitejs_cancel_all() stopped the call, each such final is a new call -that begins after the cancel, so the cancel does not stop it. On SQLite -3.41 and later the interrupt the cancel left on the connection does. -Before 3.41, which has no sqlite3_is_interrupted(), nothing did, and a -final that never ends hung the statement for good. +or aggregate function its statement was computing. Each final enters +JavaScript as a new outermost call, so js_enter() took the cancel epoch +of that moment and a cancel during the call no longer stopped it. On +SQLite 3.41 and later the interrupt the cancel left on the connection +does; before 3.41 nothing did, and a final that never ends hung the +statement for good. -A call that a cancel stopped is now told apart in js_leave() by its -cancel epoch. The finals that ending its result sets runs are stopped, -and reading on from those result sets throws "interrupted", as after -sqlite3_interrupt() on 3.41 and later, rather than the message for a -result set that outlived its call. A final that ending them runs returns -through js_leave() itself, which now leaves the ending to the call that -started it. +The finals that ending a call's result sets runs now keep that call's +epoch. A cancel during the call, or during the ending, stops every one +of them, and a cancel that lands just before the call returns fails the +statement with an interrupt, rather than letting the call succeed with +its finals skipped. Reading on from those result sets throws +"interrupted", as after sqlite3_interrupt() on 3.41 and later, rather +than the message for a result set that outlived its call. Before 3.41, an sqlite3_interrupt() that no cancel came with still reads as the result set outliving its call: nothing shows it. --- - src/sqlitejs.c | 15 +++++++++++++-- - 1 file changed, 13 insertions(+), 2 deletions(-) + src/sqlitejs.c | 10 ++++++++-- + 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index e5fea55..a0debe7 100644 +index e5fea55..29499a0 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -75,6 +75,7 @@ typedef struct { - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - int orphans; // of those, the ones whose JavaScript object is gone - bool ending_rowsets; // js_end_rowsets() is running -+ bool ending_cancelled; // and a cancel stopped the call: see js_leave() - } globaljs_context; - - typedef struct { -@@ -366,6 +367,10 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { - if (js->db) sqlite3_interrupt(js->db); - return 1; - } -+ // Ending a cancelled call's result sets runs the finals of the window and aggregate functions -+ // they were computing, each a call that begins after the cancel: stopped too, since before -+ // SQLite 3.41 nothing else would stop one that never ends. -+ if (js->ending_cancelled) return 1; - return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); - } - -@@ -590,9 +595,15 @@ static void js_enter (globaljs_context *js) { - // ended here: see js_end_rowsets(). +@@ -576,7 +576,10 @@ static bool js_stack_room (size_t *room) { + // runs JavaScript) is on the same thread and keeps the outer call's limit. + static void js_enter (globaljs_context *js) { + if (js->depth++ > 0) return; +- js->cancel_epoch = js_cancel_epoch_load(); ++ // The finals that ending a call's result sets runs (see js_leave) belong to that call: they keep ++ // its epoch, so a cancel during the call or during the ending stops them, as it would have ++ // stopped the call. Before SQLite 3.41 nothing else would stop one that never ends. ++ if (!js->ending_rowsets) js->cancel_epoch = js_cancel_epoch_load(); + JS_UpdateStackTop(js->runtime); + // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails + // with "Maximum call stack size exceeded" rather than running past the end of the stack. A +@@ -591,7 +594,10 @@ static void js_enter (globaljs_context *js) { static void js_leave (globaljs_context *js) { if (--js->depth > 0) return; -- if (!js->rowsets) return; + if (!js->rowsets) return; - bool interrupted = (sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db); -+ // a final that ending them runs returns here: the call that is ending them goes on -+ if (!js->rowsets || js->ending_rowsets) return; + // A cancel (sqlitejs_cancel_all) during the call interrupted it, and before SQLite 3.41 is + // the only interrupt that shows: its result sets read on as interrupted. + bool cancelled = (js->cancel_epoch != js_cancel_epoch_load()); + bool interrupted = cancelled || ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)); -+ js->ending_cancelled = cancelled; js_end_rowsets(js, true, interrupted); -+ js->ending_cancelled = false; } - static globaljs_context *globaljs_init (sqlite3 *db) { -- 2.53.0 diff --git a/subprojects/sqlite-js/src/test/c/glue_test.c b/subprojects/sqlite-js/src/test/c/glue_test.c index bd2a6f33f3..28d8b8265a 100644 --- a/subprojects/sqlite-js/src/test/c/glue_test.c +++ b/subprojects/sqlite-js/src/test/c/glue_test.c @@ -88,6 +88,14 @@ static void *cancel_when_started (void *arg) { return NULL; } +// Cancels from inside the statement: the cancel lands before the call returns, but after the +// JavaScript last checked for one +static void cancel_now (sqlite3_context *context, int argc, sqlite3_value **argv) { + (void)argc; (void)argv; + sqlitejs_cancel_all(); + sqlite3_result_null(context); +} + // a statement whose JavaScript a cancel must stop: one that never ends would hang the test static void on_alarm (int sig) { (void)sig; @@ -307,15 +315,43 @@ int main (void) { check(answers(db, "SELECT js_eval('try { held.next(); \"open\" } catch (e) { \"ended: \" + e.message }')", "ended: interrupted"), "the kept result set was ended"); - // Ending a result set that is computing a window function runs the function's final, which - // begins after the cancel: the cancel must still stop it, also before SQLite 3.41 (patch 0002). + // Ending a result set that is computing a window function runs the function's final. The finals + // belong to the call that kept the result sets, so its cancel must stop every one of them, also + // before SQLite 3.41 (patch 0002). check(exec(db, "SELECT js_create_window('loop_final', 'total = 0;', '(function (args) { total += args[0]; })', " "'(function () { while (true) {} })', '(function () { return total; })', " "'(function (args) { total -= args[0]; })')") == SQLITE_OK, "a window function whose final never ends"); check(exec_cancelled(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT loop_final(column1) OVER (ORDER BY column1) " - "FROM (VALUES (1), (2), (3))\"); held.next(); db.exec(\"SELECT started()\").next(); for (;;) {}')") != SQLITE_OK, - "a cancel ends a kept result set whose window function's final never ends"); + "FROM (VALUES (1), (2), (3))\"); held.next(); " + "globalThis.held2 = db.exec(\"SELECT loop_final(column1) OVER (ORDER BY column1) " + "FROM (VALUES (1), (2), (3))\"); held2.next(); db.exec(\"SELECT started()\").next(); for (;;) {}')") != SQLITE_OK, + "a cancel ends two kept result sets whose window functions' finals never end"); + check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that cancel"); + // A call that returns normally, and the cancel lands while its result sets are ended: the + // newer one's final calls started() and never ends, then the older one's final never ends. + check(exec(db, "SELECT js_create_window('start_final', 'total = 0;', '(function (args) { total += args[0]; })', " + "'(function () { db.exec(\"SELECT started()\").next(); while (true) {} })', '(function () { return total; })', " + "'(function (args) { total -= args[0]; })')") == SQLITE_OK, + "a window function whose final starts the cancel and never ends"); + check(exec_cancelled(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT loop_final(column1) OVER (ORDER BY column1) " + "FROM (VALUES (1), (2), (3))\"); held.next(); " + "globalThis.held2 = db.exec(\"SELECT start_final(column1) OVER (ORDER BY column1) " + "FROM (VALUES (1), (2), (3))\"); held2.next(); 0')") != SQLITE_OK, + "a cancel while a call's result sets are ended stops every final"); + check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that cancel"); + // A cancel that lands as the call returns, after its JavaScript last checked for one: the call + // fails, rather than returning with its result set's final skipped. + sqlite3_create_function(db, "cancel_now", 0, SQLITE_UTF8, NULL, cancel_now, NULL, NULL); + check(exec(db, "CREATE TABLE ran(x)") == SQLITE_OK + && exec(db, "SELECT js_create_window('long_final', 'total = 0;', '(function (args) { total += args[0]; })', " + "'(function () { let s = 0; for (let i = 0; i < 20000000; i++) s += i; " + "db.exec(\"INSERT INTO ran VALUES (1)\").next(); return total; })', '(function () { return total; })', " + "'(function (args) { total -= args[0]; })')") == SQLITE_OK, + "a window function whose final takes a while and records that it ran"); + check(exec(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT long_final(column1) OVER (ORDER BY column1) " + "FROM (VALUES (1), (2), (3))\"); held.next(); db.exec(\"SELECT cancel_now()\").next(); 0')") != SQLITE_OK, + "a cancel that lands as a call returns fails the call"); check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that cancel"); // A direct sqlite3_interrupt() that reaches the SQL of a db.exec, while another result set is @@ -338,11 +374,14 @@ int main (void) { // A progress handler that stops a statement, as Android's cancelling does, interrupts nothing // else: the call's other result sets read on, on any SQLite. sqlite3_progress_handler(db, 1000, stop_statement, NULL); - check(answers(db, "SELECT js_eval('const kept = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); kept.next(); " + check(answers(db, "SELECT js_eval('globalThis.kept = db.exec(\"SELECT 1 UNION ALL SELECT 2\"); kept.next(); " "try { db.exec(\"WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 100000000) " "SELECT count(*) FROM c\").next(); } catch (e) {} kept.next() && kept.get(0)')", "2"), "a statement a progress handler stopped leaves the call's other result set readable"); sqlite3_progress_handler(db, 0, NULL, NULL); + check(answers(db, "SELECT js_eval('try { kept.next(); \"open\" } catch (e) { \"ended: \" + e.message }')", + "ended: The result set was closed when the call into JavaScript that created it returned"), + "that stop was not an interrupt: the call's kept result set reads as outliving the call"); check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after a progress handler stopped a statement"); exec(db, "SELECT js_eval('held = null; 0')"); sqlite3_close_v2(db); diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.c b/subprojects/sqlite-js/upstream/src/sqlitejs.c index a0debe729e..29499a0b57 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.c +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.c @@ -75,7 +75,6 @@ typedef struct { struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() int orphans; // of those, the ones whose JavaScript object is gone bool ending_rowsets; // js_end_rowsets() is running - bool ending_cancelled; // and a cancel stopped the call: see js_leave() } globaljs_context; typedef struct { @@ -367,10 +366,6 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { if (js->db) sqlite3_interrupt(js->db); return 1; } - // Ending a cancelled call's result sets runs the finals of the window and aggregate functions - // they were computing, each a call that begins after the cancel: stopped too, since before - // SQLite 3.41 nothing else would stop one that never ends. - if (js->ending_cancelled) return 1; return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); } @@ -581,7 +576,10 @@ static bool js_stack_room (size_t *room) { // runs JavaScript) is on the same thread and keeps the outer call's limit. static void js_enter (globaljs_context *js) { if (js->depth++ > 0) return; - js->cancel_epoch = js_cancel_epoch_load(); + // The finals that ending a call's result sets runs (see js_leave) belong to that call: they keep + // its epoch, so a cancel during the call or during the ending stops them, as it would have + // stopped the call. Before SQLite 3.41 nothing else would stop one that never ends. + if (!js->ending_rowsets) js->cancel_epoch = js_cancel_epoch_load(); JS_UpdateStackTop(js->runtime); // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails // with "Maximum call stack size exceeded" rather than running past the end of the stack. A @@ -595,15 +593,12 @@ static void js_enter (globaljs_context *js) { // ended here: see js_end_rowsets(). static void js_leave (globaljs_context *js) { if (--js->depth > 0) return; - // a final that ending them runs returns here: the call that is ending them goes on - if (!js->rowsets || js->ending_rowsets) return; + if (!js->rowsets) return; // A cancel (sqlitejs_cancel_all) during the call interrupted it, and before SQLite 3.41 is // the only interrupt that shows: its result sets read on as interrupted. bool cancelled = (js->cancel_epoch != js_cancel_epoch_load()); bool interrupted = cancelled || ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)); - js->ending_cancelled = cancelled; js_end_rowsets(js, true, interrupted); - js->ending_cancelled = false; } static globaljs_context *globaljs_init (sqlite3 *db) { From 5b5cd201cfce0e6e379736f3251b48eb891af188 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 20:18:55 -0800 Subject: [PATCH 043/203] ADFA-7082: Say what a late cancel does to a call's finals From the independent review of 5b9b062eb (no code defects; tests catch what they're named for and are not flaky in 120 runs on 2 cores and 16 on 1; two low findings and a nit): - F01: "those result sets read on as interrupted" holds only when the cancel came before the call returned. js_leave() decides that once, before ending them, so a cancel that lands while they are ended stops their finals but leaves the "closed" message. - F02: a cancel stops each final at QuickJS's next interrupt check. A final that never ends is stopped and the statement fails, but a short final can still run to its end, so "rather than skipping its finals" overstated it. The patch 0002 header and README say so; 5b9b062eb's message overstated both in the same way. Patch 0002's code is unchanged. - F03: test 36's final records that it ran, and a new test 38 checks that the late cancel stopped it before it did; test 37 is renamed to say its final is a long one. test.sh: upstream's suite 17 of 17; the glue test 45 of 45 normally and as on SQLite 3.40. With 0001 alone, tests 37 and 38 fail (the final ran to its end) and the 3.40 run fails 29 and hangs at 31; with the previous 0002, test 37 fails and the 3.40 run hangs at 34. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- subprojects/sqlite-js/README.md | 2 +- ...elled-call-s-result-sets-as-interrupted-an.patch | 13 +++++++------ subprojects/sqlite-js/src/test/c/glue_test.c | 3 ++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index c3a7cc55cc..4b98454b89 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -9,7 +9,7 @@ An AAR that lets apps built with Code on the Go define and call JavaScript funct - `upstream/`: the sqlite-js 1.4.2 release (Apache-2.0), which has our earlier changes (upstream pull requests #11 to #19, and #22 to #24), with QuickJS amalgamated in `libs/quickjs.c` (MIT), and `patches/` applied. Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. - `patches/`: our changes not upstream: - 0001 adds `sqlitejs_cancel_all()`: Android cannot otherwise stop JavaScript that never returns. It is offered upstream in sqliteai/sqlite-js issue 20. - - 0002 completes 0001. Ending a call's result sets runs the finals of the window and aggregate functions they were computing, and each final entered JavaScript as a new call, which a cancel during the call no longer stopped; before SQLite 3.41 nothing else did. The finals now belong to the call: a cancel during the call or while its result sets are ended stops them, a cancel that lands just before the call returns fails it rather than skipping its finals, and those result sets read on as "interrupted". + - 0002 completes 0001. Ending a call's result sets runs the finals of the window and aggregate functions they were computing, and each final entered JavaScript as a new call, which a cancel during the call no longer stopped; before SQLite 3.41 nothing else did. The finals now belong to the call: a cancel during the call or while its result sets are ended stops each at QuickJS's next interrupt check, so one that never ends is stopped and the statement fails, though a short final can still finish. When the cancel came before the call returned, those result sets read on as "interrupted". - Since 1.4.2 a `db.exec` result set does not outlive the call into JavaScript that created it: every one still open is ended when the call returns, because its statement keeps a read transaction open, keeps an interrupt in effect and stops the connection from closing. Reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned", or "interrupted" when a cancel (or, on SQLite 3.41 and later, `sqlite3_interrupt()`) stopped the call. One read to its end still reports the end of its rows. - `src/main/cpp/`: the CMake build of `libsqlitejs.so`, and `sqlitejs_android.c`, which is ours: JNI for `SqliteJs`, and the two entry points it names. The version script exports only the entry points (and upstream's `sqlite3_js_init`) and `JNI_OnLoad`. - `src/test/c/glue_test.c` and `test.sh`: the tests the Android build cannot run. See Testing. diff --git a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch index 8032691624..6898cf6ee3 100644 --- a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch +++ b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch @@ -14,12 +14,13 @@ does; before 3.41 nothing did, and a final that never ends hung the statement for good. The finals that ending a call's result sets runs now keep that call's -epoch. A cancel during the call, or during the ending, stops every one -of them, and a cancel that lands just before the call returns fails the -statement with an interrupt, rather than letting the call succeed with -its finals skipped. Reading on from those result sets throws -"interrupted", as after sqlite3_interrupt() on 3.41 and later, rather -than the message for a result set that outlived its call. +epoch, so a cancel during the call, or during the ending, stops each of +them at QuickJS's next interrupt check: one that never ends is stopped +and the statement fails with an interrupt, though a short final can +still run to its end. When the cancel came before the call returned, +reading on from its result sets throws "interrupted", as after +sqlite3_interrupt() on 3.41 and later, rather than the message for a +result set that outlived its call. Before 3.41, an sqlite3_interrupt() that no cancel came with still reads as the result set outliving its call: nothing shows it. diff --git a/subprojects/sqlite-js/src/test/c/glue_test.c b/subprojects/sqlite-js/src/test/c/glue_test.c index 28d8b8265a..5affa0131a 100644 --- a/subprojects/sqlite-js/src/test/c/glue_test.c +++ b/subprojects/sqlite-js/src/test/c/glue_test.c @@ -351,7 +351,8 @@ int main (void) { "a window function whose final takes a while and records that it ran"); check(exec(db, "SELECT js_eval('globalThis.held = db.exec(\"SELECT long_final(column1) OVER (ORDER BY column1) " "FROM (VALUES (1), (2), (3))\"); held.next(); db.exec(\"SELECT cancel_now()\").next(); 0')") != SQLITE_OK, - "a cancel that lands as a call returns fails the call"); + "a cancel that lands as a call returns stops its long final and fails the call"); + check(answers(db, "SELECT count(*) FROM ran", "0"), "that final did not finish"); check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that cancel"); // A direct sqlite3_interrupt() that reaches the SQL of a db.exec, while another result set is From 9d87b3e4163d0b04de3f671ac845e5fe3c88cd66 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 21:07:11 -0800 Subject: [PATCH 044/203] ADFA-7135 Set the Kotlin JVM target on the compile tasks The root build sets jvmTarget 17 on every KotlinCompile task, which overrides the module's kotlin { compilerOptions } and made compileDebugKotlin fail against compileOptions' Java 1.8 ("Inconsistent JVM-target compatibility"). Setting it on the tasks keeps 1.8, as sqlite-js uses. First compile of the Android-only files (NativeDebugEngine.kt, DebuggerStartup.kt, sqlitedbg_jni.c, the manifest): with this change :subprojects:sqlite-debugger:assembleDebug builds both ABIs, the C compiles without warnings under -Wall -Wextra, libsqlitedbg.so exports only JNI_OnLoad, and testDebugUnitTest passes 56 tests. Co-Authored-By: Claude Opus 5.5 --- subprojects/sqlite-debugger/build.gradle.kts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/build.gradle.kts b/subprojects/sqlite-debugger/build.gradle.kts index cfcf5bd174..2acf1dd65c 100644 --- a/subprojects/sqlite-debugger/build.gradle.kts +++ b/subprojects/sqlite-debugger/build.gradle.kts @@ -45,9 +45,14 @@ android { } } +// Set on the tasks, not the extension: the root build sets every KotlinCompile task's jvmTarget +// to 17, which overrides the extension and no longer matches compileOptions above. +tasks.withType().configureEach { + compilerOptions.jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8) +} + kotlin { compilerOptions { - jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8) // Apps compile against this library with Code on the Go's on-device Kotlin compiler, // which can be older than the one that builds it (as in :plugin-api). apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_0) From 0ec489aef639e84dc3effa802715700d33b22843 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:28:45 -0800 Subject: [PATCH 045/203] ADFA-7082: Read result sets as interrupted when the cancel lands while they are ended From CodeRabbit's review of 5b5cd201c (4570522172), the same gap the independent review noted as F01: js_leave() decides once, before ending a call's result sets, whether they read on as "interrupted". A cancel that landed while their finals ran stopped the finals but left the "closed when the call ... returned" message. Patch 0002 now has js_end_rowsets() number its passes and mark each result set with the pass that ended it. After the loop, where nothing runs JavaScript and so no final can have freed a listed result set, it marks that pass's result sets interrupted if the cancel epoch has moved. The README and the patch header say the message is "interrupted" whether the cancel came before the call returned or during the ending. glue_test.c: new test 36 reads both result sets after the cancel that lands during the ending, and expects "interrupted". test.sh: upstream's suite 17 of 17; the glue test 46 of 46 normally and as on SQLite 3.40, and the same under AddressSanitizer and UBSan. With the previous 0002, test 36 fails in both runs with the "closed" message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- subprojects/sqlite-js/README.md | 2 +- ...call-s-result-sets-as-interrupted-an.patch | 71 ++++++++++++++++--- subprojects/sqlite-js/src/test/c/glue_test.c | 3 + subprojects/sqlite-js/upstream/src/sqlitejs.c | 12 ++++ 4 files changed, 76 insertions(+), 12 deletions(-) diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index 4b98454b89..3dcebfe61b 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -9,7 +9,7 @@ An AAR that lets apps built with Code on the Go define and call JavaScript funct - `upstream/`: the sqlite-js 1.4.2 release (Apache-2.0), which has our earlier changes (upstream pull requests #11 to #19, and #22 to #24), with QuickJS amalgamated in `libs/quickjs.c` (MIT), and `patches/` applied. Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. - `patches/`: our changes not upstream: - 0001 adds `sqlitejs_cancel_all()`: Android cannot otherwise stop JavaScript that never returns. It is offered upstream in sqliteai/sqlite-js issue 20. - - 0002 completes 0001. Ending a call's result sets runs the finals of the window and aggregate functions they were computing, and each final entered JavaScript as a new call, which a cancel during the call no longer stopped; before SQLite 3.41 nothing else did. The finals now belong to the call: a cancel during the call or while its result sets are ended stops each at QuickJS's next interrupt check, so one that never ends is stopped and the statement fails, though a short final can still finish. When the cancel came before the call returned, those result sets read on as "interrupted". + - 0002 completes 0001. Ending a call's result sets runs the finals of the window and aggregate functions they were computing, and each final entered JavaScript as a new call, which a cancel during the call no longer stopped; before SQLite 3.41 nothing else did. The finals now belong to the call: a cancel during the call or while its result sets are ended stops each at QuickJS's next interrupt check, so one that never ends is stopped and the statement fails, though a short final can still finish. Those result sets read on as "interrupted", whether the cancel came before the call returned or while they were ended. - Since 1.4.2 a `db.exec` result set does not outlive the call into JavaScript that created it: every one still open is ended when the call returns, because its statement keeps a read transaction open, keeps an interrupt in effect and stops the connection from closing. Reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned", or "interrupted" when a cancel (or, on SQLite 3.41 and later, `sqlite3_interrupt()`) stopped the call. One read to its end still reports the end of its rows. - `src/main/cpp/`: the CMake build of `libsqlitejs.so`, and `sqlitejs_android.c`, which is ours: JNI for `SqliteJs`, and the two entry points it names. The version script exports only the entry points (and upstream's `sqlite3_js_init`) and `JNI_OnLoad`. - `src/test/c/glue_test.c` and `test.sh`: the tests the Android build cannot run. See Testing. diff --git a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch index 6898cf6ee3..9b6b872733 100644 --- a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch +++ b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch @@ -1,6 +1,6 @@ -From 0432e1e8dac47a8e54b2f4b812fabe20ea9e8be3 Mon Sep 17 00:00:00 2001 +From 2aa939e18a7adc8826318500038fda83cdbc85fc Mon Sep 17 00:00:00 2001 From: David Schachter -Date: Fri, 13 Nov 2026 16:58:23 -0800 +Date: Sun, 15 Nov 2026 21:24:53 -0800 Subject: [PATCH] End a cancelled call's result sets as interrupted, and stop their finals @@ -17,22 +17,71 @@ The finals that ending a call's result sets runs now keep that call's epoch, so a cancel during the call, or during the ending, stops each of them at QuickJS's next interrupt check: one that never ends is stopped and the statement fails with an interrupt, though a short final can -still run to its end. When the cancel came before the call returned, -reading on from its result sets throws "interrupted", as after -sqlite3_interrupt() on 3.41 and later, rather than the message for a -result set that outlived its call. +still run to its end. Reading on from those result sets throws +"interrupted", as after sqlite3_interrupt() on 3.41 and later, rather +than the message for a result set that outlived its call, whether the +cancel came before the call returned or while its result sets were +ended. js_end_rowsets() marks the latter after its loop, by the pass +that ended them, since a final it runs can free result sets of the list. Before 3.41, an sqlite3_interrupt() that no cancel came with still reads as the result set outliving its call: nothing shows it. --- - src/sqlitejs.c | 10 ++++++++-- - 1 file changed, 8 insertions(+), 2 deletions(-) + src/sqlitejs.c | 22 ++++++++++++++++++++-- + 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index e5fea55..29499a0 100644 +index e5fea55..4872407 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c -@@ -576,7 +576,10 @@ static bool js_stack_room (size_t *room) { +@@ -75,6 +75,7 @@ typedef struct { + struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() + int orphans; // of those, the ones whose JavaScript object is gone + bool ending_rowsets; // js_end_rowsets() is running ++ unsigned end_pass; // js_end_rowsets() passes that ended every result set + } globaljs_context; + + typedef struct { +@@ -117,6 +118,7 @@ typedef struct rowset { + bool ended; // ended by js_end_rowsets(): reading on throws + bool interrupted; // and an interrupt is why: reading on throws "interrupted" + bool orphaned; // its JavaScript object is gone: see js_rowset_finalizer() ++ unsigned end_pass; // the js_end_rowsets() pass that ended it + struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() + } rowset; + +@@ -272,9 +274,12 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { + // computing, whose js_leave() comes back here and whose garbage collection can free result sets + // of the list. So each statement is taken from its result set before it is finalized, the list + // is walked again from its head after each one, and a nested call does nothing. ++static unsigned js_cancel_epoch_load (void); ++ + static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { + if (js->ending_rowsets) return; + js->ending_rowsets = true; ++ unsigned pass = all ? ++js->end_pass : 0; + for (;;) { + rowset *rs = js->rowsets; + while (rs && !(rs->orphaned || (all && rs->vm))) rs = rs->next; +@@ -291,10 +296,17 @@ static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { + } else { + rs->vm = NULL; + rs->ended = true; ++ rs->end_pass = pass; + if (interrupted) rs->interrupted = true; + } + if (vm) sqlite3_finalize(vm); + } ++ // A cancel that landed while the finals ran stopped them, as one before the call returned ++ // would have: the result sets this pass ended read on as interrupted too. Nothing runs ++ // JavaScript here, so the list holds only result sets that are still allocated. ++ if (all && !interrupted && (js->cancel_epoch != js_cancel_epoch_load())) { ++ for (rowset *r = js->rowsets; r; r = r->next) if (r->ended && (r->end_pass == pass)) r->interrupted = true; ++ } + js->ending_rowsets = false; + } + +@@ -576,7 +588,10 @@ static bool js_stack_room (size_t *room) { // runs JavaScript) is on the same thread and keeps the outer call's limit. static void js_enter (globaljs_context *js) { if (js->depth++ > 0) return; @@ -44,7 +93,7 @@ index e5fea55..29499a0 100644 JS_UpdateStackTop(js->runtime); // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails // with "Maximum call stack size exceeded" rather than running past the end of the stack. A -@@ -591,7 +594,10 @@ static void js_enter (globaljs_context *js) { +@@ -591,7 +606,10 @@ static void js_enter (globaljs_context *js) { static void js_leave (globaljs_context *js) { if (--js->depth > 0) return; if (!js->rowsets) return; diff --git a/subprojects/sqlite-js/src/test/c/glue_test.c b/subprojects/sqlite-js/src/test/c/glue_test.c index 5affa0131a..af5385e3a5 100644 --- a/subprojects/sqlite-js/src/test/c/glue_test.c +++ b/subprojects/sqlite-js/src/test/c/glue_test.c @@ -340,6 +340,9 @@ int main (void) { "FROM (VALUES (1), (2), (3))\"); held2.next(); 0')") != SQLITE_OK, "a cancel while a call's result sets are ended stops every final"); check(answers(db, "SELECT 1 + 2", "3"), "the connection runs SQL after that cancel"); + check(answers(db, "SELECT js_eval('[held, held2].map((r) => { try { r.next(); return \"open\"; } catch (e) { return e.message; } }).join()')", + "interrupted,interrupted"), + "the result sets ended when that cancel landed read on as interrupted"); // A cancel that lands as the call returns, after its JavaScript last checked for one: the call // fails, rather than returning with its result set's final skipped. sqlite3_create_function(db, "cancel_now", 0, SQLITE_UTF8, NULL, cancel_now, NULL, NULL); diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.c b/subprojects/sqlite-js/upstream/src/sqlitejs.c index 29499a0b57..48724077c5 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.c +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.c @@ -75,6 +75,7 @@ typedef struct { struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() int orphans; // of those, the ones whose JavaScript object is gone bool ending_rowsets; // js_end_rowsets() is running + unsigned end_pass; // js_end_rowsets() passes that ended every result set } globaljs_context; typedef struct { @@ -117,6 +118,7 @@ typedef struct rowset { bool ended; // ended by js_end_rowsets(): reading on throws bool interrupted; // and an interrupt is why: reading on throws "interrupted" bool orphaned; // its JavaScript object is gone: see js_rowset_finalizer() + unsigned end_pass; // the js_end_rowsets() pass that ended it struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() } rowset; @@ -272,9 +274,12 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { // computing, whose js_leave() comes back here and whose garbage collection can free result sets // of the list. So each statement is taken from its result set before it is finalized, the list // is walked again from its head after each one, and a nested call does nothing. +static unsigned js_cancel_epoch_load (void); + static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { if (js->ending_rowsets) return; js->ending_rowsets = true; + unsigned pass = all ? ++js->end_pass : 0; for (;;) { rowset *rs = js->rowsets; while (rs && !(rs->orphaned || (all && rs->vm))) rs = rs->next; @@ -291,10 +296,17 @@ static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { } else { rs->vm = NULL; rs->ended = true; + rs->end_pass = pass; if (interrupted) rs->interrupted = true; } if (vm) sqlite3_finalize(vm); } + // A cancel that landed while the finals ran stopped them, as one before the call returned + // would have: the result sets this pass ended read on as interrupted too. Nothing runs + // JavaScript here, so the list holds only result sets that are still allocated. + if (all && !interrupted && (js->cancel_epoch != js_cancel_epoch_load())) { + for (rowset *r = js->rowsets; r; r = r->next) if (r->ended && (r->end_pass == pass)) r->interrupted = true; + } js->ending_rowsets = false; } From 5fc49766fe7add4df58327aa776cfb2a94ef0cbb Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:13:21 -0800 Subject: [PATCH 046/203] ADFA-7082: Address review of the sqlite-js cancel patches Patch 0002 (rebuilt from upstream PR sqliteai/sqlite-js#33) now: - drops the redundant cancelled term from js_leave: the block after the loop in js_end_rowsets marks a cancelled call's result sets interrupted; - says only JavaScript the extension runs while it initialises a connection is exempt from a cancel, not js_init_table's stored functions; - initialises a rowset's end_pass where it is created; - documents sqlitejs_cancel_all in sqlitejs.h. upstream/ is regenerated with vendor.sh. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ...call-s-result-sets-as-interrupted-an.patch | 68 +++++++++++++++---- subprojects/sqlite-js/upstream/src/sqlitejs.c | 14 ++-- subprojects/sqlite-js/upstream/src/sqlitejs.h | 2 + 3 files changed, 64 insertions(+), 20 deletions(-) diff --git a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch index 9b6b872733..3f44b8bf5d 100644 --- a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch +++ b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch @@ -1,6 +1,6 @@ -From 2aa939e18a7adc8826318500038fda83cdbc85fc Mon Sep 17 00:00:00 2001 +From 09aa66a1ed410a588afb8233ecc574d908087231 Mon Sep 17 00:00:00 2001 From: David Schachter -Date: Sun, 15 Nov 2026 21:24:53 -0800 +Date: Sun, 15 Nov 2026 22:10:52 -0800 Subject: [PATCH] End a cancelled call's result sets as interrupted, and stop their finals @@ -21,17 +21,26 @@ still run to its end. Reading on from those result sets throws "interrupted", as after sqlite3_interrupt() on 3.41 and later, rather than the message for a result set that outlived its call, whether the cancel came before the call returned or while its result sets were -ended. js_end_rowsets() marks the latter after its loop, by the pass -that ended them, since a final it runs can free result sets of the list. +ended. js_end_rowsets() marks both after its loop, by the pass that +ended them, since a final it runs can free result sets of the list; +js_leave() no longer needs to mark a cancelled call's result sets +itself. Before 3.41, an sqlite3_interrupt() that no cancel came with still reads as the result set outliving its call: nothing shows it. + +The comment at the interrupt handler now says that only the JavaScript +the extension runs while it initialises a connection is exempt from a +cancel, not stored functions loaded by js_init_table. A rowset's +end_pass is initialised where it is created, and sqlitejs_cancel_all is +documented in sqlitejs.h. --- - src/sqlitejs.c | 22 ++++++++++++++++++++-- - 1 file changed, 20 insertions(+), 2 deletions(-) + src/sqlitejs.c | 26 +++++++++++++++++++++++--- + src/sqlitejs.h | 2 ++ + 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index e5fea55..4872407 100644 +index e5fea55..0a32d36 100644 --- a/src/sqlitejs.c +++ b/src/sqlitejs.c @@ -75,6 +75,7 @@ typedef struct { @@ -81,7 +90,20 @@ index e5fea55..4872407 100644 js->ending_rowsets = false; } -@@ -576,7 +588,10 @@ static bool js_stack_room (size_t *room) { +@@ -358,8 +370,10 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { + UNUSED(rt); + globaljs_context *js = (globaljs_context *)opaque; + js_keep_gc_below_limit(js); +- // Only a call (see js_enter) is cancelled: the JavaScript a connection runs while it is set +- // up is not one, and stopping it would make the connection fail to load the extension. ++ // Only a call (see js_enter) is cancelled. The one exception is the JavaScript the extension ++ // itself runs while it initialises a connection (globaljs_init, depth 0): stopping it would ++ // make the connection fail to load. Stored functions loaded by js_init_table run as a call, ++ // so they can be cancelled. + if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { + // The statement is interrupted too: a collation cannot report an error, so the + // statement would go on calling JavaScript, each call beginning after the cancel. +@@ -576,7 +590,10 @@ static bool js_stack_room (size_t *room) { // runs JavaScript) is on the same thread and keeps the outer call's limit. static void js_enter (globaljs_context *js) { if (js->depth++ > 0) return; @@ -93,18 +115,36 @@ index e5fea55..4872407 100644 JS_UpdateStackTop(js->runtime); // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails // with "Maximum call stack size exceeded" rather than running past the end of the stack. A -@@ -591,7 +606,10 @@ static void js_enter (globaljs_context *js) { +@@ -591,6 +608,8 @@ static void js_enter (globaljs_context *js) { static void js_leave (globaljs_context *js) { if (--js->depth > 0) return; if (!js->rowsets) return; -- bool interrupted = (sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db); -+ // A cancel (sqlitejs_cancel_all) during the call interrupted it, and before SQLite 3.41 is -+ // the only interrupt that shows: its result sets read on as interrupted. -+ bool cancelled = (js->cancel_epoch != js_cancel_epoch_load()); -+ bool interrupted = cancelled || ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)); ++ // A cancel (sqlitejs_cancel_all) is not seen here: js_end_rowsets() marks its result sets ++ // interrupted itself, which is the only way they read so before SQLite 3.41. + bool interrupted = (sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db); js_end_rowsets(js, true, interrupted); } +@@ -936,6 +955,7 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int + rs->vm = vm; + rs->ncols = sqlite3_column_count(vm); + rs->ended = false; ++ rs->end_pass = 0; + rs->interrupted = false; + rs->orphaned = false; + rs->prev = rs->next = NULL; +diff --git a/src/sqlitejs.h b/src/sqlitejs.h +index ed6ce4e..7cf1ce3 100644 +--- a/src/sqlitejs.h ++++ b/src/sqlitejs.h +@@ -21,6 +21,8 @@ + int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); + const char *sqlitejs_version (void); + const char *quickjs_version (void); ++// Stops all JavaScript now running, in every connection. Safe to call from any thread. It ++// stops only JavaScript already running: calls that begin afterwards are not affected. + void sqlitejs_cancel_all (void); + #endif -- 2.53.0 diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.c b/subprojects/sqlite-js/upstream/src/sqlitejs.c index 48724077c5..0a32d36354 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.c +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.c @@ -370,8 +370,10 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { UNUSED(rt); globaljs_context *js = (globaljs_context *)opaque; js_keep_gc_below_limit(js); - // Only a call (see js_enter) is cancelled: the JavaScript a connection runs while it is set - // up is not one, and stopping it would make the connection fail to load the extension. + // Only a call (see js_enter) is cancelled. The one exception is the JavaScript the extension + // itself runs while it initialises a connection (globaljs_init, depth 0): stopping it would + // make the connection fail to load. Stored functions loaded by js_init_table run as a call, + // so they can be cancelled. if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { // The statement is interrupted too: a collation cannot report an error, so the // statement would go on calling JavaScript, each call beginning after the cancel. @@ -606,10 +608,9 @@ static void js_enter (globaljs_context *js) { static void js_leave (globaljs_context *js) { if (--js->depth > 0) return; if (!js->rowsets) return; - // A cancel (sqlitejs_cancel_all) during the call interrupted it, and before SQLite 3.41 is - // the only interrupt that shows: its result sets read on as interrupted. - bool cancelled = (js->cancel_epoch != js_cancel_epoch_load()); - bool interrupted = cancelled || ((sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db)); + // A cancel (sqlitejs_cancel_all) is not seen here: js_end_rowsets() marks its result sets + // interrupted itself, which is the only way they read so before SQLite 3.41. + bool interrupted = (sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db); js_end_rowsets(js, true, interrupted); } @@ -954,6 +955,7 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int rs->vm = vm; rs->ncols = sqlite3_column_count(vm); rs->ended = false; + rs->end_pass = 0; rs->interrupted = false; rs->orphaned = false; rs->prev = rs->next = NULL; diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.h b/subprojects/sqlite-js/upstream/src/sqlitejs.h index ed6ce4e200..7cf1ce3cfc 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.h +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.h @@ -21,6 +21,8 @@ int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); const char *sqlitejs_version (void); const char *quickjs_version (void); +// Stops all JavaScript now running, in every connection. Safe to call from any thread. It +// stops only JavaScript already running: calls that begin afterwards are not affected. void sqlitejs_cancel_all (void); #endif From 3e1830fbec93b4ce5f87d2ab15c726fea9e9cb73 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:45:22 -0800 Subject: [PATCH 047/203] ADFA-7136 Bound the request head and refuse before reading the body; say the server is read-only A local app could hold all 8 connection slots without authenticating: the 30 s timeout applied per read and the token was checked after the whole request. The head now has an overall deadline (5 s), and Host, Origin, path and token are checked before the body. The initialize instructions no longer mention a read-write mode that does not exist. Tests: sockets that send nothing or trickle bytes are closed within the deadline and the real client is then served; an unauthenticated request with an unsent body gets 401; the instructions do not mention read-write. All three fail with the fix reverted. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/McpHttp.kt | 93 +++++++++++++++---- .../sqlitedebugger/mcp/McpProtocol.kt | 2 +- .../sqlitedebugger/mcp/McpProtocolTest.kt | 63 +++++++++++++ 4 files changed, 138 insertions(+), 22 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 7421b66283..9e8aaaa95a 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -30,7 +30,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han ## Decisions that shape it - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. -- **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. It opens no event stream: GET gets 405. +- **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. - **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database; the JNI query path also rolls back any transaction left open. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index ef1028cc7f..dc7db46d46 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -41,6 +41,8 @@ class McpHttp( private val log: (String) -> Unit = {}, /** Creates the listening socket; tests pass one whose accept fails. */ private val socketFactory: () -> ServerSocket = { ServerSocket() }, + /** How long a request's head may take to arrive; see [HEAD_DEADLINE_MS]. Tests shorten it. */ + private val headDeadlineMs: Int = HEAD_DEADLINE_MS, ) { companion object { private const val B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" @@ -86,6 +88,13 @@ class McpHttp( /** A connection with no request for this long is closed. */ const val IDLE_TIMEOUT_MS = 30_000 + /** + * The whole head of a request (request line and headers) must arrive within this, counted from + * the connection for its first request and from the first byte for later ones, so a client + * that trickles bytes or never authenticates frees its slot. + */ + const val HEAD_DEADLINE_MS = 5_000 + /** After a failed accept the loop sleeps this long, doubling up to the maximum while failures continue. */ const val ACCEPT_BACKOFF_MIN_MS = 100L const val ACCEPT_BACKOFF_MAX_MS = 2_000L @@ -114,7 +123,7 @@ class McpHttp( val target: String, val version: String, val headers: Map, - val body: ByteArray, + var body: ByteArray = ByteArray(0), ) private class HttpError( @@ -218,10 +227,26 @@ class McpHttp( c.tcpNoDelay = true val input = BufferedInputStream(c.getInputStream()) val out = c.getOutputStream() + var headStart = System.currentTimeMillis() + var first = true while (running) { val req = try { - readRequest(input) ?: return + if (!first) { + // Between requests the client may idle; the head's clock starts at its first byte. + c.soTimeout = IDLE_TIMEOUT_MS + input.mark(1) + if (input.read() < 0) return + input.reset() + headStart = System.currentTimeMillis() + } + first = false + val head = readHead(input, c, headStart + headDeadlineMs) ?: return + // Refuse before reading a body, so an unauthenticated client never gets that far. + if (!allowed(head, out)) return + c.soTimeout = IDLE_TIMEOUT_MS + head.body = readBody(input, head.headers) + head } catch (e: SocketTimeoutException) { return } catch (e: HttpError) { @@ -232,6 +257,34 @@ class McpHttp( } } + /** Host, Origin, path and token. Answers and returns false when the request is refused; the connection then closes. */ + private fun allowed( + r: Request, + out: OutputStream, + ): Boolean { + fun refuse( + status: Int, + message: String, + headers: Map = emptyMap(), + ): Boolean { + respond(out, status, rpcError(message), headers, close = true) + return false + } + if (!hostAllowed(r.headers["host"])) return refuse(403, "The Host header must be 127.0.0.1 or localhost.") + val origin = r.headers["origin"] + if (origin != null && !originAllowed(origin)) return refuse(403, "Requests from web pages aren't accepted.") + if (r.target.substringBefore('?') != PATH) return refuse(404, "Not found: the MCP endpoint is $PATH.") + if (!authorized(r.headers["authorization"])) { + return refuse( + 401, + "Missing or wrong token. Code on the Go gives it to its Agent; " + + "send it as Authorization: Bearer .", + mapOf("WWW-Authenticate" to "Bearer realm=\"SQLite debugger\""), + ) + } + return true + } + /** Answers one request. Returns whether the connection stays open for another. */ private fun handle( r: Request, @@ -247,20 +300,6 @@ class McpHttp( respond(out, status, body, headers, close) return !close } - if (!hostAllowed(r.headers["host"])) return send(403, rpcError("The Host header must be 127.0.0.1 or localhost.")) - val origin = r.headers["origin"] - if (origin != null && !originAllowed(origin)) return send(403, rpcError("Requests from web pages aren't accepted.")) - if (r.target.substringBefore('?') != PATH) return send(404, rpcError("Not found: the MCP endpoint is $PATH.")) - if (!authorized(r.headers["authorization"])) { - return send( - 401, - rpcError( - "Missing or wrong token. Code on the Go gives it to its Agent; " + - "send it as Authorization: Bearer .", - ), - mapOf("WWW-Authenticate" to "Bearer realm=\"SQLite debugger\""), - ) - } val session = r.headers["mcp-session-id"] val reply = when (r.method) { @@ -322,14 +361,28 @@ class McpHttp( // ---------------------------------------------------------------- reading and writing HTTP - /** One request, or null if the connection closed before one began. */ - private fun readRequest(input: InputStream): Request? { + /** The head of one request (no body yet), or null if the connection closed before one began. */ + private fun readHead( + input: InputStream, + c: Socket, + deadlineAt: Long, + ): Request? { var budget = MAX_HEADER_BYTES + fun read(): Int { + // Each blocking read may wait only as long as the head has left, however slowly bytes come. + if (input.available() == 0) { + val left = deadlineAt - System.currentTimeMillis() + if (left <= 0) throw SocketTimeoutException("the request's head took too long") + c.soTimeout = minOf(left, IDLE_TIMEOUT_MS.toLong()).toInt() + } + return input.read() + } + fun line(): String? { val b = ByteArrayOutputStream() while (true) { - val ch = input.read() + val ch = read() if (ch < 0) { if (b.size() == 0) return null else throw HttpError(400, "The request ended early.") } @@ -354,7 +407,7 @@ class McpHttp( // A repeated header is joined, so two Host headers fail the Host check. headers[name] = headers[name]?.let { "$it, $value" } ?: value } - return Request(parts[0], parts[1], parts[2], headers, readBody(input, headers)) + return Request(parts[0], parts[1], parts[2], headers) } private fun readBody( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 21ca3deaa9..34cf7b122b 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -66,7 +66,7 @@ class McpProtocol( const val INVALID_PARAMS = -32602 const val INSTRUCTIONS = "Inspects and queries the SQLite databases of the app this server runs in, a debug " + - "build made with Code on the Go. Read-only unless the app's developer turned on read-write mode." + "build made with Code on the Go. Every tool is read-only." } /** What to send back: an HTTP status, a JSON body (or none), and extra headers. */ diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index bb7b2c1e53..b1d48bf176 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -80,6 +80,8 @@ class McpProtocolTest { assertEquals("2025-03-26", result.getString("protocolVersion")) assertEquals(McpProtocol.SERVER_NAME, result.getJSONObject("serverInfo").getString("name")) assertTrue(result.getJSONObject("capabilities").has("tools")) + // no read-write mode exists, so the agent must not be told one may be on + assertFalse(result.getString("instructions").contains("read-write", ignoreCase = true)) assertEquals(1, p.sessionCount()) } @@ -466,4 +468,65 @@ class McpProtocolTest { assertEquals(204, http(port, "DELETE", headers = auth + ("Mcp-Session-Id" to s)).status) assertEquals(404, http(port, "POST", headers = auth + ("Mcp-Session-Id" to s), body = ping).status) } + + @Test fun clientsThatTrickleOrNeverAuthenticateAreDroppedAndDoNotBlockTheRealOne() { + val s = McpHttp(protocol(), { token }, port = 0, headDeadlineMs = 600) + s.start() + server = s + val port = s.boundPort + val started = System.nanoTime() + val held = mutableListOf() + try { + repeat(McpHttp.MAX_CONNECTIONS) { i -> + val c = Socket("127.0.0.1", port) + c.soTimeout = 5000 + held += c + // half of them send a byte now and then, which resets a per-read timeout but not the deadline + if (i % 2 == 0) { + c.getOutputStream().apply { + write("POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\n".toByteArray()) + flush() + } + } + } + // the slots are full: a real client is refused with 503 + assertEquals(503, http(port, "POST", headers = auth, body = initBody()).status) + val trickler = + Thread { + try { + repeat(20) { + Thread.sleep(200) + held[0].getOutputStream().apply { + write("X-Slow: 1\r\n".toByteArray()) + flush() + } + } + } catch (ignored: Exception) { + } + } + trickler.isDaemon = true + trickler.start() + // every held connection is closed by the server within the deadline plus slack + for (c in held) assertEquals(-1, c.getInputStream().read()) + val elapsedMs = (System.nanoTime() - started) / 1_000_000 + assertTrue("took $elapsedMs ms", elapsedMs < 3_000) + assertEquals(200, http(port, "POST", headers = auth, body = initBody()).status) + } finally { + held.forEach { it.close() } + } + } + + @Test fun anUnauthenticatedRequestIsRefusedBeforeItsBodyIsRead() { + val port = startServer() + Socket("127.0.0.1", port).use { c -> + c.soTimeout = 3000 + c.getOutputStream().apply { + write("POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 1000\r\n\r\n".toByteArray()) + flush() + } + // the body never comes, yet the answer does + val line = c.getInputStream().bufferedReader().readLine() + assertTrue(line, line.startsWith("HTTP/1.1 401")) + } + } } From 7cf251bcc66d23ec8f93fcbd5d69f27de36f1c99 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:48:28 -0800 Subject: [PATCH 048/203] ADFA-7135 Refuse the process-wide heap limit and temp directory PRAGMAs on server connections SQLite applies hard_heap_limit, soft_heap_limit and temp_store_directory to the whole process, so a client's PRAGMA hard_heap_limit=1 could make the app's own connections fail with SQLITE_NOMEM. Test: each form (set and read) returns SQLITE_AUTH on a server connection; without the change all five return SQLITE_OK. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c | 6 ++++-- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h | 3 ++- subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c | 6 ++++++ 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 9e8aaaa95a..e2e9fcd7a4 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -31,7 +31,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database; the JNI query path also rolls back any transaction left open. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 929be274a2..468529a604 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -422,10 +422,12 @@ static int server_authorizer(void *unused, int action, const char *a1, const cha // PRAGMA query_only=0 would lift the guard, and a PRAGMA that stores a value writes. // PRAGMA table_info(t) also has a second argument, so only these names are checked. // locking_mode=EXCLUSIVE keeps the lock after a read, and busy_timeout (any form) lets a - // statement wait on the app's lock for as long as the client likes. + // statement wait on the app's lock for as long as the client likes. The heap limits and + // temp_store_directory are process-wide: they would change the app's own connections. if (a1 && (sqlite3_stricmp(a1, "query_only") == 0 || sqlite3_stricmp(a1, "writable_schema") == 0 || sqlite3_stricmp(a1, "locking_mode") == 0 || sqlite3_stricmp(a1, "busy_timeout") == 0 || - sqlite3_stricmp(a1, "wal_checkpoint") == 0 || + sqlite3_stricmp(a1, "hard_heap_limit") == 0 || sqlite3_stricmp(a1, "soft_heap_limit") == 0 || + sqlite3_stricmp(a1, "temp_store_directory") == 0 || sqlite3_stricmp(a1, "wal_checkpoint") == 0 || sqlite3_stricmp(a1, "incremental_vacuum") == 0 || sqlite3_stricmp(a1, "optimize") == 0)) return SQLITE_DENY; if (a1 && a2 && diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index d87890daa0..d46e7ac585 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -136,7 +136,8 @@ void sqlitedbg_set_client_connected(int connected); // Opens path for the server with the same SQLite the app uses: SQLITE_OPEN_READONLY unless // writable, PRAGMA query_only when read-only, and an authorizer that refuses ordinary writes when // read-only, and also BEGIN, SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout: a client must not -// be able to hold a lock on the app's database. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, +// be able to hold a lock on the app's database. The process-wide PRAGMAs hard_heap_limit, soft_heap_limit and +// temp_store_directory are refused too: they would change the app's own connections. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, // D11). Never traced and never listed. The caller owns *db and closes it with sqlite3_close_v2. // A server connection, unlike an app connection, may use a progress handler (for time limits). // Returns SQLITE_MISUSE before any app connection has opened (the extension then has no SQLite diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index bcb1c8460d..63bf3f736e 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -619,6 +619,12 @@ static void test_server_holds_no_locks(void) { "PRAGMA locking_mode", "PRAGMA busy_timeout=60000", "PRAGMA busy_timeout", + // process-wide settings that would reach the app's own connections + "PRAGMA hard_heap_limit=1000000000", + "PRAGMA hard_heap_limit", + "PRAGMA soft_heap_limit=1000000000", + "PRAGMA soft_heap_limit", + "PRAGMA temp_store_directory='/tmp'", }; for (size_t i = 0; i < sizeof denied / sizeof denied[0]; i++) { sqlite3 *srv = NULL; From f785f969fd547e5dedacdd764ff4eafce0133562 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:51:39 -0800 Subject: [PATCH 049/203] ADFA-7135 Give server connections a 3 s busy timeout With the app's database in rollback-journal mode, a server read failed at once with SQLITE_BUSY while the app held a write lock, exactly when the agent wants to look. The timeout is set in C and PRAGMA busy_timeout stays refused, so the client cannot change it. Test: an app connection holds BEGIN EXCLUSIVE; a server read waits about 500 ms and succeeds once it is released, and reports SQLITE_BUSY after about 3 s if it is not. Without the timeout the first read failed after 0 ms with SQLITE_BUSY. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 3 + .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 4 + .../src/test/c/sqlitedbg_test.c | 74 +++++++++++++++++++ 4 files changed, 82 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index e2e9fcd7a4..047a0cecf5 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -31,7 +31,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 468529a604..c69f5b9fdf 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -454,6 +454,9 @@ int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db) { rc = sqlite3_exec(*db, "PRAGMA query_only=1", NULL, NULL, NULL); if (rc == SQLITE_OK) rc = sqlite3_set_authorizer(*db, server_authorizer, NULL); } + // In rollback-journal mode a reader fails at once while the app holds a write lock. Wait a little, + // well under the tools' 50 s deadline; the client cannot change it (PRAGMA busy_timeout is refused). + if (rc == SQLITE_OK) rc = sqlite3_busy_timeout(*db, SQLITEDBG_SERVER_BUSY_MS); if (rc != SQLITE_OK && *db) { sqlite3_close_v2(*db); *db = NULL; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index d46e7ac585..22eb2025dd 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -133,6 +133,8 @@ void sqlitedbg_set_client_connected(int connected); // Server connections +#define SQLITEDBG_SERVER_BUSY_MS 3000 + // Opens path for the server with the same SQLite the app uses: SQLITE_OPEN_READONLY unless // writable, PRAGMA query_only when read-only, and an authorizer that refuses ordinary writes when // read-only, and also BEGIN, SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout: a client must not @@ -140,6 +142,8 @@ void sqlitedbg_set_client_connected(int connected); // temp_store_directory are refused too: they would change the app's own connections. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, // D11). Never traced and never listed. The caller owns *db and closes it with sqlite3_close_v2. // A server connection, unlike an app connection, may use a progress handler (for time limits). +// The connection waits up to SQLITEDBG_SERVER_BUSY_MS for a lock the app holds (rollback-journal mode) +// and then reports SQLITE_BUSY. // Returns SQLITE_MISUSE before any app connection has opened (the extension then has no SQLite // API to call), or what sqlite3_open_v2 returns. int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db); diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 63bf3f736e..298fdd592e 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -653,6 +653,78 @@ static void test_server_holds_no_locks(void) { CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); } +typedef struct locker { + char path[320]; + atomic_int locked, release; +} locker; + +// An app connection that holds an exclusive lock (rollback-journal mode) until told to release it. +static void *locker_main(void *arg) { + locker *l = arg; + sqlite3 *db = open_app(l->path); + exec_ok(db, "BEGIN EXCLUSIVE"); + atomic_store(&l->locked, 1); + while (!atomic_load(&l->release)) usleep(1000); + exec_ok(db, "COMMIT"); + sqlite3_close(db); + return NULL; +} + +static double since_ms(const struct timespec *t0) { + struct timespec t1; + clock_gettime(CLOCK_MONOTONIC, &t1); + return (t1.tv_sec - t0->tv_sec) * 1e3 + (t1.tv_nsec - t0->tv_nsec) / 1e6; +} + +static void *release_later(void *arg) { + usleep(500 * 1000); + atomic_store(&((locker *)arg)->release, 1); + return NULL; +} + +// A server read waits for the app's lock (rollback-journal mode) instead of failing at once. +static void test_server_waits_for_locks(void) { + locker l = {0}; + snprintf(l.path, sizeof l.path, "%s/journal.db", g_dir); + sqlite3 *app = open_app(l.path); + exec_ok(app, "PRAGMA journal_mode=DELETE"); + exec_ok(app, "CREATE TABLE j(a); INSERT INTO j VALUES(1)"); + sqlite3_close(app); + + // the lock is released after 500 ms: the read waits, then succeeds + pthread_t holder, releaser; + pthread_create(&holder, NULL, locker_main, &l); + while (!atomic_load(&l.locked)) usleep(1000); + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(l.path, 0, &srv), SQLITE_OK); + struct timespec t0; + clock_gettime(CLOCK_MONOTONIC, &t0); + pthread_create(&releaser, NULL, release_later, &l); + CHECK_EQ(step_all(srv, "SELECT * FROM j"), SQLITE_DONE); + double waited = since_ms(&t0); + CHECK(waited >= 300); + CHECK(waited < SQLITEDBG_SERVER_BUSY_MS); + pthread_join(releaser, NULL); + pthread_join(holder, NULL); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + + // a lock held past the timeout gives SQLITE_BUSY after about that long, not at once + atomic_store(&l.locked, 0); + atomic_store(&l.release, 0); + pthread_create(&holder, NULL, locker_main, &l); + while (!atomic_load(&l.locked)) usleep(1000); + CHECK_EQ(sqlitedbg_open_server(l.path, 0, &srv), SQLITE_OK); + clock_gettime(CLOCK_MONOTONIC, &t0); + CHECK_EQ(step_all(srv, "SELECT * FROM j"), SQLITE_BUSY); + waited = since_ms(&t0); + CHECK(waited >= SQLITEDBG_SERVER_BUSY_MS - 500); + CHECK(waited < SQLITEDBG_SERVER_BUSY_MS + 2000); + atomic_store(&l.release, 1); + pthread_join(holder, NULL); + CHECK_EQ(step_all(srv, "SELECT * FROM j"), SQLITE_DONE); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); +} + typedef struct worker { int index; atomic_int *stop; @@ -927,6 +999,8 @@ int main(int argc, char **argv) { test_server(); printf("# server holds no locks\n"); test_server_holds_no_locks(); + printf("# server waits for locks\n"); + test_server_waits_for_locks(); printf("# threads\n"); test_threads(); if (argc == 4 && strcmp(argv[1], "--write-fixture") == 0) write_fixture(argv[2], argv[3]); From dcd342e3b29c3791e69ae551cf2c619740818d88 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:55:39 -0800 Subject: [PATCH 050/203] ADFA-7135 Fail a query whose argument count differs from its parameter count Too few arguments left the missing parameters unbound, which SQLite reads as NULL, so the query ran and returned a plausible empty result. It now throws SQLITE_RANGE with a message naming both counts. Test (JniQueryTest, the real JNI query path on a host JVM, run by test.sh): zero args for one parameter and one for two give SQLITE_RANGE; the first expectation was NULL before, and both fail with the check disabled. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlite-debugger/src/main/cpp/sqlitedbg_jni.c | 10 ++++++++++ .../sqlite-debugger/src/test/jni/JniQueryTest.java | 9 ++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 7033766bd6..703f103d57 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -333,6 +334,15 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sqlite3_progress_handler(db, 1000, progress_cb, &dl); handler_set = 1; + // A missing argument would be bound as NULL and the query would run, returning a plausible empty result. + int wanted = st ? sqlite3_bind_parameter_count(st) : 0; + jsize given = (*env)->GetArrayLength(env, args); + if (given != wanted) { + char msg[96]; + snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)given); + throw_engine(env, SQLITE_RANGE, msg); + goto done; + } rc = st ? bind_args(env, db, st, args, &message) : SQLITE_OK; if (rc != SQLITE_OK) { if (!(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 061d813ccb..776287b498 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -196,7 +196,14 @@ public static void main(String[] a) throws Exception { eq(row[2], "a😀b", "arg text"); check(Arrays.equals((byte[]) row[3], new byte[] {9, 8, 7}), "arg blob"); eq(row[4], null, "arg null"); - eq(q(srv, "SELECT ?").rows.get(0)[0], null, "an unbound parameter is NULL"); + eq(codeOf(srv, "SELECT ?", new Object[0], FAR), 25, "too few args: SQLITE_RANGE, not a NULL parameter"); + eq(codeOf(srv, "SELECT ?, ?", new Object[] {1L}, FAR), 25, "one arg of two: SQLITE_RANGE"); + eq(codeOf(srv, "SELECT 1", new Object[] {1L}, FAR), 25, "an arg for no parameter: SQLITE_RANGE"); + try { + query(srv, "SELECT ?, ?", new Object[] {1L}, 0, 100, 4096, 1024, MAX, FAR); + } catch (DebugEngineException e) { + check(e.getMessage().contains("2 parameter") && e.getMessage().contains("1 argument"), "the message names both counts: " + e.getMessage()); + } eq(codeOf(srv, "SELECT ?", new Object[] {1L, 2L}, FAR), 25, "too many args: SQLITE_RANGE"); eq(codeOf(srv, "SELECT ?", new Object[] {new Object()}, FAR), 21, "unsupported arg type: SQLITE_MISUSE"); eq(codeOf(srv, "SELEKT 1", new Object[0], FAR), 1, "syntax error: SQLITE_ERROR"); From d90b7b420f91bd64d05c2d50bacd0a170a54bca6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:06:17 -0800 Subject: [PATCH 051/203] ADFA-7136 List an open database once when the databases folder is reached through a link list_databases matched the files of the app's databases folder against connection paths as strings, so on a phone (/data/user/0/ against /data/data/) every open database was listed again as available: false. Both sides are now canonicalised before matching; paths are reported as the connections gave them. Test: a folder listed through a symlink, and the reverse, list the open database once. Without the canonicalisation it was listed twice. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 6 +++- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 35 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 5bbed62ebf..19ceceaa98 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -255,17 +255,21 @@ class DatabaseTools( .put("required", JSONArray(listOf("database") + required)) } + private fun canonical(path: String): String = runCatching { File(path).canonicalPath }.getOrDefault(path) + private fun listDatabases(): JSONObject { val connections = engine.connections() val byPath = LinkedHashMap>() for (c in connections) if (c.path.isNotEmpty()) byPath.getOrPut(c.path) { mutableListOf() } += c.id + // The folder may be reached through a link (/data/user/0/ and /data/data/), so match resolved paths. + val openCanonical = byPath.keys.map { canonical(it) }.toSet() val list = JSONArray() for ((path, ids) in byPath) { list.put(JSONObject().put("path", path).put("available", true).put("connections", ids.size)) } databaseDir?.listFiles()?.sortedBy { it.name }?.forEach { f -> if (!f.isFile || SIDE_FILE_SUFFIXES.any { f.name.endsWith(it) }) return@forEach - if (f.absolutePath in byPath || f.path in byPath) return@forEach + if (canonical(f.absolutePath) in openCanonical) return@forEach list.put(JSONObject().put("path", f.absolutePath).put("available", false).put("connections", 0)) } return JSONObject().put("databases", list) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 21cae2b0a0..b53bfed6d9 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -116,6 +116,41 @@ class DatabaseToolsTest { } } + @Test fun listDatabasesMatchesOpenFilesThroughASymlinkedFolder() { + val root = + kotlin.io.path + .createTempDirectory("dbs") + try { + val real = + java.nio.file.Files + .createDirectory(root.resolve("real")) + .toFile() + val link = root.resolve("link") + java.nio.file.Files + .createSymbolicLink(link, real.toPath()) + listOf("open.db", "closed.db").forEach { File(real, it).writeText("x") } + // the folder is listed through the link, the connection reports the real path + dir = link.toFile() + engine.appConnections += conn(1, File(real, "open.db").absolutePath) + var dbs = ok("list_databases").getJSONArray("databases") + assertEquals(dbs.toString(), 2, dbs.length()) + assertEquals(File(real, "open.db").absolutePath, dbs.getJSONObject(0).getString("path")) + assertTrue(dbs.getJSONObject(0).getBoolean("available")) + assertFalse(dbs.getJSONObject(1).getBoolean("available")) + assertTrue(dbs.getJSONObject(1).getString("path").endsWith("closed.db")) + + // and the other way round: the connection reports the link, the folder is the real one + engine.appConnections.clear() + dir = real + engine.appConnections += conn(2, File(link.toFile(), "open.db").absolutePath) + dbs = ok("list_databases").getJSONArray("databases") + assertEquals(dbs.toString(), 2, dbs.length()) + assertEquals(File(link.toFile(), "open.db").absolutePath, dbs.getJSONObject(0).getString("path")) + } finally { + root.toFile().deleteRecursively() + } + } + @Test fun listConnectionsEncodesBigIntegersAsStrings() { engine.appConnections += conn(1, "/data/a.db", closing = true) val c = ok("list_connections").getJSONArray("connections").getJSONObject(0) From 3527173a3e5d1a483e160ee2696c8f833006056c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:06:17 -0800 Subject: [PATCH 052/203] ADFA-7135 Run the sqlite-debugger host tests in CI test.sh (the extension's C tests under ASan/UBSan and TSan, and the JNI query test) ran in no workflow. The new workflow follows test-sqlite-js.yml and also triggers on the vendored SQLite headers test.sh compares against. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .github/workflows/test-sqlite-debugger.yml | 27 ++++++++++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/test-sqlite-debugger.yml diff --git a/.github/workflows/test-sqlite-debugger.yml b/.github/workflows/test-sqlite-debugger.yml new file mode 100644 index 0000000000..b119984e49 --- /dev/null +++ b/.github/workflows/test-sqlite-debugger.yml @@ -0,0 +1,27 @@ +name: Test sqlite-debugger + +# The tests the Android build cannot run (ADFA-7135): the extension's C tests under AddressSanitizer, +# UBSan and ThreadSanitizer, and the JNI query test on a host JVM. See subprojects/sqlite-debugger/test.sh, +# which downloads the SQLite amalgamation itself and checks its hash. + +on: + pull_request: + paths: + - 'subprojects/sqlite-debugger/**' + - 'subprojects/sqlite-js/upstream/libs/**' + - '.github/workflows/test-sqlite-debugger.yml' + +permissions: + contents: read + +jobs: + + test-sqlite-debugger: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Run the sqlite-debugger tests + run: subprojects/sqlite-debugger/test.sh diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 047a0cecf5..55b60427e7 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -41,7 +41,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). No workflow in `.github/workflows` runs either yet. From e6b2e2632671812ac41b2b9b725f80bce04c04e4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:36:24 -0800 Subject: [PATCH 053/203] ADFA-7138 Add sqlite-rewrite-runtime, the helpers the requery rewrite redirects to The build-time rewrite (next commits) moves an app from android.database.sqlite to requery, which lacks a few platform entry points: open flags, CancellationSignal overloads, Context.openOrCreateDatabase and deleteDatabase, and the DatabaseUtils query helpers. The rewritten classes call static helpers for these instead. The helpers are a Java-only module, so one AAR serves every ABI. Code on the Go injects it into apps; it is not shipped in the template's libs/, so it always matches the plugin's rules. The module is registered in settings.gradle.kts and in AndroidModuleConf, which builds it as a release AAR for the apps built with Code on the Go. Tests: the pure helper functions run on the JVM in the gradle-plugin tests (next commit). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/conf/AndroidModuleConf.kt | 13 +- settings.gradle.kts | 1 + .../sqlite-rewrite-runtime/build.gradle.kts | 30 +++ .../sqliterewrite/SqliteRewriteRuntime.java | 171 ++++++++++++++++++ 4 files changed, 213 insertions(+), 2 deletions(-) create mode 100644 subprojects/sqlite-rewrite-runtime/build.gradle.kts create mode 100644 subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/conf/AndroidModuleConf.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/conf/AndroidModuleConf.kt index e418cb787a..3330baec4d 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/conf/AndroidModuleConf.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/conf/AndroidModuleConf.kt @@ -55,15 +55,24 @@ private val disableCoreLibDesugaringForModules = ":subprojects:sqlite-js", // Injected into debug builds of apps built with CoGo like :logsender (ADFA-7131). ":subprojects:sqlite-debugger", + // Injected into every variant of apps built with CoGo that opted into the rewrite, for the + // rewritten classes to call (ADFA-7138). + ":subprojects:sqlite-rewrite-runtime", ) /** * Modules without the v7/v8 flavors: libraries for other projects, which need one artifact. * :subprojects:sqlite-js and :subprojects:sqlite-debugger are AARs for apps built with CoGo, with - * all the ABIs they run on. + * all the ABIs they run on. :subprojects:sqlite-rewrite-runtime is Java-only, one AAR for apps + * built with CoGo. */ private val modulesWithoutAbiFlavors = - setOf(":plugin-api", ":subprojects:sqlite-js", ":subprojects:sqlite-debugger") + setOf( + ":plugin-api", + ":subprojects:sqlite-js", + ":subprojects:sqlite-debugger", + ":subprojects:sqlite-rewrite-runtime", + ) /** * The name of the build type used for automated testing. diff --git a/settings.gradle.kts b/settings.gradle.kts index a3b77f05a5..0912ba830d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -172,6 +172,7 @@ include( ":subprojects:shizuku-starter", ":subprojects:sqlite-debugger", ":subprojects:sqlite-js", + ":subprojects:sqlite-rewrite-runtime", ":subprojects:tooling-api", ":subprojects:tooling-api-events", ":subprojects:tooling-api-impl", diff --git a/subprojects/sqlite-rewrite-runtime/build.gradle.kts b/subprojects/sqlite-rewrite-runtime/build.gradle.kts new file mode 100644 index 0000000000..1ca7d55699 --- /dev/null +++ b/subprojects/sqlite-rewrite-runtime/build.gradle.kts @@ -0,0 +1,30 @@ +plugins { + id("com.android.library") +} + +description = "Runtime helpers for classes rewritten from android.database.sqlite to requery (ADFA-7138)" + +android { + namespace = "org.appdevforall.sqliterewrite" + + defaultConfig { + // requery's own minSdk (its AAR manifest says 21); apps rewritten to use it need no more + minSdk = 21 + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + + buildFeatures { + viewBinding = false + buildConfig = false + } +} + +dependencies { + // Not packaged: requery's AAR is a file dependency, which brings none of its own dependencies, so + // androidx.core comes from the app (AppCompat and most androidx libraries depend on it) + compileOnly(libs.androidx.core) +} diff --git a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java new file mode 100644 index 0000000000..8e810f980f --- /dev/null +++ b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java @@ -0,0 +1,171 @@ +package org.appdevforall.sqliterewrite; + +import android.content.Context; +import android.database.DatabaseErrorHandler; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteStatement; +import android.os.CancellationSignal; +import android.text.TextUtils; + +import java.io.File; + +/** + * Targets of the calls that CoGo's Gradle plugin redirects when it rewrites an app from android.database.sqlite to requery (ADFA-7138). + * + *

+ * The methods are written against Android's classes on purpose: the plugin rewrites this library like every other class of the app, so {@code SQLiteDatabase} and {@code DatabaseErrorHandler} below become requery's in the final APK. The plugin leaves this package's own calls alone, otherwise a redirect would call itself. + * + *

+ * Flag mapping, Android -> requery 3.49.0 (read from its classes.jar): + * + *

+ * OPEN_READWRITE (0)                           -> OPEN_READWRITE (2)
+ * OPEN_READONLY (1)                            -> OPEN_READONLY (1)
+ * CREATE_IF_NECESSARY (0x10000000)             -> OPEN_CREATE (4), so 6 with read-write; dropped with OPEN_READONLY
+ * ENABLE_WRITE_AHEAD_LOGGING (0x20000000)      -> same value in requery, kept
+ * NO_LOCALIZED_COLLATORS (16)                  -> dropped, requery has no collator support
+ * any other bit                                -> dropped
+ * 
+ * + * Other bits are dropped because requery hands them to sqlite3_open_v2, where 16 and 8 mean SQLITE_OPEN_EXCLUSIVE and SQLITE_OPEN_DELETEONCLOSE: an Android flag must never turn into one of those. + */ +public final class SqliteRewriteRuntime { + private static final int ANDROID_OPEN_READONLY = 1; + private static final int ANDROID_CREATE_IF_NECESSARY = 0x10000000; + private static final int ANDROID_ENABLE_WRITE_AHEAD_LOGGING = 0x20000000; + + private static final int REQUERY_OPEN_READONLY = 1; + private static final int REQUERY_OPEN_READWRITE = 2; + private static final int REQUERY_OPEN_CREATE = 4; + private static final int REQUERY_ENABLE_WRITE_AHEAD_LOGGING = 0x20000000; + + private static final int CONTEXT_MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x8; + + /** + * Same as Context.deleteDatabase, which also returns false on any exception. requery's deleteDatabase removes the -journal, -wal, -shm and -mj files next to the file, like Android's. + */ + public static boolean deleteDatabase(Context context, String name) { + try { + return SQLiteDatabase.deleteDatabase(context.getDatabasePath(name)); + } catch (Exception e) { + return false; + } + } + + public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) { + SQLiteStatement prog = db.compileStatement(query); + try { + return longForQuery(prog, selectionArgs); + } finally { + prog.close(); + } + } + + public static long longForQuery(SQLiteStatement prog, String[] selectionArgs) { + prog.bindAllArgsAsStrings(selectionArgs); + return prog.simpleQueryForLong(); + } + + public static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, + int flags) { + return SQLiteDatabase.openDatabase(path, factory, translateOpenFlags(flags)); + } + + public static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, + int flags, DatabaseErrorHandler errorHandler) { + return SQLiteDatabase.openDatabase(path, factory, translateOpenFlags(flags), + errorHandler); + } + + public static SQLiteDatabase openOrCreateDatabase(Context context, String name, int mode, + SQLiteDatabase.CursorFactory factory) { + return openOrCreateDatabase(context, name, mode, factory, null); + } + + /** + * Context.openOrCreateDatabase without the file permission bits of {@code mode}: Android applies them with a hidden API, and the modes other than private were deprecated in API 17. + */ + public static SQLiteDatabase openOrCreateDatabase(Context context, String name, int mode, + SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { + int flags = ANDROID_CREATE_IF_NECESSARY; + if ((mode & CONTEXT_MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) { + flags |= ANDROID_ENABLE_WRITE_AHEAD_LOGGING; + } + File file = context.getDatabasePath(name); + File parent = file.getParentFile(); + if (parent != null && !parent.isDirectory()) { + // getDatabasePath does this for the default directory only + parent.mkdirs(); + } + return openDatabase(file.getPath(), factory, flags, errorHandler); + } + + /** + * The DatabaseUtils methods that take SQLiteDatabase or SQLiteStatement, as Android implements them (requery has no DatabaseUtils). They call only members requery has, so they stay on this class. + */ + public static long queryNumEntries(SQLiteDatabase db, String table) { + return queryNumEntries(db, table, null, null); + } + + public static long queryNumEntries(SQLiteDatabase db, String table, String selection) { + return queryNumEntries(db, table, selection, null); + } + + public static long queryNumEntries(SQLiteDatabase db, String table, String selection, + String[] selectionArgs) { + String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : ""; + return longForQuery(db, "select count(*) from " + table + s, selectionArgs); + } + + public static String stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs) { + SQLiteStatement prog = db.compileStatement(query); + try { + return stringForQuery(prog, selectionArgs); + } finally { + prog.close(); + } + } + + public static String stringForQuery(SQLiteStatement prog, String[] selectionArgs) { + prog.bindAllArgsAsStrings(selectionArgs); + return prog.simpleQueryForString(); + } + + /** + * Android's signal for requery's. Android's signal holds one listener, so this replaces any listener the caller set on it (Android's setOnCancelListener documents that it replaces the previous one). It fires at once when the signal is cancelled already. + */ + public static androidx.core.os.CancellationSignal toCancellationSignal( + CancellationSignal signal) { + if (signal == null) { + return null; + } + final androidx.core.os.CancellationSignal converted = new androidx.core.os.CancellationSignal(); + if (signal.isCanceled()) { + converted.cancel(); + return converted; + } + signal.setOnCancelListener(new CancellationSignal.OnCancelListener() { + @Override + public void onCancel() { + converted.cancel(); + } + }); + return converted; + } + + /** Converts Android's open flags to requery's. */ + public static int translateOpenFlags(int androidFlags) { + boolean readOnly = (androidFlags & ANDROID_OPEN_READONLY) != 0; + int flags = readOnly ? REQUERY_OPEN_READONLY : REQUERY_OPEN_READWRITE; + // SQLite accepts READONLY, READWRITE and READWRITE|CREATE, and rejects READONLY|CREATE + if (!readOnly && (androidFlags & ANDROID_CREATE_IF_NECESSARY) != 0) { + flags |= REQUERY_OPEN_CREATE; + } + if ((androidFlags & ANDROID_ENABLE_WRITE_AHEAD_LOGGING) != 0) { + flags |= REQUERY_ENABLE_WRITE_AHEAD_LOGGING; + } + return flags; + } + + private SqliteRewriteRuntime() {} +} From e392fe9f31dcd8a8ca475e086a5f19725394e186 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:36:24 -0800 Subject: [PATCH 054/203] ADFA-7138 Rewrite android.database.sqlite to requery in the Gradle plugin Apps built in Code on the Go that opt in must run on requery's SQLite (3.49.0) so the debugger can hook it. SqliteRewriter is an ASM class visitor, applied by an AGP transform to the app's and its libraries' classes: - renames android.database.sqlite types to requery's, and String[] descriptors to Object[]; - redirects open flags, CancellationSignal, Context.openOrCreateDatabase and deleteDatabase, and the DatabaseUtils query helpers to sqlite-rewrite-runtime; - fails the build, naming class, method and line, for APIs requery lacks: OpenParams, COLLATE UNICODE (requery has no ICU), casts to Android's cursor classes, method handles, unredirectable Context database calls; - copies frames (COPY_FRAMES), inserting a String[] cast at the start of a method whose parameter is retyped to Object[] so its frames stay valid; memoizes hierarchy lookups; keeps the cursor taint at join points; looks up missing members through every renamed ancestor; adds OPEN_CREATE only to read-write opens. androidx.core is exempt from the build-failure rule: its SQLiteCursorCompat calls setFillWindowForwardOnly, which a real transform run found missing. FrameworkSQLiteOpenHelperFactory is not redirected to requery's factory, which ignores noBackupDirectory and allowDataLossOnRecovery; WorkManager sets both, so its database would be recreated empty on every start. androidx's framework classes are rewritten instead and honour both options. Tests: SqliteRewriterTest and SqliteRewriteResolutionTest rewrite Java samples and the real androidx.sqlite 2.6.2 framework classes and check that every reference resolves in requery 3.49.0 (except execPerConnectionSQL, which throws UnsupportedOperationException when called; Room 2.8.4 and WorkManager 2.10.0 were surveyed with javap and run on a device); BytecodeVerifier runs the JVM verifier over rewritten classes; the runtime helper's pure functions run on the JVM. The tests fail on CI when their jars are missing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/build.gradle.kts | 16 + .../gradle/sqlite/SqliteRewriteRules.kt | 271 ++++ .../sqlite/SqliteRewriteVisitorFactory.kt | 34 + .../gradle/sqlite/SqliteRewriter.kt | 759 ++++++++++ .../gradle/sqlite/BytecodeVerifier.kt | 98 ++ .../gradle/sqlite/BytecodeVerifierTest.kt | 58 + .../sqlite/SqliteRewriteResolutionTest.kt | 349 +++++ .../gradle/sqlite/SqliteRewriteRuntimeTest.kt | 48 + .../gradle/sqlite/SqliteRewriterTest.kt | 1299 +++++++++++++++++ .../gradle/sqlite/SqliteTestSupport.kt | 278 ++++ gradle/libs.versions.toml | 3 + 11 files changed, 3213 insertions(+) create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteVisitorFactory.kt create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifier.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifierTest.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index 06560adcf6..d631c8404a 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -93,10 +93,21 @@ dependencies { // claim the minAgpCheck guard below keeps honest by recompiling them against it. add("androidBuildTool", libs.android.gradle.plugin) + // The SQLite rewrite (ADFA-7138). AGP's runtime classpath carries ASM, but its API + // artifacts expose only asm itself, so the rewrite compiles against the rest of it here. + compileOnly(libs.ow2.asm) + compileOnly(libs.ow2.asmCommons) + compileOnly(libs.ow2.asmTree) + compileOnly(libs.ow2.asmAnalysis) + testImplementation(gradleTestKit()) testImplementation(libs.tests.junit.jupiter) testImplementation(libs.tests.google.truth) testImplementation(projects.shared) + testImplementation(libs.ow2.asm) + testImplementation(libs.ow2.asmCommons) + testImplementation(libs.ow2.asmTree) + testImplementation(libs.ow2.asmAnalysis) testRuntimeOnly(libs.tests.junit.platformLauncher) } @@ -125,6 +136,10 @@ dependencies { "minAgpCheckImplementation"(libs.composite.constants) "minAgpCheckImplementation"(projects.gradlePluginConfig) "minAgpCheckImplementation"(projects.buildInfo) + "minAgpCheckCompileOnly"(libs.ow2.asm) + "minAgpCheckCompileOnly"(libs.ow2.asmCommons) + "minAgpCheckCompileOnly"(libs.ow2.asmTree) + "minAgpCheckCompileOnly"(libs.ow2.asmAnalysis) } tasks.named("check") { @@ -160,6 +175,7 @@ gradlePlugin { "Gradle plugin for applying LogSender-specific configuration to projects that are built with AndroidIDE" tags.set(setOf("androidide", "logsender")) } + } } diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt new file mode 100644 index 0000000000..56281d05e7 --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -0,0 +1,271 @@ +@file:Suppress("ktlint:standard:max-line-length") + +package com.itsaky.androidide.gradle.sqlite + +/** + * The rule tables of the android.database.sqlite -> requery rewrite (ADFA-7138), from the Wave 0 + * comparison of android.jar against requery 3.49.0. Names are JVM internal names and descriptors + * with Android's original names: the rename runs after the other rules. + */ +internal object SqliteRewriteRules { + const val SQLITE_PKG = "android/database/sqlite/" + private const val REQUERY_SQLITE_PKG = "io/requery/android/database/sqlite/" + private const val REQUERY_DB_PKG = "io/requery/android/database/" + + const val DATABASE = "${SQLITE_PKG}SQLiteDatabase" + const val CURSOR_FACTORY = "${SQLITE_PKG}SQLiteDatabase\$CursorFactory" + const val CURSOR_DRIVER = "${SQLITE_PKG}SQLiteCursorDriver" + const val OPEN_HELPER = "${SQLITE_PKG}SQLiteOpenHelper" + const val QUERY_BUILDER = "${SQLITE_PKG}SQLiteQueryBuilder" + const val SQLITE_CURSOR = "${SQLITE_PKG}SQLiteCursor" + const val OPEN_PARAMS = "${SQLITE_PKG}SQLiteDatabase\$OpenParams" + const val ERROR_HANDLER = "android/database/DatabaseErrorHandler" + const val ABSTRACT_WINDOWED_CURSOR = "android/database/AbstractWindowedCursor" + const val ABSTRACT_CURSOR = "android/database/AbstractCursor" + const val CROSS_PROCESS_CURSOR = "android/database/CrossProcessCursor" + + /** + * Android cursor types that requery's cursors do not extend or implement: its SQLiteCursor extends + * its own AbstractWindowedCursor and AbstractCursor, which implement only android.database.Cursor. + */ + val ANDROID_ONLY_CURSOR_TYPES: Set = setOf(ABSTRACT_WINDOWED_CURSOR, ABSTRACT_CURSOR, CROSS_PROCESS_CURSOR) + const val CURSOR_WINDOW = "android/database/CursorWindow" + const val ANDROID_SIGNAL = "android/os/CancellationSignal" + const val CORE_SIGNAL = "androidx/core/os/CancellationSignal" + const val CONTEXT = "android/content/Context" + + val COLLATE_UNICODE = Regex("COLLATE\\s+UNICODE", RegexOption.IGNORE_CASE) + val COLLATE_LOCALIZED = Regex("COLLATE\\s+LOCALIZED", RegexOption.IGNORE_CASE) + + const val HELPER = "org/appdevforall/sqliterewrite/SqliteRewriteRuntime" + const val HELPER_PACKAGE_PREFIX = "org/appdevforall/sqliterewrite/" + const val FRAMEWORK_PACKAGE_PREFIX = "androidx/sqlite/db/framework/" + + /** + * androidx.core's SQLiteCursorCompat calls SQLiteCursor.setFillWindowForwardOnly, which requery lacks, from a + * helper only an app that calls the compat method reaches. Every app that depends on androidx.core has the + * class, so failing the build for it would fail them all. + */ + const val CORE_DATABASE_PACKAGE_PREFIX = "androidx/core/database/" + const val REQUERY_PACKAGE_PREFIX = "io/requery/" + + /** The 10 shared classes and the two error handlers requery's copies use. */ + val RENAMES: Map = + buildMap { + for (name in listOf( + "SQLiteClosable", + "SQLiteCursor", + "SQLiteCursorDriver", + "SQLiteDatabase", + "SQLiteDatabase\$CursorFactory", + "SQLiteOpenHelper", + "SQLiteProgram", + "SQLiteQuery", + "SQLiteQueryBuilder", + "SQLiteStatement", + )) { + put("$SQLITE_PKG$name", "$REQUERY_SQLITE_PKG$name") + } + put(ERROR_HANDLER, "${REQUERY_DB_PKG}DatabaseErrorHandler") + put("android/database/DefaultDatabaseErrorHandler", "${REQUERY_DB_PKG}DefaultDatabaseErrorHandler") + } + + /** The Android classes that get renamed. */ + val SQLITE_CLASSES: Set = RENAMES.keys.filter { it.startsWith(SQLITE_PKG) }.toSet() + + /** Renamed superclasses of the renamed classes, from the Wave 0 supertypes.tsv. */ + val RENAMED_SUPERS: Map> = + mapOf( + "${SQLITE_PKG}SQLiteDatabase" to listOf("${SQLITE_PKG}SQLiteClosable"), + "${SQLITE_PKG}SQLiteProgram" to listOf("${SQLITE_PKG}SQLiteClosable"), + "${SQLITE_PKG}SQLiteQuery" to listOf("${SQLITE_PKG}SQLiteProgram", "${SQLITE_PKG}SQLiteClosable"), + "${SQLITE_PKG}SQLiteStatement" to listOf("${SQLITE_PKG}SQLiteProgram", "${SQLITE_PKG}SQLiteClosable"), + ) + + /** + * Members requery lacks, or has with another meaning. Key: "owner.name" -> descriptors, or an + * empty set for every descriptor (fields and the like). + */ + val MISSING_MEMBERS: Map> = + buildMap> { + fun no( + owner: String, + name: String, + desc: String = "", + ) { + getOrPut("$SQLITE_PKG$owner.$name") { mutableSetOf() }.add(desc) + } + no("SQLiteClosable", "onAllReferencesReleasedFromContainer", "()V") + no("SQLiteClosable", "releaseReferenceFromContainer", "()V") + no("SQLiteCursor", "setFillWindowForwardOnly", "(Z)V") + // requery has only the 3-argument constructor, and its window is its own CursorWindow + no("SQLiteCursor", "", "(L$DATABASE;L$CURSOR_DRIVER;Ljava/lang/String;L${SQLITE_PKG}SQLiteQuery;)V") + no("SQLiteCursor", "setWindow", "(L$CURSOR_WINDOW;)V") + // inherited from android's AbstractCursor and AbstractWindowedCursor, which requery's copies lack + // those (found with javap over both jars; SqliteRewriteResolutionTest probes the rest) + for (name in listOf("isBlob", "isFloat", "isLong", "isString", "isFieldUpdated")) { + no("SQLiteCursor", name, "(I)Z") + } + no("SQLiteCursor", "getUpdatedField", "(I)Ljava/lang/Object;") + // requery's own mWindow has its own CursorWindow type + no("SQLiteCursor", "mWindow", "L$CURSOR_WINDOW;") + no("SQLiteCursor", "getNotificationUris", "()Ljava/util/List;") + no("SQLiteCursor", "setNotificationUris", "(Landroid/content/ContentResolver;Ljava/util/List;)V") + // The constants of SQLiteDatabase that requery lacks (JOURNAL_MODE_*, SYNC_MODE_*, NO_LOCALIZED_COLLATORS, + // SQLITE_MAX_LIKE_PATTERN_LENGTH) are not listed: javac copies them into callers, so no field access remains. + no("SQLiteDatabase", "setLockingEnabled", "(Z)V") + no("SQLiteDatabase", "isDbLockedByOtherThreads", "()Z") + no("SQLiteDatabase", "yieldIfContended", "()Z") + no("SQLiteDatabase", "getSyncedTables", "()Ljava/util/Map;") + no("SQLiteDatabase", "createInMemory", "(L$OPEN_PARAMS;)L$DATABASE;") + no("SQLiteDatabase", "setCustomScalarFunction", "(Ljava/lang/String;Ljava/util/function/UnaryOperator;)V") + no("SQLiteDatabase", "setCustomAggregateFunction", "(Ljava/lang/String;Ljava/util/function/BinaryOperator;)V") + no("SQLiteDatabase", "execPerConnectionSQL", "(Ljava/lang/String;[Ljava/lang/Object;)V") + no("SQLiteDatabase", "markTableSyncable", "(Ljava/lang/String;Ljava/lang/String;)V") + no("SQLiteDatabase", "markTableSyncable", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V") + no("SQLiteOpenHelper", "setLookasideConfig", "(II)V") + no("SQLiteOpenHelper", "setOpenParams", "(L$OPEN_PARAMS;)V") + no("SQLiteOpenHelper", "setIdleConnectionTimeout", "(J)V") + no("SQLiteProgram", "getUniqueId", "()I") + no("SQLiteQueryBuilder", "isDistinct", "()Z") + no("SQLiteQueryBuilder", "appendWhereStandalone", "(Ljava/lang/CharSequence;)V") + no("SQLiteQueryBuilder", "getProjectionMap", "()Ljava/util/Map;") + no("SQLiteQueryBuilder", "setProjectionGreylist", "(Ljava/util/Collection;)V") + no("SQLiteQueryBuilder", "getProjectionGreylist", "()Ljava/util/Collection;") + no("SQLiteQueryBuilder", "getCursorFactory", "()L$CURSOR_FACTORY;") + no("SQLiteQueryBuilder", "isStrict", "()Z") + no("SQLiteQueryBuilder", "setStrictColumns", "(Z)V") + no("SQLiteQueryBuilder", "isStrictColumns", "()Z") + no("SQLiteQueryBuilder", "setStrictGrammar", "(Z)V") + no("SQLiteQueryBuilder", "isStrictGrammar", "()Z") + no("SQLiteQueryBuilder", "insert", "(L$DATABASE;Landroid/content/ContentValues;)J") + no("SQLiteQueryBuilder", "update", "(L$DATABASE;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I") + no("SQLiteQueryBuilder", "delete", "(L$DATABASE;Ljava/lang/String;[Ljava/lang/String;)I") + // requery's versions have no selectionArgs parameter + no( + "SQLiteQueryBuilder", + "buildQuery", + "([Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", + ) + no( + "SQLiteQueryBuilder", + "buildUnionSubQuery", + "(Ljava/lang/String;[Ljava/lang/String;Ljava/util/Set;ILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", + ) + // added to android.jar after the Wave 0 members.tsv (API 35/36); requery has none of them + no("SQLiteDatabase", "beginTransactionReadOnly", "()V") + no("SQLiteDatabase", "beginTransactionWithListenerReadOnly", "(L${SQLITE_PKG}SQLiteTransactionListener;)V") + no("SQLiteDatabase", "createRawStatement", "(Ljava/lang/String;)L${SQLITE_PKG}SQLiteRawStatement;") + no("SQLiteDatabase", "getLastChangedRowCount", "()J") + no("SQLiteDatabase", "getLastInsertRowId", "()J") + no("SQLiteDatabase", "getTotalChangedRowCount", "()J") + // the OpenParams overloads + no("SQLiteDatabase", "openDatabase", "(Ljava/io/File;L$OPEN_PARAMS;)L$DATABASE;") + no("SQLiteOpenHelper", "", "(Landroid/content/Context;Ljava/lang/String;IL$OPEN_PARAMS;)V") + } + + /** + * Method names with an entry in [MISSING_MEMBERS], so other calls need no hierarchy lookup. Constructors + * are left out: a subclass has no constructor of its parent's, so only the renamed classes themselves match. + */ + val MISSING_MEMBER_NAMES: Set = + MISSING_MEMBERS.keys + .map { it.substringAfterLast('.') } + .filter { it != "" } + .toSet() + + /** Names of the fields the missing-member rule can match: entries for every descriptor, or with a field descriptor. */ + val MISSING_FIELD_NAMES: Set = + MISSING_MEMBERS + .filterValues { descs -> descs.any { !it.startsWith("(") } } + .keys + .map { it.substringAfterLast('.') } + .toSet() + + /** A call whose descriptor changes: selectionArgs-style String[] to Object[], and the signal. */ + class DescriptorRule( + val owner: String, + val name: String, + val desc: String, + val objectArrayParams: Set, + ) + + private val S = "Ljava/lang/String;" + private val SA = "[Ljava/lang/String;" + private val SIG = "L$ANDROID_SIGNAL;" + private const val CF = "L$CURSOR_FACTORY;" + private const val CUR = "Landroid/database/Cursor;" + + val DESCRIPTOR_RULES: List = + run { + fun rule( + name: String, + params: String, + ret: String, + vararg objectArrays: Int, + ) = listOf( + DescriptorRule(DATABASE, name, "($params)$ret", objectArrays.toSet()), + DescriptorRule(DATABASE, name, "($params$SIG)$ret", objectArrays.toSet()), + ) + rule("query", "Z$S$SA$S$SA$S$S$S$S", CUR, 4) + + rule("query", "$S$SA$S$SA$S$S$S", CUR, 3) + + rule("query", "$S$SA$S$SA$S$S$S$S", CUR, 3) + + rule("queryWithFactory", "${CF}Z$S$SA$S$SA$S$S$S$S", CUR, 5) + + rule("rawQuery", "$S$SA", CUR, 1) + + rule("rawQueryWithFactory", "$CF$S$SA$S", CUR, 2) + + // the one signal-only entry; its signal-less form is not an Android method + DescriptorRule(DATABASE, "validateSql", "(${S}$SIG)V", emptySet()) + + DescriptorRule(QUERY_BUILDER, "query", "(L$DATABASE;$SA$S$SA$S$S$S$S$SIG)$CUR", emptySet()) + } + + /** Names of the calls whose descriptor changes. */ + val DESCRIPTOR_RULE_NAMES: Set = DESCRIPTOR_RULES.map { it.name }.toSet() + + /** SQLiteCursorDriver.query, matched on any owner: an app class may implement the interface. */ + const val DRIVER_QUERY_NAME = "query" + const val DRIVER_QUERY_DESC = "($CF[Ljava/lang/String;)Landroid/database/Cursor;" + const val DRIVER_QUERY_NEW_DESC = "($CF[Ljava/lang/Object;)Landroid/database/Cursor;" + + const val HELPER_OPEN_DESC = "(Ljava/lang/String;${CF}I)L$DATABASE;" + const val HELPER_OPEN_HANDLER_DESC = "(Ljava/lang/String;${CF}IL$ERROR_HANDLER;)L$DATABASE;" + const val CONTEXT_OPEN_DESC = "(Ljava/lang/String;I$CF)L$DATABASE;" + const val CONTEXT_OPEN_HANDLER_DESC = "(Ljava/lang/String;I${CF}L$ERROR_HANDLER;)L$DATABASE;" + const val CONTEXT_DELETE_DESC = "(Ljava/lang/String;)Z" + const val HELPER_SIGNAL_DESC = "(L$ANDROID_SIGNAL;)L$CORE_SIGNAL;" + + const val DATABASE_UTILS = "android/database/DatabaseUtils" + + /** + * DatabaseUtils methods that take renamed types and that the runtime reimplements, as name plus + * Android descriptor. requery has no DatabaseUtils. The rest of DatabaseUtils' and other platform + * methods that mention renamed types fail the build. + */ + val REDIRECTED_UTILS: Set = + run { + val db = "L$DATABASE;" + val stmt = "L${SQLITE_PKG}SQLiteStatement;" + setOf( + "queryNumEntries($db$S)J", + "queryNumEntries($db$S$S)J", + "queryNumEntries($db$S$S$SA)J", + "longForQuery($db$S$SA)J", + "longForQuery($stmt$SA)J", + "stringForQuery($db$S$SA)$S", + "stringForQuery($stmt$SA)$S", + ) + } + + /** How a renamed class appears in a descriptor. */ + val RENAMED_DESCRIPTOR_TOKENS: List = RENAMES.keys.map { "L$it;" } + + val CONTEXT_FAMILY: Set = + setOf( + CONTEXT, + "android/content/ContextWrapper", + "android/view/ContextThemeWrapper", + "android/app/Activity", + "android/app/Application", + "android/app/Service", + "android/app/IntentService", + ) +} diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteVisitorFactory.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteVisitorFactory.kt new file mode 100644 index 0000000000..6d70446ab1 --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteVisitorFactory.kt @@ -0,0 +1,34 @@ +package com.itsaky.androidide.gradle.sqlite + +import com.android.build.api.instrumentation.AsmClassVisitorFactory +import com.android.build.api.instrumentation.ClassContext +import com.android.build.api.instrumentation.ClassData +import com.android.build.api.instrumentation.InstrumentationParameters +import org.objectweb.asm.ClassVisitor + +/** Moves classes from android.database.sqlite to requery; see [SqliteRewriter]. */ +abstract class SqliteRewriteVisitorFactory : AsmClassVisitorFactory { + override fun createClassVisitor( + classContext: ClassContext, + nextClassVisitor: ClassVisitor, + ): ClassVisitor = SqliteRewriter.createVisitor(nextClassVisitor, AgpHierarchy(classContext)) + + override fun isInstrumentable(classData: ClassData): Boolean = !RewritePolicy.isExcluded(classData.className.replace('.', '/')) + + private class AgpHierarchy( + private val context: ClassContext, + ) : ClassHierarchy { + override fun superTypes(internalName: String): Collection? { + val data = context.loadClassData(internalName.replace('/', '.')) ?: return null + val result = linkedSetOf() + val pending = ArrayDeque(data.superClasses + data.interfaces) + while (pending.isNotEmpty()) { + val name = pending.removeFirst() + if (result.add(name.replace('.', '/'))) { + context.loadClassData(name)?.let { pending.addAll(it.interfaces) } + } + } + return result + } + } +} diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt new file mode 100644 index 0000000000..f356a6e93f --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -0,0 +1,759 @@ +@file:Suppress("ktlint:standard:max-line-length") + +package com.itsaky.androidide.gradle.sqlite + +import com.android.build.api.instrumentation.FramesComputationMode +import org.gradle.api.logging.Logging +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassVisitor +import org.objectweb.asm.ClassWriter +import org.objectweb.asm.Handle +import org.objectweb.asm.Opcodes +import org.objectweb.asm.Type +import org.objectweb.asm.commons.ClassRemapper +import org.objectweb.asm.commons.Remapper +import org.objectweb.asm.tree.AbstractInsnNode +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.FieldInsnNode +import org.objectweb.asm.tree.FrameNode +import org.objectweb.asm.tree.InsnList +import org.objectweb.asm.tree.InvokeDynamicInsnNode +import org.objectweb.asm.tree.JumpInsnNode +import org.objectweb.asm.tree.LdcInsnNode +import org.objectweb.asm.tree.LineNumberNode +import org.objectweb.asm.tree.MethodInsnNode +import org.objectweb.asm.tree.MethodNode +import org.objectweb.asm.tree.TypeInsnNode +import org.objectweb.asm.tree.VarInsnNode +import org.objectweb.asm.tree.analysis.Analyzer +import org.objectweb.asm.tree.analysis.AnalyzerException +import org.objectweb.asm.tree.analysis.BasicInterpreter +import org.objectweb.asm.tree.analysis.BasicValue +import org.objectweb.asm.tree.analysis.Frame +import com.itsaky.androidide.gradle.sqlite.SqliteRewriteRules as Rules + +/** Thrown with every unsupported reference of a class, so the build names them all at once. */ +class SqliteRewriteException( + message: String, +) : RuntimeException(message) + +/** All supertypes (classes and interfaces, transitive) of a class in internal names, or null. */ +fun interface ClassHierarchy { + fun superTypes(internalName: String): Collection? + + companion object { + val NONE = ClassHierarchy { null } + } +} + +/** Which rules run on a class. The rename always runs. */ +enum class RewritePolicy( + val redirect: Boolean, + val fail: Boolean, +) { + FULL(true, true), + + /** androidx's framework classes (still reachable through AndroidSQLiteDriver; see the docs) and androidx.core's database helpers. */ + NO_FAIL(true, false), + + /** The runtime helper: its redirect targets must not be redirected themselves. */ + RENAME_ONLY(false, false), + ; + + companion object { + fun forClass(internalName: String): RewritePolicy = + when { + internalName.startsWith(Rules.HELPER_PACKAGE_PREFIX) -> RENAME_ONLY + internalName.startsWith(Rules.FRAMEWORK_PACKAGE_PREFIX) -> NO_FAIL + internalName.startsWith(Rules.CORE_DATABASE_PACKAGE_PREFIX) -> NO_FAIL + else -> FULL + } + + /** Classes the rewrite never touches: requery's own. */ + fun isExcluded(internalName: String): Boolean = internalName.startsWith(Rules.REQUERY_PACKAGE_PREFIX) + } +} + +object SqliteRewriter { + private val remapper = + object : Remapper() { + override fun map(internalName: String): String = Rules.RENAMES[internalName] ?: internalName + } + + /** + * What the plugin registers with AGP, and what [rewrite] writes. Frames are copied, so the one change + * that invalidates them, a retyped `SQLiteCursorDriver.query` parameter, is handled in [ClassRewrite]. + */ + val FRAMES_MODE = FramesComputationMode.COPY_FRAMES + + private val logger by lazy { Logging.getLogger(SqliteRewriter::class.java) } + + /** For tests: the transformed bytes of one class. */ + fun rewrite( + bytes: ByteArray, + hierarchy: ClassHierarchy = ClassHierarchy.NONE, + warn: (String) -> Unit = {}, + ): ByteArray { + val writer = ClassWriter(ClassWriter.COMPUTE_MAXS) + ClassReader(bytes).accept(createVisitor(writer, hierarchy, warn), 0) + return writer.toByteArray() + } + + /** + * Buffers the class, applies the call rules on the original (Android) names, then renames on + * the way to [next]. Throws from visitEnd, which fails the AGP transform with the message. + */ + fun createVisitor( + next: ClassVisitor, + hierarchy: ClassHierarchy, + warn: (String) -> Unit = { logger.warn(it) }, + ): ClassVisitor = + object : ClassNode(Opcodes.ASM9) { + override fun visitEnd() { + super.visitEnd() + if (RewritePolicy.isExcluded(name)) { + accept(next) + return + } + ClassRewrite(this, RewritePolicy.forClass(name), hierarchy, warn).run() + accept(ClassRemapper(next, remapper)) + } + } + + private class TaintValue( + type: Type?, + val sqliteCursor: Boolean, + ) : BasicValue(type) { + // Frame.merge keeps the old value when the merged one equals it, so the taint must count + override fun equals(other: Any?): Boolean = + other is BasicValue && super.equals(other) && sqliteCursor == ((other as? TaintValue)?.sqliteCursor ?: false) + + override fun hashCode(): Int = super.hashCode() * 31 + if (sqliteCursor) 1 else 0 + } + + private class ClassRewrite( + val cn: ClassNode, + val policy: RewritePolicy, + val hierarchy: ClassHierarchy, + val warn: (String) -> Unit, + ) { + val violations = linkedSetOf() + + fun run() { + if (policy.fail) { + checkDeclarations() + } + for (m in cn.methods) { + if (policy.fail && isContextDatabaseMethod(m.name, m.desc) && + (cn.superName in Rules.CONTEXT_FAMILY || isContext(cn.name)) + ) { + violations += "method '${m.name}${m.desc}' overrides Context.${m.name}; calls to it are redirected to requery's " + + "runtime and would skip the override" + } + if (policy.redirect && m.name == Rules.DRIVER_QUERY_NAME && m.desc == Rules.DRIVER_QUERY_DESC) { + retypeParameters(m, Rules.DRIVER_QUERY_NEW_DESC) + } + rewriteMethod(m) + } + if (violations.isNotEmpty()) { + throw SqliteRewriteException( + "Code on the Go cannot move '${cn.name.replace('/', '.')}' from android.database.sqlite to " + + "requery (cogo.sqliteDebugger=true):\n" + violations.joinToString("\n") { " - $it" }, + ) + } + } + + /** + * Gives [m] the descriptor [newDesc], which differs from its own in parameters that become wider + * (`String[]` to `Object[]`), and keeps the body valid. The body and its copied frames still treat those + * parameters as the old type, so each is cast back on entry. Frames before the first full one are relative + * to the method's implicit first frame, which now has the wide type, so every frame is written in full. + */ + fun retypeParameters( + m: MethodNode, + newDesc: String, + ) { + val oldDesc = m.desc + m.desc = newDesc + if (m.instructions.size() == 0) return + expandFrames(m, oldDesc) + val old = Type.getArgumentTypes(oldDesc) + val new = Type.getArgumentTypes(newDesc) + var slot = if (m.access and Opcodes.ACC_STATIC != 0) 0 else 1 + val prologue = InsnList() + for (i in old.indices) { + if (old[i] != new[i]) { + prologue.add(VarInsnNode(Opcodes.ALOAD, slot)) + prologue.add(TypeInsnNode(Opcodes.CHECKCAST, old[i].internalName)) + prologue.add(VarInsnNode(Opcodes.ASTORE, slot)) + } + slot += old[i].size + } + m.instructions.insert(prologue) + } + + /** Rewrites every compressed frame of [m] as a full one, starting from [originalDesc]'s parameters. */ + fun expandFrames( + m: MethodNode, + originalDesc: String, + ) { + var locals = ArrayList() + if (m.access and Opcodes.ACC_STATIC == 0) locals += cn.name + for (t in Type.getArgumentTypes(originalDesc)) { + locals += + when (t.sort) { + Type.BOOLEAN, Type.CHAR, Type.BYTE, Type.SHORT, Type.INT -> Opcodes.INTEGER + Type.FLOAT -> Opcodes.FLOAT + Type.LONG -> Opcodes.LONG + Type.DOUBLE -> Opcodes.DOUBLE + else -> t.internalName + } + } + for (frame in m.instructions) { + if (frame !is FrameNode) continue + var stack: List = emptyList() + when (frame.type) { + Opcodes.F_NEW, Opcodes.F_FULL -> { + locals = ArrayList(frame.local) + stack = ArrayList(frame.stack) + } + + Opcodes.F_APPEND -> { + locals.addAll(frame.local) + } + + Opcodes.F_CHOP -> { + repeat(frame.local.size) { locals.removeAt(locals.lastIndex) } + } + + Opcodes.F_SAME1 -> { + stack = ArrayList(frame.stack) + } + } + frame.type = Opcodes.F_NEW + frame.local = ArrayList(locals) + frame.stack = ArrayList(stack) + } + } + + fun checkDeclarations() { + for (f in cn.fields) { + if (f.desc.contains(Rules.OPEN_PARAMS)) violations += "field '${f.name}' has type OpenParams, which requery lacks" + } + for (m in cn.methods) { + if (m.desc.contains(Rules.OPEN_PARAMS)) { + violations += "method '${m.name}${m.desc}' uses OpenParams, which requery lacks" + } + } + } + + private val ancestorsCache = HashMap>() + private val superTypesCache = HashMap?>() + + private fun superTypes(owner: String): Collection? = superTypesCache.getOrPut(owner) { hierarchy.superTypes(owner) } + + /** Owners that cannot extend a renamed class: the JDK, Kotlin, and Android outside the renamed set. */ + private fun cannotBeSqlite(owner: String): Boolean = + owner.startsWith("java/") || owner.startsWith("javax/") || owner.startsWith("kotlin/") || owner.startsWith("kotlinx/") || + (owner.startsWith("android/") && owner !in Rules.SQLITE_CLASSES) + + /** The renamed classes that [owner] is or extends, nearest first, so the rule tables see them all. */ + fun renamedAncestors(owner: String): List { + if (owner.startsWith("[")) return emptyList() + return ancestorsCache.getOrPut(owner) { + val direct = + when { + owner in Rules.SQLITE_CLASSES -> listOf(owner) + cannotBeSqlite(owner) -> emptyList() + else -> superTypes(owner)?.filter { it in Rules.SQLITE_CLASSES }.orEmpty() + } + direct.flatMap { listOf(it) + Rules.RENAMED_SUPERS[it].orEmpty() }.distinct() + } + } + + fun isContext(owner: String): Boolean = owner in Rules.CONTEXT_FAMILY || superTypes(owner)?.contains(Rules.CONTEXT) == true + + fun rewriteMethod(m: MethodNode) { + val tainted = if (policy.fail) cursorCastTaint(m) else emptySet() + var line = -1 + var insn: AbstractInsnNode? = m.instructions.first + while (insn != null) { + val following = insn.next + if (insn is LineNumberNode) { + line = insn.line + } + when (insn) { + is MethodInsnNode -> { + methodInsn(m, insn, line) + } + + is FieldInsnNode -> { + fieldInsn(m, insn, line) + } + + is TypeInsnNode -> { + typeInsn(m, insn, line, tainted) + } + + is LdcInsnNode -> { + (insn.cst as? Type)?.let { + if (it.descriptor.contains(Rules.OPEN_PARAMS)) violate(m, line, "OpenParams, which requery lacks") + } + (insn.cst as? String)?.let { sqlConstant(m, line, it) } + } + + is InvokeDynamicInsnNode -> { + invokeDynamic(m, insn, line) + } + } + insn = following + } + } + + /** requery's native SQLite has no ICU: there is no UNICODE collator, and LOCALIZED compares bytes. */ + fun sqlConstant( + m: MethodNode, + line: Int, + text: String, + ) { + if (!policy.fail) return + if (Rules.COLLATE_UNICODE.containsMatchIn(text)) { + violate( + m, + line, + "SQL text uses COLLATE UNICODE, which does not exist in requery's SQLite (no ICU); the statement would fail", + ) + } + if (Rules.COLLATE_LOCALIZED.containsMatchIn(text)) { + val where = if (line >= 0) "line $line" else "no line number" + warn( + "${cn.name.replace('/', '.')}.${m.name} ($where): COLLATE LOCALIZED works in requery's SQLite but sorts by " + + "byte value (no ICU), not by the device locale", + ) + } + } + + fun invokeDynamic( + m: MethodNode, + insn: InvokeDynamicInsnNode, + line: Int, + ) { + if (insn.desc.contains(Rules.OPEN_PARAMS)) violate(m, line, "OpenParams, which requery lacks") + for (arg in insn.bsmArgs) { + when (arg) { + is String -> sqlConstant(m, line, arg) + is Handle -> handle(m, line, arg) + is Type -> if (arg.descriptor.contains(Rules.OPEN_PARAMS)) violate(m, line, "OpenParams, which requery lacks") + } + } + } + + fun violate( + m: MethodNode, + line: Int, + what: String, + ) { + if (!policy.fail) return + val where = if (line >= 0) "line $line" else "no line number" + violations += "${m.name}${m.desc} ($where): $what" + } + + fun fieldInsn( + m: MethodNode, + f: FieldInsnNode, + line: Int, + ) { + fieldProblem(f.owner, f.name, f.desc)?.let { violate(m, line, it) } + } + + fun fieldProblem( + owner: String, + name: String, + desc: String, + ): String? { + if (desc.contains(Rules.OPEN_PARAMS) || owner == Rules.OPEN_PARAMS) { + return "OpenParams, which requery lacks" + } + // only SQLiteCursor.mWindow is listed today; skip the hierarchy lookup for every other field + if (name !in Rules.MISSING_FIELD_NAMES) return null + return renamedAncestors(owner) + .firstOrNull { Rules.MISSING_MEMBERS["$it.$name"]?.let { descs -> "" in descs || desc in descs } == true } + ?.let { "${simple(it)}.$name does not exist in requery" } + } + + fun typeInsn( + m: MethodNode, + t: TypeInsnNode, + line: Int, + tainted: Set, + ) { + if (t.desc.startsWith(Rules.OPEN_PARAMS)) { + violate(m, line, "OpenParams, which requery lacks") + } + if (t.opcode == Opcodes.CHECKCAST && t.desc in Rules.ANDROID_ONLY_CURSOR_TYPES && t in tainted && + !isGuardedByInstanceof(m, t) + ) { + violate( + m, + line, + "cast of an SQLite cursor to ${t.desc.replace('/', '.')}; requery's cursors are not instances of it, " + + "so the cast would throw", + ) + } + } + + /** What the rules do with one call or method handle. */ + sealed class Action { + object None : Action() + + class Fail( + val what: String, + ) : Action() + + /** Replace the call by an INVOKESTATIC of the runtime helper. */ + class Redirect( + val name: String, + val desc: String, + ) : Action() + + /** Same call, new descriptor; [signal] inserts the CancellationSignal conversion. */ + class Retype( + val desc: String, + val signal: Boolean, + ) : Action() + } + + /** The platform methods on Context that are redirected: name, then the descriptors they match. */ + private fun isContextDatabaseMethod( + name: String, + desc: String, + ) = (name == "openOrCreateDatabase" && (desc == Rules.CONTEXT_OPEN_DESC || desc == Rules.CONTEXT_OPEN_HANDLER_DESC)) || + (name == "deleteDatabase" && desc == Rules.CONTEXT_DELETE_DESC) + + /** + * Decides, without changing anything, what happens to `owner.name desc` invoked with [opcode] + * (the opcode a method handle's kind stands for). Redirects and retyping apply only when the + * policy allows; a [Action.Fail] is reported only when it fails. + */ + fun decide( + opcode: Int, + owner: String, + name: String, + desc: String, + ): Action { + if (owner == Rules.OPEN_PARAMS || desc.contains(Rules.OPEN_PARAMS)) { + return Action.Fail("OpenParams, which requery lacks") + } + if (policy.redirect) { + redirectTarget(opcode, owner, name, desc)?.let { return it } + if (name == Rules.DRIVER_QUERY_NAME && desc == Rules.DRIVER_QUERY_DESC) { + return Action.Retype(Rules.DRIVER_QUERY_NEW_DESC, false) + } + } + if (isContextDatabaseMethod(name, desc) && !owner.startsWith("[")) { + // the redirect above did not take it: super.* calls and owners that are not known to be a Context + if (opcode == Opcodes.INVOKESPECIAL && isContext(owner)) { + return Action.Fail( + "super.$name on a Context cannot be redirected to requery; call it on this or on a Context instead", + ) + } + if (superTypes(owner) == null && owner !in Rules.CONTEXT_FAMILY) { + return Action.Fail( + "$owner.$name is a Context database method if $owner is a Context, " + + "but $owner cannot be resolved, so it cannot be redirected to requery", + ) + } + } + + // the lookup is skipped for owners no rule below can match, which is nearly every call + val ancestors = if (needsAncestors(owner, name, desc)) renamedAncestors(owner) else emptyList() + if (ancestors.isEmpty()) { + if (owner.startsWith("android/") && mentionsRenamed(desc)) { + return Action.Fail( + "${simple(owner)}.$name$desc takes or returns an SQLite class that requery replaces; " + + "the platform method would not link", + ) + } + return Action.None + } + for (c in ancestors) { + if (Rules.MISSING_MEMBERS["$c.$name"]?.let { it.isEmpty() || desc in it } == true) { + return Action.Fail("${simple(c)}.$name$desc does not exist in requery") + } + } + if (desc.contains(Rules.CURSOR_WINDOW)) { + return Action.Fail("${simple(ancestors.first())}.$name uses android.database.CursorWindow; requery has its own") + } + if (!policy.redirect) return Action.None + val rule = + Rules.DESCRIPTOR_RULES.firstOrNull { it.owner in ancestors && it.name == name && it.desc == desc } ?: return Action.None + val args = Type.getArgumentTypes(desc).map { it.descriptor }.toMutableList() + rule.objectArrayParams.forEach { args[it] = "[Ljava/lang/Object;" } + val signal = args.last() == "L${Rules.ANDROID_SIGNAL};" + if (signal) { + args[args.lastIndex] = "L${Rules.CORE_SIGNAL};" + } + return Action.Retype("(" + args.joinToString("") + ")" + Type.getReturnType(desc).descriptor, signal) + } + + fun methodInsn( + m: MethodNode, + mi: MethodInsnNode, + line: Int, + ) { + when (val action = decide(mi.opcode, mi.owner, mi.name, mi.desc)) { + Action.None -> {} + + is Action.Fail -> { + violate(m, line, action.what) + } + + is Action.Redirect -> { + mi.setOpcode(Opcodes.INVOKESTATIC) + mi.owner = Rules.HELPER + mi.name = action.name + mi.desc = action.desc + mi.itf = false + } + + is Action.Retype -> { + if (action.signal) { + m.instructions.insertBefore( + mi, + MethodInsnNode(Opcodes.INVOKESTATIC, Rules.HELPER, "toCancellationSignal", Rules.HELPER_SIGNAL_DESC, false), + ) + } + mi.desc = action.desc + } + } + } + + /** + * A method handle among an invokedynamic's bootstrap arguments (`db::rawQuery`) points at a + * member the call rules would change or reject, but the handle itself cannot be patched in + * place the way an instruction is. Such handles fail the build with a hint to write a lambda, + * whose body is an ordinary call. + */ + fun handle( + m: MethodNode, + line: Int, + h: Handle, + ) { + val what = + when (h.tag) { + Opcodes.H_GETFIELD, Opcodes.H_GETSTATIC, Opcodes.H_PUTFIELD, Opcodes.H_PUTSTATIC -> { + fieldProblem(h.owner, h.name, h.desc) + } + + else -> { + val opcode = + when (h.tag) { + Opcodes.H_INVOKESTATIC -> Opcodes.INVOKESTATIC + Opcodes.H_INVOKEINTERFACE -> Opcodes.INVOKEINTERFACE + Opcodes.H_INVOKEVIRTUAL -> Opcodes.INVOKEVIRTUAL + else -> Opcodes.INVOKESPECIAL + } + when (val action = decide(opcode, h.owner, h.name, h.desc)) { + Action.None -> null + is Action.Fail -> action.what + is Action.Redirect -> "the runtime takes this call over" + is Action.Retype -> "its descriptor changes in requery" + } + } + } + if (what != null) { + violate(m, line, "method reference ${simple(h.owner)}::${h.name} cannot be rewritten ($what); use a lambda instead") + } + } + + /** Returns the replacement for a call the runtime helper takes over, or null. */ + fun redirectTarget( + opcode: Int, + owner: String, + name: String, + desc: String, + ): Action.Redirect? = + when { + opcode == Opcodes.INVOKESTATIC && owner == Rules.DATABASE && name == "openDatabase" && + (desc == Rules.HELPER_OPEN_DESC || desc == Rules.HELPER_OPEN_HANDLER_DESC) -> { + Action.Redirect(name, desc) + } + + opcode == Opcodes.INVOKEVIRTUAL && name == "openOrCreateDatabase" && + (desc == Rules.CONTEXT_OPEN_DESC || desc == Rules.CONTEXT_OPEN_HANDLER_DESC) && isContext(owner) -> { + Action.Redirect(name, "(L${Rules.CONTEXT};" + desc.substring(1)) + } + + opcode == Opcodes.INVOKEVIRTUAL && name == "deleteDatabase" && desc == Rules.CONTEXT_DELETE_DESC && isContext(owner) -> { + Action.Redirect(name, "(L${Rules.CONTEXT};Ljava/lang/String;)Z") + } + + opcode == Opcodes.INVOKESTATIC && owner == Rules.DATABASE_UTILS && (name + desc) in Rules.REDIRECTED_UTILS -> { + Action.Redirect(name, desc) + } + + else -> { + null + } + } + + fun needsAncestors( + owner: String, + name: String, + desc: String, + ) = owner in Rules.SQLITE_CLASSES || name in Rules.MISSING_MEMBER_NAMES || name in Rules.DESCRIPTOR_RULE_NAMES || + desc.contains(Rules.CURSOR_WINDOW) + + private fun previousReal(node: AbstractInsnNode): AbstractInsnNode? { + var n = node.previous + while (n != null && n.opcode < 0) n = n.previous + return n + } + + private fun nextReal(node: AbstractInsnNode): AbstractInsnNode? { + var n = node.next + while (n != null && n.opcode < 0) n = n.next + return n + } + + /** True when the instruction before [label] never falls through to it. */ + private fun endsWithExit(label: AbstractInsnNode): Boolean { + val op = previousReal(label)?.opcode ?: return false + return op == Opcodes.GOTO || op == Opcodes.ATHROW || op in Opcodes.IRETURN..Opcodes.RETURN + } + + /** + * The idiom `if (c instanceof X) ... (X) c`: the operand of [cast] is a local read right before it, + * and an INSTANCEOF of the same type on that local sits before it in a branch that contains the + * cast, with no store to the local in between. A guard that jumps over the cast when false (IFEQ) + * covers the instructions up to its target; one that jumps to the cast when true (IFNE) must be + * followed by code that cannot fall through to its target. The cast then cannot throw, so it is + * not reported. + */ + fun isGuardedByInstanceof( + m: MethodNode, + cast: TypeInsnNode, + ): Boolean { + val local = (previousReal(cast) as? VarInsnNode)?.takeIf { it.opcode == Opcodes.ALOAD }?.`var` ?: return false + val castIndex = m.instructions.indexOf(cast) + var node: AbstractInsnNode? = cast.previous + while (node != null) { + if (node is VarInsnNode && node.`var` == local && node.opcode in Opcodes.ISTORE..Opcodes.ASTORE) return false + if (node is TypeInsnNode && node.opcode == Opcodes.INSTANCEOF && node.desc == cast.desc && + (previousReal(node) as? VarInsnNode)?.let { it.opcode == Opcodes.ALOAD && it.`var` == local } == true + ) { + val jump = nextReal(node) as? JumpInsnNode + if (jump != null) { + val target = m.instructions.indexOf(jump.label) + when (jump.opcode) { + Opcodes.IFEQ -> { + if (target > castIndex) return true + } + + Opcodes.IFNE -> { + if (target <= castIndex && target > m.instructions.indexOf(jump) && endsWithExit(jump.label)) return true + } + } + } + } + node = node.previous + } + return false + } + + fun mentionsRenamed(desc: String) = desc.contains("android/database/") && Rules.RENAMED_DESCRIPTOR_TOKENS.any { desc.contains(it) } + + fun simple(name: String) = name.substringAfterLast('/') + + /** + * The CHECKCASTs to AbstractWindowedCursor whose operand came from an SQLite API (a call on + * one of the renamed classes returning a cursor, or a parameter or instance field declared as + * SQLiteCursor), through locals and the stack. Approximate: values that went through other + * calls, array elements or static fields are not followed (a miss). + */ + fun cursorCastTaint(m: MethodNode): Set { + val casts = + m.instructions.filter { + it is TypeInsnNode && it.opcode == Opcodes.CHECKCAST && it.desc in Rules.ANDROID_ONLY_CURSOR_TYPES + } + if (casts.isEmpty()) return emptySet() + val interpreter = + object : BasicInterpreter(Opcodes.ASM9) { + override fun newValue(type: Type?): BasicValue? = + super.newValue(type)?.let { + if (it.type == + null + ) { + it + } else { + TaintValue(it.type, false) + } + } + + override fun newParameterValue( + isInstanceMethod: Boolean, + local: Int, + type: Type?, + ): BasicValue? { + val r = super.newParameterValue(isInstanceMethod, local, type) + return if (r != null && type?.descriptor == "L${Rules.SQLITE_CURSOR};") TaintValue(r.type, true) else r + } + + override fun unaryOperation( + insn: AbstractInsnNode, + value: BasicValue, + ): BasicValue? { + val r = super.unaryOperation(insn, value) + if (insn is FieldInsnNode && r != null && insn.desc == "L${Rules.SQLITE_CURSOR};") { + return TaintValue(r.type, true) + } + if (insn.opcode == Opcodes.CHECKCAST && r != null) { + val castTo = (insn as TypeInsnNode).desc + return TaintValue(r.type, (value as? TaintValue)?.sqliteCursor == true || castTo == Rules.SQLITE_CURSOR) + } + return r + } + + override fun naryOperation( + insn: AbstractInsnNode, + values: MutableList, + ): BasicValue? { + val r = super.naryOperation(insn, values) + if (insn is MethodInsnNode && r != null && r.type != null) { + val ret = Type.getReturnType(insn.desc) + val cursorLike = + ret.sort == Type.OBJECT && + (ret.internalName == "android/database/Cursor" || ret.internalName == Rules.SQLITE_CURSOR) + if (cursorLike && (renamedAncestors(insn.owner).isNotEmpty() || insn.owner == Rules.CURSOR_FACTORY)) { + return TaintValue(r.type, true) + } + } + return r + } + + override fun merge( + value1: BasicValue, + value2: BasicValue, + ): BasicValue { + val tainted = (value1 as? TaintValue)?.sqliteCursor == true || (value2 as? TaintValue)?.sqliteCursor == true + // BasicInterpreter.merge answers UNINITIALIZED for values that differ, taint included + if (tainted && value1.type != null && value1.type == value2.type) return TaintValue(value1.type, true) + return super.merge(value1, value2) + } + } + val analyzer = Analyzer(interpreter) + val frames: Array?> = + try { + analyzer.analyze(cn.name, m) + } catch (e: AnalyzerException) { + return emptySet() + } + val insns = m.instructions + return casts + .filter { cast -> + val frame = frames[insns.indexOf(cast)] + frame != null && (frame.getStack(frame.stackSize - 1) as? TaintValue)?.sqliteCursor == true + }.toSet() + } + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifier.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifier.kt new file mode 100644 index 0000000000..11f751032a --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifier.kt @@ -0,0 +1,98 @@ +package com.itsaky.androidide.gradle.sqlite + +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassWriter +import org.objectweb.asm.commons.ClassRemapper +import org.objectweb.asm.commons.Remapper +import java.io.PrintWriter +import java.io.StringWriter +import java.net.URLClassLoader + +/** + * Rewrites compiled samples the way the plugin does and verifies the result twice: with ASM's + * CheckClassAdapter (types, through a loader that sees requery, android.jar, androidx core and + * androidx sqlite) and by making the JVM link each class, which runs its verifier over the + * StackMapTable. asm-util is on the test runtime classpath through AGP only, hence the reflection. + */ +internal object BytecodeVerifier { + private val renamer = + object : Remapper() { + override fun map(internalName: String): String = SqliteRewriteRules.RENAMES[internalName] ?: internalName + } + + private val jars by lazy { + listOfNotNull( + TestJars.requeryJar, + TestJars.androidJar, + TestJars.androidxCoreJar, + TestJars.androidxSqliteJar, + TestJars.kotlinStdlibJar, + ) + } + + /** Original (Android-named) samples are added on top of the jars, renamed ones to [after]. */ + private class Universe( + val before: ClassIndex, + val after: ClassIndex, + ) + + private fun universe(originals: Map): Universe { + val before = ClassIndex(listOf(TestJars.androidJar, TestJars.androidxCoreJar)) + val after = ClassIndex(jars) + for (bytes in originals.values) { + before.addClass(bytes) + val renamed = ClassWriter(0) + ClassReader(bytes).accept(ClassRemapper(renamed, renamer), 0) + after.addClass(renamed.toByteArray()) + } + return Universe(before, after) + } + + /** Rewrites every class, then verifies all of them. Returns the rewritten bytes by original name. */ + fun rewriteAndVerify(originals: Map): Map { + val u = universe(originals) + val hierarchy = ClassHierarchy { name -> if (u.before.knows(name)) u.before.superTypes(name) else null } + val out = originals.mapValues { SqliteRewriter.rewrite(it.value, hierarchy) } + verify(out.values.associateBy { ClassReader(it).className }) + return out + } + + /** Fails with the verifier's output when any class in [classes] (by its final name) does not verify. */ + fun verify(classes: Map) { + val loader = SampleLoader(classes) + val checkClass = Class.forName("org.objectweb.asm.util.CheckClassAdapter") + val check = + checkClass.getMethod( + "verify", + ClassReader::class.java, + ClassLoader::class.java, + Boolean::class.javaPrimitiveType, + PrintWriter::class.java, + ) + val problems = StringBuilder() + for ((name, bytes) in classes) { + val sw = StringWriter() + check.invoke(null, ClassReader(bytes), loader, false, PrintWriter(sw)) + if (sw.toString().isNotBlank()) problems.append("CheckClassAdapter on $name:\n").append(sw).append('\n') + try { + // reflection links the class, which verifies it + Class.forName(name.replace('/', '.'), false, loader).declaredMethods + } catch (e: LinkageError) { + problems.append("JVM verification of $name failed: $e\n") + } + } + check(problems.isEmpty()) { "Rewritten bytecode does not verify:\n$problems" } + } + + /** A loader over the same classpath as [verify], defining [classes] (by final name). */ + fun loader(classes: Map): ClassLoader = SampleLoader(classes) + + private class SampleLoader( + private val classes: Map, + ) : URLClassLoader(jars.map { it.toURI().toURL() }.toTypedArray(), ClassLoader.getPlatformClassLoader()) { + override fun findClass(name: String): Class<*> { + val bytes = classes[name.replace('.', '/')] ?: return super.findClass(name) + return defineClass(name, bytes, 0, bytes.size) + } + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifierTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifierTest.kt new file mode 100644 index 0000000000..e3c6ba8da2 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/BytecodeVerifierTest.kt @@ -0,0 +1,58 @@ +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.objectweb.asm.ClassWriter +import org.objectweb.asm.Label +import org.objectweb.asm.Opcodes + +/** The verifier helper itself must catch a bad type and a stale frame, or its "OK" means nothing. */ +class BytecodeVerifierTest { + private fun clazz(build: (ClassWriter) -> Unit): Map { + val w = ClassWriter(0) + w.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "p/Bad", null, "java/lang/Object", null) + build(w) + w.visitEnd() + return mapOf("p/Bad" to w.toByteArray()) + } + + @Test + fun `rejects an operand of the wrong type`() { + val classes = + clazz { w -> + w.visitMethod(Opcodes.ACC_STATIC, "m", "(Ljava/lang/Object;)I", null, null).apply { + visitCode() + visitVarInsn(Opcodes.ALOAD, 0) + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "length", "()I", false) + visitInsn(Opcodes.IRETURN) + visitMaxs(1, 1) + visitEnd() + } + } + val e = assertThrows(IllegalStateException::class.java) { BytecodeVerifier.verify(classes) } + assertThat(e.message).contains("p/Bad") + } + + @Test + fun `rejects a stack map frame that disagrees with the code`() { + val classes = + clazz { w -> + w.visitMethod(Opcodes.ACC_STATIC, "m", "(Ljava/lang/Object;)I", null, null).apply { + visitCode() + val l = Label() + visitVarInsn(Opcodes.ALOAD, 0) + visitJumpInsn(Opcodes.IFNULL, l) + visitLabel(l) + // the frame claims a String where the parameter is an Object + visitFrame(Opcodes.F_NEW, 1, arrayOf("java/lang/String"), 0, arrayOf()) + visitInsn(Opcodes.ICONST_0) + visitInsn(Opcodes.IRETURN) + visitMaxs(1, 1) + visitEnd() + } + } + val e = assertThrows(IllegalStateException::class.java) { BytecodeVerifier.verify(classes) } + assertThat(e.message).contains("p/Bad") + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt new file mode 100644 index 0000000000..0661826724 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt @@ -0,0 +1,349 @@ +@file:Suppress("ktlint:standard:max-line-length") + +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.utils.FileProvider +import org.junit.jupiter.api.Test +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassWriter +import org.objectweb.asm.Opcodes +import org.objectweb.asm.Type +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.FieldInsnNode +import org.objectweb.asm.tree.MethodInsnNode +import org.objectweb.asm.tree.MethodNode + +class SqliteRewriteResolutionTest { + private val helperSource = + FileProvider + .projectRoot() + .resolve("subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java") + .toFile() + + private class Ref( + val owner: String, + val name: String, + val desc: String, + val field: Boolean, + val isStatic: Boolean, + ) { + override fun toString() = "$owner.$name$desc" + } + + private fun ClassIndex.resolve( + ref: Ref, + caller: String? = null, + protectedOk: Boolean = false, + ) = resolve(ref.owner, ref.name, ref.desc, ref.field, ref.isStatic, caller, protectedOk) + + private fun refsOf(n: ClassNode): List = + n.methods.flatMap { m -> + m.instructions.mapNotNull { insn -> + when (insn) { + is MethodInsnNode -> { + Ref(insn.owner, insn.name, insn.desc, false, insn.opcode == Opcodes.INVOKESTATIC) + } + + is FieldInsnNode -> { + Ref( + insn.owner, + insn.name, + insn.desc, + true, + insn.opcode == Opcodes.GETSTATIC || insn.opcode == Opcodes.PUTSTATIC, + ) + } + + else -> { + null + } + } + } + } + + @Test + fun `the transformed helper only references what requery, android and androidx core define`() { + val classes = + Compiler.compile( + listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText())), + listOf(TestJars.androidJar, TestJars.androidxCoreJar), + ) + val index = ClassIndex(listOf(TestJars.requeryJar, TestJars.androidJar, TestJars.androidxCoreJar)) + val unresolved = mutableListOf() + var checked = 0 + for ((name, bytes) in classes) { + val n = node(SqliteRewriter.rewrite(bytes)) + assertThat(n.name).isEqualTo(name) + for (ref in refsOf(n)) { + if (ref.owner in classes.keys) continue + checked++ + if (index.resolve(ref, caller = n.name) == null) { + unresolved += ref.toString() + } + assertThat( + ref.owner, + ).doesNotMatch("android/database/sqlite/SQLite(Database|Open|Cursor|Query|Statement|Program|Closable).*") + } + } + assertThat(checked).isGreaterThan(10) + assertThat(unresolved).isEmpty() + } + + @Test + fun `every public or protected member of the 10 renamed android classes, inherited ones included, resolves in requery or fails the build`() { + val android = TestJars.androidJar + val index = ClassIndex(listOf(TestJars.requeryJar, TestJars.androidJar, TestJars.androidxCoreJar)) + val helper = + Compiler.compile( + listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText())), + listOf(android, TestJars.androidxCoreJar), + ) + helper.values.forEach { index.addClass(SqliteRewriter.rewrite(it)) } + + val unresolved = mutableListOf() + val failed = mutableListOf() + var total = 0 + var inheritedTotal = 0 + java.util.zip.ZipFile(android).use { zip -> + fun load(name: String) = + zip.getEntry("$name.class")?.let { e -> + ClassNode().also { ClassReader(zip.getInputStream(e)).accept(it, ClassReader.SKIP_CODE) } + } + + /** Android classes the class extends or implements and that stay android's: their members are inherited. */ + fun inheritedFrom(cls: ClassNode): List { + val result = mutableListOf() + val pending = ArrayDeque(listOfNotNull(cls.superName) + cls.interfaces) + val seen = HashSet() + while (pending.isNotEmpty()) { + val n = pending.removeFirst() + if (!seen.add(n) || n in SqliteRewriteRules.RENAMES) continue + val c = load(n) ?: continue + result += c + c.superName?.let(pending::add) + pending.addAll(c.interfaces) + } + return result + } + for (cls in SqliteRewriteRules.SQLITE_CLASSES) { + val owner = load(cls)!! + val isInterface = owner.access and Opcodes.ACC_INTERFACE != 0 + val visible = Opcodes.ACC_PUBLIC or Opcodes.ACC_PROTECTED + // the member through its declaring class and through every renamed subclass; inherited ones through the class + val callOwners = listOf(cls) + SqliteRewriteRules.RENAMED_SUPERS.filterValues { cls in it }.keys + val declarers = listOf(owner to callOwners) + inheritedFrom(owner).map { it to listOf(cls) } + for ((declarer, owners) in declarers) { + val inherited = declarer !== owner + // constants are copied into callers by javac, so no field access to them exists + val fields = declarer.fields.filter { it.access and visible != 0 && it.value == null } + val methods = declarer.methods.filter { it.access and visible != 0 && !(inherited && it.name == "") } + val members = + fields.map { Triple(true, it.name, it.desc) to it.access } + + methods.map { Triple(false, it.name, it.desc) to it.access } + for ((member, memberAccess) in members) { + val (field, name, desc) = member + for (callOwner in owners) { + if (callOwner != cls && name == "") continue + total++ + if (inherited) inheritedTotal++ + val synthetic = synthesize(declarer, callOwner, isInterface, field, name, desc, memberAccess) + val label = "${cls.substringAfterLast('/')}.$name:$desc" + val out = + try { + node(SqliteRewriter.rewrite(synthetic)) + } catch (e: SqliteRewriteException) { + failed += label + continue + } + val calls = refsOf(out).filter { it.owner != "p/Probe" } + // the probe makes exactly one member reference, plus a signal conversion when inserted + val main = calls.first { it.name == name } + if (index.resolve(main, protectedOk = memberAccess and Opcodes.ACC_PROTECTED != 0) == null) { + unresolved += "$label via ${callOwner.substringAfterLast('/')}" + } + } + } + } + } + } + assertThat(inheritedTotal).isGreaterThan(100) + println("members checked: $total, fail rule: ${failed.size}") + assertThat(unresolved).isEmpty() + // everything the rule table lists as missing must be hit, and nothing else may fail + val expected = + SqliteRewriteRules.MISSING_MEMBERS.flatMap { (key, descs) -> + val prefix = key.substringBeforeLast('.').substringAfterLast('/') + "." + key.substringAfterLast('.') + ":" + descs.map { prefix + it } + } + val unexpected = + failed.filterNot { f -> + expected.contains(f) || expected.any { it.endsWith(":") && f.startsWith(it) } || + f.contains("OpenParams") || f.contains("android/database/CursorWindow") + } + assertThat(unexpected).isEmpty() + } + + @Test + fun `every other platform member that mentions a renamed class is redirected to a target that resolves or fails the build`() { + val index = ClassIndex(listOf(TestJars.requeryJar, TestJars.androidJar, TestJars.androidxCoreJar)) + val helper = + Compiler.compile( + listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText())), + listOf(TestJars.androidJar, TestJars.androidxCoreJar), + ) + helper.values.forEach { index.addClass(SqliteRewriter.rewrite(it)) } + val renamedTokens = SqliteRewriteRules.RENAMED_DESCRIPTOR_TOKENS + val unresolved = mutableListOf() + var probed = 0 + var redirected = 0 + java.util.zip.ZipFile(TestJars.androidJar).use { zip -> + for (entry in zip.entries()) { + if (!entry.name.startsWith("android/") || !entry.name.endsWith(".class")) continue + val owner = ClassNode().also { ClassReader(zip.getInputStream(entry)).accept(it, ClassReader.SKIP_CODE) } + if (owner.name in SqliteRewriteRules.RENAMES) continue + val isInterface = owner.access and Opcodes.ACC_INTERFACE != 0 + for (method in owner.methods) { + if (method.access and (Opcodes.ACC_PUBLIC or Opcodes.ACC_PROTECTED) == 0) continue + if (renamedTokens.none { method.desc.contains(it) }) continue + probed++ + val probe = synthesize(owner, owner.name, isInterface, false, method.name, method.desc, method.access) + val out = + try { + node(SqliteRewriter.rewrite(probe)) + } catch (e: SqliteRewriteException) { + continue + } + val call = refsOf(out).first { it.name == method.name } + redirected++ + if (call.owner != "org/appdevforall/sqliterewrite/SqliteRewriteRuntime" || index.resolve(call) == null) { + unresolved += "${owner.name}.${method.name}${method.desc}" + } + } + } + } + println("platform members probed: $probed, redirected: $redirected") + assertThat(probed).isGreaterThan(10) + assertThat(redirected).isGreaterThan(8) + assertThat(unresolved).isEmpty() + } + + @Test + fun `the real androidx framework classes transform, verify, and resolve in requery`() { + val framework = TestJars.androidxSqliteFrameworkJar + val sources = mutableMapOf() + java.util.zip.ZipFile(framework).use { zip -> + for (entry in zip.entries()) { + if (entry.name.startsWith(SqliteRewriteRules.FRAMEWORK_PACKAGE_PREFIX) && entry.name.endsWith(".class")) { + sources[entry.name.removeSuffix(".class")] = zip.getInputStream(entry).readBytes() + } + } + } + // FrameworkSQLiteOpenHelper and its OpenHelper, FrameworkSQLiteDatabase, -Statement, -Program, and the helpers + assertThat(sources.keys).containsAtLeast( + "androidx/sqlite/db/framework/FrameworkSQLiteOpenHelper", + "androidx/sqlite/db/framework/FrameworkSQLiteOpenHelper\$OpenHelper", + "androidx/sqlite/db/framework/FrameworkSQLiteDatabase", + "androidx/sqlite/db/framework/FrameworkSQLiteStatement", + "androidx/sqlite/db/framework/FrameworkSQLiteProgram", + "androidx/sqlite/db/framework/FrameworkSQLiteOpenHelperFactory", + ) + + val before = ClassIndex(listOf(TestJars.androidJar, TestJars.androidxCoreJar, TestJars.androidxSqliteJar, framework)) + val hierarchy = ClassHierarchy { name -> if (before.knows(name)) before.superTypes(name) else null } + val transformed = sources.mapValues { SqliteRewriter.rewrite(it.value, hierarchy) } + assertThat(transformed.keys).isEqualTo(sources.keys) + + val helper = + Compiler.compile( + listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText())), + listOf(TestJars.androidJar, TestJars.androidxCoreJar), + ) + // the framework jar also holds androidx.sqlite.util.ProcessLock, which is not rewritten + val index = + ClassIndex(listOf(TestJars.requeryJar, TestJars.androidJar, TestJars.androidxCoreJar, TestJars.androidxSqliteJar, framework)) + helper.values.forEach { index.addClass(SqliteRewriter.rewrite(it)) } + transformed.values.forEach { index.addClass(it) } + + val unresolved = mutableListOf() + var requeryRefs = 0 + for ((name, bytes) in transformed) { + for (ref in refsOf(node(bytes))) { + if (ref.owner.startsWith("kotlin/") || ref.owner.startsWith("[")) continue + if (ref.owner.startsWith("io/requery/")) requeryRefs++ + if (index.resolve(ref, caller = name) == null) unresolved += "$name -> $ref" + } + } + assertThat(requeryRefs).isGreaterThan(30) + assertThat(unresolved).isEmpty() + // requery has no execPerConnectionSQL of its own: the reference resolves to the interface's default, which throws + assertThat( + index.resolve( + "io/requery/android/database/sqlite/SQLiteDatabase", + "execPerConnectionSQL", + "(Ljava/lang/String;[Ljava/lang/Object;)V", + false, + ), + ).isEqualTo("androidx/sqlite/db/SupportSQLiteDatabase") + // every android.database.sqlite reference is gone, so nothing in the package links to the platform's SQLite + for (bytes in transformed.values) { + for (ref in refsOf(node(bytes))) { + assertThat( + ref.owner, + ).doesNotMatch("android/database/sqlite/SQLite(Database|Open|Cursor|Query|Statement|Program|Closable).*") + } + } + BytecodeVerifier.verify(transformed) + } + + /** A class `p/Probe` with one method that performs one member reference with a valid stack. */ + private fun synthesize( + owner: ClassNode, + callOwner: String, + isInterface: Boolean, + field: Boolean, + name: String, + desc: String, + access: Int, + ): ByteArray { + val cn = ClassNode() + cn.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "p/Probe", null, "java/lang/Object", null) + val m = MethodNode(Opcodes.ASM9, Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC, "probe", "()V", null, null) + val isStatic = access and Opcodes.ACC_STATIC != 0 + if (field) { + m.visitFieldInsn(if (isStatic) Opcodes.GETSTATIC else Opcodes.GETFIELD, callOwner, name, desc) + m.visitInsn(if (Type.getType(desc).size == 2) Opcodes.POP2 else Opcodes.POP) + } else { + if (!isStatic) m.visitInsn(Opcodes.ACONST_NULL) + for (arg in Type.getArgumentTypes(desc)) { + m.visitInsn( + when (arg.sort) { + Type.LONG -> Opcodes.LCONST_0 + Type.FLOAT -> Opcodes.FCONST_0 + Type.DOUBLE -> Opcodes.DCONST_0 + Type.OBJECT, Type.ARRAY -> Opcodes.ACONST_NULL + else -> Opcodes.ICONST_0 + }, + ) + } + val opcode = + when { + name == "" -> Opcodes.INVOKESPECIAL + isStatic -> Opcodes.INVOKESTATIC + isInterface -> Opcodes.INVOKEINTERFACE + else -> Opcodes.INVOKEVIRTUAL + } + m.visitMethodInsn(opcode, callOwner, name, desc, isInterface) + when (Type.getReturnType(desc).size) { + 2 -> m.visitInsn(Opcodes.POP2) + 1 -> m.visitInsn(Opcodes.POP) + } + } + m.visitInsn(Opcodes.RETURN) + m.visitMaxs(8, 0) + cn.methods.add(m) + val w = ClassWriter(0) + cn.accept(w) + return w.toByteArray() + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt new file mode 100644 index 0000000000..e8e892d959 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt @@ -0,0 +1,48 @@ +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.utils.FileProvider +import org.junit.jupiter.api.Test + +/** The pure functions of the runtime helper, run on the JVM from its bytecode compiled against android.jar. */ +class SqliteRewriteRuntimeTest { + private val runtime: Class<*> by lazy { + val source = + FileProvider + .projectRoot() + .resolve("subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java") + .toFile() + .readText() + val classes = + Compiler.compile( + listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", source)), + listOf(TestJars.androidJar, TestJars.androidxCoreJar), + ) + BytecodeVerifier.loader(classes).loadClass("org.appdevforall.sqliterewrite.SqliteRewriteRuntime") + } + + private fun translate(flags: Int) = runtime.getMethod("translateOpenFlags", Int::class.javaPrimitiveType).invoke(null, flags) as Int + + private val readOnly = 1 + private val createIfNecessary = 0x10000000 + private val wal = 0x20000000 + + @Test + fun `read-write and create keep requery's values`() { + assertThat(translate(0)).isEqualTo(2) + assertThat(translate(createIfNecessary)).isEqualTo(6) + assertThat(translate(createIfNecessary or wal)).isEqualTo(6 or wal) + } + + @Test + fun `read-only never gets the create bit, which SQLite rejects`() { + assertThat(translate(readOnly)).isEqualTo(1) + assertThat(translate(readOnly or createIfNecessary)).isEqualTo(1) + } + + @Test + fun `other Android bits are dropped`() { + assertThat(translate(16)).isEqualTo(2) + assertThat(translate(8 or createIfNecessary)).isEqualTo(6) + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt new file mode 100644 index 0000000000..36bfbf40fd --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -0,0 +1,1299 @@ +@file:Suppress("ktlint:standard:max-line-length") + +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.objectweb.asm.ClassReader +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.MethodInsnNode +import org.objectweb.asm.tree.MethodNode +import org.objectweb.asm.tree.TypeInsnNode + +private const val R = "io/requery/android/database/sqlite/" +private const val A = "android/database/sqlite/" +private const val HELPER = "org/appdevforall/sqliterewrite/SqliteRewriteRuntime" + +internal fun node(bytes: ByteArray) = ClassNode().also { ClassReader(bytes).accept(it, 0) } + +internal fun ClassNode.method(name: String): MethodNode = methods.first { it.name == name } + +internal fun MethodNode.calls(): List = instructions.filterIsInstance() + +internal fun MethodNode.call(name: String): MethodInsnNode = calls().first { it.name == name } + +internal fun src( + name: String, + body: String, +) = JavaSource(name, body) + +class SqliteRewriterTest { + private val hierarchy = + ClassHierarchy { name -> + when (name) { + "p/MyActivity" -> { + listOf( + "android/app/Activity", + "android/content/ContextWrapper", + "android/content/Context", + "java/lang/Object", + ) + } + + "p/MyBuilder" -> { + listOf(A + "SQLiteQueryBuilder", "java/lang/Object") + } + + else -> { + null + } + } + } + + private fun transform( + vararg sources: JavaSource, + extraClasspath: List = emptyList(), + ): Map = + BytecodeVerifier.rewriteAndVerify(Compiler.compile(sources.toList(), listOf(TestJars.androidJar) + extraClasspath)) + + @Test + fun `renames the shared classes, the error handlers and overrides, and leaves the kept ones`() { + val out = + transform( + src( + "p.Rename", + """ + package p; + import android.content.Context; + import android.database.*; + import android.database.sqlite.*; + public class Rename extends SQLiteOpenHelper { + public Rename(Context c) { super(c, "n", null, 1, new DefaultDatabaseErrorHandler()); } + @Override public void onCreate(SQLiteDatabase db) { db.execSQL("x"); } + @Override public void onUpgrade(SQLiteDatabase db, int a, int b) {} + public void use(SQLiteDatabase db, CursorWindow w, Cursor c, SQLiteDatabase.CursorFactory f, + SQLiteTransactionListener l) throws SQLiteException { + db.beginTransactionWithListener(l); + SQLiteStatement s = db.compileStatement("y"); + SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); + } + } + """, + ), + )["p/Rename"]!! + val n = node(out) + assertThat(n.superName).isEqualTo(R + "SQLiteOpenHelper") + assertThat(n.methods.first { it.name == "onCreate" }.desc).isEqualTo("(L${R}SQLiteDatabase;)V") + val init = n.method("") + assertThat(init.calls().first { it.name == "" && it.owner == R + "SQLiteOpenHelper" }.desc) + .isEqualTo( + "(Landroid/content/Context;Ljava/lang/String;L${R}SQLiteDatabase\$CursorFactory;IL${"io/requery/android/database/DatabaseErrorHandler"};)V", + ) + assertThat(init.instructions.filterIsInstance().map { it.desc }) + .contains("io/requery/android/database/DefaultDatabaseErrorHandler") + val use = n.method("use") + assertThat(use.desc).isEqualTo( + "(L${R}SQLiteDatabase;Landroid/database/CursorWindow;Landroid/database/Cursor;L${R}SQLiteDatabase\$CursorFactory;L${A}SQLiteTransactionListener;)V", + ) + assertThat(use.exceptions).containsExactly(A + "SQLiteException") + assertThat(use.call("beginTransactionWithListener").desc).isEqualTo("(L${A}SQLiteTransactionListener;)V") + assertThat(use.call("compileStatement").desc).isEqualTo("(Ljava/lang/String;)L${R}SQLiteStatement;") + assertThat(use.instructions.filterIsInstance().map { it.desc }).contains(R + "SQLiteQueryBuilder") + } + + @Test + fun `rewrites String array to Object array in calls and in the cursor driver override`() { + val out = + transform( + src( + "p.Args", + """ + package p; + import android.database.Cursor; + import android.database.sqlite.*; + public class Args implements SQLiteCursorDriver { + public Cursor query(SQLiteDatabase.CursorFactory f, String[] args) { return null; } + public void cursorDeactivated() {} + public void cursorRequeried(Cursor c) {} + public void cursorClosed() {} + public void setBindArguments(String[] a) {} + void calls(SQLiteDatabase db, SQLiteDatabase.CursorFactory f, SQLiteCursorDriver d, Args me, String[] a) { + db.rawQuery("s", a); + db.query("t", a, "w", a, null, null, null); + db.query("t", a, "w", a, null, null, null, "1"); + db.query(true, "t", a, "w", a, null, null, null, "1"); + db.rawQueryWithFactory(f, "s", a, "t"); + db.queryWithFactory(f, true, "t", a, "w", a, null, null, null, "1"); + d.query(f, a); + me.query(f, a); + } + } + """, + ), + )["p/Args"]!! + val n = node(out) + val decl = n.methods.first { it.name == "query" } + assertThat(decl.desc).isEqualTo("(L${R}SQLiteDatabase\$CursorFactory;[Ljava/lang/Object;)Landroid/database/Cursor;") + val calls = n.method("calls").calls() + assertThat(calls.first { it.name == "rawQuery" }.desc) + .isEqualTo("(Ljava/lang/String;[Ljava/lang/Object;)Landroid/database/Cursor;") + assertThat(calls.filter { it.name == "query" && it.owner == R + "SQLiteDatabase" }.map { it.desc }).containsExactly( + "(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", + "(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", + "(ZLjava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", + ) + assertThat(calls.first { it.name == "rawQueryWithFactory" }.desc).isEqualTo( + "(L${R}SQLiteDatabase\$CursorFactory;Ljava/lang/String;[Ljava/lang/Object;Ljava/lang/String;)Landroid/database/Cursor;", + ) + assertThat( + calls + .first { + it.name == "queryWithFactory" + }.desc, + ).contains("Ljava/lang/String;[Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)") + // the interface call, and the call on the implementing class itself + assertThat(calls.filter { it.name == "query" && it.owner != R + "SQLiteDatabase" }.map { it.desc }.toSet()) + .containsExactly("(L${R}SQLiteDatabase\$CursorFactory;[Ljava/lang/Object;)Landroid/database/Cursor;") + } + + @Test + fun `converts the cancellation signal right before the call`() { + val out = + transform( + src( + "p.Signal", + """ + package p; + import android.database.sqlite.*; + import android.os.CancellationSignal; + public class Signal { + void go(SQLiteDatabase db, SQLiteQueryBuilder qb, SQLiteDatabase.CursorFactory f, CancellationSignal s, String[] a) { + db.rawQuery("x", a, s); + db.validateSql("x", s); + qb.query(db, a, "w", a, null, null, null, "1", s); + db.rawQueryWithFactory(f, "x", a, "t", s); + } + } + """, + ), + )["p/Signal"]!! + val go = node(out).method("go") + val insns = go.instructions.toArray().toList() + for (name in listOf("rawQuery", "validateSql", "query", "rawQueryWithFactory")) { + val call = go.call(name) + assertThat(call.desc).contains("Landroidx/core/os/CancellationSignal;)") + val before = insns[insns.indexOf(call) - 1] as MethodInsnNode + assertThat(before.owner).isEqualTo(HELPER) + assertThat(before.name).isEqualTo("toCancellationSignal") + assertThat(before.desc).isEqualTo("(Landroid/os/CancellationSignal;)Landroidx/core/os/CancellationSignal;") + } + assertThat(go.call("rawQuery").desc).isEqualTo( + "(Ljava/lang/String;[Ljava/lang/Object;Landroidx/core/os/CancellationSignal;)Landroid/database/Cursor;", + ) + } + + @Test + fun `redirects open flags and the context calls (also on subclasses), and leaves androidx's factory alone`() { + val out = + transform( + src( + "androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory", + "package androidx.sqlite.db.framework; public class FrameworkSQLiteOpenHelperFactory { public FrameworkSQLiteOpenHelperFactory() {} }", + ), + src( + "p.MyActivity", + "package p; public class MyActivity extends android.app.Activity {" + + " void own(android.database.sqlite.SQLiteDatabase.CursorFactory f) {" + + " this.openOrCreateDatabase(\"n\", 0, f); deleteDatabase(\"n\"); } }", + ), + src( + "p.Redirect", + """ + package p; + import android.content.Context; + import android.database.DatabaseErrorHandler; + import android.database.sqlite.*; + public class Redirect { + Object go(Context c, SQLiteDatabase.CursorFactory f, DatabaseErrorHandler h, MyActivity a, Other o) { + SQLiteDatabase.openDatabase("p", f, SQLiteDatabase.OPEN_READONLY); + SQLiteDatabase.openDatabase("p", f, SQLiteDatabase.CREATE_IF_NECESSARY, h); + SQLiteDatabase.openOrCreateDatabase("p", f); + c.openOrCreateDatabase("n", 0, f); + c.openOrCreateDatabase("n", 0, f, h); + c.deleteDatabase("n"); + a.deleteDatabase("n"); + o.deleteDatabase("n"); + return new androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory(); + } + } + """, + ), + src("p.Other", "package p; public class Other { public boolean deleteDatabase(String n) { return true; } }"), + ) + val go = node(out["p/Redirect"]!!).method("go") + + fun redirected(name: String) = go.calls().filter { it.owner == HELPER && it.name == name } + + assertThat(redirected("openDatabase").map { it.desc }).containsExactly( + "(Ljava/lang/String;L${R}SQLiteDatabase\$CursorFactory;I)L${R}SQLiteDatabase;", + "(Ljava/lang/String;L${R}SQLiteDatabase\$CursorFactory;IL${"io/requery/android/database/DatabaseErrorHandler"};)L${R}SQLiteDatabase;", + ) + assertThat(redirected("openOrCreateDatabase").map { it.desc }).containsExactly( + "(Landroid/content/Context;Ljava/lang/String;IL${R}SQLiteDatabase\$CursorFactory;)L${R}SQLiteDatabase;", + "(Landroid/content/Context;Ljava/lang/String;IL${R}SQLiteDatabase\$CursorFactory;Lio/requery/android/database/DatabaseErrorHandler;)L${R}SQLiteDatabase;", + ) + // Context, the Activity subclass; not the unrelated class with the same method + assertThat(redirected("deleteDatabase")).hasSize(2) + assertThat(go.calls().any { it.owner == "p/Other" && it.name == "deleteDatabase" }).isTrue() + // without flags: stays a plain, renamed call + assertThat(go.calls().any { it.owner == R + "SQLiteDatabase" && it.name == "openOrCreateDatabase" }).isTrue() + // requery's factory ignores noBackupDirectory, allowDataLossOnRecovery and the framework's cross-process + // lock, so Room and WorkManager keep androidx's, which runs on requery through the renamed classes + assertThat(go.instructions.filterIsInstance().map { it.desc }) + .containsExactly("androidx/sqlite/db/framework/FrameworkSQLiteOpenHelperFactory") + assertThat( + go.calls().first { it.name == "" }.owner, + ).isEqualTo("androidx/sqlite/db/framework/FrameworkSQLiteOpenHelperFactory") + + val own = node(out["p/MyActivity"]!!).method("own") + assertThat(own.calls().map { it.owner + "." + it.name }).containsExactly("$HELPER.openOrCreateDatabase", "$HELPER.deleteDatabase") + } + + @Test + fun `branchy and looping samples of every rule kind verify, frames included`() { + val out = + transform( + src( + "p.Branchy", + """ + package p; + import android.content.Context; + import android.database.Cursor; + import android.database.DatabaseErrorHandler; + import android.database.sqlite.*; + import android.os.CancellationSignal; + public class Branchy implements SQLiteCursorDriver { + public Cursor query(SQLiteDatabase.CursorFactory f, String[] args) { + // four locals at once make javac write a full frame, which names the parameter's type + int n = 0, a = 1, b = 2, c = 3; + for (int i = 0; i < 3; i++) { + if (f == null) { + n++; + } else if (args == null) { + n--; + } + } + if (n + a + b + c > 1) { + return null; + } + return null; + } + public void cursorDeactivated() {} + public void cursorRequeried(Cursor c) {} + public void cursorClosed() {} + public void setBindArguments(String[] a) {} + + Cursor descriptors(SQLiteDatabase db, SQLiteDatabase.CursorFactory f, String[] a, boolean b, CancellationSignal s) { + Cursor c = null; + for (int i = 0; i < 3; i++) { + if (b) { + c = db.rawQuery("x", a); + } else if (s != null) { + c = db.rawQuery("y", a, s); + } else { + c = db.query("t", a, "w", a, null, null, null, "1"); + } + if (c != null && i == 1) { + c = db.rawQueryWithFactory(f, "z", a, "t"); + } + } + return c; + } + + Object redirects(Context ctx, SQLiteDatabase.CursorFactory f, DatabaseErrorHandler h, boolean b, String name) { + SQLiteDatabase db; + if (b) { + db = SQLiteDatabase.openDatabase(name, f, SQLiteDatabase.OPEN_READONLY); + } else { + db = ctx.openOrCreateDatabase(name, 0, f, h); + } + for (int i = 0; i < 2; i++) { + if (ctx.deleteDatabase(name + i)) { + db = SQLiteDatabase.openDatabase(name, f, SQLiteDatabase.CREATE_IF_NECESSARY, h); + } + } + return db; + } + + Object joins(SQLiteDatabase db, boolean b, SQLiteQueryBuilder qb) { + SQLiteClosable c = b ? db : db.compileStatement("x"); + SQLiteProgram p = b ? db.compileStatement("y") : null; + while (c != null && b) { + c.close(); + c = p; + b = false; + } + return qb != null ? c : p; + } + } + """, + ), + ) + assertThat(out["p/Branchy"]).isNotNull() + } + + @Test + fun `the androidx factory class is rewritten like the rest of its package, not excluded`() { + val name = "androidx/sqlite/db/framework/FrameworkSQLiteOpenHelperFactory" + val out = + transform( + src( + "androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory", + """ + package androidx.sqlite.db.framework; + import android.content.Context; + import android.database.sqlite.SQLiteOpenHelper; + public class FrameworkSQLiteOpenHelperFactory { + public SQLiteOpenHelper create(Context c, String n) { return null; } + } + """, + ), + ) + val n = node(out[name]!!) + assertThat(n.name).isEqualTo(name) + assertThat( + n.method("create").desc, + ).isEqualTo("(Landroid/content/Context;Ljava/lang/String;)L${R}SQLiteOpenHelper;") + assertThat(RewritePolicy.isExcluded(name)).isFalse() + } + + @Test + fun `fails with class, method and line for members requery lacks, collecting all of them`() { + val sources = + src( + "p.Bad", + """ + package p; + import android.database.sqlite.*; + public class Bad { + void one(SQLiteDatabase db) { + db.execPerConnectionSQL("x", null); + } + void two(SQLiteDatabase db, SQLiteDatabase.OpenParams params) { + db.setCustomScalarFunction("f", s -> s); + SQLiteDatabase.openDatabase(new java.io.File("f"), params); + new SQLiteDatabase.OpenParams.Builder().build(); + } + void three(MyBuilder b, SQLiteQueryBuilder q) { + b.isDistinct(); + q.setStrictGrammar(true); + } + } + """, + ) + val classes = + Compiler.compile( + listOf( + sources, + src("p.MyBuilder", "package p; public class MyBuilder extends android.database.sqlite.SQLiteQueryBuilder {}"), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Bad"]!!, hierarchy) } + val message = e.message!! + assertThat(message).contains("p.Bad") + assertThat(message).contains("one(Landroid/database/sqlite/SQLiteDatabase;)V (line 6)") + assertThat(message).contains("SQLiteDatabase.execPerConnectionSQL") + assertThat(message).contains("two(") + assertThat(message).contains("setCustomScalarFunction") + assertThat(message).contains("OpenParams") + assertThat(message).contains("(line 9)") + assertThat(message).contains("(line 10)") + assertThat(message).contains("(line 11)") + // a subclass of SQLiteQueryBuilder is resolved through the hierarchy + assertThat(message).contains("SQLiteQueryBuilder.isDistinct") + assertThat(message).contains("SQLiteQueryBuilder.setStrictGrammar") + } + + @Test + fun `a missing member is found through every renamed ancestor of the owner`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Ancestors", + """ + package p; + import android.database.sqlite.*; + public class Ancestors { + int program(SQLiteStatement stmt, SQLiteQuery query) { return stmt.getUniqueId() + query.getUniqueId(); } + void closable(SQLiteDatabase db) { db.releaseReferenceFromContainer(); } + void subclass(MyBuilder b) { b.isStrict(); b.close(); } + } + """, + ), + src( + "p.MyBuilder", + "package p; public class MyBuilder extends android.database.sqlite.SQLiteQueryBuilder { void close() {} }", + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Ancestors"]!!, hierarchy) } + val message = e.message!! + assertThat(message).contains("SQLiteProgram.getUniqueId") + assertThat(message).contains("SQLiteClosable.releaseReferenceFromContainer") + assertThat(message).contains("SQLiteQueryBuilder.isStrict") + assertThat(message).doesNotContain("close") + } + + @Test + fun `hierarchy lookups are made once per owner and not for classes that cannot be SQLite subclasses`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Chatty", + """ + package p; + import android.database.sqlite.*; + public class Chatty { + int go(String s, StringBuilder sb, java.util.List l, android.widget.TextView tv, Mine a, Mine b, SQLiteStatement st) { + sb.append(s.length()).append(s.trim()).append(l.size()); + tv.setText(s); tv.setText(s); + a.run(); a.run(); b.run(); + return st.getUniqueId() > 0 ? 1 : 0; + } + } + """, + ), + src("p.Mine", "package p; public class Mine { void run() {} }"), + ), + ) + val asked = mutableListOf() + val counting = + ClassHierarchy { name -> + asked += name + null + } + try { + SqliteRewriter.rewrite(classes["p/Chatty"]!!, counting) + } catch (e: SqliteRewriteException) { + // getUniqueId is reported, which is not what this test is about + } + assertThat(asked.filter { it.startsWith("java/") || it.startsWith("android/") }).isEmpty() + assertThat(asked.groupingBy { it }.eachCount().filterValues { it > 1 }).isEmpty() + // ordinary calls on app classes need no lookup: no rule can match their name or descriptor + assertThat(asked).doesNotContain("p/Mine") + } + + @Test + fun `a call whose name a rule lists, or whose descriptor has a CursorWindow, still looks the owner up`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Named", + """ + package p; + public class Named { + void go(Mine a, Other b, Third c, android.database.CursorWindow w) { + a.getUniqueId(); + a.getUniqueId(); + b.fetch(w); + c.ordinary(); + } + } + """, + ), + src("p.Mine", "package p; public class Mine { int getUniqueId() { return 0; } }"), + src("p.Other", "package p; public class Other { void fetch(android.database.CursorWindow w) {} }"), + src("p.Third", "package p; public class Third { void ordinary() {} }"), + ), + ) + val asked = mutableListOf() + SqliteRewriter.rewrite( + classes["p/Named"]!!, + ClassHierarchy { name -> + asked += name + null + }, + ) + assertThat(asked).containsExactly("p/Mine", "p/Other") + } + + @Test + fun `field accesses and constructors of app classes trigger no hierarchy lookup`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Fields", + """ + package p; + public class Fields { + int go(Holder h) { h.count++; return h.count + new Holder().count; } + } + """, + ), + src("p.Holder", "package p; public class Holder { int count; }"), + ), + ) + val asked = mutableListOf() + SqliteRewriter.rewrite( + classes["p/Fields"]!!, + ClassHierarchy { name -> + asked += name + null + }, + ) + assertThat(asked).isEmpty() + } + + @Test + fun `DatabaseUtils helpers that take SQLite types are redirected to the runtime`() { + val out = + transform( + src( + "p.Utils", + """ + package p; + import android.database.DatabaseUtils; + import android.database.sqlite.*; + public class Utils { + long go(SQLiteDatabase db, SQLiteStatement st, String[] a, boolean b) { + long n = 0; + if (b) { + n += DatabaseUtils.queryNumEntries(db, "t"); + n += DatabaseUtils.queryNumEntries(db, "t", "x"); + } else { + n += DatabaseUtils.queryNumEntries(db, "t", "x", a); + } + for (int i = 0; i < 2; i++) { + n += DatabaseUtils.longForQuery(db, "q", a) + DatabaseUtils.longForQuery(st, a); + n += DatabaseUtils.stringForQuery(db, "q", a).length() + DatabaseUtils.stringForQuery(st, a).length(); + } + return n; + } + } + """, + ), + )["p/Utils"]!! + val calls = node(out).method("go").calls() + assertThat(calls.filter { it.owner == "android/database/DatabaseUtils" }).isEmpty() + val redirected = calls.filter { it.owner == HELPER } + assertThat(redirected.map { it.name }.groupingBy { it }.eachCount()) + .containsExactly("queryNumEntries", 3, "longForQuery", 2, "stringForQuery", 2) + assertThat(redirected.map { it.opcode }.toSet()).containsExactly(org.objectweb.asm.Opcodes.INVOKESTATIC) + assertThat(redirected.first { it.name == "longForQuery" && it.desc.contains("Statement") }.desc) + .isEqualTo("(L${R}SQLiteStatement;[Ljava/lang/String;)J") + assertThat(redirected.first { it.name == "queryNumEntries" && it.desc.contains("Ljava/lang/String;Ljava/lang/String;)") }.desc) + .isEqualTo("(L${R}SQLiteDatabase;Ljava/lang/String;Ljava/lang/String;)J") + } + + @Test + fun `platform methods with SQLite types that have no requery counterpart fail the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.BadUtils", + """ + package p; + import android.database.DatabaseUtils; + import android.database.sqlite.*; + public class BadUtils { + void one(SQLiteDatabase db, SQLiteStatement st, String[] a, SQLiteProgram p) throws Exception { + DatabaseUtils.blobFileDescriptorForQuery(db, "q", a); + DatabaseUtils.blobFileDescriptorForQuery(st, a); + DatabaseUtils.bindObjectToProgram(p, 1, "x"); + new DatabaseUtils.InsertHelper(db, "t"); + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/BadUtils"]!!, hierarchy) } + val message = e.message!! + assertThat(message).contains("p.BadUtils") + assertThat(message).contains("DatabaseUtils.blobFileDescriptorForQuery") + assertThat(message).contains("DatabaseUtils.bindObjectToProgram") + assertThat(message).contains("DatabaseUtils\$InsertHelper.") + for (line in 7..10) assertThat(message).contains("(line $line)") + } + + @Test + fun `Context database calls that cannot be redirected fail the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.SuperCall", + """ + package p; + public class SuperCall extends android.app.Activity { + void go(android.database.sqlite.SQLiteDatabase.CursorFactory f) { + super.openOrCreateDatabase("n", 0, f); + } + boolean del() { + return super.deleteDatabase("n"); + } + } + """, + ), + src( + "p.OverridesBoth", + """ + package p; + import android.database.sqlite.*; + public class OverridesBoth extends android.content.ContextWrapper { + public OverridesBoth() { super(null); } + @Override public SQLiteDatabase openOrCreateDatabase(String n, int m, SQLiteDatabase.CursorFactory f) { return null; } + @Override public boolean deleteDatabase(String n) { return true; } + } + """, + ), + src( + "p.Unknown", + """ + package p; + public class Unknown { + boolean go(q.Lib lib, android.database.sqlite.SQLiteDatabase.CursorFactory f) { + lib.openOrCreateDatabase("n", 0, f); + return lib.deleteDatabase("n"); + } + } + """, + ), + src( + "q.Lib", + """ + package q; + public class Lib { + public android.database.sqlite.SQLiteDatabase openOrCreateDatabase(String n, int m, android.database.sqlite.SQLiteDatabase.CursorFactory f) { return null; } + public boolean deleteDatabase(String n) { return true; } + } + """, + ), + ), + ) + + fun failure(name: String) = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes[name]!!, hierarchy) + }.message!! + failure("p/SuperCall").let { + assertThat(it).contains("go(") + assertThat(it).contains("del(") + assertThat(it).contains("super") + } + failure("p/OverridesBoth").let { + assertThat(it).contains("overrides Context.openOrCreateDatabase") + assertThat(it).contains("overrides Context.deleteDatabase") + } + failure("p/Unknown").let { + assertThat(it).contains("q/Lib") + assertThat(it).contains("(line 5)") + assertThat(it).contains("(line 6)") + } + } + + @Test + fun `method references get the same rules as calls, or fail asking for a lambda`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Refs", + """ + package p; + import android.content.Context; + import android.database.Cursor; + import android.database.sqlite.*; + public class Refs { + interface Open { SQLiteDatabase open(String n, int m, SQLiteDatabase.CursorFactory f); } + interface Opener { SQLiteDatabase open(String n, SQLiteDatabase.CursorFactory f, int flags); } + Object rawQuery(SQLiteDatabase db) { + java.util.function.BiFunction f = db::rawQuery; + return f; + } + Object delete(Context ctx) { + java.util.function.Predicate p = ctx::deleteDatabase; + return p; + } + Object open(Context ctx) { + Open o = ctx::openOrCreateDatabase; + return o; + } + Object staticOpen() { + Opener o = SQLiteDatabase::openDatabase; + return o; + } + Object missing(SQLiteDatabase db) { + Runnable r = db::releaseReferenceFromContainer; + return r; + } + } + """, + ), + ), + ) + val message = + assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Refs"]!!, hierarchy) }.message!! + for (method in listOf("rawQuery", "delete", "open", "staticOpen", "missing")) { + assertThat(message).contains("$method(") + } + assertThat(message).contains("method reference") + assertThat(message).contains("lambda") + } + + @Test + fun `method references and lambdas that need no rule are left alone`() { + val out = + transform( + src( + "p.FineRefs", + """ + package p; + import android.database.Cursor; + import android.database.sqlite.*; + public class FineRefs { + Object go(SQLiteDatabase db, java.util.List l) { + Runnable begin = db::beginTransaction; + java.util.function.Function len = String::length; + java.util.function.Supplier s = () -> db.compileStatement("x"); + java.util.function.Function q = a -> db.rawQuery(a, null); + l.forEach(x -> db.execSQL(x)); + return new Object[] {begin, len, s, q}; + } + } + """, + ), + )["p/FineRefs"]!! + val n = node(out) + assertThat( + n.methods + .flatMap { it.calls() } + .filter { it.name == "rawQuery" } + .map { it.desc }, + ).containsExactly("(Ljava/lang/String;[Ljava/lang/Object;)Landroid/database/Cursor;") + } + + @Test + fun `fails for a cast of an SQLite cursor to AbstractWindowedCursor but not for other values`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Casts", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Casts { + Object viaLocal(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + return (AbstractWindowedCursor) c; + } + Object viaSqliteCursor(SQLiteCursor c) { + Object o = c; + return (AbstractWindowedCursor) o; + } + } + """, + ), + src( + "p.Fine", + """ + package p; + import android.database.*; + public class Fine { + Object other(Cursor fromContentProvider) { + return (AbstractWindowedCursor) fromContentProvider; + } + boolean guarded(Cursor c) { + return c instanceof AbstractWindowedCursor; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Casts"]!!, hierarchy) } + assertThat(e.message).contains("viaLocal") + assertThat(e.message).contains("viaSqliteCursor") + assertThat(e.message).contains("AbstractWindowedCursor") + SqliteRewriter.rewrite(classes["p/Fine"]!!, hierarchy) + } + + @Test + fun `taint of an SQLite cursor survives a join point`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Joins", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Joins { + Object assignedOnOneBranch(Cursor other, SQLiteDatabase db, boolean b) { + Cursor c = other; + if (b) { + c = db.rawQuery("x", null); + } + return (AbstractWindowedCursor) c; + } + Object assignedInElse(Cursor other, SQLiteDatabase db, boolean b) { + Cursor c; + if (b) { + c = other; + } else { + c = db.rawQuery("x", null); + } + return (AbstractWindowedCursor) c; + } + Object assignedInLoop(Cursor other, SQLiteDatabase db, int n) { + Cursor c = other; + for (int i = 0; i < n; i++) { + c = db.rawQuery("x", null); + } + return (AbstractWindowedCursor) c; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Joins"]!!, hierarchy) } + assertThat(e.message).contains("assignedOnOneBranch") + assertThat(e.message).contains("assignedInElse") + assertThat(e.message).contains("assignedInLoop") + } + + @Test + fun `casts of an SQLite cursor to AbstractCursor and CrossProcessCursor fail too`() { + val classes = + Compiler.compile( + listOf( + src( + "p.MoreCasts", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class MoreCasts { + Object toAbstract(SQLiteDatabase db) { + return (AbstractCursor) db.rawQuery("x", null); + } + Object toCrossProcess(SQLiteCursor c) { + Object o = c; + return (CrossProcessCursor) o; + } + boolean guarded(SQLiteDatabase db) { + return db.rawQuery("x", null) instanceof CrossProcessCursor; + } + } + """, + ), + src( + "p.FineCasts", + """ + package p; + import android.database.*; + public class FineCasts { + Object other(Cursor fromContentProvider) { + return (AbstractCursor) fromContentProvider; + } + Object cross(Cursor fromContentProvider) { + return (CrossProcessCursor) fromContentProvider; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/MoreCasts"]!!, hierarchy) } + assertThat(e.message).contains("toAbstract") + assertThat(e.message).contains("android.database.AbstractCursor") + assertThat(e.message).contains("toCrossProcess") + assertThat(e.message).contains("android.database.CrossProcessCursor") + assertThat(e.message).doesNotContain("guarded") + SqliteRewriter.rewrite(classes["p/FineCasts"]!!, hierarchy) + } + + @Test + fun `a call through CursorWindow of a renamed class fails`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Window", + "package p; public class Window { Object go(android.database.sqlite.SQLiteCursor c) { return c.getWindow(); } }", + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Window"]!!, hierarchy) } + assertThat(e.message).contains("CursorWindow") + } + + @Test + fun `the helper package is renamed but neither redirected nor failed, and framework only skips the fail rule`() { + val classes = + Compiler.compile( + listOf( + src( + "org.appdevforall.sqliterewrite.SqliteRewriteRuntime", + """ + package org.appdevforall.sqliterewrite; + import android.database.sqlite.SQLiteDatabase; + public class SqliteRewriteRuntime { + public static SQLiteDatabase openDatabase(String p, SQLiteDatabase.CursorFactory f, int fl) { + return SQLiteDatabase.openDatabase(p, f, fl); + } + public static void bad(SQLiteDatabase db) { db.execPerConnectionSQL("x", null); } + } + """, + ), + src( + "androidx.sqlite.db.framework.FrameworkSQLiteDatabase", + """ + package androidx.sqlite.db.framework; + import android.database.sqlite.SQLiteDatabase; + public class FrameworkSQLiteDatabase { + void exec(SQLiteDatabase db, String[] a) { + db.execPerConnectionSQL("x", null); + db.rawQuery("x", a); + } + } + """, + ), + ), + ) + val helper = node(SqliteRewriter.rewrite(classes["org/appdevforall/sqliterewrite/SqliteRewriteRuntime"]!!, hierarchy)) + val inner = helper.method("openDatabase").call("openDatabase") + assertThat(inner.owner).isEqualTo(R + "SQLiteDatabase") + assertThat(inner.desc).isEqualTo("(Ljava/lang/String;L${R}SQLiteDatabase\$CursorFactory;I)L${R}SQLiteDatabase;") + + val framework = node(SqliteRewriter.rewrite(classes["androidx/sqlite/db/framework/FrameworkSQLiteDatabase"]!!, hierarchy)) + assertThat(framework.method("exec").call("rawQuery").desc).contains("[Ljava/lang/Object;") + } + + @Test + fun `a type test on OpenParams fails too`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Fields", + "package p; public class Fields { Object go(Object o) { return o instanceof android.database.sqlite.SQLiteDatabase.OpenParams; } }", + ), + ), + ) + assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Fields"]!!, hierarchy) } + } + + @Test + fun `androidx core's SQLiteCursorCompat helper is rewritten but never fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "androidx.core.database.sqlite.SQLiteCursorCompat", + """ + package androidx.core.database.sqlite; + public class SQLiteCursorCompat { + public static void setFillWindowForwardOnly(android.database.sqlite.SQLiteCursor c, boolean b) { + c.setFillWindowForwardOnly(b); + } + } + """, + ), + ), + ) + val out = node(SqliteRewriter.rewrite(classes["androidx/core/database/sqlite/SQLiteCursorCompat"]!!, hierarchy)) + assertThat(out.method("setFillWindowForwardOnly").desc).isEqualTo("(L${R}SQLiteCursor;Z)V") + assertThat(RewritePolicy.forClass("androidx/core/database/sqlite/SQLiteCursorCompat\$Api28Impl")).isEqualTo(RewritePolicy.NO_FAIL) + } + + @Test + fun `a cursor driver that uses its String array parameter verifies and links, with every kind of frame`() { + val out = + transform( + src( + "p.Driver", + """ + package p; + import android.database.Cursor; + import android.database.sqlite.*; + public class Driver implements SQLiteCursorDriver { + static int sink(String[] a) { return a.length; } + public Cursor query(SQLiteDatabase.CursorFactory f, String[] args) { + int x = args[0].length(); + if (f == null) { + x += sink(args); + } + int a = 1, b = 2, c = 3, d = 4; + for (int i = 0; i < x; i++) { + if (args.length > i) { + x += args[i].length(); + } else { + x += sink(args); + } + } + return x > a + b + c + d ? null : null; + } + public void cursorDeactivated() {} + public void cursorRequeried(Cursor c) {} + public void cursorClosed() {} + public void setBindArguments(String[] a) {} + } + """, + ), + src( + "p.LoopFirst", + """ + package p; + import android.database.Cursor; + import android.database.sqlite.*; + public abstract class LoopFirst implements SQLiteCursorDriver { + public Cursor query(SQLiteDatabase.CursorFactory f, String[] args) { + for (;;) { + if (args[0].length() > 1) { + return null; + } + Driver.sink(args); + } + } + } + """, + ), + ) + val query = node(out["p/Driver"]!!).method("query") + assertThat(query.desc).isEqualTo("(L${R}SQLiteDatabase\$CursorFactory;[Ljava/lang/Object;)Landroid/database/Cursor;") + val first = query.instructions.filter { it.opcode >= 0 }.take(3) + assertThat(first.map { it.opcode }).containsExactly(25, 192, 58).inOrder() // ALOAD, CHECKCAST, ASTORE + assertThat((first[1] as TypeInsnNode).desc).isEqualTo("[Ljava/lang/String;") + } + + @Test + fun `SQL text with COLLATE UNICODE fails the build, with class, method and line`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Dao", + """ + package p; + public class Dao { + static final String K = "SELECT * FROM t ORDER BY n Collate Unicode"; + String direct() { + return "SELECT * FROM t ORDER BY n COLLATE\n\tUNICODE".trim(); + } + String viaConstant() { return K; } + String fine() { return "SELECT * FROM t ORDER BY n COLLATE NOCASE; collateral unicode"; } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Dao"]!!) } + val message = e.message!! + assertThat(message).contains("p.Dao") + assertThat(message).contains("direct()Ljava/lang/String; (line ") + assertThat(message).contains("viaConstant()Ljava/lang/String; (line ") + assertThat(message).contains("COLLATE UNICODE") + assertThat(message).doesNotContain("fine") + } + + @Test + fun `COLLATE LOCALIZED only warns`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Sorted", + "package p; public class Sorted { String q() { return \"SELECT * FROM t ORDER BY n collate localized\"; } String n() { return \"x\"; } }", + ), + ), + ) + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/Sorted"]!!, warn = { warnings += it }) + assertThat(warnings).hasSize(1) + assertThat(warnings.single()).contains("p.Sorted.q") + assertThat(warnings.single()).contains("line ") + assertThat(warnings.single()).contains("byte") + } + + @Test + fun `calls on android's CursorWindow are not reported even when the hierarchy says it extends SQLiteClosable`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Windows", + """ + package p; + import android.database.CursorWindow; + public class Windows { + void go(CursorWindow w) { w.releaseReferenceFromContainer(); w.close(); } + Object parcel(android.os.Parcel p) { return CursorWindow.newFromParcel(p); } + } + """, + ), + ), + ) + val withClosable = + ClassHierarchy { name -> + if (name == "android/database/CursorWindow") listOf(A + "SQLiteClosable", "java/lang/Object") else null + } + SqliteRewriter.rewrite(classes["p/Windows"]!!, withClosable) + } + + @Test + fun `inherited deprecated cursor members that requery lacks fail the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.CursorUser", + """ + package p; + import android.database.sqlite.SQLiteCursor; + public class CursorUser { + boolean types(SQLiteCursor c) { return c.isBlob(0) || c.isFloat(1) || c.isLong(2) || c.isString(3); } + Object uris(SQLiteCursor c) { return c.getNotificationUris(); } + } + """, + ), + src( + "p.MyCursor", + """ + package p; + import android.database.sqlite.*; + public class MyCursor extends SQLiteCursor { + public MyCursor(SQLiteCursorDriver d, String t, SQLiteQuery q) { super(d, t, q); } + boolean updated(int i) { return isFieldUpdated(i) || getUpdatedField(i) != null; } + Object window() { return mWindow; } + boolean fine() { return isClosed() && getCount() > 0; } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/CursorUser"]!!, hierarchy) } + for (name in listOf("isBlob", "isFloat", "isLong", "isString", "getNotificationUris")) { + assertThat(e.message).contains("SQLiteCursor.$name") + } + val viaSubclass = + ClassHierarchy { name -> + if (name == + "p/MyCursor" + ) { + listOf(A + "SQLiteCursor", "android/database/AbstractWindowedCursor", "java/lang/Object") + } else { + null + } + } + val e2 = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/MyCursor"]!!, viaSubclass) } + assertThat(e2.message).contains("SQLiteCursor.isFieldUpdated") + assertThat(e2.message).contains("SQLiteCursor.getUpdatedField") + assertThat(e2.message).contains("SQLiteCursor.mWindow") + assertThat(e2.message).doesNotContain("isClosed") + assertThat(e2.message).doesNotContain("getCount") + } + + @Test + fun `a cast guarded by an instanceof of the same type on the same value is not reported`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Guarded", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Guarded { + Object ifBlock(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + if (c instanceof AbstractWindowedCursor) { + AbstractWindowedCursor w = (AbstractWindowedCursor) c; + return w.getWindow(); + } + return null; + } + Object and(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + return c instanceof AbstractCursor && ((AbstractCursor) c).getCount() > 0; + } + Object ternary(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + return c instanceof CrossProcessCursor ? (CrossProcessCursor) c : null; + } + Object early(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + if (!(c instanceof AbstractWindowedCursor)) { + return null; + } + return (AbstractWindowedCursor) c; + } + } + """, + ), + src( + "p.Unguarded", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Unguarded { + Object otherType(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + if (c instanceof AbstractCursor) { + return (AbstractWindowedCursor) c; + } + return null; + } + Object otherValue(SQLiteDatabase db, Cursor d) { + Cursor c = db.rawQuery("x", null); + if (d instanceof AbstractWindowedCursor) { + return (AbstractWindowedCursor) c; + } + return null; + } + Object reassigned(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + if (c instanceof AbstractWindowedCursor) { + c = db.rawQuery("y", null); + return (AbstractWindowedCursor) c; + } + return null; + } + Object afterTheBlock(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + if (c instanceof AbstractWindowedCursor) { + c.close(); + } + return (AbstractWindowedCursor) c; + } + Object negatedWithoutExit(SQLiteDatabase db) { + Cursor c = db.rawQuery("x", null); + if (!(c instanceof AbstractWindowedCursor)) { + c.close(); + } + return (AbstractWindowedCursor) c; + } + } + """, + ), + ), + ) + SqliteRewriter.rewrite(classes["p/Guarded"]!!, hierarchy) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Unguarded"]!!, hierarchy) } + for (name in listOf("otherType", "otherValue", "reassigned", "afterTheBlock", "negatedWithoutExit")) { + assertThat(e.message).contains(name) + } + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt new file mode 100644 index 0000000000..fd9e8a91eb --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt @@ -0,0 +1,278 @@ +package com.itsaky.androidide.gradle.sqlite + +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.objectweb.asm.ClassReader +import org.objectweb.asm.Opcodes +import org.objectweb.asm.tree.ClassNode +import java.io.File +import java.net.URI +import java.nio.file.Files +import java.util.zip.ZipFile +import javax.tools.JavaFileObject +import javax.tools.SimpleJavaFileObject +import javax.tools.ToolProvider + +/** + * Prints one line naming what the environment lacks. Then skips the test locally, where not everyone has + * every jar, but fails it when the environment variable CI is set: a CI run that skips these tests + * looks green while checking nothing. + */ +internal fun requireEnvironment( + present: Boolean, + missing: String, +) { + if (present) return + val onCi = !System.getenv("CI").isNullOrEmpty() + System.err.println("SQLITE REWRITE TESTS: missing $missing (${if (onCi) "failing, CI is set" else "skipping, set CI to fail instead"})") + if (onCi) throw AssertionError("The environment lacks $missing, and CI is set, so the SQLite rewrite tests do not skip") + assumeTrue(false, missing) +} + +/** Jars the tests compile and resolve against. Each lookup skips the test with a message, or fails it on CI. */ +internal object TestJars { + private val home = File(System.getProperty("user.home")) + + val androidJar: File by lazy { + val sdkRoots = + listOfNotNull( + System.getenv("ANDROID_HOME"), + System.getenv("ANDROID_SDK_ROOT"), + generateSequence(File("").absoluteFile) { it.parentFile } + .map { File(it, "local.properties") } + .firstOrNull { it.isFile } + ?.readLines() + ?.firstOrNull { it.startsWith("sdk.dir=") } + ?.substringAfter("="), + File(home, "Android/Sdk").path, + ) + val jar = + sdkRoots + .flatMap { root -> listOf(36, 35, 34, 33).map { File(root, "platforms/android-$it/android.jar") } } + .firstOrNull { it.isFile } + requireEnvironment(jar != null, "No android.jar found: set ANDROID_HOME or sdk.dir in local.properties") + jar!! + } + + private fun gradleCacheAar( + group: String, + artifact: String, + version: String, + file: String, + ): File? = + File(home, ".gradle/caches/modules-2/files-2.1/$group/$artifact/$version") + .walkTopDown() + .firstOrNull { it.name == file } + + private fun classesJarOf( + aar: File, + name: String, + ): File { + val out = Files.createTempDirectory("sqlite-rewrite-test").toFile().also { it.deleteOnExit() } + val jar = File(out, "$name.jar") + ZipFile(aar).use { zip -> + zip.getInputStream(zip.getEntry("classes.jar")).use { input -> jar.outputStream().use { input.copyTo(it) } } + } + return jar + } + + val requeryJar: File by lazy { + val aar = + System.getenv("REQUERY_AAR")?.let(::File)?.takeIf { it.isFile } + ?: gradleCacheAar("com.github.requery", "sqlite-android", "3.49.0", "sqlite-android-3.49.0.aar") + requireEnvironment(aar != null, "requery 3.49.0 AAR not found: set REQUERY_AAR or resolve it into the Gradle cache") + classesJarOf(aar!!, "requery") + } + + val androidxSqliteJar: File by lazy { + val aar = gradleCacheAar("androidx.sqlite", "sqlite-android", "2.6.2", "sqlite.aar") + requireEnvironment(aar != null, "androidx.sqlite 2.6.2 AAR not found in the Gradle cache") + classesJarOf(aar!!, "androidx-sqlite") + } + + val androidxSqliteFrameworkJar: File by lazy { + val aar = gradleCacheAar("androidx.sqlite", "sqlite-framework-android", "2.6.2", "sqlite-framework.aar") + requireEnvironment(aar != null, "androidx.sqlite framework 2.6.2 AAR not found in the Gradle cache") + classesJarOf(aar!!, "androidx-sqlite-framework") + } + + /** The Kotlin classes the framework classes call; null when the Gradle cache has none. */ + val kotlinStdlibJar: File? by lazy { + File(home, ".gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib") + .walkTopDown() + .filter { it.name.startsWith("kotlin-stdlib-") && it.name.endsWith(".jar") && "sources" !in it.name } + .maxByOrNull { it.name } + } + + val androidxCoreJar: File by lazy { + val aar = gradleCacheAar("androidx.core", "core", "1.13.1", "core-1.13.1.aar") + requireEnvironment(aar != null, "androidx.core 1.13.1 AAR not found in the Gradle cache") + classesJarOf(aar!!, "androidx-core") + } +} + +internal class JavaSource( + val className: String, + val code: String, +) : SimpleJavaFileObject(URI.create("string:///${className.replace('.', '/')}.java"), JavaFileObject.Kind.SOURCE) { + override fun getCharContent(ignoreEncodingErrors: Boolean) = code +} + +internal object Compiler { + /** Class bytes by internal name, compiled with debug info (line numbers) against [classpath]. */ + fun compile( + sources: List, + classpath: List = listOf(TestJars.androidJar), + ): Map { + val compiler = ToolProvider.getSystemJavaCompiler() ?: error("No system Java compiler: run the tests on a JDK") + val out = Files.createTempDirectory("sqlite-rewrite-classes").toFile().also { it.deleteOnExit() } + val diagnostics = StringBuilder() + val task = + compiler.getTask( + null, + null, + { diagnostics.appendLine(it.toString()) }, + listOf( + "-g", + "-proc:none", + "-source", + "8", + "-target", + "8", + "-Xlint:-options", + "-d", + out.path, + "-classpath", + classpath.joinToString(File.pathSeparator), + ), + null, + sources, + ) + check(task.call()) { "Sample failed to compile:\n$diagnostics" } + return out + .walkTopDown() + .filter { it.extension == "class" } + .associate { it.relativeTo(out).path.removeSuffix(".class") to it.readBytes() } + } +} + +/** Class members of jars, for resolving a reference the way the JVM does. */ +internal class ClassIndex( + jars: List, +) { + private val classes = HashMap() + + init { + for (jar in jars) { + ZipFile(jar).use { zip -> + for (entry in zip.entries()) { + if (entry.name.endsWith(".class")) { + classes[entry.name.removeSuffix(".class")] = + ClassNode().also { ClassReader(zip.getInputStream(entry)).accept(it, ClassReader.SKIP_CODE) } + } + } + } + } + } + + fun addClass(bytes: ByteArray) { + val n = ClassNode().also { ClassReader(bytes).accept(it, ClassReader.SKIP_CODE) } + classes[n.name] = n + } + + private fun load(name: String): ClassNode? = + classes[name] + ?: ClassLoader.getSystemResourceAsStream("$name.class")?.use { s -> + ClassNode().also { ClassReader(s).accept(it, ClassReader.SKIP_CODE) } + } + + fun knows(name: String) = load(name) != null + + fun superClass(name: String): String? = load(name)?.superName + + fun superTypes(name: String): List { + val result = mutableListOf() + val pending = ArrayDeque(listOf(name)) + while (pending.isNotEmpty()) { + val n = pending.removeFirst() + val c = load(n) ?: continue + if (n != name) result += n + c.superName?.let(pending::add) + pending.addAll(c.interfaces) + } + return result + } + + private fun packageOf(name: String) = name.substringBeforeLast('/', "") + + private fun accessible( + access: Int, + declaring: String, + caller: String?, + protectedOk: Boolean, + ): Boolean = + when { + access and Opcodes.ACC_PUBLIC != 0 -> { + true + } + + access and Opcodes.ACC_PRIVATE != 0 -> { + caller == declaring + } + + access and Opcodes.ACC_PROTECTED != 0 -> { + protectedOk || ( + caller != null && ( + caller == declaring || declaring in + superTypes( + caller, + ) || packageOf(caller) == packageOf(declaring) + ) + ) + } + + else -> { + caller != null && packageOf(caller) == packageOf(declaring) + } + } + + /** + * The class declaring the member, or null when the JVM would not link the reference: the member is + * missing, static where the call is not (or the reverse), or not accessible from [caller], a class + * in [classes] (null: an unrelated class in another package). [protectedOk] accepts protected members + * for a caller that is not a subclass, as a probe that stands in for one. + */ + fun resolve( + owner: String, + name: String, + desc: String, + field: Boolean, + isStatic: Boolean? = null, + caller: String? = null, + protectedOk: Boolean = false, + ): String? { + val ownerNode = load(owner) ?: return null + if (!accessible(ownerNode.access, owner, caller, false)) return null + val pending = ArrayDeque(listOf(owner)) + val seen = HashSet() + while (pending.isNotEmpty()) { + val n = pending.removeFirst() + if (!seen.add(n)) continue + val c = load(n) ?: continue + val access = + if (field) { + c.fields.firstOrNull { it.name == name && it.desc == desc }?.access + } else { + c.methods.firstOrNull { it.name == name && it.desc == desc }?.access + } + if (access != null) { + if (isStatic != null && (access and Opcodes.ACC_STATIC != 0) != isStatic) return null + return if (accessible(access, n, caller, protectedOk)) n else null + } + c.superName?.let(pending::add) + pending.addAll(c.interfaces) + } + return null + } + + fun isInterface(name: String) = load(name)?.let { it.access and Opcodes.ACC_INTERFACE != 0 } ?: false +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index cdc27caaf2..45225bc68f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -291,6 +291,9 @@ composeRuntimeDaemonTests = { module = "androidx.compose.runtime:runtime-android # Only :quickbuild:daemon uses this, and it takes the jar from the on-device Gradle # distribution rather than the APK - so the version is the distribution's, not ours. ow2-asm = { module = "org.ow2.asm:asm", version = "9.9" } +ow2-asmAnalysis = { module = "org.ow2.asm:asm-analysis", version = "9.9" } +ow2-asmCommons = { module = "org.ow2.asm:asm-commons", version = "9.9" } +ow2-asmTree = { module = "org.ow2.asm:asm-tree", version = "9.9" } # Tests tests-junit = { module = "junit:junit", version = "4.13.2" } From 0c28568934e8a9df2cbe23953f754cafeb4dcdfb Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:51:37 -0800 Subject: [PATCH 055/203] ADFA-7138 Code on the Go injects the rewrite runtime AAR and checks the classpath The rewrite is useful only when the helper AAR is on the app's classpath and requery is present. Code on the Go bundles the helper in its assets (release AAR, no v7/v8 flavors), extracts it at startup, and passes its path to Gradle as -Pandroidide.sqliteRewriteRuntime.aar, always, like logsender: the plugin reads it only for an opted-in project and then names the missing file instead of a missing property. SqliteRewritePlugin registers the class transform on every variant and adds the helper to every variant's runtime classpath. checkSqliteRewriteClasspath fails the build with a clear message when requery or androidx.sqlite is missing from the app: requery comes from the project's libs/, as in ADFA-7082, and the build says so. withRuntimeConfiguration moves from LogSenderPlugin to a shared internal function so the rewrite and the debugger plugins use the same one. GradlePluginConfig names the opt-in property cogo.sqliteDebugger. Tests: the plugin and the check task run in a real Gradle build with the sample project, in the commit that applies the plugin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- app/build.gradle.kts | 2 + .../services/builder/GradleBuildService.kt | 4 + .../androidide/managers/ToolsManager.java | 14 +++ .../itsaky/androidide/utils/Environment.java | 5 + .../main/java/org/adfa/constants/constants.kt | 4 + .../plugins/AndroidIDEAssetsPlugin.kt | 18 ++++ .../tooling/api/GradlePluginConfig.java | 10 ++ .../androidide/gradle/LogSenderPlugin.kt | 16 ++-- .../sqlite/CheckSqliteRewriteClasspathTask.kt | 82 ++++++++++++++++ .../gradle/sqlite/SqliteRewritePlugin.kt | 94 +++++++++++++++++++ 10 files changed, 243 insertions(+), 6 deletions(-) create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 55c5fdec0f..0e99bc11cc 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -523,6 +523,8 @@ dependencies { // (QuickBuildArtifactStager). evaluationDependsOn(":quickbuild:runtime") evaluationDependsOn(":quickbuild:daemon") +// The assets plugin bundles its release AAR (ADFA-7131). +evaluationDependsOn(":subprojects:sqlite-rewrite-runtime") // ADFA-4931: jars the daemon loads from the on-device Gradle distribution instead of shipping its // own copy, since `gradle-dists/` and `quickbuild/` both sit under . diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt index 88452a86ad..8064b11c7e 100644 --- a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt +++ b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt @@ -53,6 +53,7 @@ import com.itsaky.androidide.tooling.api.ForwardingToolingApiClient import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_JDWP_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_LOG_SENDER_AAR import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_LOG_SENDER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR import com.itsaky.androidide.tooling.api.IToolingApiClient import com.itsaky.androidide.tooling.api.IToolingApiServer import com.itsaky.androidide.tooling.api.messages.BuildId @@ -726,6 +727,9 @@ class GradleBuildService : extraArgs.add("-P${PROPERTY_JDWP_ENABLED}=$enableJdwp") extraArgs.add("-P${PROPERTY_LOG_SENDER_ENABLED}=$enableLogSender") extraArgs.add("-P${PROPERTY_LOG_SENDER_AAR}=${Environment.LOGSENDER_AAR.absolutePath}") + // Always passed, like logsender's: the plugin reads it only for a project that opted in, and + // then names the missing file instead of a missing property. + extraArgs.add("-P${PROPERTY_SQLITE_REWRITE_RUNTIME_AAR}=${Environment.SQLITE_REWRITE_RUNTIME_AAR.absolutePath}") extraArgs.addAll(relocatedBuildOutputArgs(isSync)) diff --git a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java index 3977d3fc94..3c0cd978c0 100755 --- a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java +++ b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java @@ -129,6 +129,7 @@ public static void init(@NonNull BaseApplication app, Runnable onFinish) { ensureToolingJar(app); extractLogSender(app); + extractSqliteRewriteRuntime(); writeNoMediaFile(); extractCogoPlugin(); @@ -261,6 +262,19 @@ private static void extractLogSender(BaseApplication app) { Environment.LOGSENDER_AAR.getAbsolutePath()); } + @WorkerThread + private static void extractSqliteRewriteRuntime() { + if (Environment.SQLITE_REWRITE_RUNTIME_AAR.exists()) { + FileUtils.delete(Environment.SQLITE_REWRITE_RUNTIME_AAR); + } + + Environment.mkdirIfNotExists(Environment.SQLITE_REWRITE_RUNTIME_DIR); + + // Java only, so one AAR for both ABIs + ResourceUtils.copyFileFromAssets(getCommonAsset("sqlite-rewrite-runtime-release.aar"), + Environment.SQLITE_REWRITE_RUNTIME_AAR.getAbsolutePath()); + } + private static void generateKeystore() { try { String keystorePath = Environment.KEYSTORE_RELEASE.getPath(); diff --git a/common/src/main/java/com/itsaky/androidide/utils/Environment.java b/common/src/main/java/com/itsaky/androidide/utils/Environment.java index ce5e1f0db9..07cec9b4cb 100755 --- a/common/src/main/java/com/itsaky/androidide/utils/Environment.java +++ b/common/src/main/java/com/itsaky/androidide/utils/Environment.java @@ -18,6 +18,7 @@ import static org.adfa.constants.ConstantsKt.GRADLE_DISTRIBUTION_VERSION; import static org.adfa.constants.ConstantsKt.LOGSENDER_AAR_NAME; +import static org.adfa.constants.ConstantsKt.SQLITE_REWRITE_RUNTIME_AAR_NAME; import android.annotation.SuppressLint; import android.content.Context; @@ -66,6 +67,8 @@ public final class Environment { public static File OPT_DIR; public static File LOGSENDER_DIR; public static File LOGSENDER_AAR; + public static File SQLITE_REWRITE_RUNTIME_DIR; + public static File SQLITE_REWRITE_RUNTIME_AAR; public static File PROJECTS_DIR; // split assets vars @@ -154,6 +157,8 @@ public static void init(Context context) { OPT_DIR = mkdirIfNotExists(new File(PREFIX, "opt")); LOGSENDER_DIR = mkdirIfNotExists(new File(ANDROIDIDE_HOME, "logsender")); LOGSENDER_AAR = mkdirIfNotExists(new File(LOGSENDER_DIR, LOGSENDER_AAR_NAME)); + SQLITE_REWRITE_RUNTIME_DIR = mkdirIfNotExists(new File(ANDROIDIDE_HOME, "sqlite-rewrite-runtime")); + SQLITE_REWRITE_RUNTIME_AAR = new File(SQLITE_REWRITE_RUNTIME_DIR, SQLITE_REWRITE_RUNTIME_AAR_NAME); PROJECTS_DIR = mkdirIfNotExists(new File(FileUtil.getExternalStorageDir(), PROJECTS_FOLDER)); // NOTE: change location of android.jar from ANDROIDIDE_HOME to inside android-sdk // and don't create the dir if it doesn't exist diff --git a/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt b/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt index cf9d02b859..b50688e819 100644 --- a/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt +++ b/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt @@ -83,6 +83,10 @@ const val DOCUMENTATION_DB = "documentation.db" const val LOGSENDER_AAR_NAME = "logsender.aar" +// The helpers the build-time android.database.sqlite -> requery rewrite redirects to (ADFA-7138), +// injected into every variant of apps built with CoGo that opted in +const val SQLITE_REWRITE_RUNTIME_AAR_NAME = "sqlite-rewrite-runtime.aar" + // Generated Gradle Api Jar const val GRADLE_API_NAME_JAR = "gradle-api-$GRADLE_DISTRIBUTION_VERSION.jar" const val GRADLE_API_NAME_JAR_ZIP = "${GRADLE_API_NAME_JAR}.zip" diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt index fa69885a18..2ff3f922e0 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt @@ -71,6 +71,9 @@ class AndroidIDEAssetsPlugin : Plugin { // Add logsender.aar registerLogSenderAarCopierTask(variant, variantNameCapitalized) + // Add sqlite-rewrite-runtime-release.aar + registerSqliteRewriteRuntimeAarCopierTask(variant, variantNameCapitalized) + // Add plugin-artifacts.zip registerPluginArtifactsCopierTask(variant, variantNameCapitalized) @@ -216,6 +219,21 @@ class AndroidIDEAssetsPlugin : Plugin { } } + /** Java only, no v7/v8 flavors: every variant bundles the same file. The release build type, as above. */ + private fun Project.registerSqliteRewriteRuntimeAarCopierTask( + variant: Variant, + variantName: String, + ) { + addProjectArtifactToAssets( + variant = variant, + taskName = "copy${variantName}SqliteRewriteRuntimeAar", + projectPath = ":subprojects:sqlite-rewrite-runtime", + projectTask = "assembleRelease", + ) { project -> + project.layout.buildDirectory.file("outputs/aar/sqlite-rewrite-runtime-release.aar") + } + } + private inline fun Project.addProjectArtifactToAssets( variant: Variant, taskName: String, diff --git a/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java b/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java index 4bd6180f1e..03c72716af 100644 --- a/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java +++ b/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java @@ -64,6 +64,16 @@ public final class GradlePluginConfig { */ public static final String PROPERTY_LOG_SENDER_AAR = "androidide.logsender.aar"; + /** + * Property, normally in the project's gradle.properties, that opts the project into the SQLite debugger (ADFA-7131). The debugger is added to debuggable variants only, and only when the value is true. + */ + public static final String PROPERTY_SQLITE_DEBUGGER_ENABLED = "cogo.sqliteDebugger"; + + /** + * The path to the AAR with the helpers the SQLite rewrite redirects to (ADFA-7138), passed by Code on the Go like {@link #PROPERTY_SQLITE_DEBUGGER_AAR}. + */ + public static final String PROPERTY_SQLITE_REWRITE_RUNTIME_AAR = "androidide.sqliteRewriteRuntime.aar"; + /** * Property that is set in tests to indicate that the plugin is being applied in a test environment. *

diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt index 4819ca0dd9..99416b3d7d 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt @@ -85,12 +85,16 @@ class LogSenderPlugin : Plugin { } } } +} - private fun ApplicationVariant.withRuntimeConfiguration(action: Configuration.() -> Unit) { - if (this is ApplicationVariantImpl) { - variantDependencies.runtimeClasspath.action() - } else if (this is AnalyticsEnabledApplicationVariant) { - delegate.withRuntimeConfiguration(action) - } +/** + * Runs [action] on the variant's runtime classpath configuration. Shared with + * [SqliteDebuggerPlugin]; does nothing for a variant type it does not recognize. + */ +internal fun ApplicationVariant.withRuntimeConfiguration(action: Configuration.() -> Unit) { + if (this is ApplicationVariantImpl) { + variantDependencies.runtimeClasspath.action() + } else if (this is AnalyticsEnabledApplicationVariant) { + delegate.withRuntimeConfiguration(action) } } diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt new file mode 100644 index 0000000000..39422df3fb --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt @@ -0,0 +1,82 @@ +package com.itsaky.androidide.gradle.sqlite + +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Classpath +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction +import java.io.File +import java.util.zip.ZipFile + +/** + * Fails the build, before anything is compiled or rewritten, when the variant's runtime classpath + * lacks what the rewritten classes load: requery itself and androidx.sqlite. requery reaches an app + * as a file dependency from `libs/`, which brings none of its own dependencies. + */ +abstract class CheckSqliteRewriteClasspathTask : DefaultTask() { + @get:Input + abstract val variantName: Property + + @get:Classpath + abstract val runtimeClasspath: ConfigurableFileCollection + + /** Written on success, so an unchanged classpath is not scanned again. */ + @get:OutputFile + abstract val stamp: RegularFileProperty + + @TaskAction + fun check() { + val files = runtimeClasspath.files + val missing = REQUIRED.filter { (_, entry) -> files.none { contains(it, entry) } } + if (missing.isNotEmpty()) { + throw GradleException(message(variantName.get(), missing.map { it.first })) + } + stamp.get().asFile.apply { + parentFile.mkdirs() + writeText("ok") + } + } + + private fun contains( + file: File, + entry: String, + ): Boolean = + when { + file.isDirectory -> File(file, entry).isFile + file.isFile -> runCatching { ZipFile(file).use { it.getEntry(entry) != null } }.getOrDefault(false) + else -> false + } + + companion object { + internal const val REQUERY_ENTRY = "io/requery/android/database/sqlite/SQLiteDatabase.class" + internal const val ANDROIDX_SQLITE_ENTRY = "androidx/sqlite/db/SupportSQLiteDatabase.class" + + private val REQUIRED = + listOf( + "requery's SQLiteDatabase ($REQUERY_ENTRY)" to REQUERY_ENTRY, + "androidx.sqlite's SupportSQLiteDatabase ($ANDROIDX_SQLITE_ENTRY)" to ANDROIDX_SQLITE_ENTRY, + ) + + internal fun message( + variant: String, + missing: List, + ) = "cogo.sqliteDebugger=true moves the app to requery, but the runtime classpath of variant '$variant' has no " + + missing.joinToString(" and no ") + + ". requery's AAR comes from the project's libs/ directory as a file dependency, which brings none of its own " + + "dependencies: add requery's AAR to libs/ (implementation(files(\"libs/sqlite-android.aar\"))) and androidx.sqlite " + + "(implementation(\"androidx.sqlite:sqlite:\"), or a library that depends on it, such as Room or WorkManager). " + + "Remove cogo.sqliteDebugger from gradle.properties to build without them." + + /** The tasks of a variant that must not start before the check: compiling and the rewrite itself. */ + internal fun guardedTaskNames(capitalizedVariant: String) = + setOf( + "compile${capitalizedVariant}JavaWithJavac", + "compile${capitalizedVariant}Kotlin", + "transform${capitalizedVariant}ClassesWithAsm", + ) + } +} diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt new file mode 100644 index 0000000000..a3b621b501 --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt @@ -0,0 +1,94 @@ +@file:Suppress("ktlint:standard:max-line-length") + +package com.itsaky.androidide.gradle.sqlite + +import com.android.build.api.instrumentation.InstrumentationScope +import com.android.build.api.variant.ApplicationAndroidComponentsExtension +import com.itsaky.androidide.gradle.APP_PLUGIN +import com.itsaky.androidide.gradle.withRuntimeConfiguration +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR +import org.gradle.api.GradleException +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.type.ArtifactTypeDefinition +import org.gradle.api.logging.Logging +import java.io.File + +/** + * Registers the android.database.sqlite -> requery class rewrite on every variant (ADFA-7138), adds the + * helpers the rewritten classes call to every variant's runtime classpath, and checks that requery and + * androidx.sqlite are there too. + * + * Applied only when [PROPERTY_SQLITE_DEBUGGER_ENABLED] is "true": the rewritten classes need requery in + * the app, and it reaches apps only through the template's libs/ (ADFA-7082), so a project that + * did not opt in would crash at class load. The helper AAR is Code on the Go's, passed in like the + * debugger's; the build fails when it is missing, because the project opted in. + */ +class SqliteRewritePlugin : Plugin { + companion object { + private val logger = Logging.getLogger(SqliteRewritePlugin::class.java) + + /** AGP's artifact-type attribute for a dependency's classes as a jar; AGP-internal, so the raw string. */ + internal const val CLASSES_JAR_ARTIFACT_TYPE = "android-classes-jar" + } + + override fun apply(target: Project) { + if (!target.plugins.hasPlugin(APP_PLUGIN)) { + return + } + logger.info("Applying SqliteRewritePlugin to project '${target.path}'") + + val runtimeAar = + target.findProperty(PROPERTY_SQLITE_REWRITE_RUNTIME_AAR)?.let { File(it.toString()) } + ?: throw GradleException( + "'$PROPERTY_SQLITE_DEBUGGER_ENABLED' is true but no property '$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR' is set. " + + "Remove the line from gradle.properties to build without the SQLite rewrite.", + ) + if (!runtimeAar.isFile) { + throw GradleException( + "SQLite rewrite runtime AAR not found at '${runtimeAar.absolutePath}'. " + + "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it.", + ) + } + + target.extensions.getByType(ApplicationAndroidComponentsExtension::class.java).onVariants { variant -> + variant.instrumentation.transformClassesWith( + SqliteRewriteVisitorFactory::class.java, + InstrumentationScope.ALL, + ) {} + // Frames are copied; the rewriter keeps the one method whose descriptor changes valid itself. + variant.instrumentation.setAsmFramesComputationMode(SqliteRewriter.FRAMES_MODE) + + val capitalized = variant.name.replaceFirstChar { it.uppercase() } + variant.withRuntimeConfiguration { + logger.lifecycle("Adding SQLite rewrite runtime dependency to variant '{}' of project '{}'", variant.name, target.path) + dependencies.add(target.dependencies.create(target.fileTree(runtimeAar))) + + val check = + target.tasks.register( + "check${capitalized}SqliteRewriteClasspath", + CheckSqliteRewriteClasspathTask::class.java, + ) { task -> + task.variantName.set(variant.name) + task.runtimeClasspath.from( + incoming + .artifactView { view -> + view.attributes { + it.attribute( + ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, + CLASSES_JAR_ARTIFACT_TYPE, + ) + } + view.setLenient(true) + }.files, + ) + task.stamp.set(target.layout.buildDirectory.file("intermediates/sqlite_rewrite_classpath/${variant.name}/ok")) + } + target.tasks + .matching { it.name in CheckSqliteRewriteClasspathTask.guardedTaskNames(capitalized) } + .configureEach { it.dependsOn(check) } + } + } + } +} From b65e5936d0fa6ff7d23b1f4c55bdaaa42031f7c6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:06:02 -0800 Subject: [PATCH 056/203] ADFA-7138 Add the SQLite debugger AAR to debuggable variants when opted in Code on the Go bundles the sqlite-debugger release AAR (one AAR carries both ABIs), extracts it at startup and passes its path to Gradle as -Pandroidide.sqliteDebugger.aar, like logsender. SqliteDebuggerPlugin adds it and kotlin-stdlib to the runtime classpath of debuggable variants only: it reads Variant.debuggable in onVariants. A release build never carries the debugger. Tests: SqliteDebuggerPluginTest, with the commit that applies the plugin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- app/build.gradle.kts | 1 + .../services/builder/GradleBuildService.kt | 2 + .../androidide/managers/ToolsManager.java | 14 +++ .../itsaky/androidide/utils/Environment.java | 5 + .../main/java/org/adfa/constants/constants.kt | 3 + .../plugins/AndroidIDEAssetsPlugin.kt | 21 ++++ .../tooling/api/GradlePluginConfig.java | 5 + gradle-plugin/build.gradle.kts | 8 ++ .../androidide/gradle/SqliteDebuggerPlugin.kt | 98 +++++++++++++++++++ .../androidide/gradle/SqliteBuildSupport.kt | 68 +++++++++++++ 10 files changed, 225 insertions(+) create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteBuildSupport.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0e99bc11cc..8164293585 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -524,6 +524,7 @@ dependencies { evaluationDependsOn(":quickbuild:runtime") evaluationDependsOn(":quickbuild:daemon") // The assets plugin bundles its release AAR (ADFA-7131). +evaluationDependsOn(":subprojects:sqlite-debugger") evaluationDependsOn(":subprojects:sqlite-rewrite-runtime") // ADFA-4931: jars the daemon loads from the on-device Gradle distribution instead of shipping its diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt index 8064b11c7e..640054e6c9 100644 --- a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt +++ b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt @@ -53,6 +53,7 @@ import com.itsaky.androidide.tooling.api.ForwardingToolingApiClient import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_JDWP_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_LOG_SENDER_AAR import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_LOG_SENDER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR import com.itsaky.androidide.tooling.api.IToolingApiClient import com.itsaky.androidide.tooling.api.IToolingApiServer @@ -729,6 +730,7 @@ class GradleBuildService : extraArgs.add("-P${PROPERTY_LOG_SENDER_AAR}=${Environment.LOGSENDER_AAR.absolutePath}") // Always passed, like logsender's: the plugin reads it only for a project that opted in, and // then names the missing file instead of a missing property. + extraArgs.add("-P${PROPERTY_SQLITE_DEBUGGER_AAR}=${Environment.SQLITE_DEBUGGER_AAR.absolutePath}") extraArgs.add("-P${PROPERTY_SQLITE_REWRITE_RUNTIME_AAR}=${Environment.SQLITE_REWRITE_RUNTIME_AAR.absolutePath}") extraArgs.addAll(relocatedBuildOutputArgs(isSync)) diff --git a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java index 3c0cd978c0..b097f8e08c 100755 --- a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java +++ b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java @@ -129,6 +129,7 @@ public static void init(@NonNull BaseApplication app, Runnable onFinish) { ensureToolingJar(app); extractLogSender(app); + extractSqliteDebugger(); extractSqliteRewriteRuntime(); writeNoMediaFile(); @@ -262,6 +263,19 @@ private static void extractLogSender(BaseApplication app) { Environment.LOGSENDER_AAR.getAbsolutePath()); } + @WorkerThread + private static void extractSqliteDebugger() { + if (Environment.SQLITE_DEBUGGER_AAR.exists()) { + FileUtils.delete(Environment.SQLITE_DEBUGGER_AAR); + } + + Environment.mkdirIfNotExists(Environment.SQLITE_DEBUGGER_DIR); + + // One AAR with both ABIs, unlike logsender's per-flavor AARs + ResourceUtils.copyFileFromAssets(getCommonAsset("sqlite-debugger-release.aar"), + Environment.SQLITE_DEBUGGER_AAR.getAbsolutePath()); + } + @WorkerThread private static void extractSqliteRewriteRuntime() { if (Environment.SQLITE_REWRITE_RUNTIME_AAR.exists()) { diff --git a/common/src/main/java/com/itsaky/androidide/utils/Environment.java b/common/src/main/java/com/itsaky/androidide/utils/Environment.java index 07cec9b4cb..44c1585bed 100755 --- a/common/src/main/java/com/itsaky/androidide/utils/Environment.java +++ b/common/src/main/java/com/itsaky/androidide/utils/Environment.java @@ -18,6 +18,7 @@ import static org.adfa.constants.ConstantsKt.GRADLE_DISTRIBUTION_VERSION; import static org.adfa.constants.ConstantsKt.LOGSENDER_AAR_NAME; +import static org.adfa.constants.ConstantsKt.SQLITE_DEBUGGER_AAR_NAME; import static org.adfa.constants.ConstantsKt.SQLITE_REWRITE_RUNTIME_AAR_NAME; import android.annotation.SuppressLint; @@ -67,6 +68,8 @@ public final class Environment { public static File OPT_DIR; public static File LOGSENDER_DIR; public static File LOGSENDER_AAR; + public static File SQLITE_DEBUGGER_DIR; + public static File SQLITE_DEBUGGER_AAR; public static File SQLITE_REWRITE_RUNTIME_DIR; public static File SQLITE_REWRITE_RUNTIME_AAR; public static File PROJECTS_DIR; @@ -157,6 +160,8 @@ public static void init(Context context) { OPT_DIR = mkdirIfNotExists(new File(PREFIX, "opt")); LOGSENDER_DIR = mkdirIfNotExists(new File(ANDROIDIDE_HOME, "logsender")); LOGSENDER_AAR = mkdirIfNotExists(new File(LOGSENDER_DIR, LOGSENDER_AAR_NAME)); + SQLITE_DEBUGGER_DIR = mkdirIfNotExists(new File(ANDROIDIDE_HOME, "sqlite-debugger")); + SQLITE_DEBUGGER_AAR = new File(SQLITE_DEBUGGER_DIR, SQLITE_DEBUGGER_AAR_NAME); SQLITE_REWRITE_RUNTIME_DIR = mkdirIfNotExists(new File(ANDROIDIDE_HOME, "sqlite-rewrite-runtime")); SQLITE_REWRITE_RUNTIME_AAR = new File(SQLITE_REWRITE_RUNTIME_DIR, SQLITE_REWRITE_RUNTIME_AAR_NAME); PROJECTS_DIR = mkdirIfNotExists(new File(FileUtil.getExternalStorageDir(), PROJECTS_FOLDER)); diff --git a/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt b/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt index b50688e819..88d6c608a0 100644 --- a/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt +++ b/composite-builds/build-deps-common/constants/src/main/java/org/adfa/constants/constants.kt @@ -83,6 +83,9 @@ const val DOCUMENTATION_DB = "documentation.db" const val LOGSENDER_AAR_NAME = "logsender.aar" +// The SQLite debugger AAR (ADFA-7131), injected into debug builds of apps built with CoGo +const val SQLITE_DEBUGGER_AAR_NAME = "sqlite-debugger.aar" + // The helpers the build-time android.database.sqlite -> requery rewrite redirects to (ADFA-7138), // injected into every variant of apps built with CoGo that opted in const val SQLITE_REWRITE_RUNTIME_AAR_NAME = "sqlite-rewrite-runtime.aar" diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt index 2ff3f922e0..28dad8c713 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/AndroidIDEAssetsPlugin.kt @@ -71,6 +71,9 @@ class AndroidIDEAssetsPlugin : Plugin { // Add logsender.aar registerLogSenderAarCopierTask(variant, variantNameCapitalized) + // Add sqlite-debugger-release.aar + registerSqliteDebuggerAarCopierTask(variant, variantNameCapitalized) + // Add sqlite-rewrite-runtime-release.aar registerSqliteRewriteRuntimeAarCopierTask(variant, variantNameCapitalized) @@ -219,6 +222,24 @@ class AndroidIDEAssetsPlugin : Plugin { } } + /** + * The debugger module has no v7/v8 flavors: one AAR carries both ABIs, so every variant bundles + * the same file. The release build type, as for logsender. + */ + private fun Project.registerSqliteDebuggerAarCopierTask( + variant: Variant, + variantName: String, + ) { + addProjectArtifactToAssets( + variant = variant, + taskName = "copy${variantName}SqliteDebuggerAar", + projectPath = ":subprojects:sqlite-debugger", + projectTask = "assembleRelease", + ) { project -> + project.layout.buildDirectory.file("outputs/aar/sqlite-debugger-release.aar") + } + } + /** Java only, no v7/v8 flavors: every variant bundles the same file. The release build type, as above. */ private fun Project.registerSqliteRewriteRuntimeAarCopierTask( variant: Variant, diff --git a/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java b/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java index 03c72716af..705f174240 100644 --- a/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java +++ b/gradle-plugin-config/src/main/java/com/itsaky/androidide/tooling/api/GradlePluginConfig.java @@ -69,6 +69,11 @@ public final class GradlePluginConfig { */ public static final String PROPERTY_SQLITE_DEBUGGER_ENABLED = "cogo.sqliteDebugger"; + /** + * The path to the SQLite debugger AAR file, passed by Code on the Go like {@link #PROPERTY_LOG_SENDER_AAR}. + */ + public static final String PROPERTY_SQLITE_DEBUGGER_AAR = "androidide.sqliteDebugger.aar"; + /** * The path to the AAR with the helpers the SQLite rewrite redirects to (ADFA-7138), passed by Code on the Go like {@link #PROPERTY_SQLITE_DEBUGGER_AAR}. */ diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index d631c8404a..ac6d85a7c2 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -176,6 +176,14 @@ gradlePlugin { tags.set(setOf("androidide", "logsender")) } + create("sqliteDebuggerPlugin") { + id = "${BuildConfig.PACKAGE_NAME}.sqlitedebugger" + implementationClass = "${BuildConfig.PACKAGE_NAME}.gradle.SqliteDebuggerPlugin" + displayName = "AndroidIDE SQLite Debugger Gradle Plugin" + description = + "Gradle plugin for adding the SQLite debugger to debuggable variants of projects that are built with AndroidIDE" + tags.set(setOf("androidide", "sqlite")) + } } } diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt new file mode 100644 index 0000000000..bb37d6a7b1 --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt @@ -0,0 +1,98 @@ +package com.itsaky.androidide.gradle + +import com.android.build.api.variant.ApplicationAndroidComponentsExtension +import com.android.build.api.variant.ApplicationVariant +import com.android.build.api.variant.Component +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import org.adfa.constants.KOTLIN_VERSION +import org.gradle.api.GradleException +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.logging.Logging +import java.io.File +import java.lang.reflect.Method + +/** + * Adds the SQLite debugger (ADFA-7131) to the debuggable variants of an Android application, as + * [LogSenderPlugin] does for LogSender. [AndroidIDEGradlePlugin] applies it only when the project + * sets [PROPERTY_SQLITE_DEBUGGER_ENABLED] to `true`. + * + * Fails the build when the AAR is not there: the project opted in, and a build that quietly drops + * the debugger leaves the user wondering why no database shows up. + */ +class SqliteDebuggerPlugin : Plugin { + companion object { + private val logger = Logging.getLogger(SqliteDebuggerPlugin::class.java) + + /** + * The debugger is Kotlin, and the AAR is a file dependency, which brings no POM and so no + * kotlin-stdlib. KOTLIN_VERSION is the version CoGo's local Maven repository always holds + * (new projects are generated with it), so this resolves offline. Gradle keeps the highest + * version of a module, so an app on a newer Kotlin is not downgraded. + */ + internal const val KOTLIN_STDLIB_COORDINATES = "org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION" + + /** + * `Component.debuggable`, which AGP added after the oldest version this plugin supports, so it is + * reached by reflection: minAgpCheck compiles this file against that oldest version. Null there. + */ + private val componentDebuggable: Method? = runCatching { Component::class.java.getMethod("getDebuggable") }.getOrNull() + + /** Null when this AGP has no `Variant.debuggable`. */ + internal fun readDebuggable(variant: ApplicationVariant): Boolean? = componentDebuggable?.invoke(variant) as Boolean? + } + + override fun apply(target: Project) { + if (!target.plugins.hasPlugin(APP_PLUGIN)) { + return + } + + logger.info("Applying {} to project '${target.path}'", SqliteDebuggerPlugin::class.simpleName) + + if (target.isTestEnv) { + logger.lifecycle("Applying {} to project '{}'", javaClass.simpleName, target.path) + } + + val aar = + target.findProperty(PROPERTY_SQLITE_DEBUGGER_AAR)?.let { File(it.toString()) } + ?: throw GradleException( + "'$PROPERTY_SQLITE_DEBUGGER_ENABLED' is true but no property '$PROPERTY_SQLITE_DEBUGGER_AAR' is set. " + + "Remove the line from gradle.properties to build without the SQLite debugger.", + ) + + if (!aar.isFile) { + throw GradleException( + "SQLite debugger AAR not found at '${aar.absolutePath}'. " + + "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it.", + ) + } + + target.extensions.getByType(ApplicationAndroidComponentsExtension::class.java).apply { + val addDebugger = { variant: ApplicationVariant -> + variant.withRuntimeConfiguration { + logger.lifecycle( + "Adding SQLite debugger dependency to variant '{}' of project '{}'", + variant.name, + target.path, + ) + + dependencies.add(target.dependencies.create(target.fileTree(aar))) + dependencies.add(target.dependencies.create(KOTLIN_STDLIB_COORDINATES)) + } + } + // onDebuggableVariants reads variantBuilder.debuggable in beforeVariants, which AGP 8.11 rejects + // when a plugin is applied from CoGo's init script (see QuickBuildPlugin). Variant.debuggable in + // onVariants is the sanctioned read; AGPs that predate it still allow the builder's. + if (componentDebuggable != null) { + onVariants { variant -> + if (readDebuggable(variant) == true) { + addDebugger(variant) + } + } + } else { + onDebuggableVariants(addDebugger) + } + } + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteBuildSupport.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteBuildSupport.kt new file mode 100644 index 0000000000..4024a65278 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteBuildSupport.kt @@ -0,0 +1,68 @@ +package com.itsaky.androidide.gradle + +import java.io.File +import java.nio.file.Path +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +/** Prints what each variant's runtime classpath declares, without resolving anything. */ +internal fun printDepsInitScript(dir: File): File = + File(dir, "print-deps.init.gradle").apply { + writeText( + """ + allprojects { p -> + p.afterEvaluate { + if (p.plugins.hasPlugin('com.android.application')) { + p.tasks.register('printRuntimeDeps') { + doLast { + ['demoDebug', 'fullDebug', 'demoRelease', 'fullRelease'].each { v -> + p.configurations.getByName(v + 'RuntimeClasspath').allDependencies.each { d -> + if (d instanceof org.gradle.api.artifacts.FileCollectionDependency) { + d.files.each { println "RTDEP ${'$'}v file ${'$'}{it.name}" } + } else { + println "RTDEP ${'$'}v ${'$'}{d.group}:${'$'}{d.name}:${'$'}{d.version}" + } + } + } + } + } + } + } + } + """.trimIndent(), + ) + } + +/** A jar or AAR file with the given entries, for stand-ins whose class bytes nobody reads. */ +internal fun standIn( + file: File, + vararg entries: Pair, +): File { + file.parentFile.mkdirs() + ZipOutputStream(file.outputStream()).use { zip -> + for ((name, bytes) in entries) { + zip.putNextEntry(ZipEntry(name)) + zip.write(bytes) + zip.closeEntry() + } + } + return file +} + +/** A copy of the sample project in [into], without build output, with [extraBuildScript] appended to the app's script. */ +internal fun copySampleProject( + into: File, + extraBuildScript: String, +): Path { + val source = openProject().toFile() + val dest = File(into, "project") + source + .walkTopDown() + .onEnter { it.name != "build" && it.name != ".gradle" } + .forEach { file -> + val target = File(dest, file.relativeTo(source).path) + if (file.isDirectory) target.mkdirs() else file.copyTo(target, overwrite = true) + } + File(dest, "app/build.gradle.kts").appendText("\n" + extraBuildScript + "\n") + return dest.toPath() +} From 2a5cb6d9368f7649f78d6067ed98b46d5cbde887 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:06:02 -0800 Subject: [PATCH 057/203] ADFA-7138 Apply the rewrite and the debugger from one opt-in property cogo.sqliteDebugger=true in gradle.properties applies both plugins: the rewrite moves the app to requery in every variant, and the debugger, which needs requery, goes into the debuggable variants only. Without the property neither is applied. Tests: a dry run shows the class transform task for a project with the property and none without; the rewrite plugin and the classpath check task run in real Gradle builds with the sample project; a transform run compiles an app and checks the rewritten classes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/AndroidIDEGradlePlugin.kt | 10 + .../gradle/SqliteRewriteBuildTest.kt | 51 +++++ .../gradle/SqliteRewritePluginTest.kt | 172 +++++++++++++++++ .../gradle/SqliteRewriteTransformTest.kt | 175 ++++++++++++++++++ 4 files changed, 408 insertions(+) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteBuildTest.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt index 0a880dfeff..598b4d9259 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt @@ -16,10 +16,12 @@ */ package com.itsaky.androidide.gradle +import com.itsaky.androidide.gradle.sqlite.SqliteRewritePlugin import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_JDWP_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_LOG_SENDER_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_PROFILEABLE_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_QUICK_BUILD_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project @@ -55,6 +57,14 @@ class AndroidIDEGradlePlugin : Plugin { pluginManager.apply(LogSenderPlugin::class.java) } + // One opt-in for both (D13): the rewrite moves the app to requery in every variant, the + // debugger needs requery and goes into the debuggable variants only. + val isSqliteDebuggerEnabled = findProperty(PROPERTY_SQLITE_DEBUGGER_ENABLED) == "true" + if (isSqliteDebuggerEnabled) { + pluginManager.apply(SqliteRewritePlugin::class.java) + pluginManager.apply(SqliteDebuggerPlugin::class.java) + } + val isJdwpEnabled = findProperty(PROPERTY_JDWP_ENABLED) == "true" if (isJdwpEnabled) { pluginManager.apply(JdwpPlugin::class.java) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteBuildTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteBuildTest.kt new file mode 100644 index 0000000000..e3915e03e1 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteBuildTest.kt @@ -0,0 +1,51 @@ +package com.itsaky.androidide.gradle + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File + +/** + * The class rewrite (ADFA-7138) is registered only for projects that opt in: without requery in + * the app the rewritten classes cannot load. AGP schedules an ASM transform task per variant + * exactly when a class visitor is registered, so `--dry-run` tells the two cases apart without + * compiling the sample app. + */ +class SqliteRewriteBuildTest { + @Test + fun `a project with the property gets the class transform and one without does not`( + @TempDir dir: File, + ) { + // The same property also adds the debugger, which needs its AAR; --dry-run never reads it. + val aar = File(dir, "sqlite-debugger-release.aar").apply { writeText("aar") } + val runtimeAar = File(dir, "sqlite-rewrite-runtime-release.aar").apply { writeText("aar") } + val enabled = + buildProject( + task = ":app:assembleDemoDebug", + configureArgs = { + it.add("-P$PROPERTY_SQLITE_DEBUGGER_ENABLED=true") + it.add("-P$PROPERTY_SQLITE_DEBUGGER_AAR=${aar.absolutePath}") + it.add("-P$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR=${runtimeAar.absolutePath}") + it.add("--dry-run") + }, + ) + val disabled = + buildProject( + task = ":app:assembleDemoDebug", + configureArgs = { it.add("--dry-run") }, + ) + + assertThat(enabled.output).contains("transformDemoDebugClassesWithAsm") + // the classpath check runs before the compile and the rewrite of its variant + val lines = enabled.output.lines() + val check = lines.indexOfFirst { it.contains("checkDemoDebugSqliteRewriteClasspath") } + assertThat(check).isAtLeast(0) + assertThat(check).isLessThan(lines.indexOfFirst { it.contains("transformDemoDebugClassesWithAsm") }) + assertThat(check).isLessThan(lines.indexOfFirst { it.contains("compileDemoDebugJavaWithJavac") }) + assertThat(disabled.output).doesNotContain("ClassesWithAsm") + assertThat(disabled.output).doesNotContain("SqliteRewriteClasspath") + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt new file mode 100644 index 0000000000..03924efb01 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt @@ -0,0 +1,172 @@ +package com.itsaky.androidide.gradle + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.gradle.sqlite.CheckSqliteRewriteClasspathTask +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR +import org.gradle.testkit.runner.BuildResult +import org.gradle.testkit.runner.TaskOutcome +import org.gradle.testkit.runner.UnexpectedBuildResultException +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File +import java.nio.file.Path + +/** + * The helpers the rewritten classes call (ADFA-7138) are injected by Code on the Go into every variant of a + * project that opted in, and a per-variant task checks that requery and androidx.sqlite are on the + * runtime classpath before anything is compiled. + */ +class SqliteRewritePluginTest { + private val runtimeAarName = "sqlite-rewrite-runtime-release.aar" + private val allVariants = listOf("demoDebug", "fullDebug", "demoRelease", "fullRelease") + private val requeryEntry = CheckSqliteRewriteClasspathTask.REQUERY_ENTRY + private val androidxSqliteEntry = CheckSqliteRewriteClasspathTask.ANDROIDX_SQLITE_ENTRY + + private fun build( + dir: File, + task: String, + enabled: String? = "true", + runtimeAar: File? = File(dir, runtimeAarName).apply { writeText("aar") }, + project: Path? = null, + extraArgs: List = emptyList(), + ): BuildResult { + val debuggerAar = File(dir, "sqlite-debugger-release.aar").apply { writeText("aar") } + return buildProject(task = task, projectDir = project, configureArgs = { + if (task == ":app:printRuntimeDeps") { + it += "--init-script" + it += printDepsInitScript(dir).absolutePath + } + if (enabled != null) it += "-P$PROPERTY_SQLITE_DEBUGGER_ENABLED=$enabled" + it += "-P$PROPERTY_SQLITE_DEBUGGER_AAR=${debuggerAar.absolutePath}" + if (runtimeAar != null) it += "-P$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR=${runtimeAar.absolutePath}" + it += extraArgs + }) + } + + private fun BuildResult.declared(variant: String) = output.lines().filter { it.startsWith("RTDEP $variant ") } + + private fun failureOf(block: () -> BuildResult): String { + val failure = runCatching(block).exceptionOrNull() + assertThat(failure).isInstanceOf(UnexpectedBuildResultException::class.java) + return failure!!.message!! + } + + @Test + fun `the helper AAR is added to every variant when opted in, not only the debuggable ones`( + @TempDir dir: File, + ) { + val result = build(dir, ":app:printRuntimeDeps") + + for (variant in allVariants) { + assertThat(result.declared(variant)).contains("RTDEP $variant file $runtimeAarName") + assertThat(result.output).contains("Adding SQLite rewrite runtime dependency to variant '$variant' of project ':app'") + } + } + + @Test + fun `a project that did not opt in gets no helper AAR and no check`( + @TempDir dir: File, + ) { + for (enabled in listOf(null, "false")) { + val result = build(dir, ":app:printRuntimeDeps", enabled) + + for (variant in allVariants) { + assertThat(result.declared(variant).filter { it.contains(runtimeAarName) }).isEmpty() + } + assertThat(result.output).doesNotContain("Adding SQLite rewrite runtime dependency") + } + } + + @Test + fun `opted in without the helper AAR property fails the build and says how to fix it`( + @TempDir dir: File, + ) { + val message = failureOf { build(dir, ":app:printRuntimeDeps", runtimeAar = null) } + + assertThat(message).contains("no property '$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR' is set") + assertThat(message).contains("Remove the line from gradle.properties") + } + + @Test + fun `opted in with a missing helper AAR file fails the build and says how to fix it`( + @TempDir dir: File, + ) { + val message = failureOf { build(dir, ":app:printRuntimeDeps", runtimeAar = File(dir, "absent.aar")) } + + assertThat(message).contains("SQLite rewrite runtime AAR not found") + assertThat(message).contains("Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties") + } + + private fun jar( + dir: File, + name: String, + vararg entries: String, + ) = standIn(File(dir, "libs/$name"), *entries.map { it to ByteArray(0) }.toTypedArray()) + + private fun project( + dir: File, + script: String, + ) = copySampleProject(dir, script) + + @Test + fun `the check fails without requery on the runtime classpath and says how to add it`( + @TempDir dir: File, + ) { + val project = project(dir, "") + val message = failureOf { build(dir, ":app:checkDemoDebugSqliteRewriteClasspath", project = project) } + + assertThat(message).contains("variant 'demoDebug'") + assertThat(message).contains(requeryEntry) + assertThat(message).doesNotContain(androidxSqliteEntry) + assertThat(message).contains("file dependency") + assertThat(message).contains("brings none of its own dependencies") + } + + @Test + fun `the check fails without androidx sqlite, which requery's file dependency does not bring`( + @TempDir dir: File, + ) { + val requery = jar(dir, "requery.jar", requeryEntry) + val project = + project( + dir, + """ + configurations.all { exclude(group = "androidx.sqlite") } + dependencies { implementation(files("${requery.invariantSeparatorsPath}")) } + """.trimIndent(), + ) + val message = failureOf { build(dir, ":app:checkDemoDebugSqliteRewriteClasspath", project = project) } + + assertThat(message).contains(androidxSqliteEntry) + assertThat(message).doesNotContain("requery's SQLiteDatabase") + } + + @Test + fun `the check passes with stand-in jars that contain the two class entries, and is reused from the configuration cache`( + @TempDir dir: File, + ) { + val requery = jar(dir, "requery.jar", requeryEntry) + val sqlite = jar(dir, "sqlite.jar", androidxSqliteEntry) + val project = + project( + dir, + """ + configurations.all { exclude(group = "androidx.sqlite") } + dependencies { + implementation(files("${requery.invariantSeparatorsPath}")) + implementation(files("${sqlite.invariantSeparatorsPath}")) + } + """.trimIndent(), + ) + val first = + build(dir, ":app:checkDemoDebugSqliteRewriteClasspath", project = project, extraArgs = listOf("--configuration-cache")) + assertThat(first.task(":app:checkDemoDebugSqliteRewriteClasspath")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) + + val second = + build(dir, ":app:checkDemoDebugSqliteRewriteClasspath", project = project, extraArgs = listOf("--configuration-cache")) + assertThat(second.output).contains("Reusing configuration cache") + assertThat(second.task(":app:checkDemoDebugSqliteRewriteClasspath")!!.outcome).isEqualTo(TaskOutcome.UP_TO_DATE) + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt new file mode 100644 index 0000000000..b392f5da73 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt @@ -0,0 +1,175 @@ +@file:Suppress("ktlint:standard:max-line-length") + +package com.itsaky.androidide.gradle + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.gradle.sqlite.Compiler +import com.itsaky.androidide.gradle.sqlite.JavaSource +import com.itsaky.androidide.gradle.sqlite.TestJars +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR +import com.itsaky.androidide.utils.FileProvider +import org.gradle.testkit.runner.TaskOutcome +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.objectweb.asm.ClassReader +import org.objectweb.asm.tree.ClassNode +import org.objectweb.asm.tree.MethodInsnNode +import java.io.ByteArrayOutputStream +import java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream + +/** + * A real build, not a dry run: AGP runs the ASM transform of a variant over a class in a local AAR, and the + * transformed class refers to requery. The check of the classpath passes because stand-in jars hold the class + * entries it looks for; nothing loads them. + */ +class SqliteRewriteTransformTest { + private fun classesJar(classes: Map): ByteArray { + val bytes = ByteArrayOutputStream() + ZipOutputStream(bytes).use { zip -> + zip.putNextEntry(ZipEntry("META-INF/stand-in")) + zip.closeEntry() + for ((name, content) in classes) { + zip.putNextEntry(ZipEntry("$name.class")) + zip.write(content) + zip.closeEntry() + } + } + return bytes.toByteArray() + } + + private fun aar( + file: File, + namespace: String, + classes: Map, + ): File = + standIn( + file, + "AndroidManifest.xml" to + "".toByteArray(), + "R.txt" to ByteArray(0), + "classes.jar" to classesJar(classes), + ) + + /** + * AGP instruments the classes of dependencies with artifact transforms, which the dex builder triggers, not + * in the variant's transform task, so the output is in Gradle's transform cache: the jars that hold [entry]. The class of this run + * has a name no earlier run used, so a hit is this run's. + */ + private fun transformedJarsWith(entry: String): List { + val cache = FileProvider.projectRoot().resolve("gradle-plugin/build/tmp/test/work/.gradle-test-kit/caches").toFile() + return cache + .walkTopDown() + .filter { it.extension == "jar" && "/transforms/" in it.path } + .mapNotNull { jar -> + runCatching { ZipFile(jar).use { zip -> zip.getEntry(entry)?.let { zip.getInputStream(it).readBytes() } } }.getOrNull() + }.toList() + } + + @Test + fun `AGP's transform rewrites a class of a local AAR to call requery with Object arrays`( + @TempDir dir: File, + ) { + val daoName = "Dao${System.nanoTime()}" + val library = + Compiler.compile( + listOf( + JavaSource( + "x.lib.$daoName", + "package x.lib; public class $daoName { public Object q(android.database.sqlite.SQLiteDatabase db, String[] a) { return db.rawQuery(\"select 1\", a); } }", + ), + ), + ) + val helperSource = + FileProvider + .projectRoot() + .resolve("subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java") + .toFile() + val helper = + Compiler.compile( + listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText())), + listOf(TestJars.androidJar, TestJars.androidxCoreJar), + ) + val libAar = aar(File(dir, "libs/x.aar"), "x.lib", library) + val runtimeAar = aar(File(dir, "sqlite-rewrite-runtime-release.aar"), "org.appdevforall.sqliterewrite", helper) + // real, empty classes: the dex builder reads them + val requery = + standIn( + File(dir, "libs/requery.jar"), + *Compiler + .compile( + listOf( + JavaSource( + "io.requery.android.database.sqlite.SQLiteDatabase", + "package io.requery.android.database.sqlite; public class SQLiteDatabase {}", + ), + ), + ).map { (name, bytes) -> "$name.class" to bytes } + .toTypedArray(), + ) + // the debugger goes into the debug variants with the rewrite, and AGP reads its manifest + val debuggerAar = aar(File(dir, "sqlite-debugger-release.aar"), "org.appdevforall.sqlitedebugger", emptyMap()) + val project = + copySampleProject( + dir, + """ + // the sample compiles against 33, which AGP's AAR metadata check rejects for its own view binding + android { compileSdk = 36 } + dependencies { + implementation(files("${libAar.invariantSeparatorsPath}")) + implementation(files("${requery.invariantSeparatorsPath}")) + } + """.trimIndent(), + ) + + val result = + buildProject( + task = ":app:dexBuilderDemoDebug", + projectDir = project, + configureArgs = { + it += "-P$PROPERTY_SQLITE_DEBUGGER_ENABLED=true" + it += "-P$PROPERTY_SQLITE_DEBUGGER_AAR=${debuggerAar.absolutePath}" + it += "-P$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR=${runtimeAar.absolutePath}" + }, + ) + + assertThat(result.task(":app:checkDemoDebugSqliteRewriteClasspath")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) + assertThat(result.task(":app:transformDemoDebugClassesWithAsm")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) + + // the unmodified copy from extracting the AAR is in the cache too; the rewritten one is the other + val daos = transformedJarsWith("x/lib/$daoName.class").map { bytes -> ClassNode().also { ClassReader(bytes).accept(it, 0) } } + assertThat(daos).isNotEmpty() + val rewritten = + daos.filter { dao -> + dao.methods + .first { it.name == "q" } + .instructions + .filterIsInstance() + .any { it.owner.startsWith("io/requery/") } + } + assertThat(rewritten).isNotEmpty() + val q = rewritten.first().methods.first { it.name == "q" } + val call = q.instructions.filterIsInstance().first { it.name == "rawQuery" } + assertThat(call.owner).isEqualTo("io/requery/android/database/sqlite/SQLiteDatabase") + assertThat(call.desc).isEqualTo("(Ljava/lang/String;[Ljava/lang/Object;)Landroid/database/Cursor;") + assertThat(q.desc).isEqualTo("(Lio/requery/android/database/sqlite/SQLiteDatabase;[Ljava/lang/String;)Ljava/lang/Object;") + + // the injected helper AAR goes through the same transform: its class is rewritten to requery too + val helpers = + transformedJarsWith("org/appdevforall/sqliterewrite/SqliteRewriteRuntime.class") + .map { bytes -> ClassNode().also { ClassReader(bytes).accept(it, 0) } } + assertThat(helpers).isNotEmpty() + assertThat( + helpers.any { helper -> + helper.methods.any { method -> + "io/requery/" in method.desc || + method.instructions.filterIsInstance().any { it.owner.startsWith("io/requery/") } + } + }, + ).isTrue() + } +} From 9dc56f06f686f807b229ec46d837369543d84aca Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:06:02 -0800 Subject: [PATCH 058/203] ADFA-7138 Do not apply or provision Quick Build for a project that opted into the debugger Quick Build ships edited classes as a separate payload, compiled by its own daemon from the project's source, so it never passes through the SQLite rewrite. Mixed with rewritten baseline classes it would hand android.database.sqlite objects to requery ones. - AndroidIDEGradlePlugin does not apply Quick Build to an opted-in project and logs why. - GradleQuickBuildProvisioner refuses before staging, which writes into the project, and the IDE shows a string saying why, instead of ending in "variant setup missing". - ComponentProxiabilityResolver keeps DebuggerStartup in its by-name list as a guard only. Tests: SqliteDebuggerPluginTest checks which variants get the debugger AAR, with the property absent and set, and that Quick Build is not applied; QuickBuildProjectSupport decides the opt-in from gradle.properties as the Gradle plugin does (root file read, missing file is no opt-in); the provisioner refuses before staging with its own message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 16 +- .../quickbuild/QuickBuildProjectSupport.kt | 44 ++++++ ...dleQuickBuildProvisionerFailureArmsTest.kt | 20 +++ .../QuickBuildProjectSupportTest.kt | 34 +++++ .../gradle/AndroidIDEGradlePlugin.kt | 14 +- .../ComponentProxiabilityResolver.kt | 4 + .../gradle/SqliteDebuggerPluginTest.kt | 142 ++++++++++++++++++ .../ComponentProxiabilityResolverTest.kt | 2 + resources/src/main/res/values/strings.xml | 1 + 9 files changed, 274 insertions(+), 3 deletions(-) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 7b616cfc23..ae0c963fd9 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -340,11 +340,23 @@ class GradleQuickBuildProvisioner( log.info("A Gradle build is already in progress; not staging for the Quick Build proxy app build") return ProxyAppBuildResult.SlotBusy } - stage(context, paths) - val projectManager = lookupProjectManager() val projectRoot = File(projectManager.projectDirPath) + // Before staging, which writes into the project: the Gradle plugin never applies Quick Build + // to an opted-in project, so building would only end in "variant setup missing". + QuickBuildProjectSupport + .sqliteDebuggerMessage(QuickBuildProjectSupport.isSqliteDebuggerEnabled(projectRoot)) + ?.let { refusal -> + log.info( + "Quick Build is not provisioned: {} is true in {}/gradle.properties", + GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, + projectRoot, + ) + return ProxyAppBuildResult.Failed(context.getString(refusal)) + } + stage(context, paths) + // The project model only exists once CoGo's Gradle sync has populated it, and a tap // during sync is common (the user opens a project and reaches straight for Quick // Build). Queue behind the sync rather than failing: the session is already in diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt index bdef298fd4..89728f2f6c 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt @@ -2,6 +2,10 @@ package com.itsaky.androidide.quickbuild import androidx.annotation.StringRes import com.itsaky.androidide.resources.R +import com.itsaky.androidide.tooling.api.GradlePluginConfig +import java.io.File +import java.io.StringReader +import java.util.Properties /** * The reasons Quick Build refuses a project up front, as string resources. @@ -61,4 +65,44 @@ object QuickBuildProjectSupport { } else { null } + + /** + * A project with `cogo.sqliteDebugger=true` is moved to requery by the Gradle plugin, which + * never applies Quick Build to it (its payload would compile the source without the move). The + * IDE must not provision it either: the build would succeed and then end in a "variant setup + * missing" message that blames the variant. + * + * @param sqliteDebuggerEnabled see [isSqliteDebuggerEnabled]. + * @return the refusal message, or null when Quick Build may run. + */ + @StringRes + fun sqliteDebuggerMessage(sqliteDebuggerEnabled: Boolean): Int? = + if (sqliteDebuggerEnabled) { + R.string.quick_build_disabled_sqlite_debugger + } else { + null + } + + /** + * Whether the root `gradle.properties` text opts in, decided as the Gradle plugin does: the + * value is exactly `true`. + * + * @param gradleProperties the file's text, or null when the project has none. + */ + fun isSqliteDebuggerEnabled(gradleProperties: String?): Boolean { + if (gradleProperties == null) return false + val properties = Properties() + return try { + properties.load(StringReader(gradleProperties)) + properties.getProperty(GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED) == "true" + } catch (e: IllegalArgumentException) { + false + } + } + + /** [isSqliteDebuggerEnabled] for the `gradle.properties` in [projectRoot]; false when it cannot be read. */ + fun isSqliteDebuggerEnabled(projectRoot: File): Boolean = + isSqliteDebuggerEnabled( + runCatching { File(projectRoot, "gradle.properties").takeIf { it.isFile }?.readText() }.getOrNull(), + ) } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt index 168ca584de..dbb526cced 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt @@ -69,6 +69,26 @@ class GradleQuickBuildProvisionerFailureArmsTest { assertThat(gradle.executedTasks).isNull() } + @Test + fun `a project that opted into the SQLite debugger is refused before staging, with its own message`() = + runTest { + File(projectRoot, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + var staged = 0 + val gradle = FakeBuildService() + + val outcome = + testProvisioner( + context = context, + projectRoot = projectRoot, + buildService = gradle, + stage = { _, _ -> staged++ }, + ).provision() + + assertThat(failureText(outcome)).isEqualTo(context.getString(R.string.quick_build_disabled_sqlite_debugger)) + assertThat(staged).isEqualTo(0) + assertThat(gradle.executedTasks).isNull() + } + @Test fun `a slot that goes busy between the staging and the build still reads as a busy slot`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt index 0c3af40b4b..ae57986533 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt @@ -76,4 +76,38 @@ class QuickBuildProjectSupportTest { assertThat(QuickBuildProjectSupport.nonDebuggableVariantMessage("staging")).isNull() assertThat(QuickBuildProjectSupport.nonDebuggableVariantMessage("demoStaging")).isNull() } + + @Test + fun `an opted-in SQLite debugger project is refused with its own message`() { + assertThat(QuickBuildProjectSupport.sqliteDebuggerMessage(sqliteDebuggerEnabled = true)) + .isEqualTo(R.string.quick_build_disabled_sqlite_debugger) + assertThat(QuickBuildProjectSupport.sqliteDebuggerMessage(sqliteDebuggerEnabled = false)).isNull() + } + + @Test + fun `gradle properties decide the opt-in as the Gradle plugin does`() { + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("org.gradle.jvmargs=-Xmx2g\ncogo.sqliteDebugger=true\n")).isTrue() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebugger = true")).isTrue() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("#cogo.sqliteDebugger=true")).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebugger=false")).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebugger=TRUE")).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebuggerX=true")).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("")).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(null as String?)).isFalse() + } + + @Test + fun `the root gradle properties file is read, a missing one is not an opt-in`() { + val dir = + java.nio.file.Files + .createTempDirectory("qb-sqlite") + .toFile() + try { + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(dir)).isFalse() + java.io.File(dir, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(dir)).isTrue() + } finally { + dir.deleteRecursively() + } + } } diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt index 598b4d9259..d82dce3507 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/AndroidIDEGradlePlugin.kt @@ -44,6 +44,16 @@ class AndroidIDEGradlePlugin : Plugin { * `QuickBuildPluginTest`. */ internal const val QUICK_BUILD_PLUGIN_CLASS = "com.itsaky.androidide.gradle.QuickBuildPlugin" + + /** + * Quick Build ships edited classes as a separate payload, compiled by its own daemon from the + * project's source and so never passed through the SQLite rewrite. Mixed with rewritten + * baseline classes it would hand android.database.sqlite objects to requery ones. + */ + internal const val QUICK_BUILD_SQLITE_DEBUGGER_MESSAGE = + "Quick Build is not applied: cogo.sqliteDebugger=true moves the app to requery at build time, " + + "and Quick Build's hot payload is compiled separately and would still use android.database.sqlite. " + + "Building normally; use a Standard Run, or remove the property to use Quick Build." } override fun apply(target: Project) { @@ -76,7 +86,9 @@ class AndroidIDEGradlePlugin : Plugin { } val isQuickBuildEnabled = findProperty(PROPERTY_QUICK_BUILD_ENABLED) == "true" - if (isQuickBuildEnabled) { + if (isQuickBuildEnabled && isSqliteDebuggerEnabled) { + logger.lifecycle(QUICK_BUILD_SQLITE_DEBUGGER_MESSAGE) + } else if (isQuickBuildEnabled) { // By name, not ::class: Quick Build classes load (and touch newer AGP APIs) // only when the property enables them - see QUICK_BUILD_PLUGIN_CLASS. pluginManager.apply(Class.forName(QUICK_BUILD_PLUGIN_CLASS)) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolver.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolver.kt index ba9e0201f2..b8f22e4967 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolver.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolver.kt @@ -120,6 +120,10 @@ class ComponentProxiabilityResolver( "com.itsaky.androidide.quickbuild.runtime.QuickBuildKeepAliveService" to "the quick-build runtime's own keep-alive, not user code; skipping keeps it out " + "of the component list and the deploy policy's restart rule", + // Guard only: AndroidIDEGradlePlugin never applies Quick Build to a project that opted into the SQLite debugger. + "org.appdevforall.sqlitedebugger.DebuggerStartup" to + "CoGo's injected SQLite debugger provider (ADFA-7131); it runs once from the base APK dex, " + + "and skipping keeps it out of the component list and the deploy policy's restart rule", "com.google.firebase.components.ComponentDiscoveryService" to "Firebase plumbing whose class never travels in the payload; skipping keeps it out " + "of the component list and the deploy policy's restart rule", diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt new file mode 100644 index 0000000000..edb4bc1cc1 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt @@ -0,0 +1,142 @@ +package com.itsaky.androidide.gradle + +import com.android.build.api.variant.ApplicationVariant +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_QUICK_BUILD_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_QUICK_BUILD_RUNTIME_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR +import org.adfa.constants.KOTLIN_VERSION +import org.gradle.testkit.runner.BuildResult +import org.gradle.testkit.runner.UnexpectedBuildResultException +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File +import java.lang.reflect.Proxy + +/** + * The SQLite debugger (ADFA-7131) reaches the debuggable variants' runtime classpath, and only + * when the project opts in. The fixture project has the debuggable `demoDebug`/`fullDebug` and the + * non-debuggable `demoRelease`/`fullRelease` variants. + */ +class SqliteDebuggerPluginTest { + private val aarName = "sqlite-debugger-release.aar" + private val stdlib = "org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION" + private val debugVariants = listOf("demoDebug", "fullDebug") + private val releaseVariants = listOf("demoRelease", "fullRelease") + + private fun build( + dir: File, + enabled: String?, + aar: File?, + quickBuildAar: File? = null, + runtimeAar: File? = File(dir, "sqlite-rewrite-runtime-release.aar").apply { writeText("aar") }, + ): BuildResult = + buildProject(task = ":app:printRuntimeDeps", configureArgs = { + it += "--init-script" + it += printDepsInitScript(dir).absolutePath + if (enabled != null) it += "-P$PROPERTY_SQLITE_DEBUGGER_ENABLED=$enabled" + if (aar != null) it += "-P$PROPERTY_SQLITE_DEBUGGER_AAR=${aar.absolutePath}" + if (runtimeAar != null) it += "-P$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR=${runtimeAar.absolutePath}" + if (quickBuildAar != null) { + it += "-P$PROPERTY_QUICK_BUILD_ENABLED=true" + it += "-P$PROPERTY_QUICK_BUILD_RUNTIME_AAR=${quickBuildAar.absolutePath}" + } + }) + + private fun BuildResult.declared(variant: String) = output.lines().filter { it.startsWith("RTDEP $variant ") } + + @Test + fun `enabled adds the AAR and kotlin-stdlib to debuggable variants only`( + @TempDir dir: File, + ) { + val aar = File(dir, aarName).apply { writeText("aar") } + val result = build(dir, "true", aar) + + assertThat(result.output).contains("Applying SqliteDebuggerPlugin to project ':app'") + for (variant in debugVariants) { + assertThat(result.declared(variant)).contains("RTDEP $variant file $aarName") + assertThat(result.declared(variant)).contains("RTDEP $variant $stdlib") + assertThat(result.output) + .contains("Adding SQLite debugger dependency to variant '$variant' of project ':app'") + } + for (variant in releaseVariants) { + // The fixture's own libraries declare other kotlin-stdlib versions in every variant + assertThat(result.declared(variant).filter { it.contains(aarName) || it.endsWith(stdlib) }) + .isEmpty() + assertThat(result.output) + .doesNotContain("Adding SQLite debugger dependency to variant '$variant' of project ':app'") + } + } + + @Test + fun `debuggable is read from the variant itself, not from a builder`() { + fun variant(debuggable: Boolean): ApplicationVariant = + Proxy.newProxyInstance( + ApplicationVariant::class.java.classLoader, + arrayOf(ApplicationVariant::class.java), + ) { _, method, _ -> + when (method.name) { + "getDebuggable" -> debuggable + else -> throw UnsupportedOperationException(method.name) + } + } as ApplicationVariant + + assertThat(SqliteDebuggerPlugin.readDebuggable(variant(true))).isTrue() + assertThat(SqliteDebuggerPlugin.readDebuggable(variant(false))).isFalse() + } + + @Test + fun `quick build is not applied to a project that opted into the debugger`( + @TempDir dir: File, + ) { + val aar = File(dir, aarName).apply { writeText("aar") } + val runtime = File(dir, "quickbuild-runtime.aar").apply { writeText("aar") } + + val withDebugger = build(dir, "true", aar, runtime) + assertThat(withDebugger.output).contains(AndroidIDEGradlePlugin.QUICK_BUILD_SQLITE_DEBUGGER_MESSAGE) + assertThat(withDebugger.output).doesNotContain("Configuring Quick Build for variant") + assertThat(withDebugger.output).contains("Adding SQLite debugger dependency to variant 'demoDebug'") + + // the control: without the opt-in the same invocation configures Quick Build + val without = build(dir, null, aar, runtime) + assertThat(without.output).doesNotContain(AndroidIDEGradlePlugin.QUICK_BUILD_SQLITE_DEBUGGER_MESSAGE) + assertThat(without.output).contains("Configuring Quick Build for variant") + } + + @Test + fun `a property that is not true adds nothing`( + @TempDir dir: File, + ) { + val aar = File(dir, aarName).apply { writeText("aar") } + for (enabled in listOf(null, "false")) { + val result = build(dir, enabled, aar) + + assertThat(result.output).doesNotContain("Applying SqliteDebuggerPlugin") + for (variant in debugVariants + releaseVariants) { + assertThat(result.declared(variant).filter { it.contains(aarName) }).isEmpty() + } + } + } + + @Test + fun `enabled without the AAR property fails the build and says how to fix it`( + @TempDir dir: File, + ) { + val failure = runCatching { build(dir, "true", null) }.exceptionOrNull() + + assertThat(failure).isInstanceOf(UnexpectedBuildResultException::class.java) + assertThat(failure!!.message).contains("no property '$PROPERTY_SQLITE_DEBUGGER_AAR' is set") + } + + @Test + fun `enabled with a missing AAR file fails the build and says how to fix it`( + @TempDir dir: File, + ) { + val failure = runCatching { build(dir, "true", File(dir, "absent.aar")) }.exceptionOrNull() + + assertThat(failure).isInstanceOf(UnexpectedBuildResultException::class.java) + assertThat(failure!!.message).contains("SQLite debugger AAR not found") + } +} diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolverTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolverTest.kt index f8e066361b..382f522096 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolverTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/quickbuild/ComponentProxiabilityResolverTest.kt @@ -78,6 +78,8 @@ class ComponentProxiabilityResolverTest { // library plumbing that must stay out of the component list and the restart rule. assertThat(resolver.resolve("com.google.firebase.components.ComponentDiscoveryService")) .isInstanceOf(ComponentProxiabilityResolver.Resolution.Skip::class.java) + assertThat(resolver.resolve("org.appdevforall.sqlitedebugger.DebuggerStartup")) + .isInstanceOf(ComponentProxiabilityResolver.Resolution.Skip::class.java) } @Test diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 49f1ed7302..ba8a7c439b 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1233,6 +1233,7 @@ Quick Build needs an Android app module, and this project has none. Quick Build needs a debuggable build variant, and \"%1$s\" is a release variant. Open Build Variants in the sidebar and select a debug variant. Quick Build could not set up \"%1$s\". If that variant is not debuggable, open Build Variants in the sidebar and select a debug variant. + Quick Build is off while the SQLite debugger is on (cogo.sqliteDebugger=true in gradle.properties), because it would compile your source without the move to requery. Use Run to build the app, or remove that line to use Quick Build. Quick Build setup failed. Check the Build Output for what went wrong. Another build is running. Wait for it to finish, then start Quick Build again. Quick Build could not rebuild your app. Check the Build Output for what went wrong. From dd570d45f5d616049a47ee6fde7ea03b3f1904f6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:06:03 -0800 Subject: [PATCH 059/203] ADFA-7138 Add a script that checks an APK carries no SQLite debugger scripts/check-release-apk-no-sqlite-debugger.sh fails when an APK holds libsqlitedbg.so, the DebuggerStartup provider, the entry for Code on the Go, or the debugger's class prefix in any dex, so a release build can be checked by script (acceptance criteria 2 and 3). INTERNET is only a warning line: the app may declare it for itself. It runs with pipefail and reads the APK with unzip and aapt2. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../check-release-apk-no-sqlite-debugger.sh | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100755 scripts/check-release-apk-no-sqlite-debugger.sh diff --git a/scripts/check-release-apk-no-sqlite-debugger.sh b/scripts/check-release-apk-no-sqlite-debugger.sh new file mode 100755 index 0000000000..5e25938e5e --- /dev/null +++ b/scripts/check-release-apk-no-sqlite-debugger.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# Usage: check-release-apk-no-sqlite-debugger.sh +# +# Fails (exit 1, one line per finding) when an APK carries the SQLite debugger (ADFA-7131): +# - a lib//libsqlitedbg.so entry, +# - the provider org.appdevforall.sqlitedebugger.DebuggerStartup in the manifest, +# - a package com.itsaky.androidide in the manifest, +# - the class descriptor prefix Lorg/appdevforall/sqlitedebugger/ in any classes*.dex. +# INTERNET is only a WARNING line, not a failure: the app may declare it for itself, and the +# manifest cannot say which declaration it came from. Without the provider above, treat the +# warning as the app's own. +# Exit 2 on bad usage or when aapt2, unzip or the APK cannot be found. +# +# aapt2 comes from $AAPT2, else the newest build-tools under $ANDROID_HOME / $ANDROID_SDK_ROOT +# / ~/Android/Sdk. + +set -u +set -o pipefail + +if [ $# -ne 1 ] || [ ! -f "$1" ]; then + echo "usage: $0 " >&2 + exit 2 +fi +apk=$1 + +if ! command -v unzip >/dev/null 2>&1; then + echo "unzip not found: install it to inspect the APK" >&2 + exit 2 +fi + +aapt2=${AAPT2:-} +if [ -z "$aapt2" ]; then + for sdk in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk"; do + [ -n "$sdk" ] || continue + candidate=$(ls -d "$sdk"/build-tools/*/aapt2 2>/dev/null | sort -V | tail -n 1) + if [ -n "$candidate" ]; then + aapt2=$candidate + break + fi + done +fi +if [ -z "$aapt2" ] || [ ! -x "$aapt2" ]; then + echo "aapt2 not found: set AAPT2 or ANDROID_HOME" >&2 + exit 2 +fi + +manifest=$("$aapt2" dump xmltree --file AndroidManifest.xml "$apk" 2>&1) || { + echo "cannot read the manifest of $apk: $manifest" >&2 + exit 2 +} + +failed=0 +fail() { + echo "FAIL: $1" + failed=1 +} + +libs=$(unzip -Z1 "$apk" | grep -E '^lib/[^/]+/libsqlitedbg\.so$' || true) +for entry in $libs; do + fail "native library $entry" +done + +if grep -q 'org\.appdevforall\.sqlitedebugger\.DebuggerStartup' <<<"$manifest"; then + fail "manifest declares provider org.appdevforall.sqlitedebugger.DebuggerStartup" +fi + +# xmltree indents children deeper than their parent: collect the lines under , then look +# at the name of its children. +if awk ' + { match($0, /^ */); indent = RLENGTH } + /E: queries / { inq = 1; qindent = indent; next } + inq && indent <= qindent { inq = 0 } + inq && /E: package / { pkg = 1; next } + inq && /E: / { pkg = 0 } + inq && pkg && /:name\(.*"com\.itsaky\.androidide"/ { found = 1 } + END { exit !found } +' <<<"$manifest"; then + fail "manifest lists package com.itsaky.androidide" +fi + +# A dex stores type descriptors as plain strings, so a debugger class that got in shows up here even when +# the manifest is clean (a library that registers nothing). +# grep -c reads all its input: with pipefail, grep -q exiting early would make unzip die of SIGPIPE +# and the pipeline report failure. +dex_hits=$(unzip -p "$apk" 'classes*.dex' 2>/dev/null | grep -ac 'Lorg/appdevforall/sqlitedebugger/' || true) +if [ "${dex_hits:-0}" -gt 0 ]; then + fail "a classes*.dex contains org.appdevforall.sqlitedebugger classes" +fi + +if grep -q 'android.permission.INTERNET' <<<"$manifest"; then + echo "WARN: manifest has android.permission.INTERNET. It comes from the debugger only if the provider DebuggerStartup is also present (that is a FAIL above); otherwise it is the app's own." +fi + +if [ "$failed" -eq 0 ]; then + echo "OK: no SQLite debugger found in $apk" +fi +exit "$failed" From 4a9bc950b5228c03f7b0ce3e0199d060915c7003 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:06:03 -0800 Subject: [PATCH 060/203] ADFA-7138 Docs: describe the SQLite rewrite and the Gradle wiring gradle-plugin/docs/sqlite-rewrite.md explains the rewrite: what it renames and redirects, what it rejects, the Spike 0 survey result, the helper and debugger AAR wiring, the Quick Build exclusion and the APK check. The sqlite-debugger README, CLAUDE.md and ARCHITECTURE.md list the new module and point to it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- ARCHITECTURE.md | 5 +- CLAUDE.md | 4 +- gradle-plugin/docs/sqlite-rewrite.md | 171 ++++++++++++++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 4 files changed, 177 insertions(+), 5 deletions(-) create mode 100644 gradle-plugin/docs/sqlite-rewrite.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e8247b2966..7009784bce 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -95,7 +95,7 @@ Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle buil - **`app` depends inward; libraries never depend on `app`.** Subsystems are consumed by `app`, not vice versa. - **Vendored forks are substituted, not imported ad hoc.** `composite-builds/build-deps` and `build-deps-common` provide forked `javac`/`jdt`/`layoutlib`/etc.; `settings.gradle.kts` substitutes them in for `com.itsaky.androidide.build:*`. Don't add a Maven coordinate for something already substituted. Pebble is likewise built from source, as `subprojects:pebble`, for a lexer fix Android needs (its `NOTICE` says what changed); depend on `projects.subprojects.pebble`, not `io.pebbletemplates:pebble`. -- **All module config flows through `composite-builds/build-logic`.** Every Android module gets the `v7`/`v8` ABI flavors centrally (`AndroidModuleConf.kt`) — there is no flavorless `assembleDebug`. `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger`, libraries for other projects that need one artifact, are intentionally excluded from flavors. +- **All module config flows through `composite-builds/build-logic`.** Every Android module gets the `v7`/`v8` ABI flavors centrally (`AndroidModuleConf.kt`) — there is no flavorless `assembleDebug`. `:plugin-api`, `:subprojects:sqlite-js`, `:subprojects:sqlite-debugger` and `:subprojects:sqlite-rewrite-runtime`, libraries for other projects that need one artifact, are intentionally excluded from flavors. - **`RepositoriesMode.FAIL_ON_PROJECT_REPOS`** — repositories are declared once in `settings.gradle.kts`; modules must not declare their own. - **Avoid new dependencies.** Check `gradle/libs.versions.toml` first; the build almost certainly already has it. @@ -104,11 +104,12 @@ Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle buil These structural facts shape every module. Day-to-day build *commands* live in `CLAUDE.md`; the rules that produce them live here. - **Centralized convention logic.** All Android module setup flows through `composite-builds/build-logic` (`conf/AndroidModuleConf.kt`). Modules stay thin and share configuration, so understanding any module's setup starts here. -- **ABI product flavors.** Every Android module *except* `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. +- **ABI product flavors.** Every Android module *except* `:plugin-api`, `:subprojects:sqlite-js`, `:subprojects:sqlite-debugger` and `:subprojects:sqlite-rewrite-runtime` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: sqlite-js vendored with our patches (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. - **SQLite debugger for apps built with CoGo** (ADFA-7131). `subprojects:sqlite-debugger` builds an AAR with a debug-only SQLite debugger and MCP server for apps built with CoGo: a native extension on requery's SQLite plus a loopback HTTP server. Like sqlite-js it has no ABI flavors, and nothing in CoGo depends on it; see its README. +- **AARs bundled for apps built with CoGo.** `:logsender`, `:subprojects:sqlite-debugger` and `:subprojects:sqlite-rewrite-runtime` are built as AARs and bundled into the IDE's assets (`AndroidIDEAssetsPlugin`). Code on the Go extracts them and passes their paths to Gradle as properties, and its Gradle plugin injects each into the app: logsender and the debugger into debuggable variants, the rewrite runtime into every variant of a project with `cogo.sqliteDebugger=true`. `:subprojects:sqlite-rewrite-runtime` is Java-only, has no ABI flavors and holds the helpers the build-time rewrite to requery redirects to (ADFA-7138); see `gradle-plugin/docs/sqlite-rewrite.md`. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). - **`app` package layout is by concern, not feature:** `activities`, `fragments`, `services`, `di`, `agent`, `viewmodel(s)`, `repositories`, `roomData`, `localWebServer`, `preferences`, `ui` (Compose screens live under `ui/compose`), `templates/manager` (the Manager screen's `.cgt`-parsing data layer, with direct filesystem access to `Environment.TEMPLATES_DIR` — distinct from the plugin-facing `IdeTemplateService` in `plugin-api`/`plugin-manager`), `utils`, …. diff --git a/CLAUDE.md b/CLAUDE.md index 7334588a8c..1d9f9d7499 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,7 +15,7 @@ flox activate -d flox/local -- ./gradlew ``` - **Debug APK (arm64, the usual target):** `flox activate -d flox/local -- ./gradlew :app:assembleV8Debug --parallel --max-workers=6` -- **Module unit tests:** `flox activate -d flox/local -- ./gradlew :editor:testV7DebugUnitTest` - unit tests are per-flavor, there is no plain `test` task. `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger` are the modules without flavors: `:plugin-api:testDebugUnitTest`. +- **Module unit tests:** `flox activate -d flox/local -- ./gradlew :editor:testV7DebugUnitTest` - unit tests are per-flavor, there is no plain `test` task. `:plugin-api`, `:subprojects:sqlite-js`, `:subprojects:sqlite-debugger` and `:subprojects:sqlite-rewrite-runtime` are the modules without flavors: `:plugin-api:testDebugUnitTest`. - **Single unit test:** append `--tests "com.itsaky.androidide.SomeTest"` to the flavored task above. - **Fast iteration:** during multi-file/multi-module changes, verify with targeted `:module:compileV8DebugKotlin`/`compileV8DebugJavaWithJavac` invocations (batch several modules into one Gradle call) rather than a full assemble. Reserve `:app:assembleV8Debug` for final end-to-end verification — it's slow (multi-minute) in this multi-module project, and running it after every small change adds up. - **Long-running commands: narrate them, and background only the read-only ones.** Anything that can exceed ~60s — `assembleV8Debug`, a full test sweep, a cold Gradle invocation of any kind (daemon start plus configuring this many modules is ~20s before any task runs, and far worse under memory pressure), and `git push`, which runs Spotless through the hook — gets a line before it starts saying what is running and roughly how long it takes, and a status line every couple of minutes while it runs: elapsed time, the last output line, whether it is still progressing. A silent terminal is indistinguishable from a hang, and saying which it is is your job, not the user's to ask. @@ -26,7 +26,7 @@ When the user names a CI/CD job ("the sonar job", "the analyze workflow"), read ### ABI product flavors (v7 / v8) -Every module except `:plugin-api`, `:subprojects:sqlite-js` and `:subprojects:sqlite-debugger` carries `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) flavors, so build tasks are `assembleV8Debug`, `assembleV7Release`, etc. — there is **no** flavorless `assembleDebug`. Those three build one artifact for other projects. See [ARCHITECTURE.md](ARCHITECTURE.md) (Build & Module Configuration) for flavors, native asset bundling, and SDK levels. +Every module except `:plugin-api`, `:subprojects:sqlite-js`, `:subprojects:sqlite-debugger` and `:subprojects:sqlite-rewrite-runtime` carries `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) flavors, so build tasks are `assembleV8Debug`, `assembleV7Release`, etc. — there is **no** flavorless `assembleDebug`. Those four build one artifact for other projects. See [ARCHITECTURE.md](ARCHITECTURE.md) (Build & Module Configuration) for flavors, native asset bundling, and SDK levels. ### Emulator / device diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md new file mode 100644 index 0000000000..2b6cf2186e --- /dev/null +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -0,0 +1,171 @@ +# SQLite rewrite (ADFA-7138) + +When `cogo.sqliteDebugger=true`, the Gradle plugin registers an AGP class transform +(`com.itsaky.androidide.gradle.sqlite.SqliteRewriteVisitorFactory`, scope ALL, every variant) that moves +the app's and its libraries' classes from `android.database.sqlite` to requery 3.49.0, so debug and release +run the same SQLite. User source does not change. + +## Turning it on + +An existing project needs: + +1. `cogo.sqliteDebugger=true` in `gradle.properties`. +2. requery's AAR (`sqlite-android.aar`) in the app's `libs/`, as a file dependency + (`implementation(files("libs/sqlite-android.aar"))`), as the ADFA-7082 template does. +3. androidx.sqlite on the runtime classpath (`androidx.sqlite:sqlite`, which Room, WorkManager and most androidx + libraries bring). A file dependency brings none of the dependencies of the AAR, and requery implements + androidx.sqlite's interfaces. It also calls `androidx.core.os.CancellationSignal`, which AppCompat's + androidx.core provides. + +The helper classes the rewrite redirects to (`SqliteRewriteRuntime`) are not in `libs/`: Code on the Go bundles +`subprojects/sqlite-rewrite-runtime`'s release AAR, extracts it with the other tools and passes its path as +`androidide.sqliteRewriteRuntime.aar`, as it does for the debugger AAR. `SqliteRewritePlugin` adds it to the +runtime classpath of every variant of a project that opted in, and fails the build when the file is missing. + +A task `checkSqliteRewriteClasspath` runs before the compile and the transform of each variant. It fails +with an actionable message when the variant's runtime classpath has no +`io/requery/android/database/sqlite/SQLiteDatabase.class` or `androidx/sqlite/db/SupportSQLiteDatabase.class`. + +The property is required because requery reaches apps only through `libs/`. Without it the rewritten classes +cannot load, so the transform runs only on projects that opted in. Commenting the line out turns it off. + +## Rules + +- Rename: the 10 classes requery shares (`SQLiteClosable`, `SQLiteCursor`, `SQLiteCursorDriver`, + `SQLiteDatabase`, `SQLiteDatabase$CursorFactory`, `SQLiteOpenHelper`, `SQLiteProgram`, `SQLiteQuery`, + `SQLiteQueryBuilder`, `SQLiteStatement`) and `android.database.DatabaseErrorHandler` and + `DefaultDatabaseErrorHandler`. androidx's `FrameworkSQLiteOpenHelperFactory` is not renamed; see the design + change below. Kept: the exceptions, `SQLiteTransactionListener`, `android.database.Cursor`, `CursorWindow`. + Overrides count: a `SQLiteOpenHelper` subclass or a `SQLiteCursorDriver`/`CursorFactory` implementation + ends up with requery's descriptors. +- Descriptor: `String[]` becomes `Object[]` (selectionArgs) for `query`, `queryWithFactory`, `rawQuery`, + `rawQueryWithFactory` and `SQLiteCursorDriver.query`, in calls and in the override declaration. +- Redirect to `org.appdevforall.sqliterewrite.SqliteRewriteRuntime`: `SQLiteDatabase.openDatabase` with + flags (Android's flag values differ from requery's; the flags are compiled into the app), + `Context.openOrCreateDatabase` / `deleteDatabase` (INVOKEVIRTUAL on `Context` or a subclass; subclasses + are found with AGP's class loader, plus a fixed list of the framework ones), and an + `android.os.CancellationSignal` argument of a requery-bound call, converted right before the call (it + is always the last argument), and `android.database.DatabaseUtils.queryNumEntries`, `longForQuery` and + `stringForQuery` (every overload; requery has no `DatabaseUtils`, so the runtime carries Android's own + implementations, written against Android's types). +- Fail the build, naming class, method and line: a call to a member requery lacks (for example + `execPerConnectionSQL`, `setCustomScalarFunction`, `SQLiteQueryBuilder.isStrict`; also the deprecated cursor + members `SQLiteCursor` inherits from android's `AbstractCursor` and `AbstractWindowedCursor` that requery's + copies lack: `isBlob`, `isFloat`, `isLong`, `isString`, `getUpdatedField`, `isFieldUpdated`, + `getNotificationUris`, `setNotificationUris`, and the protected field `mWindow`; `SqliteRewriteResolutionTest` probes the inherited members of every + renamed class against requery), SQL text with `COLLATE UNICODE` (any case or whitespace, in any string + constant, which covers Room's generated `_Impl` classes: requery's native SQLite has no ICU, so the collation + does not exist), any use of + `SQLiteDatabase.OpenParams`, a call that passes android's `CursorWindow` to a renamed class (calls on + `CursorWindow` itself are fine), and a cast of + an SQLite cursor to `android.database.AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` + (requery's cursors extend its own copies of the first two, and implement only `android.database.Cursor`). + A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, + or an early return when it is false) is not reported. `COLLATE LOCALIZED` only logs a warning: it works, but + compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together. A platform method outside the renamed set whose + descriptor mentions a renamed class (found with javap over android.jar: the other `DatabaseUtils` methods + `blobFileDescriptorForQuery` and `bindObjectToProgram`, `DatabaseUtils$InsertHelper`, `OpenParams` + accessors) cannot link once the descriptor is renamed, so a call to one that is not redirected above fails + the build. `SqliteRewriteResolutionTest` probes every such member in android.jar. + A `Context.openOrCreateDatabase` / `deleteDatabase` call that cannot be redirected also fails the build: + `super.` calls (INVOKESPECIAL), calls whose owner class cannot be resolved (it might be a Context), and + a method with one of those signatures that overrides it in a Context subclass (the redirect would skip + the override). +- Method references: a handle in an invokedynamic (`db::rawQuery`, `ctx::deleteDatabase`) that any rule + above would change, redirect or reject fails the build, naming class, method and line, with the advice to + write a lambda (its body is an ordinary call, which the rules handle). The rules are not applied to the + handle itself: it cannot be redirected in place, and its descriptor is fixed by the call site. +- Frames: `COPY_FRAMES`, AGP's default. The one change that breaks them is a retyped + `SQLiteCursorDriver.query` implementation, whose `String[]` parameter becomes `Object[]` while its body, and + the full frames copied from it, still say `String[]`. For each non-abstract method whose descriptor is retyped + that way, the rewriter inserts `ALOAD n; CHECKCAST [Ljava/lang/String;; ASTORE n` at method entry, so the body + stays valid, and writes every frame of that method in full (compressed frames are relative to the implicit first + frame, which now has the wide type). A driver that is handed an `Object[]` with an element that is not a + `String` throws `ClassCastException` on entry; requery's own drivers pass strings. + +Excluded: `io.requery.**`. The helper's package is renamed only (a redirect would call itself). +`androidx.sqlite.db.framework.**` and `androidx.core.database.**` are rewritten but exempt from the fail rule: see +below, and androidx.core's `SQLiteCursorCompat$Api28Impl` calls `SQLiteCursor.setFillWindowForwardOnly`, which requery +lacks, so failing the build for it would fail every app that depends on androidx.core (found by the transform test +on androidx.core 1.9.0). Calling `SQLiteCursorCompat.setFillWindowForwardOnly` on requery's cursor throws +`NoSuchMethodError`. + +## Survey: what reaches Android's SQLite (androidx.sqlite framework 2.6.2, Room 2.8.4, WorkManager 2.10.0) + +| Where | Reference | Handling | +| --- | --- | --- | +| `RoomDatabase$Builder.build`, `PrePackagedCopyOpenHelper`, WorkManager's `WorkDatabase$Companion` | `new FrameworkSQLiteOpenHelperFactory` | kept: androidx's factory runs on requery through the renamed classes (design change below) | +| `FrameworkSQLiteDatabase`, `FrameworkSQLiteOpenHelper$OpenHelper`, `FrameworkSQLiteProgram`/`Statement` | every member of the renamed classes they use | all resolve in requery after the rules; `SqliteRewriteResolutionTest` transforms the real 2.6.2 framework classes, verifies them and resolves every reference (access and static-ness included) | +| `FrameworkSQLiteDatabase$Api30Impl` | `execPerConnectionSQL` (NO in requery's own class) | the only reference to a member requery lacks; it resolves to `SupportSQLiteDatabase`'s default method, which throws `UnsupportedOperationException` | +| `FrameworkSQLiteDatabase.query(.., CancellationSignal)` | `rawQueryWithFactory` with android's signal | signal converted | +| `FrameworkSQLiteOpenHelper$OpenHelper`, `PrePackagedCopyOpenHelper` | `Context.deleteDatabase`, `getDatabasePath` | redirect (`deleteDatabase`); `getDatabasePath` needs none | +| Room `DBUtil.query` | `instanceof` and cast to `AbstractWindowedCursor`, `CursorWindow.getNumRows` | untouched: the value comes from `SupportSQLiteDatabase.query`, not an SQLite API, and the cast is guarded by `instanceof`, which is false for requery's cursor (Room skips its copy optimisation) | +| Room `checkUniquenessException` | `SQLiteConstraintException` | kept class | +| `androidx.sqlite.driver.AndroidSQLiteDriver.open` | `SQLiteDatabase.openOrCreateDatabase(String, null)` and `new FrameworkSQLiteDatabase(SQLiteDatabase)` | works only if `FrameworkSQLiteDatabase` is rewritten too | + +### Design change (2026-11-13): androidx's factory stays + +The first version renamed `new FrameworkSQLiteOpenHelperFactory()` to requery's `RequerySQLiteOpenHelperFactory` +and excluded the factory class. That is dropped. requery's factory reads only the context, the name and the +callback of the `SupportSQLiteOpenHelper.Configuration` (checked with javap): it ignores `noBackupDirectory` and +`allowDataLossOnRecovery`, and has none of the framework's cross-process lock. WorkManager 2.10 sets the first +two, so its database would be recreated empty after `WorkDatabasePathHelper.migrateDatabase` on each start. + +Instead the androidx.sqlite framework classes (`androidx.sqlite.db.framework.*`, rewritten with the fail rule +off) run on requery through the normal rename and descriptor rules: `FrameworkSQLiteOpenHelper`, its inner +`OpenHelper` (a subclass of the renamed `SQLiteOpenHelper`), `FrameworkSQLiteDatabase`, `-Statement` and +`-Program` keep their behaviour, including the no-backup directory and the recovery flags, and call requery's +classes. They are not excluded, which also keeps `androidx.sqlite.driver.AndroidSQLiteDriver` working: it builds a +`FrameworkSQLiteDatabase` from a plain `SQLiteDatabase`. + +Every reference of these classes resolves in requery. The one member requery's own `SQLiteDatabase` lacks is +`execPerConnectionSQL`, which `FrameworkSQLiteDatabase$Api30Impl` calls; it resolves to the default method of +`SupportSQLiteDatabase` (checked with javap), which throws `UnsupportedOperationException`. So +`execPerConnectionSQL` through the `SupportSQLiteDatabase` interface stays unsupported, and the fail rule is off for +this package, so the build does not report it. + +## Checking a release APK + +`scripts/check-release-apk-no-sqlite-debugger.sh ` fails when an APK carries the debugger (native library, +provider, `` entry or classes). QA runs it on the release APK of an opted-in project: the release build must never contain the debugger. + +## Known limits + +- Room's `BundledSQLiteDriver` is not covered (it brings its own SQLite). +- requery's native library is built without ICU: there is no `UNICODE` collator (a `COLLATE UNICODE` string + constant fails the build, see above) and `LOCALIZED` compares bytes (a warning). +- `SupportSQLiteDatabase.execPerConnectionSQL` is unsupported (see the design change): no build failure, an + `UnsupportedOperationException` when called. +- Passing an Android `CursorWindow` where a (renamed) `SQLiteClosable` is expected cannot work: android's + `CursorWindow` extends android's `SQLiteClosable`, which stays the platform's class. Calls that name a + `CursorWindow` in a renamed class's descriptor fail the build; calls on a `CursorWindow` are left alone. +- The items below were reported by review and not verified here: `ATTACH` on a WAL database (requery runs it on + one connection only; Android turns write-ahead logging off on the first `ATTACH`); a cancelled query throws + `androidx.core.os.OperationCanceledException`, not `android.os.OperationCanceledException`; page size and + `wal_autocheckpoint` defaults can differ from the platform's; there is no compatibility WAL mode; the cursor + window is a fixed 2 MB, and a row larger than it throws `IllegalStateException`; `beginTransactionReadOnly` + is not in requery (it fails the build) and its read-only semantics have no counterpart; requery has no + `StrictMode` hooks, so StrictMode does not report database access on the main thread. +- Quick Build is not applied to a project with `cogo.sqliteDebugger=true`: its hot payload is compiled by + the Quick Build daemon from the project's source (and its baseline payload is diverted out of the classes + pipeline), so those classes would still use `android.database.sqlite` next to rewritten baseline classes. + The plugin logs why and the build is a normal one. The IDE does not provision Quick Build for such a project + either (`QuickBuildProjectSupport.sqliteDebuggerMessage`): it shows `quick_build_disabled_sqlite_debugger`, which + says Quick Build is off while the SQLite debugger is on. +- Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not + rewritten. +- The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a + cursor that reached the method through a field, a parameter or another call is not seen (the app throws + `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an + SQLite cursor cannot be a false positive. +- Compile-time constants are copied into callers, so uses of `NO_LOCALIZED_COLLATORS`, `JOURNAL_MODE_*` or `SYNC_MODE_*` are + not visible to the fail rule. `NO_LOCALIZED_COLLATORS` is dropped by the flag translation. +- The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied. +- A direct subclass of `SQLiteQueryBuilder` or `SQLiteCursor` that overrides a member requery lacks is not + reported. +- `instanceof` is not rewritten: `cursor instanceof AbstractWindowedCursor`, `AbstractCursor` or + `CrossProcessCursor` is silently false for requery's cursors (no build failure), which is what Room's + `DBUtil.query` relies on. +- Android's `CancellationSignal` holds one listener: the conversion replaces any listener the caller set. +- Which `SQLiteException` subclass requery throws for an error code (for example `SQLiteConstraintException`, which + Room catches) is decided by its native layer; this rewrite does not change it and the survey did not check it. diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 55b60427e7..08f92e3e6d 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -22,6 +22,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. +- **Gradle plugin wiring (ADFA-7138).** An app opts in with `cogo.sqliteDebugger=true` in its `gradle.properties`; commenting the line out turns everything off. With it, Code on the Go's Gradle plugin (`AndroidIDEGradlePlugin`) applies two plugins. `SqliteRewritePlugin` registers a class transform on every variant that moves the app's and its libraries' classes from `android.database.sqlite` to requery (see `gradle-plugin/docs/sqlite-rewrite.md`) and adds the rewrite's helper AAR (`:subprojects:sqlite-rewrite-runtime`) to every variant. `SqliteDebuggerPlugin` adds the debugger AAR and kotlin-stdlib to debuggable variants only. Code on the Go passes both AAR paths to Gradle as properties. Quick Build is not applied to an opted-in project, because its payload would compile the project's source without the rewrite. The apps' minSdk must be at least 21, the floor of requery, the helper AAR and the debugger. ### The event record @@ -49,6 +50,5 @@ No workflow in `.github/workflows` runs either yet. ## Not done yet - Broadcasting the port and token to Code on the Go (ADFA-7137). `DebuggerStartup` only keeps them in `DebuggerStartup.port` and `endpointToken` and logs the port, never the token. -- Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138). - The AI-Agent-MCP side that connects to the server (ADFA-7139). - Verification on a device. The C tests run on the host and the Kotlin tests on the JVM; nothing has run in an app on a device or emulator. From 2c78e0af9b4fff8a49fb3db5aaf6a1cf2391a490 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:47:07 -0800 Subject: [PATCH 061/203] ADFA-7138 Quick Build opt-in check reads the sources Gradle's findProperty sees The plugin decides the opt-in with findProperty, which sees the Gradle user home and the app module gradle.properties as well as the root one. The IDE read only the root file, so such a project was staged and then refused with the misleading variant-setup message, and a read failure counted as not opted in without a log line. The check now reads user home, app module and root (first defining one wins) and logs a read failure. Tests: opt-in in root, in user home, in the module, false overriding true, and an unreadable file reported and treated as not set. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 13 ++-- .../quickbuild/QuickBuildProjectSupport.kt | 68 ++++++++++++++----- .../QuickBuildProjectSupportTest.kt | 63 +++++++++++++++-- gradle-plugin/docs/sqlite-rewrite.md | 6 +- 4 files changed, 122 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index ae0c963fd9..28bc92cec4 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -15,6 +15,7 @@ import com.itsaky.androidide.tooling.api.messages.BuildRunType import com.itsaky.androidide.tooling.api.messages.GradleBuildParams import com.itsaky.androidide.tooling.api.messages.TaskExecutionMessage import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult +import com.itsaky.androidide.utils.Environment import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -346,12 +347,16 @@ class GradleQuickBuildProvisioner( // Before staging, which writes into the project: the Gradle plugin never applies Quick Build // to an opted-in project, so building would only end in "variant setup missing". QuickBuildProjectSupport - .sqliteDebuggerMessage(QuickBuildProjectSupport.isSqliteDebuggerEnabled(projectRoot)) - ?.let { refusal -> + .sqliteDebuggerMessage( + QuickBuildProjectSupport.isSqliteDebuggerEnabled( + projectRoot, + Environment.GRADLE_USER_HOME, + projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, + ), + )?.let { refusal -> log.info( - "Quick Build is not provisioned: {} is true in {}/gradle.properties", + "Quick Build is not provisioned: {} is true in the project's or the Gradle user home's gradle.properties", GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, - projectRoot, ) return ProxyAppBuildResult.Failed(context.getString(refusal)) } diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt index 89728f2f6c..58fe82ebff 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt @@ -3,7 +3,9 @@ package com.itsaky.androidide.quickbuild import androidx.annotation.StringRes import com.itsaky.androidide.resources.R import com.itsaky.androidide.tooling.api.GradlePluginConfig +import org.slf4j.LoggerFactory import java.io.File +import java.io.IOException import java.io.StringReader import java.util.Properties @@ -84,25 +86,59 @@ object QuickBuildProjectSupport { } /** - * Whether the root `gradle.properties` text opts in, decided as the Gradle plugin does: the - * value is exactly `true`. + * Whether one `gradle.properties` text opts in, decided as the Gradle plugin does: the value is + * exactly `true`. * - * @param gradleProperties the file's text, or null when the project has none. + * @param gradleProperties the file's text, or null when there is none. */ - fun isSqliteDebuggerEnabled(gradleProperties: String?): Boolean { - if (gradleProperties == null) return false - val properties = Properties() - return try { - properties.load(StringReader(gradleProperties)) - properties.getProperty(GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED) == "true" - } catch (e: IllegalArgumentException) { - false + fun isSqliteDebuggerEnabled(gradleProperties: String?): Boolean = gradleProperties != null && propertyValue(gradleProperties) == "true" + + /** + * Whether the project opts in, from the same files the Gradle plugin's `findProperty` sees in + * Code on the Go's builds: the Gradle user home `gradle.properties` (`GRADLE_USER_HOME`, which + * overrides the project files), the app module's, and the root's. Gradle loads a + * `gradle.properties` from every project directory into that project, and a subproject also + * inherits its parent's properties, so the first of these that defines the property wins. + * `-P` arguments are not read: Code on the Go passes none for this property. + * + * A file that cannot be read is reported to [onReadFailure] and counts as not defining it. + * + * @param moduleDirs the directories of the app modules the plugin is applied to. + */ + fun isSqliteDebuggerEnabled( + projectRoot: File, + gradleUserHome: File?, + moduleDirs: List = emptyList(), + onReadFailure: (File, Throwable) -> Unit = { file, error -> + log.warn("Cannot read {}; treating it as not defining the SQLite debugger opt-in", file, error) + }, + readText: (File) -> String = File::readText, + ): Boolean { + val files = + listOfNotNull(gradleUserHome) + moduleDirs + projectRoot + for (entry in files) { + val file = File(entry, "gradle.properties") + val text = + try { + file.takeIf { it.isFile }?.let(readText) + } catch (e: IOException) { + onReadFailure(file, e) + null + } ?: continue + val value = propertyValue(text) ?: continue + return value == "true" } + return false } - /** [isSqliteDebuggerEnabled] for the `gradle.properties` in [projectRoot]; false when it cannot be read. */ - fun isSqliteDebuggerEnabled(projectRoot: File): Boolean = - isSqliteDebuggerEnabled( - runCatching { File(projectRoot, "gradle.properties").takeIf { it.isFile }?.readText() }.getOrNull(), - ) + private fun propertyValue(gradleProperties: String): String? = + try { + Properties() + .apply { load(StringReader(gradleProperties)) } + .getProperty(GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED) + } catch (e: IllegalArgumentException) { + null + } + + private val log = LoggerFactory.getLogger("QB-Support") } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt index ae57986533..ceb3e13999 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt @@ -96,18 +96,67 @@ class QuickBuildProjectSupportTest { assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(null as String?)).isFalse() } - @Test - fun `the root gradle properties file is read, a missing one is not an opt-in`() { - val dir = + private fun withDirs(block: (root: java.io.File, home: java.io.File, module: java.io.File) -> Unit) { + val base = java.nio.file.Files .createTempDirectory("qb-sqlite") .toFile() try { - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(dir)).isFalse() - java.io.File(dir, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(dir)).isTrue() + block( + java.io.File(base, "root").apply { mkdirs() }, + java.io.File(base, "home").apply { mkdirs() }, + java.io.File(base, "root/app").apply { mkdirs() }, + ) } finally { - dir.deleteRecursively() + base.deleteRecursively() } } + + private fun java.io.File.props(text: String) = java.io.File(this, "gradle.properties").writeText(text) + + @Test + fun `the root gradle properties file is read, a missing one is not an opt-in`() = + withDirs { root, home, _ -> + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home)).isFalse() + root.props("cogo.sqliteDebugger=true\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home)).isTrue() + } + + @Test + fun `the Gradle user home gradle properties opts in`() = + withDirs { root, home, module -> + home.props("cogo.sqliteDebugger=true\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home, listOf(module))).isTrue() + } + + @Test + fun `the app module gradle properties opts in`() = + withDirs { root, home, module -> + module.props("cogo.sqliteDebugger=true\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home, listOf(module))).isTrue() + } + + @Test + fun `false in a higher-priority file overrides true in the root`() = + withDirs { root, home, module -> + root.props("cogo.sqliteDebugger=true\n") + home.props("cogo.sqliteDebugger=false\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home, listOf(module))).isFalse() + } + + @Test + fun `an unreadable file is logged and treated as not set`() = + withDirs { root, home, _ -> + home.props("cogo.sqliteDebugger=true\n") + val failures = mutableListOf() + val enabled = + QuickBuildProjectSupport.isSqliteDebuggerEnabled( + root, + home, + onReadFailure = { file, _ -> failures += file }, + readText = { throw java.io.IOException("denied") }, + ) + assertThat(enabled).isFalse() + assertThat(failures).containsExactly(java.io.File(home, "gradle.properties")) + } } diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 2b6cf2186e..85310aa101 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -9,7 +9,11 @@ run the same SQLite. User source does not change. An existing project needs: -1. `cogo.sqliteDebugger=true` in `gradle.properties`. +1. `cogo.sqliteDebugger=true` in `gradle.properties`. The plugin reads it with Gradle's `findProperty`, so the + project's root file, the app module's own `gradle.properties` and the Gradle user home's + (`GRADLE_USER_HOME`, `~/.gradle` under Code on the Go's home) all work, the user home first. The IDE's Quick + Build check (`QuickBuildProjectSupport.isSqliteDebuggerEnabled`) reads those same three files, in that order, + and logs a file it cannot read; it does not see `-P` arguments, which Code on the Go does not pass for this. 2. requery's AAR (`sqlite-android.aar`) in the app's `libs/`, as a file dependency (`implementation(files("libs/sqlite-android.aar"))`), as the ADFA-7082 template does. 3. androidx.sqlite on the runtime classpath (`androidx.sqlite:sqlite`, which Room, WorkManager and most androidx From 4e4718f4cd5dbf609e0fdacf70de2253c2f87b50 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 22:47:07 -0800 Subject: [PATCH 062/203] ADFA-7138 Fail the build when a variant's runtime classpath cannot be reached SqliteRewritePlugin registers the class rewrite before it adds the helper AAR and the classpath check, and withRuntimeConfiguration silently skipped a variant type it did not know, so the app would build and throw NoClassDefFoundError on the device. The two SQLite plugins now use requireRuntimeConfiguration, which throws naming the variant and its class; LogSender keeps the skipping helper. Test: a stand-in variant (TestKit cannot produce an unknown variant type) makes the decision function throw, while withRuntimeConfiguration still skips it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 5 ++- .../androidide/gradle/LogSenderPlugin.kt | 38 +++++++++++++---- .../androidide/gradle/SqliteDebuggerPlugin.kt | 2 +- .../gradle/sqlite/SqliteRewritePlugin.kt | 4 +- .../gradle/RuntimeConfigurationTest.kt | 42 +++++++++++++++++++ 5 files changed, 80 insertions(+), 11 deletions(-) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/RuntimeConfigurationTest.kt diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 85310aa101..2472d1d548 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -24,7 +24,10 @@ An existing project needs: The helper classes the rewrite redirects to (`SqliteRewriteRuntime`) are not in `libs/`: Code on the Go bundles `subprojects/sqlite-rewrite-runtime`'s release AAR, extracts it with the other tools and passes its path as `androidide.sqliteRewriteRuntime.aar`, as it does for the debugger AAR. `SqliteRewritePlugin` adds it to the -runtime classpath of every variant of a project that opted in, and fails the build when the file is missing. +runtime classpath of every variant of a project that opted in, and fails the build when the file is missing or +when a variant's runtime classpath cannot be reached (a variant type the plugin does not know, named in the message): +the rewrite is already registered for it, so going on would give an app that throws `NoClassDefFoundError`. +`SqliteDebuggerPlugin` fails the same way for the variants it adds the debugger to. A task `checkSqliteRewriteClasspath` runs before the compile and the transform of each variant. It fails with an actionable message when the variant's runtime classpath has no diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt index 99416b3d7d..4cb348c462 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/LogSenderPlugin.kt @@ -88,13 +88,37 @@ class LogSenderPlugin : Plugin { } /** - * Runs [action] on the variant's runtime classpath configuration. Shared with - * [SqliteDebuggerPlugin]; does nothing for a variant type it does not recognize. + * The variant's runtime classpath configuration, or null for a variant type it does not recognize + * (a wrapper a future AGP may add). */ -internal fun ApplicationVariant.withRuntimeConfiguration(action: Configuration.() -> Unit) { - if (this is ApplicationVariantImpl) { - variantDependencies.runtimeClasspath.action() - } else if (this is AnalyticsEnabledApplicationVariant) { - delegate.withRuntimeConfiguration(action) +internal fun ApplicationVariant.runtimeConfigurationOrNull(): Configuration? = + when (this) { + is ApplicationVariantImpl -> variantDependencies.runtimeClasspath + is AnalyticsEnabledApplicationVariant -> delegate.runtimeConfigurationOrNull() + else -> null } + +/** + * Runs [action] on the variant's runtime classpath configuration. Used by [LogSenderPlugin], and + * does nothing for a variant type it does not recognize; the SQLite plugins use + * [requireRuntimeConfiguration] instead. + */ +internal fun ApplicationVariant.withRuntimeConfiguration(action: Configuration.() -> Unit) { + runtimeConfigurationOrNull()?.action() +} + +/** + * Like [withRuntimeConfiguration], but fails the build when the configuration cannot be reached. For + * plugins that have already registered something that needs what [action] adds: skipping it would + * build an app that throws NoClassDefFoundError on the device. + */ +internal fun ApplicationVariant.requireRuntimeConfiguration(action: Configuration.() -> Unit) { + val configuration = + runtimeConfigurationOrNull() + ?: throw GradleException( + "Cannot reach the runtime classpath of variant '$name': its type ${javaClass.name} is not one this " + + "plugin knows. The SQLite debugger cannot add its runtime dependencies to it, so the app would " + + "fail at run time. Remove 'cogo.sqliteDebugger' from gradle.properties to build without it.", + ) + configuration.action() } diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt index bb37d6a7b1..72e2b3985d 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt @@ -70,7 +70,7 @@ class SqliteDebuggerPlugin : Plugin { target.extensions.getByType(ApplicationAndroidComponentsExtension::class.java).apply { val addDebugger = { variant: ApplicationVariant -> - variant.withRuntimeConfiguration { + variant.requireRuntimeConfiguration { logger.lifecycle( "Adding SQLite debugger dependency to variant '{}' of project '{}'", variant.name, diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt index a3b621b501..3f80201b35 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt @@ -5,7 +5,7 @@ package com.itsaky.androidide.gradle.sqlite import com.android.build.api.instrumentation.InstrumentationScope import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.itsaky.androidide.gradle.APP_PLUGIN -import com.itsaky.androidide.gradle.withRuntimeConfiguration +import com.itsaky.androidide.gradle.requireRuntimeConfiguration import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR import org.gradle.api.GradleException @@ -61,7 +61,7 @@ class SqliteRewritePlugin : Plugin { variant.instrumentation.setAsmFramesComputationMode(SqliteRewriter.FRAMES_MODE) val capitalized = variant.name.replaceFirstChar { it.uppercase() } - variant.withRuntimeConfiguration { + variant.requireRuntimeConfiguration { logger.lifecycle("Adding SQLite rewrite runtime dependency to variant '{}' of project '{}'", variant.name, target.path) dependencies.add(target.dependencies.create(target.fileTree(runtimeAar))) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/RuntimeConfigurationTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/RuntimeConfigurationTest.kt new file mode 100644 index 0000000000..506e1b8ddb --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/RuntimeConfigurationTest.kt @@ -0,0 +1,42 @@ +package com.itsaky.androidide.gradle + +import com.android.build.api.variant.ApplicationVariant +import com.google.common.truth.Truth.assertThat +import org.gradle.api.GradleException +import org.junit.jupiter.api.Test +import java.lang.reflect.Proxy + +/** + * A variant type the helper does not know cannot be given the SQLite runtime dependencies, and a + * build that went on would crash on the device (NoClassDefFoundError). A TestKit build cannot produce + * such a variant, so this tests the decision function with a stand-in variant. + */ +class RuntimeConfigurationTest { + private val unknownVariant = + Proxy.newProxyInstance( + javaClass.classLoader, + arrayOf(ApplicationVariant::class.java), + ) { _, method, _ -> + if (method.name == "getName") "stagingDebug" else null + } as ApplicationVariant + + @Test + fun `requireRuntimeConfiguration fails naming the variant and its class`() { + var ran = false + val failure = runCatching { unknownVariant.requireRuntimeConfiguration { ran = true } }.exceptionOrNull() + + assertThat(failure).isInstanceOf(GradleException::class.java) + assertThat(failure!!.message).contains("variant 'stagingDebug'") + assertThat(failure.message).contains(unknownVariant.javaClass.name) + assertThat(ran).isFalse() + } + + @Test + fun `withRuntimeConfiguration still skips an unknown variant for LogSender`() { + var ran = false + unknownVariant.withRuntimeConfiguration { ran = true } + + assertThat(ran).isFalse() + assertThat(unknownVariant.runtimeConfigurationOrNull()).isNull() + } +} From b15fa5df56525120319bda04718a94f6fa43a0dd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 01:01:38 -0800 Subject: [PATCH 063/203] ADFA-7082: Vendor the sqlite-js 1.4.3 release, with no patches Upstream merged sqliteai/sqlite-js#33, our patches 0001 (cancel) and 0002 (a cancelled call's finals and result sets) unmodified, and released them in 1.4.3 with one fix of the maintainer's: a cancel no longer stops a stored function's code while js_init_table(1) loads it, as it already spared the JavaScript that loads the extension. Before, a cancel in flight left the connection without that function. Only that call is exempt: JavaScript the code runs through SQL is still cancelled. - upstream/ is plain 1.4.3; patches/ is gone. vendor.sh and test.sh apply any patches/ there may be later (nullglob). - The glue still loads a stored function up to three times, for the case 1.4.3 still cancels. glue_test.c: new test 20 checks that a cancel during a function's own load code does not stop it (fails on 1.4.2 with the two patches); the w and h tests now cancel JavaScript that the load code runs through SQL (they fail with one try). - README, SqliteJs.cancelAll() javadoc: a cancel interrupts the connection, so any other statement in progress on it fails too, and it spares loading stored functions. The README now says the 1.4.2 build passed on the phone and the 1.4.3 build has not run on one yet. test.sh: upstream's suite 17 of 17; glue test 50 of 50 normally and as on SQLite 3.40, and the same under ASan, LeakSanitizer and UBSan. vendor.sh --check passes. NDK 29 builds for both ABIs: no warnings, the same four exports, version string 1.4.3. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .github/workflows/test-sqlite-js.yml | 4 +- ARCHITECTURE.md | 2 +- subprojects/sqlite-js/README.md | 20 +- ...e-host-cancel-all-running-JavaScript.patch | 268 ------------------ ...call-s-result-sets-as-interrupted-an.patch | 150 ---------- .../sqlite-js/src/main/cpp/CMakeLists.txt | 2 +- .../sqlite-js/src/main/cpp/sqlitejs_android.c | 6 +- .../org/appdevforall/sqlitejs/SqliteJs.java | 2 +- subprojects/sqlite-js/src/test/c/glue_test.c | 35 ++- subprojects/sqlite-js/test.sh | 7 +- subprojects/sqlite-js/upstream/src/sqlitejs.c | 30 +- subprojects/sqlite-js/upstream/src/sqlitejs.h | 15 +- subprojects/sqlite-js/vendor.sh | 13 +- 13 files changed, 92 insertions(+), 462 deletions(-) delete mode 100644 subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch delete mode 100644 subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch diff --git a/.github/workflows/test-sqlite-js.yml b/.github/workflows/test-sqlite-js.yml index 2a35ffdec1..8c79da6dac 100644 --- a/.github/workflows/test-sqlite-js.yml +++ b/.github/workflows/test-sqlite-js.yml @@ -1,7 +1,7 @@ name: Test sqlite-js -# The tests the Android build cannot run (ADFA-7082): that upstream/ is sqlite-js with patches/ -# applied, upstream's test suite with the patches, and the test of sqlitejs_android.c's entry +# The tests the Android build cannot run (ADFA-7082): that upstream/ is the sqlite-js release with +# any patches/ applied, upstream's test suite on it, and the test of sqlitejs_android.c's entry # points. See subprojects/sqlite-js/test.sh. on: diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b4046e491d..0a7b2ef3eb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -107,7 +107,7 @@ These structural facts shape every module. Day-to-day build *commands* live in ` - **ABI product flavors.** Every Android module *except* `:plugin-api` and `:subprojects:sqlite-js` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. -- **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: sqlite-js vendored with our patches (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. +- **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: the sqlite-js release vendored (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). - **`app` package layout is by concern, not feature:** `activities`, `fragments`, `services`, `di`, `agent`, `viewmodel(s)`, `repositories`, `roomData`, `localWebServer`, `preferences`, `ui` (Compose screens live under `ui/compose`), `templates/manager` (the Manager screen's `.cgt`-parsing data layer, with direct filesystem access to `Environment.TEMPLATES_DIR` — distinct from the plugin-facing `IdeTemplateService` in `plugin-api`/`plugin-manager`), `utils`, …. diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index 3dcebfe61b..45948b157c 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -1,16 +1,14 @@ # sqlite-js for apps -An AAR that lets apps built with Code on the Go define and call JavaScript functions in SQLite (ADFA-7082). It is the sqlite-js SQLite extension, which runs JavaScript with QuickJS (quickjs-ng), with our patches. Nothing in CoGo itself depends on it: the JavaScript-in-SQLite project template does. +An AAR that lets apps built with Code on the Go define and call JavaScript functions in SQLite (ADFA-7082). It is the sqlite-js SQLite extension, which runs JavaScript with QuickJS (quickjs-ng). Nothing in CoGo itself depends on it: the JavaScript-in-SQLite project template does. `createSqliteJsAar` writes `build/libs/sqlite-js.aar`. The manual `release-sqlite-js.yml` workflow builds it from `main` and publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template. ## Contents -- `upstream/`: the sqlite-js 1.4.2 release (Apache-2.0), which has our earlier changes (upstream pull requests #11 to #19, and #22 to #24), with QuickJS amalgamated in `libs/quickjs.c` (MIT), and `patches/` applied. Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. -- `patches/`: our changes not upstream: - - 0001 adds `sqlitejs_cancel_all()`: Android cannot otherwise stop JavaScript that never returns. It is offered upstream in sqliteai/sqlite-js issue 20. - - 0002 completes 0001. Ending a call's result sets runs the finals of the window and aggregate functions they were computing, and each final entered JavaScript as a new call, which a cancel during the call no longer stopped; before SQLite 3.41 nothing else did. The finals now belong to the call: a cancel during the call or while its result sets are ended stops each at QuickJS's next interrupt check, so one that never ends is stopped and the statement fails, though a short final can still finish. Those result sets read on as "interrupted", whether the cancel came before the call returned or while they were ended. -- Since 1.4.2 a `db.exec` result set does not outlive the call into JavaScript that created it: every one still open is ended when the call returns, because its statement keeps a read transaction open, keeps an interrupt in effect and stops the connection from closing. Reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned", or "interrupted" when a cancel (or, on SQLite 3.41 and later, `sqlite3_interrupt()`) stopped the call. One read to its end still reports the end of its rows. +- `upstream/`: the sqlite-js 1.4.3 release (Apache-2.0), which has all our changes (upstream pull requests #11 to #19, #22 to #24, and #33, which added `sqlitejs_cancel_all()`), with QuickJS amalgamated in `libs/quickjs.c` (MIT). Only the files the build uses, plus `LICENSE` and `LICENSE.quickjs`. +- `patches/`, when there is one: our changes not yet upstream, which `vendor.sh` and `test.sh` apply in order. There are none now. +- Since 1.4.2 a `db.exec` result set does not outlive the call into JavaScript that created it: every one still open is ended when the call returns, because its statement keeps a read transaction open, keeps an interrupt in effect and stops the connection from closing. Reading one afterwards throws "The result set was closed when the call into JavaScript that created it returned", or "interrupted" when a cancel (or, on SQLite 3.41 and later, `sqlite3_interrupt()`) stopped the call. Ending them runs the finals of the window and aggregate functions they were computing, and a cancel during the call or while they are ended stops each final at QuickJS's next interrupt check. One read to its end still reports the end of its rows. - `src/main/cpp/`: the CMake build of `libsqlitejs.so`, and `sqlitejs_android.c`, which is ours: JNI for `SqliteJs`, and the two entry points it names. The version script exports only the entry points (and upstream's `sqlite3_js_init`) and `JNI_OnLoad`. - `src/test/c/glue_test.c` and `test.sh`: the tests the Android build cannot run. See Testing. - `src/main/java/`: `SqliteJs`. @@ -34,18 +32,18 @@ Room.databaseBuilder(context, AppDb::class.java, name).openHelperFactory(factory ``` - `SqliteJs.ENTRY_POINT` loads sqlite-js and runs nothing stored in the database, so it is safe for any database file. -- `SqliteJs.ENTRY_POINT_FOR_TRUSTED_DATABASE` also loads the functions stored in the database's `js_functions` table (see `js_init_table`), on every connection, since each connection has its own JavaScript runtime. Loading a stored function runs its code, which can run SQL and read the app's files, so use it only for a database the app made and keeps. Open a downloaded or shared file, or a restored backup, with `ENTRY_POINT`: with the trusted entry point, its stored code would run as soon as the app opened it. A stored function that fails to load is logged (`sqlite3_log`) and skipped, and the rest still load. One whose loading `cancelAll()` stops (see below) is loaded again, up to three tries, and its stored code runs again each time. +- `SqliteJs.ENTRY_POINT_FOR_TRUSTED_DATABASE` also loads the functions stored in the database's `js_functions` table (see `js_init_table`), on every connection, since each connection has its own JavaScript runtime. Loading a stored function runs its code, which can run SQL and read the app's files, so use it only for a database the app made and keeps. Open a downloaded or shared file, or a restored backup, with `ENTRY_POINT`: with the trusted entry point, its stored code would run as soon as the app opened it. A stored function that fails to load is logged (`sqlite3_log`) and skipped, and the rest still load. `cancelAll()` (see below) does not stop a stored function's code while it loads, but does stop JavaScript that code runs through SQL; a function whose loading that stops is loaded again, up to three tries, and its stored code runs again each time. - A connection that opened before a function was stored does not have it. So store the functions before Room opens the database, on a connection opened with `ENTRY_POINT`, since a connection cannot redefine a function it has. - Room checks queries at build time with its own SQLite, which has no JavaScript functions: mark DAO methods that call them `@SkipQueryVerification`. - SQLite loads the extension from a file, so set `packaging.jniLibs.useLegacyPackaging = true`. -- Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its statement is interrupted too, so that one whose JavaScript cannot report an error (a collation) also stops. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted `INSERT`, `UPDATE` or `DELETE` inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a new connection. The `db.exec` result sets of a call it stops are ended, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. +- Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its connection is interrupted too, as `sqlite3_interrupt()` does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted `INSERT`, `UPDATE` or `DELETE` inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. The `db.exec` result sets of a call it stops are ended, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. -Built from 1.4.1 with our patches of the time, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 25 ms. The build from 1.4.2 has not been run on a phone yet. +Built from 1.4.1 with our patches of the time, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 25 ms. The build from 1.4.2 with our two cancel patches, which 1.4.3 has, passed the trial app's checks in both processes and on both databases, and the template stopped its runaway query 11 to 13 ms after Cancel. The build from 1.4.3 has not been run on a phone yet. ## Testing -The Android build compiles but does not run sqlite-js. `test.sh` builds it on the host and runs upstream's test suite (`test/main.c`, which is not vendored) on its source with `patches/` applied, and `src/test/c/glue_test.c` on `upstream/` and `sqlitejs_android.c`: what each entry point loads and runs, that a stored function that fails to load is skipped, that one whose loading is cancelled loads on a second try, even when its code keeps a result set open, what reading a kept result set throws after a cancel or a direct interrupt, that a cancel stops every window function's final that ending the call's result sets runs, also when it lands while they are ended or just before the call returns, and that a statement a progress handler stops is not an interrupt. It runs `glue_test.c` twice, the second time with sqlite-js working as on SQLite before 3.41 (for patch 0002). It needs gcc, make and a JDK (for `jni.h`). The `test-sqlite-js.yml` workflow runs `vendor.sh --check` and `test.sh` on every pull request that changes this module. +The Android build compiles but does not run sqlite-js. `test.sh` builds it on the host and runs upstream's test suite (`test/main.c`, which is not vendored) on its source, with any `patches/` applied, and `src/test/c/glue_test.c` on `upstream/` and `sqlitejs_android.c`: what each entry point loads and runs, that a stored function that fails to load is skipped, that a cancel does not stop a stored function's code while it loads, that one whose loading a cancel stops in JavaScript the code runs through SQL loads on a second try, even when its code keeps a result set open, what reading a kept result set throws after a cancel or a direct interrupt, that a cancel stops every window function's final that ending the call's result sets runs, also when it lands while they are ended or just before the call returns, and that a statement a progress handler stops is not an interrupt. It runs `glue_test.c` twice, the second time with sqlite-js working as on SQLite before 3.41, where only the cancel stops a final that never ends. It needs gcc, make and a JDK (for `jni.h`). The `test-sqlite-js.yml` workflow runs `vendor.sh --check` and `test.sh` on every pull request that changes this module. ## Updating -`vendor.sh` rebuilds `upstream/` and the license notices from the source archive of the sqlite-js release `VERSION` (checked against its SHA-256) and `patches/`. `vendor.sh --check` tells whether they match. To move to a new release, change `VERSION` and `SHA256` in `vendor.sh`. For a commit between releases, point `URL` at the commit's archive (`archive/.tar.gz`) and name `VERSION` as the Termux package does; the scripts take the archive's top directory, whatever it is named. Drop a patch once upstream has it, refresh the rest, and run `vendor.sh`. +`vendor.sh` rebuilds `upstream/` and the license notices from the source archive of the sqlite-js release `VERSION` (checked against its SHA-256) and any `patches/`. `vendor.sh --check` tells whether they match. To move to a new release, change `VERSION` and `SHA256` in `vendor.sh`. For a commit between releases, point `URL` at the commit's archive (`archive/.tar.gz`) and name `VERSION` as the Termux package does; the scripts take the archive's top directory, whatever it is named. Drop a patch once upstream has it, refresh the rest, and run `vendor.sh`. diff --git a/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch b/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch deleted file mode 100644 index f45def7dd5..0000000000 --- a/subprojects/sqlite-js/patches/0001-Let-the-host-cancel-all-running-JavaScript.patch +++ /dev/null @@ -1,268 +0,0 @@ -From 8ba5688b1cd9c9560345da31989288760049da8f Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Thu, 12 Nov 2026 00:05:58 -0800 -Subject: [PATCH 1/2] Let the host cancel all running JavaScript - -sqlitejs_cancel_all() stops the JavaScript running in every connection: -each call fails with an "interrupted" error, even code that catches -every exception. JavaScript that begins afterwards runs normally. - -Android cannot otherwise stop a runaway function: it cancels a query -with a progress handler, which SQLite never calls while a function runs, -and Room 2.7 and later pass no cancellation signal at all. A global -epoch, read when the outermost call into JavaScript begins and compared -by the existing interrupt handler, makes the cancel reach every runtime -without a list of connections. The interrupt handler is now installed -even when sqlite3_is_interrupted() is unavailable (SQLite before 3.41), -so cancelling still works there. - -When the cancel stops a call, the handler also interrupts that call's -connection with sqlite3_interrupt(), so its statement stops too. A -collation cannot report an error: without this, a sort went on calling -it, each call beginning after the cancel, and never ended. Add to the -Cancel all test a runaway collation that one cancel stops; it hung -without this. - -The test's worker cancels only once the JavaScript under test has called -started(), an SQL function, since a cancel that came first would leave -the JavaScript running. If that has not happened within 10 seconds, the -worker fails the test with a message instead of cancelling. Like the -Interrupt test, a watchdog ends the program if the JavaScript cannot be -stopped. - -Only a call into JavaScript is cancelled, not the JavaScript a connection -runs while it is set up: a cancel then made the connection fail to load -the extension (SQLITE_NOMEM), and an app's query on a new pool -connection failed. The Cancel all test now opens 200 connections while -another thread cancels without pause; without this, the first failed. - -Co-Authored-By: Claude Opus 5.5 -Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw ---- - src/sqlitejs.c | 42 +++++++++++++++++-- - src/sqlitejs.h | 1 + - test/main.c | 109 +++++++++++++++++++++++++++++++++++++++++++++++++ - 3 files changed, 149 insertions(+), 3 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index 26af849..e5fea55 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -70,6 +70,8 @@ typedef struct { - size_t mem_peak; // the most in use since the last result or error - size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() - int depth; // calls into JavaScript in progress: see js_enter() -+ unsigned cancel_epoch; // js_cancel_epoch when the outermost call began -+ bool check_interrupted; // sqlite3_is_interrupted() is available - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - int orphans; // of those, the ones whose JavaScript object is gone - bool ending_rowsets; // js_end_rowsets() is running -@@ -325,6 +327,30 @@ static void js_collect_below_limit (globaljs_context *js) { - js_keep_gc_below_limit(js); - } - -+// Bumped by sqlitejs_cancel_all(): JavaScript that began before stops, as if interrupted. -+static unsigned js_cancel_epoch; -+ -+static unsigned js_cancel_epoch_load (void) { -+#if defined(__clang__) || defined(__GNUC__) -+ return __atomic_load_n(&js_cancel_epoch, __ATOMIC_ACQUIRE); -+#else -+ return *(volatile unsigned *)&js_cancel_epoch; -+#endif -+} -+ -+// Stops all JavaScript that is running now, in every connection: each call fails with an -+// "interrupted" error, and the statement that called it is interrupted. JavaScript that begins -+// afterwards runs normally. Safe from any thread. -+// For hosts whose own cancelling cannot reach JavaScript: Android cancels a query with a -+// progress handler, which SQLite never calls while a JavaScript function runs. -+void sqlitejs_cancel_all (void) { -+#if defined(__clang__) || defined(__GNUC__) -+ __atomic_add_fetch(&js_cancel_epoch, 1, __ATOMIC_RELEASE); -+#else -+ (*(volatile unsigned *)&js_cancel_epoch)++; -+#endif -+} -+ - // QuickJS calls this from time to time while it runs code. A non-zero result stops the code - // with an uncatchable "interrupted" error, so sqlite3_interrupt() (Ctrl-C in the sqlite3 shell, - // a cancelled query in an app) also stops JavaScript that never returns to SQLite. -@@ -332,7 +358,15 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { - UNUSED(rt); - globaljs_context *js = (globaljs_context *)opaque; - js_keep_gc_below_limit(js); -- return (js->db != NULL) && sqlite3_is_interrupted(js->db); -+ // Only a call (see js_enter) is cancelled: the JavaScript a connection runs while it is set -+ // up is not one, and stopping it would make the connection fail to load the extension. -+ if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { -+ // The statement is interrupted too: a collation cannot report an error, so the -+ // statement would go on calling JavaScript, each call beginning after the cancel. -+ if (js->db) sqlite3_interrupt(js->db); -+ return 1; -+ } -+ return js->check_interrupted && (js->db != NULL) && sqlite3_is_interrupted(js->db); - } - - // The most memory, in bytes, the JavaScript runtime of a connection may allocate until -@@ -542,6 +576,7 @@ static bool js_stack_room (size_t *room) { - // runs JavaScript) is on the same thread and keeps the outer call's limit. - static void js_enter (globaljs_context *js) { - if (js->depth++ > 0) return; -+ js->cancel_epoch = js_cancel_epoch_load(); - JS_UpdateStackTop(js->runtime); - // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails - // with "Maximum call stack size exceeded" rather than running past the end of the stack. A -@@ -577,8 +612,9 @@ static globaljs_context *globaljs_init (sqlite3 *db) { - //JS_SetMaxStackSize(rt, 10 * 1024); - - // sqlite3_is_interrupted() is new in SQLite 3.41.0: an older library has no such entry -- // in its sqlite3_api_routines, so JavaScript cannot be interrupted there -- if (sqlite3_libversion_number() >= 3041000) JS_SetInterruptHandler(rt, js_interrupt_handler, js); -+ // in its sqlite3_api_routines, so JavaScript cannot be interrupted there, only cancelled -+ js->check_interrupted = (sqlite3_libversion_number() >= 3041000); -+ JS_SetInterruptHandler(rt, js_interrupt_handler, js); - - // the default stack size must fit in the stack of the thread that loads the extension: Windows - // gives a main thread 1 MB, and apps often give their threads no more -diff --git a/src/sqlitejs.h b/src/sqlitejs.h -index fb0172d..ed6ce4e 100644 ---- a/src/sqlitejs.h -+++ b/src/sqlitejs.h -@@ -21,5 +21,6 @@ - int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); - const char *sqlitejs_version (void); - const char *quickjs_version (void); -+void sqlitejs_cancel_all (void); - - #endif -diff --git a/test/main.c b/test/main.c -index 8cc3706..d0930e6 100644 ---- a/test/main.c -+++ b/test/main.c -@@ -1047,6 +1047,114 @@ abort_test: - return rc; - } - -+// MARK: - Cancel all - -+ -+// Set by started(), an SQL function that the JavaScript under test calls before it spins, so -+// that the worker cancels only JavaScript that is running: a cancel that came first would not -+// stop it -+static int test_js_started; -+ -+static void test_started (sqlite3_context *context, int argc, sqlite3_value **argv) { -+ (void)argc; (void)argv; -+ __atomic_store_n(&test_js_started, 1, __ATOMIC_RELEASE); -+ sqlite3_result_null(context); -+} -+ -+static void *test_cancel_all_worker (void *ptr) { -+ (void)ptr; -+ // wait for the JavaScript to start, for at most 10 s; cancelling before it starts would -+ // leave it running, so a JavaScript that has not started by then fails the test here -+ for (int i = 0; i < 1000 && !__atomic_load_n(&test_js_started, __ATOMIC_ACQUIRE); ++i) usleep(10 * 1000); -+ if (!__atomic_load_n(&test_js_started, __ATOMIC_ACQUIRE)) { -+ printf("FAIL: the JavaScript under test did not start in 10 seconds\n"); -+ fflush(stdout); -+ abort(); -+ } -+ sqlitejs_cancel_all(); -+ return NULL; -+} -+ -+static int test_cancelling; -+ -+static void *test_cancel_loop (void *ptr) { -+ (void)ptr; -+ while (__atomic_load_n(&test_cancelling, __ATOMIC_ACQUIRE)) sqlitejs_cancel_all(); -+ return NULL; -+} -+ -+// Opens connections while another thread cancels without pause. Setting up a connection runs -+// JavaScript of its own, and a cancel that stopped it made the connection fail to load. -+static int test_cancel_during_open (void) { -+ pthread_t thread; -+ __atomic_store_n(&test_cancelling, 1, __ATOMIC_RELEASE); -+ if (pthread_create(&thread, NULL, test_cancel_loop, NULL) != 0) return SQLITE_ERROR; -+ int rc = SQLITE_OK; -+ for (int i = 0; (i < 200) && (rc == SQLITE_OK); ++i) { -+ sqlite3 *db = NULL; -+ rc = test_open(&db); -+ if (rc != SQLITE_OK) printf("FAIL: connection %d did not open while another thread cancelled: %s\n", i, db ? sqlite3_errmsg(db) : sqlite3_errstr(rc)); -+ if (db) sqlite3_close(db); -+ } -+ __atomic_store_n(&test_cancelling, 0, __ATOMIC_RELEASE); -+ pthread_join(thread, NULL); -+ return rc; -+} -+ -+// sqlitejs_cancel_all() stops the JavaScript running in every connection, as Android's own -+// cancelling (a progress handler, which SQLite never calls while a function runs) cannot. -+int test_cancel_all (void) { -+ sqlite3 *db = NULL, *db2 = NULL; -+ pthread_t thread; -+ -+ int seconds = 30; -+ pthread_t watchdog; -+ test_watchdog_stop = 0; -+ bool watching = (pthread_create(&watchdog, NULL, test_watchdog, &seconds) == 0); -+ -+ int rc = test_open(&db); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = sqlite3_create_function(db, "started", 0, SQLITE_UTF8, NULL, test_started, NULL, NULL); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = db_exec(db, "SELECT js_create_scalar('spin', '(function (args) { db.exec(\"SELECT started()\").next(); for (;;) { try { while (true) {} } catch (e) {} } })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // JavaScript running now stops, even code that catches every exception -+ test_js_started = 0; -+ if (pthread_create(&thread, NULL, test_cancel_all_worker, NULL) != 0) { rc = SQLITE_ERROR; goto abort_test; } -+ rc = check_error(db, "SELECT spin();", "interrupted"); -+ pthread_join(thread, NULL); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // a collation cannot report an error, so its statement is interrupted too: otherwise the sort -+ // would go on calling it, and each call, begun after the cancel, would run -+ rc = db_exec(db, "SELECT js_create_collation('spin_collation', '(function (a, b) { db.exec(\"SELECT started()\").next(); for (;;) {} })');"); -+ if (rc != SQLITE_OK) goto abort_test; -+ test_js_started = 0; -+ if (pthread_create(&thread, NULL, test_cancel_all_worker, NULL) != 0) { rc = SQLITE_ERROR; goto abort_test; } -+ rc = check_error(db, "SELECT column1 FROM (VALUES ('a'), ('b'), ('c')) ORDER BY column1 COLLATE spin_collation;", "interrupted"); -+ pthread_join(thread, NULL); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // JavaScript that begins afterwards runs normally, on this connection and on a new one -+ rc = check_query(db, "SELECT js_eval('1 + 1');", "2"); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = test_open(&db2); -+ if (rc != SQLITE_OK) goto abort_test; -+ rc = check_query(db2, "SELECT js_eval('2 + 2');", "4"); -+ if (rc != SQLITE_OK) goto abort_test; -+ -+ // and a connection opened while cancels go on still loads the extension -+ rc = test_cancel_during_open(); -+ -+abort_test: -+ test_watchdog_stop = 1; -+ if (watching) pthread_join(watchdog, NULL); -+ if (rc != SQLITE_OK && db) printf("Error: %s\n", sqlite3_errmsg(db)); -+ if (db) sqlite3_close(db); -+ if (db2) sqlite3_close(db2); -+ return rc; -+} -+ - // MARK: - Stack size - - - int test_stack_size (void) { -@@ -1276,6 +1384,7 @@ int main (void) { - result += test_report("Serialization 3", test_serialization(DB_PATH, true, 3)); // load the new implementations - result += test_report("Thread", test_thread()); - result += test_report("Interrupt", test_interrupt()); -+ result += test_report("Cancel all", test_cancel_all()); - result += test_report("Direct only", test_direct_only()); - result += test_report("Aggregate errors", test_aggregate_errors()); - result += test_report("Exec errors", test_exec_errors()); --- -2.53.0 - diff --git a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch b/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch deleted file mode 100644 index 3f44b8bf5d..0000000000 --- a/subprojects/sqlite-js/patches/0002-End-a-cancelled-call-s-result-sets-as-interrupted-an.patch +++ /dev/null @@ -1,150 +0,0 @@ -From 09aa66a1ed410a588afb8233ecc574d908087231 Mon Sep 17 00:00:00 2001 -From: David Schachter -Date: Sun, 15 Nov 2026 22:10:52 -0800 -Subject: [PATCH] End a cancelled call's result sets as interrupted, and stop - their finals - -Since 1.4.2 every result set still open when the outermost call into -JavaScript returns is ended there, which runs the final of each window -or aggregate function its statement was computing. Each final enters -JavaScript as a new outermost call, so js_enter() took the cancel epoch -of that moment and a cancel during the call no longer stopped it. On -SQLite 3.41 and later the interrupt the cancel left on the connection -does; before 3.41 nothing did, and a final that never ends hung the -statement for good. - -The finals that ending a call's result sets runs now keep that call's -epoch, so a cancel during the call, or during the ending, stops each of -them at QuickJS's next interrupt check: one that never ends is stopped -and the statement fails with an interrupt, though a short final can -still run to its end. Reading on from those result sets throws -"interrupted", as after sqlite3_interrupt() on 3.41 and later, rather -than the message for a result set that outlived its call, whether the -cancel came before the call returned or while its result sets were -ended. js_end_rowsets() marks both after its loop, by the pass that -ended them, since a final it runs can free result sets of the list; -js_leave() no longer needs to mark a cancelled call's result sets -itself. - -Before 3.41, an sqlite3_interrupt() that no cancel came with still reads -as the result set outliving its call: nothing shows it. - -The comment at the interrupt handler now says that only the JavaScript -the extension runs while it initialises a connection is exempt from a -cancel, not stored functions loaded by js_init_table. A rowset's -end_pass is initialised where it is created, and sqlitejs_cancel_all is -documented in sqlitejs.h. ---- - src/sqlitejs.c | 26 +++++++++++++++++++++++--- - src/sqlitejs.h | 2 ++ - 2 files changed, 25 insertions(+), 3 deletions(-) - -diff --git a/src/sqlitejs.c b/src/sqlitejs.c -index e5fea55..0a32d36 100644 ---- a/src/sqlitejs.c -+++ b/src/sqlitejs.c -@@ -75,6 +75,7 @@ typedef struct { - struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() - int orphans; // of those, the ones whose JavaScript object is gone - bool ending_rowsets; // js_end_rowsets() is running -+ unsigned end_pass; // js_end_rowsets() passes that ended every result set - } globaljs_context; - - typedef struct { -@@ -117,6 +118,7 @@ typedef struct rowset { - bool ended; // ended by js_end_rowsets(): reading on throws - bool interrupted; // and an interrupt is why: reading on throws "interrupted" - bool orphaned; // its JavaScript object is gone: see js_rowset_finalizer() -+ unsigned end_pass; // the js_end_rowsets() pass that ended it - struct rowset *prev, *next; // in the connection's list: see js_end_rowsets() - } rowset; - -@@ -272,9 +274,12 @@ static void js_rowset_finalizer(JSRuntime *rt, JSValue val) { - // computing, whose js_leave() comes back here and whose garbage collection can free result sets - // of the list. So each statement is taken from its result set before it is finalized, the list - // is walked again from its head after each one, and a nested call does nothing. -+static unsigned js_cancel_epoch_load (void); -+ - static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { - if (js->ending_rowsets) return; - js->ending_rowsets = true; -+ unsigned pass = all ? ++js->end_pass : 0; - for (;;) { - rowset *rs = js->rowsets; - while (rs && !(rs->orphaned || (all && rs->vm))) rs = rs->next; -@@ -291,10 +296,17 @@ static void js_end_rowsets (globaljs_context *js, bool all, bool interrupted) { - } else { - rs->vm = NULL; - rs->ended = true; -+ rs->end_pass = pass; - if (interrupted) rs->interrupted = true; - } - if (vm) sqlite3_finalize(vm); - } -+ // A cancel that landed while the finals ran stopped them, as one before the call returned -+ // would have: the result sets this pass ended read on as interrupted too. Nothing runs -+ // JavaScript here, so the list holds only result sets that are still allocated. -+ if (all && !interrupted && (js->cancel_epoch != js_cancel_epoch_load())) { -+ for (rowset *r = js->rowsets; r; r = r->next) if (r->ended && (r->end_pass == pass)) r->interrupted = true; -+ } - js->ending_rowsets = false; - } - -@@ -358,8 +370,10 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { - UNUSED(rt); - globaljs_context *js = (globaljs_context *)opaque; - js_keep_gc_below_limit(js); -- // Only a call (see js_enter) is cancelled: the JavaScript a connection runs while it is set -- // up is not one, and stopping it would make the connection fail to load the extension. -+ // Only a call (see js_enter) is cancelled. The one exception is the JavaScript the extension -+ // itself runs while it initialises a connection (globaljs_init, depth 0): stopping it would -+ // make the connection fail to load. Stored functions loaded by js_init_table run as a call, -+ // so they can be cancelled. - if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { - // The statement is interrupted too: a collation cannot report an error, so the - // statement would go on calling JavaScript, each call beginning after the cancel. -@@ -576,7 +590,10 @@ static bool js_stack_room (size_t *room) { - // runs JavaScript) is on the same thread and keeps the outer call's limit. - static void js_enter (globaljs_context *js) { - if (js->depth++ > 0) return; -- js->cancel_epoch = js_cancel_epoch_load(); -+ // The finals that ending a call's result sets runs (see js_leave) belong to that call: they keep -+ // its epoch, so a cancel during the call or during the ending stops them, as it would have -+ // stopped the call. Before SQLite 3.41 nothing else would stop one that never ends. -+ if (!js->ending_rowsets) js->cancel_epoch = js_cancel_epoch_load(); - JS_UpdateStackTop(js->runtime); - // A thread with less room than SQLITE_JS_STACK_MIN keeps it too: JavaScript there then fails - // with "Maximum call stack size exceeded" rather than running past the end of the stack. A -@@ -591,6 +608,8 @@ static void js_enter (globaljs_context *js) { - static void js_leave (globaljs_context *js) { - if (--js->depth > 0) return; - if (!js->rowsets) return; -+ // A cancel (sqlitejs_cancel_all) is not seen here: js_end_rowsets() marks its result sets -+ // interrupted itself, which is the only way they read so before SQLite 3.41. - bool interrupted = (sqlite3_libversion_number() >= 3041000) && js->db && sqlite3_is_interrupted(js->db); - js_end_rowsets(js, true, interrupted); - } -@@ -936,6 +955,7 @@ static JSValue js_sqlite_exec (JSContext *ctx, sqlite3 *db, const char *sql, int - rs->vm = vm; - rs->ncols = sqlite3_column_count(vm); - rs->ended = false; -+ rs->end_pass = 0; - rs->interrupted = false; - rs->orphaned = false; - rs->prev = rs->next = NULL; -diff --git a/src/sqlitejs.h b/src/sqlitejs.h -index ed6ce4e..7cf1ce3 100644 ---- a/src/sqlitejs.h -+++ b/src/sqlitejs.h -@@ -21,6 +21,8 @@ - int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); - const char *sqlitejs_version (void); - const char *quickjs_version (void); -+// Stops all JavaScript now running, in every connection. Safe to call from any thread. It -+// stops only JavaScript already running: calls that begin afterwards are not affected. - void sqlitejs_cancel_all (void); - - #endif --- -2.53.0 - diff --git a/subprojects/sqlite-js/src/main/cpp/CMakeLists.txt b/subprojects/sqlite-js/src/main/cpp/CMakeLists.txt index 78e6ed0077..1784e93e15 100644 --- a/subprojects/sqlite-js/src/main/cpp/CMakeLists.txt +++ b/subprojects/sqlite-js/src/main/cpp/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.22.1) project(sqlitejs C) -# sqlite-js with our patches applied; see ../../../README.md and ../../../vendor.sh +# sqlite-js, with any patches of ours applied; see ../../../README.md and ../../../vendor.sh set(UPSTREAM ${CMAKE_CURRENT_SOURCE_DIR}/../../../upstream) add_library(sqlitejs SHARED diff --git a/subprojects/sqlite-js/src/main/cpp/sqlitejs_android.c b/subprojects/sqlite-js/src/main/cpp/sqlitejs_android.c index 948825068f..665715799b 100644 --- a/subprojects/sqlite-js/src/main/cpp/sqlitejs_android.c +++ b/subprojects/sqlite-js/src/main/cpp/sqlitejs_android.c @@ -23,9 +23,9 @@ int sqlite3_sqlitejs_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routi // this row: an unqualified name finds the TEMP table first, and js_init_table's // CREATE TABLE IF NOT EXISTS still sees the main one. // A cancel (SqliteJs.cancelAll(), for a query on any connection) that lands while a function -// loads stops its code as it stops any JavaScript then running, and only loading it again puts the -// function on this connection. So such a load is tried again, up to STORED_FUNCTION_TRIES times -// in all, and its stored code runs again each time. +// loads does not stop its code, but stops any JavaScript that code runs through SQL, which fails +// the load, and only loading it again puts the function on this connection. So such a load is +// tried again, up to STORED_FUNCTION_TRIES times in all, and its stored code runs again each time. #define STORED_FUNCTION_TRIES 3 static void load_stored_function (sqlite3 *db, sqlite3_int64 rowid) { diff --git a/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java b/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java index 639940219d..b52db57660 100644 --- a/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java +++ b/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java @@ -31,7 +31,7 @@ public final class SqliteJs { } /** - * Stops the JavaScript that is running now, in every query on every connection: each running call fails with an "interrupted" error, and its statement is interrupted too, so that a statement whose JavaScript cannot report an error (a collation) also stops. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted INSERT, UPDATE or DELETE inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started: a query that has not reached its JavaScript yet runs it normally, so call it again until the query being stopped ends. It does not stop the JavaScript sqlite-js runs while it sets up a new connection. It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through db.exec (a long + * Stops the JavaScript that is running now, in every query on every connection: each running call fails with an "interrupted" error, and its connection is interrupted too, as sqlite3_interrupt() does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted INSERT, UPDATE or DELETE inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started: a query that has not reached its JavaScript yet runs it normally, so call it again until the query being stopped ends. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through db.exec (a long * next() or toArray()), finishes before the cancel reaches it. Safe from any thread. Android's own cancelling (a CancellationSignal) cannot stop a JavaScript function. */ public static native void cancelAll(); diff --git a/subprojects/sqlite-js/src/test/c/glue_test.c b/subprojects/sqlite-js/src/test/c/glue_test.c index af5385e3a5..5e5726ba9b 100644 --- a/subprojects/sqlite-js/src/test/c/glue_test.c +++ b/subprojects/sqlite-js/src/test/c/glue_test.c @@ -258,17 +258,38 @@ int main (void) { unlink(upper); // A cancel that lands while a stored function loads, from cancelAll() for a query on another - // connection, stops its code as it stops any JavaScript then running. The function is loaded - // again, rather than left out of this connection for good. + // connection, does not stop the function's own code: since 1.4.3 loading it sets the + // connection up, as loading the extension does, so it loads on the first try. + char loading[512]; + snprintf(loading, sizeof(loading), "%s/loading.db", dir); + db = open_with(loading, sqlite3_sqlitejs_init); + check(exec(db, "SELECT js_init_table()") == SQLITE_OK + && exec(db, "INSERT INTO js_functions (name, kind, step_code) VALUES ('v', 'scalar', " + "'(db.exec(\"SELECT cancel_once()\").next(), (function () { for (let i = 0; i < 1000000; i++); })(), " + "function (args) { return 6; })')") == SQLITE_OK, + "a database with a function v whose code cancels the first time it loads"); + sqlite3_close(db); + logged[0] = 0; + db = open_trusted_with_cancel_once(loading); + check(cancel_calls == 1, "the cancel does not stop v's code while it loads"); + check(answers(db, "SELECT v()", "6"), "v is loaded"); + check(strstr(logged, "stored function v did not load") == NULL, "it does not log that v did not load"); + sqlite3_close(db); + unlink(loading); + + // But it stops JavaScript that the code runs through SQL, which is a call of its own, and that + // fails the load. The function is loaded again, rather than left out of this connection. char cancelled[512]; snprintf(cancelled, sizeof(cancelled), "%s/cancelled.db", dir); db = open_with(cancelled, sqlite3_sqlitejs_init); check(exec(db, "SELECT js_init_table()") == SQLITE_OK && exec(db, "INSERT INTO js_functions (name, kind, step_code) VALUES ('w', 'scalar', " - "'(db.exec(\"SELECT cancel_once()\").next(), (function () { for (let i = 0; i < 1000000; i++); })(), " + "'(db.exec(\"SELECT cancel_once()\").next(), " + "db.exec(\"SELECT js_eval(''for (let i = 0; i < 1000000; i++); 1'')\").next(), " "function (args) { return 8; })')") == SQLITE_OK, - "a database with a function w whose code cancels the first time it loads"); + "a database with a function w whose code cancels the first time it loads, then runs JavaScript through SQL"); sqlite3_close(db); + cancel_calls = 0; logged[0] = 0; db = open_trusted_with_cancel_once(cancelled); check(cancel_calls == 2, "the trusted entry point loads w again after the cancel stops it"); @@ -286,9 +307,11 @@ int main (void) { check(exec(db, "SELECT js_init_table()") == SQLITE_OK && exec(db, "INSERT INTO js_functions (name, kind, step_code) VALUES ('h', 'scalar', " "'(globalThis.held = db.exec(\"SELECT 1 UNION ALL SELECT 2\"), held.next(), " - "db.exec(\"SELECT cancel_once()\").next(), (function () { for (let i = 0; i < 1000000; i++); })(), " + "db.exec(\"SELECT cancel_once()\").next(), " + "db.exec(\"SELECT js_eval(''for (let i = 0; i < 1000000; i++); 1'')\").next(), " "function (args) { return 9; })')") == SQLITE_OK, - "a database with a function h whose code keeps a result set open and cancels the first time it loads"); + "a database with a function h whose code keeps a result set open, cancels the first time it loads, " + "then runs JavaScript through SQL"); sqlite3_close(db); cancel_calls = 0; logged[0] = 0; diff --git a/subprojects/sqlite-js/test.sh b/subprojects/sqlite-js/test.sh index fc959acc20..cb66baf954 100755 --- a/subprojects/sqlite-js/test.sh +++ b/subprojects/sqlite-js/test.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Tests sqlite-js on this host: upstream's suite (test/main.c, not vendored) on its source with -# patches/ applied, then src/test/c/glue_test.c, the test of the Android entry points, on the +# any patches/ applied, then src/test/c/glue_test.c, the test of the Android entry points, on the # vendored upstream/. Run vendor.sh --check first: it shows the two are the same. # Usage: test.sh [TARBALL] (without TARBALL, downloads it) # Needs gcc, make, curl and a JDK (JAVA_HOME, or javac on the PATH) for jni.h. @@ -15,6 +15,7 @@ echo "$SHA256 $TARBALL" | sha256sum -c --quiet - SRC=$WORK/src mkdir "$SRC" tar -xzf "$TARBALL" -C "$SRC" --strip-components=1 +shopt -s nullglob # patches/ holds our changes not yet upstream, and may be empty or missing for p in "$HERE"/patches/*.patch; do patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch <"$p" done @@ -22,7 +23,7 @@ done # upstream's own build prints many warnings in QuickJS and SQLite: shown only if it fails build () { "$@" >"$WORK/build.log" 2>&1 || { cat "$WORK/build.log"; exit 1; }; } -echo "# upstream test suite with patches/" +echo "# upstream test suite" build make -C "$SRC" dist/js.so dist/main ( cd "$SRC" && ./dist/main ) @@ -39,7 +40,7 @@ build gcc -O1 -g -Wall -Wextra -Werror "${DEFS[@]}" "${INC[@]}" \ "$WORK/sqlitejs.o" "$WORK/quickjs.o" "$WORK/sqlite3.o" -o "$WORK/glue_test" -lm -lpthread -ldl "$WORK/glue_test" -# again with sqlite-js working as on SQLite before 3.41, which patch 0002 is for +# again with sqlite-js working as on SQLite before 3.41, where only a cancel stops a final that never ends echo "# sqlitejs_android.c, as on SQLite 3.40" build gcc -O1 -g -w "${DEFS[@]}" "${INC[@]}" -Dsqlite3_libversion_number=glue_sqlite3_libversion_number \ -c "$U/src/sqlitejs.c" -o "$WORK/sqlitejs-3.40.o" diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.c b/subprojects/sqlite-js/upstream/src/sqlitejs.c index 0a32d36354..538f4f2acd 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.c +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.c @@ -71,6 +71,7 @@ typedef struct { size_t stack_size; // in bytes, 0 for no check: see js_set_max_stack_size() int depth; // calls into JavaScript in progress: see js_enter() unsigned cancel_epoch; // js_cancel_epoch when the outermost call began + int setup_depth; // depth of a call that sets the connection up, 0 for none: see js_interrupt_handler() bool check_interrupted; // sqlite3_is_interrupted() is available struct rowset *rowsets; // result sets not yet freed: see js_end_rowsets() int orphans; // of those, the ones whose JavaScript object is gone @@ -351,8 +352,10 @@ static unsigned js_cancel_epoch_load (void) { } // Stops all JavaScript that is running now, in every connection: each call fails with an -// "interrupted" error, and the statement that called it is interrupted. JavaScript that begins -// afterwards runs normally. Safe from any thread. +// "interrupted" error, and the connection it was running on is interrupted, so every statement +// that connection has in progress fails with SQLITE_INTERRUPT too (see js_interrupt_handler). +// JavaScript that begins afterwards runs normally, and the JavaScript the extension itself runs +// to set a connection up is never stopped. Safe from any thread. // For hosts whose own cancelling cannot reach JavaScript: Android cancels a query with a // progress handler, which SQLite never calls while a JavaScript function runs. void sqlitejs_cancel_all (void) { @@ -370,11 +373,16 @@ static int js_interrupt_handler (JSRuntime *rt, void *opaque) { UNUSED(rt); globaljs_context *js = (globaljs_context *)opaque; js_keep_gc_below_limit(js); - // Only a call (see js_enter) is cancelled. The one exception is the JavaScript the extension - // itself runs while it initialises a connection (globaljs_init, depth 0): stopping it would - // make the connection fail to load. Stored functions loaded by js_init_table run as a call, - // so they can be cancelled. - if ((js->depth > 0) && (js->cancel_epoch != js_cancel_epoch_load())) { + // Only a call (see js_enter) is cancelled, and never the JavaScript the extension itself runs + // to set a connection up: while it loads the extension (globaljs_init, depth 0), and while + // js_init_table(1) restores the functions of the js_functions table (js_create_common, which + // records its depth in setup_depth). Stopping either leaves the connection short of what an + // app expects of it: a cancel during the first made it fail to load, and one during the second + // left it without its stored functions, each reported only by a statement an app need not look + // at. Like the depth 0 exemption, this one covers that call alone: JavaScript the loading code + // runs through SQL is a call of its own, at a greater depth, and is cancelled. And on SQLite + // 3.41 and later sqlite3_interrupt() still stops setup JavaScript that never ends, as always. + if ((js->depth > 0) && (js->depth != js->setup_depth) && (js->cancel_epoch != js_cancel_epoch_load())) { // The statement is interrupted too: a collation cannot report an error, so the // statement would go on calling JavaScript, each call beginning after the cancel. if (js->db) sqlite3_interrupt(js->db); @@ -1668,7 +1676,15 @@ static bool js_create_function (sqlite3_context *context, const char *type, cons bool js_create_common (sqlite3_context *context, const char *type, const char *name, const char *init_code, const char *step_code, const char *final_code, const char *value_code, const char *inverse_code, bool is_load) { globaljs_context *js = (globaljs_context *)sqlite3_user_data(context); js_enter(js); + // Restoring a function of the js_functions table (is_load) sets the connection up, as loading + // the extension does, so sqlitejs_cancel_all() does not stop it: see js_interrupt_handler(). + // Only this call is exempt, not JavaScript it runs through SQL, which is a call of its own at + // a greater depth. The previous value is kept for an is_load that a stored function's own code + // reaches through js_init_table(). + int setup_depth = js->setup_depth; + if (is_load) js->setup_depth = js->depth; bool ok = js_create_function(context, type, name, init_code, step_code, final_code, value_code, inverse_code, is_load); + js->setup_depth = setup_depth; js_leave(js); return ok; } diff --git a/subprojects/sqlite-js/upstream/src/sqlitejs.h b/subprojects/sqlite-js/upstream/src/sqlitejs.h index 7cf1ce3cfc..9d54f92281 100644 --- a/subprojects/sqlite-js/upstream/src/sqlitejs.h +++ b/subprojects/sqlite-js/upstream/src/sqlitejs.h @@ -16,13 +16,22 @@ #include "sqlite3.h" #endif -#define SQLITE_JS_VERSION "1.4.2" +#define SQLITE_JS_VERSION "1.4.3" int sqlite3_js_init (sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); const char *sqlitejs_version (void); const char *quickjs_version (void); -// Stops all JavaScript now running, in every connection. Safe to call from any thread. It -// stops only JavaScript already running: calls that begin afterwards are not affected. +// Stops all JavaScript now running, in every connection: each call into JavaScript fails with an +// "interrupted" error, and a result set it leaves open reads on as interrupted. Safe to call from +// any thread. +// It stops only JavaScript already running: calls that begin afterwards are not affected, and +// neither is the JavaScript the extension itself runs to set a connection up, while it loads the +// extension and while js_init_table(1) restores the functions of the js_functions table. +// A connection whose JavaScript is stopped is also interrupted, as sqlite3_interrupt() does it: +// a collation cannot report an error, so without that its sort would go on calling JavaScript. +// So any other statement that connection has in progress fails with SQLITE_INTERRUPT as well, +// and sqlite3_is_interrupted() stays true for it until the connection next prepares or steps a +// statement with none of its own still running, as after any sqlite3_interrupt(). void sqlitejs_cancel_all (void); #endif diff --git a/subprojects/sqlite-js/vendor.sh b/subprojects/sqlite-js/vendor.sh index 124e3aad79..b7bc0d3725 100755 --- a/subprojects/sqlite-js/vendor.sh +++ b/subprojects/sqlite-js/vendor.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash -# Rebuilds upstream/ from the sqlite-js release VERSION and patches/, or checks that it matches. +# Rebuilds upstream/ from the sqlite-js release VERSION and any patches/, or checks that it matches. # Usage: vendor.sh [--check] [TARBALL] (without TARBALL, downloads it) set -euo pipefail -VERSION=1.4.2 -SHA256=1aa4c566491f1b56f3fd676b80880fdccbf0806b8f3cd015f60cd0f1c171cf24 +VERSION=1.4.3 +SHA256=a2ed16f353757767188134f74fc9f0b07feefa96abfa56bcc211758b4105ad0a URL=https://github.com/sqliteai/sqlite-js/archive/refs/tags/$VERSION.tar.gz HERE=$(cd "$(dirname "$0")" && pwd) CHECK=false @@ -17,6 +17,7 @@ echo "$SHA256 $TARBALL" | sha256sum -c --quiet - SRC=$WORK/src mkdir "$SRC" tar -xzf "$TARBALL" -C "$SRC" --strip-components=1 +shopt -s nullglob # patches/ holds our changes not yet upstream, and may be empty or missing for p in "$HERE"/patches/*.patch; do patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch <"$p" done @@ -38,15 +39,15 @@ NOTICES="LICENSE:META-INF/LICENSE-sqlite-js.txt LICENSE.quickjs:META-INF/LICENSE RES=$HERE/src/main/resources if $CHECK; then for f in $FILES; do - cmp -s "$SRC/$f" "$HERE/upstream/$f" || { echo "upstream/$f is not sqlite-js $VERSION with patches/ applied" >&2; exit 1; } + cmp -s "$SRC/$f" "$HERE/upstream/$f" || { echo "upstream/$f is not sqlite-js $VERSION with any patches/ applied" >&2; exit 1; } done for n in $NOTICES; do cmp -s "$SRC/${n%%:*}" "$RES/${n#*:}" || { echo "src/main/resources/${n#*:} is not ${n%%:*}" >&2; exit 1; } done - echo "upstream/ is sqlite-js $VERSION with patches/ applied" + echo "upstream/ is sqlite-js $VERSION with any patches/ applied" else rm -rf "$HERE/upstream" for f in $FILES; do install -D -m 644 "$SRC/$f" "$HERE/upstream/$f"; done for n in $NOTICES; do install -D -m 644 "$SRC/${n%%:*}" "$RES/${n#*:}"; done - echo "upstream/ rebuilt from sqlite-js $VERSION and patches/" + echo "upstream/ rebuilt from sqlite-js $VERSION and any patches/" fi From d6e0d1ab5528eb5d964ff30ada4c8244f40f0ea0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 01:02:14 -0800 Subject: [PATCH 064/203] style: spotless rewrap of the cancelAll() javadoc, no functional change Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../src/main/java/org/appdevforall/sqlitejs/SqliteJs.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java b/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java index b52db57660..f829bb88c9 100644 --- a/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java +++ b/subprojects/sqlite-js/src/main/java/org/appdevforall/sqlitejs/SqliteJs.java @@ -31,8 +31,8 @@ public final class SqliteJs { } /** - * Stops the JavaScript that is running now, in every query on every connection: each running call fails with an "interrupted" error, and its connection is interrupted too, as sqlite3_interrupt() does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted INSERT, UPDATE or DELETE inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started: a query that has not reached its JavaScript yet runs it normally, so call it again until the query being stopped ends. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through db.exec (a long - * next() or toArray()), finishes before the cancel reaches it. Safe from any thread. Android's own cancelling (a CancellationSignal) cannot stop a JavaScript function. + * Stops the JavaScript that is running now, in every query on every connection: each running call fails with an "interrupted" error, and its connection is interrupted too, as sqlite3_interrupt() does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted INSERT, UPDATE or DELETE inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started: a query that has not reached its JavaScript yet runs it normally, so call it again until the query being stopped ends. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, + * and while it loads each stored function. It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through db.exec (a long next() or toArray()), finishes before the cancel reaches it. Safe from any thread. Android's own cancelling (a CancellationSignal) cannot stop a JavaScript function. */ public static native void cancelAll(); From 0c2e603eeae6d4bdc3324ea40f4e82040612021c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 01:05:54 -0800 Subject: [PATCH 065/203] ADFA-7082: Answer the independent review of the 1.4.3 move No correctness defects; two nits: - F01: two glue-test comments still credited "patch 0002" for what sqlite-js 1.4.3 now does. - F02: the v test assumed cancel_calls was still 0; it now resets it, as the w and h tests do. Glue test 50 of 50 normally and as on SQLite 3.40. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- subprojects/sqlite-js/src/test/c/glue_test.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-js/src/test/c/glue_test.c b/subprojects/sqlite-js/src/test/c/glue_test.c index 5e5726ba9b..95f83a97c2 100644 --- a/subprojects/sqlite-js/src/test/c/glue_test.c +++ b/subprojects/sqlite-js/src/test/c/glue_test.c @@ -269,6 +269,7 @@ int main (void) { "function (args) { return 6; })')") == SQLITE_OK, "a database with a function v whose code cancels the first time it loads"); sqlite3_close(db); + cancel_calls = 0; logged[0] = 0; db = open_trusted_with_cancel_once(loading); check(cancel_calls == 1, "the cancel does not stop v's code while it loads"); @@ -325,7 +326,7 @@ int main (void) { // A result set JavaScript keeps is ended when the call that made it returns (sqlite-js 1.4.2), // or the interrupt would stay in effect and every later statement on the connection fail. // After a cancel, reading on throws "interrupted", also as on SQLite before 3.41 - // (GLUE_AS_SQLITE_3_40), where only the cancel itself shows it (patch 0002). + // (GLUE_AS_SQLITE_3_40), where only the cancel itself shows it (sqlite-js 1.4.3). signal(SIGALRM, on_alarm); char kept[512]; snprintf(kept, sizeof(kept), "%s/kept.db", dir); @@ -340,7 +341,7 @@ int main (void) { // Ending a result set that is computing a window function runs the function's final. The finals // belong to the call that kept the result sets, so its cancel must stop every one of them, also - // before SQLite 3.41 (patch 0002). + // before SQLite 3.41 (sqlite-js 1.4.3). check(exec(db, "SELECT js_create_window('loop_final', 'total = 0;', '(function (args) { total += args[0]; })', " "'(function () { while (true) {} })', '(function () { return total; })', " "'(function (args) { total -= args[0]; })')") == SQLITE_OK, From f46e68e2a96908dc97a8b8b69ebd49b913f85974 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 09:57:46 -0800 Subject: [PATCH 066/203] ADFA-7082: Record the phone run of the 1.4.3 build On the Note20, with an AAR built from 0c2e603ee: the trial app passes 7 of 7 as a 64-bit and as a 32-bit process, on a new and an existing database, and the template (dev-assets #79) stops its runaway query 11 to 12 ms after Cancel in its 64-bit and 32-bit debug builds and its release build. The README said the 1.4.3 build had not run on a phone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- subprojects/sqlite-js/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/sqlite-js/README.md b/subprojects/sqlite-js/README.md index 45948b157c..7fff743dba 100644 --- a/subprojects/sqlite-js/README.md +++ b/subprojects/sqlite-js/README.md @@ -38,7 +38,7 @@ Room.databaseBuilder(context, AppDb::class.java, name).openHelperFactory(factory - SQLite loads the extension from a file, so set `packaging.jniLibs.useLegacyPackaging = true`. - Neither Room nor Android's cancelling can stop a JavaScript function that never returns: Room 2.7 and later pass no cancellation signal, and Android cancels with a progress handler, which SQLite never calls while a function runs. `SqliteJs.cancelAll()` stops the JavaScript running at that moment, in every query on every connection: each call fails with "interrupted", and its connection is interrupted too, as `sqlite3_interrupt()` does it, so that a statement whose JavaScript cannot report an error (a collation) also stops, and so does any other statement that connection has in progress. That includes calls in queries the app did not mean to stop, which then need to be retried. An interrupted `INSERT`, `UPDATE` or `DELETE` inside an explicit transaction rolls the whole transaction back, so retry the transaction, not only the statement. So call it only when a runaway function is known to be running, for example from a Cancel button, not whenever a coroutine is cancelled. It stops only JavaScript that has started, so call it again until the query being stopped ends, as the template's `cancellable()` does. It does not stop the JavaScript sqlite-js runs while it sets up a connection: while it loads, and while it loads each stored function. The `db.exec` result sets of a call it stops are ended, and reading on from one throws "interrupted". It takes effect when JavaScript next runs: SQL that the JavaScript runs itself, through `db.exec` (a long `next()` or `toArray()`), finishes before the cancel reaches it. -Built from 1.4.1 with our patches of the time, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 25 ms. The build from 1.4.2 with our two cancel patches, which 1.4.3 has, passed the trial app's checks in both processes and on both databases, and the template stopped its runaway query 11 to 13 ms after Cancel. The build from 1.4.3 has not been run on a phone yet. +Built from 1.4.1 with our patches of the time, it was tested in a trial app (requery 3.49.0, Room 2.8.4) on a Galaxy Note20 Ultra, as a 64-bit and as a 32-bit process, on a new and an existing database, with Room's default write-ahead logging: a scalar and an aggregate from DAOs, deep recursion from four pool threads, 32 parallel queries, and a runaway query stopped by `cancelAll()` within 25 ms. The build from 1.4.2 with our two cancel patches, which 1.4.3 has, passed the trial app's checks in both processes and on both databases, and the template stopped its runaway query 11 to 13 ms after Cancel. The build from 1.4.3 passed the same checks, and the template stopped its runaway query 11 to 12 ms after Cancel, in its 64-bit and 32-bit debug builds and its release build. ## Testing From 627aa94c61882f735a0a739e1eb30d53dbbe07c4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 10:45:36 -0800 Subject: [PATCH 067/203] ADFA-7138: Say how to turn the SQLite debugger on in an app Adds a how-to for existing projects to the debugger's README (ADFA-7138, item 5): the gradle.properties line, requery's AAR in libs/, the androidx libraries requery needs, and what to expect in a debug build. It says what the line changes (every variant moves to requery, Quick Build is off), that commenting it out turns it off, and that Room's BundledSQLiteDriver is not covered. The details stay in gradle-plugin/docs/sqlite-rewrite.md, which it links to. The template line itself is in dev-assets, on sqlite-debugger/ADFA-7138, stacked on dev-assets#79. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 08f92e3e6d..36a5d61128 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -4,6 +4,19 @@ A debug-only SQLite debugger and MCP server that runs inside apps built with Cod The module builds an AAR with `libsqlitedbg.so` for arm64-v8a and armeabi-v7a in one artifact, so it has no v7/v8 flavors (`AndroidModuleConf`). Its minSdk is 21, requery's, because the debugger runs on requery's SQLite. The unit test task is `:subprojects:sqlite-debugger:testDebugUnitTest`. +## Turning it on in an app + +A project made from the JavaScript in SQLite template has it on already. For any other project: + +1. Add `cogo.sqliteDebugger=true` to the project's `gradle.properties` ([where else it can go](../../gradle-plugin/docs/sqlite-rewrite.md#turning-it-on)). +2. Copy `app/libs/sqlite-android.aar` (requery) from a project made from that template into the app's `libs/`, and add `implementation(files("libs/sqlite-android.aar"))`. +3. Check that the app depends on androidx.sqlite (Room and WorkManager bring it) and androidx.core (AppCompat brings it). requery needs both, and a file dependency brings neither. +4. Build and run the debug variant. The app starts the server and sends its port and token to Code on the Go (ADFA-7137), and AI-Agent-MCP connects to it with no setup (ADFA-7139). In phase 1 the Agent asks before each call (ADFA-7147). + +The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. Commenting the line out turns all of this off. + +Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails and names the class, method and line; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). + ## How it fits together ``` From 5b54c337903b8ff18f3be2b16942b5b36ace6ded Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 10:58:37 -0800 Subject: [PATCH 068/203] ADFA-7135: Correct two README lines the CI and device work made false "No workflow runs either yet" has been false since the test-sqlite-debugger workflow: it runs test.sh, the C and JNI tests. The JVM tests are still in no workflow, which the line now says. "Nothing has run in an app on a device" has been false since the device runs recorded on ADFA-7135. What is left is a device run of the current code, because those results predate the review fixes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 55b60427e7..9b32e7c718 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -44,11 +44,11 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). -No workflow in `.github/workflows` runs either yet. +`.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. No workflow runs the JVM tests. ## Not done yet - Broadcasting the port and token to Code on the Go (ADFA-7137). `DebuggerStartup` only keeps them in `DebuggerStartup.port` and `endpointToken` and logs the port, never the token. - Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138). - The AI-Agent-MCP side that connects to the server (ADFA-7139). -- Verification on a device. The C tests run on the host and the Kotlin tests on the JVM; nothing has run in an app on a device or emulator. +- A device run of the current code. The device results on ADFA-7135 (statements captured on both ABIs, the overhead) predate the review fixes. From 2394a80e8dada7c41246c2263e5672862b4b7f44 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 10:59:54 -0800 Subject: [PATCH 069/203] ADFA-7138: Say how to build when the rewrite fails on a library class The rewrite fails the build on a class that uses something requery lacks, naming class, method and line. For the app's own code that is enough; for a library class the user cannot change, the message gave no way out. It now ends with one: comment out cogo.sqliteDebugger=true in gradle.properties to build without the SQLite debugger. The transform cannot tell an app class from a library class, so the line covers both. The fail rule itself stays (decided 2026-11-16): the rewrite runs in release builds too, so a warning would let a released app ship a call that crashes when it runs. The new test fails without the change (its "in a library" check); the rewrite tests pass with it. The rewrite doc and the debugger README say the message now carries the way out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 ++- .../gradle/sqlite/SqliteRewriter.kt | 8 ++++++- .../gradle/sqlite/SqliteRewriterTest.kt | 24 +++++++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 2472d1d548..92c4da1c2d 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -69,7 +69,8 @@ cannot load, so the transform runs only on projects that opted in. Commenting th (requery's cursors extend its own copies of the first two, and implement only `android.database.Cursor`). A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported. `COLLATE LOCALIZED` only logs a warning: it works, but - compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together. A platform method outside the renamed set whose + compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together, with + the way out for a library class, which the user cannot change: comment out `cogo.sqliteDebugger=true`. A platform method outside the renamed set whose descriptor mentions a renamed class (found with javap over android.jar: the other `DatabaseUtils` methods `blobFileDescriptorForQuery` and `bindObjectToProgram`, `DatabaseUtils$InsertHelper`, `OpenParams` accessors) cannot link once the descriptor is renamed, so a call to one that is not redirected above fails diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index f356a6e93f..18553c7e58 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -75,6 +75,11 @@ enum class RewritePolicy( } object SqliteRewriter { + /** The transform cannot tell an app class from a library class, so the message covers both. */ + private const val WAY_OUT = + "If this class is the app's, change the code above. If it is in a library, the library cannot run on " + + "requery: comment out cogo.sqliteDebugger=true in gradle.properties to build without the SQLite debugger." + private val remapper = object : Remapper() { override fun map(internalName: String): String = Rules.RENAMES[internalName] ?: internalName @@ -158,7 +163,8 @@ object SqliteRewriter { if (violations.isNotEmpty()) { throw SqliteRewriteException( "Code on the Go cannot move '${cn.name.replace('/', '.')}' from android.database.sqlite to " + - "requery (cogo.sqliteDebugger=true):\n" + violations.joinToString("\n") { " - $it" }, + "requery (cogo.sqliteDebugger=true):\n" + violations.joinToString("\n") { " - $it" } + + "\n" + WAY_OUT, ) } } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 36bfbf40fd..70e7e6e7b2 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -415,6 +415,30 @@ class SqliteRewriterTest { assertThat(message).contains("SQLiteQueryBuilder.setStrictGrammar") } + @Test + fun `the failure says how to build when the class is in a library`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Lib", + """ + package p; + public class Lib { + void one(android.database.sqlite.SQLiteDatabase db) { + db.execPerConnectionSQL("x", null); + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Lib"]!!, hierarchy) } + val lastLine = e.message!!.lines().last() + assertThat(lastLine).contains("in a library") + assertThat(lastLine).contains("comment out cogo.sqliteDebugger=true in gradle.properties") + } + @Test fun `a missing member is found through every renamed ancestor of the owner`() { val classes = diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 36a5d61128..a23365bc11 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -15,7 +15,7 @@ A project made from the JavaScript in SQLite template has it on already. For any The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. Commenting the line out turns all of this off. -Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails and names the class, method and line; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). +Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails, names the class, method and line, and says how to build without the debugger; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). ## How it fits together From efc07f76ed980228cdb064726999a00d41bf705a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:27:47 -0800 Subject: [PATCH 070/203] ADFA-7138: Stub the module directory in the Quick Build provisioner fakes 2c78e0af9 made the opt-in check read each app module's projectDirPath, but the shared test double androidModule() did not stub it, so mockk threw, runProxyAppBuild caught it as a build failure, and 21 of the 43 GradleQuickBuildProvisioner* tests failed with the generic failure (FailureArms 9, Signing 7, Baseline 3, BuildDir 2). None of the PR's checks runs :app's unit tests. androidModule() now takes a projectDir (default /fake-project/app), and testProvisioner's default module sits under the test's project root. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisionerFakes.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt index b46b121d99..fd4f00882d 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt @@ -144,15 +144,19 @@ internal fun unsyncedProjectManager(projectRoot: File): FakeProjectManager = Fak * @param variantName the selected variant, or null for the mid-sync read the provisioner * falls back to the default variant on. * @param buildDir the module's build directory as the synced model reports it. + * @param projectDir the module's directory, where the SQLite debugger opt-in check reads its + * `gradle.properties`. */ internal fun androidModule( path: String = ":app", variantName: String? = "debug", buildDir: File = File("/fake-project/app/build"), + projectDir: File = File("/fake-project/app"), ): AndroidModule = mockk().also { module -> every { module.path } returns path every { module.buildDirPath } returns buildDir.path + every { module.projectDirPath } returns projectDir.path every { module.getSelectedVariant() } returns variantName?.let { AndroidModels.AndroidVariant @@ -257,7 +261,10 @@ internal fun testProvisioner( projectRoot: File, buildService: BuildService? = FakeBuildService(), projectManager: IProjectManager = - FakeProjectManager(projectRoot, appModules = listOf(androidModule(buildDir = File(projectRoot, "app/build")))), + FakeProjectManager( + projectRoot, + appModules = listOf(androidModule(buildDir = File(projectRoot, "app/build"), projectDir = File(projectRoot, "app"))), + ), installer: ProxyAppInstaller = recordingInstaller(), packages: InstalledPackages = FakePackages(), apkCertSha256: (File) -> String? = { null }, From 1407eae8c09ddac08c0c135a5d0d35937ea3a099 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:27:57 -0800 Subject: [PATCH 071/203] ADFA-7138: Check a module's SQLite debugger opt-in after the sync too The Quick Build opt-in check ran before awaitProjectModel. While the Gradle sync has not published the model, getAndroidAppModules() is empty, so a tap during the sync read only the user home's and the root's gradle.properties. A project with cogo.sqliteDebugger=true in its app module's own file was staged and built, and ended in "variant setup missing". The check still runs first, so a root or user home opt-in is refused at once as before. When the model was not ready then, it runs again after the wait, with the modules. In that case staging (into Code on the Go's own quickbuild directory, not the project) has already run, which a refused build can afford. A model that is ready at the tap sees no change. Test: GradleQuickBuildProvisionerFailureArmsTest, an opt-in in the app module's gradle.properties with the modules published during staging is refused with quick_build_disabled_sqlite_debugger and runs no build. Without the fix it gets quick_build_variant_setup_missing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 49 +++++++++++++------ ...dleQuickBuildProvisionerFailureArmsTest.kt | 29 +++++++++++ .../GradleQuickBuildProvisionerFakes.kt | 17 +++++++ 3 files changed, 79 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 28bc92cec4..635fa875ed 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -344,22 +344,12 @@ class GradleQuickBuildProvisioner( val projectManager = lookupProjectManager() val projectRoot = File(projectManager.projectDirPath) - // Before staging, which writes into the project: the Gradle plugin never applies Quick Build - // to an opted-in project, so building would only end in "variant setup missing". - QuickBuildProjectSupport - .sqliteDebuggerMessage( - QuickBuildProjectSupport.isSqliteDebuggerEnabled( - projectRoot, - Environment.GRADLE_USER_HOME, - projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, - ), - )?.let { refusal -> - log.info( - "Quick Build is not provisioned: {} is true in the project's or the Gradle user home's gradle.properties", - GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, - ) - return ProxyAppBuildResult.Failed(context.getString(refusal)) - } + // Before staging, which a refused build need not pay for: the Gradle plugin never applies Quick + // Build to an opted-in project, so building would only end in "variant setup missing". During + // a sync the model has no app modules yet, so an opt-in in a module's own gradle.properties is + // seen only by the second check, after the wait for the model. + val modulesKnown = projectManager.workspace != null + sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } stage(context, paths) // The project model only exists once CoGo's Gradle sync has populated it, and a tap @@ -372,6 +362,9 @@ class GradleQuickBuildProvisioner( context.getString(R.string.quick_build_waiting_for_sync), ) } + if (!modulesKnown) { + sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } + } val module = quickBuildModule(projectManager) @@ -543,6 +536,30 @@ class GradleQuickBuildProvisioner( } } + /** + * The refusal for a project with `cogo.sqliteDebugger=true`, or null. It reads the app modules' + * own `gradle.properties` only for the modules [projectManager] knows, which is none before the + * sync publishes the model. + */ + private fun sqliteDebuggerRefusal( + projectManager: IProjectManager, + projectRoot: File, + ): ProxyAppBuildResult.Failed? { + val refusal = + QuickBuildProjectSupport.sqliteDebuggerMessage( + QuickBuildProjectSupport.isSqliteDebuggerEnabled( + projectRoot, + Environment.GRADLE_USER_HOME, + projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, + ), + ) ?: return null + log.info( + "Quick Build is not provisioned: {} is true in the Gradle user home's, an app module's or the project's gradle.properties", + GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, + ) + return ProxyAppBuildResult.Failed(context.getString(refusal)) + } + /** `:app` -> `/app`; nested paths (`:feature:home`) map to nested dirs. */ private fun moduleDir( projectRoot: File, diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt index dbb526cced..01913f067d 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt @@ -89,6 +89,35 @@ class GradleQuickBuildProvisionerFailureArmsTest { assertThat(gradle.executedTasks).isNull() } + @Test + fun `an opt-in in the app module's gradle properties is refused when the tap comes during the sync`() = + runTest { + val moduleDir = moduleDir() + File(moduleDir, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + val gradle = FakeBuildService() + val project = + SyncingProjectManager( + FakeProjectManager( + projectRoot, + appModules = listOf(androidModule(buildDir = File(moduleDir, "build"), projectDir = moduleDir)), + ), + ) + + val outcome = + testProvisioner( + context = context, + projectRoot = projectRoot, + buildService = gradle, + projectManager = project, + // The sync publishes the modules while Quick Build stages, so only a check made after + // the wait for the model can read the module's gradle.properties. + stage = { _, _ -> project.published = true }, + ).provision() + + assertThat(failureText(outcome)).isEqualTo(context.getString(R.string.quick_build_disabled_sqlite_debugger)) + assertThat(gradle.executedTasks).isNull() + } + @Test fun `a slot that goes busy between the staging and the build still reads as a busy slot`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt index fd4f00882d..eb6e4c9022 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt @@ -133,6 +133,23 @@ internal class FakeProjectManager( */ internal fun unsyncedProjectManager(projectRoot: File): FakeProjectManager = FakeProjectManager(projectRoot, workspace = null) +/** + * A project model that has no workspace and no modules until [published] is set, when it answers + * as [synced] does: a tap during the sync, and the sync finishing while Quick Build works. + */ +internal class SyncingProjectManager( + private val synced: FakeProjectManager, +) : IProjectManager by synced { + var published = false + + override val workspace: Workspace? + get() = if (published) synced.workspace else null + + override fun getAndroidModules(): List = if (published) synced.getAndroidModules() else emptyList() + + override fun getAndroidAppModules(): List = if (published) synced.getAndroidAppModules() else emptyList() +} + /** * An Android module as the Build Variants sidebar presents it. * From 7a227633b96164f52b59c6e91bfd8cb043d33f50 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:27:57 -0800 Subject: [PATCH 072/203] ADFA-7138: Require androidx.core in the rewrite's classpath check checkSqliteRewriteClasspath required requery's and androidx.sqlite's classes but not androidx.core's, which requery 3.49.0 needs too. jdeps and javap over the classes.jar of the template's sqlite-android.aar: 12 requery classes reference androidx.core.os.CancellationSignal; SQLiteSession calls its throwIfCanceled, SQLiteConnection and SQLiteConnectionPool call setOnCancelListener, SQLiteDatabase.query(SupportSQLiteQuery, android.os.CancellationSignal) constructs one, and SQLiteConnectionPool constructs androidx.core.os.OperationCanceledException. The rewrite's own SqliteRewriteRuntime.toCancellationSignal constructs one for every converted signal. An app with androidx.sqlite but without androidx.core passed the check and fails with NoClassDefFoundError on the first query that passes a cancellation signal. The check now also requires androidx/core/os/CancellationSignal.class (present in androidx.core 1.9.0 through 1.16.0), and the message says how to add androidx.core. The rewrite doc lists what requery takes from each library, including androidx.collection's LruCache, which requery's statement cache extends and which androidx.core brings. Tests: SqliteRewritePluginTest, a new case excludes androidx.core and expects its entry and coordinates in the message; the requery and androidx.sqlite cases assert the real androidx.core AAR satisfies the check; the passing case uses a stand-in jar for androidx.core too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 13 ++++--- .../sqlite/CheckSqliteRewriteClasspathTask.kt | 13 +++++-- .../gradle/SqliteRewritePluginTest.kt | 38 +++++++++++++++++-- 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 92c4da1c2d..ff317cac29 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -16,10 +16,12 @@ An existing project needs: and logs a file it cannot read; it does not see `-P` arguments, which Code on the Go does not pass for this. 2. requery's AAR (`sqlite-android.aar`) in the app's `libs/`, as a file dependency (`implementation(files("libs/sqlite-android.aar"))`), as the ADFA-7082 template does. -3. androidx.sqlite on the runtime classpath (`androidx.sqlite:sqlite`, which Room, WorkManager and most androidx - libraries bring). A file dependency brings none of the dependencies of the AAR, and requery implements - androidx.sqlite's interfaces. It also calls `androidx.core.os.CancellationSignal`, which AppCompat's - androidx.core provides. +3. androidx.sqlite and androidx.core on the runtime classpath (`androidx.sqlite:sqlite`, which Room, WorkManager + and most androidx libraries bring, and `androidx.core:core`, which AppCompat brings). A file dependency brings + none of the dependencies of the AAR: requery implements androidx.sqlite's interfaces, takes and calls + androidx.core's `CancellationSignal` (the rewrite converts android's signal to it) and throws its + `OperationCanceledException`, and its statement cache extends androidx.collection's `LruCache`, which + androidx.core brings. The helper classes the rewrite redirects to (`SqliteRewriteRuntime`) are not in `libs/`: Code on the Go bundles `subprojects/sqlite-rewrite-runtime`'s release AAR, extracts it with the other tools and passes its path as @@ -31,7 +33,8 @@ the rewrite is already registered for it, so going on would give an app that thr A task `checkSqliteRewriteClasspath` runs before the compile and the transform of each variant. It fails with an actionable message when the variant's runtime classpath has no -`io/requery/android/database/sqlite/SQLiteDatabase.class` or `androidx/sqlite/db/SupportSQLiteDatabase.class`. +`io/requery/android/database/sqlite/SQLiteDatabase.class`, `androidx/sqlite/db/SupportSQLiteDatabase.class` or +`androidx/core/os/CancellationSignal.class`. The property is required because requery reaches apps only through `libs/`. Without it the rewritten classes cannot load, so the transform runs only on projects that opted in. Commenting the line out turns it off. diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt index 39422df3fb..38ed312638 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/CheckSqliteRewriteClasspathTask.kt @@ -14,8 +14,10 @@ import java.util.zip.ZipFile /** * Fails the build, before anything is compiled or rewritten, when the variant's runtime classpath - * lacks what the rewritten classes load: requery itself and androidx.sqlite. requery reaches an app - * as a file dependency from `libs/`, which brings none of its own dependencies. + * lacks what the rewritten classes load: requery itself, androidx.sqlite (whose interfaces requery + * implements) and androidx.core (whose CancellationSignal requery's API takes, and the rewrite + * converts android's signal to). requery reaches an app as a file dependency from `libs/`, which + * brings none of its own dependencies. */ abstract class CheckSqliteRewriteClasspathTask : DefaultTask() { @get:Input @@ -54,11 +56,13 @@ abstract class CheckSqliteRewriteClasspathTask : DefaultTask() { companion object { internal const val REQUERY_ENTRY = "io/requery/android/database/sqlite/SQLiteDatabase.class" internal const val ANDROIDX_SQLITE_ENTRY = "androidx/sqlite/db/SupportSQLiteDatabase.class" + internal const val ANDROIDX_CORE_ENTRY = "${SqliteRewriteRules.CORE_SIGNAL}.class" private val REQUIRED = listOf( "requery's SQLiteDatabase ($REQUERY_ENTRY)" to REQUERY_ENTRY, "androidx.sqlite's SupportSQLiteDatabase ($ANDROIDX_SQLITE_ENTRY)" to ANDROIDX_SQLITE_ENTRY, + "androidx.core's CancellationSignal ($ANDROIDX_CORE_ENTRY)" to ANDROIDX_CORE_ENTRY, ) internal fun message( @@ -67,8 +71,9 @@ abstract class CheckSqliteRewriteClasspathTask : DefaultTask() { ) = "cogo.sqliteDebugger=true moves the app to requery, but the runtime classpath of variant '$variant' has no " + missing.joinToString(" and no ") + ". requery's AAR comes from the project's libs/ directory as a file dependency, which brings none of its own " + - "dependencies: add requery's AAR to libs/ (implementation(files(\"libs/sqlite-android.aar\"))) and androidx.sqlite " + - "(implementation(\"androidx.sqlite:sqlite:\"), or a library that depends on it, such as Room or WorkManager). " + + "dependencies: add requery's AAR to libs/ (implementation(files(\"libs/sqlite-android.aar\"))), androidx.sqlite " + + "(implementation(\"androidx.sqlite:sqlite:\"), or a library that depends on it, such as Room or WorkManager) " + + "and androidx.core (implementation(\"androidx.core:core:\"), or a library that depends on it, such as AppCompat). " + "Remove cogo.sqliteDebugger from gradle.properties to build without them." /** The tasks of a variant that must not start before the check: compiling and the rewrite itself. */ diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt index 03924efb01..93514157a2 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt @@ -15,14 +15,15 @@ import java.nio.file.Path /** * The helpers the rewritten classes call (ADFA-7138) are injected by Code on the Go into every variant of a - * project that opted in, and a per-variant task checks that requery and androidx.sqlite are on the - * runtime classpath before anything is compiled. + * project that opted in, and a per-variant task checks that requery, androidx.sqlite and androidx.core are on + * the runtime classpath before anything is compiled. */ class SqliteRewritePluginTest { private val runtimeAarName = "sqlite-rewrite-runtime-release.aar" private val allVariants = listOf("demoDebug", "fullDebug", "demoRelease", "fullRelease") private val requeryEntry = CheckSqliteRewriteClasspathTask.REQUERY_ENTRY private val androidxSqliteEntry = CheckSqliteRewriteClasspathTask.ANDROIDX_SQLITE_ENTRY + private val androidxCoreEntry = CheckSqliteRewriteClasspathTask.ANDROIDX_CORE_ENTRY private fun build( dir: File, @@ -119,7 +120,9 @@ class SqliteRewritePluginTest { assertThat(message).contains("variant 'demoDebug'") assertThat(message).contains(requeryEntry) + // the sample project's Room and AppCompat bring the real AARs, which the check must find assertThat(message).doesNotContain(androidxSqliteEntry) + assertThat(message).doesNotContain(androidxCoreEntry) assertThat(message).contains("file dependency") assertThat(message).contains("brings none of its own dependencies") } @@ -141,22 +144,49 @@ class SqliteRewritePluginTest { assertThat(message).contains(androidxSqliteEntry) assertThat(message).doesNotContain("requery's SQLiteDatabase") + assertThat(message).doesNotContain(androidxCoreEntry) } @Test - fun `the check passes with stand-in jars that contain the two class entries, and is reused from the configuration cache`( + fun `the check fails without androidx core, whose CancellationSignal requery's API takes`( + @TempDir dir: File, + ) { + val requery = jar(dir, "requery.jar", requeryEntry) + val project = + project( + dir, + """ + configurations.all { exclude(group = "androidx.core") } + dependencies { implementation(files("${requery.invariantSeparatorsPath}")) } + """.trimIndent(), + ) + val message = failureOf { build(dir, ":app:checkDemoDebugSqliteRewriteClasspath", project = project) } + + assertThat(message).contains(androidxCoreEntry) + assertThat(message).contains("androidx.core:core") + assertThat(message).doesNotContain("requery's SQLiteDatabase") + assertThat(message).doesNotContain(androidxSqliteEntry) + } + + @Test + fun `the check passes with stand-in jars that contain the three class entries, and is reused from the configuration cache`( @TempDir dir: File, ) { val requery = jar(dir, "requery.jar", requeryEntry) val sqlite = jar(dir, "sqlite.jar", androidxSqliteEntry) + val core = jar(dir, "core.jar", androidxCoreEntry) val project = project( dir, """ - configurations.all { exclude(group = "androidx.sqlite") } + configurations.all { + exclude(group = "androidx.sqlite") + exclude(group = "androidx.core") + } dependencies { implementation(files("${requery.invariantSeparatorsPath}")) implementation(files("${sqlite.invariantSeparatorsPath}")) + implementation(files("${core.invariantSeparatorsPath}")) } """.trimIndent(), ) From 157387859673e06c062c66de94475fb2f221ecf8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:27:57 -0800 Subject: [PATCH 073/203] ADFA-7138: Make every missing-member entry name its descriptors MISSING_MEMBERS' builder no() defaulted desc to "", and its KDoc promised an empty set for "every descriptor". The two readers disagreed on that sentinel: SqliteRewriter.decide matched an empty set, fieldProblem and MISSING_FIELD_NAMES matched "". A method entry written without a descriptor would have been stored as {""} and matched no call, so the unsupported call would have passed the rewrite and thrown NoSuchMethodError on the device. No entry used the default, so nothing misbehaved. The descriptor is now required, and the "every descriptor" meaning is gone: decide and fieldProblem match the listed descriptors only, and SqliteRewriteResolutionTest no longer treats a trailing ":" as a wildcard. Requiring it is clearer than an empty-set sentinel in a builder that adds to a set, where a member listed once without and once with a descriptor would end up narrowed to the one. Test: SqliteRewriteRulesTest checks that every entry lists at least one descriptor and that each parses as a JVM descriptor (no blank). It cannot fail on the old code, whose entries all had descriptors, and a call without one no longer compiles; with the old default and one such call added, it fails on that entry's '' descriptor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriteRules.kt | 8 ++++---- .../gradle/sqlite/SqliteRewriter.kt | 4 ++-- .../sqlite/SqliteRewriteResolutionTest.kt | 3 +-- .../gradle/sqlite/SqliteRewriteRulesTest.kt | 20 +++++++++++++++++++ 4 files changed, 27 insertions(+), 8 deletions(-) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index 56281d05e7..b238f290b9 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -83,15 +83,15 @@ internal object SqliteRewriteRules { ) /** - * Members requery lacks, or has with another meaning. Key: "owner.name" -> descriptors, or an - * empty set for every descriptor (fields and the like). + * Members requery lacks, or has with another meaning. Key: "owner.name" -> the descriptors it lacks; + * other overloads are not matched, so every entry names its descriptors. */ val MISSING_MEMBERS: Map> = buildMap> { fun no( owner: String, name: String, - desc: String = "", + desc: String, ) { getOrPut("$SQLITE_PKG$owner.$name") { mutableSetOf() }.add(desc) } @@ -174,7 +174,7 @@ internal object SqliteRewriteRules { .filter { it != "" } .toSet() - /** Names of the fields the missing-member rule can match: entries for every descriptor, or with a field descriptor. */ + /** Names of the fields the missing-member rule can match: entries with a field descriptor. */ val MISSING_FIELD_NAMES: Set = MISSING_MEMBERS .filterValues { descs -> descs.any { !it.startsWith("(") } } diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 18553c7e58..96628ae14b 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -383,7 +383,7 @@ object SqliteRewriter { // only SQLiteCursor.mWindow is listed today; skip the hierarchy lookup for every other field if (name !in Rules.MISSING_FIELD_NAMES) return null return renamedAncestors(owner) - .firstOrNull { Rules.MISSING_MEMBERS["$it.$name"]?.let { descs -> "" in descs || desc in descs } == true } + .firstOrNull { Rules.MISSING_MEMBERS["$it.$name"]?.contains(desc) == true } ?.let { "${simple(it)}.$name does not exist in requery" } } @@ -483,7 +483,7 @@ object SqliteRewriter { return Action.None } for (c in ancestors) { - if (Rules.MISSING_MEMBERS["$c.$name"]?.let { it.isEmpty() || desc in it } == true) { + if (Rules.MISSING_MEMBERS["$c.$name"]?.contains(desc) == true) { return Action.Fail("${simple(c)}.$name$desc does not exist in requery") } } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt index 0661826724..01bab6fa4a 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteResolutionTest.kt @@ -178,8 +178,7 @@ class SqliteRewriteResolutionTest { } val unexpected = failed.filterNot { f -> - expected.contains(f) || expected.any { it.endsWith(":") && f.startsWith(it) } || - f.contains("OpenParams") || f.contains("android/database/CursorWindow") + expected.contains(f) || f.contains("OpenParams") || f.contains("android/database/CursorWindow") } assertThat(unexpected).isEmpty() } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt new file mode 100644 index 0000000000..e9e416aa6f --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -0,0 +1,20 @@ +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertWithMessage +import org.junit.jupiter.api.Test +import org.objectweb.asm.Type + +class SqliteRewriteRulesTest { + @Test + fun `every missing member lists the exact descriptors requery lacks, each a well-formed descriptor`() { + // The rewriter fails a call or a field access only when its descriptor is in the entry's set, so an + // entry with no descriptor, or a blank one, would match nothing. + for ((member, descs) in SqliteRewriteRules.MISSING_MEMBERS) { + assertWithMessage(member).that(descs).isNotEmpty() + for (desc in descs) { + val parsed = runCatching { if (desc.startsWith("(")) Type.getMethodType(desc) else Type.getType(desc) }.getOrNull() + assertWithMessage("$member descriptor '$desc'").that(parsed?.descriptor).isEqualTo(desc) + } + } + } +} From 49c84c033198a45fc2be2b49ad5228a3b309b6f6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:31:34 -0800 Subject: [PATCH 074/203] ADFA-7135 Refuse SQL that holds more than one statement bridge_query prepared with no tail pointer, so SQLite compiled only the first statement: query with "SELECT 1; SELECT 2" ran the first, dropped the second and reported success, and explain_query_plan (which prefixes the client's SQL) did the same. A lone comment returned an empty result, and anything after a NUL character was dropped too, since SQLite reads no further. prepare_one now prepares the tail as well. Whitespace, comments and semicolons prepare to no statement and are accepted; anything else, including a tail that fails to prepare (the server's authorizer refuses a trailing write at prepare time), fails the call with SQLITE_ERROR, "the SQL holds more than one statement; run one statement per call". SQL with no statement, or with a NUL, fails with its own message. Every tool reaches SQLite through bridge_query, so this covers query and explain_query_plan; the other tools send fixed SQL, and get_stats builds its COUNT(*) from quoted table names, not client input. Preparing the tail is not running it: the only effects are those a PRAGMA can have at prepare time, under the same authorizer a client already meets by sending that statement alone. Test (JniQueryTest, the real JNI path on a host JVM, run by test.sh): two statements, a statement after a comment, a trailing DELETE, a trailing syntax error and EXPLAIN QUERY PLAN with a second statement give the more-than-one message; a lone comment, a lone semicolon and a NUL give theirs; trailing semicolons, whitespace, comments, an open comment and a leading comment still run. With the fix reverted the 8 refusal checks fail, each "null vs 1 the SQL holds ...": the call ran. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 +- .../src/main/cpp/sqlitedbg_jni.c | 46 ++++++++++++++++--- .../sqlitedebugger/engine/DebugEngine.kt | 6 ++- .../src/test/jni/JniQueryTest.java | 27 +++++++++++ 4 files changed, 72 insertions(+), 11 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 9b32e7c718..016f4e27bf 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,13 +35,13 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. ## Testing - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. No workflow runs the JVM tests. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 703f103d57..ac1cb63747 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -258,6 +258,38 @@ static int utf8_prefix(const unsigned char *s, int len, int max) { return max; } +// Prepares sql, which must hold exactly one statement: SQLite compiles only the first statement of a +// string and reads no further than a NUL, so anything after either would be dropped without a word. +// Returns SQLITE_OK with *st set, or a code with *message set (left NULL for sqlite3_errmsg). +static int prepare_one(sqlite3 *db, const jchar *sql, jsize len, sqlite3_stmt **st, const char **message) { + *st = NULL; + for (jsize i = 0; i < len; i++) { + if (sql[i] == 0) { + *message = "the SQL holds a NUL character, and SQLite reads no further than it"; + return SQLITE_ERROR; + } + } + const void *tail = NULL; + int rc = sqlite3_prepare16_v2(db, sql, len * 2, st, &tail); + if (rc != SQLITE_OK) return rc; + if (!*st) { + *message = "the SQL holds no statement, only whitespace or comments"; + return SQLITE_ERROR; + } + // Whitespace, comments and semicolons prepare to no statement. Anything else is a second + // statement, also when it fails to prepare: the server's authorizer refuses a write then. + int left = len * 2 - (int)((const char *)tail - (const char *)sql); + sqlite3_stmt *next = NULL; + if (left > 0 && (sqlite3_prepare16_v2(db, tail, left, &next, NULL) != SQLITE_OK || next)) { + sqlite3_finalize(next); + sqlite3_finalize(*st); + *st = NULL; + *message = "the SQL holds more than one statement; run one statement per call"; + return SQLITE_ERROR; + } + return SQLITE_OK; +} + // One cell as a Java object, or NULL for SQL NULL (or on failure, with an exception pending). // *cut is set when a TEXT or BLOB was cut at its limit, and *bytes grows by what the cell costs the // result: the TEXT or BLOB bytes kept, 8 for a number. @@ -322,10 +354,10 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring jsize sql_len = (*env)->GetStringLength(env, sql); const jchar *sql_chars = (*env)->GetStringChars(env, sql, NULL); if (!sql_chars) return NULL; - rc = sqlite3_prepare16_v2(db, sql_chars, sql_len * 2, &st, NULL); + rc = prepare_one(db, sql_chars, sql_len, &st, &message); (*env)->ReleaseStringChars(env, sql, sql_chars); if (rc != SQLITE_OK) { - throw_engine(env, rc, sqlite3_errmsg(db)); + throw_engine(env, rc, message ? message : sqlite3_errmsg(db)); return NULL; } @@ -335,7 +367,7 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring handler_set = 1; // A missing argument would be bound as NULL and the query would run, returning a plausible empty result. - int wanted = st ? sqlite3_bind_parameter_count(st) : 0; + int wanted = sqlite3_bind_parameter_count(st); jsize given = (*env)->GetArrayLength(env, args); if (given != wanted) { char msg[96]; @@ -343,13 +375,13 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring throw_engine(env, SQLITE_RANGE, msg); goto done; } - rc = st ? bind_args(env, db, st, args, &message) : SQLITE_OK; + rc = bind_args(env, db, st, args, &message); if (rc != SQLITE_OK) { if (!(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); goto done; } - int ncols = st ? sqlite3_column_count(st) : 0; + int ncols = sqlite3_column_count(st); jobjectArray names = (*env)->NewObjectArray(env, ncols, g_string, NULL); jobject rows = names ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; if (!rows) goto done; @@ -364,7 +396,7 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring int has_more = 0, row_count = 0; int64_t total = 0; jlong skipped = 0; - while (st && (rc = sqlite3_step(st)) == SQLITE_ROW) { + while ((rc = sqlite3_step(st)) == SQLITE_ROW) { if (skipped < offset) { skipped++; continue; @@ -413,7 +445,7 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring if ((*env)->ExceptionCheck(env)) goto done; row_count++; } - if (st && !has_more && rc != SQLITE_DONE) { + if (!has_more && rc != SQLITE_DONE) { if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); else throw_engine(env, rc, sqlite3_errmsg(db)); goto done; diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 7aeabc53fa..7dc8fa0fdb 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -39,13 +39,15 @@ interface DebugEngine { /** A connection the server opened with [DebugEngine.openServerConnection]. Use from one thread at a time. */ interface ServerConnection : Closeable { /** - * Runs [sql] with [args] bound (null, [Long], [Double], [String] or [ByteArray]), skips + * Runs [sql], which must hold exactly one statement (trailing semicolons and comments are fine), + * with [args] bound (null, [Long], [Double], [String] or [ByteArray]), skips * [offset] rows, and returns at most [QueryLimits.maxRows]. Paging re-runs the statement, so a * later page can differ if the data changed. Stops the statement (sqlite3_interrupt, through a * progress handler on this server connection) once [deadlineMillis] (System.currentTimeMillis * clock) has passed. * - * @throws DebugEngineException for SQLite errors, a refused write, or the deadline. + * @throws DebugEngineException for SQLite errors, SQL with no statement or more than one, a + * refused write, or the deadline. */ fun query( sql: String, diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 776287b498..9358d0824e 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -74,6 +74,16 @@ static int codeOf(long h, String sql, Object[] args, long deadline) { } } + /** "code message" of the refusal, or null when the query ran. */ + static String refusal(long h, String sql) { + try { + q(h, sql); + return null; + } catch (DebugEngineException e) { + return e.sqliteCode + " " + e.getMessage(); + } + } + static Set set(Long... v) { return new HashSet<>(Arrays.asList(v)); } @@ -208,6 +218,23 @@ public static void main(String[] a) throws Exception { eq(codeOf(srv, "SELECT ?", new Object[] {new Object()}, FAR), 21, "unsupported arg type: SQLITE_MISUSE"); eq(codeOf(srv, "SELEKT 1", new Object[0], FAR), 1, "syntax error: SQLITE_ERROR"); + // one statement per call: SQLite compiles only the first, so a second is refused, not dropped + String more = "1 the SQL holds more than one statement; run one statement per call"; + eq(refusal(srv, "SELECT 1; SELECT 2"), more, "two statements"); + eq(refusal(srv, "SELECT 1;\n-- why\nSELECT id FROM t"), more, "a statement after a comment"); + eq(refusal(srv, "SELECT 1; DELETE FROM t"), more, "a write the authorizer refuses at prepare time is a second statement, not SQLITE_AUTH"); + eq(refusal(srv, "SELECT 1; nonsense"), more, "a second statement that fails to prepare"); + eq(refusal(srv, "EXPLAIN QUERY PLAN SELECT id FROM t; SELECT 2"), more, "what explain_query_plan sends for two statements"); + eq(refusal(srv, "-- only a comment"), "1 the SQL holds no statement, only whitespace or comments", "no statement"); + eq(refusal(srv, " ;\n"), "1 the SQL holds no statement, only whitespace or comments", "only a semicolon"); + eq(refusal(srv, "SELECT 1\0; DELETE FROM t"), "1 the SQL holds a NUL character, and SQLite reads no further than it", "a NUL"); + for (String sql : new String[] {"SELECT 41 + 1;", "SELECT 41 + 1 ; \n\t", "SELECT 41 + 1; -- done", "SELECT 41 + 1 /* c */;;", + "SELECT 41 + 1; /* open", "-- why\n;SELECT 41 + 1"}) { + eq(refusal(srv, sql), null, "accepted: " + sql); + eq(q(srv, sql).rows.get(0)[0], 42L, "and run: " + sql); + } + eq(q(srv, "SELECT count(*) FROM t WHERE id = 1").rows.get(0)[0], 1L, "nothing deleted"); + // a refused write is SQLITE_AUTH, and the data is untouched eq(codeOf(srv, "INSERT INTO t(id) VALUES(5)", new Object[0], FAR), 23, "write refused: SQLITE_AUTH"); eq(codeOf(srv, "DELETE FROM t", new Object[0], FAR), 23, "delete refused: SQLITE_AUTH"); From ff0bd0c6b8a66872d61fee8145c9452b826b8685 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:31:42 -0800 Subject: [PATCH 075/203] ADFA-7136 Say when a query ran out of time waiting for another tool call A query's 50 s deadline is set before runChecked waits for the tools' lock, so a call queued behind a slow one could fail with "the time limit passed before the query started" or "the query ran past its time limit", and the agent would read that as its own query being too slow. The deadline still starts before the wait (decided in review, so it bounds the wait for an answer once set); only the error changes. runChecked times its wait for the lock, and when the time ran out (SQLITE_INTERRUPT) after that wait took at least half of what the call had left, the message adds "(this call waited N s of its 50 s for another tool call to finish; tool calls run one at a time, so retry it)". Not counted: get_stats sets its deadline before its path check, which also takes the lock, so a wait there is not attributed. A tool call's first wait, in the idle check, comes before any deadline is set. Test (DatabaseToolsTest, fake clock): a second call takes the lock just after the query set its deadline, as a third concurrent call can, and holds it while the fake clock moves. A wait of 50.001 s and of 30 s each get the note; a 10 s wait followed by the query's own timeout does not. Without the fix the first two fail: expected "...started (this call waited 50.001 s of its 50 s ...)" but was "...started", and "the query ran past its time limit" with no note. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 24 +++- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 112 ++++++++++++++++++ 3 files changed, 133 insertions(+), 5 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 016f4e27bf..60a3b9ff0d 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A query's 50 s deadline starts before it waits for the lock, so a query queued behind a slow call can run out of time; when that wait took at least half of its time, the error says so, for the agent to retry. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 19ceceaa98..e369b60426 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -21,7 +21,9 @@ import java.util.TimerTask * * One lock guards the cached server connections and every query, so tool calls run one at a time: * a slow query (up to [DEADLINE_MS]) makes the others wait. That is accepted: the debugger serves - * one agent, and a connection per call would open the app's file many times over. + * one agent, and a connection per call would open the app's file many times over. A query's + * deadline is set before it waits for the lock, so a call whose time ran out mostly in that wait + * says so in its error. */ class DatabaseTools( private val engine: DebugEngine, @@ -497,8 +499,10 @@ class DatabaseTools( offset: Long, limits: QueryLimits, deadline: Long, - ): QueryResult = - synchronized(lock) { + ): QueryResult { + val waitStart = clock() + return synchronized(lock) { + val waited = clock() - waitStart try { val live = engine.connections() dropStaleServerConnections(live) @@ -510,9 +514,21 @@ class DatabaseTools( }.connection conn.query(sql, bind, offset, limits, deadline) } catch (e: DebugEngineException) { - throw engineError(e) + val error = engineError(e) + // The deadline counts this wait for the lock, so a quick query can run out of time behind a slow + // call: say so, for the agent to retry, not simplify it. + val had = deadline - waitStart + if (e.sqliteCode == DebugEngineException.SQLITE_INTERRUPT && had > 0 && waited * 2 >= had) { + throw McpToolError( + "${error.message} (this call waited ${waited / 1000.0} s of its ${DEADLINE_MS / 1000} s for another tool " + + "call to finish; tool calls run one at a time, so retry it)", + error.details, + ) + } + throw error } } + } /** * Closes cached server connections whose file may be gone: after the app deletes and recreates a diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index b53bfed6d9..e8b2e168e0 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -1,10 +1,13 @@ package org.appdevforall.sqlitedebugger.mcp import org.appdevforall.sqlitedebugger.engine.AppConnection +import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException import org.appdevforall.sqlitedebugger.engine.EventKind import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine +import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult +import org.appdevforall.sqlitedebugger.engine.ServerConnection import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertEquals @@ -12,6 +15,8 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicLong class DatabaseToolsTest { private val engine = FakeDebugEngine() @@ -283,6 +288,113 @@ class DatabaseToolsTest { assertEquals(now + 50_000, deadline) } + /** [engine], refusing like the native one to start a query whose deadline has passed. */ + private fun nativeDeadline(clock: () -> Long) = + object : DebugEngine by engine { + override fun openServerConnection( + path: String, + writable: Boolean, + ) = engine.openServerConnection(path, writable).let { c -> + object : ServerConnection by c { + override fun query( + sql: String, + args: List, + offset: Long, + limits: QueryLimits, + deadlineMillis: Long, + ): QueryResult { + if (clock() >= deadlineMillis) { + throw DebugEngineException( + DebugEngineException.SQLITE_INTERRUPT, + "the time limit passed before the query started", + ) + } + return c.query(sql, args, offset, limits, deadlineMillis) + } + } + } + } + + /** + * Runs a query that waits [waitMs] of the fake clock for the lock while another call holds it, then + * is answered by [then]. The other call takes the lock just after the query set its deadline, as a + * third concurrent call can. Returns the query's tool result. + */ + private fun queuedBehindAnotherCall( + waitMs: Long, + then: () -> QueryResult, + ): JSONObject { + engine.appConnections += conn(1, "/data/a.db") + val time = AtomicLong(now) + val holding = CountDownLatch(1) + val release = CountDownLatch(1) + engine.answer = { _, _, sql, _ -> + if (sql == "slow") { + holding.countDown() + release.await() + QueryResult(emptyList(), emptyList(), 0, false) + } else { + then() + } + } + lateinit var slow: Thread + lateinit var queued: Thread + var hooked = false + // the queued call's first clock read sets its deadline (with no get_events call the idle check reads none) + val t = + DatabaseTools(nativeDeadline(time::get), null, { + if (Thread.currentThread() === queued && !hooked) { + hooked = true + slow.start() + holding.await() + } + time.get() + }) + slow = Thread({ ok("query", db().put("sql", "slow"), t) }, "dbtools-slow") + var result: JSONObject? = null + queued = Thread({ result = runTool(t, "query", db().put("sql", "select 1")) }, "dbtools-queued") + queued.start() + // BLOCKED is a wait to enter a monitor; the slow call holds the tools' lock, and has already loaded every class on the path + while (queued.state != Thread.State.BLOCKED) Thread.sleep(5) + time.addAndGet(waitMs) + release.countDown() + queued.join() + slow.join() + return result!! + } + + private val ranPastItsLimit: () -> QueryResult = { + throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the query ran past its time limit") + } + + private fun errorText(r: JSONObject): String { + assertTrue(r.toString(), r.getBoolean("isError")) + return r.getJSONArray("content").getJSONObject(0).getString("text") + } + + @Test(timeout = 10_000) + fun aCallWhoseTimeRanOutWaitingForAnotherCallSaysSo() { + val r = queuedBehindAnotherCall(DatabaseTools.DEADLINE_MS + 1) { QueryResult(emptyList(), emptyList(), 0, false) } + assertEquals( + "the time limit passed before the query started (this call waited 50.001 s of its 50 s for another tool call to finish; " + + "tool calls run one at a time, so retry it)", + errorText(r), + ) + assertEquals(DebugEngineException.SQLITE_INTERRUPT, r.getJSONObject("structuredContent").getInt("sqlite_code")) + } + + @Test(timeout = 10_000) + fun aCallWhoseTimeRanOutMostlyWaitingSaysSo() { + val r = queuedBehindAnotherCall(30_000, ranPastItsLimit) + assertTrue(errorText(r), errorText(r).startsWith("the query ran past its time limit (this call waited 30.0 s of its 50 s")) + } + + @Test(timeout = 10_000) + fun aQueryThatUsedMostOfItsOwnTimeIsNotTiedToTheWait() { + val r = queuedBehindAnotherCall(10_000, ranPastItsLimit) + assertEquals("the query ran past its time limit", errorText(r)) + } + @Test fun jsonEncodesNonFiniteDoublesBigIntegersAndBlobs() { engine.appConnections += conn(1, "/data/a.db") val big = 9_007_199_254_740_993L From 0da5af2145bc0f965a7ec804c09e24f0ba2714fc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:42:10 -0800 Subject: [PATCH 076/203] ADFA-7136 Start a tool call's time limit when the call begins The 50 s limit was meant to make the server give up before the client (60 s), so a timed-out call never leaves a query holding the lock after the client has stopped waiting. It did not: every call first waited for the lock in the idle check, and run() set its deadline only after that and the path check, so a call queued behind a slow one could run a full 50 s after the wait. Each tool call now gets a Call when it begins: its deadline (DEADLINE_MS, unchanged) and the time it has spent waiting for the lock. Every lock taken inside the call (idle check, path check, each query, get_stats included) goes through Call.locked, which adds the wait. The note from ff0bd0c6b now uses that total: when the time runs out after waits of at least half the limit, the error says the call waited N s for another tool call and should be retried. Test (DatabaseToolsTest, fake clock): a call starts while another holds the lock and waits for it in the idle check. After a 50.001 s wait a query fails with "the time limit passed before the query started (this call waited 50.001 s ...)"; after 30 s a query that then times out gets the note; get_stats after a 50 s wait fails the same way; a 10 s wait gets no note. Against ff0bd0c6b three fail: the 50.001 s query and get_stats succeed (AssertionError: {"isError":false,...}), and the 30 s case reads "the query ran past its time limit" with no note. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 129 +++++++++++------- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 38 +++--- 3 files changed, 102 insertions(+), 67 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 60a3b9ff0d..804093af93 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A query's 50 s deadline starts before it waits for the lock, so a query queued behind a slow call can run out of time; when that wait took at least half of its time, the error says so, for the agent to retry. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index e369b60426..6a9bfa281e 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -21,9 +21,9 @@ import java.util.TimerTask * * One lock guards the cached server connections and every query, so tool calls run one at a time: * a slow query (up to [DEADLINE_MS]) makes the others wait. That is accepted: the debugger serves - * one agent, and a connection per call would open the app's file many times over. A query's - * deadline is set before it waits for the lock, so a call whose time ran out mostly in that wait - * says so in its error. + * one agent, and a connection per call would open the app's file many times over. A tool call's + * time limit starts when the call begins, so its waits for the lock count and the server gives up + * before the client does; a call whose time went mostly to waiting says so in its error. */ class DatabaseTools( private val engine: DebugEngine, @@ -40,7 +40,10 @@ class DatabaseTools( /** The most cell bytes one tool result holds (the engine's `maxTotalBytes`); the rest is paged. */ const val MAX_TOTAL_BYTES = 4 * 1024 * 1024 - /** Below the client's 60 s limit on a tool call. */ + /** + * A tool call's time limit, from when the call begins, waits for the lock included: below the + * client's 60 s limit, so a query never holds the lock after the client has stopped waiting. + */ const val DEADLINE_MS = 50_000L const val EVENT_BATCH_BYTES = 256 * 1024 const val MAX_TABLES_FOR_COUNTS = 10 @@ -113,6 +116,20 @@ class DatabaseTools( val appConnectionIds: Set, ) + /** One tool call: its deadline, set when it begins, and the time it has spent waiting for [lock]. */ + private inner class Call { + val deadline = clock() + DEADLINE_MS + var waitedMs = 0L + + fun locked(block: () -> T): T { + val before = clock() + return synchronized(lock) { + waitedMs += clock() - before + block() + } + } + } + /** Closes the server connections and tells the engine no client is watching. Call when the server stops. */ fun onServerStopped() { synchronized(lock) { @@ -132,12 +149,12 @@ class DatabaseTools( * expanding every statement costs memory, and nobody is reading. Checked on every tool call and * by a timer, so it also happens when no call comes. */ - fun expireIdleClient() { - synchronized(lock) { - if (clientConnected && clock() - lastEventsCallMs >= EVENTS_IDLE_MS) { - clientConnected = false - engine.setClientConnected(false) - } + fun expireIdleClient() = synchronized(lock) { expireIdleClientLocked() } + + private fun expireIdleClientLocked() { + if (clientConnected && clock() - lastEventsCallMs >= EVENTS_IDLE_MS) { + clientConnected = false + engine.setClientConnected(false) } } @@ -163,18 +180,18 @@ class DatabaseTools( "List databases", "Lists the app's databases: each one an app connection has open (available), and the files in the app's database folder " + "that none has opened (not available: not inspectable until the app opens them).", - ) { listDatabases() }, + ) { _, _ -> listDatabases() }, tool( "list_connections", "List connections", "Lists the app's open SQLite connections (not yet freed by SQLite), oldest first.", - ) { listConnections() }, + ) { _, _ -> listConnections() }, tool( "get_schema", "Get schema", "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_master.", databaseSchema(), - ) { getSchema(it) }, + ) { call, args -> getSchema(call, args) }, tool( "query", "Run a query", @@ -189,7 +206,7 @@ class DatabaseTools( "max_rows" to prop("integer", "Rows to return. Default $DEFAULT_MAX_ROWS, at most $MAX_ROWS."), required = listOf("sql"), ), - ) { query(it) }, + ) { call, args -> query(call, args) }, tool( "explain_query_plan", "Explain a query plan", @@ -199,21 +216,21 @@ class DatabaseTools( "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), required = listOf("sql"), ), - ) { explain(it) }, + ) { call, args -> explain(call, args) }, tool( "get_stats", "Get statistics", "Returns page_count, page_size, freelist_count, and the row count of each table when the database has fewer than " + "$MAX_TABLES_FOR_COUNTS tables.", databaseSchema(), - ) { getStats(it) }, + ) { call, args -> getStats(call, args) }, tool( "integrity_check", "Check integrity", "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. " + "ok is true when SQLite reports no problem.", databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), - ) { integrityCheck(it) }, + ) { call, args -> integrityCheck(call, args) }, tool( "get_events", "Get SQL events", @@ -225,7 +242,7 @@ class DatabaseTools( .put("additionalProperties", false) .put("properties", JSONObject().put("after", prop("integer", "Cursor: the next from the last call. Default 0."))) .put("required", JSONArray()), - ) { getEvents(it) }, + ) { _, args -> getEvents(args) }, ) private fun tool( @@ -233,10 +250,11 @@ class DatabaseTools( title: String, description: String, inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), - run: (JSONObject) -> JSONObject, + run: (Call, JSONObject) -> JSONObject, ) = McpTool(name, title, description, inputSchema, readOnly = true, run = { args -> - expireIdleClient() - run(args) + val call = Call() + call.locked { expireIdleClientLocked() } + run(call, args) }) private fun prop( @@ -293,9 +311,13 @@ class DatabaseTools( return JSONObject().put("connections", list) } - private fun getSchema(args: JSONObject): JSONObject { + private fun getSchema( + call: Call, + args: JSONObject, + ): JSONObject { val result = run( + call, args, "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", emptyList(), @@ -315,19 +337,26 @@ class DatabaseTools( .put("truncated", result.hasMore) } - private fun query(args: JSONObject): JSONObject { + private fun query( + call: Call, + args: JSONObject, + ): JSONObject { val sql = stringArg(args, "sql") val offset = intArg(args, "offset", 0, 0, Long.MAX_VALUE) val maxRows = intArg(args, "max_rows", DEFAULT_MAX_ROWS.toLong(), 1, MAX_ROWS.toLong()).toInt() - val result = run(args, sql, bindArgs(args), offset, QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) + val result = run(call, args, sql, bindArgs(args), offset, QueryLimits(maxRows, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val out = encodeResult(result, offset) out.put("note", PAGING_NOTE) return out } - private fun explain(args: JSONObject): JSONObject { + private fun explain( + call: Call, + args: JSONObject, + ): JSONObject { val result = run( + call, args, "EXPLAIN QUERY PLAN " + stringArg(args, "sql"), bindArgs(args), @@ -337,12 +366,14 @@ class DatabaseTools( return JSONObject().put("plan", rowsAsObjects(result)) } - private fun getStats(args: JSONObject): JSONObject { + private fun getStats( + call: Call, + args: JSONObject, + ): JSONObject { val limits = QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES) - val deadline = clock() + DEADLINE_MS - val path = checkedPath(args) + val path = checkedPath(call, args) - fun pragma(name: String) = runChecked(path, "PRAGMA $name", emptyList(), 0, limits, deadline).rows.firstOrNull()?.firstOrNull() + fun pragma(name: String) = runChecked(call, path, "PRAGMA $name", emptyList(), 0, limits).rows.firstOrNull()?.firstOrNull() val pageCount = pragma("page_count") as? Long val pageSize = pragma("page_size") as? Long val out = @@ -353,12 +384,12 @@ class DatabaseTools( if (pageCount != null && pageSize != null) out.put("size_bytes", encodeLong(pageCount * pageSize)) val tables = runChecked( + call, path, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", emptyList(), 0, limits, - deadline, ).rows .map { it[0] as String } if (tables.size < MAX_TABLES_FOR_COUNTS) { @@ -367,12 +398,12 @@ class DatabaseTools( val n = try { runChecked( + call, path, "SELECT COUNT(*) FROM ${quoteIdentifier(t)}", emptyList(), 0, limits, - deadline, ).rows.firstOrNull()?.firstOrNull() } catch (e: McpToolError) { e.message @@ -386,7 +417,10 @@ class DatabaseTools( return out } - private fun integrityCheck(args: JSONObject): JSONObject { + private fun integrityCheck( + call: Call, + args: JSONObject, + ): JSONObject { val full = when (val v = args.opt("full")) { null, JSONObject.NULL -> false @@ -394,7 +428,7 @@ class DatabaseTools( else -> throw McpToolError("full must be true or false.") } val pragma = if (full) "PRAGMA integrity_check" else "PRAGMA quick_check" - val result = run(args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) + val result = run(call, args, pragma, emptyList(), 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES)) val messages = result.rows.map { it.firstOrNull()?.toString() ?: "" } return JSONObject() .put("check", if (full) "integrity_check" else "quick_check") @@ -466,7 +500,10 @@ class DatabaseTools( return arr } - private fun checkedPath(args: JSONObject): String { + private fun checkedPath( + call: Call, + args: JSONObject, + ): String { val path = stringArg(args, "database") val known = engine @@ -474,7 +511,7 @@ class DatabaseTools( .map { it.path } .filter { it.isNotEmpty() } .distinct() - synchronized(lock) { dropStaleServerConnections(engine.connections()) } + call.locked { dropStaleServerConnections(engine.connections()) } if (path !in known) { throw McpToolError( "Unknown database \"$path\": use a path from list_databases that is available.", @@ -485,24 +522,23 @@ class DatabaseTools( } private fun run( + call: Call, args: JSONObject, sql: String, bind: List, offset: Long, limits: QueryLimits, - ): QueryResult = runChecked(checkedPath(args), sql, bind, offset, limits, clock() + DEADLINE_MS) + ): QueryResult = runChecked(call, checkedPath(call, args), sql, bind, offset, limits) private fun runChecked( + call: Call, path: String, sql: String, bind: List, offset: Long, limits: QueryLimits, - deadline: Long, - ): QueryResult { - val waitStart = clock() - return synchronized(lock) { - val waited = clock() - waitStart + ): QueryResult = + call.locked { try { val live = engine.connections() dropStaleServerConnections(live) @@ -512,13 +548,13 @@ class DatabaseTools( val ids = live.filter { it.path == path && !it.closing }.map { it.id }.toSet() CachedConnection(engine.openServerConnection(path, writable = false), ids) }.connection - conn.query(sql, bind, offset, limits, deadline) + conn.query(sql, bind, offset, limits, call.deadline) } catch (e: DebugEngineException) { val error = engineError(e) - // The deadline counts this wait for the lock, so a quick query can run out of time behind a slow - // call: say so, for the agent to retry, not simplify it. - val had = deadline - waitStart - if (e.sqliteCode == DebugEngineException.SQLITE_INTERRUPT && had > 0 && waited * 2 >= had) { + // The time limit counts the call's waits for the lock, so a quick query can run out of time + // behind a slow call: say so, for the agent to retry, not simplify it. + val waited = call.waitedMs + if (e.sqliteCode == DebugEngineException.SQLITE_INTERRUPT && waited * 2 >= DEADLINE_MS) { throw McpToolError( "${error.message} (this call waited ${waited / 1000.0} s of its ${DEADLINE_MS / 1000} s for another tool " + "call to finish; tool calls run one at a time, so retry it)", @@ -528,7 +564,6 @@ class DatabaseTools( throw error } } - } /** * Closes cached server connections whose file may be gone: after the app deletes and recreates a diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index e8b2e168e0..78419fd37c 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -316,13 +316,14 @@ class DatabaseToolsTest { } /** - * Runs a query that waits [waitMs] of the fake clock for the lock while another call holds it, then - * is answered by [then]. The other call takes the lock just after the query set its deadline, as a - * third concurrent call can. Returns the query's tool result. + * Runs tool [name] while another call holds the lock: it waits for it [waitMs] of the fake clock + * (in the idle check, its first wait), then its query is answered by [then]. Returns its result. */ private fun queuedBehindAnotherCall( waitMs: Long, then: () -> QueryResult, + name: String = "query", + args: JSONObject = db().put("sql", "select 1"), ): JSONObject { engine.appConnections += conn(1, "/data/a.db") val time = AtomicLong(now) @@ -337,22 +338,12 @@ class DatabaseToolsTest { then() } } - lateinit var slow: Thread - lateinit var queued: Thread - var hooked = false - // the queued call's first clock read sets its deadline (with no get_events call the idle check reads none) - val t = - DatabaseTools(nativeDeadline(time::get), null, { - if (Thread.currentThread() === queued && !hooked) { - hooked = true - slow.start() - holding.await() - } - time.get() - }) - slow = Thread({ ok("query", db().put("sql", "slow"), t) }, "dbtools-slow") + val t = DatabaseTools(nativeDeadline(time::get), null, time::get) + val slow = Thread({ ok("query", db().put("sql", "slow"), t) }, "dbtools-slow") + slow.start() + holding.await() var result: JSONObject? = null - queued = Thread({ result = runTool(t, "query", db().put("sql", "select 1")) }, "dbtools-queued") + val queued = Thread({ result = runTool(t, name, args) }, "dbtools-queued") queued.start() // BLOCKED is a wait to enter a monitor; the slow call holds the tools' lock, and has already loaded every class on the path while (queued.state != Thread.State.BLOCKED) Thread.sleep(5) @@ -363,6 +354,8 @@ class DatabaseToolsTest { return result!! } + private val answersEmpty: () -> QueryResult = { QueryResult(emptyList(), emptyList(), 0, false) } + private val ranPastItsLimit: () -> QueryResult = { throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the query ran past its time limit") } @@ -374,7 +367,7 @@ class DatabaseToolsTest { @Test(timeout = 10_000) fun aCallWhoseTimeRanOutWaitingForAnotherCallSaysSo() { - val r = queuedBehindAnotherCall(DatabaseTools.DEADLINE_MS + 1) { QueryResult(emptyList(), emptyList(), 0, false) } + val r = queuedBehindAnotherCall(DatabaseTools.DEADLINE_MS + 1, answersEmpty) assertEquals( "the time limit passed before the query started (this call waited 50.001 s of its 50 s for another tool call to finish; " + "tool calls run one at a time, so retry it)", @@ -389,6 +382,13 @@ class DatabaseToolsTest { assertTrue(errorText(r), errorText(r).startsWith("the query ran past its time limit (this call waited 30.0 s of its 50 s")) } + @Test(timeout = 10_000) + fun getStatsCountsTheWaitForTheLockInItsTimeLimit() { + val r = queuedBehindAnotherCall(DatabaseTools.DEADLINE_MS, answersEmpty, "get_stats", db()) + val text = errorText(r) + assertTrue(text, text.startsWith("the time limit passed before the query started (this call waited 50.0 s of its 50 s")) + } + @Test(timeout = 10_000) fun aQueryThatUsedMostOfItsOwnTimeIsNotTiedToTheWait() { val r = queuedBehindAnotherCall(10_000, ranPastItsLimit) From d097e5d23f48ceea8d9a24675470fc8c52c3797c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 21:34:41 -0800 Subject: [PATCH 077/203] ADFA-7135 Let the query backstop's ROLLBACK past the server's authorizer After every query bridge_query ran ROLLBACK when the connection was not in autocommit, as a backstop for a transaction left open. On a read-only server connection, the kind every tool uses, the authorizer denies SQLITE_TRANSACTION, and SQLite authorizes ROLLBACK as that action: the ROLLBACK failed with "not authorized", its result was ignored, and the transaction and its lock on the app's database stayed. Nothing a client sends opens one today (BEGIN and SAVEPOINT are refused), so the backstop only mattered for a hole in the authorizer, and there it did nothing. sqlitedbg_end_transaction (sqlitedbg.h) now does the rollback. It sets a thread-local flag around its own sqlite3_exec("ROLLBACK"), and the authorizer lets SQLITE_TRANSACTION through only when that flag is set and the statement is ROLLBACK. A client's BEGIN, COMMIT, END and ROLLBACK are still refused, also while a transaction is open, and SAVEPOINT (with ROLLBACK TO) is untouched. bridge_query checks the result: a rollback that fails becomes the call's error, "a transaction was left open and rolling it back failed: ", with ROLLBACK's code. If the query had already failed, that error is kept instead. The connection stays cached either way, so each later query tries the rollback again. Tests: - C (sqlitedbg_test.c, test_server_ends_transaction): a read-only server connection is put into a transaction holding a read lock by clearing the authorizer, running BEGIN and a SELECT, and putting the real authorizer back (a SQLITEDBG_TEST hook exposes it). The app's write gets SQLITE_BUSY. The client's ROLLBACK, COMMIT and BEGIN still get SQLITE_AUTH. sqlitedbg_end_transaction returns SQLITE_OK, the connection is back in autocommit, and the app can write. Afterwards the client's BEGIN and ROLLBACK are still refused. test_server_holds_no_locks also checks that COMMIT, END and ROLLBACK are refused. With the authorizer change reverted it fails with "sqlitedbg_end_transaction(srv) == SQLITE_OK (23 vs 0)", then autocommit stays 0 and the app's write is "database is locked". - JNI (JniQueryTest): a writable server connection holding BEGIN IMMEDIATE, with an authorizer that refuses ROLLBACK, fails the next query with "23 a transaction was left open and rolling it back failed: not authorized" while the app stays locked out. Once that authorizer is cleared, the next query rolls the transaction back and the app can write. With the old unchecked ROLLBACK restored it fails with "the failed rollback is reported: null vs 23 ...": the query returned as if nothing were wrong. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 21 +++++++++- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 7 ++++ .../src/main/cpp/sqlitedbg_jni.c | 11 ++++- .../src/test/c/sqlitedbg_test.c | 42 +++++++++++++++++++ .../sqlite-debugger/src/test/jni/Helper.java | 2 + .../src/test/jni/JniQueryTest.java | 10 +++++ .../sqlite-debugger/src/test/jni/helper.c | 17 ++++++++ 8 files changed, 109 insertions(+), 5 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 804093af93..4af4ca5c78 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -31,7 +31,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). @@ -41,7 +41,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. No workflow runs the JVM tests. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index c69f5b9fdf..c84192d81e 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -62,6 +62,8 @@ static uint64_t g_next_seq = 1; // Set around the server's own sqlite3_open_v2: auto extensions run on the opening thread, inside it. static __thread int tls_opening_server; +// Set around sqlitedbg_end_transaction's ROLLBACK, which the authorizer checks on this thread. +static __thread int tls_ending_transaction; static int64_t now_ns(void) { struct timespec ts; @@ -415,9 +417,11 @@ static int server_authorizer(void *unused, int action, const char *a1, const cha case SQLITE_ATTACH: case SQLITE_DETACH: // A client could open a transaction or savepoint and hold a lock on the app's database. - case SQLITE_TRANSACTION: case SQLITE_SAVEPOINT: return SQLITE_DENY; + case SQLITE_TRANSACTION: + // Only the ROLLBACK of sqlitedbg_end_transaction, which ends one, gets past. + return tls_ending_transaction && a1 && strcmp(a1, "ROLLBACK") == 0 ? SQLITE_OK : SQLITE_DENY; case SQLITE_PRAGMA: // PRAGMA query_only=0 would lift the guard, and a PRAGMA that stores a value writes. // PRAGMA table_info(t) also has a second argument, so only these names are checked. @@ -440,6 +444,21 @@ static int server_authorizer(void *unused, int action, const char *a1, const cha } } +#ifdef SQLITEDBG_TEST +// Host tests: the authorizer, to put back after opening a transaction with it cleared, as a way past +// it would leave a server connection. +int (*const sqlitedbg_test_server_authorizer)(void *, int, const char *, const char *, const char *, + const char *) = server_authorizer; +#endif + +int sqlitedbg_end_transaction(sqlite3 *db) { + if (sqlite3_get_autocommit(db)) return SQLITE_OK; + tls_ending_transaction = 1; + int rc = sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL); + tls_ending_transaction = 0; + return rc; +} + int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db) { *db = NULL; pthread_mutex_lock(&g_lock); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 22eb2025dd..65795d8aa8 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -148,6 +148,13 @@ void sqlitedbg_set_client_connected(int connected); // API to call), or what sqlite3_open_v2 returns. int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db); +// Ends a transaction left open on a server connection with ROLLBACK, which the read-only authorizer +// lets past for this call only: a client's BEGIN, COMMIT and ROLLBACK stay refused. The JNI layer +// calls it after every query as a backstop; nothing a client can send opens one on a read-only +// connection. Returns SQLITE_OK when none was open or it was rolled back, else what ROLLBACK +// returned, and the transaction is still open. +int sqlitedbg_end_transaction(sqlite3 *db); + #ifdef __cplusplus } #endif diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index ac1cb63747..bb4da44059 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -467,8 +467,15 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sqlite3_finalize(st); free(cut_cells); // Backstop: a transaction left open (a writable connection, or a way past the authorizer) - // would hold a lock on the app's database until the next query. - if (sqlite3_get_autocommit(db) == 0) sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL); + // would hold a lock on the app's database until the next query. A failure is the call's error, + // unless the query already failed: that error is kept. + rc = sqlitedbg_end_transaction(db); + if (rc != SQLITE_OK) { + char msg[256]; + snprintf(msg, sizeof msg, "a transaction was left open and rolling it back failed: %s", sqlite3_errmsg(db)); + throw_engine(env, rc, msg); + result = NULL; + } return result; } diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 298fdd592e..d886e3378c 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -614,6 +614,9 @@ static void test_server_holds_no_locks(void) { "BEGIN", "BEGIN IMMEDIATE", "BEGIN EXCLUSIVE", + "COMMIT", + "END", + "ROLLBACK", "SAVEPOINT s", "PRAGMA locking_mode=EXCLUSIVE", "PRAGMA locking_mode", @@ -653,6 +656,44 @@ static void test_server_holds_no_locks(void) { CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); } +extern int (*const sqlitedbg_test_server_authorizer)(void *, int, const char *, const char *, const char *, + const char *); // sqlitedbg.c, built with SQLITEDBG_TEST + +// The backstop for a transaction left open on a server connection (ADFA-7135 review, F37): the +// authorizer refuses ROLLBACK like any transaction statement, so sqlitedbg_end_transaction's own has +// to get past it, and only that one. +static void test_server_ends_transaction(void) { + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_OK); + CHECK_EQ(sqlitedbg_end_transaction(srv), SQLITE_OK); // none open + CHECK_EQ(sqlite3_get_autocommit(srv), 1); + + // a transaction opened past the authorizer, as a hole in it would leave one, holding a read lock + CHECK_EQ(sqlite3_set_authorizer(srv, NULL, NULL), SQLITE_OK); + CHECK_EQ(step_all(srv, "BEGIN"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "SELECT count(*) FROM t"), SQLITE_DONE); + CHECK_EQ(sqlite3_set_authorizer(srv, sqlitedbg_test_server_authorizer, NULL), SQLITE_OK); + CHECK_EQ(sqlite3_get_autocommit(srv), 0); + CHECK_EQ(sqlite3_exec(g_main, "INSERT INTO t VALUES(4244)", NULL, NULL, NULL), SQLITE_BUSY); + + // the client still cannot end it or open another + CHECK_EQ(step_all(srv, "ROLLBACK"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "COMMIT"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "BEGIN"), SQLITE_AUTH); + CHECK_EQ(sqlite3_get_autocommit(srv), 0); + + CHECK_EQ(sqlitedbg_end_transaction(srv), SQLITE_OK); + CHECK_EQ(sqlite3_get_autocommit(srv), 1); + exec_ok(g_main, "INSERT INTO t VALUES(4244)"); + exec_ok(g_main, "DELETE FROM t WHERE a=4244"); + + // the exemption ends with the call + CHECK_EQ(step_all(srv, "BEGIN"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "ROLLBACK"), SQLITE_AUTH); + CHECK_EQ(step_all(srv, "SELECT count(*) FROM t"), SQLITE_DONE); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); +} + typedef struct locker { char path[320]; atomic_int locked, release; @@ -999,6 +1040,7 @@ int main(int argc, char **argv) { test_server(); printf("# server holds no locks\n"); test_server_holds_no_locks(); + test_server_ends_transaction(); printf("# server waits for locks\n"); test_server_waits_for_locks(); printf("# threads\n"); diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java index e283c57768..da3de3a40d 100644 --- a/subprojects/sqlite-debugger/src/test/jni/Helper.java +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -5,4 +5,6 @@ public class Helper { static native int exec(long db, String sql); static native int close(long db); + + static native int denyTransactions(long db, boolean deny); } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 9358d0824e..ef41873045 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -271,6 +271,16 @@ public static void main(String[] a) throws Exception { q(w, "BEGIN"); q(w, "INSERT INTO t(id) VALUES(4245)"); eq(q(w, "SELECT count(*) FROM t WHERE id = 4245").rows.get(0)[0], 1L, "an autocommit insert on the writable connection stays"); + // a rollback the backstop cannot make is the query's error, not a lock held in silence + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the query path"); + eq(Helper.denyTransactions(w, true), 0, "an authorizer that refuses ROLLBACK"); + eq(refusal(w, "SELECT 1"), "23 a transaction was left open and rolling it back failed: not authorized", + "the failed rollback is reported"); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4246)"), 5, "the app is still locked out: SQLITE_BUSY"); + eq(Helper.denyTransactions(w, false), 0, "the authorizer cleared"); + eq(refusal(w, "SELECT 1"), null, "the next query rolls it back"); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4246)"), 0, "the app can write again"); + Helper.exec(app, "DELETE FROM t WHERE id = 4246"); NativeBridge.close(w); Helper.exec(app, "DELETE FROM t WHERE id = 4245"); diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c index 9fe88d041a..e69df00f10 100644 --- a/subprojects/sqlite-debugger/src/test/jni/helper.c +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -25,3 +25,20 @@ JNIEXPORT jint JNICALL Java_Helper_close(JNIEnv *e, jclass c, jlong db) { (void)c; return sqlite3_close((sqlite3 *)(intptr_t)db); } + +static int deny_transactions(void *u, int action, const char *a1, const char *a2, const char *d, const char *t) { + (void)u; + (void)a1; + (void)a2; + (void)d; + (void)t; + return action == SQLITE_TRANSACTION ? SQLITE_DENY : SQLITE_OK; +} + +// An authorizer on any connection, a server one included, that refuses BEGIN, COMMIT and ROLLBACK, +// or none (deny false). +JNIEXPORT jint JNICALL Java_Helper_denyTransactions(JNIEnv *e, jclass c, jlong db, jboolean deny) { + (void)e; + (void)c; + return sqlite3_set_authorizer((sqlite3 *)(intptr_t)db, deny ? deny_transactions : 0, 0); +} From 0d4022223547dee542eb0c8d13d700bf84ebe586 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 21:39:05 -0800 Subject: [PATCH 078/203] ADFA-7136 Say when get_schema cut a CREATE statement get_schema reads sqlite_master with a 64 KiB text limit but reported only truncated: result.hasMore, which means more rows exist. A view or trigger whose SQL is longer than 64 KiB came back as a prefix with truncated false, and an agent would read it as the full definition. Each entry now has truncated, true when a value in its row was cut. The result also has truncated_cells, the count of cut values, named as query names it. The top-level truncated is true when anything was cut or rows past the first 1000 were left out. The tool description gives the 64 KiB limit and the three fields. The limit is now a constant, MAX_SCHEMA_SQL_BYTES. The README's Limits paragraph says it too. Other tools checked: query already reports truncated_cells and has_more. explain_query_plan and integrity_check use the 4 KiB text limit and report neither, and were left alone: a plan line or an integrity message near 4 KiB, or more than 1000 of them, is not a realistic case, and integrity_check's ok compares against "ok", which a cut value cannot equal. get_stats reads only numbers and table names. Tests (DatabaseToolsTest with FakeDebugEngine): getSchemaSaysWhichCreateStatementWasCut gives get_schema a result whose view SQL is listed as cut. The top-level truncated is true, truncated_cells is 1, the view entry has truncated true, and the table entry has truncated false. getSchemaIsTruncatedPastMaxRowsEntries checks that 1001 entries still give truncated true with truncated_cells 0. getSchemaGroupsByType checks false and 0 when nothing is cut. With the reporting reverted the first fails with "a cut CREATE statement makes the result truncated", and the other two fail on the missing truncated_cells. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 22 +++++++++--- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 35 +++++++++++++++++++ 3 files changed, 53 insertions(+), 6 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 4af4ca5c78..6f4d509637 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 6a9bfa281e..50482df7ca 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -37,6 +37,9 @@ class DatabaseTools( const val MAX_TEXT_BYTES = 4096 const val MAX_BLOB_BYTES = 1024 + /** get_schema's limit on a CREATE statement, well above [MAX_TEXT_BYTES]. */ + const val MAX_SCHEMA_SQL_BYTES = 65536 + /** The most cell bytes one tool result holds (the engine's `maxTotalBytes`); the rest is paged. */ const val MAX_TOTAL_BYTES = 4 * 1024 * 1024 @@ -189,7 +192,10 @@ class DatabaseTools( tool( "get_schema", "Get schema", - "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_master.", + "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_master. " + + "A CREATE statement is cut at ${MAX_SCHEMA_SQL_BYTES / 1024} KiB: its entry then has truncated true, and " + + "truncated_cells counts the cut values. The top-level truncated is true when anything was cut or entries past " + + "the first $MAX_ROWS were left out.", databaseSchema(), ) { call, args -> getSchema(call, args) }, tool( @@ -322,11 +328,16 @@ class DatabaseTools( "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", emptyList(), 0, - QueryLimits(MAX_ROWS, 65536, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), + QueryLimits(MAX_ROWS, MAX_SCHEMA_SQL_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) val groups = linkedMapOf("table" to JSONArray(), "index" to JSONArray(), "view" to JSONArray(), "trigger" to JSONArray()) - for (row in result.rows) { - val item = JSONObject().put("name", encodeValue(row[1])).put("table", encodeValue(row[2])).put("sql", encodeValue(row[3])) + result.rows.forEachIndexed { r, row -> + val item = + JSONObject() + .put("name", encodeValue(row[1])) + .put("table", encodeValue(row[2])) + .put("sql", encodeValue(row[3])) + .put("truncated", row.indices.any { result.isTruncated(r, it) }) groups[row[0] as? String]?.put(item) } return JSONObject() @@ -334,7 +345,8 @@ class DatabaseTools( .put("indexes", groups["index"]) .put("views", groups["view"]) .put("triggers", groups["trigger"]) - .put("truncated", result.hasMore) + .put("truncated", result.hasMore || result.truncatedCells > 0) + .put("truncated_cells", result.truncatedCells) } private fun query( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 78419fd37c..b1abf4c16c 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -485,6 +485,41 @@ class DatabaseToolsTest { assertEquals(1, r.getJSONArray("triggers").length()) assertTrue(seenSql.single().contains("FROM sqlite_master")) assertFalse(seenSql.single().contains("sqlite_schema")) // an alias that needs SQLite 3.33 + assertFalse(r.getBoolean("truncated")) + assertEquals(0, r.getInt("truncated_cells")) + assertFalse(r.getJSONArray("tables").getJSONObject(0).getBoolean("truncated")) + } + + @Test fun getSchemaSaysWhichCreateStatementWasCut() { + engine.appConnections += conn(1, "/data/a.db") + // the engine kept MAX_SCHEMA_SQL_BYTES of a longer statement + val cut = "CREATE VIEW big AS SELECT " + "1 + ".repeat((DatabaseTools.MAX_SCHEMA_SQL_BYTES - 26) / 4) + answerWith( + "SELECT type" to + QueryResult( + listOf("type", "name", "tbl_name", "sql"), + listOf(listOf("table", "t", "t", "CREATE TABLE t(a)"), listOf("view", "big", "big", cut)), + 1, + false, + setOf(7L), // row 1, column 3 + ), + ) + val r = ok("get_schema", db()) + assertTrue("a cut CREATE statement makes the result truncated", r.getBoolean("truncated")) + assertEquals(1, r.getInt("truncated_cells")) + assertTrue(r.getJSONArray("views").getJSONObject(0).getBoolean("truncated")) + assertEquals(cut, r.getJSONArray("views").getJSONObject(0).getString("sql")) + assertFalse(r.getJSONArray("tables").getJSONObject(0).getBoolean("truncated")) + } + + @Test fun getSchemaIsTruncatedPastMaxRowsEntries() { + engine.appConnections += conn(1, "/data/a.db") + val rows = (0..DatabaseTools.MAX_ROWS).map { listOf("table", "t$it", "t$it", "CREATE TABLE t$it(a)") } + answerWith("SELECT type" to QueryResult(listOf("type", "name", "tbl_name", "sql"), rows, 0, false)) + val r = ok("get_schema", db()) + assertEquals(DatabaseTools.MAX_ROWS, r.getJSONArray("tables").length()) + assertTrue(r.getBoolean("truncated")) + assertEquals(0, r.getInt("truncated_cells")) } @Test fun explainQueryPlanPrefixesTheSql() { From 403746ba55bcdd0024fef02bb2ac151d7a8b7155 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 22:37:46 -0800 Subject: [PATCH 079/203] ADFA-7136 Say that functions the app adds to its own connections are missing Every tool runs on a server connection the SQLite debugger opens itself, never on an app connection, and SQLite registers functions per connection. So what the app adds to its own connections (requery's SQLiteCustomFunction and SQLiteCustomExtension, sqlite-js and its stored JavaScript functions) does not exist there: SELECT median(price) fails with "no such function: median" through query, and through explain_query_plan or a view, although the app's own queries run it. The query and explain_query_plan descriptions now say so, so the agent reads the rows or computes in plain SQL instead, and the README states the limit and why. No behaviour change. A test pins the phrase in both descriptions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 1 + .../appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 9 +++++++-- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 10 ++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 6f4d509637..8a02f0a7e7 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,6 +34,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. +- **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). - **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 50482df7ca..2fe0f8a837 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -59,6 +59,11 @@ class DatabaseTools( const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + /** Server connections never load what the app registers on its own connections (see the README). */ + private const val APP_FUNCTIONS_NOTE = + "Functions the app adds to its own connections, such as sqlite-js's stored JavaScript functions, do not exist " + + "here (\"no such function\", also through a view)" + /** A SQLite value as JSON: org.json throws on NaN and infinities, and JSON numbers lose integers past 2^53. */ fun encodeValue( value: Any?, @@ -204,7 +209,7 @@ class DatabaseTools( "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true). Use offset to page. " + - "$PAGING_NOTE Writes are refused.", + "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead.", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), @@ -216,7 +221,7 @@ class DatabaseTools( tool( "explain_query_plan", "Explain a query plan", - "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run.", + "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run. $APP_FUNCTIONS_NOTE.", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index b1abf4c16c..7a215d3bcd 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -210,6 +210,16 @@ class DatabaseToolsTest { ) } + @Test fun toolDescriptionsStateTheLimitsAnAgentMustPlanAround() { + val descriptions = tools.tools().associate { it.name to it.description } + // The server's own connection lacks what the app registers per connection (sqlite-js, requery custom functions). + for (name in listOf("query", "explain_query_plan")) { + assertTrue(name, descriptions.getValue(name).contains("Functions the app adds to its own connections")) + assertTrue(name, descriptions.getValue(name).contains("no such function")) + } + assertTrue(descriptions.getValue("query").contains("compute in plain SQL")) + } + @Test fun queryChecksItsArguments() { engine.appConnections += conn(1, "/data/a.db") From 9c916cad3bc70391181957b2698a09c60ca5aecc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 22:39:22 -0800 Subject: [PATCH 080/203] ADFA-7136 Name both limits that can leave get_schema entries out get_schema's description gave "past the first 1000 entries" as the only reason for the top-level truncated, but the 4 MiB result budget ends the result too, after about 64 CREATE statements of 64 KiB. The agent then saw truncated true with no entry cut, and get_schema has no offset. The description now names both limits and sends the agent to page through sqlite_master with query, reading a statement longer than query's 4096-byte TEXT limit in parts with substr. The README says the same. No behaviour change. The description test pins both causes and the way out; a new test shows the budget ends a get_schema result of 64 KiB statements with truncated true and truncated_cells 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 7 +++++-- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8a02f0a7e7..5fcde2f961 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query`, reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr`. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 2fe0f8a837..defe35a5f7 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -199,8 +199,11 @@ class DatabaseTools( "Get schema", "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_master. " + "A CREATE statement is cut at ${MAX_SCHEMA_SQL_BYTES / 1024} KiB: its entry then has truncated true, and " + - "truncated_cells counts the cut values. The top-level truncated is true when anything was cut or entries past " + - "the first $MAX_ROWS were left out.", + "truncated_cells counts the cut values. The top-level truncated is true when anything was cut or entries were left " + + "out: past the first $MAX_ROWS, or past about ${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (about " + + "${MAX_TOTAL_BYTES / MAX_SCHEMA_SQL_BYTES} statements of ${MAX_SCHEMA_SQL_BYTES / 1024} KiB). There is no offset: " + + "to read the rest, page through sqlite_master with query, and read a statement longer than its " + + "$MAX_TEXT_BYTES-byte TEXT limit in parts with substr.", databaseSchema(), ) { call, args -> getSchema(call, args) }, tool( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 7a215d3bcd..589cea8305 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -218,6 +218,11 @@ class DatabaseToolsTest { assertTrue(name, descriptions.getValue(name).contains("no such function")) } assertTrue(descriptions.getValue("query").contains("compute in plain SQL")) + // get_schema has no offset, and either limit can leave entries out. + val schema = descriptions.getValue("get_schema") + assertTrue(schema, schema.contains("past the first ${DatabaseTools.MAX_ROWS}")) + assertTrue(schema, schema.contains("past about 4 MiB of cell bytes")) + assertTrue(schema, schema.contains("page through sqlite_master with query")) } @Test fun queryChecksItsArguments() { @@ -532,6 +537,19 @@ class DatabaseToolsTest { assertEquals(0, r.getInt("truncated_cells")) } + @Test fun getSchemaIsTruncatedWhenTheResultBudgetIsSpent() { + engine.appConnections += conn(1, "/data/a.db") + // statements at the per-cell limit: the 4 MiB budget ends the result long before MAX_ROWS entries + val big = "CREATE VIEW v AS SELECT '" + "x".repeat(DatabaseTools.MAX_SCHEMA_SQL_BYTES - 27) + "'" + val rows = (0 until 70).map { listOf("view", "v$it", "v$it", big) } + answerWith("SELECT type" to QueryResult(listOf("type", "name", "tbl_name", "sql"), rows, 0, false)) + val r = ok("get_schema", db()) + val views = r.getJSONArray("views").length() + assertTrue("$views views", views in 1 until DatabaseTools.MAX_TOTAL_BYTES / DatabaseTools.MAX_SCHEMA_SQL_BYTES) + assertTrue(r.getBoolean("truncated")) + assertEquals(0, r.getInt("truncated_cells")) + } + @Test fun explainQueryPlanPrefixesTheSql() { engine.appConnections += conn(1, "/data/a.db") answerWith( From acab92691cb896f9f768d06e29d7b6eca2f2e61e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 23:35:51 -0800 Subject: [PATCH 081/203] ADFA-7138: Quick Build status line says "off", not "setup failed", for the SQLite debugger refusal With cogo.sqliteDebugger=true, Quick Build refuses on purpose, but the refusal went through the failed-start path, so the status line read "Quick Build: setup failed - tap to retry" although nothing failed and a retry cannot help. The provisioner now reports the refusal as its own message (QuickBuildMessage.DisabledBySqliteDebugger), the reducer records it as startRefused beside lastStartFailed, and the status line, Build Output and flashes treat it as a separate StartRefused transition. The status line reads "Quick Build: off while the SQLite debugger is on - tap for details"; a tap re-runs the cheap check and shows the full refusal again. Other failure paths are unchanged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 34 +++++++++++++------ .../quickbuild/QuickBuildFlashes.kt | 1 + .../quickbuild/QuickBuildMessages.kt | 4 +++ .../quickbuild/QuickBuildOutputLines.kt | 6 ++++ .../quickbuild/QuickBuildStatusBar.kt | 6 ++++ .../quickbuild/QuickBuildTransitions.kt | 11 +++++- ...dleQuickBuildProvisionerFailureArmsTest.kt | 15 ++++++++ .../quickbuild/QuickBuildStatusBarTest.kt | 29 ++++++++++++++++ .../domain/session/QuickBuildMessage.kt | 7 ++++ .../domain/session/QuickBuildSessionState.kt | 7 ++++ .../domain/session/QuickBuildStatus.kt | 7 ++-- .../domain/session/SessionReducer.kt | 24 ++++++++++--- resources/src/main/res/values/strings.xml | 1 + 13 files changed, 134 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 635fa875ed..0d2eda903a 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -112,6 +112,10 @@ class GradleQuickBuildProvisioner( built } + ProxyAppBuildResult.Refused -> { + return ProvisionOutcome.Failure(QuickBuildMessage.DisabledBySqliteDebugger) + } + is ProxyAppBuildResult.Failed -> { return ProvisionOutcome.Failure( built.message?.let(QuickBuildMessage::Literal) @@ -202,6 +206,10 @@ class GradleQuickBuildProvisioner( return ProxyAppRebuildOutcome.BuildSlotBusy } + ProxyAppBuildResult.Refused -> { + return ProxyAppRebuildOutcome.Failure(QuickBuildMessage.DisabledBySqliteDebugger) + } + is ProxyAppBuildResult.Failed -> { return ProxyAppRebuildOutcome.Failure( built.message?.let(QuickBuildMessage::Literal) @@ -313,6 +321,13 @@ class GradleQuickBuildProvisioner( /** Another Gradle build owns the single slot, so nothing ran. */ data object SlotBusy : ProxyAppBuildResult + /** + * Quick Build is deliberately off for this project (the SQLite debugger is on), so nothing + * ran and nothing failed. Split from [Failed] so the session can say so rather than offer a + * retry. + */ + data object Refused : ProxyAppBuildResult + /** * [message] replaces the caller's generic wording when the cause is one the user can * act on. Null keeps the generic "proxy app build failed" for genuine build failures. @@ -544,20 +559,19 @@ class GradleQuickBuildProvisioner( private fun sqliteDebuggerRefusal( projectManager: IProjectManager, projectRoot: File, - ): ProxyAppBuildResult.Failed? { - val refusal = - QuickBuildProjectSupport.sqliteDebuggerMessage( - QuickBuildProjectSupport.isSqliteDebuggerEnabled( - projectRoot, - Environment.GRADLE_USER_HOME, - projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, - ), - ) ?: return null + ): ProxyAppBuildResult.Refused? { + QuickBuildProjectSupport.sqliteDebuggerMessage( + QuickBuildProjectSupport.isSqliteDebuggerEnabled( + projectRoot, + Environment.GRADLE_USER_HOME, + projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, + ), + ) ?: return null log.info( "Quick Build is not provisioned: {} is true in the Gradle user home's, an app module's or the project's gradle.properties", GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, ) - return ProxyAppBuildResult.Failed(context.getString(refusal)) + return ProxyAppBuildResult.Refused } /** `:app` -> `/app`; nested paths (`:feature:home`) map to nested dirs. */ diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildFlashes.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildFlashes.kt index 30294662df..1b0167691c 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildFlashes.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildFlashes.kt @@ -77,6 +77,7 @@ class QuickBuildFlashes { // nothing here either. QuickBuildTransition.SessionStopped, QuickBuildTransition.StartFailed, + QuickBuildTransition.StartRefused, -> { flashedFailure = null null diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt index 6f5b065d98..94e43e1469 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt @@ -78,6 +78,10 @@ fun QuickBuildMessage.resolve(context: Context): String = context.getString(R.string.quick_build_scratch_dir_unavailable, path) } + QuickBuildMessage.DisabledBySqliteDebugger -> { + context.getString(R.string.quick_build_disabled_sqlite_debugger) + } + QuickBuildMessage.DaemonRejectedConfiguration -> { context.getString(R.string.quick_build_daemon_rejected_config) } diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildOutputLines.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildOutputLines.kt index 3b8d9ef50a..4cf21345b6 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildOutputLines.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildOutputLines.kt @@ -48,6 +48,12 @@ fun quickBuildOutputLines( listOf("could not start - tap Quick Build to retry.") } + // The refusal itself went to the flash and the log line that made it; a refusal is not a + // failure, so this only says what the tap does. + QuickBuildTransition.StartRefused -> { + listOf("off while the SQLite debugger is on - tap Quick Build to see why.") + } + is QuickBuildTransition.ProvisioningStarted -> { when (val kind = transition.kind) { is ProvisioningKind.Rebaseline -> { diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt index 47f9f10694..fc75a5546a 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt @@ -88,6 +88,12 @@ fun quickBuildStatusBarUpdate( QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_start_failed) } + QuickBuildTransition.StartRefused -> { + // Not a failure: Quick Build is deliberately off here, and a retry cannot help. The tap + // shows the full refusal again. + QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_off_sqlite_debugger) + } + is QuickBuildTransition.ProvisioningStarted -> { when (transition.kind) { is ProvisioningKind.Rebaseline -> { diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTransitions.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTransitions.kt index 289192acbc..e24a80b995 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTransitions.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTransitions.kt @@ -30,6 +30,13 @@ internal sealed interface QuickBuildTransition { */ data object StartFailed : QuickBuildTransition + /** + * A session start was declined on purpose: Quick Build is off for this project while the + * SQLite debugger is on. Nothing failed and retrying cannot help, so surfaces must not say + * "failed" or offer a retry; the tap shows the refusal again. + */ + data object StartRefused : QuickBuildTransition + /** * A full Gradle build started. * @@ -132,7 +139,9 @@ internal fun quickBuildTransition( } return when (current) { is QuickBuildStatus.Hidden -> { - if (current.lastStartFailed) { + if (current.lastStartFailed && current.startRefused) { + QuickBuildTransition.StartRefused + } else if (current.lastStartFailed) { QuickBuildTransition.StartFailed } else { QuickBuildTransition.SessionStopped diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt index 01913f067d..d7b1655fcc 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt @@ -216,6 +216,21 @@ class GradleQuickBuildProvisionerFailureArmsTest { .isEqualTo(context.getString(R.string.quick_build_variant_setup_missing, "debug")) } + @Test + fun `a project with the SQLite debugger on is refused as an off state, not a setup failure`() = + runTest { + File(projectRoot, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + val gradle = FakeBuildService(result = TaskExecutionResult(true, null)) + + val outcome = testProvisioner(context, projectRoot, buildService = gradle).provision() + + // Its own message, so the session can tell this deliberate refusal from a fault. + assertThat(outcome).isEqualTo(ProvisionOutcome.Failure(QuickBuildMessage.DisabledBySqliteDebugger)) + assertThat(failureText(outcome)).isEqualTo(context.getString(R.string.quick_build_disabled_sqlite_debugger)) + assertThat(failureText(outcome)).isNotEqualTo(context.getString(R.string.quick_build_setup_failed)) + assertThat(gradle.executedTasks).isNull() + } + @Test fun `a Gradle build that failed falls back to the generic setup-failure text`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt index 1bd4a2acc3..bc5952fc6a 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.resources.R import org.appdevforall.cotg.quickbuild.domain.classify.InvalidationReason import org.appdevforall.cotg.quickbuild.domain.reload.BuildDiagnostic +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildMessage import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildSessionState import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildStatus import org.appdevforall.cotg.quickbuild.domain.session.SessionEvent @@ -278,6 +279,34 @@ class QuickBuildStatusBarTest { .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_start_failed)) } + @Test + fun `a refused start says Quick Build is off, not that setup failed, and a real failure still does`() { + val reducer = SessionReducer() + val refused = + reducer + .reduce( + QuickBuildSessionState.Provisioning(), + SessionEvent.ProvisioningFailed(QuickBuildMessage.DisabledBySqliteDebugger), + ).state + val failed = + reducer + .reduce( + QuickBuildSessionState.Provisioning(), + SessionEvent.ProvisioningFailed(QuickBuildMessage.RebuildFailed), + ).state + + assertThat(update(QuickBuildStatus.Provisioning(), QuickBuildStatus.from(refused))) + .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_off_sqlite_debugger)) + // A recreation resubscribes with no previous status and must read the same. + assertThat(update(null, QuickBuildStatus.from(refused))) + .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_off_sqlite_debugger)) + assertThat(update(QuickBuildStatus.Provisioning(), QuickBuildStatus.from(failed))) + .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_start_failed)) + // A save clears the carried refusal as it does a failure. + assertThat(QuickBuildStatus.from(reducer.reduce(refused, SessionEvent.FileSaved).state)) + .isEqualTo(QuickBuildStatus.Hidden()) + } + @Test fun `closing the project ends the failed-start story, so the next one keeps its own line`() { // The bar cannot tell a recreation - where the failed-start line must come back, pinned diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt index b6f9f2774e..9192c8e5ff 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt @@ -20,6 +20,13 @@ sealed interface QuickBuildMessage { val text: String, ) : QuickBuildMessage + /** + * Quick Build is deliberately off for this project because the SQLite debugger is on + * (`cogo.sqliteDebugger=true`). Nothing failed and a retry cannot help, so the session records + * it apart from a failed start ([QuickBuildSessionState.Idle.startRefused]). + */ + data object DisabledBySqliteDebugger : QuickBuildMessage + /** * The OS wants the reinstall confirmed but no dialog could be shown, because CoGo was not * in the foreground to host it. Returning to CoGo is what re-prompts. diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildSessionState.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildSessionState.kt index 522e896738..bd45278231 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildSessionState.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildSessionState.kt @@ -19,9 +19,14 @@ sealed interface QuickBuildSessionState { * failure flash. Cleared by the next tap (which starts a fresh provision anyway) or the next * save ([SessionEvent.FileSaved]) - the save clears the tone only and never retries the * start; a retry stays a tap. + * @property startRefused the failed start was a deliberate refusal + * ([QuickBuildMessage.DisabledBySqliteDebugger]) rather than a fault, so the status line says + * Quick Build is off instead of offering a retry that cannot help. Only meaningful with + * [lastStartFailed]; cleared by the same gestures. */ data class Idle( val lastStartFailed: Boolean = false, + val startRefused: Boolean = false, ) : QuickBuildSessionState /** @@ -33,10 +38,12 @@ sealed interface QuickBuildSessionState { * @property lastStartFailed carried from [Idle.lastStartFailed] so the silent warm build does * not clear the failed-start error tone on its way through; a queued tap clears it, and a * tapless finish hands it back to [Idle]. + * @property startRefused carried from [Idle.startRefused] alongside [lastStartFailed]. */ data class Prebuilding( val tapQueued: Boolean = false, val lastStartFailed: Boolean = false, + val startRefused: Boolean = false, ) : QuickBuildSessionState /** diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt index 78480dcd52..c53d6b3723 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt @@ -19,9 +19,12 @@ sealed interface QuickBuildStatus { * ([QuickBuildSessionState.Idle.lastStartFailed]), so the bolt keeps the error tone until * the next tap or save; carried here because a failed start rests in Hidden and the tone * is derived from status alone. + * @property startRefused that failed start was Quick Build deliberately declining the project + * ([QuickBuildSessionState.Idle.startRefused]), not a fault; surfaces word it differently. */ data class Hidden( val lastStartFailed: Boolean = false, + val startRefused: Boolean = false, ) : QuickBuildStatus /** @@ -120,7 +123,7 @@ sealed interface QuickBuildStatus { fun from(state: QuickBuildSessionState): QuickBuildStatus = when (state) { is QuickBuildSessionState.Idle -> { - Hidden(state.lastStartFailed) + Hidden(state.lastStartFailed, state.startRefused) } // A warm-up the user never asked for stays invisible - but it must not clear a @@ -128,7 +131,7 @@ sealed interface QuickBuildStatus { is QuickBuildSessionState.Prebuilding -> { // A warm build has no baseline to replace, so a tap that queues on one is // always a session's first provision. - if (state.tapQueued) Provisioning() else Hidden(state.lastStartFailed) + if (state.tapQueued) Provisioning() else Hidden(state.lastStartFailed, state.startRefused) } is QuickBuildSessionState.Provisioning -> { diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/SessionReducer.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/SessionReducer.kt index 04870a25ab..59fcf0a523 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/SessionReducer.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/SessionReducer.kt @@ -99,7 +99,10 @@ class SessionReducer { // The flag rides along so the silent warm build cannot clear a failed-start // tone: only a tap or a save is a user gesture. SessionTransition( - QuickBuildSessionState.Prebuilding(lastStartFailed = state.lastStartFailed), + QuickBuildSessionState.Prebuilding( + lastStartFailed = state.lastStartFailed, + startRefused = state.startRefused, + ), listOf(SessionEffect.StartProxyAppPrebuild), ) } @@ -164,13 +167,16 @@ class SessionReducer { // the tooling server); it queues and fires on PrebuildFinished. The tap is also // the retry gesture, so it clears a carried failed-start tone. is SessionEvent.QuickBuildTapped -> { - SessionTransition(state.copy(tapQueued = true, lastStartFailed = false), listOf(SessionEffect.RecordAsk)) + SessionTransition( + state.copy(tapQueued = true, lastStartFailed = false, startRefused = false), + listOf(SessionEffect.RecordAsk), + ) } SessionEvent.FileSaved -> { // Same clearing gesture as in Idle; the warm build itself is not one. if (state.lastStartFailed) { - SessionTransition(state.copy(lastStartFailed = false)) + SessionTransition(state.copy(lastStartFailed = false, startRefused = false)) } else { SessionTransition(state) } @@ -186,7 +192,12 @@ class SessionReducer { } else { // A carried failed-start tone goes back to Idle uncleared: the warm build's // outcome is silent either way, and only a tap or a save clears the tone. - SessionTransition(QuickBuildSessionState.Idle(lastStartFailed = state.lastStartFailed)) + SessionTransition( + QuickBuildSessionState.Idle( + lastStartFailed = state.lastStartFailed, + startRefused = state.startRefused, + ), + ) } } @@ -300,7 +311,10 @@ class SessionReducer { // lastStartFailed keeps the error tone on the bolt after the failure flash // fades - a plain Idle here read READY right after a failed start (Q8). SessionTransition( - QuickBuildSessionState.Idle(lastStartFailed = true), + QuickBuildSessionState.Idle( + lastStartFailed = true, + startRefused = event.message == QuickBuildMessage.DisabledBySqliteDebugger, + ), listOf(SessionEffect.WithdrawAsk, SessionEffect.SurfaceProvisioningError(event.message)), ) } diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index ba8a7c439b..fbd9b0622e 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1218,6 +1218,7 @@ Quick Build: starting a full build… Quick Build failed - see Build Output Quick Build: setup failed - tap to retry + Quick Build: off while the SQLite debugger is on - tap for details Quick Build failed. See the Build Output panel for more details. Quick Build successful Quick Build compiler restarting… From 6468cff87d01eea0e458e59899b9289669a7b07b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 08:40:11 -0800 Subject: [PATCH 082/203] ADFA-7136 Say that a full integrity_check fails on the app's index functions A full integrity_check evaluates the functions an index uses and fails with "unknown function" when the app added one to its own connections; quick_check does not. integrity_check's description and the README say so and name quick_check as the alternative. The description test pins the phrase. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 4 +++- .../org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 4 ++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 5fcde2f961..248d961c6c 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,7 +34,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. -- **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. +- **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. A full `integrity_check` (`full: true`) fails the same way, with "unknown function", when one of the app's indexes is on an expression that calls such a function; `quick_check` (the default) does not, and the description of `integrity_check` says to use it then. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). - **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query`, reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr`. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index defe35a5f7..d27e0d0a53 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -242,7 +242,9 @@ class DatabaseTools( "integrity_check", "Check integrity", "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. " + - "ok is true when SQLite reports no problem.", + "ok is true when SQLite reports no problem. A full integrity_check fails with \"unknown function\" when one of the " + + "app's indexes uses a function the app adds to its own connections (an index on an expression); quick_check " + + "does not, so use it then.", databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), ) { call, args -> integrityCheck(call, args) }, tool( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 589cea8305..7c04dfc122 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -223,6 +223,10 @@ class DatabaseToolsTest { assertTrue(schema, schema.contains("past the first ${DatabaseTools.MAX_ROWS}")) assertTrue(schema, schema.contains("past about 4 MiB of cell bytes")) assertTrue(schema, schema.contains("page through sqlite_master with query")) + // A full integrity_check evaluates the app's index functions; quick_check does not. + val integrity = descriptions.getValue("integrity_check") + assertTrue(integrity, integrity.contains("full integrity_check fails with \"unknown function\"")) + assertTrue(integrity, integrity.contains("quick_check does not")) } @Test fun queryChecksItsArguments() { From cee95acd7d5f8a86cf65a143eda806533630e6c2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 08:40:11 -0800 Subject: [PATCH 083/203] ADFA-7136 Give get_schema's paging advice an ORDER BY and the right unit The advice to page through sqlite_master gave no ORDER BY, so pages could overlap or skip rows; it now says ORDER BY name. substr counts characters while the TEXT limit counts bytes, which the description and README now say. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 4 ++-- .../org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 248d961c6c..e95de90e75 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. A full `integrity_check` (`full: true`) fails the same way, with "unknown function", when one of the app's indexes is on an expression that calls such a function; `quick_check` (the default) does not, and the description of `integrity_check` says to use it then. - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query`, reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr`. A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY name`), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index d27e0d0a53..aa125641a9 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -202,8 +202,8 @@ class DatabaseTools( "truncated_cells counts the cut values. The top-level truncated is true when anything was cut or entries were left " + "out: past the first $MAX_ROWS, or past about ${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (about " + "${MAX_TOTAL_BYTES / MAX_SCHEMA_SQL_BYTES} statements of ${MAX_SCHEMA_SQL_BYTES / 1024} KiB). There is no offset: " + - "to read the rest, page through sqlite_master with query, and read a statement longer than its " + - "$MAX_TEXT_BYTES-byte TEXT limit in parts with substr.", + "to read the rest, page through sqlite_master with query (ORDER BY name), and read a statement longer than its " + + "$MAX_TEXT_BYTES-byte TEXT limit in parts with substr (it counts characters, not bytes).", databaseSchema(), ) { call, args -> getSchema(call, args) }, tool( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 7c04dfc122..838af5b267 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -222,7 +222,8 @@ class DatabaseToolsTest { val schema = descriptions.getValue("get_schema") assertTrue(schema, schema.contains("past the first ${DatabaseTools.MAX_ROWS}")) assertTrue(schema, schema.contains("past about 4 MiB of cell bytes")) - assertTrue(schema, schema.contains("page through sqlite_master with query")) + assertTrue(schema, schema.contains("page through sqlite_master with query (ORDER BY name)")) + assertTrue(schema, schema.contains("counts characters, not bytes")) // A full integrity_check evaluates the app's index functions; quick_check does not. val integrity = descriptions.getValue("integrity_check") assertTrue(integrity, integrity.contains("full integrity_check fails with \"unknown function\"")) From 0550b8899c1e983129fda2a28cb5769bf02987e5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 08:48:37 -0800 Subject: [PATCH 084/203] ADFA-7138 End a live Quick Build session in the refused state when the SQLite debugger is turned on Adding cogo.sqliteDebugger=true and saving during a live session made the rebaseline refuse, but the manager recorded that as a failed rebuild ("Quick Build failed"), parked for retry, and was refused again on every save. A refused rebuild now ends like a refused start: the session goes to Idle with startRefused, so the status line reads "Quick Build: off while the SQLite debugger is on - tap for details", and nothing retries. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../session/QuickBuildSessionManager.kt | 8 ++++++- .../session/QuickBuildSessionManagerTest.kt | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt index 353850626e..5678923034 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt @@ -1343,7 +1343,13 @@ class QuickBuildSessionManager( // event, so a still-broken build file does not loop. session.orchestrator.onProxyAppRebuildFailed() val park = rebuildPark - if (park != null) { + if (result.message == QuickBuildMessage.DisabledBySqliteDebugger) { + // Not a build failure: the user turned the SQLite debugger on mid-session, so + // Quick Build is off for this project. A park would retry on every save and be + // refused each time; end like a refused start (Idle, "off" status) instead. + log.info("Proxy app rebuild refused: the SQLite debugger is on; ending the session") + dispatch(SessionEvent.ProvisioningFailed(result.message)) + } else if (park != null) { // Park recoverable instead of dying to Idle: the session and the running proxy // app are both fine; what failed is the user's build files. The message is // surfaced here rather than through SurfaceProvisioningError, whose effect diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt index ae7120ce84..212220a830 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt @@ -1680,6 +1680,28 @@ class QuickBuildSessionManagerTest { assertThat(userMessages).contains(QuickBuildMessage.Literal("manifest does not build")) } + @Test + fun `a rebuild refused for the SQLite debugger ends in the refused state with no retry`() = + runTest { + proxyAppRebuildOutcome = { ProxyAppRebuildOutcome.Failure(QuickBuildMessage.DisabledBySqliteDebugger) } + val manager = createManager() + manager.onQuickBuildTapped() + advanceUntilIdle() + + manager.save(gradleFile) + advanceUntilIdle() + + // Same state as a refused start, not a parked failed rebuild. + assertThat(manager.state.value) + .isEqualTo(QuickBuildSessionState.Idle(lastStartFailed = true, startRefused = true)) + assertThat(userMessages).contains(QuickBuildMessage.DisabledBySqliteDebugger) + assertThat(proxyAppRebuildCount).isEqualTo(1) + + manager.save(gradleFile) + advanceUntilIdle() + assertThat(proxyAppRebuildCount).isEqualTo(1) + } + // Review gap (2026-07-26 #69): pin the failed proxy app rebuild's DAEMON state and the // recovery - the session must stay recoverable, not linger wedged and daemon-less. @Test From babc5fe530a63d08dff1ac3129cc37bd0408d29e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 08:55:56 -0800 Subject: [PATCH 085/203] ADFA-7138 Drop the unused sqliteDebuggerMessage and share the AAR-property check The Quick Build opt-in check threw sqliteDebuggerMessage's result away and kept only its null test, and the function's doc still pointed at that use; it and its test are gone and the doc moved to isSqliteDebuggerEnabled. SqliteRewritePlugin repeated SqliteDebuggerPlugin's AAR-property check; both now call Project.requireSqliteAar, with the same messages. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 6 ++-- .../quickbuild/QuickBuildProjectSupport.kt | 24 ++++--------- .../QuickBuildProjectSupportTest.kt | 7 ---- .../com/itsaky/androidide/gradle/SqliteAar.kt | 34 +++++++++++++++++++ .../androidide/gradle/SqliteDebuggerPlugin.kt | 16 +-------- .../gradle/sqlite/SqliteRewritePlugin.kt | 15 ++------ 6 files changed, 46 insertions(+), 56 deletions(-) create mode 100644 gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 0d2eda903a..db7848ac70 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -560,13 +560,13 @@ class GradleQuickBuildProvisioner( projectManager: IProjectManager, projectRoot: File, ): ProxyAppBuildResult.Refused? { - QuickBuildProjectSupport.sqliteDebuggerMessage( + val enabled = QuickBuildProjectSupport.isSqliteDebuggerEnabled( projectRoot, Environment.GRADLE_USER_HOME, projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, - ), - ) ?: return null + ) + if (!enabled) return null log.info( "Quick Build is not provisioned: {} is true in the Gradle user home's, an app module's or the project's gradle.properties", GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt index 58fe82ebff..6ad9f0beac 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt @@ -68,23 +68,6 @@ object QuickBuildProjectSupport { null } - /** - * A project with `cogo.sqliteDebugger=true` is moved to requery by the Gradle plugin, which - * never applies Quick Build to it (its payload would compile the source without the move). The - * IDE must not provision it either: the build would succeed and then end in a "variant setup - * missing" message that blames the variant. - * - * @param sqliteDebuggerEnabled see [isSqliteDebuggerEnabled]. - * @return the refusal message, or null when Quick Build may run. - */ - @StringRes - fun sqliteDebuggerMessage(sqliteDebuggerEnabled: Boolean): Int? = - if (sqliteDebuggerEnabled) { - R.string.quick_build_disabled_sqlite_debugger - } else { - null - } - /** * Whether one `gradle.properties` text opts in, decided as the Gradle plugin does: the value is * exactly `true`. @@ -94,7 +77,12 @@ object QuickBuildProjectSupport { fun isSqliteDebuggerEnabled(gradleProperties: String?): Boolean = gradleProperties != null && propertyValue(gradleProperties) == "true" /** - * Whether the project opts in, from the same files the Gradle plugin's `findProperty` sees in + * Whether the project opts in to `cogo.sqliteDebugger=true`, in which case Quick Build must not + * provision it: the Gradle plugin moves such a project to requery and never applies Quick Build + * to it, so a build would succeed and end in a "variant setup missing" message that blames the + * variant. Decided per project, from all app modules (see [moduleDirs]). + * + * Reads the opt-in from the same files the Gradle plugin's `findProperty` sees in * Code on the Go's builds: the Gradle user home `gradle.properties` (`GRADLE_USER_HOME`, which * overrides the project files), the app module's, and the root's. Gradle loads a * `gradle.properties` from every project directory into that project, and a subproject also diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt index ceb3e13999..9a6ab5b9ee 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt @@ -77,13 +77,6 @@ class QuickBuildProjectSupportTest { assertThat(QuickBuildProjectSupport.nonDebuggableVariantMessage("demoStaging")).isNull() } - @Test - fun `an opted-in SQLite debugger project is refused with its own message`() { - assertThat(QuickBuildProjectSupport.sqliteDebuggerMessage(sqliteDebuggerEnabled = true)) - .isEqualTo(R.string.quick_build_disabled_sqlite_debugger) - assertThat(QuickBuildProjectSupport.sqliteDebuggerMessage(sqliteDebuggerEnabled = false)).isNull() - } - @Test fun `gradle properties decide the opt-in as the Gradle plugin does`() { assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("org.gradle.jvmargs=-Xmx2g\ncogo.sqliteDebugger=true\n")).isTrue() diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt new file mode 100644 index 0000000000..625f2c997b --- /dev/null +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt @@ -0,0 +1,34 @@ +package com.itsaky.androidide.gradle + +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import org.gradle.api.GradleException +import org.gradle.api.Project +import java.io.File + +/** + * The AAR that [property] names, for a plugin applied only when `cogo.sqliteDebugger=true`. + * Fails the build when the property is unset or the file is missing: the project opted in, and a + * build that quietly drops the feature leaves the user wondering why it does nothing. + * + * @param aarLabel what the AAR is called in the "not found" message. + * @param feature what the user's opt-in turns on, for the "remove the line" advice. + */ +internal fun Project.requireSqliteAar( + property: String, + aarLabel: String, + feature: String, +): File { + val aar = + findProperty(property)?.let { File(it.toString()) } + ?: throw GradleException( + "'$PROPERTY_SQLITE_DEBUGGER_ENABLED' is true but no property '$property' is set. " + + "Remove the line from gradle.properties to build without the $feature.", + ) + if (!aar.isFile) { + throw GradleException( + "$aarLabel not found at '${aar.absolutePath}'. " + + "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it.", + ) + } + return aar +} diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt index 72e2b3985d..a52cfbb5f7 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteDebuggerPlugin.kt @@ -6,11 +6,9 @@ import com.android.build.api.variant.Component import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED import org.adfa.constants.KOTLIN_VERSION -import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.logging.Logging -import java.io.File import java.lang.reflect.Method /** @@ -54,19 +52,7 @@ class SqliteDebuggerPlugin : Plugin { logger.lifecycle("Applying {} to project '{}'", javaClass.simpleName, target.path) } - val aar = - target.findProperty(PROPERTY_SQLITE_DEBUGGER_AAR)?.let { File(it.toString()) } - ?: throw GradleException( - "'$PROPERTY_SQLITE_DEBUGGER_ENABLED' is true but no property '$PROPERTY_SQLITE_DEBUGGER_AAR' is set. " + - "Remove the line from gradle.properties to build without the SQLite debugger.", - ) - - if (!aar.isFile) { - throw GradleException( - "SQLite debugger AAR not found at '${aar.absolutePath}'. " + - "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it.", - ) - } + val aar = target.requireSqliteAar(PROPERTY_SQLITE_DEBUGGER_AAR, "SQLite debugger AAR", "SQLite debugger") target.extensions.getByType(ApplicationAndroidComponentsExtension::class.java).apply { val addDebugger = { variant: ApplicationVariant -> diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt index 3f80201b35..5fece80083 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewritePlugin.kt @@ -6,14 +6,13 @@ import com.android.build.api.instrumentation.InstrumentationScope import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.itsaky.androidide.gradle.APP_PLUGIN import com.itsaky.androidide.gradle.requireRuntimeConfiguration +import com.itsaky.androidide.gradle.requireSqliteAar import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR -import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.type.ArtifactTypeDefinition import org.gradle.api.logging.Logging -import java.io.File /** * Registers the android.database.sqlite -> requery class rewrite on every variant (ADFA-7138), adds the @@ -40,17 +39,7 @@ class SqliteRewritePlugin : Plugin { logger.info("Applying SqliteRewritePlugin to project '${target.path}'") val runtimeAar = - target.findProperty(PROPERTY_SQLITE_REWRITE_RUNTIME_AAR)?.let { File(it.toString()) } - ?: throw GradleException( - "'$PROPERTY_SQLITE_DEBUGGER_ENABLED' is true but no property '$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR' is set. " + - "Remove the line from gradle.properties to build without the SQLite rewrite.", - ) - if (!runtimeAar.isFile) { - throw GradleException( - "SQLite rewrite runtime AAR not found at '${runtimeAar.absolutePath}'. " + - "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it.", - ) - } + target.requireSqliteAar(PROPERTY_SQLITE_REWRITE_RUNTIME_AAR, "SQLite rewrite runtime AAR", "SQLite rewrite") target.extensions.getByType(ApplicationAndroidComponentsExtension::class.java).onVariants { variant -> variant.instrumentation.transformClassesWith( From b93bf8e3e2b37e37dbde60f37771526e306adeb7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 08:55:56 -0800 Subject: [PATCH 086/203] ADFA-7138 Document that the SQLite debugger opt-in is decided from all app modules Quick Build builds only the first app module, but the opt-in check reads every app module's gradle.properties, so two app modules that disagree are refused for both. That is deliberate: the opt-in is per project. A comment at the check and a sentence in the README say so. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt | 2 ++ subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index db7848ac70..908d0b80b8 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -560,6 +560,8 @@ class GradleQuickBuildProvisioner( projectManager: IProjectManager, projectRoot: File, ): ProxyAppBuildResult.Refused? { + // Every app module's gradle.properties is read, although Quick Build builds only the first + // app module: the opt-in is decided per project, so two modules that disagree refuse here. val enabled = QuickBuildProjectSupport.isSqliteDebuggerEnabled( projectRoot, diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 25e532f056..8d6516f4a1 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -13,7 +13,7 @@ A project made from the JavaScript in SQLite template has it on already. For any 3. Check that the app depends on androidx.sqlite (Room and WorkManager bring it) and androidx.core (AppCompat brings it). requery needs both, and a file dependency brings neither. 4. Build and run the debug variant. The app starts the server and sends its port and token to Code on the Go (ADFA-7137), and AI-Agent-MCP connects to it with no setup (ADFA-7139). In phase 1 the Agent asks before each call (ADFA-7147). -The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. Commenting the line out turns all of this off. +The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. The opt-in is decided per project from all app modules: Code on the Go reads the Gradle user home, every app module and the root, so one module that opts in turns Quick Build off for all of them, even though Quick Build builds only the first app module. Commenting the line out turns all of this off. Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails, names the class, method and line, and says how to build without the debugger; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). From bc76c142d703fa0d45e48b72f16a5cbd77877269 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:18:20 -0800 Subject: [PATCH 087/203] ADFA-7136 Say which app functions make quick_check and integrity_check fail A CHECK constraint or a NOT NULL virtual generated column that calls an app function makes quick_check fail too; an index on an expression or a partial index whose WHERE calls one fails only the full integrity_check (verified with SQLite 3.46). Views, triggers and other generated columns fail neither. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 8 +++++--- .../appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 7 +++++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index e95de90e75..08c7a2ebcb 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,7 +34,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. -- **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. A full `integrity_check` (`full: true`) fails the same way, with "unknown function", when one of the app's indexes is on an expression that calls such a function; `quick_check` (the default) does not, and the description of `integrity_check` says to use it then. +- **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). - **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY name`), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index aa125641a9..3bf024a998 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -242,9 +242,11 @@ class DatabaseTools( "integrity_check", "Check integrity", "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. " + - "ok is true when SQLite reports no problem. A full integrity_check fails with \"unknown function\" when one of the " + - "app's indexes uses a function the app adds to its own connections (an index on an expression); quick_check " + - "does not, so use it then.", + "ok is true when SQLite reports no problem. Both checks fail with \"unknown function\" when a CHECK constraint or a " + + "NOT NULL virtual generated column calls a function the app adds to its own connections. A full integrity_check " + + "also fails on an index on such an expression and on a partial index whose WHERE calls one; " + + "quick_check does not fail on those two, so use it then. " + + "Views, triggers and other generated columns do not make either fail.", databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), ) { call, args -> integrityCheck(call, args) }, tool( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 838af5b267..da30f2253c 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -226,8 +226,11 @@ class DatabaseToolsTest { assertTrue(schema, schema.contains("counts characters, not bytes")) // A full integrity_check evaluates the app's index functions; quick_check does not. val integrity = descriptions.getValue("integrity_check") - assertTrue(integrity, integrity.contains("full integrity_check fails with \"unknown function\"")) - assertTrue(integrity, integrity.contains("quick_check does not")) + assertTrue(integrity, integrity.contains("Both checks fail with \"unknown function\" when a CHECK constraint")) + assertTrue(integrity, integrity.contains("NOT NULL virtual generated column")) + assertTrue(integrity, integrity.contains("full integrity_check also fails on an index")) + assertTrue(integrity, integrity.contains("partial index")) + assertTrue(integrity, integrity.contains("quick_check does not fail on those two")) } @Test fun queryChecksItsArguments() { From e1864d22da02a65f34fb65343f0a6c33651f67b6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:18:31 -0800 Subject: [PATCH 088/203] ADFA-7136 Advise ORDER BY type, name to page through sqlite_master get_schema sorts by type, name, and a trigger can share a table's name, so ORDER BY name alone skips or repeats entries when paging with an offset. (type, name) is unique in sqlite_master. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 5 +++-- .../org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 08c7a2ebcb..29675853f9 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY name`), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 3bf024a998..fb274090fb 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -202,8 +202,9 @@ class DatabaseTools( "truncated_cells counts the cut values. The top-level truncated is true when anything was cut or entries were left " + "out: past the first $MAX_ROWS, or past about ${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (about " + "${MAX_TOTAL_BYTES / MAX_SCHEMA_SQL_BYTES} statements of ${MAX_SCHEMA_SQL_BYTES / 1024} KiB). There is no offset: " + - "to read the rest, page through sqlite_master with query (ORDER BY name), and read a statement longer than its " + - "$MAX_TEXT_BYTES-byte TEXT limit in parts with substr (it counts characters, not bytes).", + "to read the rest, page through sqlite_master with query (ORDER BY type, name, the order get_schema uses), " + + "and read a statement longer than its $MAX_TEXT_BYTES-byte TEXT limit in parts with substr " + + "(it counts characters, not bytes).", databaseSchema(), ) { call, args -> getSchema(call, args) }, tool( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index da30f2253c..52450bff2b 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -222,7 +222,7 @@ class DatabaseToolsTest { val schema = descriptions.getValue("get_schema") assertTrue(schema, schema.contains("past the first ${DatabaseTools.MAX_ROWS}")) assertTrue(schema, schema.contains("past about 4 MiB of cell bytes")) - assertTrue(schema, schema.contains("page through sqlite_master with query (ORDER BY name)")) + assertTrue(schema, schema.contains("page through sqlite_master with query (ORDER BY type, name, the order get_schema uses)")) assertTrue(schema, schema.contains("counts characters, not bytes")) // A full integrity_check evaluates the app's index functions; quick_check does not. val integrity = descriptions.getValue("integrity_check") From 541a706ac41cc46cc714170e33af04807792e732 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:40:08 -0800 Subject: [PATCH 089/203] ADFA-7138 Watch every gradle.properties the SQLite debugger opt-in reads QuickBuildProjectLayout.watchedFiles() listed only the root's gradle.properties, so turning cogo.sqliteDebugger=true on in an app module's or the Gradle user home's gradle.properties never invalidated a live Quick Build session and Quick Build stayed on. It now lists every module's and the Gradle user home's gradle.properties too, so a change invalidates the session and the next start refuses. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 2 ++ .../data/QuickBuildProjectLayout.kt | 15 +++++++++---- .../data/QuickBuildProjectLayoutTest.kt | 22 +++++++++++++++++++ 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 908d0b80b8..d6588555bf 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -169,6 +169,7 @@ class GradleQuickBuildProvisioner( extraSourceRoots = proxyApp.sourceRoots, stableIdsFile = proxyApp.stableIdsFile, libraryResourceFlats = proxyApp.libraryResourceFlats, + gradleUserHome = Environment.GRADLE_USER_HOME, ), variantName = buildResult.variantName, baselineGeneration = buildResult.baselineGeneration, @@ -255,6 +256,7 @@ class GradleQuickBuildProvisioner( extraSourceRoots = buildResult.proxyApp.sourceRoots, stableIdsFile = buildResult.proxyApp.stableIdsFile, libraryResourceFlats = buildResult.proxyApp.libraryResourceFlats, + gradleUserHome = Environment.GRADLE_USER_HOME, ), ) } diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt index f0dcf22769..e47c0b1243 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt @@ -29,6 +29,8 @@ import java.io.File * @property libraryResourceFlats pre-compiled `.flat` resource units from the proxy app build, * passed to `aapt2 link` as `-R` overlays so a relink can resolve a resource only a dependency * AAR declares (e.g. Material3's `Theme.Material3.DayNight.NoActionBar`). + * @property gradleUserHome the Gradle user home, whose `gradle.properties` is watched with the + * project's own; null when there is none to watch. */ class QuickBuildProjectLayout( val projectRoot: File, @@ -37,6 +39,7 @@ class QuickBuildProjectLayout( private val extraSourceRoots: List = emptyList(), private val stableIdsFile: File? = null, private val libraryResourceFlats: List = emptyList(), + private val gradleUserHome: File? = null, ) { private val mainDir = File(appModuleDir, "src/main") @@ -107,18 +110,22 @@ class QuickBuildProjectLayout( /** * Exact files watched outside the roots (gradle config; changes invalidate). * - * @return the root's settings/properties/version-catalog files plus both build-script - * spellings for every module, listed unconditionally - only the existing ones are polled. + * @return the root's settings/properties/version-catalog files, both build-script spellings + * and a `gradle.properties` for every module, and the Gradle user home's `gradle.properties`, + * listed unconditionally - only the existing ones are polled. Every `gradle.properties` that + * `QuickBuildProjectSupport.isSqliteDebuggerEnabled` can read is here, so turning the + * opt-in on invalidates a live session. */ fun watchedFiles(): List = - listOf( + listOfNotNull( File(projectRoot, "settings.gradle"), File(projectRoot, "settings.gradle.kts"), File(projectRoot, "gradle.properties"), File(projectRoot, "gradle/libs.versions.toml"), + gradleUserHome?.let { File(it, "gradle.properties") }, ) + moduleDirs().flatMap { - listOf(File(it, "build.gradle"), File(it, "build.gradle.kts")) + listOf(File(it, "build.gradle"), File(it, "build.gradle.kts"), File(it, "gradle.properties")) } /** diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayoutTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayoutTest.kt index cdb7410ea8..9342209127 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayoutTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayoutTest.kt @@ -1,6 +1,7 @@ package org.appdevforall.cotg.quickbuild.data import com.google.common.truth.Truth.assertThat +import org.appdevforall.cotg.quickbuild.domain.watch.WatchFilter import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.io.File @@ -142,6 +143,27 @@ class QuickBuildProjectLayoutTest { ) } + @Test + fun `watchedFiles includes every gradle properties file the sqlite debugger opt-in reads`() { + write("app/build.gradle.kts") + write("feature-login/build.gradle") + val home = File(root, "gradle-user-home") + + val layout = QuickBuildProjectLayout(root, gradleUserHome = home) + val watched = layout.watchedFiles() + + assertThat(watched).containsAtLeast( + File(root, "gradle.properties"), + File(root, "app/gradle.properties"), + File(root, "feature-login/gradle.properties"), + File(home, "gradle.properties"), + ) + // The session's filter must pass a change to each of them, or the opt-in goes unseen. + val filter = WatchFilter(layout.watchedRoots(), watched) + assertThat(filter.isRelevant(File(home, "gradle.properties"))).isTrue() + assertThat(filter.isRelevant(File(root, "feature-login/gradle.properties"))).isTrue() + } + @Test fun `module discovery skips build intermediates and hidden dirs`() { write("app/build.gradle.kts") From 5ebd1fc54b54adb15283777858d80200defd2343 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:40:08 -0800 Subject: [PATCH 090/203] ADFA-7138 Name the Quick Build refusal that replaced sqliteDebuggerMessage in the docs Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index ff317cac29..cd7a92d8ce 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -161,7 +161,7 @@ provider, `` entry or classes). QA runs it on the release APK of an opt the Quick Build daemon from the project's source (and its baseline payload is diverted out of the classes pipeline), so those classes would still use `android.database.sqlite` next to rewritten baseline classes. The plugin logs why and the build is a normal one. The IDE does not provision Quick Build for such a project - either (`QuickBuildProjectSupport.sqliteDebuggerMessage`): it shows `quick_build_disabled_sqlite_debugger`, which + either (`GradleQuickBuildProvisioner.sqliteDebuggerRefusal`): it shows `quick_build_disabled_sqlite_debugger`, which says Quick Build is off while the SQLite debugger is on. - Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not rewritten. From b843c60d0e091c4740bc7a358c94c69cf5165879 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:40:08 -0800 Subject: [PATCH 091/203] ADFA-7138 Describe the opt-in rule: the first file that defines it decides Modules that disagree do not refuse: the Gradle user home, then each app module, then the root are read in order and the first one that defines cogo.sqliteDebugger decides for the whole project. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/quickbuild/GradleQuickBuildProvisioner.kt | 4 +++- subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index d6588555bf..452fed5594 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -563,7 +563,9 @@ class GradleQuickBuildProvisioner( projectRoot: File, ): ProxyAppBuildResult.Refused? { // Every app module's gradle.properties is read, although Quick Build builds only the first - // app module: the opt-in is decided per project, so two modules that disagree refuse here. + // app module: the opt-in is decided per project, and the first file that defines the + // property decides it (the Gradle user home, then the modules in order, then the root), so + // a module's `false` overrides a root `true` as it does in Gradle. val enabled = QuickBuildProjectSupport.isSqliteDebuggerEnabled( projectRoot, diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8d6516f4a1..e01df107f5 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -13,7 +13,7 @@ A project made from the JavaScript in SQLite template has it on already. For any 3. Check that the app depends on androidx.sqlite (Room and WorkManager bring it) and androidx.core (AppCompat brings it). requery needs both, and a file dependency brings neither. 4. Build and run the debug variant. The app starts the server and sends its port and token to Code on the Go (ADFA-7137), and AI-Agent-MCP connects to it with no setup (ADFA-7139). In phase 1 the Agent asks before each call (ADFA-7147). -The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. The opt-in is decided per project from all app modules: Code on the Go reads the Gradle user home, every app module and the root, so one module that opts in turns Quick Build off for all of them, even though Quick Build builds only the first app module. Commenting the line out turns all of this off. +The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. The opt-in is decided per project from all app modules: Code on the Go reads the Gradle user home, every app module and the root, so the first of those files that defines the line decides for the whole project, whatever the other modules say, even though Quick Build builds only the first app module. Commenting the line out turns all of this off. Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails, names the class, method and line, and says how to build without the debugger; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). From 299266ee73ce318039090e957db033c55dfe9a3f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:50:37 -0800 Subject: [PATCH 092/203] ADFA-7135 Register consumer-rules.pro so an app's R8 keeps NativeBridge The file existed but no consumerProguardFiles line named it, so proguard.txt was missing from the AAR and an app's minified build could rename or strip the JNI-registered NativeBridge functions and the DebugEngineException constructor the native code calls. The rules cover every class sqlitedbg_jni.c looks up by name. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/build.gradle.kts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/subprojects/sqlite-debugger/build.gradle.kts b/subprojects/sqlite-debugger/build.gradle.kts index 2acf1dd65c..8223239452 100644 --- a/subprojects/sqlite-debugger/build.gradle.kts +++ b/subprojects/sqlite-debugger/build.gradle.kts @@ -25,6 +25,8 @@ android { arguments += "-DANDROID_STL=none" } } + // The keep rules for the JNI-registered NativeBridge: an app's R8 would otherwise rename or strip them + consumerProguardFiles("consumer-rules.pro") } compileOptions { From 8acd4bdbb9eccb0079c78f5fbb6c8d6adb0553cf Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:50:37 -0800 Subject: [PATCH 093/203] ADFA-7135 Refuse a server connection to a path the app no longer has open checkedPath and runChecked read separate connection snapshots, so a cache miss could open a server connection after the app closed its last connection to that path. Re-check against the snapshot taken under the lock and answer with the same unknown database error. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 27 +++++++++-------- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 30 +++++++++++++++++++ 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index fb274090fb..569a49ee90 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -530,22 +530,22 @@ class DatabaseTools( args: JSONObject, ): String { val path = stringArg(args, "database") - val known = - engine - .connections() - .map { it.path } - .filter { it.isNotEmpty() } - .distinct() + val known = knownPaths(engine.connections()) call.locked { dropStaleServerConnections(engine.connections()) } - if (path !in known) { - throw McpToolError( - "Unknown database \"$path\": use a path from list_databases that is available.", - JSONObject().put("available", JSONArray(known)), - ) - } + if (path !in known) throw unknownDatabase(path, known) return path } + private fun knownPaths(live: List) = live.map { it.path }.filter { it.isNotEmpty() }.distinct() + + private fun unknownDatabase( + path: String, + known: List, + ) = McpToolError( + "Unknown database \"$path\": use a path from list_databases that is available.", + JSONObject().put("available", JSONArray(known)), + ) + private fun run( call: Call, args: JSONObject, @@ -570,6 +570,9 @@ class DatabaseTools( val conn = serverConnections .getOrPut(path) { + // checkedPath looked at an earlier snapshot: the app may have closed its last connection + // to this path since, and the server never opens a database the app doesn't have open. + if (path !in knownPaths(live)) throw unknownDatabase(path, knownPaths(live)) val ids = live.filter { it.path == path && !it.closing }.map { it.id }.toSet() CachedConnection(engine.openServerConnection(path, writable = false), ids) }.connection diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 52450bff2b..0b399c2ade 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -185,6 +185,36 @@ class DatabaseToolsTest { assertTrue(engine.openedServerConnections.isEmpty()) } + @Test fun aQueryRefusesAPathWhoseLastAppConnectionClosedAfterTheFirstCheck() { + engine.appConnections += conn(1, "/data/a.db") + // the app closes its last connection to a.db right after checkedPath's snapshot + val racing = + object : DebugEngine by engine { + private var snapshots = 0 + + override fun connections() = + engine.connections().also { + if (++snapshots == + 1 + ) { + engine.appConnections.removeAll { c -> c.path == "/data/a.db" } + } + } + } + engine.appConnections += conn(2, "/data/b.db") + val r = runTool(DatabaseTools(racing, dir, { now }), "query", db().put("sql", "select 1")) + assertTrue(r.getBoolean("isError")) + assertTrue( + r.toString(), + r + .getJSONArray("content") + .getJSONObject(0) + .getString("text") + .startsWith("Unknown database"), + ) + assertTrue(engine.openedServerConnections.isEmpty()) + } + @Test fun emptyPathOfAnInMemoryConnectionIsNotOpenable() { engine.appConnections += conn(1, "") assertTrue(runTool(tools, "get_stats", db("")).getBoolean("isError")) From e6d91718655b3f119f26ec07b5c605713d865e32 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:50:37 -0800 Subject: [PATCH 094/203] ADFA-7135 Bound a JSON-RPC batch by message count and reply size A batch kept every reply, each up to about 8 MiB, with no limit, all in the host app's heap. Refuse a batch of more than 32 messages whole (400, invalid request), and once a batch's replies reach 8 MiB answer its remaining requests with a -32000 error without running them. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/McpProtocol.kt | 42 ++++++++++++++++++- .../sqlitedebugger/mcp/McpProtocolTest.kt | 37 ++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 34cf7b122b..31dab302ce 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -64,6 +64,19 @@ class McpProtocol( const val INVALID_REQUEST = -32600 const val METHOD_NOT_FOUND = -32601 const val INVALID_PARAMS = -32602 + + /** JSON-RPC's range for errors the server defines: a batch ran past its reply budget. */ + const val BATCH_BUDGET_EXCEEDED = -32000 + + /** Most messages in one batch. A client that needs more sends several POSTs. */ + const val MAX_BATCH_MESSAGES = 32 + + /** + * Once the replies of a batch add up to this many characters, its remaining requests are answered with + * [BATCH_BUDGET_EXCEEDED] without running. A tool reply is at most about 8 MiB (4 MiB of cells, sent as + * text and again as structured content), so a batch holds at most this plus one reply, in the host app's heap. + */ + const val MAX_BATCH_REPLY_CHARS = 8 * 1024 * 1024 const val INSTRUCTIONS = "Inspects and queries the SQLite databases of the app this server runs in, a debug " + "build made with Code on the Go. Every tool is read-only." @@ -113,7 +126,25 @@ class McpProtocol( val detail = "Unsupported MCP-Protocol-Version $versionHeader; this server speaks ${VERSIONS.joinToString()}." return Reply(400, error(null, INVALID_REQUEST, detail).toString()) } - val replies = messages.mapNotNull { handle(it) } + if (messages.size > MAX_BATCH_MESSAGES) { + // Nothing has run: refusing the batch whole beats guessing which messages the client meant to keep. + val detail = "A batch holds at most $MAX_BATCH_MESSAGES messages; send ${messages.size} in several POSTs." + return Reply(400, error(null, INVALID_REQUEST, detail).toString()) + } + val replies = mutableListOf() + var chars = 0L + for (message in messages) { + val reply = + if (chars >= MAX_BATCH_REPLY_CHARS) { + skipped(message) + } else { + handle(message) + } + if (reply == null) continue + // The size is counted as the reply is made, because it all stays in memory until the batch is sent. + chars += reply.toString().length + replies += reply + } if (replies.isEmpty()) return Reply(202, null) return Reply(200, if (parsed is JSONArray) JSONArray(replies).toString() else replies[0].toString()) } @@ -161,6 +192,15 @@ class McpProtocol( return Reply(200, ok(id, result).toString(), mapOf(SESSION_HEADER to session)) } + /** The answer to a message of a batch that is past its reply budget: not run; null for one that needs no answer. */ + private fun skipped(raw: Any?): JSONObject? { + val m = raw as? JSONObject ?: return null + if (m.opt("method") !is String || !m.has("id")) return null + val id = m.opt("id") + val detail = "This batch's replies already reached ${MAX_BATCH_REPLY_CHARS / (1024 * 1024)} MiB: send the rest in another POST." + return error(if (validId(id)) id else null, BATCH_BUDGET_EXCEEDED, detail) + } + /** One message of a POST; null when it needs no answer. */ private fun handle(raw: Any?): JSONObject? { val m = raw as? JSONObject ?: return error(null, INVALID_REQUEST, "Each message must be a JSON object.") diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index b1d48bf176..2788ae745f 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -224,6 +224,43 @@ class McpProtocolTest { assertEquals(2, replies.getJSONObject(1).getInt("id")) } + @Test fun batchOverTheMessageLimitIsRefusedWholeAndRunsNothing() { + val p = protocol() + val s = session(p) + val batch = JSONArray() + repeat(McpProtocol.MAX_BATCH_MESSAGES + 1) { batch.put(request(it, "ping")) } + val r = p.post(batch.toString(), s, null) + assertEquals(400, r.status) + assertEquals(McpProtocol.INVALID_REQUEST, JSONObject(r.body!!).getJSONObject("error").getInt("code")) + val atLimit = JSONArray() + repeat(McpProtocol.MAX_BATCH_MESSAGES) { atLimit.put(request(it, "ping")) } + assertEquals(McpProtocol.MAX_BATCH_MESSAGES, JSONArray(p.post(atLimit.toString(), s, null).body!!).length()) + } + + @Test fun batchPastTheReplyBudgetAnswersTheRestWithAnErrorWithoutRunningThem() { + val p = protocol() + val s = session(p) + val big = "x".repeat(McpProtocol.MAX_BATCH_REPLY_CHARS / 2) + + fun echoCall(id: Int) = request(id, "tools/call", JSONObject().put("name", "echo").put("arguments", JSONObject().put("v", big))) + // each reply is over twice big (the arguments come back as text and as structured content) + val batch = + JSONArray() + .put(echoCall(1)) + .put(echoCall(2)) + .put(echoCall(3)) + .put(request(4, "ping")) + batch.put(JSONObject().put("jsonrpc", "2.0").put("method", "notifications/x")) + val replies = JSONArray(p.post(batch.toString(), s, null).body!!) + assertEquals(4, replies.length()) + assertTrue(replies.getJSONObject(0).has("result")) + for (i in 1..3) { + val e = replies.getJSONObject(i) + assertEquals(i + 1, e.getInt("id")) + assertEquals(McpProtocol.BATCH_BUDGET_EXCEEDED, e.getJSONObject("error").getInt("code")) + } + } + @Test fun initializeMustBeAlone() { val batch = JSONArray().put(JSONObject(initBody())).put(request(2, "ping")) assertEquals(400, protocol().post(batch.toString(), null, null).status) From bc94eaa633a7e60ee1349e4e0f8b3873811384c1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 12:49:04 -0800 Subject: [PATCH 095/203] ADFA-7135 State the true bound on a batch's replies The KDoc said a tool reply is at most about 8 MiB, so a batch holds at most 8 MiB plus one reply. The 4 MiB cap counts cell bytes, not JSON: org.json writes most control characters as a six-character escape, and the text copy escapes the structured copy again, so a TEXT cell of them takes about 13 characters per byte (measured with org.json), and NULL cells count no bytes. Say that the one reply past the budget can be several times 8 MiB. Documentation only: no behaviour change, so no test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 31dab302ce..58ebaa047a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -73,8 +73,11 @@ class McpProtocol( /** * Once the replies of a batch add up to this many characters, its remaining requests are answered with - * [BATCH_BUDGET_EXCEEDED] without running. A tool reply is at most about 8 MiB (4 MiB of cells, sent as - * text and again as structured content), so a batch holds at most this plus one reply, in the host app's heap. + * [BATCH_BUDGET_EXCEEDED] without running. So a batch holds at most this plus one reply in the host app's + * heap, and that one reply can be several times this size. A tool result holds up to 4 MiB of cell bytes, + * sent as text and again as structured content, but that cap counts cell bytes, not JSON: org.json writes + * most control characters as a six-character escape such as `\u0001`, which the text copy escapes again, + * so a TEXT cell of them takes about 13 characters per byte. A NULL cell counts no bytes but is still sent. */ const val MAX_BATCH_REPLY_CHARS = 8 * 1024 * 1024 const val INSTRUCTIONS = From 0defc3f9ab17d241e537dbe5d75e32807b078fb0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 12:49:04 -0800 Subject: [PATCH 096/203] ADFA-7135 Document the batch limits in the README The Limits list left out the two batch caps: more than 32 messages, which is refused whole with a 400 and a null id, and the 8 MiB reply budget, past which the remaining requests get -32000 unrun, to be resent in another POST. Note, as the KDoc does, that the reply crossing the budget can be several times 8 MiB. Documentation only: no behaviour change, so no test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 29675853f9..886fe19407 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing From 85fbbd9a37f67cad0cb6c53b66ce4fd7e0a1ff67 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 12:49:04 -0800 Subject: [PATCH 097/203] ADFA-7135 Refuse a server connection when every app connection to the path is closing runChecked's cache-miss re-check used knownPaths, which counts connections marked closing. When the app's last connection to a path began closing after checkedPath's snapshot, the check passed and the server opened a handle with an empty ids set: the next call dropped it, but that one query read a database the app was closing. Compute the non-closing ids first and answer with the same unknown database error when there are none; the error still lists knownPaths. Test: aQueryRefusesAPathWhoseLastAppConnectionBeganClosingAfterTheFirstCheck fails without the fix at assertTrue(r.getBoolean("isError")) (the query ran, isError false). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 7 +++-- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 28 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 569a49ee90..e572fd158c 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -570,10 +570,11 @@ class DatabaseTools( val conn = serverConnections .getOrPut(path) { - // checkedPath looked at an earlier snapshot: the app may have closed its last connection - // to this path since, and the server never opens a database the app doesn't have open. - if (path !in knownPaths(live)) throw unknownDatabase(path, knownPaths(live)) + // checkedPath looked at an earlier snapshot: the app may have closed, or begun closing, its + // last connection to this path since, and the server never opens a database the app doesn't + // have open. A closing connection is still listed, so knownPaths alone would let it through. val ids = live.filter { it.path == path && !it.closing }.map { it.id }.toSet() + if (ids.isEmpty()) throw unknownDatabase(path, knownPaths(live)) CachedConnection(engine.openServerConnection(path, writable = false), ids) }.connection conn.query(sql, bind, offset, limits, call.deadline) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 0b399c2ade..131fbb6b97 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -215,6 +215,34 @@ class DatabaseToolsTest { assertTrue(engine.openedServerConnections.isEmpty()) } + @Test fun aQueryRefusesAPathWhoseLastAppConnectionBeganClosingAfterTheFirstCheck() { + engine.appConnections += conn(1, "/data/a.db") + engine.appConnections += conn(2, "/data/b.db") + // the app begins closing its last connection to a.db right after checkedPath's snapshot; it stays listed + val racing = + object : DebugEngine by engine { + private var snapshots = 0 + + override fun connections() = + engine.connections().also { + if (++snapshots == 1) { + engine.appConnections.replaceAll { c -> if (c.path == "/data/a.db") c.copy(closing = true) else c } + } + } + } + val r = runTool(DatabaseTools(racing, dir, { now }), "query", db().put("sql", "select 1")) + assertTrue(r.toString(), r.getBoolean("isError")) + assertTrue( + r.toString(), + r + .getJSONArray("content") + .getJSONObject(0) + .getString("text") + .startsWith("Unknown database"), + ) + assertEquals(emptyList>(), engine.openedServerConnections) + } + @Test fun emptyPathOfAnInMemoryConnectionIsNotOpenable() { engine.appConnections += conn(1, "") assertTrue(runTool(tools, "get_stats", db("")).getBoolean("isError")) From 90266f213dce525a468496f8f5398971619fb27d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 12:53:52 -0800 Subject: [PATCH 098/203] ADFA-7138 Narrow the watchedFiles KDoc to the modules the scan finds The KDoc said every gradle.properties isSqliteDebuggerEnabled can read is watched. sqliteDebuggerRefusal reads the directories of every app module in the project model, but watchedFiles lists only the app module Quick Build builds plus the modules moduleDirs finds, at most MODULE_SCAN_MAX_DEPTH levels below the root. Say so, and that a deeper app module's opt-in is read at the next proxy app build (provision or rebaseline) but does not end a running session. Documentation only: no behaviour change, so no test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../cotg/quickbuild/data/QuickBuildProjectLayout.kt | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt index e47c0b1243..454e570131 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt @@ -111,10 +111,13 @@ class QuickBuildProjectLayout( * Exact files watched outside the roots (gradle config; changes invalidate). * * @return the root's settings/properties/version-catalog files, both build-script spellings - * and a `gradle.properties` for every module, and the Gradle user home's `gradle.properties`, - * listed unconditionally - only the existing ones are polled. Every `gradle.properties` that - * `QuickBuildProjectSupport.isSqliteDebuggerEnabled` can read is here, so turning the - * opt-in on invalidates a live session. + * and a `gradle.properties` for every module [moduleDirs] returns (the app module Quick Build + * builds, and each module the scan finds up to [MODULE_SCAN_MAX_DEPTH] levels below the root), + * and the Gradle user home's `gradle.properties`, listed unconditionally - only the existing + * ones are polled. So turning `QuickBuildProjectSupport.isSqliteDebuggerEnabled`'s opt-in on + * in one of those files invalidates a live session. Another app module nested deeper is read + * at the next proxy app build (a provision or a rebaseline), but its `gradle.properties` is + * not watched, so turning the opt-in on there does not end a running session. */ fun watchedFiles(): List = listOfNotNull( From 92007729f0b81b3f3f9ac8fa4faef71b7f72649d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 13:07:20 -0800 Subject: [PATCH 099/203] ADFA-7135 Say the first row of a result can pass the 4 MiB cap The native query always keeps the first row, so a page makes progress, which means a result holds at most 4 MiB of cell bytes or its first row, whichever is larger. The README, the MAX_TOTAL_BYTES and MAX_BATCH_REPLY_CHARS KDoc and the query tool's description stated the cap without that exception. In query, a row can have 2000 columns (SQLite's default SQLITE_MAX_COLUMN; requery 3.49.0's Android.mk does not change it and nothing here calls sqlite3_limit) of 4096 bytes each, about 7.8 MiB. get_schema's 4 columns of at most 64 KiB keep its first row under the cap, so its description stands. Documentation only (the query description is text an agent reads): no behaviour change, so no test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 9 +++++++-- .../org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt | 9 +++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 886fe19407..dcbfad6e66 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a wide SELECT cannot exhaust the app's heap; the rest is paged (`has_more`). The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index e572fd158c..977fb8b483 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -40,7 +40,11 @@ class DatabaseTools( /** get_schema's limit on a CREATE statement, well above [MAX_TEXT_BYTES]. */ const val MAX_SCHEMA_SQL_BYTES = 65536 - /** The most cell bytes one tool result holds (the engine's `maxTotalBytes`); the rest is paged. */ + /** + * The most cell bytes one tool result holds (the engine's `maxTotalBytes`); the rest is paged. The first + * row always comes back whole, so one wider row passes it: in query, up to 2000 columns (SQLite's default + * SQLITE_MAX_COLUMN, which requery keeps) of [MAX_TEXT_BYTES] each, about 7.8 MiB. + */ const val MAX_TOTAL_BYTES = 4 * 1024 * 1024 /** @@ -212,7 +216,8 @@ class DatabaseTools( "Run a query", "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. A result also stops at about " + - "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true). Use offset to page. " + + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + + "comes back whole. Use offset to page. " + "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead.", databaseSchema( "sql" to prop("string", "The SQL statement."), diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index 58ebaa047a..a8257bec02 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -74,10 +74,11 @@ class McpProtocol( /** * Once the replies of a batch add up to this many characters, its remaining requests are answered with * [BATCH_BUDGET_EXCEEDED] without running. So a batch holds at most this plus one reply in the host app's - * heap, and that one reply can be several times this size. A tool result holds up to 4 MiB of cell bytes, - * sent as text and again as structured content, but that cap counts cell bytes, not JSON: org.json writes - * most control characters as a six-character escape such as `\u0001`, which the text copy escapes again, - * so a TEXT cell of them takes about 13 characters per byte. A NULL cell counts no bytes but is still sent. + * heap, and that one reply can be several times this size. A tool result holds up to 4 MiB of cell bytes + * (more only when its first row alone is wider: the first row always comes back whole), sent as text and + * again as structured content, but that cap counts cell bytes, not JSON: org.json writes most control + * characters as a six-character escape such as `\u0001`, which the text copy escapes again, so a TEXT cell + * of them takes about 13 characters per byte. A NULL cell counts no bytes but is still sent. */ const val MAX_BATCH_REPLY_CHARS = 8 * 1024 * 1024 const val INSTRUCTIONS = From dcadfe183a240b46ae46eff68e0f4e903ab92f02 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 14:22:49 -0800 Subject: [PATCH 100/203] ADFA-7135 Say a call that waited half its time limit says so The DatabaseTools KDoc said a call whose time went "mostly" to waiting says so in its error. The check is waited * 2 >= DEADLINE_MS, so it fires at half the 50 s limit, as the README already says ("at least half"). Make the KDoc say at least half, and rename the test that said "mostly", moving its wait from 30 s to exactly half (25 s) so the boundary the KDoc states is pinned: with > in place of >=, that test fails. Documentation only: no behaviour change, so no regression test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 2 +- .../appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 977fb8b483..618ddde9d0 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -23,7 +23,7 @@ import java.util.TimerTask * a slow query (up to [DEADLINE_MS]) makes the others wait. That is accepted: the debugger serves * one agent, and a connection per call would open the app's file many times over. A tool call's * time limit starts when the call begins, so its waits for the lock count and the server gives up - * before the client does; a call whose time went mostly to waiting says so in its error. + * before the client does; a call that waited at least half its time limit says so in its error. */ class DatabaseTools( private val engine: DebugEngine, diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 131fbb6b97..3f14cc4dbf 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -458,9 +458,9 @@ class DatabaseToolsTest { } @Test(timeout = 10_000) - fun aCallWhoseTimeRanOutMostlyWaitingSaysSo() { - val r = queuedBehindAnotherCall(30_000, ranPastItsLimit) - assertTrue(errorText(r), errorText(r).startsWith("the query ran past its time limit (this call waited 30.0 s of its 50 s")) + fun aCallThatWaitedHalfItsTimeLimitSaysSo() { + val r = queuedBehindAnotherCall(DatabaseTools.DEADLINE_MS / 2, ranPastItsLimit) + assertTrue(errorText(r), errorText(r).startsWith("the query ran past its time limit (this call waited 25.0 s of its 50 s")) } @Test(timeout = 10_000) From 27e004b6263815d88a5d9d2fce38c8fa1bcf1c17 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 19:09:05 -0800 Subject: [PATCH 101/203] ADFA-7138 Run the release-APK guard on every push Nothing ran scripts/check-release-apk-no-sqlite-debugger.sh. SqliteReleaseApkTest builds the minified release and the debug variant of the functional tests' sample app, opted in, with the SQLite debugger and rewrite runtime AARs this repo builds and requery 3.49.0 (JitPack) as a file dependency, and runs the script on both APKs. The release must pass. The debug APK is the control: it must fail on the manifest provider and on libsqlitedbg.so, the checks R8 cannot defeat by renaming classes. The release build also runs the classpath check against requery's real AAR, which the other tests replace with jar stand-ins. :gradle-plugin:sqliteReleaseApkTest builds the two AARs and passes their paths, so :gradle-plugin:test leaves the class out. debug.yml's build_apk job runs the task before the assemble, which then finds the AARs up to date. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .github/workflows/debug.yml | 10 ++ gradle-plugin/build.gradle.kts | 63 ++++++++++++- gradle-plugin/docs/sqlite-rewrite.md | 11 ++- .../androidide/gradle/SqliteReleaseApkTest.kt | 94 +++++++++++++++++++ gradle/libs.versions.toml | 2 + .../check-release-apk-no-sqlite-debugger.sh | 3 +- 6 files changed, 178 insertions(+), 5 deletions(-) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt diff --git a/.github/workflows/debug.yml b/.github/workflows/debug.yml index b0f21d2304..9800a82276 100644 --- a/.github/workflows/debug.yml +++ b/.github/workflows/debug.yml @@ -221,6 +221,16 @@ jobs: exit "$status" fi + # ADFA-7138: builds the minified release and the debug variant of a sample app that opted into the + # SQLite debugger, with the real debugger, rewrite runtime and requery AARs, and runs + # scripts/check-release-apk-no-sqlite-debugger.sh on both. The release must pass; the debug APK must + # fail, which shows the check still sees the debugger. The AARs it builds are the ones the assemble + # below bundles, so they are not built twice. + - name: Check that an opted-in app's release APK carries no SQLite debugger + run: | + command -v unzip || { sudo apt-get update && sudo apt-get install -y unzip; } + flox activate -d flox/base -- ./gradlew :gradle-plugin:sqliteReleaseApkTest --no-daemon + - name: Install advancecomp (advzip, used by recompressApk) run: | command -v advzip || { sudo apt-get update && sudo apt-get install -y advancecomp; } diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index ac6d85a7c2..96cee1492b 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -35,9 +35,7 @@ description = "Gradle Plugin for projects that are built with AndroidIDE" // projectsEvaluated sweep silently misses projects under configure-on-demand. val mavenLocalStagingProjects = listOf(":logsender", ":logger", ":build-info") -tasks.named("test") { - useJUnitPlatform() - +fun Test.stageMavenLocalRepos() { val stagedRepos = mavenLocalStagingProjects.map { path -> dependsOn("$path:publishAllPublicationsToBuildMavenLocalRepository") @@ -65,6 +63,65 @@ tasks.named("test") { } } +val sqliteReleaseApkTestClass = "com.itsaky.androidide.gradle.SqliteReleaseApkTest" + +tasks.named("test") { + useJUnitPlatform() + stageMavenLocalRepos() + // Run by sqliteReleaseApkTest below, which builds the AARs it needs + filter { excludeTestsMatching(sqliteReleaseApkTestClass) } +} + +// The release-APK guard (ADFA-7138): SqliteReleaseApkTest builds the minified release and the debug variant +// of a sample app that opted into the SQLite debugger, with the real debugger, rewrite runtime and requery +// AARs, and runs scripts/check-release-apk-no-sqlite-debugger.sh on both APKs. A task of its own because it +// needs the NDK-built debugger AAR, which the other tests do not; CI's build_apk job runs it on every push. +val requeryAar = + configurations.create("sqliteReleaseApkTestRequery") { + isCanBeConsumed = false + isTransitive = false + } + +dependencies { + add(requeryAar.name, variantOf(libs.tests.requery.sqliteAndroid) { artifactType("aar") }) +} + +// Under configure-on-demand the AAR projects are not configured yet when the task below reads their build +// directories, as in :app +val sqliteReleaseApkTestAarProjects = + mapOf( + "debugger" to ":subprojects:sqlite-debugger", + "rewriteRuntime" to ":subprojects:sqlite-rewrite-runtime", + ) +sqliteReleaseApkTestAarProjects.values.forEach(::evaluationDependsOn) + +tasks.register("sqliteReleaseApkTest") { + description = "Builds an opted-in sample app's release APK and checks that it carries no SQLite debugger" + group = "verification" + val testSourceSet = sourceSets["test"] + testClassesDirs = testSourceSet.output.classesDirs + classpath = testSourceSet.runtimeClasspath + useJUnitPlatform() + stageMavenLocalRepos() + filter { includeTestsMatching(sqliteReleaseApkTestClass) } + + // The tasks AndroidIDEAssetsPlugin bundles these AARs with, so this task and :app:assemble build them once + for ((name, path) in sqliteReleaseApkTestAarProjects) { + dependsOn("$path:assembleRelease") + val aar = + project(path) + .layout.buildDirectory + .file("outputs/aar/${path.substringAfterLast(':')}-release.aar") + .get() + .asFile + inputs.file(aar).withPropertyName("${name}Aar") + systemProperty("cogo.test.sqlite.${name}Aar", aar.absolutePath) + } + inputs.files(requeryAar).withPropertyName("requeryAar") + inputs.file(rootProject.file("scripts/check-release-apk-no-sqlite-debugger.sh")).withPropertyName("checkScript") + jvmArgumentProviders.add(CommandLineArgumentProvider { listOf("-Dcogo.test.sqlite.requeryAar=${requeryAar.singleFile.absolutePath}") }) +} + configurations { val androidBuildTool = create("androidBuildTool") diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index cd7a92d8ce..f1ef51e631 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -138,7 +138,16 @@ this package, so the build does not report it. ## Checking a release APK `scripts/check-release-apk-no-sqlite-debugger.sh ` fails when an APK carries the debugger (native library, -provider, `` entry or classes). QA runs it on the release APK of an opted-in project: the release build must never contain the debugger. +provider, `` entry or classes). The release build must never contain the debugger. R8 renames and drops +classes in a minified release, so the class check can miss them; the manifest and native-library checks are the +ones that hold. + +`:gradle-plugin:sqliteReleaseApkTest` (`SqliteReleaseApkTest`) runs it on every push, in the `build_apk` job of +`.github/workflows/debug.yml`. It builds the minified release and the debug variant of the functional tests' sample +app, opted in, with the debugger and rewrite runtime AARs this repo builds and requery 3.49.0 from JitPack as a file +dependency, and runs the script on both APKs. The release must pass. The debug APK must fail on the provider and on +`libsqlitedbg.so`, which shows the check still sees what the AAR brings. The task builds the AARs it needs, so +`:gradle-plugin:test` leaves this test out. QA can still run the script on any release APK. ## Known limits diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt new file mode 100644 index 0000000000..e290ea18b1 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt @@ -0,0 +1,94 @@ +package com.itsaky.androidide.gradle + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.gradle.sqlite.requireEnvironment +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED +import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR +import com.itsaky.androidide.utils.FileProvider +import org.gradle.testkit.runner.TaskOutcome +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File +import java.util.concurrent.TimeUnit + +/** + * The release-APK guard (ADFA-7138): an app that opted into the SQLite debugger gets it in its debuggable + * variants only. Builds the sample app's minified release and its debug variant with the real debugger, + * rewrite runtime and requery AARs, and runs scripts/check-release-apk-no-sqlite-debugger.sh on both APKs. + * + * The debug APK is the control: it must fail the check, which shows the check still sees the debugger the + * AAR brings. R8 renames and drops classes in a release, so the dex grep of the script can miss them; the + * manifest provider and libsqlitedbg.so are what the control requires to fail. + * + * Run by the sqliteReleaseApkTest task, which builds the AARs and passes their paths. + */ +class SqliteReleaseApkTest { + private fun aar(name: String): File { + val path = System.getProperty("cogo.test.sqlite.${name}Aar") + requireEnvironment(path != null && File(path).isFile, "the $name AAR: run the :gradle-plugin:sqliteReleaseApkTest task") + return File(path!!) + } + + private class CheckResult( + val exitCode: Int, + val output: String, + ) + + private fun checkApk(apk: File): CheckResult { + assertWithMessage("APK not built").that(apk.isFile).isTrue() + val script = FileProvider.projectRoot().resolve("scripts/check-release-apk-no-sqlite-debugger.sh").toFile() + val process = ProcessBuilder("bash", script.path, apk.path).redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().readText() + check(process.waitFor(1, TimeUnit.MINUTES)) { "the check script did not finish" } + println("${apk.name}: exit ${process.exitValue()}\n$output") + return CheckResult(process.exitValue(), output) + } + + @Test + fun `an opted-in app's release APK carries no SQLite debugger, and its debug APK fails the check`( + @TempDir dir: File, + ) { + val debuggerAar = aar("debugger") + val rewriteRuntimeAar = aar("rewriteRuntime") + val requeryAar = aar("requery") + + // compileSdk: the platform CI's flox environment installs. requery comes from libs/ in a real app. + val project = + copySampleProject( + dir, + """ + android { compileSdk = 36 } + dependencies { implementation(files("${requeryAar.invariantSeparatorsPath}")) } + """.trimIndent(), + ) + // R8 does not fit in the fixture's 512m daemon + project.resolve("gradle.properties").toFile().appendText("\norg.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8\n") + + val result = + buildProject(task = ":app:assembleDemoRelease", projectDir = project, configureArgs = { + it += ":app:assembleDemoDebug" + it += "-P$PROPERTY_SQLITE_DEBUGGER_ENABLED=true" + it += "-P$PROPERTY_SQLITE_DEBUGGER_AAR=${debuggerAar.absolutePath}" + it += "-P$PROPERTY_SQLITE_REWRITE_RUNTIME_AAR=${rewriteRuntimeAar.absolutePath}" + }) + + // The release is a real opted-in build: its classpath check accepts requery's AAR as a file dependency, + // and it is rewritten, then minified + assertThat(result.task(":app:checkDemoReleaseSqliteRewriteClasspath")?.outcome).isEqualTo(TaskOutcome.SUCCESS) + assertThat(result.task(":app:transformDemoReleaseClassesWithAsm")?.outcome).isEqualTo(TaskOutcome.SUCCESS) + assertThat(result.task(":app:minifyDemoReleaseWithR8")?.outcome).isEqualTo(TaskOutcome.SUCCESS) + assertThat(result.output).contains("Adding SQLite debugger dependency to variant 'demoDebug' of project ':app'") + + val apks = project.resolve("app/build/outputs/apk/demo").toFile() + val release = checkApk(File(apks, "release/app-demo-release-unsigned.apk")) + assertWithMessage(release.output).that(release.exitCode).isEqualTo(0) + assertThat(release.output).contains("OK: no SQLite debugger found") + + val debug = checkApk(File(apks, "debug/app-demo-debug.apk")) + assertWithMessage(debug.output).that(debug.exitCode).isEqualTo(1) + assertThat(debug.output).contains("FAIL: manifest declares provider org.appdevforall.sqlitedebugger.DebuggerStartup") + assertThat(debug.output).containsMatch("FAIL: native library lib/[^/]+/libsqlitedbg\\.so") + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 45225bc68f..0e023731a4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -302,6 +302,8 @@ tests-junit-platformLauncher = { module = "org.junit.platform:junit-platform-lau tests-junit-vintageEngine = { module = "org.junit.vintage:junit-vintage-engine", version.ref = "junit-jupiter" } core-tests-anroidx-arch = { module = "androidx.arch.core:core-testing", version.ref = "anroidx-test-core" } tests-google-truth = { module = "com.google.truth:truth", version = "1.4.1" } +# The requery the ADFA-7082 template ships in libs/ (JitPack); :gradle-plugin's sqliteReleaseApkTest builds against it +tests-requery-sqliteAndroid = { module = "com.github.requery:sqlite-android", version = "3.49.0" } tests-robolectric = { module = "org.robolectric:robolectric", version = "4.11.1" } tests-androidx-test-core = { module = "androidx.test:core", version = "1.5.0" } tests-androidx-test-monitor = { module = "androidx.test:monitor", version = "1.8.0" } diff --git a/scripts/check-release-apk-no-sqlite-debugger.sh b/scripts/check-release-apk-no-sqlite-debugger.sh index 5e25938e5e..53a6cf42f9 100755 --- a/scripts/check-release-apk-no-sqlite-debugger.sh +++ b/scripts/check-release-apk-no-sqlite-debugger.sh @@ -79,7 +79,8 @@ if awk ' fi # A dex stores type descriptors as plain strings, so a debugger class that got in shows up here even when -# the manifest is clean (a library that registers nothing). +# the manifest is clean (a library that registers nothing). R8 can rename or drop classes in a minified release, +# so this check can miss them: the manifest and native-library checks above are the ones that hold. # grep -c reads all its input: with pipefail, grep -q exiting early would make unzip die of SIGPIPE # and the pipeline report failure. dex_hits=$(unzip -p "$apk" 'classes*.dex' 2>/dev/null | grep -ac 'Lorg/appdevforall/sqlitedebugger/' || true) From 298071c398c29484e1a1af4a962d11d1299e6733 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 19:09:05 -0800 Subject: [PATCH 102/203] ADFA-7138 Document that COPY_FRAMES cannot weaken another instrumentation Review asked whether the rewrite's per-variant COPY_FRAMES could leave stale frames in classes another instrumentation changes. It cannot: AGP 7.3.0, 8.8.2 and 9.3.1 keep the highest mode any plugin asks for (javap of AsmClassVisitorsFactoryRegistry.setAsmFramesComputationMode), and COPY_FRAMES is the lowest. The docs record that and the one-off AGP 9.3.1 build that confirmed it, with its control. No code change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index f1ef51e631..084754990d 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -93,6 +93,20 @@ cannot load, so the transform runs only on projects that opted in. Commenting th stays valid, and writes every frame of that method in full (compressed frames are relative to the implicit first frame, which now has the wide type). A driver that is handed an `Object[]` with an element that is not a `String` throws `ClassCastException` on entry; requery's own drivers pass strings. + The mode is per variant, but `COPY_FRAMES` cannot weaken another instrumentation in the same build (Hilt, Firebase, + an app's own `transformClassesWith`) that needs frames computed: `setAsmFramesComputationMode` keeps the highest + mode any plugin asks for (AGP 7.3.0, 8.8.2 and 9.3.1 compare the enum ordinals; checked with javap), and + `COPY_FRAMES` is the lowest. Checked once (2026-11-17, AGP 9.3.1, not a standing test) in the order a last-call-wins + rule would break: CoGo applies its plugin in `afterEvaluate`, so its `onVariants` runs after the app's. The + functional tests' sample app, opted in, got a `SQLiteOpenHelper` subclass, a `SQLiteCursorDriver` and a second + `AsmClassVisitorFactory` (scope ALL) that inserts `if (0 != 0) throw null` at the start of every method but + constructors of the app, androidx.sqlite and Room, and asks for `COMPUTE_FRAMES_FOR_INSTRUMENTED_METHODS`. + demoDebug and demoRelease assembled (D8, R8). Their transformed classes, 232 each, pass ASM's `CheckClassAdapter` + and the JVM's verifier (each class linked against android.jar and the instrumented dependency jars), except Room's + `LimitOffsetDataSource`, which cannot load because the app has no `androidx.paging`. `Driver.query` carries the + `CHECKCAST` prologue and the branch, with a computed frame at the branch target. The control, the same build + without the request for computed frames, fails the JVM's verifier (`Expecting a stackmap frame at branch + target`), so the check does see stale frames. Excluded: `io.requery.**`. The helper's package is renamed only (a redirect would call itself). `androidx.sqlite.db.framework.**` and `androidx.core.database.**` are rewritten but exempt from the fail rule: see From 61104a772731b85797c103f7ab8ffb7f0313bac8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 19:09:05 -0800 Subject: [PATCH 103/203] ADFA-7138 Warn about strings that name a class the rewrite moves to requery Strings are not rewritten, so Class.forName("android.database.sqlite.SQLiteDatabase") or reflection on such a name reaches Android's class while the rewritten code uses requery's. Under the full policy, a string constant naming one of the renamed classes (dots or slashes, '$' or '.' before a nested class) now logs a warning with class, method and line. Not a failure: the string may only be printed. Names of kept classes, such as SQLiteException or SQLiteDatabaseLockedException, are not reported. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 4 ++- .../gradle/sqlite/SqliteRewriteRules.kt | 14 ++++++++++ .../gradle/sqlite/SqliteRewriter.kt | 10 ++++++- .../gradle/sqlite/SqliteRewriterTest.kt | 27 +++++++++++++++++++ 4 files changed, 53 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 084754990d..c248a82194 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -187,7 +187,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A either (`GradleQuickBuildProvisioner.sqliteDebuggerRefusal`): it shows `quick_build_disabled_sqlite_debugger`, which says Quick Build is off while the SQLite debugger is on. - Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not - rewritten. + rewritten. A string constant that names one of the renamed classes (dots or slashes, `$` or `.` before a nested + class) logs a warning with class, method and line, in the classes the fail rule covers; names of kept classes such + as `SQLiteException` do not. - The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a cursor that reached the method through a field, a parameter or another call is not seen (the app throws `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index b238f290b9..f7cd025855 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -73,6 +73,20 @@ internal object SqliteRewriteRules { /** The Android classes that get renamed. */ val SQLITE_CLASSES: Set = RENAMES.keys.filter { it.startsWith(SQLITE_PKG) }.toSet() + /** + * A renamed class in a string, as Class.forName or reflection spells it: dots or slashes, `$` or `.` before a + * nested class. Longest names first, and not followed by more of a name, so a kept class such as + * SQLiteDatabaseLockedException does not match SQLiteDatabase. + */ + val RENAMED_CLASS_NAME: Regex = + Regex( + RENAMES.keys + .sortedByDescending { it.length } + .joinToString("|", prefix = "(?:", postfix = ")(?![A-Za-z0-9_])") { + it.replace("$", "[.$]").replace("/", "[./]") + }, + ) + /** Renamed superclasses of the renamed classes, from the Wave 0 supertypes.tsv. */ val RENAMED_SUPERS: Map> = mapOf( diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 96628ae14b..ef801f9b19 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -330,13 +330,21 @@ object SqliteRewriter { "SQL text uses COLLATE UNICODE, which does not exist in requery's SQLite (no ICU); the statement would fail", ) } + val where = if (line >= 0) "line $line" else "no line number" if (Rules.COLLATE_LOCALIZED.containsMatchIn(text)) { - val where = if (line >= 0) "line $line" else "no line number" warn( "${cn.name.replace('/', '.')}.${m.name} ($where): COLLATE LOCALIZED works in requery's SQLite but sorts by " + "byte value (no ICU), not by the device locale", ) } + // A warning, not a failure: the string may only be printed. Strings are not rewritten, so a class loaded by + // this name is Android's, which the rewritten code cannot mix with requery's. + Rules.RENAMED_CLASS_NAME.find(text)?.let { + warn( + "${cn.name.replace('/', '.')}.${m.name} ($where): the string \"${it.value}\" names a class the rewrite moves " + + "to requery. Strings are not rewritten: Class.forName or reflection on it reaches Android's class, not requery's", + ) + } } fun invokeDynamic( diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 70e7e6e7b2..809cc62335 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1150,6 +1150,33 @@ class SqliteRewriterTest { assertThat(warnings.single()).contains("byte") } + @Test + fun `a string naming a renamed class only warns, and one naming a kept class does not`() { + val classes = + Compiler.compile( + listOf( + src( + "p.ByName", + """ + package p; + public class ByName { + Class db() throws Exception { return Class.forName("android.database.sqlite.SQLiteDatabase"); } + String factory() { return "android/database/sqlite/SQLiteDatabase${'$'}CursorFactory"; } + String kept() { return "android.database.sqlite.SQLiteException android.database.sqlite.SQLiteDatabaseLockedException"; } + } + """.trimIndent(), + ), + ), + ) + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/ByName"]!!, warn = { warnings += it }) + assertThat(warnings).hasSize(2) + assertThat(warnings[0]).contains("p.ByName.db (line ") + assertThat(warnings[0]).contains("\"android.database.sqlite.SQLiteDatabase\"") + assertThat(warnings[1]).contains("p.ByName.factory (line ") + assertThat(warnings[1]).contains("\"android/database/sqlite/SQLiteDatabase\$CursorFactory\"") + } + @Test fun `calls on android's CursorWindow are not reported even when the hierarchy says it extends SQLiteClosable`() { val classes = From 9ca47ff481277ecd62387549ab5b7e6d41cc0c31 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 19:56:39 -0800 Subject: [PATCH 104/203] ADFA-7138 Run the release-APK guard without the Maven signing key The first CI run of the guard failed before the test: the functional tests stage :logger, :logsender and :build-info into build-local Maven repositories, and with debug.yml's ORG_GRADLE_PROJECT_signingInMemoryKey in the environment MavenPublishConf runs the Sign tasks, which failed ("Could not evaluate spec for 'Signing is required, or signatory is set'"). Staging needs no signing, so the step drops the three signing variables, as on a developer machine. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .github/workflows/debug.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/debug.yml b/.github/workflows/debug.yml index 9800a82276..6ef3e75efc 100644 --- a/.github/workflows/debug.yml +++ b/.github/workflows/debug.yml @@ -229,7 +229,12 @@ jobs: - name: Check that an opted-in app's release APK carries no SQLite debugger run: | command -v unzip || { sudo apt-get update && sudo apt-get install -y unzip; } - flox activate -d flox/base -- ./gradlew :gradle-plugin:sqliteReleaseApkTest --no-daemon + # The test stages :logger, :logsender and :build-info into build-local Maven repositories, which + # needs no signing. With the job's signing key present MavenPublishConf runs the Sign tasks, and + # they fail, so the key is left out of this step. + env -u ORG_GRADLE_PROJECT_signingInMemoryKey -u ORG_GRADLE_PROJECT_signingInMemoryKeyId \ + -u ORG_GRADLE_PROJECT_signingInMemoryKeyPassword \ + flox activate -d flox/base -- ./gradlew :gradle-plugin:sqliteReleaseApkTest --no-daemon - name: Install advancecomp (advzip, used by recompressApk) run: | From 22d390f28dfe81ac00db0d781b09526d19fe9d03 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 22:03:32 -0800 Subject: [PATCH 105/203] ADFA-7138 Do not warn about a string that only contains a renamed class name RENAMED_CLASS_NAME had no leading boundary and is matched with find, so under the full policy a string such as "xandroid.database.sqlite.SQLiteDatabase" or "com.android.database.sqlite.SQLiteDatabase" warned that it names a class the rewrite moves to requery. Only a warning, never a failed build. The name now may not follow a letter, digit, '_', '.' or '$'. The one prefix still allowed is the 'L' of a type descriptor, itself not following a name character: a plain lookbehind would have stopped the warning on "[Landroid.database.sqlite.SQLiteDatabase;" (the name Class.forName takes for an array) and "(Landroid/database/sqlite/SQLiteDatabase;)V" (a descriptor MethodType.fromMethodDescriptorString resolves), which reach Android's class as the plain name does. A test pins both forms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 5 +- .../gradle/sqlite/SqliteRewriteRules.kt | 12 +++-- .../gradle/sqlite/SqliteRewriterTest.kt | 47 +++++++++++++++++++ 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index c248a82194..2667295640 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -188,8 +188,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A says Quick Build is off while the SQLite debugger is on. - Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not rewritten. A string constant that names one of the renamed classes (dots or slashes, `$` or `.` before a nested - class) logs a warning with class, method and line, in the classes the fail rule covers; names of kept classes such - as `SQLiteException` do not. + class, alone or in a type descriptor) logs a warning with class, method and line, in the classes the fail rule + covers; names of kept classes such as `SQLiteException`, and longer names that contain a renamed one, such as + `xandroid.database.sqlite.SQLiteDatabase`, do not. - The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a cursor that reached the method through a field, a parameter or another call is not seen (the app throws `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index f7cd025855..9d3f47775c 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -75,14 +75,20 @@ internal object SqliteRewriteRules { /** * A renamed class in a string, as Class.forName or reflection spells it: dots or slashes, `$` or `.` before a - * nested class. Longest names first, and not followed by more of a name, so a kept class such as - * SQLiteDatabaseLockedException does not match SQLiteDatabase. + * nested class. Longest names first, and neither preceded nor followed by more of a name, so a kept class such as + * SQLiteDatabaseLockedException does not match SQLiteDatabase, nor does a longer name such as + * xandroid.database.sqlite.SQLiteDatabase. The `L` of a type descriptor may precede it, as in + * `[Landroid.database.sqlite.SQLiteDatabase;`, the name Class.forName takes for an array of it. */ val RENAMED_CLASS_NAME: Regex = Regex( RENAMES.keys .sortedByDescending { it.length } - .joinToString("|", prefix = "(?:", postfix = ")(?![A-Za-z0-9_])") { + .joinToString( + "|", + prefix = "(?:(?() + SqliteRewriter.rewrite(classes["p/Longer"]!!, warn = { warnings += it }) + assertThat(warnings).hasSize(1) + assertThat(warnings.single()).contains("p.Longer.named (line ") + } + + @Test + fun `a type descriptor or array class name naming a renamed class still warns`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Descriptors", + """ + package p; + public class Descriptors { + String array() { return "[Landroid.database.sqlite.SQLiteDatabase;"; } + String method() { return "(Landroid/database/sqlite/SQLiteDatabase;)V"; } + } + """.trimIndent(), + ), + ), + ) + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/Descriptors"]!!, warn = { warnings += it }) + assertThat(warnings).hasSize(2) + assertThat(warnings[0]).contains("p.Descriptors.array (line ") + assertThat(warnings[1]).contains("p.Descriptors.method (line ") + } + @Test fun `calls on android's CursorWindow are not reported even when the hierarchy says it extends SQLiteClosable`() { val classes = From 6fd1fdcf97a1b161ffc9249a292f2bff3c91aa94 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 22:03:32 -0800 Subject: [PATCH 106/203] ADFA-7138 Docs: say SqliteReleaseApkTest skips without its AAR paths unless CI is set Run outside the sqliteReleaseApkTest task, as from an IDE, the test has no AAR paths and skips with a message (requireEnvironment); with the environment variable CI set it fails instead. The KDoc now says so. Test KDoc only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt index e290ea18b1..b85f62305b 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt @@ -22,7 +22,8 @@ import java.util.concurrent.TimeUnit * AAR brings. R8 renames and drops classes in a release, so the dex grep of the script can miss them; the * manifest provider and libsqlitedbg.so are what the control requires to fail. * - * Run by the sqliteReleaseApkTest task, which builds the AARs and passes their paths. + * Run by the sqliteReleaseApkTest task, which builds the AARs and passes their paths. Run without an AAR's path, as + * from an IDE, it skips with a message, and fails instead when the environment variable CI is set (requireEnvironment). */ class SqliteReleaseApkTest { private fun aar(name: String): File { From 9fedd913d3df0635ae233478e86e5ae7787cb124 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 22:38:47 -0800 Subject: [PATCH 107/203] ADFA-7138 Fail the build for a SQLiteQueryBuilder override of query with a signal The rewrite gives calls to SQLiteQueryBuilder.query(..., CancellationSignal) requery's descriptor, which ends in androidx.core's signal, but left a subclass's override of that overload with Android's. The calls then resolved to requery's inherited method and skipped the override. Such an override now fails the build, naming the class and method. Retyping the declaration was the alternative: its body is written against Android's signal, so the rewrite would have to turn requery's signal back into Android's on entry and keep the two connected, and patch the frames. The signal-less overloads keep their descriptors in requery and still override as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 4 ++- .../gradle/sqlite/SqliteRewriter.kt | 15 ++++++++ .../gradle/sqlite/SqliteRewriterTest.kt | 35 +++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 2667295640..49aab18cdc 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -81,7 +81,9 @@ cannot load, so the transform runs only on projects that opted in. Commenting th A `Context.openOrCreateDatabase` / `deleteDatabase` call that cannot be redirected also fails the build: `super.` calls (INVOKESPECIAL), calls whose owner class cannot be resolved (it might be a Context), and a method with one of those signatures that overrides it in a Context subclass (the redirect would skip - the override). + the override). So does an override of `SQLiteQueryBuilder.query` with a `CancellationSignal` in a subclass: its + calls get requery's descriptor while the override keeps Android's, so they would reach requery's method and skip + it. Retyping the override would mean turning requery's signal back into Android's inside its body. - Method references: a handle in an invokedynamic (`db::rawQuery`, `ctx::deleteDatabase`) that any rule above would change, redirect or reject fails the build, naming class, method and line, with the advice to write a lambda (its body is an ordinary call, which the rules handle). The rules are not applied to the diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index ef801f9b19..044529031b 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -155,6 +155,7 @@ object SqliteRewriter { violations += "method '${m.name}${m.desc}' overrides Context.${m.name}; calls to it are redirected to requery's " + "runtime and would skip the override" } + if (policy.fail) bypassedOverride(m)?.let { violations += it } if (policy.redirect && m.name == Rules.DRIVER_QUERY_NAME && m.desc == Rules.DRIVER_QUERY_DESC) { retypeParameters(m, Rules.DRIVER_QUERY_NEW_DESC) } @@ -242,6 +243,20 @@ object SqliteRewriter { } } + /** + * A method that overrides one whose calls [decide] retypes, SQLiteQueryBuilder's `query` with a + * CancellationSignal: the calls get requery's descriptor and the declaration keeps Android's, so they would + * reach requery's inherited method and skip the override. Retyping the declaration too would mean turning + * requery's signal back into Android's in a body written for Android's, so the build fails instead. + */ + fun bypassedOverride(m: MethodNode): String? { + if (m.access and (Opcodes.ACC_STATIC or Opcodes.ACC_PRIVATE) != 0 || m.name !in Rules.DESCRIPTOR_RULE_NAMES) return null + val ancestors = cn.superName?.let { renamedAncestors(it) }.orEmpty() + val rule = Rules.DESCRIPTOR_RULES.firstOrNull { it.owner in ancestors && it.name == m.name && it.desc == m.desc } ?: return null + return "method '${m.name}${m.desc}' overrides ${simple(rule.owner)}.${m.name}, whose calls the rewrite gives requery's " + + "descriptor; they would reach requery's method and skip the override" + } + fun checkDeclarations() { for (f in cn.fields) { if (f.desc.contains(Rules.OPEN_PARAMS)) violations += "field '${f.name}' has type OpenParams, which requery lacks" diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 168c8f3283..e760dce5f7 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1394,4 +1394,39 @@ class SqliteRewriterTest { assertThat(e.message).contains(name) } } + + @Test + fun `a query builder subclass that overrides the query taking a CancellationSignal fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.MyBuilder", + """ + package p; + import android.database.Cursor; + import android.database.sqlite.*; + import android.os.CancellationSignal; + public class MyBuilder extends SQLiteQueryBuilder { + @Override + public Cursor query(SQLiteDatabase db, String[] p, String s, String[] a, String g, String h, String o, String l, + CancellationSignal c) { + return super.query(db, p, s, a, g, h, o, l, c); + } + @Override + public Cursor query(SQLiteDatabase db, String[] p, String s, String[] a, String g, String h, String o) { + return null; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/MyBuilder"]!!, hierarchy) } + val overrides = e.message!!.lines().filter { "overrides SQLiteQueryBuilder.query" in it } + // the overload without a signal keeps its descriptor in requery, so overriding it still works + assertThat(overrides).hasSize(1) + assertThat(overrides.single()).contains("Landroid/os/CancellationSignal;)Landroid/database/Cursor;'") + assertThat(e.message).contains("p.MyBuilder") + } } From 7e38a3f9d78b9fe13ccacafe9f510c6186026e8a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 22:51:28 -0800 Subject: [PATCH 108/203] ADFA-7138 Fail a call a rule could match when its owner cannot be resolved renamedAncestors turned a hierarchy lookup that found nothing (AGP's class loader cannot load the owner) into "no renamed ancestors", silently. A call such as isStrict() on an unresolved subclass of SQLiteQueryBuilder then passed the transform and would fail only at run time. Under the full policy, such a call now fails the build when its name and descriptor are those of a member a rule changes or rejects in a renamed class another class can extend: the members requery lacks and the retyped query. That is the policy the rewrite already has for a Context database method on an unresolved owner. Members of the final SQLiteDatabase, SQLiteQuery and SQLiteStatement and constructors are left out, since no other class inherits them, so a call such as rawQuery or delete(String) on an unresolved class does not fail. Field handles and method references go through the same check. The supertype cache now keeps null results too: getOrPut asked the hierarchy again for every call on an unresolved owner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 4 ++ .../gradle/sqlite/SqliteRewriteRules.kt | 21 +++++++ .../gradle/sqlite/SqliteRewriter.kt | 31 ++++++++- .../gradle/sqlite/SqliteRewriterTest.kt | 63 ++++++++++++++++--- 4 files changed, 110 insertions(+), 9 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 49aab18cdc..8ab6558de8 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -84,6 +84,10 @@ cannot load, so the transform runs only on projects that opted in. Commenting th the override). So does an override of `SQLiteQueryBuilder.query` with a `CancellationSignal` in a subclass: its calls get requery's descriptor while the override keeps Android's, so they would reach requery's method and skip it. Retyping the override would mean turning requery's signal back into Android's inside its body. + Likewise a call on an owner that AGP's class loader cannot resolve fails when its name and descriptor are those of + a member a rule above changes or rejects in a renamed class another class can extend (not the final + `SQLiteDatabase`, `SQLiteQuery` or `SQLiteStatement`): the owner may inherit that member, and its renamed + ancestors are unknown. - Method references: a handle in an invokedynamic (`db::rawQuery`, `ctx::deleteDatabase`) that any rule above would change, redirect or reject fails the build, naming class, method and line, with the advice to write a lambda (its body is an ordinary call, which the rules handle). The rules are not applied to the diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index 9d3f47775c..e378bd03f5 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -241,6 +241,27 @@ internal object SqliteRewriteRules { /** Names of the calls whose descriptor changes. */ val DESCRIPTOR_RULE_NAMES: Set = DESCRIPTOR_RULES.map { it.name }.toSet() + /** The renamed classes android.jar declares final: no other class extends them. */ + private val FINAL_CLASSES: Set = setOf(DATABASE, "${SQLITE_PKG}SQLiteQuery", "${SQLITE_PKG}SQLiteStatement") + + /** + * Name plus descriptor of each member that a rule changes or rejects and that another class can inherit (not a + * constructor, nor a member of a final class), mapped to the renamed class that declares it. A class the build + * cannot resolve may inherit one of these, so a call that matches one exactly cannot be checked. + */ + val INHERITABLE_RULE_MEMBERS: Map = + buildMap { + for ((key, descs) in MISSING_MEMBERS) { + val owner = key.substringBeforeLast('.') + val name = key.substringAfterLast('.') + if (owner in FINAL_CLASSES || name == "") continue + for (desc in descs) putIfAbsent(name + desc, owner) + } + for (rule in DESCRIPTOR_RULES) { + if (rule.owner !in FINAL_CLASSES) putIfAbsent(rule.name + rule.desc, rule.owner) + } + } + /** SQLiteCursorDriver.query, matched on any owner: an app class may implement the interface. */ const val DRIVER_QUERY_NAME = "query" const val DRIVER_QUERY_DESC = "($CF[Ljava/lang/String;)Landroid/database/Cursor;" diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 044529031b..1a578bb487 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -271,14 +271,19 @@ object SqliteRewriter { private val ancestorsCache = HashMap>() private val superTypesCache = HashMap?>() - private fun superTypes(owner: String): Collection? = superTypesCache.getOrPut(owner) { hierarchy.superTypes(owner) } + // not getOrPut, which asks again for an owner that cannot be resolved (null) + private fun superTypes(owner: String): Collection? = + if (owner in superTypesCache) superTypesCache[owner] else hierarchy.superTypes(owner).also { superTypesCache[owner] = it } /** Owners that cannot extend a renamed class: the JDK, Kotlin, and Android outside the renamed set. */ private fun cannotBeSqlite(owner: String): Boolean = owner.startsWith("java/") || owner.startsWith("javax/") || owner.startsWith("kotlin/") || owner.startsWith("kotlinx/") || (owner.startsWith("android/") && owner !in Rules.SQLITE_CLASSES) - /** The renamed classes that [owner] is or extends, nearest first, so the rule tables see them all. */ + /** + * The renamed classes that [owner] is or extends, nearest first, so the rule tables see them all. None for an + * owner that cannot be resolved: [unresolvedOwner] reports the calls a rule could match on one. + */ fun renamedAncestors(owner: String): List { if (owner.startsWith("[")) return emptyList() return ancestorsCache.getOrPut(owner) { @@ -408,6 +413,27 @@ object SqliteRewriter { return renamedAncestors(owner) .firstOrNull { Rules.MISSING_MEMBERS["$it.$name"]?.contains(desc) == true } ?.let { "${simple(it)}.$name does not exist in requery" } + ?: unresolvedOwner(owner, name, desc) + } + + /** + * Why `owner.name desc` cannot be checked, or null: [owner] cannot be resolved, so its renamed ancestors are + * unknown, and the member has the name and descriptor of one a rule changes or rejects in a renamed class + * another class can extend. Like a Context database method on an unresolved owner, this fails under the + * full policy rather than pass a call that may break at run time. + */ + fun unresolvedOwner( + owner: String, + name: String, + desc: String, + ): String? { + val declaring = Rules.INHERITABLE_RULE_MEMBERS[name + desc] ?: return null + if (owner.startsWith("[") || owner in Rules.SQLITE_CLASSES || cannotBeSqlite(owner) || RewritePolicy.isExcluded(owner)) { + return null + } + if (superTypes(owner) != null) return null + return "${owner.replace('/', '.')} cannot be resolved, so the rewrite cannot tell whether its $name$desc is " + + "${simple(declaring)}.$name, which it changes or rejects" } fun typeInsn( @@ -503,6 +529,7 @@ object SqliteRewriter { "the platform method would not link", ) } + unresolvedOwner(owner, name, desc)?.let { return Action.Fail(it) } return Action.None } for (c in ancestors) { diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index e760dce5f7..6ab23eea42 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -535,13 +535,17 @@ class SqliteRewriterTest { ), ) val asked = mutableListOf() - SqliteRewriter.rewrite( - classes["p/Named"]!!, - ClassHierarchy { name -> - asked += name - null - }, - ) + try { + SqliteRewriter.rewrite( + classes["p/Named"]!!, + ClassHierarchy { name -> + asked += name + null + }, + ) + } catch (e: SqliteRewriteException) { + // getUniqueId on an owner that cannot be resolved is reported, which is not what this test is about + } assertThat(asked).containsExactly("p/Mine", "p/Other") } @@ -1429,4 +1433,49 @@ class SqliteRewriterTest { assertThat(overrides.single()).contains("Landroid/os/CancellationSignal;)Landroid/database/Cursor;'") assertThat(e.message).contains("p.MyBuilder") } + + @Test + fun `a call a rule could match on an owner the hierarchy cannot resolve fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.UsesLost", + """ + package p; + import android.database.sqlite.*; + public class UsesLost { + void go(Lost l, SQLiteDatabase db, String[] a, android.os.CancellationSignal s) { + l.isStrict(); + l.query(db, a, "w", a, null, null, null, "1", s); + l.rawQuery("x", a); + l.delete("x"); + } + } + """, + ), + // left out of the hierarchy, as a class missing from the runtime classpath is + src( + "p.Lost", + """ + package p; + public class Lost extends android.database.sqlite.SQLiteQueryBuilder { + public android.database.Cursor rawQuery(String s, String[] a) { return null; } + public int delete(String s) { return 0; } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/UsesLost"]!!, hierarchy) } + val unresolved = + e.message!! + .lines() + .filter { "p.Lost cannot be resolved" in it } + .map { it.substringAfter("whether its ").substringBefore(" is ") } + // SQLiteDatabase is final, so no class inherits its rawQuery, and no rule has a delete(String) + assertThat(unresolved).hasSize(2) + assertThat(unresolved[0]).isEqualTo("isStrict()Z") + assertThat(unresolved[1]).startsWith("query(Landroid/database/sqlite/SQLiteDatabase;") + } } From 3bdeb36f78add77cfeaa69aca0bf68d3b4a6007d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:10:00 -0800 Subject: [PATCH 109/203] ADFA-7138 Fail the build for an SQLite cursor used as an Android cursor class The cast rule caught `(AbstractCursor) c` only where javac writes a CHECKCAST. An upcast has none: `AbstractCursor up(SQLiteCursor c) { return c; }` returns the value as is. After the rename the parameter is requery's SQLiteCursor, which does not extend Android's AbstractCursor, so the class no longer verified. A second analysis now follows values whose static type is SQLiteCursor, or a class that extends it, and fails the build where one is used as AbstractWindowedCursor, AbstractCursor or CrossProcessCursor without a cast: returned, passed, called on, stored in a field, or held in a local or stack slot that a frame declares as one of them. The frames come from a new non-mutating fullFrames, which expandFrames now uses too. Conversions to android.database.Cursor and Object stay allowed. Values that pass through arrays are not followed; storing one into such an array throws ArrayStoreException at run time. The test also shows the failure mode: the same class, rewritten in a package the fail rule exempts, fails ASM's CheckClassAdapter and the JVM verifier. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 + .../gradle/sqlite/SqliteRewriter.kt | 155 +++++++++++++++++- .../gradle/sqlite/SqliteRewriterTest.kt | 49 ++++++ 3 files changed, 204 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 8ab6558de8..623cb8a881 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -70,6 +70,9 @@ cannot load, so the transform runs only on projects that opted in. Commenting th `CursorWindow` itself are fine), and a cast of an SQLite cursor to `android.database.AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` (requery's cursors extend its own copies of the first two, and implement only `android.database.Cursor`). + The same conversion without a cast fails too: a value declared `SQLiteCursor`, or a subclass, returned, passed, + called on, stored in a field, or held in a local as one of those three types (`AbstractCursor up(SQLiteCursor c) + { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported. `COLLATE LOCALIZED` only logs a warning: it works, but compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together, with diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 1a578bb487..9d93aae8a0 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -136,6 +136,18 @@ object SqliteRewriter { override fun hashCode(): Int = super.hashCode() * 31 + if (sqliteCursor) 1 else 0 } + /** A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's. */ + private class StaticCursorValue( + type: Type?, + val renamedCursor: Boolean, + ) : BasicValue(type) { + // as TaintValue: Frame.merge keeps the old value when the merged one equals it + override fun equals(other: Any?): Boolean = + other is BasicValue && super.equals(other) && renamedCursor == ((other as? StaticCursorValue)?.renamedCursor ?: false) + + override fun hashCode(): Int = super.hashCode() * 31 + if (renamedCursor) 1 else 0 + } + private class ClassRewrite( val cn: ClassNode, val policy: RewritePolicy, @@ -204,6 +216,26 @@ object SqliteRewriter { m: MethodNode, originalDesc: String, ) { + for (full in fullFrames(m, originalDesc)) { + full.node.type = Opcodes.F_NEW + full.node.local = ArrayList(full.locals) + full.node.stack = ArrayList(full.stack) + } + } + + /** A frame of a method with its locals and stack in full, as a compressed frame leaves them implied. */ + class FullFrame( + val node: FrameNode, + val locals: List, + val stack: List, + ) + + /** Every frame of [m] in full, starting from [originalDesc]'s parameters; changes nothing. */ + fun fullFrames( + m: MethodNode, + originalDesc: String, + ): List { + val result = ArrayList() var locals = ArrayList() if (m.access and Opcodes.ACC_STATIC == 0) locals += cn.name for (t in Type.getArgumentTypes(originalDesc)) { @@ -237,10 +269,9 @@ object SqliteRewriter { stack = ArrayList(frame.stack) } } - frame.type = Opcodes.F_NEW - frame.local = ArrayList(locals) - frame.stack = ArrayList(stack) + result += FullFrame(frame, ArrayList(locals), stack) } + return result } /** @@ -301,6 +332,7 @@ object SqliteRewriter { fun rewriteMethod(m: MethodNode) { val tainted = if (policy.fail) cursorCastTaint(m) else emptySet() + val conversions = if (policy.fail) implicitCursorConversions(m) else emptyMap() var line = -1 var insn: AbstractInsnNode? = m.instructions.first while (insn != null) { @@ -308,6 +340,7 @@ object SqliteRewriter { if (insn is LineNumberNode) { line = insn.line } + conversions[insn]?.let { violate(m, line, it) } when (insn) { is MethodInsnNode -> { methodInsn(m, insn, line) @@ -721,6 +754,122 @@ object SqliteRewriter { fun simple(name: String) = name.substringAfterLast('/') + /** SQLiteCursor, or a class that extends it, which the rename makes a subclass of requery's SQLiteCursor. */ + fun isRenamedCursorType(type: Type?): Boolean = + type != null && type.sort == Type.OBJECT && type.descriptor != "Lnull;" && + Rules.SQLITE_CURSOR in renamedAncestors(type.internalName) + + /** [type]'s internal name when it is one of the Android-only cursor types, or null. */ + private fun androidOnlyCursor(type: Type): String? = if (type.sort == Type.OBJECT) androidOnlyCursor(type.internalName) else null + + /** A type in a frame or an internal name, when it is one of the Android-only cursor types, or null. */ + private fun androidOnlyCursor(entry: Any?): String? = (entry as? String)?.takeIf { it in Rules.ANDROID_ONLY_CURSOR_TYPES } + + /** Whether [m] names an Android-only cursor type where a value could be converted to it without a cast. */ + private fun mayConvertToAndroidCursor(m: MethodNode): Boolean { + fun names(desc: String) = Rules.ANDROID_ONLY_CURSOR_TYPES.any { desc.contains("L$it;") } + if (names(Type.getReturnType(m.desc).descriptor)) return true + return m.instructions.any { insn -> + when (insn) { + is MethodInsnNode -> insn.owner in Rules.ANDROID_ONLY_CURSOR_TYPES || names(insn.desc) + is InvokeDynamicInsnNode -> names(insn.desc) + is FieldInsnNode -> names(insn.desc) + is FrameNode -> (insn.local.orEmpty() + insn.stack.orEmpty()).any { androidOnlyCursor(it) != null } + else -> false + } + } + } + + /** + * The instructions where a value whose static type is SQLiteCursor, or a class that extends it, is used as an + * AbstractWindowedCursor, AbstractCursor or CrossProcessCursor without a cast, by the message for each: returned, + * passed, called on, stored in a field, or held where a frame declares one of them. javac writes no CHECKCAST + * for such an upcast, and requery's SQLiteCursor neither extends those classes nor implements the interface, so + * the renamed class would not verify (or, for the interface, the call would fail). Values stored in or loaded + * from arrays are not followed; storing one into such an array throws ArrayStoreException. + */ + fun implicitCursorConversions(m: MethodNode): Map { + if (!mayConvertToAndroidCursor(m)) return emptyMap() + val interpreter = + object : BasicInterpreter(Opcodes.ASM9) { + override fun newValue(type: Type?): BasicValue? { + val v = super.newValue(type) ?: return null + return if (v.isReference) StaticCursorValue(v.type, isRenamedCursorType(type)) else v + } + + override fun merge( + value1: BasicValue, + value2: BasicValue, + ): BasicValue { + val renamed = + (value1 as? StaticCursorValue)?.renamedCursor == true || (value2 as? StaticCursorValue)?.renamedCursor == true + if (renamed && value1.type != null && value1.type == value2.type) return StaticCursorValue(value1.type, true) + return super.merge(value1, value2) + } + } + val frames: Array?> = + try { + Analyzer(interpreter).analyze(cn.name, m) + } catch (e: AnalyzerException) { + return emptyMap() + } + val declared = fullFrames(m, m.desc).associateBy { it.node } + val returnType = Type.getReturnType(m.desc) + val result = LinkedHashMap() + for ((i, insn) in m.instructions.withIndex()) { + val f = frames[i] ?: continue + + fun renamed(value: BasicValue?) = (value as? StaticCursorValue)?.renamedCursor == true + + fun fromTop(depth: Int) = if (depth < f.stackSize) f.getStack(f.stackSize - 1 - depth) else null + val target: String? = + when { + insn is MethodInsnNode || insn is InvokeDynamicInsnNode -> { + val args = Type.getArgumentTypes((insn as? MethodInsnNode)?.desc ?: (insn as InvokeDynamicInsnNode).desc) + args.indices.firstNotNullOfOrNull { k -> + androidOnlyCursor(args[k])?.takeIf { renamed(fromTop(args.size - 1 - k)) } + } + ?: (insn as? MethodInsnNode) + ?.takeIf { + it.opcode != Opcodes.INVOKESTATIC && it.owner in Rules.ANDROID_ONLY_CURSOR_TYPES && + renamed(fromTop(args.size)) + }?.owner + } + + insn is FieldInsnNode && (insn.opcode == Opcodes.PUTFIELD || insn.opcode == Opcodes.PUTSTATIC) -> { + androidOnlyCursor(Type.getType(insn.desc))?.takeIf { renamed(fromTop(0)) } + } + + insn.opcode == Opcodes.ARETURN -> { + androidOnlyCursor(returnType)?.takeIf { renamed(fromTop(0)) } + } + + insn is FrameNode -> { + declared[insn]?.let { full -> + var slot = 0 + var hit: String? = null + for (t in full.locals) { + if (hit == null && slot < f.locals && renamed(f.getLocal(slot))) hit = androidOnlyCursor(t) + slot += if (t == Opcodes.LONG || t == Opcodes.DOUBLE) 2 else 1 + } + hit ?: full.stack.indices.firstNotNullOfOrNull { k -> + androidOnlyCursor(full.stack[k])?.takeIf { k < f.stackSize && renamed(f.getStack(k)) } + } + } + } + + else -> { + null + } + } + if (target != null) { + result[insn] = "an SQLite cursor used as ${target.replace('/', '.')} without a cast; requery's SQLiteCursor is not " + + "one, so the rewritten class would not verify or the call would fail" + } + } + return result + } + /** * The CHECKCASTs to AbstractWindowedCursor whose operand came from an SQLite API (a call on * one of the renamed classes returning a cursor, or a parameter or instance field declared as diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 6ab23eea42..f518d4787c 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1478,4 +1478,53 @@ class SqliteRewriterTest { assertThat(unresolved[0]).isEqualTo("isStrict()Z") assertThat(unresolved[1]).startsWith("query(Landroid/database/sqlite/SQLiteDatabase;") } + + @Test + fun `an SQLite cursor used as an Android cursor class without a cast fails the build, and would not verify`() { + fun up(pkg: String) = + src( + "$pkg.Up", + """ + package $pkg; + import android.database.*; + import android.database.sqlite.*; + public class Up { + AbstractCursor field; + AbstractCursor returned(SQLiteCursor c) { return c; } + void passed(SQLiteCursor c) { take(c); } + static void take(AbstractWindowedCursor w) {} + void stored(SQLiteCursor c) { field = c; } + int calledOn(SQLiteCursor c) { + AbstractCursor a = c; + return a.getCount(); + } + Object inFrame(SQLiteCursor c, boolean b) { + AbstractCursor a = c; + if (b) { + a = null; + } + return a; + } + Cursor fine(SQLiteCursor c, Cursor other) { + Cursor k = c; + Object o = c; + AbstractCursor a = (AbstractCursor) other; + return k; + } + } + """, + ) + val classes = Compiler.compile(listOf(up("p"))) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Up"]!!, hierarchy) } + for (name in listOf("returned", "passed", "stored", "calledOn", "inFrame")) { + assertThat(e.message).contains(" - $name(") + } + assertThat(e.message).contains("an SQLite cursor used as android.database.AbstractWindowedCursor without a cast") + assertThat(e.message).contains("an SQLite cursor used as android.database.AbstractCursor without a cast") + assertThat(e.message).doesNotContain("fine(") + // The failure mode: rewritten in a package the fail rule exempts, the same class does not verify + val unverified = assertThrows(IllegalStateException::class.java) { transform(up("androidx.sqlite.db.framework")) } + assertThat(unverified.message).contains("does not verify") + assertThat(unverified.message).contains("androidx/sqlite/db/framework/Up") + } } From 183a69f2a1811a951110db29f9ffa72e82468861 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:10:26 -0800 Subject: [PATCH 110/203] ADFA-7138 Check the SQLite debugger opt-in again after the model wait, always The second refusal check ran only when the model was missing at the first one (modulesKnown). A sync during the staging or the wait can replace a published model, and a module it adds can carry cogo.sqliteDebugger=true in its own gradle.properties. That project then reached Gradle and ended in "variant setup missing" instead of the refusal. The check after the wait now always runs, and modulesKnown is gone. It reads only small property files and returns early without an opt-in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 7 ++--- ...dleQuickBuildProvisionerFailureArmsTest.kt | 30 +++++++++++++++++++ .../GradleQuickBuildProvisionerFakes.kt | 21 +++++++++++++ 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 452fed5594..5e97d2d18c 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -365,7 +365,6 @@ class GradleQuickBuildProvisioner( // Build to an opted-in project, so building would only end in "variant setup missing". During // a sync the model has no app modules yet, so an opt-in in a module's own gradle.properties is // seen only by the second check, after the wait for the model. - val modulesKnown = projectManager.workspace != null sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } stage(context, paths) @@ -379,9 +378,9 @@ class GradleQuickBuildProvisioner( context.getString(R.string.quick_build_waiting_for_sync), ) } - if (!modulesKnown) { - sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } - } + // Again, whatever the first check saw: a sync during the staging or the wait can publish modules, and + // one of them can carry the opt-in in its own gradle.properties. + sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } val module = quickBuildModule(projectManager) diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt index d7b1655fcc..8b82af6c25 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt @@ -118,6 +118,36 @@ class GradleQuickBuildProvisionerFailureArmsTest { assertThat(gradle.executedTasks).isNull() } + @Test + fun `an opt-in in a module that a sync publishes during the staging is refused`() = + runTest { + val app = moduleDir() + val feature = File(projectRoot, "feature").apply { mkdirs() } + File(feature, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + val appModule = androidModule(buildDir = File(app, "build"), projectDir = app) + val featureModule = androidModule(path = ":feature", buildDir = File(feature, "build"), projectDir = feature) + val gradle = FakeBuildService() + val project = + ResyncingProjectManager( + FakeProjectManager(projectRoot, appModules = listOf(appModule)), + FakeProjectManager(projectRoot, appModules = listOf(appModule, featureModule)), + ) + + val outcome = + testProvisioner( + context = context, + projectRoot = projectRoot, + buildService = gradle, + projectManager = project, + // The model was already published, so the first check read the old modules; the module with the + // opt-in appears only after it. + stage = { _, _ -> project.resynced = true }, + ).provision() + + assertThat(failureText(outcome)).isEqualTo(context.getString(R.string.quick_build_disabled_sqlite_debugger)) + assertThat(gradle.executedTasks).isNull() + } + @Test fun `a slot that goes busy between the staging and the build still reads as a busy slot`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt index eb6e4c9022..1ce6bd7b00 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt @@ -150,6 +150,27 @@ internal class SyncingProjectManager( override fun getAndroidAppModules(): List = if (published) synced.getAndroidAppModules() else emptyList() } +/** + * A project whose model is published from the start, and replaced by a sync that runs while Quick Build stages: + * [before]'s modules until [resynced] is set, [synced]'s after. + */ +internal class ResyncingProjectManager( + private val before: FakeProjectManager, + private val synced: FakeProjectManager, +) : IProjectManager by synced { + var resynced = false + + private val current: FakeProjectManager + get() = if (resynced) synced else before + + override val workspace: Workspace? + get() = current.workspace + + override fun getAndroidModules(): List = current.getAndroidModules() + + override fun getAndroidAppModules(): List = current.getAndroidAppModules() +} + /** * An Android module as the Build Variants sidebar presents it. * From 1648b5a2670df4828bfade8fe189646894f6a719 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:10:41 -0800 Subject: [PATCH 111/203] ADFA-7138 Do not refuse Quick Build from the root opt-in before the modules are known The early refusal check ran before the wait for the model. During a sync it saw no app modules, so it read the Gradle user home and the root only, and a root cogo.sqliteDebugger=true refused at once, even when the app module sets false. The documented rule, that the first file that defines the line decides and a module's file comes before the root's, held only after the sync. The early check now runs only once the model is published. During a sync the check after the wait, which always runs, decides with the modules' files. The cost: a root opt-in tapped during a sync now pays for staging before it is refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 13 +++++---- ...dleQuickBuildProvisionerFailureArmsTest.kt | 29 +++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 5e97d2d18c..03aed21800 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -362,10 +362,13 @@ class GradleQuickBuildProvisioner( val projectRoot = File(projectManager.projectDirPath) // Before staging, which a refused build need not pay for: the Gradle plugin never applies Quick - // Build to an opted-in project, so building would only end in "variant setup missing". During - // a sync the model has no app modules yet, so an opt-in in a module's own gradle.properties is - // seen only by the second check, after the wait for the model. - sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } + // Build to an opted-in project, so building would only end in "variant setup missing". Only once + // the model has the app modules: during a sync this check would read the root's file without + // theirs, so a root opt-in would refuse a project whose module turns it off. The second check, + // after the wait for the model, decides then. + if (projectManager.workspace != null) { + sqliteDebuggerRefusal(projectManager, projectRoot)?.let { return it } + } stage(context, paths) // The project model only exists once CoGo's Gradle sync has populated it, and a tap @@ -555,7 +558,7 @@ class GradleQuickBuildProvisioner( /** * The refusal for a project with `cogo.sqliteDebugger=true`, or null. It reads the app modules' * own `gradle.properties` only for the modules [projectManager] knows, which is none before the - * sync publishes the model. + * sync publishes the model, so it decides only once the model is published. */ private fun sqliteDebuggerRefusal( projectManager: IProjectManager, diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt index 8b82af6c25..987a2f03c5 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt @@ -118,6 +118,35 @@ class GradleQuickBuildProvisionerFailureArmsTest { assertThat(gradle.executedTasks).isNull() } + @Test + fun `a root opt-in that the app module turns off is not refused when the tap comes during the sync`() = + runTest { + File(projectRoot, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + val moduleDir = moduleDir() + File(moduleDir, "gradle.properties").writeText("cogo.sqliteDebugger=false\n") + val gradle = FakeBuildService() + val project = + SyncingProjectManager( + FakeProjectManager( + projectRoot, + appModules = listOf(androidModule(buildDir = File(moduleDir, "build"), projectDir = moduleDir)), + ), + ) + + val outcome = + testProvisioner( + context = context, + projectRoot = projectRoot, + buildService = gradle, + projectManager = project, + stage = { _, _ -> project.published = true }, + ).provision() + + // The module's file comes before the root's, so its false decides, as in Gradle: the build runs. + assertThat(failureText(outcome)).isNotEqualTo(context.getString(R.string.quick_build_disabled_sqlite_debugger)) + assertThat(gradle.executedTasks).isNotNull() + } + @Test fun `an opt-in in a module that a sync publishes during the staging is refused`() = runTest { From 625924675cd61c12f9a55455a30ae8bb643bcbc7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:10:53 -0800 Subject: [PATCH 112/203] ADFA-7138 Replace the SQLite AARs in one rename when app init extracts them ToolsManager.init extracts sqlite-debugger.aar and sqlite-rewrite-runtime.aar on a background thread, and GradleBuildService passes their paths to a build without waiting. Each extractor deleted the AAR and then copied straight to its path, so a build of an opted-in project that started meanwhile could find the file missing ("not found", with the wrong advice to remove the opt-in) or read it half-written. Both now go through replaceAtomically: copy to a .part sibling, then rename over the final path, as the tooling jar already does. A build sees the previous complete AAR or the new one. This is smaller than making builds wait for extraction. The one window left is a fresh install's very first extraction: a build that early finds no file and says so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/managers/ToolsManager.java | 43 +++++++----- .../managers/ToolsManagerSqliteAarTest.kt | 66 +++++++++++++++++++ 2 files changed, 93 insertions(+), 16 deletions(-) create mode 100644 common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt diff --git a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java index b097f8e08c..12376129cb 100755 --- a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java +++ b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java @@ -210,6 +210,23 @@ static boolean isToolingJarCurrent(File toolingJarFile, File stampFile, String s return toolingJarFile.isFile() && stamp != null && stamp.equals(readStampFile(stampFile)); } + /** + * Copies the stream to a temp sibling of the target, then renames it over the target. {@link #init} extracts the SQLite AARs in the background, and GradleBuildService passes their paths to a build without waiting, so a build that starts meanwhile must find the previous complete file or the new one, never a missing or partly written one. rename(2) within one directory atomically replaces the target on Linux. Does not close the stream. + */ + @VisibleForTesting + static void replaceAtomically(InputStream source, File target) throws IOException { + final var dir = Objects.requireNonNull(target.getParentFile()); + dir.mkdirs(); + final var tempFile = new File(dir, target.getName() + ".part"); + try (final var fos = new FileOutputStream(tempFile)) { + IoUtilsKt.transferToStream(source, fos); + } + if (!tempFile.renameTo(target)) { + tempFile.delete(); + throw new IOException("Could not move " + tempFile + " to " + target); + } + } + private static void deleteIdeenv() { final var file = new File(Environment.BIN_DIR, "ideenv"); if (file.exists() && !file.delete()) { @@ -263,30 +280,24 @@ private static void extractLogSender(BaseApplication app) { Environment.LOGSENDER_AAR.getAbsolutePath()); } - @WorkerThread - private static void extractSqliteDebugger() { - if (Environment.SQLITE_DEBUGGER_AAR.exists()) { - FileUtils.delete(Environment.SQLITE_DEBUGGER_AAR); + private static void extractSqliteAar(String asset, File aar) { + try (InputStream source = BaseApplication.getBaseInstance().getAssets().open(asset)) { + replaceAtomically(source, aar); + } catch (IOException err) { + LOG.error("Failed to extract {} to {}", asset, aar, err); } + } - Environment.mkdirIfNotExists(Environment.SQLITE_DEBUGGER_DIR); - + @WorkerThread + private static void extractSqliteDebugger() { // One AAR with both ABIs, unlike logsender's per-flavor AARs - ResourceUtils.copyFileFromAssets(getCommonAsset("sqlite-debugger-release.aar"), - Environment.SQLITE_DEBUGGER_AAR.getAbsolutePath()); + extractSqliteAar(getCommonAsset("sqlite-debugger-release.aar"), Environment.SQLITE_DEBUGGER_AAR); } @WorkerThread private static void extractSqliteRewriteRuntime() { - if (Environment.SQLITE_REWRITE_RUNTIME_AAR.exists()) { - FileUtils.delete(Environment.SQLITE_REWRITE_RUNTIME_AAR); - } - - Environment.mkdirIfNotExists(Environment.SQLITE_REWRITE_RUNTIME_DIR); - // Java only, so one AAR for both ABIs - ResourceUtils.copyFileFromAssets(getCommonAsset("sqlite-rewrite-runtime-release.aar"), - Environment.SQLITE_REWRITE_RUNTIME_AAR.getAbsolutePath()); + extractSqliteAar(getCommonAsset("sqlite-rewrite-runtime-release.aar"), Environment.SQLITE_REWRITE_RUNTIME_AAR); } private static void generateKeystore() { diff --git a/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt b/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt new file mode 100644 index 0000000000..9c4a85d177 --- /dev/null +++ b/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt @@ -0,0 +1,66 @@ +package com.itsaky.androidide.managers + +import com.google.common.truth.Truth.assertThat +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.InputStream + +/** + * App init extracts the SQLite debugger and rewrite runtime AARs in the background, and a build gets their paths + * without waiting, so [ToolsManager.replaceAtomically] must never leave a missing or partly written AAR at the path. + */ +class ToolsManagerSqliteAarTest { + @get:Rule + val tempFolder = TemporaryFolder() + + /** Hands out one byte per read, and records what a build reading [target] would find before each one. */ + private class WatchingStream( + private val bytes: ByteArray, + private val target: File, + ) : InputStream() { + val seen = mutableListOf() + private var next = 0 + + override fun read(): Int { + seen += if (target.isFile) target.readText() else null + return if (next < bytes.size) bytes[next++].toInt() and 0xff else -1 + } + + override fun read( + b: ByteArray, + off: Int, + len: Int, + ): Int { + if (len == 0) return 0 + val c = read() + if (c < 0) return -1 + b[off] = c.toByte() + return 1 + } + } + + @Test + fun `a build that reads the AAR while it is replaced finds the previous complete file`() { + val aar = File(tempFolder.root, "sqlite-debugger/sqlite-debugger.aar") + aar.parentFile!!.mkdirs() + aar.writeText("previous-install-aar") + val source = WatchingStream("this-install-aar".toByteArray(), aar) + + ToolsManager.replaceAtomically(source, aar) + + assertThat(source.seen.toSet()).containsExactly("previous-install-aar") + assertThat(aar.readText()).isEqualTo("this-install-aar") + assertThat(File(aar.parentFile, "sqlite-debugger.aar.part").exists()).isFalse() + } + + @Test + fun `the first extraction creates the directory and the AAR`() { + val aar = File(tempFolder.root, "sqlite-rewrite-runtime/sqlite-rewrite-runtime.aar") + + ToolsManager.replaceAtomically("runtime-aar".byteInputStream(), aar) + + assertThat(aar.readText()).isEqualTo("runtime-aar") + } +} From 72e44e8f50f6d55178d665b0de6d0d89dbaa0acc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:58 -0800 Subject: [PATCH 113/203] ADFA-7138 Accept an instanceof guard only when it holds on every path to the cast The guard check was syntactic: an INSTANCEOF of the cast's type on the same local, followed by an IFEQ whose target lies past the cast, counted. In `if (b || c instanceof AbstractCursor) return (AbstractCursor) c;` that holds, yet b alone reaches the cast, which then throws on requery's cursor. The cast analysis now proves the guard itself. A Frame subclass sees `ALOAD n; INSTANCEOF X; IFEQ/IFNE` written back to back (no label, so no path joins in between) and, through Frame.initJumpTarget, gives local n's value the proof on the edge where the test succeeded only. The proof travels with the value through copies and casts, and a merge keeps it only when every path brings it. A store to the local replaces the value, so it drops the proof. The simple, &&, ?: and early-exit guards still pass, and a guard on a copy of the local now counts too. The syntactic check and its helpers are gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 +- .../gradle/sqlite/SqliteRewriter.kt | 161 ++++++++++-------- .../gradle/sqlite/SqliteRewriterTest.kt | 68 ++++++++ 3 files changed, 159 insertions(+), 73 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 623cb8a881..17d3f3cbfe 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -74,7 +74,8 @@ cannot load, so the transform runs only on projects that opted in. Commenting th called on, stored in a field, or held in a local as one of those three types (`AbstractCursor up(SQLiteCursor c) { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, - or an early return when it is false) is not reported. `COLLATE LOCALIZED` only logs a warning: it works, but + or an early return when it is false) is not reported when the guard holds on every path to the cast: in + `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together, with the way out for a library class, which the user cannot change: comment out `cogo.sqliteDebugger=true`. A platform method outside the renamed set whose descriptor mentions a renamed class (found with javap over android.jar: the other `DatabaseUtils` methods diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 9d93aae8a0..13d14f2668 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -18,7 +18,7 @@ import org.objectweb.asm.tree.FieldInsnNode import org.objectweb.asm.tree.FrameNode import org.objectweb.asm.tree.InsnList import org.objectweb.asm.tree.InvokeDynamicInsnNode -import org.objectweb.asm.tree.JumpInsnNode +import org.objectweb.asm.tree.LabelNode import org.objectweb.asm.tree.LdcInsnNode import org.objectweb.asm.tree.LineNumberNode import org.objectweb.asm.tree.MethodInsnNode @@ -30,6 +30,7 @@ import org.objectweb.asm.tree.analysis.AnalyzerException import org.objectweb.asm.tree.analysis.BasicInterpreter import org.objectweb.asm.tree.analysis.BasicValue import org.objectweb.asm.tree.analysis.Frame +import org.objectweb.asm.tree.analysis.Interpreter import com.itsaky.androidide.gradle.sqlite.SqliteRewriteRules as Rules /** Thrown with every unsupported reference of a class, so the build names them all at once. */ @@ -125,15 +126,64 @@ object SqliteRewriter { } } + /** [instanceOf]: the types an `instanceof` proved the value to be, on every path to here. */ private class TaintValue( type: Type?, val sqliteCursor: Boolean, + val instanceOf: Set = emptySet(), ) : BasicValue(type) { - // Frame.merge keeps the old value when the merged one equals it, so the taint must count + // Frame.merge keeps the old value when the merged one equals it, so the taint and the proofs must count override fun equals(other: Any?): Boolean = - other is BasicValue && super.equals(other) && sqliteCursor == ((other as? TaintValue)?.sqliteCursor ?: false) + other is BasicValue && super.equals(other) && sqliteCursor == ((other as? TaintValue)?.sqliteCursor ?: false) && + instanceOf == ((other as? TaintValue)?.instanceOf ?: emptySet()) - override fun hashCode(): Int = super.hashCode() * 31 + if (sqliteCursor) 1 else 0 + override fun hashCode(): Int = (super.hashCode() * 31 + if (sqliteCursor) 1 else 0) * 31 + instanceOf.hashCode() + + fun provedInstanceOf(type: String) = TaintValue(this.type, sqliteCursor, instanceOf + type) + } + + /** + * A frame that learns from `ALOAD n; INSTANCEOF X; IFEQ/IFNE`, written without anything between them (no label, so + * no other path joins there): on the edge where the test succeeded, local n's value is proved an X. The proof goes + * with the value through copies, and a merge keeps it only when every path brings it. + */ + private class GuardFrame : Frame { + constructor(numLocals: Int, maxStack: Int) : super(numLocals, maxStack) + constructor(frame: Frame) : super(frame) + + private var local = -1 + private var type: String? = null + private var provedOnJump = false + private var before: BasicValue? = null + + override fun execute( + insn: AbstractInsnNode, + interpreter: Interpreter, + ) { + local = -1 + before = null + val test = insn.previous as? TypeInsnNode + val load = test?.previous as? VarInsnNode + if ((insn.opcode == Opcodes.IFEQ || insn.opcode == Opcodes.IFNE) && test?.opcode == Opcodes.INSTANCEOF && + load?.opcode == Opcodes.ALOAD + ) { + local = load.`var` + type = test.desc + provedOnJump = insn.opcode == Opcodes.IFNE + } + super.execute(insn, interpreter) + } + + // Called on this frame once per edge of the jump, before it is merged there, in no order this relies on + override fun initJumpTarget( + opcode: Int, + target: LabelNode?, + ) { + if (local < 0) return + val value = before ?: getLocal(local).also { before = it } + val proved = (target != null) == provedOnJump + setLocal(local, if (proved && value is TaintValue) value.provedInstanceOf(type!!) else value) + } } /** A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's. */ @@ -478,9 +528,7 @@ object SqliteRewriter { if (t.desc.startsWith(Rules.OPEN_PARAMS)) { violate(m, line, "OpenParams, which requery lacks") } - if (t.opcode == Opcodes.CHECKCAST && t.desc in Rules.ANDROID_ONLY_CURSOR_TYPES && t in tainted && - !isGuardedByInstanceof(m, t) - ) { + if (t.opcode == Opcodes.CHECKCAST && t.desc in Rules.ANDROID_ONLY_CURSOR_TYPES && t in tainted) { violate( m, line, @@ -693,63 +741,6 @@ object SqliteRewriter { ) = owner in Rules.SQLITE_CLASSES || name in Rules.MISSING_MEMBER_NAMES || name in Rules.DESCRIPTOR_RULE_NAMES || desc.contains(Rules.CURSOR_WINDOW) - private fun previousReal(node: AbstractInsnNode): AbstractInsnNode? { - var n = node.previous - while (n != null && n.opcode < 0) n = n.previous - return n - } - - private fun nextReal(node: AbstractInsnNode): AbstractInsnNode? { - var n = node.next - while (n != null && n.opcode < 0) n = n.next - return n - } - - /** True when the instruction before [label] never falls through to it. */ - private fun endsWithExit(label: AbstractInsnNode): Boolean { - val op = previousReal(label)?.opcode ?: return false - return op == Opcodes.GOTO || op == Opcodes.ATHROW || op in Opcodes.IRETURN..Opcodes.RETURN - } - - /** - * The idiom `if (c instanceof X) ... (X) c`: the operand of [cast] is a local read right before it, - * and an INSTANCEOF of the same type on that local sits before it in a branch that contains the - * cast, with no store to the local in between. A guard that jumps over the cast when false (IFEQ) - * covers the instructions up to its target; one that jumps to the cast when true (IFNE) must be - * followed by code that cannot fall through to its target. The cast then cannot throw, so it is - * not reported. - */ - fun isGuardedByInstanceof( - m: MethodNode, - cast: TypeInsnNode, - ): Boolean { - val local = (previousReal(cast) as? VarInsnNode)?.takeIf { it.opcode == Opcodes.ALOAD }?.`var` ?: return false - val castIndex = m.instructions.indexOf(cast) - var node: AbstractInsnNode? = cast.previous - while (node != null) { - if (node is VarInsnNode && node.`var` == local && node.opcode in Opcodes.ISTORE..Opcodes.ASTORE) return false - if (node is TypeInsnNode && node.opcode == Opcodes.INSTANCEOF && node.desc == cast.desc && - (previousReal(node) as? VarInsnNode)?.let { it.opcode == Opcodes.ALOAD && it.`var` == local } == true - ) { - val jump = nextReal(node) as? JumpInsnNode - if (jump != null) { - val target = m.instructions.indexOf(jump.label) - when (jump.opcode) { - Opcodes.IFEQ -> { - if (target > castIndex) return true - } - - Opcodes.IFNE -> { - if (target <= castIndex && target > m.instructions.indexOf(jump) && endsWithExit(jump.label)) return true - } - } - } - } - node = node.previous - } - return false - } - fun mentionsRenamed(desc: String) = desc.contains("android/database/") && Rules.RENAMED_DESCRIPTOR_TOKENS.any { desc.contains(it) } fun simple(name: String) = name.substringAfterLast('/') @@ -873,8 +864,11 @@ object SqliteRewriter { /** * The CHECKCASTs to AbstractWindowedCursor whose operand came from an SQLite API (a call on * one of the renamed classes returning a cursor, or a parameter or instance field declared as - * SQLiteCursor), through locals and the stack. Approximate: values that went through other - * calls, array elements or static fields are not followed (a miss). + * SQLiteCursor), through locals and the stack, unless an `instanceof` of the cast's type proved + * the operand on every path to the cast (see [GuardFrame]): `if (c instanceof X) ((X) c)`, `&&`, + * `?:` and an early exit when it is false, but not `b || c instanceof X`, which reaches the cast + * with `b` alone. Approximate: values that went through other calls, array elements or static + * fields are not followed (a miss). */ fun cursorCastTaint(m: MethodNode): Set { val casts = @@ -914,7 +908,12 @@ object SqliteRewriter { } if (insn.opcode == Opcodes.CHECKCAST && r != null) { val castTo = (insn as TypeInsnNode).desc - return TaintValue(r.type, (value as? TaintValue)?.sqliteCursor == true || castTo == Rules.SQLITE_CURSOR) + val operand = value as? TaintValue + return TaintValue( + r.type, + operand?.sqliteCursor == true || castTo == Rules.SQLITE_CURSOR, + operand?.instanceOf.orEmpty(), + ) } return r } @@ -940,13 +939,30 @@ object SqliteRewriter { value1: BasicValue, value2: BasicValue, ): BasicValue { - val tainted = (value1 as? TaintValue)?.sqliteCursor == true || (value2 as? TaintValue)?.sqliteCursor == true - // BasicInterpreter.merge answers UNINITIALIZED for values that differ, taint included - if (tainted && value1.type != null && value1.type == value2.type) return TaintValue(value1.type, true) + val t1 = value1 as? TaintValue + val t2 = value2 as? TaintValue + // BasicInterpreter.merge answers UNINITIALIZED for values that differ, taint and proofs included + if ((t1 != null || t2 != null) && value1.type != null && value1.type == value2.type) { + val merged = + TaintValue( + value1.type, + t1?.sqliteCursor == true || t2?.sqliteCursor == true, + t1?.instanceOf.orEmpty() intersect t2?.instanceOf.orEmpty(), + ) + return if (merged == value1) value1 else merged + } return super.merge(value1, value2) } } - val analyzer = Analyzer(interpreter) + val analyzer = + object : Analyzer(interpreter) { + override fun newFrame( + numLocals: Int, + numStack: Int, + ): Frame = GuardFrame(numLocals, numStack) + + override fun newFrame(frame: Frame): Frame = GuardFrame(frame) + } val frames: Array?> = try { analyzer.analyze(cn.name, m) @@ -957,7 +973,8 @@ object SqliteRewriter { return casts .filter { cast -> val frame = frames[insns.indexOf(cast)] - frame != null && (frame.getStack(frame.stackSize - 1) as? TaintValue)?.sqliteCursor == true + val operand = frame?.let { it.getStack(it.stackSize - 1) } as? TaintValue + operand != null && operand.sqliteCursor && (cast as TypeInsnNode).desc !in operand.instanceOf }.toSet() } } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index f518d4787c..276264bba9 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1527,4 +1527,72 @@ class SqliteRewriterTest { assertThat(unverified.message).contains("does not verify") assertThat(unverified.message).contains("androidx/sqlite/db/framework/Up") } + + @Test + fun `an instanceof guard counts only when it covers every path to the cast`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Partly", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Partly { + Object or(SQLiteDatabase db, boolean b) { + Cursor c = db.rawQuery("x", null); + if (b || c instanceof AbstractCursor) { + return (AbstractCursor) c; + } + return null; + } + Object beforeTheLoop(SQLiteDatabase db, int n) { + Cursor c = db.rawQuery("x", null); + for (int i = 0; i < n; i++) { + if (!(c instanceof AbstractWindowedCursor)) { + return null; + } + c = db.rawQuery("y", null); + } + return (AbstractWindowedCursor) c; + } + } + """, + ), + src( + "p.Everywhere", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Everywhere { + Object andAfter(SQLiteDatabase db, boolean b) { + Cursor c = db.rawQuery("x", null); + if (c instanceof AbstractCursor && b) { + return (AbstractCursor) c; + } + return null; + } + Object onBothBranches(SQLiteDatabase db, boolean b) { + Cursor c = db.rawQuery("x", null); + if (b) { + if (!(c instanceof AbstractWindowedCursor)) return null; + } else { + if (!(c instanceof AbstractWindowedCursor)) return null; + } + Cursor copy = c; + return (AbstractWindowedCursor) copy; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Partly"]!!, hierarchy) } + // b alone reaches the cast in or; the loop may run zero times, or end on the unchecked cursor + assertThat(e.message).contains(" - or(") + assertThat(e.message).contains(" - beforeTheLoop(") + SqliteRewriter.rewrite(classes["p/Everywhere"]!!, hierarchy) + } } From abf700266c86c7dff520a3bf21ee37b477ee160e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:58 -0800 Subject: [PATCH 114/203] ADFA-7138 Cancel every query that shares an Android CancellationSignal toCancellationSignal registered a new listener on Android's signal for each call, and Android's signal holds one listener, so the second registration replaced the first. requery keeps a query's signal for its cursor's later reads, so with two lazy queries on one Android signal, cancelling it left the first cursor's signal uncancelled. Each Android signal now gets one forwarding listener, kept in a WeakHashMap, that cancels every requery signal converted from it. It holds them weakly and drops cleared ones on each call, so a closed and dropped cursor is not kept for a signal the app reuses. Because setOnCancelListener does not call a listener that is already set, a signal cancelled before the call is checked directly. The runtime test replaces android.jar's stub of the signal with a copy of Android's listener rules, to run the conversion on the JVM. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 4 +- .../gradle/sqlite/SqliteRewriteRuntimeTest.kt | 82 ++++++++++++++++++- .../sqliterewrite/SqliteRewriteRuntime.java | 63 ++++++++++++-- 3 files changed, 136 insertions(+), 13 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 17d3f3cbfe..883865954b 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -213,6 +213,8 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - `instanceof` is not rewritten: `cursor instanceof AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` is silently false for requery's cursors (no build failure), which is what Room's `DBUtil.query` relies on. -- Android's `CancellationSignal` holds one listener: the conversion replaces any listener the caller set. +- Android's `CancellationSignal` holds one listener: the conversion replaces any listener the caller set. Each + query gets its own androidx.core signal, and cancelling the Android signal cancels every one still in use, so + two lazy queries that share it both stop (requery keeps a query's signal for its cursor's later reads). - Which `SQLiteException` subclass requery throws for an error code (for example `SQLiteConstraintException`, which Room catches) is decided by its native layer; this rewrite does not change it and the survey did not check it. diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt index e8e892d959..02324e9e6c 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt @@ -1,12 +1,16 @@ package com.itsaky.androidide.gradle.sqlite import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage import com.itsaky.androidide.utils.FileProvider import org.junit.jupiter.api.Test -/** The pure functions of the runtime helper, run on the JVM from its bytecode compiled against android.jar. */ +/** + * The runtime helper's functions that need no device, run on the JVM from its bytecode compiled against android.jar, + * with Android's CancellationSignal replaced by a copy of its listener logic (android.jar's methods only throw). + */ class SqliteRewriteRuntimeTest { - private val runtime: Class<*> by lazy { + private val loader: ClassLoader by lazy { val source = FileProvider .projectRoot() @@ -15,12 +19,29 @@ class SqliteRewriteRuntimeTest { .readText() val classes = Compiler.compile( - listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", source)), + listOf( + JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", source), + JavaSource("android.os.CancellationSignal", ANDROID_SIGNAL), + ), listOf(TestJars.androidJar, TestJars.androidxCoreJar), ) - BytecodeVerifier.loader(classes).loadClass("org.appdevforall.sqliterewrite.SqliteRewriteRuntime") + BytecodeVerifier.loader(classes) } + private val runtime: Class<*> by lazy { loader.loadClass("org.appdevforall.sqliterewrite.SqliteRewriteRuntime") } + + private val androidSignal: Class<*> by lazy { loader.loadClass("android.os.CancellationSignal") } + + private fun newAndroidSignal(): Any = androidSignal.getConstructor().newInstance() + + private fun convert(signal: Any): Any = runtime.getMethod("toCancellationSignal", androidSignal).invoke(null, signal) + + private fun cancel(signal: Any) { + signal.javaClass.getMethod("cancel").invoke(signal) + } + + private fun isCanceled(signal: Any) = signal.javaClass.getMethod("isCanceled").invoke(signal) as Boolean + private fun translate(flags: Int) = runtime.getMethod("translateOpenFlags", Int::class.javaPrimitiveType).invoke(null, flags) as Int private val readOnly = 1 @@ -45,4 +66,57 @@ class SqliteRewriteRuntimeTest { assertThat(translate(16)).isEqualTo(2) assertThat(translate(8 or createIfNecessary)).isEqualTo(6) } + + @Test + fun `two queries that share an Android signal are both cancelled with it`() { + val signal = newAndroidSignal() + // requery keeps each query's signal for its cursor's later reads + val first = convert(signal) + val second = convert(signal) + + cancel(signal) + + assertWithMessage("the first query's signal").that(isCanceled(first)).isTrue() + assertWithMessage("the second query's signal").that(isCanceled(second)).isTrue() + } + + @Test + fun `a query given a signal that is already cancelled gets a cancelled one`() { + val signal = newAndroidSignal() + convert(signal) + cancel(signal) + + assertThat(isCanceled(convert(signal))).isTrue() + } + + private companion object { + /** Android's listener rules: one listener, a new one runs at once on a cancelled signal, the same one does not. */ + val ANDROID_SIGNAL = + """ + package android.os; + public final class CancellationSignal { + private boolean canceled; + private OnCancelListener listener; + public boolean isCanceled() { synchronized (this) { return canceled; } } + public void cancel() { + OnCancelListener l; + synchronized (this) { + if (canceled) return; + canceled = true; + l = listener; + } + if (l != null) l.onCancel(); + } + public void setOnCancelListener(OnCancelListener l) { + synchronized (this) { + if (listener == l) return; + listener = l; + if (!canceled || l == null) return; + } + l.onCancel(); + } + public interface OnCancelListener { void onCancel(); } + } + """.trimIndent() + } } diff --git a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java index 8e810f980f..9fc44c855a 100644 --- a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java +++ b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java @@ -8,6 +8,11 @@ import android.text.TextUtils; import java.io.File; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; /** * Targets of the calls that CoGo's Gradle plugin redirects when it rewrites an app from android.database.sqlite to requery (ADFA-7138). @@ -41,6 +46,9 @@ public final class SqliteRewriteRuntime { private static final int CONTEXT_MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x8; + /** The listener each Android signal forwards cancellation through; weak keys, so a signal the app dropped goes. */ + private static final Map FORWARDERS = new WeakHashMap<>(); + /** * Same as Context.deleteDatabase, which also returns false on any exception. requery's deleteDatabase removes the -journal, -wal, -shm and -mj files next to the file, like Android's. */ @@ -132,7 +140,7 @@ public static String stringForQuery(SQLiteStatement prog, String[] selectionArgs } /** - * Android's signal for requery's. Android's signal holds one listener, so this replaces any listener the caller set on it (Android's setOnCancelListener documents that it replaces the previous one). It fires at once when the signal is cancelled already. + * Android's signal for requery's. Each call returns a new requery signal, and cancelling Android's cancels every one of them still in use: requery keeps a query's signal for the cursor's later reads, so two lazy queries that share an Android signal must both stop. Android's signal holds one listener, so this replaces any listener the caller set on it (Android's setOnCancelListener documents that it replaces the previous one). */ public static androidx.core.os.CancellationSignal toCancellationSignal( CancellationSignal signal) { @@ -140,16 +148,21 @@ public static androidx.core.os.CancellationSignal toCancellationSignal( return null; } final androidx.core.os.CancellationSignal converted = new androidx.core.os.CancellationSignal(); + CancelForwarder forwarder; + synchronized (FORWARDERS) { + forwarder = FORWARDERS.get(signal); + if (forwarder == null) { + forwarder = new CancelForwarder(); + FORWARDERS.put(signal, forwarder); + } + } + forwarder.add(converted); + signal.setOnCancelListener(forwarder); + // setOnCancelListener does not call a listener that is already set, so a signal cancelled before this call + // has to be checked if (signal.isCanceled()) { converted.cancel(); - return converted; } - signal.setOnCancelListener(new CancellationSignal.OnCancelListener() { - @Override - public void onCancel() { - converted.cancel(); - } - }); return converted; } @@ -168,4 +181,38 @@ public static int translateOpenFlags(int androidFlags) { } private SqliteRewriteRuntime() {} + + /** + * Cancels every requery signal converted from one Android signal. It holds them weakly: a query's signal lives as long as its cursor, and a closed and dropped cursor must not be kept for a signal the app reuses. + */ + private static final class CancelForwarder implements CancellationSignal.OnCancelListener { + private final List> converted = new ArrayList<>(); + + @Override + public void onCancel() { + List live = new ArrayList<>(); + synchronized (this) { + for (WeakReference ref : converted) { + androidx.core.os.CancellationSignal signal = ref.get(); + if (signal != null) { + live.add(signal); + } + } + converted.clear(); + } + // outside the lock: requery's listener interrupts the native query + for (androidx.core.os.CancellationSignal signal : live) { + signal.cancel(); + } + } + + synchronized void add(androidx.core.os.CancellationSignal signal) { + for (int i = converted.size() - 1; i >= 0; i--) { + if (converted.get(i).get() == null) { + converted.remove(i); + } + } + converted.add(new WeakReference<>(signal)); + } + } } From 68bf024d93e0a73ce3696c1c29a9e37d02b63355 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:58 -0800 Subject: [PATCH 115/203] ADFA-7138 Docs: say a cancelled query throws androidx.core's OperationCanceledException The rewrite converts Android's CancellationSignal to androidx.core's, and requery throws androidx.core.os.OperationCanceledException for a cancelled query, from its Java check and from its native layer (checked with javap and in the 3.49.0 .so). That class does not extend Android's, and catch clauses are not rewritten, so a catch of android.os.OperationCanceledException no longer catches the cancellation. The docs listed this among the unverified review items. It is now a known limit of its own, with the multi-catch an app can use with the SQLite debugger on and off, and the rewriter's comment at the conversion says so. Docs and a comment only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 10 ++++++++-- .../itsaky/androidide/gradle/sqlite/SqliteRewriter.kt | 2 ++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 883865954b..1307fa4951 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -184,8 +184,7 @@ dependency, and runs the script on both APKs. The release must pass. The debug A `CursorWindow` extends android's `SQLiteClosable`, which stays the platform's class. Calls that name a `CursorWindow` in a renamed class's descriptor fail the build; calls on a `CursorWindow` are left alone. - The items below were reported by review and not verified here: `ATTACH` on a WAL database (requery runs it on - one connection only; Android turns write-ahead logging off on the first `ATTACH`); a cancelled query throws - `androidx.core.os.OperationCanceledException`, not `android.os.OperationCanceledException`; page size and + one connection only; Android turns write-ahead logging off on the first `ATTACH`); page size and `wal_autocheckpoint` defaults can differ from the platform's; there is no compatibility WAL mode; the cursor window is a fixed 2 MB, and a row larger than it throws `IllegalStateException`; `beginTransactionReadOnly` is not in requery (it fails the build) and its read-only semantics have no counterpart; requery has no @@ -213,6 +212,13 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - `instanceof` is not rewritten: `cursor instanceof AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` is silently false for requery's cursors (no build failure), which is what Room's `DBUtil.query` relies on. +- A cancelled query throws `androidx.core.os.OperationCanceledException`, not + `android.os.OperationCanceledException`: requery checks androidx.core's signal, which the rewrite converts Android's + to, and its native layer throws the same class (checked with javap and in requery 3.49.0's `.so`). The two classes + are unrelated, and the rewrite does not change `catch` clauses, so a `catch (android.os.OperationCanceledException e)` + around a query, or around reading its cursor, no longer catches a cancellation, which reaches the caller instead. An + app that catches it should catch both, `catch (android.os.OperationCanceledException | + androidx.core.os.OperationCanceledException e)`, which works with the SQLite debugger on and off. - Android's `CancellationSignal` holds one listener: the conversion replaces any listener the caller set. Each query gets its own androidx.core signal, and cancelling the Android signal cancels every one still in use, so two lazy queries that share it both stop (requery keeps a query's signal for its cursor's later reads). diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 13d14f2668..67dfcbe378 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -655,6 +655,8 @@ object SqliteRewriter { is Action.Retype -> { if (action.signal) { + // requery checks androidx.core's signal, so a cancelled query throws androidx.core's + // OperationCanceledException, which a catch of Android's does not catch (see the docs) m.instructions.insertBefore( mi, MethodInsnNode(Opcodes.INVOKESTATIC, Rules.HELPER, "toCancellationSignal", Rules.HELPER_SIGNAL_DESC, false), From ade142c7d940ab80dfe9e5891734a85cdbc8858e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:58 -0800 Subject: [PATCH 116/203] ADFA-7138 Look up the SQLite rewrite tests' jars in the active Gradle user home TestJars searched ~/.gradle/caches only. With GRADLE_USER_HOME or --gradle-user-home pointing elsewhere, the tests skipped locally, or failed on CI, although the jars were in the active cache. Both test tasks now pass gradle.gradleUserHomeDir as cogo.test.gradleUserHome, as a JVM argument rather than an input, so the per-machine path does not change the task's cache key. gradleUserHome() reads it, then GRADLE_USER_HOME, then falls back to ~/.gradle, as when the tests run from an IDE. Test code and build script only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/build.gradle.kts | 10 +++++++ .../gradle/sqlite/SqliteTestSupport.kt | 15 +++++++++-- .../gradle/sqlite/SqliteTestSupportTest.kt | 26 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index 96cee1492b..f8f9159f7e 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -63,11 +63,20 @@ fun Test.stageMavenLocalRepos() { } } +// The SQLite rewrite tests find the jars they compile against in the cache of this build's Gradle user home, which +// GRADLE_USER_HOME or --gradle-user-home can move from ~/.gradle. An argument, not an input: the path is per machine. +val gradleUserHomePath: String = gradle.gradleUserHomeDir.absolutePath + +fun Test.passGradleUserHome() { + jvmArgumentProviders.add(CommandLineArgumentProvider { listOf("-Dcogo.test.gradleUserHome=$gradleUserHomePath") }) +} + val sqliteReleaseApkTestClass = "com.itsaky.androidide.gradle.SqliteReleaseApkTest" tasks.named("test") { useJUnitPlatform() stageMavenLocalRepos() + passGradleUserHome() // Run by sqliteReleaseApkTest below, which builds the AARs it needs filter { excludeTestsMatching(sqliteReleaseApkTestClass) } } @@ -103,6 +112,7 @@ tasks.register("sqliteReleaseApkTest") { classpath = testSourceSet.runtimeClasspath useJUnitPlatform() stageMavenLocalRepos() + passGradleUserHome() filter { includeTestsMatching(sqliteReleaseApkTestClass) } // The tasks AndroidIDEAssetsPlugin bundles these AARs with, so this task and :app:assemble build them once diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt index fd9e8a91eb..6d677ea7e5 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt @@ -28,9 +28,20 @@ internal fun requireEnvironment( assumeTrue(false, missing) } +/** + * The Gradle user home whose cache holds the jars: the one of the build that runs the tests, which the test tasks pass + * as cogo.test.gradleUserHome, then GRADLE_USER_HOME, then ~/.gradle, as from an IDE. + */ +internal fun gradleUserHome( + property: String? = System.getProperty("cogo.test.gradleUserHome"), + env: String? = System.getenv("GRADLE_USER_HOME"), + userHome: File = File(System.getProperty("user.home")), +): File = property?.takeIf { it.isNotEmpty() }?.let(::File) ?: env?.takeIf { it.isNotEmpty() }?.let(::File) ?: File(userHome, ".gradle") + /** Jars the tests compile and resolve against. Each lookup skips the test with a message, or fails it on CI. */ internal object TestJars { private val home = File(System.getProperty("user.home")) + private val modules by lazy { File(gradleUserHome(), "caches/modules-2/files-2.1") } val androidJar: File by lazy { val sdkRoots = @@ -59,7 +70,7 @@ internal object TestJars { version: String, file: String, ): File? = - File(home, ".gradle/caches/modules-2/files-2.1/$group/$artifact/$version") + File(modules, "$group/$artifact/$version") .walkTopDown() .firstOrNull { it.name == file } @@ -97,7 +108,7 @@ internal object TestJars { /** The Kotlin classes the framework classes call; null when the Gradle cache has none. */ val kotlinStdlibJar: File? by lazy { - File(home, ".gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib") + File(modules, "org.jetbrains.kotlin/kotlin-stdlib") .walkTopDown() .filter { it.name.startsWith("kotlin-stdlib-") && it.name.endsWith(".jar") && "sources" !in it.name } .maxByOrNull { it.name } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt new file mode 100644 index 0000000000..a205592a23 --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt @@ -0,0 +1,26 @@ +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File + +/** + * The test support's own logic, which the rewrite tests rely on to find their jars and to tell a linking reference + * from a broken one. + */ +class SqliteTestSupportTest { + @Test + fun `the jars are looked up in the Gradle user home of the build that runs the tests`( + @TempDir dir: File, + ) { + val home = File(dir, "home") + val active = File(dir, "active-gradle-home") + val env = File(dir, "env-gradle-home") + + assertThat(gradleUserHome(active.path, env.path, home)).isEqualTo(active) + // run from an IDE, without the property the test tasks pass + assertThat(gradleUserHome(null, env.path, home)).isEqualTo(env) + assertThat(gradleUserHome(null, null, home)).isEqualTo(File(home, ".gradle")) + } +} From bf86cdde7fbaf2284f5a0ab8009c276a1a5434f5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:58 -0800 Subject: [PATCH 117/203] ADFA-7138 Do not inherit constructors when the tests resolve a reference ClassIndex.resolve searched superclasses for every member, so a reference to Child.()V resolved to Parent's constructor when Child declares only Child(int). The JVM rejects that invokespecial with NoSuchMethodError, so the resolution tests could accept a constructor reference that does not link. A constructor is now looked up in the named owner only; methods and fields are still inherited. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteTestSupport.kt | 4 +++- .../gradle/sqlite/SqliteTestSupportTest.kt | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt index 6d677ea7e5..99aa55cc27 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt @@ -250,7 +250,8 @@ internal class ClassIndex( * The class declaring the member, or null when the JVM would not link the reference: the member is * missing, static where the call is not (or the reverse), or not accessible from [caller], a class * in [classes] (null: an unrelated class in another package). [protectedOk] accepts protected members - * for a caller that is not a subclass, as a probe that stands in for one. + * for a caller that is not a subclass, as a probe that stands in for one. A constructor is looked up + * in [owner] only: it is not inherited. */ fun resolve( owner: String, @@ -279,6 +280,7 @@ internal class ClassIndex( if (isStatic != null && (access and Opcodes.ACC_STATIC != 0) != isStatic) return null return if (accessible(access, n, caller, protectedOk)) n else null } + if (!field && name == "") return null c.superName?.let(pending::add) pending.addAll(c.interfaces) } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt index a205592a23..56fff64fde 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt @@ -23,4 +23,23 @@ class SqliteTestSupportTest { assertThat(gradleUserHome(null, env.path, home)).isEqualTo(env) assertThat(gradleUserHome(null, null, home)).isEqualTo(File(home, ".gradle")) } + + @Test + fun `a constructor resolves in the named class only, while methods are still inherited`() { + val classes = + Compiler.compile( + listOf( + JavaSource("p.Parent", "package p; public class Parent { public Parent() {} public void m() {} }"), + JavaSource("p.Child", "package p; public class Child extends Parent { public Child(int i) {} }"), + ), + classpath = emptyList(), + ) + val index = ClassIndex(emptyList()) + classes.values.forEach(index::addClass) + + assertThat(index.resolve("p/Child", "", "(I)V", field = false)).isEqualTo("p/Child") + // the JVM throws NoSuchMethodError for `new Child()`: Parent's constructor is not Child's + assertThat(index.resolve("p/Child", "", "()V", field = false)).isNull() + assertThat(index.resolve("p/Child", "m", "()V", field = false)).isEqualTo("p/Parent") + } } From 0cab2d4cf36bfe1c0b95e61f5f757831cc9a06e1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:59 -0800 Subject: [PATCH 118/203] ADFA-7138 Bound the release-APK check script by its timeout before reading output checkApk read the script's output to its end and only then made the timed wait, so a script, or a child it left behind, that kept stdout open would hang the test past its one-minute limit. runBounded now sends the output to a temp file, waits with the timeout first, destroys the process on timeout and fails with what it printed, and reads the file after the process ends. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/gradle/SqliteReleaseApkTest.kt | 18 ++++------ .../gradle/sqlite/SqliteTestSupport.kt | 33 +++++++++++++++++++ .../gradle/sqlite/SqliteTestSupportTest.kt | 21 ++++++++++++ 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt index b85f62305b..b82e66bd76 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteReleaseApkTest.kt @@ -2,7 +2,9 @@ package com.itsaky.androidide.gradle import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.gradle.sqlite.ProcessResult import com.itsaky.androidide.gradle.sqlite.requireEnvironment +import com.itsaky.androidide.gradle.sqlite.runBounded import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_AAR import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_SQLITE_REWRITE_RUNTIME_AAR @@ -11,7 +13,6 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.io.File -import java.util.concurrent.TimeUnit /** * The release-APK guard (ADFA-7138): an app that opted into the SQLite debugger gets it in its debuggable @@ -32,19 +33,12 @@ class SqliteReleaseApkTest { return File(path!!) } - private class CheckResult( - val exitCode: Int, - val output: String, - ) - - private fun checkApk(apk: File): CheckResult { + private fun checkApk(apk: File): ProcessResult { assertWithMessage("APK not built").that(apk.isFile).isTrue() val script = FileProvider.projectRoot().resolve("scripts/check-release-apk-no-sqlite-debugger.sh").toFile() - val process = ProcessBuilder("bash", script.path, apk.path).redirectErrorStream(true).start() - val output = process.inputStream.bufferedReader().readText() - check(process.waitFor(1, TimeUnit.MINUTES)) { "the check script did not finish" } - println("${apk.name}: exit ${process.exitValue()}\n$output") - return CheckResult(process.exitValue(), output) + val result = runBounded(listOf("bash", script.path, apk.path), timeoutSeconds = 60) + println("${apk.name}: exit ${result.exitCode}\n${result.output}") + return result } @Test diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt index 99aa55cc27..d41edad4bd 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt @@ -7,6 +7,7 @@ import org.objectweb.asm.tree.ClassNode import java.io.File import java.net.URI import java.nio.file.Files +import java.util.concurrent.TimeUnit import java.util.zip.ZipFile import javax.tools.JavaFileObject import javax.tools.SimpleJavaFileObject @@ -121,6 +122,38 @@ internal object TestJars { } } +/** A finished process: its exit code, and its standard output and error together. */ +internal class ProcessResult( + val exitCode: Int, + val output: String, +) + +/** + * Runs [command] with its output going to a temp file, so the time limit holds even for a process, or a child it + * leaves behind, that keeps the output open: reading a pipe to its end would wait for that. On timeout it destroys + * the process and fails with what it printed. + */ +internal fun runBounded( + command: List, + timeoutSeconds: Long, +): ProcessResult { + val log = Files.createTempFile("sqlite-test-process", ".log").toFile() + try { + val process = + ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(log) + .start() + if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) { + process.destroyForcibly().waitFor(10, TimeUnit.SECONDS) + throw AssertionError("${command.joinToString(" ")} did not finish in $timeoutSeconds s; it printed:\n${log.readText()}") + } + return ProcessResult(process.exitValue(), log.readText()) + } finally { + log.delete() + } +} + internal class JavaSource( val className: String, val code: String, diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt index 56fff64fde..84f83ebcb5 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt @@ -1,9 +1,11 @@ package com.itsaky.androidide.gradle.sqlite import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.io.File +import java.time.Duration /** * The test support's own logic, which the rewrite tests rely on to find their jars and to tell a linking reference @@ -42,4 +44,23 @@ class SqliteTestSupportTest { assertThat(index.resolve("p/Child", "", "()V", field = false)).isNull() assertThat(index.resolve("p/Child", "m", "()V", field = false)).isEqualTo("p/Parent") } + + @Test + fun `a process that keeps its output open fails at its time limit, with what it printed`() { + val started = System.nanoTime() + + val e = assertThrows(AssertionError::class.java) { runBounded(listOf("bash", "-c", "echo started; sleep 20"), timeoutSeconds = 1) } + + assertThat(e.message).contains("did not finish in 1 s") + assertThat(e.message).contains("started") + assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(15)) + } + + @Test + fun `a process that finishes gives its exit code and output`() { + val result = runBounded(listOf("bash", "-c", "echo out; echo err >&2; exit 3"), timeoutSeconds = 30) + + assertThat(result.exitCode).isEqualTo(3) + assertThat(result.output.lines()).containsAtLeast("out", "err") + } } From 7572eced8f962e7f300e0baf69e68e0071087929 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 23:19:59 -0800 Subject: [PATCH 119/203] ADFA-7138 Check this run's helper in the transform test, not any cached one The test looked for a rewritten SqliteRewriteRuntime in every jar of the shared transform cache. The helper's name is fixed, so a rewritten copy from an earlier run passed the check even when this run left the helper alone. The helper AAR now also carries a class with a per-run name, and the test inspects only the transformed jars that hold it. Checked against a build that skips the helper package in isInstrumentable: the new test fails, and the old one still passed on a cached helper from an earlier run. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/SqliteRewriteTransformTest.kt | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt index b392f5da73..08d5583ff3 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt @@ -57,16 +57,24 @@ class SqliteRewriteTransformTest { /** * AGP instruments the classes of dependencies with artifact transforms, which the dex builder triggers, not - * in the variant's transform task, so the output is in Gradle's transform cache: the jars that hold [entry]. The class of this run - * has a name no earlier run used, so a hit is this run's. + * in the variant's transform task, so the output is in Gradle's transform cache, which every run of this test + * shares: the bytes of [read] in each jar that holds [marker]. [marker] names a class no earlier run used, so a + * hit is this run's. */ - private fun transformedJarsWith(entry: String): List { + private fun transformedJarsWith( + marker: String, + read: String = marker, + ): List { val cache = FileProvider.projectRoot().resolve("gradle-plugin/build/tmp/test/work/.gradle-test-kit/caches").toFile() return cache .walkTopDown() .filter { it.extension == "jar" && "/transforms/" in it.path } .mapNotNull { jar -> - runCatching { ZipFile(jar).use { zip -> zip.getEntry(entry)?.let { zip.getInputStream(it).readBytes() } } }.getOrNull() + runCatching { + ZipFile(jar).use { zip -> + if (zip.getEntry(marker) == null) null else zip.getEntry(read)?.let { zip.getInputStream(it).readBytes() } + } + }.getOrNull() }.toList() } @@ -89,9 +97,17 @@ class SqliteRewriteTransformTest { .projectRoot() .resolve("subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java") .toFile() + // The helper's name is fixed, so its AAR also carries a class of this run's, to tell its transformed jar apart + val markerName = "Marker${System.nanoTime()}" val helper = Compiler.compile( - listOf(JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText())), + listOf( + JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", helperSource.readText()), + JavaSource( + "org.appdevforall.sqliterewrite.$markerName", + "package org.appdevforall.sqliterewrite; class $markerName {}", + ), + ), listOf(TestJars.androidJar, TestJars.androidxCoreJar), ) val libAar = aar(File(dir, "libs/x.aar"), "x.lib", library) @@ -160,8 +176,10 @@ class SqliteRewriteTransformTest { // the injected helper AAR goes through the same transform: its class is rewritten to requery too val helpers = - transformedJarsWith("org/appdevforall/sqliterewrite/SqliteRewriteRuntime.class") - .map { bytes -> ClassNode().also { ClassReader(bytes).accept(it, 0) } } + transformedJarsWith( + "org/appdevforall/sqliterewrite/$markerName.class", + read = "org/appdevforall/sqliterewrite/SqliteRewriteRuntime.class", + ).map { bytes -> ClassNode().also { ClassReader(bytes).accept(it, 0) } } assertThat(helpers).isNotEmpty() assertThat( helpers.any { helper -> From 5a2fd6e729f68718b32a5ce70fb1ceb5dc06abdd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 04:33:28 -0800 Subject: [PATCH 120/203] ADFA-7138: Tapping the "Quick Build: off" status line shows the refusal, as the button does While the SQLite debugger is on, the status line reads "Quick Build: off while the SQLite debugger is on - tap for details", but the line was plain text: a tap fell through to the sheet header, and only the Quick Build button showed the refusal again (F221, found on a Galaxy Note 20). The refused-state QuickBuildStatusBarUpdate.Show now carries a tapLabel. ProjectHandlerActivity binds it to the status line after writing the text, and every status write by anyone (doSetStatus) unbinds it first, so the tap lasts only while that line is up. The tap runs the toolbar's Quick Build action through the registry, the button's own path; the dropdown's Quick Build row now shares that function (runQuickBuildAction) instead of repeating it. While tappable the line is clickable and focusable, and TalkBack reads "double- tap to show why Quick Build is off" (new quick_build_status_off_sqlite_debugger_action string). Its size is unchanged, so the 2x font-scale header sizing is untouched; the rest of the header still expands the sheet. Left alone: "setup failed - tap to retry", "stopped - tap to retry" and "built - tap to start app" also say "tap" and are still plain text; they are not part of F221. Test: QuickBuildStatusLineTapTest (Robolectric) inflates the real status line, applies the real mapping the way the activity does, and clicks it. The editor activity itself is too large for a JVM test, so the callback stands in for the toolbar action run. Reverting either the mapping's tapLabel or the binder's click wiring fails it at "value of: performClick() expected to be true". gradle-plugin/docs/sqlite-rewrite.md now mentions the tap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../editor/EditorHandlerActivity.kt | 20 ++- .../editor/ProjectHandlerActivity.kt | 12 ++ .../quickbuild/QuickBuildStatusBar.kt | 15 ++- .../itsaky/androidide/ui/EditorBottomSheet.kt | 15 +++ .../com/itsaky/androidide/ui/StatusLineTap.kt | 37 +++++ .../quickbuild/QuickBuildStatusBarTest.kt | 12 +- .../quickbuild/QuickBuildStatusLineTapTest.kt | 127 ++++++++++++++++++ gradle-plugin/docs/sqlite-rewrite.md | 4 +- resources/src/main/res/values/strings.xml | 2 + 9 files changed, 233 insertions(+), 11 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt create mode 100644 app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusLineTapTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt index 40f2dc6425..5942453004 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt @@ -879,9 +879,7 @@ open class EditorHandlerActivity : popup.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.action_quick_build -> { - // Through the registry, same as Standard Run below, so the menu entry - // and the toolbar tap share one code path (incl. the analytics event). - if (quickBuild != null && quickBuild.enabled) registry.executeAction(quickBuild, data) + runQuickBuildAction(data) true } @@ -907,6 +905,22 @@ open class EditorHandlerActivity : popup.show() } + /** + * Runs the toolbar's Quick Build action through the registry, as the button's own tap does, so + * the dropdown row and a status line that asks for a tap share the button's code path + * (including the analytics event). Does nothing while the button is greyed out, as the button + * does. + */ + private fun runQuickBuildAction(data: ActionData) { + val registry = getInstance() as DefaultActionsRegistry + val quickBuild = registry.findAction(EDITOR_TOOLBAR, QuickBuildAction.ID) ?: return + if (quickBuild.enabled) registry.executeAction(quickBuild, data) + } + + override fun onQuickBuildStatusLineTapped() { + runQuickBuildAction(createToolbarActionData()) + } + private fun createToolbarActionData(): ActionData { val data = ActionData.create(this) val currentEditor = getCurrentEditor() diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 126b52f792..59598551fb 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -541,6 +541,10 @@ abstract class ProjectHandlerActivity : // setStatus resets ownership (any caller takes the bar over); reclaim it. setStatus(getString(update.text, *update.args.toTypedArray())) ownsQuickBuildStatus = true + // After setStatus, which drops any tap the line had. + update.tapLabel?.let { label -> + contentOrNull?.bottomSheet?.setStatusTap(getString(label), ::onQuickBuildStatusLineTapped) + } } } @@ -1438,9 +1442,17 @@ abstract class ProjectHandlerActivity : gravity: Int, ) { ownsQuickBuildStatus = false + // A tap belongs to the line that asked for it; the next writer's line is plain text. + contentOrNull?.bottomSheet?.setStatusTap(null, null) super.doSetStatus(text, gravity) } + /** + * A tap on a Quick Build status line that asks for one: it does what a tap on the Quick Build + * button does, through the same action, so the line cannot promise what the button would not. + */ + protected abstract fun onQuickBuildStatusLineTapped() + fun appendBuildOutput(str: String) { if (_binding == null || isDestroyed || isFinishing) return content.bottomSheet.appendBuildOut(str) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt index fc75a5546a..eef44fcf6e 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBar.kt @@ -21,11 +21,16 @@ sealed interface QuickBuildStatusBarUpdate { * @property args positional format arguments for [text], in order. * @property onlyIfOwned apply only if Quick Build's text is still on the bar, so a passive * refresh cannot clobber a line another writer took over. + * @property tapLabel set for a [text] that asks for a tap: a tap on the line then does what a + * tap on the Quick Build button does, and this is what TalkBack says the tap does. Null for + * a line that is plain text. The tap lasts only while this text is on the bar; the next + * write to the bar, by anyone, drops it. */ data class Show( @param:StringRes @get:StringRes val text: Int, val args: List = emptyList(), val onlyIfOwned: Boolean = false, + @param:StringRes @get:StringRes val tapLabel: Int? = null, ) : QuickBuildStatusBarUpdate /** Clear the bar - but only if the last write was Quick Build's (the caller tracks that). */ @@ -89,9 +94,13 @@ fun quickBuildStatusBarUpdate( } QuickBuildTransition.StartRefused -> { - // Not a failure: Quick Build is deliberately off here, and a retry cannot help. The tap - // shows the full refusal again. - QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_off_sqlite_debugger) + // Not a failure: Quick Build is deliberately off here, and a retry cannot help. The text + // says "tap for details", so the line itself takes the tap: it runs the button's tap, + // which re-runs the cheap check and shows the full refusal again. + QuickBuildStatusBarUpdate.Show( + R.string.quick_build_status_off_sqlite_debugger, + tapLabel = R.string.quick_build_status_off_sqlite_debugger_action, + ) } is QuickBuildTransition.ProvisioningStarted -> { diff --git a/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt b/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt index f4cf3638cd..c2294b296a 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt @@ -421,6 +421,7 @@ class EditorBottomSheet binding.viewOptionsOutputAction.clearLongPressHelp() binding.copyDiagnosticsFab.setOnClickListener(null) binding.headerContainer.setOnClickListener(null) + setStatusTap(null, null) removeOnLayoutChangeListener(fabLayoutChangeListener) ViewCompat.setOnApplyWindowInsetsListener(this, null) @@ -757,6 +758,20 @@ class EditorBottomSheet } } + /** + * Makes the status line a button for a line that asks for a tap, or plain text again with a + * null [onTap]. Main thread only, like the status writes it follows; see [bindStatusLineTap]. + * + * @param actionLabel what the tap does, for TalkBack's "double-tap to" announcement. + * @param onTap what the tap does, or null for plain text. + */ + fun setStatusTap( + actionLabel: CharSequence?, + onTap: (() -> Unit)?, + ) { + bindStatusLineTap(binding.buildStatus.statusText, actionLabel, onTap) + } + /** * Whether a user build is narrating into the status line. While it is, the collapsed * header keeps the tallest height it has needed; when it stops, the header re-fits the diff --git a/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt b/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt new file mode 100644 index 0000000000..0ccb582194 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt @@ -0,0 +1,37 @@ +package com.itsaky.androidide.ui + +import android.widget.TextView +import androidx.core.view.ViewCompat +import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat + +/** + * Makes the editor's status line a button while its text asks for a tap, and plain text again + * when it does not. + * + * Plain text the rest of the time, so a tap on the line falls through to the header under it, + * which expands the bottom sheet. The line's size is left alone: the collapsed header is measured + * from it, and at a 2x font scale it needs every row it takes. + * + * @param statusText the status line. + * @param actionLabel what a tap does, which TalkBack reads as "double-tap to [actionLabel]". + * Ignored without [onTap]. + * @param onTap what a tap does, or null to make the line plain text again. + */ +internal fun bindStatusLineTap( + statusText: TextView, + actionLabel: CharSequence?, + onTap: (() -> Unit)?, +) { + if (onTap == null) { + statusText.setOnClickListener(null) + statusText.isClickable = false + statusText.isFocusable = false + ViewCompat.removeAccessibilityAction(statusText, AccessibilityActionCompat.ACTION_CLICK.id) + return + } + statusText.setOnClickListener { onTap() } + // Focusable so a keyboard or switch user can reach it, not only a finger. + statusText.isFocusable = true + // A null command keeps the default click; only the spoken label is replaced. + ViewCompat.replaceAccessibilityAction(statusText, AccessibilityActionCompat.ACTION_CLICK, actionLabel, null) +} diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt index bc5952fc6a..68f104fafb 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusBarTest.kt @@ -295,11 +295,15 @@ class QuickBuildStatusBarTest { SessionEvent.ProvisioningFailed(QuickBuildMessage.RebuildFailed), ).state - assertThat(update(QuickBuildStatus.Provisioning(), QuickBuildStatus.from(refused))) - .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_off_sqlite_debugger)) + // The line says "tap for details", so it carries the tap; QuickBuildStatusLineTapTest clicks it. + val off = + QuickBuildStatusBarUpdate.Show( + R.string.quick_build_status_off_sqlite_debugger, + tapLabel = R.string.quick_build_status_off_sqlite_debugger_action, + ) + assertThat(update(QuickBuildStatus.Provisioning(), QuickBuildStatus.from(refused))).isEqualTo(off) // A recreation resubscribes with no previous status and must read the same. - assertThat(update(null, QuickBuildStatus.from(refused))) - .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_off_sqlite_debugger)) + assertThat(update(null, QuickBuildStatus.from(refused))).isEqualTo(off) assertThat(update(QuickBuildStatus.Provisioning(), QuickBuildStatus.from(failed))) .isEqualTo(QuickBuildStatusBarUpdate.Show(R.string.quick_build_status_start_failed)) // A save clears the carried refusal as it does a failure. diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusLineTapTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusLineTapTest.kt new file mode 100644 index 0000000000..ee210b7a4f --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildStatusLineTapTest.kt @@ -0,0 +1,127 @@ +package com.itsaky.androidide.quickbuild + +import android.content.Context +import android.view.LayoutInflater +import android.view.View.MeasureSpec +import android.view.accessibility.AccessibilityNodeInfo +import androidx.appcompat.view.ContextThemeWrapper +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.R +import com.itsaky.androidide.databinding.LayoutEditorBuildStatusBinding +import com.itsaky.androidide.ui.bindStatusLineTap +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildMessage +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildSessionState +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildStatus +import org.appdevforall.cotg.quickbuild.domain.session.SessionEvent +import org.appdevforall.cotg.quickbuild.domain.session.SessionReducer +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import com.itsaky.androidide.resources.R as Res + +/** + * The Quick Build status line takes the tap its text asks for (F221). + * + * While the SQLite debugger is on, the line reads "Quick Build: off while the SQLite debugger is + * on - tap for details", and tapping it did nothing: only the toolbar button showed the refusal. + * A tap on the line must now run the button's tap, which shows the refusal again. + * + * The editor activity is far beyond a JVM test, so this drives the parts it joins: the real + * status mapping, the real status-line layout, and the binder the bottom sheet uses, applied the + * way ProjectHandlerActivity applies them (every write drops the tap, then a Show that asks for one + * binds it). The tap callback stands in for the activity's run of the toolbar action. + */ +@RunWith(RobolectricTestRunner::class) +class QuickBuildStatusLineTapTest { + private val context = ApplicationProvider.getApplicationContext() + + /** The real status block, inflated against the app's theme, which its text colour needs. */ + private val line = + LayoutEditorBuildStatusBinding.inflate( + LayoutInflater.from(ContextThemeWrapper(context, R.style.Theme_AndroidIDE)), + ) + + private var quickBuildTaps = 0 + + private val refused = + QuickBuildStatus.from( + SessionReducer() + .reduce( + QuickBuildSessionState.Provisioning(), + SessionEvent.ProvisioningFailed(QuickBuildMessage.DisabledBySqliteDebugger), + ).state, + ) + + private fun show(update: QuickBuildStatusBarUpdate?) { + val show = update as QuickBuildStatusBarUpdate.Show + bindStatusLineTap(line.statusText, null, null) + line.statusText.text = context.getString(show.text, *show.args.toTypedArray()) + show.tapLabel?.let { label -> + bindStatusLineTap(line.statusText, context.getString(label)) { quickBuildTaps++ } + } + } + + private fun clickAction(): AccessibilityNodeInfo.AccessibilityAction? = + line.statusText + .createAccessibilityNodeInfo() + .actionList + .singleOrNull { it.id == AccessibilityNodeInfo.ACTION_CLICK } + + private fun measuredHeight(): Int { + line.root.measure( + MeasureSpec.makeMeasureSpec(WIDTH_PX, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), + ) + return line.statusText.measuredHeight + } + + @Test + fun `a tap on the refused line runs the Quick Build button's tap`() { + show(quickBuildStatusBarUpdate(QuickBuildStatus.Provisioning(), refused)) + assertThat(line.statusText.text.toString()) + .isEqualTo(context.getString(Res.string.quick_build_status_off_sqlite_debugger)) + + assertThat(line.statusText.performClick()).isTrue() + + assertThat(quickBuildTaps).isEqualTo(1) + } + + @Test + fun `the refused line is a labelled button for TalkBack and the keyboard`() { + show(quickBuildStatusBarUpdate(null, refused)) + + assertThat(line.statusText.isClickable).isTrue() + assertThat(line.statusText.isFocusable).isTrue() + assertThat(clickAction()?.label?.toString()) + .isEqualTo(context.getString(Res.string.quick_build_status_off_sqlite_debugger_action)) + // TalkBack's double-tap is an accessibility click, not a touch. + assertThat(line.statusText.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, null)).isTrue() + assertThat(quickBuildTaps).isEqualTo(1) + } + + @Test + fun `the tap leaves the line's size alone`() { + show(quickBuildStatusBarUpdate(QuickBuildStatus.Provisioning(), refused)) + val withTap = measuredHeight() + bindStatusLineTap(line.statusText, null, null) + + assertThat(withTap).isEqualTo(measuredHeight()) + } + + @Test + fun `the next line is plain text again, so a tap on it reaches the header`() { + show(quickBuildStatusBarUpdate(QuickBuildStatus.Provisioning(), refused)) + show(quickBuildStatusBarUpdate(refused, QuickBuildStatus.Provisioning())) + + assertThat(line.statusText.isClickable).isFalse() + assertThat(line.statusText.isFocusable).isFalse() + assertThat(clickAction()).isNull() + assertThat(line.statusText.performClick()).isFalse() + assertThat(quickBuildTaps).isEqualTo(0) + } + + private companion object { + const val WIDTH_PX = 600 + } +} diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 1307fa4951..c0f2744631 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -194,7 +194,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A pipeline), so those classes would still use `android.database.sqlite` next to rewritten baseline classes. The plugin logs why and the build is a normal one. The IDE does not provision Quick Build for such a project either (`GradleQuickBuildProvisioner.sqliteDebuggerRefusal`): it shows `quick_build_disabled_sqlite_debugger`, which - says Quick Build is off while the SQLite debugger is on. + says Quick Build is off while the SQLite debugger is on. The editor's status line then reads + `quick_build_status_off_sqlite_debugger`, and a tap on it, like a tap on the Quick Build button, shows that + message again. - Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not rewritten. A string constant that names one of the renamed classes (dots or slashes, `$` or `.` before a nested class, alone or in a type descriptor) logs a warning with class, method and line, in the classes the fail rule diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 412e4da19d..9ec6aa932f 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1219,6 +1219,8 @@ Quick Build failed - see Build Output Quick Build: setup failed - tap to retry Quick Build: off while the SQLite debugger is on - tap for details + + show why Quick Build is off Quick Build failed. See the Build Output panel for more details. Quick Build successful Quick Build compiler restarting… From 5ad480da7b0cd20bcf4c9479771b86ecfe82505f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:41:02 -0800 Subject: [PATCH 121/203] ADFA-7138 Delete a failed SQLite AAR copy's temp file, and sync it before the rename replaceAtomically deleted the .part file only when the rename failed, so a copy that threw (an asset read error, a full disk) left .aar.part beside the AAR. It is now deleted in a finally block, which after a successful rename finds nothing. The copy is also synced (fd.sync()) before the rename, so a power loss after the rename cannot leave the AAR empty on a file system that does not order data before metadata. The temp name stays fixed rather than unique per extractor. ToolsManager.init is the only extractor, called once per process (CredentialProtectedApplicationLoader guards it with _isLoaded.compareAndSet) and the app runs one process, so no second extractor races it. A unique name would leave a new orphan after every process death mid-copy, which no finally block can clean, while a fixed name is overwritten by the next run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/managers/ToolsManager.java | 17 +++++++++------ .../managers/ToolsManagerSqliteAarTest.kt | 21 +++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java index 12376129cb..714bc4a16a 100755 --- a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java +++ b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java @@ -211,19 +211,24 @@ static boolean isToolingJarCurrent(File toolingJarFile, File stampFile, String s } /** - * Copies the stream to a temp sibling of the target, then renames it over the target. {@link #init} extracts the SQLite AARs in the background, and GradleBuildService passes their paths to a build without waiting, so a build that starts meanwhile must find the previous complete file or the new one, never a missing or partly written one. rename(2) within one directory atomically replaces the target on Linux. Does not close the stream. + * Copies the stream to a temp sibling of the target, syncs it, then renames it over the target. {@link #init} extracts the SQLite AARs in the background, and GradleBuildService passes their paths to a build without waiting, so a build that starts meanwhile must find the previous complete file or the new one, never a missing or partly written one. rename(2) within one directory atomically replaces the target on Linux; syncing first means a power loss after the rename cannot leave the target empty. The temp file is deleted when any step fails. Its name is fixed, not unique: init runs once per process, and the next run overwrites what a killed process left. Does not close the stream. */ @VisibleForTesting static void replaceAtomically(InputStream source, File target) throws IOException { final var dir = Objects.requireNonNull(target.getParentFile()); dir.mkdirs(); final var tempFile = new File(dir, target.getName() + ".part"); - try (final var fos = new FileOutputStream(tempFile)) { - IoUtilsKt.transferToStream(source, fos); - } - if (!tempFile.renameTo(target)) { + try { + try (final var fos = new FileOutputStream(tempFile)) { + IoUtilsKt.transferToStream(source, fos); + fos.getFD().sync(); + } + if (!tempFile.renameTo(target)) { + throw new IOException("Could not move " + tempFile + " to " + target); + } + } finally { + // gone after a successful rename; a leftover of a failed copy is what this removes tempFile.delete(); - throw new IOException("Could not move " + tempFile + " to " + target); } } diff --git a/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt b/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt index 9c4a85d177..3d95db8389 100644 --- a/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt +++ b/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt @@ -1,10 +1,12 @@ package com.itsaky.androidide.managers import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File +import java.io.IOException import java.io.InputStream /** @@ -55,6 +57,25 @@ class ToolsManagerSqliteAarTest { assertThat(File(aar.parentFile, "sqlite-debugger.aar.part").exists()).isFalse() } + @Test + fun `a copy that fails leaves the previous AAR and no temp file`() { + val aar = File(tempFolder.root, "sqlite-debugger/sqlite-debugger.aar") + aar.parentFile!!.mkdirs() + aar.writeText("previous-install-aar") + val failing = + object : InputStream() { + private var left = 4 + + override fun read(): Int = if (left-- > 0) 'x'.code else throw IOException("asset read failed") + } + + val e = assertThrows(IOException::class.java) { ToolsManager.replaceAtomically(failing, aar) } + + assertThat(e).hasMessageThat().isEqualTo("asset read failed") + assertThat(aar.readText()).isEqualTo("previous-install-aar") + assertThat(aar.parentFile!!.list()).asList().containsExactly("sqlite-debugger.aar") + } + @Test fun `the first extraction creates the directory and the AAR`() { val aar = File(tempFolder.root, "sqlite-rewrite-runtime/sqlite-rewrite-runtime.aar") From 586a9b91f443209df02ae1ab37575b0b0bc3715f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:42:05 -0800 Subject: [PATCH 122/203] ADFA-7138 Fail the build for an SQLite cursor stored into an Android cursor array javac writes no CHECKCAST for `AbstractCursor[] a; a[0] = sqliteCursor;`. After the rename the value is requery's SQLiteCursor, which is not an AbstractCursor, so the store verifies but throws ArrayStoreException at run time, in release builds too: the rewrite runs in every variant of an opted-in app (D10, SqliteRewritePlugin.kt:44). implicitCursorConversions now fails an AASTORE whose value is statically an SQLiteCursor (or a subclass) and whose array is, on every path to the store, an AbstractCursor[], AbstractWindowedCursor[] or CrossProcessCursor[] from a parameter, field, call, cast or ANEWARRAY. The message names the class, method and line, like the other rewrite failures. The analysis value carries the array's element type, and a merge keeps it only when both paths agree. The pre-filter now also looks at a method's parameters and at ANEWARRAY and array casts, since an array parameter is all such a store needs. Not checked, on purpose, and listed in sqlite-rewrite.md's known limits: a store into an array known only as a Cursor[] or Object[] (failing those would fail ordinary apps, though such an array can be an AbstractCursor[] at run time), a store whose array type differs between the paths that merge before it, and values loaded from arrays. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 9 +- .../gradle/sqlite/SqliteRewriter.kt | 52 +++++++-- .../gradle/sqlite/SqliteRewriterTest.kt | 101 ++++++++++++++++++ 3 files changed, 151 insertions(+), 11 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index c0f2744631..72636ee26b 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -72,7 +72,9 @@ cannot load, so the transform runs only on projects that opted in. Commenting th (requery's cursors extend its own copies of the first two, and implement only `android.database.Cursor`). The same conversion without a cast fails too: a value declared `SQLiteCursor`, or a subclass, returned, passed, called on, stored in a field, or held in a local as one of those three types (`AbstractCursor up(SQLiteCursor c) - { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. + { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. So does storing one + into an array of those types (`AbstractCursor[] a; a[0] = c;`), which would throw `ArrayStoreException`: the + array must be one on every path to the store, from a parameter, field, call or `new`. A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported when the guard holds on every path to the cast: in `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but @@ -202,6 +204,11 @@ dependency, and runs the script on both APKs. The release must pass. The debug A class, alone or in a type descriptor) logs a warning with class, method and line, in the classes the fail rule covers; names of kept classes such as `SQLiteException`, and longer names that contain a renamed one, such as `xandroid.database.sqlite.SQLiteDatabase`, do not. +- Stores of an SQLite cursor into an array known only as a `Cursor[]` or `Object[]` are allowed on purpose (failing + them would fail ordinary apps), but such an array can be an `AbstractCursor[]` at run time (arrays are covariant), + and a store whose array type is unknown where branches merge is not checked. Both can still throw + `ArrayStoreException`, in release builds too (the rewrite runs in every variant of an opted-in app). Cursors loaded + from arrays are not followed. - The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a cursor that reached the method through a field, a parameter or another call is not seen (the app throws `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 67dfcbe378..74c94e0270 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -186,16 +186,22 @@ object SqliteRewriter { } } - /** A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's. */ + /** + * A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's + * ([renamedCursor]), or, on every path, an array of one of the Android-only cursor types ([androidCursorArray], + * that element type). + */ private class StaticCursorValue( type: Type?, val renamedCursor: Boolean, + val androidCursorArray: String? = null, ) : BasicValue(type) { // as TaintValue: Frame.merge keeps the old value when the merged one equals it override fun equals(other: Any?): Boolean = - other is BasicValue && super.equals(other) && renamedCursor == ((other as? StaticCursorValue)?.renamedCursor ?: false) + other is BasicValue && super.equals(other) && renamedCursor == ((other as? StaticCursorValue)?.renamedCursor ?: false) && + androidCursorArray == (other as? StaticCursorValue)?.androidCursorArray - override fun hashCode(): Int = super.hashCode() * 31 + if (renamedCursor) 1 else 0 + override fun hashCode(): Int = (super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode() } private class ClassRewrite( @@ -758,15 +764,21 @@ object SqliteRewriter { /** A type in a frame or an internal name, when it is one of the Android-only cursor types, or null. */ private fun androidOnlyCursor(entry: Any?): String? = (entry as? String)?.takeIf { it in Rules.ANDROID_ONLY_CURSOR_TYPES } + /** [type]'s element type when it is a one-dimensional array of an Android-only cursor type, or null. */ + private fun androidCursorArray(type: Type?): String? = + if (type != null && type.sort == Type.ARRAY && type.dimensions == 1) androidOnlyCursor(type.elementType) else null + /** Whether [m] names an Android-only cursor type where a value could be converted to it without a cast. */ private fun mayConvertToAndroidCursor(m: MethodNode): Boolean { fun names(desc: String) = Rules.ANDROID_ONLY_CURSOR_TYPES.any { desc.contains("L$it;") } - if (names(Type.getReturnType(m.desc).descriptor)) return true + // the parameters too: an array parameter is all that a store into one needs + if (names(m.desc)) return true return m.instructions.any { insn -> when (insn) { is MethodInsnNode -> insn.owner in Rules.ANDROID_ONLY_CURSOR_TYPES || names(insn.desc) is InvokeDynamicInsnNode -> names(insn.desc) is FieldInsnNode -> names(insn.desc) + is TypeInsnNode -> names(insn.desc) || (insn.opcode == Opcodes.ANEWARRAY && androidOnlyCursor(insn.desc) != null) is FrameNode -> (insn.local.orEmpty() + insn.stack.orEmpty()).any { androidOnlyCursor(it) != null } else -> false } @@ -778,8 +790,11 @@ object SqliteRewriter { * AbstractWindowedCursor, AbstractCursor or CrossProcessCursor without a cast, by the message for each: returned, * passed, called on, stored in a field, or held where a frame declares one of them. javac writes no CHECKCAST * for such an upcast, and requery's SQLiteCursor neither extends those classes nor implements the interface, so - * the renamed class would not verify (or, for the interface, the call would fail). Values stored in or loaded - * from arrays are not followed; storing one into such an array throws ArrayStoreException. + * the renamed class would not verify (or, for the interface, the call would fail). Also an AASTORE of such a value + * into an array that is, on every path to it, one of those types' arrays (from a parameter, field, call or + * ANEWARRAY): it would throw ArrayStoreException. Not checked: stores into a Cursor[] or Object[], allowed on + * purpose although one can be such an array at run time; a store whose array type differs between the paths + * that merge before it; values loaded from arrays, which are not followed. */ fun implicitCursorConversions(m: MethodNode): Map { if (!mayConvertToAndroidCursor(m)) return emptyMap() @@ -787,16 +802,25 @@ object SqliteRewriter { object : BasicInterpreter(Opcodes.ASM9) { override fun newValue(type: Type?): BasicValue? { val v = super.newValue(type) ?: return null - return if (v.isReference) StaticCursorValue(v.type, isRenamedCursorType(type)) else v + return if (v.isReference) StaticCursorValue(v.type, isRenamedCursorType(type), androidCursorArray(type)) else v } override fun merge( value1: BasicValue, value2: BasicValue, ): BasicValue { - val renamed = - (value1 as? StaticCursorValue)?.renamedCursor == true || (value2 as? StaticCursorValue)?.renamedCursor == true - if (renamed && value1.type != null && value1.type == value2.type) return StaticCursorValue(value1.type, true) + val s1 = value1 as? StaticCursorValue + val s2 = value2 as? StaticCursorValue + // BasicInterpreter.merge answers UNINITIALIZED for values that differ in either flag + if ((s1 != null || s2 != null) && value1.type != null && value1.type == value2.type) { + val merged = + StaticCursorValue( + value1.type, + s1?.renamedCursor == true || s2?.renamedCursor == true, + s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray }, + ) + return if (merged == value1) value1 else merged + } return super.merge(value1, value2) } } @@ -815,6 +839,14 @@ object SqliteRewriter { fun renamed(value: BasicValue?) = (value as? StaticCursorValue)?.renamedCursor == true fun fromTop(depth: Int) = if (depth < f.stackSize) f.getStack(f.stackSize - 1 - depth) else null + if (insn.opcode == Opcodes.AASTORE) { + val element = (fromTop(2) as? StaticCursorValue)?.androidCursorArray + if (element != null && renamed(fromTop(0))) { + result[insn] = "an SQLite cursor stored into an array of ${element.replace('/', '.')}; requery's SQLiteCursor " + + "is not one, so the store would throw ArrayStoreException" + } + continue + } val target: String? = when { insn is MethodInsnNode || insn is InvokeDynamicInsnNode -> { diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 276264bba9..55b5fc1a51 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1528,6 +1528,107 @@ class SqliteRewriterTest { assertThat(unverified.message).contains("androidx/sqlite/db/framework/Up") } + @Test + fun `an SQLite cursor stored into an array of an Android cursor class fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Stores", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Stores { + void param(AbstractCursor[] a, SQLiteCursor c) { + a[0] = c; + } + AbstractWindowedCursor[] fresh(SQLiteCursor c) { + AbstractWindowedCursor[] a = new AbstractWindowedCursor[1]; + a[0] = c; + return a; + } + void crossProcess(CrossProcessCursor[] a, SQLiteCursor c) { + Object[] same = a; + same[0] = c; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Stores"]!!, hierarchy) } + assertThat(e.message).contains("'p.Stores'") + assertThat(e.message).contains( + " - param([Landroid/database/AbstractCursor;Landroid/database/sqlite/SQLiteCursor;)V (line 7): an SQLite cursor stored " + + "into an array of android.database.AbstractCursor; requery's SQLiteCursor is not one, so the store would throw ArrayStoreException", + ) + assertThat(e.message).contains( + " - fresh(Landroid/database/sqlite/SQLiteCursor;)[Landroid/database/AbstractWindowedCursor; (line 11): " + + "an SQLite cursor stored into an array of android.database.AbstractWindowedCursor", + ) + // the Object[] local holds the parameter's array, which is a CrossProcessCursor[] on every path + assertThat(e.message).contains( + " - crossProcess([Landroid/database/CrossProcessCursor;Landroid/database/sqlite/SQLiteCursor;)V (line 16): " + + "an SQLite cursor stored into an array of android.database.CrossProcessCursor", + ) + } + + @Test + fun `an SQLite cursor stored into a Cursor or Object array, or another value into an Android cursor array, passes`() { + val classes = + Compiler.compile( + listOf( + src( + "p.StoresFine", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class StoresFine { + void cursors(Cursor[] a, SQLiteCursor c) { + a[0] = c; + } + void objects(Object[] a, SQLiteCursor c) { + a[0] = c; + } + void otherValues(AbstractCursor[] a, MatrixCursor m) { + a[0] = m; + a[1] = null; + } + } + """, + ), + ), + ) + SqliteRewriter.rewrite(classes["p/StoresFine"]!!, hierarchy) + } + + @Test + fun `a store whose array is an Android cursor array on one path only is not checked`() { + val classes = + Compiler.compile( + listOf( + src( + "p.StoresMerged", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class StoresMerged { + void merged(AbstractCursor[] a, Cursor[] k, SQLiteCursor c, boolean b) { + Cursor[] t = b ? a : k; + t[0] = c; + } + } + """, + ), + ), + ) + // a known limit: when b is true, the store throws ArrayStoreException at run time + SqliteRewriter.rewrite(classes["p/StoresMerged"]!!, hierarchy) + } + @Test fun `an instanceof guard counts only when it covers every path to the cast`() { val classes = From db7781c772ac9db806b7266d8f36e68c6589e385 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:42:05 -0800 Subject: [PATCH 123/203] ADFA-7138 Docs: list getWindow() on an unresolvable SQLiteCursor subclass as a known miss getWindow()Landroid/database/CursorWindow; is not in the rule table, so on a SQLiteCursor subclass that the build cannot resolve the call passes the rewrite and fails at run time. Failing every unresolved call that returns a CursorWindow would fail ordinary apps: android's kept AbstractWindowedCursor and CrossProcessCursor declare getWindow too. The known limits now say so. Docs only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 72636ee26b..ab502ab813 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -218,6 +218,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied. - A direct subclass of `SQLiteQueryBuilder` or `SQLiteCursor` that overrides a member requery lacks is not reported. +- On a `SQLiteCursor` subclass whose class the build cannot resolve, `getWindow()` is not detected, and the call fails + at run time: it is not in the rule table, and failing every unresolved call that returns a `CursorWindow` would fail + ordinary apps (android's kept `AbstractWindowedCursor` and `CrossProcessCursor` declare it too). - `instanceof` is not rewritten: `cursor instanceof AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` is silently false for requery's cursors (no build failure), which is what Room's `DBUtil.query` relies on. From 229feb03657ba4dd656fa03232fb5806b91c7d17 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:42:05 -0800 Subject: [PATCH 124/203] ADFA-7138 Say to retry when an SQLite AAR is missing right after Code on the Go starts App init extracts the SQLite debugger and rewrite runtime AARs in the background, so on a fresh install an opted-in build that starts before the first extraction ends finds the AAR missing. The "not found" message only said to remove cogo.sqliteDebugger, which is the wrong advice for that transient case. It now ends: "Remove 'cogo.sqliteDebugger' from gradle.properties to build without it, or retry in a few seconds if Code on the Go has just started." The message that ADFA-7138's Steps to QA quote ("Remove cogo.sqliteDebugger from gradle.properties to build without them") is the runtime-classpath check's, which this does not change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../main/java/com/itsaky/androidide/gradle/SqliteAar.kt | 7 +++++-- .../itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt | 5 +++++ .../itsaky/androidide/gradle/SqliteRewritePluginTest.kt | 5 ++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt index 625f2c997b..73e88d2fad 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/SqliteAar.kt @@ -8,7 +8,9 @@ import java.io.File /** * The AAR that [property] names, for a plugin applied only when `cogo.sqliteDebugger=true`. * Fails the build when the property is unset or the file is missing: the project opted in, and a - * build that quietly drops the feature leaves the user wondering why it does nothing. + * build that quietly drops the feature leaves the user wondering why it does nothing. A missing file + * can be transient: app init extracts the AARs in the background, and a build started right after a + * fresh install can run before the first extraction ends, so the message also says to retry. * * @param aarLabel what the AAR is called in the "not found" message. * @param feature what the user's opt-in turns on, for the "remove the line" advice. @@ -27,7 +29,8 @@ internal fun Project.requireSqliteAar( if (!aar.isFile) { throw GradleException( "$aarLabel not found at '${aar.absolutePath}'. " + - "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it.", + "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it, " + + "or retry in a few seconds if Code on the Go has just started.", ) } return aar diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt index edb4bc1cc1..38c5146d07 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteDebuggerPluginTest.kt @@ -138,5 +138,10 @@ class SqliteDebuggerPluginTest { assertThat(failure).isInstanceOf(UnexpectedBuildResultException::class.java) assertThat(failure!!.message).contains("SQLite debugger AAR not found") + // app init extracts the AAR in the background, so right after a fresh install it can be missing for a while + assertThat(failure.message).contains( + "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it, " + + "or retry in a few seconds if Code on the Go has just started.", + ) } } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt index 93514157a2..141cae889f 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewritePluginTest.kt @@ -97,7 +97,10 @@ class SqliteRewritePluginTest { val message = failureOf { build(dir, ":app:printRuntimeDeps", runtimeAar = File(dir, "absent.aar")) } assertThat(message).contains("SQLite rewrite runtime AAR not found") - assertThat(message).contains("Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties") + assertThat(message).contains( + "Remove '$PROPERTY_SQLITE_DEBUGGER_ENABLED' from gradle.properties to build without it, " + + "or retry in a few seconds if Code on the Go has just started.", + ) } private fun jar( From f556c0c433e6447a5a6cc9fc62020bfed8bbe3a8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 10:42:05 -0800 Subject: [PATCH 125/203] ADFA-7138 Test that the SQLite rewrite tests find requery in a non-default Gradle user home SqliteTestSupportTest pinned only the order in which the Gradle user home is chosen, not the cache scan that uses it. The requery lookup is now a function of the Gradle user home (requeryAar, over gradleCacheFile), and a new test puts the AAR only in a non-default home's module cache, with the default home's cache present but without it, and checks that the scan finds it there, through the test task's property and through GRADLE_USER_HOME. With the scan hard-coded to ~/.gradle again, the test fails. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteTestSupport.kt | 45 ++++++++++++------- .../gradle/sqlite/SqliteTestSupportTest.kt | 17 +++++++ 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt index d41edad4bd..782d613ffd 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupport.kt @@ -39,10 +39,33 @@ internal fun gradleUserHome( userHome: File = File(System.getProperty("user.home")), ): File = property?.takeIf { it.isNotEmpty() }?.let(::File) ?: env?.takeIf { it.isNotEmpty() }?.let(::File) ?: File(userHome, ".gradle") +/** The module cache of [gradleHome]: group/artifact/version//file. */ +internal fun moduleCache(gradleHome: File = gradleUserHome()): File = File(gradleHome, "caches/modules-2/files-2.1") + +/** [file] of [group]:[artifact]:[version] in the module cache of [gradleHome], or null. */ +internal fun gradleCacheFile( + group: String, + artifact: String, + version: String, + file: String, + gradleHome: File = gradleUserHome(), +): File? = + File(moduleCache(gradleHome), "$group/$artifact/$version") + .walkTopDown() + .firstOrNull { it.name == file } + +/** requery's AAR: the file REQUERY_AAR names, else the one in the module cache of [gradleHome], or null. */ +internal fun requeryAar( + env: String? = System.getenv("REQUERY_AAR"), + gradleHome: File = gradleUserHome(), +): File? = + env?.let(::File)?.takeIf { it.isFile } + ?: gradleCacheFile("com.github.requery", "sqlite-android", "3.49.0", "sqlite-android-3.49.0.aar", gradleHome) + /** Jars the tests compile and resolve against. Each lookup skips the test with a message, or fails it on CI. */ internal object TestJars { private val home = File(System.getProperty("user.home")) - private val modules by lazy { File(gradleUserHome(), "caches/modules-2/files-2.1") } + private val modules by lazy { moduleCache() } val androidJar: File by lazy { val sdkRoots = @@ -65,16 +88,6 @@ internal object TestJars { jar!! } - private fun gradleCacheAar( - group: String, - artifact: String, - version: String, - file: String, - ): File? = - File(modules, "$group/$artifact/$version") - .walkTopDown() - .firstOrNull { it.name == file } - private fun classesJarOf( aar: File, name: String, @@ -88,21 +101,19 @@ internal object TestJars { } val requeryJar: File by lazy { - val aar = - System.getenv("REQUERY_AAR")?.let(::File)?.takeIf { it.isFile } - ?: gradleCacheAar("com.github.requery", "sqlite-android", "3.49.0", "sqlite-android-3.49.0.aar") + val aar = requeryAar() requireEnvironment(aar != null, "requery 3.49.0 AAR not found: set REQUERY_AAR or resolve it into the Gradle cache") classesJarOf(aar!!, "requery") } val androidxSqliteJar: File by lazy { - val aar = gradleCacheAar("androidx.sqlite", "sqlite-android", "2.6.2", "sqlite.aar") + val aar = gradleCacheFile("androidx.sqlite", "sqlite-android", "2.6.2", "sqlite.aar") requireEnvironment(aar != null, "androidx.sqlite 2.6.2 AAR not found in the Gradle cache") classesJarOf(aar!!, "androidx-sqlite") } val androidxSqliteFrameworkJar: File by lazy { - val aar = gradleCacheAar("androidx.sqlite", "sqlite-framework-android", "2.6.2", "sqlite-framework.aar") + val aar = gradleCacheFile("androidx.sqlite", "sqlite-framework-android", "2.6.2", "sqlite-framework.aar") requireEnvironment(aar != null, "androidx.sqlite framework 2.6.2 AAR not found in the Gradle cache") classesJarOf(aar!!, "androidx-sqlite-framework") } @@ -116,7 +127,7 @@ internal object TestJars { } val androidxCoreJar: File by lazy { - val aar = gradleCacheAar("androidx.core", "core", "1.13.1", "core-1.13.1.aar") + val aar = gradleCacheFile("androidx.core", "core", "1.13.1", "core-1.13.1.aar") requireEnvironment(aar != null, "androidx.core 1.13.1 AAR not found in the Gradle cache") classesJarOf(aar!!, "androidx-core") } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt index 84f83ebcb5..e3290bc65c 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteTestSupportTest.kt @@ -26,6 +26,23 @@ class SqliteTestSupportTest { assertThat(gradleUserHome(null, null, home)).isEqualTo(File(home, ".gradle")) } + @Test + fun `the requery AAR is found when only a Gradle user home other than the default one has it`( + @TempDir dir: File, + ) { + val home = File(dir, "home") + // the default home's cache exists, without requery + File(home, ".gradle/caches/modules-2/files-2.1").mkdirs() + val active = File(dir, "active-gradle-home") + val aar = File(active, "caches/modules-2/files-2.1/com.github.requery/sqlite-android/3.49.0/0123abcd/sqlite-android-3.49.0.aar") + aar.parentFile.mkdirs() + aar.writeText("aar") + + assertThat(requeryAar(env = null, gradleHome = gradleUserHome(active.path, null, home))).isEqualTo(aar) + // GRADLE_USER_HOME, as when the tests run from an IDE + assertThat(requeryAar(env = null, gradleHome = gradleUserHome(null, active.path, home))).isEqualTo(aar) + } + @Test fun `a constructor resolves in the named class only, while methods are still inherited`() { val classes = From 85c3068a69a73ea941e6f00f282be991413fab45 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 02:19:40 +0000 Subject: [PATCH 126/203] ADFA-7138: Warn, not fail, for an unresolvable owner unless the member names an SQLite type Libraries reference optional classes the app does not ship, so a bare name+descriptor match (isStrict()Z, isString(I)Z) on an unresolvable owner failed ordinary app builds with an SQLite message. It now warns; it still fails when the descriptor names an SQLite, requery, Cursor, CursorWindow, CancellationSignal or DatabaseErrorHandler type. Tests: a warn-only case (com.unknown.Row.isString), a still-fails case (SQLite descriptor), and the existing unresolved-owner test now expects isStrict()Z to warn. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- gradle-plugin/docs/sqlite-rewrite.md | 7 +- .../gradle/sqlite/SqliteRewriteRules.kt | 8 +- .../gradle/sqlite/SqliteRewriter.kt | 24 ++++-- .../gradle/sqlite/SqliteRewriterTest.kt | 74 +++++++++++++++++-- 4 files changed, 99 insertions(+), 14 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index ab502ab813..58aafa2795 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -92,8 +92,11 @@ cannot load, so the transform runs only on projects that opted in. Commenting th it. Retyping the override would mean turning requery's signal back into Android's inside its body. Likewise a call on an owner that AGP's class loader cannot resolve fails when its name and descriptor are those of a member a rule above changes or rejects in a renamed class another class can extend (not the final - `SQLiteDatabase`, `SQLiteQuery` or `SQLiteStatement`): the owner may inherit that member, and its renamed - ancestors are unknown. + `SQLiteDatabase`, `SQLiteQuery` or `SQLiteStatement`) and the descriptor names an SQLite-related type (any + `android.database.sqlite` or requery type, `Cursor`, `CursorWindow`, `CancellationSignal`, + `DatabaseErrorHandler`): the owner may inherit that member, and its renamed ancestors are unknown. When the + descriptor names none (`isStrict()Z`, `isString(I)Z`), the call only logs a warning: libraries reference optional + classes the app does not ship, and failing every app build over them would be worse than missing the case. - Method references: a handle in an invokedynamic (`db::rawQuery`, `ctx::deleteDatabase`) that any rule above would change, redirect or reject fails the build, naming class, method and line, with the advice to write a lambda (its body is an ordinary call, which the rules handle). The rules are not applied to the diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index e378bd03f5..2cd4d0ef80 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -247,7 +247,9 @@ internal object SqliteRewriteRules { /** * Name plus descriptor of each member that a rule changes or rejects and that another class can inherit (not a * constructor, nor a member of a final class), mapped to the renamed class that declares it. A class the build - * cannot resolve may inherit one of these, so a call that matches one exactly cannot be checked. + * cannot resolve may inherit one of these, so a call that matches one exactly cannot be checked. Such a call + * fails the build only when its descriptor names an SQLite-related type ([SQLITE_DESCRIPTOR_TOKENS]); otherwise + * it is a warning, since a bare name and descriptor like isStrict()Z is common in unrelated classes. */ val INHERITABLE_RULE_MEMBERS: Map = buildMap { @@ -299,6 +301,10 @@ internal object SqliteRewriteRules { /** How a renamed class appears in a descriptor. */ val RENAMED_DESCRIPTOR_TOKENS: List = RENAMES.keys.map { "L$it;" } + /** What marks a descriptor as SQLite-related: a class in either package, or one of the Cursor and signal types. */ + val SQLITE_DESCRIPTOR_TOKENS: List = + listOf("L$SQLITE_PKG", "L$REQUERY_DB_PKG", CUR, "L$CURSOR_WINDOW;", "L$ANDROID_SIGNAL;", "L$CORE_SIGNAL;", "L$ERROR_HANDLER;") + val CONTEXT_FAMILY: Set = setOf( CONTEXT, diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 74c94e0270..5b2d369445 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -211,6 +211,7 @@ object SqliteRewriter { val warn: (String) -> Unit, ) { val violations = linkedSetOf() + private val warned = hashSetOf() fun run() { if (policy.fail) { @@ -506,10 +507,12 @@ object SqliteRewriter { } /** - * Why `owner.name desc` cannot be checked, or null: [owner] cannot be resolved, so its renamed ancestors are - * unknown, and the member has the name and descriptor of one a rule changes or rejects in a renamed class - * another class can extend. Like a Context database method on an unresolved owner, this fails under the - * full policy rather than pass a call that may break at run time. + * Why `owner.name desc` cannot be checked and must fail the build, or null: [owner] cannot be resolved, so its + * renamed ancestors are unknown, the member has the name and descriptor of one a rule changes or rejects in a + * renamed class another class can extend, and the descriptor names an SQLite-related type. Like a Context + * database method on an unresolved owner, this fails under the full policy rather than pass a call that may + * break at run time. A match on name and descriptor alone (isStrict()Z, isString(I)Z) is only a warning: + * libraries reference optional classes the app does not ship, and most of them are not SQLite classes. */ fun unresolvedOwner( owner: String, @@ -521,8 +524,17 @@ object SqliteRewriter { return null } if (superTypes(owner) != null) return null - return "${owner.replace('/', '.')} cannot be resolved, so the rewrite cannot tell whether its $name$desc is " + - "${simple(declaring)}.$name, which it changes or rejects" + val cannot = "${owner.replace('/', '.')} cannot be resolved, so the rewrite cannot tell whether its $name$desc is " + if (Rules.SQLITE_DESCRIPTOR_TOKENS.any { desc.contains(it) }) { + return cannot + "${simple(declaring)}.$name, which it changes or rejects" + } + if (policy.fail) { + val message = + "${cn.name.replace('/', '.')}: $cannot${simple(declaring)}.$name, which it changes or rejects; " + + "the call is left as it is, and fails at run time if the owner extends that class" + if (warned.add(message)) warn(message) + } + return null } fun typeInsn( diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 55b5fc1a51..b1bab15fa5 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1467,16 +1467,80 @@ class SqliteRewriterTest { ), ), ) - val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/UsesLost"]!!, hierarchy) } + val warnings = mutableListOf() + val bytes = classes["p/UsesLost"]!! + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(bytes, hierarchy, warn = warnings::add) } val unresolved = e.message!! .lines() .filter { "p.Lost cannot be resolved" in it } .map { it.substringAfter("whether its ").substringBefore(" is ") } - // SQLiteDatabase is final, so no class inherits its rawQuery, and no rule has a delete(String) - assertThat(unresolved).hasSize(2) - assertThat(unresolved[0]).isEqualTo("isStrict()Z") - assertThat(unresolved[1]).startsWith("query(Landroid/database/sqlite/SQLiteDatabase;") + // SQLiteDatabase is final, so no class inherits its rawQuery, and no rule has a delete(String). + // isStrict()Z names no SQLite type, so it only warns; the query descriptor names SQLiteDatabase, so it fails. + assertThat(unresolved).hasSize(1) + assertThat(unresolved[0]).startsWith("query(Landroid/database/sqlite/SQLiteDatabase;") + assertThat(warnings).hasSize(1) + assertThat(warnings.single()).contains("p.Lost cannot be resolved") + assertThat(warnings.single()).contains("isStrict()Z") + } + + @Test + fun `an unresolvable owner whose member names no SQLite type only warns`() { + val classes = + Compiler.compile( + listOf( + src( + "p.UsesRow", + """ + package p; + public class UsesRow { + boolean go(com.unknown.Row r) { return r.isString(0); } + } + """, + ), + // left out of the hierarchy, as an optional class the app does not ship is + src("com.unknown.Row", "package com.unknown; public class Row { public boolean isString(int i) { return false; } }"), + ), + ) + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/UsesRow"]!!, hierarchy, warn = warnings::add) + assertThat(warnings).hasSize(1) + assertThat(warnings.single()).contains("p.UsesRow") + assertThat(warnings.single()).contains("com.unknown.Row cannot be resolved") + assertThat(warnings.single()).contains("isString(I)Z") + } + + @Test + fun `an unresolvable owner whose member names an SQLite type still fails`() { + val classes = + Compiler.compile( + listOf( + src( + "p.UsesQb", + """ + package p; + import android.database.sqlite.*; + public class UsesQb { + void go(com.unknown.Qb q, SQLiteDatabase db, String[] a, android.os.CancellationSignal s) { + q.query(db, a, "w", a, null, null, null, "1", s); + } + } + """, + ), + src( + "com.unknown.Qb", + """ + package com.unknown; + public class Qb extends android.database.sqlite.SQLiteQueryBuilder {} + """, + ), + ), + ) + val warnings = mutableListOf() + val bytes = classes["p/UsesQb"]!! + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(bytes, hierarchy, warn = warnings::add) } + assertThat(e.message).contains("com.unknown.Qb cannot be resolved") + assertThat(warnings).isEmpty() } @Test From d392bf6417062bc294441ff03dacf9db40fc01ed Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 18:52:27 -0800 Subject: [PATCH 127/203] ADFA-7138 Fix the rewriter tests' comments about getUniqueId after the unresolved-owner change "a call whose name a rule lists ... still looks the owner up" wrapped the rewrite in a try/catch because getUniqueId()I on the unresolvable p.Mine failed the build. Since 85c3068a6 that call only warns (its descriptor names no SQLite type), so the catch caught nothing and its comment was wrong. The try/catch is gone, which also makes the test fail if the call fails the build again. "hierarchy lookups are made once per owner ..." keeps its try/catch: its getUniqueId is on SQLiteStatement, a renamed class that resolves, and still fails the build through the missing-member rule. Its comment now says so. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriterTest.kt | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index b1bab15fa5..3dc4fb995f 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -502,7 +502,7 @@ class SqliteRewriterTest { try { SqliteRewriter.rewrite(classes["p/Chatty"]!!, counting) } catch (e: SqliteRewriteException) { - // getUniqueId is reported, which is not what this test is about + // SQLiteStatement.getUniqueId fails the build (requery lacks it), which is not what this test is about } assertThat(asked.filter { it.startsWith("java/") || it.startsWith("android/") }).isEmpty() assertThat(asked.groupingBy { it }.eachCount().filterValues { it > 1 }).isEmpty() @@ -535,17 +535,14 @@ class SqliteRewriterTest { ), ) val asked = mutableListOf() - try { - SqliteRewriter.rewrite( - classes["p/Named"]!!, - ClassHierarchy { name -> - asked += name - null - }, - ) - } catch (e: SqliteRewriteException) { - // getUniqueId on an owner that cannot be resolved is reported, which is not what this test is about - } + // getUniqueId()I names no SQLite type, so on an owner that cannot be resolved it only warns + SqliteRewriter.rewrite( + classes["p/Named"]!!, + ClassHierarchy { name -> + asked += name + null + }, + ) assertThat(asked).containsExactly("p/Mine", "p/Other") } From 56e26ffd8542b1b034df07fb9aa5eedb4b0c198e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 18:52:47 -0800 Subject: [PATCH 128/203] ADFA-7138 Docs: say which rule-table matches on an unresolvable class fail and which warn The known-limits line about getWindow() on an unresolvable SQLiteCursor subclass now also states the split 85c3068a6 made: on a class the build cannot resolve, a call that matches the rule table fails the build only when its descriptor names an SQLite-related type, and any other match (isString(I)Z, isStrict()Z) logs a warning, is left as it is, and fails at run time if the class does extend the renamed class. Docs only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 58aafa2795..6061dc6f6b 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -223,7 +223,10 @@ dependency, and runs the script on both APKs. The release must pass. The debug A reported. - On a `SQLiteCursor` subclass whose class the build cannot resolve, `getWindow()` is not detected, and the call fails at run time: it is not in the rule table, and failing every unresolved call that returns a `CursorWindow` would fail - ordinary apps (android's kept `AbstractWindowedCursor` and `CrossProcessCursor` declare it too). + ordinary apps (android's kept `AbstractWindowedCursor` and `CrossProcessCursor` declare it too). On any class the + build cannot resolve, a call that matches the rule table fails the build only when its descriptor names an + SQLite-related type (see Rules); any other match, such as `isString(I)Z` or `isStrict()Z`, logs a warning and is left + as it is, and fails at run time if the class does extend the renamed class. - `instanceof` is not rewritten: `cursor instanceof AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` is silently false for requery's cursors (no build failure), which is what Room's `DBUtil.query` relies on. From 36bdf9639a5970ed8098e56aa4edee03653dec6f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 18:53:46 -0800 Subject: [PATCH 129/203] ADFA-7138 Pin the SQLite descriptor tokens and which unresolved-owner matches fail 85c3068a6 fails a rule-table match on an unresolvable owner only when the descriptor holds one of SQLITE_DESCRIPTOR_TOKENS. The test pins the tokens as descriptor forms (a package prefix after L, or a full L...; type), and the split they make of the 34 inheritable table members: 8 fail (setWindow, mWindow, setOpenParams, getCursorFactory, insert, update, delete, and query with a signal) and 26 warn, among them isString(I)Z, isStrict()Z and getUniqueId()I. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriteRulesTest.kt | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt index e9e416aa6f..d8eb3a6042 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.gradle.sqlite +import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.jupiter.api.Test import org.objectweb.asm.Type @@ -17,4 +18,35 @@ class SqliteRewriteRulesTest { } } } + + @Test + fun `the SQLite descriptor tokens, and which table matches fail on an unresolvable owner`() { + assertThat(SqliteRewriteRules.SQLITE_DESCRIPTOR_TOKENS) + .containsExactly( + "Landroid/database/sqlite/", + "Lio/requery/android/database/", + "Landroid/database/Cursor;", + "Landroid/database/CursorWindow;", + "Landroid/os/CancellationSignal;", + "Landroidx/core/os/CancellationSignal;", + "Landroid/database/DatabaseErrorHandler;", + ).inOrder() + val tokens = SqliteRewriteRules.SQLITE_DESCRIPTOR_TOKENS + // a key is a name plus a descriptor, and no name holds a token + val (failing, warned) = SqliteRewriteRules.INHERITABLE_RULE_MEMBERS.keys.partition { key -> tokens.any { key.contains(it) } } + + assertThat(failing.map { it.substringBefore('(').removeSuffix("Landroid/database/CursorWindow;") }) + .containsExactly("setWindow", "mWindow", "setOpenParams", "getCursorFactory", "insert", "update", "delete", "query") + assertThat(warned).hasSize(26) + assertThat(warned).containsAtLeast( + "isDistinct()Z", + "isStrict()Z", + "getUniqueId()I", + "isString(I)Z", + "isLong(I)Z", + "isFloat(I)Z", + "isBlob(I)Z", + "getProjectionMap()Ljava/util/Map;", + ) + } } From fbd445136a815b8f6428d36f93898ec700ee0733 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 18:53:46 -0800 Subject: [PATCH 130/203] ADFA-7138 Check in a real AGP build that the unresolved-owner warning reaches the log The rewriter's default warn is the Gradle logger, which the unit tests replace. SqliteRewriteTransformTest's library AAR now also holds a call to com.unknown.Row.isString(I)Z, with Row left out of the AAR as an optional class a library references and the app does not ship. The same TestKit build that already runs AGP's transform over the AAR now checks that its output carries the warning, and that the build still succeeds. No extra build. Test code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/SqliteRewriteTransformTest.kt | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt index 08d5583ff3..3d3ba57261 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt @@ -84,14 +84,22 @@ class SqliteRewriteTransformTest { ) { val daoName = "Dao${System.nanoTime()}" val library = - Compiler.compile( - listOf( - JavaSource( - "x.lib.$daoName", - "package x.lib; public class $daoName { public Object q(android.database.sqlite.SQLiteDatabase db, String[] a) { return db.rawQuery(\"select 1\", a); } }", + Compiler + .compile( + listOf( + JavaSource( + "x.lib.$daoName", + "package x.lib; public class $daoName { public Object q(android.database.sqlite.SQLiteDatabase db, String[] a) { return db.rawQuery(\"select 1\", a); } " + + "public boolean probe(com.unknown.Row r) { return r.isString(0); } }", + ), + JavaSource( + "com.unknown.Row", + "package com.unknown; public class Row { public boolean isString(int column) { return false; } }", + ), ), - ), - ) + ) + // left out of the AAR, as an optional class a library references and the app does not ship + .filterKeys { it != "com/unknown/Row" } val helperSource = FileProvider .projectRoot() @@ -155,6 +163,13 @@ class SqliteRewriteTransformTest { assertThat(result.task(":app:checkDemoDebugSqliteRewriteClasspath")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) assertThat(result.task(":app:transformDemoDebugClassesWithAsm")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) + // isString(I)Z names no SQLite type, so the owner that cannot be resolved is only reported through Gradle's logger + val warning = + "x.lib.$daoName: com.unknown.Row cannot be resolved, so the rewrite cannot tell whether its isString(I)Z is " + + "SQLiteCursor.isString, which it changes or rejects; the call is left as it is, and fails at run time if the owner " + + "extends that class" + assertThat(result.output).contains(warning) + println("WARNING LINE: " + result.output.lines().first { warning in it }) // the unmodified copy from extracting the AAR is in the cache too; the rewritten one is the other val daos = transformedJarsWith("x/lib/$daoName.class").map { bytes -> ClassNode().also { ClassReader(bytes).accept(it, 0) } } From 6e16bdb7c20af833fef9da85819275fc6fa3a7e2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 21:14:40 -0800 Subject: [PATCH 131/203] ADFA-7138 Hold CancelForwarders weakly so a dropped signal's forwarder is not kept SqliteRewriteRuntime.FORWARDERS mapped each Android CancellationSignal weakly to its CancelForwarder, but a WeakHashMap keeps the value of a cleared key until the next call on the map. So each signal the app dropped left its forwarder (72 B) reachable from the static map until the next conversion. LeakCanary and a heap count on the Note 20 (C6h probe) showed both forwarders of two dropped signals retained this way after the activity was destroyed. The value is now a WeakReference. While the signal lives, its own listener field keeps the forwarder alive; a cleared reference means a new forwarder. One accepted change: a caller that sets its own listener after a query lets that forwarder go, so a later conversion starts a new one and the queries from before the caller's listener no longer stop with the signal (they had stopped doing so when the caller replaced the listener). Tests in SqliteRewriteRuntimeTest: a dropped signal's forwarder clears after GC (fails without the fix: the stale entry keeps it), a live signal keeps its forwarder through GC and still cancels, and a signal whose forwarder was collected gets a working new one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 6 +- .../gradle/sqlite/SqliteRewriteRuntimeTest.kt | 72 +++++++++++++++++++ .../sqliterewrite/SqliteRewriteRuntime.java | 14 ++-- 3 files changed, 86 insertions(+), 6 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 6061dc6f6b..703b2ccb46 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -239,6 +239,10 @@ dependency, and runs the script on both APKs. The release must pass. The debug A androidx.core.os.OperationCanceledException e)`, which works with the SQLite debugger on and off. - Android's `CancellationSignal` holds one listener: the conversion replaces any listener the caller set. Each query gets its own androidx.core signal, and cancelling the Android signal cancels every one still in use, so - two lazy queries that share it both stop (requery keeps a query's signal for its cursor's later reads). + two lazy queries that share it both stop (requery keeps a query's signal for its cursor's later reads). The + runtime's forwarder is held only as the Android signal's listener (`SqliteRewriteRuntime.FORWARDERS` holds signals + and forwarders weakly), so nothing of a signal the app dropped is kept: a strong value outlived its key until the + map's next call. A caller that sets its own listener after a query lets that forwarder go: the next query on the + signal gets a new one, and queries from before the caller's listener no longer stop with the signal. - Which `SQLiteException` subclass requery throws for an error code (for example `SQLiteConstraintException`, which Room catches) is decided by its native layer; this rewrite does not change it and the survey did not check it. diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt index 02324e9e6c..fec4064e9b 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import com.itsaky.androidide.utils.FileProvider import org.junit.jupiter.api.Test +import java.lang.ref.WeakReference /** * The runtime helper's functions that need no device, run on the JVM from its bytecode compiled against android.jar, @@ -42,6 +43,41 @@ class SqliteRewriteRuntimeTest { private fun isCanceled(signal: Any) = signal.javaClass.getMethod("isCanceled").invoke(signal) as Boolean + /** The signal's listener, read from the signal itself: a call on FORWARDERS would expunge its stale entries. */ + private fun listenerOf(signal: Any): Any? = androidSignal.getDeclaredField("listener").apply { isAccessible = true }.get(signal) + + private fun setListener( + signal: Any, + listener: Any?, + ) { + val type = loader.loadClass("android.os.CancellationSignal\$OnCancelListener") + androidSignal.getMethod("setOnCancelListener", type).invoke(signal, listener) + } + + /** Converts a signal that nothing else holds, in its own frame, and returns a weak reference to its forwarder. */ + private fun forwarderOfDroppedSignal(): WeakReference { + val signal = newAndroidSignal() + convert(signal) + return WeakReference(listenerOf(signal)!!) + } + + /** + * Requests GC until [ref] clears, at most [rounds] times. Timing-dependent only in the passing direction: HotSpot's + * System.gc() is a full collection and clears a weak reference in the first round, and the bound only ends a run in + * which it never clears. Nothing calls FORWARDERS meanwhile, as any call on it expunges the stale entries. + */ + private fun clearedAfterGc( + ref: WeakReference<*>, + rounds: Int = 50, + ): Boolean { + repeat(rounds) { + if (ref.get() == null) return true + System.gc() + Thread.sleep(20) + } + return ref.get() == null + } + private fun translate(flags: Int) = runtime.getMethod("translateOpenFlags", Int::class.javaPrimitiveType).invoke(null, flags) as Int private val readOnly = 1 @@ -89,6 +125,42 @@ class SqliteRewriteRuntimeTest { assertThat(isCanceled(convert(signal))).isTrue() } + @Test + fun `the forwarder of a signal the app dropped is not kept`() { + val forwarder = forwarderOfDroppedSignal() + + assertWithMessage("CancelForwarder of a dropped signal, kept by the value of FORWARDERS' stale entry") + .that(clearedAfterGc(forwarder)) + .isTrue() + } + + @Test + fun `a live signal keeps its forwarder through a GC and still cancels its queries`() { + val signal = newAndroidSignal() + val converted = convert(signal) + val forwarder = WeakReference(listenerOf(signal)) + + assertWithMessage("forwarder collected while its signal lives").that(clearedAfterGc(forwarder, rounds = 3)).isFalse() + cancel(signal) + + assertThat(isCanceled(converted)).isTrue() + } + + @Test + fun `a signal whose forwarder was collected gets a new one`() { + val signal = newAndroidSignal() + convert(signal) + val first = WeakReference(listenerOf(signal)) + // the caller sets its own listener, so nothing holds the first forwarder any more + setListener(signal, null) + assertWithMessage("first forwarder collected").that(clearedAfterGc(first)).isTrue() + + val converted = convert(signal) + cancel(signal) + + assertWithMessage("a query converted after the forwarder was collected").that(isCanceled(converted)).isTrue() + } + private companion object { /** Android's listener rules: one listener, a new one runs at once on a cancelled signal, the same one does not. */ val ANDROID_SIGNAL = diff --git a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java index 9fc44c855a..7917a9c3bb 100644 --- a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java +++ b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java @@ -46,8 +46,10 @@ public final class SqliteRewriteRuntime { private static final int CONTEXT_MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x8; - /** The listener each Android signal forwards cancellation through; weak keys, so a signal the app dropped goes. */ - private static final Map FORWARDERS = new WeakHashMap<>(); + /** + * The listener each Android signal forwards cancellation through. Weak keys, so a signal the app dropped goes, and weak values: a WeakHashMap keeps the value of a cleared key until a later call on the map, so a strong value kept a dropped signal's forwarder alive until the next conversion. The signal's own listener field keeps its forwarder alive while the signal lives. + */ + private static final Map> FORWARDERS = new WeakHashMap<>(); /** * Same as Context.deleteDatabase, which also returns false on any exception. requery's deleteDatabase removes the -journal, -wal, -shm and -mj files next to the file, like Android's. @@ -140,7 +142,7 @@ public static String stringForQuery(SQLiteStatement prog, String[] selectionArgs } /** - * Android's signal for requery's. Each call returns a new requery signal, and cancelling Android's cancels every one of them still in use: requery keeps a query's signal for the cursor's later reads, so two lazy queries that share an Android signal must both stop. Android's signal holds one listener, so this replaces any listener the caller set on it (Android's setOnCancelListener documents that it replaces the previous one). + * Android's signal for requery's. Each call returns a new requery signal, and cancelling Android's cancels every one of them still in use: requery keeps a query's signal for the cursor's later reads, so two lazy queries that share an Android signal must both stop. Android's signal holds one listener, so this replaces any listener the caller set on it (Android's setOnCancelListener documents that it replaces the previous one). The forwarder lives only as long as it is that listener: if the caller sets its own listener after a query, the forwarder can be collected, the next call starts a new one, and queries converted before the caller's listener no longer stop with the signal. */ public static androidx.core.os.CancellationSignal toCancellationSignal( CancellationSignal signal) { @@ -150,12 +152,14 @@ public static androidx.core.os.CancellationSignal toCancellationSignal( final androidx.core.os.CancellationSignal converted = new androidx.core.os.CancellationSignal(); CancelForwarder forwarder; synchronized (FORWARDERS) { - forwarder = FORWARDERS.get(signal); + WeakReference ref = FORWARDERS.get(signal); + forwarder = ref == null ? null : ref.get(); if (forwarder == null) { forwarder = new CancelForwarder(); - FORWARDERS.put(signal, forwarder); + FORWARDERS.put(signal, new WeakReference<>(forwarder)); } } + // the local keeps the new forwarder alive until setOnCancelListener stores it in the signal forwarder.add(converted); signal.setOnCancelListener(forwarder); // setOnCancelListener does not call a listener that is already set, so a signal cancelled before this call From b0ceebe3e6d672255f72a5c6721994e70d758391 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 22:04:40 -0800 Subject: [PATCH 132/203] ADFA-7138 Warn, not fail, for an unresolvable owner's setWindow(CursorWindow) and mWindow, and say where android.database.CursorWindow is not an SQLite type. It carries every ContentProvider cursor across processes, and Android's kept AbstractWindowedCursor declares both setWindow(CursorWindow) and mWindow, so a library's own windowed cursor on an owner the build cannot resolve matched SQLiteCursor's two members and failed the build. CursorWindow leaves SQLITE_DESCRIPTOR_TOKENS, so those two matches now only warn: of the 34 inheritable rule members, 6 fail on an unresolvable owner and 28 warn. Cursor stays a token; it changes no outcome today. The unresolved-owner warning named only the class, so a user could not find the call. It now starts with class, method and line, formatted by the same site() the string-constant warnings use, and says "field access" instead of "call" for mWindow, the first field that reaches the warning. It is still logged once per message, and the message now holds the method and line: two calls on one line warn once, two lines warn twice. Tests: an unresolvable windowed cursor's setWindow and mWindow only warn; the warning names method and line, once per place; the pinned tokens and the 6/28 split; the TestKit log line. Docs: CursorWindow leaves the list of types that make a match fail, and the known limit on getWindow() says setWindow and mWindow now only warn. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 23 +++--- .../gradle/sqlite/SqliteRewriteRules.kt | 12 +++- .../gradle/sqlite/SqliteRewriter.kt | 47 +++++++----- .../gradle/SqliteRewriteTransformTest.kt | 5 +- .../gradle/sqlite/SqliteRewriteRulesTest.kt | 10 +-- .../gradle/sqlite/SqliteRewriterTest.kt | 72 +++++++++++++++++++ 6 files changed, 135 insertions(+), 34 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 703b2ccb46..c44aa062fe 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -93,10 +93,13 @@ cannot load, so the transform runs only on projects that opted in. Commenting th Likewise a call on an owner that AGP's class loader cannot resolve fails when its name and descriptor are those of a member a rule above changes or rejects in a renamed class another class can extend (not the final `SQLiteDatabase`, `SQLiteQuery` or `SQLiteStatement`) and the descriptor names an SQLite-related type (any - `android.database.sqlite` or requery type, `Cursor`, `CursorWindow`, `CancellationSignal`, - `DatabaseErrorHandler`): the owner may inherit that member, and its renamed ancestors are unknown. When the - descriptor names none (`isStrict()Z`, `isString(I)Z`), the call only logs a warning: libraries reference optional - classes the app does not ship, and failing every app build over them would be worse than missing the case. + `android.database.sqlite` or requery type, `Cursor`, `CancellationSignal`, `DatabaseErrorHandler`): the owner may + inherit that member, and its renamed ancestors are unknown. When the descriptor names none (`isStrict()Z`, + `isString(I)Z`, `setWindow(CursorWindow)`, `mWindow`), the call or field access only logs a warning with class, + method and line: libraries reference optional classes the app does not ship, and failing every app build over them + would be worse than missing the case. `CursorWindow` is not an SQLite type: it carries every ContentProvider cursor + across processes, and android's kept `AbstractWindowedCursor` declares `setWindow(CursorWindow)` and `mWindow` too, + so a library's own windowed cursor matches them. - Method references: a handle in an invokedynamic (`db::rawQuery`, `ctx::deleteDatabase`) that any rule above would change, redirect or reject fails the build, naming class, method and line, with the advice to write a lambda (its body is an ordinary call, which the rules handle). The rules are not applied to the @@ -221,12 +224,14 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied. - A direct subclass of `SQLiteQueryBuilder` or `SQLiteCursor` that overrides a member requery lacks is not reported. -- On a `SQLiteCursor` subclass whose class the build cannot resolve, `getWindow()` is not detected, and the call fails - at run time: it is not in the rule table, and failing every unresolved call that returns a `CursorWindow` would fail - ordinary apps (android's kept `AbstractWindowedCursor` and `CrossProcessCursor` declare it too). On any class the +- On a `SQLiteCursor` subclass whose class the build cannot resolve, `getWindow()` is not detected, and + `setWindow(CursorWindow)` and `mWindow` only log a warning; each fails at run time. `getWindow()` is not in the rule + table, and failing every unresolved member that names a `CursorWindow` would fail ordinary apps (android's kept + `AbstractWindowedCursor` declares all three, and `CrossProcessCursor` declares `getWindow()`). On any class the build cannot resolve, a call that matches the rule table fails the build only when its descriptor names an - SQLite-related type (see Rules); any other match, such as `isString(I)Z` or `isStrict()Z`, logs a warning and is left - as it is, and fails at run time if the class does extend the renamed class. + SQLite-related type (see Rules); any other match, such as `isString(I)Z`, `isStrict()Z` or `setWindow(CursorWindow)`, + logs a warning with class, method and line and is left as it is, and fails at run time if the class does extend the + renamed class. - `instanceof` is not rewritten: `cursor instanceof AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` is silently false for requery's cursors (no build failure), which is what Room's `DBUtil.query` relies on. diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index 2cd4d0ef80..d06adc1c59 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -249,7 +249,8 @@ internal object SqliteRewriteRules { * constructor, nor a member of a final class), mapped to the renamed class that declares it. A class the build * cannot resolve may inherit one of these, so a call that matches one exactly cannot be checked. Such a call * fails the build only when its descriptor names an SQLite-related type ([SQLITE_DESCRIPTOR_TOKENS]); otherwise - * it is a warning, since a bare name and descriptor like isStrict()Z is common in unrelated classes. + * it is a warning, since a bare name and descriptor like isStrict()Z, or setWindow(CursorWindow) on any windowed + * cursor, is common in unrelated classes. */ val INHERITABLE_RULE_MEMBERS: Map = buildMap { @@ -301,9 +302,14 @@ internal object SqliteRewriteRules { /** How a renamed class appears in a descriptor. */ val RENAMED_DESCRIPTOR_TOKENS: List = RENAMES.keys.map { "L$it;" } - /** What marks a descriptor as SQLite-related: a class in either package, or one of the Cursor and signal types. */ + /** + * What marks a descriptor as SQLite-related: a class in either package, Cursor, the signals, or the error handler. + * Not android.database.CursorWindow, which is not an SQLite type: it carries every ContentProvider cursor across + * processes, and android's kept AbstractWindowedCursor declares setWindow(CursorWindow) and mWindow too, so a + * library's own windowed cursor on an owner the build cannot resolve would match SQLiteCursor's. + */ val SQLITE_DESCRIPTOR_TOKENS: List = - listOf("L$SQLITE_PKG", "L$REQUERY_DB_PKG", CUR, "L$CURSOR_WINDOW;", "L$ANDROID_SIGNAL;", "L$CORE_SIGNAL;", "L$ERROR_HANDLER;") + listOf("L$SQLITE_PKG", "L$REQUERY_DB_PKG", CUR, "L$ANDROID_SIGNAL;", "L$CORE_SIGNAL;", "L$ERROR_HANDLER;") val CONTEXT_FAMILY: Set = setOf( diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 5b2d369445..2baf2d0ddd 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -440,10 +440,9 @@ object SqliteRewriter { "SQL text uses COLLATE UNICODE, which does not exist in requery's SQLite (no ICU); the statement would fail", ) } - val where = if (line >= 0) "line $line" else "no line number" if (Rules.COLLATE_LOCALIZED.containsMatchIn(text)) { warn( - "${cn.name.replace('/', '.')}.${m.name} ($where): COLLATE LOCALIZED works in requery's SQLite but sorts by " + + "${site(m, line)}: COLLATE LOCALIZED works in requery's SQLite but sorts by " + "byte value (no ICU), not by the device locale", ) } @@ -451,12 +450,20 @@ object SqliteRewriter { // this name is Android's, which the rewritten code cannot mix with requery's. Rules.RENAMED_CLASS_NAME.find(text)?.let { warn( - "${cn.name.replace('/', '.')}.${m.name} ($where): the string \"${it.value}\" names a class the rewrite moves " + + "${site(m, line)}: the string \"${it.value}\" names a class the rewrite moves " + "to requery. Strings are not rewritten: Class.forName or reflection on it reaches Android's class, not requery's", ) } } + fun where(line: Int) = if (line >= 0) "line $line" else "no line number" + + /** Where a warning points: class, method and line, as `p.Dao.query (line 12)`. */ + fun site( + m: MethodNode, + line: Int, + ) = "${cn.name.replace('/', '.')}.${m.name} (${where(line)})" + fun invokeDynamic( m: MethodNode, insn: InvokeDynamicInsnNode, @@ -478,8 +485,7 @@ object SqliteRewriter { what: String, ) { if (!policy.fail) return - val where = if (line >= 0) "line $line" else "no line number" - violations += "${m.name}${m.desc} ($where): $what" + violations += "${m.name}${m.desc} (${where(line)}): $what" } fun fieldInsn( @@ -487,10 +493,13 @@ object SqliteRewriter { f: FieldInsnNode, line: Int, ) { - fieldProblem(f.owner, f.name, f.desc)?.let { violate(m, line, it) } + fieldProblem(m, line, f.owner, f.name, f.desc)?.let { violate(m, line, it) } } + /** [m] and [line] locate the access, for a warning. */ fun fieldProblem( + m: MethodNode, + line: Int, owner: String, name: String, desc: String, @@ -503,7 +512,7 @@ object SqliteRewriter { return renamedAncestors(owner) .firstOrNull { Rules.MISSING_MEMBERS["$it.$name"]?.contains(desc) == true } ?.let { "${simple(it)}.$name does not exist in requery" } - ?: unresolvedOwner(owner, name, desc) + ?: unresolvedOwner(m, line, owner, name, desc) } /** @@ -511,10 +520,13 @@ object SqliteRewriter { * renamed ancestors are unknown, the member has the name and descriptor of one a rule changes or rejects in a * renamed class another class can extend, and the descriptor names an SQLite-related type. Like a Context * database method on an unresolved owner, this fails under the full policy rather than pass a call that may - * break at run time. A match on name and descriptor alone (isStrict()Z, isString(I)Z) is only a warning: - * libraries reference optional classes the app does not ship, and most of them are not SQLite classes. + * break at run time. A match on name and descriptor alone (isStrict()Z, isString(I)Z, setWindow(CursorWindow)) + * is only a warning, naming class, method and [line] of [m]: libraries reference optional classes the app does + * not ship, and most of them are not SQLite classes. The same warning at the same place is logged once. */ fun unresolvedOwner( + m: MethodNode, + line: Int, owner: String, name: String, desc: String, @@ -529,9 +541,10 @@ object SqliteRewriter { return cannot + "${simple(declaring)}.$name, which it changes or rejects" } if (policy.fail) { + val use = if (desc.startsWith("(")) "call" else "field access" val message = - "${cn.name.replace('/', '.')}: $cannot${simple(declaring)}.$name, which it changes or rejects; " + - "the call is left as it is, and fails at run time if the owner extends that class" + "${site(m, line)}: $cannot${simple(declaring)}.$name, which it changes or rejects; " + + "the $use is left as it is, and fails at run time if the owner extends that class" if (warned.add(message)) warn(message) } return null @@ -587,9 +600,11 @@ object SqliteRewriter { /** * Decides, without changing anything, what happens to `owner.name desc` invoked with [opcode] * (the opcode a method handle's kind stands for). Redirects and retyping apply only when the - * policy allows; a [Action.Fail] is reported only when it fails. + * policy allows; a [Action.Fail] is reported only when it fails. [m] and [line] locate the call, for a warning. */ fun decide( + m: MethodNode, + line: Int, opcode: Int, owner: String, name: String, @@ -628,7 +643,7 @@ object SqliteRewriter { "the platform method would not link", ) } - unresolvedOwner(owner, name, desc)?.let { return Action.Fail(it) } + unresolvedOwner(m, line, owner, name, desc)?.let { return Action.Fail(it) } return Action.None } for (c in ancestors) { @@ -656,7 +671,7 @@ object SqliteRewriter { mi: MethodInsnNode, line: Int, ) { - when (val action = decide(mi.opcode, mi.owner, mi.name, mi.desc)) { + when (val action = decide(m, line, mi.opcode, mi.owner, mi.name, mi.desc)) { Action.None -> {} is Action.Fail -> { @@ -699,7 +714,7 @@ object SqliteRewriter { val what = when (h.tag) { Opcodes.H_GETFIELD, Opcodes.H_GETSTATIC, Opcodes.H_PUTFIELD, Opcodes.H_PUTSTATIC -> { - fieldProblem(h.owner, h.name, h.desc) + fieldProblem(m, line, h.owner, h.name, h.desc) } else -> { @@ -710,7 +725,7 @@ object SqliteRewriter { Opcodes.H_INVOKEVIRTUAL -> Opcodes.INVOKEVIRTUAL else -> Opcodes.INVOKESPECIAL } - when (val action = decide(opcode, h.owner, h.name, h.desc)) { + when (val action = decide(m, line, opcode, h.owner, h.name, h.desc)) { Action.None -> null is Action.Fail -> action.what is Action.Redirect -> "the runtime takes this call over" diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt index 3d3ba57261..d05439852e 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/SqliteRewriteTransformTest.kt @@ -163,9 +163,10 @@ class SqliteRewriteTransformTest { assertThat(result.task(":app:checkDemoDebugSqliteRewriteClasspath")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) assertThat(result.task(":app:transformDemoDebugClassesWithAsm")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) - // isString(I)Z names no SQLite type, so the owner that cannot be resolved is only reported through Gradle's logger + // isString(I)Z names no SQLite type, so the owner that cannot be resolved is only reported through Gradle's logger, + // at the calling method and line (the library's source is one line) val warning = - "x.lib.$daoName: com.unknown.Row cannot be resolved, so the rewrite cannot tell whether its isString(I)Z is " + + "x.lib.$daoName.probe (line 1): com.unknown.Row cannot be resolved, so the rewrite cannot tell whether its isString(I)Z is " + "SQLiteCursor.isString, which it changes or rejects; the call is left as it is, and fails at run time if the owner " + "extends that class" assertThat(result.output).contains(warning) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt index d8eb3a6042..e1b5ac1b14 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -26,7 +26,6 @@ class SqliteRewriteRulesTest { "Landroid/database/sqlite/", "Lio/requery/android/database/", "Landroid/database/Cursor;", - "Landroid/database/CursorWindow;", "Landroid/os/CancellationSignal;", "Landroidx/core/os/CancellationSignal;", "Landroid/database/DatabaseErrorHandler;", @@ -35,9 +34,10 @@ class SqliteRewriteRulesTest { // a key is a name plus a descriptor, and no name holds a token val (failing, warned) = SqliteRewriteRules.INHERITABLE_RULE_MEMBERS.keys.partition { key -> tokens.any { key.contains(it) } } - assertThat(failing.map { it.substringBefore('(').removeSuffix("Landroid/database/CursorWindow;") }) - .containsExactly("setWindow", "mWindow", "setOpenParams", "getCursorFactory", "insert", "update", "delete", "query") - assertThat(warned).hasSize(26) + assertThat(failing.map { it.substringBefore('(') }) + .containsExactly("setOpenParams", "getCursorFactory", "insert", "update", "delete", "query") + // CursorWindow is not an SQLite type: any windowed cursor has setWindow(CursorWindow) and mWindow + assertThat(warned).hasSize(28) assertThat(warned).containsAtLeast( "isDistinct()Z", "isStrict()Z", @@ -47,6 +47,8 @@ class SqliteRewriteRulesTest { "isFloat(I)Z", "isBlob(I)Z", "getProjectionMap()Ljava/util/Map;", + "setWindow(Landroid/database/CursorWindow;)V", + "mWindowLandroid/database/CursorWindow;", ) } } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 3dc4fb995f..f512ce5fe7 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1507,6 +1507,78 @@ class SqliteRewriterTest { assertThat(warnings.single()).contains("isString(I)Z") } + @Test + fun `an unresolvable windowed cursor's setWindow(CursorWindow) and mWindow only warn`() { + val classes = + Compiler.compile( + listOf( + src( + "p.UsesWindowed", + """ + package p; + import android.database.CursorWindow; + public class UsesWindowed { + void reset(com.unknown.Windowed c, CursorWindow w) { c.setWindow(w); } + CursorWindow window(com.unknown.Windowed c) { return c.mWindow; } + } + """, + ), + // a library's own windowed cursor, as android's AbstractWindowedCursor declares both members; left + // out of the hierarchy, as an optional class the app does not ship is + src( + "com.unknown.Windowed", + """ + package com.unknown; + public class Windowed { + public android.database.CursorWindow mWindow; + public void setWindow(android.database.CursorWindow w) {} + } + """, + ), + ), + ) + val warnings = mutableListOf() + // CursorWindow is not an SQLite type: it carries every ContentProvider cursor across processes + SqliteRewriter.rewrite(classes["p/UsesWindowed"]!!, hierarchy, warn = warnings::add) + assertThat(warnings).hasSize(2) + assertThat(warnings[0]).contains("its setWindow(Landroid/database/CursorWindow;)V is SQLiteCursor.setWindow") + assertThat(warnings[0]).contains("the call is left as it is") + assertThat(warnings[1]).contains("its mWindowLandroid/database/CursorWindow; is SQLiteCursor.mWindow") + assertThat(warnings[1]).contains("the field access is left as it is") + } + + @Test + fun `an unresolved-owner warning names the method and line, once per place`() { + val source = + """ + package p; + public class Sites { + boolean one(com.unknown.Row r) { + return r.isString(0) && r.isString(1); + } + boolean two(com.unknown.Row r) { + return r.isString(2); + } + } + """ + val classes = + Compiler.compile( + listOf( + src("p.Sites", source), + src("com.unknown.Row", "package com.unknown; public class Row { public boolean isString(int i) { return false; } }"), + ), + ) + + fun lineOf(text: String) = source.lines().indexOfFirst { text in it } + 1 + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/Sites"]!!, hierarchy, warn = warnings::add) + // the two calls on one line make the same warning, logged once + assertThat(warnings.map { it.substringBefore(": ") }) + .containsExactly("p.Sites.one (line ${lineOf("r.isString(0)")})", "p.Sites.two (line ${lineOf("r.isString(2)")})") + .inOrder() + assertThat(warnings.map { it.substringAfter(": ") }.distinct().single()).startsWith("com.unknown.Row cannot be resolved") + } + @Test fun `an unresolvable owner whose member names an SQLite type still fails`() { val classes = From d362637b6fd485c614c53451abdaf68a56e2c4ce Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:33:30 -0800 Subject: [PATCH 133/203] ADFA-7138 Fail the build for an SQLite cursor stored into an Android cursor array loaded from an array `AbstractCursor[][] g; g[0][0] = c;` passed the array-store check from 586a9b91f and threw ArrayStoreException at run time: BasicInterpreter types every AALOAD as Object, so the row g[0] carried no tag, and the tag was set only for one-dimensional arrays. The tag now holds the array type, of any dimension, and an AALOAD from a tagged array of two or more dimensions gives a value tagged with one dimension fewer. The pre-filter also looks at MULTIANEWARRAY (`new AbstractCursor[2][2]`), which may be the only place a method names the type. The new test covers a parameter, a MULTIANEWARRAY, an ANEWARRAY of rows, three dimensions and an array initializer (`new AbstractCursor[] {c}`, covered before but untested); the passing test gains a Cursor[][] store and stores of a row and of another cursor into an AbstractCursor[][]. Cursors loaded from arrays are still not followed (sqlite-rewrite.md). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 +- .../gradle/sqlite/SqliteRewriter.kt | 46 ++++++++++---- .../gradle/sqlite/SqliteRewriterTest.kt | 61 +++++++++++++++++++ 3 files changed, 98 insertions(+), 12 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index c44aa062fe..813d0cf61e 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -74,7 +74,8 @@ cannot load, so the transform runs only on projects that opted in. Commenting th called on, stored in a field, or held in a local as one of those three types (`AbstractCursor up(SQLiteCursor c) { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. So does storing one into an array of those types (`AbstractCursor[] a; a[0] = c;`), which would throw `ArrayStoreException`: the - array must be one on every path to the store, from a parameter, field, call or `new`. + array must be one on every path to the store, from a parameter, field, call or `new`, or loaded from an array of + them (`AbstractCursor[][] g; g[0][0] = c;`). A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported when the guard holds on every path to the cast: in `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 2baf2d0ddd..169e111045 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -23,6 +23,7 @@ import org.objectweb.asm.tree.LdcInsnNode import org.objectweb.asm.tree.LineNumberNode import org.objectweb.asm.tree.MethodInsnNode import org.objectweb.asm.tree.MethodNode +import org.objectweb.asm.tree.MultiANewArrayInsnNode import org.objectweb.asm.tree.TypeInsnNode import org.objectweb.asm.tree.VarInsnNode import org.objectweb.asm.tree.analysis.Analyzer @@ -188,13 +189,13 @@ object SqliteRewriter { /** * A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's - * ([renamedCursor]), or, on every path, an array of one of the Android-only cursor types ([androidCursorArray], - * that element type). + * ([renamedCursor]), or, on every path, an array of one of the Android-only cursor types, of any dimension + * ([androidCursorArray], that array type). */ private class StaticCursorValue( type: Type?, val renamedCursor: Boolean, - val androidCursorArray: String? = null, + val androidCursorArray: Type? = null, ) : BasicValue(type) { // as TaintValue: Frame.merge keeps the old value when the merged one equals it override fun equals(other: Any?): Boolean = @@ -791,9 +792,12 @@ object SqliteRewriter { /** A type in a frame or an internal name, when it is one of the Android-only cursor types, or null. */ private fun androidOnlyCursor(entry: Any?): String? = (entry as? String)?.takeIf { it in Rules.ANDROID_ONLY_CURSOR_TYPES } - /** [type]'s element type when it is a one-dimensional array of an Android-only cursor type, or null. */ - private fun androidCursorArray(type: Type?): String? = - if (type != null && type.sort == Type.ARRAY && type.dimensions == 1) androidOnlyCursor(type.elementType) else null + /** [type] when it is an array of an Android-only cursor type, of any dimension, or null. */ + private fun androidCursorArray(type: Type?): Type? = + type?.takeIf { + it.sort == Type.ARRAY && + androidOnlyCursor(it.elementType) != null + } /** Whether [m] names an Android-only cursor type where a value could be converted to it without a cast. */ private fun mayConvertToAndroidCursor(m: MethodNode): Boolean { @@ -806,6 +810,7 @@ object SqliteRewriter { is InvokeDynamicInsnNode -> names(insn.desc) is FieldInsnNode -> names(insn.desc) is TypeInsnNode -> names(insn.desc) || (insn.opcode == Opcodes.ANEWARRAY && androidOnlyCursor(insn.desc) != null) + is MultiANewArrayInsnNode -> names(insn.desc) is FrameNode -> (insn.local.orEmpty() + insn.stack.orEmpty()).any { androidOnlyCursor(it) != null } else -> false } @@ -818,10 +823,11 @@ object SqliteRewriter { * passed, called on, stored in a field, or held where a frame declares one of them. javac writes no CHECKCAST * for such an upcast, and requery's SQLiteCursor neither extends those classes nor implements the interface, so * the renamed class would not verify (or, for the interface, the call would fail). Also an AASTORE of such a value - * into an array that is, on every path to it, one of those types' arrays (from a parameter, field, call or - * ANEWARRAY): it would throw ArrayStoreException. Not checked: stores into a Cursor[] or Object[], allowed on - * purpose although one can be such an array at run time; a store whose array type differs between the paths - * that merge before it; values loaded from arrays, which are not followed. + * into an array that is, on every path to it, one of those types' arrays (from a parameter, field, call, + * ANEWARRAY or MULTIANEWARRAY, or loaded from an array of them): it would throw ArrayStoreException. Not checked: + * stores into a Cursor[] or Object[], allowed on purpose although one can be such an array at run time; a store + * whose array type differs between the paths that merge before it; cursors loaded from arrays, which are not + * followed. */ fun implicitCursorConversions(m: MethodNode): Map { if (!mayConvertToAndroidCursor(m)) return emptyMap() @@ -832,6 +838,19 @@ object SqliteRewriter { return if (v.isReference) StaticCursorValue(v.type, isRenamedCursorType(type), androidCursorArray(type)) else v } + override fun binaryOperation( + insn: AbstractInsnNode, + value1: BasicValue, + value2: BasicValue, + ): BasicValue? { + val array = (value1 as? StaticCursorValue)?.androidCursorArray + // BasicInterpreter types every AALOAD as Object; a row of an AbstractCursor[][] is an AbstractCursor[] + if (insn.opcode == Opcodes.AALOAD && array != null && array.dimensions > 1) { + return newValue(Type.getType(array.descriptor.substring(1))) + } + return super.binaryOperation(insn, value1, value2) + } + override fun merge( value1: BasicValue, value2: BasicValue, @@ -867,7 +886,12 @@ object SqliteRewriter { fun fromTop(depth: Int) = if (depth < f.stackSize) f.getStack(f.stackSize - 1 - depth) else null if (insn.opcode == Opcodes.AASTORE) { - val element = (fromTop(2) as? StaticCursorValue)?.androidCursorArray + val element = + (fromTop(2) as? StaticCursorValue) + ?.androidCursorArray + ?.takeIf { it.dimensions == 1 } + ?.elementType + ?.internalName if (element != null && renamed(fromTop(0))) { result[insn] = "an SQLite cursor stored into an array of ${element.replace('/', '.')}; requery's SQLiteCursor " + "is not one, so the store would throw ArrayStoreException" diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index f512ce5fe7..44775f51bb 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1707,6 +1707,60 @@ class SqliteRewriterTest { ) } + @Test + fun `an SQLite cursor stored into an Android cursor array loaded from an array of them fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.Nested", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class Nested { + void param(AbstractCursor[][] g, SQLiteCursor c) { + g[0][0] = c; + } + void fresh(SQLiteCursor c) { + AbstractCursor[][] g = new AbstractCursor[2][2]; + g[1][1] = c; + } + void rows(SQLiteCursor c) { + AbstractWindowedCursor[][] g = new AbstractWindowedCursor[2][]; + g[0] = new AbstractWindowedCursor[1]; + AbstractWindowedCursor[] row = g[0]; + row[0] = c; + } + void threeDims(CrossProcessCursor[][][] g, SQLiteCursor c) { + g[0][1][2] = c; + } + AbstractCursor[] initializer(SQLiteCursor c) { + return new AbstractCursor[] {c}; + } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Nested"]!!, hierarchy) } + val stored = "an SQLite cursor stored into an array of android.database" + assertThat(e.message).contains( + " - param([[Landroid/database/AbstractCursor;Landroid/database/sqlite/SQLiteCursor;)V (line 7): $stored.AbstractCursor;", + ) + // MULTIANEWARRAY, with nothing else in the method naming an Android cursor type + assertThat(e.message).contains(" - fresh(Landroid/database/sqlite/SQLiteCursor;)V (line 11): $stored.AbstractCursor;") + assertThat(e.message).contains(" - rows(Landroid/database/sqlite/SQLiteCursor;)V (line 17): $stored.AbstractWindowedCursor;") + assertThat(e.message).contains( + " - threeDims([[[Landroid/database/CrossProcessCursor;Landroid/database/sqlite/SQLiteCursor;)V (line 20): " + + "$stored.CrossProcessCursor;", + ) + // an array initializer is an ANEWARRAY and an AASTORE + assertThat(e.message).contains( + " - initializer(Landroid/database/sqlite/SQLiteCursor;)[Landroid/database/AbstractCursor; (line 23): $stored.AbstractCursor;", + ) + } + @Test fun `an SQLite cursor stored into a Cursor or Object array, or another value into an Android cursor array, passes`() { val classes = @@ -1729,6 +1783,13 @@ class SqliteRewriterTest { a[0] = m; a[1] = null; } + void nestedCursors(Cursor[][] g, SQLiteCursor c) { + g[0][0] = c; + } + void nestedRows(AbstractCursor[][] g, AbstractCursor[] row, MatrixCursor m) { + g[0] = row; + g[1][0] = m; + } } """, ), From 30e7820ca6c6edc929f8eec007575c95830f0917 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:50:04 -0800 Subject: [PATCH 134/203] ADFA-7138 Keep an Android cursor array's tag across a merge with null, and list covariant arrays as a limit `AbstractCursor[] a = null; if (b) a = p; a[0] = sqliteCursor;` passed the array-store check: the merge where the branches join kept the array's tag only when both sides had it, and null had none. A value now records that it is the null constant on every path, and a merge with it keeps the other side's tag, for locals and for the stack (`(b ? p : null)[0] = c`). When b is false that store throws NullPointerException, when it is true ArrayStoreException, so failing the build is right. Not fixed, now in the known limits of sqlite-rewrite.md and pinned by a test: an SQLiteCursor[] used without a cast as an AbstractCursor[] (`AbstractCursor[] a = new SQLiteCursor[1]`, arrays are covariant) is not reported. After the rename it is an array of requery's SQLiteCursor, so a class that passes, returns or stores it as one does not verify; the test shows that for a return, rewritten in a package the fail rule exempts. Catching it would mean following SQLiteCursor[] values through every conversion the scalar check covers. It is rare, and a class that uses one that way fails verification (the JVM verifier, in the test) rather than misbehaving later. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 14 +++-- .../gradle/sqlite/SqliteRewriter.kt | 32 +++++++--- .../gradle/sqlite/SqliteRewriterTest.kt | 63 +++++++++++++++++++ 3 files changed, 96 insertions(+), 13 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 813d0cf61e..8abad23d8a 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -74,8 +74,8 @@ cannot load, so the transform runs only on projects that opted in. Commenting th called on, stored in a field, or held in a local as one of those three types (`AbstractCursor up(SQLiteCursor c) { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. So does storing one into an array of those types (`AbstractCursor[] a; a[0] = c;`), which would throw `ArrayStoreException`: the - array must be one on every path to the store, from a parameter, field, call or `new`, or loaded from an array of - them (`AbstractCursor[][] g; g[0][0] = c;`). + array must be one on every path to the store where it is not `null`, from a parameter, field, call or `new`, or + loaded from an array of them (`AbstractCursor[][] g; g[0][0] = c;`). A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported when the guard holds on every path to the cast: in `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but @@ -213,9 +213,13 @@ dependency, and runs the script on both APKs. The release must pass. The debug A `xandroid.database.sqlite.SQLiteDatabase`, do not. - Stores of an SQLite cursor into an array known only as a `Cursor[]` or `Object[]` are allowed on purpose (failing them would fail ordinary apps), but such an array can be an `AbstractCursor[]` at run time (arrays are covariant), - and a store whose array type is unknown where branches merge is not checked. Both can still throw - `ArrayStoreException`, in release builds too (the rewrite runs in every variant of an opted-in app). Cursors loaded - from arrays are not followed. + and a store whose array type differs between branches that merge is not checked (`null` on a branch counts as + no difference). Both can still throw `ArrayStoreException`, in release builds too (the rewrite runs in every + variant of an opted-in app). Cursors loaded from arrays are not followed. +- An array of `SQLiteCursor`, or of a subclass, used without a cast as an array of `AbstractCursor`, + `AbstractWindowedCursor` or `CrossProcessCursor` (`AbstractCursor[] a = new SQLiteCursor[1];`; arrays are + covariant) is not reported. After the rename it is an array of requery's `SQLiteCursor`, which is none of those, + so a class that passes, returns or stores it as one does not verify. - The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a cursor that reached the method through a field, a parameter or another call is not seen (the app throws `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 169e111045..cafd5f72f2 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -189,20 +189,23 @@ object SqliteRewriter { /** * A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's - * ([renamedCursor]), or, on every path, an array of one of the Android-only cursor types, of any dimension - * ([androidCursorArray], that array type). + * ([renamedCursor]), or, on every path where it is not null, an array of one of the Android-only cursor types, of + * any dimension ([androidCursorArray], that array type). [nullConstant]: `null` on every path. */ private class StaticCursorValue( type: Type?, val renamedCursor: Boolean, val androidCursorArray: Type? = null, + val nullConstant: Boolean = false, ) : BasicValue(type) { // as TaintValue: Frame.merge keeps the old value when the merged one equals it override fun equals(other: Any?): Boolean = other is BasicValue && super.equals(other) && renamedCursor == ((other as? StaticCursorValue)?.renamedCursor ?: false) && - androidCursorArray == (other as? StaticCursorValue)?.androidCursorArray + androidCursorArray == (other as? StaticCursorValue)?.androidCursorArray && + nullConstant == ((other as? StaticCursorValue)?.nullConstant ?: false) - override fun hashCode(): Int = (super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode() + override fun hashCode(): Int = + ((super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode()) * 31 + if (nullConstant) 1 else 0 } private class ClassRewrite( @@ -826,8 +829,8 @@ object SqliteRewriter { * into an array that is, on every path to it, one of those types' arrays (from a parameter, field, call, * ANEWARRAY or MULTIANEWARRAY, or loaded from an array of them): it would throw ArrayStoreException. Not checked: * stores into a Cursor[] or Object[], allowed on purpose although one can be such an array at run time; a store - * whose array type differs between the paths that merge before it; cursors loaded from arrays, which are not - * followed. + * whose array type differs between the paths that merge before it (null on a path is no difference); cursors + * loaded from arrays, which are not followed; an SQLiteCursor[] used as one of those types' arrays. */ fun implicitCursorConversions(m: MethodNode): Map { if (!mayConvertToAndroidCursor(m)) return emptyMap() @@ -835,7 +838,12 @@ object SqliteRewriter { object : BasicInterpreter(Opcodes.ASM9) { override fun newValue(type: Type?): BasicValue? { val v = super.newValue(type) ?: return null - return if (v.isReference) StaticCursorValue(v.type, isRenamedCursorType(type), androidCursorArray(type)) else v + return if (v.isReference) { + val nullConstant = type == BasicInterpreter.NULL_TYPE + StaticCursorValue(v.type, isRenamedCursorType(type), androidCursorArray(type), nullConstant) + } else { + v + } } override fun binaryOperation( @@ -859,11 +867,19 @@ object SqliteRewriter { val s2 = value2 as? StaticCursorValue // BasicInterpreter.merge answers UNINITIALIZED for values that differ in either flag if ((s1 != null || s2 != null) && value1.type != null && value1.type == value2.type) { + // null on one path does not hide the array on the other: `AbstractCursor[] a = null; if (b) a = p;` + val array = + when { + s1?.nullConstant == true -> s2?.androidCursorArray + s2?.nullConstant == true -> s1?.androidCursorArray + else -> s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray } + } val merged = StaticCursorValue( value1.type, s1?.renamedCursor == true || s2?.renamedCursor == true, - s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray }, + array, + s1?.nullConstant == true && s2?.nullConstant == true, ) return if (merged == value1) value1 else merged } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 44775f51bb..563db05591 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1823,6 +1823,69 @@ class SqliteRewriterTest { SqliteRewriter.rewrite(classes["p/StoresMerged"]!!, hierarchy) } + @Test + fun `a store into an Android cursor array that is null on the other path fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.NullOnOnePath", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class NullOnOnePath { + void local(AbstractCursor[] p, SQLiteCursor c, boolean b) { + AbstractCursor[] a = null; + if (b) { + a = p; + } + a[0] = c; + } + void stack(AbstractWindowedCursor[] p, SQLiteCursor c, boolean b) { + (b ? p : null)[0] = c; + } + } + """, + ), + ), + ) + // when b is false the store throws NullPointerException; when it is true, ArrayStoreException + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/NullOnOnePath"]!!, hierarchy) } + assertThat(e.message).contains( + " - local([Landroid/database/AbstractCursor;Landroid/database/sqlite/SQLiteCursor;Z)V (line 11): " + + "an SQLite cursor stored into an array of android.database.AbstractCursor;", + ) + assertThat(e.message).contains( + " - stack([Landroid/database/AbstractWindowedCursor;Landroid/database/sqlite/SQLiteCursor;Z)V (line 14): " + + "an SQLite cursor stored into an array of android.database.AbstractWindowedCursor;", + ) + } + + @Test + fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { + fun covariant(pkg: String) = + src( + "$pkg.Covariant", + """ + package $pkg; + import android.database.*; + import android.database.sqlite.*; + public class Covariant { + AbstractCursor[] up(SQLiteCursor[] s) { + return s; + } + } + """, + ) + // a known limit: arrays are covariant, and an SQLiteCursor[] is not followed + SqliteRewriter.rewrite(Compiler.compile(listOf(covariant("p")))["p/Covariant"]!!, hierarchy) + // The failure mode: rewritten in a package the fail rule exempts, the same class does not verify + val unverified = assertThrows(IllegalStateException::class.java) { transform(covariant("androidx.sqlite.db.framework")) } + assertThat(unverified.message).contains("does not verify") + assertThat(unverified.message).contains("androidx/sqlite/db/framework/Covariant") + } + @Test fun `an instanceof guard counts only when it covers every path to the cast`() { val classes = From 9f84175b720b4b48f21ea3b3537bcf4f6bbd2b6d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:50:04 -0800 Subject: [PATCH 135/203] ADFA-7138 Log any exception from an SQLite AAR extraction, so the rest of app init runs extractSqliteAar caught only IOException. A RuntimeException (no base application yet, a failure inside the copy) left the init task and skipped every step after it: the other AAR, writeNoMediaFile, the cogo plugin, the color schemes, the init script, the keystore and deleteIdeenv. It now catches Exception and logs it; an Error still propagates. The asset lookup moves behind a @VisibleForTesting SqliteAarSource so a test can make the open and the read throw. The missing directory fsync after the rename is left as it is: init re-extracts on every start, so a rename lost to a power cut heals on the next one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/managers/ToolsManager.java | 25 +++++++++++++++---- .../managers/ToolsManagerSqliteAarTest.kt | 18 +++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java index 714bc4a16a..e585af5686 100755 --- a/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java +++ b/common/src/main/java/com/itsaky/androidide/managers/ToolsManager.java @@ -172,6 +172,18 @@ static boolean ensureToolingJar(File toolingJarFile, File stampFile, String stam return isToolingJarCurrent(toolingJarFile, stampFile, stamp); } + /** + * Replaces aar with the asset, and logs any failure instead of throwing it. {@link #init} runs the steps after this one (the cogo plugin, the init script, the keystore) only when it returns, so a RuntimeException is caught too, not only an IOException. A failed extraction leaves the previous AAR, or none, which {@link #init} replaces on the next start. + */ + @VisibleForTesting + static void extractSqliteAar(String asset, File aar, SqliteAarSource source) { + try (InputStream stream = source.open()) { + replaceAtomically(stream, aar); + } catch (Exception err) { + LOG.error("Failed to extract {} to {}", asset, aar, err); + } + } + /** * Copies the stream to a temp sibling of toolingJarFile, renames it into place, then writes the stamp. This runs asynchronously from app init while the tooling server launches `java -jar` against the same path on project open, and launching against a half-written jar kills project init ("An unexpected error occurred while trying to open file ..."), so a partial jar must never be visible at the final path. rename(2) within one directory atomically replaces the target on Linux. The stamp is written only after a successful rename, so a failure at any step leaves the stamp absent and the next launch retries. The stale-jar half of the same race - the server reaching the final path before this rename and running the previous install's jar - is closed by {@link #ensureToolingJar(Context)}, which the server calls before launching. Always closes the stream. */ @@ -286,11 +298,7 @@ private static void extractLogSender(BaseApplication app) { } private static void extractSqliteAar(String asset, File aar) { - try (InputStream source = BaseApplication.getBaseInstance().getAssets().open(asset)) { - replaceAtomically(source, aar); - } catch (IOException err) { - LOG.error("Failed to extract {} to {}", asset, aar, err); - } + extractSqliteAar(asset, aar, () -> BaseApplication.getBaseInstance().getAssets().open(asset)); } @WorkerThread @@ -480,6 +488,13 @@ private static void writeNoMediaFile() { } } + /** Opens a bundled SQLite AAR asset. */ + @VisibleForTesting + interface SqliteAarSource { + + InputStream open() throws IOException; + } + /** Opens the bundled tooling jar asset. Called only when the jar on disk is not this install's. */ @VisibleForTesting interface ToolingJarSource { diff --git a/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt b/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt index 3d95db8389..36821a8cfe 100644 --- a/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt +++ b/common/src/test/java/com/itsaky/androidide/managers/ToolsManagerSqliteAarTest.kt @@ -76,6 +76,24 @@ class ToolsManagerSqliteAarTest { assertThat(aar.parentFile!!.list()).asList().containsExactly("sqlite-debugger.aar") } + @Test + fun `an extraction that throws a RuntimeException returns, so the rest of init runs, and keeps the previous AAR`() { + val aar = File(tempFolder.root, "sqlite-debugger/sqlite-debugger.aar") + aar.parentFile!!.mkdirs() + aar.writeText("previous-install-aar") + val failing = + object : InputStream() { + override fun read(): Int = throw IllegalStateException("asset manager gone") + } + + // init calls the steps after this one (the cogo plugin, the init script, the keystore) only when it returns + ToolsManager.extractSqliteAar("sqlite-debugger-release.aar", aar) { failing } + ToolsManager.extractSqliteAar("sqlite-debugger-release.aar", aar) { throw NullPointerException("no base application") } + + assertThat(aar.readText()).isEqualTo("previous-install-aar") + assertThat(aar.parentFile!!.list()).asList().containsExactly("sqlite-debugger.aar") + } + @Test fun `the first extraction creates the directory and the AAR`() { val aar = File(tempFolder.root, "sqlite-rewrite-runtime/sqlite-rewrite-runtime.aar") From f6c8bf0d5e0c3c8c60fdbb0e98487c12a579dae7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:00:39 -0800 Subject: [PATCH 136/203] ADFA-7138 Warn, not fail, for an SQLite cursor stored into an Android cursor array on some paths only The array-store check failed the build when the array was an Android cursor array wherever it is not null and the value was an SQLite cursor on any path, without asking whether both hold on one path. So a store that can never throw failed the build: Object[] slot = null; Object r; if (useDb) r = c; else { slot = cache; r = m; } if (slot != null) slot[0] = r; The value now also records whether it is an SQLite cursor on every path where it is not null (null is neutral), merged with AND. The store fails the build only then. When the value is one on some paths only, the store logs a warning with class, method and line, once per place, saying it may throw ArrayStoreException at run time when the value is an SQLite cursor. The new flag only moves from true to false and counts in equals and hashCode, so the analysis still reaches a fixed point (the new test has a loop whose value changes on the back edge). A cursor loaded from an array is still not followed, so `b ? c : arr[0]` now warns instead of failing. The docs' rule and known limit say so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 10 +- .../gradle/sqlite/SqliteRewriter.kt | 87 ++++++++---- .../gradle/sqlite/SqliteRewriterTest.kt | 126 ++++++++++++++++++ 3 files changed, 197 insertions(+), 26 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 8abad23d8a..db062d8d1a 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -75,7 +75,11 @@ cannot load, so the transform runs only on projects that opted in. Commenting th { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. So does storing one into an array of those types (`AbstractCursor[] a; a[0] = c;`), which would throw `ArrayStoreException`: the array must be one on every path to the store where it is not `null`, from a parameter, field, call or `new`, or - loaded from an array of them (`AbstractCursor[][] g; g[0][0] = c;`). + loaded from an array of them (`AbstractCursor[][] g; g[0][0] = c;`), and the value an SQLite cursor on every path + where it is not `null`. A value that is one on some paths only (`Object v = b ? c : matrixCursor;`) logs a + warning with class, method and line instead, once per place: the check does not match the paths of the value with + those of the array, so it cannot tell whether one path brings both + (`if (useDb) v = c; else { a = cache; v = m; } if (a != null) a[0] = v;` never throws). A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported when the guard holds on every path to the cast: in `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but @@ -215,7 +219,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A them would fail ordinary apps), but such an array can be an `AbstractCursor[]` at run time (arrays are covariant), and a store whose array type differs between branches that merge is not checked (`null` on a branch counts as no difference). Both can still throw `ArrayStoreException`, in release builds too (the rewrite runs in every - variant of an opted-in app). Cursors loaded from arrays are not followed. + variant of an opted-in app). So can a store whose value is an SQLite cursor on some paths only, which logs a + warning and builds (see Rules): it throws when one path brings both the cursor and the array. Cursors loaded from + arrays are not followed: one counts as a value that is not an SQLite cursor. - An array of `SQLiteCursor`, or of a subclass, used without a cast as an array of `AbstractCursor`, `AbstractWindowedCursor` or `CrossProcessCursor` (`AbstractCursor[] a = new SQLiteCursor[1];`; arrays are covariant) is not reported. After the rename it is an array of requery's `SQLiteCursor`, which is none of those, diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index cafd5f72f2..6213c12054 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -189,23 +189,27 @@ object SqliteRewriter { /** * A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's - * ([renamedCursor]), or, on every path where it is not null, an array of one of the Android-only cursor types, of - * any dimension ([androidCursorArray], that array type). [nullConstant]: `null` on every path. + * ([renamedCursor]; [everyPathCursor] when it is one on every path where it is not null, so also for `null` + * itself), or, on every path where it is not null, an array of one of the Android-only cursor types, of any + * dimension ([androidCursorArray], that array type). [nullConstant]: `null` on every path. */ private class StaticCursorValue( type: Type?, val renamedCursor: Boolean, - val androidCursorArray: Type? = null, - val nullConstant: Boolean = false, + val androidCursorArray: Type?, + val nullConstant: Boolean, + val everyPathCursor: Boolean, ) : BasicValue(type) { // as TaintValue: Frame.merge keeps the old value when the merged one equals it override fun equals(other: Any?): Boolean = other is BasicValue && super.equals(other) && renamedCursor == ((other as? StaticCursorValue)?.renamedCursor ?: false) && androidCursorArray == (other as? StaticCursorValue)?.androidCursorArray && - nullConstant == ((other as? StaticCursorValue)?.nullConstant ?: false) + nullConstant == ((other as? StaticCursorValue)?.nullConstant ?: false) && + everyPathCursor == ((other as? StaticCursorValue)?.everyPathCursor ?: false) override fun hashCode(): Int = - ((super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode()) * 31 + if (nullConstant) 1 else 0 + (((super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode()) * 31 + if (nullConstant) 1 else 0) * + 31 + if (everyPathCursor) 1 else 0 } private class ClassRewrite( @@ -401,7 +405,7 @@ object SqliteRewriter { if (insn is LineNumberNode) { line = insn.line } - conversions[insn]?.let { violate(m, line, it) } + conversions[insn]?.let { if (it.fails) violate(m, line, it.what) else warnOnce("${site(m, line)}: ${it.what}") } when (insn) { is MethodInsnNode -> { methodInsn(m, insn, line) @@ -460,6 +464,11 @@ object SqliteRewriter { } } + /** Logs [message] unless it was logged already: one warning per place, though one place can trip it twice. */ + fun warnOnce(message: String) { + if (warned.add(message)) warn(message) + } + fun where(line: Int) = if (line >= 0) "line $line" else "no line number" /** Where a warning points: class, method and line, as `p.Dao.query (line 12)`. */ @@ -549,7 +558,7 @@ object SqliteRewriter { val message = "${site(m, line)}: $cannot${simple(declaring)}.$name, which it changes or rejects; " + "the $use is left as it is, and fails at run time if the owner extends that class" - if (warned.add(message)) warn(message) + warnOnce(message) } return null } @@ -820,19 +829,28 @@ object SqliteRewriter { } } + /** What [implicitCursorConversions] found at one instruction: a build failure, or, unless it [fails], a warning. */ + class Conversion( + val what: String, + val fails: Boolean, + ) + /** * The instructions where a value whose static type is SQLiteCursor, or a class that extends it, is used as an * AbstractWindowedCursor, AbstractCursor or CrossProcessCursor without a cast, by the message for each: returned, - * passed, called on, stored in a field, or held where a frame declares one of them. javac writes no CHECKCAST - * for such an upcast, and requery's SQLiteCursor neither extends those classes nor implements the interface, so - * the renamed class would not verify (or, for the interface, the call would fail). Also an AASTORE of such a value - * into an array that is, on every path to it, one of those types' arrays (from a parameter, field, call, - * ANEWARRAY or MULTIANEWARRAY, or loaded from an array of them): it would throw ArrayStoreException. Not checked: - * stores into a Cursor[] or Object[], allowed on purpose although one can be such an array at run time; a store - * whose array type differs between the paths that merge before it (null on a path is no difference); cursors - * loaded from arrays, which are not followed; an SQLiteCursor[] used as one of those types' arrays. + * passed, called on, stored in a field, or held where a frame declares one of them, on any path. javac writes no + * CHECKCAST for such an upcast, and requery's SQLiteCursor neither extends those classes nor implements the + * interface, so the renamed class would not verify (or, for the interface, the call would fail). Also an AASTORE of + * such a value into an array that is, on every path to it where it is not null, one of those types' arrays (from a + * parameter, field, call, ANEWARRAY or MULTIANEWARRAY, or loaded from an array of them): it would throw + * ArrayStoreException. The store fails only when the value is such a cursor on every path where it is not null; on + * some paths only, it is a warning, because the paths of the value are not matched with those of the array, and + * the store throws only on a path that brings both. Not checked: stores into a Cursor[] or Object[], allowed on + * purpose although one can be such an array at run time; a store whose array type differs between the paths that + * merge before it (null on a path is no difference); cursors loaded from arrays, which are not followed; an + * SQLiteCursor[] used as one of those types' arrays. */ - fun implicitCursorConversions(m: MethodNode): Map { + fun implicitCursorConversions(m: MethodNode): Map { if (!mayConvertToAndroidCursor(m)) return emptyMap() val interpreter = object : BasicInterpreter(Opcodes.ASM9) { @@ -840,7 +858,8 @@ object SqliteRewriter { val v = super.newValue(type) ?: return null return if (v.isReference) { val nullConstant = type == BasicInterpreter.NULL_TYPE - StaticCursorValue(v.type, isRenamedCursorType(type), androidCursorArray(type), nullConstant) + val renamed = isRenamedCursorType(type) + StaticCursorValue(v.type, renamed, androidCursorArray(type), nullConstant, renamed || nullConstant) } else { v } @@ -880,6 +899,8 @@ object SqliteRewriter { s1?.renamedCursor == true || s2?.renamedCursor == true, array, s1?.nullConstant == true && s2?.nullConstant == true, + // true on null, so null is neutral; a plain BasicValue (an element loaded from an array) is not a known cursor + s1?.everyPathCursor == true && s2?.everyPathCursor == true, ) return if (merged == value1) value1 else merged } @@ -894,7 +915,7 @@ object SqliteRewriter { } val declared = fullFrames(m, m.desc).associateBy { it.node } val returnType = Type.getReturnType(m.desc) - val result = LinkedHashMap() + val result = LinkedHashMap() for ((i, insn) in m.instructions.withIndex()) { val f = frames[i] ?: continue @@ -908,9 +929,23 @@ object SqliteRewriter { ?.takeIf { it.dimensions == 1 } ?.elementType ?.internalName - if (element != null && renamed(fromTop(0))) { - result[insn] = "an SQLite cursor stored into an array of ${element.replace('/', '.')}; requery's SQLiteCursor " + - "is not one, so the store would throw ArrayStoreException" + val value = fromTop(0) as? StaticCursorValue + if (element != null && value != null && value.renamedCursor) { + val array = "an array of ${element.replace('/', '.')}" + result[insn] = + if (value.everyPathCursor) { + Conversion( + "an SQLite cursor stored into $array; requery's SQLiteCursor is not one, so the store would throw " + + "ArrayStoreException", + fails = true, + ) + } else { + Conversion( + "the value stored into $array is an SQLite cursor on some paths only; requery's SQLiteCursor is not " + + "one, so the store may throw ArrayStoreException at run time when the value is an SQLite cursor", + fails = false, + ) + } } continue } @@ -955,8 +990,12 @@ object SqliteRewriter { } } if (target != null) { - result[insn] = "an SQLite cursor used as ${target.replace('/', '.')} without a cast; requery's SQLiteCursor is not " + - "one, so the rewritten class would not verify or the call would fail" + result[insn] = + Conversion( + "an SQLite cursor used as ${target.replace('/', '.')} without a cast; requery's SQLiteCursor is not " + + "one, so the rewritten class would not verify or the call would fail", + fails = true, + ) } } return result diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 563db05591..123ea39dd0 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1862,6 +1862,132 @@ class SqliteRewriterTest { ) } + @Test + fun `a store whose value is an SQLite cursor on some paths only warns once per place and builds`() { + val classes = + Compiler.compile( + listOf( + src( + "p.SomePaths", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class SomePaths { + Object nullGuard(SQLiteCursor c, AbstractCursor[] cache, MatrixCursor m, boolean useDb) { + Object[] slot = null; + Object result; + if (useDb) { + result = c; + } else { + slot = cache; + result = m; + } + if (slot != null) { + slot[0] = result; + } + return result; + } + void correlated(SQLiteCursor c, AbstractCursor[] a, MatrixCursor m, boolean b) { + Object[] arr = a; + Object v = m; + if (b) { + v = c; + } + if (!b) { + arr[0] = v; + } + } + void ternary(SQLiteCursor c, AbstractWindowedCursor[] a, MatrixCursor m, boolean b) { + Object[] arr = a; + arr[0] = b ? c : m; + } + void twice(SQLiteCursor c, CrossProcessCursor[] a, MatrixCursor m, boolean b) { + Object[] arr = a; + Object v = b ? c : m; + arr[0] = v; arr[1] = v; + } + void loop(SQLiteCursor c, AbstractCursor[] a, MatrixCursor m, int n) { + Object[] arr = a; + Object v = null; + for (int i = 0; i < n; i++) { + if (v != null) { + arr[i] = v; + } + if (i % 2 == 0) { + v = c; + } else { + v = m; + } + } + } + } + """, + ), + ), + ) + val warnings = mutableListOf() + // no exception: nullGuard and correlated never throw, as the cursor's paths are not the array's + SqliteRewriter.rewrite(classes["p/SomePaths"]!!, hierarchy, warn = warnings::add) + val some = + "is an SQLite cursor on some paths only; requery's SQLiteCursor is not one, so the store may throw " + + "ArrayStoreException at run time when the value is an SQLite cursor" + assertThat(warnings) + .containsExactly( + "p.SomePaths.nullGuard (line 16): the value stored into an array of android.database.AbstractCursor $some", + "p.SomePaths.correlated (line 27): the value stored into an array of android.database.AbstractCursor $some", + "p.SomePaths.ternary (line 32): the value stored into an array of android.database.AbstractWindowedCursor $some", + // two stores on one line, logged once + "p.SomePaths.twice (line 37): the value stored into an array of android.database.CrossProcessCursor $some", + // v is null on the first pass and changes on the back edge, so the analysis must reach a fixed point + "p.SomePaths.loop (line 44): the value stored into an array of android.database.AbstractCursor $some", + ).inOrder() + } + + @Test + fun `a store whose value is an SQLite cursor on every path where it is not null fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.EveryPath", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class EveryPath { + void orNull(SQLiteCursor c, AbstractCursor[] a, boolean b) { + Object[] arr = a; + arr[0] = b ? c : null; + } + void either(SQLiteCursor c, SQLiteCursor d, AbstractCursor[] a, boolean b) { + Object[] arr = a; + arr[0] = b ? c : d; + } + } + """, + ), + ), + ) + val warnings = mutableListOf() + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/EveryPath"]!!, hierarchy, warn = warnings::add) + } + // null is neutral: storing it cannot throw ArrayStoreException, so the cursor on the other path decides + assertThat(e.message).contains( + " - orNull(Landroid/database/sqlite/SQLiteCursor;[Landroid/database/AbstractCursor;Z)V (line 8): " + + "an SQLite cursor stored into an array of android.database.AbstractCursor;", + ) + assertThat(e.message).contains( + " - either(Landroid/database/sqlite/SQLiteCursor;Landroid/database/sqlite/SQLiteCursor;[Landroid/database/AbstractCursor;Z)V " + + "(line 12): an SQLite cursor stored into an array of android.database.AbstractCursor;", + ) + // the stores are the only violations: through an Object[], neither ternary is typed as an Android cursor class + assertThat(e.message).doesNotContain("without a cast") + assertThat(warnings).isEmpty() + } + @Test fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { fun covariant(pkg: String) = From dbe541112735b7da307021c04192685b225041b8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:11:50 -0800 Subject: [PATCH 137/203] ADFA-7138 Treat a row loaded from a null array as null, so a merge keeps the other path's array BasicInterpreter types every AALOAD as a plain reference, also on an array that is null on every path. A merge of that plain value with the tagged row from the other path dropped the tag, so whether the store into the row failed the build depended on which path the analysis visited first: AbstractCursor[][] g = null; if (b) g = p; g[0][0] = c; // built AbstractCursor[][] g = p; if (b) g = null; g[0][0] = c; // failed (b ? p : null)[0][0] = c; // built All three throw ArrayStoreException at run time when b brings p. A load from null always throws, so its result is now the null constant, which a merge treats as no difference. c is an SQLite cursor on every path, so all three fail the build under the every-path rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriter.kt | 7 ++- .../gradle/sqlite/SqliteRewriterTest.kt | 50 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 6213c12054..668c3634b3 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -191,7 +191,8 @@ object SqliteRewriter { * A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's * ([renamedCursor]; [everyPathCursor] when it is one on every path where it is not null, so also for `null` * itself), or, on every path where it is not null, an array of one of the Android-only cursor types, of any - * dimension ([androidCursorArray], that array type). [nullConstant]: `null` on every path. + * dimension ([androidCursorArray], that array type). [nullConstant]: `null` on every path, which an element loaded + * from it counts as, since that load throws. */ private class StaticCursorValue( type: Type?, @@ -870,6 +871,10 @@ object SqliteRewriter { value1: BasicValue, value2: BasicValue, ): BasicValue? { + // a load from null always throws, so its row is null too, which a merge with another path's row ignores + if (insn.opcode == Opcodes.AALOAD && (value1 as? StaticCursorValue)?.nullConstant == true) { + return newValue(BasicInterpreter.NULL_TYPE) + } val array = (value1 as? StaticCursorValue)?.androidCursorArray // BasicInterpreter types every AALOAD as Object; a row of an AbstractCursor[][] is an AbstractCursor[] if (insn.opcode == Opcodes.AALOAD && array != null && array.dimensions > 1) { diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 123ea39dd0..22c14ac40f 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1862,6 +1862,56 @@ class SqliteRewriterTest { ) } + @Test + fun `a store into a row of an Android cursor array that is null on the other path fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.RowOfNull", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class RowOfNull { + void nullFirst(AbstractCursor[][] p, SQLiteCursor c, boolean b) { + AbstractCursor[][] g = null; + if (b) { + g = p; + } + g[0][0] = c; + } + void nullAfter(AbstractCursor[][] p, SQLiteCursor c, boolean b) { + AbstractCursor[][] g = p; + if (b) { + g = null; + } + g[0][0] = c; + } + void stack(AbstractWindowedCursor[][] p, SQLiteCursor c, boolean b) { + (b ? p : null)[0][0] = c; + } + } + """, + ), + ), + ) + // on the null path the row load throws NullPointerException, so the row on the other path decides, whichever path + // the analysis visits first + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/RowOfNull"]!!, hierarchy) } + val stored = "an SQLite cursor stored into an array of android.database" + assertThat(e.message).contains( + " - nullFirst([[Landroid/database/AbstractCursor;Landroid/database/sqlite/SQLiteCursor;Z)V (line 11): $stored.AbstractCursor;", + ) + assertThat(e.message).contains( + " - nullAfter([[Landroid/database/AbstractCursor;Landroid/database/sqlite/SQLiteCursor;Z)V (line 18): $stored.AbstractCursor;", + ) + assertThat(e.message).contains( + " - stack([[Landroid/database/AbstractWindowedCursor;Landroid/database/sqlite/SQLiteCursor;Z)V (line 21): " + + "$stored.AbstractWindowedCursor;", + ) + } + @Test fun `a store whose value is an SQLite cursor on some paths only warns once per place and builds`() { val classes = From 95f1c49d9e9072bca6ddd820caf7b4ae1d8a9987 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:11:51 -0800 Subject: [PATCH 138/203] ADFA-7138 Say an SQLiteCursor[] stored into an array of Android cursor arrays throws, not that it fails to verify The known limit said a class that passes, returns or stores an SQLiteCursor[] as an Android cursor array does not verify. Passed, returned or stored in a field, it does not. Stored as an element of another array (`AbstractCursor[][] g; g[0] = s;`), it verifies, and the store throws ArrayStoreException at run time: checked by rewriting such a class where the fail rule is off, verifying it and calling it with a requery SQLiteCursor[]. Docs only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index db062d8d1a..c8f068ea62 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -225,7 +225,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - An array of `SQLiteCursor`, or of a subclass, used without a cast as an array of `AbstractCursor`, `AbstractWindowedCursor` or `CrossProcessCursor` (`AbstractCursor[] a = new SQLiteCursor[1];`; arrays are covariant) is not reported. After the rename it is an array of requery's `SQLiteCursor`, which is none of those, - so a class that passes, returns or stores it as one does not verify. + so a class that passes or returns it as one, or stores it in a field of that type, does not verify. Stored into an + array of those arrays (`AbstractCursor[][] g; g[0] = s;`), it verifies, and the store throws `ArrayStoreException` + at run time. - The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a cursor that reached the method through a field, a parameter or another call is not seen (the app throws `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an From e723fd8117e9cea4afbc0822d51f0d3b198cbc1a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 16:15:51 -0800 Subject: [PATCH 139/203] ADFA-7138 Flash why Quick Build is greyed out when its status line is tapped Since #2247 (ADFA-6574), tapping the greyed-out Quick Build button flashes why it is greyed out, but runQuickBuildAction, which the "tap for details" status line and the dropdown row call, still did nothing then. The line stays tappable after, for example, a switch to a release variant, so it promised details and gave none. The button's tap moves into tapToolbarAction (run the action, or for a greyed-out Quick Build button flash QuickBuildAction.disabledReason), and runQuickBuildAction calls it, so the line, the row and the button share one code path and one message source. The dropdown row is disabled while the button is greyed out, so only the status line changes in practice. The KDoc of runQuickBuildAction and of ProjectHandlerActivity.onQuickBuildStatusLineTapped now say a tap shows why instead of doing nothing, and gradle-plugin/docs/sqlite-rewrite.md says the same of the line. QuickBuildGreyedStatusLineTapTest taps the status line with Quick Build greyed out for a release variant and expects the real disabledReason text to flash, and with Quick Build enabled expects the action to run and nothing to flash. With runQuickBuildAction reverted to its old guard, the greyed-out case fails because flashInfoLong is never called. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../editor/EditorHandlerActivity.kt | 33 ++++-- .../editor/ProjectHandlerActivity.kt | 3 +- .../QuickBuildGreyedStatusLineTapTest.kt | 107 ++++++++++++++++++ gradle-plugin/docs/sqlite-rewrite.md | 4 +- 4 files changed, 132 insertions(+), 15 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt index 14d16917ef..777ac5b728 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt @@ -799,13 +799,7 @@ open class EditorHandlerActivity : // path's tint and disabled dim here. icon = toolbarIcon(action.icon, action.createColorFilter(data), action.enabled), hint = getToolbarContentDescription(action, data), - onClick = { - if (action.enabled) { - registry.executeAction(action, data) - } else if (action.id == QuickBuildAction.ID) { - QuickBuildAction.disabledReason(this)?.let(::flashInfoLong) - } - }, + onClick = { tapToolbarAction(registry, action, data) }, onLongClick = { // Quick Build is a split button: long-press opens the // Quick Build / Restart session / Help dropdown instead of the @@ -908,15 +902,30 @@ open class EditorHandlerActivity : } /** - * Runs the toolbar's Quick Build action through the registry, as the button's own tap does, so - * the dropdown row and a status line that asks for a tap share the button's code path - * (including the analytics event). Does nothing while the button is greyed out, as the button - * does. + * A tap on a toolbar button: runs its action through the registry, or, while the Quick Build + * button is greyed out, flashes why (ADFA-6574). + */ + private fun tapToolbarAction( + registry: DefaultActionsRegistry, + action: ActionItem, + data: ActionData, + ) { + if (action.enabled) { + registry.executeAction(action, data) + } else if (action.id == QuickBuildAction.ID) { + QuickBuildAction.disabledReason(this)?.let(::flashInfoLong) + } + } + + /** + * Taps the toolbar's Quick Build button, through the button's own tap, so the dropdown row and a + * status line that asks for a tap do what the button does (including the analytics event): run + * Quick Build, or, while the button is greyed out, flash the reason the button gives. */ private fun runQuickBuildAction(data: ActionData) { val registry = getInstance() as DefaultActionsRegistry val quickBuild = registry.findAction(EDITOR_TOOLBAR, QuickBuildAction.ID) ?: return - if (quickBuild.enabled) registry.executeAction(quickBuild, data) + tapToolbarAction(registry, quickBuild, data) } override fun onQuickBuildStatusLineTapped() { diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 59598551fb..e7b5e66df6 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1449,7 +1449,8 @@ abstract class ProjectHandlerActivity : /** * A tap on a Quick Build status line that asks for one: it does what a tap on the Quick Build - * button does, through the same action, so the line cannot promise what the button would not. + * button does, through the same action - runs Quick Build, or, while the button is greyed out, + * shows why - so the line cannot promise what the button would not. */ protected abstract fun onQuickBuildStatusLineTapped() diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt new file mode 100644 index 0000000000..134ac10b9f --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt @@ -0,0 +1,107 @@ +package com.itsaky.androidide.activities.editor + +import android.app.Activity +import com.itsaky.androidide.actions.ActionItem +import com.itsaky.androidide.actions.ActionItem.Location.EDITOR_TOOLBAR +import com.itsaky.androidide.actions.ActionsRegistry +import com.itsaky.androidide.actions.build.QuickBuildAction +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.quickbuild.GradleQuickBuildProvisioner +import com.itsaky.androidide.resources.R +import com.itsaky.androidide.utils.flashInfoLong +import io.mockk.coVerify +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.mockkStatic +import io.mockk.runs +import io.mockk.unmockkAll +import io.mockk.verify +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildTone +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * A tap on the "tap for details" Quick Build status line does what a tap on the button does + * (ADFA-7138, F23): since ADFA-6574 a tap on the greyed-out button flashes why it is greyed out, + * so a tap on the line must flash the same reason, not do nothing. + * + * Drives the activity's status-line callback with a Quick Build action registered as the toolbar + * would leave it. The reason comes from the real [QuickBuildAction.disabledReason]; only its + * inputs are stubbed: a release variant selected, no Quick Build session. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = QuickBuildGreyedStatusLineTapTest.TestApp::class) +class QuickBuildGreyedStatusLineTapTest { + open class TestApp : BaseApplication() + + private val registry = ActionsRegistry.getInstance() + private var previous: ActionItem? = null + private lateinit var activity: EditorHandlerActivity + + @Before + fun setUp() { + previous = registry.findAction(EDITOR_TOOLBAR, QuickBuildAction.ID) + mockkObject(IProjectManager.Companion) + every { IProjectManager.getInstance() } returns mockk(relaxed = true) + mockkObject(GradleQuickBuildProvisioner.Companion) + every { GradleQuickBuildProvisioner.selectedVariantName() } returns "release" + mockkObject(QuickBuildAction.Companion) + every { QuickBuildAction.currentTone() } returns QuickBuildTone.READY + mockkStatic("com.itsaky.androidide.utils.FlashbarActivityUtilsKt") + every { any().flashInfoLong(any()) } just runs + activity = Robolectric.buildActivity(EditorHandlerActivity::class.java).get() + } + + @After + fun tearDown() { + registry.unregisterAction(QuickBuildAction.ID) + previous?.let(registry::registerAction) + unmockkAll() + } + + private fun registerQuickBuild(enabled: Boolean): ActionItem { + val action = mockk(relaxed = true) + every { action.id } returns QuickBuildAction.ID + every { action.location } returns EDITOR_TOOLBAR + every { action.enabled } returns enabled + registry.registerAction(action) + return action + } + + /** What the bottom sheet's status line calls when the user taps it. */ + private fun tapStatusLine() { + EditorHandlerActivity::class.java + .getDeclaredMethod("onQuickBuildStatusLineTapped") + .apply { isAccessible = true } + .invoke(activity) + } + + @Test + fun `a status-line tap while Quick Build is greyed out for a release variant flashes why`() { + val quickBuild = registerQuickBuild(enabled = false) + + tapStatusLine() + + val reason = activity.getString(R.string.quick_build_non_debuggable_variant, "release") + verify(exactly = 1) { activity.flashInfoLong(reason) } + coVerify(exactly = 0) { quickBuild.execAction(any()) } + } + + @Test + fun `a status-line tap while Quick Build is enabled runs it and flashes nothing`() { + val quickBuild = registerQuickBuild(enabled = true) + + tapStatusLine() + + coVerify(timeout = 5_000) { quickBuild.execAction(any()) } + verify(exactly = 0) { activity.flashInfoLong(any()) } + } +} diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index c8f068ea62..343b5a7fe6 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -208,8 +208,8 @@ dependency, and runs the script on both APKs. The release must pass. The debug A The plugin logs why and the build is a normal one. The IDE does not provision Quick Build for such a project either (`GradleQuickBuildProvisioner.sqliteDebuggerRefusal`): it shows `quick_build_disabled_sqlite_debugger`, which says Quick Build is off while the SQLite debugger is on. The editor's status line then reads - `quick_build_status_off_sqlite_debugger`, and a tap on it, like a tap on the Quick Build button, shows that - message again. + `quick_build_status_off_sqlite_debugger`, and a tap on it does what a tap on the Quick Build button does: it + shows that message again, or, while the button is greyed out (a release variant, a plugin project), why it is. - Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not rewritten. A string constant that names one of the renamed classes (dots or slashes, `$` or `.` before a nested class, alone or in a type descriptor) logs a warning with class, method and line, in the classes the fail rule From 542307fd70e4103a19ccf008628bd62bfec6863b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 16:46:35 -0800 Subject: [PATCH 140/203] ADFA-7138 Count a row of an SQLiteCursor[] as an SQLite cursor in the array-store check A store of `b ? c : cs[0]` into an Android cursor array (cs an SQLiteCursor[]) only warned, because the AALOAD result carried no tag and "every path" was false. A row of an array whose component is SQLiteCursor or a renamed subclass is now tagged, so the build fails again. Docs: the array-store rule is path-insensitive and can give a false positive when the cursor is null on exactly the path where the array is set. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 ++ .../gradle/sqlite/SqliteRewriter.kt | 38 ++++++++++++++++--- .../gradle/sqlite/SqliteRewriterTest.kt | 31 +++++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 343b5a7fe6..61a5ce76f0 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -210,6 +210,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A says Quick Build is off while the SQLite debugger is on. The editor's status line then reads `quick_build_status_off_sqlite_debugger`, and a tap on it does what a tap on the Quick Build button does: it shows that message again, or, while the button is greyed out (a release variant, a plugin project), why it is. +- The array-store check is path-insensitive, so it gives a false positive when the cursor is null on exactly the path where + the array is set (`a = null; c = null; if (b) a = p; else c = query(); a[0] = c` fails the build although the store + never runs with both set). - Classes loaded by name (`Class.forName`, reflection, strings naming `android.database.sqlite.*`) are not rewritten. A string constant that names one of the renamed classes (dots or slashes, `$` or `.` before a nested class, alone or in a type descriptor) logs a warning with class, method and line, in the classes the fail rule diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 668c3634b3..afe0b49527 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -200,17 +200,24 @@ object SqliteRewriter { val androidCursorArray: Type?, val nullConstant: Boolean, val everyPathCursor: Boolean, + val renamedCursorArray: Boolean = false, ) : BasicValue(type) { // as TaintValue: Frame.merge keeps the old value when the merged one equals it override fun equals(other: Any?): Boolean = other is BasicValue && super.equals(other) && renamedCursor == ((other as? StaticCursorValue)?.renamedCursor ?: false) && androidCursorArray == (other as? StaticCursorValue)?.androidCursorArray && nullConstant == ((other as? StaticCursorValue)?.nullConstant ?: false) && - everyPathCursor == ((other as? StaticCursorValue)?.everyPathCursor ?: false) + everyPathCursor == ((other as? StaticCursorValue)?.everyPathCursor ?: false) && + renamedCursorArray == ((other as? StaticCursorValue)?.renamedCursorArray ?: false) override fun hashCode(): Int = - (((super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode()) * 31 + if (nullConstant) 1 else 0) * - 31 + if (everyPathCursor) 1 else 0 + ( + ( + ((super.hashCode() * 31 + if (renamedCursor) 1 else 0) * 31 + androidCursorArray.hashCode()) * 31 + + if (nullConstant) 1 else 0 + ) * + 31 + if (everyPathCursor) 1 else 0 + ) * 31 + if (renamedCursorArray) 1 else 0 } private class ClassRewrite( @@ -848,8 +855,8 @@ object SqliteRewriter { * some paths only, it is a warning, because the paths of the value are not matched with those of the array, and * the store throws only on a path that brings both. Not checked: stores into a Cursor[] or Object[], allowed on * purpose although one can be such an array at run time; a store whose array type differs between the paths that - * merge before it (null on a path is no difference); cursors loaded from arrays, which are not followed; an - * SQLiteCursor[] used as one of those types' arrays. + * merge before it (null on a path is no difference); cursors loaded from arrays other than an SQLiteCursor[] + * (a row of one is an SQLite cursor), which are not followed; an SQLiteCursor[] used as one of those types' arrays. */ fun implicitCursorConversions(m: MethodNode): Map { if (!mayConvertToAndroidCursor(m)) return emptyMap() @@ -860,7 +867,14 @@ object SqliteRewriter { return if (v.isReference) { val nullConstant = type == BasicInterpreter.NULL_TYPE val renamed = isRenamedCursorType(type) - StaticCursorValue(v.type, renamed, androidCursorArray(type), nullConstant, renamed || nullConstant) + StaticCursorValue( + v.type, + renamed, + androidCursorArray(type), + nullConstant, + renamed || nullConstant, + type != null && type.sort == Type.ARRAY && type.dimensions == 1 && isRenamedCursorType(type.elementType), + ) } else { v } @@ -880,6 +894,11 @@ object SqliteRewriter { if (insn.opcode == Opcodes.AALOAD && array != null && array.dimensions > 1) { return newValue(Type.getType(array.descriptor.substring(1))) } + // BasicInterpreter types the row as Object; a row of an SQLiteCursor[] (or of a renamed subclass's array) is an + // SQLite cursor on every path where it is not null + if (insn.opcode == Opcodes.AALOAD && (value1 as? StaticCursorValue)?.renamedCursorArray == true) { + return StaticCursorValue(super.binaryOperation(insn, value1, value2)?.type, true, null, false, true) + } return super.binaryOperation(insn, value1, value2) } @@ -898,6 +917,12 @@ object SqliteRewriter { s2?.nullConstant == true -> s1?.androidCursorArray else -> s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray } } + val renamedArray = + when { + s1?.nullConstant == true -> s2?.renamedCursorArray == true + s2?.nullConstant == true -> s1?.renamedCursorArray == true + else -> s1?.renamedCursorArray == true && s2?.renamedCursorArray == true + } val merged = StaticCursorValue( value1.type, @@ -906,6 +931,7 @@ object SqliteRewriter { s1?.nullConstant == true && s2?.nullConstant == true, // true on null, so null is neutral; a plain BasicValue (an element loaded from an array) is not a known cursor s1?.everyPathCursor == true && s2?.everyPathCursor == true, + renamedArray, ) return if (merged == value1) value1 else merged } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 22c14ac40f..f669001b49 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -2038,6 +2038,37 @@ class SqliteRewriterTest { assertThat(warnings).isEmpty() } + @Test + fun `a store of an element loaded from an SQLite cursor array still fails the build when the other path is an SQLite cursor`() { + val classes = + Compiler.compile( + listOf( + src( + "p.LoadedElement", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class LoadedElement { + void loaded(AbstractCursor[] a, SQLiteCursor c, SQLiteCursor[] cs, boolean b) { + Object[] arr = a; + arr[0] = b ? c : cs[0]; + } + } + """, + ), + ), + ) + val warnings = mutableListOf() + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/LoadedElement"]!!, hierarchy, warn = warnings::add) + } + // cs[0] is an SQLite cursor, so the value is one on every path, and the store throws ArrayStoreException when cs[0] is taken + assertThat(e.message).contains("an SQLite cursor stored into an array of android.database.AbstractCursor;") + assertThat(warnings).isEmpty() + } + @Test fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { fun covariant(pkg: String) = From e7d0da9a15a8c05b6d84e3ad93696d4853f60b57 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 17:03:51 -0800 Subject: [PATCH 141/203] ADFA-7138 Test and document that a row of an SQLiteCursor[] is an SQLite cursor for implicit conversions A row loaded from an SQLiteCursor[] returned or passed as AbstractCursor without a cast now fails the build, like any SQLite cursor. Add the test, and fix the docs line that said cursors loaded from arrays are not followed. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 8 +++-- .../gradle/sqlite/SqliteRewriterTest.kt | 35 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 61a5ce76f0..d9326a0dc1 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -72,7 +72,8 @@ cannot load, so the transform runs only on projects that opted in. Commenting th (requery's cursors extend its own copies of the first two, and implement only `android.database.Cursor`). The same conversion without a cast fails too: a value declared `SQLiteCursor`, or a subclass, returned, passed, called on, stored in a field, or held in a local as one of those three types (`AbstractCursor up(SQLiteCursor c) - { return c; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. So does storing one + { return c; }`). A row loaded from an `SQLiteCursor[]` (or an array of a subclass) counts the same way + (`AbstractCursor up(SQLiteCursor[] cs) { return cs[0]; }`). javac writes no `CHECKCAST` for it, and the renamed class would not verify. So does storing one into an array of those types (`AbstractCursor[] a; a[0] = c;`), which would throw `ArrayStoreException`: the array must be one on every path to the store where it is not `null`, from a parameter, field, call or `new`, or loaded from an array of them (`AbstractCursor[][] g; g[0][0] = c;`), and the value an SQLite cursor on every path @@ -223,8 +224,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A and a store whose array type differs between branches that merge is not checked (`null` on a branch counts as no difference). Both can still throw `ArrayStoreException`, in release builds too (the rewrite runs in every variant of an opted-in app). So can a store whose value is an SQLite cursor on some paths only, which logs a - warning and builds (see Rules): it throws when one path brings both the cursor and the array. Cursors loaded from - arrays are not followed: one counts as a value that is not an SQLite cursor. + warning and builds (see Rules): it throws when one path brings both the cursor and the array. A row loaded + from an `SQLiteCursor[]` (or an array of a subclass) is followed and counts as an SQLite cursor; rows of other + arrays are not followed, and one counts as a value that is not an SQLite cursor. - An array of `SQLiteCursor`, or of a subclass, used without a cast as an array of `AbstractCursor`, `AbstractWindowedCursor` or `CrossProcessCursor` (`AbstractCursor[] a = new SQLiteCursor[1];`; arrays are covariant) is not reported. After the rename it is an array of requery's `SQLiteCursor`, which is none of those, diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index f669001b49..1d4eb1d3e2 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -2069,6 +2069,41 @@ class SqliteRewriterTest { assertThat(warnings).isEmpty() } + @Test + fun `a row of an SQLite cursor array used as an Android cursor type without a cast fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.LoadedRow", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class LoadedRow { + AbstractCursor up(SQLiteCursor[] cs) { + return cs[0]; + } + int arg(SQLiteCursor[] cs) { + return count(cs[0]); + } + static int count(AbstractCursor c) { + return c.getCount(); + } + } + """, + ), + ), + ) + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/LoadedRow"]!!, hierarchy) + } + assertThat(e.message).contains("up([Landroid/database/sqlite/SQLiteCursor;)Landroid/database/AbstractCursor;") + assertThat(e.message).contains("arg([Landroid/database/sqlite/SQLiteCursor;)I") + assertThat(e.message).contains("without a cast") + } + @Test fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { fun covariant(pkg: String) = From 6858c9f4b32d64c1abca70226b4b856bfaeebd36 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 20:45:57 -0800 Subject: [PATCH 142/203] ADFA-7138 Follow a row of an SQLiteCursor[][] as an SQLiteCursor[] for implicit conversions renamedCursorArray is now the array type, of any dimension, so an AALOAD from an SQLiteCursor[][] (or a renamed subclass's) yields an SQLiteCursor[] row, as for AbstractCursor[][]. `return g[0][0]` as an AbstractCursor now fails the build instead of failing verification at run time. Adds a merge test, and fixes the StaticCursorValue KDoc and merge comment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 7 ++- .../gradle/sqlite/SqliteRewriter.kt | 38 +++++++----- .../gradle/sqlite/SqliteRewriterTest.kt | 61 +++++++++++++++++++ 3 files changed, 88 insertions(+), 18 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index d9326a0dc1..ffe4ad19ef 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -224,9 +224,10 @@ dependency, and runs the script on both APKs. The release must pass. The debug A and a store whose array type differs between branches that merge is not checked (`null` on a branch counts as no difference). Both can still throw `ArrayStoreException`, in release builds too (the rewrite runs in every variant of an opted-in app). So can a store whose value is an SQLite cursor on some paths only, which logs a - warning and builds (see Rules): it throws when one path brings both the cursor and the array. A row loaded - from an `SQLiteCursor[]` (or an array of a subclass) is followed and counts as an SQLite cursor; rows of other - arrays are not followed, and one counts as a value that is not an SQLite cursor. + warning and builds (see Rules): it throws when one path brings both the cursor and the array. An element + loaded from an `SQLiteCursor[]` (or an array of a subclass) counts as an SQLite cursor, and a row of an + `SQLiteCursor[][]` is followed as an `SQLiteCursor[]`, at any depth (so `return g[0][0]` as an `AbstractCursor` + fails the build); rows of other arrays are not followed, and one counts as a value that is not an SQLite cursor. - An array of `SQLiteCursor`, or of a subclass, used without a cast as an array of `AbstractCursor`, `AbstractWindowedCursor` or `CrossProcessCursor` (`AbstractCursor[] a = new SQLiteCursor[1];`; arrays are covariant) is not reported. After the rename it is an array of requery's `SQLiteCursor`, which is none of those, diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index afe0b49527..f9bd6fd1ec 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -191,8 +191,10 @@ object SqliteRewriter { * A reference whose static type, on some path, is SQLiteCursor or a subclass, which the rename makes requery's * ([renamedCursor]; [everyPathCursor] when it is one on every path where it is not null, so also for `null` * itself), or, on every path where it is not null, an array of one of the Android-only cursor types, of any - * dimension ([androidCursorArray], that array type). [nullConstant]: `null` on every path, which an element loaded - * from it counts as, since that load throws. + * dimension ([androidCursorArray], that array type), or, on every path where it is not null, an array of + * SQLiteCursor or of a subclass, of any dimension ([renamedCursorArray], that array type): a row of one is an array of + * the same kind, and an element of a one-dimensional one is a [renamedCursor]. [nullConstant]: `null` on every path, + * which an element loaded from it counts as, since that load throws. */ private class StaticCursorValue( type: Type?, @@ -200,7 +202,7 @@ object SqliteRewriter { val androidCursorArray: Type?, val nullConstant: Boolean, val everyPathCursor: Boolean, - val renamedCursorArray: Boolean = false, + val renamedCursorArray: Type? = null, ) : BasicValue(type) { // as TaintValue: Frame.merge keeps the old value when the merged one equals it override fun equals(other: Any?): Boolean = @@ -208,7 +210,7 @@ object SqliteRewriter { androidCursorArray == (other as? StaticCursorValue)?.androidCursorArray && nullConstant == ((other as? StaticCursorValue)?.nullConstant ?: false) && everyPathCursor == ((other as? StaticCursorValue)?.everyPathCursor ?: false) && - renamedCursorArray == ((other as? StaticCursorValue)?.renamedCursorArray ?: false) + renamedCursorArray == (other as? StaticCursorValue)?.renamedCursorArray override fun hashCode(): Int = ( @@ -217,7 +219,7 @@ object SqliteRewriter { if (nullConstant) 1 else 0 ) * 31 + if (everyPathCursor) 1 else 0 - ) * 31 + if (renamedCursorArray) 1 else 0 + ) * 31 + renamedCursorArray.hashCode() } private class ClassRewrite( @@ -856,7 +858,8 @@ object SqliteRewriter { * the store throws only on a path that brings both. Not checked: stores into a Cursor[] or Object[], allowed on * purpose although one can be such an array at run time; a store whose array type differs between the paths that * merge before it (null on a path is no difference); cursors loaded from arrays other than an SQLiteCursor[] - * (a row of one is an SQLite cursor), which are not followed; an SQLiteCursor[] used as one of those types' arrays. + * of any dimension (an element of a one-dimensional one is an SQLite cursor, a row of a deeper one is an array of + * them), which are not followed; an SQLiteCursor[] used as one of those types' arrays. */ fun implicitCursorConversions(m: MethodNode): Map { if (!mayConvertToAndroidCursor(m)) return emptyMap() @@ -873,7 +876,7 @@ object SqliteRewriter { androidCursorArray(type), nullConstant, renamed || nullConstant, - type != null && type.sort == Type.ARRAY && type.dimensions == 1 && isRenamedCursorType(type.elementType), + type?.takeIf { it.sort == Type.ARRAY && isRenamedCursorType(it.elementType) }, ) } else { v @@ -894,10 +897,15 @@ object SqliteRewriter { if (insn.opcode == Opcodes.AALOAD && array != null && array.dimensions > 1) { return newValue(Type.getType(array.descriptor.substring(1))) } - // BasicInterpreter types the row as Object; a row of an SQLiteCursor[] (or of a renamed subclass's array) is an - // SQLite cursor on every path where it is not null - if (insn.opcode == Opcodes.AALOAD && (value1 as? StaticCursorValue)?.renamedCursorArray == true) { - return StaticCursorValue(super.binaryOperation(insn, value1, value2)?.type, true, null, false, true) + // BasicInterpreter types the row as Object; a row of an SQLiteCursor[][] (or of a renamed subclass's array) is + // an SQLiteCursor[], and an element of an SQLiteCursor[] is an SQLite cursor, on every path where it is not null + val renamedArray = (value1 as? StaticCursorValue)?.renamedCursorArray + if (insn.opcode == Opcodes.AALOAD && renamedArray != null) { + return if (renamedArray.dimensions > 1) { + newValue(Type.getType(renamedArray.descriptor.substring(1))) + } else { + StaticCursorValue(super.binaryOperation(insn, value1, value2)?.type, true, null, false, true) + } } return super.binaryOperation(insn, value1, value2) } @@ -919,9 +927,9 @@ object SqliteRewriter { } val renamedArray = when { - s1?.nullConstant == true -> s2?.renamedCursorArray == true - s2?.nullConstant == true -> s1?.renamedCursorArray == true - else -> s1?.renamedCursorArray == true && s2?.renamedCursorArray == true + s1?.nullConstant == true -> s2?.renamedCursorArray + s2?.nullConstant == true -> s1?.renamedCursorArray + else -> s1?.renamedCursorArray?.takeIf { it == s2?.renamedCursorArray } } val merged = StaticCursorValue( @@ -929,7 +937,7 @@ object SqliteRewriter { s1?.renamedCursor == true || s2?.renamedCursor == true, array, s1?.nullConstant == true && s2?.nullConstant == true, - // true on null, so null is neutral; a plain BasicValue (an element loaded from an array) is not a known cursor + // true on null, so null is neutral; a plain BasicValue (an element of an array that is not followed) is not a known cursor s1?.everyPathCursor == true && s2?.everyPathCursor == true, renamedArray, ) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 1d4eb1d3e2..f44ab81d9f 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -2104,6 +2104,67 @@ class SqliteRewriterTest { assertThat(e.message).contains("without a cast") } + @Test + fun `an element of a row of an SQLite cursor 2D array used as an Android cursor type without a cast fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.LoadedGrid", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class LoadedGrid { + AbstractCursor up(SQLiteCursor[][] g) { + return g[0][0]; + } + } + """, + ), + ), + ) + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/LoadedGrid"]!!, hierarchy) + } + assertThat(e.message).contains("up([[Landroid/database/sqlite/SQLiteCursor;)Landroid/database/AbstractCursor;") + assertThat(e.message).contains("without a cast") + } + + @Test + fun `a merged SQLite cursor array keeps its type, and null on one path does not hide it`() { + val classes = + Compiler.compile( + listOf( + src( + "p.MergedArray", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class MergedArray { + AbstractCursor orNull(SQLiteCursor[] cs, boolean b) { + SQLiteCursor[] m = b ? cs : null; + return m[0]; + } + AbstractCursor either(SQLiteCursor[] cs1, SQLiteCursor[] cs2, boolean b) { + SQLiteCursor[] m = b ? cs1 : cs2; + return m[0]; + } + } + """, + ), + ), + ) + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/MergedArray"]!!, hierarchy) + } + assertThat(e.message).contains("orNull([Landroid/database/sqlite/SQLiteCursor;Z)Landroid/database/AbstractCursor;") + assertThat(e.message).contains("either([Landroid/database/sqlite/SQLiteCursor;[Landroid/database/sqlite/SQLiteCursor;Z)") + } + @Test fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { fun covariant(pkg: String) = From b68446b0bed59accce806456982dd82b3714a400 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:10:07 -0800 Subject: [PATCH 143/203] ADFA-7138 Call onQuickBuildStatusLineTapped directly in the greyed-out status line test The method is internal now, so QuickBuildGreyedStatusLineTapTest calls it on the activity without reflection. The assertions are unchanged; with runQuickBuildAction reverted to its old guard, the greyed-out case still fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/activities/editor/ProjectHandlerActivity.kt | 2 +- .../activities/editor/QuickBuildGreyedStatusLineTapTest.kt | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index e7b5e66df6..186bec223f 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1452,7 +1452,7 @@ abstract class ProjectHandlerActivity : * button does, through the same action - runs Quick Build, or, while the button is greyed out, * shows why - so the line cannot promise what the button would not. */ - protected abstract fun onQuickBuildStatusLineTapped() + internal abstract fun onQuickBuildStatusLineTapped() fun appendBuildOutput(str: String) { if (_binding == null || isDestroyed || isFinishing) return diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt index 134ac10b9f..c00164c705 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/QuickBuildGreyedStatusLineTapTest.kt @@ -78,10 +78,7 @@ class QuickBuildGreyedStatusLineTapTest { /** What the bottom sheet's status line calls when the user taps it. */ private fun tapStatusLine() { - EditorHandlerActivity::class.java - .getDeclaredMethod("onQuickBuildStatusLineTapped") - .apply { isAccessible = true } - .invoke(activity) + activity.onQuickBuildStatusLineTapped() } @Test From 2ae43d23ed64cc42b0ef9b767cf4a6cf0c62f97f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:39:22 -0800 Subject: [PATCH 144/203] ADFA-7138 Keep the cursor-array tag when a merge mixes SQLiteCursor[] and a subclass array The tag now survives a merge of two renamed cursor arrays of the same dimension, whichever classes. Comparing the types dropped it for SQLiteCursor[] against MyCursor[], so a store of an element of the merged array into an AbstractCursor[] was only a warning instead of a build failure. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriter.kt | 3 +- .../gradle/sqlite/SqliteRewriterTest.kt | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index f9bd6fd1ec..90d8ecdbbc 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -925,11 +925,12 @@ object SqliteRewriter { s2?.nullConstant == true -> s1?.androidCursorArray else -> s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray } } + // both paths hold renamed cursor arrays of the same dimension, whichever classes: the tag keeps the dimension val renamedArray = when { s1?.nullConstant == true -> s2?.renamedCursorArray s2?.nullConstant == true -> s1?.renamedCursorArray - else -> s1?.renamedCursorArray?.takeIf { it == s2?.renamedCursorArray } + else -> s1?.renamedCursorArray?.takeIf { s2?.renamedCursorArray?.dimensions == it.dimensions } } val merged = StaticCursorValue( diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index f44ab81d9f..7ba98aac76 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -2165,6 +2165,61 @@ class SqliteRewriterTest { assertThat(e.message).contains("either([Landroid/database/sqlite/SQLiteCursor;[Landroid/database/sqlite/SQLiteCursor;Z)") } + @Test + fun `a store of an element of a merged SQLite cursor array and subclass array still fails the build, in one and two dimensions`() { + val classes = + Compiler.compile( + listOf( + src( + "p.MyCursor", + """ + package p; + import android.database.sqlite.*; + public class MyCursor extends SQLiteCursor { + public MyCursor(SQLiteCursorDriver d, String t, SQLiteQuery q) { super(d, t, q); } + } + """, + ), + src( + "p.MixedArrays", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class MixedArrays { + void flat(AbstractCursor[] a, SQLiteCursor[] cs, MyCursor[] mcs, boolean b) { + Object[] arr = a; + arr[0] = (b ? cs : mcs)[0]; + } + void grid(AbstractCursor[] a, SQLiteCursor[][] g, MyCursor[][] mg, boolean b) { + Object[] arr = a; + arr[0] = (b ? g : mg)[0][0]; + } + } + """, + ), + ), + ) + val withSubclass = + ClassHierarchy { name -> + if (name == "p/MyCursor") { + listOf(A + "SQLiteCursor", "android/database/AbstractWindowedCursor", "java/lang/Object") + } else { + null + } + } + val warnings = mutableListOf() + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/MixedArrays"]!!, withSubclass, warn = warnings::add) + } + // the element is an SQLite cursor on every path, whichever of the two array types is taken, so these fail, not warn + assertThat(e.message).contains("flat(") + assertThat(e.message).contains("grid(") + assertThat(e.message).contains("an SQLite cursor stored into an array of android.database.AbstractCursor;") + assertThat(warnings).isEmpty() + } + @Test fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { fun covariant(pkg: String) = From f77079cdc2f8ada9759823bede5971a36971e07a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:15:44 -0800 Subject: [PATCH 145/203] ADFA-7138 Test a 3D SQLite cursor array, and name the 1D merge test a regression guard The merge test added with 6858c9f4b passes at e7d0da9a1 too: one-dimensional merges kept the tag before rows of an SQLiteCursor[][] were followed. It is renamed as a regression guard. The new test returns t[0][0][0] from an SQLiteCursor[][][] as an AbstractCursor, which fails the build only when rows are followed at any depth; with 6858c9f4b's and 2ae43d23e's code reverted it throws nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriterTest.kt | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 7ba98aac76..e93fb0da56 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -2133,7 +2133,38 @@ class SqliteRewriterTest { } @Test - fun `a merged SQLite cursor array keeps its type, and null on one path does not hide it`() { + fun `an element loaded from an SQLite cursor 3D array used as an Android cursor type without a cast fails the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.LoadedCube", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class LoadedCube { + AbstractCursor up(SQLiteCursor[][][] t) { + return t[0][0][0]; + } + } + """, + ), + ), + ) + // each row is followed as an array one dimension smaller, at any depth, not only for an SQLiteCursor[][] + val e = + assertThrows(SqliteRewriteException::class.java) { + SqliteRewriter.rewrite(classes["p/LoadedCube"]!!, hierarchy) + } + assertThat(e.message).contains("up([[[Landroid/database/sqlite/SQLiteCursor;)Landroid/database/AbstractCursor;") + assertThat(e.message).contains("without a cast") + } + + // a regression guard: this passed before rows of an SQLiteCursor[][] were followed too, when the tag was true or false + // and a merge already kept it; it checks that the tag, now an array type, is still kept for a one-dimensional array + @Test + fun `regression guard - a merged SQLite cursor array still counts, and null on one path does not hide it`() { val classes = Compiler.compile( listOf( From b9e037f3ff94aeb5e36c416530753cc7f5cfeeda Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 10:00:42 -0800 Subject: [PATCH 146/203] ADFA-7138 Test that an SQLiteCursor[] merged with an Object[] or a 2D array never fails the build The element of such a merged array is not followed: the merge drops the tag, so storing it into an AbstractCursor[] does not fail the build, whichever branch comes first. With the SQLiteCursor[] branch analysed first, the element was already seen as an SQLite cursor, so the store warns that it is one on some paths only; the test pins that, and the docs now say so. Without the takeIf in merge, both such methods fail the build; without its dimension check, the 2D one does. A flipped comparison is not caught: it drops the tag even when a value merges with itself, which is what this test expects. The renamedCursorArray KDoc now says that after a merge its element class is the first merged value's, so only its dimensions, and that it is not null, mean anything. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 ++ .../gradle/sqlite/SqliteRewriter.kt | 8 +-- .../gradle/sqlite/SqliteRewriterTest.kt | 50 +++++++++++++++++++ 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index ffe4ad19ef..fd4e778db9 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -228,6 +228,9 @@ dependency, and runs the script on both APKs. The release must pass. The debug A loaded from an `SQLiteCursor[]` (or an array of a subclass) counts as an SQLite cursor, and a row of an `SQLiteCursor[][]` is followed as an `SQLiteCursor[]`, at any depth (so `return g[0][0]` as an `AbstractCursor` fails the build); rows of other arrays are not followed, and one counts as a value that is not an SQLite cursor. + That includes an array that is an `SQLiteCursor[]` on one branch only (an `Object[]` or an `SQLiteCursor[][]` on + the other), except that when the analysis reaches the `SQLiteCursor[]` branch first, its row still counts as an + SQLite cursor on some paths, so storing it logs that warning; with the branches swapped it logs nothing. - An array of `SQLiteCursor`, or of a subclass, used without a cast as an array of `AbstractCursor`, `AbstractWindowedCursor` or `CrossProcessCursor` (`AbstractCursor[] a = new SQLiteCursor[1];`; arrays are covariant) is not reported. After the rename it is an array of requery's `SQLiteCursor`, which is none of those, diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 90d8ecdbbc..7b37e945c1 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -192,9 +192,11 @@ object SqliteRewriter { * ([renamedCursor]; [everyPathCursor] when it is one on every path where it is not null, so also for `null` * itself), or, on every path where it is not null, an array of one of the Android-only cursor types, of any * dimension ([androidCursorArray], that array type), or, on every path where it is not null, an array of - * SQLiteCursor or of a subclass, of any dimension ([renamedCursorArray], that array type): a row of one is an array of - * the same kind, and an element of a one-dimensional one is a [renamedCursor]. [nullConstant]: `null` on every path, - * which an element loaded from it counts as, since that load throws. + * SQLiteCursor or of a subclass, of any dimension ([renamedCursorArray], an array type of that dimension; after a + * merge of, say, an SQLiteCursor[] and a MyCursor[], its element class is the first merged value's, so only its + * dimensions, and that it is not null, mean anything): a row of one is an array of the same kind, and an element of + * a one-dimensional one is a [renamedCursor]. [nullConstant]: `null` on every path, which an element loaded from it + * counts as, since that load throws. */ private class StaticCursorValue( type: Type?, diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index e93fb0da56..f3dedbb98d 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -2251,6 +2251,56 @@ class SqliteRewriterTest { assertThat(warnings).isEmpty() } + @Test + fun `an element of an SQLite cursor array merged with an Object array or a 2D one does not fail the build`() { + val classes = + Compiler.compile( + listOf( + src( + "p.UnfollowedMerges", + """ + package p; + import android.database.*; + import android.database.sqlite.*; + public class UnfollowedMerges { + void cursorsOrObjects(AbstractCursor[] a, SQLiteCursor[] cs, Object[] os, boolean b) { + Object[] arr = a; + arr[0] = (b ? cs : os)[0]; + } + void objectsOrCursors(AbstractCursor[] a, SQLiteCursor[] cs, Object[] os, boolean b) { + Object[] arr = a; + arr[0] = (b ? os : cs)[0]; + } + void cursorsOrGrid(AbstractCursor[] a, SQLiteCursor[] cs, SQLiteCursor[][] g, boolean b) { + Object[] arr = a; + arr[0] = (b ? cs : g)[0]; + } + void gridOrCursors(AbstractCursor[] a, SQLiteCursor[] cs, SQLiteCursor[][] g, boolean b) { + Object[] arr = a; + arr[0] = (b ? g : cs)[0]; + } + } + """, + ), + ), + ) + val warnings = mutableListOf() + // on one path the array is not an SQLite cursor array of the same dimension, so the merge drops the tag and the + // element is not followed: no exception. Both orders, since a merge keeps the first merged value's tag, so only + // objectsOrCursors and gridOrCursors fail the build if that check is lost + SqliteRewriter.rewrite(classes["p/UnfollowedMerges"]!!, hierarchy, warn = warnings::add) + // the analysis visits the SQLiteCursor[] path first in these two and has already seen its element as an SQLite + // cursor; the element after the merge is not one, so the store's value is one on some paths only, which warns + val some = + "is an SQLite cursor on some paths only; requery's SQLiteCursor is not one, so the store may throw " + + "ArrayStoreException at run time when the value is an SQLite cursor" + assertThat(warnings) + .containsExactly( + "p.UnfollowedMerges.objectsOrCursors (line 12): the value stored into an array of android.database.AbstractCursor $some", + "p.UnfollowedMerges.gridOrCursors (line 20): the value stored into an array of android.database.AbstractCursor $some", + ).inOrder() + } + @Test fun `an SQLite cursor array used as an Android cursor array is not checked, and would not verify`() { fun covariant(pkg: String) = From 7b270b4048103b5f9643a469f424b4011ec52612 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 10:32:03 -0800 Subject: [PATCH 147/203] ADFA-7138 Test that merge keeps the cursor-array tag only for the same dimensions No build-level test caught a flipped or removed takeIf in the renamedCursorArray merge: the analysis carries the first branch's value to the store anyway. Extract the interpreter's merge into SqliteRewriter.mergeCursorValues (StaticCursorValue and the function are internal, only so the unit test can call them) and test it directly: the same dimension keeps the tag, different dimensions or no tag drop it, and an SQLiteCursor[] with a subclass array keeps it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriter.kt | 81 +++++++++++-------- .../gradle/sqlite/SqliteRewriterMergeTest.kt | 49 +++++++++++ 2 files changed, 95 insertions(+), 35 deletions(-) create mode 100644 gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterMergeTest.kt diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 7b37e945c1..032cdd794f 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -196,9 +196,9 @@ object SqliteRewriter { * merge of, say, an SQLiteCursor[] and a MyCursor[], its element class is the first merged value's, so only its * dimensions, and that it is not null, mean anything): a row of one is an array of the same kind, and an element of * a one-dimensional one is a [renamedCursor]. [nullConstant]: `null` on every path, which an element loaded from it - * counts as, since that load throws. + * counts as, since that load throws. Internal only so that [SqliteRewriterMergeTest] can build one. */ - private class StaticCursorValue( + internal class StaticCursorValue( type: Type?, val renamedCursor: Boolean, val androidCursorArray: Type?, @@ -224,6 +224,49 @@ object SqliteRewriter { ) * 31 + renamedCursorArray.hashCode() } + /** + * What [implicitCursorConversions]'s interpreter answers for a merge that involves a [StaticCursorValue], or null when + * it has none to give and the merge is BasicInterpreter's. A cursor-array tag survives a merge only when + * both paths agree on it, except that [StaticCursorValue.renamedCursorArray] needs only the same dimensions, and `null` on + * one path is neutral. Internal only so that the unit test can call it. + */ + internal fun mergeCursorValues( + value1: BasicValue, + value2: BasicValue, + ): BasicValue? { + val s1 = value1 as? StaticCursorValue + val s2 = value2 as? StaticCursorValue + // BasicInterpreter.merge answers UNINITIALIZED for values that differ in either flag + if ((s1 != null || s2 != null) && value1.type != null && value1.type == value2.type) { + // null on one path does not hide the array on the other: `AbstractCursor[] a = null; if (b) a = p;` + val array = + when { + s1?.nullConstant == true -> s2?.androidCursorArray + s2?.nullConstant == true -> s1?.androidCursorArray + else -> s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray } + } + // both paths hold renamed cursor arrays of the same dimension, whichever classes: the tag keeps the dimension + val renamedArray = + when { + s1?.nullConstant == true -> s2?.renamedCursorArray + s2?.nullConstant == true -> s1?.renamedCursorArray + else -> s1?.renamedCursorArray?.takeIf { s2?.renamedCursorArray?.dimensions == it.dimensions } + } + val merged = + StaticCursorValue( + value1.type, + s1?.renamedCursor == true || s2?.renamedCursor == true, + array, + s1?.nullConstant == true && s2?.nullConstant == true, + // true on null, so null is neutral; a plain BasicValue (an element of an array that is not followed) is not a known cursor + s1?.everyPathCursor == true && s2?.everyPathCursor == true, + renamedArray, + ) + return if (merged == value1) value1 else merged + } + return null + } + private class ClassRewrite( val cn: ClassNode, val policy: RewritePolicy, @@ -915,39 +958,7 @@ object SqliteRewriter { override fun merge( value1: BasicValue, value2: BasicValue, - ): BasicValue { - val s1 = value1 as? StaticCursorValue - val s2 = value2 as? StaticCursorValue - // BasicInterpreter.merge answers UNINITIALIZED for values that differ in either flag - if ((s1 != null || s2 != null) && value1.type != null && value1.type == value2.type) { - // null on one path does not hide the array on the other: `AbstractCursor[] a = null; if (b) a = p;` - val array = - when { - s1?.nullConstant == true -> s2?.androidCursorArray - s2?.nullConstant == true -> s1?.androidCursorArray - else -> s1?.androidCursorArray?.takeIf { it == s2?.androidCursorArray } - } - // both paths hold renamed cursor arrays of the same dimension, whichever classes: the tag keeps the dimension - val renamedArray = - when { - s1?.nullConstant == true -> s2?.renamedCursorArray - s2?.nullConstant == true -> s1?.renamedCursorArray - else -> s1?.renamedCursorArray?.takeIf { s2?.renamedCursorArray?.dimensions == it.dimensions } - } - val merged = - StaticCursorValue( - value1.type, - s1?.renamedCursor == true || s2?.renamedCursor == true, - array, - s1?.nullConstant == true && s2?.nullConstant == true, - // true on null, so null is neutral; a plain BasicValue (an element of an array that is not followed) is not a known cursor - s1?.everyPathCursor == true && s2?.everyPathCursor == true, - renamedArray, - ) - return if (merged == value1) value1 else merged - } - return super.merge(value1, value2) - } + ): BasicValue = mergeCursorValues(value1, value2) ?: super.merge(value1, value2) } val frames: Array?> = try { diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterMergeTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterMergeTest.kt new file mode 100644 index 0000000000..2b42a3c2ab --- /dev/null +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterMergeTest.kt @@ -0,0 +1,49 @@ +package com.itsaky.androidide.gradle.sqlite + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.objectweb.asm.Type + +/** + * [SqliteRewriter.mergeCursorValues] on its own. The build-level tests cannot pin the `renamedCursorArray` tag: the + * analysis carries the first branch's value to a store anyway, so a merge that wrongly drops or keeps the tag still + * passes them. + */ +class SqliteRewriterMergeTest { + // BasicInterpreter types every array reference as Object, so both merged values have the same type, as in a real frame + private val objectType = Type.getObjectType("java/lang/Object") + private val sqliteCursorArray = Type.getType("[Lio/requery/android/database/sqlite/SQLiteCursor;") + private val subclassArray = Type.getType("[Lp/MyCursor;") + + private fun tagged(tag: Type?) = SqliteRewriter.StaticCursorValue(objectType, false, null, false, true, tag) + + private fun merged( + a: SqliteRewriter.StaticCursorValue, + b: SqliteRewriter.StaticCursorValue, + ) = (SqliteRewriter.mergeCursorValues(a, b) as SqliteRewriter.StaticCursorValue).renamedCursorArray + + @Test + fun `two values tagged with the same dimension keep the tag`() { + assertThat(merged(tagged(sqliteCursorArray), tagged(sqliteCursorArray))).isEqualTo(sqliteCursorArray) + } + + @Test + fun `values tagged with different dimensions drop the tag`() { + val twoDimensions = Type.getType("[[Lio/requery/android/database/sqlite/SQLiteCursor;") + assertThat(merged(tagged(sqliteCursorArray), tagged(twoDimensions))).isNull() + assertThat(merged(tagged(twoDimensions), tagged(sqliteCursorArray))).isNull() + } + + @Test + fun `a value without a tag drops the tag`() { + assertThat(merged(tagged(sqliteCursorArray), tagged(null))).isNull() + assertThat(merged(tagged(null), tagged(sqliteCursorArray))).isNull() + assertThat(merged(tagged(null), tagged(null))).isNull() + } + + @Test + fun `an SQLiteCursor array and a subclass array of the same dimension keep the tag`() { + assertThat(merged(tagged(sqliteCursorArray), tagged(subclassArray))).isEqualTo(sqliteCursorArray) + assertThat(merged(tagged(subclassArray), tagged(sqliteCursorArray))).isEqualTo(subclassArray) + } +} From b2d7bbebcb4c315d0210b0e819912e4832249829 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:11 -0800 Subject: [PATCH 148/203] ADFA-7138 Name the opt-out that works with property precedence Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 6 ++++-- .../com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt | 4 +++- .../itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt | 5 +++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index fd4e778db9..efc50da0bf 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -37,7 +37,9 @@ with an actionable message when the variant's runtime classpath has no `androidx/core/os/CancellationSignal.class`. The property is required because requery reaches apps only through `libs/`. Without it the rewritten classes -cannot load, so the transform runs only on projects that opted in. Commenting the line out turns it off. +cannot load, so the transform runs only on projects that opted in. To turn it off, set `cogo.sqliteDebugger=false` in +the file that defines it, or in one read earlier (Gradle user home, then the app module, then the root: the first +file that defines the property decides). Commenting the line out can expose another file's `true`. ## Rules @@ -85,7 +87,7 @@ cannot load, so the transform runs only on projects that opted in. Commenting th or an early return when it is false) is not reported when the guard holds on every path to the cast: in `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together, with - the way out for a library class, which the user cannot change: comment out `cogo.sqliteDebugger=true`. A platform method outside the renamed set whose + the way out for a library class, which the user cannot change: set `cogo.sqliteDebugger=false` in the file that defines it, or in one read earlier. A platform method outside the renamed set whose descriptor mentions a renamed class (found with javap over android.jar: the other `DatabaseUtils` methods `blobFileDescriptorForQuery` and `bindObjectToProgram`, `DatabaseUtils$InsertHelper`, `OpenParams` accessors) cannot link once the descriptor is renamed, so a call to one that is not redirected above fails diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 032cdd794f..10f042f8a5 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -80,7 +80,9 @@ object SqliteRewriter { /** The transform cannot tell an app class from a library class, so the message covers both. */ private const val WAY_OUT = "If this class is the app's, change the code above. If it is in a library, the library cannot run on " + - "requery: comment out cogo.sqliteDebugger=true in gradle.properties to build without the SQLite debugger." + "requery: set cogo.sqliteDebugger=false in the gradle.properties that defines it, or in one read earlier " + + "(the first file that defines it decides: Gradle user home, then the app module, then the root), " + + "to build without the SQLite debugger. Commenting the line out can expose another file's true." private val remapper = object : Remapper() { diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index f3dedbb98d..1a2830527e 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -436,7 +436,8 @@ class SqliteRewriterTest { val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Lib"]!!, hierarchy) } val lastLine = e.message!!.lines().last() assertThat(lastLine).contains("in a library") - assertThat(lastLine).contains("comment out cogo.sqliteDebugger=true in gradle.properties") + assertThat(lastLine).contains("set cogo.sqliteDebugger=false in the gradle.properties that defines it, or in one read earlier") + assertThat(lastLine).contains("Gradle user home, then the app module, then the root") } @Test @@ -1129,7 +1130,7 @@ class SqliteRewriterTest { assertThat(message).contains("direct()Ljava/lang/String; (line ") assertThat(message).contains("viaConstant()Ljava/lang/String; (line ") assertThat(message).contains("COLLATE UNICODE") - assertThat(message).doesNotContain("fine") + assertThat(message).doesNotContain("fine()") } @Test From ece7a6766b38cacfd3a637a0e20f8ba72fcee07f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:11 -0800 Subject: [PATCH 149/203] ADFA-7138 Find COLLATE UNICODE through comments and quotes, and not in UNICODE_CI Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 +- .../gradle/sqlite/SqliteRewriteRules.kt | 14 ++++++-- .../gradle/sqlite/SqliteRewriterTest.kt | 36 +++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index efc50da0bf..ad9ffab14e 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -193,7 +193,8 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - Room's `BundledSQLiteDriver` is not covered (it brings its own SQLite). - requery's native library is built without ICU: there is no `UNICODE` collator (a `COLLATE UNICODE` string - constant fails the build, see above) and `LOCALIZED` compares bytes (a warning). + constant fails the build, see above; the clause is found through whitespace, SQL comments and a quoted name, and + `UNICODE_CI` is a different collation and passes) and `LOCALIZED` compares bytes (a warning). - `SupportSQLiteDatabase.execPerConnectionSQL` is unsupported (see the design change): no build failure, an `UnsupportedOperationException` when called. - Passing an Android `CursorWindow` where a (renamed) `SQLiteClosable` is expected cannot work: android's diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index d06adc1c59..bff457f4f8 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -34,8 +34,18 @@ internal object SqliteRewriteRules { const val CORE_SIGNAL = "androidx/core/os/CancellationSignal" const val CONTEXT = "android/content/Context" - val COLLATE_UNICODE = Regex("COLLATE\\s+UNICODE", RegexOption.IGNORE_CASE) - val COLLATE_LOCALIZED = Regex("COLLATE\\s+LOCALIZED", RegexOption.IGNORE_CASE) + /** + * A COLLATE clause names its collation after whitespace or a SQL comment, bare or quoted ("x", 'x', [x], `x`). + * The word boundary keeps a custom collation such as UNICODE_CI out. + */ + private fun collateRule(name: String) = + Regex( + "COLLATE(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))+[\"'\\[`]?$name\\b", + setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL), + ) + + val COLLATE_UNICODE = collateRule("UNICODE") + val COLLATE_LOCALIZED = collateRule("LOCALIZED") const val HELPER = "org/appdevforall/sqliterewrite/SqliteRewriteRuntime" const val HELPER_PACKAGE_PREFIX = "org/appdevforall/sqliterewrite/" diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 1a2830527e..29b2d009d9 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1133,6 +1133,42 @@ class SqliteRewriterTest { assertThat(message).doesNotContain("fine()") } + @Test + fun `COLLATE UNICODE is found through comments and quotes, and a custom UNICODE_CI collation passes`() { + val forms = + listOf( + "COLLATE /* c */ UNICODE", + "COLLATE -- c\\n UNICODE", + "COLLATE \\\"UNICODE\\\"", + "COLLATE 'UNICODE'", + "COLLATE [UNICODE]", + "COLLATE `UNICODE`", + ) + for (form in forms) { + val classes = + Compiler.compile( + listOf( + src( + "p.Q", + "package p; public class Q { String q() { return \"SELECT * FROM t ORDER BY n $form\"; } }", + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java, { SqliteRewriter.rewrite(classes["p/Q"]!!) }, "form: $form") + assertThat(e.message).contains("COLLATE UNICODE") + } + val ok = + Compiler.compile( + listOf( + src( + "p.Ci", + "package p; public class Ci { String q() { return \"SELECT * FROM t ORDER BY n COLLATE UNICODE_CI\"; } }", + ), + ), + ) + SqliteRewriter.rewrite(ok["p/Ci"]!!) + } + @Test fun `COLLATE LOCALIZED only warns`() { val classes = From 6f0ee167f904e30b104584d1d460df9096f91da6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:12 -0800 Subject: [PATCH 150/203] ADFA-7138 Reject a driver that declares both query overloads Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 2 +- .../gradle/sqlite/SqliteRewriter.kt | 8 +++++- .../gradle/sqlite/SqliteRewriterTest.kt | 26 +++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index ad9ffab14e..b91bb82d7d 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -113,7 +113,7 @@ file that defines the property decides). Commenting the line out can expose anot write a lambda (its body is an ordinary call, which the rules handle). The rules are not applied to the handle itself: it cannot be redirected in place, and its descriptor is fixed by the call site. - Frames: `COPY_FRAMES`, AGP's default. The one change that breaks them is a retyped - `SQLiteCursorDriver.query` implementation, whose `String[]` parameter becomes `Object[]` while its body, and + `SQLiteCursorDriver.query` implementation (a class that also declares the `Object[]` overload fails the build: the retype would give it two identical methods), whose `String[]` parameter becomes `Object[]` while its body, and the full frames copied from it, still say `String[]`. For each non-abstract method whose descriptor is retyped that way, the rewriter inserts `ALOAD n; CHECKCAST [Ljava/lang/String;; ASTORE n` at method entry, so the body stays valid, and writes every frame of that method in full (compressed frames are relative to the implicit first diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 10f042f8a5..8a872179e7 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -291,7 +291,13 @@ object SqliteRewriter { } if (policy.fail) bypassedOverride(m)?.let { violations += it } if (policy.redirect && m.name == Rules.DRIVER_QUERY_NAME && m.desc == Rules.DRIVER_QUERY_DESC) { - retypeParameters(m, Rules.DRIVER_QUERY_NEW_DESC) + if (cn.methods.any { it !== m && it.name == m.name && it.desc == Rules.DRIVER_QUERY_NEW_DESC }) { + // Retyping would leave two methods with one name and descriptor, which D8 rejects without a class or line. + violations += "method '${m.name}${m.desc}' and '${m.name}${Rules.DRIVER_QUERY_NEW_DESC}' are both declared; " + + "the rewrite retypes the first to the second's descriptor, so the class would declare it twice" + } else { + retypeParameters(m, Rules.DRIVER_QUERY_NEW_DESC) + } } rewriteMethod(m) } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 29b2d009d9..f08faf51cc 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1043,6 +1043,32 @@ class SqliteRewriterTest { assertThat(RewritePolicy.forClass("androidx/core/database/sqlite/SQLiteCursorCompat\$Api28Impl")).isEqualTo(RewritePolicy.NO_FAIL) } + @Test + fun `a driver that declares both query overloads fails with its class and method, before D8 would`() { + val classes = + Compiler.compile( + listOf( + src( + "p.TwoQueries", + """ + package p; + import android.database.Cursor; + import android.database.sqlite.*; + public abstract class TwoQueries implements SQLiteCursorDriver { + public Cursor query(SQLiteDatabase.CursorFactory f, String[] args) { return null; } + public Cursor query(SQLiteDatabase.CursorFactory f, Object[] args) { return null; } + } + """, + ), + ), + ) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/TwoQueries"]!!) } + val message = e.message!! + assertThat(message).contains("p.TwoQueries") + assertThat(message).contains("method 'query") + assertThat(message).contains("are both declared") + } + @Test fun `a cursor driver that uses its String array parameter verifies and links, with every kind of frame`() { val out = From cb956937748a53799bf8fe536b9a767c2116cfc7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:12 -0800 Subject: [PATCH 151/203] ADFA-7138 Check the missing-member descriptors by rebuilding them Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriteRulesTest.kt | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt index e1b5ac1b14..92266fb4cc 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -6,6 +6,27 @@ import org.junit.jupiter.api.Test import org.objectweb.asm.Type class SqliteRewriteRulesTest { + /** + * Rebuilds the descriptor from its parsed parts. `Type.getMethodType(d).descriptor` returns its input + * unchanged, so it accepts `(Q)V`; the rebuilt string differs, or ASM throws, for a malformed one. + */ + private fun isWellFormedDescriptor(desc: String): Boolean = + runCatching { + if (desc.startsWith("(")) { + Type.getMethodDescriptor(Type.getReturnType(desc), *Type.getArgumentTypes(desc)) == desc + } else { + Type.getType(desc).descriptor == desc + } + }.getOrDefault(false) + + @Test + fun `the descriptor check rejects a malformed descriptor and accepts a well-formed one`() { + assertThat(isWellFormedDescriptor("(Q)V")).isFalse() + assertThat(isWellFormedDescriptor("(Ljava/lang/String;I)V")).isTrue() + assertThat(isWellFormedDescriptor("Q")).isFalse() + assertThat(isWellFormedDescriptor("[Ljava/lang/String;")).isTrue() + } + @Test fun `every missing member lists the exact descriptors requery lacks, each a well-formed descriptor`() { // The rewriter fails a call or a field access only when its descriptor is in the entry's set, so an @@ -13,8 +34,7 @@ class SqliteRewriteRulesTest { for ((member, descs) in SqliteRewriteRules.MISSING_MEMBERS) { assertWithMessage(member).that(descs).isNotEmpty() for (desc in descs) { - val parsed = runCatching { if (desc.startsWith("(")) Type.getMethodType(desc) else Type.getType(desc) }.getOrNull() - assertWithMessage("$member descriptor '$desc'").that(parsed?.descriptor).isEqualTo(desc) + assertWithMessage("$member descriptor '$desc'").that(isWellFormedDescriptor(desc)).isTrue() } } } From e2690c8f3c2d2120d3d141801c3208d68afa4571 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:12 -0800 Subject: [PATCH 152/203] ADFA-7138 Throw the NullPointerException for a null Context in deleteDatabase Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt | 9 +++++++++ .../appdevforall/sqliterewrite/SqliteRewriteRuntime.java | 4 +++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt index fec4064e9b..0c77fd91c1 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt @@ -3,8 +3,10 @@ package com.itsaky.androidide.gradle.sqlite import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import com.itsaky.androidide.utils.FileProvider +import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import java.lang.ref.WeakReference +import java.lang.reflect.InvocationTargetException /** * The runtime helper's functions that need no device, run on the JVM from its bytecode compiled against android.jar, @@ -80,6 +82,13 @@ class SqliteRewriteRuntimeTest { private fun translate(flags: Int) = runtime.getMethod("translateOpenFlags", Int::class.javaPrimitiveType).invoke(null, flags) as Int + @Test + fun `deleteDatabase with a null context throws the NullPointerException, not false`() { + val method = runtime.getMethod("deleteDatabase", loader.loadClass("android.content.Context"), String::class.java) + val e = assertThrows(InvocationTargetException::class.java) { method.invoke(null, null, "x.db") } + assertThat(e.cause).isInstanceOf(NullPointerException::class.java) + } + private val readOnly = 1 private val createIfNecessary = 0x10000000 private val wal = 0x20000000 diff --git a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java index 7917a9c3bb..c1227a53b0 100644 --- a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java +++ b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.WeakHashMap; /** @@ -52,9 +53,10 @@ public final class SqliteRewriteRuntime { private static final Map> FORWARDERS = new WeakHashMap<>(); /** - * Same as Context.deleteDatabase, which also returns false on any exception. requery's deleteDatabase removes the -journal, -wal, -shm and -mj files next to the file, like Android's. + * Same as Context.deleteDatabase, which also returns false on any exception. requery's deleteDatabase removes the -journal, -wal, -shm and -mj files next to the file, like Android's. A null context still throws the NullPointerException the original call threw, so it is checked before the catch. */ public static boolean deleteDatabase(Context context, String name) { + Objects.requireNonNull(context); try { return SQLiteDatabase.deleteDatabase(context.getDatabasePath(name)); } catch (Exception e) { From d1f8094e64953c528aab4f77a5069d8d2fcde913 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:20 -0800 Subject: [PATCH 153/203] ADFA-7138 Keep the status-line tap with the text it was bound for Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../itsaky/androidide/ui/EditorBottomSheet.kt | 5 +- .../com/itsaky/androidide/ui/StatusLineTap.kt | 25 +++++++++ .../quickbuild/StatusLineTapBindingTest.kt | 56 +++++++++++++++++++ 3 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt b/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt index c2294b296a..0ff59f7ea8 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/EditorBottomSheet.kt @@ -124,6 +124,7 @@ class EditorBottomSheet * back to fit once the build ends. */ private var statusHeightRatchet = false + private val statusTap by lazy { StatusLineTapBinding(binding.buildStatus.statusText) } /** * The part of the sheet above the header: its status-bar top padding and the divider row. @@ -752,6 +753,8 @@ class EditorBottomSheet it.statusText.gravity = gravity it.statusText.text = text } + // A tap belongs to the text it was bound for; other text, from any writer, is plain. + statusTap.onTextWritten(text) // A longer line can take more rows than the last one did, so the header has to be // re-measured against the new text rather than against the dimen. post { refreshCollapsedHeight() } @@ -769,7 +772,7 @@ class EditorBottomSheet actionLabel: CharSequence?, onTap: (() -> Unit)?, ) { - bindStatusLineTap(binding.buildStatus.statusText, actionLabel, onTap) + statusTap.bind(actionLabel, onTap) } /** diff --git a/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt b/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt index 0ccb582194..f26e04b1c0 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt @@ -35,3 +35,28 @@ internal fun bindStatusLineTap( // A null command keeps the default click; only the spoken label is replaced. ViewCompat.replaceAccessibilityAction(statusText, AccessibilityActionCompat.ACTION_CLICK, actionLabel, null) } + +/** + * Keeps the status line's tap with the text it was bound for. [bind] remembers the text on the line, + * and [onTextWritten] drops the tap when other text replaces it, whoever wrote that text (a refused + * Quick Build's tap must not stay on the indexing line the view model writes next). The same text + * written again, as the status observer does after the refusal, keeps the tap. + */ +internal class StatusLineTapBinding( + private val statusText: TextView, +) { + private var boundText: String? = null + + fun bind( + actionLabel: CharSequence?, + onTap: (() -> Unit)?, + ) { + boundText = if (onTap == null) null else statusText.text?.toString().orEmpty() + bindStatusLineTap(statusText, actionLabel, onTap) + } + + fun onTextWritten(text: CharSequence) { + val bound = boundText ?: return + if (text.toString() != bound) bind(null, null) + } +} diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt new file mode 100644 index 0000000000..f5e1326ce1 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt @@ -0,0 +1,56 @@ +package com.itsaky.androidide.quickbuild + +import android.content.Context +import android.widget.TextView +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.ui.StatusLineTapBinding +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * A status-line tap belongs to the text it was bound for (ADFA-7138). After a refused Quick Build the + * editor view model writes the indexing line straight to the bottom sheet, so the tap must go when + * that other text lands, and stay when the refusal's own text is written again. + */ +@RunWith(RobolectricTestRunner::class) +class StatusLineTapBindingTest { + private val line = TextView(ApplicationProvider.getApplicationContext()) + private val tap = StatusLineTapBinding(line) + private var taps = 0 + + private fun write(text: String) { + line.text = text + tap.onTextWritten(text) + } + + private fun bindRefusal() { + line.text = "Quick Build: off - tap for details" + tap.bind("show why") { taps++ } + } + + @Test + fun `other status text replacing the line makes it plain text again`() { + bindRefusal() + assertThat(line.isClickable).isTrue() + + write("Indexing 3 of 9") + + assertThat(line.isClickable).isFalse() + assertThat(line.isFocusable).isFalse() + assertThat(line.performClick()).isFalse() + assertThat(taps).isEqualTo(0) + } + + @Test + fun `the same text written again keeps the tap`() { + bindRefusal() + + write("Quick Build: off - tap for details") + + assertThat(line.isClickable).isTrue() + assertThat(line.performClick()).isTrue() + assertThat(taps).isEqualTo(1) + } +} From bd26c30bafefc0397bce3cd3e7cd8be27af31b35 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:20 -0800 Subject: [PATCH 154/203] ADFA-7138 Docs: name four rare false positives of the rewrite checks Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index b91bb82d7d..5fbe49c65f 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -195,6 +195,13 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - requery's native library is built without ICU: there is no `UNICODE` collator (a `COLLATE UNICODE` string constant fails the build, see above; the clause is found through whitespace, SQL comments and a quoted name, and `UNICODE_CI` is a different collation and passes) and `LOCALIZED` compares bytes (a warning). +- Four rare false positives of the checks, each rejected on purpose rather than proven safe: + - a custom `CursorFactory` that returns a non-requery cursor, then a cast to an Android cursor class, is rejected + (the cast check follows the static type from a renamed owner; a cast through `Cursor` or an `instanceof` guard avoids it); + - the `COLLATE` rule matches any string constant on purpose (Room's generated SQL), so a quoted literal or a log + message that contains the phrase is a false positive; + - an `instanceof` proof covers the checked local only, not a copy of it; + - a subclass that declares its own version of a member requery lacks is still rejected, because the check works on class names. - `SupportSQLiteDatabase.execPerConnectionSQL` is unsupported (see the design change): no build failure, an `UnsupportedOperationException` when called. - Passing an Android `CursorWindow` where a (renamed) `SQLiteClosable` is expected cannot work: android's From 918e5f7eb59955608b4e0ddff8aab52b1583de2f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:32:14 -0800 Subject: [PATCH 155/203] ADFA-7138 Test the status-line tap wiring in EditorBottomSheet StatusLineTapBindingTest builds the binding directly, so removing either wiring call in EditorBottomSheet failed no test. The new test builds the real sheet in Robolectric and goes through setStatusTap and setStatus: a bound tap makes the status line clickable, other text drops it, and the same text keeps it. Without the setStatus call, the "other text" test fails; without the bind call, the other two fail. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../ui/EditorBottomSheetStatusTapTest.kt | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt diff --git a/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt b/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt new file mode 100644 index 0000000000..6b3b65aa98 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt @@ -0,0 +1,70 @@ +package com.itsaky.androidide.ui + +import android.view.Gravity +import androidx.fragment.app.FragmentActivity +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.R +import com.itsaky.androidide.app.BaseApplication +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The status-line tap is wired into [EditorBottomSheet] itself (d1f8094e6): [setStatus] hands every + * write to the tap binding, and [setStatusTap] binds through it. [StatusLineTapBindingTest] covers + * the binding alone, so these go through the sheet's public API and fail if either call is removed. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = EditorBottomSheetStatusTapTest.TestApp::class) +class EditorBottomSheetStatusTapTest { + open class TestApp : BaseApplication() + + private val activity = + Robolectric + .buildActivity(FragmentActivity::class.java) + .also { it.get().setTheme(R.style.Theme_AndroidIDE) } + .setup() + .get() + + private val sheet = EditorBottomSheet(activity) + private val statusText get() = sheet.binding.buildStatus.statusText + + private var taps = 0 + + private fun bindTap(text: String) { + sheet.setStatus(text, Gravity.START) + sheet.setStatusTap("show details") { taps++ } + } + + @Test + fun `binding a tap through the sheet makes the status line clickable`() { + bindTap("Quick Build: off - tap for details") + + assertThat(statusText.isClickable).isTrue() + statusText.performClick() + assertThat(taps).isEqualTo(1) + } + + @Test + fun `other text written through setStatus drops the tap`() { + bindTap("Quick Build: off - tap for details") + + sheet.setStatus("Indexing project", Gravity.START) + + assertThat(statusText.isClickable).isFalse() + assertThat(statusText.hasOnClickListeners()).isFalse() + } + + @Test + fun `the same text written again through setStatus keeps the tap`() { + bindTap("Quick Build: off - tap for details") + + sheet.setStatus("Quick Build: off - tap for details", Gravity.START) + + assertThat(statusText.isClickable).isTrue() + statusText.performClick() + assertThat(taps).isEqualTo(1) + } +} From 5407497bf5aef2ea1a489ffa75b6b7a7a07cacab Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:37:08 -0800 Subject: [PATCH 156/203] ADFA-7138 README: name the opt-out that works with property precedence b2d7bbebc fixed this sentence in the build-failure message and in sqlite-rewrite.md, but the SQLite debugger's README still said that commenting the line out turns everything off. When another file read later also sets the property to true, commenting the line out exposes that true. The README now says to set the line to false in the file that defines it, or in one read earlier, and links to sqlite-rewrite.md's order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 7511de7cf2..bdb67dbf0e 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -13,7 +13,7 @@ A project made from the JavaScript in SQLite template has it on already. For any 3. Check that the app depends on androidx.sqlite (Room and WorkManager bring it) and androidx.core (AppCompat brings it). requery needs both, and a file dependency brings neither. 4. Build and run the debug variant. The app starts the server and sends its port and token to Code on the Go (ADFA-7137), and AI-Agent-MCP connects to it with no setup (ADFA-7139). In phase 1 the Agent asks before each call (ADFA-7147). -The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. The opt-in is decided per project from all app modules: Code on the Go reads the Gradle user home, every app module and the root, so the first of those files that defines the line decides for the whole project, whatever the other modules say, even though Quick Build builds only the first app module. Commenting the line out turns all of this off. +The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. The opt-in is decided per project from all app modules: Code on the Go reads the Gradle user home, every app module and the root, so the first of those files that defines the line decides for the whole project, whatever the other modules say, even though Quick Build builds only the first app module. To turn all of this off, set the line to `cogo.sqliteDebugger=false` in the file that defines it, or in one read earlier; commenting the line out can expose another file's `true` ([details](../../gradle-plugin/docs/sqlite-rewrite.md#turning-it-on)). Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails, names the class, method and line, and says how to build without the debugger; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). @@ -35,7 +35,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. -- **Gradle plugin wiring (ADFA-7138).** An app opts in with `cogo.sqliteDebugger=true` in its `gradle.properties`; commenting the line out turns everything off. With it, Code on the Go's Gradle plugin (`AndroidIDEGradlePlugin`) applies two plugins. `SqliteRewritePlugin` registers a class transform on every variant that moves the app's and its libraries' classes from `android.database.sqlite` to requery (see `gradle-plugin/docs/sqlite-rewrite.md`) and adds the rewrite's helper AAR (`:subprojects:sqlite-rewrite-runtime`) to every variant. `SqliteDebuggerPlugin` adds the debugger AAR and kotlin-stdlib to debuggable variants only. Code on the Go passes both AAR paths to Gradle as properties. Quick Build is not applied to an opted-in project, because its payload would compile the project's source without the rewrite. The apps' minSdk must be at least 21, the floor of requery, the helper AAR and the debugger. +- **Gradle plugin wiring (ADFA-7138).** An app opts in with `cogo.sqliteDebugger=true` in its `gradle.properties`; setting it to `false` in the file that defines it, or in one read earlier, turns everything off. With it, Code on the Go's Gradle plugin (`AndroidIDEGradlePlugin`) applies two plugins. `SqliteRewritePlugin` registers a class transform on every variant that moves the app's and its libraries' classes from `android.database.sqlite` to requery (see `gradle-plugin/docs/sqlite-rewrite.md`) and adds the rewrite's helper AAR (`:subprojects:sqlite-rewrite-runtime`) to every variant. `SqliteDebuggerPlugin` adds the debugger AAR and kotlin-stdlib to debuggable variants only. Code on the Go passes both AAR paths to Gradle as properties. Quick Build is not applied to an opted-in project, because its payload would compile the project's source without the rewrite. The apps' minSdk must be at least 21, the floor of requery, the helper AAR and the debugger. ### The event record From a5224560f9e5784d5d59cbea5c4807828eae8ee5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 08:42:52 -0800 Subject: [PATCH 157/203] ADFA-7136 Count user tables whose name only looks like sqlite_ in get_stats get_stats left out tables with NOT LIKE 'sqlite_%', where "_" is a LIKE wildcard, so a user table such as sqlitecache was not counted. Match the reserved prefix literally with ESCAPE. Review thread 4607065598 (CodeRabbit). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 2 +- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 618ddde9d0..c505653b0d 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -416,7 +416,7 @@ class DatabaseTools( runChecked( call, path, - "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", emptyList(), 0, limits, diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 3f14cc4dbf..1450ff5b2d 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -654,6 +654,16 @@ class DatabaseToolsTest { assertTrue(seenSql.none { it.contains("sqlite_schema") }) } + @Test fun getStatsKeepsUserTablesThatOnlyLookLikeTheReservedPrefix() { + engine.appConnections += conn(1, "/data/a.db") + answerWith("SELECT name" to QueryResult(listOf("name"), listOf(listOf("sqlitecache")), 0, false)) + val r = ok("get_stats", db()) + // "_" is a wildcard in LIKE: without the escape, sqlitecache would be left out of the listing + val listing = seenSql.single { it.contains("FROM sqlite_master") } + assertTrue(listing, listing.contains("NOT LIKE 'sqlite\\_%' ESCAPE '\\'")) + assertTrue(r.getJSONObject("row_counts").has("sqlitecache")) + } + @Test fun getStatsSkipsCountsFromTenTables() { engine.appConnections += conn(1, "/data/a.db") answerWith("SELECT name" to QueryResult(listOf("name"), (1..10).map { listOf("t$it") }, 0, false)) From 4ee15069e5aed5291571b3b0bdf7457388b12b6d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 08:50:18 -0800 Subject: [PATCH 158/203] ADFA-7136 Report a path whose app connections are all closing as not available list_databases said available=true, and the unknown-database error listed the path as available, while runChecked refuses it. Compute availability from connections that are not closing, in listDatabases and knownPaths, the same rule runChecked applies. Review thread 4607065598's sibling, 4607065592 (CodeRabbit). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 18 ++++++++---- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 29 +++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index c505653b0d..e82b34b8d3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -303,13 +303,14 @@ class DatabaseTools( private fun listDatabases(): JSONObject { val connections = engine.connections() - val byPath = LinkedHashMap>() - for (c in connections) if (c.path.isNotEmpty()) byPath.getOrPut(c.path) { mutableListOf() } += c.id + val byPath = LinkedHashMap>() + for (c in connections) if (c.path.isNotEmpty()) byPath.getOrPut(c.path) { mutableListOf() } += c // The folder may be reached through a link (/data/user/0/ and /data/data/), so match resolved paths. val openCanonical = byPath.keys.map { canonical(it) }.toSet() val list = JSONArray() - for ((path, ids) in byPath) { - list.put(JSONObject().put("path", path).put("available", true).put("connections", ids.size)) + for ((path, conns) in byPath) { + // Same rule as runChecked: a path whose app connections are all closing is not available. + list.put(JSONObject().put("path", path).put("available", conns.any { !it.closing }).put("connections", conns.size)) } databaseDir?.listFiles()?.sortedBy { it.name }?.forEach { f -> if (!f.isFile || SIDE_FILE_SUFFIXES.any { f.name.endsWith(it) }) return@forEach @@ -541,7 +542,12 @@ class DatabaseTools( return path } - private fun knownPaths(live: List) = live.map { it.path }.filter { it.isNotEmpty() }.distinct() + private fun knownPaths(live: List) = + live + .filter { !it.closing } + .map { it.path } + .filter { it.isNotEmpty() } + .distinct() private fun unknownDatabase( path: String, @@ -577,7 +583,7 @@ class DatabaseTools( .getOrPut(path) { // checkedPath looked at an earlier snapshot: the app may have closed, or begun closing, its // last connection to this path since, and the server never opens a database the app doesn't - // have open. A closing connection is still listed, so knownPaths alone would let it through. + // have open. knownPaths skips closing connections too; this re-check covers the gap since its snapshot. val ids = live.filter { it.path == path && !it.closing }.map { it.id }.toSet() if (ids.isEmpty()) throw unknownDatabase(path, knownPaths(live)) CachedConnection(engine.openServerConnection(path, writable = false), ids) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 1450ff5b2d..7e58705eba 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -101,6 +101,35 @@ class DatabaseToolsTest { assertTrue(dbs.getJSONObject(1).getBoolean("available")) } + @Test fun listDatabasesCallsAPathAvailableOnlyWhileAnAppConnectionIsNotClosing() { + engine.appConnections += + listOf( + conn(1, "/data/a.db", closing = true), + conn(2, "/data/a.db", closing = true), + conn(3, "/data/b.db", closing = true), + conn(4, "/data/b.db"), + ) + val dbs = ok("list_databases").getJSONArray("databases") + assertEquals(2, dbs.length()) + assertEquals("/data/a.db", dbs.getJSONObject(0).getString("path")) + assertFalse("every connection to a.db is closing", dbs.getJSONObject(0).getBoolean("available")) + assertEquals(2, dbs.getJSONObject(0).getInt("connections")) + assertTrue("b.db has one connection that is not closing", dbs.getJSONObject(1).getBoolean("available")) + } + + @Test fun theUnknownDatabaseErrorListsNoPathWhoseConnectionsAreAllClosing() { + engine.appConnections += listOf(conn(1, "/data/a.db", closing = true), conn(2, "/data/b.db")) + val r = runTool(tools, "query", db("/data/a.db").put("sql", "select 1")) + assertTrue(r.toString(), r.getBoolean("isError")) + assertEquals( + listOf("/data/b.db"), + r.getJSONObject("structuredContent").getJSONArray("available").let { a -> + (0 until a.length()).map { a.getString(it) } + }, + ) + assertTrue(engine.openedServerConnections.isEmpty()) + } + @Test fun listDatabasesAddsUnopenedFilesButNotSideFiles() { val d = kotlin.io.path From f4cf4c3dfeb2a2b7105f42234d63ef93a24cffab Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:33:53 -0800 Subject: [PATCH 159/203] ADFA-7138 COLLATE rule: a quoted name must end at its closing character Review thread 4655640415: `UNICODE\b` matched COLLATE "UNICODE-CI" and [UNICODE-CI] because a word boundary falls at the hyphen. A bare name keeps the word boundary; a quoted or bracketed name now has to be followed at once by its matching closing character. Tests cover the quoted, bracketed and custom forms for UNICODE (fails the build) and LOCALIZED (warns). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriteRules.kt | 6 +- .../gradle/sqlite/SqliteRewriterTest.kt | 60 ++++++++++++++++--- 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index bff457f4f8..00f9663f9d 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -36,11 +36,13 @@ internal object SqliteRewriteRules { /** * A COLLATE clause names its collation after whitespace or a SQL comment, bare or quoted ("x", 'x', [x], `x`). - * The word boundary keeps a custom collation such as UNICODE_CI out. + * A bare name keeps a word boundary; a quoted or bracketed name must be followed at once by its closing + * character. Both keep a custom collation such as UNICODE_CI or "UNICODE-CI" out. */ private fun collateRule(name: String) = Regex( - "COLLATE(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))+[\"'\\[`]?$name\\b", + "COLLATE(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))+" + + "(?:$name\\b|\"$name\"|'$name'|\\[$name]|`$name`)", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL), ) diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index f08faf51cc..300dbc715d 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1183,16 +1183,60 @@ class SqliteRewriterTest { val e = assertThrows(SqliteRewriteException::class.java, { SqliteRewriter.rewrite(classes["p/Q"]!!) }, "form: $form") assertThat(e.message).contains("COLLATE UNICODE") } - val ok = - Compiler.compile( - listOf( - src( - "p.Ci", - "package p; public class Ci { String q() { return \"SELECT * FROM t ORDER BY n COLLATE UNICODE_CI\"; } }", + for (custom in listOf("UNICODE_CI", "\\\"UNICODE-CI\\\"", "[UNICODE-CI]", "\\\"UNICODE_CI\\\"", "'UNICODE-CI'", "`UNICODE-CI`")) { + val ok = + Compiler.compile( + listOf( + src( + "p.Ci", + "package p; public class Ci { String q() { return \"SELECT * FROM t ORDER BY n COLLATE $custom\"; } }", + ), ), - ), + ) + SqliteRewriter.rewrite(ok["p/Ci"]!!) + } + } + + @Test + fun `COLLATE LOCALIZED is found through comments and quotes, and a custom name only passes`() { + val forms = + listOf( + "COLLATE localized", + "COLLATE /* c */ LOCALIZED", + "COLLATE -- c\\n LOCALIZED", + "COLLATE \\\"LOCALIZED\\\"", + "COLLATE 'LOCALIZED'", + "COLLATE [LOCALIZED]", + "COLLATE `LOCALIZED`", ) - SqliteRewriter.rewrite(ok["p/Ci"]!!) + for (form in forms) { + val classes = + Compiler.compile( + listOf( + src( + "p.L", + "package p; public class L { String q() { return \"SELECT * FROM t ORDER BY n $form\"; } }", + ), + ), + ) + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/L"]!!, warn = { warnings += it }) + assertThat(warnings).hasSize(1) + } + for (custom in listOf("LOCALIZED_CI", "\\\"LOCALIZED-CI\\\"", "[LOCALIZED-CI]", "\\\"LOCALIZED_CI\\\"")) { + val classes = + Compiler.compile( + listOf( + src( + "p.L", + "package p; public class L { String q() { return \"SELECT * FROM t ORDER BY n COLLATE $custom\"; } }", + ), + ), + ) + val warnings = mutableListOf() + SqliteRewriter.rewrite(classes["p/L"]!!, warn = { warnings += it }) + assertThat(warnings).isEmpty() + } } @Test From eec3d54690acb8ab956980f5ca8d26c1498822a2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:33:54 -0800 Subject: [PATCH 160/203] ADFA-7138 Docs: correct the cast and subclass false-positive sentences Review thread 4655639876: cursorCastTaint carries the taint through every CHECKCAST, so a cast through Cursor does not avoid the rejection; only an instanceof guard of the cast's type on the same local does (a test already covers it). The two subclass sentences now say which case each describes: a call on a subclass that declares its own version is rejected, while the declaration of such an override is not reported by itself. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 5fbe49c65f..9a1872283d 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -197,11 +197,13 @@ dependency, and runs the script on both APKs. The release must pass. The debug A `UNICODE_CI` is a different collation and passes) and `LOCALIZED` compares bytes (a warning). - Four rare false positives of the checks, each rejected on purpose rather than proven safe: - a custom `CursorFactory` that returns a non-requery cursor, then a cast to an Android cursor class, is rejected - (the cast check follows the static type from a renamed owner; a cast through `Cursor` or an `instanceof` guard avoids it); + (the cast check follows the static type from a renamed owner, and the taint passes through every `CHECKCAST`, so a cast through `Cursor` does not avoid it; + an `instanceof` guard of the cast's type on the same local does, on every path to the cast); - the `COLLATE` rule matches any string constant on purpose (Room's generated SQL), so a quoted literal or a log message that contains the phrase is a false positive; - an `instanceof` proof covers the checked local only, not a copy of it; - - a subclass that declares its own version of a member requery lacks is still rejected, because the check works on class names. + - a call to a member requery lacks, made on a subclass that declares its own version of that member, is still rejected, + because the check matches the member's name and descriptor on the call's owner class and its renamed ancestors, not the declaration it resolves to. - `SupportSQLiteDatabase.execPerConnectionSQL` is unsupported (see the design change): no build failure, an `UnsupportedOperationException` when called. - Passing an Android `CursorWindow` where a (renamed) `SQLiteClosable` is expected cannot work: android's @@ -254,8 +256,10 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - Compile-time constants are copied into callers, so uses of `NO_LOCALIZED_COLLATORS`, `JOURNAL_MODE_*` or `SYNC_MODE_*` are not visible to the fail rule. `NO_LOCALIZED_COLLATORS` is dropped by the flag translation. - The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied. -- A direct subclass of `SQLiteQueryBuilder` or `SQLiteCursor` that overrides a member requery lacks is not - reported. +- The declaration of an override of a member requery lacks, in a direct subclass of `SQLiteQueryBuilder` or `SQLiteCursor`, + is not reported by itself: the rules check calls and field accesses, not declarations. The exceptions are the + `SQLiteQueryBuilder.query` override with a `CancellationSignal` and the `Context` database methods, which fail (see above). + A call to that override on the subclass is still rejected (see the false positive above). - On a `SQLiteCursor` subclass whose class the build cannot resolve, `getWindow()` is not detected, and `setWindow(CursorWindow)` and `mWindow` only log a warning; each fails at run time. `getWindow()` is not in the rule table, and failing every unresolved member that names a `CursorWindow` would fail ordinary apps (android's kept From c284f2cd3e7c7f67ed2b9c3ce036cd4c6bd74f89 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:46:57 -0800 Subject: [PATCH 161/203] ADFA-7138 Status-line tap: bind again when the refusal text is written back Review thread 4655640213: onTextWritten dropped the tap for good when the indexing line replaced the refusal line, so the refusal text that EditorViewModel restores when indexing ends could no longer be tapped. The binding now remembers the text, label and tap action, drops the tap on other text, and binds again when the same text returns. Tests: refusal, indexing, restored refusal, in the binding test and through the real EditorBottomSheet. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../com/itsaky/androidide/ui/StatusLineTap.kt | 39 ++++++++++++++++--- .../quickbuild/StatusLineTapBindingTest.kt | 29 ++++++++++++++ .../ui/EditorBottomSheetStatusTapTest.kt | 13 +++++++ 3 files changed, 75 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt b/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt index f26e04b1c0..812b2e14ab 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/StatusLineTap.kt @@ -37,26 +37,53 @@ internal fun bindStatusLineTap( } /** - * Keeps the status line's tap with the text it was bound for. [bind] remembers the text on the line, - * and [onTextWritten] drops the tap when other text replaces it, whoever wrote that text (a refused - * Quick Build's tap must not stay on the indexing line the view model writes next). The same text - * written again, as the status observer does after the refusal, keeps the tap. + * Keeps the status line's tap with the text it was bound for. [bind] remembers the text on the line + * with the label and the tap action, and [onTextWritten] drops the tap when other text replaces it, + * whoever wrote that text (a refused Quick Build's tap must not stay on the indexing line the view + * model writes next). The same text written again, as the view model does when indexing ends and it + * restores the refusal's line, binds the tap again; the same text written while the tap is still + * bound keeps it. An explicit [bind] with a null action forgets the binding for good. */ internal class StatusLineTapBinding( private val statusText: TextView, ) { private var boundText: String? = null + private var boundLabel: CharSequence? = null + private var boundTap: (() -> Unit)? = null + private var active = false fun bind( actionLabel: CharSequence?, onTap: (() -> Unit)?, ) { - boundText = if (onTap == null) null else statusText.text?.toString().orEmpty() + if (onTap == null) { + forget() + } else { + boundText = statusText.text?.toString().orEmpty() + boundLabel = actionLabel + boundTap = onTap + active = true + } bindStatusLineTap(statusText, actionLabel, onTap) } fun onTextWritten(text: CharSequence) { val bound = boundText ?: return - if (text.toString() != bound) bind(null, null) + val tap = boundTap ?: return + val same = text.toString() == bound + if (same && !active) { + active = true + bindStatusLineTap(statusText, boundLabel, tap) + } else if (!same && active) { + active = false + bindStatusLineTap(statusText, null, null) + } + } + + private fun forget() { + boundText = null + boundLabel = null + boundTap = null + active = false } } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt index f5e1326ce1..4454d60563 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/StatusLineTapBindingTest.kt @@ -53,4 +53,33 @@ class StatusLineTapBindingTest { assertThat(line.performClick()).isTrue() assertThat(taps).isEqualTo(1) } + + @Test + fun `the refusal text restored after indexing is tappable again`() { + bindRefusal() + + write("Indexing 3 of 9") + assertThat(line.isClickable).isFalse() + + write("Quick Build: off - tap for details") + + assertThat(line.isClickable).isTrue() + assertThat(line.isFocusable).isTrue() + assertThat(line.performClick()).isTrue() + assertThat(taps).isEqualTo(1) + + write("Indexing 4 of 9") + assertThat(line.isClickable).isFalse() + } + + @Test + fun `a binding cleared on purpose is not restored by the same text`() { + bindRefusal() + tap.bind(null, null) + + write("Quick Build: off - tap for details") + + assertThat(line.isClickable).isFalse() + assertThat(taps).isEqualTo(0) + } } diff --git a/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt b/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt index 6b3b65aa98..d7ad2f61be 100644 --- a/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt +++ b/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt @@ -67,4 +67,17 @@ class EditorBottomSheetStatusTapTest { statusText.performClick() assertThat(taps).isEqualTo(1) } + + @Test + fun `the refusal text restored after indexing is tappable again through setStatus`() { + bindTap("Quick Build: off - tap for details") + sheet.setStatus("Indexing project", Gravity.START) + assertThat(statusText.isClickable).isFalse() + + sheet.setStatus("Quick Build: off - tap for details", Gravity.START) + + assertThat(statusText.isClickable).isTrue() + statusText.performClick() + assertThat(taps).isEqualTo(1) + } } From 3a3d57addac02aef863ccaa4f83f60dfdf1a10fe Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:54:58 -0800 Subject: [PATCH 162/203] ADFA-7135 Drain unread request input before closing after an error reply The server wrote a refusal (401, 403, 404, 413, 503) and closed the socket without reading the rest of the request. Closing with unread input makes the system send a TCP reset, which can destroy the reply before the client reads it, and made a McpProtocolTest case fail locally. After such a reply the server now calls shutdownOutput(), reads and discards the client's remaining input for at most 64 KiB and 500 ms (100 ms on the accept thread), then closes, so a slow or hostile client cannot hold the thread. Review thread 4608432429 (Hal). Tests: a refusal reaches a client that already sent 48 KiB of body (401 and 413, 20 times each), and a client that never stops sending is cut off within 2 s. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/McpHttp.kt | 64 ++++++++++++++++--- .../sqlitedebugger/mcp/McpProtocolTest.kt | 59 +++++++++++++++++ 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index dc7db46d46..7cab0bc394 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -95,6 +95,15 @@ class McpHttp( */ const val HEAD_DEADLINE_MS = 5_000 + /** After a refusal, the most input discarded before the connection closes (see finishReply). */ + private const val REFUSAL_DRAIN_BYTES = 64 * 1024 + + /** After a refusal, the longest wait for the client to finish or close, on a connection's own thread. */ + private const val REFUSAL_DRAIN_MS = 500 + + /** The same on the accept thread, which every new client waits behind. */ + private const val REFUSAL_DRAIN_MS_ACCEPT = 100 + /** After a failed accept the loop sleeps this long, doubling up to the maximum while failures continue. */ const val ACCEPT_BACKOFF_MIN_MS = 100L const val ACCEPT_BACKOFF_MAX_MS = 2_000L @@ -199,6 +208,8 @@ class McpHttp( try { c.soTimeout = 1000 respond(c.getOutputStream(), 503, rpcError("Too many connections at once; try again."), emptyMap(), close = true) + // This is the accept thread: a short bound, so a client that never closes cannot hold up the accept loop. + finishReply(c, REFUSAL_DRAIN_BYTES, REFUSAL_DRAIN_MS_ACCEPT) } catch (ignored: IOException) { } close(c) @@ -207,7 +218,7 @@ class McpHttp( clients += c thread(name = "mcp-connection", isDaemon = true) { try { - serve(c) + if (serve(c)) finishReply(c, REFUSAL_DRAIN_BYTES, REFUSAL_DRAIN_MS) } catch (ignored: IOException) { // The client went away. } catch (t: Throwable) { @@ -222,7 +233,12 @@ class McpHttp( } } - private fun serve(c: Socket) { + /** + * Serves the connection until it closes. Returns true when the last thing done was a reply that + * may have left part of the request unread (a refusal or an HTTP error), so the caller must + * [finishReply] before closing. + */ + private fun serve(c: Socket): Boolean { c.soTimeout = IDLE_TIMEOUT_MS c.tcpNoDelay = true val input = BufferedInputStream(c.getInputStream()) @@ -236,25 +252,26 @@ class McpHttp( // Between requests the client may idle; the head's clock starts at its first byte. c.soTimeout = IDLE_TIMEOUT_MS input.mark(1) - if (input.read() < 0) return + if (input.read() < 0) return false input.reset() headStart = System.currentTimeMillis() } first = false - val head = readHead(input, c, headStart + headDeadlineMs) ?: return + val head = readHead(input, c, headStart + headDeadlineMs) ?: return false // Refuse before reading a body, so an unauthenticated client never gets that far. - if (!allowed(head, out)) return + if (!allowed(head, out)) return true c.soTimeout = IDLE_TIMEOUT_MS head.body = readBody(input, head.headers) head } catch (e: SocketTimeoutException) { - return + return false } catch (e: HttpError) { respond(out, e.status, rpcError(e.message ?: "Bad request."), emptyMap(), close = true) - return + return true } - if (!handle(req, out)) return + if (!handle(req, out)) return false } + return false } /** Host, Origin, path and token. Answers and returns false when the request is refused; the connection then closes. */ @@ -524,6 +541,37 @@ class McpHttp( } } + /** + * Ends a connection after a reply was written while part of the request may be unread. Closing a + * socket with unread input makes the system send a TCP reset, which can destroy the reply before + * the client reads it. So: send FIN with [Socket.shutdownOutput], read and discard what the client + * still sends, and let the caller close. The wait is bounded by [maxBytes] and [maxMs] in all, so a + * client that is slow or sends without end cannot hold the thread. + */ + private fun finishReply( + s: Socket, + maxBytes: Int, + maxMs: Int, + ) { + try { + s.shutdownOutput() + val deadline = System.nanoTime() + maxMs * 1_000_000L + val input = s.getInputStream() + val scratch = ByteArray(4096) + var total = 0 + while (total < maxBytes) { + val left = (deadline - System.nanoTime()) / 1_000_000L + if (left <= 0) break + s.soTimeout = left.toInt() + val n = input.read(scratch) + if (n < 0) break + total += n + } + } catch (ignored: IOException) { + // A timeout, a reset or a client that left: the reply has had its chance. + } + } + private fun close(s: Socket) { try { s.close() diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 2788ae745f..47602a9639 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -566,4 +566,63 @@ class McpProtocolTest { assertTrue(line, line.startsWith("HTTP/1.1 401")) } } + + /** Sends [head] then [bodyBytes] of body in one burst and reads the whole reply, as a client that writes before it reads. */ + private fun burst( + port: Int, + head: String, + bodyBytes: Int, + ): String = + Socket("127.0.0.1", port).use { c -> + c.soTimeout = 5000 + c.getOutputStream().apply { + write(head.toByteArray(Charsets.ISO_8859_1)) + write(ByteArray(bodyBytes) { 'x'.code.toByte() }) + flush() + } + c.getInputStream().readBytes().toString(Charsets.UTF_8) + } + + @Test fun aRefusalReachesAClientThatAlreadySentPartOfTheBody() { + val port = startServer() + repeat(20) { + // 401: refused before the body is read, with 48 KiB of it still on the way or in the socket + val noToken = "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: 49152\r\n\r\n" + assertTrue(burst(port, noToken, 49152).startsWith("HTTP/1.1 401")) + // 413: the declared length is over the limit, so the body is never read + val tooBig = + "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer $token\r\n" + + "Content-Type: application/json\r\nContent-Length: ${McpHttp.MAX_BODY_BYTES + 1}\r\n\r\n" + assertTrue(burst(port, tooBig, 49152).startsWith("HTTP/1.1 413")) + } + } + + @Test fun aRefusalDoesNotHoldTheServerThreadForAClientThatKeepsSending() { + val port = startServer() + Socket("127.0.0.1", port).use { c -> + c.soTimeout = 5000 + val out = c.getOutputStream() + out.write("POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 1000000\r\n\r\n".toByteArray()) + out.flush() + // the reply comes and then the server closes within its bound, although this client never stops + val sender = + Thread { + try { + while (true) { + out.write(ByteArray(1024)) + out.flush() + Thread.sleep(20) + } + } catch (ignored: Exception) { + } + } + sender.isDaemon = true + sender.start() + val started = System.nanoTime() + val text = c.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text.startsWith("HTTP/1.1 401")) + val ms = (System.nanoTime() - started) / 1_000_000 + assertTrue("the connection took $ms ms to end", ms < 2_000) + } + } } From df22b7aca3516ccb9577f533b423a392daca3391 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:59:47 -0800 Subject: [PATCH 163/203] ADFA-7136 Stop a server statement after 1.5 s on a database that is not in WAL mode On a rollback-journal database a server read holds a SHARED lock until the statement ends, and only the 50 s call deadline bounded it, so the app's own COMMIT failed with "database is locked" once requery's 2500 ms busy timeout ran out (acceptance criterion 5). Every tool steps its statements in bridge_query, so that one place now reads PRAGMA journal_mode (no value, so it only reads) on each call and, when the mode is not WAL, caps the statement at SQLITEDBG_SERVER_NON_WAL_MS = 1500 ms. The error says the database is not in WAL mode, so a longer read would block the app's writes, and to narrow the query or add a LIMIT. A WAL database keeps the 50 s deadline. The busy timeout is requery/sqlite-android 3.49.0, BUSY_TIMEOUT_MS in android_database_SQLiteConnection.cpp. The header, README and tool descriptions no longer say a client cannot hold a lock on the app's database; the tool descriptions state the 1.5 s limit, and the integrity_check one says a big non-WAL database will stop early. Tests (JNI): an app connection with a 2500 ms busy timeout commits while a server statement runs on a DELETE-mode database, and the statement ends with the non-WAL error near the cap; a WAL database keeps its deadline; a call deadline shorter than the cap keeps its own message. Review thread 4608418645 (Hal). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 14 +++- .../src/main/cpp/sqlitedbg_jni.c | 37 ++++++++- .../sqlitedebugger/mcp/DatabaseTools.kt | 20 +++-- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 18 ++++ .../sqlite-debugger/src/test/jni/Helper.java | 2 + .../src/test/jni/JniQueryTest.java | 82 +++++++++++++++++++ .../sqlite-debugger/src/test/jni/helper.c | 7 ++ 8 files changed, 172 insertions(+), 10 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index dcbfad6e66..3c80d318a7 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -31,7 +31,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock on the app's database, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can still run SQL, so the token is the boundary. - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 65795d8aa8..c3365708ab 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -135,10 +135,20 @@ void sqlitedbg_set_client_connected(int connected); #define SQLITEDBG_SERVER_BUSY_MS 3000 +// The longest a server statement may run on a database that is not in WAL mode (rollback journal, +// also "memory" and "off"). Such a statement holds a SHARED lock from its first step to its end, and +// the app's COMMIT waits for it in the app's busy handler: requery's busy timeout is 2500 ms +// (BUSY_TIMEOUT_MS in android_database_SQLiteConnection.cpp, requery/sqlite-android 3.49.0, copied from +// AOSP). The cap sits below that, with margin for the busy handler's back-off and the app's own work, so +// a long read never makes the app's commit fail with "database is locked" (ADFA-7136 acceptance +// criterion 5). A WAL database needs no cap: readers and the writer do not block each other. +#define SQLITEDBG_SERVER_NON_WAL_MS 1500 + // Opens path for the server with the same SQLite the app uses: SQLITE_OPEN_READONLY unless // writable, PRAGMA query_only when read-only, and an authorizer that refuses ordinary writes when -// read-only, and also BEGIN, SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout: a client must not -// be able to hold a lock on the app's database. The process-wide PRAGMAs hard_heap_limit, soft_heap_limit and +// read-only, and also BEGIN, SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout: a client cannot +// hold a lock across statements. Within one statement a lock is held while it runs, so the JNI query +// path stops a statement on a database that is not in WAL mode after SQLITEDBG_SERVER_NON_WAL_MS. The process-wide PRAGMAs hard_heap_limit, soft_heap_limit and // temp_store_directory are refused too: they would change the app's own connections. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, // D11). Never traced and never listed. The caller owns *db and closes it with sqlite3_close_v2. // A server connection, unlike an app connection, may use a progress handler (for time limits). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index bb4da44059..7563a3f7e3 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -197,8 +197,22 @@ static void bridge_close(JNIEnv *env, jclass cls, jlong handle) { typedef struct deadline { int64_t at_ms; int hit; + int capped; // at_ms is the non-WAL cap, earlier than the call's own deadline } deadline; +// Whether the database is in WAL mode. PRAGMA journal_mode without a value only reads the mode. Any +// failure counts as not WAL, which is the safe answer: the statement then gets the short cap. +static int is_wal_mode(sqlite3 *db) { + sqlite3_stmt *st = NULL; + int wal = 0; + if (sqlite3_prepare_v2(db, "PRAGMA journal_mode", -1, &st, NULL) == SQLITE_OK && sqlite3_step(st) == SQLITE_ROW) { + const unsigned char *mode = sqlite3_column_text(st, 0); + wal = mode && sqlite3_stricmp((const char *)mode, "wal") == 0; + } + sqlite3_finalize(st); + return wal; +} + static int progress_cb(void *p) { deadline *d = (deadline *)p; if (now_ms() < d->at_ms) return 0; @@ -342,7 +356,7 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring jobjectArray result = NULL; jlong *cut_cells = NULL; // row * columns + column of each cut cell size_t cut_n = 0, cut_cap = 0; - deadline dl = {(int64_t)deadline_ms, 0}; + deadline dl = {(int64_t)deadline_ms, 0, 0}; int handler_set = 0; const char *message = NULL; int rc; @@ -361,6 +375,18 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring return NULL; } + // Every server tool runs its statements here, so this is the one place that bounds a read on a database + // that is not in WAL mode: it holds a SHARED lock until the statement ends, and the app's commit gives + // up after requery's 2500 ms busy timeout (see SQLITEDBG_SERVER_NON_WAL_MS). The mode is read per call. + if (now_ms() + SQLITEDBG_SERVER_NON_WAL_MS < dl.at_ms && !is_wal_mode(db)) { + // counted from here, after the mode check, which can wait on the app's lock + int64_t cap_at = now_ms() + SQLITEDBG_SERVER_NON_WAL_MS; + if (cap_at < dl.at_ms) { + dl.at_ms = cap_at; + dl.capped = 1; + } + } + // SQLite checks the handler every 1000 virtual machine steps and stops the statement when it // returns non-zero; it is cleared before this returns, so it never outlives `dl`. sqlite3_progress_handler(db, 1000, progress_cb, &dl); @@ -446,7 +472,14 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring row_count++; } if (!has_more && rc != SQLITE_DONE) { - if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); + if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { + char msg[256]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s: this database is not in WAL mode, so a longer read would " + "block the app's own writes. Use a narrower query or a LIMIT; a database in WAL mode has no such limit", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the query ran past its time limit"); else throw_engine(env, rc, sqlite3_errmsg(db)); goto done; } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index e82b34b8d3..81bdd00716 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -52,6 +52,7 @@ class DatabaseTools( * client's 60 s limit, so a query never holds the lock after the client has stopped waiting. */ const val DEADLINE_MS = 50_000L + private const val DEADLINE_SECONDS = DEADLINE_MS / 1000 const val EVENT_BATCH_BYTES = 256 * 1024 const val MAX_TABLES_FOR_COUNTS = 10 @@ -63,6 +64,14 @@ class DatabaseTools( const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + /** + * Said by every tool that runs a statement. The limit itself is enforced in C (SQLITEDBG_SERVER_NON_WAL_MS in + * sqlitedbg.h, which says why); this text must follow it. + */ + const val NON_WAL_NOTE = + "On a database that is not in WAL mode a statement is stopped after 1.5 s, so a long read does not block the app's " + + "own writes; use a narrower query or a LIMIT. A database in WAL mode has no such limit (the call's $DEADLINE_SECONDS s applies)." + /** Server connections never load what the app registers on its own connections (see the README). */ private const val APP_FUNCTIONS_NOTE = "Functions the app adds to its own connections, such as sqlite-js's stored JavaScript functions, do not exist " + @@ -208,7 +217,7 @@ class DatabaseTools( "${MAX_TOTAL_BYTES / MAX_SCHEMA_SQL_BYTES} statements of ${MAX_SCHEMA_SQL_BYTES / 1024} KiB). There is no offset: " + "to read the rest, page through sqlite_master with query (ORDER BY type, name, the order get_schema uses), " + "and read a statement longer than its $MAX_TEXT_BYTES-byte TEXT limit in parts with substr " + - "(it counts characters, not bytes).", + "(it counts characters, not bytes). $NON_WAL_NOTE", databaseSchema(), ) { call, args -> getSchema(call, args) }, tool( @@ -218,7 +227,7 @@ class DatabaseTools( "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + "comes back whole. Use offset to page. " + - "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead.", + "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), @@ -230,7 +239,7 @@ class DatabaseTools( tool( "explain_query_plan", "Explain a query plan", - "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run. $APP_FUNCTIONS_NOTE.", + "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run. $APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), @@ -241,7 +250,7 @@ class DatabaseTools( "get_stats", "Get statistics", "Returns page_count, page_size, freelist_count, and the row count of each table when the database has fewer than " + - "$MAX_TABLES_FOR_COUNTS tables.", + "$MAX_TABLES_FOR_COUNTS tables. $NON_WAL_NOTE", databaseSchema(), ) { call, args -> getStats(call, args) }, tool( @@ -252,7 +261,8 @@ class DatabaseTools( "NOT NULL virtual generated column calls a function the app adds to its own connections. A full integrity_check " + "also fails on an index on such an expression and on a partial index whose WHERE calls one; " + "quick_check does not fail on those two, so use it then. " + - "Views, triggers and other generated columns do not make either fail.", + "Views, triggers and other generated columns do not make either fail. $NON_WAL_NOTE " + + "A full integrity_check of a big database that is not in WAL mode will stop early with that error.", databaseSchema("full" to prop("boolean", "Run the full integrity_check. Default false."), required = emptyList()), ) { call, args -> integrityCheck(call, args) }, tool( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 7e58705eba..7db3511cae 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -92,6 +92,24 @@ class DatabaseToolsTest { list.forEach { assertTrue(it.name, it.describe().getJSONObject("annotations").getBoolean("readOnlyHint")) } } + @Test fun everyToolThatRunsAStatementSaysAStatementOnANonWalDatabaseStopsAfterOneAndAHalfSeconds() { + val list = tools.tools().associateBy { it.name } + listOf("get_schema", "query", "explain_query_plan", "get_stats", "integrity_check").forEach { name -> + val d = list.getValue(name).describe().getString("description") + assertTrue("$name: $d", d.contains("not in WAL mode a statement is stopped after 1.5 s")) + assertTrue("$name: $d", d.contains("WAL mode has no such limit")) + } + assertTrue( + list + .getValue("integrity_check") + .describe() + .getString("description") + .contains("will stop early"), + ) + // the text has to say what the C constant is (the unit tests run in the module's folder) + assertTrue(File("src/main/cpp/sqlitedbg.h").readText().contains("#define SQLITEDBG_SERVER_NON_WAL_MS 1500\n")) + } + @Test fun listDatabasesGroupsByPathAndSkipsEmpty() { engine.appConnections += listOf(conn(1, "/data/a.db"), conn(2, "/data/a.db"), conn(3, ""), conn(4, "/data/b.db")) val dbs = ok("list_databases").getJSONArray("databases") diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java index da3de3a40d..c73cf3ad57 100644 --- a/subprojects/sqlite-debugger/src/test/jni/Helper.java +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -6,5 +6,7 @@ public class Helper { static native int close(long db); + static native int busyTimeout(long db, int ms); + static native int denyTransactions(long db, boolean deny); } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index ef41873045..b4ecec1b16 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -88,6 +88,86 @@ static Set set(Long... v) { return new HashSet<>(Arrays.asList(v)); } + /** Reads t four times over: far longer than the cap, and it holds the lock from its first step. */ + static final String LONG_READ = "SELECT count(*) FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0"; + + /** The outcome of a long server read run on its own thread. */ + static class Ran { + volatile String message; + volatile int code; + volatile long ms; + } + + static Thread longRead(long h, long deadline, Ran out) { + Thread th = new Thread(() -> { + long t = System.currentTimeMillis(); + try { + query(h, LONG_READ, new Object[0], 0, 100, 4096, 1024, MAX, deadline); + } catch (DebugEngineException e) { + out.code = e.sqliteCode; + out.message = e.getMessage(); + } + out.ms = System.currentTimeMillis() - t; + }); + th.start(); + return th; + } + + /** + * ADFA-7136 acceptance criterion 5: on a database not in WAL mode, a long read does not hold up the + * app's commit past requery's 2500 ms busy timeout. And a WAL database keeps the call's deadline. + */ + static void nonWalCap(Path dir, String delPath) throws Exception { + // DELETE mode: the app writes while the server read runs, with requery's busy timeout + long app = Helper.open(delPath); + eq(Helper.busyTimeout(app, 2500), 0, "the app's busy timeout"); + long srv = NativeBridge.openServer(delPath.getBytes(StandardCharsets.UTF_8), false); + Ran del = new Ran(); + // 8 s stands in for the 50 s call deadline: without the cap the app's commit fails at 2.5 s, and this ends + Thread th = longRead(srv, System.currentTimeMillis() + 8000, del); + Thread.sleep(300); + long t0 = System.currentTimeMillis(); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(5001)"), 0, "the app commits during a long read of a non-WAL database"); + long commitMs = System.currentTimeMillis() - t0; + th.join(); + check(commitMs < 2500, "the commit waited " + commitMs + " ms, under the busy timeout"); + eq(del.code, 9, "the long read was interrupted: SQLITE_INTERRUPT"); + check(del.message != null && del.message.contains("not in WAL mode") && del.message.contains("LIMIT"), + "the message says why and what to do: " + del.message); + check(del.ms >= 1400 && del.ms < 2500, "the read stopped after " + del.ms + " ms, near the 1500 ms cap"); + eq(q(srv, "SELECT count(*) FROM t WHERE id = 5001").rows.get(0)[0], 1L, "the commit is visible, the connection usable"); + Helper.exec(app, "DELETE FROM t WHERE id = 5001"); + // a call whose own deadline is shorter than the cap keeps its own message + Ran shorter = new Ran(); + longRead(srv, System.currentTimeMillis() + 400, shorter).join(); + eq(shorter.code, 9, "a 400 ms deadline: SQLITE_INTERRUPT"); + check(shorter.message != null && shorter.message.contains("time limit") && !shorter.message.contains("WAL"), + "the call's own deadline is reported as such: " + shorter.message); + NativeBridge.close(srv); + Helper.close(app); + + // WAL mode: no cap, the call's deadline (3.5 s here) is what stops the read, and the app is never held up + String walPath = dir.resolve("wal.db").toString(); + long walApp = Helper.open(walPath); + eq(Helper.exec(walApp, "PRAGMA journal_mode=WAL"), 0, "WAL on"); + eq(Helper.exec(walApp, "CREATE TABLE t(id INTEGER)"), 0, "create in WAL"); + eq(Helper.exec(walApp, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x<300) INSERT INTO t SELECT x FROM c"), 0, + "insert in WAL"); + long walSrv = NativeBridge.openServer(walPath.getBytes(StandardCharsets.UTF_8), false); + Ran wal = new Ran(); + Thread wt = longRead(walSrv, System.currentTimeMillis() + 3500, wal); + Thread.sleep(300); + long w0 = System.currentTimeMillis(); + eq(Helper.exec(walApp, "INSERT INTO t(id) VALUES(5001)"), 0, "the app commits during a long read of a WAL database"); + check(System.currentTimeMillis() - w0 < 500, "the WAL commit did not wait"); + wt.join(); + eq(wal.code, 9, "the WAL read ended at its deadline: SQLITE_INTERRUPT"); + check(wal.message != null && wal.message.contains("time limit") && !wal.message.contains("WAL"), "the WAL message: " + wal.message); + check(wal.ms >= 3000 && wal.ms < 5000, "the WAL read ran " + wal.ms + " ms, past the non-WAL cap"); + NativeBridge.close(walSrv); + Helper.close(walApp); + } + public static void main(String[] a) throws Exception { System.loadLibrary("sqlite3x"); System.loadLibrary("sqlitedbg"); @@ -284,6 +364,8 @@ public static void main(String[] a) throws Exception { NativeBridge.close(w); Helper.exec(app, "DELETE FROM t WHERE id = 4245"); + nonWalCap(dir, path); + try { NativeBridge.openServer(dir.resolve("none.db").toString().getBytes(StandardCharsets.UTF_8), false); check(false, "missing file"); diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c index e69df00f10..166bee1eed 100644 --- a/subprojects/sqlite-debugger/src/test/jni/helper.c +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -42,3 +42,10 @@ JNIEXPORT jint JNICALL Java_Helper_denyTransactions(JNIEnv *e, jclass c, jlong d (void)c; return sqlite3_set_authorizer((sqlite3 *)(intptr_t)db, deny ? deny_transactions : 0, 0); } + +// The app's busy timeout; requery sets 2500 ms on every app connection. +JNIEXPORT jint JNICALL Java_Helper_busyTimeout(JNIEnv *e, jclass c, jlong db, jint ms) { + (void)e; + (void)c; + return sqlite3_busy_timeout((sqlite3 *)(intptr_t)db, ms); +} From f683484ea9f46858f67ba36b8672f6542d52c803 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:59:54 -0800 Subject: [PATCH 164/203] ADFA-7135 Run the SQLite debugger's Kotlin unit tests in CI test-sqlite-debugger.yml runs only test.sh (the C and JNI tests), and debug.yml ran only the :plugin-api unit tests, so the module's JVM tests (EventDecoder, McpProtocol, McpHttp, DatabaseTools) never ran in CI. Add a step to debug.yml beside the :plugin-api one, in the same flox style, and say so in the README. It follows the McpHttp fix, so CI does not go red on the flaky test. Review thread 4608432556 (Hal). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .github/workflows/debug.yml | 7 +++++++ subprojects/sqlite-debugger/README.md | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/debug.yml b/.github/workflows/debug.yml index d918ad6772..ed07b819d8 100644 --- a/.github/workflows/debug.yml +++ b/.github/workflows/debug.yml @@ -204,6 +204,13 @@ jobs: run: | flox activate -d flox/base -- ./gradlew :plugin-api:testDebugUnitTest --no-daemon + # The SQLite debugger's Kotlin tests (EventDecoder, McpProtocol, McpHttp, DatabaseTools). Its own + # workflow, test-sqlite-debugger.yml, runs only test.sh (the C and JNI tests) on ubuntu-latest. Like + # :plugin-api it has no product flavors, so the task is testDebugUnitTest. + - name: Run sqlite-debugger unit tests + run: | + flox activate -d flox/base -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest --no-daemon + # Combined with a compile task on purpose: spotlessCheck alone never pulls a # source-tree-writing task into the graph, so the implicit-dependency failure ADFA-5244 fixed # cannot reproduce in a standalone run. Without this step a regression of that exclude is diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 3c80d318a7..8900c17a74 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -45,7 +45,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). -`.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. No workflow runs the JVM tests. +`.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. ## Not done yet From 9ff51c2e9a13bb7534c34bbaa9097fdb4e8d5ae0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 11:22:23 -0800 Subject: [PATCH 165/203] ADFA-7138 Docs: a cast to a non-SQLite cursor type can be a false positive with a custom factory The AbstractWindowedCursor limit said that a cast of a cursor from an SQLite API to a type that is not an SQLite cursor cannot be a false positive. With a custom CursorFactory that returns a non-requery cursor, such as a MatrixCursor, the cast can be safe; that is the first of the four accepted false positives. Qualify the sentence (CodeRabbit, thread 4655085967). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 9a1872283d..32887b24e6 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -252,7 +252,8 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - The `AbstractWindowedCursor` check follows the cursor through locals and the stack only. A cast of a cursor that reached the method through a field, a parameter or another call is not seen (the app throws `ClassCastException` at run time), and a cast of a cursor from an SQLite API to a type that is not an - SQLite cursor cannot be a false positive. + SQLite cursor is a false positive only when a custom `CursorFactory` returns a non-requery cursor (the first + of the four false positives above). - Compile-time constants are copied into callers, so uses of `NO_LOCALIZED_COLLATORS`, `JOURNAL_MODE_*` or `SYNC_MODE_*` are not visible to the fail rule. `NO_LOCALIZED_COLLATORS` is dropped by the flag translation. - The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied. From f532ce67921e1153613bd0a3a6cfb43f977e5931 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 12:44:56 -0800 Subject: [PATCH 166/203] ADFA-7138 Status-line tap test: place the sheet in a CoordinatorLayout and stop the crash-handler loop EditorBottomSheetStatusTapTest built a Robolectric activity and an EditorBottomSheet in field initializers, with the sheet outside any CoordinatorLayout. When the activity started, the sheet's sheetState collector called BottomSheetBehavior.from(sheet), which threw "The view is not a child of CoordinatorLayout" as an uncaught exception. Run alone, the default handler took it and the class passed. After another test had created an IDEApplication in the same JVM, IDEApplication's and CredentialProtectedApplicationLoader's handleUncaughtException called each other until the stack overflowed (IDEApplication.kt:273 and CredentialProtectedApplicationLoader.kt:230), and the errors this left, each with a message of about 120 KB, filled the 1 GB test heap: the full :app suite died with OutOfMemoryError (ADFA-7259). The test now creates the activity, places the sheet in a CoordinatorLayout with EditorBottomSheetBehavior as content_editor.xml does, and only then starts the activity; it destroys the activity after each test. A default handler set for the test keeps uncaught exceptions out of the IDEApplication loop: one on the main thread, where the sheet's collectors run, fails the test, and one from a thread another test left running is printed. The assertions are unchanged. Checked: both classes pass in one Gradle call; the full :app suite passes (1803 tests); removing either wiring call in EditorBottomSheet fails the tests named for it; without the sheet's behavior all four tests fail with the sheet's IllegalArgumentException instead of crashing the JVM. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../ui/EditorBottomSheetStatusTapTest.kt | 63 ++++++++++++++++--- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt b/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt index d7ad2f61be..f533fa94a8 100644 --- a/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt +++ b/app/src/test/java/com/itsaky/androidide/ui/EditorBottomSheetStatusTapTest.kt @@ -1,14 +1,20 @@ package com.itsaky.androidide.ui +import android.os.Looper import android.view.Gravity +import android.view.ViewGroup.LayoutParams.MATCH_PARENT +import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.fragment.app.FragmentActivity import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.R import com.itsaky.androidide.app.BaseApplication +import org.junit.After +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner +import org.robolectric.android.controller.ActivityController import org.robolectric.annotation.Config /** @@ -21,14 +27,57 @@ import org.robolectric.annotation.Config class EditorBottomSheetStatusTapTest { open class TestApp : BaseApplication() - private val activity = - Robolectric - .buildActivity(FragmentActivity::class.java) - .also { it.get().setTheme(R.style.Theme_AndroidIDE) } - .setup() - .get() + private lateinit var controller: ActivityController + private lateinit var sheet: EditorBottomSheet + private var savedHandler: Thread.UncaughtExceptionHandler? = null + private val uncaught = mutableListOf() + + @Before + fun setUp() { + // IDEApplication.onCreate chains the previous default handler into its own, so once a JVM has + // created two of them, an uncaught exception loops between the handlers until the heap runs + // out (ADFA-7259). Catch uncaught exceptions here instead. The sheet's collectors run on the + // main thread, so only an exception there fails the test; one from a thread another test + // left running is printed. + savedHandler = Thread.getDefaultUncaughtExceptionHandler() + val main = Looper.getMainLooper().thread + Thread.setDefaultUncaughtExceptionHandler { thread, error -> + if (thread === main) { + uncaught += "${thread.name}: $error" + } else { + System.err.println("Uncaught on ${thread.name} during EditorBottomSheetStatusTapTest: $error") + } + } + + controller = Robolectric.buildActivity(FragmentActivity::class.java) + val activity = controller.get() + activity.setTheme(R.style.Theme_AndroidIDE) + controller.create() + // The sheet's collectors start with the activity and look up its BottomSheetBehavior, so + // place the sheet the way content_editor.xml does before the activity starts. + sheet = EditorBottomSheet(activity) + val root = CoordinatorLayout(activity) + root.addView( + sheet, + CoordinatorLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT).apply { + behavior = EditorBottomSheetBehavior(activity, null) + }, + ) + activity.setContentView(root) + controller + .start() + .postCreate(null) + .resume() + .visible() + } + + @After + fun tearDown() { + controller.pause().stop().destroy() + Thread.setDefaultUncaughtExceptionHandler(savedHandler) + assertThat(uncaught).isEmpty() + } - private val sheet = EditorBottomSheet(activity) private val statusText get() = sheet.binding.buildStatus.statusText private var taps = 0 From 3ae862a1deb34796f806aadc70aaf3c92efc16a9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 20:00:37 +0000 Subject: [PATCH 167/203] ADFA-7135 sqlite-debugger README: say where the rest lands and what ran on devices "Not done yet" listed a device run of the current code as missing. The whole stack, which includes this code, ran on a Galaxy Note 20 (Android 13, arm64-v8a) and a Galaxy J7 (Android 9, armeabi-v7a) on 2026-11-21. The section now says so, and names the stacked PR for each item that is outside this module. Docs only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba --- subprojects/sqlite-debugger/README.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8900c17a74..4f162e64d6 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -49,7 +49,14 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han ## Not done yet -- Broadcasting the port and token to Code on the Go (ADFA-7137). `DebuggerStartup` only keeps them in `DebuggerStartup.port` and `endpointToken` and logs the port, never the token. -- Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138). -- The AI-Agent-MCP side that connects to the server (ADFA-7139). -- A device run of the current code. The device results on ADFA-7135 (statements captured on both ABIs, the overhead) predate the review fixes. +These are outside this module and come in the PRs stacked on it: + +- Broadcasting the port and token to Code on the Go (ADFA-7137, #2260). Here `DebuggerStartup` only keeps them in `DebuggerStartup.port` and `endpointToken` and logs the port, never the token. +- Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138, #2262). +- The AI-Agent-MCP side that connects to the server (ADFA-7139, #2261 and addons #166). + +On devices, this code has run only as part of the whole stack, on 2026-11-21: +- on a Galaxy Note 20 (Android 13, arm64-v8a); +- on a Galaxy J7 (Android 9, armeabi-v7a). + +On both, the server started and Code on the Go paired with the app. On the Note 20 the Agent also queried the app's database; AI-Agent-MCP needs Android 13. The results are on ADFA-7131. From 52bc0ad3cf2722c4a624d210af120109cfe1d377 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 12:56:10 -0800 Subject: [PATCH 168/203] ADFA-7135 sqlite-debugger README: the device runs predate the review fixes The device lines from ea03fe969 said "this code" ran on both phones on 2026-11-21. That run was at 632bc27eb; the review fixes since, including the 1.5 s limit on a database not in WAL mode (df22b7aca) and draining the request before closing after an error reply (3a3d57add), have not run on a device. Say so (ADFA-7131 comment 41490 asked for the lines to be checked). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 4f162e64d6..6ff6f12b02 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -55,8 +55,8 @@ These are outside this module and come in the PRs stacked on it: - Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138, #2262). - The AI-Agent-MCP side that connects to the server (ADFA-7139, #2261 and addons #166). -On devices, this code has run only as part of the whole stack, on 2026-11-21: +On devices, this module has run only as part of the whole stack, at 632bc27eb, on 2026-11-21: - on a Galaxy Note 20 (Android 13, arm64-v8a); - on a Galaxy J7 (Android 9, armeabi-v7a). -On both, the server started and Code on the Go paired with the app. On the Note 20 the Agent also queried the app's database; AI-Agent-MCP needs Android 13. The results are on ADFA-7131. +On both, the server started and Code on the Go paired with the app. On the Note 20 the Agent also queried the app's database; AI-Agent-MCP needs Android 13. The results are on ADFA-7131. The review fixes after 632bc27eb have not run on a device yet, among them the 1.5 s limit on a database not in WAL mode (df22b7aca) and draining the request before closing after an error reply (3a3d57add). From 3412fe0e5454f66ee37ffebfc624f0f6f37d886f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 18:21:18 -0800 Subject: [PATCH 169/203] ADFA-7138 Quick Build tap: no "Replace the installed app?" when the SQLite debugger will refuse On a Galaxy Note 20 (2026-11-23), with com.example.probe installed by Run and the SQLite debugger on, the status line's "tap for details" asked "Replace the installed app?" instead of explaining. The tap runs the Quick Build button's own path, and that path asked the replace question before the provisioner's SQLite debugger check. Replace led to the refusal; Cancel ended the tap with no explanation at all. The button had the same order. The tap now reads the provisioner's check after the save and skips the question when the build will be refused: the refusal comes before anything is staged or installed, so there is no replacement to ask about. The session then shows the refusal as before, as the banner and as the "tap for details" line. GradleQuickBuildProvisioner.refusesForSqliteDebugger is that check, shared with provision(): false while the project model is not published, when the provisioner decides only after the sync (a module's file can turn the opt-in off), so the tap asks as before. A failure to read the opt-in also asks as before. Covered: the toolbar button, the status-line tap, the dropdown row and the plugin API all start a tap through QuickBuildAction.launchTap. Standard Run's own clobber question is a different gate and is unchanged. Limit: the check and the provisioner read the same files a moment apart. A change to them in between (an external write or a sync finishing) could let the provisioner build and install without the question. The save that could write such a change runs before the check. Tests: QuickBuildReplaceQuestionTest (the question is not asked when refused; otherwise its answer decides) and QuickBuildTapSqliteDebuggerCheckTest (the tap's check agrees with provision() for a root opt-in, a module opt-in, a module false over a root true and no opt-in; false during a sync). The call inside launchTap needs EditorHandlerActivity and has no JVM test. With the fix reverted, the tests named for it fail. The full :app suite (1810 tests) and spotlessCheck pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../actions/build/QuickBuildAction.kt | 44 ++++++++- .../quickbuild/GradleQuickBuildProvisioner.kt | 39 +++++--- .../build/QuickBuildReplaceQuestionTest.kt | 41 ++++++++ .../QuickBuildTapSqliteDebuggerCheckTest.kt | 94 +++++++++++++++++++ 4 files changed, 202 insertions(+), 16 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/actions/build/QuickBuildReplaceQuestionTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt b/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt index ae88ece543..650f576516 100644 --- a/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt +++ b/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt @@ -30,6 +30,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildTone import org.appdevforall.cotg.quickbuild.domain.session.toTone import org.appdevforall.cotg.quickbuild.service.session.QuickBuildSessionManager @@ -150,10 +151,13 @@ class QuickBuildAction( private val tapInFlight = AtomicBoolean(false) /** - * Runs a Quick Build tap: save the open files, confirm replacing an installed app, then - * hand the tap to [sessionManager]. The toolbar button and the plugin API both start - * Quick Build here, so they cannot drift apart. + * Runs a Quick Build tap: save the open files, confirm replacing an installed app unless the + * SQLite debugger will refuse the build, then hand the tap to [sessionManager]. The toolbar + * button, the status line's "tap for details" and the plugin API all start Quick Build here, + * so they cannot drift apart. * + * @param refusedForSqliteDebugger read off the main thread after the save: true when the + * provisioner will refuse the build because the project turns the SQLite debugger on. * @param beforeSession asked on the main thread just before the tap reaches the session; * false drops it, for a caller that cancelled while the tap was saving or asking. * @param onOutcome told once how the tap ended, unless the activity is destroyed or @@ -163,6 +167,7 @@ class QuickBuildAction( internal fun launchTap( activity: EditorHandlerActivity, sessionManager: QuickBuildSessionManager, + refusedForSqliteDebugger: () -> Boolean = { GradleQuickBuildProvisioner.refusesForSqliteDebugger() }, beforeSession: () -> Boolean = { true }, onOutcome: (TapOutcome) -> Unit = {}, ): Job? { @@ -170,13 +175,14 @@ class QuickBuildAction( log.info("Quick Build: a tap is already in flight; dropping this one") return null } - return startTap(activity, sessionManager, beforeSession, onOutcome) + return startTap(activity, sessionManager, refusedForSqliteDebugger, beforeSession, onOutcome) .also { it.invokeOnCompletion { tapInFlight.set(false) } } } private fun startTap( activity: EditorHandlerActivity, sessionManager: QuickBuildSessionManager, + refusedForSqliteDebugger: () -> Boolean, beforeSession: () -> Boolean, onOutcome: (TapOutcome) -> Unit, ): Job = @@ -209,6 +215,19 @@ class QuickBuildAction( onOutcome(TapOutcome.SAVE_FAILED) return@launch } + // Read after the save, which can write a gradle.properties the user just edited, and + // before the activity check, since it leaves the main thread. + val refused = + withContext(Dispatchers.IO) { + try { + refusedForSqliteDebugger() + } catch (e: Exception) { + // Unknown, so ask about the installed app as a tap always did; the provisioner + // still makes its own check. + log.warn("Quick Build: could not read the SQLite debugger opt-in; asking about the installed app", e) + false + } + } if (activity.isDestroyed || activity.isFinishing) { log.info("Quick Build: the activity went away during the save; dropping the tap") onOutcome(TapOutcome.ACTIVITY_GONE) @@ -218,7 +237,7 @@ class QuickBuildAction( // project's real applicationId. If the Standard Run build currently occupies that // id, a tap replaces it, so the activity confirms the clobber first and the build // proceeds only on accept. - if (!activity.awaitQuickBuildClobberConfirmed()) { + if (!replaceConfirmedUnlessRefused(refused) { activity.awaitQuickBuildClobberConfirmed() }) { onOutcome(TapOutcome.DECLINED) return@launch } @@ -235,6 +254,21 @@ class QuickBuildAction( onOutcome(TapOutcome.STARTED) } + /** + * Whether a tap may go on to the session, as far as replacing the installed app goes. Not + * asked when the SQLite debugger will refuse the build: the provisioner refuses before + * anything is staged or installed, so the question would be about a replacement that cannot + * happen, and its Cancel would hide the refusal that explains why Quick Build is off. The + * session then shows that refusal, as the banner and as the status line's "tap for details". + * + * @param refused whether the SQLite debugger will refuse the build. + * @param confirm asks the user, on the main thread; true to replace the installed app. + */ + internal suspend fun replaceConfirmedUnlessRefused( + refused: Boolean, + confirm: suspend () -> Boolean, + ): Boolean = refused || confirm() + /** * The one bit the tap carries across the save/watch boundary: whether the save-all * will write anything. SaveResult does not say, but saveAllResult only writes diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 03aed21800..508c1d246f 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -564,17 +564,7 @@ class GradleQuickBuildProvisioner( projectManager: IProjectManager, projectRoot: File, ): ProxyAppBuildResult.Refused? { - // Every app module's gradle.properties is read, although Quick Build builds only the first - // app module: the opt-in is decided per project, and the first file that defines the - // property decides it (the Gradle user home, then the modules in order, then the root), so - // a module's `false` overrides a root `true` as it does in Gradle. - val enabled = - QuickBuildProjectSupport.isSqliteDebuggerEnabled( - projectRoot, - Environment.GRADLE_USER_HOME, - projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, - ) - if (!enabled) return null + if (!isSqliteDebuggerOn(projectManager, projectRoot)) return null log.info( "Quick Build is not provisioned: {} is true in the Gradle user home's, an app module's or the project's gradle.properties", GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, @@ -608,6 +598,33 @@ class GradleQuickBuildProvisioner( manager.getAndroidAppModules().firstOrNull() ?: manager.getAndroidModules().firstOrNull() + /** + * Whether a Quick Build tap now would be refused because the project turns the SQLite + * debugger on, read as [provision] reads it before staging: false while the project model is + * not published, when the provisioner decides only after the sync. For a tap to read before it + * asks to replace the installed app: the refusal comes before anything is staged or installed, + * so there is no replacement to ask about. + */ + fun refusesForSqliteDebugger(projectManager: IProjectManager = IProjectManager.getInstance()): Boolean = + projectManager.workspace != null && isSqliteDebuggerOn(projectManager) + + /** + * Whether `cogo.sqliteDebugger=true` is in force for [projectManager]'s project. Every app + * module's gradle.properties is read, although Quick Build builds only the first app module: + * the opt-in is decided per project, and the first file that defines the property decides it + * (the Gradle user home, then the modules in order, then the root), so a module's `false` + * overrides a root `true` as it does in Gradle. + */ + private fun isSqliteDebuggerOn( + projectManager: IProjectManager, + projectRoot: File = File(projectManager.projectDirPath), + ): Boolean = + QuickBuildProjectSupport.isSqliteDebuggerEnabled( + projectRoot, + Environment.GRADLE_USER_HOME, + projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, + ) + /** * The Build Variants selection Quick Build would build right now, or null when the * project model has no module to ask - during a sync, or for a project with no Android diff --git a/app/src/test/java/com/itsaky/androidide/actions/build/QuickBuildReplaceQuestionTest.kt b/app/src/test/java/com/itsaky/androidide/actions/build/QuickBuildReplaceQuestionTest.kt new file mode 100644 index 0000000000..81f6172668 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/actions/build/QuickBuildReplaceQuestionTest.kt @@ -0,0 +1,41 @@ +package com.itsaky.androidide.actions.build + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import org.junit.Test + +/** + * The "Replace the installed app?" question on a Quick Build tap. A project that turns the SQLite + * debugger on is refused before anything is installed, so the question must not be asked: on a + * Galaxy Note 20 it came before the refusal, and its Cancel hid the refusal that the status line's + * "tap for details" exists to show. + */ +class QuickBuildReplaceQuestionTest { + @Test + fun `the question is not asked when the SQLite debugger will refuse the build`() = + runTest { + var asked = false + + val proceed = + QuickBuildAction.replaceConfirmedUnlessRefused(refused = true) { + asked = true + false + } + + assertThat(asked).isFalse() + assertThat(proceed).isTrue() + } + + @Test + fun `otherwise the question is asked, and its answer decides`() = + runTest { + var asked = 0 + + val replace = QuickBuildAction.replaceConfirmedUnlessRefused(refused = false) { ++asked > 0 } + val cancel = QuickBuildAction.replaceConfirmedUnlessRefused(refused = false) { ++asked < 0 } + + assertThat(asked).isEqualTo(2) + assertThat(replace).isTrue() + assertThat(cancel).isFalse() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt new file mode 100644 index 0000000000..1eddffb0e6 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt @@ -0,0 +1,94 @@ +package com.itsaky.androidide.quickbuild + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.projects.IProjectManager +import kotlinx.coroutines.test.runTest +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildMessage +import org.appdevforall.cotg.quickbuild.service.provision.ProvisionOutcome +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +/** + * [GradleQuickBuildProvisioner.refusesForSqliteDebugger], which a Quick Build tap reads to skip the + * "Replace the installed app?" question. Skipping it is safe only when the provisioner will refuse + * before it installs anything, so each case checks that the tap's answer agrees with what + * [GradleQuickBuildProvisioner.provision] does for the same project. + */ +@RunWith(RobolectricTestRunner::class) +class QuickBuildTapSqliteDebuggerCheckTest { + @get:Rule + val temp = TemporaryFolder() + + private val context: Context get() = ApplicationProvider.getApplicationContext() + + private val projectRoot: File get() = temp.root + + private fun appModuleDir(): File = File(projectRoot, "app").apply { mkdirs() } + + private fun publishedProject(): FakeProjectManager { + val moduleDir = appModuleDir() + return FakeProjectManager( + projectRoot, + appModules = listOf(androidModule(buildDir = File(moduleDir, "build"), projectDir = moduleDir)), + ) + } + + private suspend fun provisionerRefuses(projectManager: IProjectManager): Boolean = + testProvisioner(context = context, projectRoot = projectRoot, projectManager = projectManager) + .provision() == ProvisionOutcome.Failure(QuickBuildMessage.DisabledBySqliteDebugger) + + @Test + fun `a root opt-in is refused, by the tap's check and by the provisioner`() = + runTest { + File(projectRoot, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + val project = publishedProject() + + assertThat(GradleQuickBuildProvisioner.refusesForSqliteDebugger(project)).isTrue() + assertThat(provisionerRefuses(project)).isTrue() + } + + @Test + fun `an opt-in in the app module's gradle properties is refused`() = + runTest { + File(appModuleDir(), "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + val project = publishedProject() + + assertThat(GradleQuickBuildProvisioner.refusesForSqliteDebugger(project)).isTrue() + assertThat(provisionerRefuses(project)).isTrue() + } + + @Test + fun `a root opt-in that the app module turns off is not refused, so the tap still asks`() = + runTest { + File(projectRoot, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + File(appModuleDir(), "gradle.properties").writeText("cogo.sqliteDebugger=false\n") + val project = publishedProject() + + assertThat(GradleQuickBuildProvisioner.refusesForSqliteDebugger(project)).isFalse() + assertThat(provisionerRefuses(project)).isFalse() + } + + @Test + fun `a project without the opt-in is not refused`() = + runTest { + val project = publishedProject() + + assertThat(GradleQuickBuildProvisioner.refusesForSqliteDebugger(project)).isFalse() + assertThat(provisionerRefuses(project)).isFalse() + } + + @Test + fun `during a sync the tap's check says no, and the tap asks as before`() { + // The provisioner decides only after the sync publishes the modules, whose own files can turn + // the opt-in off, so the tap cannot know yet and must not skip the question. + File(projectRoot, "gradle.properties").writeText("cogo.sqliteDebugger=true\n") + + assertThat(GradleQuickBuildProvisioner.refusesForSqliteDebugger(unsyncedProjectManager(projectRoot))).isFalse() + } +} From 6926346081d6c2be55175e16c1f8bc003226357d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 22:49:09 -0800 Subject: [PATCH 170/203] ADFA-7138 Quick Build SQLite debugger opt-in: decide it for the module Quick Build builds, as Gradle does The IDE read the Gradle user home, every app module and the root, and the first file that defined cogo.sqliteDebugger decided for the whole project. Gradle decides per app module with findProperty, so the two disagreed in a multi-app project: root true with the first app unset and the second app false let Quick Build go on and end in "variant setup missing"; an opt-in only in the second app refused a first app that Gradle leaves alone; and a parent project's gradle.properties was never read. Now the check reads the Gradle user home, the module Quick Build builds (quickBuildModule), each parent Gradle project, then the root, first definition wins. Parent directories come from the project model (Workspace.subProjects lists every IDEA module of the build, Android or not: RootModelBuilder); a parent the model lacks is taken from the default layout, which misses a projectDir remapped in settings.gradle (accepted, stated in the KDoc and docs). With no Android module only the user home and the root are read. QuickBuildProjectSupport.isSqliteDebuggerEnabled(File, List) replaces the (root, home, moduleDirs) overload; propertyDirs builds the nearest-first list. provision() (sqliteDebuggerRefusal) and the tap's refusesForSqliteDebugger still share one function, isSqliteDebuggerOn. Siblings checked: the only other callers of isSqliteDebuggerEnabled are the two above and the String overload (unchanged, tests only). QuickBuildAction only calls refusesForSqliteDebugger. QuickBuildMessages, the status line and the session state only map the DisabledBySqliteDebugger message and keep no opt-in logic. Left alone: QuickBuildProjectLayout.watchedFiles watches the module, scanned-module and root files and the user home; a parent project's gradle.properties is watched only when that directory has a build script, so turning the opt-in on in a bare parent ends no running session until the next proxy app build (KDoc says so). SqliteRewriter's WAY_OUT build message lists user home, module, root and omits parent projects; not touched (gradle-plugin module, wording only). Docs: sqlite-debugger README and the "Turning it on" section of gradle-plugin/docs/sqlite-rewrite.md say Gradle decides per app module, another app module does not affect Quick Build, and how to turn it off across a project; KDocs of both isSqliteDebuggerEnabled overloads, isSqliteDebuggerOn and refusesForSqliteDebugger match. Tests: QuickBuildTapSqliteDebuggerCheckTest gains 8 cases, each asserting the tap check and provision() agree: root true with second app false (refused), opt-in only in the second app (not refused), parent true (refused), parent dir remapped in the model (refused), module false over parent true, parent false over root true, user home false over module true (all not refused), user home true (refused). QuickBuildProjectSupportTest moves to the new signature and adds nearest-first and propertyDirs cases. Changed expectations: GradleQuickBuildProvisionerFailureArmsTest "an opt-in in a module that a sync publishes during the staging is refused" put the opt-in in a second app module, which no longer counts; it now publishes the module as the first app module (renamed). Revert proof: with the old lookup (app modules then root) restored, 5 of the 8 new cases fail, e.g. "expected: true but was: false" for the second app's false over a root true, and "expected: false but was: true" for an opt-in only in the second app; the 3 that agree under both rules (module false over parent true, and the two user home cases) are guards. With the fix: 116 tests in the targeted classes pass; spotlessCheck passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 55 ++++--- .../quickbuild/QuickBuildProjectSupport.kt | 63 ++++++-- ...dleQuickBuildProvisionerFailureArmsTest.kt | 6 +- .../QuickBuildProjectSupportTest.kt | 59 +++++++- .../QuickBuildTapSqliteDebuggerCheckTest.kt | 139 +++++++++++++++++- gradle-plugin/docs/sqlite-rewrite.md | 16 +- .../data/QuickBuildProjectLayout.kt | 9 +- subprojects/sqlite-debugger/README.md | 2 +- 8 files changed, 295 insertions(+), 54 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 508c1d246f..a304163562 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -556,9 +556,9 @@ class GradleQuickBuildProvisioner( } /** - * The refusal for a project with `cogo.sqliteDebugger=true`, or null. It reads the app modules' - * own `gradle.properties` only for the modules [projectManager] knows, which is none before the - * sync publishes the model, so it decides only once the model is published. + * The refusal for a module with `cogo.sqliteDebugger=true` in force, or null. The module and its + * parent projects come from [projectManager], which knows none before the sync publishes the + * model, so it decides only once the model is published. */ private fun sqliteDebuggerRefusal( projectManager: IProjectManager, @@ -566,7 +566,7 @@ class GradleQuickBuildProvisioner( ): ProxyAppBuildResult.Refused? { if (!isSqliteDebuggerOn(projectManager, projectRoot)) return null log.info( - "Quick Build is not provisioned: {} is true in the Gradle user home's, an app module's or the project's gradle.properties", + "Quick Build is not provisioned: {} is true for the module it builds (Gradle user home, module, parent projects or root)", GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, ) return ProxyAppBuildResult.Refused @@ -599,31 +599,46 @@ class GradleQuickBuildProvisioner( ?: manager.getAndroidModules().firstOrNull() /** - * Whether a Quick Build tap now would be refused because the project turns the SQLite - * debugger on, read as [provision] reads it before staging: false while the project model is - * not published, when the provisioner decides only after the sync. For a tap to read before it - * asks to replace the installed app: the refusal comes before anything is staged or installed, - * so there is no replacement to ask about. + * Whether a Quick Build tap now would be refused because the module Quick Build builds has the + * SQLite debugger opt-in in force, read as [provision] reads it before staging: false while the + * project model is not published, when the provisioner decides only after the sync. For a tap + * to read before it asks to replace the installed app: the refusal comes before anything is + * staged or installed, so there is no replacement to ask about. */ fun refusesForSqliteDebugger(projectManager: IProjectManager = IProjectManager.getInstance()): Boolean = projectManager.workspace != null && isSqliteDebuggerOn(projectManager) /** - * Whether `cogo.sqliteDebugger=true` is in force for [projectManager]'s project. Every app - * module's gradle.properties is read, although Quick Build builds only the first app module: - * the opt-in is decided per project, and the first file that defines the property decides it - * (the Gradle user home, then the modules in order, then the root), so a module's `false` - * overrides a root `true` as it does in Gradle. + * Whether `cogo.sqliteDebugger=true` is in force for the module Quick Build builds + * ([quickBuildModule]), as Gradle decides it for that module: the Gradle user home, then the + * module's `gradle.properties`, then each parent project's, then the root's, the first that + * defines the property winning. Another app module's file does not count, since Gradle skips + * Quick Build per module. Parent projects come from the project model, which lists every Gradle + * project; one it lacks is taken from the module's directory layout (see + * [QuickBuildProjectSupport.propertyDirs]). With no Android module there is no module to ask, + * so only the Gradle user home and the root are read. */ private fun isSqliteDebuggerOn( projectManager: IProjectManager, projectRoot: File = File(projectManager.projectDirPath), - ): Boolean = - QuickBuildProjectSupport.isSqliteDebuggerEnabled( - projectRoot, - Environment.GRADLE_USER_HOME, - projectManager.getAndroidAppModules().map { File(it.projectDirPath) }, - ) + ): Boolean { + val module = quickBuildModule(projectManager) + val projectDirs = + if (module == null) { + listOf(projectRoot) + } else { + QuickBuildProjectSupport.propertyDirs( + projectRoot, + module.path, + File(module.projectDirPath), + projectManager.workspace + ?.subProjects + .orEmpty() + .associate { it.path to File(it.projectDirPath) }, + ) + } + return QuickBuildProjectSupport.isSqliteDebuggerEnabled(Environment.GRADLE_USER_HOME, projectDirs) + } /** * The Build Variants selection Quick Build would build right now, or null when the diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt index 6ad9f0beac..1ac9073e5c 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt @@ -77,34 +77,67 @@ object QuickBuildProjectSupport { fun isSqliteDebuggerEnabled(gradleProperties: String?): Boolean = gradleProperties != null && propertyValue(gradleProperties) == "true" /** - * Whether the project opts in to `cogo.sqliteDebugger=true`, in which case Quick Build must not - * provision it: the Gradle plugin moves such a project to requery and never applies Quick Build - * to it, so a build would succeed and end in a "variant setup missing" message that blames the - * variant. Decided per project, from all app modules (see [moduleDirs]). + * The directories whose `gradle.properties` Gradle's `findProperty` reads for the project at + * [modulePath], nearest first: the module's own directory, each parent project's, then the root. + * A project inherits its parent's properties, so `:group:app` sees `:group`'s file before the + * root's. * - * Reads the opt-in from the same files the Gradle plugin's `findProperty` sees in - * Code on the Go's builds: the Gradle user home `gradle.properties` (`GRADLE_USER_HOME`, which - * overrides the project files), the app module's, and the root's. Gradle loads a + * A parent's directory comes from [projectDirs] (Gradle path to directory, from the project + * model, which lists the projects that have no Android plugin as well). A parent the model + * lacks is taken from the default layout: the module's directory walked up one level per path + * segment, which is wrong for a `projectDir` that `settings.gradle` has remapped. + * + * @param projectRoot the root project's directory, always last. + * @param modulePath the module's Gradle path, such as `:group:app`. + * @param moduleDir the module's own directory. + */ + fun propertyDirs( + projectRoot: File, + modulePath: String, + moduleDir: File, + projectDirs: Map = emptyMap(), + ): List { + val segments = modulePath.split(':').filter { it.isNotEmpty() } + val dirs = LinkedHashSet() + dirs += moduleDir + var walked: File? = moduleDir + for (depth in segments.size - 1 downTo 1) { + walked = walked?.parentFile + (projectDirs[":" + segments.take(depth).joinToString(":")] ?: walked)?.let(dirs::add) + } + dirs += projectRoot + return dirs.toList() + } + + /** + * Whether the module whose directories are [projectDirs] opts in to `cogo.sqliteDebugger=true`, + * in which case Quick Build must not provision it: the Gradle plugin moves such a module to + * requery and never applies Quick Build to it, so a build would succeed and end in a "variant + * setup missing" message that blames the variant. Decided for the module Quick Build builds + * alone, as Gradle decides it: another app module's value does not matter. + * + * Reads the files the Gradle plugin's `findProperty` sees for that module in Code on the Go's + * builds, and the first one that defines the property decides: the Gradle user home + * `gradle.properties` (`GRADLE_USER_HOME`, which overrides the project files), then [projectDirs] + * in order (see [propertyDirs]: the module, its parent projects, the root). Gradle loads a * `gradle.properties` from every project directory into that project, and a subproject also - * inherits its parent's properties, so the first of these that defines the property wins. - * `-P` arguments are not read: Code on the Go passes none for this property. + * inherits its parent's properties. `-P` arguments are not read: Code on the Go passes none for + * this property. * * A file that cannot be read is reported to [onReadFailure] and counts as not defining it. * - * @param moduleDirs the directories of the app modules the plugin is applied to. + * @param gradleUserHome the Gradle user home, or null when there is none. + * @param projectDirs the module's directory, its parents', and the root's, nearest first. */ fun isSqliteDebuggerEnabled( - projectRoot: File, gradleUserHome: File?, - moduleDirs: List = emptyList(), + projectDirs: List, onReadFailure: (File, Throwable) -> Unit = { file, error -> log.warn("Cannot read {}; treating it as not defining the SQLite debugger opt-in", file, error) }, readText: (File) -> String = File::readText, ): Boolean { - val files = - listOfNotNull(gradleUserHome) + moduleDirs + projectRoot - for (entry in files) { + for (entry in listOfNotNull(gradleUserHome) + projectDirs) { val file = File(entry, "gradle.properties") val text = try { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt index 987a2f03c5..cd4ccd08a7 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFailureArmsTest.kt @@ -148,7 +148,7 @@ class GradleQuickBuildProvisionerFailureArmsTest { } @Test - fun `an opt-in in a module that a sync publishes during the staging is refused`() = + fun `an opt-in in the app module that a sync publishes as the first one during the staging is refused`() = runTest { val app = moduleDir() val feature = File(projectRoot, "feature").apply { mkdirs() } @@ -159,7 +159,7 @@ class GradleQuickBuildProvisionerFailureArmsTest { val project = ResyncingProjectManager( FakeProjectManager(projectRoot, appModules = listOf(appModule)), - FakeProjectManager(projectRoot, appModules = listOf(appModule, featureModule)), + FakeProjectManager(projectRoot, appModules = listOf(featureModule, appModule)), ) val outcome = @@ -169,7 +169,7 @@ class GradleQuickBuildProvisionerFailureArmsTest { buildService = gradle, projectManager = project, // The model was already published, so the first check read the old modules; the module with the - // opt-in appears only after it. + // opt-in appears only after it, ahead of :app, the module Quick Build then builds. stage = { _, _ -> project.resynced = true }, ).provision() diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt index 9a6ab5b9ee..908190f170 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt @@ -110,23 +110,23 @@ class QuickBuildProjectSupportTest { @Test fun `the root gradle properties file is read, a missing one is not an opt-in`() = withDirs { root, home, _ -> - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home)).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(root))).isFalse() root.props("cogo.sqliteDebugger=true\n") - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home)).isTrue() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(root))).isTrue() } @Test fun `the Gradle user home gradle properties opts in`() = withDirs { root, home, module -> home.props("cogo.sqliteDebugger=true\n") - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home, listOf(module))).isTrue() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(module, root))).isTrue() } @Test fun `the app module gradle properties opts in`() = withDirs { root, home, module -> module.props("cogo.sqliteDebugger=true\n") - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home, listOf(module))).isTrue() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(module, root))).isTrue() } @Test @@ -134,7 +134,16 @@ class QuickBuildProjectSupportTest { withDirs { root, home, module -> root.props("cogo.sqliteDebugger=true\n") home.props("cogo.sqliteDebugger=false\n") - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(root, home, listOf(module))).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(module, root))).isFalse() + } + + @Test + fun `the first directory that defines the property decides, nearest first`() = + withDirs { root, home, module -> + root.props("cogo.sqliteDebugger=true\n") + module.props("cogo.sqliteDebugger=false\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(module, root))).isFalse() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(root, module))).isTrue() } @Test @@ -144,12 +153,50 @@ class QuickBuildProjectSupportTest { val failures = mutableListOf() val enabled = QuickBuildProjectSupport.isSqliteDebuggerEnabled( - root, home, + listOf(root), onReadFailure = { file, _ -> failures += file }, readText = { throw java.io.IOException("denied") }, ) assertThat(enabled).isFalse() assertThat(failures).containsExactly(java.io.File(home, "gradle.properties")) } + + @Test + fun `property dirs run from the module up through its parent projects to the root`() { + val root = java.io.File("/p") + val dirs = QuickBuildProjectSupport.propertyDirs(root, ":group:sub:app", java.io.File("/p/group/sub/app")) + + assertThat(dirs) + .containsExactly( + java.io.File("/p/group/sub/app"), + java.io.File("/p/group/sub"), + java.io.File("/p/group"), + root, + ).inOrder() + } + + @Test + fun `a parent directory from the project model wins over the default layout`() { + val root = java.io.File("/p") + val dirs = + QuickBuildProjectSupport.propertyDirs( + root, + ":group:app", + java.io.File("/elsewhere/app"), + mapOf(":group" to java.io.File("/elsewhere/g")), + ) + + assertThat(dirs).containsExactly(java.io.File("/elsewhere/app"), java.io.File("/elsewhere/g"), root).inOrder() + } + + @Test + fun `a top-level module has only itself and the root`() { + val root = java.io.File("/p") + + assertThat(QuickBuildProjectSupport.propertyDirs(root, ":app", java.io.File("/p/app"))) + .containsExactly(java.io.File("/p/app"), root) + .inOrder() + assertThat(QuickBuildProjectSupport.propertyDirs(root, ":", root)).containsExactly(root) + } } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt index 1eddffb0e6..1219282ed9 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt @@ -4,9 +4,16 @@ import android.content.Context import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.projects.api.GradleProject +import com.itsaky.androidide.projects.api.Workspace +import com.itsaky.androidide.utils.Environment +import io.mockk.every +import io.mockk.mockk import kotlinx.coroutines.test.runTest import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildMessage import org.appdevforall.cotg.quickbuild.service.provision.ProvisionOutcome +import org.junit.After +import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -18,7 +25,9 @@ import java.io.File * [GradleQuickBuildProvisioner.refusesForSqliteDebugger], which a Quick Build tap reads to skip the * "Replace the installed app?" question. Skipping it is safe only when the provisioner will refuse * before it installs anything, so each case checks that the tap's answer agrees with what - * [GradleQuickBuildProvisioner.provision] does for the same project. + * [GradleQuickBuildProvisioner.provision] does for the same project. Gradle decides the opt-in per + * app module, so the cases also pin that only the module Quick Build builds (the first app module) + * and its parent projects count. */ @RunWith(RobolectricTestRunner::class) class QuickBuildTapSqliteDebuggerCheckTest { @@ -29,6 +38,55 @@ class QuickBuildTapSqliteDebuggerCheckTest { private val projectRoot: File get() = temp.root + private val gradleUserHome: File by lazy { File(projectRoot, "gradle-user-home").apply { mkdirs() } } + + private var savedGradleUserHome: File? = null + + @Before + fun pointGradleUserHomeAtTemp() { + savedGradleUserHome = Environment.GRADLE_USER_HOME + Environment.GRADLE_USER_HOME = gradleUserHome + } + + @After + fun restoreGradleUserHome() { + Environment.GRADLE_USER_HOME = savedGradleUserHome + } + + private fun File.props(text: String) = File(this, "gradle.properties").writeText(text) + + private fun dir(relative: String): File = File(projectRoot, relative).apply { mkdirs() } + + /** App modules `paths` (in order) under `projectRoot`, with a model that also lists [extraProjects]. */ + private fun projectOf( + vararg paths: String, + extraProjects: Map = emptyMap(), + ): FakeProjectManager { + val modules = + paths.map { path -> + val moduleDir = dir(path.trim(':').replace(':', '/')) + androidModule(path = path, buildDir = File(moduleDir, "build"), projectDir = moduleDir) + } + val listed = modules.associate { it.path to File(it.projectDirPath) } + extraProjects + val workspace = mockk() + every { workspace.subProjects } returns + listed.map { (path, dir) -> + mockk().also { + every { it.path } returns path + every { it.projectDirPath } returns dir.path + } + } + return FakeProjectManager(projectRoot, workspace = workspace, appModules = modules) + } + + private suspend fun assertTapAndProvisionerAgree( + project: IProjectManager, + refused: Boolean, + ) { + assertThat(GradleQuickBuildProvisioner.refusesForSqliteDebugger(project)).isEqualTo(refused) + assertThat(provisionerRefuses(project)).isEqualTo(refused) + } + private fun appModuleDir(): File = File(projectRoot, "app").apply { mkdirs() } private fun publishedProject(): FakeProjectManager { @@ -83,6 +141,85 @@ class QuickBuildTapSqliteDebuggerCheckTest { assertThat(provisionerRefuses(project)).isFalse() } + @Test + fun `a root true that the second app module turns off still refuses the first app module`() = + runTest { + // Gradle skips Quick Build for :app, which inherits the root's true; :other's false is its own. + projectRoot.props("cogo.sqliteDebugger=true\n") + val project = projectOf(":app", ":other") + dir("other").props("cogo.sqliteDebugger=false\n") + + assertTapAndProvisionerAgree(project, refused = true) + } + + @Test + fun `an opt-in in the second app module does not refuse the first`() = + runTest { + val project = projectOf(":app", ":other") + dir("other").props("cogo.sqliteDebugger=true\n") + + assertTapAndProvisionerAgree(project, refused = false) + } + + @Test + fun `an opt-in in a parent project refuses its app module`() = + runTest { + val project = projectOf(":group:app") + dir("group").props("cogo.sqliteDebugger=true\n") + + assertTapAndProvisionerAgree(project, refused = true) + } + + @Test + fun `a parent project's directory comes from the model, not the directory layout`() = + runTest { + val remapped = dir("elsewhere/g") + remapped.props("cogo.sqliteDebugger=true\n") + // The default layout would read group/, which has no file. + val project = projectOf(":group:app", extraProjects = mapOf(":group" to remapped)) + + assertTapAndProvisionerAgree(project, refused = true) + } + + @Test + fun `an app module's false overrides its parent's true`() = + runTest { + val project = projectOf(":group:app") + dir("group").props("cogo.sqliteDebugger=true\n") + dir("group/app").props("cogo.sqliteDebugger=false\n") + + assertTapAndProvisionerAgree(project, refused = false) + } + + @Test + fun `a parent's false overrides the root's true`() = + runTest { + projectRoot.props("cogo.sqliteDebugger=true\n") + val project = projectOf(":group:app") + dir("group").props("cogo.sqliteDebugger=false\n") + + assertTapAndProvisionerAgree(project, refused = false) + } + + @Test + fun `the Gradle user home's false overrides an app module's true`() = + runTest { + val project = projectOf(":app") + dir("app").props("cogo.sqliteDebugger=true\n") + gradleUserHome.props("cogo.sqliteDebugger=false\n") + + assertTapAndProvisionerAgree(project, refused = false) + } + + @Test + fun `the Gradle user home's true refuses a module that sets nothing`() = + runTest { + val project = projectOf(":app") + gradleUserHome.props("cogo.sqliteDebugger=true\n") + + assertTapAndProvisionerAgree(project, refused = true) + } + @Test fun `during a sync the tap's check says no, and the tap asks as before`() { // The provisioner decides only after the sync publishes the modules, whose own files can turn diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 32887b24e6..a61c4a52c0 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -9,11 +9,17 @@ run the same SQLite. User source does not change. An existing project needs: -1. `cogo.sqliteDebugger=true` in `gradle.properties`. The plugin reads it with Gradle's `findProperty`, so the - project's root file, the app module's own `gradle.properties` and the Gradle user home's - (`GRADLE_USER_HOME`, `~/.gradle` under Code on the Go's home) all work, the user home first. The IDE's Quick - Build check (`QuickBuildProjectSupport.isSqliteDebuggerEnabled`) reads those same three files, in that order, - and logs a file it cannot read; it does not see `-P` arguments, which Code on the Go does not pass for this. +1. `cogo.sqliteDebugger=true` in `gradle.properties`. The plugin reads it with Gradle's `findProperty` for each app + module it is applied to, so Gradle decides per module: the Gradle user home's file + (`GRADLE_USER_HOME`, `~/.gradle` under Code on the Go's home) first, then the module's own `gradle.properties`, + then each parent project's (`:group` for `:group:app`), then the root's; the first that defines the property + decides. Quick Build is off when the module it builds (the first app module) has the opt-in in force; another app + module's value does not affect Quick Build. To turn the rewrite off across a project, set + `cogo.sqliteDebugger=false` where the opt-in is in force for each app module, or in the Gradle user home. The + IDE's Quick Build check (`QuickBuildProjectSupport.isSqliteDebuggerEnabled`) reads those files for the Quick + Build module in that order. It takes a parent project's directory from the project model and, for a parent the + model lacks, from the default directory layout (it would miss a `projectDir` remapped in `settings.gradle`). It logs a + file it cannot read, and does not see `-P` arguments, which Code on the Go does not pass for this. 2. requery's AAR (`sqlite-android.aar`) in the app's `libs/`, as a file dependency (`implementation(files("libs/sqlite-android.aar"))`), as the ADFA-7082 template does. 3. androidx.sqlite and androidx.core on the runtime classpath (`androidx.sqlite:sqlite`, which Room, WorkManager diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt index 454e570131..b6b58fe5f8 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/data/QuickBuildProjectLayout.kt @@ -115,9 +115,12 @@ class QuickBuildProjectLayout( * builds, and each module the scan finds up to [MODULE_SCAN_MAX_DEPTH] levels below the root), * and the Gradle user home's `gradle.properties`, listed unconditionally - only the existing * ones are polled. So turning `QuickBuildProjectSupport.isSqliteDebuggerEnabled`'s opt-in on - * in one of those files invalidates a live session. Another app module nested deeper is read - * at the next proxy app build (a provision or a rebaseline), but its `gradle.properties` is - * not watched, so turning the opt-in on there does not end a running session. + * in one of those files invalidates a live session. A parent project's `gradle.properties` is + * watched only when its directory holds a build script, so turning the opt-in on in one that + * does not leaves a running session up until the next proxy app build. Another app module + * nested deeper is read at the next proxy app build (a provision or a rebaseline), but its + * `gradle.properties` is not watched, so turning the opt-in on there does not end a running + * session. */ fun watchedFiles(): List = listOfNotNull( diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 16a35e9bb2..2516671245 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -13,7 +13,7 @@ A project made from the JavaScript in SQLite template has it on already. For any 3. Check that the app depends on androidx.sqlite (Room and WorkManager bring it) and androidx.core (AppCompat brings it). requery needs both, and a file dependency brings neither. 4. Build and run the debug variant. The app starts the server and sends its port and token to Code on the Go (ADFA-7137), and AI-Agent-MCP connects to it with no setup (ADFA-7139). In phase 1 the Agent asks before each call (ADFA-7147). -The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on, Quick Build is off for the project. The opt-in is decided per project from all app modules: Code on the Go reads the Gradle user home, every app module and the root, so the first of those files that defines the line decides for the whole project, whatever the other modules say, even though Quick Build builds only the first app module. To turn all of this off, set the line to `cogo.sqliteDebugger=false` in the file that defines it, or in one read earlier; commenting the line out can expose another file's `true` ([details](../../gradle-plugin/docs/sqlite-rewrite.md#turning-it-on)). +The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on for an app module, Quick Build is off when that is the module it builds (the first app module). Gradle decides the line per app module, from the first of these files that defines it: the Gradle user home, the module's own `gradle.properties`, each parent project's, then the root's. Another app module's value does not affect Quick Build. To turn all of this off across a project, set `cogo.sqliteDebugger=false` where the line is in force for each app module (or once in the Gradle user home); commenting the line out can expose another file's `true` ([details](../../gradle-plugin/docs/sqlite-rewrite.md#turning-it-on)). Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails, names the class, method and line, and says how to build without the debugger; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). From 33c9bac731b2baaf4f46a789d5def9a61b736769 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 22:30:11 -0800 Subject: [PATCH 171/203] ADFA-7138 Reject OpenParams in array instructions (MULTIANEWARRAY, array casts) A method returning Object could return `new OpenParams[1][1]` without OpenParams in its descriptor: MULTIANEWARRAY was not scanned, and CHECKCAST/INSTANCEOF/ANEWARRAY of an array type passed `typeInsn`'s startsWith check because the descriptor starts with '['. Both would link to a class requery lacks. typeInsn now matches the OpenParams name anywhere in the type descriptor, and a MultiANewArrayInsnNode branch applies the same test (any number of dimensions). Same diagnostic as the scalar case. Arrays of other types are untouched. The doc's rule list says arrays count. Sweep of the other places OpenParams can appear. Already covered (a `contains` test on the descriptor): field and method declarations, method and field instruction owners and descriptors, method handles, LDC class constants, invokedynamic descriptors and class bootstrap arguments. Left alone: local variable table entries and generic Signature attributes (debug and metadata only; a use of the value needs one of the instructions above), try/catch types (OpenParams is not a Throwable) and annotations. Tests (SqliteRewriterTest): `new OpenParams[1][1]` returned as Object, a cast to `OpenParams[]`, `new OpenParams[1][]`, instanceof `OpenParams[][]` fail; arrays of SQLiteDatabase and String still pass. Revert proof: with only the SqliteRewriter.kt fix reverted, 4 of the 5 new tests fail with "Expected SqliteRewriteException to be thrown, but nothing was thrown" (the fifth is the still-passes case); with the fix, 77 tests in the three sqlite rewrite classes pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 2 +- .../gradle/sqlite/SqliteRewriter.kt | 7 ++- .../gradle/sqlite/SqliteRewriterTest.kt | 54 +++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index a61c4a52c0..0c0c67941b 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -74,7 +74,7 @@ file that defines the property decides). Commenting the line out can expose anot renamed class against requery), SQL text with `COLLATE UNICODE` (any case or whitespace, in any string constant, which covers Room's generated `_Impl` classes: requery's native SQLite has no ICU, so the collation does not exist), any use of - `SQLiteDatabase.OpenParams`, a call that passes android's `CursorWindow` to a renamed class (calls on + `SQLiteDatabase.OpenParams` (an array of it too, of any dimension: `new OpenParams[1][1]`, a cast to `OpenParams[]`), a call that passes android's `CursorWindow` to a renamed class (calls on `CursorWindow` itself are fine), and a cast of an SQLite cursor to `android.database.AbstractWindowedCursor`, `AbstractCursor` or `CrossProcessCursor` (requery's cursors extend its own copies of the first two, and implement only `android.database.Cursor`). diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 8a872179e7..c9c9d8f94f 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -482,6 +482,10 @@ object SqliteRewriter { typeInsn(m, insn, line, tainted) } + is MultiANewArrayInsnNode -> { + if (insn.desc.contains(Rules.OPEN_PARAMS)) violate(m, line, "OpenParams, which requery lacks") + } + is LdcInsnNode -> { (insn.cst as? Type)?.let { if (it.descriptor.contains(Rules.OPEN_PARAMS)) violate(m, line, "OpenParams, which requery lacks") @@ -632,7 +636,8 @@ object SqliteRewriter { line: Int, tainted: Set, ) { - if (t.desc.startsWith(Rules.OPEN_PARAMS)) { + // contains, not startsWith: an array type's descriptor starts with '[' (CHECKCAST, INSTANCEOF, ANEWARRAY of arrays) + if (t.desc.contains(Rules.OPEN_PARAMS)) { violate(m, line, "OpenParams, which requery lacks") } if (t.opcode == Opcodes.CHECKCAST && t.desc in Rules.ANDROID_ONLY_CURSOR_TYPES && t in tainted) { diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 300dbc715d..2664e384a9 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1020,6 +1020,60 @@ class SqliteRewriterTest { assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Fields"]!!, hierarchy) } } + private fun openParamsArrayFailure(body: String): String { + val classes = + Compiler.compile( + listOf(src("p.Arrays", "package p; import android.database.sqlite.*; public class Arrays { $body }")), + ) + return assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/Arrays"]!!, hierarchy) }.message!! + } + + @Test + fun `a two-dimensional OpenParams array returned as Object fails (MULTIANEWARRAY)`() { + val message = openParamsArrayFailure("Object go() { return new SQLiteDatabase.OpenParams[1][1]; }") + assertThat(message).contains("OpenParams, which requery lacks") + assertThat(message).contains("go()Ljava/lang/Object; (line 1)") + } + + @Test + fun `a cast to an OpenParams array fails`() { + val message = openParamsArrayFailure("Object go(Object o) { return (SQLiteDatabase.OpenParams[]) o; }") + assertThat(message).contains("OpenParams, which requery lacks") + } + + @Test + fun `a two-dimensional OpenParams ANEWARRAY fails`() { + val message = openParamsArrayFailure("Object go() { return new SQLiteDatabase.OpenParams[1][]; }") + assertThat(message).contains("OpenParams, which requery lacks") + } + + @Test + fun `an instanceof test on an OpenParams array fails`() { + val message = openParamsArrayFailure("boolean go(Object o) { return o instanceof SQLiteDatabase.OpenParams[][]; }") + assertThat(message).contains("OpenParams, which requery lacks") + } + + @Test + fun `arrays of a supported type still pass`() { + val out = + transform( + src( + "p.Ok", + """ + package p; + import android.database.sqlite.*; + public class Ok { + Object two() { return new SQLiteDatabase[1][1]; } + Object one() { return new SQLiteDatabase[1]; } + Object cast(Object o) { return (SQLiteDatabase[]) o; } + Object strings() { return new String[1][1]; } + } + """, + ), + ) + assertThat(out).containsKey("p/Ok") + } + @Test fun `androidx core's SQLiteCursorCompat helper is rewritten but never fails the build`() { val classes = From ae88e4f45100ec8d9726e0d6977d8ac7c121843a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 22:50:43 -0800 Subject: [PATCH 172/203] ADFA-7138 COLLATE rule: a quoted or bracketed collation name needs no space The COLLATE rule required whitespace or a comment after the keyword, so `COLLATE"UNICODE"`, `COLLATE'UNICODE'`, `COLLATE[UNICODE]` and COLLATE followed by a backquoted name passed the build check, and the statement then fails on requery (no ICU). A quote or bracket starts a new token, so SQLite reads these as a COLLATE clause. Checked with the SQLite 3.46.1 that Python here links (not 3.49.0, requery's version): `select 'a' collate"nocase"`, `collate'nocase'`, `collate[nocase]`, the backquoted form and `collate/*c*/nocase` all run as a COLLATE clause, while `collatenocase` parses as a column alias. collateRule now accepts a quoted or bracketed name straight after the keyword, for both UNICODE and LOCALIZED. A bare name still needs a separator and a word boundary, so `COLLATEUNICODE` and UNICODE_CI stay out, and a quoted name must close right after it, so "UNICODE-CI" stays out. The doc's known-limits line says the quoted name needs no space. Tests: SqliteRewriteRulesTest (quoted forms match without a space, `COLLATEUNICODE`, `COLLATEUNICODE x`, "UNICODE-CI", 'UNICODE_CI', [UNICODE-CI] do not, for UNICODE and LOCALIZED) and the no-space forms added to the two COLLATE tests in SqliteRewriterTest. Revert proof: with only SqliteRewriteRules.kt reverted, the new Rules test fails with `COLLATE"UNICODE"\nexpected to be true`; with the fix, 78 tests in the three sqlite rewrite classes pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 2 +- .../gradle/sqlite/SqliteRewriteRules.kt | 14 ++++++++------ .../gradle/sqlite/SqliteRewriteRulesTest.kt | 16 ++++++++++++++++ .../gradle/sqlite/SqliteRewriterTest.kt | 8 ++++++++ 4 files changed, 33 insertions(+), 7 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 0c0c67941b..c2f44c3225 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -199,7 +199,7 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - Room's `BundledSQLiteDriver` is not covered (it brings its own SQLite). - requery's native library is built without ICU: there is no `UNICODE` collator (a `COLLATE UNICODE` string - constant fails the build, see above; the clause is found through whitespace, SQL comments and a quoted name, and + constant fails the build, see above; the clause is found through whitespace, SQL comments and a quoted name, which needs no space after `COLLATE`, and `UNICODE_CI` is a different collation and passes) and `LOCALIZED` compares bytes (a warning). - Four rare false positives of the checks, each rejected on purpose rather than proven safe: - a custom `CursorFactory` that returns a non-requery cursor, then a cast to an Android cursor class, is rejected diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index 00f9663f9d..7d61aff8b3 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -36,15 +36,17 @@ internal object SqliteRewriteRules { /** * A COLLATE clause names its collation after whitespace or a SQL comment, bare or quoted ("x", 'x', [x], `x`). - * A bare name keeps a word boundary; a quoted or bracketed name must be followed at once by its closing - * character. Both keep a custom collation such as UNICODE_CI or "UNICODE-CI" out. + * A quoted or bracketed name needs no separator: the quote starts a new token (`COLLATE"x"`). A bare name keeps + * a separator and a word boundary, so `COLLATEUNICODE` and UNICODE_CI stay out; a quoted name must be followed + * at once by its closing character, which keeps "UNICODE-CI" out. */ - private fun collateRule(name: String) = - Regex( - "COLLATE(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))+" + - "(?:$name\\b|\"$name\"|'$name'|\\[$name]|`$name`)", + private fun collateRule(name: String): Regex { + val quoted = "\"$name\"|'$name'|\\[$name]|`$name`" + return Regex( + "COLLATE(?:(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))+(?:$name\\b|$quoted)|$quoted)", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL), ) + } val COLLATE_UNICODE = collateRule("UNICODE") val COLLATE_LOCALIZED = collateRule("LOCALIZED") diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt index 92266fb4cc..16a8a7c57b 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -71,4 +71,20 @@ class SqliteRewriteRulesTest { "mWindowLandroid/database/CursorWindow;", ) } + + private val collations = + mapOf("UNICODE" to SqliteRewriteRules.COLLATE_UNICODE, "LOCALIZED" to SqliteRewriteRules.COLLATE_LOCALIZED) + + @Test + fun `COLLATE accepts a quoted or bracketed name right after the keyword, a bare name needs a separator`() { + for ((name, rule) in collations) { + val quoted = listOf("COLLATE\"$name\"", "COLLATE'$name'", "COLLATE[$name]", "COLLATE`$name`", "collate\"${name.lowercase()}\"") + for (form in quoted) { + assertWithMessage(form).that(rule.containsMatchIn("SELECT 'a' $form")).isTrue() + } + for (form in listOf("COLLATE$name", "COLLATE$name x", "COLLATE\"$name-CI\"", "COLLATE'${name}_CI'", "COLLATE[$name-CI]")) { + assertWithMessage(form).that(rule.containsMatchIn("SELECT 'a' $form")).isFalse() + } + } + } } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 2664e384a9..b890488666 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1223,6 +1223,10 @@ class SqliteRewriterTest { "COLLATE 'UNICODE'", "COLLATE [UNICODE]", "COLLATE `UNICODE`", + "COLLATE\\\"UNICODE\\\"", + "COLLATE'UNICODE'", + "COLLATE[UNICODE]", + "COLLATE`UNICODE`", ) for (form in forms) { val classes = @@ -1262,6 +1266,10 @@ class SqliteRewriterTest { "COLLATE 'LOCALIZED'", "COLLATE [LOCALIZED]", "COLLATE `LOCALIZED`", + "COLLATE\\\"LOCALIZED\\\"", + "COLLATE'LOCALIZED'", + "COLLATE[LOCALIZED]", + "COLLATE`LOCALIZED`", ) for (form in forms) { val classes = From 650d1fc238d89af636cee453711a38f64ad60681 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 23:03:13 -0800 Subject: [PATCH 173/203] ADFA-7138 COLLATE rule: a block comment ends at its first star-slash The comment token `/\*.*?\*/` with DOT_MATCHES_ALL can backtrack past the first `*/`, so `SELECT 'a' COLLATE /* first */ NOCASE /* second */ UNICODE` matched through the second comment and failed the build, although NOCASE is the collation and UNICODE a column alias. Checked with the SQLite 3.46.1 that Python here links: that statement runs and returns the row, with UNICODE read as an alias. The token is now `/\*(?:[^*]|\*(?!/))*\*/`, which cannot contain `*/`. DOT_MATCHES_ALL is dropped: no `.` is left in the pattern. Same pattern for UNICODE and LOCALIZED. Tests (SqliteRewriteRulesTest, both names): the statement above does not match, nor does a lone `COLLATE /* c */ NOCASE`; `COLLATE /* c */ NAME`, `COLLATE/*c*/NAME`, two comments in a row, a comment holding a lone `*`, and a `--` line comment before the name still match. Revert proof: with only SqliteRewriteRules.kt reverted, the new test fails with `UNICODE\nexpected to be false`; with the fix, 79 tests in the three sqlite rewrite classes pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/gradle/sqlite/SqliteRewriteRules.kt | 7 ++++--- .../gradle/sqlite/SqliteRewriteRulesTest.kt | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index 7d61aff8b3..7e2b2e9d39 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -38,13 +38,14 @@ internal object SqliteRewriteRules { * A COLLATE clause names its collation after whitespace or a SQL comment, bare or quoted ("x", 'x', [x], `x`). * A quoted or bracketed name needs no separator: the quote starts a new token (`COLLATE"x"`). A bare name keeps * a separator and a word boundary, so `COLLATEUNICODE` and UNICODE_CI stay out; a quoted name must be followed - * at once by its closing character, which keeps "UNICODE-CI" out. + * at once by its closing character, which keeps "UNICODE-CI" out. A block comment ends at its first star-slash + * (a lazy dot could run on to a later one and reach a UNICODE that follows another collation). */ private fun collateRule(name: String): Regex { val quoted = "\"$name\"|'$name'|\\[$name]|`$name`" return Regex( - "COLLATE(?:(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))+(?:$name\\b|$quoted)|$quoted)", - setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL), + "COLLATE(?:(?:\\s|/\\*(?:[^*]|\\*(?!/))*\\*/|--[^\\n]*(?:\\n|$))+(?:$name\\b|$quoted)|$quoted)", + setOf(RegexOption.IGNORE_CASE), ) } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt index 16a8a7c57b..9fdfef6032 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -87,4 +87,18 @@ class SqliteRewriteRulesTest { } } } + + @Test + fun `a block comment ends at its first star-slash`() { + for ((name, rule) in collations) { + // NOCASE is the collation, the name after the second comment is a column alias + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE /* first */ NOCASE /* second */ $name")).isFalse() + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE /* c */ $name")).isTrue() + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE/*c*/$name")).isTrue() + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE /* a */ /* b */ $name")).isTrue() + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE /* a * b */ $name")).isTrue() + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE -- c\n $name")).isTrue() + assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE /* c */ NOCASE")).isFalse() + } + } } From 1651a0c3bcab3c3b05a84c4683584f181d0a4e0a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 23:06:04 -0800 Subject: [PATCH 174/203] ADFA-7138 COLLATE LOCALIZED warning: say what happens to existing indexes The warning said only that LOCALIZED sorts by bytes. After an existing database switches engines (the opt-in turned on or off over existing data), an index on a LOCALIZED column keeps the order the other engine gave it, and a lookup that searches it with the new engine's comparator can miss rows. The warning and the doc now say so, and tell the user to run REINDEX LOCALIZED under the new engine before relying on the indexes (also when turning the opt-in off), or to start from an empty database. A new Known limits entry in sqlite-rewrite.md holds the details. What was checked, and what was not: - Android: AOSP android-15.0.0_r1 SQLiteConnection.setLocaleFromConfiguration registers the collators, returns early when the locale in android_metadata equals the configured one, and otherwise runs REINDEX LOCALIZED. android/sqlite3_android.cpp registers LOCALIZED from ucol_open(locale) at primary strength (ICU). - requery 3.49.0 (the AAR in the Gradle cache, javap -c -p): its SQLiteConnection has the same method with the same early return and the same REINDEX LOCALIZED. - Not checked: that requery's LOCALIZED collator compares bytes (the existing claim, kept as it was), and the missed-rows outcome itself (reasoned from the two code paths, not run on a device). The doc marks both. - The build sees only SQL in string constants, so a schema from a prepackaged database file gets no warning; the doc says so. Test: the COLLATE LOCALIZED warning test now also asserts the REINDEX LOCALIZED, missed-rows and empty-database text. 79 tests in the three sqlite rewrite classes pass. The subprojects/sqlite-debugger README and the "Turning it on" section were not touched. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 13 ++++++++++++- .../androidide/gradle/sqlite/SqliteRewriter.kt | 6 +++++- .../androidide/gradle/sqlite/SqliteRewriterTest.kt | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index c2f44c3225..8fdc80f798 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -92,7 +92,7 @@ file that defines the property decides). Commenting the line out can expose anot A cast guarded by `instanceof` of the same type on the same local (`if (c instanceof X) ((X) c)`, `&&`, `?:`, or an early return when it is false) is not reported when the guard holds on every path to the cast: in `if (b || c instanceof X) ((X) c)` the cast is reached with `b` alone, so it is reported. `COLLATE LOCALIZED` only logs a warning: it works, but - compares bytes (no ICU) instead of sorting by locale. All violations of a class are reported together, with + compares bytes (no ICU) instead of sorting by locale, and it warns about existing indexes (see Known limits). All violations of a class are reported together, with the way out for a library class, which the user cannot change: set `cogo.sqliteDebugger=false` in the file that defines it, or in one read earlier. A platform method outside the renamed set whose descriptor mentions a renamed class (found with javap over android.jar: the other `DatabaseUtils` methods `blobFileDescriptorForQuery` and `bindObjectToProgram`, `DatabaseUtils$InsertHelper`, `OpenParams` @@ -201,6 +201,17 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - requery's native library is built without ICU: there is no `UNICODE` collator (a `COLLATE UNICODE` string constant fails the build, see above; the clause is found through whitespace, SQL comments and a quoted name, which needs no space after `COLLATE`, and `UNICODE_CI` is a different collation and passes) and `LOCALIZED` compares bytes (a warning). +- Existing `LOCALIZED` indexes after an engine switch. Android builds a `LOCALIZED` index with ICU's collator for the + device locale (AOSP android-15.0.0_r1, `register_localized_collators`: `ucol_open`, primary strength); requery's + collator compares bytes (not re-checked here: the claim above is from the earlier review). Both engines' + `SQLiteConnection.setLocaleFromConfiguration` (AOSP android-15.0.0_r1 and requery 3.49.0, read with javap) run + `REINDEX LOCALIZED` only when the locale in `android_metadata` differs from the configured one, and return + early when it matches. So when the opt-in is turned on or off over an existing database and the device locale has not changed, + the indexes keep the other engine's order. Searching one with a comparator that does not match its order can miss + rows (reasoned from that code, not run on a device). Run `REINDEX LOCALIZED` on the database under the new engine + before relying on those indexes (this applies when turning the opt-in off again as well), or start from an empty + database; if neither is possible, do not switch engines on that database. The build warns at each + `COLLATE LOCALIZED` string constant; a schema that comes from elsewhere (a prepackaged database file) is not seen. - Four rare false positives of the checks, each rejected on purpose rather than proven safe: - a custom `CursorFactory` that returns a non-requery cursor, then a cast to an Android cursor class, is rejected (the cast check follows the static type from a renamed owner, and the taint passes through every `CHECKCAST`, so a cast through `Cursor` does not avoid it; diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index c9c9d8f94f..3ee98b54cc 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -518,7 +518,11 @@ object SqliteRewriter { if (Rules.COLLATE_LOCALIZED.containsMatchIn(text)) { warn( "${site(m, line)}: COLLATE LOCALIZED works in requery's SQLite but sorts by " + - "byte value (no ICU), not by the device locale", + "byte value (no ICU), not by the device locale. An index on a LOCALIZED column that the other engine " + + "built is ordered by that engine's comparator, and both engines rebuild such indexes only when the " + + "locale in android_metadata changes, so on an existing database an indexed lookup can miss rows. " + + "After the opt-in is turned on or off over existing data, run REINDEX LOCALIZED before relying on " + + "the indexes, or start from an empty database", ) } // A warning, not a failure: the string may only be printed. Strings are not rewritten, so a class loaded by diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index b890488666..81e9235cd0 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1318,6 +1318,9 @@ class SqliteRewriterTest { assertThat(warnings.single()).contains("p.Sorted.q") assertThat(warnings.single()).contains("line ") assertThat(warnings.single()).contains("byte") + assertThat(warnings.single()).contains("REINDEX LOCALIZED") + assertThat(warnings.single()).contains("indexed lookup can miss rows") + assertThat(warnings.single()).contains("start from an empty database") } @Test From 0a7a0b2a83a093587181eb6f917c50506b276fa2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 23:09:31 -0800 Subject: [PATCH 175/203] ADFA-7138 Runtime openOrCreateDatabase: throw for world-access modes like Android The runtime's openOrCreateDatabase ignored the mode's MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE bits. Android's ContextImpl.checkMode (AOSP android-15.0.0_r1) throws SecurityException("MODE_WORLD_READABLE no longer supported") or ("MODE_WORLD_WRITEABLE no longer supported") for them when the app targets API 24 or later (the method exists from Android 7), before getDatabasePath, so an app that relied on that exception opened the database after the rewrite. The 5-argument helper (the 4-argument one delegates to it) now checks, before getDatabasePath, Build.VERSION.SDK_INT >= 24 and the context's targetSdkVersion >= 24, and throws the same exceptions in the same order (readable first). MODE_PRIVATE and the WAL flag still open. An app that targets an older API still gets no exception, and the world-readable file Android would make for it is not made (same as before, now stated in the Javadoc and the doc's known-limits entry). Sweep of the other Context database methods: in AOSP's ContextImpl, deleteDatabase, getDatabasePath and databaseList have no checkMode (read in the source); the rewrite redirects only openOrCreateDatabase (two descriptors) and deleteDatabase, so nothing else needed the check. The other checkMode sites (SharedPreferences, openFileOutput, getDir) are not database methods. Tests (SqliteRewriteRuntimeTest, on the JVM with fake Context, ApplicationInfo and Build.VERSION): both overloads throw the right message for each bit, both bits, and a bit plus WAL, and getDatabasePath is not called; MODE_PRIVATE, WAL, a target below 24 and a device below 24 reach android.jar's SQLiteDatabase stub ("Stub!") after one getDatabasePath call. Revert proof: with only the runtime fix reverted, the first test fails with "mode 1, handler false expected instance of: java.lang.SecurityException but was instance of : java.lang.RuntimeException ... Stub!"; with the fix, 81 tests in the three sqlite rewrite classes pass. Not run on a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 8 +- .../gradle/sqlite/SqliteRewriteRuntimeTest.kt | 127 +++++++++++++++++- .../sqliterewrite/SqliteRewriteRuntime.java | 19 ++- 3 files changed, 151 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 8fdc80f798..dfe2406833 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -273,7 +273,13 @@ dependency, and runs the script on both APKs. The release must pass. The debug A of the four false positives above). - Compile-time constants are copied into callers, so uses of `NO_LOCALIZED_COLLATORS`, `JOURNAL_MODE_*` or `SYNC_MODE_*` are not visible to the fail rule. `NO_LOCALIZED_COLLATORS` is dropped by the flag translation. -- The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied. +- The file permission bits of the `mode` of `Context.openOrCreateDatabase` are not applied (Android sets 0660 with a + hidden API; requery's file gets whatever its open gives, not checked). The world-access bits are checked, as Android's + `ContextImpl.checkMode` does (AOSP android-15.0.0_r1): on Android 7 or later, an app that targets API 24 or later + gets `SecurityException("MODE_WORLD_READABLE no longer supported")` or `("MODE_WORLD_WRITEABLE no longer supported")` + before the path is resolved, from either overload. An app that targets an older API gets no exception, and no + world-readable or world-writable file either (Android would make one). `deleteDatabase` has no such check in + Android's `ContextImpl`, so the redirected one has none, and `getDatabasePath` and `databaseList` are not redirected. - The declaration of an override of a member requery lacks, in a direct subclass of `SQLiteQueryBuilder` or `SQLiteCursor`, is not reported by itself: the rules check calls and field accesses, not declarations. The exceptions are the `SQLiteQueryBuilder.query` override with a `CancellationSignal` and the `Context` database methods, which fail (see above). diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt index 0c77fd91c1..5d4a77a7a7 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRuntimeTest.kt @@ -10,7 +10,8 @@ import java.lang.reflect.InvocationTargetException /** * The runtime helper's functions that need no device, run on the JVM from its bytecode compiled against android.jar, - * with Android's CancellationSignal replaced by a copy of its listener logic (android.jar's methods only throw). + * with Android's CancellationSignal replaced by a copy of its listener logic (android.jar's methods only throw), and + * Context, ApplicationInfo and Build.VERSION replaced by fakes that hold what the checks read. */ class SqliteRewriteRuntimeTest { private val loader: ClassLoader by lazy { @@ -25,6 +26,9 @@ class SqliteRewriteRuntimeTest { listOf( JavaSource("org.appdevforall.sqliterewrite.SqliteRewriteRuntime", source), JavaSource("android.os.CancellationSignal", ANDROID_SIGNAL), + JavaSource("android.content.Context", FAKE_CONTEXT), + JavaSource("android.content.pm.ApplicationInfo", FAKE_APPLICATION_INFO), + JavaSource("android.os.Build", FAKE_BUILD), ), listOf(TestJars.androidJar, TestJars.androidxCoreJar), ) @@ -170,6 +174,103 @@ class SqliteRewriteRuntimeTest { assertWithMessage("a query converted after the forwarder was collected").that(isCanceled(converted)).isTrue() } + private val worldReadable = 1 + private val worldWriteable = 2 + private val enableWal = 8 + + private fun fakeContext(targetSdk: Int): Any { + val context = loader.loadClass("android.content.Context").getConstructor().newInstance() + val info = loader.loadClass("android.content.pm.ApplicationInfo").getConstructor().newInstance() + info.javaClass.getField("targetSdkVersion").setInt(info, targetSdk) + context.javaClass.getField("info").set(context, info) + context.javaClass.getField("dbPath").set(context, java.io.File(System.getProperty("java.io.tmpdir"), "rewrite-runtime-test.db")) + return context + } + + private fun pathCalls(context: Any) = context.javaClass.getField("pathCalls").getInt(context) + + /** Calls the helper's 4-argument or 5-argument openOrCreateDatabase on a device whose API level is [sdk]. */ + private fun openOrCreate( + context: Any, + mode: Int, + sdk: Int = 34, + withHandler: Boolean = false, + ) { + val versionClass = loader.loadClass("android.os.Build\$VERSION") + val sdkField = versionClass.getField("SDK_INT") + val saved = sdkField.getInt(null) + sdkField.setInt(null, sdk) + try { + val contextClass = loader.loadClass("android.content.Context") + val factory = loader.loadClass("android.database.sqlite.SQLiteDatabase\$CursorFactory") + if (withHandler) { + runtime + .getMethod( + "openOrCreateDatabase", + contextClass, + String::class.java, + Int::class.javaPrimitiveType, + factory, + loader.loadClass("android.database.DatabaseErrorHandler"), + ).invoke(null, context, "x.db", mode, null, null) + } else { + runtime + .getMethod("openOrCreateDatabase", contextClass, String::class.java, Int::class.javaPrimitiveType, factory) + .invoke(null, context, "x.db", mode, null) + } + } finally { + sdkField.setInt(null, saved) + } + } + + /** The failure of the call, unwrapped. Past the checks the call reaches android.jar's SQLiteDatabase, whose stub throws "Stub!". */ + private fun failureOf(block: () -> Unit): Throwable? = + try { + block() + null + } catch (e: InvocationTargetException) { + e.cause + } + + @Test + fun `a world-access mode throws SecurityException before the path is resolved when the app targets API 24 or later`() { + for (withHandler in listOf(false, true)) { + for ((mode, message) in listOf( + worldReadable to "MODE_WORLD_READABLE no longer supported", + worldWriteable to "MODE_WORLD_WRITEABLE no longer supported", + (worldReadable or worldWriteable) to "MODE_WORLD_READABLE no longer supported", + (worldWriteable or enableWal) to "MODE_WORLD_WRITEABLE no longer supported", + )) { + val context = fakeContext(targetSdk = 24) + val failure = failureOf { openOrCreate(context, mode, withHandler = withHandler) } + assertWithMessage("mode $mode, handler $withHandler").that(failure).isInstanceOf(SecurityException::class.java) + assertThat(failure).hasMessageThat().isEqualTo(message) + assertWithMessage("getDatabasePath calls").that(pathCalls(context)).isEqualTo(0) + } + } + } + + @Test + fun `MODE_PRIVATE and the WAL flag still open, and an app that targets an older API or a device before API 24 gets no exception`() { + val cases = + listOf( + Triple(0, 34, 30), + Triple(enableWal, 34, 30), + Triple(worldReadable or worldWriteable, 34, 23), + Triple(worldReadable, 23, 30), + Triple(worldWriteable, 23, 30), + ) + for ((mode, sdk, target) in cases) { + val context = fakeContext(targetSdk = target) + val failure = failureOf { openOrCreate(context, mode, sdk = sdk) } + // past the checks the call reaches android.jar's stub + assertWithMessage("mode $mode, device API $sdk, target $target").that(failure).isInstanceOf(RuntimeException::class.java) + assertWithMessage("mode $mode, device API $sdk, target $target").that(failure).isNotInstanceOf(SecurityException::class.java) + assertThat(failure).hasMessageThat().isEqualTo("Stub!") + assertWithMessage("getDatabasePath calls").that(pathCalls(context)).isEqualTo(1) + } + } + private companion object { /** Android's listener rules: one listener, a new one runs at once on a cancelled signal, the same one does not. */ val ANDROID_SIGNAL = @@ -199,5 +300,29 @@ class SqliteRewriteRuntimeTest { public interface OnCancelListener { void onCancel(); } } """.trimIndent() + + val FAKE_CONTEXT = + """ + package android.content; + public class Context { + public android.content.pm.ApplicationInfo info; + public java.io.File dbPath; + public int pathCalls; + public android.content.pm.ApplicationInfo getApplicationInfo() { return info; } + public java.io.File getDatabasePath(String name) { pathCalls++; return dbPath; } + } + """.trimIndent() + + val FAKE_APPLICATION_INFO = + """ + package android.content.pm; + public class ApplicationInfo { public int targetSdkVersion; } + """.trimIndent() + + val FAKE_BUILD = + """ + package android.os; + public class Build { public static class VERSION { public static int SDK_INT = 34; } } + """.trimIndent() } } diff --git a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java index c1227a53b0..92f60c7d93 100644 --- a/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java +++ b/subprojects/sqlite-rewrite-runtime/src/main/java/org/appdevforall/sqliterewrite/SqliteRewriteRuntime.java @@ -4,6 +4,7 @@ import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; +import android.os.Build; import android.os.CancellationSignal; import android.text.TextUtils; @@ -45,7 +46,10 @@ public final class SqliteRewriteRuntime { private static final int REQUERY_OPEN_CREATE = 4; private static final int REQUERY_ENABLE_WRITE_AHEAD_LOGGING = 0x20000000; + private static final int CONTEXT_MODE_WORLD_READABLE = 0x1; + private static final int CONTEXT_MODE_WORLD_WRITEABLE = 0x2; private static final int CONTEXT_MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x8; + private static final int ANDROID_N = 24; /** * The listener each Android signal forwards cancellation through. Weak keys, so a signal the app dropped goes, and weak values: a WeakHashMap keeps the value of a cleared key until a later call on the map, so a strong value kept a dropped signal's forwarder alive until the next conversion. The signal's own listener field keeps its forwarder alive while the signal lives. @@ -95,10 +99,11 @@ public static SQLiteDatabase openOrCreateDatabase(Context context, String name, } /** - * Context.openOrCreateDatabase without the file permission bits of {@code mode}: Android applies them with a hidden API, and the modes other than private were deprecated in API 17. + * Context.openOrCreateDatabase without the file permission bits of {@code mode}: Android applies them with a hidden API, and the modes other than private were deprecated in API 17. The world-access bits are checked first, as ContextImpl.checkMode does (AOSP android-15.0.0_r1): on Android 7 or later, an app that targets API 24 or later gets a SecurityException for MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE, before the database path is resolved. An app that targets an older API gets no exception here, and Android's world-readable or world-writable file is not made either. */ public static SQLiteDatabase openOrCreateDatabase(Context context, String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { + checkMode(context, mode); int flags = ANDROID_CREATE_IF_NECESSARY; if ((mode & CONTEXT_MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) { flags |= ANDROID_ENABLE_WRITE_AHEAD_LOGGING; @@ -186,6 +191,18 @@ public static int translateOpenFlags(int androidFlags) { return flags; } + private static void checkMode(Context context, int mode) { + if (Build.VERSION.SDK_INT >= ANDROID_N + && context.getApplicationInfo().targetSdkVersion >= ANDROID_N) { + if ((mode & CONTEXT_MODE_WORLD_READABLE) != 0) { + throw new SecurityException("MODE_WORLD_READABLE no longer supported"); + } + if ((mode & CONTEXT_MODE_WORLD_WRITEABLE) != 0) { + throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported"); + } + } + } + private SqliteRewriteRuntime() {} /** From bb6194e0cc12b54946e169287bb7cfa68e1b89d9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 23:10:01 -0800 Subject: [PATCH 176/203] ADFA-7138 sqlite-rewrite.md: an inherited query(CursorFactory, Object[]) is a known limit CodeRabbit (review body on SqliteRewriter.kt:294) noted that the duplicate check before retyping a driver's query(CursorFactory, String[]) scans only the class's own methods. Read in SqliteRewriter.run and retypeParameters: when a superclass declares query(CursorFactory, Object[]), the retyped method gets the same name and descriptor and so overrides it; a non-abstract one starts with ALOAD, CHECKCAST [Ljava/lang/String;, ASTORE, so a call through the superclass type with an array whose run-time class is not String[] throws ClassCastException, where the superclass's method ran before the rewrite. An abstract method has no prologue and only becomes the override. No code change, as asked: the doc's known limits now describe the inherited case next to the same-class failure. Not run: read from the code, labelled so in the doc. Also corrected the Frames paragraph: the CHECKCAST tests the array's run-time class, so an Object[] that holds only strings throws too, not only one with a non-String element. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index dfe2406833..7b165ed68e 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -123,8 +123,8 @@ file that defines the property decides). Commenting the line out can expose anot the full frames copied from it, still say `String[]`. For each non-abstract method whose descriptor is retyped that way, the rewriter inserts `ALOAD n; CHECKCAST [Ljava/lang/String;; ASTORE n` at method entry, so the body stays valid, and writes every frame of that method in full (compressed frames are relative to the implicit first - frame, which now has the wide type). A driver that is handed an `Object[]` with an element that is not a - `String` throws `ClassCastException` on entry; requery's own drivers pass strings. + frame, which now has the wide type). A driver that is handed an array whose run-time class is not + `String[]` (an `Object[]`, even one that holds only strings) throws `ClassCastException` on entry; requery's own drivers pass strings. The mode is per variant, but `COPY_FRAMES` cannot weaken another instrumentation in the same build (Hilt, Firebase, an app's own `transformClassesWith`) that needs frames computed: `setAsmFramesComputationMode` keeps the highest mode any plugin asks for (AGP 7.3.0, 8.8.2 and 9.3.1 compare the enum ordinals; checked with javap), and @@ -221,6 +221,12 @@ dependency, and runs the script on both APKs. The release must pass. The debug A - an `instanceof` proof covers the checked local only, not a copy of it; - a call to a member requery lacks, made on a subclass that declares its own version of that member, is still rejected, because the check matches the member's name and descriptor on the call's owner class and its renamed ancestors, not the declaration it resolves to. +- An inherited `query(CursorFactory, Object[])` is not checked. The build fails when a class declares both `query` + overloads, but it looks only at the methods the class declares. If a superclass declares `query(CursorFactory, + Object[])` (a method the subclass can override), the retyped `query(CursorFactory, String[])` gets the same name and + descriptor and overrides it. A call through the superclass type then runs the driver's method (if it is not + abstract), whose entry `CHECKCAST [Ljava/lang/String;` throws `ClassCastException` unless the argument's run-time class is `String[]`, where + before the rewrite the superclass's method ran. Read from `retypeParameters` and the duplicate check, not run. - `SupportSQLiteDatabase.execPerConnectionSQL` is unsupported (see the design change): no build failure, an `UnsupportedOperationException` when called. - Passing an Android `CursorWindow` where a (renamed) `SQLiteClosable` is expected cannot work: android's From 87f30172093135dc5e3a8582de835dfd458e325a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 23:28:38 -0800 Subject: [PATCH 177/203] ADFA-7138 SQLite debugger opt-out wording: name parent projects in the read order The build failure's way out, sqlite-rewrite.md and the SQLite debugger's README listed the files that decide cogo.sqliteDebugger as the Gradle user home, the app module, then the root. Gradle's findProperty also reads each parent project between the module and the root (692634608 made Quick Build's check do the same), so the lists now name parent projects. The README's plugin-wiring line now says the opt-in and the Quick Build skip are per app module, as AndroidIDEGradlePlugin decides them. Siblings: SqliteRewriter.WAY_OUT, sqlite-rewrite.md's "Turning it on" paragraph on turning it off, the README's wiring line, and the SqliteRewriterTest assertion on the message. Wording only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 4 ++-- .../com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt | 2 +- .../com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt | 2 +- subprojects/sqlite-debugger/README.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 7b165ed68e..68385fc1c1 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -44,8 +44,8 @@ with an actionable message when the variant's runtime classpath has no The property is required because requery reaches apps only through `libs/`. Without it the rewritten classes cannot load, so the transform runs only on projects that opted in. To turn it off, set `cogo.sqliteDebugger=false` in -the file that defines it, or in one read earlier (Gradle user home, then the app module, then the root: the first -file that defines the property decides). Commenting the line out can expose another file's `true`. +the file that defines it, or in one read earlier (Gradle user home, then the app module, its parent projects, then +the root: the first file that defines the property decides). Commenting the line out can expose another file's `true`. ## Rules diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 3ee98b54cc..4a4e77c0ee 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -81,7 +81,7 @@ object SqliteRewriter { private const val WAY_OUT = "If this class is the app's, change the code above. If it is in a library, the library cannot run on " + "requery: set cogo.sqliteDebugger=false in the gradle.properties that defines it, or in one read earlier " + - "(the first file that defines it decides: Gradle user home, then the app module, then the root), " + + "(the first file that defines it decides: Gradle user home, then the app module, its parent projects, then the root), " + "to build without the SQLite debugger. Commenting the line out can expose another file's true." private val remapper = diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 81e9235cd0..caafbda9c4 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -437,7 +437,7 @@ class SqliteRewriterTest { val lastLine = e.message!!.lines().last() assertThat(lastLine).contains("in a library") assertThat(lastLine).contains("set cogo.sqliteDebugger=false in the gradle.properties that defines it, or in one read earlier") - assertThat(lastLine).contains("Gradle user home, then the app module, then the root") + assertThat(lastLine).contains("Gradle user home, then the app module, its parent projects, then the root") } @Test diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 2516671245..14d22206ef 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `engine/`: `DebugEngine` is what the server needs from the extension, `NativeDebugEngine` implements it over JNI, and `EventDecoder` turns the event buffer's bytes into `Event`s. - `mcp/`: `McpHttp` is the HTTP/1.1 listener, `McpProtocol` is JSON-RPC and the MCP session handling, `DatabaseTools` is the tools: `list_databases`, `list_connections`, `get_schema`, `query`, `explain_query_plan`, `get_stats`, `integrity_check`, `get_events`. - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. -- **Gradle plugin wiring (ADFA-7138).** An app opts in with `cogo.sqliteDebugger=true` in its `gradle.properties`; setting it to `false` in the file that defines it, or in one read earlier, turns everything off. With it, Code on the Go's Gradle plugin (`AndroidIDEGradlePlugin`) applies two plugins. `SqliteRewritePlugin` registers a class transform on every variant that moves the app's and its libraries' classes from `android.database.sqlite` to requery (see `gradle-plugin/docs/sqlite-rewrite.md`) and adds the rewrite's helper AAR (`:subprojects:sqlite-rewrite-runtime`) to every variant. `SqliteDebuggerPlugin` adds the debugger AAR and kotlin-stdlib to debuggable variants only. Code on the Go passes both AAR paths to Gradle as properties. Quick Build is not applied to an opted-in project, because its payload would compile the project's source without the rewrite. The apps' minSdk must be at least 21, the floor of requery, the helper AAR and the debugger. +- **Gradle plugin wiring (ADFA-7138).** An app opts in with `cogo.sqliteDebugger=true` in its `gradle.properties`; setting it to `false` in the file that defines it, or in one read earlier, turns everything off for that app module (Gradle decides it per app module). With it, Code on the Go's Gradle plugin (`AndroidIDEGradlePlugin`) applies two plugins. `SqliteRewritePlugin` registers a class transform on every variant that moves the app's and its libraries' classes from `android.database.sqlite` to requery (see `gradle-plugin/docs/sqlite-rewrite.md`) and adds the rewrite's helper AAR (`:subprojects:sqlite-rewrite-runtime`) to every variant. `SqliteDebuggerPlugin` adds the debugger AAR and kotlin-stdlib to debuggable variants only. Code on the Go passes both AAR paths to Gradle as properties. Quick Build is not applied to an opted-in app module, because its payload would compile the project's source without the rewrite. The apps' minSdk must be at least 21, the floor of requery, the helper AAR and the debugger. ### The event record From 4ff13a592a7ad14b306c84ece74b74818e50708a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 03:31:11 -0800 Subject: [PATCH 178/203] ADFA-7138 COLLATE check: take each comment and whitespace run whole, so long ones don't overflow the stack A SQL string constant with COLLATE followed by a block comment of about 4,096 characters or more made the COLLATE UNICODE/LOCALIZED check throw StackOverflowError, which ends the build instead of giving a diagnostic. 650d1fc23 introduced that by matching the comment body one character per loop pass, and java.util.regex recurses once per pass. A run of about 20,000 spaces or about 3,000 separate comments between COLLATE and the name overflowed both before and after 650d1fc23, because the separator loop took one whitespace character per pass. The separator is now a possessive loop over whole items: a possessive whitespace run, an atomic block comment (a lazy dot inside an atomic group, so the comment still ends at its first star-slash and is never extended to a later one), or a possessive line comment. java.util.regex loops over those instead of recursing. Nothing that follows COLLATE can start inside a separator, so giving nothing back changes no match. Checked: on JDK 17.0.19 with the default stack, a standalone check of the old, the current and the new pattern over 18 inputs: the existing short cases (quoted name with no space, COLLATEUNICODE, first star-slash, comment with a newline), a comment of 5,000 characters, a 5,000-pair body of stars, 20,000 spaces, 30 spaces before NOCASE repeated 1,000 times (no catastrophic backtracking), a 20,000-character line comment, 3,000 separate comments and an unterminated comment. The new pattern gave the expected answer in each, each in 3 ms or less. The rule's only callers are the two containsMatchIn calls in SqliteRewriter. Test: SqliteRewriteRulesTest "long comments and whitespace before the name do not overflow the stack" (100,000-character block and line comments, 50,000 star pairs, 100,000 spaces, 20,000 comments; NOCASE and an unterminated comment do not match). With the old pattern restored it fails with StackOverflowError at Pattern.java:3954. :gradle-plugin:test 279 tests (4 skipped, as before) and spotlessCheck pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriteRules.kt | 9 ++++--- .../gradle/sqlite/SqliteRewriteRulesTest.kt | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt index 7e2b2e9d39..314b74583c 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRules.kt @@ -39,13 +39,16 @@ internal object SqliteRewriteRules { * A quoted or bracketed name needs no separator: the quote starts a new token (`COLLATE"x"`). A bare name keeps * a separator and a word boundary, so `COLLATEUNICODE` and UNICODE_CI stay out; a quoted name must be followed * at once by its closing character, which keeps "UNICODE-CI" out. A block comment ends at its first star-slash - * (a lazy dot could run on to a later one and reach a UNICODE that follows another collation). + * (an atomic group: backtracking into the lazy dot could run on to a later one and reach a UNICODE that follows + * another collation). Each whitespace run and comment is taken whole and never given back, so java.util.regex + * loops instead of recursing per character; a per-character loop overflowed the stack on a comment or a run of + * spaces a few thousand characters long. */ private fun collateRule(name: String): Regex { val quoted = "\"$name\"|'$name'|\\[$name]|`$name`" return Regex( - "COLLATE(?:(?:\\s|/\\*(?:[^*]|\\*(?!/))*\\*/|--[^\\n]*(?:\\n|$))+(?:$name\\b|$quoted)|$quoted)", - setOf(RegexOption.IGNORE_CASE), + "COLLATE(?:(?:\\s++|(?>/\\*.*?\\*/)|--[^\\n]*+(?:\\n|$))++(?:$name\\b|$quoted)|$quoted)", + setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL), ) } diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt index 9fdfef6032..fc0b2640b1 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriteRulesTest.kt @@ -101,4 +101,31 @@ class SqliteRewriteRulesTest { assertWithMessage(name).that(rule.containsMatchIn("SELECT 'a' COLLATE /* c */ NOCASE")).isFalse() } } + + @Test + fun `long comments and whitespace before the name do not overflow the stack`() { + val long = "x".repeat(100_000) + for ((name, rule) in collations) { + val matches = + mapOf( + "block comment" to "SELECT 'a' COLLATE /*$long*/ $name", + "block comment of stars" to "SELECT 'a' COLLATE /*${"*a".repeat(50_000)}*/ $name", + "whitespace" to "SELECT 'a' COLLATE${" ".repeat(100_000)}$name", + "line comment" to "SELECT 'a' COLLATE --$long\n$name", + "many comments" to "SELECT 'a' COLLATE${" /**/".repeat(20_000)} $name", + ) + for ((form, sql) in matches) { + assertWithMessage("$name, $form").that(rule.containsMatchIn(sql)).isTrue() + } + val misses = + mapOf( + "block comment, then NOCASE" to "SELECT 'a' COLLATE /*$long*/ NOCASE", + "unterminated block comment" to "SELECT 'a' COLLATE /*$long $name", + "whitespace, then NOCASE" to "SELECT 'a' COLLATE${" ".repeat(100_000)}NOCASE", + ) + for ((form, sql) in misses) { + assertWithMessage("$name, $form").that(rule.containsMatchIn(sql)).isFalse() + } + } + } } From f6de53de6a8b826d959dbd76257c8f58d8e4c2ea Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 12:12:34 -0800 Subject: [PATCH 179/203] ADFA-7135 Remove separator comments from the SQLite debugger module CLAUDE.md forbids separator or decorative comments, and four of them had crept into McpHttp.kt and McpProtocolTest.kt. Deleted the four (McpHttp.kt "checks" and "reading and writing HTTP", McpProtocolTest.kt "the protocol" and "the HTTP side") with the blank line after each. Swept the module (main, test, jni, cpp, test.sh, build files) with a grep for // or /* or # followed by runs of - = * ~ _ # +: no others. Comments only, no behaviour change. Review thread 4659142375 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt | 4 ---- .../org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt | 4 ---- 2 files changed, 8 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index 7cab0bc394..1050bdda26 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -350,8 +350,6 @@ class McpHttp( return send(reply.status, reply.body, reply.headers) } - // ---------------------------------------------------------------- checks - /** 127.0.0.1 or localhost, on any port: adb forward may bring the request in from another port. */ private fun hostAllowed(host: String?): Boolean { val h = host?.trim()?.lowercase() ?: return false @@ -376,8 +374,6 @@ class McpHttp( return MessageDigest.isEqual(h.substring(7).trim().toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8)) } - // ---------------------------------------------------------------- reading and writing HTTP - /** The head of one request (no body yet), or null if the connection closed before one began. */ private fun readHead( input: InputStream, diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 47602a9639..0b727c4f20 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -69,8 +69,6 @@ class McpProtocolTest { return JSONObject(r.body!!) } - // ---------------------------------------------------------------- the protocol - @Test fun initializeAgreesVersionAndStartsSession() { val p = protocol() val r = p.post(initBody("2025-03-26"), null, null) @@ -294,8 +292,6 @@ class McpProtocolTest { assertEquals(404, p.post(request(1, "ping").toString(), s, null).status) } - // ---------------------------------------------------------------- the HTTP side - private val token = "secret-token" private var server: McpHttp? = null From 12a3bd68c638b0f49f008174ce596dbf14a4fa5d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 12:12:34 -0800 Subject: [PATCH 180/203] ADFA-7135 Say in the README that test.sh runs on Linux only test.sh does not run on macOS, and the README did not say so. Added one sentence where the README lists test.sh's tools. Read test.sh: GNU `sed -i` without a suffix (cuts the amalgamation), `sha256sum`, `readlink -f`, `include/linux` for jni.h, and `.so` outputs. Read .github/workflows/test-sqlite-debugger.yml: `runs-on: ubuntu-latest`. Docs only, nothing run. Review thread 4659142377 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 6ff6f12b02..c2bb673cf9 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -40,7 +40,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han ## Testing -- **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. +- **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. - **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp` and `DatabaseTools` (with `FakeDebugEngine`). From 212c1431498f9f149dd33d84aa15b6b82d6db421 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 12:20:14 -0800 Subject: [PATCH 181/203] ADFA-7135 Clear a connection's closing flag when a later statement runs The trace callback marks a connection closing on SQLITE_TRACE_CLOSE, but a sqlite3_close that then fails with SQLITE_BUSY leaves the connection open and the flag never cleared, so the Kotlin side treated a live database as unavailable. In SQLite 3.49.1 (the sqlite3.c test.sh builds; the AAR compiles no SQLite of its own) sqlite3Close fires the callback before the busy check: sqlite3.c:182781 if( db->mTrace & SQLITE_TRACE_CLOSE ){ sqlite3.c:182782 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); sqlite3.c:182800 if( !forceZombie && connectionIsBusy(db) ){ ... return SQLITE_BUSY; A statement or profile event on the same connection now clears `closing` (any non-close event proves the connection is open). `closing` is now accessed with relaxed __atomic ops only, so the hot path takes no lock and stays race-free under TSan; the close event no longer takes g_lock. Checked: knownPaths, runChecked (both snapshots) and listDatabases in DatabaseTools.kt all read AppConnection.closing from engine.connections(), so the path is available again once the flag clears. Accepted limit: a zombie left by sqlite3_close_v2 also reads closing 0 once a statement still pending on it runs (probed on 3.49.1) until SQLite frees it; sqlitedbg.h says so. Test: test_close_and_list in sqlitedbg_test.c leaves a statement unfinalized, sqlite3_close returns SQLITE_BUSY and the connection reads as closing; a statement on it clears closing; a second failed close sets it again. With only the fix reverted it fails: "FAIL src/test/c/sqlitedbg_test.c:484: find_conn(&l, id)->closing == 0 (1 vs 0)". test.sh passes with the fix (ASan+UBSan 13128 checks, TSan 13118, JNI 178). Review thread 4659142357 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c | 11 ++++++----- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h | 7 +++++-- .../sqlite-debugger/src/test/c/sqlitedbg_test.c | 8 ++++++++ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index c84192d81e..e61611dd2b 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -35,7 +35,7 @@ typedef struct conn_state { uint64_t id; char *path; int read_only; - int closing; + int closing; // atomic: set by the close event, cleared by a later statement event int64_t opened_at_ns; int64_t open_thread_id; } conn_state; @@ -167,6 +167,9 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { switch (type) { case SQLITE_TRACE_STMT: case SQLITE_TRACE_PROFILE: { + // SQLite fires the close event before it checks for unfinalized statements, so a close that + // then fails with SQLITE_BUSY leaves the connection open. A statement event proves it is. + if (__atomic_load_n(&cs->closing, __ATOMIC_RELAXED)) __atomic_store_n(&cs->closing, 0, __ATOMIC_RELAXED); sqlite3_stmt *stmt = (sqlite3_stmt *)p; const char *sql = NULL; char *expanded = NULL; @@ -198,9 +201,7 @@ static int trace_cb(unsigned type, void *c, void *p, void *x) { } case SQLITE_TRACE_CLOSE: // The close can still fail or leave a zombie, so only mark it: xDestroy frees. - pthread_mutex_lock(&g_lock); - cs->closing = 1; - pthread_mutex_unlock(&g_lock); + __atomic_store_n(&cs->closing, 1, __ATOMIC_RELAXED); add_event(SQLITEDBG_EVENT_CLOSE, cs->id, -1, 0, "", 0); break; } @@ -337,7 +338,7 @@ size_t sqlitedbg_each_connection(void (*fn)(void *context, const sqlitedbg_conne c.id = cs->id; c.path = cs->path; c.read_only = cs->read_only; - c.closing = cs->closing; + c.closing = __atomic_load_n(&cs->closing, __ATOMIC_RELAXED); c.opened_at_ns = cs->opened_at_ns; c.open_thread_id = cs->open_thread_id; fn(context, &c); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index c3365708ab..9190884af7 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -57,8 +57,11 @@ typedef struct sqlitedbg_connection { const char *path; // 1 if the main database is read-only (sqlite3_db_readonly). int read_only; - // 1 once the trace "close" event has fired. The close may still fail, and the app may retry - // it, so the connection stays listed until SQLite frees it. + // 1 once the trace "close" event has fired. The close may still fail (SQLITE_BUSY with an + // unfinalized statement), and the app may retry it, so the connection stays listed until SQLite + // frees it. A later statement event on the connection resets this to 0, as it shows the close + // failed. A zombie left by sqlite3_close_v2 also reads 0 once a statement still pending on it + // runs (checked in SQLite 3.49.1), until its last statement is finalized and SQLite frees it. int closing; // CLOCK_REALTIME, nanoseconds, when the extension first saw the connection. int64_t opened_at_ns; diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index d886e3378c..a408de7eef 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -478,6 +478,14 @@ static void test_close_and_list(void) { CHECK_EQ(b.events[0].sql_bytes, 0); batch_free(&b); + // the failed close left the connection open: a statement on it clears closing, a second failed close sets it + exec_ok(c, "SELECT 1"); + list_conns(&l); + CHECK_EQ(find_conn(&l, id)->closing, 0); + CHECK_EQ(sqlite3_close(c), SQLITE_BUSY); + list_conns(&l); + CHECK_EQ(find_conn(&l, id)->closing, 1); + // the app retries once the statement is gone sqlite3_finalize(st); CHECK_EQ(list_conns(&l), before + 1); From 3db82a509fd9db984dae690ccae093d95aac6477 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 12:25:47 -0800 Subject: [PATCH 182/203] ADFA-7136 Keep one pending idle check in DatabaseTools Every get_events that reconnected after the 60 s idle expiry added a TimerTask, and the task already pending rescheduled itself while the client was connected, so each expire-and-reconnect cycle left one more copy running. scheduleIdleCheck now cancels the pending check before it schedules the next, onServerStopped cancels it, and a check that was already running when it was cancelled no longer reschedules (a generation counter, read under the lock). The timer moved behind a small internal IdleScheduler (the default makes one daemon Timer per pending check and ends it on cancel), which the test replaces; the public DatabaseTools constructor is unchanged. Checked: scheduleIdleCheck has one caller (getEvents) and the timer is used nowhere else in the module; expireIdleClient behaviour is untouched. DebuggerStartup uses the public constructor. Tests (DatabaseToolsTest, fake scheduler): over three expire-and-reconnect cycles exactly one check is pending; stopping the server leaves none; a check running during the stop does not reschedule. With only the cancel call removed the first fails: "cycle 0: after the reconnect expected:<1> but was:<2>". The stop-while-running test is covered by the generation check, not by that call, so it passes on that revert; it was not proven separately. Review thread 4659142364 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseTools.kt | 72 ++++++++++++++----- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 65 +++++++++++++++++ 2 files changed, 120 insertions(+), 17 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 81bdd00716..6b678aae09 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -25,12 +25,19 @@ import java.util.TimerTask * time limit starts when the call begins, so its waits for the lock count and the server gives up * before the client does; a call that waited at least half its time limit says so in its error. */ -class DatabaseTools( +class DatabaseTools internal constructor( private val engine: DebugEngine, /** The app's database folder, to list files no connection has opened; null on the JVM. */ - private val databaseDir: File? = null, - private val clock: () -> Long = System::currentTimeMillis, + private val databaseDir: File?, + private val clock: () -> Long, + private val idleScheduler: IdleScheduler, ) { + constructor( + engine: DebugEngine, + databaseDir: File? = null, + clock: () -> Long = System::currentTimeMillis, + ) : this(engine, databaseDir, clock, TimerIdleScheduler()) + companion object { const val DEFAULT_MAX_ROWS = 100 const val MAX_ROWS = 1000 @@ -129,7 +136,8 @@ class DatabaseTools( private val serverConnections = HashMap() private var clientConnected = false private var lastEventsCallMs = 0L - private var idleTimer: Timer? = null + private var cancelIdleCheck: (() -> Unit)? = null + private var idleCheckGeneration = 0 /** A server connection and the ids of the app connections to its path when it was opened. */ private class CachedConnection( @@ -156,8 +164,7 @@ class DatabaseTools( synchronized(lock) { serverConnections.values.forEach { runCatching { it.connection.close() } } serverConnections.clear() - idleTimer?.cancel() - idleTimer = null + cancelPendingIdleCheck() if (clientConnected) { clientConnected = false engine.setClientConnected(false) @@ -179,19 +186,24 @@ class DatabaseTools( } } + /** Cancels the pending check, and a check already running no longer reschedules. [lock] held. */ + private fun cancelPendingIdleCheck() { + idleCheckGeneration++ + cancelIdleCheck?.invoke() + cancelIdleCheck = null + } + + /** At most one check is pending: each one cancels the one before it. [lock] held. */ private fun scheduleIdleCheck() { - val timer = idleTimer ?: Timer("sqlite-debugger-idle", true).also { idleTimer = it } - timer.schedule( - object : TimerTask() { - override fun run() { - expireIdleClient() - synchronized(lock) { - if (clientConnected && idleTimer === timer) scheduleIdleCheck() - } + cancelPendingIdleCheck() + val generation = idleCheckGeneration + cancelIdleCheck = + idleScheduler.schedule(EVENTS_IDLE_MS / 4) { + expireIdleClient() + synchronized(lock) { + if (clientConnected && idleCheckGeneration == generation) scheduleIdleCheck() } - }, - EVENTS_IDLE_MS / 4, - ) + } } fun tools(): List = @@ -682,3 +694,29 @@ class DatabaseTools( } } } + +/** Runs the idle check later; a test seam, the real one is [TimerIdleScheduler]. */ +internal fun interface IdleScheduler { + /** Runs [task] once after [delayMs]; the result cancels it. */ + fun schedule( + delayMs: Long, + task: Runnable, + ): () -> Unit +} + +/** One daemon timer thread per pending check, ended by its cancel. */ +private class TimerIdleScheduler : IdleScheduler { + override fun schedule( + delayMs: Long, + task: Runnable, + ): () -> Unit { + val timer = Timer("sqlite-debugger-idle", true) + timer.schedule( + object : TimerTask() { + override fun run() = task.run() + }, + delayMs, + ) + return { timer.cancel() } + } +} diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 7db3511cae..ea4c5cceae 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -813,6 +813,71 @@ class DatabaseToolsTest { t.onServerStopped() } + private class FakeIdleScheduler : IdleScheduler { + class Check( + val task: Runnable, + ) { + var done = false + } + + val checks = mutableListOf() + val pending get() = checks.filter { !it.done } + + override fun schedule( + delayMs: Long, + task: Runnable, + ): () -> Unit { + val check = Check(task) + checks += check + return { check.done = true } + } + + fun runPending() { + val check = pending.single() + check.done = true + check.task.run() + } + } + + @Test fun onlyOneIdleCheckIsPendingAcrossExpireAndReconnectCycles() { + val scheduler = FakeIdleScheduler() + val t = DatabaseTools(engine, dir, { now }, scheduler) + ok("get_events", t = t) + assertEquals(1, scheduler.pending.size) + repeat(3) { cycle -> + // the check finds the client still connected and reschedules itself + now += 15_000 + scheduler.runPending() + assertTrue(engine.clientConnected) + assertEquals("cycle $cycle: after the check rescheduled", 1, scheduler.pending.size) + // a tool call expires the client, and get_events reconnects while a check is still pending + now += 61_000 + ok("list_connections", t = t) + assertFalse(engine.clientConnected) + ok("get_events", t = t) + assertTrue(engine.clientConnected) + assertEquals("cycle $cycle: after the reconnect", 1, scheduler.pending.size) + } + now += 61_000 + scheduler.runPending() // expires the client and does not reschedule + assertFalse(engine.clientConnected) + assertEquals(0, scheduler.pending.size) + ok("get_events", t = t) + assertEquals(1, scheduler.pending.size) + t.onServerStopped() + assertEquals("stopping the server cancels the check", 0, scheduler.pending.size) + } + + @Test fun aCheckThatWasRunningWhenTheServerStoppedDoesNotReschedule() { + val scheduler = FakeIdleScheduler() + val t = DatabaseTools(engine, dir, { now }, scheduler) + ok("get_events", t = t) + val running = scheduler.pending.single() + t.onServerStopped() + running.task.run() + assertEquals(0, scheduler.pending.size) + } + @Test fun stoppingTheServerClosesServerConnections() { engine.appConnections += conn(1, "/data/a.db") val t = tools From c84d987608ec727563eeb88cd8ff696915ac819f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 12:33:30 -0800 Subject: [PATCH 183/203] ADFA-7136 List the cut cells in truncated_cell_indexes encodeValue ignored `truncated` for a String, so a TEXT cell cut at MAX_TEXT_BYTES looked complete and only the total truncated_cells hinted that something was cut. query, explain_query_plan and integrity_check now return truncated_cell_indexes beside truncated_cells: [row, column] pairs, from 0, the row relative to the rows returned (the engine's own cut set, which the JNI query path fills for TEXT and BLOB alike). Cell types are unchanged: no wrapping of strings. A cut BLOB is listed too and keeps its own truncated flag; truncated_cells is the list's size. The tool descriptions of query, explain_query_plan, integrity_check and get_schema and the README say so. The list is bounded by the 4 MiB cell budget plus the always-whole first row. Swept the other tools: get_schema keeps its per-entry truncated (the result is grouped, so a row index would not match) and its description says there is no list; get_stats returns numbers and table names and reports no cuts (a table name over 4096 bytes would be cut there; not tested). explain_query_plan and integrity_check had no truncated_cells at all; both now have it. Tests (DatabaseToolsTest): a result with two cut TEXT cells, a short one and a cut BLOB lists exactly [0,0] [0,2] [1,1], strings stay strings; no cuts gives an empty list; explain_query_plan and integrity_check list theirs; get_schema has no list; the descriptions mention it. With the three put calls removed all three behaviour tests fail with: org.json.JSONException: JSONObject["truncated_cell_indexes"] not found. Review thread 4659142361 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 36 +++++++++-- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 62 +++++++++++++++++++ 3 files changed, 94 insertions(+), 6 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index c2bb673cf9..e0967f08cd 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 6b678aae09..a525d5b72f 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -71,6 +71,12 @@ class DatabaseTools internal constructor( const val PAGING_NOTE = "Paging re-runs the query for each page, so a later page can differ if the data changed." + /** Said by the tools that return cells whose TEXT and BLOB values the server can cut. */ + private const val CUT_CELLS_NOTE = + "truncated_cells counts the cut cells and truncated_cell_indexes lists each as [row, column], both from 0 and " + + "the row relative to the rows returned; a TEXT cell has no marker of its own, and a cut BLOB is in the list too " + + "(it also has truncated true)." + /** * Said by every tool that runs a statement. The limit itself is enforced in C (SQLITEDBG_SERVER_NON_WAL_MS in * sqlitedbg.h, which says why); this text must follow it. @@ -224,7 +230,8 @@ class DatabaseTools internal constructor( "Get schema", "Returns the tables, indexes, views and triggers of a database, with their CREATE statements, from sqlite_master. " + "A CREATE statement is cut at ${MAX_SCHEMA_SQL_BYTES / 1024} KiB: its entry then has truncated true, and " + - "truncated_cells counts the cut values. The top-level truncated is true when anything was cut or entries were left " + + "truncated_cells counts the cut values (there is no truncated_cell_indexes: the entry says which). " + + "The top-level truncated is true when anything was cut or entries were left " + "out: past the first $MAX_ROWS, or past about ${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (about " + "${MAX_TOTAL_BYTES / MAX_SCHEMA_SQL_BYTES} statements of ${MAX_SCHEMA_SQL_BYTES / 1024} KiB). There is no offset: " + "to read the rest, page through sqlite_master with query (ORDER BY type, name, the order get_schema uses), " + @@ -236,7 +243,8 @@ class DatabaseTools internal constructor( "query", "Run a query", "Runs one read-only SQL statement. Returns at most max_rows rows (default $DEFAULT_MAX_ROWS, at most $MAX_ROWS); " + - "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES. A result also stops at about " + + "TEXT cells are cut at $MAX_TEXT_BYTES bytes and BLOBs at $MAX_BLOB_BYTES: $CUT_CELLS_NOTE " + + "A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + "comes back whole. Use offset to page. " + "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", @@ -251,7 +259,8 @@ class DatabaseTools internal constructor( tool( "explain_query_plan", "Explain a query plan", - "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run. $APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", + "Runs EXPLAIN QUERY PLAN on a SQL statement and returns SQLite's plan. The statement is not run. " + + "A cell cut at $MAX_TEXT_BYTES bytes is listed as in query: $CUT_CELLS_NOTE $APP_FUNCTIONS_NOTE. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters."), @@ -269,7 +278,9 @@ class DatabaseTools internal constructor( "integrity_check", "Check integrity", "Runs PRAGMA quick_check, or the slower PRAGMA integrity_check when full is true. " + - "ok is true when SQLite reports no problem. Both checks fail with \"unknown function\" when a CHECK constraint or a " + + "ok is true when SQLite reports no problem. A message cut at $MAX_TEXT_BYTES bytes is listed as in query " + + "(truncated_cells, truncated_cell_indexes: [message index, 0]). " + + "Both checks fail with \"unknown function\" when a CHECK constraint or a " + "NOT NULL virtual generated column calls a function the app adds to its own connections. A full integrity_check " + "also fails on an index on such an expression and on a partial index whose WHERE calls one; " + "quick_check does not fail on those two, so use it then. " + @@ -416,7 +427,10 @@ class DatabaseTools internal constructor( 0, QueryLimits(MAX_ROWS, MAX_TEXT_BYTES, MAX_BLOB_BYTES, MAX_TOTAL_BYTES), ) - return JSONObject().put("plan", rowsAsObjects(result)) + return JSONObject() + .put("plan", rowsAsObjects(result)) + .put("truncated_cells", result.truncatedCells) + .put("truncated_cell_indexes", truncatedCellIndexes(result)) } private fun getStats( @@ -487,6 +501,8 @@ class DatabaseTools internal constructor( .put("check", if (full) "integrity_check" else "quick_check") .put("ok", messages == listOf("ok")) .put("messages", JSONArray(messages)) + .put("truncated_cells", result.truncatedCells) + .put("truncated_cell_indexes", truncatedCellIndexes(result)) } private fun getEvents(args: JSONObject): JSONObject { @@ -539,10 +555,20 @@ class DatabaseTools internal constructor( .put("offset", encodeLong(offset)) .put("has_more", result.hasMore) .put("truncated_cells", result.truncatedCells) + .put("truncated_cell_indexes", truncatedCellIndexes(result)) if (result.hasMore) out.put("next_offset", encodeLong(offset + result.rows.size)) return out } + /** The cut cells as `[row, column]` pairs, the row relative to the rows in [result]. */ + private fun truncatedCellIndexes(result: QueryResult): JSONArray { + val out = JSONArray() + val columns = result.columns.size.toLong() + if (columns == 0L) return out + for (i in result.truncatedCellIndexes.sorted()) out.put(JSONArray().put((i / columns).toInt()).put((i % columns).toInt())) + return out + } + private fun rowsAsObjects(result: QueryResult): JSONArray { val arr = JSONArray() result.rows.forEachIndexed { r, row -> diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index ea4c5cceae..8782d5a5a0 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -576,6 +576,68 @@ class DatabaseToolsTest { assertEquals(1, r.getInt("truncated_cells")) } + private fun cutCells(r: JSONObject): List> = + r.getJSONArray("truncated_cell_indexes").let { a -> + (0 until a.length()).map { a.getJSONArray(it).let { p -> p.getInt(0) to p.getInt(1) } } + } + + @Test fun queryListsExactlyTheCutCellsTextAndBlobAlike() { + engine.appConnections += conn(1, "/data/a.db") + val cutText = "x".repeat(DatabaseTools.MAX_TEXT_BYTES) + val cutBlob = ByteArray(DatabaseTools.MAX_BLOB_BYTES) + engine.answer = { _, _, _, _ -> + QueryResult( + listOf("a", "b", "c"), + listOf(listOf(cutText, "short", cutText), listOf("short", cutBlob, 5L), listOf("short", "short", "short")), + 3, + false, + setOf(0L, 2L, 4L), + ) + } + val r = ok("query", db().put("sql", "x")) + assertEquals(listOf(0 to 0, 0 to 2, 1 to 1), cutCells(r)) + assertEquals(3, r.getInt("truncated_cells")) + val rows = r.getJSONArray("rows") + assertEquals("a TEXT cell stays a string", cutText, rows.getJSONArray(0).get(0)) + assertTrue(rows.getJSONArray(1).getJSONObject(1).getBoolean("truncated")) + } + + @Test fun queryListsNoCutCellsWhenNothingWasCut() { + engine.appConnections += conn(1, "/data/a.db") + engine.answer = { _, _, _, _ -> QueryResult(listOf("a"), listOf(listOf("x")), 0, false) } + val r = ok("query", db().put("sql", "x")) + assertEquals(0, r.getJSONArray("truncated_cell_indexes").length()) + assertEquals(0, r.getInt("truncated_cells")) + } + + @Test fun explainAndIntegrityCheckListCutCellsAndGetSchemaDoesNot() { + engine.appConnections += conn(1, "/data/a.db") + answerWith( + "EXPLAIN" to + QueryResult(listOf("id", "parent", "notused", "detail"), listOf(listOf(2L, 0L, 0L, "SCAN t")), 1, false, setOf(3L)), + "PRAGMA quick_check" to QueryResult(listOf("quick_check"), listOf(listOf("ok"), listOf("bad")), 1, false, setOf(1L)), + "SELECT type" to + QueryResult(listOf("type", "name", "tbl_name", "sql"), listOf(listOf("table", "t", "t", "CREATE")), 1, false, setOf(3L)), + ) + val plan = ok("explain_query_plan", db().put("sql", "select 1")) + assertEquals(listOf(0 to 3), cutCells(plan)) + assertEquals(1, plan.getInt("truncated_cells")) + val check = ok("integrity_check", db()) + assertEquals(listOf(1 to 0), cutCells(check)) + assertEquals(1, check.getInt("truncated_cells")) + val schema = ok("get_schema", db()) + assertFalse("each entry says whether it was cut", schema.has("truncated_cell_indexes")) + assertTrue(schema.getJSONArray("tables").getJSONObject(0).getBoolean("truncated")) + } + + @Test fun theToolDescriptionsExplainTheCutCellList() { + val byName = tools.tools().associateBy { it.name } + for (name in listOf("query", "explain_query_plan", "integrity_check", "get_schema")) { + assertTrue(name, byName.getValue(name).description.contains("truncated_cell_indexes")) + } + assertTrue(byName.getValue("query").description.contains("a cut BLOB is in the list too")) + } + @Test fun aResultStopsAtTheTotalBudgetAndPages() { engine.appConnections += conn(1, "/data/a.db") val big = "x".repeat(3 * 1024 * 1024) From 4911b948e8946ea77e861fd612e9cdc08d650654 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 12:39:28 -0800 Subject: [PATCH 184/203] ADFA-7136 Give one deadline to every tool call of a POST Each tool call of a JSON-RPC batch started its own 50 s deadline, so one POST of up to 32 slow calls could hold the tool lock for about 27 minutes (32 x 50 s), long after the client stopped waiting. The server still accepts protocol versions 2025-03-26 and 2024-11-05 (McpProtocol.VERSIONS), which allow batches. McpProtocol takes postTimeLimitMs (and a clock), fixes one deadline when post() starts and hands it to every tool call of the batch: McpTool.run now gets (args, deadlineMs), null when the protocol sets no limit, and then the tool starts its own as before. DatabaseTools.Call uses the POST's deadline; DebuggerStartup passes DatabaseTools.DEADLINE_MS. A call that starts after the deadline fails at once with the existing time-limit error, because the engine refuses to start a query past its deadline (sqlitedbg_jni.c, bridge_query: "the time limit passed before the query started"). A single call gets the same limit as before. The README, the KDoc and the NON_WAL_NOTE wording now say the limit belongs to the POST. Checked: McpTool is built only in DatabaseTools and the tests; McpProtocol only in DebuggerStartup and the tests. Accepted limits: list_databases, list_connections and get_events run no SQL and still answer after the deadline; that the client's 60 s limit is per request, so per POST, is an assumption not checked against a client. Tests: McpProtocolTest, every call of a batch sees the POST's deadline, a later POST a new one, and null without a limit. DatabaseToolsTest, with the fake clock and a fake engine whose queries take 20 s and stop at the deadline: a batch of five ends after exactly DEADLINE_MS, the late calls fail with the time-limit error and never start; a single call and a later POST keep a full deadline. With only the fix reverted (the Call uses its own clock() + DEADLINE_MS and the protocol passes null) two tests fail: "one deadline for the POST, not one per call expected:<50000> but was:<100000>" and "expected:<[6000, 6000, 6000]> but was:<[null, null, null]>"; the single-call test passes, as it pins unchanged behaviour. Review thread 4659142372 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlitedebugger/DebuggerStartup.kt | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 28 +++-- .../sqlitedebugger/mcp/McpProtocol.kt | 27 +++-- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 103 ++++++++++++++++++ .../sqlitedebugger/mcp/McpProtocolTest.kt | 42 ++++++- 6 files changed, 180 insertions(+), 24 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index e0967f08cd..a535fa355b 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,7 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). -- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. A tool call's 50 s time limit starts when the call begins, waits behind other calls included, so the server gives up before the client's 60 s limit and a timed-out query never holds the lock after the client has stopped waiting; when waiting took at least half of it, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). +- **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. The 50 s time limit belongs to the POST: `McpProtocol` sets one deadline when it starts handling a POST and passes it to every tool call of the batch, so waits behind other calls count and a batch of slow calls ends within 50 s in all, not 50 s each (32 calls would have held the lock for about 27 minutes). A call that starts after the deadline fails at once with the time-limit error (the engine refuses to start a query past its deadline); `list_databases`, `list_connections` and `get_events` run no SQL and still answer. A single call gets the same limit as before. The server therefore gives up before the client's 60 s limit, which is taken to be per request and is unchecked for a batch, so a timed-out query does not hold the lock after the client has stopped waiting; when waiting for the lock took at least half of the limit, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt index a2605df810..ab7c93a472 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/DebuggerStartup.kt @@ -52,7 +52,7 @@ class DebuggerStartup : ContentProvider() { ) { val tools = DatabaseTools(engine, databaseDir) val token = McpHttp.newToken() - val protocol = McpProtocol(tools.tools(), "1", { UUID.randomUUID().toString() }) + val protocol = McpProtocol(tools.tools(), "1", { UUID.randomUUID().toString() }, postTimeLimitMs = DatabaseTools.DEADLINE_MS) val http = McpHttp(protocol, { token }, log = { Log.w(TAG, it) }) http.start() port = http.boundPort diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index a525d5b72f..96bcd8c384 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -21,9 +21,12 @@ import java.util.TimerTask * * One lock guards the cached server connections and every query, so tool calls run one at a time: * a slow query (up to [DEADLINE_MS]) makes the others wait. That is accepted: the debugger serves - * one agent, and a connection per call would open the app's file many times over. A tool call's - * time limit starts when the call begins, so its waits for the lock count and the server gives up - * before the client does; a call that waited at least half its time limit says so in its error. + * one agent, and a connection per call would open the app's file many times over. The time limit + * belongs to the POST ([McpProtocol] passes it in): it starts when the POST is handled and is shared + * by every call of a batch, so waits for the lock count and the server gives up before the client + * does; a call that waited at least half the limit says so in its error. A call that starts after + * the limit fails at once, as the engine refuses to start a query past its deadline; the tools that + * run no SQL (list_databases, list_connections, get_events) still answer, as they are quick. */ class DatabaseTools internal constructor( private val engine: DebugEngine, @@ -55,8 +58,9 @@ class DatabaseTools internal constructor( const val MAX_TOTAL_BYTES = 4 * 1024 * 1024 /** - * A tool call's time limit, from when the call begins, waits for the lock included: below the - * client's 60 s limit, so a query never holds the lock after the client has stopped waiting. + * The time limit of a POST, from when it is handled, waits for the lock included and shared by every call + * of a batch: below the client's 60 s limit, so a query never holds the lock after the client has stopped + * waiting. A call made outside a POST that sets a limit starts its own. */ const val DEADLINE_MS = 50_000L private const val DEADLINE_SECONDS = DEADLINE_MS / 1000 @@ -83,7 +87,7 @@ class DatabaseTools internal constructor( */ const val NON_WAL_NOTE = "On a database that is not in WAL mode a statement is stopped after 1.5 s, so a long read does not block the app's " + - "own writes; use a narrower query or a LIMIT. A database in WAL mode has no such limit (the call's $DEADLINE_SECONDS s applies)." + "own writes; use a narrower query or a LIMIT. A database in WAL mode has no such limit (the $DEADLINE_SECONDS s limit applies)." /** Server connections never load what the app registers on its own connections (see the README). */ private const val APP_FUNCTIONS_NOTE = @@ -151,9 +155,11 @@ class DatabaseTools internal constructor( val appConnectionIds: Set, ) - /** One tool call: its deadline, set when it begins, and the time it has spent waiting for [lock]. */ - private inner class Call { - val deadline = clock() + DEADLINE_MS + /** One tool call: its deadline, the POST's (or its own when none was set), and the time it has spent waiting for [lock]. */ + private inner class Call( + postDeadline: Long?, + ) { + val deadline = postDeadline ?: (clock() + DEADLINE_MS) var waitedMs = 0L fun locked(block: () -> T): T { @@ -308,8 +314,8 @@ class DatabaseTools internal constructor( description: String, inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), run: (Call, JSONObject) -> JSONObject, - ) = McpTool(name, title, description, inputSchema, readOnly = true, run = { args -> - val call = Call() + ) = McpTool(name, title, description, inputSchema, readOnly = true, run = { args, deadline -> + val call = Call(deadline) call.locked { expireIdleClientLocked() } run(call, args) }) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index a8257bec02..b0d017b73f 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -6,8 +6,9 @@ import org.json.JSONTokener /** * A tool an MCP client can call. [run] gets the call's arguments (an empty object when none were - * sent) and returns what happened, as JSON; it throws [McpToolError] for a failure the client - * should read, such as "a person is needed". + * sent) and the time limit of its POST (see [McpProtocol.postTimeLimitMs]; null when there is none), + * and returns what happened, as JSON; it throws [McpToolError] for a failure the client should + * read, such as "a person is needed". */ class McpTool( val name: String, @@ -16,7 +17,7 @@ class McpTool( val inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), /** Only reports; changes nothing. Shown to clients as a hint, not relied on. */ val readOnly: Boolean = true, - val run: (JSONObject) -> JSONObject, + val run: (args: JSONObject, deadlineMs: Long?) -> JSONObject, ) { fun describe(): JSONObject = JSONObject() @@ -54,6 +55,13 @@ class McpProtocol( private val serverVersion: String, private val newSessionId: () -> String, private val maxSessions: Int = 16, + /** + * How long one POST may spend in tools, from when [post] starts. Every tool call of a batch gets the same + * deadline (start plus this, by [clock]), so a batch of slow calls cannot hold the tools past what its + * client waits for. null: no limit is set, and a tool applies its own. + */ + private val postTimeLimitMs: Long? = null, + private val clock: () -> Long = System::currentTimeMillis, ) { companion object { /** Newest first: offered when a client asks for a version this server doesn't know. */ @@ -102,6 +110,7 @@ class McpProtocol( sessionId: String?, versionHeader: String?, ): Reply { + val deadline = postTimeLimitMs?.let { clock() + it } val parsed = try { JSONTokener(body).nextValue() @@ -142,7 +151,7 @@ class McpProtocol( if (chars >= MAX_BATCH_REPLY_CHARS) { skipped(message) } else { - handle(message) + handle(message, deadline) } if (reply == null) continue // The size is counted as the reply is made, because it all stays in memory until the batch is sent. @@ -206,7 +215,10 @@ class McpProtocol( } /** One message of a POST; null when it needs no answer. */ - private fun handle(raw: Any?): JSONObject? { + private fun handle( + raw: Any?, + deadline: Long?, + ): JSONObject? { val m = raw as? JSONObject ?: return error(null, INVALID_REQUEST, "Each message must be a JSON object.") val hasId = m.has("id") val id = m.opt("id") @@ -222,7 +234,7 @@ class McpProtocol( return when (method) { "ping" -> ok(id, JSONObject()) "tools/list" -> ok(id, JSONObject().put("tools", JSONArray().also { a -> tools.forEach { a.put(it.describe()) } })) - "tools/call" -> call(id, m.opt("params")) + "tools/call" -> call(id, m.opt("params"), deadline) else -> error(id, METHOD_NOT_FOUND, "Unknown method \"$method\".") } } @@ -230,6 +242,7 @@ class McpProtocol( private fun call( id: Any, rawParams: Any?, + deadline: Long?, ): JSONObject { val params = rawParams as? JSONObject ?: return error(id, INVALID_PARAMS, "tools/call needs params, with the tool's name.") val name = params.opt("name") as? String ?: return error(id, INVALID_PARAMS, "tools/call needs the tool's name.") @@ -242,7 +255,7 @@ class McpProtocol( } val result = try { - val out = tool.run(args) + val out = tool.run(args, deadline) JSONObject().put("content", JSONArray().put(text(out.toString()))).put("structuredContent", out).put("isError", false) } catch (e: McpToolError) { JSONObject().put("content", JSONArray().put(text(e.message ?: "The tool failed."))).put("isError", true).also { r -> diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 8782d5a5a0..7cd9dd5a63 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -482,6 +482,109 @@ class DatabaseToolsTest { return result!! } + /** + * [engine] with queries that each take [runMs] of the fake clock, as the native one stops a query at its deadline + * and refuses to start one past it. [started] lists the queries that began. + */ + private fun slowQueries( + runMs: Long, + started: MutableList, + ) = object : DebugEngine by engine { + override fun openServerConnection( + path: String, + writable: Boolean, + ) = engine.openServerConnection(path, writable).let { c -> + object : ServerConnection by c { + override fun query( + sql: String, + args: List, + offset: Long, + limits: QueryLimits, + deadlineMillis: Long, + ): QueryResult { + if (now >= deadlineMillis) { + throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the time limit passed before the query started") + } + started += sql + if (now + runMs >= deadlineMillis) { + now = deadlineMillis + throw DebugEngineException(DebugEngineException.SQLITE_INTERRUPT, "the query ran past its time limit") + } + now += runMs + return c.query(sql, args, offset, limits, deadlineMillis) + } + } + } + } + + private fun post( + t: DatabaseTools, + vararg sql: String, + ): JSONArray { + val protocol = McpProtocol(t.tools(), "test", { "s" }, 4, DatabaseTools.DEADLINE_MS) { now } + val session = protocol.post(initBody(), null, null).headers[McpProtocol.SESSION_HEADER]!! + val batch = JSONArray() + sql.forEachIndexed { i, text -> + val args = db().put("sql", text) + val params = JSONObject().put("name", "query").put("arguments", args) + batch.put( + JSONObject() + .put("jsonrpc", "2.0") + .put("id", i) + .put("method", "tools/call") + .put("params", params), + ) + } + return JSONArray(protocol.post(batch.toString(), session, null).body!!) + } + + private fun initBody() = + JSONObject() + .put("jsonrpc", "2.0") + .put("id", 1) + .put("method", "initialize") + .put("params", JSONObject().put("protocolVersion", "2025-06-18")) + .toString() + + private fun resultText(reply: JSONObject) = + reply + .getJSONObject("result") + .getJSONArray("content") + .getJSONObject(0) + .getString("text") + + @Test fun aBatchOfSlowCallsEndsWithinOneDeadlineAndTheLateCallsFailAtOnce() { + engine.appConnections += conn(1, "/data/a.db") + val started = mutableListOf() + val t = DatabaseTools(slowQueries(20_000, started), dir, { now }) + val start = now + val replies = post(t, "q1", "q2", "q3", "q4", "q5") + assertEquals("one deadline for the POST, not one per call", DatabaseTools.DEADLINE_MS, now - start) + assertEquals(listOf("q1", "q2", "q3"), started) // q3 ran into the deadline; q4 and q5 never started + assertFalse(replies.getJSONObject(1).getJSONObject("result").getBoolean("isError")) + assertEquals("the query ran past its time limit", resultText(replies.getJSONObject(2))) + for (i in 3..4) { + assertTrue(replies.getJSONObject(i).getJSONObject("result").getBoolean("isError")) + assertEquals("the time limit passed before the query started", resultText(replies.getJSONObject(i))) + } + } + + @Test fun aSingleCallKeepsItsOwnFullDeadlineAndEachPostStartsANewOne() { + engine.appConnections += conn(1, "/data/a.db") + val started = mutableListOf() + val t = DatabaseTools(slowQueries(20_000, started), dir, { now }) + val start = now + assertFalse(post(t, "q1").getJSONObject(0).getJSONObject("result").getBoolean("isError")) + assertEquals(20_000, now - start) + assertFalse("a new POST has a new deadline", post(t, "q2").getJSONObject(0).getJSONObject("result").getBoolean("isError")) + assertEquals(40_000, now - start) + val slow = DatabaseTools(slowQueries(DatabaseTools.DEADLINE_MS + 1, started), dir, { now }) + val before = now + val r = post(slow, "q3").getJSONObject(0) + assertEquals("the query ran past its time limit", resultText(r)) + assertEquals(DatabaseTools.DEADLINE_MS, now - before) + } + private val answersEmpty: () -> QueryResult = { QueryResult(emptyList(), emptyList(), 0, false) } private val ranPastItsLimit: () -> QueryResult = { diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 0b727c4f20..84a4818aa5 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -17,13 +17,13 @@ import java.net.Socket */ class McpProtocolTest { private var sessionNumber = 0 - private val echo = McpTool("echo", "Echo", "Returns its arguments.") { args -> JSONObject().put("got", args) } + private val echo = McpTool("echo", "Echo", "Returns its arguments.") { args, _ -> JSONObject().put("got", args) } private val needsPerson = - McpTool("needs_person", "Needs a person", "Always says a person is needed.", readOnly = false) { _ -> + McpTool("needs_person", "Needs a person", "Always says a person is needed.", readOnly = false) { _, _ -> throw McpToolError("A person is needed: tap Allow on the sharing phone.", JSONObject().put("person_needed", true)) } - private val crashes = McpTool("crashes", "Crashes", "Throws an unexpected exception.") { _ -> throw IllegalStateException("boom") } - private val linkFails = McpTool("link_fails", "Link fails", "Throws an Error.") { _ -> throw UnsatisfiedLinkError("no library") } + private val crashes = McpTool("crashes", "Crashes", "Throws an unexpected exception.") { _, _ -> throw IllegalStateException("boom") } + private val linkFails = McpTool("link_fails", "Link fails", "Throws an Error.") { _, _ -> throw UnsatisfiedLinkError("no library") } private fun protocol(maxSessions: Int = 16) = McpProtocol(listOf(echo, needsPerson, crashes, linkFails), "test", { "s${++sessionNumber}" }, maxSessions) @@ -222,6 +222,40 @@ class McpProtocolTest { assertEquals(2, replies.getJSONObject(1).getInt("id")) } + @Test fun everyToolCallOfABatchGetsTheDeadlineOfItsPostAndANewPostGetsANewOne() { + var now = 5_000L + val seen = mutableListOf() + val slow = + McpTool("slow", "Slow", "Takes 400 ms.") { _, deadline -> + seen += deadline + now += 400 + JSONObject() + } + val p = McpProtocol(listOf(slow), "test", { "s" }, postTimeLimitMs = 1_000, clock = { now }) + val s = p.post(initBody(), null, null).headers[McpProtocol.SESSION_HEADER]!! + val callSlow = JSONObject().put("name", "slow") + val batch = JSONArray() + repeat(3) { batch.put(request(it, "tools/call", callSlow)) } + p.post(batch.toString(), s, null) + assertEquals(listOf(6_000, 6_000, 6_000), seen) + seen.clear() + p.post(request(9, "tools/call", callSlow).toString(), s, null) + assertEquals("a later POST starts its own", listOf(now - 400 + 1_000), seen) + } + + @Test fun withoutAPostTimeLimitToolsGetNoDeadline() { + val seen = mutableListOf() + val probe = + McpTool("probe", "Probe", "Records its deadline.") { _, deadline -> + seen += deadline + JSONObject() + } + val p = McpProtocol(listOf(probe), "test", { "s" }) + val s = p.post(initBody(), null, null).headers[McpProtocol.SESSION_HEADER]!! + p.post(request(1, "tools/call", JSONObject().put("name", "probe")).toString(), s, null) + assertEquals(listOf(null), seen) + } + @Test fun batchOverTheMessageLimitIsRefusedWholeAndRunsNothing() { val p = protocol() val s = session(p) From ee7fa6f36c98eca527021aa22e73d074e67b000b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 23 Nov 2026 13:02:27 -0800 Subject: [PATCH 185/203] ADFA-7136 Tell a get_events client when its cursor is from an earlier app process g_next_seq restarts at 1 in every process. After the app restarted, an agent passing its old `next` got events [] and dropped 0 when `after` was at or past the new count, and silently skipped the first `after` events when it was below. Contract now: every get_events result carries `run`, a random UUID fixed for the process (DebugEngine.runId; NativeDebugEngine makes it once per process in its companion). get_events takes an optional `run`; one that differs from the current reads from the start (as after 0) and the result has reset: true. An `after` at or past g_next_seq also resets, which catches a client that sends no run. That check lives in C, because only C knows the newest number assigned: sqlitedbg_read_events does it under g_lock and reports sqlitedbg_read_result.reset, which the JNI layer returns as a fourth long (Kotlin allocates 4) and EventBatch.reset carries. `after` equal to the newest seq is a caught-up reader and gets no reset. The struct sqlitedbg_read_result changed, so SQLITEDBG_INTERFACE_VERSION is 2. sqlitedbg_event_record is unchanged, so events.bin and events.tsv are too (test.sh checks them). Tool description, input schema and README updated. Accepted limit, in the README: a client that sends no run and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events; `after` alone cannot tell them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so addons need no change (taken from the brief; the addons code was not read). Tests: C, test_cursor_reset (after one past the newest, far past it and UINT64_MAX reset and read everything; caught up does not; the cursor the reset returned is valid). Kotlin, DatabaseToolsTest: a run mismatch, a matching run, after past the newest, the caught-up case, and a simulated restart (FakeDebugEngine.restartProcess); NativeDebugEngineTest: runId is a UUID shared by instances. Revert proof. C, with the reset block removed: "FAIL sqlitedbg_test.c:478: b.reset == 1 (0 vs 1)" and "b.count == stored (0 vs 128)" for each of the three cursors, 12 failures. Kotlin, with the run check and the reset flag removed: getEventsWithAnotherRunReadsFromTheStartAndSaysReset (assertTrue at line 950), getEventsWithACursorPastTheNewestSaysResetEvenWithoutARun (line 960) and anAgentWithACursorFromBeforeAnAppRestart... (line 975) fail with a bare AssertionError. Review thread 4659142347 (Daniel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 1 + .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 9 ++- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 10 ++- .../src/main/cpp/sqlitedbg_jni.c | 4 +- .../sqlitedebugger/engine/DebugEngine.kt | 13 ++- .../sqlitedebugger/engine/NativeBridge.kt | 2 +- .../engine/NativeDebugEngine.kt | 16 +++- .../sqlitedebugger/mcp/DatabaseTools.kt | 33 ++++++-- .../src/test/c/sqlitedbg_test.c | 42 +++++++++- .../sqlitedebugger/engine/FakeDebugEngine.kt | 12 +++ .../engine/NativeDebugEngineTest.kt | 13 +++ .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 81 +++++++++++++++++++ 12 files changed, 220 insertions(+), 16 deletions(-) create mode 100644 subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngineTest.kt diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index a535fa355b..f7fafa37eb 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -36,6 +36,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). +- **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` is 2 for the changed struct), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. - **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. The 50 s time limit belongs to the POST: `McpProtocol` sets one deadline when it starts handling a POST and passes it to every tool call of the batch, so waits behind other calls count and a batch of slow calls ends within 50 s in all, not 50 s each (32 calls would have held the lock for about 27 minutes). A call that starts after the deadline fails at once with the time-limit error (the engine refuses to start a query past its deadline); `list_databases`, `list_connections` and `get_events` run no SQL and still answer. A single call gets the same limit as before. The server therefore gives up before the client's 60 s limit, which is taken to be per request and is unchecked for a batch, so a timed-out query does not hold the lock after the client has stopped waiting; when waiting for the lock took at least half of the limit, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index e61611dd2b..d55c47afac 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -349,11 +349,18 @@ size_t sqlitedbg_each_connection(void (*fn)(void *context, const sqlitedbg_conne } void sqlitedbg_read_events(uint64_t after, void *out, size_t out_bytes, sqlitedbg_read_result *result) { - result->next = after; result->dropped = 0; result->bytes = 0; result->count = 0; + result->reset = 0; pthread_mutex_lock(&g_lock); + // seq restarts at 1 in every process, so a cursor at or past the next seq to be assigned comes from an + // earlier process (or is made up): read from the start, and say so. + if (after >= g_next_seq) { + result->reset = 1; + after = 0; + } + result->next = after; if (g_ring) { uint64_t oldest = oldest_seq(); if (oldest > after && oldest - after > 1) { diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 9190884af7..164e5df8cb 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -23,7 +23,7 @@ extern "C" { #endif // The interface version. Raise it when anything below changes shape. -#define SQLITEDBG_INTERFACE_VERSION 1 +#define SQLITEDBG_INTERFACE_VERSION 2 // sqlite3_auto_extension's type. On a device the JNI layer looks it up in libsqlite3x.so with // dlsym (requery exports every sqlite3_ function); host tests pass SQLite's own. @@ -122,9 +122,15 @@ typedef struct sqlitedbg_read_result { size_t bytes; // Records written to out. size_t count; + // 1 if `after` was at or past the next seq to be assigned, which no cursor of this process can be: it + // comes from an earlier process (seq restarts at 1 in each) or was made up. The read then ran as if + // `after` were 0, and next and dropped refer to that read. 0 otherwise, including `after` equal to + // the newest seq (a reader that is caught up). + int reset; } sqlitedbg_read_result; -// Copies out the events with seq > after, oldest first, as whole records, until out is full. +// Copies out the events with seq > after, oldest first, as whole records, until out is full. An +// `after` that is not a seq this process has assigned (see sqlitedbg_read_result.reset) reads from 0. // The copy is made under the extension's lock with no SQLite call, so it never waits on a // statement. A record larger than out_bytes is never split: an out smaller than one record of // max_sql_bytes may return count 0 with events still waiting. Never fails. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 7563a3f7e3..5683a9fb56 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -156,8 +156,8 @@ static void bridge_read_events(JNIEnv *env, jclass cls, jlong after, jbyteArray sqlitedbg_read_events((uint64_t)after, tmp, (size_t)cap, &r); (*env)->SetByteArrayRegion(env, buf, 0, (jsize)r.bytes, (const jbyte *)tmp); free(tmp); - jlong values[3] = {(jlong)r.next, (jlong)r.dropped, (jlong)r.bytes}; - (*env)->SetLongArrayRegion(env, out, 0, 3, values); + jlong values[4] = {(jlong)r.next, (jlong)r.dropped, (jlong)r.bytes, (jlong)r.reset}; + (*env)->SetLongArrayRegion(env, out, 0, 4, values); } static void bridge_set_client_connected(JNIEnv *env, jclass cls, jboolean connected) { diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 7dc8fa0fdb..0225492399 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -8,12 +8,21 @@ import java.io.Closeable * block briefly and must not run on the main thread. */ interface DebugEngine { + /** + * An opaque string that stays the same for the life of the app process and differs in each process + * (random, never repeated after a restart). The event numbers start again at 1 in a new process, so a + * client keeps this with its [EventBatch.next] to tell a cursor of an earlier process from one of this. + */ + val runId: String + /** The app's connections SQLite has not yet freed, oldest first. Server connections are not listed. */ fun connections(): List /** * Events with [Event.seq] greater than [after], oldest first, up to about [maxBytes] of - * native records. Pass [EventBatch.next] as [after] next time; start from 0. + * native records. Pass [EventBatch.next] as [after] next time; start from 0. An [after] at or past the + * next number to be assigned cannot be a cursor of this process: the read starts from 0 and + * [EventBatch.reset] is true. */ fun readEvents( after: Long, @@ -106,6 +115,8 @@ data class EventBatch( val next: Long, /** Events after the requested cursor that left the buffer before they were read. */ val dropped: Long, + /** The requested cursor was past every event number this process has assigned, so the read started from 0. */ + val reset: Boolean = false, ) data class QueryLimits( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index fa95abee7b..2aee5d390a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -13,7 +13,7 @@ internal object NativeBridge { @JvmStatic external fun connections(): Array - /** Fills [buf] with records after [after]; [out] gets next, dropped and the bytes written. */ + /** Fills [buf] with records after [after]; [out] (4 longs) gets next, dropped, the bytes written and reset (0 or 1). */ @JvmStatic external fun readEvents( after: Long, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index f020c2d1e7..de4217fb02 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -1,11 +1,15 @@ package org.appdevforall.sqlitedebugger.engine +import java.util.UUID + /** * [DebugEngine] over the JNI layer of libsqlitedbg.so. Needs requery's libsqlite3x.so in the process: * the extension runs inside it, on connections it opens after [install]. Call [install] before * anything else; the native state is per process, so every instance shares it. */ class NativeDebugEngine : DebugEngine { + override val runId: String get() = RUN_ID + /** * Loads requery's SQLite and the debugger's library and registers the extension. Connections * opened before this are never seen, so call it as early as the process allows. Calling it @@ -54,9 +58,14 @@ class NativeDebugEngine : DebugEngine { maxBytes: Int, ): EventBatch { val buffer = ByteArray(maxBytes.coerceIn(1, MAX_READ_BYTES)) - val out = LongArray(3) + val out = LongArray(4) NativeBridge.readEvents(after, buffer, out) - return EventBatch(events = EventDecoder.decode(buffer, out[2].toInt()), next = out[0], dropped = out[1]) + return EventBatch( + events = EventDecoder.decode(buffer, out[2].toInt()), + next = out[0], + dropped = out[1], + reset = out[3] != 0L, + ) } override fun setClientConnected(connected: Boolean) = NativeBridge.setClientConnected(connected) @@ -126,6 +135,9 @@ class NativeDebugEngine : DebugEngine { const val META_PER_CONNECTION = 5 const val MAX_READ_BYTES = 16 shl 20 + /** Random per process, as the event numbers restart at 1 in each; shared by every instance, like the native state. */ + val RUN_ID: String = UUID.randomUUID().toString() + val lock = Any() var installed = false } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 96bcd8c384..a4d48ea4e5 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -297,14 +297,23 @@ class DatabaseTools internal constructor( tool( "get_events", "Get SQL events", - "Returns the SQL the app ran, oldest first, after the cursor. Pass the returned next as after to continue; " + - "dropped counts events that left the buffer unread. The first call starts recording bound values into the SQL; " + + "Returns the SQL the app ran, oldest first, after the cursor. Pass the returned next as after and the returned run " + + "as run to continue; dropped counts events that left the buffer unread. reset true means the app restarted " + + "(run differs, or after is past the newest event), and events are read from the start. " + + "The first call starts recording bound values into the SQL; " + "that stops ${EVENTS_IDLE_MS / 1000} s after the last get_events call, so call it at least that often while watching.", JSONObject() .put("type", "object") .put("additionalProperties", false) - .put("properties", JSONObject().put("after", prop("integer", "Cursor: the next from the last call. Default 0."))) - .put("required", JSONArray()), + .put( + "properties", + JSONObject() + .put("after", prop("integer", "Cursor: the next from the last call. Default 0.")) + .put( + "run", + prop("string", "The run from the last call. If it differs from the current, the read starts from 0."), + ), + ).put("required", JSONArray()), ) { _, args -> getEvents(args) }, ) @@ -513,6 +522,13 @@ class DatabaseTools internal constructor( private fun getEvents(args: JSONObject): JSONObject { val after = intArg(args, "after", 0, 0, Long.MAX_VALUE) + val run = + when (val v = args.opt("run")) { + null, JSONObject.NULL -> null + is String -> v + else -> throw McpToolError("run must be a string.") + } + val otherRun = run != null && run != engine.runId synchronized(lock) { lastEventsCallMs = clock() if (!clientConnected) { @@ -523,7 +539,7 @@ class DatabaseTools internal constructor( } val batch = try { - engine.readEvents(after, EVENT_BATCH_BYTES) + engine.readEvents(if (otherRun) 0 else after, EVENT_BATCH_BYTES) } catch (e: DebugEngineException) { throw engineError(e) } @@ -542,7 +558,12 @@ class DatabaseTools internal constructor( .put("expanded", e.expanded), ) } - return JSONObject().put("next", encodeLong(batch.next)).put("dropped", encodeLong(batch.dropped)).put("events", events) + return JSONObject() + .put("run", engine.runId) + .put("reset", otherRun || batch.reset) + .put("next", encodeLong(batch.next)) + .put("dropped", encodeLong(batch.dropped)) + .put("events", events) } private fun encodeResult( diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index a408de7eef..5f3d6c637d 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -78,6 +78,7 @@ typedef struct batch { ev *events; size_t count; uint64_t next, dropped; + int reset; } batch; static void batch_free(batch *b) { free(b->events); } @@ -93,8 +94,9 @@ static void read_all(uint64_t after, batch *b) { b->count = r.count; b->next = r.next; b->dropped = r.dropped; + b->reset = r.reset; size_t off = 0; - uint64_t prev = after; + uint64_t prev = r.reset ? 0 : after; for (size_t i = 0; i < r.count; i++) { const sqlitedbg_event_record *rec = (const sqlitedbg_event_record *)(void *)(buf + off); CHECK(rec->record_bytes >= sizeof *rec); @@ -452,6 +454,42 @@ static void test_burst(void) { CHECK_EQ(got, 50 * 10 * 2); } +static void test_cursor_reset(void) { + exec_ok(g_main, "SELECT 1"); + batch b; + read_all(0, &b); + const uint64_t newest = b.next; + const size_t stored = b.count; + CHECK(newest > 1); + CHECK_EQ(b.reset, 0); + batch_free(&b); + + // caught up: the newest seq is a valid cursor + read_all(newest, &b); + CHECK_EQ(b.reset, 0); + CHECK_EQ(b.count, 0); + CHECK_EQ(b.next, newest); + batch_free(&b); + + // one past the newest, and far past it, cannot be a cursor of this process: read from the start + const uint64_t past[] = {newest + 1, newest + 1000, UINT64_MAX}; + for (size_t i = 0; i < sizeof past / sizeof past[0]; i++) { + read_all(past[i], &b); + CHECK_EQ(b.reset, 1); + CHECK_EQ(b.count, stored); + CHECK_EQ(b.next, newest); + CHECK_EQ(b.dropped + b.count, newest); + batch_free(&b); + } + + // the first event made after a reset is read normally by the cursor the reset gave + exec_ok(g_main, "SELECT 2"); + read_all(newest, &b); + CHECK_EQ(b.reset, 0); + CHECK_EQ(b.count, 2); + batch_free(&b); +} + static void test_close_and_list(void) { listing l; size_t before = list_conns(&l); @@ -1040,6 +1078,8 @@ int main(int argc, char **argv) { test_truncation(); printf("# burst\n"); test_burst(); + printf("# cursor reset\n"); + test_cursor_reset(); printf("# close and list\n"); test_close_and_list(); printf("# init failure\n"); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index b6d9a59484..c3a4fb80dd 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -12,6 +12,16 @@ class FakeDebugEngine( ) : DebugEngine { val appConnections = mutableListOf() + override var runId = "run-1" + private set + + /** What a new app process looks like to a client: another [runId], and the event numbers start again at 1. */ + fun restartProcess(newRunId: String) { + runId = newRunId + buffered.clear() + lastSeq = 0 + } + /** Events still in the buffer, oldest first; [lastSeq] counts every event made. */ private val buffered = ArrayDeque() private var lastSeq = 0L @@ -52,6 +62,8 @@ class FakeDebugEngine( after: Long, maxBytes: Int, ): EventBatch { + val reset = after >= lastSeq + 1 + if (reset) return readEvents(0, maxBytes).copy(reset = true) val oldest = buffered.firstOrNull()?.seq ?: (lastSeq + 1) val dropped = (oldest - 1 - after).coerceAtLeast(0) val events = mutableListOf() diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngineTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngineTest.kt new file mode 100644 index 0000000000..63059be4c6 --- /dev/null +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngineTest.kt @@ -0,0 +1,13 @@ +package org.appdevforall.sqlitedebugger.engine + +import org.junit.Assert.assertEquals +import org.junit.Test +import java.util.UUID + +class NativeDebugEngineTest { + @Test fun theRunIdIsARandomUuidSharedByEveryInstanceOfTheProcess() { + val a = NativeDebugEngine().runId + assertEquals(a, UUID.fromString(a).toString()) + assertEquals(a, NativeDebugEngine().runId) + } +} diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 7cd9dd5a63..0d8e672faf 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -921,6 +921,87 @@ class DatabaseToolsTest { assertFalse(engine.clientConnected) } + private fun seqs(r: JSONObject) = r.getJSONArray("events").let { a -> (0 until a.length()).map { a.getJSONObject(it).getLong("seq") } } + + private fun addStatements(count: Int) = repeat(count) { engine.addEvent(EventKind.STATEMENT, "select ${it + 1}") } + + @Test fun getEventsCarriesTheRunAndNoResetForACaughtUpCursor() { + addStatements(3) + val t = tools + val first = ok("get_events", t = t) + assertEquals(engine.runId, first.getString("run")) + assertFalse(first.getBoolean("reset")) + assertEquals(listOf(1L, 2L, 3L), seqs(first)) + val caughtUp = ok("get_events", JSONObject().put("after", first.getLong("next")).put("run", first.getString("run")), t) + assertFalse("after equal to the newest seq is a reader that kept up", caughtUp.getBoolean("reset")) + assertEquals(emptyList(), seqs(caughtUp)) + assertEquals(3, caughtUp.getInt("next")) + engine.addEvent(EventKind.STATEMENT, "select 4") + val more = ok("get_events", JSONObject().put("after", 3).put("run", engine.runId), t) + assertFalse(more.getBoolean("reset")) + assertEquals(listOf(4L), seqs(more)) + t.onServerStopped() + } + + @Test fun getEventsWithAnotherRunReadsFromTheStartAndSaysReset() { + addStatements(3) + val t = tools + val r = ok("get_events", JSONObject().put("after", 3).put("run", "a-run-of-an-earlier-process"), t) + assertTrue(r.getBoolean("reset")) + assertEquals("read as if after were 0", listOf(1L, 2L, 3L), seqs(r)) + assertEquals(engine.runId, r.getString("run")) + t.onServerStopped() + } + + @Test fun getEventsWithACursorPastTheNewestSaysResetEvenWithoutARun() { + addStatements(3) + val t = tools + val r = ok("get_events", JSONObject().put("after", 4), t) + assertTrue(r.getBoolean("reset")) + assertEquals(listOf(1L, 2L, 3L), seqs(r)) + assertEquals(3, r.getInt("next")) + t.onServerStopped() + } + + @Test fun anAgentWithACursorFromBeforeAnAppRestartIsToldAndReadsTheNewProcessFromTheStart() { + addStatements(5) + val t = tools + val before = ok("get_events", t = t) + val oldRun = before.getString("run") + assertEquals(5, before.getInt("next")) + engine.restartProcess("run-2") + addStatements(2) + val withRun = ok("get_events", JSONObject().put("after", 5).put("run", oldRun), t) + assertTrue(withRun.getBoolean("reset")) + assertEquals("run-2", withRun.getString("run")) + assertEquals(listOf(1L, 2L), seqs(withRun)) + val withoutRun = ok("get_events", JSONObject().put("after", 5), t) + assertTrue("past the new process's newest seq (2)", withoutRun.getBoolean("reset")) + assertEquals(listOf(1L, 2L), seqs(withoutRun)) + val next = ok("get_events", JSONObject().put("after", withRun.getLong("next")).put("run", withRun.getString("run")), t) + assertFalse("the cursor and run from the reset are valid", next.getBoolean("reset")) + assertEquals(emptyList(), seqs(next)) + t.onServerStopped() + } + + @Test fun getEventsRunMustBeAString() { + val r = runTool(tools, "get_events", JSONObject().put("run", 5)) + assertEquals("run must be a string.", errorText(r)) + } + + @Test fun getEventsDescribesRunAndReset() { + val tool = tools.tools().single { it.name == "get_events" } + assertTrue(tool.description.contains("Pass the returned next as after and the returned run as run")) + assertTrue(tool.description.contains("reset true means the app restarted")) + assertTrue( + tool + .describe() + .getJSONObject("inputSchema") + .getJSONObject("properties") + .has("run"), + ) + } + @Test fun aServerConnectionIsDroppedWhenTheAppRecreatesTheDatabase() { engine.appConnections += conn(1, "/data/a.db") val t = tools From c78cc27d78b5201a96bff68bc23a6d31273e0e6a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 13:25:38 -0800 Subject: [PATCH 186/203] ADFA-7135 Roll back an open transaction when a query fails before it starts Failure: bridge_query returned early when the deadline had already passed, when GetStringChars failed, and when prepare_one failed, all before the sqlitedbg_end_transaction backstop at its end. A transaction left open on the server connection stayed open after such a call. Fix: the three early returns now go to the `done` label, so the backstop runs. A failing rollback does not replace the original error: throw_engine returns when an exception is already pending. Checked: the other return NULL paths in bridge_query already reach `done`. Tests (JniQueryTest, Helper.autocommit = sqlite3_get_autocommit): a transaction is opened with sqlite3_exec on a writable server connection (outside the query path; the read-only authorizer refuses BEGIN there), then a syntax error, a second statement, a NUL, a missing table and a past deadline each leave it closed, and a refused rollback keeps the syntax error. The GetStringChars failure has no test (it needs an out-of-memory JVM). With only the fix reverted, 10 checks fail, first "rolled back after a failed prepare: SELEKT 1: 0 vs 1" and "rolled back after a deadline already past: 0 vs 1"; the rest follow because BEGIN then runs inside the open transaction. test.sh passes with it. CodeRabbit thread PRRT_kwDONcONtM66nRMs (F03) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../src/main/cpp/sqlitedbg_jni.c | 6 +++--- .../sqlite-debugger/src/test/jni/Helper.java | 2 ++ .../src/test/jni/JniQueryTest.java | 21 +++++++++++++++++++ .../sqlite-debugger/src/test/jni/helper.c | 7 +++++++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 5683a9fb56..01f0811efe 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -363,16 +363,16 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring if (now_ms() >= dl.at_ms) { throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); - return NULL; + goto done; } jsize sql_len = (*env)->GetStringLength(env, sql); const jchar *sql_chars = (*env)->GetStringChars(env, sql, NULL); - if (!sql_chars) return NULL; + if (!sql_chars) goto done; rc = prepare_one(db, sql_chars, sql_len, &st, &message); (*env)->ReleaseStringChars(env, sql, sql_chars); if (rc != SQLITE_OK) { throw_engine(env, rc, message ? message : sqlite3_errmsg(db)); - return NULL; + goto done; } // Every server tool runs its statements here, so this is the one place that bounds a read on a database diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java index c73cf3ad57..dcca237348 100644 --- a/subprojects/sqlite-debugger/src/test/jni/Helper.java +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -2,6 +2,8 @@ public class Helper { static native long open(String path); + static native int autocommit(long db); + static native int exec(long db, String sql); static native int close(long db); diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index b4ecec1b16..c2eb3ee7f0 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -361,6 +361,27 @@ public static void main(String[] a) throws Exception { eq(refusal(w, "SELECT 1"), null, "the next query rolls it back"); eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4246)"), 0, "the app can write again"); Helper.exec(app, "DELETE FROM t WHERE id = 4246"); + + // the backstop also runs when the query fails before it starts: a transaction opened outside the + // query path (sqlite3_exec on the handle, as above) is rolled back by each early return + String[][] early = {{"SELEKT 1", "1"}, {"SELECT 1; SELECT 2", "1"}, {"SELECT 1\0", "1"}, {"SELECT * FROM no_such_table", "1"}}; + for (String[] c : early) { + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the query path before " + c[0]); + eq(Helper.autocommit(w), 0, "it is open"); + eq(codeOf(w, c[0], new Object[0], FAR), Integer.parseInt(c[1]), "the original error is kept: " + c[0]); + eq(Helper.autocommit(w), 1, "rolled back after a failed prepare: " + c[0]); + } + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the query path before a past deadline"); + eq(codeOf(w, "SELECT 1", new Object[0], System.currentTimeMillis() - 1), 9, "a deadline already past: SQLITE_INTERRUPT"); + eq(Helper.autocommit(w), 1, "rolled back after a deadline already past"); + // a rollback that fails does not replace the original error + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the query path, rollback to be refused"); + eq(Helper.denyTransactions(w, true), 0, "an authorizer that refuses ROLLBACK, again"); + eq(refusal(w, "SELEKT 1").startsWith("1 "), true, "the syntax error, not the rollback failure, is reported"); + eq(Helper.autocommit(w), 0, "the refused rollback left it open"); + eq(Helper.denyTransactions(w, false), 0, "the authorizer cleared, again"); + eq(refusal(w, "SELECT 1"), null, "the next query rolls it back, again"); + eq(Helper.autocommit(w), 1, "closed"); NativeBridge.close(w); Helper.exec(app, "DELETE FROM t WHERE id = 4245"); diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c index 166bee1eed..35ac9df938 100644 --- a/subprojects/sqlite-debugger/src/test/jni/helper.c +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -49,3 +49,10 @@ JNIEXPORT jint JNICALL Java_Helper_busyTimeout(JNIEnv *e, jclass c, jlong db, ji (void)c; return sqlite3_busy_timeout((sqlite3 *)(intptr_t)db, ms); } + +// sqlite3_get_autocommit: 1 when no transaction is open. +JNIEXPORT jint JNICALL Java_Helper_autocommit(JNIEnv *e, jclass c, jlong db) { + (void)e; + (void)c; + return sqlite3_get_autocommit((sqlite3 *)(intptr_t)db); +} From c84ae0cab3ea982d5691a8e0c0c0c80f7e2054bb Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 13:27:04 -0800 Subject: [PATCH 187/203] ADFA-7135 Stop JNI_OnLoad at the first failed lookup or allocation Failure: JNI_OnLoad checked the class globals and the UTF-8 string together and only after that made the g_utf8_name global ref, which it never checked; a failed lookup left the next call running with a pending exception. Fix: each class lookup, the UTF-8 name and its global ref are checked in turn and return JNI_ERR at the first failure; the local ref of the name is freed. The method id lookups after them were already checked as a group. Checked: test.sh builds the library with -Wall -Wextra -Werror and the JNI test passes (205 checks, 0 failures). No test: a failing FindClass or NewGlobalRef needs a JVM that fails on demand. CodeRabbit thread PRRT_kwDONcONtM66nRMz (F05) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlite-debugger/src/main/cpp/sqlitedbg_jni.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 01f0811efe..8d19317ff2 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -518,14 +518,22 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; g_object = global_class(env, "java/lang/Object"); + if (!g_object) return JNI_ERR; g_string = global_class(env, "java/lang/String"); + if (!g_string) return JNI_ERR; g_array_list = global_class(env, "java/util/ArrayList"); + if (!g_array_list) return JNI_ERR; g_long = global_class(env, "java/lang/Long"); + if (!g_long) return JNI_ERR; g_double = global_class(env, "java/lang/Double"); + if (!g_double) return JNI_ERR; g_exception = global_class(env, EXCEPTION_CLASS); + if (!g_exception) return JNI_ERR; jstring utf8 = (*env)->NewStringUTF(env, "UTF-8"); - if (!g_object || !g_string || !g_array_list || !g_long || !g_double || !g_exception || !utf8) return JNI_ERR; + if (!utf8) return JNI_ERR; g_utf8_name = (jstring)(*env)->NewGlobalRef(env, utf8); + (*env)->DeleteLocalRef(env, utf8); + if (!g_utf8_name) return JNI_ERR; g_string_from_bytes = (*env)->GetMethodID(env, g_string, "", "([BLjava/lang/String;)V"); g_list_init = (*env)->GetMethodID(env, g_array_list, "", "()V"); From a645f21cd2f3f4e3af4f0874fc3afa8e12fdead8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 13:27:05 -0800 Subject: [PATCH 188/203] ADFA-7135 Document the setup failures of sqlitedbg_open_server The comment said only "what sqlite3_open_v2 returns". In sqlitedbg.c a failure of PRAGMA query_only, of the authorizer or of the busy timeout closes the connection (sqlite3_close_v2), sets *db to NULL and returns that code; so does a failed open itself. The comment now says so. Checked against sqlitedbg_open_server in sqlitedbg.c. Comment only, no test. CodeRabbit thread PRRT_kwDONcONtM66nRM1 (F06) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 164e5df8cb..4b342ce878 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -164,7 +164,9 @@ void sqlitedbg_set_client_connected(int connected); // The connection waits up to SQLITEDBG_SERVER_BUSY_MS for a lock the app holds (rollback-journal mode) // and then reports SQLITE_BUSY. // Returns SQLITE_MISUSE before any app connection has opened (the extension then has no SQLite -// API to call), or what sqlite3_open_v2 returns. +// API to call), or what sqlite3_open_v2 returns. A failure after the open (PRAGMA query_only, the +// authorizer or the busy timeout) closes the connection, sets *db to NULL and returns that code, as +// does a failed open: *db is non-NULL only with SQLITE_OK. int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db); // Ends a transaction left open on a server connection with ROLLBACK, which the read-only authorizer From 5540ee5c2d9106ddd7336ae6953c7881fdff3793 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 13:46:37 -0800 Subject: [PATCH 189/203] ADFA-7138 Read the SQLite debugger opt-in in Gradle's order: user home, module, root, then parents Quick Build read cogo.sqliteDebugger from the module, then each parent project, then the root. Gradle gives the root's value precedence over every parent's, so with root=false and group=true Gradle's build rewrote nothing while Quick Build refused, and with root=true and group=false the reverse: Quick Build ran on a project the plugin had moved to requery. propertyDirs now returns module, root, then parents nearest first; the user home stays first. KDoc, the provisioner's log text and KDoc, the rewriter's WAY_OUT message, sqlite-rewrite.md and the sqlite-debugger README state the new order. Checked: the main session ran Gradle 8.14.4 on a three-level project (:group:app): root false + group true gives false; root true + group false gives true; root true + group false + module false gives false; no root value + group false gives false. The user home overriding all of them is from the Gradle docs, not run. QuickBuildProjectLayout (quickbuild/core) only decides which gradle.properties files invalidate a session, not their precedence, so it needs no change. Tests: QuickBuildProjectSupportTest (order of propertyDirs, and the four Gradle cases above through isSqliteDebuggerEnabled), and QuickBuildTapSqliteDebuggerCheckTest, where "a parent's false overrides the root's true" becomes "the root's true outranks a parent's false" plus the mirror case. With the old order restored, 5 of these fail (for example "the root's true outranks a parent's false": expected: true but was : false). Review thread 4675254921 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/GradleQuickBuildProvisioner.kt | 6 +-- .../quickbuild/QuickBuildProjectSupport.kt | 16 ++++---- .../QuickBuildProjectSupportTest.kt | 40 +++++++++++++++++-- .../QuickBuildTapSqliteDebuggerCheckTest.kt | 12 +++++- gradle-plugin/docs/sqlite-rewrite.md | 8 ++-- .../gradle/sqlite/SqliteRewriter.kt | 2 +- .../gradle/sqlite/SqliteRewriterTest.kt | 2 +- subprojects/sqlite-debugger/README.md | 2 +- 8 files changed, 66 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index a304163562..01ae48bea2 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -566,7 +566,7 @@ class GradleQuickBuildProvisioner( ): ProxyAppBuildResult.Refused? { if (!isSqliteDebuggerOn(projectManager, projectRoot)) return null log.info( - "Quick Build is not provisioned: {} is true for the module it builds (Gradle user home, module, parent projects or root)", + "Quick Build is not provisioned: {} is true for the module it builds (Gradle user home, module, root or parent projects)", GradlePluginConfig.PROPERTY_SQLITE_DEBUGGER_ENABLED, ) return ProxyAppBuildResult.Refused @@ -611,8 +611,8 @@ class GradleQuickBuildProvisioner( /** * Whether `cogo.sqliteDebugger=true` is in force for the module Quick Build builds * ([quickBuildModule]), as Gradle decides it for that module: the Gradle user home, then the - * module's `gradle.properties`, then each parent project's, then the root's, the first that - * defines the property winning. Another app module's file does not count, since Gradle skips + * module's `gradle.properties`, then the root's, then each parent project's nearest first, the + * first that defines the property winning. Another app module's file does not count, since Gradle skips * Quick Build per module. Parent projects come from the project model, which lists every Gradle * project; one it lacks is taken from the module's directory layout (see * [QuickBuildProjectSupport.propertyDirs]). With no Android module there is no module to ask, diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt index 1ac9073e5c..fde414543d 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt @@ -78,16 +78,16 @@ object QuickBuildProjectSupport { /** * The directories whose `gradle.properties` Gradle's `findProperty` reads for the project at - * [modulePath], nearest first: the module's own directory, each parent project's, then the root. - * A project inherits its parent's properties, so `:group:app` sees `:group`'s file before the - * root's. + * [modulePath], in Gradle's precedence: the module's own directory, the root's, then each parent + * project's, nearest first. Gradle gives the root's value precedence over every parent's, so for + * `:group:app` the root's file comes before `:group`'s. * * A parent's directory comes from [projectDirs] (Gradle path to directory, from the project * model, which lists the projects that have no Android plugin as well). A parent the model * lacks is taken from the default layout: the module's directory walked up one level per path * segment, which is wrong for a `projectDir` that `settings.gradle` has remapped. * - * @param projectRoot the root project's directory, always last. + * @param projectRoot the root project's directory, second after the module's. * @param modulePath the module's Gradle path, such as `:group:app`. * @param moduleDir the module's own directory. */ @@ -100,12 +100,12 @@ object QuickBuildProjectSupport { val segments = modulePath.split(':').filter { it.isNotEmpty() } val dirs = LinkedHashSet() dirs += moduleDir + dirs += projectRoot var walked: File? = moduleDir for (depth in segments.size - 1 downTo 1) { walked = walked?.parentFile (projectDirs[":" + segments.take(depth).joinToString(":")] ?: walked)?.let(dirs::add) } - dirs += projectRoot return dirs.toList() } @@ -119,15 +119,15 @@ object QuickBuildProjectSupport { * Reads the files the Gradle plugin's `findProperty` sees for that module in Code on the Go's * builds, and the first one that defines the property decides: the Gradle user home * `gradle.properties` (`GRADLE_USER_HOME`, which overrides the project files), then [projectDirs] - * in order (see [propertyDirs]: the module, its parent projects, the root). Gradle loads a + * in order (see [propertyDirs]: the module, the root, then its parent projects). Gradle loads a * `gradle.properties` from every project directory into that project, and a subproject also - * inherits its parent's properties. `-P` arguments are not read: Code on the Go passes none for + * inherits its parents' properties, the root's before any other parent's. `-P` arguments are not read: Code on the Go passes none for * this property. * * A file that cannot be read is reported to [onReadFailure] and counts as not defining it. * * @param gradleUserHome the Gradle user home, or null when there is none. - * @param projectDirs the module's directory, its parents', and the root's, nearest first. + * @param projectDirs the module's directory, the root's, then its parents', in [propertyDirs]' order. */ fun isSqliteDebuggerEnabled( gradleUserHome: File?, diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt index 908190f170..bfb373d4bb 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt @@ -163,19 +163,53 @@ class QuickBuildProjectSupportTest { } @Test - fun `property dirs run from the module up through its parent projects to the root`() { + fun `property dirs run module, root, then parent projects nearest first`() { val root = java.io.File("/p") val dirs = QuickBuildProjectSupport.propertyDirs(root, ":group:sub:app", java.io.File("/p/group/sub/app")) assertThat(dirs) .containsExactly( java.io.File("/p/group/sub/app"), + root, java.io.File("/p/group/sub"), java.io.File("/p/group"), - root, ).inOrder() } + @Test + fun `the root's value outranks a parent project's, as Gradle resolves it`() { + val base = + java.nio.file.Files + .createTempDirectory("qb-order") + .toFile() + try { + val root = base.resolve("root").apply { mkdirs() } + val group = root.resolve("group").apply { mkdirs() } + val module = group.resolve("app").apply { mkdirs() } + val home = base.resolve("home").apply { mkdirs() } + val dirs = QuickBuildProjectSupport.propertyDirs(root, ":group:app", module) + + root.props("cogo.sqliteDebugger=false\n") + group.props("cogo.sqliteDebugger=true\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, dirs)).isFalse() + + root.props("cogo.sqliteDebugger=true\n") + group.props("cogo.sqliteDebugger=false\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, dirs)).isTrue() + + module.props("cogo.sqliteDebugger=false\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, dirs)).isFalse() + + module.resolve("gradle.properties").delete() + root.resolve("gradle.properties").delete() + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, dirs)).isFalse() + group.props("cogo.sqliteDebugger=true\n") + assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, dirs)).isTrue() + } finally { + base.deleteRecursively() + } + } + @Test fun `a parent directory from the project model wins over the default layout`() { val root = java.io.File("/p") @@ -187,7 +221,7 @@ class QuickBuildProjectSupportTest { mapOf(":group" to java.io.File("/elsewhere/g")), ) - assertThat(dirs).containsExactly(java.io.File("/elsewhere/app"), java.io.File("/elsewhere/g"), root).inOrder() + assertThat(dirs).containsExactly(java.io.File("/elsewhere/app"), root, java.io.File("/elsewhere/g")).inOrder() } @Test diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt index 1219282ed9..7b58fd65e9 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTapSqliteDebuggerCheckTest.kt @@ -192,12 +192,22 @@ class QuickBuildTapSqliteDebuggerCheckTest { } @Test - fun `a parent's false overrides the root's true`() = + fun `the root's true outranks a parent's false, as Gradle resolves it`() = runTest { projectRoot.props("cogo.sqliteDebugger=true\n") val project = projectOf(":group:app") dir("group").props("cogo.sqliteDebugger=false\n") + assertTapAndProvisionerAgree(project, refused = true) + } + + @Test + fun `the root's false outranks a parent's true, as Gradle resolves it`() = + runTest { + projectRoot.props("cogo.sqliteDebugger=false\n") + val project = projectOf(":group:app") + dir("group").props("cogo.sqliteDebugger=true\n") + assertTapAndProvisionerAgree(project, refused = false) } diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index 68385fc1c1..bca7813b6e 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -12,8 +12,8 @@ An existing project needs: 1. `cogo.sqliteDebugger=true` in `gradle.properties`. The plugin reads it with Gradle's `findProperty` for each app module it is applied to, so Gradle decides per module: the Gradle user home's file (`GRADLE_USER_HOME`, `~/.gradle` under Code on the Go's home) first, then the module's own `gradle.properties`, - then each parent project's (`:group` for `:group:app`), then the root's; the first that defines the property - decides. Quick Build is off when the module it builds (the first app module) has the opt-in in force; another app + then the root's, then each parent project's (`:group` for `:group:app`), nearest first; the first that defines the + property decides. The root's value outranks every parent's, as Gradle resolves it. Quick Build is off when the module it builds (the first app module) has the opt-in in force; another app module's value does not affect Quick Build. To turn the rewrite off across a project, set `cogo.sqliteDebugger=false` where the opt-in is in force for each app module, or in the Gradle user home. The IDE's Quick Build check (`QuickBuildProjectSupport.isSqliteDebuggerEnabled`) reads those files for the Quick @@ -44,8 +44,8 @@ with an actionable message when the variant's runtime classpath has no The property is required because requery reaches apps only through `libs/`. Without it the rewritten classes cannot load, so the transform runs only on projects that opted in. To turn it off, set `cogo.sqliteDebugger=false` in -the file that defines it, or in one read earlier (Gradle user home, then the app module, its parent projects, then -the root: the first file that defines the property decides). Commenting the line out can expose another file's `true`. +the file that defines it, or in one read earlier (Gradle user home, then the app module, the root, then +its parent projects: the first file that defines the property decides). Commenting the line out can expose another file's `true`. ## Rules diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 4a4e77c0ee..74f136fbe6 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -81,7 +81,7 @@ object SqliteRewriter { private const val WAY_OUT = "If this class is the app's, change the code above. If it is in a library, the library cannot run on " + "requery: set cogo.sqliteDebugger=false in the gradle.properties that defines it, or in one read earlier " + - "(the first file that defines it decides: Gradle user home, then the app module, its parent projects, then the root), " + + "(the first file that defines it decides: Gradle user home, then the app module, the root, then its parent projects), " + "to build without the SQLite debugger. Commenting the line out can expose another file's true." private val remapper = diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index caafbda9c4..448ed4619b 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -437,7 +437,7 @@ class SqliteRewriterTest { val lastLine = e.message!!.lines().last() assertThat(lastLine).contains("in a library") assertThat(lastLine).contains("set cogo.sqliteDebugger=false in the gradle.properties that defines it, or in one read earlier") - assertThat(lastLine).contains("Gradle user home, then the app module, its parent projects, then the root") + assertThat(lastLine).contains("Gradle user home, then the app module, the root, then its parent projects") } @Test diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 4ad2fba5fd..f033bea3be 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -13,7 +13,7 @@ A project made from the JavaScript in SQLite template has it on already. For any 3. Check that the app depends on androidx.sqlite (Room and WorkManager bring it) and androidx.core (AppCompat brings it). requery needs both, and a file dependency brings neither. 4. Build and run the debug variant. The app starts the server and sends its port and token to Code on the Go (ADFA-7137), and AI-Agent-MCP connects to it with no setup (ADFA-7139). In phase 1 the Agent asks before each call (ADFA-7147). -The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on for an app module, Quick Build is off when that is the module it builds (the first app module). Gradle decides the line per app module, from the first of these files that defines it: the Gradle user home, the module's own `gradle.properties`, each parent project's, then the root's. Another app module's value does not affect Quick Build. To turn all of this off across a project, set `cogo.sqliteDebugger=false` where the line is in force for each app module (or once in the Gradle user home); commenting the line out can expose another file's `true` ([details](../../gradle-plugin/docs/sqlite-rewrite.md#turning-it-on)). +The app's code does not change: the build moves the app and its libraries from Android's SQLite to requery in every variant, release included, so debug and release run the same SQLite. Release builds never contain the debugger. While the line is on for an app module, Quick Build is off when that is the module it builds (the first app module). Gradle decides the line per app module, from the first of these files that defines it: the Gradle user home, the module's own `gradle.properties`, the root's, then each parent project's. Another app module's value does not affect Quick Build. To turn all of this off across a project, set `cogo.sqliteDebugger=false` where the line is in force for each app module (or once in the Gradle user home); commenting the line out can expose another file's `true` ([details](../../gradle-plugin/docs/sqlite-rewrite.md#turning-it-on)). Not covered: Room's `BundledSQLiteDriver`, which brings its own SQLite. When the app or one of its libraries uses something requery lacks, the build fails, names the class, method and line, and says how to build without the debugger; the list is under [Rules](../../gradle-plugin/docs/sqlite-rewrite.md#rules). From 1954dcdd45f6f6735c37b4e19d021c0e03429bd1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:25:16 -0800 Subject: [PATCH 190/203] ADFA-7138 Show a Quick Build refusal as off, not as a failure, on the toolbar and to plugins When the SQLite debugger refused a Quick Build start, QuickBuildTone.toTone() mapped Hidden(lastStartFailed = true) to ERROR without reading startRefused. The toolbar showed the error glyph (seen on a Note 20 on 2026-11-24), a plugin's getQuickBuildStatus() returned ERROR, and QuickBuildRunTracker returned Failed("Quick Build could not start.") with no reason. A refused start now maps to QuickBuildTone.SLOW, and the tracker returns QuickBuildResult.Refused(reason) with the refusal's own text (quick_build_disabled_sqlite_debugger, the string the status line and Build Output already use; PluginQuickBuildCoordinator passes it in, so no new string). SLOW fits best of the existing tones: the hollow bolt reads as "still the Quick Build button, but not ready and fast", and its tint is neutral. READY would show the filled bolt in colorSuccess ("all good"), RECONNECTING the sync glyph (work in progress), ERROR the fault. Checked end to end: the plugin's startQuickBuild() now completes with Refused(reason), the API's result for "Quick Build never started", and getQuickBuildStatus() returns FULL_BUILD_NEXT for SLOW. That state's wording ("the next Quick Build is a full build") is not exact for a refusal, and the toolbar's content description for SLOW says the same (cd_quick_build_slow); both are left as they are, as separate tones would need new strings and an API value. docs/PLUGIN_API_CHANGELOG.md records ABI additions and breaking changes, and the refusal first appears in this PR (origin/stage has no DisabledBySqliteDebugger), so there is no shipped behaviour to log. Tests: QuickBuildToneTest, QuickBuildRunTrackerTest and PluginQuickBuildCoordinatorTest (the status flows through track() to the plugin's result). With the fix reverted, the three fail: "expected: SLOW but was : ERROR", and "expected: Refused(reason=off while the SQLite debugger is on) but was : Failed(reason=Quick Build could not start., output=the log)". Review thread 4675254932 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/app/PluginQuickBuildCoordinator.kt | 1 + .../androidide/quickbuild/QuickBuildRunTracker.kt | 5 ++++- .../app/PluginQuickBuildCoordinatorTest.kt | 15 +++++++++++++++ .../quickbuild/QuickBuildRunTrackerTest.kt | 15 ++++++++++++++- .../quickbuild/domain/session/QuickBuildStatus.kt | 5 +++-- .../quickbuild/domain/session/QuickBuildTone.kt | 9 +++++++-- .../domain/session/QuickBuildToneTest.kt | 7 +++++++ 7 files changed, 51 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/app/PluginQuickBuildCoordinator.kt b/app/src/main/java/com/itsaky/androidide/app/PluginQuickBuildCoordinator.kt index 96b4569d86..1e01142656 100644 --- a/app/src/main/java/com/itsaky/androidide/app/PluginQuickBuildCoordinator.kt +++ b/app/src/main/java/com/itsaky/androidide/app/PluginQuickBuildCoordinator.kt @@ -148,6 +148,7 @@ internal class PluginQuickBuildCoordinator( QuickBuildRunTracker( start = sessionManager.status.value, startedAtMillis = SystemClock.elapsedRealtime(), + refusalReason = { IDEApplication.instance.getString(R.string.quick_build_disabled_sqlite_debugger) }, buildOutput = ::buildOutput, ) val run = Run(tracker, result, TapHandoff(sessionManager::onCancelRequested)) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildRunTracker.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildRunTracker.kt index 3286cec805..8932a3c8ed 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildRunTracker.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildRunTracker.kt @@ -20,11 +20,13 @@ import org.appdevforall.cotg.quickbuild.domain.session.SessionFailure * @param start the status when the plugin asked, before the tap saves: a build the save itself * starts carries the plugin's changes, so it is this tap's result. * @param startedAtMillis when the plugin asked, for [QuickBuildResult.Reloaded.durationMillis]. + * @param refusalReason the text for a start Quick Build declined on purpose ([QuickBuildResult.Refused]). * @param buildOutput the Build Output pane's text, attached to a failure. */ internal class QuickBuildRunTracker( private val start: QuickBuildStatus, private val startedAtMillis: Long, + private val refusalReason: () -> String = { "Quick Build did not start." }, private val buildOutput: () -> String?, ) { /** A proxy app build ran, so the landing relaunched the app. */ @@ -122,7 +124,8 @@ internal class QuickBuildRunTracker( is QuickBuildStatus.Hidden -> { if (status.lastStartFailed && moved) { - return failed("Quick Build could not start.") + // A refusal is Quick Build declining the project, not a fault the plugin must report. + return if (status.startRefused) QuickBuildResult.Refused(refusalReason()) else failed("Quick Build could not start.") } // A stop during the first build drops the session. if (sawWork) return QuickBuildResult.Cancelled diff --git a/app/src/test/java/com/itsaky/androidide/app/PluginQuickBuildCoordinatorTest.kt b/app/src/test/java/com/itsaky/androidide/app/PluginQuickBuildCoordinatorTest.kt index 85f12c9a7f..96316deb4e 100644 --- a/app/src/test/java/com/itsaky/androidide/app/PluginQuickBuildCoordinatorTest.kt +++ b/app/src/test/java/com/itsaky/androidide/app/PluginQuickBuildCoordinatorTest.kt @@ -194,6 +194,21 @@ class PluginQuickBuildCoordinatorTest { assertThat(result.await()).isInstanceOf(QuickBuildResult.Failed::class.java) } + @Test + fun `a start the SQLite debugger refuses reaches the plugin as Refused, not Failed`() = + runTest { + val idle = QuickBuildStatus.Hidden() + val status = MutableStateFlow(idle) + val tracker = QuickBuildRunTracker(idle, 0L, { "off while the SQLite debugger is on" }) { null } + + val result = trackAsync(status, tracker) + runCurrent() + status.value = QuickBuildStatus.Hidden(lastStartFailed = true, startRefused = true) + runCurrent() + + assertThat(result.await()).isEqualTo(QuickBuildResult.Refused("off while the SQLite debugger is on")) + } + @Test fun `a throw while following the run fails it instead of escaping`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildRunTrackerTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildRunTrackerTest.kt index 0d64457a01..38f6fe096e 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildRunTrackerTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildRunTrackerTest.kt @@ -10,7 +10,10 @@ import org.junit.Test /** How one plugin-started Quick Build's result is read off the session's status (ADFA-6493). */ class QuickBuildRunTrackerTest { - private fun tracker(start: QuickBuildStatus) = QuickBuildRunTracker(start, startedAtMillis = 1_000L, buildOutput = { "the log" }) + private fun tracker(start: QuickBuildStatus) = + QuickBuildRunTracker(start, startedAtMillis = 1_000L, refusalReason = { + "off while the SQLite debugger is on" + }, buildOutput = { "the log" }) /** Feeds [statuses] in order; the result of the last one, or null if none settled. */ private fun QuickBuildRunTracker.run(vararg statuses: QuickBuildStatus): QuickBuildResult? { @@ -160,6 +163,16 @@ class QuickBuildRunTrackerTest { assertThat(result).isEqualTo(QuickBuildResult.Failed("Quick Build could not start.", "the log")) } + @Test + fun `a refused start is Refused with the refusal's reason, not a failure`() { + val hidden = QuickBuildStatus.Hidden(lastStartFailed = true, startRefused = true) + val tracker = tracker(QuickBuildStatus.Hidden()) + + val result = tracker.run(QuickBuildStatus.Provisioning(), hidden) + + assertThat(result).isEqualTo(QuickBuildResult.Refused("off while the SQLite debugger is on")) + } + @Test fun `a full build that parks fails`() { val tracker = tracker(upToDate) diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt index c53d6b3723..9145dfbe76 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildStatus.kt @@ -16,11 +16,12 @@ sealed interface QuickBuildStatus { * No session - nothing in progress to narrate. * * @property lastStartFailed the last session start failed - * ([QuickBuildSessionState.Idle.lastStartFailed]), so the bolt keeps the error tone until + * ([QuickBuildSessionState.Idle.lastStartFailed]), so the bolt keeps the error tone (unless [startRefused]) until * the next tap or save; carried here because a failed start rests in Hidden and the tone * is derived from status alone. * @property startRefused that failed start was Quick Build deliberately declining the project - * ([QuickBuildSessionState.Idle.startRefused]), not a fault; surfaces word it differently. + * ([QuickBuildSessionState.Idle.startRefused]), not a fault: the tone is + * [QuickBuildTone.SLOW] rather than ERROR, and a plugin's run ends as a refusal. */ data class Hidden( val lastStartFailed: Boolean = false, diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildTone.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildTone.kt index 48d545fd3d..602edd08b1 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildTone.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildTone.kt @@ -37,9 +37,14 @@ enum class QuickBuildTone { fun QuickBuildStatus.toTone(): QuickBuildTone = when (this) { // A failed START is a failure the user has to deal with - only a tap retries it - so - // it must not settle back to the green bolt the moment the failure flash fades. + // it must not settle back to the green bolt the moment the failure flash fades. A + // refusal is Quick Build deliberately off, so it takes the neutral hollow bolt (SLOW). is QuickBuildStatus.Hidden -> { - if (lastStartFailed) QuickBuildTone.ERROR else QuickBuildTone.READY + when { + lastStartFailed && startRefused -> QuickBuildTone.SLOW + lastStartFailed -> QuickBuildTone.ERROR + else -> QuickBuildTone.READY + } } is QuickBuildStatus.UpToDate -> { diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildToneTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildToneTest.kt index abfefedc12..c3fdbed28f 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildToneTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildToneTest.kt @@ -49,6 +49,13 @@ class QuickBuildToneTest { assertThat(QuickBuildStatus.Failed(1, failure).toTone()).isEqualTo(QuickBuildTone.ERROR) } + @Test + fun `a failed start is ERROR, but a refused start is SLOW because Quick Build is off on purpose`() { + assertThat(QuickBuildStatus.Hidden(lastStartFailed = true).toTone()).isEqualTo(QuickBuildTone.ERROR) + assertThat(QuickBuildStatus.Hidden(lastStartFailed = true, startRefused = true).toTone()) + .isEqualTo(QuickBuildTone.SLOW) + } + @Test fun `needing a full build is SLOW, not an error - it is ordinary work`() { assertThat( From 7e43c175476da7d51a37801fd13e1987c26f6731 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:25:16 -0800 Subject: [PATCH 191/203] ADFA-7138 Fail on an unresolvable Context-method owner only for a virtual call decide() failed the build for any call whose owner cannot be resolved and whose name and descriptor match Context.deleteDatabase or openOrCreateDatabase, whatever the opcode. Context is a class, so only INVOKEVIRTUAL can reach one; a static call such as INVOKESTATIC com/vendor/Store.deleteDatabase(Ljava/lang/String;)Z on a library that is missing from the classpath failed an app build for nothing. The check now requires INVOKEVIRTUAL, beside the existing INVOKESPECIAL branch for super calls. Checked: decide() has two callers. Method handles reach it with their tag mapped to an opcode (H_INVOKEVIRTUAL to INVOKEVIRTUAL), so a virtual method reference on an unresolvable owner still fails (read from the code, not run); a static handle no longer does, as for a static call. INVOKEINTERFACE cannot name a class, so it is out too. Tests: SqliteRewriterTest, a static call on an unresolvable owner rewrites without failing, and a virtual call on another unresolvable owner still fails. With the fix reverted, the static case fails: SqliteRewriteException: ... go()Z (line 4): com/vendor/Store.deleteDatabase is a Context database method if com/vendor/Store is a Context, but ... cannot be resolved. Review thread 4675254944 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../gradle/sqlite/SqliteRewriter.kt | 3 +- .../gradle/sqlite/SqliteRewriterTest.kt | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt index 74f136fbe6..b38f2940ba 100644 --- a/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt +++ b/gradle-plugin/src/main/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriter.kt @@ -711,7 +711,8 @@ object SqliteRewriter { "super.$name on a Context cannot be redirected to requery; call it on this or on a Context instead", ) } - if (superTypes(owner) == null && owner !in Rules.CONTEXT_FAMILY) { + // Context is a class: only a virtual call can reach it, so a static or interface call on an owner we cannot resolve is not one + if (opcode == Opcodes.INVOKEVIRTUAL && superTypes(owner) == null && owner !in Rules.CONTEXT_FAMILY) { return Action.Fail( "$owner.$name is a Context database method if $owner is a Context, " + "but $owner cannot be resolved, so it cannot be redirected to requery", diff --git a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt index 448ed4619b..701cc542a4 100644 --- a/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt +++ b/gradle-plugin/src/test/java/com/itsaky/androidide/gradle/sqlite/SqliteRewriterTest.kt @@ -1653,6 +1653,56 @@ class SqliteRewriterTest { assertThat(warnings.single()).contains("isStrict()Z") } + @Test + fun `a static call on an unresolvable owner is not a Context call, a virtual one still fails`() { + val classes = + Compiler.compile( + listOf( + src( + "p.UsesStatic", + """ + package p; + public class UsesStatic { + boolean go() { return com.vendor.Store.deleteDatabase("n"); } + } + """, + ), + src( + "p.UsesVirtual", + """ + package p; + public class UsesVirtual { + boolean go(com.vendor.Dyn d) { return d.deleteDatabase("n"); } + } + """, + ), + // left out of the hierarchy, as a library missing from the classpath is + src( + "com.vendor.Store", + """ + package com.vendor; + public class Store { + public static boolean deleteDatabase(String n) { return true; } + } + """, + ), + src( + "com.vendor.Dyn", + """ + package com.vendor; + public class Dyn { + public boolean deleteDatabase(String n) { return true; } + } + """, + ), + ), + ) + // INVOKESTATIC com/vendor/Store.deleteDatabase(Ljava/lang/String;)Z + SqliteRewriter.rewrite(classes["p/UsesStatic"]!!, hierarchy) + val e = assertThrows(SqliteRewriteException::class.java) { SqliteRewriter.rewrite(classes["p/UsesVirtual"]!!, hierarchy) } + assertThat(e.message).contains("com/vendor/Dyn.deleteDatabase is a Context database method") + } + @Test fun `an unresolvable owner whose member names no SQLite type only warns`() { val classes = From dcb55066cae0f9f7888c68c108ff244f1c974981 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:28:20 -0800 Subject: [PATCH 192/203] ADFA-7136 Say "at least N tables" when get_stats hit the table list cap Failure: get_stats reads the table list with a limit of MAX_ROWS (1000) rows and then said "The database has N tables" with N the length of that list, so a database with 1200 tables was reported as having 1000. Fix: when the list holds MAX_ROWS names the message says "at least 1000 tables" (a list of exactly 1000 is still a correct lower bound); a shorter list keeps the exact wording. Test (DatabaseToolsTest.getStatsSaysAtLeastWhenTheTableListHitTheCap, with the fake engine, whose query applies the same maxRows cut as the native one): 1005 tables give "at least 1000", 999 give "999 tables". With only the fix reverted it fails: "The database has 1000 tables; counts are given only under 10." CodeRabbit thread PRRT_kwDONcONtM66nRM6 (F09) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 4 +++- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index a4d48ea4e5..001b466389 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -494,7 +494,9 @@ class DatabaseTools internal constructor( } out.put("row_counts", counts) } else { - out.put("row_counts_skipped", "The database has ${tables.size} tables; counts are given only under $MAX_TABLES_FOR_COUNTS.") + // The list above stops at MAX_ROWS, so a full one is a lower bound. + val count = if (tables.size >= MAX_ROWS) "at least ${tables.size}" else "${tables.size}" + out.put("row_counts_skipped", "The database has $count tables; counts are given only under $MAX_TABLES_FOR_COUNTS.") } return out } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 0d8e672faf..b8c36bbd53 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -885,6 +885,17 @@ class DatabaseToolsTest { assertTrue(seenSql.none { it.startsWith("SELECT COUNT") }) } + @Test fun getStatsSaysAtLeastWhenTheTableListHitTheCap() { + engine.appConnections += conn(1, "/data/a.db") + val names = (1..DatabaseTools.MAX_ROWS + 5).map { listOf("t$it") } + answerWith("SELECT name" to QueryResult(listOf("name"), names, 0, false)) + val capped = ok("get_stats", db()).getString("row_counts_skipped") + assertTrue(capped, capped.startsWith("The database has at least ${DatabaseTools.MAX_ROWS} tables;")) + answerWith("SELECT name" to QueryResult(listOf("name"), names.take(DatabaseTools.MAX_ROWS - 1), 0, false)) + val exact = ok("get_stats", db()).getString("row_counts_skipped") + assertTrue(exact, exact.startsWith("The database has ${DatabaseTools.MAX_ROWS - 1} tables;")) + } + @Test fun integrityCheckIsQuickUnlessAskedForFull() { engine.appConnections += conn(1, "/data/a.db") answerWith("PRAGMA" to QueryResult(listOf("quick_check"), listOf(listOf("ok")), 0, false)) From a24a886eb73d4b4d6acc4ebbf65e772a2bcb387e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:28:27 -0800 Subject: [PATCH 193/203] ADFA-7136 Answer Expect: 100-continue before reading the request body Failure: McpHttp never sent "HTTP/1.1 100 Continue". A client that sends "Expect: 100-continue" with its POST waits for it before sending the body, and so stalls until its own timeout (how long depends on the client; unverified). Fix: once the head has passed auth and every check that can refuse before the body (Host, Origin, path, token, and in readBody the Transfer-Encoding, Content-Length and size checks), and just before the body is read, the server writes "HTTP/1.1 100 Continue" and flushes, when the request asks for it (value compared case-insensitively). A request refused earlier gets only its final response. HTTP/1.0 requests are ignored. A Content-Length of 0 gets no interim reply. A refusal that comes after the body (415 in handle) is not covered: it needs the body read first. RFC 9110 section 10.1.1 (read from rfc-editor.org): the value is case-insensitive, a server must ignore the expectation in an HTTP/1.0 request, and may omit the 100 when it has already received the body. Tests (McpProtocolTest, raw socket): with "Expect: 100-Continue" the interim line arrives before the body is sent, then the body gets 200; without Expect there is no interim line; a wrong token (401) and a body over the limit (413) send only their final reply. With only the fix reverted, httpAnswers100ContinueBeforeTheBodyWhenAsked fails with "java.net.SocketTimeoutException: Read timed out" (McpProtocolTest.kt:564, the read of the interim line); the other three pass either way, as intended. CodeRabbit thread PRRT_kwDONcONtM66nRNA (F11) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/McpHttp.kt | 13 +++- .../sqlitedebugger/mcp/McpProtocolTest.kt | 65 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index 1050bdda26..7900ce446e 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -261,7 +261,15 @@ class McpHttp( // Refuse before reading a body, so an unauthenticated client never gets that far. if (!allowed(head, out)) return true c.soTimeout = IDLE_TIMEOUT_MS - head.body = readBody(input, head.headers) + head.body = + readBody(input, head.headers) { + // RFC 9110 10.1.1: a client that sent Expect: 100-continue waits for this before + // the body. HTTP/1.0 requests are ignored, as the RFC says. + if (head.version != "HTTP/1.0" && head.headers["expect"].equals("100-continue", ignoreCase = true)) { + out.write("HTTP/1.1 100 Continue\r\n\r\n".toByteArray(Charsets.ISO_8859_1)) + out.flush() + } + } head } catch (e: SocketTimeoutException) { return false @@ -426,16 +434,19 @@ class McpHttp( private fun readBody( input: InputStream, h: Map, + beforeRead: () -> Unit, ): ByteArray { val te = h["transfer-encoding"] if (te != null) { if (!te.equals("chunked", ignoreCase = true)) throw HttpError(501, "Transfer-Encoding $te isn't supported.") if (h.containsKey("content-length")) throw HttpError(400, "Both Content-Length and Transfer-Encoding were sent.") + beforeRead() return readChunked(input) } val len = h["content-length"] ?: return ByteArray(0) val n = len.toLongOrNull()?.takeIf { it >= 0 } ?: throw HttpError(400, "Content-Length isn't a number.") if (n > MAX_BODY_BYTES) throw HttpError(413, "The request is larger than ${MAX_BODY_BYTES / 1024} KB.") + if (n > 0) beforeRead() return readExactly(input, n.toInt()) } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 84a4818aa5..5748ed030b 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -527,6 +527,71 @@ class McpProtocolTest { assertEquals(200, http(s.boundPort, "POST", headers = auth, body = initBody()).status) } + /** Opens a connection, writes [head] and flushes it, and passes the socket on; the body is the test's to send. */ + private fun rawPost( + port: Int, + extra: String, + bodyBytes: Int, + use: (Socket) -> T, + ): T = + Socket("127.0.0.1", port).use { s -> + s.soTimeout = 5000 + val head = + "POST ${McpHttp.PATH} HTTP/1.1\r\nHost: 127.0.0.1:$port\r\nConnection: close\r\n" + + "Content-Type: application/json\r\nContent-Length: $bodyBytes\r\n$extra\r\n" + s.getOutputStream().apply { + write(head.toByteArray(Charsets.ISO_8859_1)) + flush() + } + use(s) + } + + @Test fun httpAnswers100ContinueBeforeTheBodyWhenAsked() { + val port = startServer() + val body = initBody().toByteArray(Charsets.UTF_8) + rawPost(port, "Authorization: Bearer $token\r\nExpect: 100-Continue\r\n", body.size) { s -> + val interim = "HTTP/1.1 100 Continue\r\n\r\n" + s.soTimeout = 2000 + assertEquals(interim, s.getInputStream().readNBytes(interim.length).toString(Charsets.ISO_8859_1)) + s.soTimeout = 5000 + s.getOutputStream().apply { + write(body) + flush() + } + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text, text.startsWith("HTTP/1.1 200")) + } + } + + @Test fun httpSendsNoInterimReplyWithoutExpect() { + val port = startServer() + val body = initBody().toByteArray(Charsets.UTF_8) + rawPost(port, "Authorization: Bearer $token\r\n", body.size) { s -> + s.getOutputStream().apply { + write(body) + flush() + } + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text, text.startsWith("HTTP/1.1 200")) + assertFalse(text, text.contains("100 Continue")) + } + } + + @Test fun httpRefusalBeforeTheBodySendsOnlyItsFinalReply() { + val port = startServer() + // a wrong token, and a body over the limit: each is refused before the body, with no interim reply + for ((extra, size, status) in listOf( + Triple("Authorization: Bearer wrong\r\nExpect: 100-continue\r\n", 10, 401), + Triple("Authorization: Bearer $token\r\nExpect: 100-continue\r\n", McpHttp.MAX_BODY_BYTES + 1, 413), + )) { + rawPost(port, extra, size) { s -> + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text, text.startsWith("HTTP/1.1 $status")) + assertFalse(text, text.contains("100 Continue")) + } + } + } + @Test fun httpSessionThenDelete() { val port = startServer() val s = http(port, "POST", headers = auth, body = initBody()).headers["mcp-session-id"]!! From afaf027ecfcbe3d6b43d6319be515bb017a67250 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:28:27 -0800 Subject: [PATCH 194/203] ADFA-7136 Answer 400 when a chunked body ends inside the trailer section Failure: in readChunked, after the zero-size chunk the trailer loop did `shortLine(...) ?: break`, so end of stream there counted as the end of the body. A request cut off after "0\r\n" was handled as if complete, while the chunk size line already answered 400 for the same cut. Fix: end of stream in the trailer section throws HttpError(400, "The request ended early."), as the size line does. Test (McpProtocolTest.httpChunkedBodyThatEndsInTheTrailerSectionIsA400): a valid initialize request sent as one chunk, then "0\r\n", then the output is shut down; expects 400. With only the fix reverted it fails: the server answers "HTTP/1.1 200 OK" with a session id (the message of the failed assertTrue is that whole reply). Checked the other readers: shortLine(input, 2) after a chunk and readExactly already throw 400 on end of stream. CodeRabbit thread PRRT_kwDONcONtM66nRNE (F13) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/McpHttp.kt | 2 +- .../sqlitedebugger/mcp/McpProtocolTest.kt | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt index 7900ce446e..3e2e84ff87 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpHttp.kt @@ -465,7 +465,7 @@ class McpHttp( // Trailers, if any, up to a blank line. var lines = 0 while (true) { - val t = shortLine(input, 1024) ?: break + val t = shortLine(input, 1024) ?: throw HttpError(400, "The request ended early.") if (t.isEmpty()) break if (++lines > 32) throw HttpError(431, "Too many trailers.") } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 5748ed030b..1311fe6fd4 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -592,6 +592,25 @@ class McpProtocolTest { } } + @Test fun httpChunkedBodyThatEndsInTheTrailerSectionIsA400() { + val port = startServer() + val body = initBody() + Socket("127.0.0.1", port).use { s -> + s.soTimeout = 5000 + val request = + "POST ${McpHttp.PATH} HTTP/1.1\r\nHost: 127.0.0.1:$port\r\nConnection: close\r\n" + + "Authorization: Bearer $token\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n" + + "${body.toByteArray().size.toString(16)}\r\n$body\r\n0\r\n" + s.getOutputStream().apply { + write(request.toByteArray(Charsets.UTF_8)) + flush() + } + s.shutdownOutput() + val text = s.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(text, text.startsWith("HTTP/1.1 400")) + } + } + @Test fun httpSessionThenDelete() { val port = startServer() val s = http(port, "POST", headers = auth, body = initBody()).headers["mcp-session-id"]!! From 18304caa073ed3e07e93fc2cbd38f60dd7f68b78 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:28:27 -0800 Subject: [PATCH 195/203] ADFA-7136 Count open attempts in FakeDebugEngine so "never opened" can fail Problem: FakeDebugEngine.openServerConnection throws for a path no app connection has open before it records anything, and openedServerConnections holds only successes. So the assertions that the engine was never asked to open a path (isEmpty / emptyList) passed whether or not the server asked. Change: openAttempts counts every call, before any refusal. DatabaseToolsTest asserts it is 0 at the six sites that claim the engine was not asked (the unknown-path listing, the bad-argument tools, two "Unknown database" cases, the in-memory empty path, the bad paging arguments); the old assertions stay. Checked: the six sites are every assertTrue(isEmpty) / assertEquals(emptyList) of openedServerConnections in the file; the other uses assert sizes after a successful open. Test-only change, no production code. Not run with a mutant that opens anyway: the counter is incremented on the first line of the method, so any call to it is counted. CodeRabbit thread PRRT_kwDONcONtM66nRNF (F14) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt | 5 +++++ .../appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index c3a4fb80dd..f889ba3684 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -31,6 +31,10 @@ class FakeDebugEngine( val openedServerConnections = mutableListOf>() + /** How many times the server asked to open one, counted before any refusal: [openedServerConnections] holds only successes. */ + var openAttempts = 0 + private set + /** How many server connections were closed. */ var closedServerConnections = 0 private set @@ -87,6 +91,7 @@ class FakeDebugEngine( path: String, writable: Boolean, ): ServerConnection { + openAttempts++ if (appConnections.isEmpty()) { throw DebugEngineException(DebugEngineException.SQLITE_MISUSE, "no app connection has opened yet") } diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index b8c36bbd53..79f08bd324 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -146,6 +146,7 @@ class DatabaseToolsTest { }, ) assertTrue(engine.openedServerConnections.isEmpty()) + assertEquals(0, engine.openAttempts) } @Test fun listDatabasesAddsUnopenedFilesButNotSideFiles() { @@ -230,6 +231,7 @@ class DatabaseToolsTest { assertTrue(name, missing.getBoolean("isError")) } assertTrue(engine.openedServerConnections.isEmpty()) + assertEquals(0, engine.openAttempts) } @Test fun aQueryRefusesAPathWhoseLastAppConnectionClosedAfterTheFirstCheck() { @@ -260,6 +262,7 @@ class DatabaseToolsTest { .startsWith("Unknown database"), ) assertTrue(engine.openedServerConnections.isEmpty()) + assertEquals(0, engine.openAttempts) } @Test fun aQueryRefusesAPathWhoseLastAppConnectionBeganClosingAfterTheFirstCheck() { @@ -288,12 +291,14 @@ class DatabaseToolsTest { .startsWith("Unknown database"), ) assertEquals(emptyList>(), engine.openedServerConnections) + assertEquals(0, engine.openAttempts) } @Test fun emptyPathOfAnInMemoryConnectionIsNotOpenable() { engine.appConnections += conn(1, "") assertTrue(runTool(tools, "get_stats", db("")).getBoolean("isError")) assertTrue(engine.openedServerConnections.isEmpty()) + assertEquals(0, engine.openAttempts) } @Test fun queryOpensReadOnlyAndPages() { @@ -354,6 +359,7 @@ class DatabaseToolsTest { bad("sql" to "x", "args" to "nope") bad("sql" to "x", "args" to JSONArray().put(JSONObject())) assertTrue(engine.openedServerConnections.isEmpty()) + assertEquals(0, engine.openAttempts) } @Test fun queryBindsArgsByType() { From 242f68a6c8728aa42e73987c1367d01f8b452822 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:28:28 -0800 Subject: [PATCH 196/203] ADFA-7136 Bound the waits in queuedBehindAnotherCall and release in finally Problem: the test helper waited for Thread.State.BLOCKED in an unbounded loop, awaited its `holding` latch without a limit, and counted `release` down only on the success path with plain join(). A failure in between (the queued call never blocking, or an assertion) left the slow worker parked on `release` and the test hanging. Change: holding.await and the BLOCKED loop give up after 10 s with an assertion; release.countDown() and both joins (10 s each) are in a finally, joining only threads that were started; afterwards both threads must not be alive. Test-only, no production code. Checked: the four callers of the helper pass unchanged in the full run of 108 tests. CodeRabbit thread PRRT_kwDONcONtM66nRNI (F15) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 79f08bd324..c804bb99c1 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -16,6 +16,7 @@ import org.junit.Assert.assertTrue import org.junit.Test import java.io.File import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong class DatabaseToolsTest { @@ -474,17 +475,26 @@ class DatabaseToolsTest { } val t = DatabaseTools(nativeDeadline(time::get), null, time::get) val slow = Thread({ ok("query", db().put("sql", "slow"), t) }, "dbtools-slow") - slow.start() - holding.await() var result: JSONObject? = null val queued = Thread({ result = runTool(t, name, args) }, "dbtools-queued") - queued.start() - // BLOCKED is a wait to enter a monitor; the slow call holds the tools' lock, and has already loaded every class on the path - while (queued.state != Thread.State.BLOCKED) Thread.sleep(5) - time.addAndGet(waitMs) - release.countDown() - queued.join() - slow.join() + try { + slow.start() + assertTrue("the slow call never reached the engine", holding.await(10, TimeUnit.SECONDS)) + queued.start() + // BLOCKED is a wait to enter a monitor; the slow call holds the tools' lock, and has already loaded every class on the path + val giveUp = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (queued.state != Thread.State.BLOCKED) { + assertTrue("the queued call never blocked on the lock: ${queued.state}", System.nanoTime() < giveUp) + Thread.sleep(5) + } + time.addAndGet(waitMs) + } finally { + release.countDown() + queued.takeIf { it.state != Thread.State.NEW }?.join(10_000) + slow.takeIf { it.state != Thread.State.NEW }?.join(10_000) + } + assertFalse("the queued call did not finish", queued.isAlive) + assertFalse("the slow call did not finish", slow.isAlive) return result!! } From 860cac5611369996dd59d6db77609f9b0aed5b6e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:28:51 -0800 Subject: [PATCH 197/203] ADFA-7136 Wait for the recorded accept retries instead of sleeping in the timing test Problem: httpAcceptBacksOffAfterFailuresAndKeepsServing slept 1200 ms and then read a synchronizedList's size and iterated it without its lock, so a slow machine could see fewer attempts than the sleeps need (and the iteration is not atomic with the list's writer, as the Collections.synchronizedList docs require for iteration). Change: the test polls (bounded at 10 s, every 10 ms) until the fifth attempt is recorded, then copies the list under synchronized(attempts) and checks the gaps of the copy: 100, 200, 400 and now also 800 ms of back-off (the fourth gap). The check that a spinning loop did not run is now the attempt count of the copy being five or six, and the gaps. Checked: the test passes in the full run (108 tests). Not run under load to see the old version fail: unverified. CodeRabbit thread PRRT_kwDONcONtM66nRNK (F17) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlitedebugger/mcp/McpProtocolTest.kt | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt index 1311fe6fd4..34892e4efc 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/McpProtocolTest.kt @@ -519,11 +519,20 @@ class McpProtocolTest { val s = McpHttp(protocol(), { token }, port = 0, socketFactory = { flaky }) s.start() server = s - Thread.sleep(1_200) // 100 + 200 + 400 ms of sleeps, then the fourth failure sleeps 800 ms + // 100 + 200 + 400 ms of sleeps, then the fourth failure sleeps 800 ms, then the fifth accept succeeds and waits + val giveUp = + System.nanoTime() + + java.util.concurrent.TimeUnit.SECONDS + .toNanos(10) + while (attempts.size < failures + 1) { + assertTrue("attempts so far: ${attempts.size}", System.nanoTime() < giveUp) + Thread.sleep(10) + } + val seen = synchronized(attempts) { attempts.toList() } // a spinning loop would have made thousands of attempts by now - assertTrue("attempts so far: ${attempts.size}", attempts.size in 4..6) - val gaps = attempts.zipWithNext { a, b -> (b - a) / 1_000_000 } - assertTrue("gaps $gaps", gaps[0] >= 90 && gaps[1] >= 190 && gaps[2] >= 390) + assertTrue("attempts so far: ${seen.size}", seen.size in (failures + 1)..(failures + 2)) + val gaps = seen.zipWithNext { a, b -> (b - a) / 1_000_000 } + assertTrue("gaps $gaps", gaps[0] >= 90 && gaps[1] >= 190 && gaps[2] >= 390 && gaps[3] >= 790) assertEquals(200, http(s.boundPort, "POST", headers = auth, body = initBody()).status) } From 29f355d1185ec96af4c720e0c50ef05cfee81b26 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:29:14 -0800 Subject: [PATCH 198/203] ADFA-7135 Open the JNI test's app fixture with UTF-8 bytes and check the result Problem: test/jni/helper.c opened the "app" connection with GetStringUTFChars, which is modified UTF-8 (a NUL as C0 80, a character outside the BMP as two three-byte surrogates), while the server is opened with real UTF-8 bytes from String.getBytes; and it ignored sqlite3_open's result, so a failed open returned a handle to a failed connection and the test went on. Change: Helper.open takes the path as UTF-8 bytes (Java side getBytes(UTF_8), native openBytes), opens it as such, closes and returns 0 on a failed sqlite3_open, and Helper.open throws when it gets 0. Checked: test.sh passes, JNI part 205 checks, 0 failures. All three callers of Helper.open use ASCII paths today, so no check changes outcome; no test of a non-BMP path (whether the host's file names take one depends on the JVM's sun.jnu.encoding: unverified). CodeRabbit thread PRRT_kwDONcONtM66nRNP (F18) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../sqlite-debugger/src/test/jni/Helper.java | 8 +++++++- .../sqlite-debugger/src/test/jni/helper.c | 19 +++++++++++++++---- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/subprojects/sqlite-debugger/src/test/jni/Helper.java b/subprojects/sqlite-debugger/src/test/jni/Helper.java index dcca237348..5c89abc374 100644 --- a/subprojects/sqlite-debugger/src/test/jni/Helper.java +++ b/subprojects/sqlite-debugger/src/test/jni/Helper.java @@ -1,6 +1,12 @@ /** Opens and uses "app" connections with the same libsqlite3x.so the debugger runs in. */ public class Helper { - static native long open(String path); + static long open(String path) { + long db = openBytes(path.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + if (db == 0) throw new IllegalStateException("sqlite3_open failed for " + path); + return db; + } + + private static native long openBytes(byte[] utf8Path); static native int autocommit(long db); diff --git a/subprojects/sqlite-debugger/src/test/jni/helper.c b/subprojects/sqlite-debugger/src/test/jni/helper.c index 35ac9df938..d42983c3cd 100644 --- a/subprojects/sqlite-debugger/src/test/jni/helper.c +++ b/subprojects/sqlite-debugger/src/test/jni/helper.c @@ -1,14 +1,25 @@ // The "app" side of the JNI test: plain sqlite3 calls into libsqlite3x.so, as requery's do. #include #include +#include #include "sqlite3.h" -JNIEXPORT jlong JNICALL Java_Helper_open(JNIEnv *e, jclass c, jstring p) { +// The path arrives as UTF-8 bytes and is opened as such, as sqlitedbg_open_server's path is: a +// GetStringUTFChars path would be modified UTF-8. Returns 0 when sqlite3_open fails. +JNIEXPORT jlong JNICALL Java_Helper_openBytes(JNIEnv *e, jclass c, jbyteArray p) { (void)c; - const char *s = (*e)->GetStringUTFChars(e, p, 0); + jsize n = (*e)->GetArrayLength(e, p); + char *s = malloc((size_t)n + 1); + if (!s) return 0; + (*e)->GetByteArrayRegion(e, p, 0, n, (jbyte *)s); + s[n] = 0; sqlite3 *db = 0; - sqlite3_open(s, &db); - (*e)->ReleaseStringUTFChars(e, p, s); + int rc = sqlite3_open(s, &db); + free(s); + if (rc != SQLITE_OK) { + sqlite3_close(db); + return 0; + } return (jlong)(intptr_t)db; } From f3fce48cde6cbf66df0866debb126c81891c2691 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:29:14 -0800 Subject: [PATCH 199/203] ADFA-7135 Fail the parameter diagnostic JNI test when the query succeeds Problem: in JniQueryTest the check of the "N parameter(s) but M argument(s)" message sat in the catch block of a try around the query, so if the query ran and returned (no exception) the test passed without checking anything. Change: a check(false, ...) after the query call in the try, so a successful query fails the test. Checked: the test passes against the real library (JNI part: 205 checks, 0 failures), where the query is refused with SQLITE_RANGE. Not run against a mutant that accepts the mismatch: unverified. CodeRabbit thread PRRT_kwDONcONtM66nRNX (F20) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index c2eb3ee7f0..5e47180211 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -291,6 +291,7 @@ public static void main(String[] a) throws Exception { eq(codeOf(srv, "SELECT 1", new Object[] {1L}, FAR), 25, "an arg for no parameter: SQLITE_RANGE"); try { query(srv, "SELECT ?, ?", new Object[] {1L}, 0, 100, 4096, 1024, MAX, FAR); + check(false, "a statement with two parameters and one argument ran"); } catch (DebugEngineException e) { check(e.getMessage().contains("2 parameter") && e.getMessage().contains("1 argument"), "the message names both counts: " + e.getMessage()); } From ba78ebbb245d4bee562e90b95d973b5287b03784 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:29:24 -0800 Subject: [PATCH 200/203] ADFA-7136 Say in the README that the time limits and two idle paths are best effort The README and the tool descriptions called the 1.5 s (database not in WAL mode) and 50 s statement limits plain limits. They are checked by the progress handler every 1000 SQLite VM instructions (sqlite3_progress_handler(db, 1000, ...) in sqlitedbg_jni.c), so not while a statement waits in the busy handler (SQLITEDBG_SERVER_BUSY_MS, 3000) and not inside one long instruction: a result can arrive up to about 3 s late; the client waits 60 s. Also documented: the column names are read before the first sqlite3_step (sqlitedbg_jni.c), so a schema change by the app between prepare and first step can return the old column set; and turning off bound-value recording after the idle time goes through expireIdleClient, which takes the tools' lock that a running query holds for up to 50 s, so it can be up to 50 s late. The README gets three bullets before its "Limits" bullet; every existing value is kept. NON_WAL_NOTE, the text of every tool that runs SQL, now says "best effort" and "up to about 3 s longer" after its unchanged first words (DatabaseToolsTest still checks them). Checked in the code as quoted above; the claim that the progress handler does not run during the busy wait is from SQLite's documented behaviour (it runs in the VM), not from a test. CodeRabbit threads PRRT_kwDONcONtM66nRMj (F01), PRRT_kwDONcONtM66nRMo (F02), PRRT_kwDONcONtM66nRMw (F04), PRRT_kwDONcONtM66nRM2 (F07) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 3 +++ .../org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index f7fafa37eb..6dbdfaaea9 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -37,6 +37,9 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). - **Bound values are recorded only while a client is connected.** Expanding the SQL costs memory on every run, so `sqlitedbg_set_client_connected` turns it on; the first `get_events` call does, and it goes off again 60 s after the last one (checked on every tool call and by a timer). - **The event cursor names its process.** Event numbers (`seq`) start at 1 in every app process, so a cursor from before an app restart would silently skip events, or return none. Every `get_events` result carries `run`, a random UUID fixed for the process (`DebugEngine.runId`; `NativeDebugEngine` makes it once per process), and the agent passes the last `next` as `after` and the last `run` as `run`. A `run` that differs from the current one reads from the start (as `after` 0) and sets `reset: true`. So does an `after` at or past the next number the process would assign (`after >= g_next_seq`, checked in `sqlitedbg_read_events` under the lock, which reports it as `sqlitedbg_read_result.reset`; `SQLITEDBG_INTERFACE_VERSION` is 2 for the changed struct), which catches a client that sends no `run`; `after` equal to the newest number is a reader that is caught up and gets no reset. Limit: a client that sends no `run` and holds a cursor from an earlier process that is still below the new process's count gets no reset and misses those events, as nothing in `after` alone tells them apart. AI-Agent-MCP does not keep the cursor (the model passes `after` itself), so it needs no change. +- **The time limits are best effort.** The 1.5 s limit on a database that is not in WAL mode and the 50 s limit per call are checked by the progress handler, every 1,000 SQLite VM instructions. They are not checked while a statement waits for a lock the app holds (the busy wait, up to 3 s, `SQLITEDBG_SERVER_BUSY_MS`) or inside one long VM instruction, so a result can arrive up to about 3 s after its limit (the client waits 60 s). The tool descriptions say "best effort" too. +- **Column names can be stale after a schema change.** The column names are read after prepare and before the first step, so a schema change by the app between the two can return the old column set. +- **Turning off bound-value recording can be late.** After the client goes idle (60 s after the last `get_events`), turning recording off takes the tools' lock, so it waits for a running query and can be up to 50 s late (more by the overrun above). - **Limits.** Connections opened before `install` are not seen, so `DebuggerStartup` runs as early as the process allows. requery's own `sqlite3_trace` replaces ours on a connection when `log.tag.SQLiteStatements` or `log.tag.SQLiteTime` is VERBOSE, so events from such connections stop. Events are dropped, oldest first, when the buffer (4 MiB by default) is full, and `get_events` reports how many. A query result holds at most 4 MiB of cell bytes (`QueryLimits.maxTotalBytes`: TEXT and BLOB bytes kept, 8 per number), so a SELECT of many rows cannot exhaust the app's heap; the rest is paged (`has_more`). The first row always comes back whole, so that a page makes progress, and one very wide row can pass the cap: in `query`, 2000 columns (SQLite's default `SQLITE_MAX_COLUMN`, which requery keeps) of 4096-byte TEXT come to about 7.8 MiB. The engine reports which cells were cut (`QueryResult.truncatedCellIndexes`), so a BLOB of exactly the limit is not flagged. `query`, `explain_query_plan` and `integrity_check` return that list as `truncated_cell_indexes`, `[row, column]` pairs from 0 with the row relative to the rows returned, beside the count `truncated_cells`; a cut TEXT cell stays a plain string, so this list is the only mark on it, and a cut BLOB is listed too (it also has `truncated: true`). `get_schema` has no such list: each entry says whether one of its cells was cut. `get_stats` returns numbers and table names and does not report cuts (a table name over 4096 bytes would be cut there; not tested). `get_schema` cuts a CREATE statement at 64 KiB and says so, in the entry's `truncated` and in `truncated_cells` as `query` does. Its top-level `truncated` also says when entries were left out, past the first 1000 or past the 4 MiB budget (about 64 statements of 64 KiB). It has no `offset`, so its description sends the agent to page through `sqlite_master` with `query` (`ORDER BY type, name`, the order `get_schema` uses, which is unique), reading a statement longer than `query`'s 4096-byte TEXT limit in parts with `substr` (which counts characters, not bytes). A query holds exactly one statement: SQLite compiles only the first, so SQL with a second statement (or with none, or a NUL) is refused rather than half run. Tool calls run one at a time. The 50 s time limit belongs to the POST: `McpProtocol` sets one deadline when it starts handling a POST and passes it to every tool call of the batch, so waits behind other calls count and a batch of slow calls ends within 50 s in all, not 50 s each (32 calls would have held the lock for about 27 minutes). A call that starts after the deadline fails at once with the time-limit error (the engine refuses to start a query past its deadline); `list_databases`, `list_connections` and `get_events` run no SQL and still answer. A single call gets the same limit as before. The server therefore gives up before the client's 60 s limit, which is taken to be per request and is unchecked for a batch, so a timed-out query does not hold the lock after the client has stopped waiting; when waiting for the lock took at least half of the limit, the error says so, for the agent to retry. A batch holds at most 32 messages, notifications included, and a longer one is refused whole (HTTP 400, null `id`) with nothing run. Once a batch's replies reach 8 MiB (counted in JSON characters), its remaining requests are answered with error -32000 without running, to be sent again in another POST; the reply that crosses that line is sent whole and can be several times 8 MiB, as the 4 MiB cap counts cell bytes, not JSON (a control character such as 0x01 in TEXT becomes 13 characters, escaped in the structured content and again in its text copy). ## Testing diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index 001b466389..ac343b44af 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -86,8 +86,9 @@ class DatabaseTools internal constructor( * sqlitedbg.h, which says why); this text must follow it. */ const val NON_WAL_NOTE = - "On a database that is not in WAL mode a statement is stopped after 1.5 s, so a long read does not block the app's " + - "own writes; use a narrower query or a LIMIT. A database in WAL mode has no such limit (the $DEADLINE_SECONDS s limit applies)." + "On a database that is not in WAL mode a statement is stopped after 1.5 s (best effort: it can run up to about 3 s " + + "longer), so a long read does not block the app's own writes; use a narrower query or a LIMIT. A database in " + + "WAL mode has no such limit (the $DEADLINE_SECONDS s limit applies, also best effort)." /** Server connections never load what the app registers on its own connections (see the README). */ private const val APP_FUNCTIONS_NOTE = From 38ee6693301d9853ef257f49088452b746b3b173 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:39:11 -0800 Subject: [PATCH 201/203] ADFA-7138 Remove the one-argument isSqliteDebuggerEnabled, which only tests called isSqliteDebuggerEnabled(String?) had no production caller: the provisioner calls the multi-file overload. Its parsing is the same Properties lookup (value exactly "true") that the multi-file overload already runs, so the function is deleted rather than kept private, and the parsing test now goes through the multi-file overload with a real gradle.properties file. The null case (no file) is covered by "the root gradle properties file is read, a missing one is not an opt-in". Checked: grep finds no other caller in app/ or quickbuild/. No behaviour change, so no revert proof. Tests: QuickBuildProjectSupportTest. Review thread 4675254948 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../quickbuild/QuickBuildProjectSupport.kt | 8 ------- .../QuickBuildProjectSupportTest.kt | 24 +++++++++++-------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt index fde414543d..bf726ab60e 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupport.kt @@ -68,14 +68,6 @@ object QuickBuildProjectSupport { null } - /** - * Whether one `gradle.properties` text opts in, decided as the Gradle plugin does: the value is - * exactly `true`. - * - * @param gradleProperties the file's text, or null when there is none. - */ - fun isSqliteDebuggerEnabled(gradleProperties: String?): Boolean = gradleProperties != null && propertyValue(gradleProperties) == "true" - /** * The directories whose `gradle.properties` Gradle's `findProperty` reads for the project at * [modulePath], in Gradle's precedence: the module's own directory, the root's, then each parent diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt index bfb373d4bb..cb4ee0f07e 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildProjectSupportTest.kt @@ -78,16 +78,20 @@ class QuickBuildProjectSupportTest { } @Test - fun `gradle properties decide the opt-in as the Gradle plugin does`() { - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("org.gradle.jvmargs=-Xmx2g\ncogo.sqliteDebugger=true\n")).isTrue() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebugger = true")).isTrue() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("#cogo.sqliteDebugger=true")).isFalse() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebugger=false")).isFalse() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebugger=TRUE")).isFalse() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("cogo.sqliteDebuggerX=true")).isFalse() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled("")).isFalse() - assertThat(QuickBuildProjectSupport.isSqliteDebuggerEnabled(null as String?)).isFalse() - } + fun `gradle properties decide the opt-in as the Gradle plugin does`() = + withDirs { root, home, _ -> + fun enabledBy(text: String): Boolean { + root.props(text) + return QuickBuildProjectSupport.isSqliteDebuggerEnabled(home, listOf(root), readText = { it.readText() }) + } + assertThat(enabledBy("org.gradle.jvmargs=-Xmx2g\ncogo.sqliteDebugger=true\n")).isTrue() + assertThat(enabledBy("cogo.sqliteDebugger = true")).isTrue() + assertThat(enabledBy("#cogo.sqliteDebugger=true")).isFalse() + assertThat(enabledBy("cogo.sqliteDebugger=false")).isFalse() + assertThat(enabledBy("cogo.sqliteDebugger=TRUE")).isFalse() + assertThat(enabledBy("cogo.sqliteDebuggerX=true")).isFalse() + assertThat(enabledBy("")).isFalse() + } private fun withDirs(block: (root: java.io.File, home: java.io.File, module: java.io.File) -> Unit) { val base = From acdca5acd3bdd0a8d63001141f8b3c34bbe82bdf Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:39:11 -0800 Subject: [PATCH 202/203] ADFA-7138 Note the window left by skipping the replace question on a refusal replaceConfirmedUnlessRefused skips "Replace the installed app?" on the tap's own refusal check, and the provisioner decides again moments later. If the model or gradle.properties changes between the two (a sync, or an edit), the provisioner may not refuse and the app is replaced without the question. The PR description already lists this window; the KDoc now says so. Comment only, no code change, no tests. Review thread 4675254937 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../com/itsaky/androidide/actions/build/QuickBuildAction.kt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt b/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt index 650f576516..e1267e8a82 100644 --- a/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt +++ b/app/src/main/java/com/itsaky/androidide/actions/build/QuickBuildAction.kt @@ -261,6 +261,10 @@ class QuickBuildAction( * happen, and its Cancel would hide the refusal that explains why Quick Build is off. The * session then shows that refusal, as the banner and as the status line's "tap for details". * + * Skipping the question relies on the provisioner reading the same model and files moments + * later. A change in between (a sync, or an edit to gradle.properties) could install over + * the app without asking. + * * @param refused whether the SQLite debugger will refuse the build. * @param confirm asks the user, on the main thread; true to replace the installed app. */ From 0b4ebca2cdfc48262de3de2ea2c360f143edf5f4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:39:11 -0800 Subject: [PATCH 203/203] ADFA-7138 Document that androidTest classes are not rewritten SqliteRewritePlugin registers the transform in onVariants on the variant's own instrumentation (InstrumentationScope.ALL) and never on variant.androidTest, so an androidTest component's classes keep Android's SQLite types. An instrumented test that calls app code with SQLite types in its signatures can fail to link (NoSuchMethodError). Added under Known limits in sqlite-rewrite.md. Checked by reading the registration; not run on a device, and nothing in the repo exercises it. Docs only, no tests. Review thread 4675254941 (Hal) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- gradle-plugin/docs/sqlite-rewrite.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/gradle-plugin/docs/sqlite-rewrite.md b/gradle-plugin/docs/sqlite-rewrite.md index bca7813b6e..c12b12e4b4 100644 --- a/gradle-plugin/docs/sqlite-rewrite.md +++ b/gradle-plugin/docs/sqlite-rewrite.md @@ -198,6 +198,11 @@ dependency, and runs the script on both APKs. The release must pass. The debug A ## Known limits - Room's `BundledSQLiteDriver` is not covered (it brings its own SQLite). +- `androidTest` classes are not rewritten: `SqliteRewritePlugin` registers the transform on each variant's + `instrumentation` only, not on `variant.androidTest`'s (read from the code, not run). An instrumented test that + calls app code with SQLite types in its signatures (for example `val db: SQLiteDatabase = MyHelper(ctx).writableDatabase`) + keeps the platform descriptor, while the rewritten app class has requery's, so it can fail to link with a + `NoSuchMethodError` (not run). - requery's native library is built without ICU: there is no `UNICODE` collator (a `COLLATE UNICODE` string constant fails the build, see above; the clause is found through whitespace, SQL comments and a quoted name, which needs no space after `COLLATE`, and `UNICODE_CI` is a different collation and passes) and `LOCALIZED` compares bytes (a warning).