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

未關閉
#67,798 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
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 小時
30 天內合併 PR
266

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

nodejs/node 的其他 Issue

查看 nodejs/node 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。