Commit ffc57f007f6 for nodejs

commit ffc57f007f6037e2b8f423795499e656a98bce50
Author: Jiawen Geng <technicalcute@gmail.com>
Date:   Wed Nov 25 20:23:02 2026 +0800

    sqlite: guard re-entrant reset of a virtual table cursor

    StatementIterator::Return() and SQLTagStore::ResetAndBindStatement()
    called sqlite3_reset() without a SteppingStatementGuard. Resetting a
    statement with an open virtual-table cursor runs the generator's
    finally block, and that JavaScript can reset the same statement
    again. SQLite then halts the VM a second time while the cursor slot
    still points at the cursor, so xClose frees the same NodeVTabCursor
    twice.

    Hold the stepping guard across those resets so the re-entrant call
    fails with "statement is already being executed" instead of closing
    the cursor again. Ignore a second xClose on a cursor that is already
    closing.

    Assisted-by: Cursor Grok 4.7
    Signed-off-by: gengjiawen <technicalcute@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/67540
    Reviewed-By: Colin Ihrig <cjihrig@gmail.com>

diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc
index 59f7dd5818b..1622916edc0 100644
--- a/src/node_sqlite.cc
+++ b/src/node_sqlite.cc
@@ -1298,6 +1298,7 @@ int VirtualTableModule::xOpen(sqlite3_vtab* pVTab,
   cursor->hidden_values.assign(vtab->module->num_columns_, nullptr);
   cursor->rowid = 0;
   cursor->done = true;
+  cursor->closing = false;
   *ppCursor = &cursor->base;
   return SQLITE_OK;
 }
