GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/inspector_js_api.cc Lines: 194 214 90.7 %
Date: 2021-02-11 04:11:15 Branches: 41 86 47.7 %

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
1163
std::unique_ptr<StringBuffer> ToProtocolString(Isolate* isolate,
35
                                               Local<Value> value) {
36
2326
  TwoByteValue buffer(isolate, value);
37
2326
  return StringBuffer::create(StringView(*buffer, buffer.length()));
38
}
39
40
struct LocalConnection {
41
888
  static std::unique_ptr<InspectorSession> Connect(
42
      Agent* inspector, std::unique_ptr<InspectorSessionDelegate> delegate) {
43
888
    return inspector->Connect(std::move(delegate), false);
44
  }
45
46
444
  static Local<String> GetClassName(Environment* env) {
47
444
    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
444
  static Local<String> GetClassName(Environment* env) {
58
444
    return FIXED_ONE_BYTE_STRING(env->isolate(), "MainThreadConnection");
59
  }
60
};
61
62
template <typename ConnectionType>
63
2667
class JSBindingsConnection : public AsyncWrap {
64
 public:
65
1778
  class JSBindingsSessionDelegate : public InspectorSessionDelegate {
66
   public:
67
890
    JSBindingsSessionDelegate(Environment* env,
68
                              JSBindingsConnection* connection)
69
                              : env_(env),
70
890
                                connection_(connection) {
71
890
    }
72
73
5848
    void SendMessageToFrontend(const v8_inspector::StringView& message)
74
        override {
75
5848
      Isolate* isolate = env_->isolate();
76
11696
      HandleScope handle_scope(isolate);
77
5848
      Context::Scope context_scope(env_->context());
78
      MaybeLocal<String> v8string =
79
5848
          String::NewFromTwoByte(isolate, message.characters16(),
80
11696
                                 NewStringType::kNormal, message.length());
81
11696
      Local<Value> argument = v8string.ToLocalChecked().As<Value>();
82
5848
      connection_->OnMessage(argument);
83
5848
    }
84
85
   private:
86
    Environment* env_;
87
    BaseObjectPtr<JSBindingsConnection> connection_;
88
  };
89
90
890
  JSBindingsConnection(Environment* env,
91
                       Local<Object> wrap,
92
                       Local<Function> callback)
93
                       : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING),
94
890
                         callback_(env->isolate(), callback) {
95
890
    Agent* inspector = env->inspector_agent();
96
890
    session_ = ConnectionType::Connect(
97
        inspector, std::make_unique<JSBindingsSessionDelegate>(env, this));
98
890
  }
99
100
5848
  void OnMessage(Local<Value> value) {
101
11696
    MakeCallback(callback_.Get(env()->isolate()), 1, &value);
102
5848
  }
103
104
888
  static void Bind(Environment* env, Local<Object> target) {
105
    Local<FunctionTemplate> tmpl =
106
888
        env->NewFunctionTemplate(JSBindingsConnection::New);
107
1776
    tmpl->InstanceTemplate()->SetInternalFieldCount(
108
        JSBindingsConnection::kInternalFieldCount);
109
1776
    tmpl->Inherit(AsyncWrap::GetConstructorTemplate(env));
110
888
    env->SetProtoMethod(tmpl, "dispatch", JSBindingsConnection::Dispatch);
111
888
    env->SetProtoMethod(tmpl, "disconnect", JSBindingsConnection::Disconnect);
112
888
    env->SetConstructorFunction(
113
        target,
114
        ConnectionType::GetClassName(env),
115
        tmpl);
116
888
  }
117
118
890
  static void New(const FunctionCallbackInfo<Value>& info) {
119
890
    Environment* env = Environment::GetCurrent(info);
120

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

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

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

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

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

1163
    if (session->session_) {
143
2326
      session->session_->Dispatch(
144
2326
          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
17780
static bool InspectorEnabled(Environment* env) {
167
17780
  Agent* agent = env->inspector_agent();
168
17780
  return agent->IsActive();
169
}
170
171
444
void SetConsoleExtensionInstaller(const FunctionCallbackInfo<Value>& info) {
172
444
  auto env = Environment::GetCurrent(info);
173
174
444
  CHECK_EQ(info.Length(), 1);
175
888
  CHECK(info[0]->IsFunction());
176
177
888
  env->set_inspector_console_extension_installer(info[0].As<Function>());
178
444
}
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
24
                                       call_args.length(), call_args.out());
189
6
  if (!retval.IsEmpty()) {
190
10
    args.GetReturnValue().Set(retval.ToLocalChecked());
191
  }
192
6
}
193
194
17775
void InspectorConsoleCall(const FunctionCallbackInfo<Value>& info) {
195
17775
  Environment* env = Environment::GetCurrent(info);
196
17775
  Isolate* isolate = env->isolate();
197
17775
  Local<Context> context = isolate->GetCurrentContext();
198
17775
  CHECK_GE(info.Length(), 2);
199
35541
  SlicedArguments call_args(info, /* start */ 2);
200
17775
  if (InspectorEnabled(env)) {
201
17769
    Local<Value> inspector_method = info[0];
202
17769
    CHECK(inspector_method->IsFunction());
203
17769
    if (!env->is_in_inspector_console_call()) {
204
17768
      env->set_is_in_inspector_console_call(true);
205
      MaybeLocal<Value> ret =
206
35536
          inspector_method.As<Function>()->Call(context,
207
                                                info.Holder(),
208
17768
                                                call_args.length(),
209
71072
                                                call_args.out());
210
17768
      env->set_is_in_inspector_console_call(false);
211
17768
      if (ret.IsEmpty())
212
9
        return;
213
    }
214
  }
215
216
17766
  Local<Value> node_method = info[1];
217
17766
  CHECK(node_method->IsFunction());
218
53298
  node_method.As<Function>()->Call(context,
219
                                   info.Holder(),
220
17766
                                   call_args.length(),
221
71064
                                   call_args.out()).FromMaybe(Local<Value>());
222
}
223
224
7
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
7
  return reinterpret_cast<void*>(asyncId << 1);
234
}
235
236
template <void (Agent::*asyncTaskFn)(void*)>
237
6
static void InvokeAsyncTaskFnWithId(const FunctionCallbackInfo<Value>& args) {
238
6
  Environment* env = Environment::GetCurrent(args);
239

12
  CHECK(args[0]->IsNumber());
240
24
  int64_t task_id = args[0]->IntegerValue(env->context()).FromJust();
241
6
  (env->inspector_agent()->*asyncTaskFn)(GetAsyncTask(task_id));
242
6
}
243
244
1
static void AsyncTaskScheduledWrapper(const FunctionCallbackInfo<Value>& args) {
245
1
  Environment* env = Environment::GetCurrent(args);
246
247
3
  CHECK(args[0]->IsString());
248
2
  Local<String> task_name = args[0].As<String>();
249
2
  String::Value task_name_value(args.GetIsolate(), task_name);
250
1
  StringView task_name_view(*task_name_value, task_name_value.length());
251
252
2
  CHECK(args[1]->IsNumber());
253
4
  int64_t task_id = args[1]->IntegerValue(env->context()).FromJust();
254
1
  void* task = GetAsyncTask(task_id);
255
256
2
  CHECK(args[2]->IsBoolean());
257
3
  bool recurring = args[2]->BooleanValue(args.GetIsolate());
258
259
1
  env->inspector_agent()->AsyncTaskScheduled(task_name_view, task, recurring);
260
1
}
261
262
5025
static void RegisterAsyncHookWrapper(const FunctionCallbackInfo<Value>& args) {
263
5025
  Environment* env = Environment::GetCurrent(args);
264
265
10050
  CHECK(args[0]->IsFunction());
266
10050
  Local<Function> enable_function = args[0].As<Function>();
267
10050
  CHECK(args[1]->IsFunction());
268
10050
  Local<Function> disable_function = args[1].As<Function>();
269
5025
  env->inspector_agent()->RegisterAsyncHook(env->isolate(),
270
5025
    enable_function, disable_function);
271
5025
}
272
273
5
void IsEnabled(const FunctionCallbackInfo<Value>& args) {
274
5
  Environment* env = Environment::GetCurrent(args);
275
15
  args.GetReturnValue().Set(InspectorEnabled(env));
276
5
}
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
    ExclusiveAccess<HostPort>::Scoped host_port(agent->host_port());
285
    host_port->set_port(static_cast<int>(port));
286
  }
