GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_worker.cc Lines: 445 476 93.5 %
Date: 2022-09-07 04:19:57 Branches: 174 240 72.5 %

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
960
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
960
               const SnapshotData* snapshot_data)
55
    : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_WORKER),
56
      per_isolate_opts_(per_isolate_opts),
57
      exec_argv_(exec_argv),
58
960
      platform_(env->isolate_data()->platform()),
59
960
      thread_id_(AllocateEnvironmentThreadId()),
60
      env_vars_(env_vars),
61
1920
      snapshot_data_(snapshot_data) {
62
960
  Debug(this, "Creating new worker instance with thread id %llu",
63
960
        thread_id_.id);
64
65
  // Set up everything that needs to be set up in the parent environment.
66
960
  MessagePort* parent_port = MessagePort::New(env, env->context());
67
960
  if (parent_port == nullptr) {
68
    // This can happen e.g. because execution is terminating.
69
    return;
70
  }
71
72
960
  child_port_data_ = std::make_unique<MessagePortData>(nullptr);
73
960
  MessagePort::Entangle(parent_port, child_port_data_.get());
74
75
960
  object()
76
2880
      ->Set(env->context(), env->message_port_string(), parent_port->object())
77
      .Check();
78
79
960
  object()->Set(env->context(),
80
                env->thread_id_string(),
81
2880
                Number::New(env->isolate(), static_cast<double>(thread_id_.id)))
82
      .Check();
83
84
1920
  inspector_parent_handle_ = GetInspectorParentHandle(
85
960
      env, thread_id_, url.c_str());
86
87
1920
  argv_ = std::vector<std::string>{env->argv()[0]};
88
  // Mark this Worker object as weak until we actually start the thread.
89
960
  MakeWeak();
90
91
960
  Debug(this, "Preparation for worker %llu finished", thread_id_.id);
92
}
93
94
2890
bool Worker::is_stopped() const {
95
5780
  Mutex::ScopedLock lock(mutex_);
96
2890
  if (env_ != nullptr)
97
719
    return env_->is_stopping();
98
2171
  return stopped_;
99
}
100
101
731
void Worker::UpdateResourceConstraints(ResourceConstraints* constraints) {
102
731
  constraints->set_stack_limit(reinterpret_cast<uint32_t*>(stack_base_));
103
104
731
  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
730
    resource_limits_[kMaxYoungGenerationSizeMb] =
109
730
        constraints->max_young_generation_size_in_bytes() / kMB;
110
  }
111
112
731
  if (resource_limits_[kMaxOldGenerationSizeMb] > 0) {
113
3
    constraints->set_max_old_generation_size_in_bytes(
114
3
        static_cast<size_t>(resource_limits_[kMaxOldGenerationSizeMb] * kMB));
115
  } else {
116
728
    resource_limits_[kMaxOldGenerationSizeMb] =
117
728
        constraints->max_old_generation_size_in_bytes() / kMB;
118
  }
119
120
731
  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
730
    resource_limits_[kCodeRangeSizeMb] =
125
730
        constraints->code_range_size_in_bytes() / kMB;
126
  }
127
731
}
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
957
  explicit WorkerThreadData(Worker* w)
