V8: a GC inside a fast API call skips the stacks of threads archived by v8::Unlocker (use-after-free)

オープン
#67,798 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
45/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
cpp, javascript, node.js

調査の方向性

Start with deps/v8/src/execution/frames.cc, especially StackFrameIterator::Reset(ThreadLocalTop* top), and compare how it handles the current thread and archived thread tops. The issue includes a three-file native addon reproduction; build it against the v26.13.1 V8 headers and run node --allow-natives-syntax repro.js 15 fast turbofan. Done means the reproducer prints pass and archived stack roots remain valid during GC; check Deoptimizer::DeoptimizeMarkedCode too, since it uses the same reset.

索引モデルが issue の本文から書いたものです。

説明

Version

v26.13.1 (V8 14.6.202.34-node.40)

Platform
Microsoft Windows 11 Pro 10.0.26200 x64
Subsystem

v8

What steps will reproduce the bug?

A native addon unlocks the isolate on the main thread (v8::Unlocker) and runs a Turbofan-optimized
function on a second thread that locks it (v8::Locker). The function calls a fast API callback that
allocates through FastApiCallbackOptions::isolate, so scavenges run inside the fast call. The main
thread keeps young objects in a JS frame and checks them when control returns.

  1. Save the three files below in one folder. Point include_dirs in binding.gyp at deps/v8/include
    of the v26.13.1 sources, because the Node headers do not ship v8-fast-api-calls.h.
  2. node-gyp --target=26.13.1 rebuild
  3. node --allow-natives-syntax repro.js 15 fast turbofan
locker_repro.cc
#include <node.h>
#include <v8-fast-api-calls.h>
#include <cstring>
#include <thread>

using namespace v8;

namespace {

void Allocate(Isolate* isolate, int32_t count) {
  static uint8_t chars[4096];
  if (chars[0] == 0) memset(chars, 'a', sizeof(chars));
  HandleScope scope(isolate);
  for (int32_t i = 0; i < count; ++i) {
    String::NewFromOneByte(isolate, chars, NewStringType::kNormal, sizeof(chars))
        .ToLocalChecked();
  }
}

int32_t FastAlloc(Local<Value> receiver, int32_t count, FastApiCallbackOptions& options) {
  Allocate(options.isolate, count);
  return count;
}

void SlowAlloc(const FunctionCallbackInfo<Value>& args) {
  int32_t count = args[0].As<Int32>()->Value();
  Allocate(args.GetIsolate(), count);
  args.GetReturnValue().Set(count);
}

CFunction fast_alloc(CFunction::Make(FastAlloc));

// runOnThread(fn): unlock here, call fn() on another thread that locks the isolate.
void RunOnThread(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Global<Context> context(isolate, isolate->GetCurrentContext());
  Global<Function> fn(isolate, args[0].As<Function>());
  {
    Unlocker unlocker(isolate);
    std::thread thread([&] {
      Locker locker(isolate);
      Isolate::Scope isolate_scope(isolate);
      HandleScope scope(isolate);
      Local<Context> ctx = context.Get(isolate);
      Context::Scope context_scope(ctx);
      TryCatch try_catch(isolate);
      (void)fn.Get(isolate)->Call(ctx, ctx->Global(), 0, nullptr);
    });
    thread.join();
  }
}

void Init(Local<Object> exports) {
  Isolate* isolate = Isolate::GetCurrent();
  Local<Context> context = isolate->GetCurrentContext();
  Local<FunctionTemplate> alloc = FunctionTemplate::New(
      isolate, SlowAlloc, Local<Value>(), Local<Signature>(), 0,
      ConstructorBehavior::kThrow, SideEffectType::kHasSideEffect, &fast_alloc);
  exports->Set(context, String::NewFromUtf8Literal(isolate, "alloc"),
               alloc->GetFunction(context).ToLocalChecked()).Check();
  exports->Set(context, String::NewFromUtf8Literal(isolate, "allocSlow"),
               FunctionTemplate::New(isolate, SlowAlloc)->GetFunction(context).ToLocalChecked()).Check();
  exports->Set(context, String::NewFromUtf8Literal(isolate, "runOnThread"),
               FunctionTemplate::New(isolate, RunOnThread)->GetFunction(context).ToLocalChecked()).Check();
}

}  // namespace

