GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_worker.cc Lines: 456 488 93.4 %
Date: 2022-10-07 04:22:37 Branches: 175 242 72.3 %

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

1143
  TRACE_EVENT_METADATA1(
275
      "__metadata", "thread_name", "name",
276
      TRACE_STR_COPY(name.c_str()));
277
962
  CHECK_NOT_NULL(platform_);
278
279
962
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
280
281
962
  WorkerThreadData data(this);
282
962
  if (isolate_ == nullptr) return;
283
738
  CHECK(data.loop_is_usable());
284
285
738
  Debug(this, "Starting worker with id %llu", thread_id_.id);
286
  {
287
738
    Locker locker(isolate_);
288
738
    Isolate::Scope isolate_scope(isolate_);
289
738
    SealHandleScope outer_seal(isolate_);
290
291
738
    DeleteFnPtr<Environment, FreeEnvironment> env_;
292
738
    auto cleanup_env = OnScopeLeave([&]() {
293
      // TODO(addaleax): This call is harmless but should not be necessary.
294
      // Figure out why V8 is raising a DCHECK() here without it
295
      // (in test/parallel/test-async-hooks-worker-asyncfn-terminate-4.js).
296
738
      isolate_->CancelTerminateExecution();
297
298
738
      if (!env_) return;
299
727
      env_->set_can_call_into_js(false);
300
301
      {
302
727
        Mutex::ScopedLock lock(mutex_);
303
727
        stopped_ = true;
304
727
        this->env_ = nullptr;
305
      }
306
307
727
      env_.reset();
308
738
    });
309
310
738
    if (is_stopped()) return;
311
    {
312
727
      HandleScope handle_scope(isolate_);
313
      Local<Context> context;
314
      {
315
        // We create the Context object before we have an Environment* in place
316
        // that we could use for error handling. If creation fails due to
317
        // resource constraints, we need something in place to handle it,
318
        // though.
319
727
        TryCatch try_catch(isolate_);
320
727
        if (snapshot_data_ != nullptr) {
321
726
          context = Context::FromSnapshot(isolate_,
322
726
                                          SnapshotData::kNodeBaseContextIndex)
323
726
                        .ToLocalChecked();
324
1452
          if (!context.IsEmpty() &&
325

2178
              !InitializeContextRuntime(context).IsJust()) {
326
            context = Local<Context>();
327
          }
328
        } else {
329
1
          context = NewContext(isolate_);
330
        }
331
727
        if (context.IsEmpty()) {
332
          // TODO(joyeecheung): maybe this should be kBootstrapFailure instead?
333
          Exit(ExitCode::kGenericUserError,
334
               "ERR_WORKER_INIT_FAILED",
335
               "Failed to create new Context");
336
          return;
337
        }
338
      }
339
340
727
      if (is_stopped()) return;
341
727
      CHECK(!context.IsEmpty());
342
727
      Context::Scope context_scope(context);
343
      {
344
1454
        env_.reset(CreateEnvironment(
345
            data.isolate_data_.get(),
346
            context,
347
727
            std::move(argv_),
348
727
            std::move(exec_argv_),
349
727
            static_cast<EnvironmentFlags::Flags>(environment_flags_),
350
            thread_id_,
351
727
            std::move(inspector_parent_handle_)));
352
727
        if (is_stopped()) return;
353
726
        CHECK_NOT_NULL(env_);
354
726
        env_->set_env_vars(std::move(env_vars_));
355
726
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
356
60
          Exit(static_cast<ExitCode>(exit_code));
357
60
        });
358
      }
359
      {
360
726
        Mutex::ScopedLock lock(mutex_);
361
726
        if (stopped_) return;
362
726
        this->env_ = env_.get();
363
      }
364
726
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
365
726
      if (is_stopped()) return;
366
      {
367
726
        if (!CreateEnvMessagePort(env_.get())) {
368
          return;
369
        }
370
371
726
        Debug(this, "Created message port for worker %llu", thread_id_.id);
372
1452
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
373
          return;
374
375
726
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
376
      }
377
    }
378
379
    {
380
726
      Maybe<ExitCode> exit_code = SpinEventLoopInternal(env_.get());
381
726
      Mutex::ScopedLock lock(mutex_);
382

1102
      if (exit_code_ == ExitCode::kNoFailure && exit_code.IsJust()) {
383
357
        exit_code_ = exit_code.FromJust();
384
      }
385
386
726
      Debug(this,
387
            "Exiting thread for worker %llu with exit code %d",
388
726
            thread_id_.id,
389
1452
            static_cast<int>(exit_code_));
390
    }
