GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_worker.cc Lines: 407 456 89.3 %
Date: 2021-04-29 04:13:25 Branches: 192 258 74.4 %

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
653
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
653
               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
653
      platform_(env->isolate_data()->platform()),
57
      thread_id_(AllocateEnvironmentThreadId()),
58
1306
      env_vars_(env_vars) {
59
653
  Debug(this, "Creating new worker instance with thread id %llu",
60
        thread_id_.id);
61
62
  // Set up everything that needs to be set up in the parent environment.
63
653
  parent_port_ = MessagePort::New(env, env->context());
64
653
  if (parent_port_ == nullptr) {
65
    // This can happen e.g. because execution is terminating.
66
    return;
67
  }
68
69
653
  child_port_data_ = std::make_unique<MessagePortData>(nullptr);
70
653
  MessagePort::Entangle(parent_port_, child_port_data_.get());
71
72
1959
  object()->Set(env->context(),
73
                env->message_port_string(),
74
3265
                parent_port_->object()).Check();
75
76
1959
  object()->Set(env->context(),
77
                env->thread_id_string(),
78
3265
                Number::New(env->isolate(), static_cast<double>(thread_id_.id)))
79
      .Check();
80
81
1306
  inspector_parent_handle_ = GetInspectorParentHandle(
82
653
      env, thread_id_, url.c_str());
83
84
653
  argv_ = std::vector<std::string>{env->argv()[0]};
85
  // Mark this Worker object as weak until we actually start the thread.
86
653
  MakeWeak();
87
88
653
  Debug(this, "Preparation for worker %llu finished", thread_id_.id);
89
}
90
91
1622
bool Worker::is_stopped() const {
92
3244
  Mutex::ScopedLock lock(mutex_);
93
1622
  if (env_ != nullptr)
94
401
    return env_->is_stopping();
95
1221
  return stopped_;
96
}
97
98
416
void Worker::UpdateResourceConstraints(ResourceConstraints* constraints) {
99
416
  constraints->set_stack_limit(reinterpret_cast<uint32_t*>(stack_base_));
100
101
415
  if (resource_limits_[kMaxYoungGenerationSizeMb] > 0) {
102
1
    constraints->set_max_young_generation_size_in_bytes(
103
2
        static_cast<size_t>(resource_limits_[kMaxYoungGenerationSizeMb] * kMB));
104
  } else {
105
414
    resource_limits_[kMaxYoungGenerationSizeMb] =
106
414
        constraints->max_young_generation_size_in_bytes() / kMB;
107
  }
108
109
415
  if (resource_limits_[kMaxOldGenerationSizeMb] > 0) {
110
2
    constraints->set_max_old_generation_size_in_bytes(
111
4
        static_cast<size_t>(resource_limits_[kMaxOldGenerationSizeMb] * kMB));
112
  } else {
113
413
    resource_limits_[kMaxOldGenerationSizeMb] =
114
413
        constraints->max_old_generation_size_in_bytes() / kMB;
115
  }
116
117
415
  if (resource_limits_[kCodeRangeSizeMb] > 0) {
118
1
    constraints->set_code_range_size_in_bytes(
119
2
        static_cast<size_t>(resource_limits_[kCodeRangeSizeMb] * kMB));
120
  } else {
121
414
    resource_limits_[kCodeRangeSizeMb] =
122
414
        constraints->code_range_size_in_bytes() / kMB;
123
  }
124
415
}
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
650
  explicit WorkerThreadData(Worker* w)
132
650
    : w_(w) {
133
650
    int ret = uv_loop_init(&loop_);
134
648
    if (ret != 0) {
135
      char err_buf[128];
136
233
      uv_err_name_r(ret, err_buf, sizeof(err_buf));
137
231
      w->Exit(1, "ERR_WORKER_INIT_FAILED", err_buf);
138
233
      return;
139
    }
140
415
    loop_init_failed_ = false;
141
415
    uv_loop_configure(&loop_, UV_METRICS_IDLE_TIME);
142
143
    std::shared_ptr<ArrayBufferAllocator> allocator =
144
831
        ArrayBufferAllocator::Create();
145
830
    Isolate::CreateParams params;
146
414
    SetIsolateCreateParamsForNode(&params);
147
415
    params.array_buffer_allocator_shared = allocator;
148
149
416
    w->UpdateResourceConstraints(&params.constraints);
150
151
415
    Isolate* isolate = Isolate::Allocate();
152
416
    if (isolate == nullptr) {
153
      w->Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Isolate");
154
      return;
155
    }
156
157
416
    w->platform_->RegisterIsolate(isolate, &loop_);
158
416
    Isolate::Initialize(isolate, params);
159
416
    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
416
    isolate->AddNearHeapLimitCallback(Worker::NearHeapLimit, w);
165
166
    {
167
416
      Locker locker(isolate);
168
832
      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
416
      isolate->SetStackLimit(w->stack_base_);
172
173
832
      HandleScope handle_scope(isolate);
174
832
      isolate_data_.reset(CreateIsolateData(isolate,
175
                                            &loop_,
176
416
                                            w_->platform_,
177
416
                                            allocator.get()));
178
416
      CHECK(isolate_data_);
179
416
      if (w_->per_isolate_opts_)
180
111
        isolate_data_->set_options(std::move(w_->per_isolate_opts_));
181
416
      isolate_data_->set_worker_context(w_);
182
832
      isolate_data_->max_young_gen_size =
183
416
          params.constraints.max_young_generation_size_in_bytes();
184
    }
185
186
832
    Mutex::ScopedLock lock(w_->mutex_);
187
416
    w_->isolate_ = isolate;
188
  }
