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-06-06 04:11:53 Branches: 191 258 74.0 %

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

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

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

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

117
      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
1316
  if (args[2]->IsArray()) {
494
226
    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
223
    std::vector<std::string> exec_argv = {""};
498
113
    uint32_t length = array->Length();
499
168
    for (uint32_t i = 0; i < length; i++) {
500
      Local<Value> arg;
501
165
      if (!array->Get(env->context(), i).ToLocal(&arg)) {
502
        return;
503
      }
504
      Local<String> arg_v8;
505
165
      if (!arg->ToString(env->context()).ToLocal(&arg_v8)) {
506
        return;
507
      }
508
110
      Utf8Value arg_utf8_value(args.GetIsolate(), arg_v8);
509
110
      std::string arg_string(arg_utf8_value.out(), arg_utf8_value.length());
510
55
      exec_argv.push_back(arg_string);
511
    }
512
513
223
    std::vector<std::string> invalid_args{};
514
223
    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
113
    options_parser::Parse(
518
        &exec_argv,
519
        &exec_argv_out,
520
        &invalid_args,
521
        per_isolate_opts.get(),
522
        kDisallowedInEnvironment,
523
113
        &errors);
524
525
    // The first argument is program name.
526
113
    invalid_args.erase(invalid_args.begin());
527

113
    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
545
    exec_argv_out = env->exec_argv();
543
  }
544
545
  Worker* worker = new Worker(env,
546
1310
                              args.This(),
547
                              url,
548
                              per_isolate_opts,
549
                              std::move(exec_argv_out),
550
655
                              env_vars);
551
552
1310
  CHECK(args[3]->IsFloat64Array());
553
1310
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
554
655
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
555
1310
  limit_info->CopyContents(worker->resource_limits_,
556
655
                           sizeof(worker->resource_limits_));
557
558
1310
  CHECK(args[4]->IsBoolean());
559

1310
  if (args[4]->IsTrue() || env->tracks_unmanaged_fds())
560
654
    worker->environment_flags_ |= EnvironmentFlags::kTrackUnmanagedFds;
561
}
562
563
652
void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
564
  Worker* w;
565
652
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
566
1304
  Mutex::ScopedLock lock(w->mutex_);
567
568
652
  w->stopped_ = false;
569
570
652
  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
643
    w->resource_limits_[kStackSizeMb] = w->stack_size_ / kMB;
580
  }
581
582
  uv_thread_options_t thread_options;
583
652
  thread_options.flags = UV_THREAD_HAS_STACK_SIZE;
584
652
  thread_options.stack_size = w->stack_size_;
585
3260
  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
652
    Worker* w = static_cast<Worker*>(arg);
590
652
    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
652
    w->stack_base_ = stack_top - (w->stack_size_ - kStackBufferSize);
595
596
652
    w->Run();
597
598
1304
    Mutex::ScopedLock lock(w->mutex_);
599
1304
    w->env()->SetImmediateThreadsafe(
600
2562
        [w = std::unique_ptr<Worker>(w)](Environment* env) {
601
630
          if (w->has_ref_)
602
628
            env->add_refs(-1);
603
630
          w->JoinThread();
604
          // implicitly delete w
605
1280
        });
606
2608
  }, static_cast<void*>(w));
607
608
652
  if (ret == 0) {
609
    // The object now owns the created thread and should not be garbage
610
    // collected until that finishes.
611
652
    w->ClearWeak();
612
652
    w->thread_joined_ = false;
613
614
652
    if (w->has_ref_)
615
652
      w->env()->add_refs(1);
616
617
652
    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
101
void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
632
  Worker* w;
633
101
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
634
635
101
  Debug(w, "Worker %llu is getting stopped by parent", w->thread_id_.id);
636
101
  w->Exit(1);
637
}
638
639
103
void Worker::Ref(const FunctionCallbackInfo<Value>& args) {
640
  Worker* w;
641
103
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
642

103
  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
5
    w->has_ref_ = false;
653
5
    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
414
Local<Float64Array> Worker::GetResourceLimits(Isolate* isolate) const {
664
414
  Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, sizeof(resource_limits_));
665
666
1242
  memcpy(ab->GetBackingStore()->Data(),
667
         resource_limits_,
668
414
         sizeof(resource_limits_));
669
414
  return Float64Array::New(ab, 0, kTotalResourceLimitCount);
670
}
671
672
412
void Worker::Exit(int code, const char* error_code, const char* error_message) {
673
824
  Mutex::ScopedLock lock(mutex_);
674
412
  Debug(this, "Worker %llu called Exit(%d, %s, %s)",
675
        thread_id_.id, code, error_code, error_message);
676
677
412
  if (error_code != nullptr) {
678
230
    custom_error_ = error_code;
679
230
    custom_error_str_ = error_message;
680
  }
681
682
412
  if (env_ != nullptr) {
683
113
    exit_code_ = code;
684
113
    Stop(env_);
685
  } else {
686
299
    stopped_ = true;
687
  }
688
412
}
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
827
void GetEnvMessagePort(const FunctionCallbackInfo<Value>& args) {
785
827
  Environment* env = Environment::GetCurrent(args);
786
827
  Local<Object> port = env->message_port();
787

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

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