GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/api/environment.cc Lines: 331 367 90.2 %
Date: 2021-04-26 04:12:24 Branches: 110 178 61.8 %

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

276
  return wasm_code_gen->IsUndefined() || wasm_code_gen->IsTrue();
39
}
40
41
33
bool ShouldAbortOnUncaughtException(Isolate* isolate) {
42
33
  DebugSealHandleScope scope(isolate);
43
33
  Environment* env = Environment::GetCurrent(isolate);
44
33
  return env != nullptr &&
45

68
         (env->is_main_thread() || !env->is_stopping()) &&
46
63
         env->abort_on_uncaught_exception() &&
47

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

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

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

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

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

1920
  if (context->Global()->SetPrivate(context, key, exports).IsNothing() ||
498
480
      !InitializePrimordials(context))
499
4
    return MaybeLocal<Object>();
500
476
  return handle_scope.Escape(exports);
501
}
502
503
// Any initialization logic should be performed in
504
// InitializeContext, because embedders don't necessarily
505
// call NewContext and so they will experience breakages.
506
474
Local<Context> NewContext(Isolate* isolate,
507
                          Local<ObjectTemplate> object_template) {
508
948
  auto context = Context::New(isolate, nullptr, object_template);
509
474
  if (context.IsEmpty()) return context;
510
511
474
  if (!InitializeContext(context)) {
512
4
    return Local<Context>();
513
  }
514
515
470
  return context;
516
}
517
518
8
void ProtoThrower(const FunctionCallbackInfo<Value>& info) {
519
8
  THROW_ERR_PROTO_ACCESS(info.GetIsolate());
520
8
}
521
522
// This runs at runtime, regardless of whether the context
523
// is created from a snapshot.
524
5801
void InitializeContextRuntime(Local<Context> context) {
525
5801
  Isolate* isolate = context->GetIsolate();
526
11602
  HandleScope handle_scope(isolate);
527
528
  // Delete `Intl.v8BreakIterator`
529
  // https://github.com/nodejs/node/issues/14909
530
5801
  Local<String> intl_string = FIXED_ONE_BYTE_STRING(isolate, "Intl");
531
  Local<String> break_iter_string =
532
5801
    FIXED_ONE_BYTE_STRING(isolate, "v8BreakIterator");
533
  Local<Value> intl_v;
534

23204
  if (context->Global()->Get(context, intl_string).ToLocal(&intl_v) &&
535
5801
      intl_v->IsObject()) {
536
5801
    Local<Object> intl = intl_v.As<Object>();
537
11602
    intl->Delete(context, break_iter_string).Check();
538
  }
539
540
  // Delete `Atomics.wake`
541
  // https://github.com/nodejs/node/issues/21219
542
5801
  Local<String> atomics_string = FIXED_ONE_BYTE_STRING(isolate, "Atomics");
543
5801
  Local<String> wake_string = FIXED_ONE_BYTE_STRING(isolate, "wake");
544
  Local<Value> atomics_v;
545

23204
  if (context->Global()->Get(context, atomics_string).ToLocal(&atomics_v) &&
546
5801
      atomics_v->IsObject()) {
547
5793
    Local<Object> atomics = atomics_v.As<Object>();
548
11586
    atomics->Delete(context, wake_string).Check();
549
  }
550
551
  // Remove __proto__
552
  // https://github.com/nodejs/node/issues/31951
553
5801
  Local<String> object_string = FIXED_ONE_BYTE_STRING(isolate, "Object");
554
5801
  Local<String> prototype_string = FIXED_ONE_BYTE_STRING(isolate, "prototype");
555
11602
  Local<Object> prototype = context->Global()
556
17403
                                ->Get(context, object_string)
557
11602
                                .ToLocalChecked()
558
11602
                                .As<Object>()
559
17403
                                ->Get(context, prototype_string)
560
11602
                                .ToLocalChecked()
561
5801
                                .As<Object>();
562
5801
  Local<String> proto_string = FIXED_ONE_BYTE_STRING(isolate, "__proto__");
563
5801
  if (per_process::cli_options->disable_proto == "delete") {
564
8
    prototype->Delete(context, proto_string).ToChecked();
565
5797
  } else if (per_process::cli_options->disable_proto == "throw") {
566
    Local<Value> thrower =
567
8
        Function::New(context, ProtoThrower).ToLocalChecked();
568
8
    PropertyDescriptor descriptor(thrower, thrower);
569
4
    descriptor.set_enumerable(false);
570
4
    descriptor.set_configurable(true);
571
8
    prototype->DefineProperty(context, proto_string, descriptor).ToChecked();
572
5793
  } else if (per_process::cli_options->disable_proto != "") {
573
    // Validated in ProcessGlobalArgs
574
    FatalError("InitializeContextRuntime()", "invalid --disable-proto mode");
575
  }
576
5801
}
577
578
475
bool InitializeContextForSnapshot(Local<Context> context) {
579
475
  Isolate* isolate = context->GetIsolate();
580
950
  HandleScope handle_scope(isolate);
581
582
950
  context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
583
475
                           True(isolate));
