GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_contextify.cc Lines: 616 669 92.1 %
Date: 2022-10-14 05:16:24 Branches: 275 408 67.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_snapshot_builder.h"
32
#include "node_watchdog.h"
33
#include "util-inl.h"
34
35
namespace node {
36
namespace contextify {
37
38
using errors::TryCatchScope;
39
40
using v8::Array;
41
using v8::ArrayBufferView;
42
using v8::Boolean;
43
using v8::Context;
44
using v8::EscapableHandleScope;
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::String;
74
using v8::Uint32;
75
using v8::UnboundScript;
76
using v8::Value;
77
using v8::WeakCallbackInfo;
78
using v8::WeakCallbackType;
79
80
// The vm module executes code in a sandboxed environment with a different
81
// global object than the rest of the code. This is achieved by applying
82
// every call that changes or queries a property on the global `this` in the
83
// sandboxed code, to the sandbox object.
84
//
85
// The implementation uses V8's interceptors for methods like `set`, `get`,
86
// `delete`, `defineProperty`, and for any query of the property attributes.
87
// Property handlers with interceptors are set on the object template for
88
// the sandboxed code. Handlers for both named properties and for indexed
89
// properties are used. Their functionality is almost identical, the indexed
90
// interceptors mostly just call the named interceptors.
91
//
92
// For every `get` of a global property in the sandboxed context, the
93
// interceptor callback checks the sandbox object for the property.
94
// If the property is defined on the sandbox, that result is returned to
95
// the original call instead of finishing the query on the global object.
96
//
97
// For every `set` of a global property, the interceptor callback defines or
98
// changes the property both on the sandbox and the global proxy.
99
100
namespace {
101
102
// Convert an int to a V8 Name (String or Symbol).
103
3
Local<Name> Uint32ToName(Local<Context> context, uint32_t index) {
104
12
  return Uint32::New(context->GetIsolate(), index)->ToString(context)
105
6
      .ToLocalChecked();
106
}
107
108
}  // anonymous namespace
109
110
622
BaseObjectPtr<ContextifyContext> ContextifyContext::New(
111
    Environment* env,
112
    Local<Object> sandbox_obj,
113
    const ContextOptions& options) {
114
1244
  HandleScope scope(env->isolate());
115
622
  InitializeGlobalTemplates(env->isolate_data());
116
622
  Local<ObjectTemplate> object_template = env->contextify_global_template();
117
  DCHECK(!object_template.IsEmpty());
118
622
  bool use_node_snapshot = per_process::cli_options->node_snapshot;
119
  const SnapshotData* snapshot_data =
120
622
      use_node_snapshot ? SnapshotBuilder::GetEmbeddedSnapshotData() : nullptr;
121
122
  MicrotaskQueue* queue =
123
      options.microtask_queue_wrap
124
1239
          ? options.microtask_queue_wrap->microtask_queue().get()
125
2478
          : env->isolate()->GetCurrentContext()->GetMicrotaskQueue();
126
127
  Local<Context> v8_context;
128
1244
  if (!(CreateV8Context(env->isolate(), object_template, snapshot_data, queue)
129
622
            .ToLocal(&v8_context))) {
130
    // Allocation failure, maximum call stack size reached, termination, etc.
131
    return BaseObjectPtr<ContextifyContext>();
132
  }
133
622
  return New(v8_context, env, sandbox_obj, options);
134
}
135
136
void ContextifyContext::MemoryInfo(MemoryTracker* tracker) const {
137
  if (microtask_queue_wrap_) {
138
    tracker->TrackField("microtask_queue_wrap",
139
                        microtask_queue_wrap_->object());
140
  }
141
}
142
143
622
ContextifyContext::ContextifyContext(Environment* env,
144
                                     Local<Object> wrapper,
145
                                     Local<Context> v8_context,
146
622
                                     const ContextOptions& options)
147
    : BaseObject(env, wrapper),
148
1244
      microtask_queue_wrap_(options.microtask_queue_wrap) {
149
622
  context_.Reset(env->isolate(), v8_context);
150
  // This should only be done after the initial initializations of the context
151
  // global object is finished.
152
  DCHECK_NULL(v8_context->GetAlignedPointerFromEmbedderData(
153
      ContextEmbedderIndex::kContextifyContext));
154
622
  v8_context->SetAlignedPointerInEmbedderData(
155
      ContextEmbedderIndex::kContextifyContext, this);
156
  // It's okay to make this reference weak - V8 would create an internal
157
  // reference to this context via the constructor of the wrapper.
158
  // As long as the wrapper is alive, it's constructor is alive, and so
159
  // is the context.
160
622
  context_.SetWeak();
161
622
}
162
163
2036
ContextifyContext::~ContextifyContext() {
164
509
  Isolate* isolate = env()->isolate();
165
1018
  HandleScope scope(isolate);
166
167
  env()->async_hooks()
168
509
    ->RemoveContext(PersistentToLocal::Weak(isolate, context_));
169
509
  context_.Reset();
170
1018
}
171
172
1418
void ContextifyContext::InitializeGlobalTemplates(IsolateData* isolate_data) {
173
2836
  if (!isolate_data->contextify_global_template().IsEmpty()) {
174
622
    return;
175
  }
176
  DCHECK(isolate_data->contextify_wrapper_template().IsEmpty());
177
  Local<FunctionTemplate> global_func_template =
178
796
      FunctionTemplate::New(isolate_data->isolate());
179
  Local<ObjectTemplate> global_object_template =
180
796
      global_func_template->InstanceTemplate();
181
182
  NamedPropertyHandlerConfiguration config(
183
      PropertyGetterCallback,
184
      PropertySetterCallback,
185
      PropertyDescriptorCallback,
186
      PropertyDeleterCallback,
187
      PropertyEnumeratorCallback,
188
      PropertyDefinerCallback,
189
      {},
190
796
      PropertyHandlerFlags::kHasNoSideEffect);
191
192
  IndexedPropertyHandlerConfiguration indexed_config(
193
      IndexedPropertyGetterCallback,
194
      IndexedPropertySetterCallback,
195
      IndexedPropertyDescriptorCallback,
196
      IndexedPropertyDeleterCallback,
197
      PropertyEnumeratorCallback,
198
      IndexedPropertyDefinerCallback,
199
      {},
200
796
      PropertyHandlerFlags::kHasNoSideEffect);
201
202
796
  global_object_template->SetHandler(config);
203
796
  global_object_template->SetHandler(indexed_config);
204
796
  isolate_data->set_contextify_global_template(global_object_template);
205
206
  Local<FunctionTemplate> wrapper_func_template =
207
796
      BaseObject::MakeLazilyInitializedJSTemplate(isolate_data);
208
  Local<ObjectTemplate> wrapper_object_template =
209
796
      wrapper_func_template->InstanceTemplate();
210
796
  isolate_data->set_contextify_wrapper_template(wrapper_object_template);
211
}
212
213
629
MaybeLocal<Context> ContextifyContext::CreateV8Context(
214
    Isolate* isolate,
215
    Local<ObjectTemplate> object_template,
216
    const SnapshotData* snapshot_data,
217
    MicrotaskQueue* queue) {
218
629
  EscapableHandleScope scope(isolate);
219
220
  Local<Context> ctx;
221
629
  if (snapshot_data == nullptr) {
222
9
    ctx = Context::New(isolate,
223
                       nullptr,  // extensions
224
                       object_template,
225
                       {},  // global object
226
                       {},  // deserialization callback
227
18
                       queue);
228

18
    if (ctx.IsEmpty() || InitializeBaseContextForSnapshot(ctx).IsNothing()) {
229
      return MaybeLocal<Context>();
230
    }
231
1860
  } else if (!Context::FromSnapshot(isolate,
232
                                    SnapshotData::kNodeVMContextIndex,
233
                                    {},       // deserialization callback
234
                                    nullptr,  // extensions
235
                                    {},       // global object
236
1240
                                    queue)
237
620
                  .ToLocal(&ctx)) {
238
    return MaybeLocal<Context>();
239
  }
240
241
629
  return scope.Escape(ctx);
242
}
243
244
622
BaseObjectPtr<ContextifyContext> ContextifyContext::New(
245
    Local<Context> v8_context,
246
    Environment* env,
247
    Local<Object> sandbox_obj,
248
    const ContextOptions& options) {
249
1244
  HandleScope scope(env->isolate());
250
  // This only initializes part of the context. The primordials are
251
  // only initilaized when needed because even deserializing them slows
252
  // things down significantly and they are only needed in rare occasions
253
  // in the vm contexts.
254
1244
  if (InitializeContextRuntime(v8_context).IsNothing()) {
255
    return BaseObjectPtr<ContextifyContext>();
256
  }
257
258
622
  Local<Context> main_context = env->context();
259
622
  Local<Object> new_context_global = v8_context->Global();
260
1244
  v8_context->SetSecurityToken(main_context->GetSecurityToken());
261
262
  // We need to tie the lifetime of the sandbox object with the lifetime of
263
  // newly created context. We do this by making them hold references to each
264
  // other. The context can directly hold a reference to the sandbox as an
265
  // embedder data field. The sandbox uses a private symbol to hold a reference
266
  // to the ContextifyContext wrapper which in turn internally references
267
  // the context from its constructor.
268
1244
  v8_context->SetEmbedderData(ContextEmbedderIndex::kSandboxObject,
269
                              sandbox_obj);
270
271
  // Delegate the code generation validation to
272
  // node::ModifyCodeGenerationFromStrings.
273
622
  v8_context->AllowCodeGenerationFromStrings(false);
274
1244
  v8_context->SetEmbedderData(
275
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings,
276
      options.allow_code_gen_strings);
277
1244
  v8_context->SetEmbedderData(ContextEmbedderIndex::kAllowWasmCodeGeneration,
278
                              options.allow_code_gen_wasm);
279
280
1244
  Utf8Value name_val(env->isolate(), options.name);
281
1244
  ContextInfo info(*name_val);
282
1244
  if (!options.origin.IsEmpty()) {
283
4
    Utf8Value origin_val(env->isolate(), options.origin);
284
2
    info.origin = *origin_val;
285
  }
286
287
1244
  BaseObjectPtr<ContextifyContext> result;
288
  Local<Object> wrapper;
289
  {
290
622
    Context::Scope context_scope(v8_context);
291
622
    Local<String> ctor_name = sandbox_obj->GetConstructorName();
292

2492
    if (!ctor_name->Equals(v8_context, env->object_string()).FromMaybe(false) &&
293
        new_context_global
294
626
            ->DefineOwnProperty(
295
                v8_context,
296
                v8::Symbol::GetToStringTag(env->isolate()),
297
                ctor_name,
298
630
                static_cast<v8::PropertyAttribute>(v8::DontEnum))
299
4
            .IsNothing()) {
300
      return BaseObjectPtr<ContextifyContext>();
301
    }
302
622
    env->AssignToContext(v8_context, nullptr, info);
303
304
1866
    if (!env->contextify_wrapper_template()
305
1244
             ->NewInstance(v8_context)
306
622
             .ToLocal(&wrapper)) {
307
      return BaseObjectPtr<ContextifyContext>();
308
    }
309
310
622
    result =
311
1244
        MakeBaseObject<ContextifyContext>(env, wrapper, v8_context, options);
312
    // The only strong reference to the wrapper will come from the sandbox.
313
622
    result->MakeWeak();
314
  }
315
316
622
  if (sandbox_obj
317
1244
          ->SetPrivate(
318
1866
              v8_context, env->contextify_context_private_symbol(), wrapper)
319
622
          .IsNothing()) {
320
    return BaseObjectPtr<ContextifyContext>();
321
  }
322
323
622
  return result;
324
}
325
326
786
void ContextifyContext::Init(Environment* env, Local<Object> target) {
327
786
  Local<Context> context = env->context();
328
786
  SetMethod(context, target, "makeContext", MakeContext);
329
786
  SetMethod(context, target, "isContext", IsContext);
330
786
  SetMethod(context, target, "compileFunction", CompileFunction);
331
786
}
332
333
5551
void ContextifyContext::RegisterExternalReferences(
334
    ExternalReferenceRegistry* registry) {
335
5551
  registry->Register(MakeContext);
336
5551
  registry->Register(IsContext);
337
5551
  registry->Register(CompileFunction);
338
5551
  registry->Register(PropertyGetterCallback);
339
5551
  registry->Register(PropertySetterCallback);
340
5551
  registry->Register(PropertyDescriptorCallback);
341
5551
  registry->Register(PropertyDeleterCallback);
342
5551
  registry->Register(PropertyEnumeratorCallback);
343
5551
  registry->Register(PropertyDefinerCallback);
344
5551
  registry->Register(IndexedPropertyGetterCallback);
345
5551
  registry->Register(IndexedPropertySetterCallback);
346
5551
  registry->Register(IndexedPropertyDescriptorCallback);
347
5551
  registry->Register(IndexedPropertyDeleterCallback);
348
5551
  registry->Register(IndexedPropertyDefinerCallback);
349
5551
}
350
351
// makeContext(sandbox, name, origin, strings, wasm);
352
622
void ContextifyContext::MakeContext(const FunctionCallbackInfo<Value>& args) {
353
622
  Environment* env = Environment::GetCurrent(args);
354
355
622
  CHECK_EQ(args.Length(), 6);
356
1244
  CHECK(args[0]->IsObject());
357
1244
  Local<Object> sandbox = args[0].As<Object>();
358
359
  // Don't allow contextifying a sandbox multiple times.
360
1244
  CHECK(
361
      !sandbox->HasPrivate(
362
          env->context(),
363
          env->contextify_context_private_symbol()).FromJust());
364
365
1244
  ContextOptions options;
366
367
1866
  CHECK(args[1]->IsString());
368
1244
  options.name = args[1].As<String>();
369
370

3726
  CHECK(args[2]->IsString() || args[2]->IsUndefined());
371
1866
  if (args[2]->IsString()) {
372
4
    options.origin = args[2].As<String>();
373
  }
374
375
1244
  CHECK(args[3]->IsBoolean());
376
1244
  options.allow_code_gen_strings = args[3].As<Boolean>();
377
378
1244
  CHECK(args[4]->IsBoolean());
379
1244
  options.allow_code_gen_wasm = args[4].As<Boolean>();
380
381

1871
  if (args[5]->IsObject() &&
382

1254
      !env->microtask_queue_ctor_template().IsEmpty() &&
383
637
      env->microtask_queue_ctor_template()->HasInstance(args[5])) {
384
5
    options.microtask_queue_wrap.reset(
385
10
        Unwrap<MicrotaskQueueWrap>(args[5].As<Object>()));
386
  }
387
388
1244
  TryCatchScope try_catch(env);
389
  BaseObjectPtr<ContextifyContext> context_ptr =
390
1244
      ContextifyContext::New(env, sandbox, options);
391
392
622
  if (try_catch.HasCaught()) {
393
    if (!try_catch.HasTerminated())
394
      try_catch.ReThrow();
395
    return;
396
  }
397
}
398
399
400
6083
void ContextifyContext::IsContext(const FunctionCallbackInfo<Value>& args) {
401
6083
  Environment* env = Environment::GetCurrent(args);
402
403
12166
  CHECK(args[0]->IsObject());
404
12166
  Local<Object> sandbox = args[0].As<Object>();
405
406
  Maybe<bool> result =
407
      sandbox->HasPrivate(env->context(),
408
6083
                          env->contextify_context_private_symbol());
409
18249
  args.GetReturnValue().Set(result.FromJust());
410
6083
}
411
412
413
void ContextifyContext::WeakCallback(
414
    const WeakCallbackInfo<ContextifyContext>& data) {
415
  ContextifyContext* context = data.GetParameter();
416
  delete context;
417
}
418
419
// static
420
5403
ContextifyContext* ContextifyContext::ContextFromContextifiedSandbox(
421
    Environment* env,
422
    const Local<Object>& sandbox) {
423
  Local<Value> context_global;
424
5403
  if (sandbox
425
10806
          ->GetPrivate(env->context(), env->contextify_context_private_symbol())
426

10806
          .ToLocal(&context_global) &&
427
5403
      context_global->IsObject()) {
428
5403
    return Unwrap<ContextifyContext>(context_global.As<Object>());
429
  }
430
  return nullptr;
431
}
432
433
template <typename T>
434
1049302
ContextifyContext* ContextifyContext::Get(const PropertyCallbackInfo<T>& args) {
435
1049302
  return Get(args.This());
436
}
437
438
1049302
ContextifyContext* ContextifyContext::Get(Local<Object> object) {
439
  Local<Context> context;
440
2098604
  if (!object->GetCreationContext().ToLocal(&context)) {
441
    return nullptr;
442
  }
443
1049302
  if (!ContextEmbedderTag::IsNodeContext(context)) {
444
44
    return nullptr;
445
  }
446
  return static_cast<ContextifyContext*>(
447
1049258
      context->GetAlignedPointerFromEmbedderData(
448
1049258
          ContextEmbedderIndex::kContextifyContext));
449
}
450
451
1049302
bool ContextifyContext::IsStillInitializing(const ContextifyContext* ctx) {
452

2097938
  return ctx == nullptr || ctx->context_.IsEmpty();
453
}
454
455
// static
456
1048788
void ContextifyContext::PropertyGetterCallback(
457
    Local<Name> property,
458
    const PropertyCallbackInfo<Value>& args) {
459
1048788
  ContextifyContext* ctx = ContextifyContext::Get(args);
460
461
  // Still initializing
462
1048788
  if (IsStillInitializing(ctx)) return;
463
464
1048153
  Local<Context> context = ctx->context();
465
1048153
  Local<Object> sandbox = ctx->sandbox();
466
  MaybeLocal<Value> maybe_rv =
467
1048153
      sandbox->GetRealNamedProperty(context, property);
468
1048153
  if (maybe_rv.IsEmpty()) {
469
43866
    maybe_rv =
470
131598
        ctx->global_proxy()->GetRealNamedProperty(context, property);
471
  }
472
473
  Local<Value> rv;
474
1048153
  if (maybe_rv.ToLocal(&rv)) {
475
1048084
    if (rv == sandbox)
476
10
      rv = ctx->global_proxy();
477
478
2096168
    args.GetReturnValue().Set(rv);
479
  }
480
}
481
482
// static
483
175
void ContextifyContext::PropertySetterCallback(
484
    Local<Name> property,
485
    Local<Value> value,
486
    const PropertyCallbackInfo<Value>& args) {
487
175
  ContextifyContext* ctx = ContextifyContext::Get(args);
488
489
  // Still initializing
490
212
  if (IsStillInitializing(ctx)) return;
491
492
152
  Local<Context> context = ctx->context();
493
152
  PropertyAttribute attributes = PropertyAttribute::None;
494
304
  bool is_declared_on_global_proxy = ctx->global_proxy()
495
304
      ->GetRealNamedPropertyAttributes(context, property)
496
152
      .To(&attributes);
497
152
  bool read_only =
498
152
      static_cast<int>(attributes) &
499
      static_cast<int>(PropertyAttribute::ReadOnly);
500
501
304
  bool is_declared_on_sandbox = ctx->sandbox()
502
304
      ->GetRealNamedPropertyAttributes(context, property)
503
152
      .To(&attributes);
504

300
  read_only = read_only ||
505
148
      (static_cast<int>(attributes) &
506
      static_cast<int>(PropertyAttribute::ReadOnly));
507
508
152
  if (read_only)
509
13
    return;
510
511
  // true for x = 5
512
  // false for this.x = 5
513
  // false for Object.defineProperty(this, 'foo', ...)
514
  // false for vmResult.x = 5 where vmResult = vm.runInContext();
515
278
  bool is_contextual_store = ctx->global_proxy() != args.This();
516
517
  // Indicator to not return before setting (undeclared) function declarations
518
  // on the sandbox in strict mode, i.e. args.ShouldThrowOnError() = true.
519
  // True for 'function f() {}', 'this.f = function() {}',
520
  // 'var f = function()'.
521
  // In effect only for 'function f() {}' because
522
  // var f = function(), is_declared = true
523
  // this.f = function() {}, is_contextual_store = false.
524
139
  bool is_function = value->IsFunction();
525
526

139
  bool is_declared = is_declared_on_global_proxy || is_declared_on_sandbox;
527


230
  if (!is_declared && args.ShouldThrowOnError() && is_contextual_store &&
528
30
      !is_function)
529
1
    return;
530
531
414
  USE(ctx->sandbox()->Set(context, property, value));
532
276
  args.GetReturnValue().Set(value);
533
}
534
535
// static
536
59
void ContextifyContext::PropertyDescriptorCallback(
537
    Local<Name> property,
538
    const PropertyCallbackInfo<Value>& args) {
539
59
  ContextifyContext* ctx = ContextifyContext::Get(args);
540
541
  // Still initializing
542
59
  if (IsStillInitializing(ctx)) return;
543
544
55
  Local<Context> context = ctx->context();
545
546
55
  Local<Object> sandbox = ctx->sandbox();
547
548
110
  if (sandbox->HasOwnProperty(context, property).FromMaybe(false)) {
549
    Local<Value> desc;
550
78
    if (sandbox->GetOwnPropertyDescriptor(context, property).ToLocal(&desc)) {
551
78
      args.GetReturnValue().Set(desc);
552
    }
553
  }
554
}
555
556
// static
557
19
void ContextifyContext::PropertyDefinerCallback(
558
    Local<Name> property,
559
    const PropertyDescriptor& desc,
560
    const PropertyCallbackInfo<Value>& args) {
561
19
  ContextifyContext* ctx = ContextifyContext::Get(args);
562
563
  // Still initializing
564
23
  if (IsStillInitializing(ctx)) return;
565
566
15
  Local<Context> context = ctx->context();
567
15
  Isolate* isolate = context->GetIsolate();
568
569
15
  PropertyAttribute attributes = PropertyAttribute::None;
570
  bool is_declared =
571
45
      ctx->global_proxy()->GetRealNamedPropertyAttributes(context,
572
15
                                                          property)
573
15
          .To(&attributes);
574
15
  bool read_only =
575
15
      static_cast<int>(attributes) &
576
          static_cast<int>(PropertyAttribute::ReadOnly);
577
578
  // If the property is set on the global as read_only, don't change it on
579
  // the global or sandbox.
580

15
  if (is_declared && read_only)
581
    return;
582
583
15
  Local<Object> sandbox = ctx->sandbox();
584
585
  auto define_prop_on_sandbox =
586
15
      [&] (PropertyDescriptor* desc_for_sandbox) {
587
31
        if (desc.has_enumerable()) {
588
2
          desc_for_sandbox->set_enumerable(desc.enumerable());
589
        }
590
15
        if (desc.has_configurable()) {
591
1
          desc_for_sandbox->set_configurable(desc.configurable());
592
        }
593
        // Set the property on the sandbox.
594
30
        USE(sandbox->DefineProperty(context, property, *desc_for_sandbox));
595
30
      };
596
597

15
  if (desc.has_get() || desc.has_set()) {
598
    PropertyDescriptor desc_for_sandbox(
599
10
        desc.has_get() ? desc.get() : Undefined(isolate).As<Value>(),
600

28
        desc.has_set() ? desc.set() : Undefined(isolate).As<Value>());
601
602
5
    define_prop_on_sandbox(&desc_for_sandbox);
603
  } else {
604
    Local<Value> value =
605
12
        desc.has_value() ? desc.value() : Undefined(isolate).As<Value>();
606
607
10
    if (desc.has_writable()) {
608
      PropertyDescriptor desc_for_sandbox(value, desc.writable());
609
      define_prop_on_sandbox(&desc_for_sandbox);
610
    } else {
611
20
      PropertyDescriptor desc_for_sandbox(value);
612
10
      define_prop_on_sandbox(&desc_for_sandbox);
613
    }
614
  }
615
}
616
617
// static
618
2
void ContextifyContext::PropertyDeleterCallback(
619
    Local<Name> property,
620
    const PropertyCallbackInfo<Boolean>& args) {
621
2
  ContextifyContext* ctx = ContextifyContext::Get(args);
622
623
  // Still initializing
624
3
  if (IsStillInitializing(ctx)) return;
625
626
6
  Maybe<bool> success = ctx->sandbox()->Delete(ctx->context(), property);
627
628
4
  if (success.FromMaybe(false))
629
1
    return;
630
631
  // Delete failed on the sandbox, intercept and do not delete on
632
  // the global object.
633
2
  args.GetReturnValue().Set(false);
634
}
635
636
// static
637
256
void ContextifyContext::PropertyEnumeratorCallback(
638
    const PropertyCallbackInfo<Array>& args) {
639
256
  ContextifyContext* ctx = ContextifyContext::Get(args);
640
641
  // Still initializing
642
256
  if (IsStillInitializing(ctx)) return;
643
644
  Local<Array> properties;
645
646
768
  if (!ctx->sandbox()->GetPropertyNames(ctx->context()).ToLocal(&properties))
647
    return;
648
649
512
  args.GetReturnValue().Set(properties);
650
}
651
652
// static
653
void ContextifyContext::IndexedPropertyGetterCallback(
654
    uint32_t index,
655
    const PropertyCallbackInfo<Value>& args) {
656
  ContextifyContext* ctx = ContextifyContext::Get(args);
657
658
  // Still initializing
659
  if (IsStillInitializing(ctx)) return;
660
661
  ContextifyContext::PropertyGetterCallback(
662
      Uint32ToName(ctx->context(), index), args);
663
}
664
665
666
1
void ContextifyContext::IndexedPropertySetterCallback(
667
    uint32_t index,
668
    Local<Value> value,
669
    const PropertyCallbackInfo<Value>& args) {
670
1
  ContextifyContext* ctx = ContextifyContext::Get(args);
671
672
  // Still initializing
673
1
  if (IsStillInitializing(ctx)) return;
674
675
1
  ContextifyContext::PropertySetterCallback(
676
      Uint32ToName(ctx->context(), index), value, args);
677
}
678
679
// static
680
1
void ContextifyContext::IndexedPropertyDescriptorCallback(
681
    uint32_t index,
682
    const PropertyCallbackInfo<Value>& args) {
683
1
  ContextifyContext* ctx = ContextifyContext::Get(args);
684
685
  // Still initializing
686
1
  if (IsStillInitializing(ctx)) return;
687
688
1
  ContextifyContext::PropertyDescriptorCallback(
689
      Uint32ToName(ctx->context(), index), args);
690
}
691
692
693
1
void ContextifyContext::IndexedPropertyDefinerCallback(
694
    uint32_t index,
695
    const PropertyDescriptor& desc,
696
    const PropertyCallbackInfo<Value>& args) {
697
1
  ContextifyContext* ctx = ContextifyContext::Get(args);
698
699
  // Still initializing
700
1
  if (IsStillInitializing(ctx)) return;
701
702
1
  ContextifyContext::PropertyDefinerCallback(
703
      Uint32ToName(ctx->context(), index), desc, args);
704
}
705
706
// static
707
void ContextifyContext::IndexedPropertyDeleterCallback(
708
    uint32_t index,
709
    const PropertyCallbackInfo<Boolean>& args) {
710
  ContextifyContext* ctx = ContextifyContext::Get(args);
711
712
  // Still initializing
713
  if (IsStillInitializing(ctx)) return;
714
715
  Maybe<bool> success = ctx->sandbox()->Delete(ctx->context(), index);
716
717
  if (success.FromMaybe(false))
718
    return;
719
720
  // Delete failed on the sandbox, intercept and do not delete on
721
  // the global object.
722
  args.GetReturnValue().Set(false);
723
}
724
725
786
void ContextifyScript::Init(Environment* env, Local<Object> target) {
726
786
  Isolate* isolate = env->isolate();
727
1572
  HandleScope scope(env->isolate());
728
  Local<String> class_name =
729
786
      FIXED_ONE_BYTE_STRING(env->isolate(), "ContextifyScript");
730
731
786
  Local<FunctionTemplate> script_tmpl = NewFunctionTemplate(isolate, New);
732
1572
  script_tmpl->InstanceTemplate()->SetInternalFieldCount(
733
      ContextifyScript::kInternalFieldCount);
734
786
  script_tmpl->SetClassName(class_name);
735
786
  SetProtoMethod(isolate, script_tmpl, "createCachedData", CreateCachedData);
736
786
  SetProtoMethod(isolate, script_tmpl, "runInContext", RunInContext);
737
738
786
  Local<Context> context = env->context();
739
740
1572
  target->Set(context, class_name,
741
2358
      script_tmpl->GetFunction(context).ToLocalChecked()).Check();
742
786
  env->set_script_context_constructor_template(script_tmpl);
743
786
}
744
745
5551
void ContextifyScript::RegisterExternalReferences(
746
    ExternalReferenceRegistry* registry) {
747
5551
  registry->Register(New);
748
5551
  registry->Register(CreateCachedData);
749
5551
  registry->Register(RunInContext);
750
5551
}
751
752
6410
void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
753
6410
  Environment* env = Environment::GetCurrent(args);
754
6410
  Isolate* isolate = env->isolate();
755
6410
  Local<Context> context = env->context();
756
757
6410
  CHECK(args.IsConstructCall());
758
759
6410
  const int argc = args.Length();
760
6410
  CHECK_GE(argc, 2);
761
762
19230
  CHECK(args[0]->IsString());
763
12820
  Local<String> code = args[0].As<String>();
764
765
19230
  CHECK(args[1]->IsString());
766
12820
  Local<String> filename = args[1].As<String>();
767
768
6410
  int line_offset = 0;
769
6410
  int column_offset = 0;
770
  Local<ArrayBufferView> cached_data_buf;
771
6410
  bool produce_cached_data = false;
772
6410
  Local<Context> parsing_context = context;
773
774
6410
  if (argc > 2) {
775
    // new ContextifyScript(code, filename, lineOffset, columnOffset,
776
    //                      cachedData, produceCachedData, parsingContext)
777
6410
    CHECK_EQ(argc, 7);
778
12820
    CHECK(args[2]->IsNumber());
779
19230
    line_offset = args[2].As<Int32>()->Value();
780
12820
    CHECK(args[3]->IsNumber());
781
19230
    column_offset = args[3].As<Int32>()->Value();
782
19230
    if (!args[4]->IsUndefined()) {
783
50
      CHECK(args[4]->IsArrayBufferView());
784
50
      cached_data_buf = args[4].As<ArrayBufferView>();
785
    }
786
12820
    CHECK(args[5]->IsBoolean());
787
12820
    produce_cached_data = args[5]->IsTrue();
788
19230
    if (!args[6]->IsUndefined()) {
789
5022
      CHECK(args[6]->IsObject());
790
      ContextifyContext* sandbox =
791
2511
          ContextifyContext::ContextFromContextifiedSandbox(
792
7533
              env, args[6].As<Object>());
793
2511
      CHECK_NOT_NULL(sandbox);
794
2511
      parsing_context = sandbox->context();
795
    }
796
  }
797
798
  ContextifyScript* contextify_script =
799
6410
      new ContextifyScript(env, args.This());
800
801
12820
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
802
6410
          TRACING_CATEGORY_NODE2(vm, script)) != 0) {
803
14
    Utf8Value fn(isolate, filename);
804

14
    TRACE_EVENT_BEGIN1(TRACING_CATEGORY_NODE2(vm, script),
805
                       "ContextifyScript::New",
806
                       "filename",
807
                       TRACE_STR_COPY(*fn));
808
  }
