GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/environment.cc Lines: 348 393 88.5 %
Date: 2022-05-03 04:14:50 Branches: 118 192 61.5 %

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_options-inl.h"
7
#include "node_platform.h"
8
#include "node_shadow_realm.h"
9
#include "node_v8_platform-inl.h"
10
#include "node_wasm_web_api.h"
11
#include "uv.h"
12
13
#if HAVE_INSPECTOR
14
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
15
#endif
16
17
namespace node {
18
using errors::TryCatchScope;
19
using v8::Array;
20
using v8::Context;
21
using v8::EscapableHandleScope;
22
using v8::Function;
23
using v8::FunctionCallbackInfo;
24
using v8::HandleScope;
25
using v8::Isolate;
26
using v8::Just;
27
using v8::Local;
28
using v8::Maybe;
29
using v8::MaybeLocal;
30
using v8::Nothing;
31
using v8::Null;
32
using v8::Object;
33
using v8::ObjectTemplate;
34
using v8::Private;
35
using v8::PropertyDescriptor;
36
using v8::SealHandleScope;
37
using v8::String;
38
using v8::Value;
39
40
357
bool AllowWasmCodeGenerationCallback(Local<Context> context,
41
                                     Local<String>) {
42
  Local<Value> wasm_code_gen =
43
714
      context->GetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration);
44

1071
  return wasm_code_gen->IsUndefined() || wasm_code_gen->IsTrue();
45
}
46
47
33
bool ShouldAbortOnUncaughtException(Isolate* isolate) {
48
33
  DebugSealHandleScope scope(isolate);
49
33
  Environment* env = Environment::GetCurrent(isolate);
50
33
  return env != nullptr &&
51

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

65594
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
81
2
    try_catch.ReThrow();
82
  }
83
65594
  return result;
84
}
85
86
331742
void* NodeArrayBufferAllocator::Allocate(size_t size) {
87
  void* ret;
88

331742
  if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers)
89
54437
    ret = UncheckedCalloc(size);
90
  else
91
277305
    ret = UncheckedMalloc(size);
92
331742
  if (LIKELY(ret != nullptr))
93
331742
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
94
331742
  return ret;
95
}
96
97
149185
void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) {
98
149185
  void* ret = node::UncheckedMalloc(size);
99
149185
  if (LIKELY(ret != nullptr))
100
149185
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
101
149185
  return ret;
102
}
103
104
60583
void* NodeArrayBufferAllocator::Reallocate(
105
    void* data, size_t old_size, size_t size) {
106
60583
  void* ret = UncheckedRealloc<char>(static_cast<char*>(data), size);
107

60583
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
108
60583
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
109
60583
  return ret;
110
}
111
112
459204
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
113
459204
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
114
459204
  free(data);
