GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_worker.cc Lines: 405 453 89.4 %
Date: 2021-09-08 04:14:13 Branches: 147 208 70.7 %

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
795
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
795
               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
795
      platform_(env->isolate_data()->platform()),
57
795
      thread_id_(AllocateEnvironmentThreadId()),
58
1590
      env_vars_(env_vars) {
59
795
  Debug(this, "Creating new worker instance with thread id %llu",
60
795
        thread_id_.id);
61
62
  // Set up everything that needs to be set up in the parent environment.
63
795
  parent_port_ = MessagePort::New(env, env->context());
64
795
  if (parent_port_ == nullptr) {
65
    // This can happen e.g. because execution is terminating.
66
    return;
67
  }
68
69
795
  child_port_data_ = std::make_unique<MessagePortData>(nullptr);
70
795
  MessagePort::Entangle(parent_port_, child_port_data_.get());
71
72
795
  object()->Set(env->context(),
73
                env->message_port_string(),
74
2385
                parent_port_->object()).Check();
75
76
795
  object()->Set(env->context(),
77
                env->thread_id_string(),
78
2385
                Number::New(env->isolate(), static_cast<double>(thread_id_.id)))
79
      .Check();
80
81
1590
  inspector_parent_handle_ = GetInspectorParentHandle(
82
795
      env, thread_id_, url.c_str());
83
84
1590
  argv_ = std::vector<std::string>{env->argv()[0]};
85
  // Mark this Worker object as weak until we actually start the thread.
86
795
  MakeWeak();
87
88
795
  Debug(this, "Preparation for worker %llu finished", thread_id_.id);
89
}
90
91
2217
bool Worker::is_stopped() const {
92
4434
  Mutex::ScopedLock lock(mutex_);
93
2217
  if (env_ != nullptr)
94
549
    return env_->is_stopping();
95
1668
  return stopped_;
96
}
97
98
564
void Worker::UpdateResourceConstraints(ResourceConstraints* constraints) {
99
564
  constraints->set_stack_limit(reinterpret_cast<uint32_t*>(stack_base_));
100
101
564
  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
563
    resource_limits_[kMaxYoungGenerationSizeMb] =
106
563
        constraints->max_young_generation_size_in_bytes() / kMB;
107
  }
108
109
564
  if (resource_limits_[kMaxOldGenerationSizeMb] > 0) {
110
2
    constraints->set_max_old_generation_size_in_bytes(
111
2
        static_cast<size_t>(resource_limits_[kMaxOldGenerationSizeMb] * kMB));
112
  } else {
113
562
    resource_limits_[kMaxOldGenerationSizeMb] =
114
562
        constraints->max_old_generation_size_in_bytes() / kMB;
115
  }
116
117
564
  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
563
    resource_limits_[kCodeRangeSizeMb] =
122
563
        constraints->code_range_size_in_bytes() / kMB;
123
  }
124
564
}
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
792
  explicit WorkerThreadData(Worker* w)
132
792
    : w_(w) {
133
792
    int ret = uv_loop_init(&loop_);
134
792
    if (ret != 0) {
135
      char err_buf[128];
136
228
      uv_err_name_r(ret, err_buf, sizeof(err_buf));
137
228
      w->Exit(1, "ERR_WORKER_INIT_FAILED", err_buf);
138
228
      return;
139
    }
140
564
    loop_init_failed_ = false;
141
564
    uv_loop_configure(&loop_, UV_METRICS_IDLE_TIME);
142
143
    std::shared_ptr<ArrayBufferAllocator> allocator =
144
564
        ArrayBufferAllocator::Create();
145
564
    Isolate::CreateParams params;
146
564
    SetIsolateCreateParamsForNode(&params);
147
564
    params.array_buffer_allocator_shared = allocator;
148
149
564
    w->UpdateResourceConstraints(&params.constraints);
150
151
564
    Isolate* isolate = Isolate::Allocate();
152
564
    if (isolate == nullptr) {
153
      w->Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Isolate");
154
      return;
155
    }
156
157
564
    w->platform_->RegisterIsolate(isolate, &loop_);
158
564
    Isolate::Initialize(isolate, params);
159
564
    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
564
    isolate->AddNearHeapLimitCallback(Worker::NearHeapLimit, w);
165
166
    {
167
564
      Locker locker(isolate);
168
1128
      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
564
      isolate->SetStackLimit(w->stack_base_);
172
173
564
      HandleScope handle_scope(isolate);
174
1128
      isolate_data_.reset(CreateIsolateData(isolate,
175
                                            &loop_,
176
564
                                            w_->platform_,
177
                                            allocator.get()));
178
564
      CHECK(isolate_data_);
179
564
      if (w_->per_isolate_opts_)
180
250
        isolate_data_->set_options(std::move(w_->per_isolate_opts_));
181
564
      isolate_data_->set_worker_context(w_);
182
1128
      isolate_data_->max_young_gen_size =
183
564
          params.constraints.max_young_generation_size_in_bytes();
184
    }
185
186
564
    Mutex::ScopedLock lock(w_->mutex_);
187
564
    w_->isolate_ = isolate;
188
  }