809
810
6410
  ScriptCompiler::CachedData* cached_data = nullptr;
811
6410
  if (!cached_data_buf.IsEmpty()) {
812
50
    uint8_t* data = static_cast<uint8_t*>(cached_data_buf->Buffer()->Data());
813
50
    cached_data = new ScriptCompiler::CachedData(
814
75
        data + cached_data_buf->ByteOffset(), cached_data_buf->ByteLength());
815
  }
816
817
  Local<PrimitiveArray> host_defined_options =
818
6410
      PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
819
12820
  host_defined_options->Set(isolate, loader::HostDefinedOptions::kType,
820
                            Number::New(isolate, loader::ScriptType::kScript));
821
19230
  host_defined_options->Set(isolate, loader::HostDefinedOptions::kID,
822
6410
                            Number::New(isolate, contextify_script->id()));
823
824
  ScriptOrigin origin(isolate,
825
                      filename,
826
                      line_offset,                          // line offset
827
                      column_offset,                        // column offset
828
                      true,                                 // is cross origin
829
                      -1,                                   // script id
830
                      Local<Value>(),                       // source map URL
831
                      false,                                // is opaque (?)
832
                      false,                                // is WASM
833
                      false,                                // is ES Module
834
6410
                      host_defined_options);
835
6217
  ScriptCompiler::Source source(code, origin, cached_data);
