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 207 88.4 %
Date: 2019-08-17 22:35:23 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
5167
V8ProfilerConnection::V8ProfilerConnection(Environment* env)
31
    : session_(env->inspector_agent()->Connect(
32
          std::make_unique<V8ProfilerConnection::V8ProfilerSessionDelegate>(
33
              this),
34
          false)),
35
5167
      env_(env) {}
36
37
15320
size_t V8ProfilerConnection::DispatchMessage(const char* method,
38
                                             const char* params) {
39
15320
  std::stringstream ss;
40
15320
  size_t id = next_id();
41
15320
  ss << R"({ "id": )" << id;
42
  DCHECK(method != nullptr);
43
15320
  ss << R"(, "method": ")" << method << '"';
44
15320
  if (params != nullptr) {
45
5167
    ss << R"(, "params": )" << params;
46
  }
47
15320
  ss << " }";
48
30640
  std::string message = ss.str();
49
  const uint8_t* message_data =
50
15320
      reinterpret_cast<const uint8_t*>(message.c_str());
51
  Debug(env(),
52
        DebugCategory::INSPECTOR_PROFILER,
53
        "Dispatching message %s\n",
54
30640
        message.c_str());
55
15320
  session_->Dispatch(StringView(message_data, message.length()));
56
  // TODO(joyeecheung): use this to identify the ending message.
57
30642
  return id;
58
}
59
60
4957
static void WriteResult(Environment* env,
61
                        const char* path,
62
                        Local<String> result) {
63
4957
  int ret = WriteFileSync(env->isolate(), path, result);
64
4958
  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
4958
    return;
69
  }
70
  Debug(env, DebugCategory::INSPECTOR_PROFILER, "Written result to %s\n", path);
71
}
72
73
15321
void V8ProfilerConnection::V8ProfilerSessionDelegate::SendMessageToFrontend(
74
    const v8_inspector::StringView& message) {
75
15321
  Environment* env = connection_->env();
76
15321
  Isolate* isolate = env->isolate();
77
15321
  HandleScope handle_scope(isolate);
78
20298
  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
15321
  const char* type = connection_->type();
84
  Debug(env,
85
        DebugCategory::INSPECTOR_PROFILER,
86
        "Receive %s profile message, ending = %s\n",
87
        type,
88
30642
        connection_->ending() ? "true" : "false");
89
15321
  if (!connection_->ending()) {
90
10344
    return;
91
  }
92
93
  // Convert StringView to a Local<String>.
94
  Local<String> message_str;
95
9954
  if (!String::NewFromTwoByte(isolate,
96
                              message.characters16(),
97
                              NewStringType::kNormal,
98
4977
                              message.length())
99
14931
           .ToLocal(&message_str)) {
100
    fprintf(stderr, "Failed to convert %s profile message\n", type);
101
    return;
102
  }
103
104
9954
  connection_->WriteProfile(message_str);
105
}
106
107
4958
static bool EnsureDirectory(const std::string& directory, const char* type) {
108
  uv_fs_t req;
109
4958
  int ret = fs::MKDirpSync(nullptr, &req, directory, 0777, nullptr);
110
4958
  uv_fs_req_cleanup(&req);
111

4957
  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
1
    return false;
120
  }
121
4957
  return true;
122
}
123
124
4937
std::string V8CoverageConnection::GetFilename() const {
125
4937
  std::string thread_id = std::to_string(env()->thread_id());
126
9876
  std::string pid = std::to_string(uv_os_getpid());
127
  std::string timestamp = std::to_string(
128
9876
      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
4938
           thread_id.c_str());
136
9876
  return filename;
137
}
138
139
4977
static MaybeLocal<Object> ParseProfile(Environment* env,
140
                                       Local<String> message,
141
                                       const char* type) {
142
4977
  Local<Context> context = env->context();
143
4977
  Isolate* isolate = env->isolate();
144
145
  // Get message.result from the response
146
  Local<Value> parsed;
147


14931
  if (!v8::JSON::Parse(context, message).ToLocal(&parsed) ||
148
4977
      !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
9954
  if (!parsed.As<Object>()
155
19908
           ->Get(context, FIXED_ONE_BYTE_STRING(isolate, "result"))
156
14931
           .ToLocal(&result_v)) {
157
    fprintf(stderr, "Failed to get 'result' from %s profile message\n", type);
158
    return MaybeLocal<Object>();
159
  }
160
161
4977
  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
4976
  return result_v.As<Object>();
168
}
169
170
4977
void V8ProfilerConnection::WriteProfile(Local<String> message) {
171
4977
  Local<Context> context = env_->context();
172
173
  // Get message.result from the response.
174
  Local<Object> result;
175
9953
  if (!ParseProfile(env_, message, type()).ToLocal(&result)) {
176
19
    return;
177
  }
178
  // Generate the profile output from the subclass.
179
  Local<Object> profile;
180
9952
  if (!GetProfile(result).ToLocal(&profile)) {
181
    return;
182
  }
183
  Local<String> result_s;
184
9952
  if (!v8::JSON::Stringify(context, profile).ToLocal(&result_s)) {
185
19
    fprintf(stderr, "Failed to stringify %s profile result\n", type());
186
19
    return;
187
  }
188
189
  // Create the directory if necessary.
190
4957
  std::string directory = GetDirectory();
191
  DCHECK(!directory.empty());
192
4958
  if (!EnsureDirectory(directory, type())) {
193
    return;
194
  }
195
196
9916
  std::string filename = GetFilename();
197
  DCHECK(!filename.empty());
198
9916
  std::string path = directory + kPathSeparator + filename;
199
200
9916
  WriteResult(env_, path.c_str(), result_s);
201
}
202
203
4956
MaybeLocal<Object> V8CoverageConnection::GetProfile(Local<Object> result) {
204
4956
  return result;
205
}
206
207
4937
std::string V8CoverageConnection::GetDirectory() const {
208
4937
  return env()->coverage_directory();
209
}
210
211
5147
void V8CoverageConnection::Start() {
212
5147
  DispatchMessage("Profiler.enable");
213
  DispatchMessage("Profiler.startPreciseCoverage",
214
5147
                  R"({ "callCount": true, "detailed": true })");
215
5147
}
216
217
4956
void V8CoverageConnection::End() {
218
4956
  CHECK_EQ(ending_, false);
219
4956
  ending_ = true;
220
4956
  DispatchMessage("Profiler.takePreciseCoverage");
221
4956
}
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
5051
void EndStartedProfilers(Environment* env) {
303
  Debug(env, DebugCategory::INSPECTOR_PROFILER, "EndStartedProfilers\n");
304
5052
  V8ProfilerConnection* connection = env->cpu_profiler_connection();
305

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

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

5052
  if (connection != nullptr && !connection->ending()) {
318
    Debug(
319
        env, DebugCategory::INSPECTOR_PROFILER, "Ending coverage collection\n");
320
4956
    connection->End();
321
  }
322
5051
}
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
5152
void StartProfilers(Environment* env) {
341
5152
  Isolate* isolate = env->isolate();
342
10304
  Local<String> coverage_str = env->env_vars()->Get(
343
5152
      isolate, FIXED_ONE_BYTE_STRING(isolate, "NODE_V8_COVERAGE"));
344

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

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