GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/environment.cc Lines: 343 396 86.6 %
Date: 2022-10-07 04:22:37 Branches: 108 188 57.4 %

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
382
bool AllowWasmCodeGenerationCallback(Local<Context> context,
44
                                     Local<String>) {
45
  Local<Value> wasm_code_gen =
46
764
      context->GetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration);
47

1146
  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
96
         env->should_abort_on_uncaught_toggle()[0] &&
57
34
         !env->inside_should_not_abort_on_uncaught_scope();
58
}
59
60
67741
MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context,
61
                                            Local<Value> exception,
62
                                            Local<Array> trace) {
63
67741
  Environment* env = Environment::GetCurrent(context);
64
67741
  if (env == nullptr) {
65
    return exception->ToString(context).FromMaybe(Local<Value>());
66
  }
67
67741
  Local<Function> prepare = env->prepare_stack_trace_callback();
68
67741
  if (prepare.IsEmpty()) {
69
    return exception->ToString(context).FromMaybe(Local<Value>());
70
  }
71
  Local<Value> args[] = {
72
      context->Global(),
73
      exception,
74
      trace,
75
135482
  };
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
67741
  TryCatchScope try_catch(env);
81
  MaybeLocal<Value> result = prepare->Call(
82
135482
      context, Undefined(env->isolate()), arraysize(args), args);
83

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

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

62609
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
111
62609
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
112
62609
  return ret;
113
}
114
115
525476
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
116
525476
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
117
525476
  allocator_->Free(data, size);
118
525476
}
119
120
12
DebuggingArrayBufferAllocator::~DebuggingArrayBufferAllocator() {
121
6
  CHECK(allocations_.empty());
122
12
}
123
124
80
void* DebuggingArrayBufferAllocator::Allocate(size_t size) {
125
80
  Mutex::ScopedLock lock(mutex_);
126
80
  void* data = NodeArrayBufferAllocator::Allocate(size);
127
80
  RegisterPointerInternal(data, size);
128
80
  return data;
129
}
130
131
42
void* DebuggingArrayBufferAllocator::AllocateUninitialized(size_t size) {
132
42
  Mutex::ScopedLock lock(mutex_);
133
42
  void* data = NodeArrayBufferAllocator::AllocateUninitialized(size);
134
42
  RegisterPointerInternal(data, size);
135
42
  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
6327
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
202

6327
  if (debug || per_process::cli_options->debug_arraybuffer_allocations)
203
3
    return std::make_unique<DebuggingArrayBufferAllocator>();
204
  else
205
6324
    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
6325
void SetIsolateCreateParamsForNode(Isolate::CreateParams* params) {
217
6325
  const uint64_t constrained_memory = uv_get_constrained_memory();
218
12642
  const uint64_t total_memory = constrained_memory > 0 ?
219
6317
      std::min(uv_get_total_memory(), constrained_memory) :
220
8
      uv_get_total_memory();
221
6325
  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
6325
    params->constraints.ConfigureDefaults(total_memory, 0);
226
  }
227
6325
  params->embedder_wrapper_object_index = BaseObject::InternalFields::kSlot;
228
6325
  params->embedder_wrapper_type_index = std::numeric_limits<int>::max();
229
6325
}
230
231
6325
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
232
6325
  if (s.flags & MESSAGE_LISTENER_WITH_ERROR_LEVEL)
233
6325
    isolate->AddMessageListenerWithErrorLevel(
234
            errors::PerIsolateMessageListener,
235
            Isolate::MessageErrorLevel::kMessageError |
236
                Isolate::MessageErrorLevel::kMessageWarning);
237
238
6325
  auto* abort_callback = s.should_abort_on_uncaught_exception_callback ?
239
      s.should_abort_on_uncaught_exception_callback :
240
      ShouldAbortOnUncaughtException;
241
6325
  isolate->SetAbortOnUncaughtExceptionCallback(abort_callback);
242
243
6325
  auto* fatal_error_cb = s.fatal_error_callback ?
244
      s.fatal_error_callback : OnFatalError;
245
6325
  isolate->SetFatalErrorHandler(fatal_error_cb);
246
6325
  isolate->SetOOMErrorHandler(OOMErrorHandler);
247
248
6325
  if ((s.flags & SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK) == 0) {
249
6325
    auto* prepare_stack_trace_cb = s.prepare_stack_trace_callback ?
250
        s.prepare_stack_trace_callback : PrepareStackTraceCallback;
251
6325
    isolate->SetPrepareStackTraceCallback(prepare_stack_trace_cb);
252
  }
253
6325
}
254
255
6332
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
256
6332
  isolate->SetMicrotasksPolicy(s.policy);
