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: 332 368 90.2 %
Date: 2021-05-26 04:16:18 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
75219
MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context,
52
                                            Local<Value> exception,
53
                                            Local<Array> trace) {
54
75219
  Environment* env = Environment::GetCurrent(context);
55
75219
  if (env == nullptr) {
56
    return exception->ToString(context).FromMaybe(Local<Value>());
57
  }
58
75219
  Local<Function> prepare = env->prepare_stack_trace_callback();
59
75219
  if (prepare.IsEmpty()) {
60
    return exception->ToString(context).FromMaybe(Local<Value>());
61
  }
62
  Local<Value> args[] = {
63
      context->Global(),
64
      exception,
65
      trace,
66
300876
  };
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
150438
  TryCatchScope try_catch(env);
72
  MaybeLocal<Value> result = prepare->Call(
73
150438
      context, Undefined(env->isolate()), arraysize(args), args);
74

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

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

61740
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
102
61740
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
103
61740
  return ret;
104
}
105
106
291771
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
107
291771
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
108
291771
  free(data);
109
291771
}
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
5252
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
189

5252
  if (debug || per_process::cli_options->debug_arraybuffer_allocations)
190
3
    return std::make_unique<DebuggingArrayBufferAllocator>();
191
  else
192
5249
    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
5250
void SetIsolateCreateParamsForNode(Isolate::CreateParams* params) {
204
5250
  const uint64_t constrained_memory = uv_get_constrained_memory();
205
10490
  const uint64_t total_memory = constrained_memory > 0 ?
206
10490
      std::min(uv_get_total_memory(), constrained_memory) :
207
5250
      uv_get_total_memory();
208
5250
  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
5250
    params->constraints.ConfigureDefaults(total_memory, 0);
213
  }
214
5250
  params->embedder_wrapper_object_index = BaseObject::InternalFields::kSlot;
215
5250
  params->embedder_wrapper_type_index = std::numeric_limits<int>::max();
216
5250
}
217
218
5250
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
219
5250
  if (s.flags & MESSAGE_LISTENER_WITH_ERROR_LEVEL)
220
5250
    isolate->AddMessageListenerWithErrorLevel(
221
            errors::PerIsolateMessageListener,
222
            Isolate::MessageErrorLevel::kMessageError |
223
5250
                Isolate::MessageErrorLevel::kMessageWarning);
224
225
5250
  auto* abort_callback = s.should_abort_on_uncaught_exception_callback ?
226
      s.should_abort_on_uncaught_exception_callback :
227
5250
      ShouldAbortOnUncaughtException;
228
5250
  isolate->SetAbortOnUncaughtExceptionCallback(abort_callback);
229
230
5250
  auto* fatal_error_cb = s.fatal_error_callback ?
231
5250
      s.fatal_error_callback : OnFatalError;
232
5250
  isolate->SetFatalErrorHandler(fatal_error_cb);
233
234
5250
  if ((s.flags & SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK) == 0) {
235
5250
    auto* prepare_stack_trace_cb = s.prepare_stack_trace_callback ?
236
5250
        s.prepare_stack_trace_callback : PrepareStackTraceCallback;
237
5250
    isolate->SetPrepareStackTraceCallback(prepare_stack_trace_cb);
238
  }
239
5250
}
240
241
5258
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
242
5258
  isolate->SetMicrotasksPolicy(s.policy);
243
244
5258
  auto* allow_wasm_codegen_cb = s.allow_wasm_code_generation_callback ?
245
5258
    s.allow_wasm_code_generation_callback : AllowWasmCodeGenerationCallback;
246
5258
  isolate->SetAllowWasmCodeGenerationCallback(allow_wasm_codegen_cb);
247
248
5258
  if ((s.flags & SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK) == 0) {
249
5258
    auto* promise_reject_cb = s.promise_reject_callback ?
250
5258
      s.promise_reject_callback : PromiseRejectCallback;
251
5258
    isolate->SetPromiseRejectCallback(promise_reject_cb);
252
  }
253
254
5258
  if (s.flags & DETAILED_SOURCE_POSITIONS_FOR_PROFILING)
255
5258
    v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
256
5258
}
257
258
483
void SetIsolateUpForNode(v8::Isolate* isolate,
259
                         const IsolateSettings& settings) {
260
483
  SetIsolateErrorHandlers(isolate, settings);
261
483
  SetIsolateMiscHandlers(isolate, settings);
262
483
}
263
264
483
void SetIsolateUpForNode(v8::Isolate* isolate) {
265
483
  IsolateSettings settings;
266
483
  SetIsolateUpForNode(isolate, settings);
267
483
}
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
468
IsolateData* CreateIsolateData(Isolate* isolate,
305
                               uv_loop_t* loop,
306
                               MultiIsolatePlatform* platform,
307
                               ArrayBufferAllocator* allocator) {
308
468
  return new IsolateData(isolate, loop, platform, allocator);
309
}
310
311
466
void FreeIsolateData(IsolateData* isolate_data) {
312
466
  delete isolate_data;
313
466
}
314
315
656
InspectorParentHandle::~InspectorParentHandle() {}
316
317
// Hide the internal handle class from the public API.
318
#if HAVE_INSPECTOR
319
1312
struct InspectorParentHandleImpl : public InspectorParentHandle {
320
  std::unique_ptr<inspector::ParentInspectorHandle> impl;
321
322
656
  explicit InspectorParentHandleImpl(
323
      std::unique_ptr<inspector::ParentInspectorHandle>&& impl)
324
656
    : impl(std::move(impl)) {}
325
};
326
#endif
327
328
453
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
453
  Isolate* isolate = context->GetIsolate();
