GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_contextify.cc Lines: 591 646 91.5 %
Date: 2022-05-15 04:15:05 Branches: 297 464 64.0 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_contextify.h"
23
24
#include "base_object-inl.h"
25
#include "memory_tracker-inl.h"
26
#include "module_wrap.h"
27
#include "node_context_data.h"
28
#include "node_errors.h"
29
#include "node_external_reference.h"
30
#include "node_internals.h"
31
#include "node_watchdog.h"
32
#include "util-inl.h"
33
34
namespace node {
35
namespace contextify {
36
37
using errors::TryCatchScope;
38
39
using v8::Array;
40
using v8::ArrayBufferView;
41
using v8::Boolean;
42
using v8::Context;
43
using v8::EscapableHandleScope;
44
using v8::External;
45
using v8::Function;
46
using v8::FunctionCallbackInfo;
47
using v8::FunctionTemplate;
48
using v8::HandleScope;
49
using v8::IndexedPropertyHandlerConfiguration;
50
using v8::Int32;
51
using v8::Isolate;
52
using v8::Local;
53
using v8::Maybe;
54
using v8::MaybeLocal;
55
using v8::MeasureMemoryExecution;
56
using v8::MeasureMemoryMode;
57
using v8::MicrotaskQueue;
58
using v8::MicrotasksPolicy;
59
using v8::Name;
60
using v8::NamedPropertyHandlerConfiguration;
61
using v8::Number;
62
using v8::Object;
63
using v8::ObjectTemplate;
64
using v8::PrimitiveArray;
65
using v8::Promise;
66
using v8::PropertyAttribute;
67
using v8::PropertyCallbackInfo;
68
using v8::PropertyDescriptor;
69
using v8::PropertyHandlerFlags;
70
using v8::Script;
71
using v8::ScriptCompiler;
72
using v8::ScriptOrigin;
73
using v8::ScriptOrModule;
74
using v8::String;
75
using v8::Uint32;
76
using v8::UnboundScript;
77
using v8::Value;
78
using v8::WeakCallbackInfo;
79
using v8::WeakCallbackType;
80
81
// The vm module executes code in a sandboxed environment with a different
82
// global object than the rest of the code. This is achieved by applying
83
// every call that changes or queries a property on the global `this` in the
84
// sandboxed code, to the sandbox object.
85
//
86
// The implementation uses V8's interceptors for methods like `set`, `get`,
87
// `delete`, `defineProperty`, and for any query of the property attributes.
88
// Property handlers with interceptors are set on the object template for
89
// the sandboxed code. Handlers for both named properties and for indexed
90
// properties are used. Their functionality is almost identical, the indexed
91
// interceptors mostly just call the named interceptors.
92
//
93
// For every `get` of a global property in the sandboxed context, the
94
// interceptor callback checks the sandbox object for the property.
95
// If the property is defined on the sandbox, that result is returned to
96
// the original call instead of finishing the query on the global object.
97
//
98
// For every `set` of a global property, the interceptor callback defines or
99
// changes the property both on the sandbox and the global proxy.
100
101
namespace {
102
103
// Convert an int to a V8 Name (String or Symbol).
104
3
Local<Name> Uint32ToName(Local<Context> context, uint32_t index) {
105
6
  return Uint32::New(context->GetIsolate(), index)->ToString(context)
106
3
      .ToLocalChecked();
107
}
108
109
}  // anonymous namespace
110
111
610
ContextifyContext::ContextifyContext(
112
    Environment* env,
113
    Local<Object> sandbox_obj,
114
610
    const ContextOptions& options)
115
  : env_(env),
116
1220
    microtask_queue_wrap_(options.microtask_queue_wrap) {
117
610
  MaybeLocal<Context> v8_context = CreateV8Context(env, sandbox_obj, options);
118
119
  // Allocation failure, maximum call stack size reached, termination, etc.
120
610
  if (v8_context.IsEmpty()) return;
121
122
1220
  context_.Reset(env->isolate(), v8_context.ToLocalChecked());
123
610
  context_.SetWeak(this, WeakCallback, WeakCallbackType::kParameter);
124
610
  env->AddCleanupHook(CleanupHook, this);
125
}
126
127
128
503
ContextifyContext::~ContextifyContext() {
129
503
  env()->RemoveCleanupHook(CleanupHook, this);
130
503
  Isolate* isolate = env()->isolate();
131
1006
  HandleScope scope(isolate);
132
133
  env()->async_hooks()
134
503
    ->RemoveContext(PersistentToLocal::Weak(isolate, context_));
135
503
}
136
137
138
442
void ContextifyContext::CleanupHook(void* arg) {
139
442
  ContextifyContext* self = static_cast<ContextifyContext*>(arg);
140
442
  self->context_.Reset();
141
442
  delete self;
142
442
}
143
144
145
// This is an object that just keeps an internal pointer to this
146
// ContextifyContext.  It's passed to the NamedPropertyHandler.  If we
147
// pass the main JavaScript context object we're embedded in, then the
148
// NamedPropertyHandler will store a reference to it forever and keep it
149
// from getting gc'd.
150
610
MaybeLocal<Object> ContextifyContext::CreateDataWrapper(Environment* env) {
151
  Local<Object> wrapper;
152
610
  if (!env->script_data_constructor_function()
153
610
           ->NewInstance(env->context())
154
610
           .ToLocal(&wrapper)) {
155
    return MaybeLocal<Object>();
156
  }
157
158
610
  wrapper->SetAlignedPointerInInternalField(ContextifyContext::kSlot, this);
159
610
  return wrapper;
160
}
161
162
610
MaybeLocal<Context> ContextifyContext::CreateV8Context(
163
    Environment* env,
164
    Local<Object> sandbox_obj,
165
    const ContextOptions& options) {
166
610
  EscapableHandleScope scope(env->isolate());
167
  Local<FunctionTemplate> function_template =
168
610
      FunctionTemplate::New(env->isolate());
169
170
610
  function_template->SetClassName(sandbox_obj->GetConstructorName());
171
172
  Local<ObjectTemplate> object_template =
173
610
      function_template->InstanceTemplate();
174
175
  Local<Object> data_wrapper;
176
1220
  if (!CreateDataWrapper(env).ToLocal(&data_wrapper))
177
    return MaybeLocal<Context>();
178
179
  NamedPropertyHandlerConfiguration config(
180
      PropertyGetterCallback,
181
      PropertySetterCallback,
182
      PropertyDescriptorCallback,
183
      PropertyDeleterCallback,
184
      PropertyEnumeratorCallback,
185
      PropertyDefinerCallback,
186
      data_wrapper,
187
610
      PropertyHandlerFlags::kHasNoSideEffect);
188
189
  IndexedPropertyHandlerConfiguration indexed_config(
190
      IndexedPropertyGetterCallback,
191
      IndexedPropertySetterCallback,
192
      IndexedPropertyDescriptorCallback,
193
      IndexedPropertyDeleterCallback,
194
      PropertyEnumeratorCallback,
195
      IndexedPropertyDefinerCallback,
196
      data_wrapper,
197
610
      PropertyHandlerFlags::kHasNoSideEffect);
198
199
610
  object_template->SetHandler(config);
200
610
  object_template->SetHandler(indexed_config);
201
  Local<Context> ctx = Context::New(
202
      env->isolate(),
203
      nullptr,  // extensions
204
      object_template,
205
      {},       // global object
206
      {},       // deserialization callback
207
1220
      microtask_queue() ?
208
615
          microtask_queue().get() :
209

1830
          env->isolate()->GetCurrentContext()->GetMicrotaskQueue());
210
610
  if (ctx.IsEmpty()) return MaybeLocal<Context>();
211
  // Only partially initialize the context - the primordials are left out
212
  // and only initialized when necessary.
213
1220
  if (InitializeContextRuntime(ctx).IsNothing()) {
214
    return MaybeLocal<Context>();
215
  }
216
217
610
  if (ctx.IsEmpty()) {
218
    return MaybeLocal<Context>();
219
  }
220
221
610
  Local<Context> context = env->context();
222
610
  ctx->SetSecurityToken(context->GetSecurityToken());
223
224
  // We need to tie the lifetime of the sandbox object with the lifetime of
225
  // newly created context. We do this by making them hold references to each
226
  // other. The context can directly hold a reference to the sandbox as an
227
  // embedder data field. However, we cannot hold a reference to a v8::Context
228
  // directly in an Object, we instead hold onto the new context's global
229
  // object instead (which then has a reference to the context).
230
610
  ctx->SetEmbedderData(ContextEmbedderIndex::kSandboxObject, sandbox_obj);
231
  sandbox_obj->SetPrivate(context,
232
                          env->contextify_global_private_symbol(),
233
1220
                          ctx->Global());
234
235
1220
  Utf8Value name_val(env->isolate(), options.name);
236
610
  ctx->AllowCodeGenerationFromStrings(options.allow_code_gen_strings->IsTrue());
237
610
  ctx->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
238
                       options.allow_code_gen_wasm);
239
240
1220
  ContextInfo info(*name_val);
241
242
610
  if (!options.origin.IsEmpty()) {
243
4
    Utf8Value origin_val(env->isolate(), options.origin);
244
2
    info.origin = *origin_val;
245
  }
246
247
610
  env->AssignToContext(ctx, info);
248
249
610
  return scope.Escape(ctx);
250
}
251
252
253
852
void ContextifyContext::Init(Environment* env, Local<Object> target) {
254
  Local<FunctionTemplate> function_template =
255
852
      FunctionTemplate::New(env->isolate());
256
1704
  function_template->InstanceTemplate()->SetInternalFieldCount(
257
      ContextifyContext::kInternalFieldCount);
258
852
  env->set_script_data_constructor_function(
259
852
      function_template->GetFunction(env->context()).ToLocalChecked());
260
261
852
  env->SetMethod(target, "makeContext", MakeContext);
262
852
  env->SetMethod(target, "isContext", IsContext);
263
852
  env->SetMethod(target, "compileFunction", CompileFunction);
264
852
}
265
266
5179
void ContextifyContext::RegisterExternalReferences(
267
    ExternalReferenceRegistry* registry) {
268
5179
  registry->Register(MakeContext);
269
5179
  registry->Register(IsContext);
270
5179
  registry->Register(CompileFunction);
271
5179
}
272
273
// makeContext(sandbox, name, origin, strings, wasm);
274
610
void ContextifyContext::MakeContext(const FunctionCallbackInfo<Value>& args) {
275
610
  Environment* env = Environment::GetCurrent(args);
276
277
610
  CHECK_EQ(args.Length(), 6);
278
610
  CHECK(args[0]->IsObject());
279
1220
  Local<Object> sandbox = args[0].As<Object>();
280
281
  // Don't allow contextifying a sandbox multiple times.
282
1220
  CHECK(
283
      !sandbox->HasPrivate(
284
          env->context(),
285
          env->contextify_context_private_symbol()).FromJust());
286
287
610
  ContextOptions options;
288
289
1220
  CHECK(args[1]->IsString());
290
1220
  options.name = args[1].As<String>();
291
292

2436
  CHECK(args[2]->IsString() || args[2]->IsUndefined());
293
1220
  if (args[2]->IsString()) {
294
4
    options.origin = args[2].As<String>();
295
  }
296
297
610
  CHECK(args[3]->IsBoolean());
298
1220
  options.allow_code_gen_strings = args[3].As<Boolean>();
299
300
610
  CHECK(args[4]->IsBoolean());
301
1220
  options.allow_code_gen_wasm = args[4].As<Boolean>();
302
303
610
  if (args[5]->IsObject() &&
304

620
      !env->microtask_queue_ctor_template().IsEmpty() &&
305

625
      env->microtask_queue_ctor_template()->HasInstance(args[5])) {
306
5
    options.microtask_queue_wrap.reset(
307
10
        Unwrap<MicrotaskQueueWrap>(args[5].As<Object>()));
308
  }
309
310
610
  TryCatchScope try_catch(env);
311
  std::unique_ptr<ContextifyContext> context_ptr =
312
610
      std::make_unique<ContextifyContext>(env, sandbox, options);
313
314
610
  if (try_catch.HasCaught()) {
315
    if (!try_catch.HasTerminated())
316
      try_catch.ReThrow();
317
    return;
318
  }
319
320
1220
  if (context_ptr->context().IsEmpty())
321
    return;
322
323
  sandbox->SetPrivate(
324
      env->context(),
325
      env->contextify_context_private_symbol(),
326
1220
      External::New(env->isolate(), context_ptr.release()));
327
}
328
329
330
2053
void ContextifyContext::IsContext(const FunctionCallbackInfo<Value>& args) {
331
2053
  Environment* env = Environment::GetCurrent(args);
332
333
2053
  CHECK(args[0]->IsObject());
334
4106
  Local<Object> sandbox = args[0].As<Object>();
335
336
  Maybe<bool> result =
337
      sandbox->HasPrivate(env->context(),
338
2053
                          env->contextify_context_private_symbol());
339
4106
  args.GetReturnValue().Set(result.FromJust());
340
2053
}
341
342
343
61
void ContextifyContext::WeakCallback(
344
    const WeakCallbackInfo<ContextifyContext>& data) {
345
61
  ContextifyContext* context = data.GetParameter();
346
61
  delete context;
347
61
}
348
349
// static
350
1385
ContextifyContext* ContextifyContext::ContextFromContextifiedSandbox(
351
    Environment* env,
352
    const Local<Object>& sandbox) {
353
  MaybeLocal<Value> maybe_value =
354
      sandbox->GetPrivate(env->context(),
355
1385
                          env->contextify_context_private_symbol());
356
  Local<Value> context_external_v;
357

2770
  if (maybe_value.ToLocal(&context_external_v) &&
358
1385
      context_external_v->IsExternal()) {
359
1385
    Local<External> context_external = context_external_v.As<External>();
360
1385
    return static_cast<ContextifyContext*>(context_external->Value());
361
  }
362
  return nullptr;
363
}
364
365
// static
366
template <typename T>
367
2096696
ContextifyContext* ContextifyContext::Get(const PropertyCallbackInfo<T>& args) {
368
2096696
  Local<Value> data = args.Data();
369
  return static_cast<ContextifyContext*>(
370
4193392
      data.As<Object>()->GetAlignedPointerFromInternalField(
371
2096696
          ContextifyContext::kSlot));
372
}
373
374
// static
375
1047875
void ContextifyContext::PropertyGetterCallback(
376
    Local<Name> property,
377
    const PropertyCallbackInfo<Value>& args) {
378
1047875
  ContextifyContext* ctx = ContextifyContext::Get(args);
379
380
  // Still initializing
381
1047875
  if (ctx->context_.IsEmpty())
382
2440
    return;
383
384
1045435
  Local<Context> context = ctx->context();
385
1045435
  Local<Object> sandbox = ctx->sandbox();
386
  MaybeLocal<Value> maybe_rv =
387
1045435
      sandbox->GetRealNamedProperty(context, property);
388
1045435
  if (maybe_rv.IsEmpty()) {
389
    maybe_rv =
390
82702
        ctx->global_proxy()->GetRealNamedProperty(context, property);
391
  }
392
393
  Local<Value> rv;
394
1045435
  if (maybe_rv.ToLocal(&rv)) {
395
1045366
    if (rv == sandbox)
396
10
      rv = ctx->global_proxy();
397
398
2090732
    args.GetReturnValue().Set(rv);
399
  }
400
}
401
402
// static
403
150
void ContextifyContext::PropertySetterCallback(
404
    Local<Name> property,
405
    Local<Value> value,
406
    const PropertyCallbackInfo<Value>& args) {
407
150
  ContextifyContext* ctx = ContextifyContext::Get(args);
408
409
  // Still initializing
410
150
  if (ctx->context_.IsEmpty())
411
14
    return;
412
413
150
  Local<Context> context = ctx->context();
414
150
  PropertyAttribute attributes = PropertyAttribute::None;
415
150
  bool is_declared_on_global_proxy = ctx->global_proxy()
416
150
      ->GetRealNamedPropertyAttributes(context, property)
417
150
      .To(&attributes);
418
150
  bool read_only =
419
150
      static_cast<int>(attributes) &
420
      static_cast<int>(PropertyAttribute::ReadOnly);
421
422
150
  bool is_declared_on_sandbox = ctx->sandbox()
423
150
      ->GetRealNamedPropertyAttributes(context, property)
424
150
      .To(&attributes);
425
296
  read_only = read_only ||
426
146
      (static_cast<int>(attributes) &
427
      static_cast<int>(PropertyAttribute::ReadOnly));
428
429
150
  if (read_only)
430
13
    return;
431
432
  // true for x = 5
433
  // false for this.x = 5
434
  // false for Object.defineProperty(this, 'foo', ...)
435
  // false for vmResult.x = 5 where vmResult = vm.runInContext();
436
274
  bool is_contextual_store = ctx->global_proxy() != args.This();
437
438
  // Indicator to not return before setting (undeclared) function declarations
439
  // on the sandbox in strict mode, i.e. args.ShouldThrowOnError() = true.
440
  // True for 'function f() {}', 'this.f = function() {}',
441
  // 'var f = function()'.
442
  // In effect only for 'function f() {}' because
443
  // var f = function(), is_declared = true
444
  // this.f = function() {}, is_contextual_store = false.
445
137
  bool is_function = value->IsFunction();
446
447

137
  bool is_declared = is_declared_on_global_proxy || is_declared_on_sandbox;
448


228
  if (!is_declared && args.ShouldThrowOnError() && is_contextual_store &&
449
30
      !is_function)
450
1
    return;
451
452
272
  USE(ctx->sandbox()->Set(context, property, value));
453
272
  args.GetReturnValue().Set(value);
454
}
455
456
// static
457
55
void ContextifyContext::PropertyDescriptorCallback(
458
    Local<Name> property,
459
    const PropertyCallbackInfo<Value>& args) {
460
55
  ContextifyContext* ctx = ContextifyContext::Get(args);
461
462
  // Still initializing
463
55
  if (ctx->context_.IsEmpty())
464
    return;
465
466
55
  Local<Context> context = ctx->context();
467
468
55
  Local<Object> sandbox = ctx->sandbox();
469
470

110
  if (sandbox->HasOwnProperty(context, property).FromMaybe(false)) {
471
    Local<Value> desc;
472
78
    if (sandbox->GetOwnPropertyDescriptor(context, property).ToLocal(&desc)) {
473
78
      args.GetReturnValue().Set(desc);
474
    }
475
  }
476
}
477
478
// static
479
15
void ContextifyContext::PropertyDefinerCallback(
480
    Local<Name> property,
481
    const PropertyDescriptor& desc,
482
    const PropertyCallbackInfo<Value>& args) {
483
15
  ContextifyContext* ctx = ContextifyContext::Get(args);
484
485
  // Still initializing
486
15
  if (ctx->context_.IsEmpty())
487
    return;
488
489
15
  Local<Context> context = ctx->context();
490
15
  Isolate* isolate = context->GetIsolate();
491
492
15
  PropertyAttribute attributes = PropertyAttribute::None;
493
  bool is_declared =
494
15
      ctx->global_proxy()->GetRealNamedPropertyAttributes(context,
495
15
                                                          property)
496
15
          .To(&attributes);
497
15
  bool read_only =
498
15
      static_cast<int>(attributes) &
499
          static_cast<int>(PropertyAttribute::ReadOnly);
500
501
  // If the property is set on the global as read_only, don't change it on
502
  // the global or sandbox.
503

15
  if (is_declared && read_only)
504
    return;
505
506
15
  Local<Object> sandbox = ctx->sandbox();
507
508
  auto define_prop_on_sandbox =
509
15
      [&] (PropertyDescriptor* desc_for_sandbox) {
510
15
        if (desc.has_enumerable()) {
511
2
          desc_for_sandbox->set_enumerable(desc.enumerable());
512
        }
513
15
        if (desc.has_configurable()) {
514
1
          desc_for_sandbox->set_configurable(desc.configurable());
515
        }
516
        // Set the property on the sandbox.
517
15
        USE(sandbox->DefineProperty(context, property, *desc_for_sandbox));
518
30
      };
519
520

15
  if (desc.has_get() || desc.has_set()) {
521
    PropertyDescriptor desc_for_sandbox(
522
15
        desc.has_get() ? desc.get() : Undefined(isolate).As<Value>(),
523

23
        desc.has_set() ? desc.set() : Undefined(isolate).As<Value>());
524
525
5
    define_prop_on_sandbox(&desc_for_sandbox);
526
  } else {
527
    Local<Value> value =
528
12
        desc.has_value() ? desc.value() : Undefined(isolate).As<Value>();
529
530
10
    if (desc.has_writable()) {
531
      PropertyDescriptor desc_for_sandbox(value, desc.writable());
532
      define_prop_on_sandbox(&desc_for_sandbox);
533
    } else {
534
20
      PropertyDescriptor desc_for_sandbox(value);
535
10
      define_prop_on_sandbox(&desc_for_sandbox);
536
    }
537
  }
538
}
539
540
// static
541
2
void ContextifyContext::PropertyDeleterCallback(
542
    Local<Name> property,
543
    const PropertyCallbackInfo<Boolean>& args) {
544
2
  ContextifyContext* ctx = ContextifyContext::Get(args);
545
546
  // Still initializing
547
2
  if (ctx->context_.IsEmpty())
548
1
    return;
549
550
4
  Maybe<bool> success = ctx->sandbox()->Delete(ctx->context(), property);
551
552

4
  if (success.FromMaybe(false))
553
1
    return;
554
555
  // Delete failed on the sandbox, intercept and do not delete on
556
  // the global object.
557
2
  args.GetReturnValue().Set(false);
558
}
559
560
// static
561
248
void ContextifyContext::PropertyEnumeratorCallback(
562
    const PropertyCallbackInfo<Array>& args) {
563
248
  ContextifyContext* ctx = ContextifyContext::Get(args);
564
565
  // Still initializing
566
248
  if (ctx->context_.IsEmpty())
567
    return;
568
569
  Local<Array> properties;
570
571
744
  if (!ctx->sandbox()->GetPropertyNames(ctx->context()).ToLocal(&properties))
572
    return;
573
574
496
  args.GetReturnValue().Set(properties);
575
}
576
577
// static
578
void ContextifyContext::IndexedPropertyGetterCallback(
579
    uint32_t index,
580
    const PropertyCallbackInfo<Value>& args) {
581
  ContextifyContext* ctx = ContextifyContext::Get(args);
582
583
  // Still initializing
584
  if (ctx->context_.IsEmpty())
585
    return;
586
587
  ContextifyContext::PropertyGetterCallback(
588
      Uint32ToName(ctx->context(), index), args);
589
}
590
591
592
1
void ContextifyContext::IndexedPropertySetterCallback(
593
    uint32_t index,
594
    Local<Value> value,
595
    const PropertyCallbackInfo<Value>& args) {
596
1
  ContextifyContext* ctx = ContextifyContext::Get(args);
597
598
  // Still initializing
599
1
  if (ctx->context_.IsEmpty())
600
    return;
601
602
1
  ContextifyContext::PropertySetterCallback(
603
      Uint32ToName(ctx->context(), index), value, args);
604
}
605
606
// static
607
1
void ContextifyContext::IndexedPropertyDescriptorCallback(
608
    uint32_t index,
609
    const PropertyCallbackInfo<Value>& args) {
610
1
  ContextifyContext* ctx = ContextifyContext::Get(args);
611
612
  // Still initializing
613
1
  if (ctx->context_.IsEmpty())
614
    return;
615
616
1
  ContextifyContext::PropertyDescriptorCallback(
617
      Uint32ToName(ctx->context(), index), args);
618
}
619
620
621
1
void ContextifyContext::IndexedPropertyDefinerCallback(
622
    uint32_t index,
623
    const PropertyDescriptor& desc,
624
    const PropertyCallbackInfo<Value>& args) {
625
1
  ContextifyContext* ctx = ContextifyContext::Get(args);
626
627
  // Still initializing
628
1
  if (ctx->context_.IsEmpty())
629
    return;
630
631
1
  ContextifyContext::PropertyDefinerCallback(
632
      Uint32ToName(ctx->context(), index), desc, args);
633
}
634
635
// static
636
void ContextifyContext::IndexedPropertyDeleterCallback(
637
    uint32_t index,
638
    const PropertyCallbackInfo<Boolean>& args) {
639
  ContextifyContext* ctx = ContextifyContext::Get(args);
640
641
  // Still initializing
642
  if (ctx->context_.IsEmpty())
643
    return;
644
645
  Maybe<bool> success = ctx->sandbox()->Delete(ctx->context(), index);
646
647
  if (success.FromMaybe(false))
648
    return;
649
650
  // Delete failed on the sandbox, intercept and do not delete on
651
  // the global object.
652
  args.GetReturnValue().Set(false);
653
}
654
655
852
void ContextifyScript::Init(Environment* env, Local<Object> target) {
656
1704
  HandleScope scope(env->isolate());
657
  Local<String> class_name =
658
852
      FIXED_ONE_BYTE_STRING(env->isolate(), "ContextifyScript");
659
660
852
  Local<FunctionTemplate> script_tmpl = env->NewFunctionTemplate(New);
661
1704
  script_tmpl->InstanceTemplate()->SetInternalFieldCount(
662
      ContextifyScript::kInternalFieldCount);
663
852
  script_tmpl->SetClassName(class_name);
664
852
  env->SetProtoMethod(script_tmpl, "createCachedData", CreateCachedData);
665
852
  env->SetProtoMethod(script_tmpl, "runInContext", RunInContext);
666
852
  env->SetProtoMethod(script_tmpl, "runInThisContext", RunInThisContext);
667
668
852
  Local<Context> context = env->context();
669
670
852
  target->Set(context, class_name,
671
1704
      script_tmpl->GetFunction(context).ToLocalChecked()).Check();
672
852
  env->set_script_context_constructor_template(script_tmpl);
673
852
}
674
675
5179
void ContextifyScript::RegisterExternalReferences(
676
    ExternalReferenceRegistry* registry) {
677
5179
  registry->Register(New);
678
5179
  registry->Register(CreateCachedData);
679
5179
  registry->Register(RunInContext);
680
5179
  registry->Register(RunInThisContext);
681
5179
}
682
683
3630
void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
684
3630
  Environment* env = Environment::GetCurrent(args);
685
3630
  Isolate* isolate = env->isolate();
686
3630
  Local<Context> context = env->context();
687
688
3630
  CHECK(args.IsConstructCall());
689
690
3630
  const int argc = args.Length();
691
3630
  CHECK_GE(argc, 2);
692
693
7260
  CHECK(args[0]->IsString());
694
7260
  Local<String> code = args[0].As<String>();
695
696
7260
  CHECK(args[1]->IsString());
697
3630
  Local<String> filename = args[1].As<String>();
698
699
3630
  int line_offset = 0;
700
3630
  int column_offset = 0;
701
  Local<ArrayBufferView> cached_data_buf;
702
3630
  bool produce_cached_data = false;
703
3630
  Local<Context> parsing_context = context;
704
705
3630
  if (argc > 2) {
706
    // new ContextifyScript(code, filename, lineOffset, columnOffset,
707
    //                      cachedData, produceCachedData, parsingContext)
708
3630
    CHECK_EQ(argc, 7);
709
3630
    CHECK(args[2]->IsNumber());
710
7260
    line_offset = args[2].As<Int32>()->Value();
711
3630
    CHECK(args[3]->IsNumber());
712
7260
    column_offset = args[3].As<Int32>()->Value();
713
7260
    if (!args[4]->IsUndefined()) {
714
23
      CHECK(args[4]->IsArrayBufferView());
715
46
      cached_data_buf = args[4].As<ArrayBufferView>();
716
    }
717
3630
    CHECK(args[5]->IsBoolean());
718
3630
    produce_cached_data = args[5]->IsTrue();
719
7260
    if (!args[6]->IsUndefined()) {
720
506
      CHECK(args[6]->IsObject());
721
      ContextifyContext* sandbox =
722
506
          ContextifyContext::ContextFromContextifiedSandbox(
723
1012
              env, args[6].As<Object>());
724
506
      CHECK_NOT_NULL(sandbox);
725
506
      parsing_context = sandbox->context();
726
    }
727
  }
728
729
  ContextifyScript* contextify_script =
730
3630
      new ContextifyScript(env, args.This());
731
732
3630
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
733
3630
          TRACING_CATEGORY_NODE2(vm, script)) != 0) {
734
14
    Utf8Value fn(isolate, filename);
735

14
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
736
        TRACING_CATEGORY_NODE2(vm, script),
737
        "ContextifyScript::New",
738
        contextify_script,
739
        "filename", TRACE_STR_COPY(*fn));