391
  }
392
393
726
  Debug(this, "Worker %llu thread stops", thread_id_.id);
394
}
395
396
726
bool Worker::CreateEnvMessagePort(Environment* env) {
397
1452
  HandleScope handle_scope(isolate_);
398
1452
  std::unique_ptr<MessagePortData> data;
399
  {
400
1452
    Mutex::ScopedLock lock(mutex_);
401
726
    data = std::move(child_port_data_);
402
  }
403
404
  // Set up the message channel for receiving messages in the child.
405
1452
  MessagePort* child_port = MessagePort::New(env,
406
                                             env->context(),
407
726
                                             std::move(data));
408
  // MessagePort::New() may return nullptr if execution is terminated
409
  // within it.
410
726
  if (child_port != nullptr)
411
726
    env->set_message_port(child_port->object(isolate_));
412
413
726
  return child_port;
414
}
415
416
967
void Worker::JoinThread() {
417
967
  if (!tid_.has_value())
418
5
    return;
419
962
  CHECK_EQ(uv_thread_join(&tid_.value()), 0);
420
962
  tid_.reset();
421
422
962
  env()->remove_sub_worker_context(this);
423
424
  {
425
1922
    HandleScope handle_scope(env()->isolate());
426
962
    Context::Scope context_scope(env()->context());
427
428
    // Reset the parent port as we're closing it now anyway.
429
962
    object()->Set(env()->context(),
430
                  env()->message_port_string(),
431
2886
                  Undefined(env()->isolate())).Check();
432
433
    Local<Value> args[] = {
434
962
        Integer::New(env()->isolate(), static_cast<int>(exit_code_)),
435
962
        custom_error_ != nullptr
436
456
            ? OneByteString(env()->isolate(), custom_error_).As<Value>()
437
2202
            : Null(env()->isolate()).As<Value>(),
438
1924
        !custom_error_str_.empty()
439
228
            ? OneByteString(env()->isolate(), custom_error_str_.c_str())
440
228
                  .As<Value>()
441
2202
            : Null(env()->isolate()).As<Value>(),
442

2886
    };
443
444
962
    MakeCallback(env()->onexit_string(), arraysize(args), args);
445
  }
446
447
  // If we get here, the tid_.has_value() condition at the top of the function
448
  // implies that the thread was running. In that case, its final action will
449
  // be to schedule a callback on the parent thread which will delete this
450
  // object, so there's nothing more to do here.
451
}
452
453
3760
Worker::~Worker() {
454
3760
  Mutex::ScopedLock lock(mutex_);
455
456
1880
  CHECK(stopped_);
457
1880
  CHECK_NULL(env_);
458
1880
  CHECK(!tid_.has_value());
459
460
1880
  Debug(this, "Worker %llu destroyed", thread_id_.id);
461
3760
}
462
463
969
void Worker::New(const FunctionCallbackInfo<Value>& args) {
464
969
  Environment* env = Environment::GetCurrent(args);
465
969
  Isolate* isolate = args.GetIsolate();
466
467
969
  CHECK(args.IsConstructCall());
468
469
969
  if (env->isolate_data()->platform() == nullptr) {
470
    THROW_ERR_MISSING_PLATFORM_FOR_WORKER(env);
471
4
    return;
472
  }
473
474
969
  std::string url;
475
969
  std::shared_ptr<PerIsolateOptions> per_isolate_opts = nullptr;
476
969
  std::shared_ptr<KVStore> env_vars = nullptr;
477
478
969
  std::vector<std::string> exec_argv_out;
479
480
  // Argument might be a string or URL
481
1938
  if (!args[0]->IsNullOrUndefined()) {
482
    Utf8Value value(
483
1467
        isolate, args[0]->ToString(env->context()).FromMaybe(Local<String>()));
484
489
    url.append(value.out(), value.length());
485
  }
486
487
1938
  if (args[1]->IsNull()) {
488
    // Means worker.env = { ...process.env }.
489
941
    env_vars = env->env_vars()->Clone(isolate);
490
28
  } else if (args[1]->IsObject()) {
491
    // User provided env.
492
27
    env_vars = KVStore::CreateMapKVStore();
493
27
    env_vars->AssignFromObject(isolate->GetCurrentContext(),
494
81
                               args[1].As<Object>());
495
  } else {
496
    // Env is shared.
497
1
    env_vars = env->env_vars();
498
  }
499
500

1911
  if (args[1]->IsObject() || args[2]->IsArray()) {
501
297
    per_isolate_opts.reset(new PerIsolateOptions());
502
503
297
    HandleEnvOptions(per_isolate_opts->per_env, [&env_vars](const char* name) {
504
2376
      return env_vars->Get(name).FromMaybe("");
505
    });
506
507
#ifndef NODE_WITHOUT_NODE_OPTIONS
508
    MaybeLocal<String> maybe_node_opts =
509
297
        env_vars->Get(isolate, OneByteString(isolate, "NODE_OPTIONS"));
510
    Local<String> node_opts;
511
297
    if (maybe_node_opts.ToLocal(&node_opts)) {
512
888
      std::string node_options(*String::Utf8Value(isolate, node_opts));
513
296
      std::vector<std::string> errors{};
514
      std::vector<std::string> env_argv =
515
296
          ParseNodeOptionsEnvVar(node_options, &errors);
516
      // [0] is expected to be the program name, add dummy string.
517
296
      env_argv.insert(env_argv.begin(), "");
518
296
      std::vector<std::string> invalid_args{};
519
296
      options_parser::Parse(&env_argv,
520
                            nullptr,
521
                            &invalid_args,
522
                            per_isolate_opts.get(),
523
                            kAllowedInEnvironment,
524
                            &errors);
525

297
      if (!errors.empty() && args[1]->IsObject()) {
526
        // Only fail for explicitly provided env, this protects from failures
527
        // when NODE_OPTIONS from parent's env is used (which is the default).
528
        Local<Value> error;
529
2
        if (!ToV8Value(env->context(), errors).ToLocal(&error)) return;
530
        Local<String> key =
531
1
            FIXED_ONE_BYTE_STRING(env->isolate(), "invalidNodeOptions");
532
        // Ignore the return value of Set() because exceptions bubble up to JS
533
        // when we return anyway.
534
1
        USE(args.This()->Set(env->context(), key, error));
535
1
        return;
536
      }
537
    }
538
#endif  // NODE_WITHOUT_NODE_OPTIONS
539
  }
540
541
968
  if (args[2]->IsArray()) {
542
293
    Local<Array> array = args[2].As<Array>();
543
    // The first argument is reserved for program name, but we don't need it
544
    // in workers.
545
1172
    std::vector<std::string> exec_argv = {""};
546
293
    uint32_t length = array->Length();
547
394
    for (uint32_t i = 0; i < length; i++) {
548
      Local<Value> arg;
549
202
      if (!array->Get(env->context(), i).ToLocal(&arg)) {
550
        return;
551
      }
552
      Local<String> arg_v8;
553
202
      if (!arg->ToString(env->context()).ToLocal(&arg_v8)) {
554
        return;
555
      }
556
202
      Utf8Value arg_utf8_value(args.GetIsolate(), arg_v8);
557
202
      std::string arg_string(arg_utf8_value.out(), arg_utf8_value.length());
558
101
      exec_argv.push_back(arg_string);
559
    }
560
561
293
    std::vector<std::string> invalid_args{};
562
293
    std::vector<std::string> errors{};
563
    // Using invalid_args as the v8_args argument as it stores unknown
564
    // options for the per isolate parser.
565
293
    options_parser::Parse(
566
        &exec_argv,
567
        &exec_argv_out,
568
        &invalid_args,
569
        per_isolate_opts.get(),
570
        kDisallowedInEnvironment,
571
        &errors);
572
573
    // The first argument is program name.
574
293
    invalid_args.erase(invalid_args.begin());
575

293
    if (errors.size() > 0 || invalid_args.size() > 0) {
576
      Local<Value> error;
577
3
      if (!ToV8Value(env->context(),
578
3
                     errors.size() > 0 ? errors : invalid_args)
579
3
                         .ToLocal(&error)) {
580
        return;
581
      }
582
      Local<String> key =
583
3
          FIXED_ONE_BYTE_STRING(env->isolate(), "invalidExecArgv");
584
      // Ignore the return value of Set() because exceptions bubble up to JS
585
      // when we return anyway.
586
3
      USE(args.This()->Set(env->context(), key, error));
587
3
      return;
588
    }
589
  } else {
590
675
    exec_argv_out = env->exec_argv();
591
  }
592
593
965
  bool use_node_snapshot = per_process::cli_options->node_snapshot;
594
  const SnapshotData* snapshot_data =
595
965
      use_node_snapshot ? SnapshotBuilder::GetEmbeddedSnapshotData() : nullptr;
596
597
  Worker* worker = new Worker(env,
598
1930
                              args.This(),
599
                              url,
600
                              per_isolate_opts,
601
965
                              std::move(exec_argv_out),
602
                              env_vars,
603
965
                              snapshot_data);
604
605
965
  CHECK(args[3]->IsFloat64Array());
606
1930
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
607
965
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
608
965
  limit_info->CopyContents(worker->resource_limits_,
609
                           sizeof(worker->resource_limits_));
610
611
965
  CHECK(args[4]->IsBoolean());
612

965
  if (args[4]->IsTrue() || env->tracks_unmanaged_fds())
613
964
    worker->environment_flags_ |= EnvironmentFlags::kTrackUnmanagedFds;
614
965
  if (env->hide_console_windows())
615
    worker->environment_flags_ |= EnvironmentFlags::kHideConsoleWindows;
616
965
  if (env->no_native_addons())
617
4
    worker->environment_flags_ |= EnvironmentFlags::kNoNativeAddons;
618
965
  if (env->no_global_search_paths())
619
    worker->environment_flags_ |= EnvironmentFlags::kNoGlobalSearchPaths;
620
965
  if (env->no_browser_globals())
621
    worker->environment_flags_ |= EnvironmentFlags::kNoBrowserGlobals;
622
}
623
624
962
void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
625
  Worker* w;