135
957
    : w_(w) {
136
957
    int ret = uv_loop_init(&loop_);
137
957
    if (ret != 0) {
138
      char err_buf[128];
139
226
      uv_err_name_r(ret, err_buf, sizeof(err_buf));
140
226
      w->Exit(1, "ERR_WORKER_INIT_FAILED", err_buf);
141
226
      return;
142
    }
143
731
    loop_init_failed_ = false;
144
731
    uv_loop_configure(&loop_, UV_METRICS_IDLE_TIME);
145
146
    std::shared_ptr<ArrayBufferAllocator> allocator =
147
731
        ArrayBufferAllocator::Create();
148
731
    Isolate::CreateParams params;
149
731
    SetIsolateCreateParamsForNode(&params);
150
731
    params.array_buffer_allocator_shared = allocator;
151
152
731
    if (w->snapshot_data() != nullptr) {
153
730
      SnapshotBuilder::InitializeIsolateParams(w->snapshot_data(), &params);
154
    }
155
731
    w->UpdateResourceConstraints(&params.constraints);
156
157
731
    Isolate* isolate = Isolate::Allocate();
158
731
    if (isolate == nullptr) {
159
      w->Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Isolate");
160
      return;
161
    }
162
163
731
    w->platform_->RegisterIsolate(isolate, &loop_);
164
731
    Isolate::Initialize(isolate, params);
165
731
    SetIsolateUpForNode(isolate);
166
167
    // Be sure it's called before Environment::InitializeDiagnostics()
168
    // so that this callback stays when the callback of
169
    // --heapsnapshot-near-heap-limit gets is popped.
170
731
    isolate->AddNearHeapLimitCallback(Worker::NearHeapLimit, w);
171
172
    {
173
731
      Locker locker(isolate);
174
1462
      Isolate::Scope isolate_scope(isolate);
175
      // V8 computes its stack limit the first time a `Locker` is used based on
176
      // --stack-size. Reset it to the correct value.
177
731
      isolate->SetStackLimit(w->stack_base_);
178
179
731
      HandleScope handle_scope(isolate);
180
1462
      isolate_data_.reset(CreateIsolateData(isolate,
181
                                            &loop_,
182
731
                                            w_->platform_,
183
                                            allocator.get()));
184
731
      CHECK(isolate_data_);
185
731
      if (w_->per_isolate_opts_)
186
288
        isolate_data_->set_options(std::move(w_->per_isolate_opts_));
187
731
      isolate_data_->set_worker_context(w_);
188
731
      isolate_data_->max_young_gen_size =
189
731
          params.constraints.max_young_generation_size_in_bytes();
190
    }
191
192
731
    Mutex::ScopedLock lock(w_->mutex_);
193
731
    w_->isolate_ = isolate;
194
  }
195
196
957
  ~WorkerThreadData() {
197
957
    Debug(w_, "Worker %llu dispose isolate", w_->thread_id_.id);
198
    Isolate* isolate;
199
    {
200
957
      Mutex::ScopedLock lock(w_->mutex_);
201
957
      isolate = w_->isolate_;
202
957
      w_->isolate_ = nullptr;
203
    }
204
205
957
    if (isolate != nullptr) {
206
731
      CHECK(!loop_init_failed_);
207
731
      bool platform_finished = false;
208
209
731
      isolate_data_.reset();
210
211
731
      w_->platform_->AddIsolateFinishedCallback(isolate, [](void* data) {
212
731
        *static_cast<bool*>(data) = true;
213
731
      }, &platform_finished);
214
215
      // The order of these calls is important; if the Isolate is first disposed
216
      // and then unregistered, there is a race condition window in which no
217
      // new Isolate at the same address can successfully be registered with
218
      // the platform.
219
      // (Refs: https://github.com/nodejs/node/issues/30846)
220
731
      w_->platform_->UnregisterIsolate(isolate);
221
731
      isolate->Dispose();
222
223
      // Wait until the platform has cleaned up all relevant resources.
224
1462
      while (!platform_finished) {
225
731
        uv_run(&loop_, UV_RUN_ONCE);
226
      }
227
    }
228
957
    if (!loop_init_failed_) {
229
731
      CheckedUvLoopClose(&loop_);
230
    }
231
957
  }
232
233
731
  bool loop_is_usable() const { return !loop_init_failed_; }
234
235
 private:
236
  Worker* const w_;
237
  uv_loop_t loop_;
238
  bool loop_init_failed_ = true;
239
  DeleteFnPtr<IsolateData, FreeIsolateData> isolate_data_;
240
  const SnapshotData* snapshot_data_ = nullptr;
241
  friend class Worker;