740
  }
741
742
3630
  ScriptCompiler::CachedData* cached_data = nullptr;
743
3630
  if (!cached_data_buf.IsEmpty()) {
744
    uint8_t* data = static_cast<uint8_t*>(
745
46
        cached_data_buf->Buffer()->GetBackingStore()->Data());
746
23
    cached_data = new ScriptCompiler::CachedData(
747
23
        data + cached_data_buf->ByteOffset(), cached_data_buf->ByteLength());
748
  }
749
750
  Local<PrimitiveArray> host_defined_options =
751
3630
      PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
752
7260
  host_defined_options->Set(isolate, loader::HostDefinedOptions::kType,
753
                            Number::New(isolate, loader::ScriptType::kScript));
754
7260
  host_defined_options->Set(isolate, loader::HostDefinedOptions::kID,
755
3630
                            Number::New(isolate, contextify_script->id()));
756
757
  ScriptOrigin origin(isolate,
758
                      filename,
759
                      line_offset,                          // line offset
760
                      column_offset,                        // column offset
761
                      true,                                 // is cross origin
762
                      -1,                                   // script id
763
                      Local<Value>(),                       // source map URL
764
                      false,                                // is opaque (?)
765
                      false,                                // is WASM
766
                      false,                                // is ES Module
767
7260
                      host_defined_options);
