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: 326 362 90.1 %
Date: 2020-11-20 19:51:53 Branches: 110 176 62.5 %

Line Branch Exec Source
1
#include "node.h"
2
#include "node_context_data.h"
3
#include "node_errors.h"
4
#include "node_internals.h"
5
#include "node_native_module_env.h"
6
#include "node_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
91
bool AllowWasmCodeGenerationCallback(Local<Context> context,
35
                                     Local<String>) {
36
  Local<Value> wasm_code_gen =
37
182
      context->GetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration);
38

273
  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
71657
MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context,
52
                                            Local<Value> exception,
53
                                            Local<Array> trace) {
54
71657
  Environment* env = Environment::GetCurrent(context);
55
71657
  if (env == nullptr) {
56
    return exception->ToString(context).FromMaybe(Local<Value>());
57
  }
58
71657
  Local<Function> prepare = env->prepare_stack_trace_callback();
59
71657
  if (prepare.IsEmpty()) {
60
    return exception->ToString(context).FromMaybe(Local<Value>());
61
  }
62
  Local<Value> args[] = {
63
      context->Global(),
64
      exception,
65
      trace,
66
286628
  };
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
143314
  TryCatchScope try_catch(env);
72
  MaybeLocal<Value> result = prepare->Call(
73
143314
      context, Undefined(env->isolate()), arraysize(args), args);
74

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

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

306226
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
102
306226
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
103
306226
  return ret;
104
}
105
106
492877
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
107
492877
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
108
492877
  free(data);
109
492877
}
110
111
9
DebuggingArrayBufferAllocator::~DebuggingArrayBufferAllocator() {
112
3
  CHECK(allocations_.empty());
113
6
}
114
115
35
void* DebuggingArrayBufferAllocator::Allocate(size_t size) {
116
70
  Mutex::ScopedLock lock(mutex_);
117
35
  void* data = NodeArrayBufferAllocator::Allocate(size);
118
35
  RegisterPointerInternal(data, size);
119
70
  return data;
120
}
121
122
28
void* DebuggingArrayBufferAllocator::AllocateUninitialized(size_t size) {
123
56
  Mutex::ScopedLock lock(mutex_);
124
28
  void* data = NodeArrayBufferAllocator::AllocateUninitialized(size);
125
28
  RegisterPointerInternal(data, size);
126
56
  return data;
127
}
128
129
63
void DebuggingArrayBufferAllocator::Free(void* data, size_t size) {
130
126
  Mutex::ScopedLock lock(mutex_);
131
63
  UnregisterPointerInternal(data, size);
132
63
  NodeArrayBufferAllocator::Free(data, size);
133
63
}
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
63
void DebuggingArrayBufferAllocator::UnregisterPointerInternal(void* data,
169
                                                              size_t size) {
170
63
  if (data == nullptr) return;
171
63
  auto it = allocations_.find(data);
172
63
  CHECK_NE(it, allocations_.end());
173
63
  if (size > 0) {
174
    // We allow allocations with size 1 for 0-length buffers to avoid having
175
    // to deal with nullptr values.
176
63
    CHECK_EQ(it->second, size);
177
  }
178
63
  allocations_.erase(it);
179
}
180
181
63
void DebuggingArrayBufferAllocator::RegisterPointerInternal(void* data,
182
                                                            size_t size) {
183
63
  if (data == nullptr) return;
184
63
  CHECK_EQ(allocations_.count(data), 0);
185
63
  allocations_[data] = size;
186
}
187
188
5054
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
189

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

1800
  if (context->Global()->SetPrivate(context, key, exports).IsNothing() ||
488
450
      !InitializePrimordials(context))
489
4
    return MaybeLocal<Object>();
490
446
  return handle_scope.Escape(exports);