584
950
  return InitializePrimordials(context);
585
}
586
587
955
bool InitializePrimordials(Local<Context> context) {
588
  // Run per-context JS files.
589
955
  Isolate* isolate = context->GetIsolate();
590
  Context::Scope context_scope(context);
591
  Local<Object> exports;
592
593
  Local<String> primordials_string =
594
955
      FIXED_ONE_BYTE_STRING(isolate, "primordials");
595
955
  Local<String> global_string = FIXED_ONE_BYTE_STRING(isolate, "global");
596
955
  Local<String> exports_string = FIXED_ONE_BYTE_STRING(isolate, "exports");
597
598
  // Create primordials first and make it available to per-context scripts.
599
955
  Local<Object> primordials = Object::New(isolate);
600

4772
  if (!primordials->SetPrototype(context, Null(isolate)).FromJust() ||
601

3814
      !GetPerContextExports(context).ToLocal(&exports) ||
602
2856
      !exports->Set(context, primordials_string, primordials).FromJust()) {
603
4
    return false;
604
  }
605
606
  static const char* context_files[] = {"internal/per_context/primordials",
607
                                        "internal/per_context/domexception",
608
                                        "internal/per_context/messageport",
609
                                        nullptr};
610
611
3791
  for (const char** module = context_files; *module != nullptr; module++) {
612
    std::vector<Local<String>> parameters = {
613
5685
        global_string, exports_string, primordials_string};
614
14222
    Local<Value> arguments[] = {context->Global(), exports, primordials};
615
    MaybeLocal<Function> maybe_fn =
616
        native_module::NativeModuleEnv::LookupAndCompile(
617
2844
            context, *module, &parameters, nullptr);
618
    Local<Function> fn;
619
2845
    if (!maybe_fn.ToLocal(&fn)) {
620
      return false;
621
    }
622
    MaybeLocal<Value> result =
623
5690
        fn->Call(context, Undefined(isolate), arraysize(arguments), arguments);
624
    // Execution failed during context creation.
625
    // TODO(joyeecheung): deprecate this signature and return a MaybeLocal.
626
2844
    if (result.IsEmpty()) {
627
4
      return false;
628
    }
629
  }
630
631
947
  return true;
632
}
633
634
475
bool InitializeContext(Local<Context> context) {
635
475
  if (!InitializeContextForSnapshot(context)) {
636
4
    return false;
637
  }
638
639
471
  InitializeContextRuntime(context);
640
471
  return true;
641
}
642
643
10
uv_loop_t* GetCurrentEventLoop(Isolate* isolate) {
644
20
  HandleScope handle_scope(isolate);
645
10
  Local<Context> context = isolate->GetCurrentContext();
646
10
  if (context.IsEmpty()) return nullptr;
647
10
  Environment* env = Environment::GetCurrent(context);
648
10
  if (env == nullptr) return nullptr;
649
10
  return env->event_loop();
650
}
651
652
3
void AddLinkedBinding(Environment* env, const node_module& mod) {
653
3
  CHECK_NOT_NULL(env);
654
6
  Mutex::ScopedLock lock(env->extra_linked_bindings_mutex());
655
656
3
  node_module* prev_head = env->extra_linked_bindings_head();
657
3
  env->extra_linked_bindings()->push_back(mod);
658
3
  if (prev_head != nullptr)
659
    prev_head->nm_link = &env->extra_linked_bindings()->back();
660
3
}
661
662
2
void AddLinkedBinding(Environment* env, const napi_module& mod) {
663
2
  AddLinkedBinding(env, napi_module_to_node_module(&mod));
664
2
}
665
666
1
void AddLinkedBinding(Environment* env,
667
                      const char* name,
668
                      addon_context_register_func fn,
669
                      void* priv) {
670
  node_module mod = {
671
    NODE_MODULE_VERSION,
672
    NM_F_LINKED,
673
    nullptr,  // nm_dso_handle
674
    nullptr,  // nm_filename
675
    nullptr,  // nm_register_func
676
    fn,
677
    name,
678
    priv,
679
    nullptr   // nm_link
680
1
  };
681
1
  AddLinkedBinding(env, mod);
682
1
}
683
684
static std::atomic<uint64_t> next_thread_id{0};
685
686
5457
ThreadId AllocateEnvironmentThreadId() {
687
5457
  return ThreadId { next_thread_id++ };
688
}
689
690
566
void DefaultProcessExitHandler(Environment* env, int exit_code) {
691
566
  env->set_can_call_into_js(false);
692
566
  env->stop_sub_worker_contexts();
693
566
  DisposePlatform();
694
566
  uv_library_shutdown();
695
566
  exit(exit_code);
696
}
697
698
699
417
void SetProcessExitHandler(Environment* env,
700
                           std::function<void(Environment*, int)>&& handler) {
701
417
  env->set_process_exit_handler(std::move(handler));
702
417
}
703
704

14475
}  // namespace node