768
3630
  ScriptCompiler::Source source(code, origin, cached_data);
769
3630
  ScriptCompiler::CompileOptions compile_options =
770
      ScriptCompiler::kNoCompileOptions;
771
772
3630
  if (source.GetCachedData() != nullptr)
773
23
    compile_options = ScriptCompiler::kConsumeCodeCache;
774
775
3630
  TryCatchScope try_catch(env);
776
3630
  ShouldNotAbortOnUncaughtScope no_abort_scope(env);
777
3630
  Context::Scope scope(parsing_context);
778
779
  MaybeLocal<UnboundScript> v8_script = ScriptCompiler::CompileUnboundScript(
780
      isolate,
781
      &source,
782
3630
      compile_options);
783
784
3630
  if (v8_script.IsEmpty()) {
785
193
    errors::DecorateErrorStack(env, try_catch);
786
193
    no_abort_scope.Close();
787
193
    if (!try_catch.HasTerminated())
788
193
      try_catch.ReThrow();
789

221
    TRACE_EVENT_NESTABLE_ASYNC_END0(
790
        TRACING_CATEGORY_NODE2(vm, script),
791
        "ContextifyScript::New",
792
        contextify_script);
793
193
    return;
794
  }
795
6874
  contextify_script->script_.Reset(isolate, v8_script.ToLocalChecked());
