GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_process_methods.cc Lines: 192 210 91.4 %
Date: 2020-02-27 22:14:15 Branches: 64 96 66.7 %

Line Branch Exec Source
1
#include "base_object-inl.h"
2
#include "debug_utils-inl.h"
3
#include "env-inl.h"
4
#include "node.h"
5
#include "node_errors.h"
6
#include "node_internals.h"
7
#include "node_process.h"
8
#include "util-inl.h"
9
#include "uv.h"
10
#include "v8.h"
11
12
#include <vector>
13
14
#if HAVE_INSPECTOR
15
#include "inspector_io.h"
16
#endif
17
18
#include <climits>  // PATH_MAX
19
#include <cstdio>
20
21
#if defined(_MSC_VER)
22
#include <direct.h>
23
#include <io.h>
24
#define umask _umask
25
typedef int mode_t;
26
#else
27
#include <pthread.h>
28
#include <sys/resource.h>  // getrlimit, setrlimit
29
#include <termios.h>  // tcgetattr, tcsetattr
30
#endif
31
32
namespace node {
33
34
using v8::Array;
35
using v8::ArrayBuffer;
36
using v8::BigUint64Array;
37
using v8::Context;
38
using v8::Float64Array;
39
using v8::Function;
40
using v8::FunctionCallbackInfo;
41
using v8::HeapStatistics;
42
using v8::Integer;
43
using v8::Isolate;
44
using v8::Local;
45
using v8::Name;
46
using v8::NewStringType;
47
using v8::Number;
48
using v8::Object;
49
using v8::String;
50
using v8::Uint32;
51
using v8::Uint32Array;
52
using v8::Value;
53
54
namespace per_process {
55
4202
Mutex umask_mutex;
56
}   // namespace per_process
57
58
// Microseconds in a second, as a float, used in CPUUsage() below
59
#define MICROS_PER_SEC 1e6
60
// used in Hrtime() and Uptime() below
61
#define NANOS_PER_SEC 1000000000
62
63
static void Abort(const FunctionCallbackInfo<Value>& args) {
64
  Abort();
65
}
66
67
// For internal testing only, not exposed to userland.
68
static void CauseSegfault(const FunctionCallbackInfo<Value>& args) {
69
  // This should crash hard all platforms.
70
  volatile void** d = static_cast<volatile void**>(nullptr);
71
  *d = nullptr;
72
}
73
74
387
static void Chdir(const FunctionCallbackInfo<Value>& args) {
75
387
  Environment* env = Environment::GetCurrent(args);
76
387
  CHECK(env->owns_process_state());
77
78
387
  CHECK_EQ(args.Length(), 1);
79
1161
  CHECK(args[0]->IsString());
80
773
  Utf8Value path(env->isolate(), args[0]);
81
387
  int err = uv_chdir(*path);
82
387
  if (err) {
83
    // Also include the original working directory, since that will usually
84
    // be helpful information when debugging a `chdir()` failure.
85
    char buf[PATH_MAX_BYTES];
86
1
    size_t cwd_len = sizeof(buf);
87
1
    uv_cwd(buf, &cwd_len);
88
1
    return env->ThrowUVException(err, "chdir", nullptr, buf, *path);
89
  }
90
}
91
92
// CPUUsage use libuv's uv_getrusage() this-process resource usage accessor,
93
// to access ru_utime (user CPU time used) and ru_stime (system CPU time used),
94
// which are uv_timeval_t structs (long tv_sec, long tv_usec).
95
// Returns those values as Float64 microseconds in the elements of the array
96
// passed to the function.
97
33
static void CPUUsage(const FunctionCallbackInfo<Value>& args) {
98
  uv_rusage_t rusage;
99
100
  // Call libuv to get the values we'll return.
101
33
  int err = uv_getrusage(&rusage);
102
33
  if (err) {
103
    // On error, return the strerror version of the error code.
104
    Local<String> errmsg = OneByteString(args.GetIsolate(), uv_strerror(err));
105
    return args.GetReturnValue().Set(errmsg);
106
  }
107
108
  // Get the double array pointer from the Float64Array argument.
109
66
  CHECK(args[0]->IsFloat64Array());
110
66
  Local<Float64Array> array = args[0].As<Float64Array>();
111
33
  CHECK_EQ(array->Length(), 2);
112
33
  Local<ArrayBuffer> ab = array->Buffer();
113
33
  double* fields = static_cast<double*>(ab->GetBackingStore()->Data());
114
115
  // Set the Float64Array elements to be user / system values in microseconds.
116
33
  fields[0] = MICROS_PER_SEC * rusage.ru_utime.tv_sec + rusage.ru_utime.tv_usec;
117
33
  fields[1] = MICROS_PER_SEC * rusage.ru_stime.tv_sec + rusage.ru_stime.tv_usec;
118
}
119
120
4713
static void Cwd(const FunctionCallbackInfo<Value>& args) {
121
4713
  Environment* env = Environment::GetCurrent(args);
122
4713
  CHECK(env->has_run_bootstrapping_code());
123
  char buf[PATH_MAX_BYTES];
124
4713
  size_t cwd_len = sizeof(buf);
125
4713
  int err = uv_cwd(buf, &cwd_len);
126
4713
  if (err)
127
12
    return env->ThrowUVException(err, "uv_cwd");
128
129
9402
  Local<String> cwd = String::NewFromUtf8(env->isolate(),
130
                                          buf,
131
                                          NewStringType::kNormal,
132
9402
                                          cwd_len).ToLocalChecked();
133
9402
  args.GetReturnValue().Set(cwd);
134
}
135
136
137
// Hrtime exposes libuv's uv_hrtime() high-resolution timer.
138
139
// This is the legacy version of hrtime before BigInt was introduced in
140
// JavaScript.
141
// The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
142
// so this function instead fills in an Uint32Array with 3 entries,
143
// to avoid any integer overflow possibility.
144
// The first two entries contain the second part of the value
145
// broken into the upper/lower 32 bits to be converted back in JS,
146
// because there is no Uint64Array in JS.
147
// The third entry contains the remaining nanosecond part of the value.
148
82632
static void Hrtime(const FunctionCallbackInfo<Value>& args) {
149
82632
  uint64_t t = uv_hrtime();
150
151
247896
  Local<ArrayBuffer> ab = args[0].As<Uint32Array>()->Buffer();
152
82632
  uint32_t* fields = static_cast<uint32_t*>(ab->GetBackingStore()->Data());
153
154
82632
  fields[0] = (t / NANOS_PER_SEC) >> 32;
155
82632
  fields[1] = (t / NANOS_PER_SEC) & 0xffffffff;
156
82632
  fields[2] = t % NANOS_PER_SEC;
157
82632
}
158
159
3744384
static void HrtimeBigInt(const FunctionCallbackInfo<Value>& args) {
160
11233152
  Local<ArrayBuffer> ab = args[0].As<BigUint64Array>()->Buffer();
161
3744384
  uint64_t* fields = static_cast<uint64_t*>(ab->GetBackingStore()->Data());
162
3744384
  fields[0] = uv_hrtime();
163
3744384
}
164
165
63
static void Kill(const FunctionCallbackInfo<Value>& args) {
166
63
  Environment* env = Environment::GetCurrent(args);
167
63
  Local<Context> context = env->context();
168
169
63
  if (args.Length() != 2)
170
    return env->ThrowError("Bad argument.");
171
172
  int pid;
173
189
  if (!args[0]->Int32Value(context).To(&pid)) return;
174
  int sig;
175
189
  if (!args[1]->Int32Value(context).To(&sig)) return;
176
177
63
  uv_pid_t own_pid = uv_os_getpid();
178

187
  if (sig > 0 &&
179


150
      (pid == 0 || pid == -1 || pid == own_pid || pid == -own_pid) &&
180
27
      !HasSignalJSHandler(sig)) {
181
    // This is most likely going to terminate this process.
182
    // It's not an exact method but it might be close enough.
183
18
    RunAtExit(env);
184
  }
185
186
63
  int err = uv_kill(pid, sig);
187
126
  args.GetReturnValue().Set(err);
188
}
189
190
527
static void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
191
527
  Environment* env = Environment::GetCurrent(args);
192
193
  size_t rss;
194
527
  int err = uv_resident_set_memory(&rss);
195
527
  if (err)
196
    return env->ThrowUVException(err, "uv_resident_set_memory");
197
198
527
  Isolate* isolate = env->isolate();
199
  // V8 memory usage
200
527
  HeapStatistics v8_heap_stats;
201
527
  isolate->GetHeapStatistics(&v8_heap_stats);
202
203
  NodeArrayBufferAllocator* array_buffer_allocator =
204
527
      env->isolate_data()->node_allocator();
205
206
  // Get the double array pointer from the Float64Array argument.
207
1054
  CHECK(args[0]->IsFloat64Array());
208
1054
  Local<Float64Array> array = args[0].As<Float64Array>();
209
527
  CHECK_EQ(array->Length(), 5);
210
527
  Local<ArrayBuffer> ab = array->Buffer();
211
527
  double* fields = static_cast<double*>(ab->GetBackingStore()->Data());
212
213
527
  fields[0] = rss;
214
527
  fields[1] = v8_heap_stats.total_heap_size();
215
527
  fields[2] = v8_heap_stats.used_heap_size();
216
527
  fields[3] = v8_heap_stats.external_memory();
217
1054
  fields[4] = array_buffer_allocator == nullptr ?
218
527
      0 : array_buffer_allocator->total_mem_usage();
219
}
220
221
13
void RawDebug(const FunctionCallbackInfo<Value>& args) {
222


52
  CHECK(args.Length() == 1 && args[0]->IsString() &&
223
        "must be called with a single string");
224
26
  Utf8Value message(args.GetIsolate(), args[0]);
225
13
  FPrintF(stderr, "%s\n", message);
226
13
  fflush(stderr);
227
13
}
228
229
static void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
230
  Environment* env = Environment::GetCurrent(args);