836
6410
  ScriptCompiler::CompileOptions compile_options =
837
      ScriptCompiler::kNoCompileOptions;
838
839
6410
  if (source.GetCachedData() != nullptr)
840
25
    compile_options = ScriptCompiler::kConsumeCodeCache;
841
842
12627
  TryCatchScope try_catch(env);
843
12627
  ShouldNotAbortOnUncaughtScope no_abort_scope(env);
844
6217
  Context::Scope scope(parsing_context);
845
846
  MaybeLocal<UnboundScript> v8_script = ScriptCompiler::CompileUnboundScript(
847
      isolate,
848
      &source,
849
6410
      compile_options);
850
851
6410
  if (v8_script.IsEmpty()) {
852
193
    errors::DecorateErrorStack(env, try_catch);
853
193
    no_abort_scope.Close();
854
193
    if (!try_catch.HasTerminated())
855
193
      try_catch.ReThrow();
856

386
    TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(vm, script),
857
                     "ContextifyScript::New");
858
193
    return;
859
  }
860
18651
  contextify_script->script_.Reset(isolate, v8_script.ToLocalChecked());
861
862
6217
  Local<Context> env_context = env->context();
863
6217
  if (compile_options == ScriptCompiler::kConsumeCodeCache) {
864
100
    args.This()->Set(
865
        env_context,
866
        env->cached_data_rejected_string(),
867
100
        Boolean::New(isolate, source.GetCachedData()->rejected)).Check();
868
6192
  } else if (produce_cached_data) {
869
    std::unique_ptr<ScriptCompiler::CachedData> cached_data {
870
12
      ScriptCompiler::CreateCodeCache(v8_script.ToLocalChecked()) };
871
6
    bool cached_data_produced = cached_data != nullptr;
872
6
    if (cached_data_produced) {
873
      MaybeLocal<Object> buf = Buffer::Copy(
874
          env,
875
6
          reinterpret_cast<const char*>(cached_data->data),
876
12
          cached_data->length);
877
24
      args.This()->Set(env_context,
878
                       env->cached_data_string(),
879
18
                       buf.ToLocalChecked()).Check();
880
    }
881
24
    args.This()->Set(
882
        env_context,
883
        env->cached_data_produced_string(),
884
18
        Boolean::New(isolate, cached_data_produced)).Check();
885
  }
