GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: module_wrap.cc Lines: 385 428 90.0 %
Date: 2021-09-25 04:12:41 Branches: 174 295 59.0 %

Line Branch Exec Source
1
#include "module_wrap.h"
2
3
#include "env.h"
4
#include "memory_tracker-inl.h"
5
#include "node_contextify.h"
6
#include "node_errors.h"
7
#include "node_internals.h"
8
#include "node_process-inl.h"
9
#include "node_url.h"
10
#include "node_watchdog.h"
11
#include "util-inl.h"
12
13
#include <sys/stat.h>  // S_IFDIR
14
15
#include <algorithm>
16
17
namespace node {
18
namespace loader {
19
20
using errors::TryCatchScope;
21
22
using node::contextify::ContextifyContext;
23
using node::url::URL;
24
using node::url::URL_FLAGS_FAILED;
25
using v8::Array;
26
using v8::ArrayBufferView;
27
using v8::Context;
28
using v8::EscapableHandleScope;
29
using v8::FixedArray;
30
using v8::Function;
31
using v8::FunctionCallbackInfo;
32
using v8::FunctionTemplate;
33
using v8::HandleScope;
34
using v8::Int32;
35
using v8::Integer;
36
using v8::IntegrityLevel;
37
using v8::Isolate;
38
using v8::Local;
39
using v8::MaybeLocal;
40
using v8::MicrotaskQueue;
41
using v8::Module;
42
using v8::ModuleRequest;
43
using v8::Number;
44
using v8::Object;
45
using v8::PrimitiveArray;
46
using v8::Promise;
47
using v8::ScriptCompiler;
48
using v8::ScriptOrigin;
49
using v8::ScriptOrModule;
50
using v8::String;
51
using v8::UnboundModuleScript;
52
using v8::Undefined;
53
using v8::Value;
54
55
45193
ModuleWrap::ModuleWrap(Environment* env,
56
                       Local<Object> object,
57
                       Local<Module> module,
58
45193
                       Local<String> url)
59
  : BaseObject(env, object),
60
    module_(env->isolate(), module),
61
90386
    id_(env->get_next_module_id()) {
62
45193
  env->id_to_module_map.emplace(id_, this);
63
64
90386
  Local<Value> undefined = Undefined(env->isolate());
65
45193
  object->SetInternalField(kURLSlot, url);
66
45193
  object->SetInternalField(kSyntheticEvaluationStepsSlot, undefined);
67
45193
  object->SetInternalField(kContextObjectSlot, undefined);
68
45193
}
69
70
250464
ModuleWrap::~ModuleWrap() {
71
166976
  HandleScope scope(env()->isolate());
72
83488
  Local<Module> module = module_.Get(env()->isolate());
73
83488
  env()->id_to_module_map.erase(id_);
74
83488
  auto range = env()->hash_to_module_map.equal_range(module->GetIdentityHash());
75
83488
  for (auto it = range.first; it != range.second; ++it) {
76
83488
    if (it->second == this) {
77
83488
      env()->hash_to_module_map.erase(it);
78
83488
      break;
79
    }
80
  }
81
166976
}
82
83
90460
Local<Context> ModuleWrap::context() const {
84
271380
  Local<Value> obj = object()->GetInternalField(kContextObjectSlot);
85
90460
  if (obj.IsEmpty()) return {};
86
180920
  return obj.As<Object>()->GetCreationContext().ToLocalChecked();
87
}
88
89
45392
ModuleWrap* ModuleWrap::GetFromModule(Environment* env,
90
                                      Local<Module> module) {
91
45392
  auto range = env->hash_to_module_map.equal_range(module->GetIdentityHash());
92
45392
  for (auto it = range.first; it != range.second; ++it) {
93

90784
    if (it->second->module_ == module) {
94
45392
      return it->second;
95
    }
96
  }
97
  return nullptr;
98
}
99
100
156
ModuleWrap* ModuleWrap::GetFromID(Environment* env, uint32_t id) {
101
156
  auto module_wrap_it = env->id_to_module_map.find(id);
102
156
  if (module_wrap_it == env->id_to_module_map.end()) {
103
    return nullptr;
104
  }
105
156
  return module_wrap_it->second;
106
}
107
108
// new ModuleWrap(url, context, source, lineOffset, columnOffset)
109
// new ModuleWrap(url, context, exportNames, syntheticExecutionFunction)
110
45201
void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
111
45201
  CHECK(args.IsConstructCall());
112
45201
  CHECK_GE(args.Length(), 3);
113
114
45201
  Environment* env = Environment::GetCurrent(args);
115
45201
  Isolate* isolate = env->isolate();
116
117
45201
  Local<Object> that = args.This();
118
119
90402
  CHECK(args[0]->IsString());
120
90402
  Local<String> url = args[0].As<String>();
121
122
  Local<Context> context;
123
45201
  ContextifyContext* contextify_context = nullptr;
124
90402
  if (args[1]->IsUndefined()) {
125
90358
    context = that->GetCreationContext().ToLocalChecked();
126
  } else {
127
22
    CHECK(args[1]->IsObject());
128
44
    contextify_context = ContextifyContext::ContextFromContextifiedSandbox(
129
44
        env, args[1].As<Object>());
130
22
    CHECK_NOT_NULL(contextify_context);
131
22
    context = contextify_context->context();
132
  }
133
134
45201
  int line_offset = 0;
135
45201
  int column_offset = 0;
136
137
45201
  bool synthetic = args[2]->IsArray();
138
45201
  if (synthetic) {
139
    // new ModuleWrap(url, context, exportNames, syntheticExecutionFunction)
140
44643
    CHECK(args[3]->IsFunction());
141
  } else {
142
    // new ModuleWrap(url, context, source, lineOffset, columOffset, cachedData)
143
1116
    CHECK(args[2]->IsString());
144
558
    CHECK(args[3]->IsNumber());
145
1116
    line_offset = args[3].As<Int32>()->Value();
146
558
    CHECK(args[4]->IsNumber());
147
1116
    column_offset = args[4].As<Int32>()->Value();
148
  }
149
150
  Local<PrimitiveArray> host_defined_options =
151
45201
      PrimitiveArray::New(isolate, HostDefinedOptions::kLength);
152
90402
  host_defined_options->Set(isolate, HostDefinedOptions::kType,
153
                            Number::New(isolate, ScriptType::kModule));
154
155
45201
  ShouldNotAbortOnUncaughtScope no_abort_scope(env);
156
45201
  TryCatchScope try_catch(env);
157
158
  Local<Module> module;
159
160
  {
161
45201
    Context::Scope context_scope(context);
162
45201
    if (synthetic) {
163
44643
      CHECK(args[2]->IsArray());
164
89286
      Local<Array> export_names_arr = args[2].As<Array>();
165
166
44643
      uint32_t len = export_names_arr->Length();
167
89286
      std::vector<Local<String>> export_names(len);
168
1437851
      for (uint32_t i = 0; i < len; i++) {
169
        Local<Value> export_name_val =
170
2786416
            export_names_arr->Get(context, i).ToLocalChecked();
171
2786416
        CHECK(export_name_val->IsString());
172
2786416
        export_names[i] = export_name_val.As<String>();
173
      }
174
175
      module = Module::CreateSyntheticModule(isolate, url, export_names,
176
44643
        SyntheticModuleEvaluationStepsCallback);
177
    } else {
178
558
      ScriptCompiler::CachedData* cached_data = nullptr;
179
1116
      if (!args[5]->IsUndefined()) {
180
2
        CHECK(args[5]->IsArrayBufferView());
181
4
        Local<ArrayBufferView> cached_data_buf = args[5].As<ArrayBufferView>();
182
        uint8_t* data = static_cast<uint8_t*>(
183
4
            cached_data_buf->Buffer()->GetBackingStore()->Data());
184
2
        cached_data =
185
2
            new ScriptCompiler::CachedData(data + cached_data_buf->ByteOffset(),
186
2
                                           cached_data_buf->ByteLength());
187
      }
188
189
1116
      Local<String> source_text = args[2].As<String>();
190
      ScriptOrigin origin(isolate,
191
                          url,
192
                          line_offset,
193
                          column_offset,
194
                          true,                             // is cross origin
195
                          -1,                               // script id
196
                          Local<Value>(),                   // source map URL
197
                          false,                            // is opaque (?)
198
                          false,                            // is WASM
199
                          true,                             // is ES Module
200
1116
                          host_defined_options);
201
558
      ScriptCompiler::Source source(source_text, origin, cached_data);
202
      ScriptCompiler::CompileOptions options;
203
558
      if (source.GetCachedData() == nullptr) {
204
556
        options = ScriptCompiler::kNoCompileOptions;
205
      } else {
206
2
        options = ScriptCompiler::kConsumeCodeCache;
207
      }
208
558
      if (!ScriptCompiler::CompileModule(isolate, &source, options)
209
558
               .ToLocal(&module)) {
210

7
        if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
211
14
          CHECK(!try_catch.Message().IsEmpty());
212
14
          CHECK(!try_catch.Exception().IsEmpty());
213
7
          AppendExceptionLine(env, try_catch.Exception(), try_catch.Message(),
214
                              ErrorHandlingMode::MODULE_ERROR);
215
7
          try_catch.ReThrow();
216
        }
217
7
        return;
218
      }
219

553
      if (options == ScriptCompiler::kConsumeCodeCache &&
220
2
          source.GetCachedData()->rejected) {
221
1
        THROW_ERR_VM_MODULE_CACHED_DATA_REJECTED(
222
            env, "cachedData buffer was rejected");
223
1
        try_catch.ReThrow();
224
1
        return;
225
      }
226
    }
227
  }
228
229

135579
  if (!that->Set(context, env->url_string(), url).FromMaybe(false)) {
230
    return;
231
  }
232
233
45193
  ModuleWrap* obj = new ModuleWrap(env, that, module, url);
234
235
45193
  if (synthetic) {
236
44643
    obj->synthetic_ = true;
237
133929
    obj->object()->SetInternalField(kSyntheticEvaluationStepsSlot, args[3]);
238
  }
239
240
  // Use the extras object as an object whose GetCreationContext() will be the
241
  // original `context`, since the `Context` itself strictly speaking cannot
242
  // be stored in an internal field.
243
135579
  obj->object()->SetInternalField(kContextObjectSlot,
244
      context->GetExtrasBindingObject());
245
45193
  obj->contextify_context_ = contextify_context;
246
247
45193
  env->hash_to_module_map.emplace(module->GetIdentityHash(), obj);
248
249
90386
  host_defined_options->Set(isolate, HostDefinedOptions::kID,
250
45193
                            Number::New(isolate, obj->id()));
251
252
45193
  that->SetIntegrityLevel(context, IntegrityLevel::kFrozen);
253
90386
  args.GetReturnValue().Set(that);
254
}
255
256
827
void ModuleWrap::Link(const FunctionCallbackInfo<Value>& args) {
257
827
  Environment* env = Environment::GetCurrent(args);
258
827
  Isolate* isolate = args.GetIsolate();
259
260
827
  CHECK_EQ(args.Length(), 1);
261
827
  CHECK(args[0]->IsFunction());
262
263
827
  Local<Object> that = args.This();
264
265
  ModuleWrap* obj;
266
830
  ASSIGN_OR_RETURN_UNWRAP(&obj, that);
267
268
827
  if (obj->linked_)
269
3
    return;
270
824
  obj->linked_ = true;
271
272
824
  Local<Function> resolver_arg = args[0].As<Function>();
273
274
824
  Local<Context> mod_context = obj->context();
275
1648
  Local<Module> module = obj->module_.Get(isolate);
276
277
824
  Local<FixedArray> module_requests = module->GetModuleRequests();
278
824
  const int module_requests_length = module_requests->Length();
279
824
  MaybeStackBuffer<Local<Value>, 16> promises(module_requests_length);
280
281
  // call the dependency resolve callbacks
282
1516
  for (int i = 0; i < module_requests_length; i++) {
283
    Local<ModuleRequest> module_request =
284
1384
      module_requests->Get(env->context(), i).As<ModuleRequest>();
285
692
    Local<String> specifier = module_request->GetSpecifier();
286
692
    Utf8Value specifier_utf8(env->isolate(), specifier);
287
1384
    std::string specifier_std(*specifier_utf8, specifier_utf8.length());
288
289
692
    Local<FixedArray> raw_assertions = module_request->GetImportAssertions();
290
    Local<Object> assertions =
291
1384
        Object::New(isolate, v8::Null(env->isolate()), nullptr, nullptr, 0);
292
1386
    for (int i = 0; i < raw_assertions->Length(); i += 3) {
293
      assertions
294
2
          ->Set(env->context(),
295
                Local<String>::Cast(raw_assertions->Get(env->context(), i)),
296
8
                Local<Value>::Cast(raw_assertions->Get(env->context(), i + 1)))
297
          .ToChecked();
298
    }
299
300
    Local<Value> argv[] = {
301
        specifier,
302
        assertions,
303
692
    };
304
305
    MaybeLocal<Value> maybe_resolve_return_value =
306
692
        resolver_arg->Call(mod_context, that, arraysize(argv), argv);
307
692
    if (maybe_resolve_return_value.IsEmpty()) {
308
      return;
309
    }
310
    Local<Value> resolve_return_value =
311
692
        maybe_resolve_return_value.ToLocalChecked();
312
692
    if (!resolve_return_value->IsPromise()) {
313
      THROW_ERR_VM_MODULE_LINK_FAILURE(
314
          env, "request for '%s' did not return promise", specifier_std);
315
      return;
316
    }
317
692
    Local<Promise> resolve_promise = resolve_return_value.As<Promise>();
318
692
    obj->resolve_cache_[specifier_std].Reset(env->isolate(), resolve_promise);
319
320
692
    promises[i] = resolve_promise;
321
  }
322
323
1648
  args.GetReturnValue().Set(
324
      Array::New(isolate, promises.out(), promises.length()));
325
}
326
327
44818
void ModuleWrap::Instantiate(const FunctionCallbackInfo<Value>& args) {
328
44818
  Environment* env = Environment::GetCurrent(args);
329
44818
  Isolate* isolate = args.GetIsolate();
330
  ModuleWrap* obj;
331
44831
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
332
44818
  Local<Context> context = obj->context();
333
44818
  Local<Module> module = obj->module_.Get(isolate);
334
44818
  TryCatchScope try_catch(env);
335
44818
  USE(module->InstantiateModule(context, ResolveModuleCallback));
336
337
  // clear resolve cache on instantiate
338
44818
  obj->resolve_cache_.clear();
339
340

44818
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
341
26
    CHECK(!try_catch.Message().IsEmpty());
342
26
    CHECK(!try_catch.Exception().IsEmpty());
343
13
    AppendExceptionLine(env, try_catch.Exception(), try_catch.Message(),
344
                        ErrorHandlingMode::MODULE_ERROR);
345
13
    try_catch.ReThrow();
346
13
    return;
347
  }