287
288
  if (args.Length() > 1 && args[1]->IsString()) {
289
    Utf8Value host(env->isolate(), args[1].As<String>());
290
    ExclusiveAccess<HostPort>::Scoped host_port(agent->host_port());
291
    host_port->set_host(*host);
292
  }
293
294
  agent->StartIoThread();
295
}
296
297
void WaitForDebugger(const FunctionCallbackInfo<Value>& args) {
298
  Environment* env = Environment::GetCurrent(args);
299
  Agent* agent = env->inspector_agent();
300
  if (agent->IsActive())
301
    agent->WaitForConnect();
302
  args.GetReturnValue().Set(agent->IsActive());
303
}
304
305
6
void Url(const FunctionCallbackInfo<Value>& args) {
306
6
  Environment* env = Environment::GetCurrent(args);
307
11
  std::string url = env->inspector_agent()->GetWsUrl();
308
6
  if (url.empty()) {
309
1
    return;
310
  }
311
15
  args.GetReturnValue().Set(OneByteString(env->isolate(), url.c_str()));
312
}
313
314
444
void Initialize(Local<Object> target, Local<Value> unused,
315
                Local<Context> context, void* priv) {
316
444
  Environment* env = Environment::GetCurrent(context);
317
318
  v8::Local<v8::Function> consoleCallFunc =
319
888
      env->NewFunctionTemplate(InspectorConsoleCall, v8::Local<v8::Signature>(),
320
                               v8::ConstructorBehavior::kThrow,
321
444
                               v8::SideEffectType::kHasSideEffect)
322
888
          ->GetFunction(context)
323
444
          .ToLocalChecked();
324
444
  auto name_string = FIXED_ONE_BYTE_STRING(env->isolate(), "consoleCall");
325
888
  target->Set(context, name_string, consoleCallFunc).Check();
326
444
  consoleCallFunc->SetName(name_string);
327
328
  env->SetMethod(
329
444
      target, "setConsoleExtensionInstaller", SetConsoleExtensionInstaller);
330
444
  env->SetMethod(target, "callAndPauseOnStart", CallAndPauseOnStart);
331
444
  env->SetMethod(target, "open", Open);
332
444
  env->SetMethodNoSideEffect(target, "url", Url);
333
444
  env->SetMethod(target, "waitForDebugger", WaitForDebugger);
334
335
444
  env->SetMethod(target, "asyncTaskScheduled", AsyncTaskScheduledWrapper);
336
  env->SetMethod(target, "asyncTaskCanceled",
337
444
      InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>);
338
  env->SetMethod(target, "asyncTaskStarted",
339
444
      InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>);
340
  env->SetMethod(target, "asyncTaskFinished",
341
444
      InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>);
342
343
444
  env->SetMethod(target, "registerAsyncHook", RegisterAsyncHookWrapper);
344
444
  env->SetMethodNoSideEffect(target, "isEnabled", IsEnabled);
345
346
444
  JSBindingsConnection<LocalConnection>::Bind(env, target);
347
444
  JSBindingsConnection<MainThreadConnection>::Bind(env, target);
348
444
}
349
350
}  // namespace
351
352
4621
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
353
4621
  registry->Register(InspectorConsoleCall);
