Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions NativeScript/inspector/InspectorModule.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#ifndef InspectorModule_h
#define InspectorModule_h

#include "include/v8.h"

namespace v8_inspector {

// The natives of the ns:inspector builtin module (runtime/js/ns-inspector.js).
// Built in every isolate; `available` is false where no frontend can attach:
// release builds and workers.
v8::MaybeLocal<v8::Object> NsInspectorBinding(v8::Local<v8::Context> context);

} // namespace v8_inspector

#endif /* InspectorModule_h */
347 changes: 347 additions & 0 deletions NativeScript/inspector/InspectorModule.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,347 @@
#include "InspectorModule.h"

#include <mach/mach_time.h>

#include <chrono>
#include <memory>
#include <string>
#include <vector>

#include "Helpers.h"
#include "JsV8InspectorClient.h"
#include "include/inspector/Runtime.h"
#include "utils.h"
#include "third_party/inspector_protocol/crdtp/json.h"

using namespace v8;

namespace v8_inspector {

namespace {

StringView Make8BitStringView(const std::string& value) {
return StringView(reinterpret_cast<const uint8_t*>(value.data()), value.size());
}

void ThrowError(Isolate* isolate, const std::string& message) {
isolate->ThrowException(Exception::Error(tns::ToV8String(isolate, message)));
}

JsV8InspectorClient* ClientOrThrow(Isolate* isolate) {
JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate);
if (client == nullptr) {
ThrowError(isolate, "The inspector is not available");
}
return client;
}

// The session of the frontend the first argument names, or null with an
// exception set.
V8InspectorSession* SessionOrThrow(const FunctionCallbackInfo<Value>& info,
JsV8InspectorClient* client) {
Isolate* isolate = info.GetIsolate();
if (info.Length() < 1 || !info[0]->IsNumber()) {
ThrowError(isolate, "Invalid session");
return nullptr;
}
auto connectionId = static_cast<uint64_t>(info[0].As<Number>()->Value());
V8InspectorSession* session = client->SessionFor(connectionId);
if (session == nullptr) {
ThrowError(isolate, "The session is closed");
}
return session;
}

// A protocol object as the JSON value a frontend would receive. V8 only
// serializes them to CBOR.
template <typename T>
MaybeLocal<Value> ToValue(Local<Context> context, const T& object) {
std::vector<uint8_t> cbor;
object.AppendSerialized(&cbor);
std::string json;
if (!v8_crdtp::json::ConvertCBORToJSON(v8_crdtp::SpanFrom(cbor), &json).ok()) {
return MaybeLocal<Value>();
}
return JSON::Parse(context, tns::ToV8String(Isolate::GetCurrent(), json));
}

class FunctionInspectable final : public V8InspectorSession::Inspectable {
public:
FunctionInspectable(Isolate* isolate, Local<Function> getter)
: isolate_(isolate), getter_(isolate, getter) {}

Local<Value> get(Local<Context> context) override {
EscapableHandleScope scope(isolate_);
TryCatch tc(isolate_);
Local<Value> value;
if (!getter_.Get(isolate_)->Call(context, Undefined(isolate_), 0, nullptr).ToLocal(&value)) {
return scope.Escape(Undefined(isolate_).As<Value>());
}
return scope.Escape(value);
}

private:
Isolate* isolate_;
Global<Function> getter_;
};

void AttachCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = ClientOrThrow(isolate);
if (client == nullptr) {
return;
}
if (info.Length() < 1 || !info[0]->IsObject()) {
ThrowError(isolate, "attach expects a router");
return;
}
client->SetJsDomainRouter(info[0].As<Object>());
}

void RegisterCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = ClientOrThrow(isolate);
if (client == nullptr) {
return;
}
std::string name = tns::ToString(isolate, info[0]);
std::vector<uint64_t> enabledBefore;
std::string error;
if (!client->RegisterJsDomain(name, enabledBefore, error)) {
ThrowError(isolate, error);
return;
}
Local<Context> context = isolate->GetCurrentContext();
Local<Array> result = Array::New(isolate, static_cast<int>(enabledBefore.size()));
for (size_t i = 0; i < enabledBefore.size(); i++) {
result
->Set(context, static_cast<uint32_t>(i),
Number::New(isolate, static_cast<double>(enabledBefore[i])))
.Check();
}
info.GetReturnValue().Set(result);
}