115
459204
}
116
117
12
DebuggingArrayBufferAllocator::~DebuggingArrayBufferAllocator() {
118
6
  CHECK(allocations_.empty());
119
12
}
120
121
78
void* DebuggingArrayBufferAllocator::Allocate(size_t size) {
122
78
  Mutex::ScopedLock lock(mutex_);
123
78
  void* data = NodeArrayBufferAllocator::Allocate(size);
124
78
  RegisterPointerInternal(data, size);
125
78
  return data;
126
}
127
128
41
void* DebuggingArrayBufferAllocator::AllocateUninitialized(size_t size) {
129
41
  Mutex::ScopedLock lock(mutex_);
130
41
  void* data = NodeArrayBufferAllocator::AllocateUninitialized(size);
131
41
  RegisterPointerInternal(data, size);
132
41
  return data;
133
}
134
135
119
void DebuggingArrayBufferAllocator::Free(void* data, size_t size) {
136
238
  Mutex::ScopedLock lock(mutex_);
137
119
  UnregisterPointerInternal(data, size);
138
119
  NodeArrayBufferAllocator::Free(data, size);
139
119
}
140
141
void* DebuggingArrayBufferAllocator::Reallocate(void* data,
142
                                                size_t old_size,
143
                                                size_t size) {
144
  Mutex::ScopedLock lock(mutex_);
145
  void* ret = NodeArrayBufferAllocator::Reallocate(data, old_size, size);
146
  if (ret == nullptr) {
147
    if (size == 0) {  // i.e. equivalent to free().
148
      // suppress coverity warning as data is used as key versus as pointer
149
      // in UnregisterPointerInternal
150
      // coverity[pass_freed_arg]
151
      UnregisterPointerInternal(data, old_size);
152
    }
153
    return nullptr;
154
  }
155
156
  if (data != nullptr) {
157
    auto it = allocations_.find(data);
158
    CHECK_NE(it, allocations_.end());
159
    allocations_.erase(it);
160
  }
161
162
  RegisterPointerInternal(ret, size);
163
  return ret;
164
}
165
166
void DebuggingArrayBufferAllocator::RegisterPointer(void* data, size_t size) {
167
  Mutex::ScopedLock lock(mutex_);
168
  NodeArrayBufferAllocator::RegisterPointer(data, size);
169
  RegisterPointerInternal(data, size);
170
}
171
172
void DebuggingArrayBufferAllocator::UnregisterPointer(void* data, size_t size) {
173
  Mutex::ScopedLock lock(mutex_);
174
  NodeArrayBufferAllocator::UnregisterPointer(data, size);
175
  UnregisterPointerInternal(data, size);
176
}
177
178
119
void DebuggingArrayBufferAllocator::UnregisterPointerInternal(void* data,
179
                                                              size_t size) {
180
119
  if (data == nullptr) return;
181
119
  auto it = allocations_.find(data);
182
119
  CHECK_NE(it, allocations_.end());
183
119
  if (size > 0) {
184
    // We allow allocations with size 1 for 0-length buffers to avoid having
185
    // to deal with nullptr values.
186
119
    CHECK_EQ(it->second, size);
187
  }
188
119
  allocations_.erase(it);
189
}
190
191
119
void DebuggingArrayBufferAllocator::RegisterPointerInternal(void* data,
192
                                                            size_t size) {
193
119
  if (data == nullptr) return;
194
119
  CHECK_EQ(allocations_.count(data), 0);
195
119
  allocations_[data] = size;
196
}
197
198
5596
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
199

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

1911
      InitializePrimordials(context).IsNothing())
530
4
    return MaybeLocal<Object>();
531
633
  return handle_scope.Escape(exports);