796
797
3437
  Local<Context> env_context = env->context();
798
3437
  if (compile_options == ScriptCompiler::kConsumeCodeCache) {
799
23
    args.This()->Set(
800
        env_context,
801
        env->cached_data_rejected_string(),
802
92
        Boolean::New(isolate, source.GetCachedData()->rejected)).Check();
803
3414
  } else if (produce_cached_data) {
804
    std::unique_ptr<ScriptCompiler::CachedData> cached_data {
805
6
      ScriptCompiler::CreateCodeCache(v8_script.ToLocalChecked()) };
806
6
    bool cached_data_produced = cached_data != nullptr;
807
6
    if (cached_data_produced) {
808
      MaybeLocal<Object> buf = Buffer::Copy(
809
          env,
810
12
          reinterpret_cast<const char*>(cached_data->data),
811
6
          cached_data->length);
812
6
      args.This()->Set(env_context,
813
                       env->cached_data_string(),
814
24
                       buf.ToLocalChecked()).Check();
815
    }
816
6
    args.This()->Set(
817
        env_context,
818
        env->cached_data_produced_string(),
819
24
        Boolean::New(isolate, cached_data_produced)).Check();
820
  }
821

4179
  TRACE_EVENT_NESTABLE_ASYNC_END0(
822
      TRACING_CATEGORY_NODE2(vm, script),
823
      "ContextifyScript::New",
824
      contextify_script);
