c84c972dceaf80993446acba2f0cb3d4da5dca1f
[WebKit-https.git] / Source / JavaScriptCore / runtime / FunctionConstructor.cpp
1 /*
2  *  Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
3  *  Copyright (C) 2003-2017 Apple Inc. All rights reserved.
4  *
5  *  This library is free software; you can redistribute it and/or
6  *  modify it under the terms of the GNU Lesser General Public
7  *  License as published by the Free Software Foundation; either
8  *  version 2 of the License, or (at your option) any later version.
9  *
10  *  This library is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  *  Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public
16  *  License along with this library; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  */
20
21 #include "config.h"
22 #include "FunctionConstructor.h"
23
24 #include "Completion.h"
25 #include "ExceptionHelpers.h"
26 #include "FunctionPrototype.h"
27 #include "JSAsyncFunction.h"
28 #include "JSAsyncGeneratorFunction.h"
29 #include "JSFunction.h"
30 #include "JSGeneratorFunction.h"
31 #include "JSGlobalObject.h"
32 #include "JSCInlines.h"
33 #include <wtf/text/StringBuilder.h>
34
35 namespace JSC {
36
37 STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(FunctionConstructor);
38
39 const ClassInfo FunctionConstructor::s_info = { "Function", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(FunctionConstructor) };
40
41 static EncodedJSValue JSC_HOST_CALL constructWithFunctionConstructor(ExecState* exec)
42 {
43     ArgList args(exec);
44     return JSValue::encode(constructFunction(exec, jsCast<InternalFunction*>(exec->jsCallee())->globalObject(exec->vm()), args, FunctionConstructionMode::Function, exec->newTarget()));
45 }
46
47 // ECMA 15.3.1 The Function Constructor Called as a Function
48 static EncodedJSValue JSC_HOST_CALL callFunctionConstructor(ExecState* exec)
49 {
50     ArgList args(exec);
51     return JSValue::encode(constructFunction(exec, jsCast<InternalFunction*>(exec->jsCallee())->globalObject(exec->vm()), args));
52 }
53
54 FunctionConstructor::FunctionConstructor(VM& vm, Structure* structure)
55     : InternalFunction(vm, structure, callFunctionConstructor, constructWithFunctionConstructor)
56 {
57 }
58
59 void FunctionConstructor::finishCreation(VM& vm, FunctionPrototype* functionPrototype)
60 {
61     Base::finishCreation(vm, functionPrototype->classInfo()->className);
62     putDirectWithoutTransition(vm, vm.propertyNames->prototype, functionPrototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
63     putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum);
64 }
65
66 // ECMA 15.3.2 The Function Constructor
67 JSObject* constructFunction(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, const Identifier& functionName, const SourceOrigin& sourceOrigin, const String& sourceURL, const TextPosition& position, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
68 {
69     VM& vm = exec->vm();
70     auto scope = DECLARE_THROW_SCOPE(vm);
71
72     if (!globalObject->evalEnabled())
73         return throwException(exec, scope, createEvalError(exec, globalObject->evalDisabledErrorMessage()));
74     RELEASE_AND_RETURN(scope, constructFunctionSkippingEvalEnabledCheck(exec, globalObject, args, functionName, sourceOrigin, sourceURL, position, -1, functionConstructionMode, newTarget));
75 }
76
77 JSObject* constructFunctionSkippingEvalEnabledCheck(
78     ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, 
79     const Identifier& functionName, const SourceOrigin& sourceOrigin, const String& sourceURL, 
80     const TextPosition& position, int overrideLineNumber, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
81 {
82     VM& vm = exec->vm();
83     auto scope = DECLARE_THROW_SCOPE(vm);
84
85     const char* prefix = nullptr;
86     switch (functionConstructionMode) {
87     case FunctionConstructionMode::Function:
88         prefix = "function ";
89         break;
90     case FunctionConstructionMode::Generator:
91         prefix = "function *";
92         break;
93     case FunctionConstructionMode::Async:
94         prefix = "async function ";
95         break;
96     case FunctionConstructionMode::AsyncGenerator:
97         prefix = "async function*";
98         break;
99     }
100
101     // How we stringify functions is sometimes important for web compatibility.
102     // See https://bugs.webkit.org/show_bug.cgi?id=24350.
103     String program;
104     Optional<int> functionConstructorParametersEndPosition = WTF::nullopt;
105     if (args.isEmpty())
106         program = makeString(prefix, functionName.string(), "() {\n\n}");
107     else if (args.size() == 1) {
108         auto body = args.at(0).toWTFString(exec);
109         RETURN_IF_EXCEPTION(scope, nullptr);
110         program = makeString(prefix, functionName.string(), "() {\n", body, "\n}");
111     } else {
112         StringBuilder builder(StringBuilder::OverflowHandler::RecordOverflow);
113         builder.append(prefix);
114         builder.append(functionName.string());
115
116         builder.append('(');
117         auto viewWithString = args.at(0).toString(exec)->viewWithUnderlyingString(exec);
118         RETURN_IF_EXCEPTION(scope, nullptr);
119         builder.append(viewWithString.view);
120         for (size_t i = 1; !builder.hasOverflowed() && i < args.size() - 1; i++) {
121             builder.appendLiteral(", ");
122             auto viewWithString = args.at(i).toString(exec)->viewWithUnderlyingString(exec);
123             RETURN_IF_EXCEPTION(scope, nullptr);
124             builder.append(viewWithString.view);
125         }
126         if (builder.hasOverflowed()) {
127             throwOutOfMemoryError(exec, scope);
128             return nullptr;
129         }
130
131         functionConstructorParametersEndPosition = builder.length() + 1;
132         builder.appendLiteral(") {\n");
133
134         auto body = args.at(args.size() - 1).toString(exec)->viewWithUnderlyingString(exec);
135         RETURN_IF_EXCEPTION(scope, nullptr);
136         builder.append(body.view);
137         builder.appendLiteral("\n}");
138         if (builder.hasOverflowed()) {
139             throwOutOfMemoryError(exec, scope);
140             return nullptr;
141         }
142         program = builder.toString();
143     }
144
145     SourceCode source = makeSource(program, sourceOrigin, URL({ }, sourceURL), position);
146     JSObject* exception = nullptr;
147     FunctionExecutable* function = FunctionExecutable::fromGlobalCode(functionName, *exec, source, exception, overrideLineNumber, functionConstructorParametersEndPosition);
148     if (!function) {
149         ASSERT(exception);
150         return throwException(exec, scope, exception);
151     }
152
153     Structure* structure = nullptr;
154     switch (functionConstructionMode) {
155     case FunctionConstructionMode::Function:
156         structure = JSFunction::selectStructureForNewFuncExp(globalObject, function);
157         break;
158     case FunctionConstructionMode::Generator:
159         structure = globalObject->generatorFunctionStructure();
160         break;
161     case FunctionConstructionMode::Async:
162         structure = globalObject->asyncFunctionStructure();
163         break;
164     case FunctionConstructionMode::AsyncGenerator:
165         structure = globalObject->asyncGeneratorFunctionStructure();
166         break;
167     }
168
169     Structure* subclassStructure = InternalFunction::createSubclassStructure(exec, newTarget, structure);
170     RETURN_IF_EXCEPTION(scope, nullptr);
171
172     switch (functionConstructionMode) {
173     case FunctionConstructionMode::Function:
174         return JSFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
175     case FunctionConstructionMode::Generator:
176         return JSGeneratorFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
177     case FunctionConstructionMode::Async:
178         return JSAsyncFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
179     case FunctionConstructionMode::AsyncGenerator:
180         return JSAsyncGeneratorFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
181     }
182
183     ASSERT_NOT_REACHED();
184     return nullptr;
185 }
186
187 // ECMA 15.3.2 The Function Constructor
188 JSObject* constructFunction(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
189 {
190     VM& vm = exec->vm();
191     return constructFunction(exec, globalObject, args, vm.propertyNames->anonymous, exec->callerSourceOrigin(), String(), TextPosition(), functionConstructionMode, newTarget);
192 }
193
194 } // namespace JSC