242
};
243
244
3
size_t Worker::NearHeapLimit(void* data, size_t current_heap_limit,
245
                             size_t initial_heap_limit) {
246
3
  Worker* worker = static_cast<Worker*>(data);
247
3
  worker->Exit(1, "ERR_WORKER_OUT_OF_MEMORY", "JS heap out of memory");
248
  // Give the current GC some extra leeway to let it finish rather than
249
  // crash hard. We are not going to perform further allocations anyway.
250
3
  constexpr size_t kExtraHeapAllowance = 16 * 1024 * 1024;
251
3
  return current_heap_limit + kExtraHeapAllowance;
252
}
253
254
957
void Worker::Run() {
255
957
  std::string name = "WorkerThread ";
256
957
  name += std::to_string(thread_id_.id);
257

1136
  TRACE_EVENT_METADATA1(
258
      "__metadata", "thread_name", "name",
259
      TRACE_STR_COPY(name.c_str()));
260
957
  CHECK_NOT_NULL(platform_);
261
262
957
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
263
264
957
  WorkerThreadData data(this);
265
957
  if (isolate_ == nullptr) return;
266
731
  CHECK(data.loop_is_usable());
267
268
731
  Debug(this, "Starting worker with id %llu", thread_id_.id);
269
  {
270
731
    Locker locker(isolate_);
271
731
    Isolate::Scope isolate_scope(isolate_);
272
731
    SealHandleScope outer_seal(isolate_);
273
274
731
    DeleteFnPtr<Environment, FreeEnvironment> env_;
275
731
    auto cleanup_env = OnScopeLeave([&]() {
276
      // TODO(addaleax): This call is harmless but should not be necessary.
277
      // Figure out why V8 is raising a DCHECK() here without it
278
      // (in test/parallel/test-async-hooks-worker-asyncfn-terminate-4.js).
279
731
      isolate_->CancelTerminateExecution();
280
281
731
      if (!env_) return;
282
720
      env_->set_can_call_into_js(false);
283
284
      {
285
720
        Mutex::ScopedLock lock(mutex_);
286
720
        stopped_ = true;
287
720
        this->env_ = nullptr;
288
      }
289
290
720
      env_.reset();
291
731
    });
292
293
731
    if (is_stopped()) return;
294
    {
295
720
      HandleScope handle_scope(isolate_);
296
      Local<Context> context;
297
      {
298
        // We create the Context object before we have an Environment* in place
299
        // that we could use for error handling. If creation fails due to
300
        // resource constraints, we need something in place to handle it,
301
        // though.
302
720
        TryCatch try_catch(isolate_);
303
720
        if (snapshot_data_ != nullptr) {
304
719
          context = Context::FromSnapshot(isolate_,
305
719
                                          SnapshotData::kNodeBaseContextIndex)
306
719
                        .ToLocalChecked();
307
1438
          if (!context.IsEmpty() &&
308

2157
              !InitializeContextRuntime(context).IsJust()) {
309
            context = Local<Context>();
310
          }
311
        } else {
312
1
          context = NewContext(isolate_);
313
        }
314
720
        if (context.IsEmpty()) {
315
          Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Context");
316
          return;
317
        }
318
      }
319
320
720
      if (is_stopped()) return;
321
720
      CHECK(!context.IsEmpty());
322
720
      Context::Scope context_scope(context);
323
      {
324
1440
        env_.reset(CreateEnvironment(
325
            data.isolate_data_.get(),
326
            context,
327
720
            std::move(argv_),
328
720
            std::move(exec_argv_),
329
720
            static_cast<EnvironmentFlags::Flags>(environment_flags_),
330
            thread_id_,
331
720
            std::move(inspector_parent_handle_)));
332
720
        if (is_stopped()) return;
333
719
        CHECK_NOT_NULL(env_);
334
719
        env_->set_env_vars(std::move(env_vars_));
335
719
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
336
60
          Exit(exit_code);
337
60
        });
338
      }
339
      {
340
719
        Mutex::ScopedLock lock(mutex_);
341
719
        if (stopped_) return;
342
719
        this->env_ = env_.get();
343
      }
344
719
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
345
719
      if (is_stopped()) return;
346
      {
347
719
        if (!CreateEnvMessagePort(env_.get())) {
348
          return;
349
        }
350
351
719
        Debug(this, "Created message port for worker %llu", thread_id_.id);
352
1438
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
353
          return;
354
355
719
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
356
      }
357
    }
358
359
    {
360
719
      Maybe<int> exit_code = SpinEventLoop(env_.get());
361
1438
      Mutex::ScopedLock lock(mutex_);
362

1105
      if (exit_code_ == 0 && exit_code.IsJust()) {
363
367
        exit_code_ = exit_code.FromJust();
364
      }
365
366
719
      Debug(this, "Exiting thread for worker %llu with exit code %d",
367
719
            thread_id_.id, exit_code_);
368
    }