825
}
826
827
3415
bool ContextifyScript::InstanceOf(Environment* env,
828
                                  const Local<Value>& value) {
829

6830
  return !value.IsEmpty() &&
830
10245
         env->script_context_constructor_template()->HasInstance(value);
831
}
832
833
11
void ContextifyScript::CreateCachedData(
834
    const FunctionCallbackInfo<Value>& args) {
835
11
  Environment* env = Environment::GetCurrent(args);
836
  ContextifyScript* wrapped_script;
837
11
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder());
838
  Local<UnboundScript> unbound_script =
839
11
      PersistentToLocal::Default(env->isolate(), wrapped_script->script_);
840
  std::unique_ptr<ScriptCompiler::CachedData> cached_data(
841
22
      ScriptCompiler::CreateCodeCache(unbound_script));
842
11
  if (!cached_data) {
843
    args.GetReturnValue().Set(Buffer::New(env, 0).ToLocalChecked());
844
  } else {
845
    MaybeLocal<Object> buf = Buffer::Copy(
846
        env,
847
22
        reinterpret_cast<const char*>(cached_data->data),
848
11
        cached_data->length);
849
22
    args.GetReturnValue().Set(buf.ToLocalChecked());
850
  }
851
}
852
853
2565
void ContextifyScript::RunInThisContext(
854
    const FunctionCallbackInfo<Value>& args) {
855
2565
  Environment* env = Environment::GetCurrent(args);
856
857
  ContextifyScript* wrapped_script;
858
2565
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder());
859
860

3135
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
861
      TRACING_CATEGORY_NODE2(vm, script), "RunInThisContext", wrapped_script);
862
863
  // TODO(addaleax): Use an options object or otherwise merge this with
864
  // RunInContext().
865
2565
  CHECK_EQ(args.Length(), 4);
866
867
2565
  CHECK(args[0]->IsNumber());
868
5130
  int64_t timeout = args[0]->IntegerValue(env->context()).FromJust();
869
870
2565
  CHECK(args[1]->IsBoolean());
871
2565
  bool display_errors = args[1]->IsTrue();
872
873
2565
  CHECK(args[2]->IsBoolean());
874
2565
  bool break_on_sigint = args[2]->IsTrue();
875
876
2565
  CHECK(args[3]->IsBoolean());
877
2565
  bool break_on_first_line = args[3]->IsTrue();
878
879
  // Do the eval within this context
880
2565
  EvalMachine(env,
881
              timeout,
882
              display_errors,
883
              break_on_sigint,
884
              break_on_first_line,
885
              nullptr,  // microtask_queue
886
              args);
887
888

3106
  TRACE_EVENT_NESTABLE_ASYNC_END0(
889
      TRACING_CATEGORY_NODE2(vm, script), "RunInThisContext", wrapped_script);
890
}
891
892
850
void ContextifyScript::RunInContext(const FunctionCallbackInfo<Value>& args) {
893
850
  Environment* env = Environment::GetCurrent(args);
894
895
  ContextifyScript* wrapped_script;
896
850
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder());
897
898
850
  CHECK_EQ(args.Length(), 5);
899
900
850
  CHECK(args[0]->IsObject());
901
850
  Local<Object> sandbox = args[0].As<Object>();
902
  // Get the context from the sandbox
903
  ContextifyContext* contextify_context =
904
850
      ContextifyContext::ContextFromContextifiedSandbox(env, sandbox);
