1/*
2 * Copyright (C) 2012-2018 Apple Inc. All Rights Reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "UnlinkedFunctionExecutable.h"
28
29#include "BuiltinExecutables.h"
30#include "BytecodeGenerator.h"
31#include "CachedTypes.h"
32#include "ClassInfo.h"
33#include "CodeCache.h"
34#include "Debugger.h"
35#include "ExecutableInfo.h"
36#include "FunctionOverrides.h"
37#include "IsoCellSetInlines.h"
38#include "JSCInlines.h"
39#include "Parser.h"
40#include "SourceProvider.h"
41#include "Structure.h"
42#include "UnlinkedFunctionCodeBlock.h"
43#include <wtf/Optional.h>
44
45namespace JSC {
46
47static_assert(sizeof(UnlinkedFunctionExecutable) <= 128, "UnlinkedFunctionExecutable should fit in a 128-byte cell to keep allocated blocks count to only one after initializing JSGlobalObject.");
48
49const ClassInfo UnlinkedFunctionExecutable::s_info = { "UnlinkedFunctionExecutable", nullptr, nullptr, nullptr, CREATE_METHOD_TABLE(UnlinkedFunctionExecutable) };
50
51static UnlinkedFunctionCodeBlock* generateUnlinkedFunctionCodeBlock(
52 VM& vm, UnlinkedFunctionExecutable* executable, const SourceCode& source,
53 CodeSpecializationKind kind, OptionSet<CodeGenerationMode> codeGenerationMode,
54 UnlinkedFunctionKind functionKind, ParserError& error, SourceParseMode parseMode)
55{
56 JSParserBuiltinMode builtinMode = executable->isBuiltinFunction() ? JSParserBuiltinMode::Builtin : JSParserBuiltinMode::NotBuiltin;
57 JSParserStrictMode strictMode = executable->isInStrictContext() ? JSParserStrictMode::Strict : JSParserStrictMode::NotStrict;
58 JSParserScriptMode scriptMode = executable->scriptMode();
59 ASSERT(isFunctionParseMode(executable->parseMode()));
60 std::unique_ptr<FunctionNode> function = parse<FunctionNode>(
61 &vm, source, executable->name(), builtinMode, strictMode, scriptMode, executable->parseMode(), executable->superBinding(), error, nullptr);
62
63 if (!function) {
64 ASSERT(error.isValid());
65 return nullptr;
66 }
67
68 function->finishParsing(executable->name(), executable->functionMode());
69 executable->recordParse(function->features(), function->hasCapturedVariables());
70
71 bool isClassContext = executable->superBinding() == SuperBinding::Needed;
72
73 UnlinkedFunctionCodeBlock* result = UnlinkedFunctionCodeBlock::create(&vm, FunctionCode, ExecutableInfo(function->usesEval(), function->isStrictMode(), kind == CodeForConstruct, functionKind == UnlinkedBuiltinFunction, executable->constructorKind(), scriptMode, executable->superBinding(), parseMode, executable->derivedContextType(), false, isClassContext, EvalContextType::FunctionEvalContext), codeGenerationMode);
74
75 VariableEnvironment parentScopeTDZVariables = executable->parentScopeTDZVariables();
76 error = BytecodeGenerator::generate(vm, function.get(), source, result, codeGenerationMode, &parentScopeTDZVariables);
77
78 if (error.isValid())
79 return nullptr;
80 vm.codeCache()->updateCache(executable, source, kind, result);
81 return result;
82}
83
84UnlinkedFunctionExecutable::UnlinkedFunctionExecutable(VM* vm, Structure* structure, const SourceCode& parentSource, FunctionMetadataNode* node, UnlinkedFunctionKind kind, ConstructAbility constructAbility, JSParserScriptMode scriptMode, Optional<CompactVariableMap::Handle> parentScopeTDZVariables, DerivedContextType derivedContextType, bool isBuiltinDefaultClassConstructor)
85 : Base(*vm, structure)
86 , m_firstLineOffset(node->firstLine() - parentSource.firstLine().oneBasedInt())
87 , m_isInStrictContext(node->isInStrictContext())
88 , m_lineCount(node->lastLine() - node->firstLine())
89 , m_hasCapturedVariables(false)
90 , m_unlinkedFunctionNameStart(node->functionNameStart() - parentSource.startOffset())
91 , m_isBuiltinFunction(kind == UnlinkedBuiltinFunction)
92 , m_unlinkedBodyStartColumn(node->startColumn())
93 , m_isBuiltinDefaultClassConstructor(isBuiltinDefaultClassConstructor)
94 , m_unlinkedBodyEndColumn(m_lineCount ? node->endColumn() : node->endColumn() - node->startColumn())
95 , m_constructAbility(static_cast<unsigned>(constructAbility))
96 , m_startOffset(node->source().startOffset() - parentSource.startOffset())
97 , m_scriptMode(static_cast<unsigned>(scriptMode))
98 , m_sourceLength(node->source().length())
99 , m_superBinding(static_cast<unsigned>(node->superBinding()))
100 , m_parametersStartOffset(node->parametersStart())
101 , m_isCached(false)
102 , m_typeProfilingStartOffset(node->functionKeywordStart())
103 , m_typeProfilingEndOffset(node->startStartOffset() + node->source().length() - 1)
104 , m_parameterCount(node->parameterCount())
105 , m_features(0)
106 , m_sourceParseMode(node->parseMode())
107 , m_constructorKind(static_cast<unsigned>(node->constructorKind()))
108 , m_functionMode(static_cast<unsigned>(node->functionMode()))
109 , m_derivedContextType(static_cast<unsigned>(derivedContextType))
110 , m_unlinkedCodeBlockForCall()
111 , m_unlinkedCodeBlockForConstruct()
112 , m_name(node->ident())
113 , m_ecmaName(node->ecmaName())
114{
115 // Make sure these bitfields are adequately wide.
116 ASSERT(m_constructAbility == static_cast<unsigned>(constructAbility));
117 ASSERT(m_constructorKind == static_cast<unsigned>(node->constructorKind()));
118 ASSERT(m_functionMode == static_cast<unsigned>(node->functionMode()));
119 ASSERT(m_scriptMode == static_cast<unsigned>(scriptMode));
120 ASSERT(m_superBinding == static_cast<unsigned>(node->superBinding()));
121 ASSERT(m_derivedContextType == static_cast<unsigned>(derivedContextType));
122 ASSERT(!(m_isBuiltinDefaultClassConstructor && constructorKind() == ConstructorKind::None));
123 if (!node->classSource().isNull())
124 setClassSource(node->classSource());
125 if (parentScopeTDZVariables)
126 ensureRareData().m_parentScopeTDZVariables = WTFMove(*parentScopeTDZVariables);
127}
128
129UnlinkedFunctionExecutable::~UnlinkedFunctionExecutable()
130{
131 if (m_isCached)
132 m_decoder.~RefPtr();
133}
134
135void UnlinkedFunctionExecutable::destroy(JSCell* cell)
136{
137 static_cast<UnlinkedFunctionExecutable*>(cell)->~UnlinkedFunctionExecutable();
138}
139
140void UnlinkedFunctionExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
141{
142 UnlinkedFunctionExecutable* thisObject = jsCast<UnlinkedFunctionExecutable*>(cell);
143 ASSERT_GC_OBJECT_INHERITS(thisObject, info());
144 Base::visitChildren(thisObject, visitor);
145 if (!thisObject->m_isCached) {
146 visitor.append(thisObject->m_unlinkedCodeBlockForCall);
147 visitor.append(thisObject->m_unlinkedCodeBlockForConstruct);
148 }
149}
150
151SourceCode UnlinkedFunctionExecutable::linkedSourceCode(const SourceCode& passedParentSource) const
152{
153 const SourceCode& parentSource = !m_isBuiltinDefaultClassConstructor ? passedParentSource : BuiltinExecutables::defaultConstructorSourceCode(constructorKind());
154 unsigned startColumn = linkedStartColumn(parentSource.startColumn().oneBasedInt());
155 unsigned startOffset = parentSource.startOffset() + m_startOffset;
156 unsigned firstLine = parentSource.firstLine().oneBasedInt() + m_firstLineOffset;
157 return SourceCode(parentSource.provider(), startOffset, startOffset + m_sourceLength, firstLine, startColumn);
158}
159
160FunctionExecutable* UnlinkedFunctionExecutable::link(VM& vm, ScriptExecutable* topLevelExecutable, const SourceCode& passedParentSource, Optional<int> overrideLineNumber, Intrinsic intrinsic)
161{
162 SourceCode source = linkedSourceCode(passedParentSource);
163 FunctionOverrides::OverrideInfo overrideInfo;
164 bool hasFunctionOverride = false;
165 if (UNLIKELY(Options::functionOverrides()))
166 hasFunctionOverride = FunctionOverrides::initializeOverrideFor(source, overrideInfo);
167
168 FunctionExecutable* result = FunctionExecutable::create(vm, topLevelExecutable, source, this, intrinsic);
169 if (overrideLineNumber)
170 result->setOverrideLineNumber(*overrideLineNumber);
171
172 if (UNLIKELY(hasFunctionOverride))
173 result->overrideInfo(overrideInfo);
174
175 return result;
176}
177
178UnlinkedFunctionExecutable* UnlinkedFunctionExecutable::fromGlobalCode(
179 const Identifier& name, ExecState& exec, const SourceCode& source,
180 JSObject*& exception, int overrideLineNumber, Optional<int> functionConstructorParametersEndPosition)
181{
182 ParserError error;
183 VM& vm = exec.vm();
184 auto& globalObject = *exec.lexicalGlobalObject();
185 CodeCache* codeCache = vm.codeCache();
186 OptionSet<CodeGenerationMode> codeGenerationMode = globalObject.defaultCodeGenerationMode();
187 UnlinkedFunctionExecutable* executable = codeCache->getUnlinkedGlobalFunctionExecutable(vm, name, source, codeGenerationMode, functionConstructorParametersEndPosition, error);
188
189 if (globalObject.hasDebugger())
190 globalObject.debugger()->sourceParsed(&exec, source.provider(), error.line(), error.message());
191
192 if (error.isValid()) {
193 exception = error.toErrorObject(&globalObject, source, overrideLineNumber);
194 return nullptr;
195 }
196
197 return executable;
198}
199
200UnlinkedFunctionCodeBlock* UnlinkedFunctionExecutable::unlinkedCodeBlockFor(CodeSpecializationKind specializationKind)
201{
202 switch (specializationKind) {
203 case CodeForCall:
204 return m_unlinkedCodeBlockForCall.get();
205 case CodeForConstruct:
206 return m_unlinkedCodeBlockForConstruct.get();
207 }
208 ASSERT_NOT_REACHED();
209 return nullptr;
210}
211
212UnlinkedFunctionCodeBlock* UnlinkedFunctionExecutable::unlinkedCodeBlockFor(
213 VM& vm, const SourceCode& source, CodeSpecializationKind specializationKind,
214 OptionSet<CodeGenerationMode> codeGenerationMode, ParserError& error, SourceParseMode parseMode)
215{
216 if (m_isCached)
217 decodeCachedCodeBlocks();
218 switch (specializationKind) {
219 case CodeForCall:
220 if (UnlinkedFunctionCodeBlock* codeBlock = m_unlinkedCodeBlockForCall.get())
221 return codeBlock;
222 break;
223 case CodeForConstruct:
224 if (UnlinkedFunctionCodeBlock* codeBlock = m_unlinkedCodeBlockForConstruct.get())
225 return codeBlock;
226 break;
227 }
228
229 UnlinkedFunctionCodeBlock* result = generateUnlinkedFunctionCodeBlock(
230 vm, this, source, specializationKind, codeGenerationMode,
231 isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction,
232 error, parseMode);
233
234 if (error.isValid())
235 return nullptr;
236
237 switch (specializationKind) {
238 case CodeForCall:
239 m_unlinkedCodeBlockForCall.set(vm, this, result);
240 break;
241 case CodeForConstruct:
242 m_unlinkedCodeBlockForConstruct.set(vm, this, result);
243 break;
244 }
245 vm.unlinkedFunctionExecutableSpace.set.add(this);
246 return result;
247}
248
249void UnlinkedFunctionExecutable::decodeCachedCodeBlocks()
250{
251 ASSERT(m_isCached);
252 ASSERT(m_decoder);
253 ASSERT(m_cachedCodeBlockForCallOffset || m_cachedCodeBlockForConstructOffset);
254
255 RefPtr<Decoder> decoder = WTFMove(m_decoder);
256 int32_t cachedCodeBlockForCallOffset = m_cachedCodeBlockForCallOffset;
257 int32_t cachedCodeBlockForConstructOffset = m_cachedCodeBlockForConstructOffset;
258
259 DeferGC deferGC(decoder->vm().heap);
260
261 // No need to clear m_unlinkedCodeBlockForCall here, since we moved the decoder out of the same slot
262 if (cachedCodeBlockForCallOffset)
263 decodeFunctionCodeBlock(*decoder, cachedCodeBlockForCallOffset, m_unlinkedCodeBlockForCall, this);
264 if (cachedCodeBlockForConstructOffset)
265 decodeFunctionCodeBlock(*decoder, cachedCodeBlockForConstructOffset, m_unlinkedCodeBlockForConstruct, this);
266 else
267 m_unlinkedCodeBlockForConstruct.clear();
268
269 WTF::storeStoreFence();
270 m_isCached = false;
271 decoder->vm().heap.writeBarrier(this);
272}
273
274UnlinkedFunctionExecutable::RareData& UnlinkedFunctionExecutable::ensureRareDataSlow()
275{
276 ASSERT(!m_rareData);
277 m_rareData = std::make_unique<RareData>();
278 return *m_rareData;
279}
280
281void UnlinkedFunctionExecutable::setInvalidTypeProfilingOffsets()
282{
283 m_typeProfilingStartOffset = std::numeric_limits<unsigned>::max();
284 m_typeProfilingEndOffset = std::numeric_limits<unsigned>::max();
285}
286
287} // namespace JSC
288