369
  }
370
371
719
  Debug(this, "Worker %llu thread stops", thread_id_.id);
372
}
373
374
719
bool Worker::CreateEnvMessagePort(Environment* env) {
375
1438
  HandleScope handle_scope(isolate_);
376
1438
  std::unique_ptr<MessagePortData> data;
377
  {
378
1438
    Mutex::ScopedLock lock(mutex_);
379
719
    data = std::move(child_port_data_);
380
  }
381
382
  // Set up the message channel for receiving messages in the child.
383
1438
  MessagePort* child_port = MessagePort::New(env,
384
                                             env->context(),
385
719
                                             std::move(data));
386
  // MessagePort::New() may return nullptr if execution is terminated
387
  // within it.
388
719
  if (child_port != nullptr)
389
719
    env->set_message_port(child_port->object(isolate_));
390
391
719
  return child_port;
392
}
393
394
961
void Worker::JoinThread() {
395
961
  if (!tid_.has_value())
396
4
    return;
397
957
  CHECK_EQ(uv_thread_join(&tid_.value()), 0);
398
957
  tid_.reset();
399
400
957
  env()->remove_sub_worker_context(this);
401
402
  {
403
1912
    HandleScope handle_scope(env()->isolate());
404
957
    Context::Scope context_scope(env()->context());
405
406
    // Reset the parent port as we're closing it now anyway.
407
957
    object()->Set(env()->context(),
408
                  env()->message_port_string(),
409
2871
                  Undefined(env()->isolate())).Check();
410
411
    Local<Value> args[] = {
412
        Integer::New(env()->isolate(), exit_code_),
413
957
        custom_error_ != nullptr
414
458
            ? OneByteString(env()->isolate(), custom_error_).As<Value>()
415
2184
            : Null(env()->isolate()).As<Value>(),
416
1914
        !custom_error_str_.empty()
417
229
            ? OneByteString(env()->isolate(), custom_error_str_.c_str())
418
229
                  .As<Value>()
419
2184
            : Null(env()->isolate()).As<Value>(),
420

2871
    };
421
422
957
    MakeCallback(env()->onexit_string(), arraysize(args), args);
423
  }
424
425
  // If we get here, the tid_.has_value() condition at the top of the function
426
  // implies that the thread was running. In that case, its final action will
427
  // be to schedule a callback on the parent thread which will delete this
428
  // object, so there's nothing more to do here.
429
}
430
431
3740
Worker::~Worker() {
432
3740
  Mutex::ScopedLock lock(mutex_);
433
434
1870
  CHECK(stopped_);
435
1870
  CHECK_NULL(env_);
436
1870
  CHECK(!tid_.has_value());
437
438
1870
  Debug(this, "Worker %llu destroyed", thread_id_.id);
439
3740
}
440
441
964
void Worker::New(const FunctionCallbackInfo<Value>& args) {
442
964
  Environment* env = Environment::GetCurrent(args);
443
964
  Isolate* isolate = args.GetIsolate();
444
445
964
  CHECK(args.IsConstructCall());
446
447
964
  if (env->isolate_data()->platform() == nullptr) {
448
    THROW_ERR_MISSING_PLATFORM_FOR_WORKER(env);
449
4
    return;
450
  }
451
452
964
  std::string url;
453
964
  std::shared_ptr<PerIsolateOptions> per_isolate_opts = nullptr;
454
964
  std::shared_ptr<KVStore> env_vars = nullptr;
455
456
964
  std::vector<std::string> exec_argv_out;
457
458
  // Argument might be a string or URL
459
1928
  if (!args[0]->IsNullOrUndefined()) {
460
    Utf8Value value(
461
1452
        isolate, args[0]->ToString(env->context()).FromMaybe(Local<String>()));
462
484
    url.append(value.out(), value.length());
463
  }
464
465
1928
  if (args[1]->IsNull()) {
466
    // Means worker.env = { ...process.env }.
467
937
    env_vars = env->env_vars()->Clone(isolate);
468
27
  } else if (args[1]->IsObject()) {
469
    // User provided env.
470
26
    env_vars = KVStore::CreateMapKVStore();
471
26
    env_vars->AssignFromObject(isolate->GetCurrentContext(),
472
78
                               args[1].As<Object>());
473
  } else {
474
    // Env is shared.
475
1
    env_vars = env->env_vars();
476
  }
477
478

1902
  if (args[1]->IsObject() || args[2]->IsArray()) {
479
292
    per_isolate_opts.reset(new PerIsolateOptions());
480
481
292
    HandleEnvOptions(per_isolate_opts->per_env, [&env_vars](const char* name) {
482
2336
      return env_vars->Get(name).FromMaybe("");
483
    });
484
485
#ifndef NODE_WITHOUT_NODE_OPTIONS
486
    MaybeLocal<String> maybe_node_opts =
487
292
        env_vars->Get(isolate, OneByteString(isolate, "NODE_OPTIONS"));
488
    Local<String> node_opts;
489
292
    if (maybe_node_opts.ToLocal(&node_opts)) {
490
873
      std::string node_options(*String::Utf8Value(isolate, node_opts));
491
291
      std::vector<std::string> errors{};
492
      std::vector<std::string> env_argv =
493
291
          ParseNodeOptionsEnvVar(node_options, &errors);
494
      // [0] is expected to be the program name, add dummy string.
495
291
      env_argv.insert(env_argv.begin(), "");
496
291
      std::vector<std::string> invalid_args{};
497
291
      options_parser::Parse(&env_argv,
498
                            nullptr,
499
                            &invalid_args,
500
                            per_isolate_opts.get(),
501
                            kAllowedInEnvironment,
502
                            &errors);
503

292
      if (!errors.empty() && args[1]->IsObject()) {
504
        // Only fail for explicitly provided env, this protects from failures
505
        // when NODE_OPTIONS from parent's env is used (which is the default).
506
        Local<Value> error;
507
2
        if (!ToV8Value(env->context(), errors).ToLocal(&error)) return;
508
        Local<String> key =
509
1
            FIXED_ONE_BYTE_STRING(env->isolate(), "invalidNodeOptions");
510
        // Ignore the return value of Set() because exceptions bubble up to JS
511
        // when we return anyway.
512
1
        USE(args.This()->Set(env->context(), key, error));
513
1
        return;
514
      }
515
    }
516
#endif  // NODE_WITHOUT_NODE_OPTIONS
517
  }
518
519
963
  if (args[2]->IsArray()) {
520
289
    Local<Array> array = args[2].As<Array>();
521
    // The first argument is reserved for program name, but we don't need it
522
    // in workers.
523
1156
    std::vector<std::string> exec_argv = {""};
524
289
    uint32_t length = array->Length();
525
427
    for (uint32_t i = 0; i < length; i++) {
526
      Local<Value> arg;
527
276
      if (!array->Get(env->context(), i).ToLocal(&arg)) {
528
        return;
529
      }
530
      Local<String> arg_v8;
531
276
      if (!arg->ToString(env->context()).ToLocal(&arg_v8)) {
532
        return;
533
      }
534
276
      Utf8Value arg_utf8_value(args.GetIsolate(), arg_v8);
535
276
      std::string arg_string(arg_utf8_value.out(), arg_utf8_value.length());
536
138
      exec_argv.push_back(arg_string);
537
    }
538
539
289
    std::vector<std::string> invalid_args{};
540
289
    std::vector<std::string> errors{};
541
    // Using invalid_args as the v8_args argument as it stores unknown
542
    // options for the per isolate parser.
543
289
    options_parser::Parse(
544
        &exec_argv,
545
        &exec_argv_out,
546
        &invalid_args,
547
        per_isolate_opts.get(),
548
        kDisallowedInEnvironment,
549
        &errors);
550
551
    // The first argument is program name.
552
289
    invalid_args.erase(invalid_args.begin());
553

289
    if (errors.size() > 0 || invalid_args.size() > 0) {
554
      Local<Value> error;
555
3
      if (!ToV8Value(env->context(),
556
3
                     errors.size() > 0 ? errors : invalid_args)
557
3
                         .ToLocal(&error)) {
558
        return;
559
      }
560
      Local<String> key =
561
3
          FIXED_ONE_BYTE_STRING(env->isolate(), "invalidExecArgv");
562
      // Ignore the return value of Set() because exceptions bubble up to JS
563
      // when we return anyway.
564
3
      USE(args.This()->Set(env->context(), key, error));
565
3
      return;
566
    }
567
  } else {
568
674
    exec_argv_out = env->exec_argv();
569
  }
570
571
960
  bool use_node_snapshot = per_process::cli_options->node_snapshot;
572
  const SnapshotData* snapshot_data =
573
960
      use_node_snapshot ? SnapshotBuilder::GetEmbeddedSnapshotData() : nullptr;
574
575
  Worker* worker = new Worker(env,
576
1920
                              args.This(),
577
                              url,
578
                              per_isolate_opts,
579
960
                              std::move(exec_argv_out),
580
                              env_vars,
581
960
                              snapshot_data);
582
583
960
  CHECK(args[3]->IsFloat64Array());
584
1920
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
585
960
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
586
960
  limit_info->CopyContents(worker->resource_limits_,
587
                           sizeof(worker->resource_limits_));
588
589
960
  CHECK(args[4]->IsBoolean());
590

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

386
  if (!w->has_ref_ && w->tid_.has_value()) {
684
5
    w->has_ref_ = true;
685
5
    w->env()->add_refs(1);
686
  }
687
}
688
689
9
void Worker::HasRef(const FunctionCallbackInfo<Value>& args) {
690
  Worker* w;
691
9
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
692
16
  args.GetReturnValue().Set(w->has_ref_);
693
}
694
695
7
void Worker::Unref(const FunctionCallbackInfo<Value>& args) {
696
  Worker* w;
697
7
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
698

7
  if (w->has_ref_ && w->tid_.has_value()) {
699
7
    w->has_ref_ = false;
700
7
    w->env()->add_refs(-1);
701
  }
702
}
703
704
1
void Worker::GetResourceLimits(const FunctionCallbackInfo<Value>& args) {
705
  Worker* w;
706
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
707
2
  args.GetReturnValue().Set(w->GetResourceLimits(args.GetIsolate()));
708
}
709
710
721
Local<Float64Array> Worker::GetResourceLimits(Isolate* isolate) const {
711
721
  Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, sizeof(resource_limits_));
