【问题标题】:V8 Segfault when using Global with Value使用带值的全局时的 V8 段错误
【发布时间】:2018-12-30 23:20:12
【问题描述】:

我开始嵌入 v8,但遇到了一些“意外行为”。当变量 value_ 最后不是 Reset 时,以下代码生成 Segmentation fault (core dumped)(请参阅代码中的注释)。但是,这不适用于上下文context_。为什么? This answer 似乎是相关的,但没有提供解释。

我的期望是isolate->Dispose() 兼顾两者。

#include <stdlib.h>

#include "include/libplatform/libplatform.h"
#include "include/v8.h"

int main(int argc, char* argv[]) {
  v8::V8::InitializeICUDefaultLocation(argv[0]);
  v8::V8::InitializeExternalStartupData(argv[0]);
  std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(platform.get());
  v8::V8::Initialize();

  {
    // Initialize V8.
    // Create a new Isolate and make it the current one.
    v8::Isolate::CreateParams create_params;
    create_params.array_buffer_allocator =
        v8::ArrayBuffer::Allocator::NewDefaultAllocator();

    v8::Isolate* isolate = v8::Isolate::New(create_params);
    v8::Global<v8::Context> context_;
    v8::Global<v8::String> value_;
    {
      // Global Context Setup
      v8::Isolate::Scope isolate_scope(isolate);
      v8::HandleScope handle_scope(isolate);

      v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);

      v8::Local<v8::Context> context = v8::Context::New(isolate, NULL, global);
      context_.Reset(isolate, context);

      // Global Value Setup
      v8::Context::Scope context_scope(context);
      v8::Local<v8::String> value = v8::String::NewFromUtf8(isolate, "segfault", v8::NewStringType::kNormal).ToLocalChecked();
      value_.Reset(isolate, value);
    }

    // value_.Reset(); // <- Why is this line needed?
    // context_.Reset(); // <- Why is this line NOT needed?
    isolate->Dispose();
    delete create_params.array_buffer_allocator;
  }

  v8::V8::Dispose();
  v8::V8::ShutdownPlatform();
  return 0;
}

构建设置:

按照官方Getting started with embedding V8运行示例中的说明进行操作。将代码保存到 sample/wasm.cc 并执行以下命令:

$ g++ -I. -O2 -Iinclude samples/segfault.cc -o segfault  -lv8_monolith -Lout.gn/x64.release.sample/obj/ -pthread -std=c++17
$ ./segfault

【问题讨论】:

    标签: c++ v8 embedded-v8


    【解决方案1】:

    因此,如果你不调用Global::Reset(),而是DisposeIsolate在销毁一个Global之前,Global的析构函数会导致一个access-after-free,这是一个典型的未定义行为。

    Reset() 将内部指针设置为nullptr,随后的调用将检查这个事实并且不做任何事情。这就是为什么您可以在Dispose() 之前添加Reset() 以避免UB。

    对于您的 Global&lt;Context&gt; 也是如此,它不会自我证明,因为 access-after-free 并不总是会触发段错误。

    【讨论】:

    • 有什么原因,为什么Global::Reset()在调用Isolate::Dispose()时没有在所有注册的全局对象上自动调用?
    • @mhk Global 本质上包含一个指向存储节点的指针。 Isolate 无法更改该指针值。因为Isolate 不知道Global 在用户代码中的位置。
    猜你喜欢
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2014-12-17
    • 2021-12-24
    相关资源
    最近更新 更多