GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: module_wrap.cc Lines: 390 433 90.1 %
Date: 2022-01-24 04:14:22 Branches: 173 295 58.6 %

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
46871
ModuleWrap::ModuleWrap(Environment* env,
56
                       Local<Object> object,
57
                       Local<Module> module,
58
46871
                       Local<String> url)
59
  : BaseObject(env, object),
60
    module_(env->isolate(), module),
61
93742
    id_(env->get_next_module_id()) {
62
46871
  env->id_to_module_map.emplace(id_, this);
63
64
93742
  Local<Value> undefined = Undefined(env->isolate());
65
46871
  object->SetInternalField(kURLSlot, url);
66
46871
  object->SetInternalField(kSyntheticEvaluationStepsSlot, undefined);
67
46871
  object->SetInternalField(kContextObjectSlot, undefined);
68
46871
}
69
70
265566
ModuleWrap::~ModuleWrap() {
71
177044
  HandleScope scope(env()->isolate());
72
88522
  Local<Module> module = module_.Get(env()->isolate());
73
88522
  env()->id_to_module_map.erase(id_);
74
88522
  auto range = env()->hash_to_module_map.equal_range(module->GetIdentityHash());
75
88522
  for (auto it = range.first; it != range.second; ++it) {
76
88522
    if (it->second == this) {
77
88522
      env()->hash_to_module_map.erase(it);
78
88522
      break;
79
    }
80
  }
81
177044
}
82
83
93870
Local<Context> ModuleWrap::context() const {
84
281610
  Local<Value> obj = object()->GetInternalField(kContextObjectSlot);
85
93870
  if (obj.IsEmpty()) return {};
86
187740
  return obj.As<Object>()->GetCreationContext().ToLocalChecked();
87
}
88
89
47153
ModuleWrap* ModuleWrap::GetFromModule(Environment* env,
90
                                      Local<Module> module) {
91
47153
  auto range = env->hash_to_module_map.equal_range(module->GetIdentityHash());
92
47153
  for (auto it = range.first; it != range.second; ++it) {
93

94306
    if (it->second->module_ == module) {
94
47153
      return it->second;
95
    }
96
  }
97
  return nullptr;
98
}
99
100
184
ModuleWrap* ModuleWrap::GetFromID(Environment* env, uint32_t id) {
101
184
  auto module_wrap_it = env->id_to_module_map.find(id);
102
184
  if (module_wrap_it == env->id_to_module_map.end()) {
103
    return nullptr;
104
  }
105
184
  return module_wrap_it->second;
106
}
107
108
// new ModuleWrap(url, context, source, lineOffset, columnOffset)
109
// new ModuleWrap(url, context, exportNames, syntheticExecutionFunction)
110
46878
void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
111
46878
  CHECK(args.IsConstructCall());
112
46878
  CHECK_GE(args.Length(), 3);
113
114
46878
  Environment* env = Environment::GetCurrent(args);
115
46878
  Isolate* isolate = env->isolate();
116
117
46878
  Local<Object> that = args.This();
118
119
93756
  CHECK(args[0]->IsString());
120
93756
  Local<String> url = args[0].As<String>();
121
122
  Local<Context> context;
123
46878
  ContextifyContext* contextify_context = nullptr;