257
258
6332
  auto* allow_wasm_codegen_cb = s.allow_wasm_code_generation_callback ?
259
    s.allow_wasm_code_generation_callback : AllowWasmCodeGenerationCallback;
260
6332
  isolate->SetAllowWasmCodeGenerationCallback(allow_wasm_codegen_cb);
261
6332
  isolate->SetModifyCodeGenerationFromStringsCallback(
262
      ModifyCodeGenerationFromStrings);
263
264
12664
  Mutex::ScopedLock lock(node::per_process::cli_options_mutex);
265
6332
  if (per_process::cli_options->get_per_isolate_options()
266
6332
          ->get_per_env_options()
267
6332
          ->experimental_fetch) {
268
6331
    isolate->SetWasmStreamingCallback(wasm_web_api::StartStreamingCompilation);
269
  }
270
271
6332
  if (per_process::cli_options->get_per_isolate_options()
272
6332
          ->experimental_shadow_realm) {
273
1
    isolate->SetHostCreateShadowRealmContextCallback(
274
        shadow_realm::HostCreateShadowRealmContextCallback);
275
  }
276
277
6332
  if ((s.flags & SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK) == 0) {
278
6332
    auto* promise_reject_cb = s.promise_reject_callback ?
279
      s.promise_reject_callback : PromiseRejectCallback;
280
6332
    isolate->SetPromiseRejectCallback(promise_reject_cb);
281
  }
282
283
6332
  if (s.flags & DETAILED_SOURCE_POSITIONS_FOR_PROFILING)
284
6332
    v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
285
6332
}
286
287
806
void SetIsolateUpForNode(v8::Isolate* isolate,
288
                         const IsolateSettings& settings) {
289
806
  SetIsolateErrorHandlers(isolate, settings);
290
806
  SetIsolateMiscHandlers(isolate, settings);
291
806
}
292
293
806
void SetIsolateUpForNode(v8::Isolate* isolate) {
294
806
  IsolateSettings settings;
295
806
  SetIsolateUpForNode(isolate, settings);
296
806
}
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
60
  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
8
  return NewIsolate(&params, event_loop, platform);
331
}
332
333
789
IsolateData* CreateIsolateData(Isolate* isolate,
334
                               uv_loop_t* loop,
335
                               MultiIsolatePlatform* platform,
336
                               ArrayBufferAllocator* allocator) {
337
789
  return new IsolateData(isolate, loop, platform, allocator);
338
}
339
340
787
void FreeIsolateData(IsolateData* isolate_data) {
341
787
  delete isolate_data;
342
787
}
343
344
1932
InspectorParentHandle::~InspectorParentHandle() {}
345
346
// Hide the internal handle class from the public API.
347
#if HAVE_INSPECTOR
348
struct InspectorParentHandleImpl : public InspectorParentHandle {
349
  std::unique_ptr<inspector::ParentInspectorHandle> impl;
350
351
966
  explicit InspectorParentHandleImpl(
352
      std::unique_ptr<inspector::ParentInspectorHandle>&& impl)
353
966
    : impl(std::move(impl)) {}
354
};
355
#endif
356
357
778
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
778
  Isolate* isolate = context->GetIsolate();
366
1556
  HandleScope handle_scope(isolate);
367
778
  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
778
      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
778
  if (env->should_create_inspector()) {
375
778
    if (inspector_parent_handle) {
376
728
      env->InitializeInspector(
377
          std::move(static_cast<InspectorParentHandleImpl*>(
378
728
              inspector_parent_handle.get())->impl));
379
    } else {
380
50
      env->InitializeInspector({});
381
    }
382
  }
383
#endif
384
385
1556
  if (env->principal_realm()->RunBootstrapping().IsEmpty()) {
386
    FreeEnvironment(env);
387
    return nullptr;
388
  }
389
390
778
  return env;