886

12434
  TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(vm, script), "ContextifyScript::New");
887
}
888
889
6196
bool ContextifyScript::InstanceOf(Environment* env,
890
                                  const Local<Value>& value) {
891

12392
  return !value.IsEmpty() &&
892
18588
         env->script_context_constructor_template()->HasInstance(value);
893
}
894
895
11
void ContextifyScript::CreateCachedData(
896
    const FunctionCallbackInfo<Value>& args) {
897
11
  Environment* env = Environment::GetCurrent(args);
898
  ContextifyScript* wrapped_script;
899
11
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder());
900
  Local<UnboundScript> unbound_script =
901
11
      PersistentToLocal::Default(env->isolate(), wrapped_script->script_);
902
  std::unique_ptr<ScriptCompiler::CachedData> cached_data(
903
22
      ScriptCompiler::CreateCodeCache(unbound_script));
904
11
  if (!cached_data) {
905
    args.GetReturnValue().Set(Buffer::New(env, 0).ToLocalChecked());
906
  } else {
907
    MaybeLocal<Object> buf = Buffer::Copy(
908
        env,
909
11
        reinterpret_cast<const char*>(cached_data->data),
910
22
        cached_data->length);
911
22
    args.GetReturnValue().Set(buf.ToLocalChecked());
912
  }