124
93756
  if (args[1]->IsUndefined()) {
125
93712
    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
46878
  int line_offset = 0;
135
46878
  int column_offset = 0;
136
137
46878
  bool synthetic = args[2]->IsArray();
138
46878
  if (synthetic) {
139
    // new ModuleWrap(url, context, exportNames, syntheticExecutionFunction)
140
46251
    CHECK(args[3]->IsFunction());
141
  } else {
142
    // new ModuleWrap(url, context, source, lineOffset, columOffset, cachedData)
143
1254
    CHECK(args[2]->IsString());
144
627
    CHECK(args[3]->IsNumber());
145
1254
    line_offset = args[3].As<Int32>()->Value();
146
627
    CHECK(args[4]->IsNumber());
147
1254
    column_offset = args[4].As<Int32>()->Value();
148
  }
149
150
  Local<PrimitiveArray> host_defined_options =
151
46878
      PrimitiveArray::New(isolate, HostDefinedOptions::kLength);
152
93756
  host_defined_options->Set(isolate, HostDefinedOptions::kType,
153
                            Number::New(isolate, ScriptType::kModule));
154
155
46878
  ShouldNotAbortOnUncaughtScope no_abort_scope(env);
156
46878
  TryCatchScope try_catch(env);
157
158
  Local<Module> module;
159
160
  {
161
46878
    Context::Scope context_scope(context);
162
46878
    if (synthetic) {
163
46251
      CHECK(args[2]->IsArray());
164
92502
      Local<Array> export_names_arr = args[2].As<Array>();
165
166
46251
      uint32_t len = export_names_arr->Length();
167
92502
      std::vector<Local<String>> export_names(len);
168
1488177
      for (uint32_t i = 0; i < len; i++) {
169
        Local<Value> export_name_val =
170
2883852
            export_names_arr->Get(context, i).ToLocalChecked();
171
2883852
        CHECK(export_name_val->IsString());
172
1441926
        export_names[i] = export_name_val.As<String>();
173
      }
174
175
      module = Module::CreateSyntheticModule(isolate, url, export_names,
176
46251
        SyntheticModuleEvaluationStepsCallback);
177
    } else {
178
627
      ScriptCompiler::CachedData* cached_data = nullptr;
179
1254
      if (!args[5]->IsUndefined()) {
180
4
        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
1254
      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
1254
                          host_defined_options);
201
627
      ScriptCompiler::Source source(source_text, origin, cached_data);
202
      ScriptCompiler::CompileOptions options;
203
627
      if (source.GetCachedData() == nullptr) {
204
625
        options = ScriptCompiler::kNoCompileOptions;
205
      } else {
206
2
        options = ScriptCompiler::kConsumeCodeCache;
207
      }
208
627
      if (!ScriptCompiler::CompileModule(isolate, &source, options)
209
627
               .ToLocal(&module)) {
210

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

623
      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

140613
  if (!that->Set(context, env->url_string(), url).FromMaybe(false)) {
230
    return;
231
  }
232
233
46871
  ModuleWrap* obj = new ModuleWrap(env, that, module, url);
234
235
46871
  if (synthetic) {
236
46251
    obj->synthetic_ = true;
237
138753
    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
140613
  obj->object()->SetInternalField(kContextObjectSlot,
244
      context->GetExtrasBindingObject());
245
46871
  obj->contextify_context_ = contextify_context;
246
247
46871
  env->hash_to_module_map.emplace(module->GetIdentityHash(), obj);
248
249
93742
  host_defined_options->Set(isolate, HostDefinedOptions::kID,
250
46871
                            Number::New(isolate, obj->id()));
251
252
46871
  that->SetIntegrityLevel(context, IntegrityLevel::kFrozen);
253
93742
  args.GetReturnValue().Set(that);
254
}
255
256
1110
static Local<Object> createImportAssertionContainer(Environment* env,
257
  Isolate* isolate, Local<FixedArray> raw_assertions) {
258
  Local<Object> assertions =
259
2220
        Object::New(isolate, v8::Null(env->isolate()), nullptr, nullptr, 0);
260
2265
  for (int i = 0; i < raw_assertions->Length(); i += 3) {
261
      assertions
262
45
          ->Set(env->context(),
263
45
                raw_assertions->Get(env->context(), i).As<String>(),
264
135
                raw_assertions->Get(env->context(), i + 1).As<Value>())
265
          .ToChecked();
266
  }
267
268
1110
  return assertions;
269
}
270
271
979
void ModuleWrap::Link(const FunctionCallbackInfo<Value>& args) {
272
979
  Environment* env = Environment::GetCurrent(args);
273
979
  Isolate* isolate = args.GetIsolate();
274
275
979
  CHECK_EQ(args.Length(), 1);
276
979
  CHECK(args[0]->IsFunction());
277
278
979
  Local<Object> that = args.This();
279
280
  ModuleWrap* obj;
281
982
  ASSIGN_OR_RETURN_UNWRAP(&obj, that);
282
283
979
  if (obj->linked_)
284
3
    return;
285
976
  obj->linked_ = true;
286
287
976
  Local<Function> resolver_arg = args[0].As<Function>();
288
289
976
  Local<Context> mod_context = obj->context();
290
1952
  Local<Module> module = obj->module_.Get(isolate);
291
292
976
  Local<FixedArray> module_requests = module->GetModuleRequests();
293
976
  const int module_requests_length = module_requests->Length();
294
976
  MaybeStackBuffer<Local<Value>, 16> promises(module_requests_length);
295
296
  // call the dependency resolve callbacks
297
1795
  for (int i = 0; i < module_requests_length; i++) {
298
    Local<ModuleRequest> module_request =
299
1638
      module_requests->Get(env->context(), i).As<ModuleRequest>();
300
819
    Local<String> specifier = module_request->GetSpecifier();
301
819
    Utf8Value specifier_utf8(env->isolate(), specifier);
302
1638
    std::string specifier_std(*specifier_utf8, specifier_utf8.length());
303
304
819
    Local<FixedArray> raw_assertions = module_request->GetImportAssertions();
305
    Local<Object> assertions =
306
819
      createImportAssertionContainer(env, isolate, raw_assertions);
307
308
    Local<Value> argv[] = {
309
        specifier,
310
        assertions,
311
819
    };
312
313
    MaybeLocal<Value> maybe_resolve_return_value =
314
819
        resolver_arg->Call(mod_context, that, arraysize(argv), argv);
315
819
    if (maybe_resolve_return_value.IsEmpty()) {
316
      return;
317
    }
318
    Local<Value> resolve_return_value =
319
819
        maybe_resolve_return_value.ToLocalChecked();
320
819
    if (!resolve_return_value->IsPromise()) {
321
      THROW_ERR_VM_MODULE_LINK_FAILURE(
322
          env, "request for '%s' did not return promise", specifier_std);
323
      return;
324
    }
325
819
    Local<Promise> resolve_promise = resolve_return_value.As<Promise>();
326
819
    obj->resolve_cache_[specifier_std].Reset(env->isolate(), resolve_promise);
327
328
819
    promises[i] = resolve_promise;
329
  }
330
331
1952
  args.GetReturnValue().Set(
332
      Array::New(isolate, promises.out(), promises.length()));
333
}
334
335
46442
void ModuleWrap::Instantiate(const FunctionCallbackInfo<Value>& args) {
336
46442
  Environment* env = Environment::GetCurrent(args);
337
46442
  Isolate* isolate = args.GetIsolate();
338
  ModuleWrap* obj;
339
46456
  ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
340
46442
  Local<Context> context = obj->context();
341
46442
  Local<Module> module = obj->module_.Get(isolate);
342
46442
  TryCatchScope try_catch(env);
343
46442
  USE(module->InstantiateModule(context, ResolveModuleCallback));
344
345
  // clear resolve cache on instantiate
346
46442
  obj->resolve_cache_.clear();
347
348

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

46449
    if (!result.IsEmpty() && microtask_queue)
390
1
      microtask_queue->PerformCheckpoint(isolate);
391
46449
    return result;
392
46452
  };
393

46452
  if (break_on_sigint && timeout != -1) {
394
    Watchdog wd(isolate, timeout, &timed_out);
395
    SigintWatchdog swd(isolate, &received_signal);
396
    result = run();
397
46452
  } else if (break_on_sigint) {
398
    SigintWatchdog swd(isolate, &received_signal);
399
    result = run();
400
46452
  } else if (timeout != -1) {
401
6
    Watchdog wd(isolate, timeout, &timed_out);
402
3
    result = run();
403
  } else {
404
46449
    result = run();
405
  }
406
407
46449
  if (result.IsEmpty()) {
408
3
    CHECK(try_catch.HasCaught());
409
  }
410
411
  // Convert the termination exception into a regular exception.
412

46449
  if (timed_out || received_signal) {
413

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

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

121
  if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
668
    try_catch.ReThrow();
669
  }
670
}
671
672
5508
void ModuleWrap::SetInitializeImportMetaObjectCallback(
673
    const FunctionCallbackInfo<Value>& args) {
674
5508
  Environment* env = Environment::GetCurrent(args);
675
5508
  Isolate* isolate = env->isolate();
676
677
5508
  CHECK_EQ(args.Length(), 1);
678
5508
  CHECK(args[0]->IsFunction());
679
5508
  Local<Function> import_meta_callback = args[0].As<Function>();
680
5508
  env->set_host_initialize_import_meta_object_callback(import_meta_callback);
681
682
5508
  isolate->SetHostInitializeImportMetaObjectCallback(
683
      HostInitializeImportMetaObjectCallback);
684
5508
}
685
686
46234
MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback(
687
    Local<Context> context, Local<Module> module) {
688
46234
  Environment* env = Environment::GetCurrent(context);
689
46234
  Isolate* isolate = env->isolate();
690
691
46234
  ModuleWrap* obj = GetFromModule(env, module);
692
693
92468
  TryCatchScope try_catch(env);
694
  Local<Function> synthetic_evaluation_steps =
695
138702
      obj->object()->GetInternalField(kSyntheticEvaluationStepsSlot)
696
46234
          .As<Function>();
697
138702
  obj->object()->SetInternalField(
698
      kSyntheticEvaluationStepsSlot, Undefined(isolate));
699
  MaybeLocal<Value> ret = synthetic_evaluation_steps->Call(context,
700
92468
      obj->object(), 0, nullptr);
701
46234
  if (ret.IsEmpty()) {
702
5
    CHECK(try_catch.HasCaught());
703
  }
704

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