[ES6] Implement Reflect.enumerate
[WebKit-https.git] / Source / JavaScriptCore / runtime / JSGlobalObject.cpp
1 /*
2  * Copyright (C) 2007, 2008, 2009, 2014, 2015 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich (cwzwarich@uwaterloo.ca)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "JSGlobalObject.h"
32
33 #include "ArrayConstructor.h"
34 #include "ArrayIteratorPrototype.h"
35 #include "ArrayPrototype.h"
36 #include "BooleanConstructor.h"
37 #include "BooleanPrototype.h"
38 #include "BuiltinNames.h"
39 #include "ClonedArguments.h"
40 #include "CodeBlock.h"
41 #include "CodeCache.h"
42 #include "ConsolePrototype.h"
43 #include "DateConstructor.h"
44 #include "DatePrototype.h"
45 #include "Debugger.h"
46 #include "DebuggerScope.h"
47 #include "DirectArguments.h"
48 #include "Error.h"
49 #include "ErrorConstructor.h"
50 #include "ErrorPrototype.h"
51 #include "FunctionConstructor.h"
52 #include "FunctionPrototype.h"
53 #include "GetterSetter.h"
54 #include "HeapIterationScope.h"
55 #include "Interpreter.h"
56 #include "IteratorPrototype.h"
57 #include "JSAPIWrapperObject.h"
58 #include "JSArrayBuffer.h"
59 #include "JSArrayBufferConstructor.h"
60 #include "JSArrayBufferPrototype.h"
61 #include "JSArrayIterator.h"
62 #include "JSBoundFunction.h"
63 #include "JSCInlines.h"
64 #include "JSCallbackConstructor.h"
65 #include "JSCallbackFunction.h"
66 #include "JSCallbackObject.h"
67 #include "JSCatchScope.h"
68 #include "JSConsole.h"
69 #include "JSDataView.h"
70 #include "JSDataViewPrototype.h"
71 #include "JSDollarVM.h"
72 #include "JSDollarVMPrototype.h"
73 #include "JSFunction.h"
74 #include "JSFunctionNameScope.h"
75 #include "JSGenericTypedArrayViewConstructorInlines.h"
76 #include "JSGenericTypedArrayViewInlines.h"
77 #include "JSGenericTypedArrayViewPrototypeInlines.h"
78 #include "JSGlobalObjectFunctions.h"
79 #include "JSJob.h"
80 #include "JSLexicalEnvironment.h"
81 #include "JSLock.h"
82 #include "JSMap.h"
83 #include "JSMapIterator.h"
84 #include "JSONObject.h"
85 #include "JSPromise.h"
86 #include "JSPromiseConstructor.h"
87 #include "JSPromisePrototype.h"
88 #include "JSPropertyNameIterator.h"
89 #include "JSSet.h"
90 #include "JSSetIterator.h"
91 #include "JSStringIterator.h"
92 #include "JSTemplateRegistryKey.h"
93 #include "JSTypedArrayConstructors.h"
94 #include "JSTypedArrayPrototypes.h"
95 #include "JSTypedArrays.h"
96 #include "JSWeakMap.h"
97 #include "JSWeakSet.h"
98 #include "JSWithScope.h"
99 #include "LegacyProfiler.h"
100 #include "Lookup.h"
101 #include "MapConstructor.h"
102 #include "MapIteratorPrototype.h"
103 #include "MapPrototype.h"
104 #include "MathObject.h"
105 #include "Microtask.h"
106 #include "NativeErrorConstructor.h"
107 #include "NativeErrorPrototype.h"
108 #include "NullGetterFunction.h"
109 #include "NullSetterFunction.h"
110 #include "NumberConstructor.h"
111 #include "NumberPrototype.h"
112 #include "ObjCCallbackFunction.h"
113 #include "ObjectConstructor.h"
114 #include "ObjectPrototype.h"
115 #include "ParserError.h"
116 #include "ReflectObject.h"
117 #include "RegExpConstructor.h"
118 #include "RegExpMatchesArray.h"
119 #include "RegExpObject.h"
120 #include "RegExpPrototype.h"
121 #include "ScopedArguments.h"
122 #include "SetConstructor.h"
123 #include "SetIteratorPrototype.h"
124 #include "SetPrototype.h"
125 #include "StrictEvalActivation.h"
126 #include "StringConstructor.h"
127 #include "StringIteratorPrototype.h"
128 #include "StringPrototype.h"
129 #include "Symbol.h"
130 #include "SymbolConstructor.h"
131 #include "SymbolPrototype.h"
132 #include "VariableWriteFireDetail.h"
133 #include "WeakGCMapInlines.h"
134 #include "WeakMapConstructor.h"
135 #include "WeakMapPrototype.h"
136 #include "WeakSetConstructor.h"
137 #include "WeakSetPrototype.h"
138
139 #if ENABLE(INTL)
140 #include "IntlObject.h"
141 #endif // ENABLE(INTL)
142
143 #if ENABLE(REMOTE_INSPECTOR)
144 #include "JSGlobalObjectDebuggable.h"
145 #include "JSGlobalObjectInspectorController.h"
146 #endif
147
148 #if ENABLE(WEB_REPLAY)
149 #include "EmptyInputCursor.h"
150 #include "JSReplayInputs.h"
151 #endif
152
153 #include "JSGlobalObject.lut.h"
154
155 namespace JSC {
156
157 const ClassInfo JSGlobalObject::s_info = { "GlobalObject", &Base::s_info, &globalObjectTable, CREATE_METHOD_TABLE(JSGlobalObject) };
158
159 const GlobalObjectMethodTable JSGlobalObject::s_globalObjectMethodTable = { &allowsAccessFrom, &supportsProfiling, &supportsRichSourceInfo, &shouldInterruptScript, &javaScriptRuntimeFlags, nullptr, &shouldInterruptScriptBeforeTimeout };
160
161 /* Source for JSGlobalObject.lut.h
162 @begin globalObjectTable
163   parseFloat            globalFuncParseFloat            DontEnum|Function 1
164   isNaN                 globalFuncIsNaN                 DontEnum|Function 1
165   isFinite              globalFuncIsFinite              DontEnum|Function 1
166   escape                globalFuncEscape                DontEnum|Function 1
167   unescape              globalFuncUnescape              DontEnum|Function 1
168   decodeURI             globalFuncDecodeURI             DontEnum|Function 1
169   decodeURIComponent    globalFuncDecodeURIComponent    DontEnum|Function 1
170   encodeURI             globalFuncEncodeURI             DontEnum|Function 1
171   encodeURIComponent    globalFuncEncodeURIComponent    DontEnum|Function 1
172 @end
173 */
174
175 static EncodedJSValue JSC_HOST_CALL getTemplateObject(ExecState* exec)
176 {
177     JSValue thisValue = exec->thisValue();
178     ASSERT(thisValue.inherits(JSTemplateRegistryKey::info()));
179     return JSValue::encode(exec->lexicalGlobalObject()->templateRegistry().getTemplateObject(exec, jsCast<JSTemplateRegistryKey*>(thisValue)->templateRegistryKey()));
180 }
181
182
183 static EncodedJSValue JSC_HOST_CALL enqueueJob(ExecState* exec)
184 {
185     VM& vm = exec->vm();
186     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
187
188     JSValue job = exec->argument(0);
189     JSValue arguments = exec->argument(1);
190     ASSERT(arguments.inherits(JSArray::info()));
191
192     globalObject->queueMicrotask(createJSJob(vm, job, jsCast<JSArray*>(arguments)));
193
194     return JSValue::encode(jsUndefined());
195 }
196
197 JSGlobalObject::JSGlobalObject(VM& vm, Structure* structure, const GlobalObjectMethodTable* globalObjectMethodTable)
198     : Base(vm, structure, 0)
199     , m_vm(vm)
200 #if ENABLE(WEB_REPLAY)
201     , m_inputCursor(EmptyInputCursor::create())
202 #endif
203     , m_masqueradesAsUndefinedWatchpoint(adoptRef(new WatchpointSet(IsWatched)))
204     , m_havingABadTimeWatchpoint(adoptRef(new WatchpointSet(IsWatched)))
205     , m_varInjectionWatchpoint(adoptRef(new WatchpointSet(IsWatched)))
206     , m_weakRandom(Options::forceWeakRandomSeed() ? Options::forcedWeakRandomSeed() : static_cast<unsigned>(randomNumber() * (std::numeric_limits<unsigned>::max() + 1.0)))
207     , m_templateRegistry(vm)
208     , m_evalEnabled(true)
209     , m_runtimeFlags()
210     , m_consoleClient(nullptr)
211     , m_globalObjectMethodTable(globalObjectMethodTable ? globalObjectMethodTable : &s_globalObjectMethodTable)
212 {
213 }
214
215 JSGlobalObject::~JSGlobalObject()
216 {
217 #if ENABLE(REMOTE_INSPECTOR)
218     m_inspectorController->globalObjectDestroyed();
219 #endif
220
221     if (m_debugger)
222         m_debugger->detach(this, Debugger::GlobalObjectIsDestructing);
223
224     if (LegacyProfiler* profiler = vm().enabledProfiler())
225         profiler->stopProfiling(this);
226 }
227
228 void JSGlobalObject::destroy(JSCell* cell)
229 {
230     static_cast<JSGlobalObject*>(cell)->JSGlobalObject::~JSGlobalObject();
231 }
232
233 void JSGlobalObject::setGlobalThis(VM& vm, JSObject* globalThis)
234 {
235     m_globalThis.set(vm, this, globalThis);
236 }
237
238 void JSGlobalObject::init(VM& vm)
239 {
240     ASSERT(vm.currentThreadIsHoldingAPILock());
241
242     JSGlobalObject::globalExec()->init(0, 0, CallFrame::noCaller(), 0, 0);
243
244     m_debugger = 0;
245
246 #if ENABLE(REMOTE_INSPECTOR)
247     m_inspectorController = std::make_unique<Inspector::JSGlobalObjectInspectorController>(*this);
248     m_inspectorDebuggable = std::make_unique<JSGlobalObjectDebuggable>(*this);
249     m_inspectorDebuggable->init();
250     m_consoleClient = m_inspectorController->consoleClient();
251 #endif
252
253     ExecState* exec = JSGlobalObject::globalExec();
254
255     m_functionPrototype.set(vm, this, FunctionPrototype::create(vm, FunctionPrototype::createStructure(vm, this, jsNull()))); // The real prototype will be set once ObjectPrototype is created.
256     m_calleeStructure.set(vm, this, JSCallee::createStructure(vm, this, jsNull()));
257
258     // Need to create the callee structure (above) before creating the callee.
259     m_globalCallee.set(vm, this, JSCallee::create(vm, this, this));
260     exec->setCallee(m_globalCallee.get());
261
262     m_functionStructure.set(vm, this, JSFunction::createStructure(vm, this, m_functionPrototype.get()));
263     m_boundFunctionStructure.set(vm, this, JSBoundFunction::createStructure(vm, this, m_functionPrototype.get()));
264     m_namedFunctionStructure.set(vm, this, Structure::addPropertyTransition(vm, m_functionStructure.get(), vm.propertyNames->name, DontDelete | ReadOnly | DontEnum, m_functionNameOffset));
265     m_internalFunctionStructure.set(vm, this, InternalFunction::createStructure(vm, this, m_functionPrototype.get()));
266     JSFunction* callFunction = 0;
267     JSFunction* applyFunction = 0;
268     m_functionPrototype->addFunctionProperties(exec, this, &callFunction, &applyFunction);
269     m_callFunction.set(vm, this, callFunction);
270     m_applyFunction.set(vm, this, applyFunction);
271     m_arrayProtoValuesFunction.set(vm, this, JSFunction::create(vm, this, 0, vm.propertyNames->values.string(), arrayProtoFuncValues));
272     m_initializePromiseFunction.set(vm, this, JSFunction::createBuiltinFunction(vm, operationsPromiseInitializePromiseCodeGenerator(vm), this));
273     m_newPromiseDeferredFunction.set(vm, this, JSFunction::createBuiltinFunction(vm, operationsPromiseNewPromiseDeferredCodeGenerator(vm), this));
274     m_nullGetterFunction.set(vm, this, NullGetterFunction::create(vm, NullGetterFunction::createStructure(vm, this, m_functionPrototype.get())));
275     m_nullSetterFunction.set(vm, this, NullSetterFunction::create(vm, NullSetterFunction::createStructure(vm, this, m_functionPrototype.get())));
276     m_objectPrototype.set(vm, this, ObjectPrototype::create(vm, this, ObjectPrototype::createStructure(vm, this, jsNull())));
277     GetterSetter* protoAccessor = GetterSetter::create(vm, this);
278     protoAccessor->setGetter(vm, this, JSFunction::create(vm, this, 0, String(), globalFuncProtoGetter));
279     protoAccessor->setSetter(vm, this, JSFunction::create(vm, this, 0, String(), globalFuncProtoSetter));
280     m_objectPrototype->putDirectNonIndexAccessor(vm, vm.propertyNames->underscoreProto, protoAccessor, Accessor | DontEnum);
281     m_functionPrototype->structure()->setPrototypeWithoutTransition(vm, m_objectPrototype.get());
282     
283     m_typedArrays[toIndex(TypeInt8)].prototype.set(vm, this, JSInt8ArrayPrototype::create(vm, this, JSInt8ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
284     m_typedArrays[toIndex(TypeInt16)].prototype.set(vm, this, JSInt16ArrayPrototype::create(vm, this, JSInt16ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
285     m_typedArrays[toIndex(TypeInt32)].prototype.set(vm, this, JSInt32ArrayPrototype::create(vm, this, JSInt32ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
286     m_typedArrays[toIndex(TypeUint8)].prototype.set(vm, this, JSUint8ArrayPrototype::create(vm, this, JSUint8ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
287     m_typedArrays[toIndex(TypeUint8Clamped)].prototype.set(vm, this, JSUint8ClampedArrayPrototype::create(vm, this, JSUint8ClampedArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
288     m_typedArrays[toIndex(TypeUint16)].prototype.set(vm, this, JSUint16ArrayPrototype::create(vm, this, JSUint16ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
289     m_typedArrays[toIndex(TypeUint32)].prototype.set(vm, this, JSUint32ArrayPrototype::create(vm, this, JSUint32ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
290     m_typedArrays[toIndex(TypeFloat32)].prototype.set(vm, this, JSFloat32ArrayPrototype::create(vm, this, JSFloat32ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
291     m_typedArrays[toIndex(TypeFloat64)].prototype.set(vm, this, JSFloat64ArrayPrototype::create(vm, this, JSFloat64ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
292     m_typedArrays[toIndex(TypeDataView)].prototype.set(vm, this, JSDataViewPrototype::create(vm, JSDataViewPrototype::createStructure(vm, this, m_objectPrototype.get())));
293     
294     m_typedArrays[toIndex(TypeInt8)].structure.set(vm, this, JSInt8Array::createStructure(vm, this, m_typedArrays[toIndex(TypeInt8)].prototype.get()));
295     m_typedArrays[toIndex(TypeInt16)].structure.set(vm, this, JSInt16Array::createStructure(vm, this, m_typedArrays[toIndex(TypeInt16)].prototype.get()));
296     m_typedArrays[toIndex(TypeInt32)].structure.set(vm, this, JSInt32Array::createStructure(vm, this, m_typedArrays[toIndex(TypeInt32)].prototype.get()));
297     m_typedArrays[toIndex(TypeUint8)].structure.set(vm, this, JSUint8Array::createStructure(vm, this, m_typedArrays[toIndex(TypeUint8)].prototype.get()));
298     m_typedArrays[toIndex(TypeUint8Clamped)].structure.set(vm, this, JSUint8ClampedArray::createStructure(vm, this, m_typedArrays[toIndex(TypeUint8Clamped)].prototype.get()));
299     m_typedArrays[toIndex(TypeUint16)].structure.set(vm, this, JSUint16Array::createStructure(vm, this, m_typedArrays[toIndex(TypeUint16)].prototype.get()));
300     m_typedArrays[toIndex(TypeUint32)].structure.set(vm, this, JSUint32Array::createStructure(vm, this, m_typedArrays[toIndex(TypeUint32)].prototype.get()));
301     m_typedArrays[toIndex(TypeFloat32)].structure.set(vm, this, JSFloat32Array::createStructure(vm, this, m_typedArrays[toIndex(TypeFloat32)].prototype.get()));
302     m_typedArrays[toIndex(TypeFloat64)].structure.set(vm, this, JSFloat64Array::createStructure(vm, this, m_typedArrays[toIndex(TypeFloat64)].prototype.get()));
303     m_typedArrays[toIndex(TypeDataView)].structure.set(vm, this, JSDataView::createStructure(vm, this, m_typedArrays[toIndex(TypeDataView)].prototype.get()));
304     
305     m_catchScopeStructure.set(vm, this, JSCatchScope::createStructure(vm, this, jsNull()));
306     m_functionNameScopeStructure.set(vm, this, JSFunctionNameScope::createStructure(vm, this, jsNull()));
307     m_lexicalEnvironmentStructure.set(vm, this, JSLexicalEnvironment::createStructure(vm, this));
308     m_strictEvalActivationStructure.set(vm, this, StrictEvalActivation::createStructure(vm, this, jsNull()));
309     m_debuggerScopeStructure.set(m_vm, this, DebuggerScope::createStructure(m_vm, this));
310     m_withScopeStructure.set(vm, this, JSWithScope::createStructure(vm, this, jsNull()));
311     
312     m_nullPrototypeObjectStructure.set(vm, this, JSFinalObject::createStructure(vm, this, jsNull(), JSFinalObject::defaultInlineCapacity()));
313     
314     m_callbackFunctionStructure.set(vm, this, JSCallbackFunction::createStructure(vm, this, m_functionPrototype.get()));
315     m_directArgumentsStructure.set(vm, this, DirectArguments::createStructure(vm, this, m_objectPrototype.get()));
316     m_scopedArgumentsStructure.set(vm, this, ScopedArguments::createStructure(vm, this, m_objectPrototype.get()));
317     m_outOfBandArgumentsStructure.set(vm, this, ClonedArguments::createStructure(vm, this, m_objectPrototype.get()));
318     m_callbackConstructorStructure.set(vm, this, JSCallbackConstructor::createStructure(vm, this, m_objectPrototype.get()));
319     m_callbackObjectStructure.set(vm, this, JSCallbackObject<JSDestructibleObject>::createStructure(vm, this, m_objectPrototype.get()));
320 #if JSC_OBJC_API_ENABLED
321     m_objcCallbackFunctionStructure.set(vm, this, ObjCCallbackFunction::createStructure(vm, this, m_functionPrototype.get()));
322     m_objcWrapperObjectStructure.set(vm, this, JSCallbackObject<JSAPIWrapperObject>::createStructure(vm, this, m_objectPrototype.get()));
323 #endif
324     
325     m_arrayPrototype.set(vm, this, ArrayPrototype::create(vm, this, ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
326     
327     m_originalArrayStructureForIndexingShape[UndecidedShape >> IndexingShapeShift].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithUndecided));
328     m_originalArrayStructureForIndexingShape[Int32Shape >> IndexingShapeShift].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithInt32));
329     m_originalArrayStructureForIndexingShape[DoubleShape >> IndexingShapeShift].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithDouble));
330     m_originalArrayStructureForIndexingShape[ContiguousShape >> IndexingShapeShift].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithContiguous));
331     m_originalArrayStructureForIndexingShape[ArrayStorageShape >> IndexingShapeShift].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithArrayStorage));
332     m_originalArrayStructureForIndexingShape[SlowPutArrayStorageShape >> IndexingShapeShift].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithSlowPutArrayStorage));
333     for (unsigned i = 0; i < NumberOfIndexingShapes; ++i)
334         m_arrayStructureForIndexingShapeDuringAllocation[i] = m_originalArrayStructureForIndexingShape[i];
335
336     RegExp* emptyRegex = RegExp::create(vm, "", NoFlags);
337     
338     m_regExpPrototype.set(vm, this, RegExpPrototype::create(vm, RegExpPrototype::createStructure(vm, this, m_objectPrototype.get()), emptyRegex));
339     m_regExpStructure.set(vm, this, RegExpObject::createStructure(vm, this, m_regExpPrototype.get()));
340     m_regExpMatchesArrayStructure.set(vm, this, createRegExpMatchesArrayStructure(vm, *this));
341     
342     m_promisePrototype.set(vm, this, JSPromisePrototype::create(exec, this, JSPromisePrototype::createStructure(vm, this, m_objectPrototype.get())));
343     m_promiseStructure.set(vm, this, JSPromise::createStructure(vm, this, m_promisePrototype.get()));
344
345     m_parseIntFunction.set(vm, this, JSFunction::create(vm, this, 2, vm.propertyNames->parseInt.string(), globalFuncParseInt, NoIntrinsic));
346     putDirectWithoutTransition(vm, vm.propertyNames->parseInt, m_parseIntFunction.get(), DontEnum | Function);
347
348 #define CREATE_PROTOTYPE_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
349 m_ ## lowerName ## Prototype.set(vm, this, capitalName##Prototype::create(vm, this, capitalName##Prototype::createStructure(vm, this, m_objectPrototype.get()))); \
350 m_ ## properName ## Structure.set(vm, this, instanceType::createStructure(vm, this, m_ ## lowerName ## Prototype.get()));
351     
352     FOR_EACH_SIMPLE_BUILTIN_TYPE(CREATE_PROTOTYPE_FOR_SIMPLE_TYPE)
353     
354 #undef CREATE_PROTOTYPE_FOR_SIMPLE_TYPE
355
356     m_iteratorPrototype.set(vm, this, IteratorPrototype::create(vm, this, IteratorPrototype::createStructure(vm, this, m_objectPrototype.get())));
357
358 #define CREATE_PROTOTYPE_FOR_DERIVED_ITERATOR_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
359 m_ ## lowerName ## Prototype.set(vm, this, capitalName##Prototype::create(vm, this, capitalName##Prototype::createStructure(vm, this, m_iteratorPrototype.get()))); \
360 m_ ## properName ## Structure.set(vm, this, instanceType::createStructure(vm, this, m_ ## lowerName ## Prototype.get()));
361     
362     FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(CREATE_PROTOTYPE_FOR_DERIVED_ITERATOR_TYPE)
363     m_propertyNameIteratorStructure.set(vm, this, JSPropertyNameIterator::createStructure(vm, this, m_iteratorPrototype.get()));
364     
365 #undef CREATE_PROTOTYPE_FOR_DERIVED_ITERATOR_TYPE
366
367     // Constructors
368     
369     ObjectConstructor* objectConstructor = ObjectConstructor::create(vm, this, ObjectConstructor::createStructure(vm, this, m_functionPrototype.get()), m_objectPrototype.get());
370     m_objectConstructor.set(vm, this, objectConstructor);
371
372     JSFunction* definePropertyFunction = m_objectConstructor->addDefineProperty(exec, this);
373     m_definePropertyFunction.set(vm, this, definePropertyFunction);
374
375     JSCell* functionConstructor = FunctionConstructor::create(vm, FunctionConstructor::createStructure(vm, this, m_functionPrototype.get()), m_functionPrototype.get());
376     JSCell* arrayConstructor = ArrayConstructor::create(vm, ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_arrayPrototype.get());
377     
378     m_regExpConstructor.set(vm, this, RegExpConstructor::create(vm, RegExpConstructor::createStructure(vm, this, m_functionPrototype.get()), m_regExpPrototype.get()));
379     
380 #define CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
381 capitalName ## Constructor* lowerName ## Constructor = capitalName ## Constructor::create(vm, capitalName ## Constructor::createStructure(vm, this, m_functionPrototype.get()), m_ ## lowerName ## Prototype.get()); \
382 m_ ## lowerName ## Prototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, lowerName ## Constructor, DontEnum); \
383
384     FOR_EACH_SIMPLE_BUILTIN_TYPE(CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE)
385     
386 #undef CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE
387     
388     m_errorConstructor.set(vm, this, errorConstructor);
389     
390     Structure* nativeErrorPrototypeStructure = NativeErrorPrototype::createStructure(vm, this, m_errorPrototype.get());
391     Structure* nativeErrorStructure = NativeErrorConstructor::createStructure(vm, this, m_functionPrototype.get());
392     m_evalErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("EvalError")));
393     m_rangeErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("RangeError")));
394     m_referenceErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("ReferenceError")));
395     m_syntaxErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("SyntaxError")));
396     m_typeErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("TypeError")));
397     m_URIErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("URIError")));
398     m_promiseConstructor.set(vm, this, JSPromiseConstructor::create(vm, JSPromiseConstructor::createStructure(vm, this, m_functionPrototype.get()), m_promisePrototype.get()));
399     
400     m_objectPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, objectConstructor, DontEnum);
401     m_functionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, functionConstructor, DontEnum);
402     m_arrayPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, arrayConstructor, DontEnum);
403     m_regExpPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, m_regExpConstructor.get(), DontEnum);
404     m_promisePrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, m_promiseConstructor.get(), DontEnum);
405     
406     putDirectWithoutTransition(vm, vm.propertyNames->Object, objectConstructor, DontEnum);
407     putDirectWithoutTransition(vm, vm.propertyNames->Function, functionConstructor, DontEnum);
408     putDirectWithoutTransition(vm, vm.propertyNames->Array, arrayConstructor, DontEnum);
409     putDirectWithoutTransition(vm, vm.propertyNames->RegExp, m_regExpConstructor.get(), DontEnum);
410     putDirectWithoutTransition(vm, vm.propertyNames->EvalError, m_evalErrorConstructor.get(), DontEnum);
411     putDirectWithoutTransition(vm, vm.propertyNames->RangeError, m_rangeErrorConstructor.get(), DontEnum);
412     putDirectWithoutTransition(vm, vm.propertyNames->ReferenceError, m_referenceErrorConstructor.get(), DontEnum);
413     putDirectWithoutTransition(vm, vm.propertyNames->SyntaxError, m_syntaxErrorConstructor.get(), DontEnum);
414     putDirectWithoutTransition(vm, vm.propertyNames->TypeError, m_typeErrorConstructor.get(), DontEnum);
415     putDirectWithoutTransition(vm, vm.propertyNames->URIError, m_URIErrorConstructor.get(), DontEnum);
416     putDirectWithoutTransition(vm, vm.propertyNames->Promise, m_promiseConstructor.get(), DontEnum);
417     
418     
419 #define PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
420 putDirectWithoutTransition(vm, vm.propertyNames-> jsName, lowerName ## Constructor, DontEnum); \
421
422     FOR_EACH_SIMPLE_BUILTIN_TYPE_WITH_CONSTRUCTOR(PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE)
423
424 #undef PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE
425     PrototypeMap& prototypeMap = vm.prototypeMap;
426     Structure* iteratorResultStructure = prototypeMap.emptyObjectStructureForPrototype(m_objectPrototype.get(), JSFinalObject::defaultInlineCapacity());
427     PropertyOffset offset;
428     iteratorResultStructure = Structure::addPropertyTransition(vm, iteratorResultStructure, vm.propertyNames->done, 0, offset);
429     iteratorResultStructure = Structure::addPropertyTransition(vm, iteratorResultStructure, vm.propertyNames->value, 0, offset);
430     m_iteratorResultStructure.set(vm, this, iteratorResultStructure);
431     
432     m_evalFunction.set(vm, this, JSFunction::create(vm, this, 1, vm.propertyNames->eval.string(), globalFuncEval));
433     putDirectWithoutTransition(vm, vm.propertyNames->eval, m_evalFunction.get(), DontEnum);
434     
435 #if ENABLE(INTL)
436     putDirectWithoutTransition(vm, vm.propertyNames->Intl, IntlObject::create(vm, IntlObject::createStructure(vm, this, m_objectPrototype.get())), DontEnum);
437 #endif // ENABLE(INTL)
438     putDirectWithoutTransition(vm, vm.propertyNames->JSON, JSONObject::create(vm, JSONObject::createStructure(vm, this, m_objectPrototype.get())), DontEnum);
439     putDirectWithoutTransition(vm, vm.propertyNames->Math, MathObject::create(vm, this, MathObject::createStructure(vm, this, m_objectPrototype.get())), DontEnum);
440     putDirectWithoutTransition(vm, vm.propertyNames->Reflect, ReflectObject::create(vm, this, ReflectObject::createStructure(vm, this, m_objectPrototype.get())), DontEnum);
441     
442     std::array<InternalFunction*, NUMBER_OF_TYPED_ARRAY_TYPES> typedArrayConstructors;
443     typedArrayConstructors[toIndex(TypeInt8)] = JSInt8ArrayConstructor::create(vm, JSInt8ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeInt8)].prototype.get(), ASCIILiteral("Int8Array"));
444     typedArrayConstructors[toIndex(TypeInt16)] = JSInt16ArrayConstructor::create(vm, JSInt16ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeInt16)].prototype.get(), ASCIILiteral("Int16Array"));
445     typedArrayConstructors[toIndex(TypeInt32)] = JSInt32ArrayConstructor::create(vm, JSInt32ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeInt32)].prototype.get(), ASCIILiteral("Int32Array"));
446     typedArrayConstructors[toIndex(TypeUint8)] = JSUint8ArrayConstructor::create(vm, JSUint8ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeUint8)].prototype.get(), ASCIILiteral("Uint8Array"));
447     typedArrayConstructors[toIndex(TypeUint8Clamped)] = JSUint8ClampedArrayConstructor::create(vm, JSUint8ClampedArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeUint8Clamped)].prototype.get(), ASCIILiteral("Uint8ClampedArray"));
448     typedArrayConstructors[toIndex(TypeUint16)] = JSUint16ArrayConstructor::create(vm, JSUint16ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeUint16)].prototype.get(), ASCIILiteral("Uint16Array"));
449     typedArrayConstructors[toIndex(TypeUint32)] = JSUint32ArrayConstructor::create(vm, JSUint32ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeUint32)].prototype.get(), ASCIILiteral("Uint32Array"));
450     typedArrayConstructors[toIndex(TypeFloat32)] = JSFloat32ArrayConstructor::create(vm, JSFloat32ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeFloat32)].prototype.get(), ASCIILiteral("Float32Array"));
451     typedArrayConstructors[toIndex(TypeFloat64)] = JSFloat64ArrayConstructor::create(vm, JSFloat64ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeFloat64)].prototype.get(), ASCIILiteral("Float64Array"));
452     typedArrayConstructors[toIndex(TypeDataView)] = JSDataViewConstructor::create(vm, JSDataViewConstructor::createStructure(vm, this, m_functionPrototype.get()), m_typedArrays[toIndex(TypeDataView)].prototype.get(), ASCIILiteral("DataView"));
453     
454     for (unsigned typedArrayIndex = NUMBER_OF_TYPED_ARRAY_TYPES; typedArrayIndex--;) {
455         m_typedArrays[typedArrayIndex].prototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, typedArrayConstructors[typedArrayIndex], DontEnum);
456         putDirectWithoutTransition(vm, Identifier::fromString(exec, typedArrayConstructors[typedArrayIndex]->name(exec)), typedArrayConstructors[typedArrayIndex], DontEnum);
457     }
458     
459     JSFunction* builtinLog = JSFunction::create(vm, this, 1, vm.propertyNames->emptyIdentifier.string(), globalFuncBuiltinLog);
460
461     JSFunction* privateFuncAbs = JSFunction::create(vm, this, 0, String(), mathProtoFuncAbs, AbsIntrinsic);
462     JSFunction* privateFuncFloor = JSFunction::create(vm, this, 0, String(), mathProtoFuncFloor, FloorIntrinsic);
463     JSFunction* privateFuncIsFinite = JSFunction::create(vm, this, 0, String(), globalFuncIsFinite);
464
465     JSFunction* privateFuncGetTemplateObject = JSFunction::create(vm, this, 0, String(), getTemplateObject);
466     JSFunction* privateFuncToLength = JSFunction::createBuiltinFunction(vm, globalObjectToLengthCodeGenerator(vm), this);
467     JSFunction* privateFuncToInteger = JSFunction::createBuiltinFunction(vm, globalObjectToIntegerCodeGenerator(vm), this);
468
469     GlobalPropertyInfo staticGlobals[] = {
470         GlobalPropertyInfo(vm.propertyNames->NaN, jsNaN(), DontEnum | DontDelete | ReadOnly),
471         GlobalPropertyInfo(vm.propertyNames->Infinity, jsNumber(std::numeric_limits<double>::infinity()), DontEnum | DontDelete | ReadOnly),
472         GlobalPropertyInfo(vm.propertyNames->undefinedKeyword, jsUndefined(), DontEnum | DontDelete | ReadOnly),
473         GlobalPropertyInfo(vm.propertyNames->undefinedPrivateName, jsUndefined(), DontEnum | DontDelete | ReadOnly),
474         GlobalPropertyInfo(vm.propertyNames->ObjectPrivateName, objectConstructor, DontEnum | DontDelete | ReadOnly),
475         GlobalPropertyInfo(vm.propertyNames->ownEnumerablePropertyKeysPrivateName, JSFunction::create(vm, this, 0, String(), ownEnumerablePropertyKeys), DontEnum | DontDelete | ReadOnly),
476         GlobalPropertyInfo(vm.propertyNames->getTemplateObjectPrivateName, privateFuncGetTemplateObject, DontEnum | DontDelete | ReadOnly),
477         GlobalPropertyInfo(vm.propertyNames->enqueueJobPrivateName, JSFunction::create(vm, this, 0, String(), enqueueJob), DontEnum | DontDelete | ReadOnly),
478         GlobalPropertyInfo(vm.propertyNames->TypeErrorPrivateName, m_typeErrorConstructor.get(), DontEnum | DontDelete | ReadOnly),
479         GlobalPropertyInfo(vm.propertyNames->BuiltinLogPrivateName, builtinLog, DontEnum | DontDelete | ReadOnly),
480         GlobalPropertyInfo(vm.propertyNames->ArrayPrivateName, arrayConstructor, DontEnum | DontDelete | ReadOnly),
481         GlobalPropertyInfo(vm.propertyNames->NumberPrivateName, numberConstructor, DontEnum | DontDelete | ReadOnly),
482         GlobalPropertyInfo(vm.propertyNames->StringPrivateName, stringConstructor, DontEnum | DontDelete | ReadOnly),
483         GlobalPropertyInfo(vm.propertyNames->absPrivateName, privateFuncAbs, DontEnum | DontDelete | ReadOnly),
484         GlobalPropertyInfo(vm.propertyNames->floorPrivateName, privateFuncFloor, DontEnum | DontDelete | ReadOnly),
485         GlobalPropertyInfo(vm.propertyNames->getPrototypeOfPrivateName, privateFuncFloor, DontEnum | DontDelete | ReadOnly),
486         GlobalPropertyInfo(vm.propertyNames->getOwnPropertyNamesPrivateName, privateFuncFloor, DontEnum | DontDelete | ReadOnly),
487         GlobalPropertyInfo(vm.propertyNames->isFinitePrivateName, privateFuncIsFinite, DontEnum | DontDelete | ReadOnly),
488         GlobalPropertyInfo(vm.propertyNames->arrayIterationKindKeyPrivateName, jsNumber(ArrayIterateKey), DontEnum | DontDelete | ReadOnly),
489         GlobalPropertyInfo(vm.propertyNames->arrayIterationKindValuePrivateName, jsNumber(ArrayIterateValue), DontEnum | DontDelete | ReadOnly),
490         GlobalPropertyInfo(vm.propertyNames->arrayIterationKindKeyValuePrivateName, jsNumber(ArrayIterateKeyValue), DontEnum | DontDelete | ReadOnly),
491         GlobalPropertyInfo(vm.propertyNames->builtinNames().symbolIteratorPrivateName(), Symbol::create(vm, static_cast<SymbolImpl&>(*vm.propertyNames->iteratorSymbol.impl())), DontEnum | DontDelete | ReadOnly),
492         GlobalPropertyInfo(vm.propertyNames->PromisePrivateName, m_promiseConstructor.get(), DontEnum | DontDelete | ReadOnly),
493         GlobalPropertyInfo(vm.propertyNames->promisePendingPrivateName, jsNumber(static_cast<unsigned>(JSPromise::Status::Pending)), DontEnum | DontDelete | ReadOnly),
494         GlobalPropertyInfo(vm.propertyNames->promiseFulfilledPrivateName, jsNumber(static_cast<unsigned>(JSPromise::Status::Fulfilled)), DontEnum | DontDelete | ReadOnly),
495         GlobalPropertyInfo(vm.propertyNames->promiseRejectedPrivateName, jsNumber(static_cast<unsigned>(JSPromise::Status::Rejected)), DontEnum | DontDelete | ReadOnly),
496         GlobalPropertyInfo(vm.propertyNames->builtinNames().toLengthPrivateName(), privateFuncToLength, DontEnum | DontDelete | ReadOnly),
497         GlobalPropertyInfo(vm.propertyNames->builtinNames().toIntegerPrivateName(), privateFuncToInteger, DontEnum | DontDelete | ReadOnly),
498         GlobalPropertyInfo(vm.propertyNames->builtinNames().isObjectPrivateName(), JSFunction::createBuiltinFunction(vm, globalObjectIsObjectCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
499         GlobalPropertyInfo(vm.propertyNames->builtinNames().isPromisePrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseIsPromiseCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
500         GlobalPropertyInfo(vm.propertyNames->builtinNames().newPromiseReactionPrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseNewPromiseReactionCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
501         GlobalPropertyInfo(vm.propertyNames->builtinNames().newPromiseCapabilityPrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseNewPromiseCapabilityCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
502         GlobalPropertyInfo(vm.propertyNames->builtinNames().triggerPromiseReactionsPrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseTriggerPromiseReactionsCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
503         GlobalPropertyInfo(vm.propertyNames->builtinNames().rejectPromisePrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseRejectPromiseCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
504         GlobalPropertyInfo(vm.propertyNames->builtinNames().fulfillPromisePrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseFulfillPromiseCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
505         GlobalPropertyInfo(vm.propertyNames->builtinNames().createResolvingFunctionsPrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromiseCreateResolvingFunctionsCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
506         GlobalPropertyInfo(vm.propertyNames->builtinNames().promiseReactionJobPrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromisePromiseReactionJobCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
507         GlobalPropertyInfo(vm.propertyNames->builtinNames().promiseResolveThenableJobPrivateName(), JSFunction::createBuiltinFunction(vm, operationsPromisePromiseResolveThenableJobCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
508     };
509     addStaticGlobals(staticGlobals, WTF_ARRAY_LENGTH(staticGlobals));
510     
511     m_specialPointers[Special::CallFunction] = m_callFunction.get();
512     m_specialPointers[Special::ApplyFunction] = m_applyFunction.get();
513     m_specialPointers[Special::ObjectConstructor] = objectConstructor;
514     m_specialPointers[Special::ArrayConstructor] = arrayConstructor;
515
516     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::DefinePropertyFunction)] = m_definePropertyFunction.get();
517
518     ConsolePrototype* consolePrototype = ConsolePrototype::create(vm, this, ConsolePrototype::createStructure(vm, this, m_objectPrototype.get()));
519     m_consoleStructure.set(vm, this, JSConsole::createStructure(vm, this, consolePrototype));
520     JSConsole* consoleObject = JSConsole::create(vm, m_consoleStructure.get());
521     putDirectWithoutTransition(vm, Identifier::fromString(exec, "console"), consoleObject, DontEnum);
522
523     if (UNLIKELY(Options::enableDollarVM())) {
524         JSDollarVMPrototype* dollarVMPrototype = JSDollarVMPrototype::create(vm, this, JSDollarVMPrototype::createStructure(vm, this, m_objectPrototype.get()));
525         m_dollarVMStructure.set(vm, this, JSDollarVM::createStructure(vm, this, dollarVMPrototype));
526         JSDollarVM* dollarVM = JSDollarVM::create(vm, m_dollarVMStructure.get());
527         putDirectWithoutTransition(vm, Identifier::fromString(exec, "$vm"), dollarVM, DontEnum);
528     }
529
530     resetPrototype(vm, prototype());
531 }
532
533 void JSGlobalObject::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
534 {
535     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(cell);
536     ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(thisObject));
537
538     if (symbolTablePut(thisObject, exec, propertyName, value, slot.isStrictMode()))
539         return;
540     Base::put(thisObject, exec, propertyName, value, slot);
541 }
542
543 bool JSGlobalObject::defineOwnProperty(JSObject* object, ExecState* exec, PropertyName propertyName, const PropertyDescriptor& descriptor, bool shouldThrow)
544 {
545     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(object);
546     PropertySlot slot(thisObject);
547     // silently ignore attempts to add accessors aliasing vars.
548     if (descriptor.isAccessorDescriptor() && symbolTableGet(thisObject, propertyName, slot))
549         return false;
550     return Base::defineOwnProperty(thisObject, exec, propertyName, descriptor, shouldThrow);
551 }
552
553 void JSGlobalObject::addGlobalVar(const Identifier& ident)
554 {
555     ConcurrentJITLocker locker(symbolTable()->m_lock);
556     SymbolTableEntry entry = symbolTable()->get(locker, ident.impl());
557     if (!entry.isNull())
558         return;
559     
560     ScopeOffset offset = symbolTable()->takeNextScopeOffset(locker);
561     SymbolTableEntry newEntry(VarOffset(offset), 0);
562     newEntry.prepareToWatch();
563     symbolTable()->add(locker, ident.impl(), newEntry);
564     
565     ScopeOffset offsetForAssert = addVariables(1);
566     RELEASE_ASSERT(offsetForAssert == offset);
567 }
568
569 void JSGlobalObject::addFunction(ExecState* exec, const Identifier& propertyName)
570 {
571     VM& vm = exec->vm();
572     removeDirect(vm, propertyName); // Newly declared functions overwrite existing properties.
573     addGlobalVar(propertyName);
574 }
575
576 static inline JSObject* lastInPrototypeChain(JSObject* object)
577 {
578     JSObject* o = object;
579     while (o->prototype().isObject())
580         o = asObject(o->prototype());
581     return o;
582 }
583
584 // Private namespace for helpers for JSGlobalObject::haveABadTime()
585 namespace {
586
587 class ObjectsWithBrokenIndexingFinder : public MarkedBlock::VoidFunctor {
588 public:
589     ObjectsWithBrokenIndexingFinder(MarkedArgumentBuffer&, JSGlobalObject*);
590     IterationStatus operator()(JSCell*);
591
592 private:
593     void visit(JSCell*);
594
595     MarkedArgumentBuffer& m_foundObjects;
596     JSGlobalObject* m_globalObject;
597 };
598
599 ObjectsWithBrokenIndexingFinder::ObjectsWithBrokenIndexingFinder(
600     MarkedArgumentBuffer& foundObjects, JSGlobalObject* globalObject)
601     : m_foundObjects(foundObjects)
602     , m_globalObject(globalObject)
603 {
604 }
605
606 inline bool hasBrokenIndexing(JSObject* object)
607 {
608     // This will change if we have more indexing types.
609     IndexingType type = object->indexingType();
610     // This could be made obviously more efficient, but isn't made so right now, because
611     // we expect this to be an unlikely slow path anyway.
612     return hasUndecided(type) || hasInt32(type) || hasDouble(type) || hasContiguous(type) || hasArrayStorage(type);
613 }
614
615 inline void ObjectsWithBrokenIndexingFinder::visit(JSCell* cell)
616 {
617     if (!cell->isObject())
618         return;
619     
620     JSObject* object = asObject(cell);
621
622     // Run this filter first, since it's cheap, and ought to filter out a lot of objects.
623     if (!hasBrokenIndexing(object))
624         return;
625     
626     // We only want to have a bad time in the affected global object, not in the entire
627     // VM. But we have to be careful, since there may be objects that claim to belong to
628     // a different global object that have prototypes from our global object.
629     bool foundGlobalObject = false;
630     for (JSObject* current = object; ;) {
631         if (current->globalObject() == m_globalObject) {
632             foundGlobalObject = true;
633             break;
634         }
635         
636         JSValue prototypeValue = current->prototype();
637         if (prototypeValue.isNull())
638             break;
639         current = asObject(prototypeValue);
640     }
641     if (!foundGlobalObject)
642         return;
643     
644     m_foundObjects.append(object);
645 }
646
647 IterationStatus ObjectsWithBrokenIndexingFinder::operator()(JSCell* cell)
648 {
649     visit(cell);
650     return IterationStatus::Continue;
651 }
652
653 } // end private namespace for helpers for JSGlobalObject::haveABadTime()
654
655 void JSGlobalObject::haveABadTime(VM& vm)
656 {
657     ASSERT(&vm == &this->vm());
658     
659     if (isHavingABadTime())
660         return;
661     
662     // Make sure that all allocations or indexed storage transitions that are inlining
663     // the assumption that it's safe to transition to a non-SlowPut array storage don't
664     // do so anymore.
665     m_havingABadTimeWatchpoint->fireAll("Having a bad time");
666     ASSERT(isHavingABadTime()); // The watchpoint is what tells us that we're having a bad time.
667     
668     // Make sure that all JSArray allocations that load the appropriate structure from
669     // this object now load a structure that uses SlowPut.
670     for (unsigned i = 0; i < NumberOfIndexingShapes; ++i)
671         m_arrayStructureForIndexingShapeDuringAllocation[i].set(vm, this, originalArrayStructureForIndexingType(ArrayWithSlowPutArrayStorage));
672     
673     // Make sure that all objects that have indexed storage switch to the slow kind of
674     // indexed storage.
675     MarkedArgumentBuffer foundObjects; // Use MarkedArgumentBuffer because switchToSlowPutArrayStorage() may GC.
676     ObjectsWithBrokenIndexingFinder finder(foundObjects, this);
677     {
678         HeapIterationScope iterationScope(vm.heap);
679         vm.heap.objectSpace().forEachLiveCell(iterationScope, finder);
680     }
681     while (!foundObjects.isEmpty()) {
682         JSObject* object = asObject(foundObjects.last());
683         foundObjects.removeLast();
684         ASSERT(hasBrokenIndexing(object));
685         object->switchToSlowPutArrayStorage(vm);
686     }
687 }
688
689 bool JSGlobalObject::objectPrototypeIsSane()
690 {
691     return !hasIndexedProperties(m_objectPrototype->indexingType())
692         && m_objectPrototype->prototype().isNull();
693 }
694
695 bool JSGlobalObject::arrayPrototypeChainIsSane()
696 {
697     return !hasIndexedProperties(m_arrayPrototype->indexingType())
698         && m_arrayPrototype->prototype() == m_objectPrototype.get()
699         && objectPrototypeIsSane();
700 }
701
702 bool JSGlobalObject::stringPrototypeChainIsSane()
703 {
704     return !hasIndexedProperties(m_stringPrototype->indexingType())
705         && m_stringPrototype->prototype() == m_objectPrototype.get()
706         && objectPrototypeIsSane();
707 }
708
709 void JSGlobalObject::createThrowTypeError(VM& vm)
710 {
711     JSFunction* thrower = JSFunction::create(vm, this, 0, String(), globalFuncThrowTypeError);
712     GetterSetter* getterSetter = GetterSetter::create(vm, this);
713     getterSetter->setGetter(vm, this, thrower);
714     getterSetter->setSetter(vm, this, thrower);
715     m_throwTypeErrorGetterSetter.set(vm, this, getterSetter);
716 }
717
718 // Set prototype, and also insert the object prototype at the end of the chain.
719 void JSGlobalObject::resetPrototype(VM& vm, JSValue prototype)
720 {
721     setPrototype(vm, prototype);
722
723     JSObject* oldLastInPrototypeChain = lastInPrototypeChain(this);
724     JSObject* objectPrototype = m_objectPrototype.get();
725     if (oldLastInPrototypeChain != objectPrototype)
726         oldLastInPrototypeChain->setPrototype(vm, objectPrototype);
727
728     // Whenever we change the prototype of the global object, we need to create a new JSProxy with the correct prototype.
729     setGlobalThis(vm, JSProxy::create(vm, JSProxy::createStructure(vm, this, prototype, PureForwardingProxyType), this));
730 }
731
732 void JSGlobalObject::visitChildren(JSCell* cell, SlotVisitor& visitor)
733
734     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(cell);
735     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
736     Base::visitChildren(thisObject, visitor);
737
738     visitor.append(&thisObject->m_globalThis);
739
740     visitor.append(&thisObject->m_globalCallee);
741     visitor.append(&thisObject->m_regExpConstructor);
742     visitor.append(&thisObject->m_errorConstructor);
743     visitor.append(&thisObject->m_evalErrorConstructor);
744     visitor.append(&thisObject->m_rangeErrorConstructor);
745     visitor.append(&thisObject->m_referenceErrorConstructor);
746     visitor.append(&thisObject->m_syntaxErrorConstructor);
747     visitor.append(&thisObject->m_typeErrorConstructor);
748     visitor.append(&thisObject->m_URIErrorConstructor);
749     visitor.append(&thisObject->m_objectConstructor);
750     visitor.append(&thisObject->m_promiseConstructor);
751
752     visitor.append(&thisObject->m_nullGetterFunction);
753     visitor.append(&thisObject->m_nullSetterFunction);
754
755     visitor.append(&thisObject->m_parseIntFunction);
756     visitor.append(&thisObject->m_evalFunction);
757     visitor.append(&thisObject->m_callFunction);
758     visitor.append(&thisObject->m_applyFunction);
759     visitor.append(&thisObject->m_definePropertyFunction);
760     visitor.append(&thisObject->m_arrayProtoValuesFunction);
761     visitor.append(&thisObject->m_initializePromiseFunction);
762     visitor.append(&thisObject->m_newPromiseDeferredFunction);
763     visitor.append(&thisObject->m_throwTypeErrorGetterSetter);
764
765     visitor.append(&thisObject->m_objectPrototype);
766     visitor.append(&thisObject->m_functionPrototype);
767     visitor.append(&thisObject->m_arrayPrototype);
768     visitor.append(&thisObject->m_errorPrototype);
769     visitor.append(&thisObject->m_iteratorPrototype);
770     visitor.append(&thisObject->m_promisePrototype);
771
772     visitor.append(&thisObject->m_debuggerScopeStructure);
773     visitor.append(&thisObject->m_withScopeStructure);
774     visitor.append(&thisObject->m_strictEvalActivationStructure);
775     visitor.append(&thisObject->m_lexicalEnvironmentStructure);
776     visitor.append(&thisObject->m_catchScopeStructure);
777     visitor.append(&thisObject->m_functionNameScopeStructure);
778     visitor.append(&thisObject->m_directArgumentsStructure);
779     visitor.append(&thisObject->m_scopedArgumentsStructure);
780     visitor.append(&thisObject->m_outOfBandArgumentsStructure);
781     for (unsigned i = 0; i < NumberOfIndexingShapes; ++i)
782         visitor.append(&thisObject->m_originalArrayStructureForIndexingShape[i]);
783     for (unsigned i = 0; i < NumberOfIndexingShapes; ++i)
784         visitor.append(&thisObject->m_arrayStructureForIndexingShapeDuringAllocation[i]);
785     visitor.append(&thisObject->m_booleanObjectStructure);
786     visitor.append(&thisObject->m_callbackConstructorStructure);
787     visitor.append(&thisObject->m_callbackFunctionStructure);
788     visitor.append(&thisObject->m_callbackObjectStructure);
789     visitor.append(&thisObject->m_propertyNameIteratorStructure);
790 #if JSC_OBJC_API_ENABLED
791     visitor.append(&thisObject->m_objcCallbackFunctionStructure);
792     visitor.append(&thisObject->m_objcWrapperObjectStructure);
793 #endif
794     visitor.append(&thisObject->m_nullPrototypeObjectStructure);
795     visitor.append(&thisObject->m_errorStructure);
796     visitor.append(&thisObject->m_calleeStructure);
797     visitor.append(&thisObject->m_functionStructure);
798     visitor.append(&thisObject->m_boundFunctionStructure);
799     visitor.append(&thisObject->m_namedFunctionStructure);
800     visitor.append(&thisObject->m_symbolObjectStructure);
801     visitor.append(&thisObject->m_regExpStructure);
802     visitor.append(&thisObject->m_regExpMatchesArrayStructure);
803     visitor.append(&thisObject->m_consoleStructure);
804     visitor.append(&thisObject->m_dollarVMStructure);
805     visitor.append(&thisObject->m_internalFunctionStructure);
806     visitor.append(&thisObject->m_promiseStructure);
807
808 #define VISIT_SIMPLE_TYPE(CapitalName, lowerName, properName, instanceType, jsName) \
809     visitor.append(&thisObject->m_ ## lowerName ## Prototype); \
810     visitor.append(&thisObject->m_ ## properName ## Structure); \
811
812     FOR_EACH_SIMPLE_BUILTIN_TYPE(VISIT_SIMPLE_TYPE)
813     FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(VISIT_SIMPLE_TYPE)
814
815 #undef VISIT_SIMPLE_TYPE
816
817     for (unsigned i = NUMBER_OF_TYPED_ARRAY_TYPES; i--;) {
818         visitor.append(&thisObject->m_typedArrays[i].prototype);
819         visitor.append(&thisObject->m_typedArrays[i].structure);
820     }
821 }
822
823 JSValue JSGlobalObject::toThis(JSCell*, ExecState* exec, ECMAMode ecmaMode)
824 {
825     if (ecmaMode == StrictMode)
826         return jsUndefined();
827     return exec->globalThisValue();
828 }
829
830 ExecState* JSGlobalObject::globalExec()
831 {
832     return CallFrame::create(m_globalCallFrame);
833 }
834
835 void JSGlobalObject::addStaticGlobals(GlobalPropertyInfo* globals, int count)
836 {
837     ScopeOffset startOffset = addVariables(count);
838
839     for (int i = 0; i < count; ++i) {
840         GlobalPropertyInfo& global = globals[i];
841         ASSERT(global.attributes & DontDelete);
842         
843         ScopeOffset offset;
844         {
845             ConcurrentJITLocker locker(symbolTable()->m_lock);
846             offset = symbolTable()->takeNextScopeOffset(locker);
847             RELEASE_ASSERT(offset = startOffset + i);
848             SymbolTableEntry newEntry(VarOffset(offset), global.attributes);
849             symbolTable()->add(locker, global.identifier.impl(), newEntry);
850         }
851         variableAt(offset).set(vm(), this, global.value);
852     }
853 }
854
855 bool JSGlobalObject::getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
856 {
857     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(object);
858     if (getStaticFunctionSlot<Base>(exec, globalObjectTable, thisObject, propertyName, slot))
859         return true;
860     return symbolTableGet(thisObject, propertyName, slot);
861 }
862
863 void JSGlobalObject::clearRareData(JSCell* cell)
864 {
865     jsCast<JSGlobalObject*>(cell)->m_rareData = nullptr;
866 }
867
868 void slowValidateCell(JSGlobalObject* globalObject)
869 {
870     RELEASE_ASSERT(globalObject->isGlobalObject());
871     ASSERT_GC_OBJECT_INHERITS(globalObject, JSGlobalObject::info());
872 }
873
874 UnlinkedProgramCodeBlock* JSGlobalObject::createProgramCodeBlock(CallFrame* callFrame, ProgramExecutable* executable, JSObject** exception)
875 {
876     ParserError error;
877     JSParserStrictMode strictMode = executable->isStrictMode() ? JSParserStrictMode::Strict : JSParserStrictMode::NotStrict;
878     DebuggerMode debuggerMode = hasDebugger() ? DebuggerOn : DebuggerOff;
879     ProfilerMode profilerMode = hasProfiler() ? ProfilerOn : ProfilerOff;
880     UnlinkedProgramCodeBlock* unlinkedCodeBlock = vm().codeCache()->getProgramCodeBlock(
881         vm(), executable, executable->source(), JSParserBuiltinMode::NotBuiltin, strictMode, 
882         debuggerMode, profilerMode, error);
883
884     if (hasDebugger())
885         debugger()->sourceParsed(callFrame, executable->source().provider(), error.line(), error.message());
886
887     if (error.isValid()) {
888         *exception = error.toErrorObject(this, executable->source());
889         return nullptr;
890     }
891     
892     return unlinkedCodeBlock;
893 }
894
895 UnlinkedEvalCodeBlock* JSGlobalObject::createEvalCodeBlock(CallFrame* callFrame, EvalExecutable* executable, ThisTDZMode thisTDZMode, const VariableEnvironment* variablesUnderTDZ)
896 {
897     ParserError error;
898     JSParserStrictMode strictMode = executable->isStrictMode() ? JSParserStrictMode::Strict : JSParserStrictMode::NotStrict;
899     DebuggerMode debuggerMode = hasDebugger() ? DebuggerOn : DebuggerOff;
900     ProfilerMode profilerMode = hasProfiler() ? ProfilerOn : ProfilerOff;
901     UnlinkedEvalCodeBlock* unlinkedCodeBlock = vm().codeCache()->getEvalCodeBlock(
902         vm(), executable, executable->source(), JSParserBuiltinMode::NotBuiltin, strictMode, thisTDZMode, debuggerMode, profilerMode, error, variablesUnderTDZ);
903
904     if (hasDebugger())
905         debugger()->sourceParsed(callFrame, executable->source().provider(), error.line(), error.message());
906
907     if (error.isValid()) {
908         throwVMError(callFrame, error.toErrorObject(this, executable->source()));
909         return nullptr;
910     }
911
912     return unlinkedCodeBlock;
913 }
914
915 void JSGlobalObject::setRemoteDebuggingEnabled(bool enabled)
916 {
917 #if ENABLE(REMOTE_INSPECTOR)
918     m_inspectorDebuggable->setRemoteDebuggingAllowed(enabled);
919 #else
920     UNUSED_PARAM(enabled);
921 #endif
922 }
923
924 bool JSGlobalObject::remoteDebuggingEnabled() const
925 {
926 #if ENABLE(REMOTE_INSPECTOR)
927     return m_inspectorDebuggable->remoteDebuggingAllowed();
928 #else
929     return false;
930 #endif
931 }
932
933 #if ENABLE(WEB_REPLAY)
934 void JSGlobalObject::setInputCursor(PassRefPtr<InputCursor> prpCursor)
935 {
936     m_inputCursor = prpCursor;
937     ASSERT(m_inputCursor);
938
939     InputCursor& cursor = inputCursor();
940     // Save or set the random seed. This performed here rather than the constructor
941     // to avoid threading the input cursor through all the abstraction layers.
942     if (cursor.isCapturing())
943         cursor.appendInput<SetRandomSeed>(m_weakRandom.seedUnsafe());
944     else if (cursor.isReplaying()) {
945         if (SetRandomSeed* input = cursor.fetchInput<SetRandomSeed>())
946             m_weakRandom.initializeSeed(static_cast<unsigned>(input->randomSeed()));
947     }
948 }
949 #endif
950
951 void JSGlobalObject::setName(const String& name)
952 {
953     m_name = name;
954
955 #if ENABLE(REMOTE_INSPECTOR)
956     m_inspectorDebuggable->update();
957 #endif
958 }
959
960 void JSGlobalObject::queueMicrotask(PassRefPtr<Microtask> task)
961 {
962     if (globalObjectMethodTable()->queueTaskToEventLoop) {
963         globalObjectMethodTable()->queueTaskToEventLoop(this, task);
964         return;
965     }
966
967     vm().queueMicrotask(this, task);
968 }
969
970 } // namespace JSC