GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_contextify.cc Lines: 589 644 91.5 %
Date: 2022-06-06 04:15:48 Branches: 289 456 63.4 %

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
501
ContextifyContext::~ContextifyContext() {
129
501
  env()->RemoveCleanupHook(CleanupHook, this);
130
501
  Isolate* isolate = env()->isolate();
131
1002
  HandleScope scope(isolate);
132
133
  env()->async_hooks()
134
501
    ->RemoveContext(PersistentToLocal::Weak(isolate, context_));
135
501
}
136
137
138
440
void ContextifyContext::CleanupHook(void* arg) {
139
440
  ContextifyContext* self = static_cast<ContextifyContext*>(arg);
140
440
  self->context_.Reset();
141
440
  delete self;
142
440
}
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
854
void ContextifyContext::Init(Environment* env, Local<Object> target) {
254
  Local<FunctionTemplate> function_template =
255
854
      FunctionTemplate::New(env->isolate());
256
1708
  function_template->InstanceTemplate()->SetInternalFieldCount(
257
      ContextifyContext::kInternalFieldCount);
258
854
  env->set_script_data_constructor_function(
259
854
      function_template->GetFunction(env->context()).ToLocalChecked());
260
261
854
  env->SetMethod(target, "makeContext", MakeContext);
262
854
  env->SetMethod(target, "isContext", IsContext);
263
854
  env->SetMethod(target, "compileFunction", CompileFunction);
264
854
}
265
266
5206
void ContextifyContext::RegisterExternalReferences(
267
    ExternalReferenceRegistry* registry) {
268
5206
  registry->Register(MakeContext);
269
5206
  registry->Register(IsContext);
270
5206
  registry->Register(CompileFunction);
271
5206
}
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
2061
void ContextifyContext::IsContext(const FunctionCallbackInfo<Value>& args) {
331
2061
  Environment* env = Environment::GetCurrent(args);
332
333
2061
  CHECK(args[0]->IsObject());
334
4122
  Local<Object> sandbox = args[0].As<Object>();
335
336
  Maybe<bool> result =
337
      sandbox->HasPrivate(env->context(),
338
2061
                          env->contextify_context_private_symbol());
339
4122
  args.GetReturnValue().Set(result.FromJust());
340
2061
}
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
1393
ContextifyContext* ContextifyContext::ContextFromContextifiedSandbox(
351
    Environment* env,
352
    const Local<Object>& sandbox) {
353
  MaybeLocal<Value> maybe_value =
354
      sandbox->GetPrivate(env->context(),
355
1393
                          env->contextify_context_private_symbol());
356
  Local<Value> context_external_v;
357

2786
  if (maybe_value.ToLocal(&context_external_v) &&
358
1393
      context_external_v->IsExternal()) {
359
1393
    Local<External> context_external = context_external_v.As<External>();
360
1393
    return static_cast<ContextifyContext*>(context_external->Value());
361
  }
362
  return nullptr;
363
}
364
365
// static
366
template <typename T>
367
2096620
ContextifyContext* ContextifyContext::Get(const PropertyCallbackInfo<T>& args) {
368
2096620
  Local<Value> data = args.Data();
369
  return static_cast<ContextifyContext*>(
370
4193240
      data.As<Object>()->GetAlignedPointerFromInternalField(
371
2096620
          ContextifyContext::kSlot));
372
}
373
374
// static
375
1047835
void ContextifyContext::PropertyGetterCallback(
376
    Local<Name> property,
377
    const PropertyCallbackInfo<Value>& args) {
378
1047835
  ContextifyContext* ctx = ContextifyContext::Get(args);
379
380
  // Still initializing
381
1047835
  if (ctx->context_.IsEmpty())
382
2440
    return;
383
384
1045395
  Local<Context> context = ctx->context();
385
1045395
  Local<Object> sandbox = ctx->sandbox();
386
  MaybeLocal<Value> maybe_rv =
387
1045395
      sandbox->GetRealNamedProperty(context, property);
388
1045395
  if (maybe_rv.IsEmpty()) {
389
    maybe_rv =
390
82634
        ctx->global_proxy()->GetRealNamedProperty(context, property);
391
  }
392
393
  Local<Value> rv;
394
1045395
  if (maybe_rv.ToLocal(&rv)) {
395
1045326
    if (rv == sandbox)
396
10
      rv = ctx->global_proxy();
397
398
2090652
    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
250
void ContextifyContext::PropertyEnumeratorCallback(
562
    const PropertyCallbackInfo<Array>& args) {
563
250
  ContextifyContext* ctx = ContextifyContext::Get(args);
564
565
  // Still initializing
566
250
  if (ctx->context_.IsEmpty())
567
    return;
568
569
  Local<Array> properties;
570
571
750
  if (!ctx->sandbox()->GetPropertyNames(ctx->context()).ToLocal(&properties))
572
    return;
573
574
500
  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
854
void ContextifyScript::Init(Environment* env, Local<Object> target) {
656
1708
  HandleScope scope(env->isolate());
657
  Local<String> class_name =
658
854
      FIXED_ONE_BYTE_STRING(env->isolate(), "ContextifyScript");
659
660
854
  Local<FunctionTemplate> script_tmpl = env->NewFunctionTemplate(New);
661
1708
  script_tmpl->InstanceTemplate()->SetInternalFieldCount(
662
      ContextifyScript::kInternalFieldCount);
663
854
  script_tmpl->SetClassName(class_name);
664
854
  env->SetProtoMethod(script_tmpl, "createCachedData", CreateCachedData);
665
854
  env->SetProtoMethod(script_tmpl, "runInContext", RunInContext);
666
854
  env->SetProtoMethod(script_tmpl, "runInThisContext", RunInThisContext);
667
668
854
  Local<Context> context = env->context();
669
670
854
  target->Set(context, class_name,
671
1708
      script_tmpl->GetFunction(context).ToLocalChecked()).Check();
672
854
  env->set_script_context_constructor_template(script_tmpl);
673
854
}
674
675
5206
void ContextifyScript::RegisterExternalReferences(
676
    ExternalReferenceRegistry* registry) {
677
5206
  registry->Register(New);
678
5206
  registry->Register(CreateCachedData);
679
5206
  registry->Register(RunInContext);
680
5206
  registry->Register(RunInThisContext);
681
5206
}
682
683
3737
void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
684
3737
  Environment* env = Environment::GetCurrent(args);
685
3737
  Isolate* isolate = env->isolate();
686
3737
  Local<Context> context = env->context();
687
688
3737
  CHECK(args.IsConstructCall());
689
690
3737
  const int argc = args.Length();
691
3737
  CHECK_GE(argc, 2);
692
693
7474
  CHECK(args[0]->IsString());
694
7474
  Local<String> code = args[0].As<String>();
695
696
7474
  CHECK(args[1]->IsString());
697
3737
  Local<String> filename = args[1].As<String>();
698
699
3737
  int line_offset = 0;
700
3737
  int column_offset = 0;
701
  Local<ArrayBufferView> cached_data_buf;
702
3737
  bool produce_cached_data = false;
703
3737
  Local<Context> parsing_context = context;
704
705
3737
  if (argc > 2) {
706
    // new ContextifyScript(code, filename, lineOffset, columnOffset,
707
    //                      cachedData, produceCachedData, parsingContext)
708
3737
    CHECK_EQ(argc, 7);
709
3737
    CHECK(args[2]->IsNumber());
710
7474
    line_offset = args[2].As<Int32>()->Value();
711
3737
    CHECK(args[3]->IsNumber());
712
7474
    column_offset = args[3].As<Int32>()->Value();
713
7474
    if (!args[4]->IsUndefined()) {
714
25
      CHECK(args[4]->IsArrayBufferView());
715
50
      cached_data_buf = args[4].As<ArrayBufferView>();
716
    }
717
3737
    CHECK(args[5]->IsBoolean());
718
3737
    produce_cached_data = args[5]->IsTrue();
719
7474
    if (!args[6]->IsUndefined()) {
720
510
      CHECK(args[6]->IsObject());
721
      ContextifyContext* sandbox =
722
510
          ContextifyContext::ContextFromContextifiedSandbox(
723
1020
              env, args[6].As<Object>());
724
510
      CHECK_NOT_NULL(sandbox);
725
510
      parsing_context = sandbox->context();
726
    }
727
  }
728
729
  ContextifyScript* contextify_script =
730
3737
      new ContextifyScript(env, args.This());
731
732
3737
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
733
3737
          TRACING_CATEGORY_NODE2(vm, script)) != 0) {
734
14
    Utf8Value fn(isolate, filename);
735

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

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

4287
  TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(vm, script), "ContextifyScript::New");
819
}
820
821
3522
bool ContextifyScript::InstanceOf(Environment* env,
822
                                  const Local<Value>& value) {
823

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

3238
  TRACE_EVENT0(TRACING_CATEGORY_NODE2(vm, script), "RunInThisContext");
855
856
  // TODO(addaleax): Use an options object or otherwise merge this with
857
  // RunInContext().
858
2668
  CHECK_EQ(args.Length(), 4);
859
860
2668
  CHECK(args[0]->IsNumber());
861
5336
  int64_t timeout = args[0]->IntegerValue(env->context()).FromJust();
862
863
2668
  CHECK(args[1]->IsBoolean());
864
2668
  bool display_errors = args[1]->IsTrue();
865
866
2668
  CHECK(args[2]->IsBoolean());
867
2668
  bool break_on_sigint = args[2]->IsTrue();
868
869
2668
  CHECK(args[3]->IsBoolean());
870
2668
  bool break_on_first_line = args[3]->IsTrue();
871
872
  // Do the eval within this context
873
2668
  EvalMachine(env,
874
              timeout,
875
              display_errors,
876
              break_on_sigint,
877
              break_on_first_line,
878
              nullptr,  // microtask_queue
879
              args);
880
}
881
882
854
void ContextifyScript::RunInContext(const FunctionCallbackInfo<Value>& args) {
883
854
  Environment* env = Environment::GetCurrent(args);
884
885
  ContextifyScript* wrapped_script;
886
854
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder());
887
888
854
  CHECK_EQ(args.Length(), 5);