NODE_MODULE(locker_repro, Init)
repro.js
'use strict';
const addon = require('./build/Release/locker_repro.node');
const seconds = Number(process.argv[2] || 20);
const mode = process.argv[3] || 'fast';
const tier = process.argv[4] || 'turbofan';

function workFast() {
  let total = 0;
  for (let i = 0; i < 64; ++i) total += addon.alloc(16);
  return total;
}
function workSlow() {
  let total = 0;
  for (let i = 0; i < 64; ++i) total += addon.allocSlow(16);
  return total;
}

const work = mode === 'fast' ? workFast : workSlow;
%PrepareFunctionForOptimization(work);
work(); work();
if (tier === 'maglev') %OptimizeMaglevOnNextCall(work); else %OptimizeFunctionOnNextCall(work);
work();

function hold(round) {
  const o = {round, list: [round, round + 1], name: 'round ' + round};
  addon.runOnThread(work);   // main thread is archived while `work` runs on another thread
  if (o.round !== round || o.list[1] !== round + 1 || o.name !== 'round ' + round) {
    throw new Error(`stale object in round ${round}`);
  }
}

const end = Date.now() + seconds * 1000;
let round = 0;
while (Date.now() < end) hold(round++);
console.log(`pass, rounds ${round}`);
binding.gyp
{
  'targets': [
    {
      'target_name': 'locker_repro',
      'sources': [ 'locker_repro.cc' ],
      # node does not ship v8-fast-api-calls.h; take it from the V8 of the same Node version
      'include_dirs': [ '<path to node v26.13.1 sources>/deps/v8/include' ],
    },
  ],
}
How often does it reproduce? Is there a required condition?

Every run, within about 60 ms. It needs the fast API call: repro.js 15 slow turbofan (a regular API
callback) passes.

What is the expected behavior? Why is that the expected behavior?

pass, rounds N. The main thread's stack is archived by v8::Unlocker, and the GC must visit it as a
root, so the objects held in hold() stay valid.

What do you see instead?

The official v26.13.1 binary exits with code -1073741819 (0xC0000005, access violation) and never
prints pass.

Additional information

Cause (V8): StackFrameIterator::Reset(ThreadLocalTop* top) in deps/v8/src/execution/frames.cc
starts the walk from isolate_->isolate_data()->fast_c_call_caller_fp() also for an archived top.
That value belongs to the thread holding the lock. A GC inside a fast call therefore walks the current
stack again for every archived thread, and never visits the archived stacks:

  • objects referenced only from them are freed;
  • objects also reachable from the heap are moved, and the archived frames keep their old addresses.

Deoptimizer::DeoptimizeMarkedCode uses the same Reset for archived threads.

Fix (passes the repro; our production workload no longer crashes):

-  const Address fast_c_call_caller_fp =
-      isolate_->isolate_data()->fast_c_call_caller_fp();
+  // The fast C call belongs to the current thread; an archived thread is walked
+  // from its own c_entry_fp.
+  const Address fast_c_call_caller_fp =
+      top == isolate_->thread_local_top()
+          ? isolate_->isolate_data()->fast_c_call_caller_fp()
+          : kNullAddress;

Workaround: --no-turbo-fast-api-calls.

V8: reported upstream as https://issues.chromium.org/issues/590742958; the code is unchanged on V8
main. Chrome VRP closed the security report because Chrome does not share an isolate between threads,
so it is filed there as a functional bug. In Node it takes a native addon that uses v8::Locker
(for example node-fibers, where we hit it in production), which Node's threat model trusts, so I am
filing it here publicly.

Could you consider floating the fix on v26.x (and any other line with V8 14) until V8 picks it up?

主要言語
JavaScript
スター
124k
フォーク
38k
平均マージ
4日 2時間
マージ済み PR(30日)
266

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

nodejs/node のほかの issue

nodejs/node の issue をすべて見る

似ている issue

JavaScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。