626
962
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
627
1924
  Mutex::ScopedLock lock(w->mutex_);
628
629
962
  w->stopped_ = false;
630
631
962
  if (w->resource_limits_[kStackSizeMb] > 0) {
632
6
    if (w->resource_limits_[kStackSizeMb] * kMB < kStackBufferSize) {
633
      w->resource_limits_[kStackSizeMb] = kStackBufferSize / kMB;
634
      w->stack_size_ = kStackBufferSize;
635
    } else {
636
12
      w->stack_size_ =
637
6
          static_cast<size_t>(w->resource_limits_[kStackSizeMb] * kMB);
638
    }
639
  } else {
640
956
    w->resource_limits_[kStackSizeMb] = w->stack_size_ / kMB;
641
  }
642
643
  uv_thread_options_t thread_options;
644
962
  thread_options.flags = UV_THREAD_HAS_STACK_SIZE;
645
962
  thread_options.stack_size = w->stack_size_;
646
647
962
  uv_thread_t* tid = &w->tid_.emplace();  // Create uv_thread_t instance
648
962
  int ret = uv_thread_create_ex(tid, &thread_options, [](void* arg) {
649
    // XXX: This could become a std::unique_ptr, but that makes at least
650
    // gcc 6.3 detect undefined behaviour when there shouldn't be any.
651
    // gcc 7+ handles this well.
652
962
    Worker* w = static_cast<Worker*>(arg);
653
962
    const uintptr_t stack_top = reinterpret_cast<uintptr_t>(&arg);
654
655
    // Leave a few kilobytes just to make sure we're within limits and have
656
    // some space to do work in C++ land.
657
962
    w->stack_base_ = stack_top - (w->stack_size_ - kStackBufferSize);
658
659
962
    w->Run();
660
661
962
    Mutex::ScopedLock lock(w->mutex_);
662
962
    w->env()->SetImmediateThreadsafe(
663
939
        [w = std::unique_ptr<Worker>(w)](Environment* env) {
664
939
          if (w->has_ref_)
665
937
            env->add_refs(-1);
666
939
          w->JoinThread();
667
          // implicitly delete w
668
937
        });
669
962
  }, static_cast<void*>(w));