889
890
854
  CHECK(args[0]->IsObject());
891
854
  Local<Object> sandbox = args[0].As<Object>();
892
  // Get the context from the sandbox
893
  ContextifyContext* contextify_context =
894
854
      ContextifyContext::ContextFromContextifiedSandbox(env, sandbox);
895
854
  CHECK_NOT_NULL(contextify_context);
896
897
854
  Local<Context> context = contextify_context->context();
898
854
  if (context.IsEmpty())
899
    return;
900
901

1939
  TRACE_EVENT0(TRACING_CATEGORY_NODE2(vm, script), "RunInContext");
902
903
854
  CHECK(args[1]->IsNumber());
904
1708
  int64_t timeout = args[1]->IntegerValue(env->context()).FromJust();
905
906
854
  CHECK(args[2]->IsBoolean());
907
854
  bool display_errors = args[2]->IsTrue();
908
909
854
  CHECK(args[3]->IsBoolean());
910
854
  bool break_on_sigint = args[3]->IsTrue();
911
912
854
  CHECK(args[4]->IsBoolean());
913
854
  bool break_on_first_line = args[4]->IsTrue();
914
915
  // Do the eval within the context
916
854
  Context::Scope context_scope(context);
917
854
  EvalMachine(contextify_context->env(),
918
              timeout,
919
              display_errors,
920
              break_on_sigint,
921
              break_on_first_line,
922
1708
              contextify_context->microtask_queue(),
923
              args);