337
906
  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
453
      isolate_data, context, args, exec_args, nullptr, flags, thread_id);
343
#if HAVE_INSPECTOR
344
453
  if (inspector_parent_handle) {
345
818
    env->InitializeInspector(
346
        std::move(static_cast<InspectorParentHandleImpl*>(
347
818
            inspector_parent_handle.get())->impl));
348
  } else {
349
44
    env->InitializeInspector({});
350
  }
351
#endif
352
353
905
  if (env->RunBootstrapping().IsEmpty()) {
354
    FreeEnvironment(env);
355
    return nullptr;
356
  }
357
358
453
  return env;
359
}
360
361
4654
void FreeEnvironment(Environment* env) {
362
  Isolate::DisallowJavascriptExecutionScope disallow_js(env->isolate(),
363
9310
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
364
  {
365
9310
    HandleScope handle_scope(env->isolate());  // For env->context().
366
4655
    Context::Scope context_scope(env->context());
367
9310
    SealHandleScope seal_handle_scope(env->isolate());
368
369
4654
    env->set_stopping(true);
370
4655
    env->stop_sub_worker_contexts();
371
4654
    env->RunCleanup();
372
4655
    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
4656
  MultiIsolatePlatform* platform = env->isolate_data()->platform();
379
4656
  if (platform != nullptr)
380
4656
    platform->DrainTasks(env->isolate());
381
382
4656
  delete env;
383
4656
}
384
385
656
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
386
    Environment* env,
387
    ThreadId thread_id,
388
    const char* url) {
389
656
  CHECK_NOT_NULL(env);
390
656
  CHECK_NE(thread_id.id, static_cast<uint64_t>(-1));
391
#if HAVE_INSPECTOR
392
1312
  return std::make_unique<InspectorParentHandleImpl>(
393
1968
      env->inspector_agent()->GetParentHandle(thread_id.id, url));
394
#else
395
  return {};
396
#endif
397
}
398
399
5195
MaybeLocal<Value> LoadEnvironment(
400
    Environment* env,
401
    StartExecutionCallback cb) {
402
5195
  env->InitializeLibuv();
403
5195
  env->InitializeDiagnostics();
404
405
5195
  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
4893
MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env) {
450
4893
  return GetMultiIsolatePlatform(env->isolate_data());
451
}
452
453
4893
MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) {
454
4893
  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,
469
                                      tracing_controller)
470
      .release();
471
}
472
473
void FreePlatform(MultiIsolatePlatform* platform) {
474
  delete platform;
475
}
476
477
7
std::unique_ptr<MultiIsolatePlatform> MultiIsolatePlatform::Create(
478
    int thread_pool_size,
479
    v8::TracingController* tracing_controller,
480
    v8::PageAllocator* page_allocator) {
481
14
  return std::make_unique<NodePlatform>(thread_pool_size,
482
                                        tracing_controller,
483
14
                                        page_allocator);
484
}
485
486
34890
MaybeLocal<Object> GetPerContextExports(Local<Context> context) {
487
34890
  Isolate* isolate = context->GetIsolate();
488
34890
  EscapableHandleScope handle_scope(isolate);
489
490
34890
  Local<Object> global = context->Global();
491
  Local<Private> key = Private::ForApi(isolate,
492
34890
      FIXED_ONE_BYTE_STRING(isolate, "node:per_context_binding_exports"));
493
494
  Local<Value> existing_value;
495
69780
  if (!global->GetPrivate(context, key).ToLocal(&existing_value))
496
    return MaybeLocal<Object>();
497
34890
  if (existing_value->IsObject())
498
34416
    return handle_scope.Escape(existing_value.As<Object>());
499
500
474
  Local<Object> exports = Object::New(isolate);
501

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

23240
  if (context->Global()->Get(context, intl_string).ToLocal(&intl_v) &&
539
5810
      intl_v->IsObject()) {
540
5810
    Local<Object> intl = intl_v.As<Object>();
541
11620
    intl->Delete(context, break_iter_string).Check();
542
  }
543
544
  // Delete `Atomics.wake`
545
  // https://github.com/nodejs/node/issues/21219
546
5810
  Local<String> atomics_string = FIXED_ONE_BYTE_STRING(isolate, "Atomics");
547
5810
  Local<String> wake_string = FIXED_ONE_BYTE_STRING(isolate, "wake");
548
  Local<Value> atomics_v;
549

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

4715
  if (!primordials->SetPrototype(context, Null(isolate)).FromJust() ||
605

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

14520
}  // namespace node