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

Đang mở
#67,798 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
45/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
cpp, javascript, node.js
Lĩnh vực
backend, testing-qa

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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?

Ngôn ngữ chính
JavaScript
Star
124k
Fork
38k
Merge trung bình
4 ngày 2 giờ
Pull request đã merge (30 ngày)
266

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của nodejs/node

Tất cả issue của nodejs/node

Issue tương tự

Thêm issue về JavaScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.