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: 387 436 88.8 %
Date: 2020-08-07 22:13:19 Branches: 184 258 71.3 %

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

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

263
          if (more && !is_stopped()) continue;
349
350
264
          EmitBeforeExit(env_.get());
351
352
          // Emit `beforeExit` if the loop became alive either after emitting
353
          // event, or after running some callbacks.
354
264
          more = uv_loop_alive(&data.loop_);
355

263
        } while (more == true && !is_stopped());
356
342
        env_->performance_state()->Mark(
357
343
            node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
358
      }
359
    }
360
361
    {
362
      int exit_code;
363
343
      bool stopped = is_stopped();
364
343
      if (!stopped)
365
262
        exit_code = EmitExit(env_.get());
366
686
      Mutex::ScopedLock lock(mutex_);
367

343
      if (exit_code_ == 0 && !stopped)
368
260
        exit_code_ = exit_code;
369
370
343
      Debug(this, "Exiting thread for worker %llu with exit code %d",
371
            thread_id_.id, exit_code_);
372
    }
373
  }
374
375
343
  Debug(this, "Worker %llu thread stops", thread_id_.id);
376
}
377
378
343
void Worker::CreateEnvMessagePort(Environment* env) {
379
686
  HandleScope handle_scope(isolate_);
380
686
  Mutex::ScopedLock lock(mutex_);
381
  // Set up the message channel for receiving messages in the child.
382
686
  MessagePort* child_port = MessagePort::New(env,
383
                                             env->context(),
384
686
                                             std::move(child_port_data_));
385
  // MessagePort::New() may return nullptr if execution is terminated
386
  // within it.
387
343
  if (child_port != nullptr)
388
343
    env->set_message_port(child_port->object(isolate_));
389
343
}
390
391
564
void Worker::JoinThread() {
392
564
  if (thread_joined_)
393
4
    return;
394
560
  CHECK_EQ(uv_thread_join(&tid_), 0);
395
560
  thread_joined_ = true;
396
397
560
  env()->remove_sub_worker_context(this);
398
399
  {
400
1118
    HandleScope handle_scope(env()->isolate());
401
560
    Context::Scope context_scope(env()->context());
402
403
    // Reset the parent port as we're closing it now anyway.
404
1680
    object()->Set(env()->context(),
405
                  env()->message_port_string(),
406
2800
                  Undefined(env()->isolate())).Check();
407
408
    Local<Value> args[] = {
409
        Integer::New(env()->isolate(), exit_code_),
410
560
        custom_error_ != nullptr
411
767
            ? OneByteString(env()->isolate(), custom_error_).As<Value>()
412
1266
            : Null(env()->isolate()).As<Value>(),
413
560
        !custom_error_str_.empty()
414
767
            ? OneByteString(env()->isolate(), custom_error_str_.c_str())
415
                  .As<Value>()
416
1266
            : Null(env()->isolate()).As<Value>(),
417

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

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

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

41
    if (errors.size() > 0 || invalid_args.size() > 0) {
551
      Local<Value> error;
552
6
      if (!ToV8Value(env->context(),
553
3
                     errors.size() > 0 ? errors : invalid_args)
554
3
                         .ToLocal(&error)) {
555
        return;
556
      }
557
      Local<String> key =
558
3
          FIXED_ONE_BYTE_STRING(env->isolate(), "invalidExecArgv");
559
      // Ignore the return value of Set() because exceptions bubble up to JS
560
      // when we return anyway.
561
9
      USE(args.This()->Set(env->context(), key, error));
562
3
      return;
563
    }
564
  } else {
565
524
    exec_argv_out = env->exec_argv();
566
  }
567
568
  Worker* worker = new Worker(env,
569
1124
                              args.This(),
570
                              url,
571
                              per_isolate_opts,
572
                              std::move(exec_argv_out),
573
562
                              env_vars);
574
575
1124
  CHECK(args[3]->IsFloat64Array());
576
1124
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
577
562
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
578
1124
  limit_info->CopyContents(worker->resource_limits_,
579
562
                           sizeof(worker->resource_limits_));
580
581
1124
  CHECK(args[4]->IsBoolean());
582

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

34
  if (!w->has_ref_ && !w->thread_joined_) {
665
3
    w->has_ref_ = true;
666
3
    w->env()->add_refs(1);
667
  }
668
}
669
670
5
void Worker::Unref(const FunctionCallbackInfo<Value>& args) {
671
  Worker* w;
672
5
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
673

5
  if (w->has_ref_ && !w->thread_joined_) {
674
4
    w->has_ref_ = false;
675
4
    w->env()->add_refs(-1);
676
  }
677
}
678
679
1
void Worker::GetResourceLimits(const FunctionCallbackInfo<Value>& args) {
680
  Worker* w;
681
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
682
3
  args.GetReturnValue().Set(w->GetResourceLimits(args.GetIsolate()));
683
}
684
685
346
Local<Float64Array> Worker::GetResourceLimits(Isolate* isolate) const {
686
346
  Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, sizeof(resource_limits_));
687
688
1038
  memcpy(ab->GetBackingStore()->Data(),
689
         resource_limits_,
690
346
         sizeof(resource_limits_));
691
346
  return Float64Array::New(ab, 0, kTotalResourceLimitCount);
692
}
693
694
310
void Worker::Exit(int code, const char* error_code, const char* error_message) {
695
620
  Mutex::ScopedLock lock(mutex_);
696
310
  Debug(this, "Worker %llu called Exit(%d, %s, %s)",
697
        thread_id_.id, code, error_code, error_message);
698
699
310
  if (error_code != nullptr) {
700
207
    custom_error_ = error_code;
701
207
    custom_error_str_ = error_message;
702
  }
703
704
310
  if (env_ != nullptr) {
705
84
    exit_code_ = code;
706
84
    Stop(env_);
707
  } else {
708
226
    stopped_ = true;
709
  }
710
310
}
711
712
void Worker::MemoryInfo(MemoryTracker* tracker) const {
713
  tracker->TrackField("parent_port", parent_port_);
714
}
715
716
class WorkerHeapSnapshotTaker : public AsyncWrap {
717
 public:
718
  WorkerHeapSnapshotTaker(Environment* env, Local<Object> obj)
719
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_WORKERHEAPSNAPSHOT) {}
720
721
  SET_NO_MEMORY_INFO()
