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

Aberta
#67,798 2 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
45/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
cpp, javascript, node.js
Domínio
backend, testing-qa

Direção de pesquisa

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.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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?

Linguagem predominante
JavaScript
Estrelas
124k
Forks
38k
Merge médio
4d 2h
PRs com merge (30d)
266

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de nodejs/node

Todas as issues de nodejs/node

Issues semelhantes

Mais issues de JavaScript

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.