@@ -1306,6 +1307,15 @@ int VirtualTableModule::xClose(sqlite3_vtab_cursor* pCursor) {
   NodeVTabCursor* cursor = reinterpret_cast<NodeVTabCursor*>(pCursor);
   VirtualTableModule* mod = cursor->module;

+  // sqlite3_reset() from the iterator's return() can halt this VM again
+  // before the cursor slot is cleared, so xClose would run twice and free
+  // the cursor twice. The stepping guard rejects that re-entry; ignore a
+  // second close here as well.
+  if (cursor->closing) {
+    return SQLITE_OK;
+  }
+  cursor->closing = true;
+
   // Close the iterator so generator `finally` blocks still run when SQLite
   // stops stepping early, as it does for LIMIT or a `break` out of a for...of
   // loop. SQLite discards xClose's return value, so a throwing cleanup is
@@ -4467,6 +4477,10 @@ bool SQLTagStore::ResetAndBindStatement(
     Statement* stmt,
     const FunctionCallbackInfo<Value>& args) {
   Isolate* isolate = env->isolate();
+  // sqlite3_reset() closes an open virtual-table cursor, and xClose runs the
+  // generator's return() in JavaScript. Hold the stepping guard so a nested
+  // reset of this same statement fails instead of freeing that cursor twice.
+  SteppingStatementGuard stepping(stmt->db_.get(), stmt->statement_.get());
   int r = stmt->ResetStatement();
   CHECK_ERROR_OR_THROW(isolate, stmt->db_.get(), r, SQLITE_OK, false);

@@ -4567,6 +4581,11 @@ void SQLTagStore::All(const FunctionCallbackInfo<Value>& args) {
   }
   Environment* env = Environment::GetCurrent(args);

+  // PrepareForExecution() holds the guard for its own reset, but this one
+  // also spans the reset below, which runs on the error path and can close
+  // a virtual-table cursor as well.
+  SteppingStatementGuard stepping(stmt->db_.get(), stmt->statement_.get());
+
   Isolate* isolate = env->isolate();
   bool needs_reset = true;
   auto reset = OnScopeLeave([&]() {
@@ -4889,6 +4908,11 @@ void StatementIterator::Return(const FunctionCallbackInfo<Value>& args) {
     // is invoked by the language during abrupt completion (e.g. a `throw`
     // inside a `for...of` body), and throwing on a deferred SQLite error
     // would discard the caller's already-pending exception.
+    // sqlite3_reset() closes an open virtual-table cursor and runs its
+    // generator's return() in JavaScript. The guard makes a nested reset of
+    // this same statement fail instead of freeing that cursor twice.
+    SteppingStatementGuard stepping(iter->stmt_->db_.get(),
+                                    iter->stmt_->statement_.get());
     sqlite3_reset(iter->stmt_->statement_.get());
   }
   iter->done_ = true;
diff --git a/src/node_sqlite.h b/src/node_sqlite.h
index 460e9a4a8bc..11ee35741b9 100644
--- a/src/node_sqlite.h
+++ b/src/node_sqlite.h
@@ -696,6 +696,9 @@ struct NodeVTabCursor {
   std::vector<sqlite3_value*> hidden_values;
   sqlite3_int64 rowid;
   bool done;
+  // Set while xClose is running. A nested sqlite3_reset() can otherwise call
+  // xClose on this same cursor again and free it twice.
+  bool closing = false;
 };

 class VirtualTableModule {
diff --git a/test/parallel/test-sqlite-virtual-table.js b/test/parallel/test-sqlite-virtual-table.js
index 8e55a0ea444..5f8c9057a79 100644
--- a/test/parallel/test-sqlite-virtual-table.js
+++ b/test/parallel/test-sqlite-virtual-table.js
@@ -1090,4 +1090,116 @@ suite('Database.prototype.createModule()', () => {
       db.close();
     });
   });
+
+  suite('re-entrant reset of a virtual table cursor', () => {
+    // xClose runs the generator's return(). Resetting that same statement
+    // from `finally` must fail instead of closing the cursor twice.
+    function moduleWithFinally(db, name, onFinally) {
+      db.createModule(name, {
+        columns: [{ name: 'v', type: 'INTEGER' }],
+        *rows() {
+          try {
+            yield [1];
+            yield [2];
+          } finally {
+            onFinally();
+          }
+        },
+      });
+    }
+
+    test('iterator.return() from finally throws instead of crashing', () => {
+      const db = new Database(':memory:');
+      let it;
+      let caught;
+      moduleWithFinally(db, 'gen_return', () => {
+        try {
+          it.return();
+        } catch (err) {
+          caught = err;
+        }
+      });
+      it = db.prepare('SELECT v FROM gen_return').iterate();
+      assert.strictEqual(it.next().value.v, 1);
+      assert.strictEqual(it.return().done, true);
+      assert.strictEqual(caught.code, 'ERR_INVALID_STATE');
+      assert.strictEqual(
+        caught.message,
+        'statement is already being executed',
+      );
+      db.close();
+    });
+
+    test('statement.get() from finally throws instead of crashing', () => {
+      const db = new Database(':memory:');
+      let stmt;
+      let caught;
+      moduleWithFinally(db, 'gen_get', () => {
+        try {
+          stmt.get();
+        } catch (err) {
+          caught = err;
+        }
+      });
+      stmt = db.prepare('SELECT v FROM gen_get');
+      const it = stmt.iterate();
+      assert.strictEqual(it.next().value.v, 1);
+      assert.strictEqual(it.return().done, true);
+      assert.strictEqual(caught.code, 'ERR_INVALID_STATE');
+      assert.strictEqual(
+        caught.message,
+        'statement is already being executed',
+      );
+      db.close();
+    });
+
+    test('tagged get() from finally throws instead of crashing', () => {
+      const db = new Database(':memory:');
+      const sql = db.createTagStore();
+      let caught;
+      moduleWithFinally(db, 'gen_tag', () => {
+        try {
+          sql.get`SELECT v FROM gen_tag`; // eslint-disable-line no-unused-expressions
+        } catch (err) {
+          caught = err;
+        }
+      });
+      const it = sql.iterate`SELECT v FROM gen_tag`;
+      assert.strictEqual(it.next().value.v, 1);
+      assert.strictEqual(sql.get`SELECT v FROM gen_tag`.v, 1);
+      assert.strictEqual(caught.code, 'ERR_INVALID_STATE');
+      assert.strictEqual(
+        caught.message,
+        'statement is already being executed',
+      );
+      db.close();
+    });
+
+    test('for...of break that queries again throws instead of crashing', () => {
+      const db = new Database(':memory:');
+      let stmt;
+      let caught;
+      moduleWithFinally(db, 'gen_break', () => {
+        try {
+          stmt.get();
+        } catch (err) {
+          caught = err;
+        }
+      });
+      stmt = db.prepare('SELECT v FROM gen_break');
+      let seen = 0;
+      for (const row of stmt.iterate()) {
+        assert.strictEqual(row.v, 1);
+        seen++;
+        break;
+      }
+      assert.strictEqual(seen, 1);
+      assert.strictEqual(caught.code, 'ERR_INVALID_STATE');
+      assert.strictEqual(
+        caught.message,
+        'statement is already being executed',
+      );
+      db.close();
+    });
+  });
 });