712
713
721
  memcpy(ab->Data(), resource_limits_, sizeof(resource_limits_));
714
721
  return Float64Array::New(ab, 0, kTotalResourceLimitCount);
715
}
716
717
698
void Worker::Exit(int code, const char* error_code, const char* error_message) {
718
1396
  Mutex::ScopedLock lock(mutex_);
719
698
  Debug(this, "Worker %llu called Exit(%d, %s, %s)",
720
698
        thread_id_.id, code, error_code, error_message);
721
722
698
  if (error_code != nullptr) {
723
229
    custom_error_ = error_code;
724
229
    custom_error_str_ = error_message;
725
  }
726
727
698
  if (env_ != nullptr) {
728
354
    exit_code_ = code;
729
354
    Stop(env_);
730
  } else {
731
344
    stopped_ = true;
732
  }
733
698
}
734
735
bool Worker::IsNotIndicativeOfMemoryLeakAtExit() const {
736
  // Worker objects always stay alive as long as the child thread, regardless
737
  // of whether they are being referenced in the parent thread.
738
  return true;
739
}
740
741
class WorkerHeapSnapshotTaker : public AsyncWrap {
742
 public:
743
1
  WorkerHeapSnapshotTaker(Environment* env, Local<Object> obj)
744
1
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_WORKERHEAPSNAPSHOT) {}
745
746
  SET_NO_MEMORY_INFO()