905
850
  CHECK_NOT_NULL(contextify_context);
906
907
850
  Local<Context> context = contextify_context->context();
908
850
  if (context.IsEmpty())
909
    return;
910
911

1080
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
912
      TRACING_CATEGORY_NODE2(vm, script), "RunInContext", wrapped_script);
913
914
850
  CHECK(args[1]->IsNumber());
915
1700
  int64_t timeout = args[1]->IntegerValue(env->context()).FromJust();
916
917
850
  CHECK(args[2]->IsBoolean());
918
850
  bool display_errors = args[2]->IsTrue();
919
920
850
  CHECK(args[3]->IsBoolean());
921
850
  bool break_on_sigint = args[3]->IsTrue();
922
923
850
  CHECK(args[4]->IsBoolean());
924
850
  bool break_on_first_line = args[4]->IsTrue();
925
926
  // Do the eval within the context
927
850
  Context::Scope context_scope(context);
928
850
  EvalMachine(contextify_context->env(),
929
              timeout,
930
              display_errors,
931
              break_on_sigint,
932
              break_on_first_line,
933
1700
              contextify_context->microtask_queue(),
934
              args);
935
936

1080
  TRACE_EVENT_NESTABLE_ASYNC_END0(
937
      TRACING_CATEGORY_NODE2(vm, script), "RunInContext", wrapped_script);
938
}
939
940
3415
bool ContextifyScript::EvalMachine(Environment* env,
941
                                   const int64_t timeout,
942
                                   const bool display_errors,
943
                                   const bool break_on_sigint,
944
                                   const bool break_on_first_line,
945
                                   std::shared_ptr<MicrotaskQueue> mtask_queue,
946
                                   const FunctionCallbackInfo<Value>& args) {
947
3415
  if (!env->can_call_into_js())
948
    return false;
949
3415
  if (!ContextifyScript::InstanceOf(env, args.Holder())) {
950
    THROW_ERR_INVALID_THIS(
951
        env,
952
        "Script methods can only be called on script instances.");
953
    return false;
954
  }
955
6814
  TryCatchScope try_catch(env);
956
6814
  Isolate::SafeForTerminationScope safe_for_termination(env->isolate());
957
  ContextifyScript* wrapped_script;
958
3415
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder(), false);
959
  Local<UnboundScript> unbound_script =
960
3415
      PersistentToLocal::Default(env->isolate(), wrapped_script->script_);
961
3415
  Local<Script> script = unbound_script->BindToCurrentContext();
962
963
#if HAVE_INSPECTOR
964
3415
  if (break_on_first_line) {
965
10
    env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start");
966
  }
967
#endif
968
969
  MaybeLocal<Value> result;
970
3415
  bool timed_out = false;
971
3415
  bool received_signal = false;
972
3415
  auto run = [&]() {
973
3415
    MaybeLocal<Value> result = script->Run(env->context());
974

3399
    if (!result.IsEmpty() && mtask_queue)
975
2
      mtask_queue->PerformCheckpoint(env->isolate());
976
3399
    return result;
977
3415
  };
978

3415
  if (break_on_sigint && timeout != -1) {
979
    Watchdog wd(env->isolate(), timeout, &timed_out);
980
    SigintWatchdog swd(env->isolate(), &received_signal);
981
    result = run();
982
3415
  } else if (break_on_sigint) {
983
381
    SigintWatchdog swd(env->isolate(), &received_signal);
984
192
    result = run();
985
3223
  } else if (timeout != -1) {
986
30
    Watchdog wd(env->isolate(), timeout, &timed_out);
987
15
    result = run();
988
  } else {
989
3208
    result = run();
990
  }
991
992
  // Convert the termination exception into a regular exception.
993

3399
  if (timed_out || received_signal) {
994

21
    if (!env->is_main_thread() && env->is_stopping())
995
      return false;
996
21
    env->isolate()->CancelTerminateExecution();
997
    // It is possible that execution was terminated by another timeout in
998
    // which this timeout is nested, so check whether one of the watchdogs
999
    // from this invocation is responsible for termination.
1000
21
    if (timed_out) {
1001
10
      node::THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, timeout);
1002
11
    } else if (received_signal) {
1003
11
      node::THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED(env);
1004
    }
1005
  }
1006
1007
3399
  if (try_catch.HasCaught()) {
1008

167
    if (!timed_out && !received_signal && display_errors) {
1009
      // We should decorate non-termination exceptions
1010
95
      errors::DecorateErrorStack(env, try_catch);
1011
    }
1012
1013
    // If there was an exception thrown during script execution, re-throw it.
1014
    // If one of the above checks threw, re-throw the exception instead of
1015
    // letting try_catch catch it.
1016
    // If execution has been terminated, but not by one of the watchdogs from
1017
    // this invocation, this will re-throw a `null` value.
1018
167
    if (!try_catch.HasTerminated())
1019
164
      try_catch.ReThrow();
1020
1021
167
    return false;
1022
  }
1023
1024
3232
  args.GetReturnValue().Set(result.ToLocalChecked());
1025
3232
  return true;
1026
}
1027
1028
1029
3630
ContextifyScript::ContextifyScript(Environment* env, Local<Object> object)
1030
    : BaseObject(env, object),