354
4621
  registry->Register(SetConsoleExtensionInstaller);
355
4621
  registry->Register(CallAndPauseOnStart);
356
4621
  registry->Register(Open);
357
4621
  registry->Register(Url);
358
4621
  registry->Register(WaitForDebugger);
359
360
4621
  registry->Register(AsyncTaskScheduledWrapper);
361
4621
  registry->Register(InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>);
362
4621
  registry->Register(InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>);
363
4621
  registry->Register(InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>);
364
365
4621
  registry->Register(RegisterAsyncHookWrapper);
366
4621
  registry->Register(IsEnabled);
367
368
4621
  registry->Register(JSBindingsConnection<LocalConnection>::New);
369
4621
  registry->Register(JSBindingsConnection<LocalConnection>::Dispatch);
370
4621
  registry->Register(JSBindingsConnection<LocalConnection>::Disconnect);
371
4621
  registry->Register(JSBindingsConnection<MainThreadConnection>::New);
372
4621
  registry->Register(JSBindingsConnection<MainThreadConnection>::Dispatch);
373
4621
  registry->Register(JSBindingsConnection<MainThreadConnection>::Disconnect);
374
4621
}
375
376
}  // namespace inspector
377
}  // namespace node
378
379
4691
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector,
380
                                  node::inspector::Initialize)
381

18718
NODE_MODULE_EXTERNAL_REFERENCE(inspector,
382
                               node::inspector::RegisterExternalReferences)