231
  env->StartProfilerIdleNotifier();
232
}
233
234
static void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
235
  Environment* env = Environment::GetCurrent(args);
236
  env->StopProfilerIdleNotifier();
237
}
238
239
4542
static void Umask(const FunctionCallbackInfo<Value>& args) {
240
4542
  Environment* env = Environment::GetCurrent(args);
241
4542
  CHECK(env->has_run_bootstrapping_code());
242
4542
  CHECK_EQ(args.Length(), 1);
243

20506
  CHECK(args[0]->IsUndefined() || args[0]->IsUint32());
244
9084
  Mutex::ScopedLock scoped_lock(per_process::umask_mutex);
245
246
  uint32_t old;
247
13626
  if (args[0]->IsUndefined()) {
248
1102
    old = umask(0);
249
1102
    umask(static_cast<mode_t>(old));
250
  } else {
251
10320
    int oct = args[0].As<Uint32>()->Value();
252
3440
    old = umask(static_cast<mode_t>(oct));
253
  }
254
255
9084
  args.GetReturnValue().Set(old);
256
4542
}
257
258
4
static void Uptime(const FunctionCallbackInfo<Value>& args) {
259
4
  Environment* env = Environment::GetCurrent(args);
260
261
4
  uv_update_time(env->event_loop());
262
  double uptime =
263
4
      static_cast<double>(uv_hrtime() - per_process::node_start_time);
264
4
  Local<Number> result = Number::New(env->isolate(), uptime / NANOS_PER_SEC);
265
8
  args.GetReturnValue().Set(result);
266
4
}
267
268
1
static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
269
1
  Environment* env = Environment::GetCurrent(args);