532
}
533
534
// Any initialization logic should be performed in
535
// InitializeContext, because embedders don't necessarily
536
// call NewContext and so they will experience breakages.
537
631
Local<Context> NewContext(Isolate* isolate,
538
                          Local<ObjectTemplate> object_template) {
539
1262
  auto context = Context::New(isolate, nullptr, object_template);
540
631
  if (context.IsEmpty()) return context;
541
542
1262
  if (InitializeContext(context).IsNothing()) {
543
4
    return Local<Context>();
544
  }
545
546
627
  return context;
547
}
548
549
8
void ProtoThrower(const FunctionCallbackInfo<Value>& info) {
550
8
  THROW_ERR_PROTO_ACCESS(info.GetIsolate());
551
8
}
552
553
// This runs at runtime, regardless of whether the context
554
// is created from a snapshot.
555
6160
Maybe<bool> InitializeContextRuntime(Local<Context> context) {
556
6160
  Isolate* isolate = context->GetIsolate();
557
12320
  HandleScope handle_scope(isolate);
558
559
  // Delete `Intl.v8BreakIterator`
560
  // https://github.com/nodejs/node/issues/14909
561
  {
562
    Local<String> intl_string =
563
6160
      FIXED_ONE_BYTE_STRING(isolate, "Intl");
564
    Local<String> break_iter_string =
565
6160
      FIXED_ONE_BYTE_STRING(isolate, "v8BreakIterator");
566
567
    Local<Value> intl_v;
568
6160
    if (!context->Global()
569
6160
        ->Get(context, intl_string)
570
6160
        .ToLocal(&intl_v)) {
571
      return Nothing<bool>();
572
    }
573
574
12320
    if (intl_v->IsObject() &&
575
6160
        intl_v.As<Object>()
576
12320
          ->Delete(context, break_iter_string)
577
6160
          .IsNothing()) {
578
      return Nothing<bool>();
579
    }
580
  }
581
582
  // Delete `Atomics.wake`
583
  // https://github.com/nodejs/node/issues/21219
584
  {
585
    Local<String> atomics_string =
586
6160
      FIXED_ONE_BYTE_STRING(isolate, "Atomics");
587
    Local<String> wake_string =
588
6160
      FIXED_ONE_BYTE_STRING(isolate, "wake");
589
590
    Local<Value> atomics_v;
591
6160
    if (!context->Global()
592
6160
        ->Get(context, atomics_string)
593
6160
        .ToLocal(&atomics_v)) {
594
      return Nothing<bool>();
595
    }
596
597
12314
    if (atomics_v->IsObject() &&
598
6154
        atomics_v.As<Object>()
599
12314
          ->Delete(context, wake_string)
600
6154
          .IsNothing()) {
601
      return Nothing<bool>();
602
    }
603
  }
604
605
  // Remove __proto__
606
  // https://github.com/nodejs/node/issues/31951
607
  Local<Object> prototype;
608
  {
609
    Local<String> object_string =
610
6160
      FIXED_ONE_BYTE_STRING(isolate, "Object");
611
    Local<String> prototype_string =
612
6160
      FIXED_ONE_BYTE_STRING(isolate, "prototype");
613
614
    Local<Value> object_v;
615
6160
    if (!context->Global()
616
6160
        ->Get(context, object_string)
617
6160
        .ToLocal(&object_v)) {
618
      return Nothing<bool>();
619
    }
620
621
    Local<Value> prototype_v;
622
6160
    if (!object_v.As<Object>()
623
6160
        ->Get(context, prototype_string)
624
6160
        .ToLocal(&prototype_v)) {
625
      return Nothing<bool>();
626
    }
627
628
6160
    prototype = prototype_v.As<Object>();
629
  }
630
631
  Local<String> proto_string =
632
6160
    FIXED_ONE_BYTE_STRING(isolate, "__proto__");
633
634
6160
  if (per_process::cli_options->disable_proto == "delete") {
635
4
    if (prototype
636
4
        ->Delete(context, proto_string)
637
4
        .IsNothing()) {
638
      return Nothing<bool>();
639
    }
640
6156
  } else if (per_process::cli_options->disable_proto == "throw") {
641
    Local<Value> thrower;
642
4
    if (!Function::New(context, ProtoThrower)
643
4
        .ToLocal(&thrower)) {
644
      return Nothing<bool>();
645
    }
646
647
4
    PropertyDescriptor descriptor(thrower, thrower);
648
4
    descriptor.set_enumerable(false);
649
4
    descriptor.set_configurable(true);
650
4
    if (prototype
651
4
        ->DefineProperty(context, proto_string, descriptor)
652
4
        .IsNothing()) {
653
      return Nothing<bool>();
654
    }
655
6152
  } else if (per_process::cli_options->disable_proto != "") {
656
    // Validated in ProcessGlobalArgs
657
    FatalError("InitializeContextRuntime()",
658
               "invalid --disable-proto mode");
659
  }
660
661
6160
  return Just(true);
662
}
663
664
632
Maybe<bool> InitializeContextForSnapshot(Local<Context> context) {
665
632
  Isolate* isolate = context->GetIsolate();
666
1264
  HandleScope handle_scope(isolate);
667
668
1264
  context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
669
                           True(isolate));
670
671
632
  return InitializePrimordials(context);