189
190
1297
  ~WorkerThreadData() {
191
650
    Debug(w_, "Worker %llu dispose isolate", w_->thread_id_.id);
192
    Isolate* isolate;
193
    {
194
1295
      Mutex::ScopedLock lock(w_->mutex_);
195
646
      isolate = w_->isolate_;
196
646
      w_->isolate_ = nullptr;
197
    }
198
199
647
    if (isolate != nullptr) {
200
416
      CHECK(!loop_init_failed_);
201
416
      bool platform_finished = false;
202
203
416
      isolate_data_.reset();
204
205
2496
      w_->platform_->AddIsolateFinishedCallback(isolate, [](void* data) {
206
416
        *static_cast<bool*>(data) = true;
207
2080
      }, &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
416
      w_->platform_->UnregisterIsolate(isolate);
215
416
      isolate->Dispose();
216
217
      // Wait until the platform has cleaned up all relevant resources.
218
1248
      while (!platform_finished) {
219
416
        uv_run(&loop_, UV_RUN_ONCE);
220
      }
221
    }
222
647
    if (!loop_init_failed_) {
223
416
      CheckedUvLoopClose(&loop_);
224
    }
225
648
  }
226
227
416
  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
650
void Worker::Run() {
249
1051
  std::string name = "WorkerThread ";
250
650
  name += std::to_string(thread_id_.id);
251
650
  TRACE_EVENT_METADATA1(
252
      "__metadata", "thread_name", "name",
253
      TRACE_STR_COPY(name.c_str()));
254
800
  CHECK_NOT_NULL(platform_);
255
650
256
650
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
257
4
258
1051
  WorkerThreadData data(this);
259
650
  if (isolate_ == nullptr) return;
260
416
  CHECK(data.loop_is_usable());
261
262
416
  Debug(this, "Starting worker with id %llu", thread_id_.id);
263
  {
264
817
    Locker locker(isolate_);
265
817
    Isolate::Scope isolate_scope(isolate_);
266
817
    SealHandleScope outer_seal(isolate_);
267
268
817
    DeleteFnPtr<Environment, FreeEnvironment> env_;
269
415
    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
1616
      isolate_->CancelTerminateExecution();
274
275
816
      if (!env_) return;
276
400
      env_->set_can_call_into_js(false);
277
278
      {
279
801
        Mutex::ScopedLock lock(mutex_);
280
400
        stopped_ = true;
281
400
        this->env_ = nullptr;
282
      }
283
284
401
      env_.reset();
285
817
    });
286
287
416
    if (is_stopped()) return;
288
    {
289
809
      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
812
        TryCatch try_catch(isolate_);
297
408
        context = NewContext(isolate_);
298
408
        if (context.IsEmpty()) {
299
4
          Exit(1, "ERR_WORKER_INIT_FAILED", "Failed to create new Context");
300
4
          return;
301
        }
302
      }
303
304
404
      if (is_stopped()) return;
305
401
      CHECK(!context.IsEmpty());
306
401
      Context::Scope context_scope(context);
307
      {
308
1203
        env_.reset(CreateEnvironment(
309
            data.isolate_data_.get(),
310
            context,
311
401
            std::move(argv_),
312
401
            std::move(exec_argv_),
313
401
            static_cast<EnvironmentFlags::Flags>(environment_flags_),
314
            thread_id_,
315
802
            std::move(inspector_parent_handle_)));
316
401
        if (is_stopped()) return;
317
401
        CHECK_NOT_NULL(env_);
318
401
        env_->set_env_vars(std::move(env_vars_));
319
856
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
320
54
          Exit(exit_code);
321
456
        });
