GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_worker.cc Lines: 410 460 89.1 %
Date: 2021-10-05 04:12:38 Branches: 152 214 71.0 %

Line Branch Exec Source
1
#include "node_worker.h"
2
#include "debug_utils-inl.h"
3
#include "histogram-inl.h"
4
#include "memory_tracker-inl.h"
5
#include "node_errors.h"
6
#include "node_external_reference.h"
7
#include "node_buffer.h"
8
#include "node_options-inl.h"
9
#include "node_perf.h"
10
#include "util-inl.h"
11
#include "async_wrap-inl.h"
12
13
#include <memory>
14
#include <string>
15
#include <vector>
16
17
using node::kAllowedInEnvironment;
18
using node::kDisallowedInEnvironment;
19
using v8::Array;
20
using v8::ArrayBuffer;
21
using v8::Boolean;
22
using v8::Context;
23
using v8::Float64Array;
24
using v8::FunctionCallbackInfo;
25
using v8::FunctionTemplate;
26
using v8::HandleScope;
27
using v8::Integer;
28
using v8::Isolate;
29
using v8::Local;
30
using v8::Locker;
31
using v8::Maybe;
32
using v8::MaybeLocal;
33
using v8::Null;
34
using v8::Number;
35
using v8::Object;
36
using v8::ResourceConstraints;
37
using v8::SealHandleScope;
38
using v8::String;
39
using v8::TryCatch;
40
using v8::Value;
41
42
namespace node {
43
namespace worker {
44
45
constexpr double kMB = 1024 * 1024;
46
47
805
Worker::Worker(Environment* env,
48
               Local<Object> wrap,
49
               const std::string& url,
50
               std::shared_ptr<PerIsolateOptions> per_isolate_opts,
51
               std::vector<std::string>&& exec_argv,
52
805
               std::shared_ptr<KVStore> env_vars)
53
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_WORKER),
54
      per_isolate_opts_(per_isolate_opts),
55
      exec_argv_(exec_argv),
56
805
      platform_(env->isolate_data()->platform()),
57
805
      thread_id_(AllocateEnvironmentThreadId()),
58
1610
      env_vars_(env_vars) {
59
805
  Debug(this, "Creating new worker instance with thread id %llu",
60
805
        thread_id_.id);
61
62
  // Set up everything that needs to be set up in the parent environment.
63
805
  parent_port_ = MessagePort::New(env, env->context());
64
805
  if (parent_port_ == nullptr) {
65
    // This can happen e.g. because execution is terminating.
66
    return;
67
  }
68
69
805
  child_port_data_ = std::make_unique<MessagePortData>(nullptr);
70
805
  MessagePort::Entangle(parent_port_, child_port_data_.get());
71
72
805
  object()->Set(env->context(),
73
                env->message_port_string(),
74
2415
                parent_port_->object()).Check();
75
76
805
  object()->Set(env->context(),
77
                env->thread_id_string(),
78
2415
                Number::New(env->isolate(), static_cast<double>(thread_id_.id)))
79
      .Check();
80
81
1610
  inspector_parent_handle_ = GetInspectorParentHandle(
82
805
      env, thread_id_, url.c_str());
83
84
1610
  argv_ = std::vector<std::string>{env->argv()[0]};
85
  // Mark this Worker object as weak until we actually start the thread.
86
805
  MakeWeak();
87
88
805
  Debug(this, "Preparation for worker %llu finished", thread_id_.id);
89
}
90
91
2256
bool Worker::is_stopped() const {
92
4512
  Mutex::ScopedLock lock(mutex_);
93
2256
  if (env_ != nullptr)
94
559
    return env_->is_stopping();
95
1697
  return stopped_;
96
}
97
98
575
void Worker::UpdateResourceConstraints(ResourceConstraints* constraints) {
99
575
  constraints->set_stack_limit(reinterpret_cast<uint32_t*>(stack_base_));
100
101
575
  if (resource_limits_[kMaxYoungGenerationSizeMb] > 0) {
102
1
    constraints->set_max_young_generation_size_in_bytes(
103
1
        static_cast<size_t>(resource_limits_[kMaxYoungGenerationSizeMb] * kMB));
104
  } else {
105
574
    resource_limits_[kMaxYoungGenerationSizeMb] =
106
574
        constraints->max_young_generation_size_in_bytes() / kMB;
107
  }
108
109
575
  if (resource_limits_[kMaxOldGenerationSizeMb] > 0) {
110
3
    constraints->set_max_old_generation_size_in_bytes(
111
3
        static_cast<size_t>(resource_limits_[kMaxOldGenerationSizeMb] * kMB));
112
  } else {
113
572
    resource_limits_[kMaxOldGenerationSizeMb] =
114
572
        constraints->max_old_generation_size_in_bytes() / kMB;
115
  }
116
117
575
  if (resource_limits_[kCodeRangeSizeMb] > 0) {
118
1
    constraints->set_code_range_size_in_bytes(
119
1
        static_cast<size_t>(resource_limits_[kCodeRangeSizeMb] * kMB));
120
  } else {
121
574
    resource_limits_[kCodeRangeSizeMb] =
122
574
        constraints->code_range_size_in_bytes() / kMB;
123
  }
124
575
}
125
126
// This class contains data that is only relevant to the child thread itself,
127
// and only while it is running.
128
// (Eventually, the Environment instance should probably also be moved here.)
129
class WorkerThreadData {
130
 public:
131
802
  explicit WorkerThreadData(Worker* w)
132
802
    : w_(w) {
133
802
    int ret = uv_loop_init(&loop_);
134
802
    if (ret != 0) {
135
      char err_buf[128];
136
227
      uv_err_name_r(ret, err_buf, sizeof(err_buf));
137
227
      w->Exit(1, "ERR_WORKER_INIT_FAILED", err_buf);
138
227
      return;
139
    }
140
575
    loop_init_failed_ = false;
141
575
    uv_loop_configure(&loop_, UV_METRICS_IDLE_TIME);
142
143
    std::shared_ptr<ArrayBufferAllocator> allocator =
144
575
        ArrayBufferAllocator::Create();
145
575
    Isolate::CreateParams params;
146
575
    SetIsolateCreateParamsForNode(&params);
147
575
    params.array_buffer_allocator_shared = allocator;
148
149
575
    w->UpdateResourceConstraints(&params.constraints);
150
151
575
    Isolate* isolate = Isolate::Allocate();
152
575
    if (isolate == nullptr) {
153
      w->Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Isolate");
154
      return;
155
    }
156
157
575
    w->platform_->RegisterIsolate(isolate, &loop_);
158
575
    Isolate::Initialize(isolate, params);
159
575
    SetIsolateUpForNode(isolate);
160
161
    // Be sure it's called before Environment::InitializeDiagnostics()
162
    // so that this callback stays when the callback of
163
    // --heapsnapshot-near-heap-limit gets is popped.
164
575
    isolate->AddNearHeapLimitCallback(Worker::NearHeapLimit, w);
165
166
    {
167
575
      Locker locker(isolate);
168
1150
      Isolate::Scope isolate_scope(isolate);
169
      // V8 computes its stack limit the first time a `Locker` is used based on
170
      // --stack-size. Reset it to the correct value.
171
575
      isolate->SetStackLimit(w->stack_base_);
172
173
575
      HandleScope handle_scope(isolate);
174
1150
      isolate_data_.reset(CreateIsolateData(isolate,
175
                                            &loop_,
176
575
                                            w_->platform_,
177
                                            allocator.get()));
178
575
      CHECK(isolate_data_);
179
575
      if (w_->per_isolate_opts_)
180
257
        isolate_data_->set_options(std::move(w_->per_isolate_opts_));
181
575
      isolate_data_->set_worker_context(w_);
182
1150
      isolate_data_->max_young_gen_size =
183
575
          params.constraints.max_young_generation_size_in_bytes();
184
    }
185
186
575
    Mutex::ScopedLock lock(w_->mutex_);
187
575
    w_->isolate_ = isolate;
188
  }
189
190
802
  ~WorkerThreadData() {
191
802
    Debug(w_, "Worker %llu dispose isolate", w_->thread_id_.id);
192
    Isolate* isolate;
193
    {
194
802
      Mutex::ScopedLock lock(w_->mutex_);
195
802
      isolate = w_->isolate_;
196
802
      w_->isolate_ = nullptr;
197
    }
198
199
802
    if (isolate != nullptr) {
200
575
      CHECK(!loop_init_failed_);
201
575
      bool platform_finished = false;
202
203
575
      isolate_data_.reset();
204
205
575
      w_->platform_->AddIsolateFinishedCallback(isolate, [](void* data) {
206
575
        *static_cast<bool*>(data) = true;
207
575
      }, &platform_finished);
208
209
      // The order of these calls is important; if the Isolate is first disposed
210
      // and then unregistered, there is a race condition window in which no
211
      // new Isolate at the same address can successfully be registered with
212
      // the platform.
213
      // (Refs: https://github.com/nodejs/node/issues/30846)
214
575
      w_->platform_->UnregisterIsolate(isolate);
215
575
      isolate->Dispose();
216
217
      // Wait until the platform has cleaned up all relevant resources.
218
1150
      while (!platform_finished) {
219
575
        uv_run(&loop_, UV_RUN_ONCE);
220
      }
221
    }
222
802
    if (!loop_init_failed_) {
223
575
      CheckedUvLoopClose(&loop_);
224
    }
225
802
  }
226
227
575
  bool loop_is_usable() const { return !loop_init_failed_; }
228
229
 private:
230
  Worker* const w_;
231
  uv_loop_t loop_;
232
  bool loop_init_failed_ = true;
233
  DeleteFnPtr<IsolateData, FreeIsolateData> isolate_data_;
234
235
  friend class Worker;
236
};
237
238
3
size_t Worker::NearHeapLimit(void* data, size_t current_heap_limit,
239
                             size_t initial_heap_limit) {
240
3
  Worker* worker = static_cast<Worker*>(data);
241
3
  worker->Exit(1, "ERR_WORKER_OUT_OF_MEMORY", "JS heap out of memory");
242
  // Give the current GC some extra leeway to let it finish rather than
243
  // crash hard. We are not going to perform further allocations anyway.
244
3
  constexpr size_t kExtraHeapAllowance = 16 * 1024 * 1024;
245
3
  return current_heap_limit + kExtraHeapAllowance;
246
}
247
248
802
void Worker::Run() {
249
802
  std::string name = "WorkerThread ";
250
802
  name += std::to_string(thread_id_.id);
251

965
  TRACE_EVENT_METADATA1(
252
      "__metadata", "thread_name", "name",
253
      TRACE_STR_COPY(name.c_str()));
254
802
  CHECK_NOT_NULL(platform_);
255
256
802
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
257
258
802
  WorkerThreadData data(this);
259
802
  if (isolate_ == nullptr) return;
260
575
  CHECK(data.loop_is_usable());
261
262
575
  Debug(this, "Starting worker with id %llu", thread_id_.id);
263
  {
264
575
    Locker locker(isolate_);
265
575
    Isolate::Scope isolate_scope(isolate_);
266
575
    SealHandleScope outer_seal(isolate_);
267
268
575
    DeleteFnPtr<Environment, FreeEnvironment> env_;
269
575
    auto cleanup_env = OnScopeLeave([&]() {
270
      // TODO(addaleax): This call is harmless but should not be necessary.
271
      // Figure out why V8 is raising a DCHECK() here without it
272
      // (in test/parallel/test-async-hooks-worker-asyncfn-terminate-4.js).
273
575
      isolate_->CancelTerminateExecution();
274
275
575
      if (!env_) return;
276
560
      env_->set_can_call_into_js(false);
277
278
      {
279
560
        Mutex::ScopedLock lock(mutex_);
280
560
        stopped_ = true;
281
560
        this->env_ = nullptr;
282
      }
283
284
560
      env_.reset();
285
575
    });
286
287
575
    if (is_stopped()) return;
288
    {
289
566
      HandleScope handle_scope(isolate_);
290
      Local<Context> context;
291
      {
292
        // We create the Context object before we have an Environment* in place
293
        // that we could use for error handling. If creation fails due to
294
        // resource constraints, we need something in place to handle it,
295
        // though.
296
566
        TryCatch try_catch(isolate_);
297
566
        context = NewContext(isolate_);
298
566
        if (context.IsEmpty()) {
299
4
          Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Context");
300
4
          return;
301
        }
302
      }
303
304
562
      if (is_stopped()) return;
305
560
      CHECK(!context.IsEmpty());
306
560
      Context::Scope context_scope(context);
307
      {
308
1120
        env_.reset(CreateEnvironment(
309
            data.isolate_data_.get(),
310
            context,
311
560
            std::move(argv_),
312
560
            std::move(exec_argv_),
313
560
            static_cast<EnvironmentFlags::Flags>(environment_flags_),
314
            thread_id_,
315
560
            std::move(inspector_parent_handle_)));
316
560
        if (is_stopped()) return;
317
559
        CHECK_NOT_NULL(env_);
318
559
        env_->set_env_vars(std::move(env_vars_));
319
559
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
320
70
          Exit(exit_code);
321
70
        });
322
      }
323
      {
324
559
        Mutex::ScopedLock lock(mutex_);
325
559
        if (stopped_) return;
326
559
        this->env_ = env_.get();
327
      }
328
559
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
329
559
      if (is_stopped()) return;
330
      {
331
559
        if (!CreateEnvMessagePort(env_.get())) {
332
          return;
333
        }
334
335
559
        Debug(this, "Created message port for worker %llu", thread_id_.id);
336
1118
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
337
          return;
338
339
559
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
340
      }
341
    }
342
343
    {
344
559
      Maybe<int> exit_code = SpinEventLoop(env_.get());
345
1118
      Mutex::ScopedLock lock(mutex_);
346

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

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

1592
  if (args[1]->IsObject() || args[2]->IsArray()) {
463
261
    per_isolate_opts.reset(new PerIsolateOptions());
464
465
261
    HandleEnvOptions(per_isolate_opts->per_env, [&env_vars](const char* name) {
466
2088
      return env_vars->Get(name).FromMaybe("");
467
    });
468
469
#ifndef NODE_WITHOUT_NODE_OPTIONS
470
    MaybeLocal<String> maybe_node_opts =
471
261
        env_vars->Get(isolate, OneByteString(isolate, "NODE_OPTIONS"));
472
    Local<String> node_opts;
473
261
    if (maybe_node_opts.ToLocal(&node_opts)) {
474
780
      std::string node_options(*String::Utf8Value(isolate, node_opts));
475
260
      std::vector<std::string> errors{};
476
      std::vector<std::string> env_argv =
477
260
          ParseNodeOptionsEnvVar(node_options, &errors);
478
      // [0] is expected to be the program name, add dummy string.
479
260
      env_argv.insert(env_argv.begin(), "");
480
260
      std::vector<std::string> invalid_args{};
481
260
      options_parser::Parse(&env_argv,
482
                            nullptr,
483
                            &invalid_args,
484
                            per_isolate_opts.get(),
485
                            kAllowedInEnvironment,
486
                            &errors);
487

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

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

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

230
  if (!w->has_ref_ && !w->thread_joined_) {
659
3
    w->has_ref_ = true;
660
3
    w->env()->add_refs(1);
661
  }
662
}
663
664
5
void Worker::Unref(const FunctionCallbackInfo<Value>& args) {
665
  Worker* w;
666
5
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
667

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

7
  if (w->stopped_ || w->env_ == nullptr)
772
    return args.GetReturnValue().Set(-1);
773
774
7
  uint64_t idle_time = uv_metrics_idle_time(w->env_->event_loop());
775
14
  args.GetReturnValue().Set(1.0 * idle_time / 1e6);
776
}
777
778
1
void Worker::LoopStartTime(const FunctionCallbackInfo<Value>& args) {
779
  Worker* w;
780
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
781
782
1
  Mutex::ScopedLock lock(w->mutex_);
783
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
784
  // before locking the mutex is a race condition. So manually do the same
785
  // check.
786

1
  if (w->stopped_ || w->env_ == nullptr)
787
    return args.GetReturnValue().Set(-1);
788
789
1
  double loop_start_time = w->env_->performance_state()->milestones[
790
1
      node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START];
791
1
  CHECK_GE(loop_start_time, 0);
792
1
  args.GetReturnValue().Set(
793
1
      (loop_start_time - node::performance::timeOrigin) / 1e6);
794
}
795
796
namespace {
797
798
// Return the MessagePort that is global for this Environment and communicates
799
// with the internal [kPort] port of the JS Worker class in the parent thread.
800
1119
void GetEnvMessagePort(const FunctionCallbackInfo<Value>& args) {
801
1119
  Environment* env = Environment::GetCurrent(args);
802
1119
  Local<Object> port = env->message_port();
803

2238
  CHECK_IMPLIES(!env->is_main_thread(), !port.IsEmpty());
804
1119
  if (!port.IsEmpty()) {
805
3357
    CHECK_EQ(port->GetCreationContext().ToLocalChecked()->GetIsolate(),
806
             args.GetIsolate());
807
2238
    args.GetReturnValue().Set(port);
808
  }
809
1119
}
810
811
615
void InitWorker(Local<Object> target,
812
                Local<Value> unused,
813
                Local<Context> context,
814
                void* priv) {
815
615
  Environment* env = Environment::GetCurrent(context);
816
817
  {
818
615
    Local<FunctionTemplate> w = env->NewFunctionTemplate(Worker::New);
819
820
1230
    w->InstanceTemplate()->SetInternalFieldCount(
821
        Worker::kInternalFieldCount);
822
615
    w->Inherit(AsyncWrap::GetConstructorTemplate(env));
823
824
615
    env->SetProtoMethod(w, "startThread", Worker::StartThread);
825
615
    env->SetProtoMethod(w, "stopThread", Worker::StopThread);
826
615
    env->SetProtoMethod(w, "ref", Worker::Ref);
827
615
    env->SetProtoMethod(w, "unref", Worker::Unref);
828
615
    env->SetProtoMethod(w, "getResourceLimits", Worker::GetResourceLimits);
829
615
    env->SetProtoMethod(w, "takeHeapSnapshot", Worker::TakeHeapSnapshot);
830
615
    env->SetProtoMethod(w, "loopIdleTime", Worker::LoopIdleTime);
831
615
    env->SetProtoMethod(w, "loopStartTime", Worker::LoopStartTime);
832
833
615
    env->SetConstructorFunction(target, "Worker", w);
834
  }
835
836
  {
837
615
    Local<FunctionTemplate> wst = FunctionTemplate::New(env->isolate());
838
839
1230
    wst->InstanceTemplate()->SetInternalFieldCount(
840
        WorkerHeapSnapshotTaker::kInternalFieldCount);
841
615
    wst->Inherit(AsyncWrap::GetConstructorTemplate(env));
842
843
    Local<String> wst_string =
844
615
        FIXED_ONE_BYTE_STRING(env->isolate(), "WorkerHeapSnapshotTaker");
845
615
    wst->SetClassName(wst_string);
846
615
    env->set_worker_heap_snapshot_taker_template(wst->InstanceTemplate());
847
  }
848
849
615
  env->SetMethod(target, "getEnvMessagePort", GetEnvMessagePort);
850
851
  target
852
615
      ->Set(env->context(),
853
            env->thread_id_string(),
854
2460
            Number::New(env->isolate(), static_cast<double>(env->thread_id())))
855
      .Check();
856
857
  target
858
615
      ->Set(env->context(),
859
            FIXED_ONE_BYTE_STRING(env->isolate(), "isMainThread"),
860
2460
            Boolean::New(env->isolate(), env->is_main_thread()))
861
      .Check();
862
863
  target
864
615
      ->Set(env->context(),
865
            FIXED_ONE_BYTE_STRING(env->isolate(), "ownsProcessState"),
866
1845
            Boolean::New(env->isolate(), env->owns_process_state()))
867
      .Check();
868
869
615
  if (!env->is_main_thread()) {
870
    target
871
560
        ->Set(env->context(),
872
              FIXED_ONE_BYTE_STRING(env->isolate(), "resourceLimits"),
873
2240
              env->worker_context()->GetResourceLimits(env->isolate()))
874
        .Check();
875
  }
876
877
1845
  NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb);
878
1845
  NODE_DEFINE_CONSTANT(target, kMaxOldGenerationSizeMb);
879
1845
  NODE_DEFINE_CONSTANT(target, kCodeRangeSizeMb);
880
1845
  NODE_DEFINE_CONSTANT(target, kStackSizeMb);
881
1230
  NODE_DEFINE_CONSTANT(target, kTotalResourceLimitCount);
882
615
}
883
884
4853
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
885
4853
  registry->Register(GetEnvMessagePort);
886
4853
  registry->Register(Worker::New);
887
4853
  registry->Register(Worker::StartThread);
888
4853
  registry->Register(Worker::StopThread);
889
4853
  registry->Register(Worker::Ref);
890
4853
  registry->Register(Worker::Unref);
891
4853
  registry->Register(Worker::GetResourceLimits);
892
4853
  registry->Register(Worker::TakeHeapSnapshot);
893
4853
  registry->Register(Worker::LoopIdleTime);
894
4853
  registry->Register(Worker::LoopStartTime);
895
4853
}
896
897
}  // anonymous namespace
898
}  // namespace worker
899
}  // namespace node
900
901
4926
NODE_MODULE_CONTEXT_AWARE_INTERNAL(worker, node::worker::InitWorker)
902
4853
NODE_MODULE_EXTERNAL_REFERENCE(worker, node::worker::RegisterExternalReferences)