GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_worker.cc Lines: 411 462 89.0 %
Date: 2022-01-06 04:14:11 Branches: 153 216 70.8 %

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

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

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

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

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

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

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

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

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

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

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

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

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