/
JSModuleRecord.cpp
269 lines (235 loc) · 13.5 KB
/
JSModuleRecord.cpp
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
/*
* Copyright (C) 2015-2022 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 "JSCInlines.h"
#include "JSModuleEnvironment.h"
#include "JSModuleLoader.h"
#include "JSModuleNamespaceObject.h"
#include "UnlinkedModuleProgramCodeBlock.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)
{
}
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);
}
DEFINE_VISIT_CHILDREN(JSModuleRecord);
Synchronousness JSModuleRecord::link(JSGlobalObject* globalObject, JSValue scriptFetcher)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
ModuleProgramExecutable* executable = ModuleProgramExecutable::create(globalObject, sourceCode());
EXCEPTION_ASSERT(!!scope.exception() == !executable);
if (!executable) {
throwSyntaxError(globalObject, scope);
return 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:
throwSyntaxError(globalObject, scope, makeString("Indirectly exported binding name '"_s, StringView(exportEntry.exportName.impl()), "' is not found."_s));
return;
case Resolution::Type::Ambiguous:
throwSyntaxError(globalObject, scope, makeString("Indirectly exported binding name '"_s, StringView(exportEntry.exportName.impl()), "' cannot be resolved due to ambiguous multiple bindings."_s));
return;
case Resolution::Type::Error:
throwSyntaxError(globalObject, scope, "Indirectly exported binding name 'default' cannot be resolved by star export entries."_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 (UNLIKELY(importedModule == bitwise_cast<AbstractModuleRecord*>(encodedJSUndefined()))) {
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 '", String(importEntry.moduleRequest.impl()), "' is not found."));
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;
}
case AbstractModuleRecord::ImportEntryType::Single: {
Resolution resolution = importedModule->resolveExport(globalObject, importEntry.importName);
RETURN_IF_EXCEPTION(scope, void());
switch (resolution.type) {
case Resolution::Type::NotFound:
throwSyntaxError(globalObject, scope, makeString("Importing binding name '"_s, StringView(importEntry.importName.impl()), "' is not found."_s));
return;
case Resolution::Type::Ambiguous:
throwSyntaxError(globalObject, scope, makeString("Importing binding name '"_s, StringView(importEntry.importName.impl()), "' cannot be resolved due to ambiguous multiple bindings."_s));
return;
case Resolution::Type::Error:
throwSyntaxError(globalObject, scope, "Importing binding name 'default' cannot be resolved by star export entries."_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->typeProfilingStartOffset(),
unlinkedFunctionExecutable->typeProfilingEndOffset());
}
JSFunction* function = JSFunction::create(vm, unlinkedFunctionExecutable->link(vm, moduleProgramExecutable, moduleProgramExecutable->source()), 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