270
271
2
  std::vector<Local<Value>> request_v;
272
13
  for (ReqWrapBase* req_wrap : *env->req_wrap_queue()) {
273
12
    AsyncWrap* w = req_wrap->GetAsyncWrap();
274
24
    if (w->persistent().IsEmpty())
275
      continue;
276
12
    request_v.emplace_back(w->GetOwner());
277
  }
278
279
3
  args.GetReturnValue().Set(
280
      Array::New(env->isolate(), request_v.data(), request_v.size()));
281
1
}
282
283
// Non-static, friend of HandleWrap. Could have been a HandleWrap method but
284
// implemented here for consistency with GetActiveRequests().
285
4
void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
286
4
  Environment* env = Environment::GetCurrent(args);
287
288
8
  std::vector<Local<Value>> handle_v;
289
24
  for (auto w : *env->handle_wrap_queue()) {
290
20
    if (!HandleWrap::HasRef(w))
291
1
      continue;
292
19
    handle_v.emplace_back(w->GetOwner());
293
  }
294
12
  args.GetReturnValue().Set(
295
      Array::New(env->isolate(), handle_v.data(), handle_v.size()));
296
4
}
297
298
1
static void ResourceUsage(const FunctionCallbackInfo<Value>& args) {
299
1
  Environment* env = Environment::GetCurrent(args);
300
301
  uv_rusage_t rusage;
302
1
  int err = uv_getrusage(&rusage);
303
1
  if (err)
304
    return env->ThrowUVException(err, "uv_getrusage");
305
306
2
  CHECK(args[0]->IsFloat64Array());
307
2
  Local<Float64Array> array = args[0].As<Float64Array>();
308
1
  CHECK_EQ(array->Length(), 16);
309
1
  Local<ArrayBuffer> ab = array->Buffer();
310
1
  double* fields = static_cast<double*>(ab->GetBackingStore()->Data());
311
312
1
  fields[0] = MICROS_PER_SEC * rusage.ru_utime.tv_sec + rusage.ru_utime.tv_usec;
313
1
  fields[1] = MICROS_PER_SEC * rusage.ru_stime.tv_sec + rusage.ru_stime.tv_usec;
314
1
  fields[2] = rusage.ru_maxrss;
315
1
  fields[3] = rusage.ru_ixrss;
316
1
  fields[4] = rusage.ru_idrss;
317
1
  fields[5] = rusage.ru_isrss;
318
1
  fields[6] = rusage.ru_minflt;
319
1
  fields[7] = rusage.ru_majflt;
320
1
  fields[8] = rusage.ru_nswap;
321
1
  fields[9] = rusage.ru_inblock;
322
1
  fields[10] = rusage.ru_oublock;
323
1
  fields[11] = rusage.ru_msgsnd;
324
1
  fields[12] = rusage.ru_msgrcv;
325
1
  fields[13] = rusage.ru_nsignals;
326
1
  fields[14] = rusage.ru_nvcsw;
327
1
  fields[15] = rusage.ru_nivcsw;
328
}
329
330
#ifdef __POSIX__
331
3
static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
332
3
  Environment* env = Environment::GetCurrent(args);