913
}
914
915
6196
void ContextifyScript::RunInContext(const FunctionCallbackInfo<Value>& args) {
916
6196
  Environment* env = Environment::GetCurrent(args);
917
918
  ContextifyScript* wrapped_script;
919
6196
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder());
920
921
6196
  CHECK_EQ(args.Length(), 5);
922

22391
  CHECK(args[0]->IsObject() || args[0]->IsNull());
923
924
  Local<Context> context;
925
12376
  std::shared_ptr<MicrotaskQueue> microtask_queue;
926
927
12392
  if (args[0]->IsObject()) {
928
5726
    Local<Object> sandbox = args[0].As<Object>();
929
    // Get the context from the sandbox
930
    ContextifyContext* contextify_context =
931
2863
        ContextifyContext::ContextFromContextifiedSandbox(env, sandbox);
932
2863
    CHECK_NOT_NULL(contextify_context);
933
2863
    CHECK_EQ(contextify_context->env(), env);
934
935
2863
    context = contextify_context->context();
936
2863
    if (context.IsEmpty()) return;
937
938
2863
    microtask_queue = contextify_context->microtask_queue();
939
  } else {
940
3333
    context = env->context();
941
  }
942
943

18572
  TRACE_EVENT0(TRACING_CATEGORY_NODE2(vm, script), "RunInContext");