348
}
349
350
44818
void ModuleWrap::Evaluate(const FunctionCallbackInfo<Value>& args) {
351
44818
  Environment* env = Environment::GetCurrent(args);
352
44818
  Isolate* isolate = env->isolate();
353
  ModuleWrap* obj;
354
44827
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
355
44818
  Local<Context> context = obj->context();
356
44818
  Local<Module> module = obj->module_.Get(isolate);
357
358
44818
  ContextifyContext* contextify_context = obj->contextify_context_;
359
44818
  std::shared_ptr<MicrotaskQueue> microtask_queue;
360
44818
  if (contextify_context != nullptr)
361
4
      microtask_queue = contextify_context->microtask_queue();
362
363
  // module.evaluate(timeout, breakOnSigint)
364
44818
  CHECK_EQ(args.Length(), 2);
365
366
44818
  CHECK(args[0]->IsNumber());
367
89636
  int64_t timeout = args[0]->IntegerValue(env->context()).FromJust();
368
369
44818
  CHECK(args[1]->IsBoolean());
370
44818
  bool break_on_sigint = args[1]->IsTrue();
371
372
44818
  ShouldNotAbortOnUncaughtScope no_abort_scope(env);
373
44818
  TryCatchScope try_catch(env);
374
44818
  Isolate::SafeForTerminationScope safe_for_termination(env->isolate());
375
376
44818
  bool timed_out = false;
377
44818
  bool received_signal = false;
378
  MaybeLocal<Value> result;
379
44818
  auto run = [&]() {
380
44818
    MaybeLocal<Value> result = module->Evaluate(context);
381

44816
    if (!result.IsEmpty() && microtask_queue)
382
1
      microtask_queue->PerformCheckpoint(isolate);
383
44816
    return result;
384
44818
  };
385

44818
  if (break_on_sigint && timeout != -1) {
386
    Watchdog wd(isolate, timeout, &timed_out);
387
    SigintWatchdog swd(isolate, &received_signal);
388
    result = run();
389
44818
  } else if (break_on_sigint) {
390
    SigintWatchdog swd(isolate, &received_signal);
391
    result = run();
392
44818
  } else if (timeout != -1) {
393
6
    Watchdog wd(isolate, timeout, &timed_out);
394
3
    result = run();
395
  } else {
396
44815
    result = run();
397
  }
398
399
44816
  if (result.IsEmpty()) {
400
3
    CHECK(try_catch.HasCaught());
401
  }
402
403
  // Convert the termination exception into a regular exception.
404

44816
  if (timed_out || received_signal) {
405

3
    if (!env->is_main_thread() && env->is_stopping())
406
      return;
407
3
    env->isolate()->CancelTerminateExecution();
408
    // It is possible that execution was terminated by another timeout in
409
    // which this timeout is nested, so check whether one of the watchdogs
410
    // from this invocation is responsible for termination.
411
3
    if (timed_out) {
412
3
      THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, timeout);
413
    } else if (received_signal) {
414
      THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED(env);
415
    }
416
  }