333
334
3
  if (args.Length() != 1) {
335
    return env->ThrowError("Invalid number of arguments.");
336
  }
337
338
6
  CHECK(args[0]->IsNumber());
339
9
  pid_t pid = args[0].As<Integer>()->Value();
340
3
  int r = kill(pid, SIGUSR1);
341
342
3
  if (r != 0) {
343
1
    return env->ThrowErrnoException(errno, "kill");
344
  }
345
}
346
#endif  // __POSIX__
347
348
#ifdef _WIN32
349
static int GetDebugSignalHandlerMappingName(DWORD pid,
350
                                            wchar_t* buf,
351
                                            size_t buf_len) {
352
  return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
353
}
354
355
static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
356
  Environment* env = Environment::GetCurrent(args);
357
  Isolate* isolate = args.GetIsolate();
358
359
  if (args.Length() != 1) {
360
    env->ThrowError("Invalid number of arguments.");
361
    return;
362
  }
363
364
  HANDLE process = nullptr;
365
  HANDLE thread = nullptr;
366
  HANDLE mapping = nullptr;
367
  wchar_t mapping_name[32];
368
  LPTHREAD_START_ROUTINE* handler = nullptr;
369
  DWORD pid = 0;
370
371
  auto cleanup = OnScopeLeave([&]() {
372
    if (process != nullptr) CloseHandle(process);
373
    if (thread != nullptr) CloseHandle(thread);
374
    if (handler != nullptr) UnmapViewOfFile(handler);
375
    if (mapping != nullptr) CloseHandle(mapping);
376
  });
377
378
  CHECK(args[0]->IsNumber());
379
  pid = args[0].As<Integer>()->Value();
380
381
  process =
382
      OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
383
                      PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ,
384
                  FALSE,
385
                  pid);
386
  if (process == nullptr) {
387
    isolate->ThrowException(
388
        WinapiErrnoException(isolate, GetLastError(), "OpenProcess"));
389
    return;
390
  }
