Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions subprojects/sqlite-debugger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,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 <token>`, 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 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.
- **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. So is an error from `sqlite3_finalize`, where a writable connection's autocommit write commits when a page stops before its last row (an INSERT with RETURNING), unless the query had already failed. 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).
Expand All @@ -43,7 +43,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han
- **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).
- **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. The extension keeps each connection's state as the user data of the function it registers on that connection, `sqlitedbg_connection_id()` (no arguments), and SQLite frees the state through that function's destructor. If the app registers a function with the same name and no arguments on the same connection, which replaces ours, or deletes ours, SQLite frees the state while the trace callback still uses it: a use after free in the app's process. Don't give an app function that name. 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

Expand Down
2 changes: 2 additions & 0 deletions subprojects/sqlite-debugger/src/main/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ 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.
# A change to the version script alone must relink.
set_target_properties(sqlitedbg PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/sqlitedbg.map)
target_link_options(sqlitedbg PRIVATE
-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/sqlitedbg.map
-Wl,-z,max-page-size=16384)
12 changes: 11 additions & 1 deletion subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c
Original file line number Diff line number Diff line change
Expand Up @@ -497,8 +497,18 @@ 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);
// A statement stopped before SQLITE_DONE (a page cut short) ends here: on a writable connection an
// autocommit write, such as an INSERT ... RETURNING, commits here, and a commit that fails rolls the
// write back. That is the call's error, unless the query already failed: that error is kept.
rc = sqlite3_finalize(st);
free(cut_cells);
if (rc != SQLITE_OK && !(*env)->ExceptionCheck(env)) {
char msg[256];
snprintf(msg, sizeof msg, "the statement failed as it was finished, and nothing it changed was kept: %s",
sqlite3_errmsg(db));
throw_engine(env, rc, msg);
result = NULL;
}
// 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. A failure is the call's error,
// unless the query already failed: that error is kept.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -760,16 +760,23 @@ internal fun interface IdleScheduler {
): () -> Unit
}

/** One daemon timer thread per pending check, ended by its cancel. */
private class TimerIdleScheduler : IdleScheduler {
/** One daemon timer thread per pending check, ended by its cancel or once its task has run. */
internal 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()
override fun run() {
try {
task.run()
} finally {
// The thread would otherwise stay parked until the next schedule cancels it.
timer.cancel()
}
}
},
delayMs,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,8 @@ class McpHttp(
c.tcpNoDelay = true
val input = BufferedInputStream(c.getInputStream())
val out = c.getOutputStream()
var headStart = System.currentTimeMillis()
// nanoTime, not the wall clock: a clock set back would extend the head's deadline (as in finishReply)
var headStart = System.nanoTime()
Comment thread
davidschachterADFA marked this conversation as resolved.
Resolved
var first = true
while (running) {
val req =
Expand All @@ -254,10 +255,10 @@ class McpHttp(
input.mark(1)
if (input.read() < 0) return false
input.reset()
headStart = System.currentTimeMillis()
headStart = System.nanoTime()
}
first = false
val head = readHead(input, c, headStart + headDeadlineMs) ?: return false
val head = readHead(input, c, headStart + headDeadlineMs * 1_000_000L) ?: return false
// Refuse before reading a body, so an unauthenticated client never gets that far.
if (!allowed(head, out)) return true
c.soTimeout = IDLE_TIMEOUT_MS
Expand Down Expand Up @@ -382,7 +383,7 @@ class McpHttp(
return MessageDigest.isEqual(h.substring(7).trim().toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8))
}

/** The head of one request (no body yet), or null if the connection closed before one began. */
/** The head of one request (no body yet), or null if the connection closed before one began. [deadlineAt] is in nanoTime. */
private fun readHead(
input: InputStream,
c: Socket,
Expand All @@ -393,7 +394,7 @@ class McpHttp(
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()
val left = (deadlineAt - System.nanoTime()) / 1_000_000L
if (left <= 0) throw SocketTimeoutException("the request's head took too long")
c.soTimeout = minOf(left, IDLE_TIMEOUT_MS.toLong()).toInt()
}
Expand Down
Loading
Loading