944
945
12392
  CHECK(args[1]->IsNumber());
946
18588
  int64_t timeout = args[1]->IntegerValue(env->context()).FromJust();
947
948
12392
  CHECK(args[2]->IsBoolean());
949
12392
  bool display_errors = args[2]->IsTrue();
950
951
12392
  CHECK(args[3]->IsBoolean());
952
12392
  bool break_on_sigint = args[3]->IsTrue();
953
954
12392
  CHECK(args[4]->IsBoolean());
955
12392
  bool break_on_first_line = args[4]->IsTrue();
956
957
  // Do the eval within the context
958
6196
  EvalMachine(context,
959
              env,
960
              timeout,
961
              display_errors,
962
              break_on_sigint,
963
              break_on_first_line,
964
              microtask_queue,
965
              args);
966
}
967
968
6196
bool ContextifyScript::EvalMachine(Local<Context> context,
969
                                   Environment* env,
970
                                   const int64_t timeout,
971
                                   const bool display_errors,
972
                                   const bool break_on_sigint,
973
                                   const bool break_on_first_line,
974
                                   std::shared_ptr<MicrotaskQueue> mtask_queue,
975
                                   const FunctionCallbackInfo<Value>& args) {
976
  Context::Scope context_scope(context);
977
978
6196
  if (!env->can_call_into_js())
979
    return false;
980
6196
  if (!ContextifyScript::InstanceOf(env, args.Holder())) {
981
    THROW_ERR_INVALID_THIS(
982
        env,
983
        "Script methods can only be called on script instances.");
984
    return false;
985
  }
986
987
12376
  TryCatchScope try_catch(env);
988
12376
  Isolate::SafeForTerminationScope safe_for_termination(env->isolate());
989
  ContextifyScript* wrapped_script;
990
6196
  ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.Holder(), false);
991
  Local<UnboundScript> unbound_script =
992
6196
      PersistentToLocal::Default(env->isolate(), wrapped_script->script_);
993
6196
  Local<Script> script = unbound_script->BindToCurrentContext();
994
995
#if HAVE_INSPECTOR
996
6196
  if (break_on_first_line) {
997
10
    env->inspector_agent()->PauseOnNextJavascriptStatement("Break on start");
998
  }
999
#endif
1000
1001
  MaybeLocal<Value> result;
1002
6196
  bool timed_out = false;
1003
6196
  bool received_signal = false;
1004
6196
  auto run = [&]() {
1005
12392
    MaybeLocal<Value> result = script->Run(context);
1006

6180
    if (!result.IsEmpty() && mtask_queue)
1007
2
      mtask_queue->PerformCheckpoint(env->isolate());
1008
6180
    return result;
1009
6196
  };
1010

6196
  if (break_on_sigint && timeout != -1) {
1011
    Watchdog wd(env->isolate(), timeout, &timed_out);
1012
    SigintWatchdog swd(env->isolate(), &received_signal);
1013
    result = run();
1014
6196
  } else if (break_on_sigint) {
1015
2393
    SigintWatchdog swd(env->isolate(), &received_signal);
1016
1198
    result = run();
1017
4998
  } else if (timeout != -1) {
1018
30
    Watchdog wd(env->isolate(), timeout, &timed_out);
1019
15
    result = run();
1020
  } else {
1021
4983
    result = run();
1022
  }
1023
1024
  // Convert the termination exception into a regular exception.
1025

6180
  if (timed_out || received_signal) {
1026

21
    if (!env->is_main_thread() && env->is_stopping())
1027
      return false;
1028
21
    env->isolate()->CancelTerminateExecution();
1029
    // It is possible that execution was terminated by another timeout in
1030
    // which this timeout is nested, so check whether one of the watchdogs
1031
    // from this invocation is responsible for termination.
1032
21
    if (timed_out) {
1033
10
      node::THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, timeout);
1034
11
    } else if (received_signal) {
1035
11
      node::THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED(env);
1036
    }
1037
  }
1038
1039
6180
  if (try_catch.HasCaught()) {
1040

159
    if (!timed_out && !received_signal && display_errors) {
1041
      // We should decorate non-termination exceptions
1042
87
      errors::DecorateErrorStack(env, try_catch);
1043
    }
1044
1045
    // If there was an exception thrown during script execution, re-throw it.
1046
    // If one of the above checks threw, re-throw the exception instead of
1047
    // letting try_catch catch it.
1048
    // If execution has been terminated, but not by one of the watchdogs from
1049
    // this invocation, this will re-throw a `null` value.
1050
159
    if (!try_catch.HasTerminated())
1051
156
      try_catch.ReThrow();
1052
1053
159
    return false;
1054
  }
1055
1056
12042
  args.GetReturnValue().Set(result.ToLocalChecked());
1057
6021
  return true;
1058
}
1059
1060
1061
6410
ContextifyScript::ContextifyScript(Environment* env, Local<Object> object)
1062
    : BaseObject(env, object),