670
671
962
  if (ret == 0) {
672
    // The object now owns the created thread and should not be garbage
673
    // collected until that finishes.
674
962
    w->ClearWeak();
675
676
962
    if (w->has_ref_)
677
962
      w->env()->add_refs(1);
678
679
962
    w->env()->add_sub_worker_context(w);
680
  } else {
681
    w->stopped_ = true;
682
    w->tid_.reset();
683
684
    char err_buf[128];
685
    uv_err_name_r(ret, err_buf, sizeof(err_buf));
686
    {
687
      Isolate* isolate = w->env()->isolate();
688
      HandleScope handle_scope(isolate);
689
      THROW_ERR_WORKER_INIT_FAILED(isolate, err_buf);
690
    }
691
  }
692
}
693
694
386
void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
695
  Worker* w;
696
386
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
697
698
386
  Debug(w, "Worker %llu is getting stopped by parent", w->thread_id_.id);
699
386
  w->Exit(ExitCode::kGenericUserError);
700
}
701
702
390
void Worker::Ref(const FunctionCallbackInfo<Value>& args) {
703
  Worker* w;
704
390
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
705

390
  if (!w->has_ref_ && w->tid_.has_value()) {
706
5
    w->has_ref_ = true;
707
5
    w->env()->add_refs(1);
708
  }
709
}
710
711
9
void Worker::HasRef(const FunctionCallbackInfo<Value>& args) {
712
  Worker* w;
713
9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
714
16
  args.GetReturnValue().Set(w->has_ref_);
715
}
716
717
7
void Worker::Unref(const FunctionCallbackInfo<Value>& args) {
718
  Worker* w;
719
7
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
720

7
  if (w->has_ref_ && w->tid_.has_value()) {
721
7
    w->has_ref_ = false;
722
7
    w->env()->add_refs(-1);
723
  }
724
}
725
726
1
void Worker::GetResourceLimits(const FunctionCallbackInfo<Value>& args) {
727
  Worker* w;
728
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
729
2
  args.GetReturnValue().Set(w->GetResourceLimits(args.GetIsolate()));
730
}
731
732
728
Local<Float64Array> Worker::GetResourceLimits(Isolate* isolate) const {
733
728
  Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, sizeof(resource_limits_));
