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

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

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

61752
  if (LIKELY(ret != nullptr) || UNLIKELY(size == 0))
102
61752
    total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed);
103
61752
  return ret;
104
}
105
106
304252
void NodeArrayBufferAllocator::Free(void* data, size_t size) {
107
304252
  total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
108
304252
  free(data);
109
304252
}
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
39
void* DebuggingArrayBufferAllocator::AllocateUninitialized(size_t size) {
123
78
  Mutex::ScopedLock lock(mutex_);
124
39
  void* data = NodeArrayBufferAllocator::AllocateUninitialized(size);
125
39
  RegisterPointerInternal(data, size);
126
78
  return data;
127
}
128
129
84
void DebuggingArrayBufferAllocator::Free(void* data, size_t size) {
130
168
  Mutex::ScopedLock lock(mutex_);
131
84
  UnregisterPointerInternal(data, size);
132
84
  NodeArrayBufferAllocator::Free(data, size);
133
84
}
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
84
void DebuggingArrayBufferAllocator::UnregisterPointerInternal(void* data,
169
                                                              size_t size) {
170
84
  if (data == nullptr) return;
171
84
  auto it = allocations_.find(data);
172
84
  CHECK_NE(it, allocations_.end());
173
84
  if (size > 0) {
174
    // We allow allocations with size 1 for 0-length buffers to avoid having
175
    // to deal with nullptr values.
176
84
    CHECK_EQ(it->second, size);
177
  }
178
84
  allocations_.erase(it);
179
}
180
181
84
void DebuggingArrayBufferAllocator::RegisterPointerInternal(void* data,
182
                                                            size_t size) {
183
84
  if (data == nullptr) return;
184
84
  CHECK_EQ(allocations_.count(data), 0);
185
84
  allocations_[data] = size;
186
}
187
188
5258
std::unique_ptr<ArrayBufferAllocator> ArrayBufferAllocator::Create(bool debug) {
189

5258
  if (debug || per_process::cli_options->debug_arraybuffer_allocations)
190
3
    return std::make_unique<DebuggingArrayBufferAllocator>();
191
  else
192
5255
    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
5253
void SetIsolateCreateParamsForNode(Isolate::CreateParams* params) {
204
5253
  const uint64_t constrained_memory = uv_get_constrained_memory();
205
10499
  const uint64_t total_memory = constrained_memory > 0 ?
206
10499
      std::min(uv_get_total_memory(), constrained_memory) :
207
5256
      uv_get_total_memory();
208
5256
  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
5256
    params->constraints.ConfigureDefaults(total_memory, 0);
213
  }
214
5256
  params->embedder_wrapper_object_index = BaseObject::InternalFields::kSlot;
215
5256
  params->embedder_wrapper_type_index = std::numeric_limits<int>::max();
216
5256
}
217
218
5256
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
219
5256
  if (s.flags & MESSAGE_LISTENER_WITH_ERROR_LEVEL)
220
5256
    isolate->AddMessageListenerWithErrorLevel(
221
            errors::PerIsolateMessageListener,
222
            Isolate::MessageErrorLevel::kMessageError |
223
5256
                Isolate::MessageErrorLevel::kMessageWarning);
224
225
5256
  auto* abort_callback = s.should_abort_on_uncaught_exception_callback ?
226
      s.should_abort_on_uncaught_exception_callback :
227
5256
      ShouldAbortOnUncaughtException;
228
5256
  isolate->SetAbortOnUncaughtExceptionCallback(abort_callback);
229
230
5256
  auto* fatal_error_cb = s.fatal_error_callback ?
231
5256
      s.fatal_error_callback : OnFatalError;
232
5256
  isolate->SetFatalErrorHandler(fatal_error_cb);
233
234
5256
  if ((s.flags & SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK) == 0) {
235
5256
    auto* prepare_stack_trace_cb = s.prepare_stack_trace_callback ?
236
5256
        s.prepare_stack_trace_callback : PrepareStackTraceCallback;
237
5256
    isolate->SetPrepareStackTraceCallback(prepare_stack_trace_cb);
238
  }
