FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
node/src/module_wrap.cc at main · MoLow/node · GitHub
MoLow
/
node
Public
forked from
nodejs/node
Notifications
You must be signed in to change notification settings
Fork
2
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
node
/
src
/
module_wrap.cc
Copy path
More file actions
More file actions
Latest commit
History
History
History
1711 lines (1495 loc) · 58.5 KB
Breadcrumbs
node
/
src
/
module_wrap.cc
Copy path
File metadata and controls
1711 lines (1495 loc) · 58.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
include
"
module_wrap.h
"
#
include
"
debug_utils-inl.h
"
#
include
"
env.h
"
#
include
"
memory_tracker-inl.h
"
#
include
"
node_contextify.h
"
#
include
"
node_errors.h
"
#
include
"
node_external_reference.h
"
#
include
"
node_internals.h
"
#
include
"
node_process-inl.h
"
#
include
"
node_sea.h
"
#
include
"
node_url.h
"
#
include
"
node_watchdog.h
"
#
include
"
util-inl.h
"
#
include
<
sys/stat.h
>
//
S_IFDIR
#
include
<
algorithm
>
namespace
node
{
namespace
loader
{
using
errors::TryCatchScope;
using
node::contextify::ContextifyContext;
using
v8::Array;
using
v8::ArrayBufferView;
using
v8::Boolean;
using
v8::Context;
using
v8::Data;
using
v8::EscapableHandleScope;
using
v8::Exception;
using
v8::FixedArray;
using
v8::Function;
using
v8::FunctionCallbackInfo;
using
v8::FunctionTemplate;
using
v8::Global;
using
v8::HandleScope;
using
v8::Int32;
using
v8::Integer;
using
v8::Isolate;
using
v8::Just;
using
v8::JustVoid;
using
v8::Local;
using
v8::LocalVector;
using
v8::Maybe;
using
v8::MaybeLocal;
using
v8::MemorySpan;
using
v8::Message;
using
v8::MicrotaskQueue;
using
v8::Module;
using
v8::ModuleImportPhase;
using
v8::ModuleRequest;
using
v8::Name;
using
v8::Nothing;
using
v8::Null;
using
v8::Object;
using
v8::ObjectTemplate;
using
v8::PrimitiveArray;
using
v8::Promise;
using
v8::PromiseRejectEvent;
using
v8::PropertyAttribute;
using
v8::PropertyCallbackInfo;
using
v8::ScriptCompiler;
using
v8::ScriptOrigin;
using
v8::String;
using
v8::Symbol;
using
v8::UnboundModuleScript;
using
v8::Undefined;
using
v8::Value;
inline
bool
DataIsString
(Local<Data> data) {
return
data->
IsValue
() && data.
As
<Value>()->
IsString
();
}
void
ModuleCacheKey::MemoryInfo
(MemoryTracker* tracker)
const
{
tracker->
TrackField
(
"
specifier
"
, specifier);
tracker->
TrackField
(
"
import_attributes
"
, import_attributes);
}
std::string
ModuleCacheKey::ToString
()
const
{
std::string result =
"
ModuleCacheKey(
\"
"
+ specifier +
"
\"
"
;
if
(!import_attributes.
empty
()) {
result +=
"
, {
"
;
bool
first =
true
;
for
(
const
auto
& attr : import_attributes) {
if
(first) {
first =
false
;
}
else
{
result +=
"
,
"
;
}
result += attr.
first
+
"
:
"
+ attr.
second
;
}
result +=
"
}
"
;
}
result +=
"
)
"
;
return
result;
}
template
<
int
elements_per_attribute>
ModuleCacheKey
ModuleCacheKey::From
(Local<String> specifier,
Local<FixedArray> import_attributes) {
CHECK_EQ
(import_attributes->
Length
() % elements_per_attribute,
0
);
Isolate* isolate =
Isolate::GetCurrent
();
std::
size_t
h1 = specifier->
GetIdentityHash
();
size_t
num_attributes = import_attributes->
Length
() / elements_per_attribute;
ImportAttributeVector attributes;
attributes.
reserve
(num_attributes);
std::
size_t
h2 =
0
;
for
(
int
i =
0
; i < import_attributes->
Length
();
i += elements_per_attribute) {
DCHECK
(
DataIsString
(import_attributes->
Get
(i)));
DCHECK
(
DataIsString
(import_attributes->
Get
(i +
1
)));
Local<String> v8_key = import_attributes->
Get
(i).
As
<String>();
Local<String> v8_value = import_attributes->
Get
(i +
1
).
As
<String>();
Utf8Value
key_utf8
(isolate, v8_key);
Utf8Value
value_utf8
(isolate, v8_value);
attributes.
emplace_back
(key_utf8.
ToString
(), value_utf8.
ToString
());
h2 ^= v8_key->
GetIdentityHash
();
h2 ^= v8_value->
GetIdentityHash
();
}
//
Combine the hashes using a simple XOR and bit shift to reduce
//
collisions. Note that the hash does not guarantee uniqueness.
std::
size_t
hash = h1 ^ (h2 <<
1
);
Utf8Value
utf8_specifier
(isolate, specifier);
return
ModuleCacheKey{utf8_specifier.
ToString
(), attributes, hash};
}
ModuleCacheKey
ModuleCacheKey::From
(Local<ModuleRequest> v8_request) {
return
From
(v8_request->
GetSpecifier
(), v8_request->
GetImportAttributes
());
}
ModuleWrap::ModuleWrap
(Realm* realm,
Local<Object> object,
Local<Module>
module
,
Local<String> url,
Local<Object> context_object,
Local<Value> synthetic_evaluation_step)
: BaseObject(realm, object),
url_
(Utf8Value(realm->
isolate
(), url).ToString()),
module_(realm->
isolate
(), module),
module_hash_(
module
->
GetIdentityHash
()) {
realm->
env
()->
hash_to_module_map
.
emplace
(module_hash_,
this
);
object->
SetInternalField
(
kModuleSlot
,
module
);
object->
SetInternalField
(
kModuleSourceObjectSlot
,
v8::Undefined
(realm->
isolate
()));
object->
SetInternalField
(
kSyntheticEvaluationStepsSlot
,
synthetic_evaluation_step);
object->
SetInternalField
(
kContextObjectSlot
, context_object);
object->
SetInternalField
(
kLinkedRequestsSlot
,
v8::Undefined
(realm->
isolate
()));
if
(!synthetic_evaluation_step->
IsUndefined
()) {
synthetic_ =
true
;
//
Synthetic modules have no dependencies.
linked_ =
true
;
}
MakeWeak
();
module_.
SetWeak
();
}
ModuleWrap::~ModuleWrap
() {
auto
range =
env
()->
hash_to_module_map
.
equal_range
(module_hash_);
for
(
auto
it = range.
first
; it != range.
second
; ++it) {
if
(it->
second
==
this
) {
env
()->
hash_to_module_map
.
erase
(it);
break
;
}
}
}
Local<Context>
ModuleWrap::context
()
const
{
Local<Value> obj =
object
()->
GetInternalField
(
kContextObjectSlot
).
As
<Value>();
//
If this fails, there is likely a bug e.g. ModuleWrap::context() is accessed
//
before the ModuleWrap constructor completes.
CHECK
(obj->
IsObject
());
return
obj.
As
<Object>()->
GetCreationContextChecked
();
}
ModuleWrap*
ModuleWrap::GetFromModule
(Environment* env,
Local<Module>
module
) {
auto
range = env->
hash_to_module_map
.
equal_range
(
module
->
GetIdentityHash
());
for
(
auto
it = range.
first
; it != range.
second
; ++it) {
if
(it->
second
->
module_
==
module
) {
return
it->
second
;
}
}
return
nullptr
;
}
Maybe<
bool
>
ModuleWrap::CheckUnsettledTopLevelAwait
() {
Isolate* isolate =
env
()->
isolate
();
Local<Context> context =
env
()->
context
();
//
This must be invoked when the environment is shutting down, and the module
//
is kept alive by the module wrap via an internal field.
CHECK
(
env
()->
exiting
());
CHECK
(!module_.
IsEmpty
());
Local<Module>
module
= module_.
Get
(isolate);
//
It's a synthetic module, likely a facade wrapping CJS.
if
(!
module
->
IsSourceTextModule
()) {
return
Just
(
true
);
}
if
(!
HasAsyncGraph
()) {
//
There is no TLA, no need to check.
return
Just
(
true
);
}
auto
stalled_messages =
std::get<
1
>(
module
->
GetStalledTopLevelAwaitMessages
(isolate));
if
(stalled_messages.
empty
()) {
return
Just
(
true
);
}
if
(
env
()->
options
()->
warnings
) {
for
(
auto
& message : stalled_messages) {
std::string reason =
"
Warning: Detected unsettled top-level await at
"
;
std::string info =
FormatErrorMessage
(isolate, context,
"
"
, message,
true
);
reason += info;
FPrintF
(stderr,
"
%s
\n
"
, reason);
}
}
return
Just
(
false
);
}
bool
ModuleWrap::HasAsyncGraph
() {
if
(!has_async_graph_.
has_value
()) {
Isolate* isolate =
env
()->
isolate
();
HandleScope
scope
(isolate);
has_async_graph_ = module_.
Get
(isolate)->
IsGraphAsync
();
}
return
has_async_graph_.
value
();
}
Local<PrimitiveArray>
ModuleWrap::GetHostDefinedOptions
(
Isolate* isolate, Local<Symbol> id_symbol) {
Local<PrimitiveArray> host_defined_options =
PrimitiveArray::New
(isolate, HostDefinedOptions::
kLength
);
host_defined_options->
Set
(isolate, HostDefinedOptions::
kID
, id_symbol);
return
host_defined_options;
}
//
new ModuleWrap(url, context, source, lineOffset, columnOffset[, cachedData]);
//
new ModuleWrap(url, context, source, lineOffset, columnOffset,
//
idSymbol);
//
new ModuleWrap(url, context, exportNames, evaluationCallback[, cjsModule])
void
ModuleWrap::New
(
const
FunctionCallbackInfo<Value>& args) {
CHECK
(args.
IsConstructCall
());
CHECK_GE
(args.
Length
(),
3
);
Realm* realm =
Realm::GetCurrent
(args);
Isolate* isolate = realm->
isolate
();
Local<Object> that = args.
This
();
CHECK
(args[
0
]->
IsString
());
Local<String> url = args[
0
].
As
<String>();
Local<Context> context;
ContextifyContext* contextify_context =
nullptr
;
if
(args[
1
]->
IsUndefined
()) {
context = that->
GetCreationContextChecked
();
}
else
{
CHECK
(args[
1
]->
IsObject
());
contextify_context =
ContextifyContext::ContextFromContextifiedSandbox
(
realm->
env
(), args[
1
].
As
<Object>());
CHECK_NOT_NULL
(contextify_context);
context = contextify_context->
context
();
}
int
line_offset =
0
;
int
column_offset =
0
;
bool
synthetic = args[
2
]->
IsArray
();
bool
can_use_builtin_cache =
false
;
Local<PrimitiveArray> host_defined_options =
PrimitiveArray::New
(isolate, HostDefinedOptions::
kLength
);
Local<Symbol> id_symbol;
if
(synthetic) {
//
new ModuleWrap(url, context, exportNames, evaluationCallback[,
//
cjsModule])
CHECK
(args[
3
]->
IsFunction
());
}
else
{
//
new ModuleWrap(url, context, source, lineOffset, columnOffset[,
//
cachedData]);
//
new ModuleWrap(url, context, source, lineOffset, columnOffset,
//
idSymbol);
CHECK
(args[
2
]->
IsString
());
CHECK
(args[
3
]->
IsNumber
());
line_offset = args[
3
].
As
<Int32>()->
Value
();
CHECK
(args[
4
]->
IsNumber
());
column_offset = args[
4
].
As
<Int32>()->
Value
();
if
(args[
5
]->
IsSymbol
()) {
id_symbol = args[
5
].
As
<Symbol>();
can_use_builtin_cache =
(id_symbol ==
realm->
isolate_data
()->
source_text_module_default_hdo
());
}
else
{
id_symbol =
Symbol::New
(isolate, url);
}
host_defined_options =
GetHostDefinedOptions
(isolate, id_symbol);
if
(that->
SetPrivate
(context,
realm->
isolate_data
()->
host_defined_option_symbol
(),
id_symbol)
.
IsNothing
()) {
return
;
}
}
ShouldNotAbortOnUncaughtScope
no_abort_scope
(realm->
env
());
TryCatchScope
try_catch
(realm->
env
());
Local<Module>
module
;
{
Context::Scope
context_scope
(context);
if
(synthetic) {
CHECK
(args[
2
]->
IsArray
());
Local<Array> export_names_arr = args[
2
].
As
<Array>();
uint32_t
len = export_names_arr->
Length
();
LocalVector<String>
export_names
(realm->
isolate
(), len);
for
(
uint32_t
i =
0
; i < len; i++) {
Local<Value> export_name_val;
if
(!export_names_arr->
Get
(context, i).
ToLocal
(&export_name_val)) {
return
;
}
CHECK
(export_name_val->
IsString
());
export_names[i] = export_name_val.
As
<String>();
}
const
MemorySpan<
const
Local<String>>
span
(export_names.
begin
(),
export_names.
size
());
module
=
Module::CreateSyntheticModule
(
isolate, url, span, SyntheticModuleEvaluationStepsCallback);
}
else
{
//
When we are compiling for the default loader, this will be
//
std::nullopt, and CompileSourceTextModule() should use
//
on-disk cache.
std::optional<ScriptCompiler::CachedData*> user_cached_data;
if
(id_symbol !=
realm->
isolate_data
()->
source_text_module_default_hdo
()) {
user_cached_data =
nullptr
;
}
if
(args[
5
]->
IsArrayBufferView
()) {
CHECK
(!can_use_builtin_cache);
//
We don't use this option internally.
Local<ArrayBufferView> cached_data_buf = args[
5
].
As
<ArrayBufferView>();
uint8_t
* data =
static_cast
<
uint8_t
*>(cached_data_buf->
Buffer
()->
Data
());
user_cached_data =
new
ScriptCompiler::CachedData
(data + cached_data_buf->
ByteOffset
(),
cached_data_buf->
ByteLength
());
}
#
ifndef
DISABLE_SINGLE_EXECUTABLE_APPLICATION
//
For embedder ESM in a SEA, use the bundled code cache if available.
if
(id_symbol == realm->
isolate_data
()->
embedder_module_hdo
() &&
sea::IsSingleExecutable
()) {
sea::SeaResource sea =
sea::FindSingleExecutableResource
();
if
(sea.
use_code_cache
()) {
std::string_view data = sea.
code_cache
.
value
();
user_cached_data =
new
ScriptCompiler::CachedData
(
reinterpret_cast
<
const
uint8_t
*>(data.
data
()),
static_cast
<
int
>(data.
size
()),
ScriptCompiler::CachedData::BufferNotOwned);
}
}
#
endif
//
!DISABLE_SINGLE_EXECUTABLE_APPLICATION
Local<String> source_text = args[
2
].
As
<String>();
bool
cache_rejected =
false
;
if
(!
CompileSourceTextModule
(realm,
source_text,
url,
line_offset,
column_offset,
host_defined_options,
user_cached_data,
&cache_rejected)
.
ToLocal
(&
module
)) {
if
(try_catch.
HasCaught
() && !try_catch.
HasTerminated
()) {
CHECK
(!try_catch.
Message
().
IsEmpty
());
CHECK
(!try_catch.
Exception
().
IsEmpty
());
AppendExceptionLine
(realm->
env
(),
try_catch.
Exception
(),
try_catch.
Message
(),
ErrorHandlingMode::
MODULE_ERROR
);
try_catch.
ReThrow
();
}
return
;
}
if
(user_cached_data.
has_value
() && user_cached_data.
value
() !=
nullptr
) {
#
ifndef
DISABLE_SINGLE_EXECUTABLE_APPLICATION
if
(id_symbol == realm->
isolate_data
()->
embedder_module_hdo
() &&
sea::IsSingleExecutable
()) {
if
(cache_rejected) {
per_process::Debug
(DebugCategory::
SEA
,
"
SEA module code cache rejected
\n
"
);
ProcessEmitWarningSync
(realm->
env
(),
"
Code cache data rejected.
"
);
}
else
{
per_process::Debug
(DebugCategory::
SEA
,
"
SEA module code cache accepted
\n
"
);
}
}
else
//
NOLINT(readability/braces)
#
endif
//
!DISABLE_SINGLE_EXECUTABLE_APPLICATION
if
(cache_rejected) {
THROW_ERR_VM_MODULE_CACHED_DATA_REJECTED
(
realm,
"
cachedData buffer was rejected
"
);
try_catch.
ReThrow
();
return
;
}
}
if
(that->
Set
(context,
realm->
env
()->
has_top_level_await_string
(),
Boolean::New
(isolate,
module
->
HasTopLevelAwait
()))
.
IsNothing
()) {
return
;
}
if
(that->
Set
(context,
realm->
env
()->
source_url_string
(),
module
->
GetUnboundModuleScript
()->
GetSourceURL
())
.
IsNothing
()) {
return
;
}
if
(that->
Set
(context,
realm->
env
()->
source_map_url_string
(),
module
->
GetUnboundModuleScript
()->
GetSourceMappingURL
())
.
IsNothing
()) {
return
;
}
}
}
if
(that->
Set
(context,
realm->
isolate_data
()->
synthetic_string
(),
Boolean::New
(isolate, synthetic))
.
IsNothing
()) {
return
;
}
if
(!that->
Set
(context, realm->
isolate_data
()->
url_string
(), url)
.
FromMaybe
(
false
)) {
return
;
}
if
(synthetic && args[
4
]->
IsObject
() &&
that->
Set
(context, realm->
isolate_data
()->
imported_cjs_symbol
(), args[
4
])
.
IsNothing
()) {
return
;
}
//
Initialize an empty slot for source map cache before the object is frozen.
if
(that->
SetPrivate
(context,
realm->
isolate_data
()->
source_map_data_private_symbol
(),
Undefined
(isolate))
.
IsNothing
()) {
return
;
}
//
Use the extras object as an object whose GetCreationContext() will be the
//
original `context`, since the `Context` itself strictly speaking cannot
//
be stored in an internal field.
Local<Object> context_object = context->
GetExtrasBindingObject
();
Local<Value> synthetic_evaluation_step =
synthetic ? args[
3
] :
Undefined
(realm->
isolate
()).
As
<Value>();
ModuleWrap* obj =
new
ModuleWrap
(
realm, that,
module
, url, context_object, synthetic_evaluation_step);
obj->
contextify_context_
= contextify_context;
args.
GetReturnValue
().
Set
(that);
}
MaybeLocal<Module>
ModuleWrap::CompileSourceTextModule
(
Realm* realm,
Local<String> source_text,
Local<String> url,
int
line_offset,
int
column_offset,
Local<PrimitiveArray> host_defined_options,
std::optional<ScriptCompiler::CachedData*> user_cached_data,
bool
* cache_rejected) {
Isolate* isolate = realm->
isolate
();
EscapableHandleScope
scope
(isolate);
ScriptOrigin
origin
(url,
line_offset,
column_offset,
true
,
//
is cross origin
-
1
,
//
script id
Local<Value>(),
//
source map URL
false
,
//
is opaque (?)
false
,
//
is WASM
true
,
//
is ES Module
host_defined_options);
ScriptCompiler::CachedData* cached_data =
nullptr
;
CompileCacheEntry* cache_entry =
nullptr
;
//
When compiling for the default loader, user_cached_data is std::nullptr.
//
When compiling for vm.Module, it's either nullptr or a pointer to the
//
cached data.
if
(user_cached_data.
has_value
()) {
cached_data = user_cached_data.
value
();
}
else
if
(realm->
env
()->
use_compile_cache
()) {
cache_entry = realm->
env
()->
compile_cache_handler
()->
GetOrInsert
(
source_text, url, CachedCodeType::
kESM
);
}
if
(cache_entry !=
nullptr
&& cache_entry->
cache
!=
nullptr
) {
//
source will take ownership of cached_data.
cached_data = cache_entry->
CopyCache
();
}
ScriptCompiler::Source
source
(source_text, origin, cached_data);
ScriptCompiler::CompileOptions options;
if
(cached_data ==
nullptr
) {
options = ScriptCompiler::
kNoCompileOptions
;
}
else
{
options = ScriptCompiler::
kConsumeCodeCache
;
}
Local<Module>
module
;
if
(!
ScriptCompiler::CompileModule
(isolate, &source, options)
.
ToLocal
(&
module
)) {
return
scope.
EscapeMaybe
(MaybeLocal<Module>());
}
if
(options == ScriptCompiler::
kConsumeCodeCache
) {
*cache_rejected = source.
GetCachedData
()->
rejected
;
}
if
(cache_entry !=
nullptr
) {
realm->
env
()->
compile_cache_handler
()->
MaybeSave
(
cache_entry,
module
, *cache_rejected);
}
return
scope.
Escape
(
module
);
}
ModulePhase
to_phase_constant
(ModuleImportPhase phase) {
switch
(phase) {
case
ModuleImportPhase::
kEvaluation
:
return
kEvaluationPhase
;
case
ModuleImportPhase::
kDefer
:
return
kDeferPhase
;
case
ModuleImportPhase::
kSource
:
return
kSourcePhase
;
default
:
UNREACHABLE
();
}
}
static
Local<Object>
createImportAttributesContainer
(
Realm* realm,
Isolate* isolate,
Local<FixedArray> raw_attributes,
const
int
elements_per_attribute) {
CHECK_EQ
(raw_attributes->
Length
() % elements_per_attribute,
0
);
size_t
num_attributes = raw_attributes->
Length
() / elements_per_attribute;
LocalVector<Name>
names
(isolate, num_attributes);
LocalVector<Value>
values
(isolate, num_attributes);
for
(
int
i =
0
; i < raw_attributes->
Length
(); i += elements_per_attribute) {
Local<Data> key = raw_attributes->
Get
(i);
Local<Data> value = raw_attributes->
Get
(i +
1
);
DCHECK
(
DataIsString
(key));
DCHECK
(
DataIsString
(value));
int
idx = i / elements_per_attribute;
names[idx] = key.
As
<String>();
values[idx] = value.
As
<String>();
}
Local<Object> attributes =
Object::New
(
isolate,
Null
(isolate), names.
data
(), values.
data
(), num_attributes);
attributes->
SetIntegrityLevel
(realm->
context
(), v8::IntegrityLevel::
kFrozen
)
.
Check
();
return
attributes;
}
static
Local<Array>
createModuleRequestsContainer
(
Realm* realm, Isolate* isolate, Local<FixedArray> raw_requests) {
EscapableHandleScope
scope
(isolate);
Local<Context> context = realm->
context
();
LocalVector<Value>
requests
(isolate, raw_requests->
Length
());
for
(
int
i =
0
; i < raw_requests->
Length
(); i++) {
DCHECK
(raw_requests->
Get
(i)->
IsModuleRequest
());
Local<ModuleRequest> module_request =
raw_requests->
Get
(i).
As
<ModuleRequest>();
Local<String> specifier = module_request->
GetSpecifier
();
//
Contains the import attributes for this request in the form:
//
[key1, value1, source_offset1, key2, value2, source_offset2, ...].
Local<FixedArray> raw_attributes = module_request->
GetImportAttributes
();
Local<Object> attributes =
createImportAttributesContainer
(realm, isolate, raw_attributes,
3
);
ModuleImportPhase phase = module_request->
GetPhase
();
Local<Name> names[] = {
realm->
isolate_data
()->
specifier_string
(),
realm->
isolate_data
()->
attributes_string
(),
realm->
isolate_data
()->
phase_string
(),
};
Local<Value> values[] = {
specifier,
attributes,
Integer::New
(isolate,
to_phase_constant
(phase)),
};
DCHECK_EQ
(
arraysize
(names),
arraysize
(values));
Local<Object> request =
Object::New
(isolate,
Null
(isolate), names, values,
arraysize
(names));
request->
SetIntegrityLevel
(context, v8::IntegrityLevel::
kFrozen
).
Check
();
requests[i] = request;
}
return
scope.
Escape
(
Array::New
(isolate, requests.
data
(), requests.
size
()));
}
void
ModuleWrap::GetModuleRequests
(
const
FunctionCallbackInfo<Value>& args) {
Realm* realm =
Realm::GetCurrent
(args);
Isolate* isolate = args.
GetIsolate
();
Local<Object> that = args.
This
();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, that);
Local<Module>
module
= obj->
module_
.
Get
(isolate);
args.
GetReturnValue
().
Set
(
createModuleRequestsContainer
(
realm, isolate,
module
->
GetModuleRequests
()));
}
//
moduleWrap.link(moduleWraps)
void
ModuleWrap::Link
(
const
FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.
GetIsolate
();
HandleScope
handle_scope
(isolate);
Realm* realm =
Realm::GetCurrent
(args);
Local<Context> context = realm->
context
();
ModuleWrap* dependent;
ASSIGN_OR_RETURN_UNWRAP
(&dependent, args.
This
());
CHECK_EQ
(args.
Length
(),
1
);
Local<FixedArray> requests =
dependent->
module_
.
Get
(isolate)->
GetModuleRequests
();
Local<Array> modules = args[
0
].
As
<Array>();
std::vector<Global<Value>> modules_vector;
if
(
FromV8Array
(context, modules, &modules_vector).
IsEmpty
()) {
return
;
}
size_t
request_count =
static_cast
<
size_t
>(requests->
Length
());
CHECK_EQ
(modules_vector.
size
(), request_count);
std::vector<ModuleWrap*>
linked_module_wraps
(request_count);
//
Track the duplicated module requests. For example if a modulelooks like
//
this:
//
//
import { foo } from 'mod' with { type: 'json' };
//
import source ModSource from 'mod' with { type: 'json' };
//
import { baz } from 'mod2';
//
//
The first two module requests are identical. The map would look like
//
{ mod_key: 0, mod2_key: 2 } in this case, so that module request 0 and
//
module request 1 would be mapped to mod_key and both should resolve to the
//
module identified by module request 0 (the first one with this identity),
//
and module request 2 should resolve the module identified by index 2.
std::unordered_map<ModuleCacheKey,
size_t
, ModuleCacheKey::Hash>
module_request_map;
for
(
size_t
i =
0
; i < request_count; i++) {
//
TODO(joyeecheung): merge this with the serializeKey() in module_map.js.
//
This currently doesn't sort the import attributes.
Local<Value> module_value = modules_vector[i].
Get
(isolate);
ModuleCacheKey module_cache_key =
ModuleCacheKey::From
(requests->
Get
(i).
As
<ModuleRequest>());
auto
it = module_request_map.
find
(module_cache_key);
if
(it == module_request_map.
end
()) {
//
This is the first request with this identity, record it - any mismatch
//
for this would only be found in subsequent requests, so no need to
//
check here.
module_request_map[module_cache_key] = i;
}
else
{
//
This identity has been seen before, check for mismatch.
size_t
first_seen_index = it->
second
;
//
Check that the module is the same as the one resolved by the first
//
request with this identity.
Local<Value> first_seen_value =
modules_vector[first_seen_index].
Get
(isolate);
if
(!module_value->
StrictEquals
(first_seen_value)) {
//
If the module is different from the one of the same request, throw an
//
error.
THROW_ERR_MODULE_LINK_MISMATCH
(
realm->
env
(),
"
Module request '%s' at index %d must be linked
"
"
to the same module requested at index %d
"
,
module_cache_key.
ToString
(),
i,
first_seen_index);
return
;
}
}
CHECK
(module_value->
IsObject
());
//
Guaranteed by link methods in JS land.
ModuleWrap* resolved =
BaseObject::Unwrap<ModuleWrap>(module_value.
As
<Object>());
CHECK_NOT_NULL
(resolved);
//
Guaranteed by link methods in JS land.
linked_module_wraps[i] = resolved;
}
args.
This
()->
SetInternalField
(
kLinkedRequestsSlot
, modules);
std::swap
(dependent->
linked_module_wraps_
, linked_module_wraps);
dependent->
linked_
=
true
;
}
void
ModuleWrap::Instantiate
(
const
FunctionCallbackInfo<Value>& args) {
Realm* realm =
Realm::GetCurrent
(args);
Isolate* isolate = args.
GetIsolate
();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, args.
This
());
Local<Context> context = obj->
context
();
Local<Module>
module
= obj->
module_
.
Get
(isolate);
Environment* env = realm->
env
();
if
(!obj->
IsLinked
()) {
THROW_ERR_VM_MODULE_LINK_FAILURE
(env,
"
module is not linked
"
);
return
;
}
{
TryCatchScope
try_catch
(env);
USE
(
module
->
InstantiateModule
(
context, ResolveModuleCallback, ResolveSourceCallback));
if
(try_catch.
HasCaught
() && !try_catch.
HasTerminated
()) {
CHECK
(!try_catch.
Message
().
IsEmpty
());
CHECK
(!try_catch.
Exception
().
IsEmpty
());
AppendExceptionLine
(env,
try_catch.
Exception
(),
try_catch.
Message
(),
ErrorHandlingMode::
MODULE_ERROR
);
try_catch.
ReThrow
();
return
;
}
}
}
void
ModuleWrap::Evaluate
(
const
FunctionCallbackInfo<Value>& args) {
Realm* realm =
Realm::GetCurrent
(args);
Isolate* isolate = realm->
isolate
();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, args.
This
());
Local<Context> context = obj->
context
();
Local<Module>
module
= obj->
module_
.
Get
(isolate);
ContextifyContext* contextify_context = obj->
contextify_context_
;
MicrotaskQueue* microtask_queue =
nullptr
;
if
(contextify_context !=
nullptr
)
microtask_queue = contextify_context->
microtask_queue
();
//
module.evaluate(timeout, breakOnSigint)
CHECK_EQ
(args.
Length
(),
2
);
CHECK
(args[
0
]->
IsNumber
());
int64_t
timeout;
if
(!args[
0
]->
IntegerValue
(realm->
context
()).
To
(&timeout)) {
return
;
}
CHECK
(args[
1
]->
IsBoolean
());
bool
break_on_sigint = args[
1
]->
IsTrue
();
ShouldNotAbortOnUncaughtScope
no_abort_scope
(realm->
env
());
TryCatchScope
try_catch
(realm->
env
());
bool
timed_out =
false
;
bool
received_signal =
false
;
MaybeLocal<Value> result;
{
auto
wd = timeout != -
1
? std::make_optional<Watchdog>(isolate, timeout, &timed_out)
: std::
nullopt
;
auto
swd = break_on_sigint ? std::make_optional<SigintWatchdog>(
isolate, &received_signal)
: std::
nullopt
;
result =
module
->
Evaluate
(context);
Local<Value> res;
if
(result.
ToLocal
(&res) && microtask_queue) {
DCHECK
(res->
IsPromise
());
//
To address https://github.com/nodejs/node/issues/59541 when the
//
module has its own separate microtask queue in microtaskMode
//
"afterEvaluate", we avoid returning a promise built inside the
//
module's own context.
//
//
Instead, we build a promise in the outer context, which we resolve
//
with {result}, then we checkpoint the module's own queue, and finally
//
we return the outer-context promise.
//
//
If we simply returned the inner promise {result} directly, per
//
https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob, the outer
//
context, when resolving a promise coming from a different context,
//
would need to enqueue a task (known as a thenable job task) onto the
//
queue of that different context (the module's context). But this queue
//
will normally not be checkpointed after evaluate() returns.
//
//
This means that the execution flow in the outer context would
//
silently fall through at the statement (in lib/internal/vm/module.js):
//
await this[kWrap].evaluate(timeout, breakOnSigint)
//
//
This is true for any promises created inside the module's context
//
and made available to the outer context, as the node:vm doc explains.
//
//
We must handle this particular return value differently to make it
//
possible to await on the result of evaluate().
Local<Context> outer_context = isolate->
GetCurrentContext
();
Local<Promise::Resolver> resolver;
if
(!
Promise::Resolver::New
(outer_context).
ToLocal
(&resolver)) {
result = {};
}
if
(resolver->
Resolve
(outer_context, res).
IsNothing
()) {
result = {};
}
result = resolver->
GetPromise
();
microtask_queue->
PerformCheckpoint
(isolate);
}
}
if
(result.
IsEmpty
()) {
CHECK
(try_catch.
HasCaught
());
}
//
Convert the termination exception into a regular exception.
if
(timed_out || received_signal) {
if
(!realm->
env
()->
is_main_thread
() && realm->
env
()->
is_stopping
())
return
;
isolate->
CancelTerminateExecution
();
//
It is possible that execution was terminated by another timeout in
//
which this timeout is nested, so check whether one of the watchdogs
//
from this invocation is responsible for termination.
if
(timed_out) {
THROW_ERR_SCRIPT_EXECUTION_TIMEOUT
(realm->
env
(), timeout);
}
else
if
(received_signal) {
THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED
(realm->
env
());
}
}
if
(try_catch.
HasCaught
()) {
if
(!try_catch.
HasTerminated
())
try_catch.
ReThrow
();
return
;
}
Local<Value> res;
if
(result.
ToLocal
(&res)) {
args.
GetReturnValue
().
Set
(res);
}
}
Maybe<
void
>
ThrowIfPromiseRejected
(Realm* realm, Local<Promise> promise) {
Isolate* isolate = realm->
isolate
();
Local<Context> context = realm->
context
();
if
(promise->
State
() != Promise::PromiseState::
kRejected
) {
return
JustVoid
();
}
//
The rejected promise is created by V8, so we don't get a chance to mark
//
it as resolved before the rejection happens from evaluation. But we can
//
tell the promise rejection callback to treat it as a promise rejected
//
before handler was added which would remove it from the unhandled
//
rejection handling, since we are converting it into an error and throw
//
from here directly.
Local<Value> type =
Integer::New
(isolate,
static_cast
<
int32_t
>(
PromiseRejectEvent::
kPromiseHandlerAddedAfterReject
));
Local<Value> args[] = {type, promise,
Undefined
(isolate)};
if
(realm->
promise_reject_callback
()
->
Call
(context,
Undefined
(isolate),
arraysize
(args), args)
.
IsEmpty
()) {
return
Nothing<
void
>();
}
Local<Value> exception = promise->
Result
();
Local<Message> message =
Exception::CreateMessage
(isolate, exception);
AppendExceptionLine
(
realm->
env
(), exception, message, ErrorHandlingMode::
MODULE_ERROR
);
isolate->
ThrowException
(exception);
return
Nothing<
void
>();
}
void
ThrowIfPromiseRejected
(
const
FunctionCallbackInfo<Value>& args) {
if
(!args[
0
]->
IsPromise
()) {
return
;
}
ThrowIfPromiseRejected
(
Realm::GetCurrent
(args), args[
0
].
As
<Promise>());
}
void
ModuleWrap::EvaluateSync
(
const
FunctionCallbackInfo<Value>& args) {
Realm* realm =
Realm::GetCurrent
(args);
Isolate* isolate = args.
GetIsolate
();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, args.
This
());
Local<Context> context = obj->
context
();
Local<Module>
module
= obj->
module_
.
Get
(isolate);
Environment* env = realm->
env
();
Local<Value> result;
{
TryCatchScope
try_catch
(env);
if
(!
module
->
Evaluate
(context).
ToLocal
(&result)) {
if
(try_catch.
HasCaught
()) {
if
(!try_catch.
HasTerminated
()) {
try_catch.
ReThrow
();
}
return
;
}
}
}
CHECK
(result->
IsPromise
());
Local<Promise> promise = result.
As
<Promise>();
if
(
ThrowIfPromiseRejected
(realm, promise).
IsNothing
()) {
return
;
}
//
Graphs with top-level await are rejected by the caller before evaluation
//
starts, so the promise must have been settled synchronously.
CHECK
(!obj->
HasAsyncGraph
());
CHECK_EQ
(promise->
State
(), Promise::PromiseState::
kFulfilled
);
args.
GetReturnValue
().
Set
(
module
->
GetModuleNamespace
());
}
void
ModuleWrap::GetNamespace
(
const
FunctionCallbackInfo<Value>& args) {
Realm* realm =
Realm::GetCurrent
(args);
Isolate* isolate = args.
GetIsolate
();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, args.
This
());
Local<Module>
module
= obj->
module_
.
Get
(isolate);
if
(
module
->
GetStatus
() < Module::
kInstantiated
) {
return
THROW_ERR_MODULE_NOT_INSTANTIATED
(realm->
env
());
}
Local<Value> result =
module
->
GetModuleNamespace
();
args.
GetReturnValue
().
Set
(result);
}
void
ModuleWrap::SetModuleSourceObject
(
const
FunctionCallbackInfo<Value>& args) {
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, args.
This
());
CHECK_EQ
(args.
Length
(),
1
);
CHECK
(args[
0
]->
IsObject
());
CHECK
(obj->
object
()
->
GetInternalField
(
kModuleSourceObjectSlot
)
.
As
<Value>()
->
IsUndefined
());
obj->
object
()->
SetInternalField
(
kModuleSourceObjectSlot
, args[
0
]);
}
void
ModuleWrap::GetModuleSourceObject
(
const
FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.
GetIsolate
();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP
(&obj, args.
This
());
CHECK_EQ
(args.
Length
(),
0
);
Local<Value> module_source_object =
obj->
object
()->
GetInternalField
(
kModuleSourceObjectSlot
).
As
<Value>();
if
(module_source_object->
IsUndefined
()) {
THROW_ERR_SOURCE_PHASE_NOT_DEFINED
(isolate, obj->
url_
);
return
;
}
args.
GetReturnValue
().
Set
(module_source_object);
}
void
ModuleWrap::GetStatus
(
const
FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.
GetIsolate
();
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL