Add an option that exposes functions on the global object to turn on and off the...
[WebKit-https.git] / Source / JavaScriptCore / runtime / JSGlobalObject.cpp
1 /*
2  * Copyright (C) 2007-2019 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 "AggregateError.h"
34 #include "AggregateErrorConstructor.h"
35 #include "AggregateErrorPrototype.h"
36 #include "ArrayConstructor.h"
37 #include "ArrayIteratorPrototype.h"
38 #include "ArrayPrototype.h"
39 #include "AsyncFromSyncIteratorPrototype.h"
40 #include "AsyncFunctionConstructor.h"
41 #include "AsyncFunctionPrototype.h"
42 #include "AsyncGeneratorFunctionConstructor.h"
43 #include "AsyncGeneratorFunctionPrototype.h"
44 #include "AsyncGeneratorPrototype.h"
45 #include "AsyncIteratorPrototype.h"
46 #include "BigIntConstructor.h"
47 #include "BigIntObject.h"
48 #include "BigIntPrototype.h"
49 #include "BooleanConstructor.h"
50 #include "BooleanPrototype.h"
51 #include "BuiltinNames.h"
52 #include "CatchScope.h"
53 #include "ClonedArguments.h"
54 #include "CodeBlock.h"
55 #include "CodeBlockSetInlines.h"
56 #include "ConsoleObject.h"
57 #include "DateConstructor.h"
58 #include "DatePrototype.h"
59 #include "Debugger.h"
60 #include "DebuggerScope.h"
61 #include "DirectArguments.h"
62 #include "ErrorConstructor.h"
63 #include "ErrorPrototype.h"
64 #include "FunctionConstructor.h"
65 #include "FunctionPrototype.h"
66 #include "GeneratorFunctionConstructor.h"
67 #include "GeneratorFunctionPrototype.h"
68 #include "GeneratorPrototype.h"
69 #include "GetterSetter.h"
70 #include "HeapIterationScope.h"
71 #include "InspectorInstrumentationObject.h"
72 #include "IntlCollator.h"
73 #include "IntlCollatorPrototype.h"
74 #include "IntlDateTimeFormat.h"
75 #include "IntlDateTimeFormatPrototype.h"
76 #include "IntlLocale.h"
77 #include "IntlLocalePrototype.h"
78 #include "IntlNumberFormat.h"
79 #include "IntlNumberFormatPrototype.h"
80 #include "IntlObject.h"
81 #include "IntlPluralRules.h"
82 #include "IntlPluralRulesPrototype.h"
83 #include "IntlRelativeTimeFormat.h"
84 #include "IntlRelativeTimeFormatPrototype.h"
85 #include "IteratorPrototype.h"
86 #include "JSAPIWrapperObject.h"
87 #include "JSArrayBuffer.h"
88 #include "JSArrayBufferConstructor.h"
89 #include "JSArrayBufferPrototype.h"
90 #include "JSArrayIterator.h"
91 #include "JSAsyncFunction.h"
92 #include "JSAsyncGenerator.h"
93 #include "JSAsyncGeneratorFunction.h"
94 #include "JSBoundFunction.h"
95 #include "JSCallbackConstructor.h"
96 #include "JSCallbackFunction.h"
97 #include "JSCallbackObject.h"
98 #include "JSCustomGetterSetterFunction.h"
99 #include "JSDataView.h"
100 #include "JSDataViewPrototype.h"
101 #include "JSDollarVM.h"
102 #include "JSFunction.h"
103 #include "JSGenerator.h"
104 #include "JSGeneratorFunction.h"
105 #include "JSGenericTypedArrayViewConstructorInlines.h"
106 #include "JSGenericTypedArrayViewInlines.h"
107 #include "JSGenericTypedArrayViewPrototypeInlines.h"
108 #include "JSGlobalObjectFunctions.h"
109 #include "JSInternalPromise.h"
110 #include "JSInternalPromiseConstructor.h"
111 #include "JSInternalPromisePrototype.h"
112 #include "JSLexicalEnvironment.h"
113 #include "JSMap.h"
114 #include "JSMapIterator.h"
115 #include "JSMicrotask.h"
116 #include "JSModuleEnvironment.h"
117 #include "JSModuleLoader.h"
118 #include "JSModuleNamespaceObject.h"
119 #include "JSModuleRecord.h"
120 #include "JSNativeStdFunction.h"
121 #include "JSONObject.h"
122 #include "JSPromise.h"
123 #include "JSPromiseConstructor.h"
124 #include "JSPromisePrototype.h"
125 #include "JSSet.h"
126 #include "JSSetIterator.h"
127 #include "JSStringIterator.h"
128 #include "JSTypedArrayConstructors.h"
129 #include "JSTypedArrayPrototypes.h"
130 #include "JSTypedArrayViewConstructor.h"
131 #include "JSTypedArrayViewPrototype.h"
132 #include "JSTypedArrays.h"
133 #include "JSWeakMap.h"
134 #include "JSWeakObjectRef.h"
135 #include "JSWeakSet.h"
136 #include "JSWebAssembly.h"
137 #include "JSWebAssemblyCompileError.h"
138 #include "JSWebAssemblyGlobal.h"
139 #include "JSWebAssemblyInstance.h"
140 #include "JSWebAssemblyLinkError.h"
141 #include "JSWebAssemblyMemory.h"
142 #include "JSWebAssemblyModule.h"
143 #include "JSWebAssemblyRuntimeError.h"
144 #include "JSWebAssemblyTable.h"
145 #include "JSWithScope.h"
146 #include "LazyClassStructureInlines.h"
147 #include "LazyPropertyInlines.h"
148 #include "LinkTimeConstant.h"
149 #include "MapConstructor.h"
150 #include "MapIteratorPrototype.h"
151 #include "MapPrototype.h"
152 #include "MarkedSpaceInlines.h"
153 #include "MathObject.h"
154 #include "NativeErrorConstructor.h"
155 #include "NativeErrorPrototype.h"
156 #include "NullGetterFunction.h"
157 #include "NullSetterFunction.h"
158 #include "NumberConstructor.h"
159 #include "NumberPrototype.h"
160 #include "ObjCCallbackFunction.h"
161 #include "ObjectConstructor.h"
162 #include "ObjectPropertyChangeAdaptiveWatchpoint.h"
163 #include "ObjectPropertyConditionSet.h"
164 #include "ObjectPrototype.h"
165 #include "ProxyConstructor.h"
166 #include "ProxyObject.h"
167 #include "ProxyRevoke.h"
168 #include "ReflectObject.h"
169 #include "RegExpConstructor.h"
170 #include "RegExpMatchesArray.h"
171 #include "RegExpObject.h"
172 #include "RegExpPrototype.h"
173 #include "RegExpStringIteratorPrototype.h"
174 #include "SamplingProfiler.h"
175 #include "ScopedArguments.h"
176 #include "SetConstructor.h"
177 #include "SetIteratorPrototype.h"
178 #include "SetPrototype.h"
179 #include "StrictEvalActivation.h"
180 #include "StringConstructor.h"
181 #include "StringIteratorPrototype.h"
182 #include "StringPrototype.h"
183 #include "SymbolConstructor.h"
184 #include "SymbolObject.h"
185 #include "SymbolPrototype.h"
186 #include "WasmCapabilities.h"
187 #include "WeakMapConstructor.h"
188 #include "WeakMapPrototype.h"
189 #include "WeakObjectRefConstructor.h"
190 #include "WeakObjectRefPrototype.h"
191 #include "WeakSetConstructor.h"
192 #include "WeakSetPrototype.h"
193 #include "WebAssemblyCompileErrorConstructor.h"
194 #include "WebAssemblyCompileErrorPrototype.h"
195 #include "WebAssemblyFunction.h"
196 #include "WebAssemblyGlobalConstructor.h"
197 #include "WebAssemblyGlobalPrototype.h"
198 #include "WebAssemblyInstanceConstructor.h"
199 #include "WebAssemblyInstancePrototype.h"
200 #include "WebAssemblyLinkErrorConstructor.h"
201 #include "WebAssemblyLinkErrorPrototype.h"
202 #include "WebAssemblyMemoryConstructor.h"
203 #include "WebAssemblyMemoryPrototype.h"
204 #include "WebAssemblyModuleConstructor.h"
205 #include "WebAssemblyModulePrototype.h"
206 #include "WebAssemblyModuleRecord.h"
207 #include "WebAssemblyRuntimeErrorConstructor.h"
208 #include "WebAssemblyRuntimeErrorPrototype.h"
209 #include "WebAssemblyTableConstructor.h"
210 #include "WebAssemblyTablePrototype.h"
211 #include <wtf/RandomNumber.h>
212
213 #if ENABLE(REMOTE_INSPECTOR)
214 #include "JSGlobalObjectDebuggable.h"
215 #include "JSGlobalObjectInspectorController.h"
216 #endif
217
218 #ifdef JSC_GLIB_API_ENABLED
219 #include "JSCCallbackFunction.h"
220 #include "JSCWrapperMap.h"
221 #endif
222
223 namespace JSC {
224
225 #define CHECK_FEATURE_FLAG_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
226 static_assert(std::is_same_v<std::remove_cv_t<decltype(featureFlag)>, bool> || std::is_same_v<std::remove_cv_t<decltype(featureFlag)>, bool&>);
227
228 FOR_EACH_SIMPLE_BUILTIN_TYPE(CHECK_FEATURE_FLAG_TYPE)
229 FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(CHECK_FEATURE_FLAG_TYPE)
230 FOR_EACH_LAZY_BUILTIN_TYPE(CHECK_FEATURE_FLAG_TYPE)
231
232 static JSValue createProxyProperty(VM& vm, JSObject* object)
233 {
234     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
235     return ProxyConstructor::create(vm, ProxyConstructor::createStructure(vm, global, global->functionPrototype()));
236 }
237
238 static JSValue createJSONProperty(VM& vm, JSObject* object)
239 {
240     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
241     return JSONObject::create(vm, JSONObject::createStructure(vm, global, global->objectPrototype()));
242 }
243
244 static JSValue createMathProperty(VM& vm, JSObject* object)
245 {
246     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
247     return MathObject::create(vm, global, MathObject::createStructure(vm, global, global->objectPrototype()));
248 }
249
250 static JSValue createReflectProperty(VM& vm, JSObject* object)
251 {
252     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
253     return ReflectObject::create(vm, global, ReflectObject::createStructure(vm, global, global->objectPrototype()));
254 }
255
256 static JSValue createConsoleProperty(VM& vm, JSObject* object)
257 {
258     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
259     return ConsoleObject::create(vm, global, ConsoleObject::createStructure(vm, global, constructEmptyObject(global)));
260 }
261
262 static EncodedJSValue JSC_HOST_CALL makeBoundFunction(JSGlobalObject* globalObject, CallFrame* callFrame)
263 {
264     VM& vm = globalObject->vm();
265     auto scope = DECLARE_THROW_SCOPE(vm);
266
267     JSObject* target = asObject(callFrame->uncheckedArgument(0));
268     JSValue boundThis = callFrame->uncheckedArgument(1);
269     JSValue boundArgs = callFrame->uncheckedArgument(2);
270     JSValue lengthValue = callFrame->uncheckedArgument(3);
271     JSString* nameString = asString(callFrame->uncheckedArgument(4));
272
273     ASSERT(lengthValue.isInt32AsAnyInt());
274     int32_t length = lengthValue.asInt32AsAnyInt();
275
276     RELEASE_AND_RETURN(scope, JSValue::encode(JSBoundFunction::create(vm, globalObject, target, boundThis, boundArgs.isCell() ? jsCast<JSImmutableButterfly*>(boundArgs) : nullptr, length, nameString)));
277 }
278
279 static EncodedJSValue JSC_HOST_CALL hasOwnLengthProperty(JSGlobalObject* globalObject, CallFrame* callFrame)
280 {
281     VM& vm = globalObject->vm();
282     auto scope = DECLARE_THROW_SCOPE(vm);
283
284     JSObject* target = asObject(callFrame->uncheckedArgument(0));
285     JSFunction* function = jsDynamicCast<JSFunction*>(vm, target);
286     if (function && function->canAssumeNameAndLengthAreOriginal(vm)) {
287 #if ASSERT_ENABLED
288         bool result = target->hasOwnProperty(globalObject, vm.propertyNames->length);
289         RETURN_IF_EXCEPTION(scope, { });
290         ASSERT(result);
291 #endif
292         return JSValue::encode(jsBoolean(true));
293     }
294     RELEASE_AND_RETURN(scope, JSValue::encode(jsBoolean(target->hasOwnProperty(globalObject, vm.propertyNames->length))));
295 }
296
297 #if ASSERT_ENABLED
298 static EncodedJSValue JSC_HOST_CALL assertCall(JSGlobalObject* globalObject, CallFrame* callFrame)
299 {
300     RELEASE_ASSERT(callFrame->argument(0).isBoolean());
301     if (callFrame->argument(0).asBoolean())
302         return JSValue::encode(jsUndefined());
303
304     bool iteratedOnce = false;
305     CodeBlock* codeBlock = nullptr;
306     unsigned line;
307     callFrame->iterate(globalObject->vm(), [&] (StackVisitor& visitor) {
308         if (!iteratedOnce) {
309             iteratedOnce = true;
310             return StackVisitor::Continue;
311         }
312
313         RELEASE_ASSERT(visitor->hasLineAndColumnInfo());
314         unsigned column;
315         visitor->computeLineAndColumn(line, column);
316         codeBlock = visitor->codeBlock();
317         return StackVisitor::Done;
318     });
319     RELEASE_ASSERT(!!codeBlock);
320     RELEASE_ASSERT_WITH_MESSAGE(false, "JS assertion failed at line %u in:\n%s\n", line, codeBlock->sourceCodeForTools().data());
321     return JSValue::encode(jsUndefined());
322 }
323 #endif // ASSERT_ENABLED
324
325 #if ENABLE(SAMPLING_PROFILER)
326 static EncodedJSValue JSC_HOST_CALL enableSamplingProfiler(JSGlobalObject* globalObject, CallFrame*)
327 {
328     SamplingProfiler* profiler = globalObject->vm().samplingProfiler();
329     if (!profiler)
330         profiler = &globalObject->vm().ensureSamplingProfiler(Stopwatch::create());
331     profiler->start();
332     return JSValue::encode(jsUndefined());
333 }
334
335 static EncodedJSValue JSC_HOST_CALL disableSamplingProfiler(JSGlobalObject* globalObject, CallFrame*)
336 {
337     SamplingProfiler* profiler = globalObject->vm().samplingProfiler();
338     if (!profiler)
339         profiler = &globalObject->vm().ensureSamplingProfiler(Stopwatch::create());
340
341     {
342         auto locker = holdLock(profiler->getLock());
343         profiler->pause(locker);
344     }
345
346     return JSValue::encode(jsUndefined());
347 }
348 #endif
349
350 static EncodedJSValue JSC_HOST_CALL enableSuperSampler(JSGlobalObject*, CallFrame*)
351 {
352     enableSuperSampler();
353     return JSValue::encode(jsUndefined());
354 }
355
356 static EncodedJSValue JSC_HOST_CALL disableSuperSampler(JSGlobalObject*, CallFrame*)
357 {
358     disableSuperSampler();
359     return JSValue::encode(jsUndefined());
360 }
361
362 } // namespace JSC
363
364 #include "JSGlobalObject.lut.h"
365
366 namespace JSC {
367
368 const ClassInfo JSGlobalObject::s_info = { "GlobalObject", &Base::s_info, &globalObjectTable, nullptr, CREATE_METHOD_TABLE(JSGlobalObject) };
369
370 const GlobalObjectMethodTable JSGlobalObject::s_globalObjectMethodTable = {
371     &supportsRichSourceInfo,
372     &shouldInterruptScript,
373     &javaScriptRuntimeFlags,
374     nullptr, // queueTaskToEventLoop
375     &shouldInterruptScriptBeforeTimeout,
376     nullptr, // moduleLoaderImportModule
377     nullptr, // moduleLoaderResolve
378     nullptr, // moduleLoaderFetch
379     nullptr, // moduleLoaderCreateImportMetaProperties
380     nullptr, // moduleLoaderEvaluate
381     nullptr, // promiseRejectionTracker
382     nullptr, // defaultLanguage
383     nullptr, // compileStreaming
384     nullptr, // instantiateStreaming
385 };
386
387 /* Source for JSGlobalObject.lut.h
388 @begin globalObjectTable
389   isNaN                 JSBuiltin                                    DontEnum|Function 1
390   isFinite              JSBuiltin                                    DontEnum|Function 1
391   escape                globalFuncEscape                             DontEnum|Function 1
392   unescape              globalFuncUnescape                           DontEnum|Function 1
393   decodeURI             globalFuncDecodeURI                          DontEnum|Function 1
394   decodeURIComponent    globalFuncDecodeURIComponent                 DontEnum|Function 1
395   encodeURI             globalFuncEncodeURI                          DontEnum|Function 1
396   encodeURIComponent    globalFuncEncodeURIComponent                 DontEnum|Function 1
397   eval                  JSGlobalObject::m_evalFunction               DontEnum|CellProperty
398   globalThis            JSGlobalObject::m_globalThis                 DontEnum|CellProperty
399   parseInt              JSGlobalObject::m_parseIntFunction           DontEnum|CellProperty
400   parseFloat            JSGlobalObject::m_parseFloatFunction         DontEnum|CellProperty
401   ArrayBuffer           JSGlobalObject::m_arrayBufferStructure       DontEnum|ClassStructure
402   EvalError             JSGlobalObject::m_evalErrorStructure         DontEnum|ClassStructure
403   RangeError            JSGlobalObject::m_rangeErrorStructure        DontEnum|ClassStructure
404   ReferenceError        JSGlobalObject::m_referenceErrorStructure    DontEnum|ClassStructure
405   SyntaxError           JSGlobalObject::m_syntaxErrorStructure       DontEnum|ClassStructure
406   TypeError             JSGlobalObject::m_typeErrorStructure         DontEnum|ClassStructure
407   URIError              JSGlobalObject::m_URIErrorStructure          DontEnum|ClassStructure
408   AggregateError        JSGlobalObject::m_aggregateErrorStructure    DontEnum|ClassStructure
409   Proxy                 createProxyProperty                          DontEnum|PropertyCallback
410   Reflect               createReflectProperty                        DontEnum|PropertyCallback
411   JSON                  createJSONProperty                           DontEnum|PropertyCallback
412   Math                  createMathProperty                           DontEnum|PropertyCallback
413   console               createConsoleProperty                        DontEnum|PropertyCallback
414   Int8Array             JSGlobalObject::m_typedArrayInt8             DontEnum|ClassStructure
415   Int16Array            JSGlobalObject::m_typedArrayInt16            DontEnum|ClassStructure
416   Int32Array            JSGlobalObject::m_typedArrayInt32            DontEnum|ClassStructure
417   Uint8Array            JSGlobalObject::m_typedArrayUint8            DontEnum|ClassStructure
418   Uint8ClampedArray     JSGlobalObject::m_typedArrayUint8Clamped     DontEnum|ClassStructure
419   Uint16Array           JSGlobalObject::m_typedArrayUint16           DontEnum|ClassStructure
420   Uint32Array           JSGlobalObject::m_typedArrayUint32           DontEnum|ClassStructure
421   Float32Array          JSGlobalObject::m_typedArrayFloat32          DontEnum|ClassStructure
422   Float64Array          JSGlobalObject::m_typedArrayFloat64          DontEnum|ClassStructure
423   DataView              JSGlobalObject::m_typedArrayDataView         DontEnum|ClassStructure
424   Date                  JSGlobalObject::m_dateStructure              DontEnum|ClassStructure
425   Error                 JSGlobalObject::m_errorStructure             DontEnum|ClassStructure
426   Boolean               JSGlobalObject::m_booleanObjectStructure     DontEnum|ClassStructure
427   Map                   JSGlobalObject::m_mapStructure               DontEnum|ClassStructure
428   Number                JSGlobalObject::m_numberObjectStructure      DontEnum|ClassStructure
429   Set                   JSGlobalObject::m_setStructure               DontEnum|ClassStructure
430   Symbol                JSGlobalObject::m_symbolObjectStructure      DontEnum|ClassStructure
431   WeakMap               JSGlobalObject::m_weakMapStructure           DontEnum|ClassStructure
432   WeakSet               JSGlobalObject::m_weakSetStructure           DontEnum|ClassStructure
433 @end
434 */
435
436 static EncodedJSValue JSC_HOST_CALL enqueueJob(JSGlobalObject* globalObject, CallFrame* callFrame)
437 {
438     VM& vm = globalObject->vm();
439
440     JSValue job = callFrame->argument(0);
441     JSValue argument0 = callFrame->argument(1);
442     JSValue argument1 = callFrame->argument(2);
443     JSValue argument2 = callFrame->argument(3);
444
445     globalObject->queueMicrotask(createJSMicrotask(vm, job, argument0, argument1, argument2));
446
447     return JSValue::encode(jsUndefined());
448 }
449
450 JSGlobalObject::JSGlobalObject(VM& vm, Structure* structure, const GlobalObjectMethodTable* globalObjectMethodTable)
451     : Base(vm, structure, nullptr)
452     , m_vm(&vm)
453     , m_linkTimeConstants(numberOfLinkTimeConstants)
454     , m_masqueradesAsUndefinedWatchpoint(WatchpointSet::create(IsWatched))
455     , m_havingABadTimeWatchpoint(WatchpointSet::create(IsWatched))
456     , m_varInjectionWatchpoint(WatchpointSet::create(IsWatched))
457     , m_weakRandom(Options::forceWeakRandomSeed() ? Options::forcedWeakRandomSeed() : static_cast<unsigned>(randomNumber() * (std::numeric_limits<unsigned>::max() + 1.0)))
458     , m_arrayIteratorProtocolWatchpointSet(IsWatched)
459     , m_mapIteratorProtocolWatchpointSet(IsWatched)
460     , m_setIteratorProtocolWatchpointSet(IsWatched)
461     , m_stringIteratorProtocolWatchpointSet(IsWatched)
462     , m_mapSetWatchpointSet(IsWatched)
463     , m_setAddWatchpointSet(IsWatched)
464     , m_arraySpeciesWatchpointSet(ClearWatchpoint)
465     , m_arrayJoinWatchpointSet(IsWatched)
466     , m_numberToStringWatchpointSet(IsWatched)
467     , m_runtimeFlags()
468     , m_stackTraceLimit(Options::defaultErrorStackTraceLimit())
469     , m_globalObjectMethodTable(globalObjectMethodTable ? globalObjectMethodTable : &s_globalObjectMethodTable)
470 {
471 }
472
473 JSGlobalObject::~JSGlobalObject()
474 {
475 #if ENABLE(REMOTE_INSPECTOR)
476     m_inspectorController->globalObjectDestroyed();
477 #endif
478
479     if (m_debugger)
480         m_debugger->detach(this, Debugger::GlobalObjectIsDestructing);
481 }
482
483 void JSGlobalObject::destroy(JSCell* cell)
484 {
485     static_cast<JSGlobalObject*>(cell)->JSGlobalObject::~JSGlobalObject();
486 }
487
488 void JSGlobalObject::setGlobalThis(VM& vm, JSObject* globalThis)
489 {
490     m_globalThis.set(vm, this, globalThis);
491 }
492
493 static GetterSetter* getGetterById(JSGlobalObject* globalObject, JSObject* base, const Identifier& ident)
494 {
495     JSValue baseValue = JSValue(base);
496     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::VMInquiry);
497     baseValue.getPropertySlot(globalObject, ident, slot);
498     return jsCast<GetterSetter*>(slot.getPureResult());
499 }
500
501 static ObjectPropertyCondition setupAdaptiveWatchpoint(JSGlobalObject* globalObject, JSObject* base, const Identifier& ident)
502 {
503     // Performing these gets should not throw.
504     VM& vm = globalObject->vm();
505     auto catchScope = DECLARE_CATCH_SCOPE(vm);
506     PropertySlot slot(base, PropertySlot::InternalMethodType::Get);
507     bool result = base->getOwnPropertySlot(base, globalObject, ident, slot);
508     ASSERT_UNUSED(result, result);
509     catchScope.assertNoException();
510     RELEASE_ASSERT(slot.isCacheableValue());
511     JSValue functionValue = slot.getValue(globalObject, ident);
512     catchScope.assertNoException();
513     ASSERT(jsDynamicCast<JSFunction*>(vm, functionValue));
514
515     ObjectPropertyCondition condition = generateConditionForSelfEquivalence(vm, nullptr, base, ident.impl());
516     RELEASE_ASSERT(condition.requiredValue() == functionValue);
517
518     bool isWatchable = condition.isWatchable(PropertyCondition::EnsureWatchability);
519     RELEASE_ASSERT(isWatchable); // We allow this to install the necessary watchpoints.
520
521     return condition;
522 }
523
524 template<ErrorType errorType>
525 void JSGlobalObject::initializeErrorConstructor(LazyClassStructure::Initializer& init)
526 {
527     init.setPrototype(NativeErrorPrototype::create(init.vm, NativeErrorPrototype::createStructure(init.vm, this, m_errorStructure.prototype(this)), errorTypeName(errorType)));
528     init.setStructure(ErrorInstance::createStructure(init.vm, this, init.prototype));
529     init.setConstructor(NativeErrorConstructor<errorType>::create(init.vm, NativeErrorConstructor<errorType>::createStructure(init.vm, this, m_errorStructure.constructor(this)), jsCast<NativeErrorPrototype*>(init.prototype)));
530 }
531
532 void JSGlobalObject::initializeAggregateErrorConstructor(LazyClassStructure::Initializer& init)
533 {
534     init.setPrototype(AggregateErrorPrototype::create(init.vm, this, AggregateErrorPrototype::createStructure(init.vm, this, m_errorStructure.prototype(this))));
535     init.setStructure(AggregateError::createStructure(init.vm, this, init.prototype));
536     init.setConstructor(AggregateErrorConstructor::create(init.vm, AggregateErrorConstructor::createStructure(init.vm, this, m_errorStructure.constructor(this)), jsCast<AggregateErrorPrototype*>(init.prototype)));
537 }
538
539 void JSGlobalObject::init(VM& vm)
540 {
541     ASSERT(vm.currentThreadIsHoldingAPILock());
542     auto catchScope = DECLARE_CATCH_SCOPE(vm);
543
544     Base::setStructure(vm, Structure::toCacheableDictionaryTransition(vm, structure(vm)));
545
546     m_debugger = nullptr;
547
548 #if ENABLE(REMOTE_INSPECTOR)
549     m_inspectorController = makeUnique<Inspector::JSGlobalObjectInspectorController>(*this);
550     m_inspectorDebuggable = makeUnique<JSGlobalObjectDebuggable>(*this);
551     m_inspectorDebuggable->init();
552     m_consoleClient = m_inspectorController->consoleClient();
553 #endif
554
555     m_functionPrototype.set(vm, this, FunctionPrototype::create(vm, FunctionPrototype::createStructure(vm, this, jsNull()))); // The real prototype will be set once ObjectPrototype is created.
556     m_calleeStructure.set(vm, this, JSCallee::createStructure(vm, this, jsNull()));
557
558     m_globalLexicalEnvironment.set(vm, this, JSGlobalLexicalEnvironment::create(vm, JSGlobalLexicalEnvironment::createStructure(vm, this), this));
559
560     // Need to create the callee structure (above) before creating the callee.
561     JSCallee* globalCallee = JSCallee::create(vm, this, globalScope());
562     m_globalCallee.set(vm, this, globalCallee);
563
564     CallFrame::initDeprecatedCallFrameForDebugger(JSGlobalObject::deprecatedCallFrameForDebugger(), globalCallee);
565
566     JSCallee* stackOverflowFrameCallee = JSCallee::create(vm, this, globalScope());
567     m_stackOverflowFrameCallee.set(vm, this, stackOverflowFrameCallee);
568
569     m_hostFunctionStructure.set(vm, this, JSFunction::createStructure(vm, this, m_functionPrototype.get()));
570
571     auto initFunctionStructures = [&] (FunctionStructures& structures) {
572         structures.strictFunctionStructure.set(vm, this, JSStrictFunction::createStructure(vm, this, m_functionPrototype.get()));
573         structures.sloppyFunctionStructure.set(vm, this, JSSloppyFunction::createStructure(vm, this, m_functionPrototype.get()));
574         structures.arrowFunctionStructure.set(vm, this, JSArrowFunction::createStructure(vm, this, m_functionPrototype.get()));
575     };
576     initFunctionStructures(m_builtinFunctions);
577     initFunctionStructures(m_ordinaryFunctions);
578
579     m_customGetterSetterFunctionStructure.initLater(
580         [] (const Initializer<Structure>& init) {
581             init.set(JSCustomGetterSetterFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
582         });
583     m_boundFunctionStructure.initLater(
584         [] (const Initializer<Structure>& init) {
585             init.set(JSBoundFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
586         });
587     m_nativeStdFunctionStructure.initLater(
588         [] (const Initializer<Structure>& init) {
589             init.set(JSNativeStdFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
590         });
591     JSFunction* callFunction = nullptr;
592     JSFunction* applyFunction = nullptr;
593     JSFunction* hasInstanceSymbolFunction = nullptr;
594     m_functionPrototype->addFunctionProperties(vm, this, &callFunction, &applyFunction, &hasInstanceSymbolFunction);
595     m_arrayProtoToStringFunction.initLater(
596         [] (const Initializer<JSFunction>& init) {
597             init.set(JSFunction::create(init.vm, init.owner, 0, init.vm.propertyNames->toString.string(), arrayProtoFuncToString, NoIntrinsic));
598         });
599     m_arrayProtoValuesFunction.initLater(
600         [] (const Initializer<JSFunction>& init) {
601             init.set(JSFunction::create(init.vm, init.owner, 0, init.vm.propertyNames->builtinNames().valuesPublicName().string(), arrayProtoFuncValues, ArrayValuesIntrinsic));
602         });
603
604     m_iteratorProtocolFunction.initLater(
605         [] (const Initializer<JSFunction>& init) {
606             init.set(JSFunction::create(init.vm, iteratorHelpersPerformIterationCodeGenerator(init.vm), init.owner));
607         });
608
609     m_promiseResolveFunction.initLater(
610         [] (const Initializer<JSFunction>& init) {
611             init.set(JSFunction::create(init.vm, promiseConstructorResolveCodeGenerator(init.vm), init.owner));
612         });
613
614     m_numberProtoToStringFunction.initLater(
615         [] (const Initializer<JSFunction>& init) {
616             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, init.vm.propertyNames->toString.string(), numberProtoFuncToString, NumberPrototypeToStringIntrinsic));
617         });
618
619     m_functionProtoHasInstanceSymbolFunction.set(vm, this, hasInstanceSymbolFunction);
620     m_throwTypeErrorGetterSetter.initLater(
621         [] (const Initializer<GetterSetter>& init) {
622             JSFunction* thrower = init.owner->throwTypeErrorFunction();
623             GetterSetter* getterSetter = GetterSetter::create(init.vm, init.owner, thrower, thrower);
624             init.set(getterSetter);
625         });
626
627     m_nullGetterFunction.set(vm, this, NullGetterFunction::create(vm, NullGetterFunction::createStructure(vm, this, m_functionPrototype.get())));
628     m_nullSetterFunction.set(vm, this, NullSetterFunction::create(vm, NullSetterFunction::createStructure(vm, this, m_functionPrototype.get())));
629     m_objectPrototype.set(vm, this, ObjectPrototype::create(vm, this, ObjectPrototype::createStructure(vm, this, jsNull())));
630     // We have to manually set this here because we make it a prototype without transition below.
631     m_objectPrototype.get()->didBecomePrototype();
632     GetterSetter* protoAccessor = GetterSetter::create(vm, this,
633         JSFunction::create(vm, this, 0, makeString("get ", vm.propertyNames->underscoreProto.string()), globalFuncProtoGetter, UnderscoreProtoIntrinsic),
634         JSFunction::create(vm, this, 0, makeString("set ", vm.propertyNames->underscoreProto.string()), globalFuncProtoSetter));
635     m_objectPrototype->putDirectNonIndexAccessorWithoutTransition(vm, vm.propertyNames->underscoreProto, protoAccessor, PropertyAttribute::Accessor | PropertyAttribute::DontEnum);
636     m_functionPrototype->structure(vm)->setPrototypeWithoutTransition(vm, m_objectPrototype.get());
637     m_objectStructureForObjectConstructor.set(vm, this, vm.structureCache.emptyObjectStructureForPrototype(this, m_objectPrototype.get(), JSFinalObject::defaultInlineCapacity()));
638     m_objectProtoValueOfFunction.set(vm, this, jsCast<JSFunction*>(objectPrototype()->getDirect(vm, vm.propertyNames->valueOf)));
639     
640     JSFunction* thrower = JSFunction::create(vm, this, 0, String(), globalFuncThrowTypeErrorArgumentsCalleeAndCaller);
641     GetterSetter* getterSetter = GetterSetter::create(vm, this, thrower, thrower);
642     m_throwTypeErrorArgumentsCalleeAndCallerGetterSetter.set(vm, this, getterSetter);
643     
644     m_functionPrototype->initRestrictedProperties(vm, this);
645
646     m_speciesGetterSetter.set(vm, this, GetterSetter::create(vm, this, JSFunction::create(vm, globalOperationsSpeciesGetterCodeGenerator(vm), this), nullptr));
647
648     m_typedArrayProto.initLater(
649         [] (const Initializer<JSTypedArrayViewPrototype>& init) {
650             init.set(JSTypedArrayViewPrototype::create(init.vm, init.owner, JSTypedArrayViewPrototype::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get())));
651             
652             // Make sure that the constructor gets initialized, too.
653             init.owner->m_typedArraySuperConstructor.get(init.owner);
654         });
655     m_typedArraySuperConstructor.initLater(
656         [] (const Initializer<JSTypedArrayViewConstructor>& init) {
657             JSTypedArrayViewPrototype* prototype = init.owner->m_typedArrayProto.get(init.owner);
658             JSTypedArrayViewConstructor* constructor = JSTypedArrayViewConstructor::create(init.vm, init.owner, JSTypedArrayViewConstructor::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()), prototype, init.owner->m_speciesGetterSetter.get());
659             prototype->putDirectWithoutTransition(init.vm, init.vm.propertyNames->constructor, constructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
660             init.set(constructor);
661         });
662     
663 #define INIT_TYPED_ARRAY_LATER(type) \
664     m_typedArray ## type.initLater( \
665         [] (LazyClassStructure::Initializer& init) { \
666             init.setPrototype(JS ## type ## ArrayPrototype::create(init.vm, init.global, JS ## type ## ArrayPrototype::createStructure(init.vm, init.global, init.global->m_typedArrayProto.get(init.global)))); \
667             init.setStructure(JS ## type ## Array::createStructure(init.vm, init.global, init.prototype)); \
668             init.setConstructor(JS ## type ## ArrayConstructor::create(init.vm, init.global, JS ## type ## ArrayConstructor::createStructure(init.vm, init.global, init.global->m_typedArraySuperConstructor.get(init.global)), init.prototype, #type "Array"_s, typedArrayConstructorAllocate ## type ## ArrayCodeGenerator(init.vm))); \
669             init.global->putDirect(init.vm, init.vm.propertyNames->builtinNames().type ## ArrayPrivateName(), init.constructor, static_cast<unsigned>(PropertyAttribute::DontEnum)); \
670         });
671     FOR_EACH_TYPED_ARRAY_TYPE_EXCLUDING_DATA_VIEW(INIT_TYPED_ARRAY_LATER)
672 #undef INIT_TYPED_ARRAY_LATER
673     
674     m_typedArrayDataView.initLater(
675         [] (LazyClassStructure::Initializer& init) {
676             init.setPrototype(JSDataViewPrototype::create(init.vm, JSDataViewPrototype::createStructure(init.vm, init.global, init.global->m_objectPrototype.get())));
677             init.setStructure(JSDataView::createStructure(init.vm, init.global, init.prototype));
678             init.setConstructor(JSDataViewConstructor::create(init.vm, init.global, JSDataViewConstructor::createStructure(init.vm, init.global, init.global->m_functionPrototype.get()), init.prototype, "DataView"_s, nullptr));
679         });
680     
681     m_lexicalEnvironmentStructure.set(vm, this, JSLexicalEnvironment::createStructure(vm, this));
682     m_moduleEnvironmentStructure.initLater(
683         [] (const Initializer<Structure>& init) {
684             init.set(JSModuleEnvironment::createStructure(init.vm, init.owner));
685         });
686     m_strictEvalActivationStructure.initLater(
687         [] (const Initializer<Structure>& init) {
688             init.set(StrictEvalActivation::createStructure(init.vm, init.owner, jsNull()));
689         });
690     m_debuggerScopeStructure.initLater(
691         [] (const Initializer<Structure>& init) {
692             init.set(DebuggerScope::createStructure(init.vm, init.owner));
693         });
694     m_withScopeStructure.initLater(
695         [] (const Initializer<Structure>& init) {
696             init.set(JSWithScope::createStructure(init.vm, init.owner, jsNull()));
697         });
698     
699     m_nullPrototypeObjectStructure.set(vm, this, JSFinalObject::createStructure(vm, this, jsNull(), JSFinalObject::defaultInlineCapacity()));
700     
701     m_callbackFunctionStructure.initLater(
702         [] (const Initializer<Structure>& init) {
703             init.set(JSCallbackFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
704         });
705     m_directArgumentsStructure.set(vm, this, DirectArguments::createStructure(vm, this, m_objectPrototype.get()));
706     m_scopedArgumentsStructure.set(vm, this, ScopedArguments::createStructure(vm, this, m_objectPrototype.get()));
707     m_clonedArgumentsStructure.set(vm, this, ClonedArguments::createStructure(vm, this, m_objectPrototype.get()));
708     m_callbackConstructorStructure.initLater(
709         [] (const Initializer<Structure>& init) {
710             init.set(JSCallbackConstructor::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
711         });
712     m_callbackObjectStructure.initLater(
713         [] (const Initializer<Structure>& init) {
714             init.set(JSCallbackObject<JSNonFinalObject>::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
715         });
716
717 #if JSC_OBJC_API_ENABLED
718     m_objcCallbackFunctionStructure.initLater(
719         [] (const Initializer<Structure>& init) {
720             init.set(ObjCCallbackFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
721         });
722     m_objcWrapperObjectStructure.initLater(
723         [] (const Initializer<Structure>& init) {
724             init.set(JSCallbackObject<JSAPIWrapperObject>::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
725         });
726 #endif
727 #ifdef JSC_GLIB_API_ENABLED
728     m_glibCallbackFunctionStructure.initLater(
729         [] (const Initializer<Structure>& init) {
730             init.set(JSCCallbackFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
731         });
732     m_glibWrapperObjectStructure.initLater(
733         [] (const Initializer<Structure>& init) {
734             init.set(JSCallbackObject<JSAPIWrapperObject>::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
735         });
736 #endif
737     m_arrayPrototype.set(vm, this, ArrayPrototype::create(vm, this, ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
738     
739     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(UndecidedShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithUndecided));
740     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(Int32Shape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithInt32));
741     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(DoubleShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithDouble));
742     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(ContiguousShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithContiguous));
743     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(ArrayStorageShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithArrayStorage));
744     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(SlowPutArrayStorageShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithSlowPutArrayStorage));
745     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(CopyOnWriteArrayWithInt32)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), CopyOnWriteArrayWithInt32));
746     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(CopyOnWriteArrayWithDouble)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), CopyOnWriteArrayWithDouble));
747     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(CopyOnWriteArrayWithContiguous)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), CopyOnWriteArrayWithContiguous));
748     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
749         m_arrayStructureForIndexingShapeDuringAllocation[i] = m_originalArrayStructureForIndexingShape[i];
750
751     m_regExpPrototype.set(vm, this, RegExpPrototype::create(vm, this, RegExpPrototype::createStructure(vm, this, m_objectPrototype.get())));
752     m_regExpStructure.set(vm, this, RegExpObject::createStructure(vm, this, m_regExpPrototype.get()));
753     m_regExpMatchesArrayStructure.set(vm, this, createRegExpMatchesArrayStructure(vm, this));
754
755     m_moduleRecordStructure.initLater(
756         [] (const Initializer<Structure>& init) {
757             init.set(JSModuleRecord::createStructure(init.vm, init.owner, jsNull()));
758         });
759     m_moduleNamespaceObjectStructure.initLater(
760         [] (const Initializer<Structure>& init) {
761             init.set(JSModuleNamespaceObject::createStructure(init.vm, init.owner, jsNull()));
762         });
763     m_proxyObjectStructure.initLater(
764         [] (const Initializer<Structure>& init) {
765             bool isCallable = false;
766             init.set(ProxyObject::createStructure(init.vm, init.owner, jsNull(), isCallable));
767         });
768     m_callableProxyObjectStructure.initLater(
769         [] (const Initializer<Structure>& init) {
770             bool isCallable = true;
771             init.set(ProxyObject::createStructure(init.vm, init.owner, jsNull(), isCallable));
772         });
773     m_proxyRevokeStructure.initLater(
774         [] (const Initializer<Structure>& init) {
775             init.set(ProxyRevoke::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
776         });
777
778     m_parseIntFunction.initLater(
779         [] (const Initializer<JSFunction>& init) {
780             init.set(JSFunction::create(init.vm, init.owner, 2, init.vm.propertyNames->parseInt.string(), globalFuncParseInt, ParseIntIntrinsic));
781         });
782     m_parseFloatFunction.initLater(
783         [] (const Initializer<JSFunction>& init) {
784             init.set(JSFunction::create(init.vm, init.owner, 1, init.vm.propertyNames->parseFloat.string(), globalFuncParseFloat, NoIntrinsic));
785         });
786     
787 #if ENABLE(SHARED_ARRAY_BUFFER)
788     m_sharedArrayBufferPrototype.set(vm, this, JSArrayBufferPrototype::create(vm, this, JSArrayBufferPrototype::createStructure(vm, this, m_objectPrototype.get()), ArrayBufferSharingMode::Shared));
789     m_sharedArrayBufferStructure.set(vm, this, JSArrayBuffer::createStructure(vm, this, m_sharedArrayBufferPrototype.get()));
790 #endif
791
792     m_iteratorPrototype.set(vm, this, IteratorPrototype::create(vm, this, IteratorPrototype::createStructure(vm, this, m_objectPrototype.get())));
793     m_asyncIteratorPrototype.set(vm, this, AsyncIteratorPrototype::create(vm, this, AsyncIteratorPrototype::createStructure(vm, this, m_objectPrototype.get())));
794
795     m_generatorPrototype.set(vm, this, GeneratorPrototype::create(vm, this, GeneratorPrototype::createStructure(vm, this, m_iteratorPrototype.get())));
796     m_asyncGeneratorPrototype.set(vm, this, AsyncGeneratorPrototype::create(vm, this, AsyncGeneratorPrototype::createStructure(vm, this, m_asyncIteratorPrototype.get())));
797
798     auto* arrayIteratorPrototype = ArrayIteratorPrototype::create(vm, this, ArrayIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
799     m_arrayIteratorPrototype.set(vm, this, arrayIteratorPrototype);
800     m_arrayIteratorStructure.set(vm, this, JSArrayIterator::createStructure(vm, this, arrayIteratorPrototype));
801
802     auto* mapIteratorPrototype = MapIteratorPrototype::create(vm, this, MapIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
803     m_mapIteratorPrototype.set(vm, this, mapIteratorPrototype);
804     m_mapIteratorStructure.set(vm, this, JSMapIterator::createStructure(vm, this, mapIteratorPrototype));
805
806     auto* setIteratorPrototype = SetIteratorPrototype::create(vm, this, SetIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
807     m_setIteratorPrototype.set(vm, this, setIteratorPrototype);
808     m_setIteratorStructure.set(vm, this, JSSetIterator::createStructure(vm, this, setIteratorPrototype));
809
810     JSFunction* defaultPromiseThen = JSFunction::create(vm, promisePrototypeThenCodeGenerator(vm), this);
811     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::defaultPromiseThen)].set(vm, this, defaultPromiseThen);
812
813 #define CREATE_PROTOTYPE_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) { \
814         m_ ## lowerName ## Prototype.set(vm, this, capitalName##Prototype::create(vm, this, capitalName##Prototype::createStructure(vm, this, m_ ## prototypeBase ## Prototype.get()))); \
815         m_ ## properName ## Structure.set(vm, this, instanceType::createStructure(vm, this, m_ ## lowerName ## Prototype.get())); \
816     }
817     
818     FOR_EACH_SIMPLE_BUILTIN_TYPE(CREATE_PROTOTYPE_FOR_SIMPLE_TYPE)
819     FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(CREATE_PROTOTYPE_FOR_SIMPLE_TYPE)
820     
821 #undef CREATE_PROTOTYPE_FOR_SIMPLE_TYPE
822
823 #define CREATE_PROTOTYPE_FOR_LAZY_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) {  \
824     m_ ## properName ## Structure.initLater(\
825         [] (LazyClassStructure::Initializer& init) { \
826             init.setPrototype(capitalName##Prototype::create(init.vm, init.global, capitalName##Prototype::createStructure(init.vm, init.global, init.global->m_ ## prototypeBase ## Prototype.get()))); \
827             init.setStructure(instanceType::createStructure(init.vm, init.global, init.prototype)); \
828             init.setConstructor(capitalName ## Constructor::create(init.vm, capitalName ## Constructor::createStructure(init.vm, init.global, init.global->m_functionPrototype.get()), jsCast<capitalName ## Prototype*>(init.prototype), init.global->m_speciesGetterSetter.get())); \
829         }); \
830     }
831     
832     FOR_EACH_LAZY_BUILTIN_TYPE(CREATE_PROTOTYPE_FOR_LAZY_TYPE)
833     
834     // Constructors
835
836     ObjectConstructor* objectConstructor = ObjectConstructor::create(vm, this, ObjectConstructor::createStructure(vm, this, m_functionPrototype.get()), m_objectPrototype.get());
837     m_objectConstructor.set(vm, this, objectConstructor);
838     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Object)].set(vm, this, objectConstructor);
839
840     JSFunction* throwTypeErrorFunction = JSFunction::create(vm, this, 0, String(), globalFuncThrowTypeError);
841     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::throwTypeErrorFunction)].set(vm, this, throwTypeErrorFunction);
842
843     FunctionConstructor* functionConstructor = FunctionConstructor::create(vm, FunctionConstructor::createStructure(vm, this, m_functionPrototype.get()), m_functionPrototype.get());
844     m_functionConstructor.set(vm, this, functionConstructor);
845
846     ArrayConstructor* arrayConstructor = ArrayConstructor::create(vm, this, ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_arrayPrototype.get(), m_speciesGetterSetter.get());
847     m_arrayConstructor.set(vm, this, arrayConstructor);
848     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Array)].set(vm, this, arrayConstructor);
849     
850     RegExpConstructor* regExpConstructor = RegExpConstructor::create(vm, RegExpConstructor::createStructure(vm, this, m_functionPrototype.get()), m_regExpPrototype.get(), m_speciesGetterSetter.get());
851     m_regExpConstructor.set(vm, this, regExpConstructor);
852     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::RegExp)].set(vm, this, regExpConstructor);
853     m_regExpGlobalData.cachedResult().record(vm, this, nullptr, jsEmptyString(vm), MatchResult(0, 0));
854     
855 #if ENABLE(SHARED_ARRAY_BUFFER)
856     JSSharedArrayBufferConstructor* sharedArrayBufferConstructor = nullptr;
857     sharedArrayBufferConstructor = JSSharedArrayBufferConstructor::create(vm, JSSharedArrayBufferConstructor::createStructure(vm, this, m_functionPrototype.get()), m_sharedArrayBufferPrototype.get(), m_speciesGetterSetter.get());
858     m_sharedArrayBufferPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, sharedArrayBufferConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
859
860     AtomicsObject* atomicsObject = AtomicsObject::create(vm, this, AtomicsObject::createStructure(vm, this, m_objectPrototype.get()));
861 #endif
862
863 #define CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
864 capitalName ## Constructor* lowerName ## Constructor = featureFlag ? capitalName ## Constructor::create(vm, capitalName ## Constructor::createStructure(vm, this, m_functionPrototype.get()), m_ ## lowerName ## Prototype.get(), m_speciesGetterSetter.get()) : nullptr; \
865     if (featureFlag) \
866         m_ ## lowerName ## Prototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, lowerName ## Constructor, static_cast<unsigned>(PropertyAttribute::DontEnum)); \
867
868     FOR_EACH_SIMPLE_BUILTIN_TYPE(CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE)
869     
870 #undef CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE
871
872     m_promiseConstructor.set(vm, this, promiseConstructor);
873     m_internalPromiseConstructor.set(vm, this, internalPromiseConstructor);
874     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Promise)].set(vm, this, promiseConstructor);
875     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::InternalPromise)].set(vm, this, internalPromiseConstructor);
876     
877     m_evalErrorStructure.initLater(
878         [] (LazyClassStructure::Initializer& init) {
879             init.global->initializeErrorConstructor<ErrorType::EvalError>(init);
880         });
881     m_rangeErrorStructure.initLater(
882         [] (LazyClassStructure::Initializer& init) {
883             init.global->initializeErrorConstructor<ErrorType::RangeError>(init);
884         });
885     m_referenceErrorStructure.initLater(
886         [] (LazyClassStructure::Initializer& init) {
887             init.global->initializeErrorConstructor<ErrorType::ReferenceError>(init);
888         });
889     m_syntaxErrorStructure.initLater(
890         [] (LazyClassStructure::Initializer& init) {
891             init.global->initializeErrorConstructor<ErrorType::SyntaxError>(init);
892         });
893     m_typeErrorStructure.initLater(
894         [] (LazyClassStructure::Initializer& init) {
895             init.global->initializeErrorConstructor<ErrorType::TypeError>(init);
896         });
897     m_URIErrorStructure.initLater(
898         [] (LazyClassStructure::Initializer& init) {
899             init.global->initializeErrorConstructor<ErrorType::URIError>(init);
900         });
901     m_aggregateErrorStructure.initLater(
902         [] (LazyClassStructure::Initializer& init) {
903             init.global->initializeAggregateErrorConstructor(init);
904         });
905
906     m_generatorFunctionPrototype.set(vm, this, GeneratorFunctionPrototype::create(vm, GeneratorFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
907     GeneratorFunctionConstructor* generatorFunctionConstructor = GeneratorFunctionConstructor::create(vm, GeneratorFunctionConstructor::createStructure(vm, this, functionConstructor), m_generatorFunctionPrototype.get());
908     m_generatorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, generatorFunctionConstructor, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
909     m_generatorFunctionStructure.set(vm, this, JSGeneratorFunction::createStructure(vm, this, m_generatorFunctionPrototype.get()));
910
911     m_generatorPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, m_generatorFunctionPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
912     m_generatorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->prototype, m_generatorPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
913     m_generatorStructure.set(vm, this, JSGenerator::createStructure(vm, this, m_generatorPrototype.get()));
914
915     m_asyncFunctionPrototype.set(vm, this, AsyncFunctionPrototype::create(vm, AsyncFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
916     AsyncFunctionConstructor* asyncFunctionConstructor = AsyncFunctionConstructor::create(vm, AsyncFunctionConstructor::createStructure(vm, this, functionConstructor), m_asyncFunctionPrototype.get());
917     m_asyncFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, asyncFunctionConstructor, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
918     m_asyncFunctionStructure.set(vm, this, JSAsyncFunction::createStructure(vm, this, m_asyncFunctionPrototype.get()));
919
920     m_asyncGeneratorFunctionPrototype.set(vm, this, AsyncGeneratorFunctionPrototype::create(vm, AsyncGeneratorFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
921     AsyncGeneratorFunctionConstructor* asyncGeneratorFunctionConstructor = AsyncGeneratorFunctionConstructor::create(vm, AsyncGeneratorFunctionConstructor::createStructure(vm, this, functionConstructor), m_asyncGeneratorFunctionPrototype.get());
922     m_asyncGeneratorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, asyncGeneratorFunctionConstructor, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
923     m_asyncGeneratorFunctionStructure.set(vm, this, JSAsyncGeneratorFunction::createStructure(vm, this, m_asyncGeneratorFunctionPrototype.get()));
924
925     m_asyncGeneratorPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, m_asyncGeneratorFunctionPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
926     m_asyncGeneratorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->prototype, m_asyncGeneratorPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
927     m_asyncGeneratorStructure.set(vm, this, JSAsyncGenerator::createStructure(vm, this, m_asyncGeneratorPrototype.get()));
928     
929     m_objectPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, objectConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
930     m_functionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, functionConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
931     m_arrayPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, arrayConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
932     m_regExpPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, regExpConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
933     
934     putDirectWithoutTransition(vm, vm.propertyNames->Object, objectConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
935     putDirectWithoutTransition(vm, vm.propertyNames->Function, functionConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
936     putDirectWithoutTransition(vm, vm.propertyNames->Array, arrayConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
937     putDirectWithoutTransition(vm, vm.propertyNames->RegExp, regExpConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
938
939 #if ENABLE(SHARED_ARRAY_BUFFER)
940     putDirectWithoutTransition(vm, vm.propertyNames->SharedArrayBuffer, sharedArrayBufferConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
941     putDirectWithoutTransition(vm, Identifier::fromString(vm, "Atomics"), atomicsObject, static_cast<unsigned>(PropertyAttribute::DontEnum));
942 #endif
943
944 #define PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
945     if (featureFlag) \
946         putDirectWithoutTransition(vm, vm.propertyNames-> jsName, lowerName ## Constructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
947
948
949     FOR_EACH_SIMPLE_BUILTIN_TYPE_WITH_CONSTRUCTOR(PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE)
950
951 #undef PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE
952     m_iteratorResultObjectStructure.initLater(
953         [] (const Initializer<Structure>& init) {
954             init.set(createIteratorResultObjectStructure(init.vm, *init.owner));
955         });
956     
957     m_evalFunction.initLater(
958         [] (const Initializer<JSFunction>& init) {
959             init.set(JSFunction::create(init.vm, init.owner, 1, init.vm.propertyNames->eval.string(), globalFuncEval, NoIntrinsic));
960         });
961
962     m_collatorStructure.initLater(
963         [] (const Initializer<Structure>& init) {
964             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
965             IntlCollatorPrototype* collatorPrototype = IntlCollatorPrototype::create(init.vm, globalObject, IntlCollatorPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
966             init.set(IntlCollator::createStructure(init.vm, globalObject, collatorPrototype));
967         });
968     m_dateTimeFormatStructure.initLater(
969         [] (const Initializer<Structure>& init) {
970             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
971             IntlDateTimeFormatPrototype* dateTimeFormatPrototype = IntlDateTimeFormatPrototype::create(init.vm, globalObject, IntlDateTimeFormatPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
972             init.set(IntlDateTimeFormat::createStructure(init.vm, globalObject, dateTimeFormatPrototype));
973         });
974     m_localeStructure.initLater(
975         [] (const Initializer<Structure>& init) {
976             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
977             IntlLocalePrototype* localePrototype = IntlLocalePrototype::create(init.vm, IntlLocalePrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
978             init.set(IntlLocale::createStructure(init.vm, globalObject, localePrototype));
979         });
980     m_numberFormatStructure.initLater(
981         [] (const Initializer<Structure>& init) {
982             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
983             IntlNumberFormatPrototype* numberFormatPrototype = IntlNumberFormatPrototype::create(init.vm, globalObject, IntlNumberFormatPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
984             init.set(IntlNumberFormat::createStructure(init.vm, globalObject, numberFormatPrototype));
985         });
986     m_pluralRulesStructure.initLater(
987         [] (const Initializer<Structure>& init) {
988             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
989             IntlPluralRulesPrototype* pluralRulesPrototype = IntlPluralRulesPrototype::create(init.vm, globalObject, IntlPluralRulesPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
990             init.set(IntlPluralRules::createStructure(init.vm, globalObject, pluralRulesPrototype));
991         });
992     m_relativeTimeFormatStructure.initLater(
993         [] (const Initializer<Structure>& init) {
994             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
995             IntlRelativeTimeFormatPrototype* relativeTimeFormatPrototype = IntlRelativeTimeFormatPrototype::create(init.vm, IntlRelativeTimeFormatPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
996             init.set(IntlRelativeTimeFormat::createStructure(init.vm, globalObject, relativeTimeFormatPrototype));
997         });
998     m_defaultCollator.initLater(
999         [] (const Initializer<IntlCollator>& init) {
1000             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
1001             VM& vm = init.vm;
1002             auto scope = DECLARE_CATCH_SCOPE(vm);
1003             IntlCollator* collator = IntlCollator::create(vm, globalObject->collatorStructure());
1004             collator->initializeCollator(globalObject, jsUndefined(), jsUndefined());
1005             scope.releaseAssertNoException();
1006             init.set(collator);
1007         });
1008
1009     IntlObject* intl = IntlObject::create(vm, this, IntlObject::createStructure(vm, this, m_objectPrototype.get()));
1010     putDirectWithoutTransition(vm, vm.propertyNames->Intl, intl, static_cast<unsigned>(PropertyAttribute::DontEnum));
1011
1012     m_moduleLoader.initLater(
1013         [] (const Initializer<JSModuleLoader>& init) {
1014             auto catchScope = DECLARE_CATCH_SCOPE(init.vm);
1015             init.set(JSModuleLoader::create(init.owner, init.vm, JSModuleLoader::createStructure(init.vm, init.owner, jsNull())));
1016             catchScope.releaseAssertNoException();
1017         });
1018     if (Options::exposeInternalModuleLoader())
1019         putDirectWithoutTransition(vm, vm.propertyNames->Loader, moduleLoader(), static_cast<unsigned>(PropertyAttribute::DontEnum));
1020
1021     GetterSetter* regExpProtoFlagsGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->flags);
1022     catchScope.assertNoException();
1023     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoFlagsGetter)].set(vm, this, regExpProtoFlagsGetter);
1024     GetterSetter* regExpProtoGlobalGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->global);
1025     catchScope.assertNoException();
1026     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoGlobalGetter)].set(vm, this, regExpProtoGlobalGetter);
1027     GetterSetter* regExpProtoIgnoreCaseGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->ignoreCase);
1028     catchScope.assertNoException();
1029     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoIgnoreCaseGetter)].set(vm, this, regExpProtoIgnoreCaseGetter);
1030     GetterSetter* regExpProtoMultilineGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->multiline);
1031     catchScope.assertNoException();
1032     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoMultilineGetter)].set(vm, this, regExpProtoMultilineGetter);
1033     GetterSetter* regExpProtoSourceGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->source);
1034     catchScope.assertNoException();
1035     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoSourceGetter)].set(vm, this, regExpProtoSourceGetter);
1036     GetterSetter* regExpProtoStickyGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->sticky);
1037     catchScope.assertNoException();
1038     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoStickyGetter)].set(vm, this, regExpProtoStickyGetter);
1039     GetterSetter* regExpProtoUnicodeGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->unicode);
1040     catchScope.assertNoException();
1041     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoUnicodeGetter)].set(vm, this, regExpProtoUnicodeGetter);
1042     JSFunction* regExpSymbolReplace = jsCast<JSFunction*>(m_regExpPrototype->getDirect(vm, vm.propertyNames->replaceSymbol));
1043     m_regExpProtoSymbolReplace.set(vm, this, regExpSymbolReplace);
1044     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpBuiltinExec)].set(vm, this, jsCast<JSFunction*>(m_regExpPrototype->getDirect(vm, vm.propertyNames->exec)));
1045     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpPrototypeSymbolMatch)].set(vm, this, m_regExpPrototype->getDirect(vm, vm.propertyNames->matchSymbol).asCell());
1046     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpPrototypeSymbolReplace)].set(vm, this, m_regExpPrototype->getDirect(vm, vm.propertyNames->replaceSymbol).asCell());
1047
1048     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isArray)].set(vm, this, arrayConstructor->getDirect(vm, vm.propertyNames->isArray).asCell());
1049     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::callFunction)].set(vm, this, callFunction);
1050     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::applyFunction)].set(vm, this, applyFunction);
1051
1052 #define INIT_PRIVATE_GLOBAL(funcName, code) \
1053     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::funcName)].initLater([] (const Initializer<JSCell>& init) { \
1054             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner); \
1055             init.set(JSFunction::create(init.vm, code ## CodeGenerator(init.vm), globalObject)); \
1056         });
1057     JSC_FOREACH_BUILTIN_FUNCTION_PRIVATE_GLOBAL_NAME(INIT_PRIVATE_GLOBAL)
1058 #undef INIT_PRIVATE_GLOBAL
1059
1060     // FIXME: Initializing them lazily.
1061     // https://bugs.webkit.org/show_bug.cgi?id=203795
1062     JSObject* asyncFromSyncIteratorPrototype = AsyncFromSyncIteratorPrototype::create(vm, this, AsyncFromSyncIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
1063     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::AsyncFromSyncIterator))->putDirect(vm, vm.propertyNames->prototype, asyncFromSyncIteratorPrototype);
1064
1065     JSObject* regExpStringIteratorPrototype = RegExpStringIteratorPrototype::create(vm, this, RegExpStringIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
1066     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::RegExpStringIterator))->putDirect(vm, vm.propertyNames->prototype, regExpStringIteratorPrototype);
1067
1068     // Map and Set helpers.
1069     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Set)].initLater([] (const Initializer<JSCell>& init) {
1070             init.set(jsCast<JSGlobalObject*>(init.owner)->setConstructor());
1071         });
1072     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketHead)].initLater([] (const Initializer<JSCell>& init) {
1073             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketHead, JSMapBucketHeadIntrinsic));
1074         });
1075     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketNext)].initLater([] (const Initializer<JSCell>& init) {
1076             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketNext, JSMapBucketNextIntrinsic));
1077         });
1078     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketKey)].initLater([] (const Initializer<JSCell>& init) {
1079             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketKey, JSMapBucketKeyIntrinsic));
1080         });
1081     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketValue)].initLater([] (const Initializer<JSCell>& init) {
1082             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketValue, JSMapBucketValueIntrinsic));
1083         });
1084     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::setBucketHead)].initLater([] (const Initializer<JSCell>& init) {
1085             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), setPrivateFuncSetBucketHead, JSSetBucketHeadIntrinsic));
1086         });
1087     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::setBucketNext)].initLater([] (const Initializer<JSCell>& init) {
1088             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), setPrivateFuncSetBucketNext, JSSetBucketNextIntrinsic));
1089         });
1090     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::setBucketKey)].initLater([] (const Initializer<JSCell>& init) {
1091             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), setPrivateFuncSetBucketKey, JSSetBucketKeyIntrinsic));
1092         });
1093
1094     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::importModule)].initLater([] (const Initializer<JSCell>& init) {
1095             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncImportModule));
1096         });
1097     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::propertyIsEnumerable)].initLater([] (const Initializer<JSCell>& init) {
1098             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncPropertyIsEnumerable));
1099         });
1100     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::ownKeys)].initLater([] (const Initializer<JSCell>& init) {
1101             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncOwnKeys));
1102         });
1103     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::enqueueJob)].initLater([] (const Initializer<JSCell>& init) {
1104             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, "enqueueJob"_s, enqueueJob));
1105         });
1106     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::makeTypeError)].initLater([] (const Initializer<JSCell>& init) {
1107             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncMakeTypeError));
1108         });
1109     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::AggregateError)].initLater([] (const Initializer<JSCell>& init) {
1110             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
1111             init.set(globalObject->m_aggregateErrorStructure.constructor(globalObject));
1112         });
1113     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArrayLength)].initLater([] (const Initializer<JSCell>& init) {
1114             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncLength));
1115         });
1116     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArrayGetOriginalConstructor)].initLater([] (const Initializer<JSCell>& init) {
1117             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncGetOriginalConstructor));
1118         });
1119     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArraySort)].initLater([] (const Initializer<JSCell>& init) {
1120             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncSort));
1121         });
1122     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isTypedArrayView)].initLater([] (const Initializer<JSCell>& init) {
1123             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncIsTypedArrayView, IsTypedArrayViewIntrinsic));
1124         });
1125     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArraySubarrayCreate)].initLater([] (const Initializer<JSCell>& init) {
1126             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncSubarrayCreate));
1127         });
1128     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isBoundFunction)].initLater([] (const Initializer<JSCell>& init) {
1129             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), isBoundFunction));
1130         });
1131     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::hasInstanceBoundFunction)].initLater([] (const Initializer<JSCell>& init) {
1132             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), hasInstanceBoundFunction));
1133         });
1134     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::instanceOf)].initLater([] (const Initializer<JSCell>& init) {
1135             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), objectPrivateFuncInstanceOf));
1136         });
1137     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::BuiltinLog)].initLater([] (const Initializer<JSCell>& init) {
1138             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), globalFuncBuiltinLog));
1139         });
1140     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::BuiltinDescribe)].initLater([] (const Initializer<JSCell>& init) {
1141             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), globalFuncBuiltinDescribe));
1142         });
1143     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::trunc)].initLater([] (const Initializer<JSCell>& init) {
1144             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mathProtoFuncTrunc, TruncIntrinsic));
1145         });
1146     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::repeatCharacter)].initLater([] (const Initializer<JSCell>& init) {
1147             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), stringProtoFuncRepeatCharacter));
1148         });
1149     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::arraySpeciesCreate)].initLater([] (const Initializer<JSCell>& init) {
1150             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), arrayProtoFuncSpeciesCreate));
1151         });
1152     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isArraySlow)].initLater([] (const Initializer<JSCell>& init) {
1153             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), arrayConstructorPrivateFuncIsArraySlow));
1154         });
1155     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::concatMemcpy)].initLater([] (const Initializer<JSCell>& init) {
1156             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), arrayProtoPrivateFuncConcatMemcpy));
1157         });
1158     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::appendMemcpy)].initLater([] (const Initializer<JSCell>& init) {
1159             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), arrayProtoPrivateFuncAppendMemcpy));
1160         });
1161     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::hostPromiseRejectionTracker)].initLater([] (const Initializer<JSCell>& init) {
1162             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), globalFuncHostPromiseRejectionTracker));
1163         });
1164     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::InspectorInstrumentation)].initLater([] (const Initializer<JSCell>& init) {
1165             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
1166             init.set(InspectorInstrumentationObject::create(init.vm, globalObject, InspectorInstrumentationObject::createStructure(init.vm, globalObject, globalObject->m_objectPrototype.get())));
1167         });
1168     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::thisTimeValue)].initLater([] (const Initializer<JSCell>& init) {
1169             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), dateProtoFuncGetTime, DatePrototypeGetTimeIntrinsic));
1170         });
1171     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::sameValue)].initLater([] (const Initializer<JSCell>& init) {
1172             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), objectConstructorIs, ObjectIsIntrinsic));
1173         });
1174
1175     // RegExp.prototype helpers.
1176     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpCreate)].initLater([] (const Initializer<JSCell>& init) {
1177             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), esSpecRegExpCreate, NoIntrinsic));
1178         });
1179     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isRegExp)].initLater([] (const Initializer<JSCell>& init) {
1180             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), esSpecIsRegExp, NoIntrinsic));
1181         });
1182     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpMatchFast)].initLater([] (const Initializer<JSCell>& init) {
1183             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), regExpProtoFuncMatchFast, RegExpMatchFastIntrinsic));
1184         });
1185     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpSearchFast)].initLater([] (const Initializer<JSCell>& init) {
1186             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), regExpProtoFuncSearchFast));
1187         });
1188     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpSplitFast)].initLater([] (const Initializer<JSCell>& init) {
1189             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), regExpProtoFuncSplitFast));
1190         });
1191     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpTestFast)].initLater([] (const Initializer<JSCell>& init) {
1192             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), regExpProtoFuncTestFast, RegExpTestFastIntrinsic));
1193         });
1194
1195     // String.prototype helpers.
1196     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringIncludesInternal)].initLater([] (const Initializer<JSCell>& init) {
1197             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), builtinStringIncludesInternal));
1198         });
1199     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringIndexOfInternal)].initLater([] (const Initializer<JSCell>& init) {
1200             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), builtinStringIndexOfInternal));
1201         });
1202     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringSplitFast)].initLater([] (const Initializer<JSCell>& init) {
1203             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), stringProtoFuncSplitFast));
1204         });
1205     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringSubstringInternal)].initLater([] (const Initializer<JSCell>& init) {
1206             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), builtinStringSubstringInternal));
1207         });
1208
1209     // Function prototype helpers.
1210     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::makeBoundFunction)].initLater([] (const Initializer<JSCell>& init) {
1211             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 5, String(), makeBoundFunction));
1212         });
1213     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::hasOwnLengthProperty)].initLater([] (const Initializer<JSCell>& init) {
1214             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), hasOwnLengthProperty));
1215         });
1216
1217     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::dateTimeFormat)].initLater([] (const Initializer<JSCell>& init) {
1218             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncDateTimeFormat));
1219         });
1220
1221 #if ENABLE(WEBASSEMBLY) && ENABLE(WEBASSEMBLY_STREAMING_API)
1222     // WebAssembly Streaming API
1223     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::webAssemblyCompileStreamingInternal)].initLater([] (const Initializer<JSCell>& init) {
1224             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), webAssemblyCompileStreamingInternal));
1225         });
1226     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::webAssemblyInstantiateStreamingInternal)].initLater([] (const Initializer<JSCell>& init) {
1227             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), webAssemblyInstantiateStreamingInternal));
1228         });
1229 #endif
1230
1231     if (Options::exposeProfilersOnGlobalObject()) {
1232 #if ENABLE(SAMPLING_PROFILER)
1233         putDirectWithoutTransition(vm, Identifier::fromString(vm, "__enableSamplingProfiler"), JSFunction::create(vm, this, 1, String(), enableSamplingProfiler), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
1234         putDirectWithoutTransition(vm, Identifier::fromString(vm, "__disableSamplingProfiler"), JSFunction::create(vm, this, 1, String(), disableSamplingProfiler), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
1235 #endif
1236         putDirectWithoutTransition(vm, Identifier::fromString(vm, "__enableSuperSampler"), JSFunction::create(vm, this, 1, String(), enableSuperSampler), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
1237         putDirectWithoutTransition(vm, Identifier::fromString(vm, "__disableSuperSampler"), JSFunction::create(vm, this, 1, String(), disableSuperSampler), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
1238     }
1239
1240     GlobalPropertyInfo staticGlobals[] = {
1241         GlobalPropertyInfo(vm.propertyNames->NaN, jsNaN(), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1242         GlobalPropertyInfo(vm.propertyNames->Infinity, jsNumber(std::numeric_limits<double>::infinity()), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1243         GlobalPropertyInfo(vm.propertyNames->undefinedKeyword, jsUndefined(), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1244 #if ASSERT_ENABLED
1245         GlobalPropertyInfo(vm.propertyNames->builtinNames().assertPrivateName(), JSFunction::create(vm, this, 1, String(), assertCall), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1246 #endif
1247     };
1248     addStaticGlobals(staticGlobals, WTF_ARRAY_LENGTH(staticGlobals));
1249     
1250     if (UNLIKELY(Options::useDollarVM()))
1251         exposeDollarVM(vm);
1252
1253 #if ENABLE(WEBASSEMBLY)
1254     if (Wasm::isSupported()) {
1255         m_webAssemblyModuleRecordStructure.initLater(
1256             [] (const Initializer<Structure>& init) {
1257                 init.set(WebAssemblyModuleRecord::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
1258             });
1259         m_webAssemblyFunctionStructure.initLater(
1260             [] (const Initializer<Structure>& init) {
1261                 init.set(WebAssemblyFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
1262             });
1263         m_jsToWasmICCalleeStructure.initLater(
1264             [] (const Initializer<Structure>& init) {
1265                 init.set(JSToWasmICCallee::createStructure(init.vm, init.owner, jsNull()));
1266             });
1267         m_webAssemblyWrapperFunctionStructure.initLater(
1268             [] (const Initializer<Structure>& init) {
1269                 init.set(WebAssemblyWrapperFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
1270             });
1271         auto* webAssembly = JSWebAssembly::create(vm, this, JSWebAssembly::createStructure(vm, this, m_objectPrototype.get()));
1272         putDirectWithoutTransition(vm, Identifier::fromString(vm, "WebAssembly"), webAssembly, static_cast<unsigned>(PropertyAttribute::DontEnum));
1273
1274 #define CREATE_WEBASSEMBLY_PROTOTYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
1275     if (featureFlag) {\
1276         m_ ## properName ## Structure.initLater(\
1277             [] (LazyClassStructure::Initializer& init) { \
1278                 init.setPrototype(capitalName##Prototype::create(init.vm, init.global, capitalName##Prototype::createStructure(init.vm, init.global, init.global->prototypeBase ## Prototype()))); \
1279                 init.setStructure(instanceType::createStructure(init.vm, init.global, init.prototype)); \
1280                 auto* constructorPrototype = strcmp(#prototypeBase, "error") == 0 ? init.global->m_errorStructure.constructor(init.global) : init.global->functionPrototype(); \
1281                 init.setConstructor(capitalName ## Constructor::create(init.vm, capitalName ## Constructor::createStructure(init.vm, init.global, constructorPrototype), jsCast<capitalName ## Prototype*>(init.prototype))); \
1282             }); \
1283     }
1284
1285         FOR_EACH_WEBASSEMBLY_CONSTRUCTOR_TYPE(CREATE_WEBASSEMBLY_PROTOTYPE)
1286
1287 #undef CREATE_WEBASSEMBLY_CONSTRUCTOR
1288     }
1289 #endif // ENABLE(WEBASSEMBLY)
1290
1291 #undef CREATE_PROTOTYPE_FOR_LAZY_TYPE
1292
1293
1294     {
1295         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, arrayIteratorPrototype, vm.propertyNames->next);
1296         m_arrayIteratorPrototypeNext = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_arrayIteratorProtocolWatchpointSet);
1297         m_arrayIteratorPrototypeNext->install(vm);
1298     }
1299     {
1300         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, this->arrayPrototype(), vm.propertyNames->iteratorSymbol);
1301         m_arrayPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_arrayIteratorProtocolWatchpointSet);
1302         m_arrayPrototypeSymbolIteratorWatchpoint->install(vm);
1303     }
1304     {
1305         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, this->arrayPrototype(), vm.propertyNames->join);
1306         m_arrayPrototypeJoinWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_arrayJoinWatchpointSet);
1307         m_arrayPrototypeJoinWatchpoint->install(vm);
1308     }
1309
1310     {
1311         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, mapIteratorPrototype, vm.propertyNames->next);
1312         m_mapIteratorPrototypeNextWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_mapIteratorProtocolWatchpointSet);
1313         m_mapIteratorPrototypeNextWatchpoint->install(vm);
1314     }
1315     {
1316         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, setIteratorPrototype, vm.propertyNames->next);
1317         m_setIteratorPrototypeNextWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_setIteratorProtocolWatchpointSet);
1318         m_setIteratorPrototypeNextWatchpoint->install(vm);
1319     }
1320     {
1321         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, m_stringIteratorPrototype.get(), vm.propertyNames->next);
1322         m_stringIteratorPrototypeNextWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_stringIteratorProtocolWatchpointSet);
1323         m_stringIteratorPrototypeNextWatchpoint->install(vm);
1324     }
1325     {
1326         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, m_stringPrototype.get(), vm.propertyNames->iteratorSymbol);
1327         m_stringPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_stringIteratorProtocolWatchpointSet);
1328         m_stringPrototypeSymbolIteratorWatchpoint->install(vm);
1329     }
1330
1331     // Unfortunately, the prototype objects of the builtin objects can be touched from concurrent compilers. So eagerly initialize them only if we use JIT.
1332     if (VM::canUseJIT()) {
1333         this->booleanPrototype();
1334         this->numberPrototype();
1335         this->symbolPrototype();
1336     }
1337
1338     fixupPrototypeChainWithObjectPrototype(vm);
1339 }
1340
1341 bool JSGlobalObject::put(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
1342 {
1343     VM& vm = globalObject->vm();
1344     auto scope = DECLARE_THROW_SCOPE(vm);
1345     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(cell);
1346     ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(thisObject));
1347
1348     if (UNLIKELY(isThisValueAltered(slot, thisObject)))
1349         RELEASE_AND_RETURN(scope, ordinarySetSlow(globalObject, thisObject, propertyName, value, slot.thisValue(), slot.isStrictMode()));
1350
1351     bool shouldThrowReadOnlyError = slot.isStrictMode();
1352     bool ignoreReadOnlyErrors = false;
1353     bool putResult = false;
1354     bool done = symbolTablePutTouchWatchpointSet(thisObject, globalObject, propertyName, value, shouldThrowReadOnlyError, ignoreReadOnlyErrors, putResult);
1355     EXCEPTION_ASSERT((!!scope.exception() == (done && !putResult)) || !shouldThrowReadOnlyError);
1356     if (done)
1357         return putResult;
1358     RELEASE_AND_RETURN(scope, Base::put(thisObject, globalObject, propertyName, value, slot));
1359 }
1360
1361 bool JSGlobalObject::defineOwnProperty(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, const PropertyDescriptor& descriptor, bool shouldThrow)
1362 {
1363     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(object);
1364     PropertySlot slot(thisObject, PropertySlot::InternalMethodType::VMInquiry);
1365     // silently ignore attempts to add accessors aliasing vars.
1366     if (descriptor.isAccessorDescriptor() && symbolTableGet(thisObject, propertyName, slot))
1367         return false;
1368     return Base::defineOwnProperty(thisObject, globalObject, propertyName, descriptor, shouldThrow);
1369 }
1370
1371 void JSGlobalObject::addGlobalVar(const Identifier& ident)
1372 {
1373     ConcurrentJSLocker locker(symbolTable()->m_lock);
1374     SymbolTableEntry entry = symbolTable()->get(locker, ident.impl());
1375     if (!entry.isNull())
1376         return;
1377     
1378     ScopeOffset offset = symbolTable()->takeNextScopeOffset(locker);
1379     SymbolTableEntry newEntry(VarOffset(offset), 0);
1380     newEntry.prepareToWatch();
1381     symbolTable()->add(locker, ident.impl(), WTFMove(newEntry));
1382     
1383     ScopeOffset offsetForAssert = addVariables(1, jsUndefined());
1384     RELEASE_ASSERT(offsetForAssert == offset);
1385 }
1386
1387 void JSGlobalObject::addFunction(JSGlobalObject* globalObject, const Identifier& propertyName)
1388 {
1389     VM& vm = globalObject->vm();
1390     VM::DeletePropertyModeScope scope(vm, VM::DeletePropertyMode::IgnoreConfigurable);
1391     JSCell::deleteProperty(this, globalObject, propertyName);
1392     addGlobalVar(propertyName);
1393 }
1394
1395 void JSGlobalObject::setGlobalScopeExtension(JSScope* scope)
1396 {
1397     m_globalScopeExtension.set(vm(), this, scope);
1398 }
1399
1400 void JSGlobalObject::clearGlobalScopeExtension()
1401 {
1402     m_globalScopeExtension.clear();
1403 }
1404
1405 static inline JSObject* lastInPrototypeChain(VM& vm, JSObject* object)
1406 {
1407     JSObject* o = object;
1408     while (o->getPrototypeDirect(vm).isObject())
1409         o = asObject(o->getPrototypeDirect(vm));
1410     return o;
1411 }
1412
1413 // Private namespace for helpers for JSGlobalObject::haveABadTime()
1414 namespace {
1415
1416 class GlobalObjectDependencyFinder : public MarkedBlock::VoidFunctor {
1417 public:
1418     GlobalObjectDependencyFinder(VM& vm)
1419         : m_vm(vm)
1420     { }
1421
1422     IterationStatus operator()(HeapCell*, HeapCell::Kind) const;
1423
1424     void addDependency(JSGlobalObject* key, JSGlobalObject* dependent);
1425     HashSet<JSGlobalObject*>* dependentsFor(JSGlobalObject* key);
1426
1427 private:
1428     void visit(JSObject*);
1429
1430     VM& m_vm;
1431     HashMap<JSGlobalObject*, HashSet<JSGlobalObject*>> m_dependencies;
1432 };
1433
1434 inline void GlobalObjectDependencyFinder::addDependency(JSGlobalObject* key, JSGlobalObject* dependent)
1435 {
1436     auto keyResult = m_dependencies.add(key, HashSet<JSGlobalObject*>());
1437     keyResult.iterator->value.add(dependent);
1438 }
1439
1440 inline HashSet<JSGlobalObject*>* GlobalObjectDependencyFinder::dependentsFor(JSGlobalObject* key)
1441 {
1442     auto iterator = m_dependencies.find(key);
1443     if (iterator == m_dependencies.end())
1444         return nullptr;
1445     return &iterator->value;
1446 }
1447
1448 inline void GlobalObjectDependencyFinder::visit(JSObject* object)
1449 {
1450     VM& vm = m_vm;
1451
1452     if (!object->mayBePrototype())
1453         return;
1454
1455     JSObject* current = object;
1456     JSGlobalObject* objectGlobalObject = object->globalObject(vm);
1457     do {
1458         JSValue prototypeValue = current->getPrototypeDirect(vm);
1459         if (prototypeValue.isNull())
1460             return;
1461         current = asObject(prototypeValue);
1462
1463         JSGlobalObject* protoGlobalObject = current->globalObject(vm);
1464         if (protoGlobalObject != objectGlobalObject)
1465             addDependency(protoGlobalObject, objectGlobalObject);
1466     } while (true);
1467 }
1468
1469 IterationStatus GlobalObjectDependencyFinder::operator()(HeapCell* cell, HeapCell::Kind kind) const
1470 {
1471     if (isJSCellKind(kind) && static_cast<JSCell*>(cell)->isObject()) {
1472         // FIXME: This const_cast exists because this isn't a C++ lambda.
1473         // https://bugs.webkit.org/show_bug.cgi?id=159644
1474         const_cast<GlobalObjectDependencyFinder*>(this)->visit(jsCast<JSObject*>(static_cast<JSCell*>(cell)));
1475     }
1476     return IterationStatus::Continue;
1477 }
1478
1479 enum class BadTimeFinderMode {
1480     SingleGlobal,
1481     MultipleGlobals
1482 };
1483
1484 template<BadTimeFinderMode mode>
1485 class ObjectsWithBrokenIndexingFinder : public MarkedBlock::VoidFunctor {
1486 public:
1487     ObjectsWithBrokenIndexingFinder(VM&, Vector<JSObject*>&, JSGlobalObject*);
1488     ObjectsWithBrokenIndexingFinder(VM&, Vector<JSObject*>&, HashSet<JSGlobalObject*>&);
1489
1490     bool needsMultiGlobalsScan() const { return m_needsMultiGlobalsScan; }
1491     IterationStatus operator()(HeapCell*, HeapCell::Kind) const;
1492
1493 private:
1494     IterationStatus visit(JSObject*);
1495
1496     VM& m_vm;
1497     Vector<JSObject*>& m_foundObjects;
1498     JSGlobalObject* m_globalObject { nullptr }; // Only used for SingleBadTimeGlobal mode.
1499     HashSet<JSGlobalObject*>* m_globalObjects { nullptr }; // Only used for BadTimeGlobalGraph mode;
1500     bool m_needsMultiGlobalsScan { false };
1501 };
1502
1503 template<>
1504 ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::SingleGlobal>::ObjectsWithBrokenIndexingFinder(
1505     VM& vm, Vector<JSObject*>& foundObjects, JSGlobalObject* globalObject)
1506     : m_vm(vm)
1507     , m_foundObjects(foundObjects)
1508     , m_globalObject(globalObject)
1509 {
1510 }
1511
1512 template<>
1513 ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::MultipleGlobals>::ObjectsWithBrokenIndexingFinder(
1514     VM& vm, Vector<JSObject*>& foundObjects, HashSet<JSGlobalObject*>& globalObjects)
1515     : m_vm(vm)
1516     , m_foundObjects(foundObjects)
1517     , m_globalObjects(&globalObjects)
1518 {
1519 }
1520
1521 inline bool hasBrokenIndexing(IndexingType type)
1522 {
1523     return type && !hasSlowPutArrayStorage(type);
1524 }
1525
1526 inline bool hasBrokenIndexing(JSObject* object)
1527 {
1528     IndexingType type = object->indexingType();
1529     return hasBrokenIndexing(type);
1530 }
1531
1532 template<BadTimeFinderMode mode>
1533 inline IterationStatus ObjectsWithBrokenIndexingFinder<mode>::visit(JSObject* object)
1534 {
1535     VM& vm = m_vm;
1536
1537     // We only want to have a bad time in the affected global object, not in the entire
1538     // VM. But we have to be careful, since there may be objects that claim to belong to
1539     // a different global object that have prototypes from our global object.
1540     auto isInAffectedGlobalObject = [&] (JSObject* object) {
1541         JSGlobalObject* objectGlobalObject { nullptr };
1542         bool objectMayBePrototype { false };
1543
1544         if (mode == BadTimeFinderMode::SingleGlobal) {
1545             objectGlobalObject = object->globalObject(vm);
1546             if (objectGlobalObject == m_globalObject)
1547                 return true;
1548
1549             objectMayBePrototype = object->mayBePrototype();
1550         }
1551
1552         for (JSObject* current = object; ;) {
1553             JSGlobalObject* currentGlobalObject = current->globalObject(vm);
1554             if (mode == BadTimeFinderMode::SingleGlobal) {
1555                 if (objectMayBePrototype && currentGlobalObject != objectGlobalObject)
1556                     m_needsMultiGlobalsScan = true;
1557                 if (currentGlobalObject == m_globalObject)
1558                     return true;
1559             } else {
1560                 if (m_globalObjects->contains(currentGlobalObject))
1561                     return true;
1562             }
1563
1564             JSValue prototypeValue = current->getPrototypeDirect(vm);
1565             if (prototypeValue.isNull())
1566                 return false;
1567             current = asObject(prototypeValue);
1568         }
1569         RELEASE_ASSERT_NOT_REACHED();
1570     };
1571
1572     if (JSFunction* function = jsDynamicCast<JSFunction*>(vm, object)) {
1573         if (FunctionRareData* rareData = function->rareData()) {
1574             // We only use this to cache JSFinalObjects. They do not start off with a broken indexing type.
1575             ASSERT(!(rareData->objectAllocationStructure() && hasBrokenIndexing(rareData->objectAllocationStructure()->indexingType())));
1576
1577             if (Structure* structure = rareData->internalFunctionAllocationStructure()) {
1578                 if (hasBrokenIndexing(structure->indexingType())) {
1579                     bool isRelevantGlobalObject =
1580                         (mode == BadTimeFinderMode::SingleGlobal
1581                             ? m_globalObject == structure->globalObject()
1582                             : m_globalObjects->contains(structure->globalObject()))
1583                         || (structure->hasMonoProto() && !structure->storedPrototype().isNull() && isInAffectedGlobalObject(asObject(structure->storedPrototype())));
1584                     if (mode == BadTimeFinderMode::SingleGlobal && m_needsMultiGlobalsScan)
1585                         return IterationStatus::Done; // Bailing early and let the MultipleGlobals path handle everything.
1586                     if (isRelevantGlobalObject)
1587                         rareData->clearInternalFunctionAllocationProfile("have a bad time breaking internal function allocation");
1588                 }
1589             }
1590         }
1591     }
1592
1593     // Run this filter first, since it's cheap, and ought to filter out a lot of objects.
1594     if (!hasBrokenIndexing(object))
1595         return IterationStatus::Continue;
1596
1597     if (isInAffectedGlobalObject(object))
1598         m_foundObjects.append(object);
1599
1600     if (mode == BadTimeFinderMode::SingleGlobal && m_needsMultiGlobalsScan)
1601         return IterationStatus::Done; // Bailing early and let the MultipleGlobals path handle everything.
1602
1603     return IterationStatus::Continue;
1604 }
1605
1606 template<BadTimeFinderMode mode>
1607 IterationStatus ObjectsWithBrokenIndexingFinder<mode>::operator()(HeapCell* cell, HeapCell::Kind kind) const
1608 {
1609     if (isJSCellKind(kind) && static_cast<JSCell*>(cell)->isObject()) {
1610         // FIXME: This const_cast exists because this isn't a C++ lambda.
1611         // https://bugs.webkit.org/show_bug.cgi?id=159644
1612         return const_cast<ObjectsWithBrokenIndexingFinder*>(this)->visit(jsCast<JSObject*>(static_cast<JSCell*>(cell)));
1613     }
1614     return IterationStatus::Continue;
1615 }
1616
1617 } // end private namespace for helpers for JSGlobalObject::haveABadTime()
1618
1619 void JSGlobalObject::fireWatchpointAndMakeAllArrayStructuresSlowPut(VM& vm)
1620 {
1621     if (isHavingABadTime())
1622         return;
1623
1624     // Make sure that all JSArray allocations that load the appropriate structure from
1625     // this object now load a structure that uses SlowPut.
1626     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
1627         m_arrayStructureForIndexingShapeDuringAllocation[i].set(vm, this, originalArrayStructureForIndexingType(ArrayWithSlowPutArrayStorage));
1628
1629     // Same for any special array structures.
1630     Structure* slowPutStructure;
1631     slowPutStructure = createRegExpMatchesArraySlowPutStructure(vm, this);
1632     m_regExpMatchesArrayStructure.set(vm, this, slowPutStructure);
1633     slowPutStructure = ClonedArguments::createSlowPutStructure(vm, this, m_objectPrototype.get());
1634     m_clonedArgumentsStructure.set(vm, this, slowPutStructure);
1635
1636     // Make sure that all allocations or indexed storage transitions that are inlining
1637     // the assumption that it's safe to transition to a non-SlowPut array storage don't
1638     // do so anymore.
1639     // Note: we are deliberately firing the watchpoint here at the end only after
1640     // making all the array structures SlowPut. This ensures that the concurrent
1641     // JIT threads will always get the SlowPut versions of the structures if
1642     // isHavingABadTime() returns true. The concurrent JIT relies on this.
1643     m_havingABadTimeWatchpoint->fireAll(vm, "Having a bad time");
1644     ASSERT(isHavingABadTime()); // The watchpoint is what tells us that we're having a bad time.
1645 };
1646
1647 void JSGlobalObject::haveABadTime(VM& vm)
1648 {
1649     ASSERT(&vm == &this->vm());
1650     
1651     if (isHavingABadTime())
1652         return;
1653
1654     vm.structureCache.clear(); // We may be caching array structures in here.
1655
1656     DeferGC deferGC(vm.heap);
1657
1658     // Consider the following objects and prototype chains:
1659     //    O (of global G1) -> A (of global G1)
1660     //    B (of global G2) where G2 has a bad time
1661     //
1662     // If we set B as the prototype of A, G1 will need to have a bad time.
1663     // See comments in Structure::mayInterceptIndexedAccesses() for why.
1664     //
1665     // Now, consider the following objects and prototype chains:
1666     //    O1 (of global G1) -> A1 (of global G1) -> B1 (of global G2)
1667     //    O2 (of global G2) -> A2 (of global G2)
1668     //    B2 (of global G3) where G3 has a bad time.
1669     //
1670     // G1 and G2 does not have a bad time, but G3 already has a bad time.
1671     // If we set B2 as the prototype of A2, then G2 needs to have a bad time.
1672     // Note that by induction, G1 also now needs to have a bad time because of
1673     // O1 -> A1 -> B1.
1674     //
1675     // We describe this as global G1 being affected by global G2, and G2 by G3.
1676     // Similarly, we say that G1 is dependent on G2, and G2 on G3.
1677     // Hence, when G3 has a bad time, we need to ensure that all globals that
1678     // are transitively dependent on it also have a bad time (G2 and G1 in this
1679     // example).
1680     //
1681     // Apart from clearing the VM structure cache above, there are 2 more things
1682     // that we have to do when globals have a bad time:
1683     // 1. For each affected global:
1684     //    a. Fire its HaveABadTime watchpoint.
1685     //    b. Convert all of its array structures to SlowPutArrayStorage.
1686     // 2. Make sure that all affected objects  switch to the slow kind of
1687     //    indexed storage. An object is considered to be affected if it has
1688     //    indexed storage and has a prototype object which may have indexed
1689     //    accessors. If the prototype object belongs to a global having a bad
1690     //    time, then the prototype object is considered to possibly have indexed
1691     //    accessors. See comments in Structure::mayInterceptIndexedAccesses()
1692     //    for details.
1693     //
1694     // Note: step 1 must be completed before step 2 because step 2 relies on
1695     // the HaveABadTime watchpoint having already been fired on all affected
1696     // globals.
1697     //
1698     // In the common case, only this global will start having a bad time here,
1699     // and no other globals are affected by it. So, we first proceed on this assumption
1700     // with a simpler ObjectsWithBrokenIndexingFinder scan to find heap objects
1701     // affected by this global that need to be converted to SlowPutArrayStorage.
1702     // We'll also have the finder check for the presence of other global objects
1703     // depending on this one.
1704     //
1705     // If we do discover other globals depending on this one, we'll abort this
1706     // first ObjectsWithBrokenIndexingFinder scan because it will be insufficient
1707     // to find all affected objects that need to be converted to SlowPutArrayStorage.
1708     // It also does not make dependent globals have a bad time. Instead, we'll
1709     // take a more comprehensive approach of first creating a dependency graph
1710     // between globals, and then using that graph to determine all affected
1711     // globals and objects. With that, we can make all affected globals have a
1712     // bad time, and convert all affected objects to SlowPutArrayStorage.
1713
1714     fireWatchpointAndMakeAllArrayStructuresSlowPut(vm); // Step 1 above.
1715     
1716     Vector<JSObject*> foundObjects;
1717     ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::SingleGlobal> finder(vm, foundObjects, this);
1718     {
1719         HeapIterationScope iterationScope(vm.heap);
1720         vm.heap.objectSpace().forEachLiveCell(iterationScope, finder); // Attempt step 2 above.
1721     }
1722
1723     if (finder.needsMultiGlobalsScan()) {
1724         foundObjects.clear();
1725
1726         // Find all globals that will also have a bad time as a side effect of
1727         // this global having a bad time.
1728         GlobalObjectDependencyFinder dependencies(vm);
1729         {
1730             HeapIterationScope iterationScope(vm.heap);
1731             vm.heap.objectSpace().forEachLiveCell(iterationScope, dependencies);
1732         }
1733
1734         HashSet<JSGlobalObject*> globalsHavingABadTime;
1735         Deque<JSGlobalObject*> globals;
1736
1737         globals.append(this);
1738         while (!globals.isEmpty()) {
1739             JSGlobalObject* global = globals.takeFirst();
1740             global->fireWatchpointAndMakeAllArrayStructuresSlowPut(vm); // Step 1 above.
1741             auto result = globalsHavingABadTime.add(global);
1742             if (result.isNewEntry) {
1743                 if (HashSet<JSGlobalObject*>* dependents = dependencies.dependentsFor(global)) {
1744                     for (JSGlobalObject* dependentGlobal : *dependents)
1745                         globals.append(dependentGlobal);
1746                 }
1747             }
1748         }
1749
1750         ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::MultipleGlobals> finder(vm, foundObjects, globalsHavingABadTime);
1751         {
1752             HeapIterationScope iterationScope(vm.heap);
1753             vm.heap.objectSpace().forEachLiveCell(iterationScope, finder); // Step 2 above.
1754         }
1755     }
1756
1757     while (!foundObjects.isEmpty()) {
1758         JSObject* object = asObject(foundObjects.last());
1759         foundObjects.removeLast();
1760         ASSERT(hasBrokenIndexing(object));
1761         object->switchToSlowPutArrayStorage(vm);
1762     }
1763 }
1764
1765 void JSGlobalObject::fixupPrototypeChainWithObjectPrototype(VM& vm)
1766 {
1767     JSObject* oldLastInPrototypeChain = lastInPrototypeChain(vm, this);
1768     JSObject* objectPrototype = m_objectPrototype.get();
1769     if (oldLastInPrototypeChain != objectPrototype)
1770         oldLastInPrototypeChain->setPrototypeDirect(vm, objectPrototype);
1771 }
1772
1773 // Set prototype, and also insert the object prototype at the end of the chain.
1774 void JSGlobalObject::resetPrototype(VM& vm, JSValue prototype)
1775 {
1776     if (getPrototypeDirect(vm) == prototype)
1777         return;
1778     setPrototypeDirect(vm, prototype);
1779     fixupPrototypeChainWithObjectPrototype(vm);
1780     // Whenever we change the prototype of the global object, we need to create a new JSProxy with the correct prototype.
1781     setGlobalThis(vm, JSProxy::create(vm, JSProxy::createStructure(vm, this, prototype, PureForwardingProxyType), this));
1782 }
1783
1784 void JSGlobalObject::visitChildren(JSCell* cell, SlotVisitor& visitor)
1785
1786     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(cell);
1787     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1788     Base::visitChildren(thisObject, visitor);
1789
1790     visitor.append(thisObject->m_globalThis);
1791
1792     visitor.append(thisObject->m_globalLexicalEnvironment);
1793     visitor.append(thisObject->m_globalScopeExtension);
1794     visitor.append(thisObject->m_globalCallee);
1795     visitor.append(thisObject->m_stackOverflowFrameCallee);
1796     thisObject->m_evalErrorStructure.visit(visitor);
1797     thisObject->m_rangeErrorStructure.visit(visitor);
1798     thisObject->m_referenceErrorStructure.visit(visitor);
1799     thisObject->m_syntaxErrorStructure.visit(visitor);
1800     thisObject->m_typeErrorStructure.visit(visitor);
1801     thisObject->m_URIErrorStructure.visit(visitor);
1802     thisObject->m_aggregateErrorStructure.visit(visitor);
1803     visitor.append(thisObject->m_arrayConstructor);
1804     visitor.append(thisObject->m_regExpConstructor);
1805     visitor.append(thisObject->m_objectConstructor);
1806     visitor.append(thisObject->m_functionConstructor);
1807     visitor.append(thisObject->m_promiseConstructor);
1808     visitor.append(thisObject->m_internalPromiseConstructor);
1809
1810     thisObject->m_defaultCollator.visit(visitor);
1811     thisObject->m_collatorStructure.visit(visitor);
1812     thisObject->m_dateTimeFormatStructure.visit(visitor);
1813     thisObject->m_numberFormatStructure.visit(visitor);
1814     thisObject->m_localeStructure.visit(visitor);
1815     thisObject->m_pluralRulesStructure.visit(visitor);
1816     thisObject->m_relativeTimeFormatStructure.visit(visitor);
1817
1818     visitor.append(thisObject->m_nullGetterFunction);
1819     visitor.append(thisObject->m_nullSetterFunction);
1820
1821     thisObject->m_parseIntFunction.visit(visitor);
1822     thisObject->m_parseFloatFunction.visit(visitor);
1823     thisObject->m_arrayProtoToStringFunction.visit(visitor);
1824     thisObject->m_arrayProtoValuesFunction.visit(visitor);
1825     thisObject->m_evalFunction.visit(visitor);
1826     thisObject->m_iteratorProtocolFunction.visit(visitor);
1827     thisObject->m_promiseResolveFunction.visit(visitor);
1828     visitor.append(thisObject->m_objectProtoValueOfFunction);
1829     thisObject->m_numberProtoToStringFunction.visit(visitor);
1830     visitor.append(thisObject->m_functionProtoHasInstanceSymbolFunction);
1831     thisObject->m_throwTypeErrorGetterSetter.visit(visitor);
1832     visitor.append(thisObject->m_regExpProtoSymbolReplace);
1833     visitor.append(thisObject->m_throwTypeErrorArgumentsCalleeAndCallerGetterSetter);
1834     thisObject->m_moduleLoader.visit(visitor);
1835
1836     visitor.append(thisObject->m_objectPrototype);
1837     visitor.append(thisObject->m_functionPrototype);
1838     visitor.append(thisObject->m_arrayPrototype);
1839     visitor.append(thisObject->m_iteratorPrototype);
1840     visitor.append(thisObject->m_generatorFunctionPrototype);
1841     visitor.append(thisObject->m_generatorPrototype);
1842     visitor.append(thisObject->m_arrayIteratorPrototype);
1843     visitor.append(thisObject->m_mapIteratorPrototype);
1844     visitor.append(thisObject->m_setIteratorPrototype);
1845     visitor.append(thisObject->m_asyncFunctionPrototype);
1846     visitor.append(thisObject->m_asyncGeneratorPrototype);
1847     visitor.append(thisObject->m_asyncIteratorPrototype);
1848     visitor.append(thisObject->m_asyncGeneratorFunctionPrototype);
1849
1850     thisObject->m_debuggerScopeStructure.visit(visitor);
1851     thisObject->m_withScopeStructure.visit(visitor);
1852     thisObject->m_strictEvalActivationStructure.visit(visitor);
1853     visitor.append(thisObject->m_lexicalEnvironmentStructure);
1854     thisObject->m_moduleEnvironmentStructure.visit(visitor);
1855     visitor.append(thisObject->m_directArgumentsStructure);
1856     visitor.append(thisObject->m_scopedArgumentsStructure);
1857     visitor.append(thisObject->m_clonedArgumentsStructure);
1858     visitor.append(thisObject->m_objectStructureForObjectConstructor);
1859     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
1860         visitor.append(thisObject->m_originalArrayStructureForIndexingShape[i]);
1861     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
1862         visitor.append(thisObject->m_arrayStructureForIndexingShapeDuringAllocation[i]);
1863     thisObject->m_callbackConstructorStructure.visit(visitor);
1864     thisObject->m_callbackFunctionStructure.visit(visitor);
1865     thisObject->m_callbackObjectStructure.visit(visitor);
1866 #if JSC_OBJC_API_ENABLED
1867     thisObject->m_objcCallbackFunctionStructure.visit(visitor);
1868     thisObject->m_objcWrapperObjectStructure.visit(visitor);
1869 #endif
1870 #ifdef JSC_GLIB_API_ENABLED
1871     thisObject->m_glibCallbackFunctionStructure.visit(visitor);
1872     thisObject->m_glibWrapperObjectStructure.visit(visitor);
1873 #endif
1874     visitor.append(thisObject->m_nullPrototypeObjectStructure);
1875     visitor.append(thisObject->m_calleeStructure);
1876
1877     visitor.append(thisObject->m_hostFunctionStructure);
1878     auto visitFunctionStructures = [&] (FunctionStructures& structures) {
1879         visitor.append(structures.arrowFunctionStructure);
1880         visitor.append(structures.sloppyFunctionStructure);
1881         visitor.append(structures.strictFunctionStructure);
1882     };
1883     visitFunctionStructures(thisObject->m_builtinFunctions);
1884     visitFunctionStructures(thisObject->m_ordinaryFunctions);
1885
1886     thisObject->m_customGetterSetterFunctionStructure.visit(visitor);
1887     thisObject->m_boundFunctionStructure.visit(visitor);
1888     thisObject->m_nativeStdFunctionStructure.visit(visitor);
1889     visitor.append(thisObject->m_regExpStructure);
1890     visitor.append(thisObject->m_generatorFunctionStructure);
1891     visitor.append(thisObject->m_asyncFunctionStructure);
1892     visitor.append(thisObject->m_asyncGeneratorFunctionStructure);
1893     visitor.append(thisObject->m_generatorStructure);
1894     visitor.append(thisObject->m_asyncGeneratorStructure);
1895     visitor.append(thisObject->m_arrayIteratorStructure);
1896     visitor.append(thisObject->m_mapIteratorStructure);
1897     visitor.append(thisObject->m_setIteratorStructure);
1898     thisObject->m_iteratorResultObjectStructure.visit(visitor);
1899     visitor.append(thisObject->m_regExpMatchesArrayStructure);
1900     thisObject->m_moduleRecordStructure.visit(visitor);
1901     thisObject->m_moduleNamespaceObjectStructure.visit(visitor);
1902     thisObject->m_proxyObjectStructure.visit(visitor);
1903     thisObject->m_callableProxyObjectStructure.visit(visitor);
1904     thisObject->m_proxyRevokeStructure.visit(visitor);
1905
1906     for (auto& property : thisObject->m_linkTimeConstants)
1907         property.visit(visitor);
1908     
1909 #if ENABLE(SHARED_ARRAY_BUFFER)
1910     visitor.append(thisObject->m_sharedArrayBufferPrototype);
1911     visitor.append(thisObject->m_sharedArrayBufferStructure);
1912 #endif
1913
1914 #define VISIT_SIMPLE_TYPE(CapitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) { \
1915         visitor.append(thisObject->m_ ## lowerName ## Prototype); \
1916         visitor.append(thisObject->m_ ## properName ## Structure); \
1917     }
1918
1919     FOR_EACH_SIMPLE_BUILTIN_TYPE(VISIT_SIMPLE_TYPE)
1920     FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(VISIT_SIMPLE_TYPE)
1921
1922 #define VISIT_LAZY_TYPE(CapitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) \
1923         thisObject->m_ ## properName ## Structure.visit(visitor);
1924
1925     FOR_EACH_LAZY_BUILTIN_TYPE(VISIT_LAZY_TYPE)
1926
1927 #if ENABLE(WEBASSEMBLY)
1928     thisObject->m_webAssemblyModuleRecordStructure.visit(visitor);
1929     thisObject->m_webAssemblyFunctionStructure.visit(visitor);
1930     thisObject->m_jsToWasmICCalleeStructure.visit(visitor);
1931     thisObject->m_webAssemblyWrapperFunctionStructure.visit(visitor);
1932     FOR_EACH_WEBASSEMBLY_CONSTRUCTOR_TYPE(VISIT_LAZY_TYPE)
1933 #endif // ENABLE(WEBASSEMBLY)
1934
1935 #undef VISIT_SIMPLE_TYPE
1936 #undef VISIT_LAZY_TYPE
1937
1938     for (unsigned i = NumberOfTypedArrayTypes; i--;)
1939         thisObject->lazyTypedArrayStructure(indexToTypedArrayType(i)).visit(visitor);
1940     
1941     visitor.append(thisObject->m_speciesGetterSetter);
1942     thisObject->m_typedArrayProto.visit(visitor);
1943     thisObject->m_typedArraySuperConstructor.visit(visitor);
1944     thisObject->m_regExpGlobalData.visitAggregate(visitor);
1945 }
1946
1947 CallFrame* JSGlobalObject::deprecatedCallFrameForDebugger()
1948 {
1949     return CallFrame::create(m_deprecatedCallFrameForDebugger);
1950 }
1951
1952 void JSGlobalObject::exposeDollarVM(VM& vm)
1953 {
1954     RELEASE_ASSERT(g_jscConfig.restrictedOptionsEnabled && Options::useDollarVM());
1955     if (hasOwnProperty(this, vm.propertyNames->builtinNames().dollarVMPrivateName()))
1956         return;
1957
1958     JSDollarVM* dollarVM = JSDollarVM::create(vm, JSDollarVM::createStructure(vm, this, m_objectPrototype.get()));
1959
1960     GlobalPropertyInfo extraStaticGlobals[] = {
1961         GlobalPropertyInfo(vm.propertyNames->builtinNames().dollarVMPrivateName(), dollarVM, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1962     };
1963     addStaticGlobals(extraStaticGlobals, WTF_ARRAY_LENGTH(extraStaticGlobals));
1964
1965     putDirect(vm, Identifier::fromString(vm, "$vm"), dollarVM, static_cast<unsigned>(PropertyAttribute::DontEnum));
1966 }
1967
1968 void JSGlobalObject::addStaticGlobals(GlobalPropertyInfo* globals, int count)
1969 {
1970     ScopeOffset startOffset = addVariables(count, jsUndefined());
1971
1972     for (int i = 0; i < count; ++i) {
1973         GlobalPropertyInfo& global = globals[i];
1974         // This `configurable = false` is necessary condition for static globals,
1975         // otherwise lexical bindings can change the result of GlobalVar queries too.
1976         // We won't be able to declare a global lexical variable with the sanem name to
1977         // the static globals because configurable = false.
1978         ASSERT(global.attributes & PropertyAttribute::DontDelete);
1979         
1980         WatchpointSet* watchpointSet = nullptr;
1981         WriteBarrierBase<Unknown>* variable = nullptr;
1982         {
1983             ConcurrentJSLocker locker(symbolTable()->m_lock);
1984             ScopeOffset offset = symbolTable()->takeNextScopeOffset(locker);
1985             RELEASE_ASSERT(offset == startOffset + i);
1986             SymbolTableEntry newEntry(VarOffset(offset), global.attributes);
1987             newEntry.prepareToWatch();
1988             watchpointSet = newEntry.watchpointSet();
1989             symbolTable()->add(locker, global.identifier.impl(), WTFMove(newEntry));
1990             variable = &variableAt(offset);
1991         }
1992         symbolTablePutTouchWatchpointSet(vm(), this, global.identifier, global.value, variable, watchpointSet);
1993     }
1994 }
1995
1996 bool JSGlobalObject::getOwnPropertySlot(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, PropertySlot& slot)
1997 {
1998     if (Base::getOwnPropertySlot(object, globalObject, propertyName, slot))
1999         return true;
2000     return symbolTableGet(jsCast<JSGlobalObject*>(object), propertyName, slot);
2001 }
2002
2003 void JSGlobalObject::clearRareData(JSCell* cell)
2004 {
2005     jsCast<JSGlobalObject*>(cell)->m_rareData = nullptr;
2006 }
2007
2008 void JSGlobalObject::tryInstallArraySpeciesWatchpoint()
2009 {
2010     RELEASE_ASSERT(!m_arrayPrototypeConstructorWatchpoint);
2011     RELEASE_ASSERT(!m_arrayConstructorSpeciesWatchpoint);
2012
2013     VM& vm = this->vm();
2014     auto scope = DECLARE_THROW_SCOPE(vm);
2015
2016     // First we need to make sure that the Array.prototype.constructor property points to Array
2017     // and that Array[Symbol.species] is the primordial GetterSetter.
2018     ArrayPrototype* arrayPrototype = this->arrayPrototype();
2019
2020     // We only initialize once so flattening the structures does not have any real cost.
2021     Structure* prototypeStructure = arrayPrototype->structure(vm);
2022     if (prototypeStructure->isDictionary())
2023         prototypeStructure = prototypeStructure->flattenDictionaryStructure(vm, arrayPrototype);
2024     RELEASE_ASSERT(!prototypeStructure->isDictionary());
2025
2026     ArrayConstructor* arrayConstructor = this->arrayConstructor();
2027
2028     auto invalidateWatchpoint = [&] {
2029         m_arraySpeciesWatchpointSet.invalidate(vm, StringFireDetail("Was not able to set up array species watchpoint."));
2030     };
2031
2032     PropertySlot constructorSlot(arrayPrototype, PropertySlot::InternalMethodType::VMInquiry);
2033     arrayPrototype->getOwnPropertySlot(arrayPrototype, this, vm.propertyNames->constructor, constructorSlot);
2034     scope.assertNoException();
2035     if (constructorSlot.slotBase() != arrayPrototype
2036         || !constructorSlot.isCacheableValue()
2037         || constructorSlot.getValue(this, vm.propertyNames->constructor) != arrayConstructor) {
2038         invalidateWatchpoint();
2039         return;
2040     }
2041
2042     Structure* constructorStructure = arrayConstructor->structure(vm);
2043     if (constructorStructure->isDictionary())
2044         constructorStructure = constructorStructure->flattenDictionaryStructure(vm, arrayConstructor);
2045
2046     PropertySlot speciesSlot(arrayConstructor, PropertySlot::InternalMethodType::VMInquiry);
2047     arrayConstructor->getOwnPropertySlot(arrayConstructor, this, vm.propertyNames->speciesSymbol, speciesSlot);
2048     scope.assertNoException();
2049     if (speciesSlot.slotBase() != arrayConstructor
2050         || !speciesSlot.isCacheableGetter()
2051         || speciesSlot.getterSetter() != speciesGetterSetter()) {
2052         invalidateWatchpoint();
2053         return;
2054     }
2055
2056     // Now we need to setup the watchpoints to make sure these conditions remain valid.
2057     prototypeStructure->startWatchingPropertyForReplacements(vm, constructorSlot.cachedOffset());
2058     constructorStructure->startWatchingPropertyForReplacements(vm, speciesSlot.cachedOffset());
2059
2060     ObjectPropertyCondition constructorCondition = ObjectPropertyCondition::equivalence(vm, arrayPrototype, arrayPrototype, vm.propertyNames->constructor.impl(), arrayConstructor);
2061     ObjectPropertyCondition speciesCondition = ObjectPropertyCondition::equivalence(vm, arrayPrototype, arrayConstructor, vm.propertyNames->speciesSymbol.impl(), speciesGetterSetter());
2062
2063     if (!constructorCondition.isWatchable() || !speciesCondition.isWatchable()) {
2064         invalidateWatchpoint();
2065         return;
2066     }
2067
2068     // We only watch this from the DFG, and the DFG makes sure to only start watching if the watchpoint is in the IsWatched state.
2069     RELEASE_ASSERT(!m_arraySpeciesWatchpointSet.isBeingWatched());
2070     m_arraySpeciesWatchpointSet.touch(vm, "Set up array species watchpoint.");
2071
2072     m_arrayPrototypeConstructorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, constructorCondition, m_arraySpeciesWatchpointSet);
2073     m_arrayPrototypeConstructorWatchpoint->install(vm);
2074
2075     m_arrayConstructorSpeciesWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, speciesCondition, m_arraySpeciesWatchpointSet);
2076     m_arrayConstructorSpeciesWatchpoint->install(vm);
2077 }
2078
2079 void JSGlobalObject::installNumberPrototypeWatchpoint(NumberPrototype* numberPrototype)
2080 {
2081     VM& vm = this->vm();
2082     ASSERT(m_numberToStringWatchpointSet.isStillValid());
2083     ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, numberPrototype, vm.propertyNames->toString);
2084     m_numberPrototypeToStringWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_numberToStringWatchpointSet);
2085     m_numberPrototypeToStringWatchpoint->install(vm);
2086 }
2087
2088 void JSGlobalObject::installMapPrototypeWatchpoint(MapPrototype* mapPrototype)
2089 {
2090     VM& vm = this->vm();
2091     if (m_mapIteratorProtocolWatchpointSet.isStillValid()) {
2092         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, mapPrototype, vm.propertyNames->iteratorSymbol);
2093         m_mapPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_mapIteratorProtocolWatchpointSet);
2094         m_mapPrototypeSymbolIteratorWatchpoint->install(vm);
2095     }
2096     ASSERT(m_mapSetWatchpointSet.isStillValid());
2097     ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, mapPrototype, vm.propertyNames->set);
2098     m_mapPrototypeSetWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_mapSetWatchpointSet);
2099     m_mapPrototypeSetWatchpoint->install(vm);
2100 }
2101
2102 void JSGlobalObject::installSetPrototypeWatchpoint(SetPrototype* setPrototype)
2103 {
2104     VM& vm = this->vm();
2105     if (m_setIteratorProtocolWatchpointSet.isStillValid()) {
2106         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, setPrototype, vm.propertyNames->iteratorSymbol);
2107         m_setPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_setIteratorProtocolWatchpointSet);
2108         m_setPrototypeSymbolIteratorWatchpoint->install(vm);
2109     }
2110     ASSERT(m_setAddWatchpointSet.isStillValid());
2111     ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this, setPrototype, vm.propertyNames->add);
2112     m_setPrototypeAddWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_setAddWatchpointSet);
2113     m_setPrototypeAddWatchpoint->install(vm);
2114 }
2115
2116 void slowValidateCell(JSGlobalObject* globalObject)
2117 {
2118     RELEASE_ASSERT(globalObject->isGlobalObject());
2119     ASSERT_GC_OBJECT_INHERITS(globalObject, JSGlobalObject::info());
2120 }
2121
2122 void JSGlobalObject::setRemoteDebuggingEnabled(bool enabled)
2123 {
2124 #if ENABLE(REMOTE_INSPECTOR)
2125     m_inspectorDebuggable->setRemoteDebuggingAllowed(enabled);
2126 #else
2127     UNUSED_PARAM(enabled);
2128 #endif
2129 }
2130
2131 bool JSGlobalObject::remoteDebuggingEnabled() const
2132 {
2133 #if ENABLE(REMOTE_INSPECTOR)
2134     return m_inspectorDebuggable->remoteDebuggingAllowed();
2135 #else
2136     return false;
2137 #endif
2138 }
2139
2140 void JSGlobalObject::setName(const String& name)
2141 {
2142     m_name = name;
2143
2144 #if ENABLE(REMOTE_INSPECTOR)
2145     m_inspectorDebuggable->update();
2146 #endif
2147 }
2148
2149 void JSGlobalObject::bumpGlobalLexicalBindingEpoch(VM& vm)
2150 {
2151     if (++m_globalLexicalBindingEpoch == Options::thresholdForGlobalLexicalBindingEpoch()) {
2152         // Since the epoch overflows, we should rewrite all the CodeBlock to adjust to the newly started generation.
2153         m_globalLexicalBindingEpoch = 1;
2154         vm.heap.codeBlockSet().iterate([&] (CodeBlock* codeBlock) {
2155             if (codeBlock->globalObject() != this)
2156                 return;
2157             codeBlock->notifyLexicalBindingUpdate();
2158         });
2159     }
2160 }
2161
2162 void JSGlobalObject::queueMicrotask(Ref<Microtask>&& task)
2163 {
2164     if (globalObjectMethodTable()->queueTaskToEventLoop) {
2165         globalObjectMethodTable()->queueTaskToEventLoop(*this, WTFMove(task));
2166         return;
2167     }
2168
2169     vm().queueMicrotask(*this, WTFMove(task));
2170 }
2171
2172 void JSGlobalObject::setDebugger(Debugger* debugger)
2173 {
2174     m_debugger = debugger;
2175     if (debugger)
2176         vm().ensureShadowChicken();
2177 }
2178
2179 bool JSGlobalObject::hasDebugger() const
2180
2181     return m_debugger;
2182 }
2183
2184 bool JSGlobalObject::hasInteractiveDebugger() const 
2185
2186     return m_debugger && m_debugger->isInteractivelyDebugging();
2187 }
2188
2189 #if ENABLE(DFG_JIT)
2190 WatchpointSet* JSGlobalObject::getReferencedPropertyWatchpointSet(UniquedStringImpl* uid)
2191 {
2192     ConcurrentJSLocker locker(m_referencedGlobalPropertyWatchpointSetsLock);
2193     return m_referencedGlobalPropertyWatchpointSets.get(uid);
2194 }
2195
2196 WatchpointSet& JSGlobalObject::ensureReferencedPropertyWatchpointSet(UniquedStringImpl* uid)
2197 {
2198     ConcurrentJSLocker locker(m_referencedGlobalPropertyWatchpointSetsLock);
2199     return m_referencedGlobalPropertyWatchpointSets.ensure(uid, [] {
2200         return WatchpointSet::create(IsWatched);
2201     }).iterator->value.get();
2202 }
2203 #endif
2204
2205 JSGlobalObject* JSGlobalObject::create(VM& vm, Structure* structure)
2206 {
2207     JSGlobalObject* globalObject = new (NotNull, allocateCell<JSGlobalObject>(vm.heap)) JSGlobalObject(vm, structure);
2208     globalObject->finishCreation(vm);
2209     return globalObject;
2210 }
2211
2212 void JSGlobalObject::finishCreation(VM& vm)
2213 {
2214     Base::finishCreation(vm);
2215     structure(vm)->setGlobalObject(vm, this);
2216     m_runtimeFlags = m_globalObjectMethodTable->javaScriptRuntimeFlags(this);
2217     init(vm);
2218     setGlobalThis(vm, JSProxy::create(vm, JSProxy::createStructure(vm, this, getPrototypeDirect(vm), PureForwardingProxyType), this));
2219     ASSERT(type() == GlobalObjectType);
2220 }
2221
2222 void JSGlobalObject::finishCreation(VM& vm, JSObject* thisValue)
2223 {
2224     Base::finishCreation(vm);
2225     structure(vm)->setGlobalObject(vm, this);
2226     m_runtimeFlags = m_globalObjectMethodTable->javaScriptRuntimeFlags(this);
2227     init(vm);
2228     setGlobalThis(vm, thisValue);
2229     ASSERT(type() == GlobalObjectType);
2230 }
2231
2232 #ifdef JSC_GLIB_API_ENABLED
2233 void JSGlobalObject::setWrapperMap(std::unique_ptr<WrapperMap>&& map)
2234 {
2235     m_wrapperMap = WTFMove(map);
2236 }
2237 #endif
2238
2239 } // namespace JSC