239
5256
}
240
241
5264
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
242
5264
  isolate->SetMicrotasksPolicy(s.policy);
243
244
5264
  auto* allow_wasm_codegen_cb = s.allow_wasm_code_generation_callback ?
245
5264
    s.allow_wasm_code_generation_callback : AllowWasmCodeGenerationCallback;
246
5264
  isolate->SetAllowWasmCodeGenerationCallback(allow_wasm_codegen_cb);
247
248
5264
  if ((s.flags & SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK) == 0) {
249
5264
    auto* promise_reject_cb = s.promise_reject_callback ?
250
5264
      s.promise_reject_callback : PromiseRejectCallback;
251
5264
    isolate->SetPromiseRejectCallback(promise_reject_cb);
252
  }
253
254
5264
  if (s.flags & DETAILED_SOURCE_POSITIONS_FOR_PROFILING)
255
5264
    v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
256
5264
}
257
258
485
void SetIsolateUpForNode(v8::Isolate* isolate,
259
                         const IsolateSettings& settings) {
260
485
  SetIsolateErrorHandlers(isolate, settings);
261
485
  SetIsolateMiscHandlers(isolate, settings);
262
485
}
263
264
485
void SetIsolateUpForNode(v8::Isolate* isolate) {
265
485
  IsolateSettings settings;
266
485
  SetIsolateUpForNode(isolate, settings);
267
485
}
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
470
IsolateData* CreateIsolateData(Isolate* isolate,
305
                               uv_loop_t* loop,
306
                               MultiIsolatePlatform* platform,
307
                               ArrayBufferAllocator* allocator) {
308
470
  return new IsolateData(isolate, loop, platform, allocator);
309
}
310
311
468
void FreeIsolateData(IsolateData* isolate_data) {
312
468
  delete isolate_data;
313
468
}
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
455
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
455
  Isolate* isolate = context->GetIsolate();
337
910
  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
455
      isolate_data, context, args, exec_args, nullptr, flags, thread_id);
343
#if HAVE_INSPECTOR
344
455
  if (inspector_parent_handle) {
345
822
    env->InitializeInspector(
346
        std::move(static_cast<InspectorParentHandleImpl*>(
347
822
            inspector_parent_handle.get())->impl));
348
  } else {
349
44
    env->InitializeInspector({});
350
  }
351
#endif
352
353
910
  if (env->RunBootstrapping().IsEmpty()) {
354
    FreeEnvironment(env);
355
    return nullptr;
356
  }
357
358
455
  return env;
359
}
360
361
4747
void FreeEnvironment(Environment* env) {
362
4747
  Isolate* isolate = env->isolate();
363
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate,
364
9497
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
365
  {
366
9497
    HandleScope handle_scope(isolate);  // For env->context().
367
4747
    Context::Scope context_scope(env->context());
368
9497
    SealHandleScope seal_handle_scope(isolate);
369
370
4747
    env->set_stopping(true);
371
4750
    env->stop_sub_worker_contexts();
372
4748
    env->RunCleanup();
373
4749
    RunAtExit(env);
374
  }
375
376
  // This call needs to be made while the `Environment` is still alive
377
  // because we assume that it is available for async tracking in the
378
  // NodePlatform implementation.
379
4750
  MultiIsolatePlatform* platform = env->isolate_data()->platform();
380
4750
  if (platform != nullptr)
381
4750
    platform->DrainTasks(isolate);
382
383
4750
  delete env;
384
4750
}
385
386
656
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
387
    Environment* env,
388
    ThreadId thread_id,
