GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/api/environment.cc Lines: 329 369 89.2 %
Date: 2020-07-19 22:14:24 Branches: 105 172 61.0 %

Line Branch Exec Source
1
#include "node.h"
2
#include "node_context_data.h"
3
#include "node_errors.h"
4
#include "node_internals.h"
5
#include "node_native_module_env.h"
6
#include "node_platform.h"
7
#include "node_v8_platform-inl.h"
8
#include "uv.h"
9
10
#if HAVE_INSPECTOR
11
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
12
#endif
13
14
namespace node {
15
using errors::TryCatchScope;
16
using v8::Array;
17
using v8::Context;
18
using v8::EscapableHandleScope;
19
using v8::Function;
20
using v8::FunctionCallbackInfo;
21
using v8::HandleScope;
22
using v8::Isolate;
23
using v8::Local;
24
using v8::MaybeLocal;
25
using v8::Null;
26
using v8::Object;
27
using v8::ObjectTemplate;
28
using v8::Private;
29
using v8::PropertyDescriptor;
30
using v8::SealHandleScope;
31
using v8::String;
32
using v8::Value;
33
34
54
static bool AllowWasmCodeGenerationCallback(Local<Context> context,
35
                                            Local<String>) {
36
  Local<Value> wasm_code_gen =
37
108
      context->GetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration);
38

162
  return wasm_code_gen->IsUndefined() || wasm_code_gen->IsTrue();
39
}
40
41
32
static bool ShouldAbortOnUncaughtException(Isolate* isolate) {
42
32
  DebugSealHandleScope scope(isolate);
43
32
  Environment* env = Environment::GetCurrent(isolate);
44
32
  return env != nullptr &&
45

64
         (env->is_main_thread() || !env->is_stopping()) &&
46

96
         env->should_abort_on_uncaught_toggle()[0] &&
47
65
         !env->inside_should_not_abort_on_uncaught_scope();
48
}
49
50
73834
static MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context,
51
                                      Local<Value> exception,
52
                                      Local<Array> trace) {
53
73834
  Environment* env = Environment::GetCurrent(context);
54
73834
  if (env == nullptr) {
55
    return exception->ToString(context).FromMaybe(Local<Value>());
56
  }
57
73834
  Local<Function> prepare = env->prepare_stack_trace_callback();
58
73834
  if (prepare.IsEmpty()) {
59
    return exception->ToString(context).FromMaybe(Local<Value>());
60
  }
61
  Local<Value> args[] = {
62
      context->Global(),
63
      exception,
64
      trace,
65
295336
  };
66
  // This TryCatch + Rethrow is required by V8 due to details around exception
67
  // handling there. For C++ callbacks, V8 expects a scheduled exception (which
68
  // is what ReThrow gives us). Just returning the empty MaybeLocal would leave
69
  // us with a pending exception.
70
147668
  TryCatchScope try_catch(env);
71
  MaybeLocal<Value> result = prepare->Call(
72
147668
      context, Undefined(env->isolate()), arraysize(args), args);
73

73834
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
74
2
    try_catch.ReThrow();
75
  }
76
73834
  return result;
77
}
78
79
478466
void* NodeArrayBufferAllocator::Allocate(size_t size) {
80
  void* ret;
81

478466
  if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers)
82
31180
    ret = UncheckedCalloc(size);
83
  else
84
447286
    ret = UncheckedMalloc(size);
85
478466
  if (LIKELY(ret != nullptr))
86
478466
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
87
478466
  return ret;
88
}
89
90
82742
void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) {
91
82742
  void* ret = node::UncheckedMalloc(size);
92
82742
  if (LIKELY(ret != nullptr))
93
82742
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
94
82742
  return ret;
95
}
96
97
325443
void* NodeArrayBufferAllocator::Reallocate(
98
    void* data, size_t old_size, size_t size) {
99
325443
  void* ret = UncheckedRealloc<char>(static_cast<char*>(data), size);
100

325443
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
101
325443
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
102
325443
  return ret;
103
}
104
105
551401
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
106
551401
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
107
551401
  free(data);
