GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/debug-agent.cc Lines: 126 148 85.1 %
Date: 2016-11-30 Branches: 18 46 39.1 %

Line Branch Exec Source
1
// Copyright Fedor Indutny and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "debug-agent.h"
23
24
#include "node.h"
25
#include "node_internals.h"  // arraysize
26
#include "env.h"
27
#include "env-inl.h"
28
#include "v8.h"
29
#include "v8-debug.h"
30
#include "util.h"
31
#include "util-inl.h"
32
33
#include <string.h>
34
35
namespace node {
36
namespace debugger {
37
38
using v8::Context;
39
using v8::FunctionCallbackInfo;
40
using v8::FunctionTemplate;
41
using v8::HandleScope;
42
using v8::Integer;
43
using v8::Isolate;
44
using v8::Local;
45
using v8::Locker;
46
using v8::NewStringType;
47
using v8::Object;
48
using v8::String;
49
using v8::Value;
50
51
52
1698
Agent::Agent(Environment* env) : state_(kNone),
53
                                 port_(5858),
54
                                 wait_(false),
55
                                 parent_env_(env),
56
                                 child_env_(nullptr),
57
6792
                                 dispatch_handler_(nullptr) {
58
1698
  CHECK_EQ(0, uv_sem_init(&start_sem_, 0));
59
1698
}
60
61
62
7460
Agent::~Agent() {
63
1492
  Stop();
64
65
1492
  uv_sem_destroy(&start_sem_);
66
67
2984
  while (AgentMessage* msg = messages_.PopFront())
68
    delete msg;
69
1492
}
70
71
72
6
bool Agent::Start(const char* host, int port, bool wait) {
73
  int err;
74
75
6
  if (state_ == kRunning)
76
    return false;
77
78
6
  err = uv_loop_init(&child_loop_);
79
6
  if (err != 0)
80
    goto loop_init_failed;
81
82
  // Interruption signal handler
83
6
  err = uv_async_init(&child_loop_, &child_signal_, ChildSignalCb);
84
6
  if (err != 0)
85
    goto async_init_failed;
86
6
  uv_unref(reinterpret_cast<uv_handle_t*>(&child_signal_));
87
88
12
  host_ = host;
89
6
  port_ = port;
90
6
  wait_ = wait;
91
92
6
  err = uv_thread_create(&thread_,
93
                         reinterpret_cast<uv_thread_cb>(ThreadCb),
94
6
                         this);
95
6
  if (err != 0)
96
    goto thread_create_failed;
97
98
6
  uv_sem_wait(&start_sem_);
99
100
6
  state_ = kRunning;
101
102
6
  return true;
103
104
 thread_create_failed:
105
  uv_close(reinterpret_cast<uv_handle_t*>(&child_signal_), nullptr);
106
107
 async_init_failed:
108
  err = uv_loop_close(&child_loop_);
109
  CHECK_EQ(err, 0);
110
111
 loop_init_failed:
112
  return false;
113
}
114
115
116
5
void Agent::Enable() {
117
5
  v8::Debug::SetMessageHandler(parent_env()->isolate(), MessageHandler);
118
119
  // Assign environment to the debugger's context
120
  // NOTE: The debugger context is created after `SetMessageHandler()` call
121
5
  auto debug_context = v8::Debug::GetDebugContext(parent_env()->isolate());
122
10
  parent_env()->AssignToContext(debug_context);
123
5
}
124
125
126
1492
void Agent::Stop() {
127
  int err;
128
129
1492
  if (state_ != kRunning) {
130
    return;
131
  }
132
133
  v8::Debug::SetMessageHandler(parent_env()->isolate(), nullptr);
134
135
  // Send empty message to terminate things
136
  EnqueueMessage(new AgentMessage(nullptr, 0));
137
138
  // Signal worker thread to make it stop
139
  err = uv_async_send(&child_signal_);
140
  CHECK_EQ(err, 0);
141
142
  err = uv_thread_join(&thread_);
143
  CHECK_EQ(err, 0);
144
145
  uv_close(reinterpret_cast<uv_handle_t*>(&child_signal_), nullptr);
146
  uv_run(&child_loop_, UV_RUN_NOWAIT);
147
148
  err = uv_loop_close(&child_loop_);
149
  CHECK_EQ(err, 0);
150
151
  state_ = kNone;
152
}
153
154
155
6
void Agent::WorkerRun() {
156
  static const char* argv[] = { "node", "--debug-agent" };
157
6
  Isolate::CreateParams params;
158
6
  ArrayBufferAllocator array_buffer_allocator;
159
6
  params.array_buffer_allocator = &array_buffer_allocator;
160
6
  Isolate* isolate = Isolate::New(params);
161
  {
162
6
    Locker locker(isolate);
163
6
    Isolate::Scope isolate_scope(isolate);
164
165
6
    HandleScope handle_scope(isolate);
166
    IsolateData isolate_data(isolate, &child_loop_,
167
6
                             array_buffer_allocator.zero_fill_field());
168
12
    Local<Context> context = Context::New(isolate);
169
170
6
    Context::Scope context_scope(context);
171
6
    Environment env(&isolate_data, context);
172
173
6
    const bool start_profiler_idle_notifier = false;
174
6
    env.Start(arraysize(argv), argv,
175
6
              arraysize(argv), argv,
176
6
              start_profiler_idle_notifier);
177
178
6
    child_env_ = &env;
179
180
    // Expose API
181
6
    InitAdaptor(&env);
182
6
    LoadEnvironment(&env);
183
184
12
    CHECK_EQ(&child_loop_, env.event_loop());
185
6
    uv_run(&child_loop_, UV_RUN_DEFAULT);
186
187
    // Clean-up peristent
188
    api_.Reset();
189
  }
190
  isolate->Dispose();
191
}
192
193
194
6
void Agent::InitAdaptor(Environment* env) {
195
6
  Isolate* isolate = env->isolate();
196
12
  HandleScope scope(isolate);
197
198
  // Create API adaptor
199
12
  Local<FunctionTemplate> t = FunctionTemplate::New(isolate);
200
12
  t->InstanceTemplate()->SetInternalFieldCount(1);
201
6
  t->SetClassName(String::NewFromUtf8(isolate, "DebugAPI"));
202
203
6
  NODE_SET_PROTOTYPE_METHOD(t, "notifyListen", NotifyListen);
204
6
  NODE_SET_PROTOTYPE_METHOD(t, "notifyWait", NotifyWait);
205
6
  NODE_SET_PROTOTYPE_METHOD(t, "sendCommand", SendCommand);
206
207
  Local<Object> api =
208
24
      t->GetFunction()->NewInstance(env->context()).ToLocalChecked();
209
6
  api->SetAlignedPointerInInternalField(0, this);
210
211
30
  api->Set(String::NewFromUtf8(isolate, "host",
212
                               NewStringType::kNormal).ToLocalChecked(),
213
6
           String::NewFromUtf8(isolate, host_.data(), NewStringType::kNormal,
214
18
                               host_.size()).ToLocalChecked());
215
18
  api->Set(String::NewFromUtf8(isolate, "port"), Integer::New(isolate, port_));
216
217
18
  env->process_object()->Set(String::NewFromUtf8(isolate, "_debugAPI"), api);
218
12
  api_.Reset(env->isolate(), api);
219
6
}
220
221
222
8
Agent* Agent::Unwrap(const v8::FunctionCallbackInfo<v8::Value>& args) {
223
16
  void* ptr = args.Holder()->GetAlignedPointerFromInternalField(0);
224
8
  return reinterpret_cast<Agent*>(ptr);
225
}
226
227
228
6
void Agent::NotifyListen(const FunctionCallbackInfo<Value>& args) {
229
6
  Agent* a = Unwrap(args);
230
231
  // Notify other thread that we are ready to process events
232
6
  uv_sem_post(&a->start_sem_);
233
6
}
234
235
236
1
void Agent::NotifyWait(const FunctionCallbackInfo<Value>& args) {
237
1
  Agent* a = Unwrap(args);
238
239
1
  a->wait_ = false;
240
241
1
  int err = uv_async_send(&a->child_signal_);
242
1
  CHECK_EQ(err, 0);
243
1
}
244
245
246
1
void Agent::SendCommand(const FunctionCallbackInfo<Value>& args) {
247
1
  Agent* a = Unwrap(args);
248
1
  Environment* env = a->child_env();
249
2
  HandleScope scope(env->isolate());
250
251
2
  String::Value v(args[0]);
252
253
1
  v8::Debug::SendCommand(a->parent_env()->isolate(), *v, v.length());
254
1
  if (a->dispatch_handler_ != nullptr)
255
1
    a->dispatch_handler_(a->parent_env());
256
1
}
257
258
259
6
void Agent::ThreadCb(Agent* agent) {
260
6
  agent->WorkerRun();
261
}
262
263
264
5
void Agent::ChildSignalCb(uv_async_t* signal) {
265
5
  Agent* a = ContainerOf(&Agent::child_signal_, signal);
266
5
  Isolate* isolate = a->child_env()->isolate();
267
268
10
  HandleScope scope(isolate);
269
5
  Local<Object> api = PersistentToLocal(isolate, a->api_);
270
271
10
  Mutex::ScopedLock scoped_lock(a->message_mutex_);
272
25
  while (AgentMessage* msg = a->messages_.PopFront()) {
273
    // Time to close everything
274
5
    if (msg->data() == nullptr) {
275
      delete msg;
276
277
      MakeCallback(isolate, api, "onclose", 0, nullptr);
278
      break;
279
    }
280
281
    // Waiting for client, do not send anything just yet
282
5
    if (a->wait_) {
283
      a->messages_.PushFront(msg);  // Push message back into the ready queue.
284
      break;
285
    }
286
287
    Local<Value> argv[] = {
288
      String::NewFromTwoByte(isolate,
289
                             msg->data(),
290
                             String::kNormalString,
291
                             msg->length())
292
10
    };
293
294
    // Emit message
295
    MakeCallback(isolate,
296
                 api,
297
                 "onmessage",
298
5
                 arraysize(argv),
299
5
                 argv);
300
5
    delete msg;
301
  }
302
5
}
303
304
305
5
void Agent::EnqueueMessage(AgentMessage* message) {
306
15
  Mutex::ScopedLock scoped_lock(message_mutex_);
307
10
  messages_.PushBack(message);
308
5
  uv_async_send(&child_signal_);
309
5
}
310
311
312
5
void Agent::MessageHandler(const v8::Debug::Message& message) {
313
5
  Isolate* isolate = message.GetIsolate();
314
5
  Environment* env = Environment::GetCurrent(isolate);
315
5
  if (env == nullptr)
316
    return;  // Called from a non-node context.
317
5
  Agent* a = env->debugger_agent();
318
5
  CHECK_NE(a, nullptr);
319
5
  CHECK_EQ(isolate, a->parent_env()->isolate());
320
321
10
  HandleScope scope(isolate);
322
5
  Local<String> json = message.GetJSON();
323
10
  String::Value v(json);
324
325
5
  AgentMessage* msg = new AgentMessage(*v, v.length());
326
5
  a->EnqueueMessage(msg);
327
}
328
329
}  // namespace debugger
330
}  // namespace node