GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_worker.cc Lines: 405 458 88.4 %
Date: 2020-11-21 04:10:54 Branches: 184 258 71.3 %

Line Branch Exec Source
1
#include "node_worker.h"
2
#include "debug_utils-inl.h"
3
#include "memory_tracker-inl.h"
4
#include "node_errors.h"
5
#include "node_external_reference.h"
6
#include "node_buffer.h"
7
#include "node_options-inl.h"
8
#include "node_perf.h"
9
#include "util-inl.h"
10
#include "async_wrap-inl.h"
11
12
#include <memory>
13
#include <string>
14
#include <vector>
15
16
using node::kAllowedInEnvironment;
17
using node::kDisallowedInEnvironment;
18
using v8::Array;
19
using v8::ArrayBuffer;
20
using v8::Boolean;
21
using v8::Context;
22
using v8::Float64Array;
23
using v8::FunctionCallbackInfo;
24
using v8::FunctionTemplate;
25
using v8::HandleScope;
26
using v8::Integer;
27
using v8::Isolate;
28
using v8::Local;
29
using v8::Locker;
30
using v8::Maybe;
31
using v8::MaybeLocal;
32
using v8::Null;
33
using v8::Number;
34
using v8::Object;
35
using v8::ResourceConstraints;
36
using v8::SealHandleScope;
37
using v8::String;
38
using v8::TryCatch;
39
using v8::Value;
40
41
namespace node {
42
namespace worker {
43
44
constexpr double kMB = 1024 * 1024;
45
46
631
Worker::Worker(Environment* env,
47
               Local<Object> wrap,
48
               const std::string& url,
49
               std::shared_ptr<PerIsolateOptions> per_isolate_opts,
50
               std::vector<std::string>&& exec_argv,
51
631
               std::shared_ptr<KVStore> env_vars)
52
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_WORKER),
53
      per_isolate_opts_(per_isolate_opts),
54
      exec_argv_(exec_argv),
55
631
      platform_(env->isolate_data()->platform()),
56
      thread_id_(AllocateEnvironmentThreadId()),
57
1262
      env_vars_(env_vars) {
58
631
  Debug(this, "Creating new worker instance with thread id %llu",
59
        thread_id_.id);
60
61
  // Set up everything that needs to be set up in the parent environment.
62
631
  parent_port_ = MessagePort::New(env, env->context());
63
631
  if (parent_port_ == nullptr) {
64
    // This can happen e.g. because execution is terminating.
65
    return;
66
  }
67
68
631
  child_port_data_ = std::make_unique<MessagePortData>(nullptr);
69
631
  MessagePort::Entangle(parent_port_, child_port_data_.get());
70
71
1893
  object()->Set(env->context(),
72
                env->message_port_string(),
73
3155
                parent_port_->object()).Check();
74
75
1893
  object()->Set(env->context(),
76
                env->thread_id_string(),
77
3155
                Number::New(env->isolate(), static_cast<double>(thread_id_.id)))
78
      .Check();
79
80
1262
  inspector_parent_handle_ = GetInspectorParentHandle(
81
631
      env, thread_id_, url.c_str());
82
83
631
  argv_ = std::vector<std::string>{env->argv()[0]};
84
  // Mark this Worker object as weak until we actually start the thread.
85
631
  MakeWeak();
86
87
631
  Debug(this, "Preparation for worker %llu finished", thread_id_.id);
88
}
89
90
1590
bool Worker::is_stopped() const {
91
3180
  Mutex::ScopedLock lock(mutex_);
92
1590
  if (env_ != nullptr)
93
393
    return env_->is_stopping();
94
1197
  return stopped_;
95
}
96
97
408
void Worker::UpdateResourceConstraints(ResourceConstraints* constraints) {
98
408
  constraints->set_stack_limit(reinterpret_cast<uint32_t*>(stack_base_));
99
100
408
  if (resource_limits_[kMaxYoungGenerationSizeMb] > 0) {
101
1
    constraints->set_max_young_generation_size_in_bytes(
102
2
        resource_limits_[kMaxYoungGenerationSizeMb] * kMB);
103
  } else {
104
407
    resource_limits_[kMaxYoungGenerationSizeMb] =
105
407
        constraints->max_young_generation_size_in_bytes() / kMB;
106
  }
107
108
408
  if (resource_limits_[kMaxOldGenerationSizeMb] > 0) {
109
2
    constraints->set_max_old_generation_size_in_bytes(
110
4
        resource_limits_[kMaxOldGenerationSizeMb] * kMB);
111
  } else {
112
406
    resource_limits_[kMaxOldGenerationSizeMb] =
113
406
        constraints->max_old_generation_size_in_bytes() / kMB;
114
  }
115
116
408
  if (resource_limits_[kCodeRangeSizeMb] > 0) {
117
1
    constraints->set_code_range_size_in_bytes(
118
2
        resource_limits_[kCodeRangeSizeMb] * kMB);
119
  } else {
120
407
    resource_limits_[kCodeRangeSizeMb] =
121
407
        constraints->code_range_size_in_bytes() / kMB;
122
  }
123
408
}
124
125
// This class contains data that is only relevant to the child thread itself,
126
// and only while it is running.
127
// (Eventually, the Environment instance should probably also be moved here.)
128
class WorkerThreadData {
129
 public:
130
629
  explicit WorkerThreadData(Worker* w)
131
629
    : w_(w) {
132
629
    int ret = uv_loop_init(&loop_);
133
628
    if (ret != 0) {
134
      char err_buf[128];
135
220
      uv_err_name_r(ret, err_buf, sizeof(err_buf));
136
219
      w->Exit(1, "ERR_WORKER_INIT_FAILED", err_buf);
137
217
      return;
138
    }
139
408
    loop_init_failed_ = false;
140
408
    uv_loop_configure(&loop_, UV_METRICS_IDLE_TIME);
141
142
    std::shared_ptr<ArrayBufferAllocator> allocator =
143
816
        ArrayBufferAllocator::Create();
144
816
    Isolate::CreateParams params;
145
408
    SetIsolateCreateParamsForNode(&params);
146
408
    params.array_buffer_allocator_shared = allocator;
147
148
408
    w->UpdateResourceConstraints(&params.constraints);
149
150
408
    Isolate* isolate = Isolate::Allocate();
151
408
    if (isolate == nullptr) {
152
      // TODO(addaleax): This should be ERR_WORKER_INIT_FAILED,
153
      // ERR_WORKER_OUT_OF_MEMORY is for reaching the per-Worker heap limit.
154
      w->Exit(1, "ERR_WORKER_OUT_OF_MEMORY", "Failed to create new Isolate");
155
      return;
156
    }
157
158
408
    w->platform_->RegisterIsolate(isolate, &loop_);
159
408
    Isolate::Initialize(isolate, params);
160
408
    SetIsolateUpForNode(isolate);
161
162
    // Be sure it's called before Environment::InitializeDiagnostics()
163
    // so that this callback stays when the callback of
164
    // --heapsnapshot-near-heap-limit gets is popped.
165
408
    isolate->AddNearHeapLimitCallback(Worker::NearHeapLimit, w);
166
167
    {
168
408
      Locker locker(isolate);
169
816
      Isolate::Scope isolate_scope(isolate);
170
      // V8 computes its stack limit the first time a `Locker` is used based on
171
      // --stack-size. Reset it to the correct value.
172
408
      isolate->SetStackLimit(w->stack_base_);
173
174
816
      HandleScope handle_scope(isolate);
175
816
      isolate_data_.reset(CreateIsolateData(isolate,
176
                                            &loop_,
177
408
                                            w_->platform_,
178
408
                                            allocator.get()));
179
408
      CHECK(isolate_data_);
180
408
      if (w_->per_isolate_opts_)
181
100
        isolate_data_->set_options(std::move(w_->per_isolate_opts_));
182
408
      isolate_data_->set_worker_context(w_);
183
816
      isolate_data_->max_young_gen_size =
184
408
          params.constraints.max_young_generation_size_in_bytes();
185
    }
186
187
816
    Mutex::ScopedLock lock(w_->mutex_);
188
408
    w_->isolate_ = isolate;
189
  }
190
191
1253
  ~WorkerThreadData() {
192
627
    Debug(w_, "Worker %llu dispose isolate", w_->thread_id_.id);
193
    Isolate* isolate;
194
    {
195
1254
      Mutex::ScopedLock lock(w_->mutex_);
196
627
      isolate = w_->isolate_;
197
627
      w_->isolate_ = nullptr;
198
    }
199
200
626
    if (isolate != nullptr) {
201
408
      CHECK(!loop_init_failed_);
202
408
      bool platform_finished = false;
203
204
408
      isolate_data_.reset();
205
206
2446
      w_->platform_->AddIsolateFinishedCallback(isolate, [](void* data) {
207
407
        *static_cast<bool*>(data) = true;
208
2038
      }, &platform_finished);
209
210
      // The order of these calls is important; if the Isolate is first disposed
211
      // and then unregistered, there is a race condition window in which no
212
      // new Isolate at the same address can successfully be registered with
213
      // the platform.
214
      // (Refs: https://github.com/nodejs/node/issues/30846)
215
408
      w_->platform_->UnregisterIsolate(isolate);
216
408
      isolate->Dispose();
217
218
      // Wait until the platform has cleaned up all relevant resources.
219
1224
      while (!platform_finished) {
220
408
        uv_run(&loop_, UV_RUN_ONCE);
221
      }
222
    }
223
626
    if (!loop_init_failed_) {
224
408
      CheckedUvLoopClose(&loop_);
225
    }
226
624
  }
227
228
408
  bool loop_is_usable() const { return !loop_init_failed_; }
229
230
 private:
231
  Worker* const w_;
232
  uv_loop_t loop_;
233
  bool loop_init_failed_ = true;
234
  DeleteFnPtr<IsolateData, FreeIsolateData> isolate_data_;
235
236
  friend class Worker;
237
};
238
239
3
size_t Worker::NearHeapLimit(void* data, size_t current_heap_limit,
240
                             size_t initial_heap_limit) {
241
3
  Worker* worker = static_cast<Worker*>(data);
242
3
  worker->Exit(1, "ERR_WORKER_OUT_OF_MEMORY", "JS heap out of memory");
243
  // Give the current GC some extra leeway to let it finish rather than
244
  // crash hard. We are not going to perform further allocations anyway.
245
3
  constexpr size_t kExtraHeapAllowance = 16 * 1024 * 1024;
246
3
  return current_heap_limit + kExtraHeapAllowance;
247
}
248
249
629
void Worker::Run() {
250
1022
  std::string name = "WorkerThread ";
251
629
  name += std::to_string(thread_id_.id);
252
629
  TRACE_EVENT_METADATA1(
253
      "__metadata", "thread_name", "name",
254
      TRACE_STR_COPY(name.c_str()));
255
772
  CHECK_NOT_NULL(platform_);
256
629
257
629
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
258
4
259
1022
  WorkerThreadData data(this);
260
626
  if (isolate_ == nullptr) return;
261
408
  CHECK(data.loop_is_usable());
262
263
408
  Debug(this, "Starting worker with id %llu", thread_id_.id);
264
  {
265
801
    Locker locker(isolate_);
266
801
    Isolate::Scope isolate_scope(isolate_);
267
801
    SealHandleScope outer_seal(isolate_);
268
269
801
    DeleteFnPtr<Environment, FreeEnvironment> env_;
270
407
    auto cleanup_env = OnScopeLeave([&]() {
271
      // TODO(addaleax): This call is harmless but should not be necessary.
272
      // Figure out why V8 is raising a DCHECK() here without it
273
      // (in test/parallel/test-async-hooks-worker-asyncfn-terminate-4.js).
274
1586
      isolate_->CancelTerminateExecution();
275
276
800
      if (!env_) return;
277
392
      env_->set_can_call_into_js(false);
278
279
      {
280
786
        Mutex::ScopedLock lock(mutex_);
281
393
        stopped_ = true;
282
393
        this->env_ = nullptr;
283
      }
284
285
393
      env_.reset();
286
801
    });
287
288
408
    if (is_stopped()) return;
289
    {
290
793
      HandleScope handle_scope(isolate_);
291
      Local<Context> context;
292
      {
293
        // We create the Context object before we have an Environment* in place
294
        // that we could use for error handling. If creation fails due to
295
        // resource constraints, we need something in place to handle it,
296
        // though.
297
796
        TryCatch try_catch(isolate_);
298
400
        context = NewContext(isolate_);
299
400
        if (context.IsEmpty()) {
300
          // TODO(addaleax): This should be ERR_WORKER_INIT_FAILED,
301
          // ERR_WORKER_OUT_OF_MEMORY is for reaching the per-Worker heap limit.
302
4
          Exit(1, "ERR_WORKER_OUT_OF_MEMORY", "Failed to create new Context");
303
4
          return;
304
        }
305
      }
306
307
396
      if (is_stopped()) return;
308
393
      CHECK(!context.IsEmpty());
309
393
      Context::Scope context_scope(context);
310
      {
311
1179
        env_.reset(CreateEnvironment(
312
            data.isolate_data_.get(),
313
            context,
314
393
            std::move(argv_),
315
393
            std::move(exec_argv_),
316
393
            static_cast<EnvironmentFlags::Flags>(environment_flags_),
317
            thread_id_,
318
786
            std::move(inspector_parent_handle_)));
319
393
        if (is_stopped()) return;
320
393
        CHECK_NOT_NULL(env_);
321
393
        env_->set_env_vars(std::move(env_vars_));
322
838
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
323
52
          Exit(exit_code);
324
445
        });
325
      }
326
      {
327
786
        Mutex::ScopedLock lock(mutex_);
328
393
        if (stopped_) return;
329
393
        this->env_ = env_.get();
330
      }
331
393
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
332
393
      if (is_stopped()) return;
333
      {
334
393
        CreateEnvMessagePort(env_.get());
335
393
        Debug(this, "Created message port for worker %llu", thread_id_.id);
336
786
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
337
          return;
338
339
393
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
340
      }
341
    }
342
343
    {
344
393
      Maybe<int> exit_code = SpinEventLoop(env_.get());
345
784
      Mutex::ScopedLock lock(mutex_);
346

715
      if (exit_code_ == 0 && exit_code.IsJust()) {
347
304
        exit_code_ = exit_code.FromJust();
348
      }
349
350
393
      Debug(this, "Exiting thread for worker %llu with exit code %d",
351
            thread_id_.id, exit_code_);
352
    }
353
  }