1031
3630
      id_(env->get_next_script_id()) {
1032
3630
  MakeWeak();
1033
3630
  env->id_to_script_map.emplace(id_, this);
1034
3630
}
1035
1036
1037
21360
ContextifyScript::~ContextifyScript() {
1038
7120
  env()->id_to_script_map.erase(id_);
1039
14240
}
1040
1041
1042
34083
void ContextifyContext::CompileFunction(
1043
    const FunctionCallbackInfo<Value>& args) {
1044
34083
  Environment* env = Environment::GetCurrent(args);
1045
34083
  Isolate* isolate = env->isolate();
1046
34083
  Local<Context> context = env->context();
1047
1048
  // Argument 1: source code
1049
68166
  CHECK(args[0]->IsString());
1050
68166
  Local<String> code = args[0].As<String>();
1051
1052
  // Argument 2: filename
1053
68166
  CHECK(args[1]->IsString());
1054
68166
  Local<String> filename = args[1].As<String>();
1055
1056
  // Argument 3: line offset
1057
34083
  CHECK(args[2]->IsNumber());
1058
68166
  int line_offset = args[2].As<Int32>()->Value();
1059
1060
  // Argument 4: column offset
1061
34083
  CHECK(args[3]->IsNumber());
1062
68166
  int column_offset = args[3].As<Int32>()->Value();
1063
1064
  // Argument 5: cached data (optional)
1065
  Local<ArrayBufferView> cached_data_buf;
1066
68166
  if (!args[4]->IsUndefined()) {
1067
    CHECK(args[4]->IsArrayBufferView());
1068
    cached_data_buf = args[4].As<ArrayBufferView>();
1069
  }
1070
1071
  // Argument 6: produce cache data
1072
34083
  CHECK(args[5]->IsBoolean());
1073
34083
  bool produce_cached_data = args[5]->IsTrue();
1074
1075
  // Argument 7: parsing context (optional)
1076
  Local<Context> parsing_context;
1077
68166
  if (!args[6]->IsUndefined()) {
1078
2
    CHECK(args[6]->IsObject());
1079
    ContextifyContext* sandbox =
1080
2
        ContextifyContext::ContextFromContextifiedSandbox(
1081
4
            env, args[6].As<Object>());
1082
2
    CHECK_NOT_NULL(sandbox);
1083
2
    parsing_context = sandbox->context();
1084
  } else {
1085
34081
    parsing_context = context;
1086
  }
1087
1088
  // Argument 8: context extensions (optional)
1089
  Local<Array> context_extensions_buf;
1090
68166
  if (!args[7]->IsUndefined()) {
1091
34083
    CHECK(args[7]->IsArray());
1092
68166
    context_extensions_buf = args[7].As<Array>();
1093
  }
1094
1095
  // Argument 9: params for the function (optional)
1096
  Local<Array> params_buf;
1097
68166
  if (!args[8]->IsUndefined()) {
1098
34076
    CHECK(args[8]->IsArray());
1099
68152
    params_buf = args[8].As<Array>();
1100
  }
1101
1102
  // Read cache from cached data buffer
1103
34083
  ScriptCompiler::CachedData* cached_data = nullptr;
1104
34083
  if (!cached_data_buf.IsEmpty()) {
1105
    uint8_t* data = static_cast<uint8_t*>(
1106
        cached_data_buf->Buffer()->GetBackingStore()->Data());
1107
    cached_data = new ScriptCompiler::CachedData(
1108
      data + cached_data_buf->ByteOffset(), cached_data_buf->ByteLength());
1109
  }
1110
1111
  // Get the function id
1112
34083
  uint32_t id = env->get_next_function_id();
1113
1114
  // Set host_defined_options
1115
  Local<PrimitiveArray> host_defined_options =
1116
34083
      PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
1117
68166
  host_defined_options->Set(
1118
      isolate,
1119
      loader::HostDefinedOptions::kType,
1120
      Number::New(isolate, loader::ScriptType::kFunction));
1121
68166
  host_defined_options->Set(
1122
      isolate, loader::HostDefinedOptions::kID, Number::New(isolate, id));
1123
1124
  ScriptOrigin origin(isolate,
1125
                      filename,
1126
                      line_offset,       // line offset
1127
                      column_offset,     // column offset
1128
                      true,              // is cross origin
1129
                      -1,                // script id
1130
                      Local<Value>(),    // source map URL
1131
                      false,             // is opaque (?)
1132
                      false,             // is WASM
1133
                      false,             // is ES Module
1134
68166
                      host_defined_options);
1135
1136
34083
  ScriptCompiler::Source source(code, origin, cached_data);
1137
  ScriptCompiler::CompileOptions options;
1138
34083
  if (source.GetCachedData() == nullptr) {
1139
34083
    options = ScriptCompiler::kNoCompileOptions;
1140
  } else {
1141
    options = ScriptCompiler::kConsumeCodeCache;
1142
  }
1143
1144
34083
  TryCatchScope try_catch(env);
1145
34083
  Context::Scope scope(parsing_context);
1146
1147
  // Read context extensions from buffer
1148
34083
  std::vector<Local<Object>> context_extensions;
1149
34083
  if (!context_extensions_buf.IsEmpty()) {
1150
68167
    for (uint32_t n = 0; n < context_extensions_buf->Length(); n++) {
1151
      Local<Value> val;
1152
2
      if (!context_extensions_buf->Get(context, n).ToLocal(&val)) return;
1153
1
      CHECK(val->IsObject());
1154
1
      context_extensions.push_back(val.As<Object>());
1155
    }
1156
  }
1157
1158
  // Read params from params buffer
1159
34083
  std::vector<Local<String>> params;
1160
34083
  if (!params_buf.IsEmpty()) {
1161
238484
    for (uint32_t n = 0; n < params_buf->Length(); n++) {
1162
      Local<Value> val;
1163
340664
      if (!params_buf->Get(context, n).ToLocal(&val)) return;
1164
340664
      CHECK(val->IsString());
1165
170332
      params.push_back(val.As<String>());
1166
    }
1167
  }
1168
1169
  Local<ScriptOrModule> script;
1170
  MaybeLocal<Function> maybe_fn = ScriptCompiler::CompileFunctionInContext(
1171
      parsing_context, &source, params.size(), params.data(),
1172
      context_extensions.size(), context_extensions.data(), options,
1173
34083
      v8::ScriptCompiler::NoCacheReason::kNoCacheNoReason, &script);
1174
1175
  Local<Function> fn;
1176
34083
  if (!maybe_fn.ToLocal(&fn)) {
1177

29
    if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
1178
29
      errors::DecorateErrorStack(env, try_catch);
1179
29
      try_catch.ReThrow();
1180
    }
1181
29
    return;
1182
  }
1183
1184
  Local<Object> cache_key;
1185
34054
  if (!env->compiled_fn_entry_template()->NewInstance(
1186
68108
           context).ToLocal(&cache_key)) {
1187
    return;
1188
  }
1189
34054
  CompiledFnEntry* entry = new CompiledFnEntry(env, cache_key, id, script);
1190
34054
  env->id_to_function_map.emplace(id, entry);
1191
1192
34054
  Local<Object> result = Object::New(isolate);
1193
102162
  if (result->Set(parsing_context, env->function_string(), fn).IsNothing())
1194
    return;
1195
68108
  if (result->Set(parsing_context, env->cache_key_string(), cache_key)
1196
34054
          .IsNothing())
1197
    return;
1198
1199
34054
  if (produce_cached_data) {
1200
    const std::unique_ptr<ScriptCompiler::CachedData> cached_data(
1201
1
        ScriptCompiler::CreateCodeCacheForFunction(fn));
1202
1
    bool cached_data_produced = cached_data != nullptr;
1203
1
    if (cached_data_produced) {
1204
      MaybeLocal<Object> buf = Buffer::Copy(
1205
          env,
1206
2
          reinterpret_cast<const char*>(cached_data->data),
1207
1
          cached_data->length);
1208
1
      if (result
1209
1
              ->Set(parsing_context,
1210
                    env->cached_data_string(),
1211
3
                    buf.ToLocalChecked())
1212
1
              .IsNothing())
1213
        return;
1214
    }
1215
1
    if (result
1216
1
            ->Set(parsing_context,
1217
                  env->cached_data_produced_string(),
1218
3
                  Boolean::New(isolate, cached_data_produced))
1219
1
            .IsNothing())
1220
      return;
1221
  }
1222
1223
68108
  args.GetReturnValue().Set(result);
1224
}
1225
1226
void CompiledFnEntry::WeakCallback(
1227
    const WeakCallbackInfo<CompiledFnEntry>& data) {
1228
  CompiledFnEntry* entry = data.GetParameter();
1229
  delete entry;
1230
}
1231
1232
34054
CompiledFnEntry::CompiledFnEntry(Environment* env,
1233
                                 Local<Object> object,
1234
                                 uint32_t id,
1235
34054
                                 Local<ScriptOrModule> script)
1236
    : BaseObject(env, object),
1237
      id_(id),
