我正在开始嵌入v8,遇到一些“意外行为”。当变量Segmentation fault (core dumped)
末尾不是value_
时,以下代码将生成Reset
(请参见代码中的注释)。但是,这不适用于上下文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
答案 0 :(得分:0)
v8::Global
有一个destructor,它将调用Reset()
。
全局句柄保存在Isolate
,the global handles will be freed之后的Isolate::Dispose()
中。
因此,如果您没有调用Global::Reset()
,而是在破坏Dispose
之前调用Isolate
Global
,则Global
的析构函数将导致免费访问,这是典型的未定义行为。
Reset()
将内部指针设置为nullptr
,随后的调用将检查此事实,并且不执行任何操作。因此,您可以在Reset()
之前添加Dispose()
来避免UB。
对于您的Global<Context>
来说也是如此,因为自由后访问并不总是会触发段错误,所以它不会演示自己。