1063
12820
      id_(env->get_next_script_id()) {
1064
6410
  MakeWeak();
1065
6410
  env->id_to_script_map.emplace(id_, this);
1066
6410
}
1067
1068
1069
25416
ContextifyScript::~ContextifyScript() {
1070
6354
  env()->id_to_script_map.erase(id_);
1071
12708
}
1072
1073
1074
37188
void ContextifyContext::CompileFunction(
1075
    const FunctionCallbackInfo<Value>& args) {
1076
37188
  Environment* env = Environment::GetCurrent(args);
1077
37188
  Isolate* isolate = env->isolate();
1078
37188
  Local<Context> context = env->context();
1079
1080
  // Argument 1: source code
1081
111564
  CHECK(args[0]->IsString());
1082
74376
  Local<String> code = args[0].As<String>();
1083
1084
  // Argument 2: filename
1085
111564
  CHECK(args[1]->IsString());
1086
74376
  Local<String> filename = args[1].As<String>();
1087
1088
  // Argument 3: line offset
1089
74376
  CHECK(args[2]->IsNumber());
1090
111564
  int line_offset = args[2].As<Int32>()->Value();
1091
1092
  // Argument 4: column offset
1093
74376
  CHECK(args[3]->IsNumber());
1094
111564
  int column_offset = args[3].As<Int32>()->Value();
1095
1096
  // Argument 5: cached data (optional)
1097
  Local<ArrayBufferView> cached_data_buf;
1098
111564
  if (!args[4]->IsUndefined()) {
1099
    CHECK(args[4]->IsArrayBufferView());
1100
    cached_data_buf = args[4].As<ArrayBufferView>();
1101
  }
1102
1103
  // Argument 6: produce cache data
1104
74376
  CHECK(args[5]->IsBoolean());
1105
74376
  bool produce_cached_data = args[5]->IsTrue();
1106
1107
  // Argument 7: parsing context (optional)
1108
  Local<Context> parsing_context;
1109
111564
  if (!args[6]->IsUndefined()) {
1110
4
    CHECK(args[6]->IsObject());
1111
    ContextifyContext* sandbox =
1112
2
        ContextifyContext::ContextFromContextifiedSandbox(
1113
6
            env, args[6].As<Object>());
1114
2
    CHECK_NOT_NULL(sandbox);
1115
2
    parsing_context = sandbox->context();
1116
  } else {
1117
37186
    parsing_context = context;
1118
  }
1119
1120
  // Argument 8: context extensions (optional)
1121
  Local<Array> context_extensions_buf;
1122
111564
  if (!args[7]->IsUndefined()) {
1123
74376
    CHECK(args[7]->IsArray());
1124
74376
    context_extensions_buf = args[7].As<Array>();
1125
  }
1126
1127
  // Argument 9: params for the function (optional)
1128
  Local<Array> params_buf;
1129
111564
  if (!args[8]->IsUndefined()) {
1130
74362
    CHECK(args[8]->IsArray());
1131
74362
    params_buf = args[8].As<Array>();
1132
  }
1133
1134
  // Read cache from cached data buffer
1135
37188
  ScriptCompiler::CachedData* cached_data = nullptr;
1136
37188
  if (!cached_data_buf.IsEmpty()) {
1137
    uint8_t* data = static_cast<uint8_t*>(cached_data_buf->Buffer()->Data());
1138
    cached_data = new ScriptCompiler::CachedData(
1139
      data + cached_data_buf->ByteOffset(), cached_data_buf->ByteLength());
1140
  }
1141
1142
  // Get the function id
1143
37188
  uint32_t id = env->get_next_function_id();
1144
1145
  // Set host_defined_options
1146
  Local<PrimitiveArray> host_defined_options =
1147
37188
      PrimitiveArray::New(isolate, loader::HostDefinedOptions::kLength);
1148
74376
  host_defined_options->Set(
1149
      isolate,
1150
      loader::HostDefinedOptions::kType,
1151
      Number::New(isolate, loader::ScriptType::kFunction));
1152
74376
  host_defined_options->Set(
1153
      isolate, loader::HostDefinedOptions::kID, Number::New(isolate, id));
1154
1155
  ScriptOrigin origin(isolate,
1156
                      filename,
1157
                      line_offset,       // line offset
1158
                      column_offset,     // column offset
1159
                      true,              // is cross origin
1160
                      -1,                // script id
1161
                      Local<Value>(),    // source map URL
1162
                      false,             // is opaque (?)
1163
                      false,             // is WASM
1164
                      false,             // is ES Module
1165
37188
                      host_defined_options);
1166
1167
37159
  ScriptCompiler::Source source(code, origin, cached_data);
1168
  ScriptCompiler::CompileOptions options;
1169
37188
  if (source.GetCachedData() == nullptr) {
1170
37188
    options = ScriptCompiler::kNoCompileOptions;
1171
  } else {
1172
    options = ScriptCompiler::kConsumeCodeCache;
1173
  }
1174
1175
74347
  TryCatchScope try_catch(env);
1176
37159
  Context::Scope scope(parsing_context);
1177
1178
  // Read context extensions from buffer
1179
74347
  std::vector<Local<Object>> context_extensions;
1180
37188
  if (!context_extensions_buf.IsEmpty()) {
1181
74378
    for (uint32_t n = 0; n < context_extensions_buf->Length(); n++) {
1182
      Local<Value> val;
1183
2
      if (!context_extensions_buf->Get(context, n).ToLocal(&val)) return;
1184
1
      CHECK(val->IsObject());
1185
1
      context_extensions.push_back(val.As<Object>());
1186
    }
1187
  }
1188
1189
  // Read params from params buffer
1190
74347
  std::vector<Local<String>> params;
1191
37188
  if (!params_buf.IsEmpty()) {
1192
446072
    for (uint32_t n = 0; n < params_buf->Length(); n++) {
1193
      Local<Value> val;
1194
371710
      if (!params_buf->Get(context, n).ToLocal(&val)) return;
1195
371710
      CHECK(val->IsString());
1196
185855
      params.push_back(val.As<String>());
1197
    }
1198
  }
1199
1200
  MaybeLocal<Function> maybe_fn = ScriptCompiler::CompileFunction(
1201
      parsing_context,
1202
      &source,
1203
      params.size(),
1204
      params.data(),
1205
      context_extensions.size(),
1206
      context_extensions.data(),
1207
      options,
1208
37188
      v8::ScriptCompiler::NoCacheReason::kNoCacheNoReason);
1209
1210
  Local<Function> fn;
1211
37188
  if (!maybe_fn.ToLocal(&fn)) {
1212

29
    if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
1213
29
      errors::DecorateErrorStack(env, try_catch);
1214
29
      try_catch.ReThrow();
1215
    }
1216
29
    return;
1217
  }
1218
1219
  Local<Object> cache_key;
1220
111477
  if (!env->compiled_fn_entry_template()->NewInstance(
1221
74318
           context).ToLocal(&cache_key)) {
1222
    return;
1223
  }
1224
37159
  CompiledFnEntry* entry = new CompiledFnEntry(env, cache_key, id, fn);
1225
37159
  env->id_to_function_map.emplace(id, entry);
1226
1227
37159
  Local<Object> result = Object::New(isolate);
1228
148636
  if (result->Set(parsing_context, env->function_string(), fn).IsNothing())
1229
    return;
1230
148636
  if (result->Set(parsing_context, env->cache_key_string(), cache_key)
1231
37159
          .IsNothing())
1232
    return;
1233
1234
37159
  if (produce_cached_data) {
1235
    const std::unique_ptr<ScriptCompiler::CachedData> cached_data(
1236
2
        ScriptCompiler::CreateCodeCacheForFunction(fn));
1237
1
    bool cached_data_produced = cached_data != nullptr;
1238
1
    if (cached_data_produced) {
1239
      MaybeLocal<Object> buf = Buffer::Copy(
1240
          env,
1241
1
          reinterpret_cast<const char*>(cached_data->data),
1242
2
          cached_data->length);
1243
1
      if (result
1244
2
              ->Set(parsing_context,
1245
                    env->cached_data_string(),
1246
3
                    buf.ToLocalChecked())
1247
1
              .IsNothing())
1248
        return;
1249
    }
1250
1
    if (result
1251
2
            ->Set(parsing_context,
1252
                  env->cached_data_produced_string(),
1253
3
                  Boolean::New(isolate, cached_data_produced))
1254
1
            .IsNothing())
1255
      return;
1256
  }
1257
1258
74318
  args.GetReturnValue().Set(result);
1259
}
1260
1261
6
void CompiledFnEntry::WeakCallback(
1262
    const WeakCallbackInfo<CompiledFnEntry>& data) {
1263
6
  CompiledFnEntry* entry = data.GetParameter();
1264
6
  delete entry;
1265
6
}
1266
1267
37159
CompiledFnEntry::CompiledFnEntry(Environment* env,
1268
                                 Local<Object> object,
1269
                                 uint32_t id,
1270
37159
                                 Local<Function> fn)