417
418
44816
  if (try_catch.HasCaught()) {
419
9
    if (!try_catch.HasTerminated())
420
8
      try_catch.ReThrow();
421
9
    return;
422
  }
423
424
  // If TLA is enabled, `result` is the evaluation's promise.
425
  // Otherwise, `result` is the last evaluated value of the module,
426
  // which could be a promise, which would result in it being incorrectly
427
  // unwrapped when the higher level code awaits the evaluation.
428
44807
  if (env->isolate_data()->options()->experimental_top_level_await) {
429
89592
    args.GetReturnValue().Set(result.ToLocalChecked());
430
  }
431
}
432
433
230
void ModuleWrap::GetNamespace(const FunctionCallbackInfo<Value>& args) {
434
230
  Environment* env = Environment::GetCurrent(args);
435
230
  Isolate* isolate = args.GetIsolate();
436
  ModuleWrap* obj;
437
230
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
438
439
460
  Local<Module> module = obj->module_.Get(isolate);
440
441
230
  switch (module->GetStatus()) {
442
    case v8::Module::Status::kUninstantiated:
443
    case v8::Module::Status::kInstantiating:
444
      return env->ThrowError(
445
          "cannot get namespace, module has not been instantiated");
446
230
    case v8::Module::Status::kInstantiated:
447
    case v8::Module::Status::kEvaluating:
448
    case v8::Module::Status::kEvaluated:
449
    case v8::Module::Status::kErrored:
450
230
      break;
451
    default:
452
      UNREACHABLE();
453
  }
454
455
230
  Local<Value> result = module->GetModuleNamespace();
456
460
  args.GetReturnValue().Set(result);
457
}
458
459
212
void ModuleWrap::GetStatus(const FunctionCallbackInfo<Value>& args) {
460
212
  Isolate* isolate = args.GetIsolate();
461
  ModuleWrap* obj;
462
212
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
463
464
424
  Local<Module> module = obj->module_.Get(isolate);
465
466
424
  args.GetReturnValue().Set(module->GetStatus());
467
}
468
469
2
void ModuleWrap::GetStaticDependencySpecifiers(
470
    const FunctionCallbackInfo<Value>& args) {
471
2
  Environment* env = Environment::GetCurrent(args);
472
  ModuleWrap* obj;
473
2
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
474
475
4
  Local<Module> module = obj->module_.Get(env->isolate());
476
477
2
  Local<FixedArray> module_requests = module->GetModuleRequests();
478
2
  int count = module_requests->Length();
479
480
2
  MaybeStackBuffer<Local<Value>, 16> specifiers(count);
481
482
3
  for (int i = 0; i < count; i++) {
483
    Local<ModuleRequest> module_request =
484
2
      module_requests->Get(env->context(), i).As<ModuleRequest>();
485
2
    specifiers[i] = module_request->GetSpecifier();
486
  }
487
488
4
  args.GetReturnValue().Set(
489
      Array::New(env->isolate(), specifiers.out(), count));
490
}
491
492
1
void ModuleWrap::GetError(const FunctionCallbackInfo<Value>& args) {
493
1
  Isolate* isolate = args.GetIsolate();
494
  ModuleWrap* obj;
495
1
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
496
497
2
  Local<Module> module = obj->module_.Get(isolate);
498
2
  args.GetReturnValue().Set(module->GetException());
499
}
500
501
671
MaybeLocal<Module> ModuleWrap::ResolveModuleCallback(
502
    Local<Context> context,
503
    Local<String> specifier,
504
    Local<FixedArray> import_assertions,
505
    Local<Module> referrer) {
506
671
  Environment* env = Environment::GetCurrent(context);
507
671
  if (env == nullptr) {
508
    Isolate* isolate = context->GetIsolate();
509
    THROW_ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE(isolate);
510
    return MaybeLocal<Module>();
511
  }
512
513
671
  Isolate* isolate = env->isolate();
514
515
1342
  Utf8Value specifier_utf8(isolate, specifier);
516
1342
  std::string specifier_std(*specifier_utf8, specifier_utf8.length());
517
518
671
  ModuleWrap* dependent = GetFromModule(env, referrer);
519
671
  if (dependent == nullptr) {
520
    THROW_ERR_VM_MODULE_LINK_FAILURE(
521
        env, "request for '%s' is from invalid module", specifier_std);
522
    return MaybeLocal<Module>();
523
  }
524
525
671
  if (dependent->resolve_cache_.count(specifier_std) != 1) {
526
    THROW_ERR_VM_MODULE_LINK_FAILURE(
527
        env, "request for '%s' is not in cache", specifier_std);
528
    return MaybeLocal<Module>();
529
  }
530
531
  Local<Promise> resolve_promise =
532
1342
      dependent->resolve_cache_[specifier_std].Get(isolate);
533
534
671
  if (resolve_promise->State() != Promise::kFulfilled) {
535
    THROW_ERR_VM_MODULE_LINK_FAILURE(
536
        env, "request for '%s' is not yet fulfilled", specifier_std);
537
    return MaybeLocal<Module>();
538
  }
539
540
1342
  Local<Object> module_object = resolve_promise->Result().As<Object>();
541

1342
  if (module_object.IsEmpty() || !module_object->IsObject()) {
542
    THROW_ERR_VM_MODULE_LINK_FAILURE(
543
        env, "request for '%s' did not return an object", specifier_std);
544
    return MaybeLocal<Module>();
545
  }
546
547
  ModuleWrap* module;
548
671
  ASSIGN_OR_RETURN_UNWRAP(&module, module_object, MaybeLocal<Module>());
549
1342
  return module->module_.Get(isolate);
550
}
551
552
234
static MaybeLocal<Promise> ImportModuleDynamically(
553
    Local<Context> context,
554
    Local<ScriptOrModule> referrer,
555
    Local<String> specifier,
556
    Local<FixedArray> import_assertions) {
557
234
  Isolate* isolate = context->GetIsolate();
558
234
  Environment* env = Environment::GetCurrent(context);
559
234
  if (env == nullptr) {
560
    THROW_ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE(isolate);
561
    return MaybeLocal<Promise>();
562
  }
563
564
234
  EscapableHandleScope handle_scope(isolate);
565
566
  Local<Function> import_callback =
567
234
    env->host_import_module_dynamically_callback();
568
569
234
  Local<PrimitiveArray> options = referrer->GetHostDefinedOptions();
570
234
  if (options->Length() != HostDefinedOptions::kLength) {
571
    Local<Promise::Resolver> resolver;
572
    if (!Promise::Resolver::New(context).ToLocal(&resolver)) return {};
573
    resolver
574
        ->Reject(context,
575
                 v8::Exception::TypeError(FIXED_ONE_BYTE_STRING(
576
                     context->GetIsolate(), "Invalid host defined options")))
577
        .ToChecked();
578
    return handle_scope.Escape(resolver->GetPromise());
579
  }
580
581
  Local<Value> object;
582
583
234
  int type = options->Get(isolate, HostDefinedOptions::kType)
584
234
                 .As<Number>()
585
234
                 ->Int32Value(context)
586
234
                 .ToChecked();
587
234
  uint32_t id = options->Get(isolate, HostDefinedOptions::kID)
588
234
                    .As<Number>()
589
234
                    ->Uint32Value(context)
590
234
                    .ToChecked();
591
234
  if (type == ScriptType::kScript) {
592
7
    contextify::ContextifyScript* wrap = env->id_to_script_map.find(id)->second;
593
14
    object = wrap->object();
594
227
  } else if (type == ScriptType::kModule) {
595
156
    ModuleWrap* wrap = ModuleWrap::GetFromID(env, id);
596
312
    object = wrap->object();
597
71
  } else if (type == ScriptType::kFunction) {
598
71
    auto it = env->id_to_function_map.find(id);
599
71
    CHECK_NE(it, env->id_to_function_map.end());
600
142
    object = it->second->object();
601
  } else {
602
    UNREACHABLE();
603
  }
604
605
  Local<Value> import_args[] = {
606
    object,
607
    Local<Value>(specifier),
608
234
  };
609
610
  Local<Value> result;
611
468
  if (import_callback->Call(
612
        context,
613
        Undefined(isolate),
614
234
        arraysize(import_args),
615
702
        import_args).ToLocal(&result)) {
616
234
    CHECK(result->IsPromise());
617
234
    return handle_scope.Escape(result.As<Promise>());
618
  }
619
620
  return MaybeLocal<Promise>();
621
}
622
623
5429
void ModuleWrap::SetImportModuleDynamicallyCallback(
624
    const FunctionCallbackInfo<Value>& args) {
625
5429
  Isolate* isolate = args.GetIsolate();
626
5429
  Environment* env = Environment::GetCurrent(args);
627
10858
  HandleScope handle_scope(isolate);
628
629
5429
  CHECK_EQ(args.Length(), 1);
630
5429
  CHECK(args[0]->IsFunction());
631
5429
  Local<Function> import_callback = args[0].As<Function>();
632
5429
  env->set_host_import_module_dynamically_callback(import_callback);
633
634
5429
  isolate->SetHostImportModuleDynamicallyCallback(ImportModuleDynamically);
635
5429
}
636
637
94
void ModuleWrap::HostInitializeImportMetaObjectCallback(
638
    Local<Context> context, Local<Module> module, Local<Object> meta) {
639
94
  Environment* env = Environment::GetCurrent(context);
640
94
  if (env == nullptr)
641
    return;
642
94
  ModuleWrap* module_wrap = GetFromModule(env, module);
643
644
94
  if (module_wrap == nullptr) {
645
    return;
646
  }
647
648
94
  Local<Object> wrap = module_wrap->object();
649
  Local<Function> callback =
650
94
      env->host_initialize_import_meta_object_callback();
651
94
  Local<Value> args[] = { wrap, meta };
652
188
  TryCatchScope try_catch(env);
653
94
  USE(callback->Call(
654
188
        context, Undefined(env->isolate()), arraysize(args), args));
655

94
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
656
    try_catch.ReThrow();
657
  }
