GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/environment.cc Lines: 343 395 86.8 %
Date: 2022-10-14 05:16:24 Branches: 111 194 57.2 %

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

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

68
         (env->is_main_thread() || !env->is_stopping()) &&
55
63
         env->abort_on_uncaught_exception() &&
56

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

68035
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
84
2
    try_catch.ReThrow();
85
  }
86
68035
  return result;
87
}
88
89
376540
void* NodeArrayBufferAllocator::Allocate(size_t size) {
90
  void* ret;
91

376540
  if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers)
92
62959
    ret = allocator_->Allocate(size);
93
  else
94
313581
    ret = allocator_->AllocateUninitialized(size);
95
376540
  if (LIKELY(ret != nullptr))
96
376540
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
97
376540
  return ret;
98
}
99
100
172056
void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) {
101
172056
  void* ret = allocator_->AllocateUninitialized(size);
102
172056
  if (LIKELY(ret != nullptr))
103
172056
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
104
172056
  return ret;
105
}
106
107
61762
void* NodeArrayBufferAllocator::Reallocate(
108
    void* data, size_t old_size, size_t size) {
109
61762
  void* ret = allocator_->Reallocate(data, old_size, size);
110

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

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

438
  if (context->Global()->SetPrivate(context, key, exports).IsNothing() ||
531
219
      InitializePrimordials(context).IsNothing())
532
    return MaybeLocal<Object>();
533
73
  return handle_scope.Escape(exports);
534
}
535
536
// Any initialization logic should be performed in
537
// InitializeContext, because embedders don't necessarily
538
// call NewContext and so they will experience breakages.
539
67
Local<Context> NewContext(Isolate* isolate,
540
                          Local<ObjectTemplate> object_template) {
541
134
  auto context = Context::New(isolate, nullptr, object_template);
542
67
  if (context.IsEmpty()) return context;
543
544
134
  if (InitializeContext(context).IsNothing()) {
545
    return Local<Context>();
546
  }
547
548
67
  return context;
549
}
550
551
8
void ProtoThrower(const FunctionCallbackInfo<Value>& info) {
552
8
  THROW_ERR_PROTO_ACCESS(info.GetIsolate());
553
8
}
554
555
// This runs at runtime, regardless of whether the context
556
// is created from a snapshot.
557
6960
Maybe<bool> InitializeContextRuntime(Local<Context> context) {
558
6960
  Isolate* isolate = context->GetIsolate();
559
13920
  HandleScope handle_scope(isolate);
560
561
  // When `IsCodeGenerationFromStringsAllowed` is true, V8 takes the fast path
562
  // and ignores the ModifyCodeGenerationFromStrings callback. Set it to false
563
  // to delegate the code generation validation to
564
  // node::ModifyCodeGenerationFromStrings.
565
  // The `IsCodeGenerationFromStringsAllowed` can be refreshed by V8 according
566
  // to the runtime flags, propagate the value to the embedder data.
567
  bool is_code_generation_from_strings_allowed =
568
6960
      context->IsCodeGenerationFromStringsAllowed();
569
6960
  context->AllowCodeGenerationFromStrings(false);
570
13920
  context->SetEmbedderData(
571
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings,
572
      is_code_generation_from_strings_allowed ? True(isolate) : False(isolate));
573
574
6960
  if (per_process::cli_options->disable_proto == "") {
575
6952
    return Just(true);
576
  }
577
578
  // Remove __proto__
579
  // https://github.com/nodejs/node/issues/31951
580
  Local<Object> prototype;
581
  {
582
    Local<String> object_string =
583
8
      FIXED_ONE_BYTE_STRING(isolate, "Object");
584
    Local<String> prototype_string =
585
8
      FIXED_ONE_BYTE_STRING(isolate, "prototype");
586
587
    Local<Value> object_v;
588
24
    if (!context->Global()
589
24
        ->Get(context, object_string)
590
8
        .ToLocal(&object_v)) {
591
      return Nothing<bool>();
592
    }
593
594
    Local<Value> prototype_v;
595
24
    if (!object_v.As<Object>()
596
24
        ->Get(context, prototype_string)
597
8
        .ToLocal(&prototype_v)) {
598
      return Nothing<bool>();
599
    }
600
601
8
    prototype = prototype_v.As<Object>();
602
  }
603
604
  Local<String> proto_string =
605
8
    FIXED_ONE_BYTE_STRING(isolate, "__proto__");
606
607
8
  if (per_process::cli_options->disable_proto == "delete") {
608
4
    if (prototype
609
12
        ->Delete(context, proto_string)
610
4
        .IsNothing()) {
611
      return Nothing<bool>();
612
    }
613
4
  } else if (per_process::cli_options->disable_proto == "throw") {
614
    Local<Value> thrower;
615
8
    if (!Function::New(context, ProtoThrower)
616
4
        .ToLocal(&thrower)) {
617
      return Nothing<bool>();
618
    }
619
620
8
    PropertyDescriptor descriptor(thrower, thrower);
621
4
    descriptor.set_enumerable(false);
622
4
    descriptor.set_configurable(true);
623
4
    if (prototype
624
12
        ->DefineProperty(context, proto_string, descriptor)
625
4
        .IsNothing()) {
626
      return Nothing<bool>();
627
    }
628
  } else if (per_process::cli_options->disable_proto != "") {
629
    // Validated in ProcessGlobalArgs
630
    FatalError("InitializeContextRuntime()",
631
               "invalid --disable-proto mode");
632
  }
633
634
8
  return Just(true);
635
}
636
637
77
Maybe<bool> InitializeBaseContextForSnapshot(Local<Context> context) {
638
77
  Isolate* isolate = context->GetIsolate();
639
154
  HandleScope handle_scope(isolate);
640
641
  // Delete `Intl.v8BreakIterator`
642
  // https://github.com/nodejs/node/issues/14909
643
  {
644
77
    Context::Scope context_scope(context);
645
77
    Local<String> intl_string = FIXED_ONE_BYTE_STRING(isolate, "Intl");
646
    Local<String> break_iter_string =
647
77
        FIXED_ONE_BYTE_STRING(isolate, "v8BreakIterator");
648
649
    Local<Value> intl_v;
650
308
    if (!context->Global()->Get(context, intl_string).ToLocal(&intl_v)) {
651
      return Nothing<bool>();
652
    }
653
654

231
    if (intl_v->IsObject() &&
655
385
        intl_v.As<Object>()->Delete(context, break_iter_string).IsNothing()) {
656
      return Nothing<bool>();
657
    }
658
  }
659
77
  return Just(true);
660
}
661
662
68
Maybe<bool> InitializeMainContextForSnapshot(Local<Context> context) {
663
68
  Isolate* isolate = context->GetIsolate();
664
136
  HandleScope handle_scope(isolate);
665
666
  // Initialize the default values.
667
136
  context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
668
                           True(isolate));