391
392
  if (GetDebugSignalHandlerMappingName(
393
          pid, mapping_name, arraysize(mapping_name)) < 0) {
394
    env->ThrowErrnoException(errno, "sprintf");
395
    return;
396
  }
397
398
  mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
399
  if (mapping == nullptr) {
400
    isolate->ThrowException(
401
        WinapiErrnoException(isolate, GetLastError(), "OpenFileMappingW"));
402
    return;
403
  }
404
405
  handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
406
      MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, sizeof *handler));
407
  if (handler == nullptr || *handler == nullptr) {
408
    isolate->ThrowException(
409
        WinapiErrnoException(isolate, GetLastError(), "MapViewOfFile"));
410
    return;
411
  }
412
413
  thread =
414
      CreateRemoteThread(process, nullptr, 0, *handler, nullptr, 0, nullptr);
415
  if (thread == nullptr) {
416
    isolate->ThrowException(
417
        WinapiErrnoException(isolate, GetLastError(), "CreateRemoteThread"));
418
    return;
419
  }
420
421
  // Wait for the thread to terminate
422
  if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
423
    isolate->ThrowException(
424
        WinapiErrnoException(isolate, GetLastError(), "WaitForSingleObject"));
425
    return;
426
  }
427
}
428
#endif  // _WIN32
429
430
6
static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
431
#if HAVE_INSPECTOR
432
6
  Environment* env = Environment::GetCurrent(args);
433
6
  if (env->inspector_agent()->IsListening()) {
434
4
    env->inspector_agent()->Stop();
435
  }
436
#endif
437
6
}
438
439
231
static void ReallyExit(const FunctionCallbackInfo<Value>& args) {
440
231
  Environment* env = Environment::GetCurrent(args);
441
231
  RunAtExit(env);
442
924
  int code = args[0]->Int32Value(env->context()).FromMaybe(0);
443
231
  env->Exit(code);
444
30
}
445
446
4392
static void InitializeProcessMethods(Local<Object> target,
447
                                     Local<Value> unused,
448
                                     Local<Context> context,
449
                                     void* priv) {
450
4392
  Environment* env = Environment::GetCurrent(context);
451
452
  // define various internal methods
453
4392
  if (env->owns_process_state()) {
454
4164
    env->SetMethod(target, "_debugProcess", DebugProcess);
455
4164
    env->SetMethod(target, "_debugEnd", DebugEnd);
456
4164
    env->SetMethod(target, "abort", Abort);
457
4164
    env->SetMethod(target, "causeSegfault", CauseSegfault);
458
4164
    env->SetMethod(target, "chdir", Chdir);
459
  }
460
461
  env->SetMethod(
462
4392
      target, "_startProfilerIdleNotifier", StartProfilerIdleNotifier);
463
4392
  env->SetMethod(target, "_stopProfilerIdleNotifier", StopProfilerIdleNotifier);
464
465
4392
  env->SetMethod(target, "umask", Umask);
466
4392
  env->SetMethod(target, "_rawDebug", RawDebug);
467
4392
  env->SetMethod(target, "memoryUsage", MemoryUsage);
468
4392
  env->SetMethod(target, "cpuUsage", CPUUsage);
469
4392
  env->SetMethod(target, "hrtime", Hrtime);
470
4392
  env->SetMethod(target, "hrtimeBigInt", HrtimeBigInt);
471
4392
  env->SetMethod(target, "resourceUsage", ResourceUsage);
472
473
4392
  env->SetMethod(target, "_getActiveRequests", GetActiveRequests);
474
4392
  env->SetMethod(target, "_getActiveHandles", GetActiveHandles);
475
4392
  env->SetMethod(target, "_kill", Kill);
476
477
4392
  env->SetMethodNoSideEffect(target, "cwd", Cwd);
478
4392
  env->SetMethod(target, "dlopen", binding::DLOpen);
479
4392
  env->SetMethod(target, "reallyExit", ReallyExit);
480
4392
  env->SetMethodNoSideEffect(target, "uptime", Uptime);
481
4392
  env->SetMethod(target, "patchProcessObject", PatchProcessObject);
482
4392
}
483
484
}  // namespace node
485
486

16807
NODE_MODULE_CONTEXT_AWARE_INTERNAL(process_methods,
487
                                   node::InitializeProcessMethods)