391
}
392
393
5730
void FreeEnvironment(Environment* env) {
394
5730
  Isolate* isolate = env->isolate();
395
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate,
396
11460
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
397
  {
398
11460
    HandleScope handle_scope(isolate);  // For env->context().
399
5730
    Context::Scope context_scope(env->context());
400
11460
    SealHandleScope seal_handle_scope(isolate);
401
402
5730
    env->set_stopping(true);
403
5730
    env->stop_sub_worker_contexts();
404
5730
    env->RunCleanup();
405
5730
    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
5730
  MultiIsolatePlatform* platform = env->isolate_data()->platform();
412
5730
  if (platform != nullptr)
413
5730
    platform->DrainTasks(isolate);
414
415
5730
  delete env;
416
5730
}
417
418
966
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
419
    Environment* env,
420
    ThreadId thread_id,
421
    const char* url) {
422
966
  CHECK_NOT_NULL(env);
423
966
  CHECK_NE(thread_id.id, static_cast<uint64_t>(-1));
424
#if HAVE_INSPECTOR
425
1932
  return std::make_unique<InspectorParentHandleImpl>(
426
2898
      env->inspector_agent()->GetParentHandle(thread_id.id, url));
427
#else
428
  return {};
429
#endif
430
}
431
432
6270
MaybeLocal<Value> LoadEnvironment(
433
    Environment* env,
434
    StartExecutionCallback cb) {
435
6270
  env->InitializeLibuv();
436
6270
  env->InitializeDiagnostics();
437
438
6270
  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
38
            String::NewFromUtf8(isolate,
452
19
                                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
36
        std::string name = "embedder_main_" + std::to_string(env->thread_id());
457
19
        builtins::BuiltinLoader::Add(
458
19
            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
19
        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
5932
MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env) {
479
5932
  return GetMultiIsolatePlatform(env->isolate_data());
480
}
481
482
5932
MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) {
483
5932
  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
7
                                        page_allocator);
513
}
514
515
36465
MaybeLocal<Object> GetPerContextExports(Local<Context> context) {
516
36465
  Isolate* isolate = context->GetIsolate();
517
36465
  EscapableHandleScope handle_scope(isolate);
518
519
36465
  Local<Object> global = context->Global();
520
  Local<Private> key = Private::ForApi(isolate,
521
36465
      FIXED_ONE_BYTE_STRING(isolate, "node:per_context_binding_exports"));
522
523
  Local<Value> existing_value;
524
72930
  if (!global->GetPrivate(context, key).ToLocal(&existing_value))
525
    return MaybeLocal<Object>();
526
36465
  if (existing_value->IsObject())
527
36392
    return handle_scope.Escape(existing_value.As<Object>());
528
529
73
  Local<Object> exports = Object::New(isolate);
530
292
  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
6947
Maybe<bool> InitializeContextRuntime(Local<Context> context) {
558
6947
  Isolate* isolate = context->GetIsolate();
559
13894
  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
6947
      context->IsCodeGenerationFromStringsAllowed();
569
6947
  context->AllowCodeGenerationFromStrings(false);
570
13894
  context->SetEmbedderData(
571
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings,
572
      is_code_generation_from_strings_allowed ? True(isolate) : False(isolate));
573
574
6947
  if (per_process::cli_options->disable_proto == "") {
575
6939
    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
8
    if (!context->Global()
589
8
        ->Get(context, object_string)
590
8
        .ToLocal(&object_v)) {
591
      return Nothing<bool>();
592
    }
593
594
    Local<Value> prototype_v;
595
8
    if (!object_v.As<Object>()
596
8
        ->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
4
        ->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
4
    if (!Function::New(context, ProtoThrower)
616
4
        .ToLocal(&thrower)) {
617
      return Nothing<bool>();
618
    }
619
620
4
    PropertyDescriptor descriptor(thrower, thrower);
621
4
    descriptor.set_enumerable(false);
622
4
    descriptor.set_configurable(true);
623
4
    if (prototype
624
4
        ->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
231
    if (!context->Global()->Get(context, intl_string).ToLocal(&intl_v)) {
651
      return Nothing<bool>();
652
    }
653
654
154
    if (intl_v->IsObject() &&
655

231
        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
141
  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
282
  if (primordials->SetPrototype(context, Null(isolate)).IsNothing() ||
690

423
      !GetPerContextExports(context).ToLocal(&exports) ||
691

423
      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
423
    Local<Value> arguments[] = {exports, primordials};
702
423
    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
6542
ThreadId AllocateEnvironmentThreadId() {
766
6542
  return ThreadId { next_thread_id++ };
767
}
768
769
571
[[noreturn]] void Exit(ExitCode exit_code) {
770
571
  exit(static_cast<int>(exit_code));
771
}
772
773
567
void DefaultProcessExitHandlerInternal(Environment* env, ExitCode exit_code) {
774
567
  env->set_can_call_into_js(false);
775
567
  env->stop_sub_worker_contexts();
776
567
  env->isolate()->DumpAndResetStats();
777
567
  DisposePlatform();
778
567
  uv_library_shutdown();
779
567
  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
729
void SetProcessExitHandler(Environment* env,
792
                           std::function<void(Environment*, int)>&& handler) {
793
729
  auto movedHandler = std::move(handler);
794
729
  env->set_process_exit_handler([=](Environment* env, ExitCode exit_code) {
795
63
    movedHandler(env, static_cast<int>(exit_code));
796
63
  });
797
729
}
798
799
}  // namespace node