658
}
659
660
5429
void ModuleWrap::SetInitializeImportMetaObjectCallback(
661
    const FunctionCallbackInfo<Value>& args) {
662
5429
  Environment* env = Environment::GetCurrent(args);
663
5429
  Isolate* isolate = env->isolate();
664
665
5429
  CHECK_EQ(args.Length(), 1);
666
5429
  CHECK(args[0]->IsFunction());
667
5429
  Local<Function> import_meta_callback = args[0].As<Function>();
668
5429
  env->set_host_initialize_import_meta_object_callback(import_meta_callback);
669
670
5429
  isolate->SetHostInitializeImportMetaObjectCallback(
671
      HostInitializeImportMetaObjectCallback);
672
5429
}
673
674
44627
MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback(
675
    Local<Context> context, Local<Module> module) {
676
44627
  Environment* env = Environment::GetCurrent(context);
677
44627
  Isolate* isolate = env->isolate();
678
679
44627
  ModuleWrap* obj = GetFromModule(env, module);
680
681
89254
  TryCatchScope try_catch(env);
682
  Local<Function> synthetic_evaluation_steps =
683
133881
      obj->object()->GetInternalField(kSyntheticEvaluationStepsSlot)
684
44627
          .As<Function>();
685
133881
  obj->object()->SetInternalField(
686
      kSyntheticEvaluationStepsSlot, Undefined(isolate));
687
  MaybeLocal<Value> ret = synthetic_evaluation_steps->Call(context,
688
89254
      obj->object(), 0, nullptr);
689
44627
  if (ret.IsEmpty()) {
690
5
    CHECK(try_catch.HasCaught());
691
  }
692

44627
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
693
10
    CHECK(!try_catch.Message().IsEmpty());
694
10
    CHECK(!try_catch.Exception().IsEmpty());
695
5
    try_catch.ReThrow();
696
5
    return MaybeLocal<Value>();
697
  }