747
  SET_MEMORY_INFO_NAME(WorkerHeapSnapshotTaker)
748
  SET_SELF_SIZE(WorkerHeapSnapshotTaker)
749
};
750
751
1
void Worker::TakeHeapSnapshot(const FunctionCallbackInfo<Value>& args) {
752
  Worker* w;
753
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
754
755
1
  Debug(w, "Worker %llu taking heap snapshot", w->thread_id_.id);
756
757
1
  Environment* env = w->env();
758
1
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(w);
759
  Local<Object> wrap;
760
1
  if (!env->worker_heap_snapshot_taker_template()
761
2
      ->NewInstance(env->context()).ToLocal(&wrap)) {
762
    return;
763
  }
764
  BaseObjectPtr<WorkerHeapSnapshotTaker> taker =
765
1
      MakeDetachedBaseObject<WorkerHeapSnapshotTaker>(env, wrap);
766
767
  // Interrupt the worker thread and take a snapshot, then schedule a call
768
  // on the parent thread that turns that snapshot into a readable stream.
769
1
  bool scheduled = w->RequestInterrupt([taker, env](Environment* worker_env) {
770
    heap::HeapSnapshotPointer snapshot {
771
1
        worker_env->isolate()->GetHeapProfiler()->TakeHeapSnapshot() };
772
1
    CHECK(snapshot);
773
2
    env->SetImmediateThreadsafe(
774
1
        [taker, snapshot = std::move(snapshot)](Environment* env) mutable {
775
2
          HandleScope handle_scope(env->isolate());
776
1
          Context::Scope context_scope(env->context());
777
778
2
          AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(taker.get());
779
          BaseObjectPtr<AsyncWrap> stream = heap::CreateHeapSnapshotStream(
780
2
              env, std::move(snapshot));
781
1
          Local<Value> args[] = { stream->object() };
782
1
          taker->MakeCallback(env->ondone_string(), arraysize(args), args);
783
1
        }, CallbackFlags::kUnrefed);
784
1
  });
785
2
  args.GetReturnValue().Set(scheduled ? taker->object() : Local<Object>());
786
}
787
788
7
void Worker::LoopIdleTime(const FunctionCallbackInfo<Value>& args) {
789
  Worker* w;
790
7
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
791
792
7
  Mutex::ScopedLock lock(w->mutex_);
793
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
794
  // before locking the mutex is a race condition. So manually do the same
795
  // check.
796

7
  if (w->stopped_ || w->env_ == nullptr)
797
    return args.GetReturnValue().Set(-1);
798
799
7
  uint64_t idle_time = uv_metrics_idle_time(w->env_->event_loop());
800
14
  args.GetReturnValue().Set(1.0 * idle_time / 1e6);
801
}
802
803
1
void Worker::LoopStartTime(const FunctionCallbackInfo<Value>& args) {
804
  Worker* w;
805
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
806
807
1
  Mutex::ScopedLock lock(w->mutex_);
808
  // Using w->is_stopped() here leads to a deadlock, and checking is_stopped()
809
  // before locking the mutex is a race condition. So manually do the same
810
  // check.
811

1
  if (w->stopped_ || w->env_ == nullptr)
812
    return args.GetReturnValue().Set(-1);
813
814
1
  double loop_start_time = w->env_->performance_state()->milestones[
815
1
      node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START];
816
1
  CHECK_GE(loop_start_time, 0);
817
2
  args.GetReturnValue().Set(loop_start_time / 1e6);
818
}
819
820
namespace {
821
822
// Return the MessagePort that is global for this Environment and communicates
823
// with the internal [kPort] port of the JS Worker class in the parent thread.
824
1440
void GetEnvMessagePort(const FunctionCallbackInfo<Value>& args) {
825
1440
  Environment* env = Environment::GetCurrent(args);
826
1440
  Local<Object> port = env->message_port();
827

2880
  CHECK_IMPLIES(!env->is_main_thread(), !port.IsEmpty());
828
1440
  if (!port.IsEmpty()) {
829
4320
    CHECK_EQ(port->GetCreationContext().ToLocalChecked()->GetIsolate(),
830
             args.GetIsolate());
831
2880
    args.GetReturnValue().Set(port);
832
  }
833
1440
}
834
835
780
void InitWorker(Local<Object> target,
836
                Local<Value> unused,
837
                Local<Context> context,
838
                void* priv) {
839
780
  Environment* env = Environment::GetCurrent(context);
840
780
  Isolate* isolate = env->isolate();
841
842
  {
843
780
    Local<FunctionTemplate> w = NewFunctionTemplate(isolate, Worker::New);
844
845
1560
    w->InstanceTemplate()->SetInternalFieldCount(
846
        Worker::kInternalFieldCount);
847
780
    w->Inherit(AsyncWrap::GetConstructorTemplate(env));
848
849
780
    SetProtoMethod(isolate, w, "startThread", Worker::StartThread);
850
780
    SetProtoMethod(isolate, w, "stopThread", Worker::StopThread);
851
780
    SetProtoMethod(isolate, w, "hasRef", Worker::HasRef);
852
780
    SetProtoMethod(isolate, w, "ref", Worker::Ref);
853
780
    SetProtoMethod(isolate, w, "unref", Worker::Unref);
854
780
    SetProtoMethod(isolate, w, "getResourceLimits", Worker::GetResourceLimits);
855
780
    SetProtoMethod(isolate, w, "takeHeapSnapshot", Worker::TakeHeapSnapshot);
856
780
    SetProtoMethod(isolate, w, "loopIdleTime", Worker::LoopIdleTime);
857
780
    SetProtoMethod(isolate, w, "loopStartTime", Worker::LoopStartTime);
858
859
780
    SetConstructorFunction(context, target, "Worker", w);
860
  }
861
862
  {
863
780
    Local<FunctionTemplate> wst = NewFunctionTemplate(isolate, nullptr);
864
865
1560
    wst->InstanceTemplate()->SetInternalFieldCount(
866
        WorkerHeapSnapshotTaker::kInternalFieldCount);
867
780
    wst->Inherit(AsyncWrap::GetConstructorTemplate(env));
868
869
    Local<String> wst_string =
870
780
        FIXED_ONE_BYTE_STRING(isolate, "WorkerHeapSnapshotTaker");
871
780
    wst->SetClassName(wst_string);
872
780
    env->set_worker_heap_snapshot_taker_template(wst->InstanceTemplate());
873
  }
874
875
780
  SetMethod(context, target, "getEnvMessagePort", GetEnvMessagePort);
876
877
  target
878
780
      ->Set(env->context(),
879
            env->thread_id_string(),
880
3120
            Number::New(isolate, static_cast<double>(env->thread_id())))
881
      .Check();
882
883
  target
884
780
      ->Set(env->context(),
885
            FIXED_ONE_BYTE_STRING(isolate, "isMainThread"),
886
3120
            Boolean::New(isolate, env->is_main_thread()))
887
      .Check();
888
889
  target
890
780
      ->Set(env->context(),
891
            FIXED_ONE_BYTE_STRING(isolate, "ownsProcessState"),
892
2340
            Boolean::New(isolate, env->owns_process_state()))
893
      .Check();
894
895
780
  if (!env->is_main_thread()) {
896
    target
897
720
        ->Set(env->context(),
898
              FIXED_ONE_BYTE_STRING(isolate, "resourceLimits"),
899
2880
              env->worker_context()->GetResourceLimits(isolate))
900
        .Check();
901
  }
902
903
2340
  NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb);
904
2340
  NODE_DEFINE_CONSTANT(target, kMaxOldGenerationSizeMb);
905
2340
  NODE_DEFINE_CONSTANT(target, kCodeRangeSizeMb);
906
2340
  NODE_DEFINE_CONSTANT(target, kStackSizeMb);
907
1560
  NODE_DEFINE_CONSTANT(target, kTotalResourceLimitCount);
908
780
}
909
910
5473
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
911
5473
  registry->Register(GetEnvMessagePort);
912
5473
  registry->Register(Worker::New);
913
5473
  registry->Register(Worker::StartThread);
914
5473
  registry->Register(Worker::StopThread);
915
5473
  registry->Register(Worker::HasRef);
916
5473
  registry->Register(Worker::Ref);
917
5473
  registry->Register(Worker::Unref);
918
5473
  registry->Register(Worker::GetResourceLimits);
919
5473
  registry->Register(Worker::TakeHeapSnapshot);
920
5473
  registry->Register(Worker::LoopIdleTime);
921
5473
  registry->Register(Worker::LoopStartTime);
922
5473
}
923
924
}  // anonymous namespace
925
}  // namespace worker
926
}  // namespace node
927
928
5545
NODE_MODULE_CONTEXT_AWARE_INTERNAL(worker, node::worker::InitWorker)
929
5473
NODE_MODULE_EXTERNAL_REFERENCE(worker, node::worker::RegisterExternalReferences)