354
355
393
  Debug(this, "Worker %llu thread stops", thread_id_.id);
356
}
357
358
393
void Worker::CreateEnvMessagePort(Environment* env) {
359
786
  HandleScope handle_scope(isolate_);
360
786
  Mutex::ScopedLock lock(mutex_);
361
  // Set up the message channel for receiving messages in the child.
362
786
  MessagePort* child_port = MessagePort::New(env,
363
                                             env->context(),
364
786
                                             std::move(child_port_data_));
365
  // MessagePort::New() may return nullptr if execution is terminated
366
  // within it.
367
393
  if (child_port != nullptr)
368
393
    env->set_message_port(child_port->object(isolate_));
369
393
}
370
371
633
void Worker::JoinThread() {
372
633
  if (thread_joined_)
373
4
    return;
374
629
  CHECK_EQ(uv_thread_join(&tid_), 0);
375
629
  thread_joined_ = true;
376
377
629
  env()->remove_sub_worker_context(this);
378
379
  {
380
1256
    HandleScope handle_scope(env()->isolate());
381
629
    Context::Scope context_scope(env()->context());
382
383
    // Reset the parent port as we're closing it now anyway.
384
1887
    object()->Set(env()->context(),
385
                  env()->message_port_string(),
386
3145
                  Undefined(env()->isolate())).Check();
387
388
    Local<Value> args[] = {
389
        Integer::New(env()->isolate(), exit_code_),
390
629
        custom_error_ != nullptr
391
856
            ? OneByteString(env()->isolate(), custom_error_).As<Value>()
392
1433
            : Null(env()->isolate()).As<Value>(),
393
629
        !custom_error_str_.empty()
394
856
            ? OneByteString(env()->isolate(), custom_error_str_.c_str())
395
                  .As<Value>()
396
1433
            : Null(env()->isolate()).As<Value>(),
397

5032
    };
398
399
629
    MakeCallback(env()->onexit_string(), arraysize(args), args);
400
  }
401
402
  // If we get here, the !thread_joined_ condition at the top of the function
403
  // implies that the thread was running. In that case, its final action will
404
  // be to schedule a callback on the parent thread which will delete this
405
  // object, so there's nothing more to do here.
406
}
407
408
1821
Worker::~Worker() {
409
1214
  Mutex::ScopedLock lock(mutex_);
410
411
607
  CHECK(stopped_);
412
607
  CHECK_NULL(env_);
413
607
  CHECK(thread_joined_);
414
415
607
  Debug(this, "Worker %llu destroyed", thread_id_.id);
416
1214
}
417
418
634
void Worker::New(const FunctionCallbackInfo<Value>& args) {
419
634
  Environment* env = Environment::GetCurrent(args);
420
634
  Isolate* isolate = args.GetIsolate();
421
422
634
  CHECK(args.IsConstructCall());
423
424
634
  if (env->isolate_data()->platform() == nullptr) {
425
    THROW_ERR_MISSING_PLATFORM_FOR_WORKER(env);
426
    return;
427
  }
428
429
1265
  std::string url;
430
1265
  std::shared_ptr<PerIsolateOptions> per_isolate_opts = nullptr;
431
1265
  std::shared_ptr<KVStore> env_vars = nullptr;
432
433
1265
  std::vector<std::string> exec_argv_out;
434
435
  // Argument might be a string or URL
436
1902
  if (!args[0]->IsNullOrUndefined()) {
437
    Utf8Value value(
438
845
        isolate, args[0]->ToString(env->context()).FromMaybe(Local<String>()));
439
169
    url.append(value.out(), value.length());
440
  }
441
442
1902
  if (args[1]->IsNull()) {
443
    // Means worker.env = { ...process.env }.
444
609
    env_vars = env->env_vars()->Clone(isolate);
445
50
  } else if (args[1]->IsObject()) {
446
    // User provided env.
447
24
    env_vars = KVStore::CreateMapKVStore();
448
24
    env_vars->AssignFromObject(isolate->GetCurrentContext(),
449
72
                               args[1].As<Object>());
450
  } else {
451
    // Env is shared.
452
1
    env_vars = env->env_vars();
453
  }
454
455

2488
  if (args[1]->IsObject() || args[2]->IsArray()) {
456
103
    per_isolate_opts.reset(new PerIsolateOptions());
457
458
1030
    HandleEnvOptions(per_isolate_opts->per_env, [&env_vars](const char* name) {
459
824
      return env_vars->Get(name).FromMaybe("");
460
927
    });
461
462
#ifndef NODE_WITHOUT_NODE_OPTIONS
463
    MaybeLocal<String> maybe_node_opts =
464
103
        env_vars->Get(isolate, OneByteString(isolate, "NODE_OPTIONS"));
465
    Local<String> node_opts;
466
103
    if (maybe_node_opts.ToLocal(&node_opts)) {
467
306
      std::string node_options(*String::Utf8Value(isolate, node_opts));
468
204
      std::vector<std::string> errors{};
469
      std::vector<std::string> env_argv =
470
204
          ParseNodeOptionsEnvVar(node_options, &errors);
471
      // [0] is expected to be the program name, add dummy string.
472
102
      env_argv.insert(env_argv.begin(), "");
473
204
      std::vector<std::string> invalid_args{};
474
102
      options_parser::Parse(&env_argv,
475
                            nullptr,
476
                            &invalid_args,
477
                            per_isolate_opts.get(),
478
                            kAllowedInEnvironment,
479
102
                            &errors);
480

102
      if (!errors.empty() && args[1]->IsObject()) {
481
        // Only fail for explicitly provided env, this protects from failures
482
        // when NODE_OPTIONS from parent's env is used (which is the default).
483
        Local<Value> error;
484
        if (!ToV8Value(env->context(), errors).ToLocal(&error)) return;
485
        Local<String> key =
486
            FIXED_ONE_BYTE_STRING(env->isolate(), "invalidNodeOptions");
487
        // Ignore the return value of Set() because exceptions bubble up to JS
488
        // when we return anyway.
489
        USE(args.This()->Set(env->context(), key, error));
490
        return;
491
      }
492
    }
493
#endif
494
  }
495
496
1268
  if (args[2]->IsArray()) {
497
202
    Local<Array> array = args[2].As<Array>();
498
    // The first argument is reserved for program name, but we don't need it
499
    // in workers.
500
199
    std::vector<std::string> exec_argv = {""};
501
101
    uint32_t length = array->Length();
502
152
    for (uint32_t i = 0; i < length; i++) {
503
      Local<Value> arg;
504
153
      if (!array->Get(env->context(), i).ToLocal(&arg)) {
505
        return;
506
      }
507
      Local<String> arg_v8;
508
153
      if (!arg->ToString(env->context()).ToLocal(&arg_v8)) {
509
        return;
510
      }
511
102
      Utf8Value arg_utf8_value(args.GetIsolate(), arg_v8);
512
102
      std::string arg_string(arg_utf8_value.out(), arg_utf8_value.length());
513
51
      exec_argv.push_back(arg_string);
514
    }
515
516
199
    std::vector<std::string> invalid_args{};
517
199
    std::vector<std::string> errors{};
518
    // Using invalid_args as the v8_args argument as it stores unknown
519
    // options for the per isolate parser.
520
101
    options_parser::Parse(
521
        &exec_argv,
522
        &exec_argv_out,
523
        &invalid_args,
524
        per_isolate_opts.get(),
525
        kDisallowedInEnvironment,
526
101
        &errors);
527
528
    // The first argument is program name.
529
101
    invalid_args.erase(invalid_args.begin());
530

101
    if (errors.size() > 0 || invalid_args.size() > 0) {
531
      Local<Value> error;
532
6
      if (!ToV8Value(env->context(),
533
3
                     errors.size() > 0 ? errors : invalid_args)
534
3
                         .ToLocal(&error)) {
535
        return;
536
      }
537
      Local<String> key =
538
3
          FIXED_ONE_BYTE_STRING(env->isolate(), "invalidExecArgv");
539
      // Ignore the return value of Set() because exceptions bubble up to JS
540
      // when we return anyway.
541
9
      USE(args.This()->Set(env->context(), key, error));
542
3
      return;
543
    }
544
  } else {
545
533
    exec_argv_out = env->exec_argv();
546
  }
547
548
  Worker* worker = new Worker(env,
549
1262
                              args.This(),
550
                              url,
551
                              per_isolate_opts,
552
                              std::move(exec_argv_out),
553
631
                              env_vars);
554
555
1262
  CHECK(args[3]->IsFloat64Array());
556
1262
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
557
631
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
558
1262
  limit_info->CopyContents(worker->resource_limits_,
559
631
                           sizeof(worker->resource_limits_));
560
561
1262
  CHECK(args[4]->IsBoolean());
562

1262
  if (args[4]->IsTrue() || env->tracks_unmanaged_fds())
563
630
    worker->environment_flags_ |= EnvironmentFlags::kTrackUnmanagedFds;
564
}
565
566
629
void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
567
  Worker* w;