189
190
792
  ~WorkerThreadData() {
191
792
    Debug(w_, "Worker %llu dispose isolate", w_->thread_id_.id);
192
    Isolate* isolate;
193
    {
194
792
      Mutex::ScopedLock lock(w_->mutex_);
195
792
      isolate = w_->isolate_;
196
792
      w_->isolate_ = nullptr;
197
    }
198
199
792
    if (isolate != nullptr) {
200
564
      CHECK(!loop_init_failed_);
201
564
      bool platform_finished = false;
202
203
564
      isolate_data_.reset();
204
205
564
      w_->platform_->AddIsolateFinishedCallback(isolate, [](void* data) {
206
564
        *static_cast<bool*>(data) = true;
207
564
      }, &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
564
      w_->platform_->UnregisterIsolate(isolate);
215
564
      isolate->Dispose();
216
217
      // Wait until the platform has cleaned up all relevant resources.
218
1128
      while (!platform_finished) {
219
564
        uv_run(&loop_, UV_RUN_ONCE);
220
      }
221
    }
222
792
    if (!loop_init_failed_) {
223
564
      CheckedUvLoopClose(&loop_);
224
    }
225
792
  }
226
227
564
  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
2
size_t Worker::NearHeapLimit(void* data, size_t current_heap_limit,
239
                             size_t initial_heap_limit) {
240
2
  Worker* worker = static_cast<Worker*>(data);
241
2
  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
2
  constexpr size_t kExtraHeapAllowance = 16 * 1024 * 1024;
245
2
  return current_heap_limit + kExtraHeapAllowance;
246
}
247
248
792
void Worker::Run() {
249
792
  std::string name = "WorkerThread ";
250
792
  name += std::to_string(thread_id_.id);
251

951
  TRACE_EVENT_METADATA1(
252
      "__metadata", "thread_name", "name",
253
      TRACE_STR_COPY(name.c_str()));
254
792
  CHECK_NOT_NULL(platform_);
255
256
792
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
257
258
792
  WorkerThreadData data(this);
259
792
  if (isolate_ == nullptr) return;
260
564
  CHECK(data.loop_is_usable());
261
262
564
  Debug(this, "Starting worker with id %llu", thread_id_.id);
263
  {
264
564
    Locker locker(isolate_);
265
564
    Isolate::Scope isolate_scope(isolate_);
266
564
    SealHandleScope outer_seal(isolate_);
267
268
564
    DeleteFnPtr<Environment, FreeEnvironment> env_;
269
564
    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
564
      isolate_->CancelTerminateExecution();
274
275
564
      if (!env_) return;
276
549
      env_->set_can_call_into_js(false);
277
278
      {
279
549
        Mutex::ScopedLock lock(mutex_);
280
549
        stopped_ = true;
281
549
        this->env_ = nullptr;
282
      }
283
284
549
      env_.reset();
285
564
    });
286
287
564
    if (is_stopped()) return;
288
    {
289
559
      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
559
        TryCatch try_catch(isolate_);
297
559
        context = NewContext(isolate_);
298
559
        if (context.IsEmpty()) {
299
4
          Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Context");
300
4
          return;
301
        }
302
      }
303
304
555
      if (is_stopped()) return;
305
549
      CHECK(!context.IsEmpty());
306
549
      Context::Scope context_scope(context);
307
      {
308
1098
        env_.reset(CreateEnvironment(
309
            data.isolate_data_.get(),
310
            context,
311
549
            std::move(argv_),
312
549
            std::move(exec_argv_),
313
549
            static_cast<EnvironmentFlags::Flags>(environment_flags_),
314
            thread_id_,
315
549
            std::move(inspector_parent_handle_)));
316
549
        if (is_stopped()) return;
317
549
        CHECK_NOT_NULL(env_);
318
549
        env_->set_env_vars(std::move(env_vars_));
319
549
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
320
66
          Exit(exit_code);
321
66
        });
322
      }
323
      {
324
549
        Mutex::ScopedLock lock(mutex_);
325
549
        if (stopped_) return;
326
549
        this->env_ = env_.get();
327
      }
328
549
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
329
549
      if (is_stopped()) return;
330
      {
331
549
        CreateEnvMessagePort(env_.get());
332
549
        Debug(this, "Created message port for worker %llu", thread_id_.id);
333
1098
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
334
          return;
335
336
549
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
337
      }
338
    }
339
340
    {
341
549
      Maybe<int> exit_code = SpinEventLoop(env_.get());
342
1098
      Mutex::ScopedLock lock(mutex_);
343

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

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

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

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

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

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

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

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

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

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

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