734
735
728
  memcpy(ab->Data(), resource_limits_, sizeof(resource_limits_));
736
728
  return Float64Array::New(ab, 0, kTotalResourceLimitCount);
737
}
738
739
702
void Worker::Exit(ExitCode code,
740
                  const char* error_code,
741
                  const char* error_message) {
742
1404
  Mutex::ScopedLock lock(mutex_);
743
702
  Debug(this,
744
        "Worker %llu called Exit(%d, %s, %s)",
745
702
        thread_id_.id,
746
702
        static_cast<int>(code),
747
        error_code,
748
        error_message);
749
750
702
  if (error_code != nullptr) {
751
228
    custom_error_ = error_code;
752
228
    custom_error_str_ = error_message;
753
  }
754
755
702
  if (env_ != nullptr) {
756
372
    exit_code_ = code;
757
372
    Stop(env_);
758
  } else {
759
330
    stopped_ = true;
760
  }
761
702
}
762
763
bool Worker::IsNotIndicativeOfMemoryLeakAtExit() const {
764
  // Worker objects always stay alive as long as the child thread, regardless
765
  // of whether they are being referenced in the parent thread.
766
  return true;
767
}
768
769
class WorkerHeapSnapshotTaker : public AsyncWrap {
770
 public:
771
1
  WorkerHeapSnapshotTaker(Environment* env, Local<Object> obj)
772
1
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_WORKERHEAPSNAPSHOT) {}
773
774
  SET_NO_MEMORY_INFO()
775
  SET_MEMORY_INFO_NAME(WorkerHeapSnapshotTaker)
776
  SET_SELF_SIZE(WorkerHeapSnapshotTaker)