669
136
  context->SetEmbedderData(
670
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings, True(isolate));
671
672
136
  if (InitializeBaseContextForSnapshot(context).IsNothing()) {
673
    return Nothing<bool>();
674
  }
675
68
  return InitializePrimordials(context);
676
}
677
678
141
Maybe<bool> InitializePrimordials(Local<Context> context) {
679
  // Run per-context JS files.
680
141
  Isolate* isolate = context->GetIsolate();
681
  Context::Scope context_scope(context);
682
  Local<Object> exports;
683
684
  Local<String> primordials_string =
685
141
      FIXED_ONE_BYTE_STRING(isolate, "primordials");
686
687
  // Create primordials first and make it available to per-context scripts.
688
141
  Local<Object> primordials = Object::New(isolate);
689

705
  if (primordials->SetPrototype(context, Null(isolate)).IsNothing() ||
690

564
      !GetPerContextExports(context).ToLocal(&exports) ||
691
564
      exports->Set(context, primordials_string, primordials).IsNothing()) {
692
    return Nothing<bool>();
693
  }
694
695
  static const char* context_files[] = {"internal/per_context/primordials",
696
                                        "internal/per_context/domexception",
697
                                        "internal/per_context/messageport",
698
                                        nullptr};
699
700
564
  for (const char** module = context_files; *module != nullptr; module++) {
701
1269
    Local<Value> arguments[] = {exports, primordials};
702
846
    if (builtins::BuiltinLoader::CompileAndCall(
703
423
            context, *module, arraysize(arguments), arguments, nullptr)
704
423
            .IsEmpty()) {
705
      // Execution failed during context creation.
706
      return Nothing<bool>();
707
    }
708
  }
709
710
141
  return Just(true);
711
}
712
713
// This initializes the main context (i.e. vm contexts are not included).
714
68
Maybe<bool> InitializeContext(Local<Context> context) {
715
136
  if (InitializeMainContextForSnapshot(context).IsNothing()) {
716
    return Nothing<bool>();
717
  }
718
719
68
  return InitializeContextRuntime(context);
720
}
721
722
10
uv_loop_t* GetCurrentEventLoop(Isolate* isolate) {
723
20
  HandleScope handle_scope(isolate);
724
10
  Local<Context> context = isolate->GetCurrentContext();
725
10
  if (context.IsEmpty()) return nullptr;
726
10
  Environment* env = Environment::GetCurrent(context);
727
10
  if (env == nullptr) return nullptr;
728
10
  return env->event_loop();
729
}
730
731
9
void AddLinkedBinding(Environment* env, const node_module& mod) {
732
9
  CHECK_NOT_NULL(env);
733
18
  Mutex::ScopedLock lock(env->extra_linked_bindings_mutex());
734
735
9
  node_module* prev_tail = env->extra_linked_bindings_tail();
736
9
  env->extra_linked_bindings()->push_back(mod);
737
9
  if (prev_tail != nullptr)
738
5
    prev_tail->nm_link = &env->extra_linked_bindings()->back();
739
9
}
740
741
3
void AddLinkedBinding(Environment* env, const napi_module& mod) {
742
3
  AddLinkedBinding(env, napi_module_to_node_module(&mod));
743
3
}
744
745
6
void AddLinkedBinding(Environment* env,
746
                      const char* name,
747
                      addon_context_register_func fn,
748
                      void* priv) {
749
6
  node_module mod = {
750
    NODE_MODULE_VERSION,
751
    NM_F_LINKED,
752
    nullptr,  // nm_dso_handle
753
    nullptr,  // nm_filename
754
    nullptr,  // nm_register_func
755
    fn,
756
    name,
757
    priv,
758
    nullptr   // nm_link
759
6
  };
760
6
  AddLinkedBinding(env, mod);
761
6
}
762
763
static std::atomic<uint64_t> next_thread_id{0};
764
765
6570
ThreadId AllocateEnvironmentThreadId() {
766
6570
  return ThreadId { next_thread_id++ };
767
}
768
769
670
[[noreturn]] void Exit(ExitCode exit_code) {
770
670
  exit(static_cast<int>(exit_code));
771
}
772
773
666
void DefaultProcessExitHandlerInternal(Environment* env, ExitCode exit_code) {
774
666
  env->set_can_call_into_js(false);
775
666
  env->stop_sub_worker_contexts();
776
666
  env->isolate()->DumpAndResetStats();
777
666
  DisposePlatform();
778
666
  uv_library_shutdown();
779
666
  Exit(exit_code);
780
}
781
782
void DefaultProcessExitHandler(Environment* env, int exit_code) {
783
  DefaultProcessExitHandlerInternal(env, static_cast<ExitCode>(exit_code));
784
}
785
786
void SetProcessExitHandler(
787
    Environment* env, std::function<void(Environment*, ExitCode)>&& handler) {
788
  env->set_process_exit_handler(std::move(handler));
789
}
790
791
727
void SetProcessExitHandler(Environment* env,
792
                           std::function<void(Environment*, int)>&& handler) {
793
1454
  auto movedHandler = std::move(handler);
794
2971
  env->set_process_exit_handler([=](Environment* env, ExitCode exit_code) {
795
63
    movedHandler(env, static_cast<int>(exit_code));
796
63
  });
797
727
}
798
799

16866
}  // namespace node