forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathJSModuleRecord.cpp
More file actions
330 lines (295 loc) · 16.9 KB
/
JSModuleRecord.cpp
File metadata and controls
330 lines (295 loc) · 16.9 KB
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
/*
* Copyright (C) 2015-2025 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSModuleRecord.h"
#include "BuiltinNames.h"
#include "Interpreter.h"
#include "JSAsyncFunction.h"
#include "JSAsyncGeneratorFunction.h"
#include "JSCInlines.h"
#include "JSGeneratorFunction.h"
#include "JSModuleEnvironment.h"
#include "JSModuleLoader.h"
#include "JSModuleNamespaceObject.h"
#include "SourceProfiler.h"
#include "UnlinkedModuleProgramCodeBlock.h"
#include <wtf/text/MakeString.h>
namespace JSC {
const ClassInfo JSModuleRecord::s_info = { "ModuleRecord"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSModuleRecord) };
Structure* JSModuleRecord::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
}
JSModuleRecord* JSModuleRecord::create(JSGlobalObject* globalObject, VM& vm, Structure* structure, const Identifier& moduleKey, const SourceCode& sourceCode, const VariableEnvironment& declaredVariables, const VariableEnvironment& lexicalVariables, CodeFeatures features)
{
JSModuleRecord* instance = new (NotNull, allocateCell<JSModuleRecord>(vm)) JSModuleRecord(vm, structure, moduleKey, sourceCode, declaredVariables, lexicalVariables, features);
instance->finishCreation(globalObject, vm);
return instance;
}
JSModuleRecord::JSModuleRecord(VM& vm, Structure* structure, const Identifier& moduleKey, const SourceCode& sourceCode, const VariableEnvironment& declaredVariables, const VariableEnvironment& lexicalVariables, CodeFeatures features)
: Base(vm, structure, moduleKey)
, m_sourceCode(sourceCode)
, m_declaredVariables(declaredVariables)
, m_lexicalVariables(lexicalVariables)
, m_features(features)
{
}
#if USE(BUN_JSC_ADDITIONS)
size_t JSModuleRecord::estimatedSize(JSCell* cell, VM& vm)
{
const auto& thisObject = jsCast<JSModuleRecord*>(cell);
size_t size = Base::estimatedSize(cell, vm);
const SourceCode& sourceCode = thisObject->sourceCode();
StringView view = sourceCode.provider() ? sourceCode.provider()->source() : StringView();
size += view.length() * (view.is8Bit() ? sizeof(Latin1Character) : sizeof(UChar));
size += sourceCode.memoryCost();
return size;
}
#endif
void JSModuleRecord::destroy(JSCell* cell)
{
JSModuleRecord* thisObject = static_cast<JSModuleRecord*>(cell);
thisObject->JSModuleRecord::~JSModuleRecord();
}
void JSModuleRecord::finishCreation(JSGlobalObject* globalObject, VM& vm)
{
Base::finishCreation(globalObject, vm);
ASSERT(inherits(info()));
}
template<typename Visitor>
void JSModuleRecord::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
JSModuleRecord* thisObject = jsCast<JSModuleRecord*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
Base::visitChildren(thisObject, visitor);
visitor.append(thisObject->m_moduleProgramExecutable);
#if USE(BUN_JSC_ADDITIONS)
visitor.reportExtraMemoryVisited(thisObject->sourceCode().memoryCost());
#endif
}
DEFINE_VISIT_CHILDREN(JSModuleRecord);
Synchronousness JSModuleRecord::link(JSGlobalObject* globalObject, JSValue scriptFetcher)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (SourceProfiler::g_profilerHook) [[unlikely]]
SourceProfiler::profile(SourceProfiler::Type::Module, sourceCode());
ModuleProgramExecutable* executable = ModuleProgramExecutable::tryCreate(globalObject, sourceCode());
RETURN_IF_EXCEPTION(scope, Synchronousness::Sync);
instantiateDeclarations(globalObject, executable, scriptFetcher);
RETURN_IF_EXCEPTION(scope, Synchronousness::Sync);
m_moduleProgramExecutable.set(vm, this, executable);
return executable->unlinkedCodeBlock()->isAsync() ? Synchronousness::Async : Synchronousness::Sync;
}
void JSModuleRecord::instantiateDeclarations(JSGlobalObject* globalObject, ModuleProgramExecutable* moduleProgramExecutable, JSValue scriptFetcher)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
SymbolTable* symbolTable = moduleProgramExecutable->moduleEnvironmentSymbolTable();
JSModuleEnvironment* moduleEnvironment = JSModuleEnvironment::create(vm, globalObject, globalObject->globalLexicalEnvironment(), symbolTable, jsTDZValue(), this);
// http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
// section 15.2.1.16.4 step 9.
// Ensure all the indirect exports are correctly resolved to unique bindings.
// Even if we avoided duplicate exports in the parser, still ambiguous exports occur due to the star export (`export * from "mod"`).
// When we see this type of ambiguity for the indirect exports here, throw a syntax error.
for (const auto& pair : exportEntries()) {
const ExportEntry& exportEntry = pair.value;
switch (exportEntry.type) {
case ExportEntry::Type::Local:
case ExportEntry::Type::Namespace:
break;
case ExportEntry::Type::Indirect: {
Resolution resolution = resolveExport(globalObject, exportEntry.exportName);
RETURN_IF_EXCEPTION(scope, void());
switch (resolution.type) {
case Resolution::Type::NotFound: {
#if USE(BUN_JSC_ADDITIONS)
if(m_isTypeScript) break;
#endif
throwSyntaxError(globalObject, scope, makeString("export '"_s, StringView(exportEntry.exportName.impl()), "' not found in '"_s, StringView(exportEntry.moduleName.impl()), "'"_s));
return;
}
case Resolution::Type::Ambiguous: {
throwSyntaxError(globalObject, scope, makeString("Cannot export '"_s, StringView(exportEntry.exportName.impl()), "' multiple times in '"_s, StringView(exportEntry.moduleName.impl()), "'"_s));
return;
}
case Resolution::Type::Error:
throwSyntaxError(globalObject, scope, "export default cannot be used with export *"_s);
return;
case Resolution::Type::Resolved:
break;
}
break;
}
}
}
// https://tc39.es/ecma262/#sec-source-text-module-record-initialize-environment step 8
// Instantiate namespace objects and initialize the bindings with them if required.
// And ensure that all the imports correctly resolved to unique bindings.
for (const auto& pair : importEntries()) {
const ImportEntry& importEntry = pair.value;
AbstractModuleRecord* importedModule = hostResolveImportedModule(globalObject, importEntry.moduleRequest);
#if CPU(ADDRESS64)
// rdar://107531050: Speculative crash mitigation
if (importedModule == std::bit_cast<AbstractModuleRecord*>(encodedJSUndefined())) [[unlikely]] {
RELEASE_ASSERT(vm.exceptionForInspection(), vm.traps().maybeNeedHandling(), vm.exceptionForInspection(), importedModule);
RELEASE_ASSERT(vm.traps().maybeNeedHandling(), vm.traps().maybeNeedHandling(), vm.exceptionForInspection(), importedModule);
if (!vm.exceptionForInspection() || !vm.traps().maybeNeedHandling()) {
throwSyntaxError(globalObject, scope, makeString("Importing module '"_s, String(importEntry.moduleRequest.impl()), "' is not found."_s));
return;
}
}
#endif
RETURN_IF_EXCEPTION(scope, void());
switch (importEntry.type) {
case AbstractModuleRecord::ImportEntryType::Namespace: {
JSModuleNamespaceObject* namespaceObject = importedModule->getModuleNamespace(globalObject);
RETURN_IF_EXCEPTION(scope, void());
bool putResult = false;
symbolTablePutTouchWatchpointSet(moduleEnvironment, globalObject, importEntry.localName, namespaceObject, /* shouldThrowReadOnlyError */ false, /* ignoreReadOnlyErrors */ true, putResult);
RETURN_IF_EXCEPTION(scope, void());
break;
}
#if USE(BUN_JSC_ADDITIONS)
case AbstractModuleRecord::ImportEntryType::SingleTypeScript:
#endif
case AbstractModuleRecord::ImportEntryType::Single: {
Resolution resolution = importedModule->resolveExport(globalObject, importEntry.importName);
RETURN_IF_EXCEPTION(scope, void());
switch (resolution.type) {
case Resolution::Type::NotFound: {
#if USE(BUN_JSC_ADDITIONS)
if(importEntry.type == AbstractModuleRecord::ImportEntryType::SingleTypeScript) {
break;
}
#endif
if (!(importEntry.localName.isNull() || importEntry.localName.isPrivateName() || importEntry.localName.isSymbol())) {
Resolution otherResolution = importedModule->resolveExport(globalObject, vm.propertyNames->defaultKeyword);
RETURN_IF_EXCEPTION(scope, void());
if (otherResolution.type == Resolution::Type::Resolved && otherResolution.localName == importEntry.localName) {
throwSyntaxError(globalObject, scope, makeString("Export named '"_s, importEntry.importName.string(), "' not found in module '"_s, importedModule->moduleKey().string(), "'. Did you mean to import default?"_s));
return;
}
}
throwSyntaxError(globalObject, scope, makeString("Export named '"_s, importEntry.importName.string(), "' not found in module '"_s, importedModule->moduleKey().string(), "'."_s));
return;
}
case Resolution::Type::Ambiguous:
throwSyntaxError(globalObject, scope, makeString("Export named '"_s, importEntry.importName.string(), "' cannot be resolved due to ambiguous multiple bindings in module '"_s, importedModule->moduleKey().string(), "'."_s));
return;
case Resolution::Type::Error: {
if (!(importEntry.localName.isNull() || importEntry.localName.isPrivateName() || importEntry.localName.isSymbol())) {
Resolution otherResolution = importedModule->resolveExport(globalObject, importEntry.localName);
RETURN_IF_EXCEPTION(scope, void());
if (otherResolution.type == Resolution::Type::Resolved) {
throwSyntaxError(globalObject, scope, makeString("module '"_s, importedModule->moduleKey().string(), "' does not have an export named 'default'. Did you mean '"_s, String(importEntry.localName.impl()), "'?"_s));
return;
}
}
throwSyntaxError(globalObject, scope, makeString("Missing 'default' export in module '"_s, importedModule->moduleKey().string(), "'."_s));
return;
}
case Resolution::Type::Resolved: {
if (vm.propertyNames->starNamespacePrivateName == resolution.localName) {
resolution.moduleRecord->getModuleNamespace(globalObject); // Force module namespace object materialization.
RETURN_IF_EXCEPTION(scope, void());
}
break;
}
}
break;
}
}
}
// http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
// section 15.2.1.16.4 step 14.
// Module environment contains the heap allocated "var", "function", "let", "const", and "class".
// When creating the environment, we initialized all the slots with empty, it's ok for lexical values.
// But for "var" and "function", we should initialize it with undefined. They are contained in the declared variables.
for (const auto& variable : declaredVariables()) {
SymbolTableEntry entry = symbolTable->get(variable.key.get());
VarOffset offset = entry.varOffset();
if (!offset.isStack()) {
bool putResult = false;
symbolTablePutTouchWatchpointSet(moduleEnvironment, globalObject, Identifier::fromUid(vm, variable.key.get()), jsUndefined(), /* shouldThrowReadOnlyError */ false, /* ignoreReadOnlyErrors */ true, putResult);
RETURN_IF_EXCEPTION(scope, void());
}
}
// http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
// section 15.2.1.16.4 step 16-a-iv.
// Initialize heap allocated function declarations.
// They can be called before the body of the module is executed under circular dependencies.
UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock = moduleProgramExecutable->unlinkedCodeBlock();
for (size_t i = 0, numberOfFunctions = unlinkedCodeBlock->numberOfFunctionDecls(); i < numberOfFunctions; ++i) {
UnlinkedFunctionExecutable* unlinkedFunctionExecutable = unlinkedCodeBlock->functionDecl(i);
SymbolTableEntry entry = symbolTable->get(unlinkedFunctionExecutable->name().impl());
VarOffset offset = entry.varOffset();
if (!offset.isStack()) {
ASSERT(!unlinkedFunctionExecutable->name().isEmpty());
if (vm.typeProfiler() || vm.controlFlowProfiler()) {
vm.functionHasExecutedCache()->insertUnexecutedRange(moduleProgramExecutable->sourceID(),
unlinkedFunctionExecutable->unlinkedFunctionStart(),
unlinkedFunctionExecutable->unlinkedFunctionEnd(),
unlinkedFunctionExecutable->ecmaName().string());
}
auto* executable = unlinkedFunctionExecutable->link(vm, moduleProgramExecutable, moduleProgramExecutable->source());
SourceParseMode parseMode = executable->parseMode();
JSFunction* function = nullptr;
if (isAsyncGeneratorWrapperParseMode(parseMode))
function = JSAsyncGeneratorFunction::create(vm, globalObject, executable, moduleEnvironment);
else if (isGeneratorWrapperParseMode(parseMode))
function = JSGeneratorFunction::create(vm, globalObject, executable, moduleEnvironment);
else if (isAsyncFunctionWrapperParseMode(parseMode))
function = JSAsyncFunction::create(vm, globalObject, executable, moduleEnvironment);
else
function = JSFunction::create(vm, globalObject, executable, moduleEnvironment);
bool putResult = false;
symbolTablePutTouchWatchpointSet(moduleEnvironment, globalObject, unlinkedFunctionExecutable->name(), function, /* shouldThrowReadOnlyError */ false, /* ignoreReadOnlyErrors */ true, putResult);
RETURN_IF_EXCEPTION(scope, void());
}
}
if (m_features & ImportMetaFeature) {
JSObject* metaProperties = globalObject->moduleLoader()->createImportMetaProperties(globalObject, identifierToJSValue(vm, moduleKey()), this, scriptFetcher);
RETURN_IF_EXCEPTION(scope, void());
bool putResult = false;
symbolTablePutTouchWatchpointSet(moduleEnvironment, globalObject, vm.propertyNames->builtinNames().metaPrivateName(), metaProperties, /* shouldThrowReadOnlyError */ false, /* ignoreReadOnlyErrors */ true, putResult);
RETURN_IF_EXCEPTION(scope, void());
}
scope.release();
setModuleEnvironment(globalObject, moduleEnvironment);
}
JSValue JSModuleRecord::evaluate(JSGlobalObject* globalObject, JSValue sentValue, JSValue resumeMode)
{
if (!m_moduleProgramExecutable)
return jsUndefined();
VM& vm = globalObject->vm();
ModuleProgramExecutable* executable = m_moduleProgramExecutable.get();
JSValue resultOrAwaitedValue = vm.interpreter.executeModuleProgram(this, executable, globalObject, moduleEnvironment(), sentValue, resumeMode);
if (JSValue state = internalField(Field::State).get(); !state.isNumber() || state.asNumber() == static_cast<unsigned>(State::Executing))
m_moduleProgramExecutable.clear();
return resultOrAwaitedValue;
}
} // namespace JSC