777
};
778
779
1
void Worker::TakeHeapSnapshot(const FunctionCallbackInfo<Value>& args) {
780
  Worker* w;
781
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
782
783
1
  Debug(w, "Worker %llu taking heap snapshot", w->thread_id_.id);
784
785
1
  Environment* env = w->env();
786
1
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(w);
787
  Local<Object> wrap;
788
1
  if (!env->worker_heap_snapshot_taker_template()
789
2
      ->NewInstance(env->context()).ToLocal(&wrap)) {
790
    return;
791
  }
792
793
  // The created WorkerHeapSnapshotTaker is an object owned by main
794
  // thread's Isolate, it can not be accessed by worker thread
795
  std::unique_ptr<BaseObjectPtr<WorkerHeapSnapshotTaker>> taker =
796
      std::make_unique<BaseObjectPtr<WorkerHeapSnapshotTaker>>(
797
2
          MakeDetachedBaseObject<WorkerHeapSnapshotTaker>(env, wrap));
798
799
  // Interrupt the worker thread and take a snapshot, then schedule a call
800
  // on the parent thread that turns that snapshot into a readable stream.
801
1
  bool scheduled = w->RequestInterrupt([taker = std::move(taker),
802
2
                                        env](Environment* worker_env) mutable {
803
    heap::HeapSnapshotPointer snapshot{
804
1
        worker_env->isolate()->GetHeapProfiler()->TakeHeapSnapshot()};
805
1
    CHECK(snapshot);
806
807
    // Here, the worker thread temporarily owns the WorkerHeapSnapshotTaker
808
    // object.
809
810
2
    env->SetImmediateThreadsafe(
811
1
        [taker = std::move(taker),
812
1
         snapshot = std::move(snapshot)](Environment* env) mutable {
813
2
          HandleScope handle_scope(env->isolate());
814
1
          Context::Scope context_scope(env->context());
815
816
2
          AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(taker->get());
817
          BaseObjectPtr<AsyncWrap> stream =
818
2
              heap::CreateHeapSnapshotStream(env, std::move(snapshot));
819
1
          Local<Value> args[] = {stream->object()};
820
1
          taker->get()->MakeCallback(
821
1
              env->ondone_string(), arraysize(args), args);
822
          // implicitly delete `taker`
823
1
        },
824
        CallbackFlags::kUnrefed);
825
826
    // Now, the lambda is delivered to the main thread, as a result, the
827
    // WorkerHeapSnapshotTaker object is delivered to the main thread, too.
828
1
  });
829
830
1
  if (scheduled) {
831
2
    args.GetReturnValue().Set(wrap);
832
  } else {
833
    args.GetReturnValue().Set(Local<Object>());
834
  }
835
}
836
837
7
void Worker::LoopIdleTime(const FunctionCallbackInfo<Value>& args) {
838
  Worker* w;
839
7
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
840
841
7
  Mutex::ScopedLock lock(w->mutex_);
842
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
843
  // before locking the mutex is a race condition. So manually do the same
844
  // check.
845

7
  if (w->stopped_ || w->env_ == nullptr)
846
    return args.GetReturnValue().Set(-1);
847
848
7
  uint64_t idle_time = uv_metrics_idle_time(w->env_->event_loop());
849
14
  args.GetReturnValue().Set(1.0 * idle_time / 1e6);
850
}
851
852
1
void Worker::LoopStartTime(const FunctionCallbackInfo<Value>& args) {
853
  Worker* w;
854
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
855
856
1
  Mutex::ScopedLock lock(w->mutex_);
857
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
858
  // before locking the mutex is a race condition. So manually do the same
859
  // check.
860

1
  if (w->stopped_ || w->env_ == nullptr)
861
    return args.GetReturnValue().Set(-1);
862
863
1
  double loop_start_time = w->env_->performance_state()->milestones[
864
1
      node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START];
865
1
  CHECK_GE(loop_start_time, 0);
866
2
  args.GetReturnValue().Set(loop_start_time / 1e6);
867
}
868
869
namespace {
870
871
// Return the MessagePort that is global for this Environment and communicates
872
// with the internal [kPort] port of the JS Worker class in the parent thread.
873
1454
void GetEnvMessagePort(const FunctionCallbackInfo<Value>& args) {
874
1454
  Environment* env = Environment::GetCurrent(args);
875
1454
  Local<Object> port = env->message_port();
876

2908
  CHECK_IMPLIES(!env->is_main_thread(), !port.IsEmpty());
877
1454
  if (!port.IsEmpty()) {
878
4362
    CHECK_EQ(port->GetCreationContext().ToLocalChecked()->GetIsolate(),
879
             args.GetIsolate());
880
2908
    args.GetReturnValue().Set(port);
881
  }
882
1454
}
883
884
787
void InitWorker(Local<Object> target,
885
                Local<Value> unused,
886
                Local<Context> context,
887
                void* priv) {
888
787
  Environment* env = Environment::GetCurrent(context);
889
787
  Isolate* isolate = env->isolate();
890
891
  {
892
787
    Local<FunctionTemplate> w = NewFunctionTemplate(isolate, Worker::New);
893
894
1574
    w->InstanceTemplate()->SetInternalFieldCount(
895
        Worker::kInternalFieldCount);
896
787
    w->Inherit(AsyncWrap::GetConstructorTemplate(env));
897
898
787
    SetProtoMethod(isolate, w, "startThread", Worker::StartThread);
899
787
    SetProtoMethod(isolate, w, "stopThread", Worker::StopThread);
900
787
    SetProtoMethod(isolate, w, "hasRef", Worker::HasRef);
901
787
    SetProtoMethod(isolate, w, "ref", Worker::Ref);
902
787
    SetProtoMethod(isolate, w, "unref", Worker::Unref);
903
787
    SetProtoMethod(isolate, w, "getResourceLimits", Worker::GetResourceLimits);
904
787
    SetProtoMethod(isolate, w, "takeHeapSnapshot", Worker::TakeHeapSnapshot);
905
787
    SetProtoMethod(isolate, w, "loopIdleTime", Worker::LoopIdleTime);
906
787
    SetProtoMethod(isolate, w, "loopStartTime", Worker::LoopStartTime);
907
908
787
    SetConstructorFunction(context, target, "Worker", w);
909
  }
910
911
  {
912
787
    Local<FunctionTemplate> wst = NewFunctionTemplate(isolate, nullptr);
913
914
1574
    wst->InstanceTemplate()->SetInternalFieldCount(
915
        WorkerHeapSnapshotTaker::kInternalFieldCount);
916
787
    wst->Inherit(AsyncWrap::GetConstructorTemplate(env));
917
918
    Local<String> wst_string =
919
787
        FIXED_ONE_BYTE_STRING(isolate, "WorkerHeapSnapshotTaker");
920
787
    wst->SetClassName(wst_string);
921
787
    env->set_worker_heap_snapshot_taker_template(wst->InstanceTemplate());
922
  }
923
924
787
  SetMethod(context, target, "getEnvMessagePort", GetEnvMessagePort);
925
926
  target
927
787
      ->Set(env->context(),
928
            env->thread_id_string(),
929
3148
            Number::New(isolate, static_cast<double>(env->thread_id())))
930
      .Check();
931
932
  target
933
787
      ->Set(env->context(),
934
            FIXED_ONE_BYTE_STRING(isolate, "isMainThread"),
935
3148
            Boolean::New(isolate, env->is_main_thread()))
936
      .Check();
937
938
  target
939
787
      ->Set(env->context(),
940
            FIXED_ONE_BYTE_STRING(isolate, "ownsProcessState"),
941
2361
            Boolean::New(isolate, env->owns_process_state()))
942
      .Check();
943
944
787
  if (!env->is_main_thread()) {
945
    target
946
727
        ->Set(env->context(),
947
              FIXED_ONE_BYTE_STRING(isolate, "resourceLimits"),
948
2908
              env->worker_context()->GetResourceLimits(isolate))
949
        .Check();
950
  }
951
952
2361
  NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb);
953
2361
  NODE_DEFINE_CONSTANT(target, kMaxOldGenerationSizeMb);
954
2361
  NODE_DEFINE_CONSTANT(target, kCodeRangeSizeMb);
955
2361
  NODE_DEFINE_CONSTANT(target, kStackSizeMb);
956
1574
  NODE_DEFINE_CONSTANT(target, kTotalResourceLimitCount);
957
787
}
958
959
5524
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
960
5524
  registry->Register(GetEnvMessagePort);
961
5524
  registry->Register(Worker::New);
962
5524
  registry->Register(Worker::StartThread);
963
5524
  registry->Register(Worker::StopThread);
964
5524
  registry->Register(Worker::HasRef);
965
5524
  registry->Register(Worker::Ref);
966
5524
  registry->Register(Worker::Unref);
967
5524
  registry->Register(Worker::GetResourceLimits);
968
5524
  registry->Register(Worker::TakeHeapSnapshot);
969
5524
  registry->Register(Worker::LoopIdleTime);
970
5524
  registry->Register(Worker::LoopStartTime);
971
5524
}
972
973
}  // anonymous namespace
974
}  // namespace worker
975
}  // namespace node
976
977
5594
NODE_MODULE_CONTEXT_AWARE_INTERNAL(worker, node::worker::InitWorker)
978
5524
NODE_MODULE_EXTERNAL_REFERENCE(worker, node::worker::RegisterExternalReferences)