GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/inspector_profiler.cc Lines: 183 208 88.0 %
Date: 2019-09-17 22:33:17 Branches: 71 102 69.6 %

Line Branch Exec Source
1
#include "inspector_profiler.h"
2
#include "base_object-inl.h"
3
#include "debug_utils.h"
4
#include "diagnosticfilename-inl.h"
5
#include "memory_tracker-inl.h"
6
#include "node_file.h"
7
#include "node_internals.h"
8
#include "util-inl.h"
9
#include "v8-inspector.h"
10
11
#include <sstream>
12
13
namespace node {
14
namespace profiler {
15
16
using v8::Context;
17
using v8::Function;
18
using v8::FunctionCallbackInfo;
19
using v8::HandleScope;
20
using v8::Isolate;
21
using v8::Local;
22
using v8::MaybeLocal;
23
using v8::NewStringType;
24
using v8::Object;
25
using v8::String;
26
using v8::Value;
27
28
using v8_inspector::StringView;
29
30
5195
V8ProfilerConnection::V8ProfilerConnection(Environment* env)
31
    : session_(env->inspector_agent()->Connect(
32
          std::make_unique<V8ProfilerConnection::V8ProfilerSessionDelegate>(
33
              this),
34
          false)),
35
5195
      env_(env) {}
36
37
15407
size_t V8ProfilerConnection::DispatchMessage(const char* method,
38
                                             const char* params) {
39
15407
  std::stringstream ss;
40
15405
  size_t id = next_id();
41
15406
  ss << R"({ "id": )" << id;
42
  DCHECK(method != nullptr);
43
15405
  ss << R"(, "method": ")" << method << '"';
44
15405
  if (params != nullptr) {
45
5195
    ss << R"(, "params": )" << params;
46
  }
47
15405
  ss << " }";
48
30812
  std::string message = ss.str();
49
  const uint8_t* message_data =
50
15407
      reinterpret_cast<const uint8_t*>(message.c_str());
51
  Debug(env(),
52
        DebugCategory::INSPECTOR_PROFILER,
53
        "Dispatching message %s\n",
54
30814
        message.c_str());
55
15407
  session_->Dispatch(StringView(message_data, message.length()));
56
  // TODO(joyeecheung): use this to identify the ending message.
57
30813
  return id;
58
}
59
60
4986
static void WriteResult(Environment* env,
61
                        const char* path,
62
                        Local<String> result) {
63
4986
  int ret = WriteFileSync(env->isolate(), path, result);
64
4986
  if (ret != 0) {
65
    char err_buf[128];
66
    uv_err_name_r(ret, err_buf, sizeof(err_buf));
67
    fprintf(stderr, "%s: Failed to write file %s\n", err_buf, path);
68
4986
    return;
69
  }
70
  Debug(env, DebugCategory::INSPECTOR_PROFILER, "Written result to %s\n", path);
71
}
72
73
15407
void V8ProfilerConnection::V8ProfilerSessionDelegate::SendMessageToFrontend(
74
    const v8_inspector::StringView& message) {
75
15407
  Environment* env = connection_->env();
76
15405
  Isolate* isolate = env->isolate();
77
15406
  HandleScope handle_scope(isolate);
78
20413
  Context::Scope context_scope(env->context());
79
80
  // TODO(joyeecheung): always parse the message so that we can use the id to
81
  // identify ending messages as well as printing the message in the debug
82
  // output when there is an error.
83
15407
  const char* type = connection_->type();
84
  Debug(env,
85
        DebugCategory::INSPECTOR_PROFILER,
86
        "Receive %s profile message, ending = %s\n",
87
        type,
88
30814
        connection_->ending() ? "true" : "false");
89
15407
  if (!connection_->ending()) {
90
10400
    return;
91
  }
92
93
  // Convert StringView to a Local<String>.
94
  Local<String> message_str;
95
10014
  if (!String::NewFromTwoByte(isolate,
96
                              message.characters16(),
97
                              NewStringType::kNormal,
98
5007
                              message.length())
99
15021
           .ToLocal(&message_str)) {
100
    fprintf(stderr, "Failed to convert %s profile message\n", type);
101
    return;
102
  }
103
104
10014
  connection_->WriteProfile(message_str);
105
}
106
107
4986
static bool EnsureDirectory(const std::string& directory, const char* type) {
108
  uv_fs_t req;
109
4986
  int ret = fs::MKDirpSync(nullptr, &req, directory, 0777, nullptr);
110
4986
  uv_fs_req_cleanup(&req);
111

4986
  if (ret < 0 && ret != UV_EEXIST) {
112
    char err_buf[128];
113
    uv_err_name_r(ret, err_buf, sizeof(err_buf));
114
    fprintf(stderr,
115
            "%s: Failed to create %s profile directory %s\n",
116
            err_buf,
117
            type,
118
            directory.c_str());
119
    return false;
120
  }
121
4986
  return true;
122
}
123
124
4966
std::string V8CoverageConnection::GetFilename() const {
125
4966
  std::string thread_id = std::to_string(env()->thread_id());
126
9932
  std::string pid = std::to_string(uv_os_getpid());
127
  std::string timestamp = std::to_string(
128
9932
      static_cast<uint64_t>(GetCurrentTimeInMicroseconds() / 1000));
129
  char filename[1024];
130
  snprintf(filename,
131
           sizeof(filename),
132
           "coverage-%s-%s-%s.json",
133
           pid.c_str(),
134
           timestamp.c_str(),
135
4966
           thread_id.c_str());
136
9932
  return filename;
137
}
138
139
5007
static MaybeLocal<Object> ParseProfile(Environment* env,
140
                                       Local<String> message,
141
                                       const char* type) {
142
5007
  Local<Context> context = env->context();
143
5007
  Isolate* isolate = env->isolate();
144
145
  // Get message.result from the response
146
  Local<Value> parsed;
147


15021
  if (!v8::JSON::Parse(context, message).ToLocal(&parsed) ||
148
5007
      !parsed->IsObject()) {
149
    fprintf(stderr, "Failed to parse %s profile result as JSON object\n", type);
150
    return MaybeLocal<Object>();
151
  }
152
153
  Local<Value> result_v;
154
10014
  if (!parsed.As<Object>()
155
20028
           ->Get(context, FIXED_ONE_BYTE_STRING(isolate, "result"))
156
15021
           .ToLocal(&result_v)) {
157
    fprintf(stderr, "Failed to get 'result' from %s profile message\n", type);
158
    return MaybeLocal<Object>();
159
  }
160
161
5007
  if (!result_v->IsObject()) {
162
    fprintf(
163
        stderr, "'result' from %s profile message is not an object\n", type);
164
    return MaybeLocal<Object>();
165
  }
166
167
5007
  return result_v.As<Object>();
168
}
169
170
5007
void V8ProfilerConnection::WriteProfile(Local<String> message) {
171
5007
  Local<Context> context = env_->context();
172
173
  // Get message.result from the response.
174
  Local<Object> result;
175
10014
  if (!ParseProfile(env_, message, type()).ToLocal(&result)) {
176
21
    return;
177
  }
178
  // Generate the profile output from the subclass.
179
  Local<Object> profile;
180
10014
  if (!GetProfile(result).ToLocal(&profile)) {
181
    return;
182
  }
183
  Local<String> result_s;
184
10014
  if (!v8::JSON::Stringify(context, profile).ToLocal(&result_s)) {
185
21
    fprintf(stderr, "Failed to stringify %s profile result\n", type());
186
21
    return;
187
  }
188
189
  // Create the directory if necessary.
190
4986
  std::string directory = GetDirectory();
191
  DCHECK(!directory.empty());
192
4986
  if (!EnsureDirectory(directory, type())) {
193
    return;
194
  }
195
196
9972
  std::string filename = GetFilename();
197
  DCHECK(!filename.empty());
198
9972
  std::string path = directory + kPathSeparator + filename;
199
200
9972
  WriteResult(env_, path.c_str(), result_s);
201
}
202
203
4987
MaybeLocal<Object> V8CoverageConnection::GetProfile(Local<Object> result) {
204
4987
  return result;
205
}
206
207
4966
std::string V8CoverageConnection::GetDirectory() const {
208
4966
  return env()->coverage_directory();
209
}
210
211
5175
void V8CoverageConnection::Start() {
212
5175
  DispatchMessage("Profiler.enable");
213
  DispatchMessage("Profiler.startPreciseCoverage",
214
5175
                  R"({ "callCount": true, "detailed": true })");
215
5175
}
216
217
4987
void V8CoverageConnection::End() {
218
4987
  CHECK_EQ(ending_, false);
219
4987
  ending_ = true;
220
4987
  DispatchMessage("Profiler.takePreciseCoverage");
221
4987
}
222
223
10
std::string V8CpuProfilerConnection::GetDirectory() const {
224
10
  return env()->cpu_prof_dir();
225
}
226
227
10
std::string V8CpuProfilerConnection::GetFilename() const {
228
10
  return env()->cpu_prof_name();
229
}
230
231
10
MaybeLocal<Object> V8CpuProfilerConnection::GetProfile(Local<Object> result) {
232
  Local<Value> profile_v;
233
20
  if (!result
234
           ->Get(env()->context(),
235
40
                 FIXED_ONE_BYTE_STRING(env()->isolate(), "profile"))
236
30
           .ToLocal(&profile_v)) {
237
    fprintf(stderr, "'profile' from CPU profile result is undefined\n");
238
    return MaybeLocal<Object>();
239
  }
240
10
  if (!profile_v->IsObject()) {
241
    fprintf(stderr, "'profile' from CPU profile result is not an Object\n");
242
    return MaybeLocal<Object>();
243
  }
244
10
  return profile_v.As<Object>();
245
}
246
247
10
void V8CpuProfilerConnection::Start() {
248
10
  DispatchMessage("Profiler.enable");
249
10
  DispatchMessage("Profiler.start");
250
10
  std::string params = R"({ "interval": )";
251
10
  params += std::to_string(env()->cpu_prof_interval());
252
10
  params += " }";
253
10
  DispatchMessage("Profiler.setSamplingInterval", params.c_str());
254
10
}
255
256
10
void V8CpuProfilerConnection::End() {
257
10
  CHECK_EQ(ending_, false);
258
10
  ending_ = true;
259
10
  DispatchMessage("Profiler.stop");
260
10
}
261
262
10
std::string V8HeapProfilerConnection::GetDirectory() const {
263
10
  return env()->heap_prof_dir();
264
}
265
266
10
std::string V8HeapProfilerConnection::GetFilename() const {
267
10
  return env()->heap_prof_name();
268
}
269
270
10
MaybeLocal<Object> V8HeapProfilerConnection::GetProfile(Local<Object> result) {
271
  Local<Value> profile_v;
272
20
  if (!result
273
           ->Get(env()->context(),
274
40
                 FIXED_ONE_BYTE_STRING(env()->isolate(), "profile"))
275
30
           .ToLocal(&profile_v)) {
276
    fprintf(stderr, "'profile' from heap profile result is undefined\n");
277
    return MaybeLocal<Object>();
278
  }
279
10
  if (!profile_v->IsObject()) {
280
    fprintf(stderr, "'profile' from heap profile result is not an Object\n");
281
    return MaybeLocal<Object>();
282
  }
283
10
  return profile_v.As<Object>();
284
}
285
286
10
void V8HeapProfilerConnection::Start() {
287
10
  DispatchMessage("HeapProfiler.enable");
288
10
  std::string params = R"({ "samplingInterval": )";
289
10
  params += std::to_string(env()->heap_prof_interval());
290
10
  params += " }";
291
10
  DispatchMessage("HeapProfiler.startSampling", params.c_str());
292
10
}
293
294
10
void V8HeapProfilerConnection::End() {
295
10
  CHECK_EQ(ending_, false);
296
10
  ending_ = true;
297
10
  DispatchMessage("HeapProfiler.stopSampling");
298
10
}
299
300
// For now, we only support coverage profiling, but we may add more
301
// in the future.
302
5084
void EndStartedProfilers(Environment* env) {
303
  Debug(env, DebugCategory::INSPECTOR_PROFILER, "EndStartedProfilers\n");
304
5084
  V8ProfilerConnection* connection = env->cpu_profiler_connection();
305

5084
  if (connection != nullptr && !connection->ending()) {
306
    Debug(env, DebugCategory::INSPECTOR_PROFILER, "Ending cpu profiling\n");
307
10
    connection->End();
308
  }
309
310
5084
  connection = env->heap_profiler_connection();
311

5084
  if (connection != nullptr && !connection->ending()) {
312
    Debug(env, DebugCategory::INSPECTOR_PROFILER, "Ending heap profiling\n");
313
10
    connection->End();
314
  }
315
316
5084
  connection = env->coverage_connection();
317

5084
  if (connection != nullptr && !connection->ending()) {
318
    Debug(
319
        env, DebugCategory::INSPECTOR_PROFILER, "Ending coverage collection\n");
320
4987
    connection->End();
321
  }
322
5084
}
323
324
10
std::string GetCwd(Environment* env) {
325
  char cwd[PATH_MAX_BYTES];
326
10
  size_t size = PATH_MAX_BYTES;
327
10
  const int err = uv_cwd(cwd, &size);
328
329
10
  if (err == 0) {
330
10
    CHECK_GT(size, 0);
331
10
    return cwd;
332
  }
333
334
  // This can fail if the cwd is deleted. In that case, fall back to
335
  // exec_path.
336
  const std::string& exec_path = env->exec_path();
337
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
338
}
339
340
5181
void StartProfilers(Environment* env) {
341
5181
  Isolate* isolate = env->isolate();
342
10362
  Local<String> coverage_str = env->env_vars()->Get(
343
5181
      isolate, FIXED_ONE_BYTE_STRING(isolate, "NODE_V8_COVERAGE"))
344
15543
      .FromMaybe(Local<String>());
345

10359
  if (!coverage_str.IsEmpty() && coverage_str->Length() > 0) {
346
5175
    CHECK_NULL(env->coverage_connection());
347
5175
    env->set_coverage_connection(std::make_unique<V8CoverageConnection>(env));
348
5175
    env->coverage_connection()->Start();
349
  }
350
5181
  if (env->options()->cpu_prof) {
351
10
    const std::string& dir = env->options()->cpu_prof_dir;
352
10
    env->set_cpu_prof_interval(env->options()->cpu_prof_interval);
353
10
    env->set_cpu_prof_dir(dir.empty() ? GetCwd(env) : dir);
354
10
    if (env->options()->cpu_prof_name.empty()) {
355
8
      DiagnosticFilename filename(env, "CPU", "cpuprofile");
356
8
      env->set_cpu_prof_name(*filename);
357
    } else {
358
2
      env->set_cpu_prof_name(env->options()->cpu_prof_name);
359
    }
360
10
    CHECK_NULL(env->cpu_profiler_connection());
361
    env->set_cpu_profiler_connection(
362
10
        std::make_unique<V8CpuProfilerConnection>(env));
363
10
    env->cpu_profiler_connection()->Start();
364
  }
365
5181
  if (env->options()->heap_prof) {
366
10
    const std::string& dir = env->options()->heap_prof_dir;
367
10
    env->set_heap_prof_interval(env->options()->heap_prof_interval);
368
10
    env->set_heap_prof_dir(dir.empty() ? GetCwd(env) : dir);
369
10
    if (env->options()->heap_prof_name.empty()) {
370
8
      DiagnosticFilename filename(env, "Heap", "heapprofile");
371
8
      env->set_heap_prof_name(*filename);
372
    } else {
373
2
      env->set_heap_prof_name(env->options()->heap_prof_name);
374
    }
375
    env->set_heap_profiler_connection(
376
10
        std::make_unique<profiler::V8HeapProfilerConnection>(env));
377
10
    env->heap_profiler_connection()->Start();
378
  }
379
5181
}
380
381
5176
static void SetCoverageDirectory(const FunctionCallbackInfo<Value>& args) {
382
15528
  CHECK(args[0]->IsString());
383
5176
  Environment* env = Environment::GetCurrent(args);
384
10352
  node::Utf8Value directory(env->isolate(), args[0].As<String>());
385
5176
  env->set_coverage_directory(*directory);
386
5176
}
387
388
5176
static void Initialize(Local<Object> target,
389
                       Local<Value> unused,
390
                       Local<Context> context,
391
                       void* priv) {
392
5176
  Environment* env = Environment::GetCurrent(context);
393
5176
  env->SetMethod(target, "setCoverageDirectory", SetCoverageDirectory);
394
5176
}
395
396
}  // namespace profiler
397
}  // namespace node
398
399

20147
NODE_MODULE_CONTEXT_AWARE_INTERNAL(profiler, node::profiler::Initialize)