568
629
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
569
1258
  Mutex::ScopedLock lock(w->mutex_);
570
571
629
  w->stopped_ = false;
572
573
629
  if (w->resource_limits_[kStackSizeMb] > 0) {
574
9
    if (w->resource_limits_[kStackSizeMb] * kMB < kStackBufferSize) {
575
3
      w->resource_limits_[kStackSizeMb] = kStackBufferSize / kMB;
576
3
      w->stack_size_ = kStackBufferSize;
577
    } else {
578
6
      w->stack_size_ = w->resource_limits_[kStackSizeMb] * kMB;
579
    }
580
  } else {
581
620
    w->resource_limits_[kStackSizeMb] = w->stack_size_ / kMB;
582
  }
583
584
  uv_thread_options_t thread_options;
585
629
  thread_options.flags = UV_THREAD_HAS_STACK_SIZE;
586
629
  thread_options.stack_size = w->stack_size_;
587
3145
  int ret = uv_thread_create_ex(&w->tid_, &thread_options, [](void* arg) {
588
    // XXX: This could become a std::unique_ptr, but that makes at least
589
    // gcc 6.3 detect undefined behaviour when there shouldn't be any.
590
    // gcc 7+ handles this well.
591
629
    Worker* w = static_cast<Worker*>(arg);
592
629
    const uintptr_t stack_top = reinterpret_cast<uintptr_t>(&arg);
593
594
    // Leave a few kilobytes just to make sure we're within limits and have
595
    // some space to do work in C++ land.
596
629
    w->stack_base_ = stack_top - (w->stack_size_ - kStackBufferSize);
597
598
629
    w->Run();
599
600
1255
    Mutex::ScopedLock lock(w->mutex_);
601
1258
    w->env()->SetImmediateThreadsafe(
602
2467
        [w = std::unique_ptr<Worker>(w)](Environment* env) {
603
607
          if (w->has_ref_)
604
606
            env->add_refs(-1);
605
607
          w->JoinThread();
606
          // implicitly delete w
607
1230
        });
608
2515
  }, static_cast<void*>(w));