698
699
  Local<Promise::Resolver> resolver;
700
89244
  if (!Promise::Resolver::New(context).ToLocal(&resolver)) {
701
    return MaybeLocal<Value>();
702
  }
703
704
133866
  resolver->Resolve(context, Undefined(isolate)).ToChecked();
705
89244
  return resolver->GetPromise();
706
}
707
708
3867183
void ModuleWrap::SetSyntheticExport(const FunctionCallbackInfo<Value>& args) {
709
3867183
  Isolate* isolate = args.GetIsolate();
710
3867183
  Local<Object> that = args.This();
711
712
  ModuleWrap* obj;
713
3867183
  ASSIGN_OR_RETURN_UNWRAP(&obj, that);
714
715
3867183
  CHECK(obj->synthetic_);
716
717
3867183
  CHECK_EQ(args.Length(), 2);
718
719
7734366
  CHECK(args[0]->IsString());
720
7734366
  Local<String> export_name = args[0].As<String>();
721
722
3867183
  Local<Value> export_value = args[1];
723
724
7734366
  Local<Module> module = obj->module_.Get(isolate);
725
3867183
  USE(module->SetSyntheticModuleExport(isolate, export_name, export_value));
726
}
727
728
1
void ModuleWrap::CreateCachedData(const FunctionCallbackInfo<Value>& args) {
729
1
  Isolate* isolate = args.GetIsolate();
730
1
  Local<Object> that = args.This();
731
732
  ModuleWrap* obj;
733
1
  ASSIGN_OR_RETURN_UNWRAP(&obj, that);
734
735
1
  CHECK(!obj->synthetic_);
736
737
2
  Local<Module> module = obj->module_.Get(isolate);
738
739
1
  CHECK_LT(module->GetStatus(), v8::Module::Status::kEvaluating);
740
741
  Local<UnboundModuleScript> unbound_module_script =
742
1
      module->GetUnboundModuleScript();
743
  std::unique_ptr<ScriptCompiler::CachedData> cached_data(
744
2
      ScriptCompiler::CreateCodeCache(unbound_module_script));
745
1
  Environment* env = Environment::GetCurrent(args);
746
1
  if (!cached_data) {
747
    args.GetReturnValue().Set(Buffer::New(env, 0).ToLocalChecked());
748
  } else {
749
    MaybeLocal<Object> buf =
750
        Buffer::Copy(env,
751
2
                     reinterpret_cast<const char*>(cached_data->data),
752
1
                     cached_data->length);
753
2
    args.GetReturnValue().Set(buf.ToLocalChecked());
754
  }
755
}
756
757
5430
void ModuleWrap::Initialize(Local<Object> target,
758
                            Local<Value> unused,
759
                            Local<Context> context,
760
                            void* priv) {
761
5430
  Environment* env = Environment::GetCurrent(context);
762
763
5430
  Local<FunctionTemplate> tpl = env->NewFunctionTemplate(New);
764
10860
  tpl->InstanceTemplate()->SetInternalFieldCount(
765
      ModuleWrap::kInternalFieldCount);
766
5430
  tpl->Inherit(BaseObject::GetConstructorTemplate(env));
767
768
5430
  env->SetProtoMethod(tpl, "link", Link);
769
5430
  env->SetProtoMethod(tpl, "instantiate", Instantiate);
770
5430
  env->SetProtoMethod(tpl, "evaluate", Evaluate);
771
5430
  env->SetProtoMethod(tpl, "setExport", SetSyntheticExport);
772
5430
  env->SetProtoMethodNoSideEffect(tpl, "createCachedData", CreateCachedData);
773
5430
  env->SetProtoMethodNoSideEffect(tpl, "getNamespace", GetNamespace);
774
5430
  env->SetProtoMethodNoSideEffect(tpl, "getStatus", GetStatus);
775
5430
  env->SetProtoMethodNoSideEffect(tpl, "getError", GetError);
776
5430
  env->SetProtoMethodNoSideEffect(tpl, "getStaticDependencySpecifiers",
777
                                  GetStaticDependencySpecifiers);
778
779
5430
  env->SetConstructorFunction(target, "ModuleWrap", tpl);
780
781
5430
  env->SetMethod(target,
782
                 "setImportModuleDynamicallyCallback",
783
                 SetImportModuleDynamicallyCallback);
784
5430
  env->SetMethod(target,
785
                 "setInitializeImportMetaObjectCallback",
786
                 SetInitializeImportMetaObjectCallback);
787
788
#define V(name)                                                                \
789
    target->Set(context,                                                       \
790
      FIXED_ONE_BYTE_STRING(env->isolate(), #name),                            \
791
      Integer::New(env->isolate(), Module::Status::name))                      \
792
        .FromJust()
793
21720
    V(kUninstantiated);
794
21720
    V(kInstantiating);
795
21720
    V(kInstantiated);
796
21720
    V(kEvaluating);
797
21720
    V(kEvaluated);
798
16290
    V(kErrored);
799
#undef V
800
5430
}
801
802
}  // namespace loader
803
}  // namespace node
804
805
4924
NODE_MODULE_CONTEXT_AWARE_INTERNAL(module_wrap,
806
                                   node::loader::ModuleWrap::Initialize)