GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: inspector_js_api.cc Lines: 198 219 90.4 %
Date: 2022-10-14 05:16:24 Branches: 45 96 46.9 %

Line Branch Exec Source
1
#include "base_object-inl.h"
2
#include "inspector_agent.h"
3
#include "inspector_io.h"
4
#include "memory_tracker-inl.h"
5
#include "node_external_reference.h"
6
#include "util-inl.h"
7
#include "v8-inspector.h"
8
#include "v8.h"
9
10
#include <memory>
11
12
namespace node {
13
namespace inspector {
14
namespace {
15
16
using v8::Context;
17
using v8::Function;
18
using v8::FunctionCallbackInfo;
19
using v8::FunctionTemplate;
20
using v8::Global;
21
using v8::HandleScope;
22
using v8::Isolate;
23
using v8::Local;
24
using v8::MaybeLocal;
25
using v8::NewStringType;
26
using v8::Object;
27
using v8::String;
28
using v8::Uint32;
29
using v8::Value;
30
31
using v8_inspector::StringBuffer;
32
using v8_inspector::StringView;
33
34
1241
std::unique_ptr<StringBuffer> ToProtocolString(Isolate* isolate,
35
                                               Local<Value> value) {
36
2482
  TwoByteValue buffer(isolate, value);
37
2482
  return StringBuffer::create(StringView(*buffer, buffer.length()));
38
}
39
40
struct LocalConnection {
41
924
  static std::unique_ptr<InspectorSession> Connect(
42
      Agent* inspector, std::unique_ptr<InspectorSessionDelegate> delegate) {
43
924
    return inspector->Connect(std::move(delegate), false);
44
  }
45
46
786
  static Local<String> GetClassName(Environment* env) {
47
786
    return FIXED_ONE_BYTE_STRING(env->isolate(), "Connection");
48
  }
49
};
50
51
struct MainThreadConnection {
52
2
  static std::unique_ptr<InspectorSession> Connect(
53
      Agent* inspector, std::unique_ptr<InspectorSessionDelegate> delegate) {
54
2
    return inspector->ConnectToMainThread(std::move(delegate), true);
55
  }
56
57
786
  static Local<String> GetClassName(Environment* env) {
58
786
    return FIXED_ONE_BYTE_STRING(env->isolate(), "MainThreadConnection");
59
  }
60
};
61
62
template <typename ConnectionType>
63
2775
class JSBindingsConnection : public AsyncWrap {
64
 public:
65
1850
  class JSBindingsSessionDelegate : public InspectorSessionDelegate {
66
   public:
67
926
    JSBindingsSessionDelegate(Environment* env,
68
                              JSBindingsConnection* connection)
69
                              : env_(env),
70
926
                                connection_(connection) {
71
926
    }
72
73
7191
    void SendMessageToFrontend(const v8_inspector::StringView& message)
74
        override {
75
7191
      Isolate* isolate = env_->isolate();
76
14382
      HandleScope handle_scope(isolate);
77

14382
      Context::Scope context_scope(env_->context());
78
      Local<Value> argument;
79

14382
      if (!String::NewFromTwoByte(isolate, message.characters16(),
80
                                  NewStringType::kNormal,
81
14382
                                  message.length()).ToLocal(&argument)) return;
82
7191
      connection_->OnMessage(argument);
83
    }
84
85
   private:
86
    Environment* env_;
87
    BaseObjectPtr<JSBindingsConnection> connection_;
88
  };
89
90
926
  JSBindingsConnection(Environment* env,
91
                       Local<Object> wrap,
92
                       Local<Function> callback)
93
                       : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING),
94
926
                         callback_(env->isolate(), callback) {
95
926
    Agent* inspector = env->inspector_agent();
96
926
    session_ = ConnectionType::Connect(
97
        inspector, std::make_unique<JSBindingsSessionDelegate>(env, this));
98
926
  }
99
100
7191
  void OnMessage(Local<Value> value) {
101
14382
    MakeCallback(callback_.Get(env()->isolate()), 1, &value);
102
7191
  }
103
104
1572
  static void Bind(Environment* env, Local<Object> target) {
105
1572
    Isolate* isolate = env->isolate();
106
1572
    Local<FunctionTemplate> tmpl =
107
1572
        NewFunctionTemplate(isolate, JSBindingsConnection::New);
108
3144
    tmpl->InstanceTemplate()->SetInternalFieldCount(
109
        JSBindingsConnection::kInternalFieldCount);
110
1572
    tmpl->Inherit(AsyncWrap::GetConstructorTemplate(env));
111
1572
    SetProtoMethod(isolate, tmpl, "dispatch", JSBindingsConnection::Dispatch);
112
1572
    SetProtoMethod(
113
        isolate, tmpl, "disconnect", JSBindingsConnection::Disconnect);
114
1572
    SetConstructorFunction(
115
        env->context(), target, ConnectionType::GetClassName(env), tmpl);
116
1572
  }
117
118
926
  static void New(const FunctionCallbackInfo<Value>& info) {
119
926
    Environment* env = Environment::GetCurrent(info);
120

1852
    CHECK(info[0]->IsFunction());
121
1852
    Local<Function> callback = info[0].As<Function>();
122
926
    new JSBindingsConnection(env, info.This(), callback);
123
926
  }
124
125
911
  void Disconnect() {
126
911
    session_.reset();
127

911
    delete this;
128
911
  }
129
130
911
  static void Disconnect(const FunctionCallbackInfo<Value>& info) {
131
    JSBindingsConnection* session;
132

911
    ASSIGN_OR_RETURN_UNWRAP(&session, info.Holder());
133
911
    session->Disconnect();
134
  }
135
136
1241
  static void Dispatch(const FunctionCallbackInfo<Value>& info) {
137
1241
    Environment* env = Environment::GetCurrent(info);
138
    JSBindingsConnection* session;
139

1241
    ASSIGN_OR_RETURN_UNWRAP(&session, info.Holder());
140

3723
    CHECK(info[0]->IsString());
141
142

1241
    if (session->session_) {
143
2482
      session->session_->Dispatch(
144
2482
          ToProtocolString(env->isolate(), info[0])->string());
145
    }
146
  }
147
148
2
  void MemoryInfo(MemoryTracker* tracker) const override {
149
2
    tracker->TrackField("callback", callback_);
150
2
    tracker->TrackFieldWithSize(
151
        "session", sizeof(*session_), "InspectorSession");
152
2
  }
153
154
2
  SET_MEMORY_INFO_NAME(JSBindingsConnection)
155
2
  SET_SELF_SIZE(JSBindingsConnection)
156
157
  bool IsNotIndicativeOfMemoryLeakAtExit() const override {
158
    return true;  // Binding connections emit events on their own.
159
  }
160
161
 private:
162
  std::unique_ptr<InspectorSession> session_;
163
  Global<Function> callback_;
164
};
165
166
71853
static bool InspectorEnabled(Environment* env) {
167
71853
  Agent* agent = env->inspector_agent();
168
71853
  return agent->IsActive();
169
}
170
171
786
void SetConsoleExtensionInstaller(const FunctionCallbackInfo<Value>& info) {
172
786
  auto env = Environment::GetCurrent(info);
173
174
786
  CHECK_EQ(info.Length(), 1);
175
1572
  CHECK(info[0]->IsFunction());
176
177
1572
  env->set_inspector_console_extension_installer(info[0].As<Function>());
178
786
}
179
180
8
void CallAndPauseOnStart(const FunctionCallbackInfo<v8::Value>& args) {
181
8
  Environment* env = Environment::GetCurrent(args);
182
8
  CHECK_GT(args.Length(), 1);
183
16
  CHECK(args[0]->IsFunction());
184
14
  SlicedArguments call_args(args, /* start */ 2);
185
8
  env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start");
186
  v8::MaybeLocal<v8::Value> retval =
187
22
      args[0].As<v8::Function>()->Call(env->context(), args[1],
188
16
                                       call_args.length(), call_args.out());
189
6
  if (!retval.IsEmpty()) {
190
10
    args.GetReturnValue().Set(retval.ToLocalChecked());
191
  }
192
6
}
193
194
71845
void InspectorConsoleCall(const FunctionCallbackInfo<Value>& info) {
195
71845
  Environment* env = Environment::GetCurrent(info);
196
71845
  Isolate* isolate = env->isolate();
197
71845
  Local<Context> context = isolate->GetCurrentContext();
198
71845
  CHECK_GE(info.Length(), 2);
199
143681
  SlicedArguments call_args(info, /* start */ 2);
200
71845
  if (InspectorEnabled(env)) {
201
71844
    Local<Value> inspector_method = info[0];
202
71844
    CHECK(inspector_method->IsFunction());
203
71844
    if (!env->is_in_inspector_console_call()) {
204
71843
      env->set_is_in_inspector_console_call(true);
205
      MaybeLocal<Value> ret =
206
143686
          inspector_method.As<Function>()->Call(context,
207
                                                info.Holder(),
208
71843
                                                call_args.length(),
209
215529
                                                call_args.out());
210
71843
      env->set_is_in_inspector_console_call(false);
211
71843
      if (ret.IsEmpty())
212
9
        return;
213
    }
214
  }
215
216
71836
  Local<Value> node_method = info[1];
217
71836
  CHECK(node_method->IsFunction());
218
215508
  USE(node_method.As<Function>()->Call(context,
219
                                   info.Holder(),
220
71836
                                   call_args.length(),
221
215508
                                   call_args.out()));
222
}
223
224
23
static void* GetAsyncTask(int64_t asyncId) {
225
  // The inspector assumes that when other clients use its asyncTask* API,
226
  // they use real pointers, or at least something aligned like real pointer.
227
  // In general it means that our task_id should always be even.
228
  //
229
  // On 32bit platforms, the 64bit asyncId would get truncated when converted
230
  // to a 32bit pointer. However, the javascript part will never enable
231
  // the async_hook on 32bit platforms, therefore the truncation will never
232
  // happen in practice.
233
23
  return reinterpret_cast<void*>(asyncId << 1);
234
}
235
236
template <void (Agent::*asyncTaskFn)(void*)>
237
20
static void InvokeAsyncTaskFnWithId(const FunctionCallbackInfo<Value>& args) {
238
20
  Environment* env = Environment::GetCurrent(args);
239

40
  CHECK(args[0]->IsNumber());
240
60
  int64_t task_id = args[0]->IntegerValue(env->context()).FromJust();
241
20
  (env->inspector_agent()->*asyncTaskFn)(GetAsyncTask(task_id));
242
20
}
243
244
3
static void AsyncTaskScheduledWrapper(const FunctionCallbackInfo<Value>& args) {
245
3
  Environment* env = Environment::GetCurrent(args);
246
247
9
  CHECK(args[0]->IsString());
248
6
  Local<String> task_name = args[0].As<String>();
249
6
  String::Value task_name_value(args.GetIsolate(), task_name);
250
3
  StringView task_name_view(*task_name_value, task_name_value.length());
251
252
6
  CHECK(args[1]->IsNumber());
253
9
  int64_t task_id = args[1]->IntegerValue(env->context()).FromJust();
254
3
  void* task = GetAsyncTask(task_id);
255
256
6
  CHECK(args[2]->IsBoolean());
257
9
  bool recurring = args[2]->BooleanValue(args.GetIsolate());
258
259
3
  env->inspector_agent()->AsyncTaskScheduled(task_name_view, task, recurring);
260
3
}
261
262
6297
static void RegisterAsyncHookWrapper(const FunctionCallbackInfo<Value>& args) {
263
6297
  Environment* env = Environment::GetCurrent(args);
264
265
12594
  CHECK(args[0]->IsFunction());
266
12594
  Local<Function> enable_function = args[0].As<Function>();
267
12594
  CHECK(args[1]->IsFunction());
268
12594
  Local<Function> disable_function = args[1].As<Function>();
269
6297
  env->inspector_agent()->RegisterAsyncHook(env->isolate(),
270
    enable_function, disable_function);
271
6297
}
272
273
8
void IsEnabled(const FunctionCallbackInfo<Value>& args) {
274
8
  Environment* env = Environment::GetCurrent(args);
275
16
  args.GetReturnValue().Set(InspectorEnabled(env));
276
8
}
277
278
void Open(const FunctionCallbackInfo<Value>& args) {
279
  Environment* env = Environment::GetCurrent(args);
280
  Agent* agent = env->inspector_agent();
281
282
  if (args.Length() > 0 && args[0]->IsUint32()) {
283
    uint32_t port = args[0].As<Uint32>()->Value();
284
    CHECK_LE(port, std::numeric_limits<uint16_t>::max());
285
    ExclusiveAccess<HostPort>::Scoped host_port(agent->host_port());
286
    host_port->set_port(static_cast<int>(port));
287
  }
288
289
  if (args.Length() > 1 && args[1]->IsString()) {
290
    Utf8Value host(env->isolate(), args[1].As<String>());
291
    ExclusiveAccess<HostPort>::Scoped host_port(agent->host_port());
292
    host_port->set_host(*host);
293
  }
294
295
  agent->StartIoThread();
296
}
297
298
void WaitForDebugger(const FunctionCallbackInfo<Value>& args) {
299
  Environment* env = Environment::GetCurrent(args);
300
  Agent* agent = env->inspector_agent();
301
  if (agent->IsActive())
302
    agent->WaitForConnect();
303
  args.GetReturnValue().Set(agent->IsActive());
304
}
305
306
6
void Url(const FunctionCallbackInfo<Value>& args) {
307
6
  Environment* env = Environment::GetCurrent(args);
308
11
  std::string url = env->inspector_agent()->GetWsUrl();
309
6
  if (url.empty()) {
310
1
    return;
311
  }
312
10
  args.GetReturnValue().Set(OneByteString(env->isolate(), url.c_str()));
313
}
314
315
786
void Initialize(Local<Object> target, Local<Value> unused,
316
                Local<Context> context, void* priv) {
317
786
  Environment* env = Environment::GetCurrent(context);
318
786
  Isolate* isolate = env->isolate();
319
320
  v8::Local<v8::Function> consoleCallFunc =
321
1572
      NewFunctionTemplate(isolate,
322
                          InspectorConsoleCall,
323
                          v8::Local<v8::Signature>(),
324
                          v8::ConstructorBehavior::kThrow,
325
786
                          v8::SideEffectType::kHasSideEffect)
326
1572
          ->GetFunction(context)
327
786
          .ToLocalChecked();
328
786
  auto name_string = FIXED_ONE_BYTE_STRING(isolate, "consoleCall");
329
2358
  target->Set(context, name_string, consoleCallFunc).Check();
330
786
  consoleCallFunc->SetName(name_string);
331
332
786
  SetMethod(context,
333
            target,
334
            "setConsoleExtensionInstaller",
335
            SetConsoleExtensionInstaller);
336
786
  SetMethod(context, target, "callAndPauseOnStart", CallAndPauseOnStart);
337
786
  SetMethod(context, target, "open", Open);
338
786
  SetMethodNoSideEffect(context, target, "url", Url);
339
786
  SetMethod(context, target, "waitForDebugger", WaitForDebugger);
340
341
786
  SetMethod(context, target, "asyncTaskScheduled", AsyncTaskScheduledWrapper);
342
786
  SetMethod(context,
343
            target,
344
            "asyncTaskCanceled",
345
            InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>);
346
786
  SetMethod(context,
347
            target,
348
            "asyncTaskStarted",
349
            InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>);
350
786
  SetMethod(context,
351
            target,
352
            "asyncTaskFinished",
353
            InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>);
354
355
786
  SetMethod(context, target, "registerAsyncHook", RegisterAsyncHookWrapper);
356
786
  SetMethodNoSideEffect(context, target, "isEnabled", IsEnabled);
357
358
786
  Local<String> console_string = FIXED_ONE_BYTE_STRING(isolate, "console");
359
360
  // Grab the console from the binding object and expose those to our binding
361
  // layer.
362
786
  Local<Object> binding = context->GetExtrasBindingObject();
363
  target
364
1572
      ->Set(context,
365
            console_string,
366
3144
            binding->Get(context, console_string).ToLocalChecked())
367
      .Check();
368
369
786
  JSBindingsConnection<LocalConnection>::Bind(env, target);
370
786
  JSBindingsConnection<MainThreadConnection>::Bind(env, target);
371
786
}
372
373
}  // namespace
374
375
5552
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
376
5552
  registry->Register(InspectorConsoleCall);
377
5552
  registry->Register(SetConsoleExtensionInstaller);
378
5552
  registry->Register(CallAndPauseOnStart);
379
5552
  registry->Register(Open);
380
5552
  registry->Register(Url);
381
5552
  registry->Register(WaitForDebugger);
382
383
5552
  registry->Register(AsyncTaskScheduledWrapper);
384
5552
  registry->Register(InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>);
385
5552
  registry->Register(InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>);
386
5552
  registry->Register(InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>);
387
388
5552
  registry->Register(RegisterAsyncHookWrapper);
389
5552
  registry->Register(IsEnabled);
390
391
5552
  registry->Register(JSBindingsConnection<LocalConnection>::New);
392
5552
  registry->Register(JSBindingsConnection<LocalConnection>::Dispatch);
393
5552
  registry->Register(JSBindingsConnection<LocalConnection>::Disconnect);
394
5552
  registry->Register(JSBindingsConnection<MainThreadConnection>::New);
395
5552
  registry->Register(JSBindingsConnection<MainThreadConnection>::Dispatch);
396
5552
  registry->Register(JSBindingsConnection<MainThreadConnection>::Disconnect);
397
5552
}
398
399
}  // namespace inspector
400
}  // namespace node
401
402
5623
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector,
403
                                  node::inspector::Initialize)
404

22421
NODE_MODULE_EXTERNAL_REFERENCE(inspector,
405
                               node::inspector::RegisterExternalReferences)