722
  SET_MEMORY_INFO_NAME(WorkerHeapSnapshotTaker)
723
  SET_SELF_SIZE(WorkerHeapSnapshotTaker)
724
};
725
726
void Worker::TakeHeapSnapshot(const FunctionCallbackInfo<Value>& args) {
727
  Worker* w;
728
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
729
730
  Debug(w, "Worker %llu taking heap snapshot", w->thread_id_.id);
731
732
  Environment* env = w->env();
733
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(w);
734
  Local<Object> wrap;
735
  if (!env->worker_heap_snapshot_taker_template()
736
      ->NewInstance(env->context()).ToLocal(&wrap)) {
737
    return;
738
  }
739
  BaseObjectPtr<WorkerHeapSnapshotTaker> taker =
740
      MakeDetachedBaseObject<WorkerHeapSnapshotTaker>(env, wrap);
741
742
  // Interrupt the worker thread and take a snapshot, then schedule a call
743
  // on the parent thread that turns that snapshot into a readable stream.
744
  bool scheduled = w->RequestInterrupt([taker, env](Environment* worker_env) {
745
    heap::HeapSnapshotPointer snapshot {
746
        worker_env->isolate()->GetHeapProfiler()->TakeHeapSnapshot() };
747
    CHECK(snapshot);
748
    env->SetImmediateThreadsafe(
749
        [taker, snapshot = std::move(snapshot)](Environment* env) mutable {
750
          HandleScope handle_scope(env->isolate());
751
          Context::Scope context_scope(env->context());
752
753
          AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(taker.get());
754
          BaseObjectPtr<AsyncWrap> stream = heap::CreateHeapSnapshotStream(
755
              env, std::move(snapshot));
756
          Local<Value> args[] = { stream->object() };
757
          taker->MakeCallback(env->ondone_string(), arraysize(args), args);
758
        }, CallbackFlags::kUnrefed);
759
  });
760
  args.GetReturnValue().Set(scheduled ? taker->object() : Local<Object>());
761
}
762
763
namespace {
764
765
// Return the MessagePort that is global for this Environment and communicates
766
// with the internal [kPort] port of the JS Worker class in the parent thread.
767
687
void GetEnvMessagePort(const FunctionCallbackInfo<Value>& args) {
768
687
  Environment* env = Environment::GetCurrent(args);
769
687
  Local<Object> port = env->message_port();
770

1374
  CHECK_IMPLIES(!env->is_main_thread(), !port.IsEmpty());
771
687
  if (!port.IsEmpty()) {
772
2061
    CHECK_EQ(port->CreationContext()->GetIsolate(), args.GetIsolate());
773
1374
    args.GetReturnValue().Set(port);
774
  }
775
687
}
776
777
4039
void InitWorker(Local<Object> target,
778
                Local<Value> unused,
779
                Local<Context> context,
780
                void* priv) {
781
4039
  Environment* env = Environment::GetCurrent(context);
782
783
  {
784
4039
    Local<FunctionTemplate> w = env->NewFunctionTemplate(Worker::New);
785
786
12117
    w->InstanceTemplate()->SetInternalFieldCount(
787
4039
        Worker::kInternalFieldCount);
788
8078
    w->Inherit(AsyncWrap::GetConstructorTemplate(env));
789
790
4039
    env->SetProtoMethod(w, "startThread", Worker::StartThread);
791
4039
    env->SetProtoMethod(w, "stopThread", Worker::StopThread);
792
4039
    env->SetProtoMethod(w, "ref", Worker::Ref);
793
4039
    env->SetProtoMethod(w, "unref", Worker::Unref);
794
4039
    env->SetProtoMethod(w, "getResourceLimits", Worker::GetResourceLimits);
795
4039
    env->SetProtoMethod(w, "takeHeapSnapshot", Worker::TakeHeapSnapshot);
796
797
    Local<String> workerString =
798
4039
        FIXED_ONE_BYTE_STRING(env->isolate(), "Worker");
799
4039
    w->SetClassName(workerString);
800
8078
    target->Set(env->context(),
801
                workerString,
802
20195
                w->GetFunction(env->context()).ToLocalChecked()).Check();
803
  }
804
805
  {
806
4039
    Local<FunctionTemplate> wst = FunctionTemplate::New(env->isolate());
807
808
12117
    wst->InstanceTemplate()->SetInternalFieldCount(
809
4039
        WorkerHeapSnapshotTaker::kInternalFieldCount);
810
8078
    wst->Inherit(AsyncWrap::GetConstructorTemplate(env));
811
812
    Local<String> wst_string =
813
4039
        FIXED_ONE_BYTE_STRING(env->isolate(), "WorkerHeapSnapshotTaker");
814
4039
    wst->SetClassName(wst_string);
815
4039
    env->set_worker_heap_snapshot_taker_template(wst->InstanceTemplate());
816
  }
817
818
4039
  env->SetMethod(target, "getEnvMessagePort", GetEnvMessagePort);
819
820
  target
821
8078
      ->Set(env->context(),
822
            env->thread_id_string(),
823
20195
            Number::New(env->isolate(), static_cast<double>(env->thread_id())))
824
      .Check();
825
826
  target
827
8078
      ->Set(env->context(),
828
            FIXED_ONE_BYTE_STRING(env->isolate(), "isMainThread"),
829
20195
            Boolean::New(env->isolate(), env->is_main_thread()))
830
      .Check();
831
832
  target
833
8078
      ->Set(env->context(),
834
            FIXED_ONE_BYTE_STRING(env->isolate(), "ownsProcessState"),
835
20195
            Boolean::New(env->isolate(), env->owns_process_state()))
836
      .Check();
837
838
4039
  if (!env->is_main_thread()) {
839
    target
840
690
        ->Set(env->context(),
841
              FIXED_ONE_BYTE_STRING(env->isolate(), "resourceLimits"),
842
1725
              env->worker_context()->GetResourceLimits(env->isolate()))
843
        .Check();
844
  }
845
846
16156
  NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb);
847
16156
  NODE_DEFINE_CONSTANT(target, kMaxOldGenerationSizeMb);
848
16156
  NODE_DEFINE_CONSTANT(target, kCodeRangeSizeMb);
849
16156
  NODE_DEFINE_CONSTANT(target, kStackSizeMb);
850
16156
  NODE_DEFINE_CONSTANT(target, kTotalResourceLimitCount);
851
4039
}
852
853
}  // anonymous namespace
854
855
}  // namespace worker
856
}  // namespace node
857
858

17763
NODE_MODULE_CONTEXT_AWARE_INTERNAL(worker, node::worker::InitWorker)