GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_contextify.cc Lines: 583 637 91.5 %
Date: 2022-08-12 04:19:25 Branches: 283 444 63.7 %

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
625
ContextifyContext::ContextifyContext(
112
    Environment* env,
113
    Local<Object> sandbox_obj,
114
625
    const ContextOptions& options)
115
  : env_(env),
116
1250
    microtask_queue_wrap_(options.microtask_queue_wrap) {
117
625
  MaybeLocal<Context> v8_context = CreateV8Context(env, sandbox_obj, options);
118
119
  // Allocation failure, maximum call stack size reached, termination, etc.
120
625
  if (v8_context.IsEmpty()) return;
121
122
1250
  context_.Reset(env->isolate(), v8_context.ToLocalChecked());
123
625
  context_.SetWeak(this, WeakCallback, WeakCallbackType::kParameter);
124
625
  env->AddCleanupHook(CleanupHook, this);
125
}
126
127
128
513
ContextifyContext::~ContextifyContext() {
129
513
  env()->RemoveCleanupHook(CleanupHook, this);
130
513
  Isolate* isolate = env()->isolate();
131
1026
  HandleScope scope(isolate);
132
133
  env()->async_hooks()
134
513
    ->RemoveContext(PersistentToLocal::Weak(isolate, context_));
135
513
}
136
137
138
450
void ContextifyContext::CleanupHook(void* arg) {
139
450
  ContextifyContext* self = static_cast<ContextifyContext*>(arg);
140
450
  self->context_.Reset();
141
450
  delete self;
142
450
}
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
625
MaybeLocal<Object> ContextifyContext::CreateDataWrapper(Environment* env) {
151
  Local<Object> wrapper;
152
625
  if (!env->script_data_constructor_function()
153
625
           ->NewInstance(env->context())
154
625
           .ToLocal(&wrapper)) {
155
    return MaybeLocal<Object>();
156
  }
157
158
625
  wrapper->SetAlignedPointerInInternalField(ContextifyContext::kSlot, this);
159
625
  return wrapper;
160
}
161
162
625
MaybeLocal<Context> ContextifyContext::CreateV8Context(
163
    Environment* env,
164
    Local<Object> sandbox_obj,
165
    const ContextOptions& options) {
166
625
  EscapableHandleScope scope(env->isolate());
167
  Local<FunctionTemplate> function_template =
168
625
      FunctionTemplate::New(env->isolate());
169
170
625
  function_template->SetClassName(sandbox_obj->GetConstructorName());
171
172
  Local<ObjectTemplate> object_template =
173
625
      function_template->InstanceTemplate();
174
175
  Local<Object> data_wrapper;
176
1250
  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
625
      PropertyHandlerFlags::kHasNoSideEffect);
188
189
  IndexedPropertyHandlerConfiguration indexed_config(
190
      IndexedPropertyGetterCallback,
191
      IndexedPropertySetterCallback,
192
      IndexedPropertyDescriptorCallback,
193
      IndexedPropertyDeleterCallback,
194
      PropertyEnumeratorCallback,
195
      IndexedPropertyDefinerCallback,
196
      data_wrapper,
197
625
      PropertyHandlerFlags::kHasNoSideEffect);
198
199
625
  object_template->SetHandler(config);
200
625
  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
1250
      microtask_queue() ?
208
630
          microtask_queue().get() :
209

1875
          env->isolate()->GetCurrentContext()->GetMicrotaskQueue());
210
625
  if (ctx.IsEmpty()) return MaybeLocal<Context>();
211
  // Only partially initialize the context - the primordials are left out
212
  // and only initialized when necessary.
213
1250
  if (InitializeContextRuntime(ctx).IsNothing()) {
214
    return MaybeLocal<Context>();
215
  }
216
217
625
  if (ctx.IsEmpty()) {
218
    return MaybeLocal<Context>();
219
  }
220
221
625
  Local<Context> context = env->context();
222
625
  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
625
  ctx->SetEmbedderData(ContextEmbedderIndex::kSandboxObject, sandbox_obj);
231
  sandbox_obj->SetPrivate(context,
232
                          env->contextify_global_private_symbol(),
233
1250
                          ctx->Global());
234
235
1250
  Utf8Value name_val(env->isolate(), options.name);
236
  // Delegate the code generation validation to
237
  // node::ModifyCodeGenerationFromStrings.
238
625
  ctx->AllowCodeGenerationFromStrings(false);
239
625
  ctx->SetEmbedderData(ContextEmbedderIndex::kAllowCodeGenerationFromStrings,
240
                       options.allow_code_gen_strings);
