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: 384 433 88.7 %
Date: 2020-06-24 22:13:30 Branches: 181 248 73.0 %

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
554
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
554
               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
554
      platform_(env->isolate_data()->platform()),
54
      thread_id_(AllocateEnvironmentThreadId()),
55
1108
      env_vars_(env_vars) {
56
554
  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
554
  parent_port_ = MessagePort::New(env, env->context());
61
554
  if (parent_port_ == nullptr) {
62
    // This can happen e.g. because execution is terminating.
63
    return;
64
  }
65
66
554
  child_port_data_ = std::make_unique<MessagePortData>(nullptr);
67
554
  MessagePort::Entangle(parent_port_, child_port_data_.get());
68
69
1662
  object()->Set(env->context(),
70
                env->message_port_string(),
71
2770
                parent_port_->object()).Check();
72
73
1662
  object()->Set(env->context(),
74
                env->thread_id_string(),
75
2770
                Number::New(env->isolate(), static_cast<double>(thread_id_.id)))
76
      .Check();
77
78
1108
  inspector_parent_handle_ = GetInspectorParentHandle(
79
554
      env, thread_id_, url.c_str());
80
81
554
  argv_ = std::vector<std::string>{env->argv()[0]};
82
  // Mark this Worker object as weak until we actually start the thread.
83
554
  MakeWeak();
84
85
554
  Debug(this, "Preparation for worker %llu finished", thread_id_.id);
86
}
87
88
2699
bool Worker::is_stopped() const {
89
5398
  Mutex::ScopedLock lock(mutex_);
90
2699
  if (env_ != nullptr)
91
1678
    return env_->is_stopping();
92
1021
  return stopped_;
93
}
94
95
350
void Worker::UpdateResourceConstraints(ResourceConstraints* constraints) {
96
350
  constraints->set_stack_limit(reinterpret_cast<uint32_t*>(stack_base_));
97
98
350
  if (resource_limits_[kMaxYoungGenerationSizeMb] > 0) {
99
1
    constraints->set_max_young_generation_size_in_bytes(
100
2
        resource_limits_[kMaxYoungGenerationSizeMb] * kMB);
101
  } else {
102
349
    resource_limits_[kMaxYoungGenerationSizeMb] =
103
349
        constraints->max_young_generation_size_in_bytes() / kMB;
104
  }
105
106
350
  if (resource_limits_[kMaxOldGenerationSizeMb] > 0) {
107
1
    constraints->set_max_old_generation_size_in_bytes(
108
2
        resource_limits_[kMaxOldGenerationSizeMb] * kMB);
109
  } else {
110
349
    resource_limits_[kMaxOldGenerationSizeMb] =
111
349
        constraints->max_old_generation_size_in_bytes() / kMB;
112
  }
113
114
350
  if (resource_limits_[kCodeRangeSizeMb] > 0) {
115
1
    constraints->set_code_range_size_in_bytes(
116
2
        resource_limits_[kCodeRangeSizeMb] * kMB);
117
  } else {
118
349
    resource_limits_[kCodeRangeSizeMb] =
119
349
        constraints->code_range_size_in_bytes() / kMB;
120
  }
121
350
}
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
552
  explicit WorkerThreadData(Worker* w)
129
552
    : w_(w) {
130
552
    int ret = uv_loop_init(&loop_);
131
552
    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
350
    loop_init_failed_ = false;
138
139
    std::shared_ptr<ArrayBufferAllocator> allocator =
140
700
        ArrayBufferAllocator::Create();
141
700
    Isolate::CreateParams params;
142
350
    SetIsolateCreateParamsForNode(&params);
143
350
    params.array_buffer_allocator_shared = allocator;
144
145
350
    w->UpdateResourceConstraints(&params.constraints);
146
147
350
    Isolate* isolate = Isolate::Allocate();
148
350
    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
350
    w->platform_->RegisterIsolate(isolate, &loop_);
156
350
    Isolate::Initialize(isolate, params);
157
350
    SetIsolateUpForNode(isolate);
158
159
350
    isolate->AddNearHeapLimitCallback(Worker::NearHeapLimit, w);
160
161
    {
162
350
      Locker locker(isolate);
163
700
      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
350
      isolate->SetStackLimit(w->stack_base_);
167
168
700
      HandleScope handle_scope(isolate);
169
700
      isolate_data_.reset(CreateIsolateData(isolate,
170
                                            &loop_,
171
350
                                            w_->platform_,
172
350
                                            allocator.get()));
173
350
      CHECK(isolate_data_);
174
350
      if (w_->per_isolate_opts_)
175
40
        isolate_data_->set_options(std::move(w_->per_isolate_opts_));
176
350
      isolate_data_->set_worker_context(w_);
177
    }
178
179
700
    Mutex::ScopedLock lock(w_->mutex_);
180
350
    w_->isolate_ = isolate;
181
  }