108
551401
}
109
110
9
DebuggingArrayBufferAllocator::~DebuggingArrayBufferAllocator() {
111
3
  CHECK(allocations_.empty());
112
6
}
113
114
35
void* DebuggingArrayBufferAllocator::Allocate(size_t size) {
115
70
  Mutex::ScopedLock lock(mutex_);
116
35
  void* data = NodeArrayBufferAllocator::Allocate(size);
117
35
  RegisterPointerInternal(data, size);
118
70
  return data;
119
}
120
121
19
void* DebuggingArrayBufferAllocator::AllocateUninitialized(size_t size) {
122
38
  Mutex::ScopedLock lock(mutex_);
123
19
  void* data = NodeArrayBufferAllocator::AllocateUninitialized(size);
124
19
  RegisterPointerInternal(data, size);
125
38
  return data;
126
}
127
128
54
void DebuggingArrayBufferAllocator::Free(void* data, size_t size) {
129
108
  Mutex::ScopedLock lock(mutex_);
130
54
  UnregisterPointerInternal(data, size);
131
54
  NodeArrayBufferAllocator::Free(data, size);
132
54
}
133
134
void* DebuggingArrayBufferAllocator::Reallocate(void* data,
135
                                                size_t old_size,
136
                                                size_t size) {
137
  Mutex::ScopedLock lock(mutex_);
138
  void* ret = NodeArrayBufferAllocator::Reallocate(data, old_size, size);
139
  if (ret == nullptr) {
140
    if (size == 0)  // i.e. equivalent to free().
141
      UnregisterPointerInternal(data, old_size);
142
    return nullptr;
143
  }
144
145
  if (data != nullptr) {
146
    auto it = allocations_.find(data);
147
    CHECK_NE(it, allocations_.end());
148
    allocations_.erase(it);
149
  }
150
151
  RegisterPointerInternal(ret, size);
152
  return ret;
153
}
154
155
void DebuggingArrayBufferAllocator::RegisterPointer(void* data, size_t size) {
156
  Mutex::ScopedLock lock(mutex_);
157
  NodeArrayBufferAllocator::RegisterPointer(data, size);
158
  RegisterPointerInternal(data, size);
159
}
160
161
void DebuggingArrayBufferAllocator::UnregisterPointer(void* data, size_t size) {
162
  Mutex::ScopedLock lock(mutex_);
163
  NodeArrayBufferAllocator::UnregisterPointer(data, size);
164
  UnregisterPointerInternal(data, size);
165
}
166
167
54
void DebuggingArrayBufferAllocator::UnregisterPointerInternal(void* data,
168
                                                              size_t size) {
169
54
  if (data == nullptr) return;
170
54
  auto it = allocations_.find(data);
171
54
  CHECK_NE(it, allocations_.end());
172
54
  if (size > 0) {
173
    // We allow allocations with size 1 for 0-length buffers to avoid having
174
    // to deal with nullptr values.
175
54
    CHECK_EQ(it->second, size);
176
  }
177
54
  allocations_.erase(it);
178
}
179
180
54
void DebuggingArrayBufferAllocator::RegisterPointerInternal(void* data,
181
                                                            size_t size) {
182
54
  if (data == nullptr) return;
183
54
  CHECK_EQ(allocations_.count(data), 0);
184
54
  allocations_[data] = size;
185
}
186
187
5333
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
188

5333
  if (debug || per_process::cli_options->debug_arraybuffer_allocations)
189
3
    return std::make_unique<DebuggingArrayBufferAllocator>();
190
  else
191
5330
    return std::make_unique<NodeArrayBufferAllocator>();
192
}
193
194
49
ArrayBufferAllocator* CreateArrayBufferAllocator() {
195
49
  return ArrayBufferAllocator::Create().release();
196
}
197
198
49
void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator) {
199
49
  delete allocator;
200
49
}
201
202
5332
void SetIsolateCreateParamsForNode(Isolate::CreateParams* params) {
203
5332
  const uint64_t constrained_memory = uv_get_constrained_memory();
204
5332
  const uint64_t total_memory = constrained_memory > 0 ?
205
5332
      std::min(uv_get_total_memory(), constrained_memory) :
206
5332
      uv_get_total_memory();
207
5332
  if (total_memory > 0) {
208
    // V8 defaults to 700MB or 1.4GB on 32 and 64 bit platforms respectively.
209
    // This default is based on browser use-cases. Tell V8 to configure the
210
    // heap based on the actual physical memory.
211
5332
    params->constraints.ConfigureDefaults(total_memory, 0);
212
  }
213
5332
  params->embedder_wrapper_object_index = BaseObject::InternalFields::kSlot;
214
5332
  params->embedder_wrapper_type_index = std::numeric_limits<int>::max();
215
5332
}
216
217
5332
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
218
5332
  if (s.flags & MESSAGE_LISTENER_WITH_ERROR_LEVEL)
219
5332
    isolate->AddMessageListenerWithErrorLevel(
220
            errors::PerIsolateMessageListener,
221
            Isolate::MessageErrorLevel::kMessageError |
222
5332
                Isolate::MessageErrorLevel::kMessageWarning);
223
224
5332
  auto* abort_callback = s.should_abort_on_uncaught_exception_callback ?
225
      s.should_abort_on_uncaught_exception_callback :
226
5332
      ShouldAbortOnUncaughtException;
227
5332
  isolate->SetAbortOnUncaughtExceptionCallback(abort_callback);
228
229
5332
  auto* fatal_error_cb = s.fatal_error_callback ?
230
5332
      s.fatal_error_callback : OnFatalError;
231
5332
  isolate->SetFatalErrorHandler(fatal_error_cb);
232
233
5332
  auto* prepare_stack_trace_cb = s.prepare_stack_trace_callback ?
234
5332
      s.prepare_stack_trace_callback : PrepareStackTraceCallback;
235
5332
  isolate->SetPrepareStackTraceCallback(prepare_stack_trace_cb);
236
5332
}
237
238
5333
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
239
5333
  isolate->SetMicrotasksPolicy(s.policy);
240
241
5333
  auto* allow_wasm_codegen_cb = s.allow_wasm_code_generation_callback ?
242
5333
    s.allow_wasm_code_generation_callback : AllowWasmCodeGenerationCallback;
243
5333
  isolate->SetAllowWasmCodeGenerationCallback(allow_wasm_codegen_cb);
244
245
5333
  auto* promise_reject_cb = s.promise_reject_callback ?
246
5333
    s.promise_reject_callback : task_queue::PromiseRejectCallback;
247
5333
  isolate->SetPromiseRejectCallback(promise_reject_cb);
248
249
5333
  if (s.flags & DETAILED_SOURCE_POSITIONS_FOR_PROFILING)
250
5333
    v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
