Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sqlite: fix use-after-free in StatementSync due to premature GC #56840

Merged
merged 1 commit into from
Feb 5, 2025

Conversation

littledivy
Copy link
Member

This patch updates StatementSync to store a strong reference to the database base object.

DatabaseSync may be garbage collected and freed while StatementSync is using it (due to MakeWeak()). The following code crashes with a segmentation fault:

import { DatabaseSync } from "node:sqlite";

const db = new DatabaseSync(':memory:');
db.exec('CREATE TABLE test (value INTEGER)');

const stmt = db.prepare('INSERT INTO test VALUES (?)');

for(;;) stmt.run(0);
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x38)
    frame #0: 0x000000010036e358 node`node::sqlite::StatementSync::Run(v8::FunctionCallbackInfo<v8::Value> const&) + 432
node`node::sqlite::StatementSync::Run:
->  0x10036e358 <+432>: ldr    x1, [x8, #0x38]
    0x10036e35c <+436>: ldr    x22, [x8, #0x78]
    0x10036e360 <+440>: ldrb   w8, [x19, #0x40]
    0x10036e364 <+444>: ldr    x24, [x25, #0xa8]

@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. needs-ci PRs that need a full CI run. sqlite Issues and PRs related to the SQLite subsystem. labels Jan 31, 2025
Copy link
Contributor

@cjihrig cjihrig left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@cjihrig cjihrig added the request-ci Add this label to start a Jenkins CI on a PR. label Jan 31, 2025
@github-actions github-actions bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jan 31, 2025
@nodejs-github-bot
Copy link
Collaborator

Copy link

codecov bot commented Jan 31, 2025

Codecov Report

Attention: Patch coverage is 50.00000% with 7 lines in your changes missing coverage. Please review.

Project coverage is 89.20%. Comparing base (316ac8c) to head (e91a418).
Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
src/node_sqlite.cc 50.00% 0 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #56840      +/-   ##
==========================================
+ Coverage   89.18%   89.20%   +0.01%     
==========================================
  Files         665      665              
  Lines      192543   192542       -1     
  Branches    37045    37051       +6     
==========================================
+ Hits       171726   171749      +23     
- Misses      13636    13639       +3     
+ Partials     7181     7154      -27     
Files with missing lines Coverage Δ
src/node_sqlite.h 70.00% <ø> (ø)
src/node_sqlite.cc 79.82% <50.00%> (-0.02%) ⬇️

... and 21 files with indirect coverage changes

@cjihrig cjihrig added the request-ci Add this label to start a Jenkins CI on a PR. label Jan 31, 2025
@github-actions github-actions bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Jan 31, 2025
@nodejs-github-bot
Copy link
Collaborator

@cjihrig
Copy link
Contributor

cjihrig commented Feb 1, 2025

Hm, it looks like there may be related failures on Windows while trying to clean up:

16:58:48     (node:12696) ExperimentalWarning: SQLite is an experimental feature and might change at any time
16:58:48     (Use `node --trace-warnings ...` to show where the warning was created)
16:58:48     Can't clean tmpdir: d:\workspace\node-test-binary-windows-js-suites\node\test\.tmp.729
16:58:48     Files blocking: [
16:58:48       'database-5.db',
16:58:48       'database-6.db',
16:58:48       'database-7.db',
16:58:48       'database-8.db',
16:58:48       'database-9.db'
16:58:48     ]
16:58:48     
16:58:48     d:\workspace\node-test-binary-windows-js-suites\node\test\common\tmpdir.js:69
16:58:48         throw e;
16:58:48         ^
16:58:48     
16:58:48     Error: EPERM, Permission denied: \\?\d:\workspace\node-test-binary-windows-js-suites\node\test\.tmp.729 '\\?\d:\workspace\node-test-binary-windows-js-suites\node\test\.tmp.729'
16:58:48         at Object.rmSync (node:fs:1250:18)
16:58:48         at rmSync (d:\workspace\node-test-binary-windows-js-suites\node\test\common\tmpdir.js:20:8)
16:58:48         at onexit (d:\workspace\node-test-binary-windows-js-suites\node\test\common\tmpdir.js:54:5)
16:58:48         at process.<anonymous> (d:\workspace\node-test-binary-windows-js-suites\node\test\common\tmpdir.js:43:14)
16:58:48         at process.emit (node:events:519:35) {
16:58:48       errno: 1,
16:58:48       code: 'EPERM',
16:58:48       path: '\\\\?\\d:\\workspace\\node-test-binary-windows-js-suites\\node\\test\\.tmp.729',
16:58:48       syscall: 'rm'
16:58:48     }
16:58:48     
16:58:48     Node.js v24.0.0-pre
16:58:48   ...

This happened a number of times on Windows. I'll restart the CI to see if that was a one off issue, but I have a feeling it's legit.

@nodejs-github-bot
Copy link
Collaborator

@cjihrig
Copy link
Contributor

cjihrig commented Feb 1, 2025

The latest run had the same file files blocking cleanup. They appear to correspond to these five tests. I'm not sure off the top of my head why those ones would be blocking. I do see that the two iterate() tests never explicitly close the database, so maybe that is related. Using in memory databases might be an option too, but that seems like a less correct solution.

@littledivy
Copy link
Member Author

littledivy commented Feb 3, 2025

I updated the two iterate() tests to close the db. The tests seem to pass locally on Windows.

@cjihrig cjihrig added the request-ci Add this label to start a Jenkins CI on a PR. label Feb 3, 2025
@github-actions github-actions bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Feb 3, 2025
@nodejs-github-bot
Copy link
Collaborator

@nodejs-github-bot
Copy link
Collaborator

@nodejs-github-bot
Copy link
Collaborator

@cjihrig cjihrig added commit-queue-squash Add this label to instruct the Commit Queue to squash all the PR commits into the first one. request-ci Add this label to start a Jenkins CI on a PR. labels Feb 4, 2025
@github-actions github-actions bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Feb 4, 2025
@nodejs-github-bot
Copy link
Collaborator

@cjihrig
Copy link
Contributor

cjihrig commented Feb 4, 2025

@littledivy can you apply these changes. These should resolve the test failures now due to a conflicting change that landed.

diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc
index 39e1be871d..1639c196ce 100644
--- a/src/node_sqlite.cc
+++ b/src/node_sqlite.cc
@@ -977,7 +977,7 @@ inline bool StatementSync::IsFinalized() {
 
 bool StatementSync::BindParams(const FunctionCallbackInfo<Value>& args) {
   int r = sqlite3_clear_bindings(statement_);
-  CHECK_ERROR_OR_THROW(env()->isolate(), db_, r, SQLITE_OK, false);
+  CHECK_ERROR_OR_THROW(env()->isolate(), db_.get(), r, SQLITE_OK, false);
 
   int anon_idx = 1;
   int anon_start = 0;
@@ -1107,7 +1107,7 @@ bool StatementSync::BindValue(const Local<Value>& value, const int index) {
     return false;
   }
 
-  CHECK_ERROR_OR_THROW(env()->isolate(), db_, r, SQLITE_OK, false);
+  CHECK_ERROR_OR_THROW(env()->isolate(), db_.get(), r, SQLITE_OK, false);
   return true;
 }
 
@@ -1173,7 +1173,7 @@ void StatementSync::All(const FunctionCallbackInfo<Value>& args) {
       env, stmt->IsFinalized(), "statement has been finalized");
   Isolate* isolate = env->isolate();
   int r = sqlite3_reset(stmt->statement_);
-  CHECK_ERROR_OR_THROW(isolate, stmt->db_, r, SQLITE_OK, void());
+  CHECK_ERROR_OR_THROW(isolate, stmt->db_.get(), r, SQLITE_OK, void());
 
   if (!stmt->BindParams(args)) {
     return;
@@ -1202,7 +1202,7 @@ void StatementSync::All(const FunctionCallbackInfo<Value>& args) {
     rows.emplace_back(row);
   }
 
-  CHECK_ERROR_OR_THROW(isolate, stmt->db_, r, SQLITE_DONE, void());
+  CHECK_ERROR_OR_THROW(isolate, stmt->db_.get(), r, SQLITE_DONE, void());
   args.GetReturnValue().Set(Array::New(isolate, rows.data(), rows.size()));
 }
 
@@ -1270,7 +1270,8 @@ void StatementSync::IterateNextCallback(
 
   int r = sqlite3_step(stmt->statement_);
   if (r != SQLITE_ROW) {
-    CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_, r, SQLITE_DONE, void());
+    CHECK_ERROR_OR_THROW(
+        env->isolate(), stmt->db_.get(), r, SQLITE_DONE, void());
 
     // cleanup when no more rows to fetch
     sqlite3_reset(stmt->statement_);
@@ -1322,7 +1323,7 @@ void StatementSync::Iterate(const FunctionCallbackInfo<Value>& args) {
   auto isolate = env->isolate();
   auto context = env->context();
   int r = sqlite3_reset(stmt->statement_);
-  CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_, r, SQLITE_OK, void());
+  CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_.get(), r, SQLITE_OK, void());
 
   if (!stmt->BindParams(args)) {
     return;
@@ -1386,7 +1387,7 @@ void StatementSync::Get(const FunctionCallbackInfo<Value>& args) {
       env, stmt->IsFinalized(), "statement has been finalized");
   Isolate* isolate = env->isolate();
   int r = sqlite3_reset(stmt->statement_);
-  CHECK_ERROR_OR_THROW(isolate, stmt->db_, r, SQLITE_OK, void());
+  CHECK_ERROR_OR_THROW(isolate, stmt->db_.get(), r, SQLITE_OK, void());
 
   if (!stmt->BindParams(args)) {
     return;
@@ -1396,7 +1397,7 @@ void StatementSync::Get(const FunctionCallbackInfo<Value>& args) {
   r = sqlite3_step(stmt->statement_);
   if (r == SQLITE_DONE) return;
   if (r != SQLITE_ROW) {
-    THROW_ERR_SQLITE_ERROR(isolate, stmt->db_);
+    THROW_ERR_SQLITE_ERROR(isolate, stmt->db_.get());
     return;
   }
 
@@ -1432,7 +1433,7 @@ void StatementSync::Run(const FunctionCallbackInfo<Value>& args) {
   THROW_AND_RETURN_ON_BAD_STATE(
       env, stmt->IsFinalized(), "statement has been finalized");
   int r = sqlite3_reset(stmt->statement_);
-  CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_, r, SQLITE_OK, void());
+  CHECK_ERROR_OR_THROW(env->isolate(), stmt->db_.get(), r, SQLITE_OK, void());
 
   if (!stmt->BindParams(args)) {
     return;
@@ -1441,7 +1442,7 @@ void StatementSync::Run(const FunctionCallbackInfo<Value>& args) {
   auto reset = OnScopeLeave([&]() { sqlite3_reset(stmt->statement_); });
   r = sqlite3_step(stmt->statement_);
   if (r != SQLITE_ROW && r != SQLITE_DONE) {
-    THROW_ERR_SQLITE_ERROR(env->isolate(), stmt->db_);
+    THROW_ERR_SQLITE_ERROR(env->isolate(), stmt->db_.get());
     return;
   }
 
@@ -1674,7 +1675,7 @@ void Session::Changeset(const FunctionCallbackInfo<Value>& args) {
   void* pChangeset;
   int r = sqliteChangesetFunc(session->session_, &nChangeset, &pChangeset);
   CHECK_ERROR_OR_THROW(
-      env->isolate(), session->database_, r, SQLITE_OK, void());
+      env->isolate(), session->database_.get(), r, SQLITE_OK, void());
 
   auto freeChangeset = OnScopeLeave([&] { sqlite3_free(pChangeset); });
 

@cjihrig cjihrig added the request-ci Add this label to start a Jenkins CI on a PR. label Feb 5, 2025
@github-actions github-actions bot removed the request-ci Add this label to start a Jenkins CI on a PR. label Feb 5, 2025
@nodejs-github-bot
Copy link
Collaborator

965022-oss referenced this pull request Feb 5, 2025
PR-URL: #56469
Reviewed-By: Jacob Smith <jacob@frende.me>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Bryan English <bryan@bryanenglish.com>
@nodejs-github-bot
Copy link
Collaborator

@cjihrig cjihrig added author ready PRs that have at least one approval, no pending requests for changes, and a CI started. commit-queue Add this label to land a pull request using GitHub Actions. and removed needs-ci PRs that need a full CI run. commit-queue-squash Add this label to instruct the Commit Queue to squash all the PR commits into the first one. labels Feb 5, 2025
Copy link
Contributor

@cjihrig cjihrig left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks again.

@nodejs-github-bot nodejs-github-bot removed the commit-queue Add this label to land a pull request using GitHub Actions. label Feb 5, 2025
@nodejs-github-bot nodejs-github-bot merged commit cebf4c8 into nodejs:main Feb 5, 2025
61 checks passed
@nodejs-github-bot
Copy link
Collaborator

Landed in cebf4c8

targos pushed a commit that referenced this pull request Feb 7, 2025
PR-URL: #56840
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
author ready PRs that have at least one approval, no pending requests for changes, and a CI started. c++ Issues and PRs that require attention from people who are familiar with C++. sqlite Issues and PRs related to the SQLite subsystem.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants