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: 330 370 89.2 %
Date: 2020-08-07 22:13:19 Branches: 104 174 59.8 %

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
31
static bool ShouldAbortOnUncaughtException(Isolate* isolate) {
42
31
  DebugSealHandleScope scope(isolate);
43
31
  Environment* env = Environment::GetCurrent(isolate);
44
31
  return env != nullptr &&
45

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

94
         env->should_abort_on_uncaught_toggle()[0] &&
47
63
         !env->inside_should_not_abort_on_uncaught_scope();
48
}
49
50
73902
static MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context,
51
                                      Local<Value> exception,
52
                                      Local<Array> trace) {
53
73902
  Environment* env = Environment::GetCurrent(context);
54
73902
  if (env == nullptr) {
55
    return exception->ToString(context).FromMaybe(Local<Value>());
56
  }
57
73902
  Local<Function> prepare = env->prepare_stack_trace_callback();
58
73902
  if (prepare.IsEmpty()) {
59
    return exception->ToString(context).FromMaybe(Local<Value>());
60
  }
61
  Local<Value> args[] = {
62
      context->Global(),
63
      exception,
64
      trace,
65
295608
  };
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
147804
  TryCatchScope try_catch(env);
71
  MaybeLocal<Value> result = prepare->Call(
72
147804
      context, Undefined(env->isolate()), arraysize(args), args);
73

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

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

316188
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
101
316188
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
102
316188
  return ret;
103
}
104
105
482632
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
106
482632
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
107
482632
  free(data);
108
482632
}
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
4787
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
188

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

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

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

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

3962
  if (!primordials->SetPrototype(context, Null(isolate)).FromJust() ||
618

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

13323
}  // namespace node