491
}
492
493
// Any initialization logic should be performed in
494
// InitializeContext, because embedders don't necessarily
495
// call NewContext and so they will experience breakages.
496
445
Local<Context> NewContext(Isolate* isolate,
497
                          Local<ObjectTemplate> object_template) {
498
890
  auto context = Context::New(isolate, nullptr, object_template);
499
445
  if (context.IsEmpty()) return context;
500
501
445
  if (!InitializeContext(context)) {
502
4
    return Local<Context>();
503
  }
504
505
441
  return context;
506
}
507
508
8
void ProtoThrower(const FunctionCallbackInfo<Value>& info) {
509
8
  THROW_ERR_PROTO_ACCESS(info.GetIsolate());
510
8
}
511
512
// This runs at runtime, regardless of whether the context
513
// is created from a snapshot.
514
5553
void InitializeContextRuntime(Local<Context> context) {
515
5553
  Isolate* isolate = context->GetIsolate();
516
11106
  HandleScope handle_scope(isolate);
517
518
  // Delete `Intl.v8BreakIterator`
519
  // https://github.com/nodejs/node/issues/14909
520
5553
  Local<String> intl_string = FIXED_ONE_BYTE_STRING(isolate, "Intl");
521
  Local<String> break_iter_string =
522
5553
    FIXED_ONE_BYTE_STRING(isolate, "v8BreakIterator");
523
  Local<Value> intl_v;
524

22212
  if (context->Global()->Get(context, intl_string).ToLocal(&intl_v) &&
525
5553
      intl_v->IsObject()) {
526
5553
    Local<Object> intl = intl_v.As<Object>();
527
11106
    intl->Delete(context, break_iter_string).Check();
528
  }
529
530
  // Delete `Atomics.wake`
531
  // https://github.com/nodejs/node/issues/21219
532
5553
  Local<String> atomics_string = FIXED_ONE_BYTE_STRING(isolate, "Atomics");
533
5553
  Local<String> wake_string = FIXED_ONE_BYTE_STRING(isolate, "wake");
534
  Local<Value> atomics_v;
535

22212
  if (context->Global()->Get(context, atomics_string).ToLocal(&atomics_v) &&
536
5553
      atomics_v->IsObject()) {
537
5545
    Local<Object> atomics = atomics_v.As<Object>();
538
11090
    atomics->Delete(context, wake_string).Check();
539
  }
540
541
  // Remove __proto__
542
  // https://github.com/nodejs/node/issues/31951
543
5553
  Local<String> object_string = FIXED_ONE_BYTE_STRING(isolate, "Object");
544
5553
  Local<String> prototype_string = FIXED_ONE_BYTE_STRING(isolate, "prototype");
545
11106
  Local<Object> prototype = context->Global()
546
16659
                                ->Get(context, object_string)
547
11106
                                .ToLocalChecked()
548
11106
                                .As<Object>()
549
16659
                                ->Get(context, prototype_string)
550
11106
                                .ToLocalChecked()
551
5553
                                .As<Object>();
552
5553
  Local<String> proto_string = FIXED_ONE_BYTE_STRING(isolate, "__proto__");
553
5553
  if (per_process::cli_options->disable_proto == "delete") {
554
8
    prototype->Delete(context, proto_string).ToChecked();
555
5549
  } else if (per_process::cli_options->disable_proto == "throw") {
556
    Local<Value> thrower =
557
8
        Function::New(context, ProtoThrower).ToLocalChecked();
558
8
    PropertyDescriptor descriptor(thrower, thrower);
559
4
    descriptor.set_enumerable(false);
560
4
    descriptor.set_configurable(true);
561
8
    prototype->DefineProperty(context, proto_string, descriptor).ToChecked();
562
5545
  } else if (per_process::cli_options->disable_proto != "") {
563
    // Validated in ProcessGlobalArgs
564
    FatalError("InitializeContextRuntime()", "invalid --disable-proto mode");
565
  }
566
5553
}
567
568
445
bool InitializeContextForSnapshot(Local<Context> context) {
569
445
  Isolate* isolate = context->GetIsolate();
570
890
  HandleScope handle_scope(isolate);
571
572
890
  context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
573
445
                           True(isolate));
574
890
  return InitializePrimordials(context);
575
}
576
577
895
bool InitializePrimordials(Local<Context> context) {
578
  // Run per-context JS files.
579
895
  Isolate* isolate = context->GetIsolate();
580
  Context::Scope context_scope(context);
581
  Local<Object> exports;
582
583
  Local<String> primordials_string =
584
895
      FIXED_ONE_BYTE_STRING(isolate, "primordials");
585
895
  Local<String> global_string = FIXED_ONE_BYTE_STRING(isolate, "global");
586
895
  Local<String> exports_string = FIXED_ONE_BYTE_STRING(isolate, "exports");
587
588
  // Create primordials first and make it available to per-context scripts.
589
895
  Local<Object> primordials = Object::New(isolate);
590

4475
  if (!primordials->SetPrototype(context, Null(isolate)).FromJust() ||
591

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

14034
}  // namespace node