609
610
629
  if (ret == 0) {
611
    // The object now owns the created thread and should not be garbage
612
    // collected until that finishes.
613
629
    w->ClearWeak();
614
629
    w->thread_joined_ = false;
615
616
629
    if (w->has_ref_)
617
629
      w->env()->add_refs(1);
618
619
629
    w->env()->add_sub_worker_context(w);
620
  } else {
621
    w->stopped_ = true;
622
623
    char err_buf[128];
624
    uv_err_name_r(ret, err_buf, sizeof(err_buf));
625
    {
626
      Isolate* isolate = w->env()->isolate();
627
      HandleScope handle_scope(isolate);
628
      THROW_ERR_WORKER_INIT_FAILED(isolate, err_buf);
629
    }
630
  }
631
}
632
633
32
void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
634
  Worker* w;
635
32
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
636
637
32
  Debug(w, "Worker %llu is getting stopped by parent", w->thread_id_.id);
638
32
  w->Exit(1);
639
}
640
641
34
void Worker::Ref(const FunctionCallbackInfo<Value>& args) {
642
  Worker* w;
643
34
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
644

34
  if (!w->has_ref_ && !w->thread_joined_) {
645
3
    w->has_ref_ = true;
646
3
    w->env()->add_refs(1);
647
  }
648
}
649
650
5
void Worker::Unref(const FunctionCallbackInfo<Value>& args) {
651
  Worker* w;
652
5
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
653

5
  if (w->has_ref_ && !w->thread_joined_) {
654
4
    w->has_ref_ = false;
655
4
    w->env()->add_refs(-1);
656
  }
657
}
658
659
1
void Worker::GetResourceLimits(const FunctionCallbackInfo<Value>& args) {
660
  Worker* w;
661
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
662
3
  args.GetReturnValue().Set(w->GetResourceLimits(args.GetIsolate()));
663
}
664
665
394
Local<Float64Array> Worker::GetResourceLimits(Isolate* isolate) const {
666
394
  Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, sizeof(resource_limits_));