672
}
673
674
1269
Maybe<bool> InitializePrimordials(Local<Context> context) {
675
  // Run per-context JS files.
676
1269
  Isolate* isolate = context->GetIsolate();
677
1269
  Context::Scope context_scope(context);
678
  Local<Object> exports;
679
680
  Local<String> primordials_string =
681
1269
      FIXED_ONE_BYTE_STRING(isolate, "primordials");
682
1269
  Local<String> global_string = FIXED_ONE_BYTE_STRING(isolate, "global");
683
1269
  Local<String> exports_string = FIXED_ONE_BYTE_STRING(isolate, "exports");
684
685
  // Create primordials first and make it available to per-context scripts.
686
1269
  Local<Object> primordials = Object::New(isolate);
687
2538
  if (primordials->SetPrototype(context, Null(isolate)).IsNothing() ||
688

3803
      !GetPerContextExports(context).ToLocal(&exports) ||
689

3799
      exports->Set(context, primordials_string, primordials).IsNothing()) {
690
4
    return Nothing<bool>();
691
  }
692
693
  static const char* context_files[] = {"internal/per_context/primordials",
694
                                        "internal/per_context/domexception",
695
                                        "internal/per_context/messageport",
696
                                        nullptr};
697
698
5048
  for (const char** module = context_files; *module != nullptr; module++) {
699
    std::vector<Local<String>> parameters = {
700
3787
        global_string, exports_string, primordials_string};
701
7574
    Local<Value> arguments[] = {context->Global(), exports, primordials};
702
    MaybeLocal<Function> maybe_fn =
703
        native_module::NativeModuleEnv::LookupAndCompile(
704
3787
            context, *module, &parameters, nullptr);
705
    Local<Function> fn;
706
3787
    if (!maybe_fn.ToLocal(&fn)) {
707
      return Nothing<bool>();
708
    }
709
    MaybeLocal<Value> result =
710
7574
        fn->Call(context, Undefined(isolate), arraysize(arguments), arguments);
711
    // Execution failed during context creation.
712
3787
    if (result.IsEmpty()) {
713
4
      return Nothing<bool>();
714
    }
715
  }
716
717
1261
  return Just(true);
718
}
719
720
632
Maybe<bool> InitializeContext(Local<Context> context) {
721
1264
  if (InitializeContextForSnapshot(context).IsNothing()) {
722
4
    return Nothing<bool>();
723
  }
724
725
628
  return InitializeContextRuntime(context);
726
}
727
728
9
uv_loop_t* GetCurrentEventLoop(Isolate* isolate) {
729
18
  HandleScope handle_scope(isolate);
730
9
  Local<Context> context = isolate->GetCurrentContext();
731
9
  if (context.IsEmpty()) return nullptr;
732
9
  Environment* env = Environment::GetCurrent(context);
733
9
  if (env == nullptr) return nullptr;
734
9
  return env->event_loop();
735
}
736
737
9
void AddLinkedBinding(Environment* env, const node_module& mod) {
738
9
  CHECK_NOT_NULL(env);
739
18
  Mutex::ScopedLock lock(env->extra_linked_bindings_mutex());
740
741
9
  node_module* prev_tail = env->extra_linked_bindings_tail();
742
9
  env->extra_linked_bindings()->push_back(mod);
743
9
  if (prev_tail != nullptr)
744
5
    prev_tail->nm_link = &env->extra_linked_bindings()->back();
745
9
}
746
747
3
void AddLinkedBinding(Environment* env, const napi_module& mod) {
748
3
  AddLinkedBinding(env, napi_module_to_node_module(&mod));
749
3
}
750
751
6
void AddLinkedBinding(Environment* env,
752
                      const char* name,
753
                      addon_context_register_func fn,
754
                      void* priv) {
755
6
  node_module mod = {
756
    NODE_MODULE_VERSION,
757
    NM_F_LINKED,
758
    nullptr,  // nm_dso_handle
759
    nullptr,  // nm_filename
760
    nullptr,  // nm_register_func
761
    fn,
762
    name,
763
    priv,
764
    nullptr   // nm_link
765
6
  };
766
6
  AddLinkedBinding(env, mod);
767
6
}
768
769
static std::atomic<uint64_t> next_thread_id{0};
770
771
5816
ThreadId AllocateEnvironmentThreadId() {
772
5816
  return ThreadId { next_thread_id++ };
773
}
774
775
602
void DefaultProcessExitHandler(Environment* env, int exit_code) {
776
602
  env->set_can_call_into_js(false);
777
602
  env->stop_sub_worker_contexts();
778
602
  DisposePlatform();
779
602
  uv_library_shutdown();
780
602
  exit(exit_code);
781
}
782
783
784
574
void SetProcessExitHandler(Environment* env,
785
                           std::function<void(Environment*, int)>&& handler) {
786
574
  env->set_process_exit_handler(std::move(handler));
787
574
}
788
789
}  // namespace node