1271
37159
    : BaseObject(env, object), id_(id), fn_(env->isolate(), fn) {
1272
37159
  fn_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
1273
37159
}
1274
1275
138804
CompiledFnEntry::~CompiledFnEntry() {
1276
34701
  env()->id_to_function_map.erase(id_);
1277
34701
  fn_.ClearWeak();
1278
69402
}
1279
1280
195
static void StartSigintWatchdog(const FunctionCallbackInfo<Value>& args) {
1281
195
  int ret = SigintWatchdogHelper::GetInstance()->Start();
1282
390
  args.GetReturnValue().Set(ret == 0);
1283
195
}
1284
1285
192
static void StopSigintWatchdog(const FunctionCallbackInfo<Value>& args) {
1286
192
  bool had_pending_signals = SigintWatchdogHelper::GetInstance()->Stop();
1287
384
  args.GetReturnValue().Set(had_pending_signals);
1288
192
}
1289
1290
3
static void WatchdogHasPendingSigint(const FunctionCallbackInfo<Value>& args) {
1291
3
  bool ret = SigintWatchdogHelper::GetInstance()->HasPendingSignal();
1292
6
  args.GetReturnValue().Set(ret);
1293
3
}
1294
1295
8
static void MeasureMemory(const FunctionCallbackInfo<Value>& args) {
1296
16
  CHECK(args[0]->IsInt32());
1297
16
  CHECK(args[1]->IsInt32());
1298
24
  int32_t mode = args[0].As<v8::Int32>()->Value();
1299
24
  int32_t execution = args[1].As<v8::Int32>()->Value();
1300
8
  Isolate* isolate = args.GetIsolate();
1301
1302
8
  Local<Context> current_context = isolate->GetCurrentContext();
1303
  Local<Promise::Resolver> resolver;
1304
16
  if (!Promise::Resolver::New(current_context).ToLocal(&resolver)) return;
1305
  std::unique_ptr<v8::MeasureMemoryDelegate> delegate =
1306
      v8::MeasureMemoryDelegate::Default(
1307
          isolate,
1308
          current_context,
1309
          resolver,
1310
16
          static_cast<v8::MeasureMemoryMode>(mode));
1311
8
  isolate->MeasureMemory(std::move(delegate),
1312
                         static_cast<v8::MeasureMemoryExecution>(execution));
1313
8
  Local<Promise> promise = resolver->GetPromise();
1314
1315
16
  args.GetReturnValue().Set(promise);
1316
}
1317
1318
5
MicrotaskQueueWrap::MicrotaskQueueWrap(Environment* env, Local<Object> obj)
1319
  : BaseObject(env, obj),
1320
    microtask_queue_(
1321
5
        MicrotaskQueue::New(env->isolate(), MicrotasksPolicy::kExplicit)) {
1322
5
  MakeWeak();
1323
5
}
1324
1325
const std::shared_ptr<MicrotaskQueue>&
1326
10
MicrotaskQueueWrap::microtask_queue() const {
1327
10
  return microtask_queue_;
1328
}
1329
1330
5
void MicrotaskQueueWrap::New(const FunctionCallbackInfo<Value>& args) {
1331
5
  CHECK(args.IsConstructCall());
1332
10
  new MicrotaskQueueWrap(Environment::GetCurrent(args), args.This());
1333
5
}
1334
1335
786
void MicrotaskQueueWrap::Init(Environment* env, Local<Object> target) {
1336
786
  Isolate* isolate = env->isolate();
1337
1572
  HandleScope scope(isolate);
1338
786
  Local<Context> context = env->context();
1339
786
  Local<FunctionTemplate> tmpl = NewFunctionTemplate(isolate, New);
1340
1572
  tmpl->InstanceTemplate()->SetInternalFieldCount(
1341
      ContextifyScript::kInternalFieldCount);
1342
786
  env->set_microtask_queue_ctor_template(tmpl);
1343
786
  SetConstructorFunction(context, target, "MicrotaskQueue", tmpl);
1344
786
}
1345
1346
5551
void MicrotaskQueueWrap::RegisterExternalReferences(
1347
    ExternalReferenceRegistry* registry) {
1348
5551
  registry->Register(New);
1349
5551
}
1350
1351
786
void Initialize(Local<Object> target,
1352
                Local<Value> unused,
1353
                Local<Context> context,
1354
                void* priv) {
1355
786
  Environment* env = Environment::GetCurrent(context);
1356
786
  Isolate* isolate = env->isolate();
1357
786
  ContextifyContext::Init(env, target);
1358
786
  ContextifyScript::Init(env, target);
1359
786
  MicrotaskQueueWrap::Init(env, target);
1360
1361
786
  SetMethod(context, target, "startSigintWatchdog", StartSigintWatchdog);
1362
786
  SetMethod(context, target, "stopSigintWatchdog", StopSigintWatchdog);
1363
  // Used in tests.
1364
786
  SetMethodNoSideEffect(
1365
      context, target, "watchdogHasPendingSigint", WatchdogHasPendingSigint);
1366
1367
  {
1368
786
    Local<FunctionTemplate> tpl = FunctionTemplate::New(env->isolate());
1369
786
    tpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "CompiledFnEntry"));
1370
1572
    tpl->InstanceTemplate()->SetInternalFieldCount(
1371
        CompiledFnEntry::kInternalFieldCount);
1372
1373
786
    env->set_compiled_fn_entry_template(tpl->InstanceTemplate());
1374
  }
1375
1376
786
  Local<Object> constants = Object::New(env->isolate());
1377
786
  Local<Object> measure_memory = Object::New(env->isolate());
1378
786
  Local<Object> memory_execution = Object::New(env->isolate());
1379
1380
  {
1381
786
    Local<Object> memory_mode = Object::New(env->isolate());
1382
786
    MeasureMemoryMode SUMMARY = MeasureMemoryMode::kSummary;
1383
786
    MeasureMemoryMode DETAILED = MeasureMemoryMode::kDetailed;
1384
3930
    NODE_DEFINE_CONSTANT(memory_mode, SUMMARY);
1385
3930
    NODE_DEFINE_CONSTANT(memory_mode, DETAILED);
1386
3144
    READONLY_PROPERTY(measure_memory, "mode", memory_mode);
1387
  }
1388
1389
  {
1390
786
    MeasureMemoryExecution DEFAULT = MeasureMemoryExecution::kDefault;
1391
786
    MeasureMemoryExecution EAGER = MeasureMemoryExecution::kEager;
1392
3930
    NODE_DEFINE_CONSTANT(memory_execution, DEFAULT);
1393
3930
    NODE_DEFINE_CONSTANT(memory_execution, EAGER);
1394
3144
    READONLY_PROPERTY(measure_memory, "execution", memory_execution);
1395
  }
1396
1397
3144
  READONLY_PROPERTY(constants, "measureMemory", measure_memory);
1398
1399
3144
  target->Set(context, env->constants_string(), constants).Check();
1400
1401
786
  SetMethod(context, target, "measureMemory", MeasureMemory);
1402
786
}
1403
1404
5551
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1405
5551
  ContextifyContext::RegisterExternalReferences(registry);
1406
5551
  ContextifyScript::RegisterExternalReferences(registry);
1407
5551
  MicrotaskQueueWrap::RegisterExternalReferences(registry);
1408
1409
5551
  registry->Register(StartSigintWatchdog);
1410
5551
  registry->Register(StopSigintWatchdog);
1411
5551
  registry->Register(WatchdogHasPendingSigint);
1412
5551
  registry->Register(MeasureMemory);
1413
5551
}
1414
}  // namespace contextify
1415
}  // namespace node
1416
1417
5622
NODE_MODULE_CONTEXT_AWARE_INTERNAL(contextify, node::contextify::Initialize)
1418

22417
NODE_MODULE_EXTERNAL_REFERENCE(contextify,
1419
                               node::contextify::RegisterExternalReferences)