241
625
  ctx->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
242
                       options.allow_code_gen_wasm);
243
244
1250
  ContextInfo info(*name_val);
245
246
625
  if (!options.origin.IsEmpty()) {
247
4
    Utf8Value origin_val(env->isolate(), options.origin);
248
2
    info.origin = *origin_val;
249
  }
250
251
625
  env->AssignToContext(ctx, info);
252
253
625
  return scope.Escape(ctx);
254
}
255
256
257
771
void ContextifyContext::Init(Environment* env, Local<Object> target) {
258
771
  Isolate* isolate = env->isolate();
259
771
  Local<Context> context = env->context();
260
261
  Local<FunctionTemplate> function_template =
262
771
      NewFunctionTemplate(isolate, nullptr);
263
1542
  function_template->InstanceTemplate()->SetInternalFieldCount(
264
      ContextifyContext::kInternalFieldCount);
265
771
  env->set_script_data_constructor_function(
266
771
      function_template->GetFunction(env->context()).ToLocalChecked());
267
268
771
  SetMethod(context, target, "makeContext", MakeContext);
269
771
  SetMethod(context, target, "isContext", IsContext);
270
771
  SetMethod(context, target, "compileFunction", CompileFunction);
271
771
}
272
273
5337
void ContextifyContext::RegisterExternalReferences(
274
    ExternalReferenceRegistry* registry) {
275
5337
  registry->Register(MakeContext);
276
5337
  registry->Register(IsContext);
277
5337
  registry->Register(CompileFunction);
278
5337
}
279
280
// makeContext(sandbox, name, origin, strings, wasm);
281
625
void ContextifyContext::MakeContext(const FunctionCallbackInfo<Value>& args) {
282
625
  Environment* env = Environment::GetCurrent(args);
283
284
625
  CHECK_EQ(args.Length(), 6);
285
625
  CHECK(args[0]->IsObject());
286
1250
  Local<Object> sandbox = args[0].As<Object>();
287
288
  // Don't allow contextifying a sandbox multiple times.
289
1250
  CHECK(
290
      !sandbox->HasPrivate(
291
          env->context(),
292
          env->contextify_context_private_symbol()).FromJust());
293
294
625
  ContextOptions options;
295
296
1250
  CHECK(args[1]->IsString());
297
1250
  options.name = args[1].As<String>();
298
299

2496
  CHECK(args[2]->IsString() || args[2]->IsUndefined());
300
1250
  if (args[2]->IsString()) {
301
4
    options.origin = args[2].As<String>();
302
  }
303
304
625
  CHECK(args[3]->IsBoolean());
305
1250
  options.allow_code_gen_strings = args[3].As<Boolean>();
306
307
625
  CHECK(args[4]->IsBoolean());
308
1250
  options.allow_code_gen_wasm = args[4].As<Boolean>();
309
310
625
  if (args[5]->IsObject() &&
311

635
      !env->microtask_queue_ctor_template().IsEmpty() &&
312

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

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

139
  bool is_declared = is_declared_on_global_proxy || is_declared_on_sandbox;
455


230
  if (!is_declared && args.ShouldThrowOnError() && is_contextual_store &&
456
30
      !is_function)
457
1
    return;
458
459
276
  USE(ctx->sandbox()->Set(context, property, value));
460
276
  args.GetReturnValue().Set(value);
461
}
462
463
// static
464
55
void ContextifyContext::PropertyDescriptorCallback(
465
    Local<Name> property,
466
    const PropertyCallbackInfo<Value>& args) {
467
55
  ContextifyContext* ctx = ContextifyContext::Get(args);
468
469
  // Still initializing
470
55
  if (ctx->context_.IsEmpty())
471
    return;
472
473
55
  Local<Context> context = ctx->context();
474
475
55
  Local<Object> sandbox = ctx->sandbox();
476
477

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

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

15
  if (desc.has_get() || desc.has_set()) {
528
    PropertyDescriptor desc_for_sandbox(
529
15
        desc.has_get() ? desc.get() : Undefined(isolate).As<Value>(),
530

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

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

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

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

6387
  TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(vm, script), "ContextifyScript::New");
824
}
825
826
5607
bool ContextifyScript::InstanceOf(Environment* env,
827
                                  const Local<Value>& value) {
828

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

11089
  CHECK(args[0]->IsObject() || args[0]->IsNull());
860
861
  Local<Context> context;
862
5607
  std::shared_ptr<v8::MicrotaskQueue> microtask_queue;
863
864
5607
  if (args[0]->IsObject()) {
865
2866
    Local<Object> sandbox = args[0].As<Object>();
866
    // Get the context from the sandbox
867
    ContextifyContext* contextify_context =
868
2866
        ContextifyContext::ContextFromContextifiedSandbox(env, sandbox);
869
2866
    CHECK_NOT_NULL(contextify_context);
870
2866
    CHECK_EQ(contextify_context->env(), env);
871
872
2866
    context = contextify_context->context();
873
2866
    if (context.IsEmpty()) return;
874
875
2866
    microtask_queue = contextify_context->microtask_queue();
876
  } else {
877
2741
    context = env->context();
878
  }
879
880

11955
  TRACE_EVENT0(TRACING_CATEGORY_NODE2(vm, script), "RunInContext");
881
882
5607
  CHECK(args[1]->IsNumber());
883
11214
  int64_t timeout = args[1]->IntegerValue(env->context()).FromJust();
884
885
5607
  CHECK(args[2]->IsBoolean());
886
5607
  bool display_errors = args[2]->IsTrue();
887
888
5607
  CHECK(args[3]->IsBoolean());
889
5607
  bool break_on_sigint = args[3]->IsTrue();
890
891
5607
  CHECK(args[4]->IsBoolean());
892
5607
  bool break_on_first_line = args[4]->IsTrue();
893
894
  // Do the eval within the context
895
5607
  Context::Scope context_scope(context);
896
5607
  EvalMachine(env,
897
              timeout,
898
              display_errors,
899
              break_on_sigint,
900
              break_on_first_line,
901
              microtask_queue,
902
              args);
903
}
904
905
5607
bool ContextifyScript::EvalMachine(Environment* env,
906
                                   const int64_t timeout,
907
                                   const bool display_errors,
908
                                   const bool break_on_sigint,
909
                                   const bool break_on_first_line,
910
                                   std::shared_ptr<MicrotaskQueue> mtask_queue,
911
                                   const FunctionCallbackInfo<Value>& args) {
912
5607
  if (!env->can_call_into_js())
913
    return false;
914
5607
  if (!ContextifyScript::InstanceOf(env, args.Holder())) {
915
    THROW_ERR_INVALID_THIS(
916
        env,
917
        "Script methods can only be called on script instances.");
918
    return false;
919
  }
920
11198
  TryCatchScope try_catch(env);
921
11198
  Isolate::SafeForTerminationScope safe_for_termination(env->isolate());
922
  ContextifyScript* wrapped_script;
923
5607
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder(), false);
924
  Local<UnboundScript> unbound_script =
925
5607
      PersistentToLocal::Default(env->isolate(), wrapped_script->script_);
926
5607
  Local<Script> script = unbound_script->BindToCurrentContext();
927
928
#if HAVE_INSPECTOR
929
5607
  if (break_on_first_line) {
930
10
    env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start");
931
  }
932
#endif
933
934
  MaybeLocal<Value> result;
935
5607
  bool timed_out = false;
936
5607
  bool received_signal = false;
937
5607
  auto run = [&]() {
938
5607
    MaybeLocal<Value> result = script->Run(env->context());
939

5591
    if (!result.IsEmpty() && mtask_queue)
940
2
      mtask_queue->PerformCheckpoint(env->isolate());
941
5591
    return result;
942
5607
  };
943

5607
  if (break_on_sigint && timeout != -1) {
944
    Watchdog wd(env->isolate(), timeout, &timed_out);
945
    SigintWatchdog swd(env->isolate(), &received_signal);
946
    result = run();
947
5607
  } else if (break_on_sigint) {
948
2393
    SigintWatchdog swd(env->isolate(), &received_signal);
949
1198
    result = run();
950
4409
  } else if (timeout != -1) {
951
30
    Watchdog wd(env->isolate(), timeout, &timed_out);
952
15
    result = run();
953
  } else {
954
4394
    result = run();
955
  }
956
957
  // Convert the termination exception into a regular exception.
958

5591
  if (timed_out || received_signal) {
959

21
    if (!env->is_main_thread() && env->is_stopping())
960
      return false;
961
21
    env->isolate()->CancelTerminateExecution();
962
    // It is possible that execution was terminated by another timeout in
963
    // which this timeout is nested, so check whether one of the watchdogs
964
    // from this invocation is responsible for termination.
965
21
    if (timed_out) {
966
10
      node::THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, timeout);
967
11
    } else if (received_signal) {
968
11
      node::THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED(env);
969
    }
970
  }
971
972
5591
  if (try_catch.HasCaught()) {
973

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

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