透過 V8 Inspector 協定除錯
V8 提供廣泛的除錯功能給使用者和嵌入式程式設計人員。使用者通常會透過 Chrome DevTools 介面與 V8 除錯工具互動。嵌入式程式設計人員(包括 DevTools)需要直接仰賴 Inspector 協定。
此頁面旨在提供嵌入式程式設計人員在 V8 中實作除錯支援所需的基本工具。
連線到 Inspector #
V8 的 命令列除錯殼層 d8
包含一個透過 InspectorFrontend
和 InspectorClient
進行簡單的 Inspector 整合。客戶端會設定一個通訊管道,以便將訊息從嵌入式程式設計人員傳送至 V8
static void SendInspectorMessage(
const v8::FunctionCallbackInfo<v8::Value>& args) {
// [...] Create a StringView that Inspector can understand.
session->dispatchProtocolMessage(message_view);
}
同時,前端會透過實作 sendResponse
和 sendNotification
(然後轉送至)來建立一個管道,以便將訊息從 V8 傳送至嵌入式程式設計人員
void Send(const v8_inspector::StringView& string) {
// [...] String transformations.
// Grab the global property called 'receive' from the current context.
Local<String> callback_name =
v8::String::NewFromUtf8(isolate_, "receive", v8::NewStringType::kNormal)
.ToLocalChecked();
Local<Context> context = context_.Get(isolate_);
Local<Value> callback =
context->Global()->Get(context, callback_name).ToLocalChecked();
// And call it to pass the message on to JS.
if (callback->IsFunction()) {
// [...]
MaybeLocal<Value> result = Local<Function>::Cast(callback)->Call(
context, Undefined(isolate_), 1, args);
}
}
使用 Inspector 協定 #
延續我們的範例,d8
會將 Inspector 訊息轉送至 JavaScript。下列程式碼透過 d8
實作一個基本但功能齊全的 Inspector 互動
// inspector-demo.js
// Receiver function called by d8.
function receive(message) {
print(message)
}
const msg = JSON.stringify({
id: 0,
method: 'Debugger.enable',
});
// Call the function provided by d8.
send(msg);
// Run this file by executing 'd8 --enable-inspector inspector-demo.js'.
進一步的文件 #
可以在 test-api.js
找到 Inspector API 使用的更詳細範例,它實作一個簡單的除錯 API 供 V8 的測試套件使用。
V8 也包含一個替代的 Inspector 整合,位於 inspector-test.cc
。
Chrome DevTools wiki 提供所有可用功能的 完整文件。