GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/environment.cc Lines: 338 387 87.3 %
Date: 2022-09-29 04:23:51 Branches: 108 188 57.4 %

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

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

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

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

371967
  if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers)
90
62694
    ret = allocator_->Allocate(size);
91
  else
92
309273
    ret = allocator_->AllocateUninitialized(size);
93
371967
  if (LIKELY(ret != nullptr))
94
371967
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
95
371967
  return ret;
96
}
97
98
170923
void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) {
99
170923
  void* ret = allocator_->AllocateUninitialized(size);
100
170923
  if (LIKELY(ret != nullptr))
101
170923
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
102
170923
  return ret;
103
}
104
105
62135
void* NodeArrayBufferAllocator::Reallocate(
106
    void* data, size_t old_size, size_t size) {
107
62135
  void* ret = allocator_->Reallocate(data, old_size, size);
108

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

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

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

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

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

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