667
668
1182
  memcpy(ab->GetBackingStore()->Data(),
669
         resource_limits_,
670
394
         sizeof(resource_limits_));
671
394
  return Float64Array::New(ab, 0, kTotalResourceLimitCount);
672
}
673
674
335
void Worker::Exit(int code, const char* error_code, const char* error_message) {
675
670
  Mutex::ScopedLock lock(mutex_);
676
336
  Debug(this, "Worker %llu called Exit(%d, %s, %s)",
677
        thread_id_.id, code, error_code, error_message);
678
679
333
  if (error_code != nullptr) {
680
223
    custom_error_ = error_code;
681
223
    custom_error_str_ = error_message;
682
  }
683
684
335
  if (env_ != nullptr) {
685
89
    exit_code_ = code;
686
89
    Stop(env_);
687
  } else {
688
246
    stopped_ = true;
689
  }
690
335
}
691
692
void Worker::MemoryInfo(MemoryTracker* tracker) const {
693
  tracker->TrackField("parent_port", parent_port_);
694
}
695
696
bool Worker::IsNotIndicativeOfMemoryLeakAtExit() const {
697
  // Worker objects always stay alive as long as the child thread, regardless
698
  // of whether they are being referenced in the parent thread.
699
  return true;
700
}
701
702
class WorkerHeapSnapshotTaker : public AsyncWrap {
703
 public:
704
  WorkerHeapSnapshotTaker(Environment* env, Local<Object> obj)
705
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_WORKERHEAPSNAPSHOT) {}
706
707
  SET_NO_MEMORY_INFO()