389
    const char* url) {
390
656
  CHECK_NOT_NULL(env);
391
656
  CHECK_NE(thread_id.id, static_cast<uint64_t>(-1));
392
#if HAVE_INSPECTOR
393
1312
  return std::make_unique<InspectorParentHandleImpl>(
394
1968
      env->inspector_agent()->GetParentHandle(thread_id.id, url));
395
#else
396
  return {};
397
#endif
398
}
399
400
5201
MaybeLocal<Value> LoadEnvironment(
401
    Environment* env,
402
    StartExecutionCallback cb) {
403
5201
  env->InitializeLibuv();
404
5201
  env->InitializeDiagnostics();
405
406
5201
  return StartExecution(env, cb);
407
}
408
409
15
MaybeLocal<Value> LoadEnvironment(
410
    Environment* env,
411
    const char* main_script_source_utf8) {
412
15
  CHECK_NOT_NULL(main_script_source_utf8);
413
15
  Isolate* isolate = env->isolate();
414
  return LoadEnvironment(
415
      env,
416
15
      [&](const StartExecutionCallbackInfo& info) -> MaybeLocal<Value> {
417
        // This is a slightly hacky way to convert UTF-8 to UTF-16.
418
        Local<String> str =
419
45
            String::NewFromUtf8(isolate,
420
45
                                main_script_source_utf8).ToLocalChecked();
421
28
        auto main_utf16 = std::make_unique<String::Value>(isolate, str);
422
423
        // TODO(addaleax): Avoid having a global table for all scripts.
424
118
        std::string name = "embedder_main_" + std::to_string(env->thread_id());
425
15
        native_module::NativeModuleEnv::Add(
426
            name.c_str(),
427
30
            UnionBytes(**main_utf16, main_utf16->length()));
428
30
        env->set_main_utf16(std::move(main_utf16));
429
        std::vector<Local<String>> params = {
430
15
            env->process_string(),
431
43
            env->require_string()};
432
        std::vector<Local<Value>> args = {
433
            env->process_object(),
434
58
            env->native_module_require()};
435
43
        return ExecuteBootstrapper(env, name.c_str(), &params, &args);
436
15
      });
437
}
438
439
5
Environment* GetCurrentEnvironment(Local<Context> context) {
440
5
  return Environment::GetCurrent(context);
441
}
442
443
1
IsolateData* GetEnvironmentIsolateData(Environment* env) {
444
1
  return env->isolate_data();
445
}
446
447
1
ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* isolate_data) {
448
1
  return isolate_data->node_allocator();
449
}
450
451
4899
MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env) {
452
4899
  return GetMultiIsolatePlatform(env->isolate_data());
453
}
454
455
4899
MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) {
456
4899
  return env->platform();
457
}
458
459
MultiIsolatePlatform* CreatePlatform(
460
    int thread_pool_size,
461
    node::tracing::TracingController* tracing_controller) {
462
  return CreatePlatform(
463
      thread_pool_size,
464
      static_cast<v8::TracingController*>(tracing_controller));
465
}
466
467
MultiIsolatePlatform* CreatePlatform(
468
    int thread_pool_size,
469
    v8::TracingController* tracing_controller) {
470
  return MultiIsolatePlatform::Create(thread_pool_size,
471
                                      tracing_controller)
472
      .release();
473
}
474
475
void FreePlatform(MultiIsolatePlatform* platform) {
476
  delete platform;
477
}
478
479
7
std::unique_ptr<MultiIsolatePlatform> MultiIsolatePlatform::Create(
480
    int thread_pool_size,
481
    v8::TracingController* tracing_controller,
482
    v8::PageAllocator* page_allocator) {
483
14
  return std::make_unique<NodePlatform>(thread_pool_size,
484
                                        tracing_controller,
485
14
                                        page_allocator);
486
}
487
488
34906
MaybeLocal<Object> GetPerContextExports(Local<Context> context) {
489
34906
  Isolate* isolate = context->GetIsolate();
490
34906
  EscapableHandleScope handle_scope(isolate);
491
492
34906
  Local<Object> global = context->Global();
493
  Local<Private> key = Private::ForApi(isolate,
494
34906
      FIXED_ONE_BYTE_STRING(isolate, "node:per_context_binding_exports"));
495
496
  Local<Value> existing_value;
497
69812
  if (!global->GetPrivate(context, key).ToLocal(&existing_value))
498
    return MaybeLocal<Object>();
499
34906
  if (existing_value->IsObject())
500
34428
    return handle_scope.Escape(existing_value.As<Object>());
501
502
478
  Local<Object> exports = Object::New(isolate);
503

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

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

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

4755
  if (!primordials->SetPrototype(context, Null(isolate)).FromJust() ||
607

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

14532
}  // namespace node