182
183
1103
  ~WorkerThreadData() {
184
551
    Debug(w_, "Worker %llu dispose isolate", w_->thread_id_.id);
185
    Isolate* isolate;
186
    {
187
1103
      Mutex::ScopedLock lock(w_->mutex_);
188
551
      isolate = w_->isolate_;
189
551
      w_->isolate_ = nullptr;
190
    }
191
192
552
    if (isolate != nullptr) {
193
350
      CHECK(!loop_init_failed_);
194
350
      bool platform_finished = false;
195
196
350
      isolate_data_.reset();
197
198
2100
      w_->platform_->AddIsolateFinishedCallback(isolate, [](void* data) {
199
350
        *static_cast<bool*>(data) = true;
200
1750
      }, &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
350
      w_->platform_->UnregisterIsolate(isolate);
208
350
      isolate->Dispose();
209
210
      // Wait until the platform has cleaned up all relevant resources.
211
1050
      while (!platform_finished) {
212
350
        uv_run(&loop_, UV_RUN_ONCE);
213
      }
214
    }
215
552
    if (!loop_init_failed_) {
216
350
      CheckedUvLoopClose(&loop_);
217
    }
218
551
  }
219
220
350
  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
552
void Worker::Run() {
242
887
  std::string name = "WorkerThread ";
243
552
  name += std::to_string(thread_id_.id);
244

1106
  TRACE_EVENT_METADATA1(
245
      "__metadata", "thread_name", "name",
246
      TRACE_STR_COPY(name.c_str()));
247
552
  CHECK_NOT_NULL(platform_);
248
249
552
  Debug(this, "Creating isolate for worker with id %llu", thread_id_.id);
250
251
887
  WorkerThreadData data(this);
252
552
  if (isolate_ == nullptr) return;
253
350
  CHECK(data.loop_is_usable());
254
255
350
  Debug(this, "Starting worker with id %llu", thread_id_.id);
256
  {
257
685
    Locker locker(isolate_);
258
685
    Isolate::Scope isolate_scope(isolate_);
259
685
    SealHandleScope outer_seal(isolate_);
260
261
684
    DeleteFnPtr<Environment, FreeEnvironment> env_;
262
349
    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
1354
      isolate_->CancelTerminateExecution();
267
268
685
      if (!env_) return;
269
335
      env_->set_can_call_into_js(false);
270
271
      {
272
670
        Mutex::ScopedLock lock(mutex_);
273
335
        stopped_ = true;
274
335
        this->env_ = nullptr;
275
      }
276
277
335
      env_.reset();
278
684
    });
279
280
350
    if (is_stopped()) return;
281
    {
282
675
      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
676
        TryCatch try_catch(isolate_);
290
340
        context = NewContext(isolate_);
291
340
        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
336
      if (is_stopped()) return;
300
335
      CHECK(!context.IsEmpty());
301
335
      Context::Scope context_scope(context);
302
      {
303
1005
        env_.reset(CreateEnvironment(
304
            data.isolate_data_.get(),
305
            context,
306
335
            std::move(argv_),
307
335
            std::move(exec_argv_),
308
            EnvironmentFlags::kNoFlags,
309
            thread_id_,
310
670
            std::move(inspector_parent_handle_)));
311
335
        if (is_stopped()) return;
312
335
        CHECK_NOT_NULL(env_);
313
335
        env_->set_env_vars(std::move(env_vars_));
314
713
        SetProcessExitHandler(env_.get(), [this](Environment*, int exit_code) {
315
43
          Exit(exit_code);
316
378
        });
317
      }
318
      {
319
670
        Mutex::ScopedLock lock(mutex_);
320
335
        if (stopped_) return;
321
335
        this->env_ = env_.get();
322
      }
323
335
      Debug(this, "Created Environment for worker with id %llu", thread_id_.id);
324
335
      if (is_stopped()) return;
325
      {
326
335
        CreateEnvMessagePort(env_.get());
327
335
        Debug(this, "Created message port for worker %llu", thread_id_.id);
328
670
        if (LoadEnvironment(env_.get(), StartExecutionCallback{}).IsEmpty())
329
          return;
330
331
335
        Debug(this, "Loaded environment for worker %llu", thread_id_.id);
332
      }
333
334
335
      if (is_stopped()) return;
335
      {
336
669
        SealHandleScope seal(isolate_);
337
        bool more;
338
335
        env_->performance_state()->Mark(
339
335
            node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
340
260
        do {
341
336
          if (is_stopped()) break;
342
336
          uv_run(&data.loop_, UV_RUN_DEFAULT);
343
336
          if (is_stopped()) break;
344
345
260
          platform_->DrainTasks(isolate_);
346
347
259
          more = uv_loop_alive(&data.loop_);
348

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

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

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

4416
    };
418
419
552
    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
1584
Worker::~Worker() {
429
1056
  Mutex::ScopedLock lock(mutex_);
430
431
528
  CHECK(stopped_);
432
528
  CHECK_NULL(env_);
433
528
  CHECK(thread_joined_);
434
435
528
  Debug(this, "Worker %llu destroyed", thread_id_.id);
436
1056
}
437
438
557
void Worker::New(const FunctionCallbackInfo<Value>& args) {
439
557
  Environment* env = Environment::GetCurrent(args);
440
557
  Isolate* isolate = args.GetIsolate();
441
442
557
  CHECK(args.IsConstructCall());
443
444
557
  if (env->isolate_data()->platform() == nullptr) {
445
    THROW_ERR_MISSING_PLATFORM_FOR_WORKER(env);
446
    return;
447
  }
448
449
1111
  std::string url;
450
1111
  std::shared_ptr<PerIsolateOptions> per_isolate_opts = nullptr;
451
1111
  std::shared_ptr<KVStore> env_vars = nullptr;
452
453
1111
  std::vector<std::string> exec_argv_out;
454
455
557
  CHECK_EQ(args.Length(), 4);
456
  // Argument might be a string or URL
457
1671
  if (!args[0]->IsNullOrUndefined()) {
458
    Utf8Value value(
459
535
        isolate, args[0]->ToString(env->context()).FromMaybe(Local<String>()));
460
107
    url.append(value.out(), value.length());
461
  }
462
463
1671
  if (args[1]->IsNull()) {
464
    // Means worker.env = { ...process.env }.
465
532
    env_vars = env->env_vars()->Clone(isolate);
466
50
  } else if (args[1]->IsObject()) {
467
    // User provided env.
468
24
    env_vars = KVStore::CreateMapKVStore();
469
24
    env_vars->AssignFromObject(isolate->GetCurrentContext(),
470
72
                               args[1].As<Object>());
471
  } else {
472
    // Env is shared.
473
1
    env_vars = env->env_vars();
474
  }
475
476

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

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

41
    if (errors.size() > 0 || invalid_args.size() > 0) {
552
      Local<Value> error;
553
6
      if (!ToV8Value(env->context(),
554
3
                     errors.size() > 0 ? errors : invalid_args)
555
3
                         .ToLocal(&error)) {
556
        return;
557
      }
558
      Local<String> key =
559
3
          FIXED_ONE_BYTE_STRING(env->isolate(), "invalidExecArgv");
560
      // Ignore the return value of Set() because exceptions bubble up to JS
561
      // when we return anyway.
562
9
      USE(args.This()->Set(env->context(), key, error));
563
3
      return;
564
    }
565
  } else {
566
516
    exec_argv_out = env->exec_argv();
567
  }
568
569
  Worker* worker = new Worker(env,
570
1108
                              args.This(),
571
                              url,
572
                              per_isolate_opts,
573
                              std::move(exec_argv_out),
574
554
                              env_vars);
575
576
1108
  CHECK(args[3]->IsFloat64Array());
577
1108
  Local<Float64Array> limit_info = args[3].As<Float64Array>();
578
554
  CHECK_EQ(limit_info->Length(), kTotalResourceLimitCount);
579
1108
  limit_info->CopyContents(worker->resource_limits_,
580
554
                           sizeof(worker->resource_limits_));
581
}
582
583
552
void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {
584
  Worker* w;
585
552
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
586
1104
  Mutex::ScopedLock lock(w->mutex_);
587
588
552
  w->stopped_ = false;
589
590
552
  if (w->resource_limits_[kStackSizeMb] > 0) {
591
9
    if (w->resource_limits_[kStackSizeMb] * kMB < kStackBufferSize) {
592
3
      w->resource_limits_[kStackSizeMb] = kStackBufferSize / kMB;
593
3
      w->stack_size_ = kStackBufferSize;
594
    } else {
595
6
      w->stack_size_ = w->resource_limits_[kStackSizeMb] * kMB;
596
    }
597
  } else {
598
543
    w->resource_limits_[kStackSizeMb] = w->stack_size_ / kMB;
599
  }
600
601
  uv_thread_options_t thread_options;
602
552
  thread_options.flags = UV_THREAD_HAS_STACK_SIZE;
603
552
  thread_options.stack_size = w->stack_size_;
604
2758
  int ret = uv_thread_create_ex(&w->tid_, &thread_options, [](void* arg) {
605
    // XXX: This could become a std::unique_ptr, but that makes at least
606
    // gcc 6.3 detect undefined behaviour when there shouldn't be any.
607
    // gcc 7+ handles this well.
608
550
    Worker* w = static_cast<Worker*>(arg);
609
550
    const uintptr_t stack_top = reinterpret_cast<uintptr_t>(&arg);
610
611
    // Leave a few kilobytes just to make sure we're within limits and have
612
    // some space to do work in C++ land.
613
550
    w->stack_base_ = stack_top - (w->stack_size_ - kStackBufferSize);
614
615
550
    w->Run();
616
617
1104
    Mutex::ScopedLock lock(w->mutex_);
618
1104
    w->env()->SetImmediateThreadsafe(
619
2159
        [w = std::unique_ptr<Worker>(w)](Environment* env) {
620
530
          if (w->has_ref_)
621
528
            env->add_refs(-1);
622
530
          w->JoinThread();
623
          // implicitly delete w
624
1077
        });
625
2208
  }, static_cast<void*>(w));
626
627
552
  if (ret == 0) {
628
    // The object now owns the created thread and should not be garbage
629
    // collected until that finishes.
630
552
    w->ClearWeak();
631
552
    w->thread_joined_ = false;
632
633
552
    if (w->has_ref_)
634
552
      w->env()->add_refs(1);
635
636
552
    w->env()->add_sub_worker_context(w);
637
  } else {
638
    w->stopped_ = true;
639
640
    char err_buf[128];
641
    uv_err_name_r(ret, err_buf, sizeof(err_buf));
642
    {
643
      Isolate* isolate = w->env()->isolate();
644
      HandleScope handle_scope(isolate);
645
      THROW_ERR_WORKER_INIT_FAILED(isolate, err_buf);
646
    }
647
  }
648
}
649
650
32
void Worker::StopThread(const FunctionCallbackInfo<Value>& args) {
651
  Worker* w;
652
32
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
653
654
32
  Debug(w, "Worker %llu is getting stopped by parent", w->thread_id_.id);
655
32
  w->Exit(1);
656
}
657
658
34
void Worker::Ref(const FunctionCallbackInfo<Value>& args) {
659
  Worker* w;
660
34
  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
661

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

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

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