924
}
925
926
3522
bool ContextifyScript::EvalMachine(Environment* env,
927
                                   const int64_t timeout,
928
                                   const bool display_errors,
929
                                   const bool break_on_sigint,
930
                                   const bool break_on_first_line,
931
                                   std::shared_ptr<MicrotaskQueue> mtask_queue,
932
                                   const FunctionCallbackInfo<Value>& args) {
933
3522
  if (!env->can_call_into_js())
934
    return false;
935
3522
  if (!ContextifyScript::InstanceOf(env, args.Holder())) {
936
    THROW_ERR_INVALID_THIS(
937
        env,
938
        "Script methods can only be called on script instances.");
939
    return false;
940
  }
941
7028
  TryCatchScope try_catch(env);
942
7028
  Isolate::SafeForTerminationScope safe_for_termination(env->isolate());
943
  ContextifyScript* wrapped_script;
944
3522
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder(), false);
945
  Local<UnboundScript> unbound_script =
946
3522
      PersistentToLocal::Default(env->isolate(), wrapped_script->script_);
947
3522
  Local<Script> script = unbound_script->BindToCurrentContext();
948
949
#if HAVE_INSPECTOR
950
3522
  if (break_on_first_line) {
951
10
    env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start");
952
  }
953
#endif
954
955
  MaybeLocal<Value> result;
956
3522
  bool timed_out = false;
957
3522
  bool received_signal = false;
958
3522
  auto run = [&]() {
959
3522
    MaybeLocal<Value> result = script->Run(env->context());
960

3506
    if (!result.IsEmpty() && mtask_queue)
961
2
      mtask_queue->PerformCheckpoint(env->isolate());
962
3506
    return result;
963
3522
  };
964

3522
  if (break_on_sigint && timeout != -1) {
965
    Watchdog wd(env->isolate(), timeout, &timed_out);
966
    SigintWatchdog swd(env->isolate(), &received_signal);
967
    result = run();
968
3522
  } else if (break_on_sigint) {
969
381
    SigintWatchdog swd(env->isolate(), &received_signal);
970
192
    result = run();
971
3330
  } else if (timeout != -1) {
972
30
    Watchdog wd(env->isolate(), timeout, &timed_out);
973
15
    result = run();
974
  } else {
975
3315
    result = run();
976
  }
977
978
  // Convert the termination exception into a regular exception.
979

3506
  if (timed_out || received_signal) {
980

21
    if (!env->is_main_thread() && env->is_stopping())
981
      return false;
982
21
    env->isolate()->CancelTerminateExecution();
983
    // It is possible that execution was terminated by another timeout in
984
    // which this timeout is nested, so check whether one of the watchdogs
985
    // from this invocation is responsible for termination.
986
21
    if (timed_out) {
987
10
      node::THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, timeout);
988
11
    } else if (received_signal) {
989
11
      node::THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED(env);
990
    }
991
  }
992
993
3506
  if (try_catch.HasCaught()) {
994

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

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