1238
34054
      script_(env->isolate(), script) {
1239
34054
  script_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
1240
34054
}
1241
1242
192642
CompiledFnEntry::~CompiledFnEntry() {
1243
64214
  env()->id_to_function_map.erase(id_);
1244
64214
  script_.ClearWeak();
1245
128428
}
1246
1247
189
static void StartSigintWatchdog(const FunctionCallbackInfo<Value>& args) {
1248
189
  int ret = SigintWatchdogHelper::GetInstance()->Start();
1249
189
  args.GetReturnValue().Set(ret == 0);
1250
189
}
1251
1252
186
static void StopSigintWatchdog(const FunctionCallbackInfo<Value>& args) {
1253
186
  bool had_pending_signals = SigintWatchdogHelper::GetInstance()->Stop();
1254
186
  args.GetReturnValue().Set(had_pending_signals);
1255
186
}
1256
1257
3
static void WatchdogHasPendingSigint(const FunctionCallbackInfo<Value>& args) {
1258
3
  bool ret = SigintWatchdogHelper::GetInstance()->HasPendingSignal();
1259
3
  args.GetReturnValue().Set(ret);
1260
3
}
1261
1262
8
static void MeasureMemory(const FunctionCallbackInfo<Value>& args) {
1263
8
  CHECK(args[0]->IsInt32());
1264
8
  CHECK(args[1]->IsInt32());
1265
16
  int32_t mode = args[0].As<v8::Int32>()->Value();
1266
16
  int32_t execution = args[1].As<v8::Int32>()->Value();
1267
8
  Isolate* isolate = args.GetIsolate();
1268
1269
8
  Local<Context> current_context = isolate->GetCurrentContext();
1270
  Local<Promise::Resolver> resolver;
1271
16
  if (!Promise::Resolver::New(current_context).ToLocal(&resolver)) return;
1272
  std::unique_ptr<v8::MeasureMemoryDelegate> delegate =
1273
      v8::MeasureMemoryDelegate::Default(
1274
          isolate,
1275
          current_context,
1276
          resolver,
1277
8
          static_cast<v8::MeasureMemoryMode>(mode));
1278
8
  isolate->MeasureMemory(std::move(delegate),
1279
                         static_cast<v8::MeasureMemoryExecution>(execution));
1280
8
  v8::Local<v8::Promise> promise = resolver->GetPromise();
1281
1282
16
  args.GetReturnValue().Set(promise);
1283
}
1284
1285
5
MicrotaskQueueWrap::MicrotaskQueueWrap(Environment* env, Local<Object> obj)
1286
  : BaseObject(env, obj),
1287
    microtask_queue_(
1288
5
        MicrotaskQueue::New(env->isolate(), MicrotasksPolicy::kExplicit)) {
1289
5
  MakeWeak();
1290
5
}
1291
1292
const std::shared_ptr<MicrotaskQueue>&
1293
15
MicrotaskQueueWrap::microtask_queue() const {
1294
15
  return microtask_queue_;
1295
}
1296
1297
5
void MicrotaskQueueWrap::New(const FunctionCallbackInfo<Value>& args) {
1298
5
  CHECK(args.IsConstructCall());
1299
10
  new MicrotaskQueueWrap(Environment::GetCurrent(args), args.This());
1300
5
}
1301
1302
852
void MicrotaskQueueWrap::Init(Environment* env, Local<Object> target) {
1303
1704
  HandleScope scope(env->isolate());
1304
852
  Local<FunctionTemplate> tmpl = env->NewFunctionTemplate(New);
1305
1704
  tmpl->InstanceTemplate()->SetInternalFieldCount(
1306
      ContextifyScript::kInternalFieldCount);
1307
852
  env->set_microtask_queue_ctor_template(tmpl);
1308
852
  env->SetConstructorFunction(target, "MicrotaskQueue", tmpl);
1309
852
}
1310
1311
5179
void MicrotaskQueueWrap::RegisterExternalReferences(
1312
    ExternalReferenceRegistry* registry) {
1313
5179
  registry->Register(New);
1314
5179
}
1315
1316
852
void Initialize(Local<Object> target,
1317
                Local<Value> unused,
1318
                Local<Context> context,
1319
                void* priv) {
1320
852
  Environment* env = Environment::GetCurrent(context);
1321
852
  Isolate* isolate = env->isolate();
1322
852
  ContextifyContext::Init(env, target);
1323
852
  ContextifyScript::Init(env, target);
1324
852
  MicrotaskQueueWrap::Init(env, target);
1325
1326
852
  env->SetMethod(target, "startSigintWatchdog", StartSigintWatchdog);
1327
852
  env->SetMethod(target, "stopSigintWatchdog", StopSigintWatchdog);
1328
  // Used in tests.
1329
852
  env->SetMethodNoSideEffect(
1330
      target, "watchdogHasPendingSigint", WatchdogHasPendingSigint);
1331
1332
  {
1333
852
    Local<FunctionTemplate> tpl = FunctionTemplate::New(env->isolate());
1334
852
    tpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "CompiledFnEntry"));
1335
1704
    tpl->InstanceTemplate()->SetInternalFieldCount(
1336
        CompiledFnEntry::kInternalFieldCount);
1337
1338
852
    env->set_compiled_fn_entry_template(tpl->InstanceTemplate());
1339
  }
1340
1341
852
  Local<Object> constants = Object::New(env->isolate());
1342
852
  Local<Object> measure_memory = Object::New(env->isolate());
1343
852
  Local<Object> memory_execution = Object::New(env->isolate());
1344
1345
  {
1346
852
    Local<Object> memory_mode = Object::New(env->isolate());
1347
852
    MeasureMemoryMode SUMMARY = MeasureMemoryMode::kSummary;
1348
852
    MeasureMemoryMode DETAILED = MeasureMemoryMode::kDetailed;
1349
2556
    NODE_DEFINE_CONSTANT(memory_mode, SUMMARY);
1350
2556
    NODE_DEFINE_CONSTANT(memory_mode, DETAILED);
1351
1704
    READONLY_PROPERTY(measure_memory, "mode", memory_mode);
1352
  }
1353
1354
  {
1355
852
    MeasureMemoryExecution DEFAULT = MeasureMemoryExecution::kDefault;
1356
852
    MeasureMemoryExecution EAGER = MeasureMemoryExecution::kEager;
1357
2556
    NODE_DEFINE_CONSTANT(memory_execution, DEFAULT);
1358
2556
    NODE_DEFINE_CONSTANT(memory_execution, EAGER);
1359
2556
    READONLY_PROPERTY(measure_memory, "execution", memory_execution);
1360
  }
1361
1362
2556
  READONLY_PROPERTY(constants, "measureMemory", measure_memory);
1363
1364
1704
  target->Set(context, env->constants_string(), constants).Check();
1365
1366
852
  env->SetMethod(target, "measureMemory", MeasureMemory);
1367
852
}
1368
1369
5179
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1370
5179
  ContextifyContext::RegisterExternalReferences(registry);
1371
5179
  ContextifyScript::RegisterExternalReferences(registry);
1372
5179
  MicrotaskQueueWrap::RegisterExternalReferences(registry);
1373
1374
5179
  registry->Register(StartSigintWatchdog);
1375
5179
  registry->Register(StopSigintWatchdog);
1376
5179
  registry->Register(WatchdogHasPendingSigint);
1377
5179
  registry->Register(MeasureMemory);
1378
5179
}
1379
}  // namespace contextify
1380
}  // namespace node
1381
1382
5247
NODE_MODULE_CONTEXT_AWARE_INTERNAL(contextify, node::contextify::Initialize)
1383
5179
NODE_MODULE_EXTERNAL_REFERENCE(contextify,
1384
                               node::contextify::RegisterExternalReferences)