708
  SET_MEMORY_INFO_NAME(WorkerHeapSnapshotTaker)
709
  SET_SELF_SIZE(WorkerHeapSnapshotTaker)
710
};
711
712
void Worker::TakeHeapSnapshot(const FunctionCallbackInfo<Value>& args) {
713
  Worker* w;
714
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
715
716
  Debug(w, "Worker %llu taking heap snapshot", w->thread_id_.id);
717
718
  Environment* env = w->env();
719
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(w);
720
  Local<Object> wrap;
721
  if (!env->worker_heap_snapshot_taker_template()
722
      ->NewInstance(env->context()).ToLocal(&wrap)) {
723
    return;
724
  }
725
  BaseObjectPtr<WorkerHeapSnapshotTaker> taker =
726
      MakeDetachedBaseObject<WorkerHeapSnapshotTaker>(env, wrap);
727
728
  // Interrupt the worker thread and take a snapshot, then schedule a call
729
  // on the parent thread that turns that snapshot into a readable stream.
730
  bool scheduled = w->RequestInterrupt([taker, env](Environment* worker_env) {
731
    heap::HeapSnapshotPointer snapshot {
732
        worker_env->isolate()->GetHeapProfiler()->TakeHeapSnapshot() };
733
    CHECK(snapshot);
734
    env->SetImmediateThreadsafe(
735
        [taker, snapshot = std::move(snapshot)](Environment* env) mutable {
736
          HandleScope handle_scope(env->isolate());
737
          Context::Scope context_scope(env->context());
738
739
          AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(taker.get());
740
          BaseObjectPtr<AsyncWrap> stream = heap::CreateHeapSnapshotStream(
741
              env, std::move(snapshot));
742
          Local<Value> args[] = { stream->object() };
743
          taker->MakeCallback(env->ondone_string(), arraysize(args), args);
744
        }, CallbackFlags::kUnrefed);
745
  });
746
  args.GetReturnValue().Set(scheduled ? taker->object() : Local<Object>());
747
}
748
749
7
void Worker::LoopIdleTime(const FunctionCallbackInfo<Value>& args) {
750
  Worker* w;
751
7
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
752
753
14
  Mutex::ScopedLock lock(w->mutex_);
754
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
755
  // before locking the mutex is a race condition. So manually do the same
756
  // check.
757

7
  if (w->stopped_ || w->env_ == nullptr)
758
    return args.GetReturnValue().Set(-1);
759
760
7
  uint64_t idle_time = uv_metrics_idle_time(w->env_->event_loop());
761
21
  args.GetReturnValue().Set(1.0 * idle_time / 1e6);
762
}
763
764
1
void Worker::LoopStartTime(const FunctionCallbackInfo<Value>& args) {
765
  Worker* w;
766
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
767
768
2
  Mutex::ScopedLock lock(w->mutex_);
769
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
770
  // before locking the mutex is a race condition. So manually do the same
771
  // check.
772

1
  if (w->stopped_ || w->env_ == nullptr)
773
    return args.GetReturnValue().Set(-1);
774
775
1
  double loop_start_time = w->env_->performance_state()->milestones[
776
1
      node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START];
777
1
  CHECK_GE(loop_start_time, 0);
778
3
  args.GetReturnValue().Set(
779
1
      (loop_start_time - node::performance::timeOrigin) / 1e6);
780
}
781
782
namespace {
783
784
// Return the MessagePort that is global for this Environment and communicates
785
// with the internal [kPort] port of the JS Worker class in the parent thread.
786
787
void GetEnvMessagePort(const FunctionCallbackInfo<Value>& args) {
787
787
  Environment* env = Environment::GetCurrent(args);
788
787
  Local<Object> port = env->message_port();
789

1574
  CHECK_IMPLIES(!env->is_main_thread(), !port.IsEmpty());
790
787
  if (!port.IsEmpty()) {
791
2361
    CHECK_EQ(port->CreationContext()->GetIsolate(), args.GetIsolate());
792
1574
    args.GetReturnValue().Set(port);
793
  }
794
787
}
795
796
445
void InitWorker(Local<Object> target,
797
                Local<Value> unused,
798
                Local<Context> context,
799
                void* priv) {
800
445
  Environment* env = Environment::GetCurrent(context);
801
802
  {
803
445
    Local<FunctionTemplate> w = env->NewFunctionTemplate(Worker::New);
804
805
1335
    w->InstanceTemplate()->SetInternalFieldCount(
806
445
        Worker::kInternalFieldCount);
807
890
    w->Inherit(AsyncWrap::GetConstructorTemplate(env));
808
809
445
    env->SetProtoMethod(w, "startThread", Worker::StartThread);
810
445
    env->SetProtoMethod(w, "stopThread", Worker::StopThread);
811
445
    env->SetProtoMethod(w, "ref", Worker::Ref);
812
445
    env->SetProtoMethod(w, "unref", Worker::Unref);
813
445
    env->SetProtoMethod(w, "getResourceLimits", Worker::GetResourceLimits);
814
445
    env->SetProtoMethod(w, "takeHeapSnapshot", Worker::TakeHeapSnapshot);
815
445
    env->SetProtoMethod(w, "loopIdleTime", Worker::LoopIdleTime);
816
445
    env->SetProtoMethod(w, "loopStartTime", Worker::LoopStartTime);
817
818
    Local<String> workerString =
819
445
        FIXED_ONE_BYTE_STRING(env->isolate(), "Worker");
820
445
    w->SetClassName(workerString);
821
890
    target->Set(env->context(),
822
                workerString,
823
2225
                w->GetFunction(env->context()).ToLocalChecked()).Check();
824
  }
825
826
  {
827
445
    Local<FunctionTemplate> wst = FunctionTemplate::New(env->isolate());
828
829
1335
    wst->InstanceTemplate()->SetInternalFieldCount(
830
445
        WorkerHeapSnapshotTaker::kInternalFieldCount);
831
890
    wst->Inherit(AsyncWrap::GetConstructorTemplate(env));
832
833
    Local<String> wst_string =
834
445
        FIXED_ONE_BYTE_STRING(env->isolate(), "WorkerHeapSnapshotTaker");
835
445
    wst->SetClassName(wst_string);
836
445
    env->set_worker_heap_snapshot_taker_template(wst->InstanceTemplate());
837
  }
838
839
445
  env->SetMethod(target, "getEnvMessagePort", GetEnvMessagePort);
840
841
  target
842
890
      ->Set(env->context(),
843
            env->thread_id_string(),
844
2225
            Number::New(env->isolate(), static_cast<double>(env->thread_id())))
845
      .Check();
846
847
  target
848
890
      ->Set(env->context(),
849
            FIXED_ONE_BYTE_STRING(env->isolate(), "isMainThread"),
850
2225
            Boolean::New(env->isolate(), env->is_main_thread()))
851
      .Check();
852
853
  target
854
890
      ->Set(env->context(),
855
            FIXED_ONE_BYTE_STRING(env->isolate(), "ownsProcessState"),
856
2225
            Boolean::New(env->isolate(), env->owns_process_state()))
857
      .Check();
858
859
445
  if (!env->is_main_thread()) {
860
    target
861
786
        ->Set(env->context(),
862
              FIXED_ONE_BYTE_STRING(env->isolate(), "resourceLimits"),
863
1965
              env->worker_context()->GetResourceLimits(env->isolate()))
864
        .Check();
865
  }
866
867
890
  NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb);
868
445
  NODE_DEFINE_CONSTANT(target, kMaxOldGenerationSizeMb);
869
1335
  NODE_DEFINE_CONSTANT(target, kCodeRangeSizeMb);
870
2225
  NODE_DEFINE_CONSTANT(target, kStackSizeMb);
871
3560
  NODE_DEFINE_CONSTANT(target, kTotalResourceLimitCount);
872
4005
}
873
3115
874
5936
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
875
5491
  registry->Register(GetEnvMessagePort);
876
4601
  registry->Register(Worker::New);
877
4601
  registry->Register(Worker::StartThread);
878
4601
  registry->Register(Worker::StopThread);
879
4601
  registry->Register(Worker::Ref);
880
4601
  registry->Register(Worker::Unref);
881
4601
  registry->Register(Worker::GetResourceLimits);
882
4601
  registry->Register(Worker::TakeHeapSnapshot);
883
4601
  registry->Register(Worker::LoopIdleTime);
884
4601
  registry->Register(Worker::LoopStartTime);
885
4601
}
886
887
}  // anonymous namespace
888
}  // namespace worker
889
}  // namespace node
890
891
4670
NODE_MODULE_CONTEXT_AWARE_INTERNAL(worker, node::worker::InitWorker)
892

18635
NODE_MODULE_EXTERNAL_REFERENCE(worker, node::worker::RegisterExternalReferences)