CodeBlocks should be in IsoSubspaces
[WebKit-https.git] / Source / JavaScriptCore / runtime / ProgramExecutable.cpp
1 /*
2  * Copyright (C) 2009-2017 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
28 #include "BatchedTransitionOptimizer.h"
29 #include "CodeBlock.h"
30 #include "CodeCache.h"
31 #include "Debugger.h"
32 #include "Exception.h"
33 #include "JIT.h"
34 #include "JSCInlines.h"
35 #include "LLIntEntrypoint.h"
36 #include "Parser.h"
37 #include "ProgramCodeBlock.h"
38 #include "TypeProfiler.h"
39 #include "VMInlines.h"
40 #include <wtf/CommaPrinter.h>
41
42 namespace JSC {
43
44 const ClassInfo ProgramExecutable::s_info = { "ProgramExecutable", &ScriptExecutable::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ProgramExecutable) };
45
46 ProgramExecutable::ProgramExecutable(ExecState* exec, const SourceCode& source)
47     : ScriptExecutable(exec->vm().programExecutableStructure.get(), exec->vm(), source, false, DerivedContextType::None, false, EvalContextType::None, NoIntrinsic)
48 {
49     ASSERT(source.provider()->sourceType() == SourceProviderSourceType::Program);
50     m_typeProfilingStartOffset = 0;
51     m_typeProfilingEndOffset = source.length() - 1;
52     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
53         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
54 }
55
56 void ProgramExecutable::destroy(JSCell* cell)
57 {
58     static_cast<ProgramExecutable*>(cell)->ProgramExecutable::~ProgramExecutable();
59 }
60
61 JSObject* ProgramExecutable::checkSyntax(ExecState* exec)
62 {
63     ParserError error;
64     VM* vm = &exec->vm();
65     JSGlobalObject* lexicalGlobalObject = exec->lexicalGlobalObject();
66     std::unique_ptr<ProgramNode> programNode = parse<ProgramNode>(
67         vm, m_source, Identifier(), JSParserBuiltinMode::NotBuiltin,
68         JSParserStrictMode::NotStrict, JSParserScriptMode::Classic, SourceParseMode::ProgramMode, SuperBinding::NotNeeded, error);
69     if (programNode)
70         return 0;
71     ASSERT(error.isValid());
72     return error.toErrorObject(lexicalGlobalObject, m_source);
73 }
74
75 // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-hasrestrictedglobalproperty
76 static bool hasRestrictedGlobalProperty(ExecState* exec, JSGlobalObject* globalObject, PropertyName propertyName)
77 {
78     PropertyDescriptor descriptor;
79     if (!globalObject->getOwnPropertyDescriptor(exec, propertyName, descriptor))
80         return false;
81     if (descriptor.configurable())
82         return false;
83     return true;
84 }
85
86 JSObject* ProgramExecutable::initializeGlobalProperties(VM& vm, CallFrame* callFrame, JSScope* scope)
87 {
88     auto throwScope = DECLARE_THROW_SCOPE(vm);
89     RELEASE_ASSERT(scope);
90     JSGlobalObject* globalObject = scope->globalObject();
91     RELEASE_ASSERT(globalObject);
92     ASSERT(&globalObject->vm() == &vm);
93
94     ParserError error;
95     JSParserStrictMode strictMode = isStrictMode() ? JSParserStrictMode::Strict : JSParserStrictMode::NotStrict;
96     DebuggerMode debuggerMode = globalObject->hasInteractiveDebugger() ? DebuggerOn : DebuggerOff;
97
98     UnlinkedProgramCodeBlock* unlinkedCodeBlock = vm.codeCache()->getUnlinkedProgramCodeBlock(
99         vm, this, source(), strictMode, debuggerMode, error);
100
101     if (globalObject->hasDebugger())
102         globalObject->debugger()->sourceParsed(callFrame, source().provider(), error.line(), error.message());
103
104     if (error.isValid())
105         return error.toErrorObject(globalObject, source());
106
107     JSValue nextPrototype = globalObject->getPrototypeDirect(vm);
108     while (nextPrototype && nextPrototype.isObject()) {
109         if (UNLIKELY(asObject(nextPrototype)->type() == ProxyObjectType)) {
110             ExecState* exec = globalObject->globalExec();
111             return createTypeError(exec, ASCIILiteral("Proxy is not allowed in the global prototype chain."));
112         }
113         nextPrototype = asObject(nextPrototype)->getPrototypeDirect(vm);
114     }
115     
116     JSGlobalLexicalEnvironment* globalLexicalEnvironment = globalObject->globalLexicalEnvironment();
117     const VariableEnvironment& variableDeclarations = unlinkedCodeBlock->variableDeclarations();
118     const VariableEnvironment& lexicalDeclarations = unlinkedCodeBlock->lexicalDeclarations();
119     // The ES6 spec says that no vars/global properties/let/const can be duplicated in the global scope.
120     // This carried out section 15.1.8 of the ES6 spec: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-globaldeclarationinstantiation
121     {
122         ExecState* exec = globalObject->globalExec();
123         // Check for intersection of "var" and "let"/"const"/"class"
124         for (auto& entry : lexicalDeclarations) {
125             if (variableDeclarations.contains(entry.key))
126                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
127         }
128
129         // Check if any new "let"/"const"/"class" will shadow any pre-existing global property names, or "var"/"let"/"const" variables.
130         // It's an error to introduce a shadow.
131         for (auto& entry : lexicalDeclarations) {
132             // The ES6 spec says that RestrictedGlobalProperty can't be shadowed.
133             bool hasProperty = hasRestrictedGlobalProperty(exec, globalObject, entry.key.get());
134             RETURN_IF_EXCEPTION(throwScope, throwScope.exception());
135             if (hasProperty)
136                 return createSyntaxError(exec, makeString("Can't create duplicate variable that shadows a global property: '", String(entry.key.get()), "'"));
137
138             hasProperty = globalLexicalEnvironment->hasProperty(exec, entry.key.get());
139             RETURN_IF_EXCEPTION(throwScope, throwScope.exception());
140             if (hasProperty) {
141                 if (UNLIKELY(entry.value.isConst() && !vm.globalConstRedeclarationShouldThrow() && !isStrictMode())) {
142                     // We only allow "const" duplicate declarations under this setting.
143                     // For example, we don't "let" variables to be overridden by "const" variables.
144                     if (globalLexicalEnvironment->isConstVariable(entry.key.get()))
145                         continue;
146                 }
147                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
148             }
149         }
150
151         // Check if any new "var"s will shadow any previous "let"/"const"/"class" names.
152         // It's an error to introduce a shadow.
153         if (!globalLexicalEnvironment->isEmpty()) {
154             for (auto& entry : variableDeclarations) {
155                 bool hasProperty = globalLexicalEnvironment->hasProperty(exec, entry.key.get());
156                 RETURN_IF_EXCEPTION(throwScope, throwScope.exception());
157                 if (hasProperty)
158                     return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
159             }
160         }
161     }
162
163
164     m_unlinkedProgramCodeBlock.set(vm, this, unlinkedCodeBlock);
165
166     BatchedTransitionOptimizer optimizer(vm, globalObject);
167
168     for (size_t i = 0, numberOfFunctions = unlinkedCodeBlock->numberOfFunctionDecls(); i < numberOfFunctions; ++i) {
169         UnlinkedFunctionExecutable* unlinkedFunctionExecutable = unlinkedCodeBlock->functionDecl(i);
170         ASSERT(!unlinkedFunctionExecutable->name().isEmpty());
171         globalObject->addFunction(callFrame, unlinkedFunctionExecutable->name());
172         if (vm.typeProfiler() || vm.controlFlowProfiler()) {
173             vm.functionHasExecutedCache()->insertUnexecutedRange(sourceID(), 
174                 unlinkedFunctionExecutable->typeProfilingStartOffset(), 
175                 unlinkedFunctionExecutable->typeProfilingEndOffset());
176         }
177     }
178
179     for (auto& entry : variableDeclarations) {
180         ASSERT(entry.value.isVar());
181         globalObject->addVar(callFrame, Identifier::fromUid(&vm, entry.key.get()));
182         throwScope.assertNoException();
183     }
184
185     {
186         JSGlobalLexicalEnvironment* globalLexicalEnvironment = jsCast<JSGlobalLexicalEnvironment*>(globalObject->globalScope());
187         SymbolTable* symbolTable = globalLexicalEnvironment->symbolTable();
188         ConcurrentJSLocker locker(symbolTable->m_lock);
189         for (auto& entry : lexicalDeclarations) {
190             if (UNLIKELY(entry.value.isConst() && !vm.globalConstRedeclarationShouldThrow() && !isStrictMode())) {
191                 if (symbolTable->contains(locker, entry.key.get()))
192                     continue;
193             }
194             ScopeOffset offset = symbolTable->takeNextScopeOffset(locker);
195             SymbolTableEntry newEntry(VarOffset(offset), static_cast<unsigned>(entry.value.isConst() ? PropertyAttribute::ReadOnly : PropertyAttribute::None));
196             newEntry.prepareToWatch();
197             symbolTable->add(locker, entry.key.get(), newEntry);
198             
199             ScopeOffset offsetForAssert = globalLexicalEnvironment->addVariables(1, jsTDZValue());
200             RELEASE_ASSERT(offsetForAssert == offset);
201         }
202     }
203     return nullptr;
204 }
205
206 void ProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
207 {
208     ProgramExecutable* thisObject = jsCast<ProgramExecutable*>(cell);
209     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
210     ScriptExecutable::visitChildren(thisObject, visitor);
211     visitor.append(thisObject->m_unlinkedProgramCodeBlock);
212     visitor.append(thisObject->m_programCodeBlock);
213 }
214
215 } // namespace JSC