forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathCodeCache.cpp
More file actions
428 lines (368 loc) · 24 KB
/
Copy pathCodeCache.cpp
File metadata and controls
428 lines (368 loc) · 24 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
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
/*
* Copyright (C) 2012-2023 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 "CodeCache.h"
#include "BytecodeGenerator.h"
#include "DirectEvalExecutable.h"
#include "IndirectEvalExecutable.h"
#include "JSThreadsSafepoint.h"
#include "ModuleProgramExecutable.h"
#include "ProgramExecutable.h"
#include "VMTraps.h"
#include <wtf/RecursiveLockAdapter.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/Threading.h>
namespace JSC {
WTF_MAKE_TZONE_ALLOCATED_IMPL(CodeCache);
// UNGIL AB18-R1-C: CodeCacheMap (m_sourceCode) is a plain HashMap on the
// shared VM. GIL-off, concurrent findCacheAndUpdateAge (which can prune ->
// m_map.remove) vs addCache (rehash) from N mutators corrupts the table.
// Serialize with the SAME IT-8 process-wide recursive compilation lock as
// UnlinkedFunctionExecutable::unlinkedCodeBlockFor — deliberately NOT a
// separate cache lock: Bun's eager generateUnlinkedCodeBlockForFunctions
// recursion means getUnlinkedGlobalCodeBlock reaches unlinkedCodeBlockFor
// under whatever this file holds, so a second lock would impose a
// cache-before-codegen order that the ScriptExecutable prepareForExecutionImpl
// path (codegen lock first, no cache lock) could invert via any future
// updateCache change — one recursive lock has no order to violate. Cost is
// fine at bring-up: these paths run once per program/eval/Function() source,
// not per call, and GIL-on/flag-off never reaches the lock (one
// predicted-untaken branch), preserving V5a flag-off identity.
//
// Scope: the lock is held across the WHOLE check-then-act pair —
// findCacheAndUpdateAge (including pruneSlowCase's m_map.remove) through
// addCache — in getUnlinkedGlobalCodeBlock and
// getUnlinkedGlobalFunctionExecutable. Double-generate of global code while a
// sibling holds the lock is impossible (whole-pair hold); the loser observes
// the winner's entry on its own pass.
//
// Deliberately NOT locked:
// - CodeCache::write(): only called from the jsc shell at teardown
// (jsc.cpp), single-mutator by construction, and has no VM& for the
// stop-protocol-safe bracket.
// - CodeCache::clear() (header-inline): runs via VM::deleteAllCode ->
// whenIdle, i.e. only when the VM is idle with no mutator in these paths.
//
// Declared locally (not in a header) — keep in sync with the definition in
// runtime/ScriptExecutable.cpp and the declarations in
// bytecompiler/BytecodeGenerator.cpp, dfg/DFGPlan.cpp and
// bytecode/UnlinkedFunctionExecutable.cpp.
RecursiveLock& gilOffCompilationLock();
namespace {
// Stop-protocol-safe acquisition — same shape as the locker in
// runtime/ScriptExecutable.cpp (see the rationale there): contended
// acquisition spins on tryLock() servicing only NeedStopTheWorld, so a
// waiting lite stays visible to the GIL-off stop fan, never parks raw while
// holding heap access (no watchdogAssertStopProgress regression), and never
// throws. The FIX-2 park poll first — deferral-immune §A.3 parking; see the
// ScriptExecutable.cpp locker comment.
class GILOffCompilationLocker {
WTF_MAKE_NONCOPYABLE(GILOffCompilationLocker);
public:
GILOffCompilationLocker(VM& vm, bool shouldLock)
: m_shouldLock(shouldLock)
{
if (!m_shouldLock) [[likely]]
return;
RecursiveLock& lock = gilOffCompilationLock();
if (lock.tryLock()) [[likely]]
return;
while (!lock.tryLock()) {
if (JSThreadsSafepoint::parkSitePollAndParkForStopTheWorld(vm))
continue; // Parked across a §A.3 window: re-validate (retry tryLock).
handleTrapsForCurrentThreadIfNeeded(vm, VMTraps::NeedStopTheWorld);
Thread::yield();
}
}
~GILOffCompilationLocker()
{
if (m_shouldLock) [[unlikely]]
gilOffCompilationLock().unlock();
}
private:
bool m_shouldLock;
};
} // anonymous namespace
void CodeCacheMap::pruneSlowCase()
{
m_minCapacity = std::max(m_size - m_sizeAtLastPrune, static_cast<int64_t>(0));
m_sizeAtLastPrune = m_size;
m_timeAtLastPrune = ApproximateTime::now();
if (m_capacity < m_minCapacity)
m_capacity = m_minCapacity;
while (m_size > m_capacity || !canPruneQuickly()) {
MapType::iterator it = m_map.begin();
writeCodeBlock(it->key, it->value);
m_size -= it->key.length();
m_map.remove(it);
}
}
static void generateUnlinkedCodeBlockForFunctions(VM& vm, UnlinkedCodeBlock* unlinkedCodeBlock, const SourceCode& parentSource, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error)
{
auto generate = [&](UnlinkedFunctionExecutable* unlinkedExecutable, CodeSpecializationKind constructorKind) {
if (constructorKind == CodeSpecializationKind::CodeForConstruct && SourceParseModeSet(SourceParseMode::AsyncArrowFunctionMode, SourceParseMode::AsyncMethodMode, SourceParseMode::AsyncFunctionMode).contains(unlinkedExecutable->parseMode()))
return;
SourceCode source = unlinkedExecutable->linkedSourceCode(parentSource);
UnlinkedFunctionCodeBlock* unlinkedFunctionCodeBlock = unlinkedExecutable->unlinkedCodeBlockFor(vm, source, constructorKind, codeGenerationMode, error, unlinkedExecutable->parseMode());
if (unlinkedFunctionCodeBlock)
generateUnlinkedCodeBlockForFunctions(vm, unlinkedFunctionCodeBlock, source, codeGenerationMode, error);
};
// FIXME: We should also generate CodeBlocks for CodeForConstruct
// https://bugs.webkit.org/show_bug.cgi?id=193823
//
// NOTE: We changed this in Bun. We check if the function is a constructor
// and if it is, we generate a CodeForConstruct block.
for (unsigned i = 0; i < unlinkedCodeBlock->numberOfFunctionDecls(); i++) {
auto* functionDecl = unlinkedCodeBlock->functionDecl(i);
if (functionDecl->isConstructor()) {
generate(functionDecl, CodeSpecializationKind::CodeForConstruct);
} else {
generate(functionDecl, CodeSpecializationKind::CodeForCall);
}
}
for (unsigned i = 0; i < unlinkedCodeBlock->numberOfFunctionExprs(); i++) {
auto* functionExpr = unlinkedCodeBlock->functionExpr(i);
if (functionExpr->isConstructor()) {
generate(functionExpr, CodeSpecializationKind::CodeForConstruct);
} else {
generate(functionExpr, CodeSpecializationKind::CodeForCall);
}
}
}
template<class UnlinkedCodeBlockType, class ExecutableType = ScriptExecutable>
UnlinkedCodeBlockType* generateUnlinkedCodeBlockImpl(VM& vm, const SourceCode& source, LexicallyScopedFeatures lexicallyScopedFeatures, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType, DerivedContextType derivedContextType, bool isArrowFunctionContext, const TDZEnvironment* variablesUnderTDZ = nullptr, const PrivateNameEnvironment* privateNameEnvironment = nullptr, ExecutableType* executable = nullptr)
{
typedef typename CacheTypes<UnlinkedCodeBlockType>::RootNode RootNode;
bool isInsideOrdinaryFunction = executable && executable->isInsideOrdinaryFunction();
std::unique_ptr<RootNode> rootNode = parse<RootNode>(
vm, source, Identifier(), ImplementationVisibility::Public, JSParserBuiltinMode::NotBuiltin, lexicallyScopedFeatures, scriptMode, CacheTypes<UnlinkedCodeBlockType>::parseMode, FunctionMode::None, SuperBinding::NotNeeded, error, ConstructorKind::None, derivedContextType, evalContextType, privateNameEnvironment, nullptr, isInsideOrdinaryFunction);
if (!rootNode)
return nullptr;
unsigned lineCount = rootNode->lastLine() - rootNode->firstLine();
unsigned startColumn = rootNode->startColumn() + 1;
bool endColumnIsOnStartLine = !lineCount;
unsigned unlinkedEndColumn = rootNode->endColumn();
unsigned endColumn = unlinkedEndColumn + (endColumnIsOnStartLine ? startColumn : 1);
if (executable)
executable->recordParse(rootNode->features(), rootNode->lexicallyScopedFeatures(), rootNode->hasCapturedVariables(), rootNode->lastLine(), endColumn);
NeedsClassFieldInitializer needsClassFieldInitializer = NeedsClassFieldInitializer::No;
PrivateBrandRequirement privateBrandRequirement = PrivateBrandRequirement::None;
if constexpr (std::is_same_v<ExecutableType, DirectEvalExecutable>) {
needsClassFieldInitializer = executable->needsClassFieldInitializer();
privateBrandRequirement = executable->privateBrandRequirement();
}
ExecutableInfo executableInfo(false, privateBrandRequirement, false, ConstructorKind::None, scriptMode, SuperBinding::NotNeeded, CacheTypes<UnlinkedCodeBlockType>::parseMode, derivedContextType, needsClassFieldInitializer, isArrowFunctionContext, false, evalContextType);
UnlinkedCodeBlockType* unlinkedCodeBlock = UnlinkedCodeBlockType::create(vm, executableInfo, codeGenerationMode);
unlinkedCodeBlock->recordParse(rootNode->features(), rootNode->lexicallyScopedFeatures(), rootNode->hasCapturedVariables(), lineCount, unlinkedEndColumn);
if (!source.provider()->sourceURLDirective().isNull())
unlinkedCodeBlock->setSourceURLDirective(source.provider()->sourceURLDirective());
if (!source.provider()->sourceMappingURLDirective().isNull())
unlinkedCodeBlock->setSourceMappingURLDirective(source.provider()->sourceMappingURLDirective());
RefPtr<TDZEnvironmentLink> parentVariablesUnderTDZ;
if (variablesUnderTDZ)
parentVariablesUnderTDZ = TDZEnvironmentLink::create(vm.m_compactVariableMap->get(*variablesUnderTDZ), nullptr);
error = BytecodeGenerator::generate(vm, rootNode.get(), source, unlinkedCodeBlock, codeGenerationMode, parentVariablesUnderTDZ, nullptr, privateNameEnvironment);
if (error.isValid())
return nullptr;
return unlinkedCodeBlock;
}
template<class UnlinkedCodeBlockType, class ExecutableType>
UnlinkedCodeBlockType* generateUnlinkedCodeBlock(VM& vm, ExecutableType* executable, const SourceCode& source, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType, const TDZEnvironment* variablesUnderTDZ = nullptr, const PrivateNameEnvironment* privateNameEnvironment = nullptr)
{
return generateUnlinkedCodeBlockImpl<UnlinkedCodeBlockType, ExecutableType>(vm, source, executable->lexicallyScopedFeatures(), scriptMode, codeGenerationMode, error, evalContextType, executable->derivedContextType(), executable->isArrowFunctionContext(), variablesUnderTDZ, privateNameEnvironment, executable);
}
UnlinkedEvalCodeBlock* generateUnlinkedCodeBlockForDirectEval(VM& vm, DirectEvalExecutable* executable, const SourceCode& source, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType, const TDZEnvironment* variablesUnderTDZ, const PrivateNameEnvironment* privateNameEnvironment)
{
return generateUnlinkedCodeBlock<UnlinkedEvalCodeBlock>(vm, executable, source, scriptMode, codeGenerationMode, error, evalContextType, variablesUnderTDZ, privateNameEnvironment);
}
template<class UnlinkedCodeBlockType>
std::enable_if_t<!std::is_same<UnlinkedCodeBlockType, UnlinkedEvalCodeBlock>::value, UnlinkedCodeBlockType*>
recursivelyGenerateUnlinkedCodeBlock(VM& vm, const SourceCode& source, LexicallyScopedFeatures lexicallyScopedFeatures, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType)
{
bool isArrowFunctionContext = false;
UnlinkedCodeBlockType* unlinkedCodeBlock = generateUnlinkedCodeBlockImpl<UnlinkedCodeBlockType>(vm, source, lexicallyScopedFeatures, scriptMode, codeGenerationMode, error, evalContextType, DerivedContextType::None, isArrowFunctionContext);
if (!unlinkedCodeBlock)
return nullptr;
generateUnlinkedCodeBlockForFunctions(vm, unlinkedCodeBlock, source, codeGenerationMode, error);
return unlinkedCodeBlock;
}
UnlinkedProgramCodeBlock* recursivelyGenerateUnlinkedCodeBlockForProgram(VM& vm, const SourceCode& source, LexicallyScopedFeatures lexicallyScopedFeatures, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType)
{
return recursivelyGenerateUnlinkedCodeBlock<UnlinkedProgramCodeBlock>(vm, source, lexicallyScopedFeatures, scriptMode, codeGenerationMode, error, evalContextType);
}
UnlinkedModuleProgramCodeBlock* recursivelyGenerateUnlinkedCodeBlockForModuleProgram(VM& vm, const SourceCode& source, LexicallyScopedFeatures lexicallyScopedFeatures, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType)
{
return recursivelyGenerateUnlinkedCodeBlock<UnlinkedModuleProgramCodeBlock>(vm, source, lexicallyScopedFeatures, scriptMode, codeGenerationMode, error, evalContextType);
}
template<class UnlinkedCodeBlockType, class ExecutableType>
UnlinkedCodeBlockType* CodeCache::getUnlinkedGlobalCodeBlock(VM& vm, ExecutableType* executable, const SourceCode& source, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType)
{
// UNGIL AB18-R1-C mode split: GIL-off, hold the compilation lock across the
// whole findCacheAndUpdateAge (may prune -> m_map.remove) / generate /
// addCache (may rehash) sequence. The eager
// generateUnlinkedCodeBlockForFunctions recursion below reaches
// UnlinkedFunctionExecutable::unlinkedCodeBlockFor, which re-enters this
// same recursive lock — see the rationale block above pruneSlowCase.
GILOffCompilationLocker compilationLocker(vm, vm.gilOffWithProcessGate());
DerivedContextType derivedContextType = executable->derivedContextType();
bool isArrowFunctionContext = executable->isArrowFunctionContext();
SourceCodeKey key(
source, String(), CacheTypes<UnlinkedCodeBlockType>::codeType, executable->lexicallyScopedFeatures(), scriptMode,
derivedContextType, evalContextType, isArrowFunctionContext, codeGenerationMode,
std::nullopt);
UnlinkedCodeBlockType* unlinkedCodeBlock = m_sourceCode.findCacheAndUpdateAge<UnlinkedCodeBlockType>(vm, key);
if (unlinkedCodeBlock && Options::useCodeCache()) {
unsigned lineCount = unlinkedCodeBlock->lineCount();
unsigned startColumn = unlinkedCodeBlock->startColumn() + source.startColumn().oneBasedInt();
bool endColumnIsOnStartLine = !lineCount;
unsigned endColumn = unlinkedCodeBlock->endColumn() + (endColumnIsOnStartLine ? startColumn : 1);
executable->recordParse(unlinkedCodeBlock->codeFeatures(), unlinkedCodeBlock->lexicallyScopedFeatures(), unlinkedCodeBlock->hasCapturedVariables(), source.firstLine().oneBasedInt() + lineCount, endColumn);
if (unlinkedCodeBlock->sourceURLDirective())
source.provider()->setSourceURLDirective(unlinkedCodeBlock->sourceURLDirective());
if (unlinkedCodeBlock->sourceMappingURLDirective())
source.provider()->setSourceMappingURLDirective(unlinkedCodeBlock->sourceMappingURLDirective());
return unlinkedCodeBlock;
}
unlinkedCodeBlock = generateUnlinkedCodeBlock<UnlinkedCodeBlockType, ExecutableType>(vm, executable, source, scriptMode, codeGenerationMode, error, evalContextType);
if (unlinkedCodeBlock && Options::useCodeCache()) {
m_sourceCode.addCache(key, SourceCodeValue(vm, unlinkedCodeBlock, m_sourceCode.age()));
key.source().provider().cacheBytecode([&] {
return encodeCodeBlock(vm, key, unlinkedCodeBlock);
});
}
return unlinkedCodeBlock;
}
UnlinkedProgramCodeBlock* CodeCache::getUnlinkedProgramCodeBlock(VM& vm, ProgramExecutable* executable, const SourceCode& source, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error)
{
return getUnlinkedGlobalCodeBlock<UnlinkedProgramCodeBlock>(vm, executable, source, JSParserScriptMode::Classic, codeGenerationMode, error, EvalContextType::None);
}
UnlinkedEvalCodeBlock* CodeCache::getUnlinkedEvalCodeBlock(VM& vm, IndirectEvalExecutable* executable, const SourceCode& source, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, EvalContextType evalContextType)
{
return getUnlinkedGlobalCodeBlock<UnlinkedEvalCodeBlock>(vm, executable, source, JSParserScriptMode::Classic, codeGenerationMode, error, evalContextType);
}
UnlinkedModuleProgramCodeBlock* CodeCache::getUnlinkedModuleProgramCodeBlock(VM& vm, ModuleProgramExecutable* executable, const SourceCode& source, OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error)
{
return getUnlinkedGlobalCodeBlock<UnlinkedModuleProgramCodeBlock>(vm, executable, source, JSParserScriptMode::Module, codeGenerationMode, error, EvalContextType::None);
}
UnlinkedFunctionExecutable* CodeCache::getUnlinkedGlobalFunctionExecutable(VM& vm, const Identifier& name, const SourceCode& source, LexicallyScopedFeatures lexicallyScopedFeatures, OptionSet<CodeGenerationMode> codeGenerationMode, std::optional<int> functionConstructorParametersEndPosition, ParserError& error)
{
// UNGIL AB18-R1-C mode split: same whole-pair hold as
// getUnlinkedGlobalCodeBlock — findCacheAndUpdateAge through addCache, plus
// the recordParse() bitfield RMW on the freshly created executable, all
// under the one recursive compilation lock (see above pruneSlowCase).
GILOffCompilationLocker compilationLocker(vm, vm.gilOffWithProcessGate());
bool isArrowFunctionContext = false;
SourceCodeKey key(
source, name.string(), SourceCodeType::FunctionType,
lexicallyScopedFeatures,
JSParserScriptMode::Classic,
DerivedContextType::None,
EvalContextType::FunctionEvalContext,
isArrowFunctionContext,
codeGenerationMode,
functionConstructorParametersEndPosition);
UnlinkedFunctionExecutable* executable = m_sourceCode.findCacheAndUpdateAge<UnlinkedFunctionExecutable>(vm, key);
if (executable && Options::useCodeCache()) {
if (!executable->sourceURLDirective().isNull())
source.provider()->setSourceURLDirective(executable->sourceURLDirective());
if (!executable->sourceMappingURLDirective().isNull())
source.provider()->setSourceMappingURLDirective(executable->sourceMappingURLDirective());
return executable;
}
JSTextPosition positionBeforeLastNewline;
std::unique_ptr<ProgramNode> program = parseFunctionForFunctionConstructor(vm, source, lexicallyScopedFeatures, error, &positionBeforeLastNewline, functionConstructorParametersEndPosition);
if (!program) {
RELEASE_ASSERT(error.isValid());
return nullptr;
}
// This function assumes an input string that would result in a single function declaration.
StatementNode* funcDecl = program->singleStatement();
if (!funcDecl) [[unlikely]] {
JSToken token;
error = ParserError(ParserError::SyntaxError, ParserError::SyntaxErrorIrrecoverable, token, "Parser error"_s, -1);
return nullptr;
}
ASSERT(funcDecl->isFuncDeclNode());
FunctionMetadataNode* metadata = static_cast<FuncDeclNode*>(funcDecl)->metadata();
ASSERT(metadata);
if (!metadata)
return nullptr;
metadata->overrideName(name);
metadata->setEndPosition(positionBeforeLastNewline);
// The Function constructor only has access to global variables, so no variables will be under TDZ unless they're
// in the global lexical environment, which we always TDZ check accesses from.
ConstructAbility constructAbility = constructAbilityForParseMode(metadata->parseMode());
UnlinkedFunctionExecutable* functionExecutable = UnlinkedFunctionExecutable::create(vm, source, metadata, UnlinkedNormalFunction, constructAbility, InlineAttribute::None, JSParserScriptMode::Classic, nullptr, std::nullopt, std::nullopt, DerivedContextType::None, EvalContextType::FunctionEvalContext, NeedsClassFieldInitializer::No, PrivateBrandRequirement::None);
if (!source.provider()->sourceURLDirective().isNull())
functionExecutable->setSourceURLDirective(source.provider()->sourceURLDirective());
if (!source.provider()->sourceMappingURLDirective().isNull())
functionExecutable->setSourceMappingURLDirective(source.provider()->sourceMappingURLDirective());
// We initially start with hasCapturedVariables = false.
functionExecutable->recordParse(program->features(), metadata->lexicallyScopedFeatures(), /* hasCapturedVariables */ false);
if (Options::useCodeCache())
m_sourceCode.addCache(key, SourceCodeValue(vm, functionExecutable, m_sourceCode.age()));
return functionExecutable;
}
void CodeCache::updateCache(const UnlinkedFunctionExecutable* executable, const SourceCode& parentSource, CodeSpecializationKind kind, const UnlinkedFunctionCodeBlock* codeBlock)
{
parentSource.provider()->updateCache(executable, parentSource, kind, codeBlock);
}
void CodeCache::write()
{
// UNGIL AB18-R1-C: deliberately unlocked — jsc-shell teardown only,
// single-mutator by construction, and no VM& for the stop-protocol-safe
// bracket. See the rationale block above pruneSlowCase.
for (auto& it : m_sourceCode)
writeCodeBlock(it.key, it.value);
}
void writeCodeBlock(const SourceCodeKey& key, const SourceCodeValue& value)
{
UnlinkedCodeBlock* codeBlock = dynamicDowncast<UnlinkedCodeBlock>(value.cell.get());
if (!codeBlock)
return;
key.source().provider().commitCachedBytecode();
}
static SourceCodeKey sourceCodeKeyForSerializedBytecode(VM&, const SourceCode& sourceCode, SourceCodeType codeType, LexicallyScopedFeatures lexicallyScopedFeatures, JSParserScriptMode scriptMode, OptionSet<CodeGenerationMode> codeGenerationMode)
{
return SourceCodeKey(
sourceCode, String(), codeType, lexicallyScopedFeatures, scriptMode,
DerivedContextType::None, EvalContextType::None, false, codeGenerationMode,
std::nullopt);
}
SourceCodeKey sourceCodeKeyForSerializedProgram(VM& vm, const SourceCode& sourceCode)
{
JSParserScriptMode scriptMode = JSParserScriptMode::Classic;
return sourceCodeKeyForSerializedBytecode(vm, sourceCode, SourceCodeType::ProgramType, NoLexicallyScopedFeatures, scriptMode, {});
}
SourceCodeKey sourceCodeKeyForSerializedModule(VM& vm, const SourceCode& sourceCode)
{
JSParserScriptMode scriptMode = JSParserScriptMode::Module;
return sourceCodeKeyForSerializedBytecode(vm, sourceCode, SourceCodeType::ModuleType, StrictModeLexicallyScopedFeature, scriptMode, {});
}
RefPtr<CachedBytecode> serializeBytecode(VM& vm, UnlinkedCodeBlock* codeBlock, const SourceCode& source, SourceCodeType codeType, LexicallyScopedFeatures lexicallyScopedFeatures, JSParserScriptMode scriptMode, FileSystem::FileHandle& fileHandle, BytecodeCacheError& error, OptionSet<CodeGenerationMode> codeGenerationMode)
{
return encodeCodeBlock(vm, sourceCodeKeyForSerializedBytecode(vm, source, codeType, lexicallyScopedFeatures, scriptMode, codeGenerationMode), codeBlock, fileHandle, error);
}
}