251
5333
}
252
253
412
void SetIsolateUpForNode(v8::Isolate* isolate,
254
                         const IsolateSettings& settings) {
255
412
  SetIsolateErrorHandlers(isolate, settings);
256
412
  SetIsolateMiscHandlers(isolate, settings);
257
412
}
258
259
412
void SetIsolateUpForNode(v8::Isolate* isolate) {
260
412
  IsolateSettings settings;
261
412
  SetIsolateUpForNode(isolate, settings);
262
412
}
263
264
Isolate* NewIsolate(ArrayBufferAllocator* allocator, uv_loop_t* event_loop) {
265
  return NewIsolate(allocator, event_loop, GetMainThreadMultiIsolatePlatform());
266
}
267
268
// TODO(joyeecheung): we may want to expose this, but then we need to be
269
// careful about what we override in the params.
270
56
Isolate* NewIsolate(Isolate::CreateParams* params,
271
                    uv_loop_t* event_loop,
272
                    MultiIsolatePlatform* platform) {
273
56
  Isolate* isolate = Isolate::Allocate();
274
56
  if (isolate == nullptr) return nullptr;
275
276
  // Register the isolate on the platform before the isolate gets initialized,
277
  // so that the isolate can access the platform during initialization.
278
56
  platform->RegisterIsolate(isolate, event_loop);
279
280
56
  SetIsolateCreateParamsForNode(params);
281
56
  Isolate::Initialize(isolate, *params);
282
56
  SetIsolateUpForNode(isolate);
283
284
56
  return isolate;
285
}
286
287
48
Isolate* NewIsolate(ArrayBufferAllocator* allocator,
288
                    uv_loop_t* event_loop,
289
                    MultiIsolatePlatform* platform) {
290
96
  Isolate::CreateParams params;
291
48
  if (allocator != nullptr) params.array_buffer_allocator = allocator;
292
96
  return NewIsolate(&params, event_loop, platform);
293
}
294
295
8
Isolate* NewIsolate(std::shared_ptr<ArrayBufferAllocator> allocator,
296
                    uv_loop_t* event_loop,
297
                    MultiIsolatePlatform* platform) {
298
16
  Isolate::CreateParams params;
299
8
  if (allocator) params.array_buffer_allocator_shared = allocator;
300
16
  return NewIsolate(&params, event_loop, platform);
301
}
302
303
397
IsolateData* CreateIsolateData(Isolate* isolate,
304
                               uv_loop_t* loop,
305
                               MultiIsolatePlatform* platform,
306
                               ArrayBufferAllocator* allocator) {
307
397
  return new IsolateData(isolate, loop, platform, allocator);
308
}
309
310
395
void FreeIsolateData(IsolateData* isolate_data) {
311
395
  delete isolate_data;
312
395
}
313
314
563
InspectorParentHandle::~InspectorParentHandle() {}
315
316
// Hide the internal handle class from the public API.
317
#if HAVE_INSPECTOR
318
1126
struct InspectorParentHandleImpl : public InspectorParentHandle {
319
  std::unique_ptr<inspector::ParentInspectorHandle> impl;
320
321
563
  explicit InspectorParentHandleImpl(
322
      std::unique_ptr<inspector::ParentInspectorHandle>&& impl)
323
563
    : impl(std::move(impl)) {}
324
};
325
#endif
326
327
1
Environment* CreateEnvironment(IsolateData* isolate_data,
328
                               Local<Context> context,
329
                               int argc,
330
                               const char* const* argv,
331
                               int exec_argc,
332
                               const char* const* exec_argv) {
333
2
  return CreateEnvironment(
334
      isolate_data, context,
335
2
      std::vector<std::string>(argv, argv + argc),
336
4
      std::vector<std::string>(exec_argv, exec_argv + exec_argc));
337
}
338
339
382
Environment* CreateEnvironment(
340
    IsolateData* isolate_data,
341
    Local<Context> context,
342
    const std::vector<std::string>& args,
343
    const std::vector<std::string>& exec_args,
344
    EnvironmentFlags::Flags flags,
345
    ThreadId thread_id,
346
    std::unique_ptr<InspectorParentHandle> inspector_parent_handle) {
347
382
  Isolate* isolate = context->GetIsolate();
348
764
  HandleScope handle_scope(isolate);
349
  Context::Scope context_scope(context);
350
  // TODO(addaleax): This is a much better place for parsing per-Environment
351
  // options than the global parse call.
352
  Environment* env = new Environment(
353
382
      isolate_data, context, args, exec_args, nullptr, flags, thread_id);
354
#if HAVE_INSPECTOR
355
381
  if (inspector_parent_handle) {
356
681
    env->InitializeInspector(
357
        std::move(static_cast<InspectorParentHandleImpl*>(
358
684
            inspector_parent_handle.get())->impl));
359
  } else {
360
40
    env->InitializeInspector({});
361
  }
362
#endif
363
364
762
  if (env->RunBootstrapping().IsEmpty()) {
365
    FreeEnvironment(env);
366
    return nullptr;
367
  }
368
369
382
  return env;
370
}
371
372
4804
void FreeEnvironment(Environment* env) {
373
  Isolate::DisallowJavascriptExecutionScope disallow_js(env->isolate(),
374
9609
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
375
  {
376
9607
    HandleScope handle_scope(env->isolate());  // For env->context().
377
4800
    Context::Scope context_scope(env->context());
378
9608
    SealHandleScope seal_handle_scope(env->isolate());
379
380
4804
    env->set_stopping(true);
381
4805
    env->stop_sub_worker_contexts();
382
4804
    env->RunCleanup();
383
4804
    RunAtExit(env);
384
  }
385
386
  // This call needs to be made while the `Environment` is still alive
387
  // because we assume that it is available for async tracking in the
388
  // NodePlatform implementation.
389
4805
  MultiIsolatePlatform* platform = env->isolate_data()->platform();
390
4805
  if (platform != nullptr)
391
4805
    platform->DrainTasks(env->isolate());
392
393
4805
  delete env;
394
4805
}
395
396
563
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
397
    Environment* env,
398
    ThreadId thread_id,
399
    const char* url) {
400
563
  CHECK_NOT_NULL(env);
401
563
  CHECK_NE(thread_id.id, static_cast<uint64_t>(-1));
402
#if HAVE_INSPECTOR
403
1126
  return std::make_unique<InspectorParentHandleImpl>(
404
1689
      env->inspector_agent()->GetParentHandle(thread_id.id, url));
405
#else
406
  return {};
407
#endif
408
}
409
410
4920
void LoadEnvironment(Environment* env) {
411
9514
  USE(LoadEnvironment(env,
412
9514
                      StartExecutionCallback{},
413
14108
                      {}));
414
4594
}
415
416
5277
MaybeLocal<Value> LoadEnvironment(
417
    Environment* env,
418
    StartExecutionCallback cb,
419
    std::unique_ptr<InspectorParentHandle> removeme) {
420
5277
  env->InitializeLibuv();
421
5277
  env->InitializeDiagnostics();
422
423
5277
  return StartExecution(env, cb);
424
}
425
426
13
MaybeLocal<Value> LoadEnvironment(
427
    Environment* env,
428
    const char* main_script_source_utf8,
429
    std::unique_ptr<InspectorParentHandle> removeme) {
430
13
  CHECK_NOT_NULL(main_script_source_utf8);
431
  return LoadEnvironment(
432
      env,
433
13
      [&](const StartExecutionCallbackInfo& info) -> MaybeLocal<Value> {
434
        // This is a slightly hacky way to convert UTF-8 to UTF-16.
435
        Local<String> str =
436
130
            String::NewFromUtf8(env->isolate(),
437
39
                                main_script_source_utf8).ToLocalChecked();
438
24
        auto main_utf16 = std::make_unique<String::Value>(env->isolate(), str);
439
440
        // TODO(addaleax): Avoid having a global table for all scripts.
441
24
        std::string name = "embedder_main_" + std::to_string(env->thread_id());
442
13
        native_module::NativeModuleEnv::Add(
443
            name.c_str(),
444
26
            UnionBytes(**main_utf16, main_utf16->length()));
445
26
        env->set_main_utf16(std::move(main_utf16));
446
        std::vector<Local<String>> params = {
447
13
            env->process_string(),
448
37
            env->require_string()};
449
        std::vector<Local<Value>> args = {
450
            env->process_object(),
451
50
            env->native_module_require()};
452
37
        return ExecuteBootstrapper(env, name.c_str(), &params, &args);
453
13
      });
454
}
455
456
5
Environment* GetCurrentEnvironment(Local<Context> context) {
457
5
  return Environment::GetCurrent(context);
458
}
459
460
MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform() {
461
  return per_process::v8_platform.Platform();
462
}
463
464
1
MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env) {
465
1
  return GetMultiIsolatePlatform(env->isolate_data());
466
}
467
468
1
MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) {
469
1
  return env->platform();
470
}
471
472
MultiIsolatePlatform* CreatePlatform(
473
    int thread_pool_size,
474
    node::tracing::TracingController* tracing_controller) {
475
  return CreatePlatform(
476
      thread_pool_size,
477
      static_cast<v8::TracingController*>(tracing_controller));
478
}
479
480
MultiIsolatePlatform* CreatePlatform(
481
    int thread_pool_size,
482
    v8::TracingController* tracing_controller) {
483
  return MultiIsolatePlatform::Create(thread_pool_size, tracing_controller)
484
      .release();
485
}
486
487
void FreePlatform(MultiIsolatePlatform* platform) {
488
  delete platform;
489
}
490
491
7
std::unique_ptr<MultiIsolatePlatform> MultiIsolatePlatform::Create(
492
    int thread_pool_size,
493
    v8::TracingController* tracing_controller) {
494
7
  return std::make_unique<NodePlatform>(thread_pool_size, tracing_controller);
495
}
496
497
34082
MaybeLocal<Object> GetPerContextExports(Local<Context> context) {
498
34082
  Isolate* isolate = context->GetIsolate();
499
34082
  EscapableHandleScope handle_scope(isolate);
500
501
34082
  Local<Object> global = context->Global();
502
  Local<Private> key = Private::ForApi(isolate,
503
34082
      FIXED_ONE_BYTE_STRING(isolate, "node:per_context_binding_exports"));
504
505
  Local<Value> existing_value;
506
68164
  if (!global->GetPrivate(context, key).ToLocal(&existing_value))
507
    return MaybeLocal<Object>();
508
34082
  if (existing_value->IsObject())
509
33688
    return handle_scope.Escape(existing_value.As<Object>());
510
511
394
  Local<Object> exports = Object::New(isolate);
512

1576
  if (context->Global()->SetPrivate(context, key, exports).IsNothing() ||
513
394
      !InitializePrimordials(context))
514
4
    return MaybeLocal<Object>();
515
390
  return handle_scope.Escape(exports);
516
}
517
518
// Any initialization logic should be performed in
519
// InitializeContext, because embedders don't necessarily
520
// call NewContext and so they will experience breakages.
521
388
Local<Context> NewContext(Isolate* isolate,
522
                          Local<ObjectTemplate> object_template) {
523
776
  auto context = Context::New(isolate, nullptr, object_template);
524
389
  if (context.IsEmpty()) return context;
525
526
389
  if (!InitializeContext(context)) {
527
4
    return Local<Context>();
528
  }
529
530
385
  return context;
531
}
532
533
8
void ProtoThrower(const FunctionCallbackInfo<Value>& info) {
534
8
  THROW_ERR_PROTO_ACCESS(info.GetIsolate());
535
8
}
536
537
// This runs at runtime, regardless of whether the context
538
// is created from a snapshot.
539
5901
void InitializeContextRuntime(Local<Context> context) {
540
5901
  Isolate* isolate = context->GetIsolate();
541
11802
  HandleScope handle_scope(isolate);
542
543
  // Delete `Intl.v8BreakIterator`
544
  // https://github.com/nodejs/node/issues/14909
545
5901
  Local<String> intl_string = FIXED_ONE_BYTE_STRING(isolate, "Intl");
546
  Local<String> break_iter_string =
547
5901
    FIXED_ONE_BYTE_STRING(isolate, "v8BreakIterator");
548
  Local<Value> intl_v;
549

23604
  if (context->Global()->Get(context, intl_string).ToLocal(&intl_v) &&
550
5901
      intl_v->IsObject()) {
551
5901
    Local<Object> intl = intl_v.As<Object>();
552
11802
    intl->Delete(context, break_iter_string).Check();
553
  }
554
555
  // Delete `Atomics.wake`
556
  // https://github.com/nodejs/node/issues/21219
557
5901
  Local<String> atomics_string = FIXED_ONE_BYTE_STRING(isolate, "Atomics");
558
5901
  Local<String> wake_string = FIXED_ONE_BYTE_STRING(isolate, "wake");
559
  Local<Value> atomics_v;
560

23604
  if (context->Global()->Get(context, atomics_string).ToLocal(&atomics_v) &&
561
5901
      atomics_v->IsObject()) {
562
5900
    Local<Object> atomics = atomics_v.As<Object>();
563
11800
    atomics->Delete(context, wake_string).Check();
564
  }
565
566
  // Remove __proto__
567
  // https://github.com/nodejs/node/issues/31951
568
5901
  Local<String> object_string = FIXED_ONE_BYTE_STRING(isolate, "Object");
569
5901
  Local<String> prototype_string = FIXED_ONE_BYTE_STRING(isolate, "prototype");
570
11802
  Local<Object> prototype = context->Global()
571
17703
                                ->Get(context, object_string)
572
11802
                                .ToLocalChecked()
573
11802
                                .As<Object>()
574
17703
                                ->Get(context, prototype_string)
575
11802
                                .ToLocalChecked()
576
5901
                                .As<Object>();
577
5901
  Local<String> proto_string = FIXED_ONE_BYTE_STRING(isolate, "__proto__");
578
5901
  if (per_process::cli_options->disable_proto == "delete") {
579
8
    prototype->Delete(context, proto_string).ToChecked();
580
5897
  } else if (per_process::cli_options->disable_proto == "throw") {
581
    Local<Value> thrower =
582
8
        Function::New(context, ProtoThrower).ToLocalChecked();
583
8
    PropertyDescriptor descriptor(thrower, thrower);
584
4
    descriptor.set_enumerable(false);
585
4
    descriptor.set_configurable(true);
586
8
    prototype->DefineProperty(context, proto_string, descriptor).ToChecked();
587
5893
  } else if (per_process::cli_options->disable_proto != "") {
588
    // Validated in ProcessGlobalArgs
589
    FatalError("InitializeContextRuntime()", "invalid --disable-proto mode");
590
  }
591
5901
}
592
593
389
bool InitializeContextForSnapshot(Local<Context> context) {
594
389
  Isolate* isolate = context->GetIsolate();
595
778
  HandleScope handle_scope(isolate);
596
597
778
  context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
598
389
                           True(isolate));
599
778
  return InitializePrimordials(context);
600
}
601
602
783
bool InitializePrimordials(Local<Context> context) {
603
  // Run per-context JS files.
604
783
  Isolate* isolate = context->GetIsolate();
605
  Context::Scope context_scope(context);
606
  Local<Object> exports;
607
608
  Local<String> primordials_string =
609
783
      FIXED_ONE_BYTE_STRING(isolate, "primordials");
610
783
  Local<String> global_string = FIXED_ONE_BYTE_STRING(isolate, "global");
611
783
  Local<String> exports_string = FIXED_ONE_BYTE_STRING(isolate, "exports");
612
613
  // Create primordials first and make it available to per-context scripts.
614
783
  Local<Object> primordials = Object::New(isolate);
615

3912
  if (!primordials->SetPrototype(context, Null(isolate)).FromJust() ||
616

3126
      !GetPerContextExports(context).ToLocal(&exports) ||
617
2340
      !exports->Set(context, primordials_string, primordials).FromJust()) {
618
4
    return false;
619
  }
620
621
  static const char* context_files[] = {"internal/per_context/primordials",
622
                                        "internal/per_context/domexception",
623
                                        "internal/per_context/messageport",
624
                                        nullptr};
625
626
3102
  for (const char** module = context_files; *module != nullptr; module++) {
627
    std::vector<Local<String>> parameters = {
628
4651
        global_string, exports_string, primordials_string};
629
11645
    Local<Value> arguments[] = {context->Global(), exports, primordials};
630
    MaybeLocal<Function> maybe_fn =
631
        native_module::NativeModuleEnv::LookupAndCompile(
632
2329
            context, *module, &parameters, nullptr);
633
    Local<Function> fn;
634
2329
    if (!maybe_fn.ToLocal(&fn)) {
635
      return false;
636
    }
637
    MaybeLocal<Value> result =
638
4658
        fn->Call(context, Undefined(isolate), arraysize(arguments), arguments);
639
    // Execution failed during context creation.
640
    // TODO(joyeecheung): deprecate this signature and return a MaybeLocal.
641
2327
    if (result.IsEmpty()) {
642
4
      return false;
643
    }
644
  }
645
646
775
  return true;
647
}
648
649
389
bool InitializeContext(Local<Context> context) {
650
389
  if (!InitializeContextForSnapshot(context)) {
651
4
    return false;
652
  }
653
654
385
  InitializeContextRuntime(context);
655
385
  return true;
656
}
657
658
8
uv_loop_t* GetCurrentEventLoop(Isolate* isolate) {
659
16
  HandleScope handle_scope(isolate);
660
8
  Local<Context> context = isolate->GetCurrentContext();
661
8
  if (context.IsEmpty()) return nullptr;
662
8
  Environment* env = Environment::GetCurrent(context);
663
8
  if (env == nullptr) return nullptr;
664
8
  return env->event_loop();
665
}
666
667
1
void AddLinkedBinding(Environment* env, const node_module& mod) {
668
1
  CHECK_NOT_NULL(env);
669
2
  Mutex::ScopedLock lock(env->extra_linked_bindings_mutex());
670
671
1
  node_module* prev_head = env->extra_linked_bindings_head();
672
1
  env->extra_linked_bindings()->push_back(mod);
673
1
  if (prev_head != nullptr)
674
    prev_head->nm_link = &env->extra_linked_bindings()->back();
675
1
}
676
677
1
void AddLinkedBinding(Environment* env,
678
                      const char* name,
679
                      addon_context_register_func fn,
680
                      void* priv) {
681
  node_module mod = {
682
    NODE_MODULE_VERSION,
683
    NM_F_LINKED,
684
    nullptr,  // nm_dso_handle
685
    nullptr,  // nm_filename
686
    nullptr,  // nm_register_func
687
    fn,
688
    name,
689
    priv,
690
    nullptr   // nm_link
691
1
  };
692
1
  AddLinkedBinding(env, mod);
693
1
}
694
695
static std::atomic<uint64_t> next_thread_id{0};
696
697
5524
ThreadId AllocateEnvironmentThreadId() {
698
5524
  return ThreadId { next_thread_id++ };
699
}
700
701
493
void DefaultProcessExitHandler(Environment* env, int exit_code) {
702
493
  env->set_can_call_into_js(false);
703
493
  env->stop_sub_worker_contexts();
704
493
  DisposePlatform();
705
493
  exit(exit_code);
706
}
707
708
709
343
void SetProcessExitHandler(Environment* env,
710
                           std::function<void(Environment*, int)>&& handler) {
711
343
  env->set_process_exit_handler(std::move(handler));
712
343
}
713
714

14970
}  // namespace node