// Throws for a domain the runtime implements, with or without a client.
void CheckDomainCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
std::string name = tns::ToString(isolate, info[0]);
if (JsV8InspectorClient::IsRuntimeDomain(name)) {
ThrowError(isolate, "The " + name + " domain is implemented by the runtime");
}
}

void UnregisterCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate);
if (client == nullptr) {
return;
}
std::vector<uint64_t> enabled;
if (info.Length() > 1 && info[1]->IsArray()) {
Local<Context> context = isolate->GetCurrentContext();
Local<Array> ids = info[1].As<Array>();
for (uint32_t i = 0; i < ids->Length(); i++) {
Local<Value> id;
if (ids->Get(context, i).ToLocal(&id) && id->IsNumber()) {
enabled.push_back(static_cast<uint64_t>(id.As<Number>()->Value()));
}
}
}
client->UnregisterJsDomain(tns::ToString(isolate, info[0]), enabled);
}

void ConnectionsCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
std::vector<uint64_t> connections;
if (JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate)) {
connections = client->Connections();
}
Local<Array> result = Array::New(isolate, static_cast<int>(connections.size()));
for (size_t i = 0; i < connections.size(); i++) {
result
->Set(context, static_cast<uint32_t>(i),
Number::New(isolate, static_cast<double>(connections[i])))
.Check();
}
info.GetReturnValue().Set(result);
}

void SendCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate);
if (client == nullptr || info.Length() < 2 || !info[0]->IsNumber() || !info[1]->IsString()) {
return;
}
auto connectionId = static_cast<uint64_t>(info[0].As<Number>()->Value());
client->SendRawToConnection(connectionId, tns::ToString(isolate, info[1]));
}

void WrapObjectCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = ClientOrThrow(isolate);
if (client == nullptr) {
return;
}
V8InspectorSession* session = SessionOrThrow(info, client);
if (session == nullptr) {
return;
}
Local<Context> context = isolate->GetCurrentContext();
std::string group = info.Length() > 2 && info[2]->IsString() ? tns::ToString(isolate, info[2])
: std::string();
bool preview = info.Length() > 3 && info[3]->BooleanValue(isolate);
std::unique_ptr<protocol::Runtime::API::RemoteObject> remote =
session->wrapObject(context, info[1], Make8BitStringView(group), preview);
if (remote == nullptr) {
ThrowError(isolate, "The value cannot be wrapped");
return;
}
Local<Value> result;
if (!ToValue(context, *remote).ToLocal(&result)) {
if (!isolate->IsExecutionTerminating()) {
ThrowError(isolate, "The value cannot be wrapped");
}
return;
}
info.GetReturnValue().Set(result);
}

void UnwrapObjectCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = ClientOrThrow(isolate);
if (client == nullptr) {
return;
}
V8InspectorSession* session = SessionOrThrow(info, client);
if (session == nullptr) {
return;
}
if (info.Length() < 2 || !info[1]->IsString()) {
ThrowError(isolate, "Invalid remote object id");
return;
}
std::string objectId = tns::ToString(isolate, info[1]);
std::unique_ptr<StringBuffer> error;
Local<Value> value;
Local<Context> context;
if (!session->unwrapObject(&error, Make8BitStringView(objectId), &value, &context, nullptr)) {
std::string message = error != nullptr ? ToStdString(error->string()) : std::string();
ThrowError(isolate, message.empty() ? "Could not find object with given id" : message);
return;
}
info.GetReturnValue().Set(value);
}

void ReleaseObjectGroupCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = ClientOrThrow(isolate);
if (client == nullptr) {
return;
}
V8InspectorSession* session = SessionOrThrow(info, client);
if (session == nullptr) {
return;
}
session->releaseObjectGroup(Make8BitStringView(tns::ToString(isolate, info[1])));
}

void AddInspectedObjectCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = ClientOrThrow(isolate);
if (client == nullptr) {
return;
}
V8InspectorSession* session = SessionOrThrow(info, client);
if (session == nullptr) {
return;
}
if (info.Length() < 2 || !info[1]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(
tns::ToV8String(isolate, "addInspectedObject expects a function")));
return;
}
session->addInspectedObject(
std::make_unique<FunctionInspectable>(isolate, info[1].As<Function>()));
}

void CaptureStackTraceCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate);
if (client == nullptr) {
return;
}
std::unique_ptr<V8StackTrace> trace = client->Inspector()->captureStackTrace(true);
if (trace == nullptr || trace->isEmpty()) {
return;
}
Local<Value> result;
if (ToValue(isolate->GetCurrentContext(), *trace->buildInspectorObject(0)).ToLocal(&result)) {
info.GetReturnValue().Set(result);
}
}

// Network.MonotonicTime: seconds on the clock the platform's TimeTicks, and
// with them trace events, use on Darwin.
void MonotonicTimeCallback(const FunctionCallbackInfo<Value>& info) {
static mach_timebase_info_data_t timebase = [] {
mach_timebase_info_data_t value;
mach_timebase_info(&value);
return value;
}();
double nanoseconds =
static_cast<double>(mach_absolute_time()) * timebase.numer / timebase.denom;
info.GetReturnValue().Set(nanoseconds / 1e9);
}

// Network.TimeSinceEpoch: seconds, fractional.
void WallTimeCallback(const FunctionCallbackInfo<Value>& info) {
info.GetReturnValue().Set(std::chrono::duration<double>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}

void LogErrorCallback(const FunctionCallbackInfo<Value>& info) {
Log(@"ns:inspector: %s", tns::ToString(info.GetIsolate(), info[0]).c_str());
}

} // namespace

MaybeLocal<Object> NsInspectorBinding(Local<Context> context) {
Isolate* isolate = Isolate::GetCurrent();
Local<Object> binding = Object::New(isolate);
bool available = JsV8InspectorClient::ForIsolate(isolate) != nullptr;
if (!binding
->Set(context, tns::ToV8String(isolate, "available"), v8::Boolean::New(isolate, available))
.FromMaybe(false)) {
return MaybeLocal<Object>();
}

const std::pair<const char*, FunctionCallback> natives[] = {
{"attach", AttachCallback},
{"checkDomain", CheckDomainCallback},
{"register", RegisterCallback},
{"unregister", UnregisterCallback},
{"connections", ConnectionsCallback},
{"send", SendCallback},
{"wrapObject", WrapObjectCallback},
{"unwrapObject", UnwrapObjectCallback},
{"releaseObjectGroup", ReleaseObjectGroupCallback},
{"addInspectedObject", AddInspectedObjectCallback},
{"captureStackTrace", CaptureStackTraceCallback},
{"monotonicTime", MonotonicTimeCallback},
{"wallTime", WallTimeCallback},
{"logError", LogErrorCallback},
};
for (const auto& native : natives) {
Local<Function> function;
if (!Function::New(context, native.second).ToLocal(&function) ||
!binding->Set(context, tns::ToV8String(isolate, native.first), function).FromMaybe(false)) {
return MaybeLocal<Object>();
}
}
return binding;
}

} // namespace v8_inspector
3 changes: 3 additions & 0 deletions NativeScript/inspector/InspectorSessions.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ class InspectorSessions {

bool Has(uint64_t connectionId) const;

// The frontend's session, or null once it is gone or closing.
V8InspectorSession* Find(uint64_t connectionId) const;

private:
class Channel;
struct Session {
Expand Down
5 changes: 5 additions & 0 deletions NativeScript/inspector/InspectorSessions.mm
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ void flushProtocolNotifications() override {}
return it != sessions_.end() && !it->second->closing;
}

V8InspectorSession* InspectorSessions::Find(uint64_t connectionId) const {
auto it = sessions_.find(connectionId);
return it != sessions_.end() && !it->second->closing ? it->second->session.get() : nullptr;
}

void InspectorSessions::Destroy(uint64_t connectionId) {
auto node = sessions_.extract(connectionId);
if (node.empty()) {
Expand Down
Loading
Loading