322
      }
323
      {
324
802
        Mutex::ScopedLock lock(mutex_);
325
401
        if (stopped_) return;
326
401
        this->env_ = env_.get();
327
      }
328
401
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
329
401
      if (is_stopped()) return;
330
      {
331
401
        CreateEnvMessagePort(env_.get());
332
401
        Debug(this, "Created message port for worker %llu", thread_id_.id);
333
802
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
334
          return;
335
336
401
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
337
      }
338
    }
339
340
    {
341
401
      Maybe<int> exit_code = SpinEventLoop(env_.get());
342
800
      Mutex::ScopedLock lock(mutex_);
343

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

5200
    };
395
396
650
    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
1887
Worker::~Worker() {
406
1258
  Mutex::ScopedLock lock(mutex_);
407
408
629
  CHECK(stopped_);
409
629
  CHECK_NULL(env_);
410
629
  CHECK(thread_joined_);
411
412
629
  Debug(this, "Worker %llu destroyed", thread_id_.id);
413
1258
}
414
415
657
void Worker::New(const FunctionCallbackInfo<Value>& args) {
416
657
  Environment* env = Environment::GetCurrent(args);
417
657
  Isolate* isolate = args.GetIsolate();
418
419
657
  CHECK(args.IsConstructCall());
420
421
657
  if (env->isolate_data()->platform() == nullptr) {
422
    THROW_ERR_MISSING_PLATFORM_FOR_WORKER(env);
423
    return;
424
  }
425
426
1310
  std::string url;
427
1310
  std::shared_ptr<PerIsolateOptions> per_isolate_opts = nullptr;
428
1310
  std::shared_ptr<KVStore> env_vars = nullptr;
429
430
1310
  std::vector<std::string> exec_argv_out;
431
432
  // Argument might be a string or URL
433
1971
  if (!args[0]->IsNullOrUndefined()) {
434
    Utf8Value value(
435
940
        isolate, args[0]->ToString(env->context()).FromMaybe(Local<String>()));
436
188
    url.append(value.out(), value.length());
437
  }
438
439
1971
  if (args[1]->IsNull()) {
440
    // Means worker.env = { ...process.env }.
441
631
    env_vars = env->env_vars()->Clone(isolate);
442
52
  } 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

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

116
      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
3
        USE(args.This()->Set(env->context(), key, error));
487
1
        return;
488
      }
489
    }
490
#endif
491
  }
492
493
1312
  if (args[2]->IsArray()) {
494
224
    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
221
    std::vector<std::string> exec_argv = {""};
498
112
    uint32_t length = array->Length();
499
166
    for (uint32_t i = 0; i < length; i++) {
500
      Local<Value> arg;
501
162
      if (!array->Get(env->context(), i).ToLocal(&arg)) {
502
        return;
503
      }
504
      Local<String> arg_v8;
505
162
      if (!arg->ToString(env->context()).ToLocal(&arg_v8)) {
506
        return;
507
      }
508
108
      Utf8Value arg_utf8_value(args.GetIsolate(), arg_v8);
509
108
      std::string arg_string(arg_utf8_value.out(), arg_utf8_value.length());
510
54
      exec_argv.push_back(arg_string);
511
    }
512
513
221
    std::vector<std::string> invalid_args{};
514
221
    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
112
    options_parser::Parse(
518
        &exec_argv,
519
        &exec_argv_out,
520
        &invalid_args,
521
        per_isolate_opts.get(),
522
        kDisallowedInEnvironment,
523
112
        &errors);
524
525
    // The first argument is program name.
526
112
    invalid_args.erase(invalid_args.begin());
527

112
    if (errors.size() > 0 || invalid_args.size() > 0) {
528
      Local<Value> error;
529
6
      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
9
      USE(args.This()->Set(env->context(), key, error));
539
3
      return;
540
    }
541
  } else {
542
544
    exec_argv_out = env->exec_argv();
543
  }
544
545
  Worker* worker = new Worker(env,
546
1306
                              args.This(),
547
                              url,
548
                              per_isolate_opts,
549
                              std::move(exec_argv_out),
550
653
                              env_vars);
551
552
1306
  CHECK(args[3]->IsFloat64Array());
553
1306
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
554
653
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
555
1306
  limit_info->CopyContents(worker->resource_limits_,
556
653
                           sizeof(worker->resource_limits_));
557
558
1306
  CHECK(args[4]->IsBoolean());
559

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

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

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

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

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

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

19246
NODE_MODULE_EXTERNAL_REFERENCE(worker, node::worker::RegisterExternalReferences)