38cfee041af923e8b351a139bbc051db55e95731
[WebKit-https.git] / Source / JavaScriptCore / jsc.cpp
1 /*
2  *  Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3  *  Copyright (C) 2004-2017 Apple Inc. All rights reserved.
4  *  Copyright (C) 2006 Bjoern Graf (bjoern.graf@gmail.com)
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Library General Public
8  *  License as published by the Free Software Foundation; either
9  *  version 2 of the License, or (at your option) any later version.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Library General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Library General Public License
17  *  along with this library; see the file COPYING.LIB.  If not, write to
18  *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  *  Boston, MA 02110-1301, USA.
20  *
21  */
22
23 #include "config.h"
24
25 #include "ArrayBuffer.h"
26 #include "ArrayPrototype.h"
27 #include "BuiltinExecutableCreator.h"
28 #include "BuiltinNames.h"
29 #include "ButterflyInlines.h"
30 #include "CodeBlock.h"
31 #include "Completion.h"
32 #include "ConfigFile.h"
33 #include "DOMJITGetterSetter.h"
34 #include "Disassembler.h"
35 #include "Exception.h"
36 #include "ExceptionHelpers.h"
37 #include "GetterSetter.h"
38 #include "HeapProfiler.h"
39 #include "HeapSnapshotBuilder.h"
40 #include "InitializeThreading.h"
41 #include "Interpreter.h"
42 #include "JIT.h"
43 #include "JSArray.h"
44 #include "JSArrayBuffer.h"
45 #include "JSCInlines.h"
46 #include "JSFunction.h"
47 #include "JSInternalPromise.h"
48 #include "JSInternalPromiseDeferred.h"
49 #include "JSLock.h"
50 #include "JSModuleLoader.h"
51 #include "JSNativeStdFunction.h"
52 #include "JSONObject.h"
53 #include "JSProxy.h"
54 #include "JSSourceCode.h"
55 #include "JSString.h"
56 #include "JSTypedArrays.h"
57 #include "JSWebAssemblyInstance.h"
58 #include "JSWebAssemblyMemory.h"
59 #include "LLIntData.h"
60 #include "LLIntThunks.h"
61 #include "ObjectConstructor.h"
62 #include "ParserError.h"
63 #include "ProfilerDatabase.h"
64 #include "PromiseDeferredTimer.h"
65 #include "ProtoCallFrame.h"
66 #include "ReleaseHeapAccessScope.h"
67 #include "SamplingProfiler.h"
68 #include "ShadowChicken.h"
69 #include "Snippet.h"
70 #include "SnippetParams.h"
71 #include "StackVisitor.h"
72 #include "StructureInlines.h"
73 #include "StructureRareDataInlines.h"
74 #include "SuperSampler.h"
75 #include "TestRunnerUtils.h"
76 #include "TypeProfilerLog.h"
77 #include "WasmContext.h"
78 #include "WasmFaultSignalHandler.h"
79 #include "WasmMemory.h"
80 #include <locale.h>
81 #include <math.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <string.h>
85 #include <thread>
86 #include <type_traits>
87 #include <wtf/CommaPrinter.h>
88 #include <wtf/CurrentTime.h>
89 #include <wtf/MainThread.h>
90 #include <wtf/NeverDestroyed.h>
91 #include <wtf/StringPrintStream.h>
92 #include <wtf/text/StringBuilder.h>
93
94 #if OS(WINDOWS)
95 #include <direct.h>
96 #include <wtf/text/win/WCharStringExtras.h>
97 #else
98 #include <unistd.h>
99 #endif
100
101 #if HAVE(READLINE)
102 // readline/history.h has a Function typedef which conflicts with the WTF::Function template from WTF/Forward.h
103 // We #define it to something else to avoid this conflict.
104 #define Function ReadlineFunction
105 #include <readline/history.h>
106 #include <readline/readline.h>
107 #undef Function
108 #endif
109
110 #if HAVE(SYS_TIME_H)
111 #include <sys/time.h>
112 #endif
113
114 #if HAVE(SIGNAL_H)
115 #include <signal.h>
116 #endif
117
118 #if COMPILER(MSVC)
119 #include <crtdbg.h>
120 #include <mmsystem.h>
121 #include <windows.h>
122 #endif
123
124 #if PLATFORM(IOS) && CPU(ARM_THUMB2)
125 #include <fenv.h>
126 #include <arm/arch.h>
127 #endif
128
129 #if !defined(PATH_MAX)
130 #define PATH_MAX 4096
131 #endif
132
133 using namespace JSC;
134 using namespace WTF;
135
136 namespace {
137
138 NO_RETURN_WITH_VALUE static void jscExit(int status)
139 {
140     waitForAsynchronousDisassembly();
141     
142 #if ENABLE(DFG_JIT)
143     if (DFG::isCrashing()) {
144         for (;;) {
145 #if OS(WINDOWS)
146             Sleep(1000);
147 #else
148             pause();
149 #endif
150         }
151     }
152 #endif // ENABLE(DFG_JIT)
153     exit(status);
154 }
155
156 class Element;
157 class ElementHandleOwner;
158 class Masuqerader;
159 class Root;
160 class RuntimeArray;
161
162 class Element : public JSNonFinalObject {
163 public:
164     Element(VM& vm, Structure* structure)
165         : Base(vm, structure)
166     {
167     }
168
169     typedef JSNonFinalObject Base;
170
171     Root* root() const { return m_root.get(); }
172     void setRoot(VM& vm, Root* root) { m_root.set(vm, this, root); }
173
174     static Element* create(VM& vm, JSGlobalObject* globalObject, Root* root)
175     {
176         Structure* structure = createStructure(vm, globalObject, jsNull());
177         Element* element = new (NotNull, allocateCell<Element>(vm.heap, sizeof(Element))) Element(vm, structure);
178         element->finishCreation(vm, root);
179         return element;
180     }
181
182     void finishCreation(VM&, Root*);
183
184     static void visitChildren(JSCell* cell, SlotVisitor& visitor)
185     {
186         Element* thisObject = jsCast<Element*>(cell);
187         ASSERT_GC_OBJECT_INHERITS(thisObject, info());
188         Base::visitChildren(thisObject, visitor);
189         visitor.append(thisObject->m_root);
190     }
191
192     static ElementHandleOwner* handleOwner();
193
194     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
195     {
196         return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
197     }
198
199     DECLARE_INFO;
200
201 private:
202     WriteBarrier<Root> m_root;
203 };
204
205 class ElementHandleOwner : public WeakHandleOwner {
206 public:
207     bool isReachableFromOpaqueRoots(Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor) override
208     {
209         Element* element = jsCast<Element*>(handle.slot()->asCell());
210         return visitor.containsOpaqueRoot(element->root());
211     }
212 };
213
214 class Masquerader : public JSNonFinalObject {
215 public:
216     Masquerader(VM& vm, Structure* structure)
217         : Base(vm, structure)
218     {
219     }
220
221     typedef JSNonFinalObject Base;
222     static const unsigned StructureFlags = Base::StructureFlags | JSC::MasqueradesAsUndefined;
223
224     static Masquerader* create(VM& vm, JSGlobalObject* globalObject)
225     {
226         globalObject->masqueradesAsUndefinedWatchpoint()->fireAll(vm, "Masquerading object allocated");
227         Structure* structure = createStructure(vm, globalObject, jsNull());
228         Masquerader* result = new (NotNull, allocateCell<Masquerader>(vm.heap, sizeof(Masquerader))) Masquerader(vm, structure);
229         result->finishCreation(vm);
230         return result;
231     }
232
233     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
234     {
235         return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
236     }
237
238     DECLARE_INFO;
239 };
240
241 class Root : public JSDestructibleObject {
242 public:
243     Root(VM& vm, Structure* structure)
244         : Base(vm, structure)
245     {
246     }
247
248     Element* element()
249     {
250         return m_element.get();
251     }
252
253     void setElement(Element* element)
254     {
255         Weak<Element> newElement(element, Element::handleOwner());
256         m_element.swap(newElement);
257     }
258
259     static Root* create(VM& vm, JSGlobalObject* globalObject)
260     {
261         Structure* structure = createStructure(vm, globalObject, jsNull());
262         Root* root = new (NotNull, allocateCell<Root>(vm.heap, sizeof(Root))) Root(vm, structure);
263         root->finishCreation(vm);
264         return root;
265     }
266
267     typedef JSDestructibleObject Base;
268
269     DECLARE_INFO;
270
271     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
272     {
273         return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
274     }
275
276     static void visitChildren(JSCell* thisObject, SlotVisitor& visitor)
277     {
278         Base::visitChildren(thisObject, visitor);
279         visitor.addOpaqueRoot(thisObject);
280     }
281
282 private:
283     Weak<Element> m_element;
284 };
285
286 class ImpureGetter : public JSNonFinalObject {
287 public:
288     ImpureGetter(VM& vm, Structure* structure)
289         : Base(vm, structure)
290     {
291     }
292
293     DECLARE_INFO;
294     typedef JSNonFinalObject Base;
295     static const unsigned StructureFlags = Base::StructureFlags | JSC::GetOwnPropertySlotIsImpure | JSC::OverridesGetOwnPropertySlot;
296
297     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
298     {
299         return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
300     }
301
302     static ImpureGetter* create(VM& vm, Structure* structure, JSObject* delegate)
303     {
304         ImpureGetter* getter = new (NotNull, allocateCell<ImpureGetter>(vm.heap, sizeof(ImpureGetter))) ImpureGetter(vm, structure);
305         getter->finishCreation(vm, delegate);
306         return getter;
307     }
308
309     void finishCreation(VM& vm, JSObject* delegate)
310     {
311         Base::finishCreation(vm);
312         if (delegate)
313             m_delegate.set(vm, this, delegate);
314     }
315
316     static bool getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName name, PropertySlot& slot)
317     {
318         VM& vm = exec->vm();
319         auto scope = DECLARE_THROW_SCOPE(vm);
320         ImpureGetter* thisObject = jsCast<ImpureGetter*>(object);
321         
322         if (thisObject->m_delegate) {
323             if (thisObject->m_delegate->getPropertySlot(exec, name, slot))
324                 return true;
325             RETURN_IF_EXCEPTION(scope, false);
326         }
327
328         return Base::getOwnPropertySlot(object, exec, name, slot);
329     }
330
331     static void visitChildren(JSCell* cell, SlotVisitor& visitor)
332     {
333         Base::visitChildren(cell, visitor);
334         ImpureGetter* thisObject = jsCast<ImpureGetter*>(cell);
335         visitor.append(thisObject->m_delegate);
336     }
337
338     void setDelegate(VM& vm, JSObject* delegate)
339     {
340         m_delegate.set(vm, this, delegate);
341     }
342
343 private:
344     WriteBarrier<JSObject> m_delegate;
345 };
346
347 class CustomGetter : public JSNonFinalObject {
348 public:
349     CustomGetter(VM& vm, Structure* structure)
350         : Base(vm, structure)
351     {
352     }
353
354     DECLARE_INFO;
355     typedef JSNonFinalObject Base;
356     static const unsigned StructureFlags = Base::StructureFlags | JSC::OverridesGetOwnPropertySlot;
357
358     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
359     {
360         return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
361     }
362
363     static CustomGetter* create(VM& vm, Structure* structure)
364     {
365         CustomGetter* getter = new (NotNull, allocateCell<CustomGetter>(vm.heap, sizeof(CustomGetter))) CustomGetter(vm, structure);
366         getter->finishCreation(vm);
367         return getter;
368     }
369
370     static bool getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
371     {
372         CustomGetter* thisObject = jsCast<CustomGetter*>(object);
373         if (propertyName == PropertyName(Identifier::fromString(exec, "customGetter"))) {
374             slot.setCacheableCustom(thisObject, DontDelete | ReadOnly | DontEnum, thisObject->customGetter);
375             return true;
376         }
377         
378         if (propertyName == PropertyName(Identifier::fromString(exec, "customGetterAccessor"))) {
379             slot.setCacheableCustom(thisObject, DontDelete | ReadOnly | DontEnum | CustomAccessor, thisObject->customGetterAcessor);
380             return true;
381         }
382         
383         return JSObject::getOwnPropertySlot(thisObject, exec, propertyName, slot);
384     }
385
386 private:
387     static EncodedJSValue customGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName)
388     {
389         VM& vm = exec->vm();
390         auto scope = DECLARE_THROW_SCOPE(vm);
391
392         CustomGetter* thisObject = jsDynamicCast<CustomGetter*>(vm, JSValue::decode(thisValue));
393         if (!thisObject)
394             return throwVMTypeError(exec, scope);
395         bool shouldThrow = thisObject->get(exec, PropertyName(Identifier::fromString(exec, "shouldThrow"))).toBoolean(exec);
396         RETURN_IF_EXCEPTION(scope, encodedJSValue());
397         if (shouldThrow)
398             return throwVMTypeError(exec, scope);
399         return JSValue::encode(jsNumber(100));
400     }
401     
402     static EncodedJSValue customGetterAcessor(ExecState* exec, EncodedJSValue thisValue, PropertyName)
403     {
404         VM& vm = exec->vm();
405         auto scope = DECLARE_THROW_SCOPE(vm);
406         
407         JSObject* thisObject = jsDynamicCast<JSObject*>(vm, JSValue::decode(thisValue));
408         if (!thisObject)
409             return throwVMTypeError(exec, scope);
410         bool shouldThrow = thisObject->get(exec, PropertyName(Identifier::fromString(exec, "shouldThrow"))).toBoolean(exec);
411         if (shouldThrow)
412             return throwVMTypeError(exec, scope);
413         return JSValue::encode(jsNumber(100));
414     }
415 };
416
417 class RuntimeArray : public JSArray {
418 public:
419     typedef JSArray Base;
420     static const unsigned StructureFlags = Base::StructureFlags | OverridesGetOwnPropertySlot | InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero | OverridesGetPropertyNames;
421
422     static RuntimeArray* create(ExecState* exec)
423     {
424         VM& vm = exec->vm();
425         JSGlobalObject* globalObject = exec->lexicalGlobalObject();
426         Structure* structure = createStructure(vm, globalObject, createPrototype(vm, globalObject));
427         RuntimeArray* runtimeArray = new (NotNull, allocateCell<RuntimeArray>(*exec->heap())) RuntimeArray(exec, structure);
428         runtimeArray->finishCreation(exec);
429         vm.heap.addFinalizer(runtimeArray, destroy);
430         return runtimeArray;
431     }
432
433     ~RuntimeArray() { }
434
435     static void destroy(JSCell* cell)
436     {
437         static_cast<RuntimeArray*>(cell)->RuntimeArray::~RuntimeArray();
438     }
439
440     static const bool needsDestruction = false;
441
442     static bool getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
443     {
444         RuntimeArray* thisObject = jsCast<RuntimeArray*>(object);
445         if (propertyName == exec->propertyNames().length) {
446             slot.setCacheableCustom(thisObject, DontDelete | ReadOnly | DontEnum, thisObject->lengthGetter);
447             return true;
448         }
449
450         std::optional<uint32_t> index = parseIndex(propertyName);
451         if (index && index.value() < thisObject->getLength()) {
452             slot.setValue(thisObject, DontDelete | DontEnum, jsNumber(thisObject->m_vector[index.value()]));
453             return true;
454         }
455
456         return JSObject::getOwnPropertySlot(thisObject, exec, propertyName, slot);
457     }
458
459     static bool getOwnPropertySlotByIndex(JSObject* object, ExecState* exec, unsigned index, PropertySlot& slot)
460     {
461         RuntimeArray* thisObject = jsCast<RuntimeArray*>(object);
462         if (index < thisObject->getLength()) {
463             slot.setValue(thisObject, DontDelete | DontEnum, jsNumber(thisObject->m_vector[index]));
464             return true;
465         }
466
467         return JSObject::getOwnPropertySlotByIndex(thisObject, exec, index, slot);
468     }
469
470     static NO_RETURN_DUE_TO_CRASH bool put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&)
471     {
472         RELEASE_ASSERT_NOT_REACHED();
473     }
474
475     static NO_RETURN_DUE_TO_CRASH bool deleteProperty(JSCell*, ExecState*, PropertyName)
476     {
477         RELEASE_ASSERT_NOT_REACHED();
478     }
479
480     unsigned getLength() const { return m_vector.size(); }
481
482     DECLARE_INFO;
483
484     static ArrayPrototype* createPrototype(VM&, JSGlobalObject* globalObject)
485     {
486         return globalObject->arrayPrototype();
487     }
488
489     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
490     {
491         return Structure::create(vm, globalObject, prototype, TypeInfo(DerivedArrayType, StructureFlags), info(), ArrayClass);
492     }
493
494 protected:
495     void finishCreation(ExecState* exec)
496     {
497         VM& vm = exec->vm();
498         Base::finishCreation(vm);
499         ASSERT(inherits(vm, info()));
500
501         for (size_t i = 0; i < exec->argumentCount(); i++)
502             m_vector.append(exec->argument(i).toInt32(exec));
503     }
504
505 private:
506     RuntimeArray(ExecState* exec, Structure* structure)
507         : JSArray(exec->vm(), structure, 0)
508     {
509     }
510
511     static EncodedJSValue lengthGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName)
512     {
513         VM& vm = exec->vm();
514         auto scope = DECLARE_THROW_SCOPE(vm);
515
516         RuntimeArray* thisObject = jsDynamicCast<RuntimeArray*>(vm, JSValue::decode(thisValue));
517         if (!thisObject)
518             return throwVMTypeError(exec, scope);
519         return JSValue::encode(jsNumber(thisObject->getLength()));
520     }
521
522     Vector<int> m_vector;
523 };
524
525 class SimpleObject : public JSNonFinalObject {
526 public:
527     SimpleObject(VM& vm, Structure* structure)
528         : Base(vm, structure)
529     {
530     }
531
532     typedef JSNonFinalObject Base;
533     static const bool needsDestruction = false;
534
535     static SimpleObject* create(VM& vm, JSGlobalObject* globalObject)
536     {
537         Structure* structure = createStructure(vm, globalObject, jsNull());
538         SimpleObject* simpleObject = new (NotNull, allocateCell<SimpleObject>(vm.heap, sizeof(SimpleObject))) SimpleObject(vm, structure);
539         simpleObject->finishCreation(vm);
540         return simpleObject;
541     }
542
543     static void visitChildren(JSCell* cell, SlotVisitor& visitor)
544     {
545         SimpleObject* thisObject = jsCast<SimpleObject*>(cell);
546         ASSERT_GC_OBJECT_INHERITS(thisObject, info());
547         Base::visitChildren(thisObject, visitor);
548         visitor.append(thisObject->m_hiddenValue);
549     }
550
551     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
552     {
553         return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
554     }
555
556     JSValue hiddenValue()
557     {
558         return m_hiddenValue.get();
559     }
560
561     void setHiddenValue(VM& vm, JSValue value)
562     {
563         ASSERT(value.isCell());
564         m_hiddenValue.set(vm, this, value);
565     }
566
567     DECLARE_INFO;
568
569 private:
570     WriteBarrier<JSC::Unknown> m_hiddenValue;
571 };
572
573 class DOMJITNode : public JSNonFinalObject {
574 public:
575     DOMJITNode(VM& vm, Structure* structure)
576         : Base(vm, structure)
577     {
578     }
579
580     DECLARE_INFO;
581     typedef JSNonFinalObject Base;
582     static const unsigned StructureFlags = Base::StructureFlags;
583
584     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
585     {
586         return Structure::create(vm, globalObject, prototype, TypeInfo(JSC::JSType(LastJSCObjectType + 1), StructureFlags), info());
587     }
588
589 #if ENABLE(JIT)
590     static Ref<Snippet> checkSubClassSnippet()
591     {
592         Ref<Snippet> snippet = Snippet::create();
593         snippet->setGenerator([=](CCallHelpers& jit, SnippetParams& params) {
594             CCallHelpers::JumpList failureCases;
595             failureCases.append(jit.branch8(
596                 CCallHelpers::NotEqual,
597                 CCallHelpers::Address(params[0].gpr(), JSCell::typeInfoTypeOffset()),
598                 CCallHelpers::TrustedImm32(JSC::JSType(LastJSCObjectType + 1))));
599             return failureCases;
600         });
601         return snippet;
602     }
603 #endif
604
605     static DOMJITNode* create(VM& vm, Structure* structure)
606     {
607         DOMJITNode* getter = new (NotNull, allocateCell<DOMJITNode>(vm.heap, sizeof(DOMJITNode))) DOMJITNode(vm, structure);
608         getter->finishCreation(vm);
609         return getter;
610     }
611
612     int32_t value() const
613     {
614         return m_value;
615     }
616
617     static ptrdiff_t offsetOfValue() { return OBJECT_OFFSETOF(DOMJITNode, m_value); }
618
619 private:
620     int32_t m_value { 42 };
621 };
622
623 class DOMJITGetter : public DOMJITNode {
624 public:
625     DOMJITGetter(VM& vm, Structure* structure)
626         : Base(vm, structure)
627     {
628     }
629
630     DECLARE_INFO;
631     typedef DOMJITNode Base;
632     static const unsigned StructureFlags = Base::StructureFlags;
633
634     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
635     {
636         return Structure::create(vm, globalObject, prototype, TypeInfo(JSC::JSType(LastJSCObjectType + 1), StructureFlags), info());
637     }
638
639     static DOMJITGetter* create(VM& vm, Structure* structure)
640     {
641         DOMJITGetter* getter = new (NotNull, allocateCell<DOMJITGetter>(vm.heap, sizeof(DOMJITGetter))) DOMJITGetter(vm, structure);
642         getter->finishCreation(vm);
643         return getter;
644     }
645
646     class DOMJITNodeDOMJIT : public DOMJIT::GetterSetter {
647     public:
648         DOMJITNodeDOMJIT()
649             : DOMJIT::GetterSetter(DOMJITGetter::customGetter, nullptr, DOMJITNode::info(), SpecInt32Only)
650         {
651         }
652
653 #if ENABLE(JIT)
654         static EncodedJSValue JIT_OPERATION slowCall(ExecState* exec, void* pointer)
655         {
656             NativeCallFrameTracer tracer(&exec->vm(), exec);
657             return JSValue::encode(jsNumber(static_cast<DOMJITGetter*>(pointer)->value()));
658         }
659
660         Ref<DOMJIT::CallDOMGetterSnippet> callDOMGetter() override
661         {
662             Ref<DOMJIT::CallDOMGetterSnippet> snippet = DOMJIT::CallDOMGetterSnippet::create();
663             snippet->requireGlobalObject = false;
664             snippet->setGenerator([=](CCallHelpers& jit, SnippetParams& params) {
665                 JSValueRegs results = params[0].jsValueRegs();
666                 GPRReg dom = params[1].gpr();
667                 params.addSlowPathCall(jit.jump(), jit, slowCall, results, dom);
668                 return CCallHelpers::JumpList();
669
670             });
671             return snippet;
672         }
673 #endif
674     };
675
676     static DOMJIT::GetterSetter* domJITNodeGetterSetter()
677     {
678         static NeverDestroyed<DOMJITNodeDOMJIT> graph;
679         return &graph.get();
680     }
681
682 private:
683     void finishCreation(VM& vm)
684     {
685         Base::finishCreation(vm);
686         DOMJIT::GetterSetter* domJIT = domJITNodeGetterSetter();
687         CustomGetterSetter* customGetterSetter = CustomGetterSetter::create(vm, domJIT->getter(), domJIT->setter(), domJIT);
688         putDirectCustomAccessor(vm, Identifier::fromString(&vm, "customGetter"), customGetterSetter, ReadOnly | CustomAccessor);
689     }
690
691     static EncodedJSValue customGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName)
692     {
693         VM& vm = exec->vm();
694         auto scope = DECLARE_THROW_SCOPE(vm);
695
696         DOMJITNode* thisObject = jsDynamicCast<DOMJITNode*>(vm, JSValue::decode(thisValue));
697         if (!thisObject)
698             return throwVMTypeError(exec, scope);
699         return JSValue::encode(jsNumber(thisObject->value()));
700     }
701 };
702
703 class DOMJITGetterComplex : public DOMJITNode {
704 public:
705     DOMJITGetterComplex(VM& vm, Structure* structure)
706         : Base(vm, structure)
707     {
708     }
709
710     DECLARE_INFO;
711     typedef DOMJITNode Base;
712     static const unsigned StructureFlags = Base::StructureFlags;
713
714     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
715     {
716         return Structure::create(vm, globalObject, prototype, TypeInfo(JSC::JSType(LastJSCObjectType + 1), StructureFlags), info());
717     }
718
719     static DOMJITGetterComplex* create(VM& vm, JSGlobalObject* globalObject, Structure* structure)
720     {
721         DOMJITGetterComplex* getter = new (NotNull, allocateCell<DOMJITGetterComplex>(vm.heap, sizeof(DOMJITGetterComplex))) DOMJITGetterComplex(vm, structure);
722         getter->finishCreation(vm, globalObject);
723         return getter;
724     }
725
726     class DOMJITNodeDOMJIT : public DOMJIT::GetterSetter {
727     public:
728         DOMJITNodeDOMJIT()
729             : DOMJIT::GetterSetter(DOMJITGetterComplex::customGetter, nullptr, DOMJITNode::info(), SpecInt32Only)
730         {
731         }
732
733 #if ENABLE(JIT)
734         static EncodedJSValue JIT_OPERATION slowCall(ExecState* exec, void* pointer)
735         {
736             VM& vm = exec->vm();
737             NativeCallFrameTracer tracer(&vm, exec);
738             auto scope = DECLARE_THROW_SCOPE(vm);
739             auto* object = static_cast<DOMJITNode*>(pointer);
740             auto* domjitGetterComplex = jsDynamicCast<DOMJITGetterComplex*>(vm, object);
741             if (domjitGetterComplex) {
742                 if (domjitGetterComplex->m_enableException)
743                     return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("DOMJITGetterComplex slow call exception"))));
744             }
745             return JSValue::encode(jsNumber(object->value()));
746         }
747
748         Ref<DOMJIT::CallDOMGetterSnippet> callDOMGetter() override
749         {
750             RefPtr<DOMJIT::CallDOMGetterSnippet> snippet = DOMJIT::CallDOMGetterSnippet::create();
751             static_assert(GPRInfo::numberOfRegisters >= 4, "Number of registers should be larger or equal to 4.");
752             snippet->numGPScratchRegisters = GPRInfo::numberOfRegisters - 4;
753             snippet->numFPScratchRegisters = 3;
754             snippet->setGenerator([=](CCallHelpers& jit, SnippetParams& params) {
755                 JSValueRegs results = params[0].jsValueRegs();
756                 GPRReg domGPR = params[1].gpr();
757                 for (unsigned i = 0; i < snippet->numGPScratchRegisters; ++i)
758                     jit.move(CCallHelpers::TrustedImm32(42), params.gpScratch(i));
759
760                 params.addSlowPathCall(jit.jump(), jit, slowCall, results, domGPR);
761                 return CCallHelpers::JumpList();
762
763             });
764             return *snippet.get();
765         }
766 #endif
767     };
768
769     static DOMJIT::GetterSetter* domJITNodeGetterSetter()
770     {
771         static NeverDestroyed<DOMJITNodeDOMJIT> graph;
772         return &graph.get();
773     }
774
775 private:
776     void finishCreation(VM& vm, JSGlobalObject* globalObject)
777     {
778         Base::finishCreation(vm);
779         DOMJIT::GetterSetter* domJIT = domJITNodeGetterSetter();
780         CustomGetterSetter* customGetterSetter = CustomGetterSetter::create(vm, domJIT->getter(), domJIT->setter(), domJIT);
781         putDirectCustomAccessor(vm, Identifier::fromString(&vm, "customGetter"), customGetterSetter, ReadOnly | CustomAccessor);
782         putDirectNativeFunction(vm, globalObject, Identifier::fromString(&vm, "enableException"), 0, functionEnableException, NoIntrinsic, 0);
783     }
784
785     static EncodedJSValue JSC_HOST_CALL functionEnableException(ExecState* exec)
786     {
787         VM& vm = exec->vm();
788         auto* object = jsDynamicCast<DOMJITGetterComplex*>(vm, exec->thisValue());
789         if (object)
790             object->m_enableException = true;
791         return JSValue::encode(jsUndefined());
792     }
793
794     static EncodedJSValue customGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName)
795     {
796         VM& vm = exec->vm();
797         auto scope = DECLARE_THROW_SCOPE(vm);
798
799         auto* thisObject = jsDynamicCast<DOMJITNode*>(vm, JSValue::decode(thisValue));
800         if (!thisObject)
801             return throwVMTypeError(exec, scope);
802         if (auto* domjitGetterComplex = jsDynamicCast<DOMJITGetterComplex*>(vm, JSValue::decode(thisValue))) {
803             if (domjitGetterComplex->m_enableException)
804                 return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("DOMJITGetterComplex slow call exception"))));
805         }
806         return JSValue::encode(jsNumber(thisObject->value()));
807     }
808
809     bool m_enableException { false };
810 };
811
812 class DOMJITFunctionObject : public DOMJITNode {
813 public:
814     DOMJITFunctionObject(VM& vm, Structure* structure)
815         : Base(vm, structure)
816     {
817     }
818
819     DECLARE_INFO;
820     typedef DOMJITNode Base;
821     static const unsigned StructureFlags = Base::StructureFlags;
822
823
824     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
825     {
826         return Structure::create(vm, globalObject, prototype, TypeInfo(JSC::JSType(LastJSCObjectType + 1), StructureFlags), info());
827     }
828
829     static DOMJITFunctionObject* create(VM& vm, JSGlobalObject* globalObject, Structure* structure)
830     {
831         DOMJITFunctionObject* object = new (NotNull, allocateCell<DOMJITFunctionObject>(vm.heap, sizeof(DOMJITFunctionObject))) DOMJITFunctionObject(vm, structure);
832         object->finishCreation(vm, globalObject);
833         return object;
834     }
835
836     static EncodedJSValue JSC_HOST_CALL safeFunction(ExecState* exec)
837     {
838         VM& vm = exec->vm();
839         auto scope = DECLARE_THROW_SCOPE(vm);
840
841         DOMJITNode* thisObject = jsDynamicCast<DOMJITNode*>(vm, exec->thisValue());
842         if (!thisObject)
843             return throwVMTypeError(exec, scope);
844         return JSValue::encode(jsNumber(thisObject->value()));
845     }
846
847     static EncodedJSValue JIT_OPERATION unsafeFunction(ExecState* exec, DOMJITNode* node)
848     {
849         NativeCallFrameTracer tracer(&exec->vm(), exec);
850         return JSValue::encode(jsNumber(node->value()));
851     }
852
853 #if ENABLE(JIT)
854     static Ref<Snippet> checkSubClassSnippet()
855     {
856         Ref<Snippet> snippet = Snippet::create();
857         snippet->numFPScratchRegisters = 1;
858         snippet->setGenerator([=](CCallHelpers& jit, SnippetParams& params) {
859             static const double value = 42.0;
860             CCallHelpers::JumpList failureCases;
861             // May use scratch registers.
862             jit.loadDouble(CCallHelpers::TrustedImmPtr(&value), params.fpScratch(0));
863             failureCases.append(jit.branch8(
864                 CCallHelpers::NotEqual,
865                 CCallHelpers::Address(params[0].gpr(), JSCell::typeInfoTypeOffset()),
866                 CCallHelpers::TrustedImm32(JSC::JSType(LastJSCObjectType + 1))));
867             return failureCases;
868         });
869         return snippet;
870     }
871 #endif
872
873 private:
874     void finishCreation(VM&, JSGlobalObject*);
875 };
876
877 static const DOMJIT::Signature DOMJITFunctionObjectSignature((uintptr_t)DOMJITFunctionObject::unsafeFunction, DOMJITFunctionObject::info(), DOMJIT::Effect::forRead(DOMJIT::HeapRange::top()), SpecInt32Only);
878
879 void DOMJITFunctionObject::finishCreation(VM& vm, JSGlobalObject* globalObject)
880 {
881     Base::finishCreation(vm);
882     putDirectNativeFunction(vm, globalObject, Identifier::fromString(&vm, "func"), 0, safeFunction, NoIntrinsic, &DOMJITFunctionObjectSignature, ReadOnly);
883 }
884
885 class DOMJITCheckSubClassObject : public DOMJITNode {
886 public:
887     DOMJITCheckSubClassObject(VM& vm, Structure* structure)
888         : Base(vm, structure)
889     {
890     }
891
892     DECLARE_INFO;
893     typedef DOMJITNode Base;
894     static const unsigned StructureFlags = Base::StructureFlags;
895
896
897     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
898     {
899         return Structure::create(vm, globalObject, prototype, TypeInfo(JSC::JSType(LastJSCObjectType + 1), StructureFlags), info());
900     }
901
902     static DOMJITCheckSubClassObject* create(VM& vm, JSGlobalObject* globalObject, Structure* structure)
903     {
904         DOMJITCheckSubClassObject* object = new (NotNull, allocateCell<DOMJITCheckSubClassObject>(vm.heap, sizeof(DOMJITCheckSubClassObject))) DOMJITCheckSubClassObject(vm, structure);
905         object->finishCreation(vm, globalObject);
906         return object;
907     }
908
909     static EncodedJSValue JSC_HOST_CALL safeFunction(ExecState* exec)
910     {
911         VM& vm = exec->vm();
912         auto scope = DECLARE_THROW_SCOPE(vm);
913
914         auto* thisObject = jsDynamicCast<DOMJITCheckSubClassObject*>(vm, exec->thisValue());
915         if (!thisObject)
916             return throwVMTypeError(exec, scope);
917         return JSValue::encode(jsNumber(thisObject->value()));
918     }
919
920     static EncodedJSValue JIT_OPERATION unsafeFunction(ExecState* exec, DOMJITNode* node)
921     {
922         NativeCallFrameTracer tracer(&exec->vm(), exec);
923         return JSValue::encode(jsNumber(node->value()));
924     }
925
926 private:
927     void finishCreation(VM&, JSGlobalObject*);
928 };
929
930 static const DOMJIT::Signature DOMJITCheckSubClassObjectSignature((uintptr_t)DOMJITCheckSubClassObject::unsafeFunction, DOMJITCheckSubClassObject::info(), DOMJIT::Effect::forRead(DOMJIT::HeapRange::top()), SpecInt32Only);
931
932 void DOMJITCheckSubClassObject::finishCreation(VM& vm, JSGlobalObject* globalObject)
933 {
934     Base::finishCreation(vm);
935     putDirectNativeFunction(vm, globalObject, Identifier::fromString(&vm, "func"), 0, safeFunction, NoIntrinsic, &DOMJITCheckSubClassObjectSignature, ReadOnly);
936 }
937
938 const ClassInfo Element::s_info = { "Element", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(Element) };
939 const ClassInfo Masquerader::s_info = { "Masquerader", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(Masquerader) };
940 const ClassInfo Root::s_info = { "Root", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(Root) };
941 const ClassInfo ImpureGetter::s_info = { "ImpureGetter", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ImpureGetter) };
942 const ClassInfo CustomGetter::s_info = { "CustomGetter", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(CustomGetter) };
943 #if ENABLE(JIT)
944 const ClassInfo DOMJITNode::s_info = { "DOMJITNode", &Base::s_info, nullptr, &DOMJITNode::checkSubClassSnippet, CREATE_METHOD_TABLE(DOMJITNode) };
945 #else
946 const ClassInfo DOMJITNode::s_info = { "DOMJITNode", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(DOMJITNode) };
947 #endif
948 const ClassInfo DOMJITGetter::s_info = { "DOMJITGetter", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(DOMJITGetter) };
949 const ClassInfo DOMJITGetterComplex::s_info = { "DOMJITGetterComplex", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(DOMJITGetterComplex) };
950 #if ENABLE(JIT)
951 const ClassInfo DOMJITFunctionObject::s_info = { "DOMJITFunctionObject", &Base::s_info, nullptr, &DOMJITFunctionObject::checkSubClassSnippet, CREATE_METHOD_TABLE(DOMJITFunctionObject) };
952 #else
953 const ClassInfo DOMJITFunctionObject::s_info = { "DOMJITFunctionObject", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(DOMJITFunctionObject) };
954 #endif
955 const ClassInfo DOMJITCheckSubClassObject::s_info = { "DOMJITCheckSubClassObject", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(DOMJITCheckSubClassObject) };
956 const ClassInfo RuntimeArray::s_info = { "RuntimeArray", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(RuntimeArray) };
957 const ClassInfo SimpleObject::s_info = { "SimpleObject", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(SimpleObject) };
958 static unsigned asyncTestPasses { 0 };
959 static unsigned asyncTestExpectedPasses { 0 };
960
961 ElementHandleOwner* Element::handleOwner()
962 {
963     static ElementHandleOwner* owner = 0;
964     if (!owner)
965         owner = new ElementHandleOwner();
966     return owner;
967 }
968
969 void Element::finishCreation(VM& vm, Root* root)
970 {
971     Base::finishCreation(vm);
972     setRoot(vm, root);
973     m_root->setElement(this);
974 }
975
976 }
977
978 static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer);
979
980 class CommandLine;
981 class GlobalObject;
982 class Workers;
983
984 template<typename Func>
985 int runJSC(CommandLine, bool isWorker, const Func&);
986 static void checkException(GlobalObject*, bool isLastFile, bool hasException, JSValue, const String& uncaughtExceptionName, bool alwaysDumpUncaughtException, bool dump, bool& success);
987
988 class Message : public ThreadSafeRefCounted<Message> {
989 public:
990     Message(ArrayBufferContents&&, int32_t);
991     ~Message();
992     
993     ArrayBufferContents&& releaseContents() { return WTFMove(m_contents); }
994     int32_t index() const { return m_index; }
995
996 private:
997     ArrayBufferContents m_contents;
998     int32_t m_index { 0 };
999 };
1000
1001 class Worker : public BasicRawSentinelNode<Worker> {
1002 public:
1003     Worker(Workers&);
1004     ~Worker();
1005     
1006     void enqueue(const AbstractLocker&, RefPtr<Message>);
1007     RefPtr<Message> dequeue();
1008     
1009     static Worker& current();
1010
1011 private:
1012     static ThreadSpecific<Worker*>& currentWorker();
1013
1014     Workers& m_workers;
1015     Deque<RefPtr<Message>> m_messages;
1016 };
1017
1018 class Workers {
1019 public:
1020     Workers();
1021     ~Workers();
1022     
1023     template<typename Func>
1024     void broadcast(const Func&);
1025     
1026     void report(String);
1027     String tryGetReport();
1028     String getReport();
1029     
1030     static Workers& singleton();
1031     
1032 private:
1033     friend class Worker;
1034     
1035     Lock m_lock;
1036     Condition m_condition;
1037     SentinelLinkedList<Worker, BasicRawSentinelNode<Worker>> m_workers;
1038     Deque<String> m_reports;
1039 };
1040
1041 static EncodedJSValue JSC_HOST_CALL functionCreateProxy(ExecState*);
1042 static EncodedJSValue JSC_HOST_CALL functionCreateRuntimeArray(ExecState*);
1043 static EncodedJSValue JSC_HOST_CALL functionCreateImpureGetter(ExecState*);
1044 static EncodedJSValue JSC_HOST_CALL functionCreateCustomGetterObject(ExecState*);
1045 static EncodedJSValue JSC_HOST_CALL functionCreateDOMJITNodeObject(ExecState*);
1046 static EncodedJSValue JSC_HOST_CALL functionCreateDOMJITGetterObject(ExecState*);
1047 static EncodedJSValue JSC_HOST_CALL functionCreateDOMJITGetterComplexObject(ExecState*);
1048 static EncodedJSValue JSC_HOST_CALL functionCreateDOMJITFunctionObject(ExecState*);
1049 static EncodedJSValue JSC_HOST_CALL functionCreateDOMJITCheckSubClassObject(ExecState*);
1050 static EncodedJSValue JSC_HOST_CALL functionCreateBuiltin(ExecState*);
1051 static EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState*);
1052 static EncodedJSValue JSC_HOST_CALL functionSetImpureGetterDelegate(ExecState*);
1053
1054 static EncodedJSValue JSC_HOST_CALL functionSetElementRoot(ExecState*);
1055 static EncodedJSValue JSC_HOST_CALL functionCreateRoot(ExecState*);
1056 static EncodedJSValue JSC_HOST_CALL functionCreateElement(ExecState*);
1057 static EncodedJSValue JSC_HOST_CALL functionGetElement(ExecState*);
1058 static EncodedJSValue JSC_HOST_CALL functionCreateSimpleObject(ExecState*);
1059 static EncodedJSValue JSC_HOST_CALL functionGetHiddenValue(ExecState*);
1060 static EncodedJSValue JSC_HOST_CALL functionSetHiddenValue(ExecState*);
1061 static EncodedJSValue JSC_HOST_CALL functionPrintStdOut(ExecState*);
1062 static EncodedJSValue JSC_HOST_CALL functionPrintStdErr(ExecState*);
1063 static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
1064 static EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState*);
1065 static EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState*);
1066 static EncodedJSValue JSC_HOST_CALL functionSleepSeconds(ExecState*);
1067 static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
1068 static EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState*);
1069 static EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState*);
1070 static EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState*);
1071 static EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*);
1072 static EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState*);
1073 static EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState*);
1074 static EncodedJSValue JSC_HOST_CALL functionGetGetterSetter(ExecState*);
1075 #ifndef NDEBUG
1076 static EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState*);
1077 #endif
1078 static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
1079 static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
1080 static EncodedJSValue JSC_HOST_CALL functionRunString(ExecState*);
1081 static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
1082 static EncodedJSValue JSC_HOST_CALL functionLoadString(ExecState*);
1083 static EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState*);
1084 static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
1085 static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
1086 static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
1087 static EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState*);
1088 static EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState*);
1089 static EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState*);
1090 static EncodedJSValue JSC_HOST_CALL functionNoOSRExitFuzzing(ExecState*);
1091 static EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState*);
1092 static EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState*);
1093 static EncodedJSValue JSC_HOST_CALL functionJSCOptions(ExecState*);
1094 static EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState*);
1095 static EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState*);
1096 static EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState*);
1097 static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
1098 static NO_RETURN_DUE_TO_CRASH EncodedJSValue JSC_HOST_CALL functionAbort(ExecState*);
1099 static EncodedJSValue JSC_HOST_CALL functionFalse1(ExecState*);
1100 static EncodedJSValue JSC_HOST_CALL functionFalse2(ExecState*);
1101 static EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*);
1102 static EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*);
1103 static EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState*);
1104 static EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*);
1105 static EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState*);
1106 static EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState*);
1107 static EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState*);
1108 static EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState*);
1109 static EncodedJSValue JSC_HOST_CALL functionFindTypeForExpression(ExecState*);
1110 static EncodedJSValue JSC_HOST_CALL functionReturnTypeFor(ExecState*);
1111 static EncodedJSValue JSC_HOST_CALL functionDumpBasicBlockExecutionRanges(ExecState*);
1112 static EncodedJSValue JSC_HOST_CALL functionHasBasicBlockExecuted(ExecState*);
1113 static EncodedJSValue JSC_HOST_CALL functionBasicBlockExecutionCount(ExecState*);
1114 static EncodedJSValue JSC_HOST_CALL functionEnableExceptionFuzz(ExecState*);
1115 static EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState*);
1116 static EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*);
1117 static EncodedJSValue JSC_HOST_CALL functionLoadModule(ExecState*);
1118 static EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState*);
1119 static EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*);
1120 static EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState*);
1121 static EncodedJSValue JSC_HOST_CALL functionResetSuperSamplerState(ExecState*);
1122 static EncodedJSValue JSC_HOST_CALL functionEnsureArrayStorage(ExecState*);
1123 #if ENABLE(SAMPLING_PROFILER)
1124 static EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState*);
1125 static EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState*);
1126 #endif
1127
1128 static EncodedJSValue JSC_HOST_CALL functionMaxArguments(ExecState*);
1129 static EncodedJSValue JSC_HOST_CALL functionAsyncTestStart(ExecState*);
1130 static EncodedJSValue JSC_HOST_CALL functionAsyncTestPassed(ExecState*);
1131
1132 #if ENABLE(WEBASSEMBLY)
1133 static EncodedJSValue JSC_HOST_CALL functionWebAssemblyMemoryMode(ExecState*);
1134 #endif
1135
1136 #if ENABLE(SAMPLING_FLAGS)
1137 static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
1138 static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
1139 #endif
1140
1141 static EncodedJSValue JSC_HOST_CALL functionShadowChickenFunctionsOnStack(ExecState*);
1142 static EncodedJSValue JSC_HOST_CALL functionSetGlobalConstRedeclarationShouldNotThrow(ExecState*);
1143 static EncodedJSValue JSC_HOST_CALL functionGetRandomSeed(ExecState*);
1144 static EncodedJSValue JSC_HOST_CALL functionSetRandomSeed(ExecState*);
1145 static EncodedJSValue JSC_HOST_CALL functionIsRope(ExecState*);
1146 static EncodedJSValue JSC_HOST_CALL functionCallerSourceOrigin(ExecState*);
1147 static EncodedJSValue JSC_HOST_CALL functionGlobalObjectForObject(ExecState*);
1148 static EncodedJSValue JSC_HOST_CALL functionDollarCreateRealm(ExecState*);
1149 static EncodedJSValue JSC_HOST_CALL functionDollarDetachArrayBuffer(ExecState*);
1150 static EncodedJSValue JSC_HOST_CALL functionDollarEvalScript(ExecState*);
1151 static EncodedJSValue JSC_HOST_CALL functionDollarAgentStart(ExecState*);
1152 static EncodedJSValue JSC_HOST_CALL functionDollarAgentReceiveBroadcast(ExecState*);
1153 static EncodedJSValue JSC_HOST_CALL functionDollarAgentReport(ExecState*);
1154 static EncodedJSValue JSC_HOST_CALL functionDollarAgentSleep(ExecState*);
1155 static EncodedJSValue JSC_HOST_CALL functionDollarAgentBroadcast(ExecState*);
1156 static EncodedJSValue JSC_HOST_CALL functionDollarAgentGetReport(ExecState*);
1157 static EncodedJSValue JSC_HOST_CALL functionDollarAgentLeaving(ExecState*);
1158 static EncodedJSValue JSC_HOST_CALL functionWaitForReport(ExecState*);
1159 static EncodedJSValue JSC_HOST_CALL functionHeapCapacity(ExecState*);
1160 static EncodedJSValue JSC_HOST_CALL functionFlashHeapAccess(ExecState*);
1161
1162 struct Script {
1163     enum class StrictMode {
1164         Strict,
1165         Sloppy
1166     };
1167
1168     enum class ScriptType {
1169         Script,
1170         Module
1171     };
1172
1173     enum class CodeSource {
1174         File,
1175         CommandLine
1176     };
1177
1178     StrictMode strictMode;
1179     CodeSource codeSource;
1180     ScriptType scriptType;
1181     char* argument;
1182
1183     Script(StrictMode strictMode, CodeSource codeSource, ScriptType scriptType, char *argument)
1184         : strictMode(strictMode)
1185         , codeSource(codeSource)
1186         , scriptType(scriptType)
1187         , argument(argument)
1188     {
1189         if (strictMode == StrictMode::Strict)
1190             ASSERT(codeSource == CodeSource::File);
1191     }
1192 };
1193
1194 class CommandLine {
1195 public:
1196     CommandLine(int argc, char** argv)
1197     {
1198         parseArguments(argc, argv);
1199     }
1200
1201     bool m_interactive { false };
1202     bool m_dump { false };
1203     bool m_module { false };
1204     bool m_exitCode { false };
1205     Vector<Script> m_scripts;
1206     Vector<String> m_arguments;
1207     bool m_profile { false };
1208     String m_profilerOutput;
1209     String m_uncaughtExceptionName;
1210     bool m_alwaysDumpUncaughtException { false };
1211     bool m_dumpSamplingProfilerData { false };
1212     bool m_enableRemoteDebugging { false };
1213
1214     void parseArguments(int, char**);
1215 };
1216
1217 static const char interactivePrompt[] = ">>> ";
1218
1219 class StopWatch {
1220 public:
1221     void start();
1222     void stop();
1223     long getElapsedMS(); // call stop() first
1224
1225 private:
1226     double m_startTime;
1227     double m_stopTime;
1228 };
1229
1230 void StopWatch::start()
1231 {
1232     m_startTime = monotonicallyIncreasingTime();
1233 }
1234
1235 void StopWatch::stop()
1236 {
1237     m_stopTime = monotonicallyIncreasingTime();
1238 }
1239
1240 long StopWatch::getElapsedMS()
1241 {
1242     return static_cast<long>((m_stopTime - m_startTime) * 1000);
1243 }
1244
1245 template<typename Vector>
1246 static inline String stringFromUTF(const Vector& utf8)
1247 {
1248     return String::fromUTF8WithLatin1Fallback(utf8.data(), utf8.size());
1249 }
1250
1251 template<typename Vector>
1252 static inline SourceCode jscSource(const Vector& utf8, const SourceOrigin& sourceOrigin, const String& filename)
1253 {
1254     String str = stringFromUTF(utf8);
1255     return makeSource(str, sourceOrigin, filename);
1256 }
1257
1258 class GlobalObject : public JSGlobalObject {
1259 private:
1260     GlobalObject(VM&, Structure*);
1261
1262 public:
1263     typedef JSGlobalObject Base;
1264
1265     static GlobalObject* create(VM& vm, Structure* structure, const Vector<String>& arguments)
1266     {
1267         GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(vm.heap)) GlobalObject(vm, structure);
1268         object->finishCreation(vm, arguments);
1269         return object;
1270     }
1271
1272     static const bool needsDestruction = false;
1273
1274     DECLARE_INFO;
1275     static const GlobalObjectMethodTable s_globalObjectMethodTable;
1276
1277     static Structure* createStructure(VM& vm, JSValue prototype)
1278     {
1279         return Structure::create(vm, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
1280     }
1281
1282     static RuntimeFlags javaScriptRuntimeFlags(const JSGlobalObject*) { return RuntimeFlags::createAllEnabled(); }
1283
1284 protected:
1285     void finishCreation(VM& vm, const Vector<String>& arguments)
1286     {
1287         Base::finishCreation(vm);
1288         
1289         addFunction(vm, "debug", functionDebug, 1);
1290         addFunction(vm, "describe", functionDescribe, 1);
1291         addFunction(vm, "describeArray", functionDescribeArray, 1);
1292         addFunction(vm, "print", functionPrintStdOut, 1);
1293         addFunction(vm, "printErr", functionPrintStdErr, 1);
1294         addFunction(vm, "quit", functionQuit, 0);
1295         addFunction(vm, "abort", functionAbort, 0);
1296         addFunction(vm, "gc", functionGCAndSweep, 0);
1297         addFunction(vm, "fullGC", functionFullGC, 0);
1298         addFunction(vm, "edenGC", functionEdenGC, 0);
1299         addFunction(vm, "forceGCSlowPaths", functionForceGCSlowPaths, 0);
1300         addFunction(vm, "gcHeapSize", functionHeapSize, 0);
1301         addFunction(vm, "addressOf", functionAddressOf, 1);
1302         addFunction(vm, "getGetterSetter", functionGetGetterSetter, 2);
1303 #ifndef NDEBUG
1304         addFunction(vm, "dumpCallFrame", functionDumpCallFrame, 0);
1305 #endif
1306         addFunction(vm, "version", functionVersion, 1);
1307         addFunction(vm, "run", functionRun, 1);
1308         addFunction(vm, "runString", functionRunString, 1);
1309         addFunction(vm, "load", functionLoad, 1);
1310         addFunction(vm, "loadString", functionLoadString, 1);
1311         addFunction(vm, "readFile", functionReadFile, 2);
1312         addFunction(vm, "read", functionReadFile, 2);
1313         addFunction(vm, "checkSyntax", functionCheckSyntax, 1);
1314         addFunction(vm, "sleepSeconds", functionSleepSeconds, 1);
1315         addFunction(vm, "jscStack", functionJSCStack, 1);
1316         addFunction(vm, "readline", functionReadline, 0);
1317         addFunction(vm, "preciseTime", functionPreciseTime, 0);
1318         addFunction(vm, "neverInlineFunction", functionNeverInlineFunction, 1);
1319         addFunction(vm, "noInline", functionNeverInlineFunction, 1);
1320         addFunction(vm, "noDFG", functionNoDFG, 1);
1321         addFunction(vm, "noFTL", functionNoFTL, 1);
1322         addFunction(vm, "noOSRExitFuzzing", functionNoOSRExitFuzzing, 1);
1323         addFunction(vm, "numberOfDFGCompiles", functionNumberOfDFGCompiles, 1);
1324         addFunction(vm, "jscOptions", functionJSCOptions, 0);
1325         addFunction(vm, "optimizeNextInvocation", functionOptimizeNextInvocation, 1);
1326         addFunction(vm, "reoptimizationRetryCount", functionReoptimizationRetryCount, 1);
1327         addFunction(vm, "transferArrayBuffer", functionTransferArrayBuffer, 1);
1328         addFunction(vm, "failNextNewCodeBlock", functionFailNextNewCodeBlock, 1);
1329 #if ENABLE(SAMPLING_FLAGS)
1330         addFunction(vm, "setSamplingFlags", functionSetSamplingFlags, 1);
1331         addFunction(vm, "clearSamplingFlags", functionClearSamplingFlags, 1);
1332 #endif
1333         addFunction(vm, "shadowChickenFunctionsOnStack", functionShadowChickenFunctionsOnStack, 0);
1334         addFunction(vm, "setGlobalConstRedeclarationShouldNotThrow", functionSetGlobalConstRedeclarationShouldNotThrow, 0);
1335         addConstructableFunction(vm, "Root", functionCreateRoot, 0);
1336         addConstructableFunction(vm, "Element", functionCreateElement, 1);
1337         addFunction(vm, "getElement", functionGetElement, 1);
1338         addFunction(vm, "setElementRoot", functionSetElementRoot, 2);
1339         
1340         addConstructableFunction(vm, "SimpleObject", functionCreateSimpleObject, 0);
1341         addFunction(vm, "getHiddenValue", functionGetHiddenValue, 1);
1342         addFunction(vm, "setHiddenValue", functionSetHiddenValue, 2);
1343         
1344         putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "DFGTrue"), 0, functionFalse1, DFGTrueIntrinsic, DontEnum);
1345         putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "OSRExit"), 0, functionUndefined1, OSRExitIntrinsic, DontEnum);
1346         putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isFinalTier"), 0, functionFalse2, IsFinalTierIntrinsic, DontEnum);
1347         putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "predictInt32"), 0, functionUndefined2, SetInt32HeapPredictionIntrinsic, DontEnum);
1348         putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isInt32"), 0, functionIsInt32, CheckInt32Intrinsic, DontEnum);
1349         putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "fiatInt52"), 0, functionIdentity, FiatInt52Intrinsic, DontEnum);
1350         
1351         addFunction(vm, "effectful42", functionEffectful42, 0);
1352         addFunction(vm, "makeMasquerader", functionMakeMasquerader, 0);
1353         addFunction(vm, "hasCustomProperties", functionHasCustomProperties, 0);
1354
1355         addFunction(vm, "createProxy", functionCreateProxy, 1);
1356         addFunction(vm, "createRuntimeArray", functionCreateRuntimeArray, 0);
1357
1358         addFunction(vm, "createImpureGetter", functionCreateImpureGetter, 1);
1359         addFunction(vm, "createCustomGetterObject", functionCreateCustomGetterObject, 0);
1360         addFunction(vm, "createDOMJITNodeObject", functionCreateDOMJITNodeObject, 0);
1361         addFunction(vm, "createDOMJITGetterObject", functionCreateDOMJITGetterObject, 0);
1362         addFunction(vm, "createDOMJITGetterComplexObject", functionCreateDOMJITGetterComplexObject, 0);
1363         addFunction(vm, "createDOMJITFunctionObject", functionCreateDOMJITFunctionObject, 0);
1364         addFunction(vm, "createDOMJITCheckSubClassObject", functionCreateDOMJITCheckSubClassObject, 0);
1365         addFunction(vm, "createBuiltin", functionCreateBuiltin, 2);
1366         addFunction(vm, "createGlobalObject", functionCreateGlobalObject, 0);
1367         addFunction(vm, "setImpureGetterDelegate", functionSetImpureGetterDelegate, 2);
1368
1369         addFunction(vm, "dumpTypesForAllVariables", functionDumpTypesForAllVariables , 0);
1370         addFunction(vm, "findTypeForExpression", functionFindTypeForExpression, 2);
1371         addFunction(vm, "returnTypeFor", functionReturnTypeFor, 1);
1372
1373         addFunction(vm, "dumpBasicBlockExecutionRanges", functionDumpBasicBlockExecutionRanges , 0);
1374         addFunction(vm, "hasBasicBlockExecuted", functionHasBasicBlockExecuted, 2);
1375         addFunction(vm, "basicBlockExecutionCount", functionBasicBlockExecutionCount, 2);
1376
1377         addFunction(vm, "enableExceptionFuzz", functionEnableExceptionFuzz, 0);
1378
1379         addFunction(vm, "drainMicrotasks", functionDrainMicrotasks, 0);
1380
1381         addFunction(vm, "getRandomSeed", functionGetRandomSeed, 0);
1382         addFunction(vm, "setRandomSeed", functionSetRandomSeed, 1);
1383         addFunction(vm, "isRope", functionIsRope, 1);
1384         addFunction(vm, "callerSourceOrigin", functionCallerSourceOrigin, 0);
1385
1386         addFunction(vm, "globalObjectForObject", functionGlobalObjectForObject, 1);
1387
1388         addFunction(vm, "is32BitPlatform", functionIs32BitPlatform, 0);
1389
1390         addFunction(vm, "loadModule", functionLoadModule, 1);
1391         addFunction(vm, "checkModuleSyntax", functionCheckModuleSyntax, 1);
1392
1393         addFunction(vm, "platformSupportsSamplingProfiler", functionPlatformSupportsSamplingProfiler, 0);
1394         addFunction(vm, "generateHeapSnapshot", functionGenerateHeapSnapshot, 0);
1395         addFunction(vm, "resetSuperSamplerState", functionResetSuperSamplerState, 0);
1396         addFunction(vm, "ensureArrayStorage", functionEnsureArrayStorage, 0);
1397 #if ENABLE(SAMPLING_PROFILER)
1398         addFunction(vm, "startSamplingProfiler", functionStartSamplingProfiler, 0);
1399         addFunction(vm, "samplingProfilerStackTraces", functionSamplingProfilerStackTraces, 0);
1400 #endif
1401
1402         addFunction(vm, "maxArguments", functionMaxArguments, 0);
1403
1404         addFunction(vm, "asyncTestStart", functionAsyncTestStart, 1);
1405         addFunction(vm, "asyncTestPassed", functionAsyncTestPassed, 1);
1406
1407 #if ENABLE(WEBASSEMBLY)
1408         addFunction(vm, "WebAssemblyMemoryMode", functionWebAssemblyMemoryMode, 1);
1409 #endif
1410
1411         if (!arguments.isEmpty()) {
1412             JSArray* array = constructEmptyArray(globalExec(), 0);
1413             for (size_t i = 0; i < arguments.size(); ++i)
1414                 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]));
1415             putDirect(vm, Identifier::fromString(globalExec(), "arguments"), array);
1416         }
1417
1418         putDirect(vm, Identifier::fromString(globalExec(), "console"), jsUndefined());
1419         
1420         Structure* plainObjectStructure = JSFinalObject::createStructure(vm, this, objectPrototype(), 0);
1421         
1422         JSObject* dollar = JSFinalObject::create(vm, plainObjectStructure);
1423         putDirect(vm, Identifier::fromString(globalExec(), "$"), dollar);
1424         
1425         addFunction(vm, dollar, "createRealm", functionDollarCreateRealm, 0);
1426         addFunction(vm, dollar, "detachArrayBuffer", functionDollarDetachArrayBuffer, 1);
1427         addFunction(vm, dollar, "evalScript", functionDollarEvalScript, 1);
1428         
1429         dollar->putDirect(vm, Identifier::fromString(globalExec(), "global"), this);
1430         
1431         JSObject* agent = JSFinalObject::create(vm, plainObjectStructure);
1432         dollar->putDirect(vm, Identifier::fromString(globalExec(), "agent"), agent);
1433         
1434         // The test262 INTERPRETING.md document says that some of these functions are just in the main
1435         // thread and some are in the other threads. We just put them in all threads.
1436         addFunction(vm, agent, "start", functionDollarAgentStart, 1);
1437         addFunction(vm, agent, "receiveBroadcast", functionDollarAgentReceiveBroadcast, 1);
1438         addFunction(vm, agent, "report", functionDollarAgentReport, 1);
1439         addFunction(vm, agent, "sleep", functionDollarAgentSleep, 1);
1440         addFunction(vm, agent, "broadcast", functionDollarAgentBroadcast, 1);
1441         addFunction(vm, agent, "getReport", functionDollarAgentGetReport, 0);
1442         addFunction(vm, agent, "leaving", functionDollarAgentLeaving, 0);
1443         
1444         addFunction(vm, "waitForReport", functionWaitForReport, 0);
1445
1446         addFunction(vm, "heapCapacity", functionHeapCapacity, 0);
1447         addFunction(vm, "flashHeapAccess", functionFlashHeapAccess, 0);
1448     }
1449     
1450     void addFunction(VM& vm, JSObject* object, const char* name, NativeFunction function, unsigned arguments)
1451     {
1452         Identifier identifier = Identifier::fromString(&vm, name);
1453         object->putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function));
1454     }
1455
1456     void addFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
1457     {
1458         addFunction(vm, this, name, function, arguments);
1459     }
1460     
1461     void addConstructableFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
1462     {
1463         Identifier identifier = Identifier::fromString(&vm, name);
1464         putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function, NoIntrinsic, function));
1465     }
1466
1467     static JSInternalPromise* moduleLoaderImportModule(JSGlobalObject*, ExecState*, JSModuleLoader*, JSString*, const SourceOrigin&);
1468     static JSInternalPromise* moduleLoaderResolve(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSValue, JSValue);
1469     static JSInternalPromise* moduleLoaderFetch(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSValue);
1470 };
1471
1472 const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(GlobalObject) };
1473 const GlobalObjectMethodTable GlobalObject::s_globalObjectMethodTable = {
1474     &supportsRichSourceInfo,
1475     &shouldInterruptScript,
1476     &javaScriptRuntimeFlags,
1477     nullptr, // queueTaskToEventLoop
1478     &shouldInterruptScriptBeforeTimeout,
1479     &moduleLoaderImportModule,
1480     &moduleLoaderResolve,
1481     &moduleLoaderFetch,
1482     nullptr, // moduleLoaderInstantiate
1483     nullptr, // moduleLoaderEvaluate
1484     nullptr, // promiseRejectionTracker
1485     nullptr, // defaultLanguage
1486 };
1487
1488 GlobalObject::GlobalObject(VM& vm, Structure* structure)
1489     : JSGlobalObject(vm, structure, &s_globalObjectMethodTable)
1490 {
1491 }
1492
1493 static UChar pathSeparator()
1494 {
1495 #if OS(WINDOWS)
1496     return '\\';
1497 #else
1498     return '/';
1499 #endif
1500 }
1501
1502 struct DirectoryName {
1503     // In unix, it is "/". In Windows, it becomes a drive letter like "C:\"
1504     String rootName;
1505
1506     // If the directory name is "/home/WebKit", this becomes "home/WebKit". If the directory name is "/", this becomes "".
1507     String queryName;
1508 };
1509
1510 struct ModuleName {
1511     ModuleName(const String& moduleName);
1512
1513     bool startsWithRoot() const
1514     {
1515         return !queries.isEmpty() && queries[0].isEmpty();
1516     }
1517
1518     Vector<String> queries;
1519 };
1520
1521 ModuleName::ModuleName(const String& moduleName)
1522 {
1523     // A module name given from code is represented as the UNIX style path. Like, `./A/B.js`.
1524     moduleName.split('/', true, queries);
1525 }
1526
1527 static std::optional<DirectoryName> extractDirectoryName(const String& absolutePathToFile)
1528 {
1529     size_t firstSeparatorPosition = absolutePathToFile.find(pathSeparator());
1530     if (firstSeparatorPosition == notFound)
1531         return std::nullopt;
1532     DirectoryName directoryName;
1533     directoryName.rootName = absolutePathToFile.substring(0, firstSeparatorPosition + 1); // Include the separator.
1534     size_t lastSeparatorPosition = absolutePathToFile.reverseFind(pathSeparator());
1535     ASSERT_WITH_MESSAGE(lastSeparatorPosition != notFound, "If the separator is not found, this function already returns when performing the forward search.");
1536     if (firstSeparatorPosition == lastSeparatorPosition)
1537         directoryName.queryName = StringImpl::empty();
1538     else {
1539         size_t queryStartPosition = firstSeparatorPosition + 1;
1540         size_t queryLength = lastSeparatorPosition - queryStartPosition; // Not include the last separator.
1541         directoryName.queryName = absolutePathToFile.substring(queryStartPosition, queryLength);
1542     }
1543     return directoryName;
1544 }
1545
1546 static std::optional<DirectoryName> currentWorkingDirectory()
1547 {
1548 #if OS(WINDOWS)
1549     // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364934.aspx
1550     // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
1551     // The _MAX_PATH in Windows is 260. If the path of the current working directory is longer than that, _getcwd truncates the result.
1552     // And other I/O functions taking a path name also truncate it. To avoid this situation,
1553     //
1554     // (1). When opening the file in Windows for modules, we always use the abosolute path and add "\\?\" prefix to the path name.
1555     // (2). When retrieving the current working directory, use GetCurrentDirectory instead of _getcwd.
1556     //
1557     // In the path utility functions inside the JSC shell, we does not handle the UNC and UNCW including the network host name.
1558     DWORD bufferLength = ::GetCurrentDirectoryW(0, nullptr);
1559     if (!bufferLength)
1560         return std::nullopt;
1561     // In Windows, wchar_t is the UTF-16LE.
1562     // https://msdn.microsoft.com/en-us/library/dd374081.aspx
1563     // https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407.aspx
1564     auto buffer = std::make_unique<wchar_t[]>(bufferLength);
1565     DWORD lengthNotIncludingNull = ::GetCurrentDirectoryW(bufferLength, buffer.get());
1566     String directoryString = wcharToString(buffer.get(), lengthNotIncludingNull);
1567     // We don't support network path like \\host\share\<path name>.
1568     if (directoryString.startsWith("\\\\"))
1569         return std::nullopt;
1570 #else
1571     auto buffer = std::make_unique<char[]>(PATH_MAX);
1572     if (!getcwd(buffer.get(), PATH_MAX))
1573         return std::nullopt;
1574     String directoryString = String::fromUTF8(buffer.get());
1575 #endif
1576     if (directoryString.isEmpty())
1577         return std::nullopt;
1578
1579     if (directoryString[directoryString.length() - 1] == pathSeparator())
1580         return extractDirectoryName(directoryString);
1581     // Append the seperator to represents the file name. extractDirectoryName only accepts the absolute file name.
1582     return extractDirectoryName(makeString(directoryString, pathSeparator()));
1583 }
1584
1585 static String resolvePath(const DirectoryName& directoryName, const ModuleName& moduleName)
1586 {
1587     Vector<String> directoryPieces;
1588     directoryName.queryName.split(pathSeparator(), false, directoryPieces);
1589
1590     // Only first '/' is recognized as the path from the root.
1591     if (moduleName.startsWithRoot())
1592         directoryPieces.clear();
1593
1594     for (const auto& query : moduleName.queries) {
1595         if (query == String(ASCIILiteral(".."))) {
1596             if (!directoryPieces.isEmpty())
1597                 directoryPieces.removeLast();
1598         } else if (!query.isEmpty() && query != String(ASCIILiteral(".")))
1599             directoryPieces.append(query);
1600     }
1601
1602     StringBuilder builder;
1603     builder.append(directoryName.rootName);
1604     for (size_t i = 0; i < directoryPieces.size(); ++i) {
1605         builder.append(directoryPieces[i]);
1606         if (i + 1 != directoryPieces.size())
1607             builder.append(pathSeparator());
1608     }
1609     return builder.toString();
1610 }
1611
1612 static String absolutePath(const String& fileName)
1613 {
1614     auto directoryName = currentWorkingDirectory();
1615     if (!directoryName)
1616         return fileName;
1617     return resolvePath(directoryName.value(), ModuleName(fileName.impl()));
1618 }
1619
1620 JSInternalPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSString* moduleNameValue, const SourceOrigin& sourceOrigin)
1621 {
1622     VM& vm = globalObject->vm();
1623     auto scope = DECLARE_CATCH_SCOPE(vm);
1624
1625     auto rejectPromise = [&] (JSValue error) {
1626         return JSInternalPromiseDeferred::create(exec, globalObject)->reject(exec, error);
1627     };
1628
1629     if (sourceOrigin.isNull())
1630         return rejectPromise(createError(exec, ASCIILiteral("Could not resolve the module specifier.")));
1631
1632     auto referrer = sourceOrigin.string();
1633     auto moduleName = moduleNameValue->value(exec);
1634     if (UNLIKELY(scope.exception())) {
1635         JSValue exception = scope.exception();
1636         scope.clearException();
1637         return rejectPromise(exception);
1638     }
1639
1640     auto directoryName = extractDirectoryName(referrer.impl());
1641     if (!directoryName)
1642         return rejectPromise(createError(exec, makeString("Could not resolve the referrer name '", String(referrer.impl()), "'.")));
1643
1644     return JSC::importModule(exec, Identifier::fromString(&vm, resolvePath(directoryName.value(), ModuleName(moduleName))), jsUndefined());
1645 }
1646
1647 JSInternalPromise* GlobalObject::moduleLoaderResolve(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue keyValue, JSValue referrerValue, JSValue)
1648 {
1649     VM& vm = globalObject->vm();
1650     auto scope = DECLARE_CATCH_SCOPE(vm);
1651
1652     JSInternalPromiseDeferred* deferred = JSInternalPromiseDeferred::create(exec, globalObject);
1653     scope.releaseAssertNoException();
1654     const Identifier key = keyValue.toPropertyKey(exec);
1655     if (UNLIKELY(scope.exception())) {
1656         JSValue exception = scope.exception();
1657         scope.clearException();
1658         return deferred->reject(exec, exception);
1659     }
1660
1661     if (key.isSymbol())
1662         return deferred->resolve(exec, keyValue);
1663
1664     if (referrerValue.isUndefined()) {
1665         auto directoryName = currentWorkingDirectory();
1666         if (!directoryName)
1667             return deferred->reject(exec, createError(exec, ASCIILiteral("Could not resolve the current working directory.")));
1668         return deferred->resolve(exec, jsString(exec, resolvePath(directoryName.value(), ModuleName(key.impl()))));
1669     }
1670
1671     const Identifier referrer = referrerValue.toPropertyKey(exec);
1672     if (UNLIKELY(scope.exception())) {
1673         JSValue exception = scope.exception();
1674         scope.clearException();
1675         return deferred->reject(exec, exception);
1676     }
1677
1678     if (referrer.isSymbol()) {
1679         auto directoryName = currentWorkingDirectory();
1680         if (!directoryName)
1681             return deferred->reject(exec, createError(exec, ASCIILiteral("Could not resolve the current working directory.")));
1682         return deferred->resolve(exec, jsString(exec, resolvePath(directoryName.value(), ModuleName(key.impl()))));
1683     }
1684
1685     // If the referrer exists, we assume that the referrer is the correct absolute path.
1686     auto directoryName = extractDirectoryName(referrer.impl());
1687     if (!directoryName)
1688         return deferred->reject(exec, createError(exec, makeString("Could not resolve the referrer name '", String(referrer.impl()), "'.")));
1689     auto result = deferred->resolve(exec, jsString(exec, resolvePath(directoryName.value(), ModuleName(key.impl()))));
1690     scope.releaseAssertNoException();
1691     return result;
1692 }
1693
1694 static void convertShebangToJSComment(Vector<char>& buffer)
1695 {
1696     if (buffer.size() >= 2) {
1697         if (buffer[0] == '#' && buffer[1] == '!')
1698             buffer[0] = buffer[1] = '/';
1699     }
1700 }
1701
1702 static bool fillBufferWithContentsOfFile(FILE* file, Vector<char>& buffer)
1703 {
1704     // We might have injected "use strict"; at the top.
1705     size_t initialSize = buffer.size();
1706     fseek(file, 0, SEEK_END);
1707     size_t bufferCapacity = ftell(file);
1708     fseek(file, 0, SEEK_SET);
1709     buffer.resize(bufferCapacity + initialSize);
1710     size_t readSize = fread(buffer.data() + initialSize, 1, buffer.size(), file);
1711     return readSize == buffer.size() - initialSize;
1712 }
1713
1714 static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer)
1715 {
1716     FILE* f = fopen(fileName.utf8().data(), "rb");
1717     if (!f) {
1718         fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1719         return false;
1720     }
1721
1722     bool result = fillBufferWithContentsOfFile(f, buffer);
1723     fclose(f);
1724
1725     return result;
1726 }
1727
1728 static bool fetchScriptFromLocalFileSystem(const String& fileName, Vector<char>& buffer)
1729 {
1730     if (!fillBufferWithContentsOfFile(fileName, buffer))
1731         return false;
1732     convertShebangToJSComment(buffer);
1733     return true;
1734 }
1735
1736 static bool fetchModuleFromLocalFileSystem(const String& fileName, Vector<char>& buffer)
1737 {
1738     // We assume that fileName is always an absolute path.
1739 #if OS(WINDOWS)
1740     // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
1741     // Use long UNC to pass the long path name to the Windows APIs.
1742     String longUNCPathName = WTF::makeString("\\\\?\\", fileName);
1743     FILE* f = _wfopen(stringToNullTerminatedWChar(longUNCPathName).data(), L"rb");
1744 #else
1745     FILE* f = fopen(fileName.utf8().data(), "r");
1746 #endif
1747     if (!f) {
1748         fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1749         return false;
1750     }
1751
1752     bool result = fillBufferWithContentsOfFile(f, buffer);
1753     if (result)
1754         convertShebangToJSComment(buffer);
1755     fclose(f);
1756
1757     return result;
1758 }
1759
1760 JSInternalPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue key, JSValue)
1761 {
1762     VM& vm = globalObject->vm();
1763     auto scope = DECLARE_CATCH_SCOPE(vm);
1764     JSInternalPromiseDeferred* deferred = JSInternalPromiseDeferred::create(exec, globalObject);
1765     String moduleKey = key.toWTFString(exec);
1766     if (UNLIKELY(scope.exception())) {
1767         JSValue exception = scope.exception();
1768         scope.clearException();
1769         return deferred->reject(exec, exception);
1770     }
1771
1772     // Here, now we consider moduleKey as the fileName.
1773     Vector<char> utf8;
1774     if (!fetchModuleFromLocalFileSystem(moduleKey, utf8))
1775         return deferred->reject(exec, createError(exec, makeString("Could not open file '", moduleKey, "'.")));
1776
1777     auto result = deferred->resolve(exec, JSSourceCode::create(exec->vm(), makeSource(stringFromUTF(utf8), SourceOrigin { moduleKey }, moduleKey, TextPosition(), SourceProviderSourceType::Module)));
1778     scope.releaseAssertNoException();
1779     return result;
1780 }
1781
1782
1783 static EncodedJSValue printInternal(ExecState* exec, FILE* out)
1784 {
1785     VM& vm = exec->vm();
1786     auto scope = DECLARE_THROW_SCOPE(vm);
1787
1788     if (asyncTestExpectedPasses) {
1789         JSValue value = exec->argument(0);
1790         if (value.isString() && WTF::equal(asString(value)->value(exec).impl(), "Test262:AsyncTestComplete")) {
1791             asyncTestPasses++;
1792             return JSValue::encode(jsUndefined());
1793         }
1794     }
1795
1796     for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1797         if (i)
1798             if (EOF == fputc(' ', out))
1799                 goto fail;
1800
1801         auto viewWithString = exec->uncheckedArgument(i).toString(exec)->viewWithUnderlyingString(exec);
1802         RETURN_IF_EXCEPTION(scope, encodedJSValue());
1803         if (fprintf(out, "%s", viewWithString.view.utf8().data()) < 0)
1804             goto fail;
1805     }
1806
1807     fputc('\n', out);
1808 fail:
1809     fflush(out);
1810     return JSValue::encode(jsUndefined());
1811 }
1812
1813 EncodedJSValue JSC_HOST_CALL functionPrintStdOut(ExecState* exec) { return printInternal(exec, stdout); }
1814 EncodedJSValue JSC_HOST_CALL functionPrintStdErr(ExecState* exec) { return printInternal(exec, stderr); }
1815
1816 #ifndef NDEBUG
1817 EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState* exec)
1818 {
1819     VMEntryFrame* topVMEntryFrame = exec->vm().topVMEntryFrame;
1820     ExecState* callerFrame = exec->callerFrame(topVMEntryFrame);
1821     if (callerFrame)
1822         exec->vm().interpreter->dumpCallFrame(callerFrame);
1823     return JSValue::encode(jsUndefined());
1824 }
1825 #endif
1826
1827 EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
1828 {
1829     VM& vm = exec->vm();
1830     auto scope = DECLARE_THROW_SCOPE(vm);
1831     auto viewWithString = exec->argument(0).toString(exec)->viewWithUnderlyingString(exec);
1832     RETURN_IF_EXCEPTION(scope, encodedJSValue());
1833     fprintf(stderr, "--> %s\n", viewWithString.view.utf8().data());
1834     return JSValue::encode(jsUndefined());
1835 }
1836
1837 EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState* exec)
1838 {
1839     if (exec->argumentCount() < 1)
1840         return JSValue::encode(jsUndefined());
1841     return JSValue::encode(jsString(exec, toString(exec->argument(0))));
1842 }
1843
1844 EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState* exec)
1845 {
1846     if (exec->argumentCount() < 1)
1847         return JSValue::encode(jsUndefined());
1848     VM& vm = exec->vm();
1849     JSObject* object = jsDynamicCast<JSObject*>(vm, exec->argument(0));
1850     if (!object)
1851         return JSValue::encode(jsNontrivialString(exec, ASCIILiteral("<not object>")));
1852     return JSValue::encode(jsNontrivialString(exec, toString("<Butterfly: ", RawPointer(object->butterfly()), "; public length: ", object->getArrayLength(), "; vector length: ", object->getVectorLength(), ">")));
1853 }
1854
1855 EncodedJSValue JSC_HOST_CALL functionSleepSeconds(ExecState* exec)
1856 {
1857     VM& vm = exec->vm();
1858     auto scope = DECLARE_THROW_SCOPE(vm);
1859
1860     if (exec->argumentCount() >= 1) {
1861         Seconds seconds = Seconds(exec->argument(0).toNumber(exec));
1862         RETURN_IF_EXCEPTION(scope, encodedJSValue());
1863         sleep(seconds);
1864     }
1865     
1866     return JSValue::encode(jsUndefined());
1867 }
1868
1869 class FunctionJSCStackFunctor {
1870 public:
1871     FunctionJSCStackFunctor(StringBuilder& trace)
1872         : m_trace(trace)
1873     {
1874     }
1875
1876     StackVisitor::Status operator()(StackVisitor& visitor) const
1877     {
1878         m_trace.append(String::format("    %zu   %s\n", visitor->index(), visitor->toString().utf8().data()));
1879         return StackVisitor::Continue;
1880     }
1881
1882 private:
1883     StringBuilder& m_trace;
1884 };
1885
1886 EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
1887 {
1888     StringBuilder trace;
1889     trace.appendLiteral("--> Stack trace:\n");
1890
1891     FunctionJSCStackFunctor functor(trace);
1892     exec->iterate(functor);
1893     fprintf(stderr, "%s", trace.toString().utf8().data());
1894     return JSValue::encode(jsUndefined());
1895 }
1896
1897 EncodedJSValue JSC_HOST_CALL functionCreateRoot(ExecState* exec)
1898 {
1899     JSLockHolder lock(exec);
1900     return JSValue::encode(Root::create(exec->vm(), exec->lexicalGlobalObject()));
1901 }
1902
1903 EncodedJSValue JSC_HOST_CALL functionCreateElement(ExecState* exec)
1904 {
1905     VM& vm = exec->vm();
1906     JSLockHolder lock(vm);
1907     auto scope = DECLARE_THROW_SCOPE(vm);
1908
1909     Root* root = jsDynamicCast<Root*>(vm, exec->argument(0));
1910     if (!root)
1911         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Cannot create Element without a Root."))));
1912     return JSValue::encode(Element::create(vm, exec->lexicalGlobalObject(), root));
1913 }
1914
1915 EncodedJSValue JSC_HOST_CALL functionGetElement(ExecState* exec)
1916 {
1917     JSLockHolder lock(exec);
1918     VM& vm = exec->vm();
1919     Root* root = jsDynamicCast<Root*>(vm, exec->argument(0));
1920     if (!root)
1921         return JSValue::encode(jsUndefined());
1922     Element* result = root->element();
1923     return JSValue::encode(result ? result : jsUndefined());
1924 }
1925
1926 EncodedJSValue JSC_HOST_CALL functionSetElementRoot(ExecState* exec)
1927 {
1928     JSLockHolder lock(exec);
1929     VM& vm = exec->vm();
1930     Element* element = jsDynamicCast<Element*>(vm, exec->argument(0));
1931     Root* root = jsDynamicCast<Root*>(vm, exec->argument(1));
1932     if (element && root)
1933         element->setRoot(exec->vm(), root);
1934     return JSValue::encode(jsUndefined());
1935 }
1936
1937 EncodedJSValue JSC_HOST_CALL functionCreateSimpleObject(ExecState* exec)
1938 {
1939     JSLockHolder lock(exec);
1940     return JSValue::encode(SimpleObject::create(exec->vm(), exec->lexicalGlobalObject()));
1941 }
1942
1943 EncodedJSValue JSC_HOST_CALL functionGetHiddenValue(ExecState* exec)
1944 {
1945     VM& vm = exec->vm();
1946     JSLockHolder lock(vm);
1947     auto scope = DECLARE_THROW_SCOPE(vm);
1948
1949     SimpleObject* simpleObject = jsDynamicCast<SimpleObject*>(vm, exec->argument(0));
1950     if (UNLIKELY(!simpleObject)) {
1951         throwTypeError(exec, scope, ASCIILiteral("Invalid use of getHiddenValue test function"));
1952         return encodedJSValue();
1953     }
1954     return JSValue::encode(simpleObject->hiddenValue());
1955 }
1956
1957 EncodedJSValue JSC_HOST_CALL functionSetHiddenValue(ExecState* exec)
1958 {
1959     VM& vm = exec->vm();
1960     JSLockHolder lock(vm);
1961     auto scope = DECLARE_THROW_SCOPE(vm);
1962
1963     SimpleObject* simpleObject = jsDynamicCast<SimpleObject*>(vm, exec->argument(0));
1964     if (UNLIKELY(!simpleObject)) {
1965         throwTypeError(exec, scope, ASCIILiteral("Invalid use of setHiddenValue test function"));
1966         return encodedJSValue();
1967     }
1968     JSValue value = exec->argument(1);
1969     simpleObject->setHiddenValue(exec->vm(), value);
1970     return JSValue::encode(jsUndefined());
1971 }
1972
1973 EncodedJSValue JSC_HOST_CALL functionCreateProxy(ExecState* exec)
1974 {
1975     JSLockHolder lock(exec);
1976     JSValue target = exec->argument(0);
1977     if (!target.isObject())
1978         return JSValue::encode(jsUndefined());
1979     JSObject* jsTarget = asObject(target.asCell());
1980     Structure* structure = JSProxy::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsTarget->getPrototypeDirect(), ImpureProxyType);
1981     JSProxy* proxy = JSProxy::create(exec->vm(), structure, jsTarget);
1982     return JSValue::encode(proxy);
1983 }
1984
1985 EncodedJSValue JSC_HOST_CALL functionCreateRuntimeArray(ExecState* exec)
1986 {
1987     JSLockHolder lock(exec);
1988     RuntimeArray* array = RuntimeArray::create(exec);
1989     return JSValue::encode(array);
1990 }
1991
1992 EncodedJSValue JSC_HOST_CALL functionCreateImpureGetter(ExecState* exec)
1993 {
1994     JSLockHolder lock(exec);
1995     JSValue target = exec->argument(0);
1996     JSObject* delegate = nullptr;
1997     if (target.isObject())
1998         delegate = asObject(target.asCell());
1999     Structure* structure = ImpureGetter::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
2000     ImpureGetter* result = ImpureGetter::create(exec->vm(), structure, delegate);
2001     return JSValue::encode(result);
2002 }
2003
2004 EncodedJSValue JSC_HOST_CALL functionCreateCustomGetterObject(ExecState* exec)
2005 {
2006     JSLockHolder lock(exec);
2007     Structure* structure = CustomGetter::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
2008     CustomGetter* result = CustomGetter::create(exec->vm(), structure);
2009     return JSValue::encode(result);
2010 }
2011
2012 EncodedJSValue JSC_HOST_CALL functionCreateDOMJITNodeObject(ExecState* exec)
2013 {
2014     JSLockHolder lock(exec);
2015     Structure* structure = DOMJITNode::createStructure(exec->vm(), exec->lexicalGlobalObject(), DOMJITGetter::create(exec->vm(), DOMJITGetter::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull())));
2016     DOMJITNode* result = DOMJITNode::create(exec->vm(), structure);
2017     return JSValue::encode(result);
2018 }
2019
2020 EncodedJSValue JSC_HOST_CALL functionCreateDOMJITGetterObject(ExecState* exec)
2021 {
2022     JSLockHolder lock(exec);
2023     Structure* structure = DOMJITGetter::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
2024     DOMJITGetter* result = DOMJITGetter::create(exec->vm(), structure);
2025     return JSValue::encode(result);
2026 }
2027
2028 EncodedJSValue JSC_HOST_CALL functionCreateDOMJITGetterComplexObject(ExecState* exec)
2029 {
2030     JSLockHolder lock(exec);
2031     Structure* structure = DOMJITGetterComplex::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
2032     DOMJITGetterComplex* result = DOMJITGetterComplex::create(exec->vm(), exec->lexicalGlobalObject(), structure);
2033     return JSValue::encode(result);
2034 }
2035
2036 EncodedJSValue JSC_HOST_CALL functionCreateDOMJITFunctionObject(ExecState* exec)
2037 {
2038     JSLockHolder lock(exec);
2039     Structure* structure = DOMJITFunctionObject::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
2040     DOMJITFunctionObject* result = DOMJITFunctionObject::create(exec->vm(), exec->lexicalGlobalObject(), structure);
2041     return JSValue::encode(result);
2042 }
2043
2044 EncodedJSValue JSC_HOST_CALL functionCreateDOMJITCheckSubClassObject(ExecState* exec)
2045 {
2046     JSLockHolder lock(exec);
2047     Structure* structure = DOMJITCheckSubClassObject::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
2048     DOMJITCheckSubClassObject* result = DOMJITCheckSubClassObject::create(exec->vm(), exec->lexicalGlobalObject(), structure);
2049     return JSValue::encode(result);
2050 }
2051
2052 EncodedJSValue JSC_HOST_CALL functionSetImpureGetterDelegate(ExecState* exec)
2053 {
2054     VM& vm = exec->vm();
2055     JSLockHolder lock(vm);
2056     auto scope = DECLARE_THROW_SCOPE(vm);
2057
2058     JSValue base = exec->argument(0);
2059     if (!base.isObject())
2060         return JSValue::encode(jsUndefined());
2061     JSValue delegate = exec->argument(1);
2062     if (!delegate.isObject())
2063         return JSValue::encode(jsUndefined());
2064     ImpureGetter* impureGetter = jsDynamicCast<ImpureGetter*>(vm, asObject(base.asCell()));
2065     if (UNLIKELY(!impureGetter)) {
2066         throwTypeError(exec, scope, ASCIILiteral("argument is not an ImpureGetter"));
2067         return encodedJSValue();
2068     }
2069     impureGetter->setDelegate(vm, asObject(delegate.asCell()));
2070     return JSValue::encode(jsUndefined());
2071 }
2072
2073 EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState* exec)
2074 {
2075     JSLockHolder lock(exec);
2076     exec->heap()->collectNow(Sync, CollectionScope::Full);
2077     return JSValue::encode(jsNumber(exec->heap()->sizeAfterLastFullCollection()));
2078 }
2079
2080 EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState* exec)
2081 {
2082     JSLockHolder lock(exec);
2083     exec->heap()->collectSync(CollectionScope::Full);
2084     return JSValue::encode(jsNumber(exec->heap()->sizeAfterLastFullCollection()));
2085 }
2086
2087 EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState* exec)
2088 {
2089     JSLockHolder lock(exec);
2090     exec->heap()->collectSync(CollectionScope::Eden);
2091     return JSValue::encode(jsNumber(exec->heap()->sizeAfterLastEdenCollection()));
2092 }
2093
2094 EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*)
2095 {
2096     // It's best for this to be the first thing called in the 
2097     // JS program so the option is set to true before we JIT.
2098     Options::forceGCSlowPaths() = true;
2099     return JSValue::encode(jsUndefined());
2100 }
2101
2102 EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState* exec)
2103 {
2104     JSLockHolder lock(exec);
2105     return JSValue::encode(jsNumber(exec->heap()->size()));
2106 }
2107
2108 // This function is not generally very helpful in 64-bit code as the tag and payload
2109 // share a register. But in 32-bit JITed code the tag may not be checked if an
2110 // optimization removes type checking requirements, such as in ===.
2111 EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState* exec)
2112 {
2113     JSValue value = exec->argument(0);
2114     if (!value.isCell())
2115         return JSValue::encode(jsUndefined());
2116     // Need to cast to uint64_t so bitwise_cast will play along.
2117     uint64_t asNumber = reinterpret_cast<uint64_t>(value.asCell());
2118     EncodedJSValue returnValue = JSValue::encode(jsNumber(bitwise_cast<double>(asNumber)));
2119     return returnValue;
2120 }
2121
2122 static EncodedJSValue JSC_HOST_CALL functionGetGetterSetter(ExecState* exec)
2123 {
2124     JSValue value = exec->argument(0);
2125     if (!value.isObject())
2126         return JSValue::encode(jsUndefined());
2127
2128     JSValue property = exec->argument(1);
2129     if (!property.isString())
2130         return JSValue::encode(jsUndefined());
2131
2132     PropertySlot slot(value, PropertySlot::InternalMethodType::VMInquiry);
2133     value.getPropertySlot(exec, asString(property)->toIdentifier(exec), slot);
2134
2135     JSValue result;
2136     if (slot.isCacheableGetter())
2137         result = slot.getterSetter();
2138     else
2139         result = jsNull();
2140
2141     return JSValue::encode(result);
2142 }
2143
2144 EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
2145 {
2146     // We need this function for compatibility with the Mozilla JS tests but for now
2147     // we don't actually do any version-specific handling
2148     return JSValue::encode(jsUndefined());
2149 }
2150
2151 EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
2152 {
2153     VM& vm = exec->vm();
2154     auto scope = DECLARE_THROW_SCOPE(vm);
2155
2156     String fileName = exec->argument(0).toWTFString(exec);
2157     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2158     Vector<char> script;
2159     if (!fetchScriptFromLocalFileSystem(fileName, script))
2160         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Could not open file."))));
2161
2162     GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
2163
2164     JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
2165     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2166     for (unsigned i = 1; i < exec->argumentCount(); ++i) {
2167         array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
2168         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2169     }
2170     globalObject->putDirect(
2171         vm, Identifier::fromString(globalObject->globalExec(), "arguments"), array);
2172
2173     NakedPtr<Exception> exception;
2174     StopWatch stopWatch;
2175     stopWatch.start();
2176     evaluate(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), exception);
2177     stopWatch.stop();
2178
2179     if (exception) {
2180         throwException(globalObject->globalExec(), scope, exception);
2181         return JSValue::encode(jsUndefined());
2182     }
2183     
2184     return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
2185 }
2186
2187 EncodedJSValue JSC_HOST_CALL functionRunString(ExecState* exec)
2188 {
2189     VM& vm = exec->vm();
2190     auto scope = DECLARE_THROW_SCOPE(vm);
2191
2192     String source = exec->argument(0).toWTFString(exec);
2193     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2194
2195     GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
2196
2197     JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
2198     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2199     for (unsigned i = 1; i < exec->argumentCount(); ++i) {
2200         array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
2201         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2202     }
2203     globalObject->putDirect(
2204         vm, Identifier::fromString(globalObject->globalExec(), "arguments"), array);
2205
2206     NakedPtr<Exception> exception;
2207     evaluate(globalObject->globalExec(), makeSource(source, exec->callerSourceOrigin()), JSValue(), exception);
2208
2209     if (exception) {
2210         scope.throwException(globalObject->globalExec(), exception);
2211         return JSValue::encode(jsUndefined());
2212     }
2213     
2214     return JSValue::encode(globalObject);
2215 }
2216
2217 EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
2218 {
2219     VM& vm = exec->vm();
2220     auto scope = DECLARE_THROW_SCOPE(vm);
2221
2222     String fileName = exec->argument(0).toWTFString(exec);
2223     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2224     Vector<char> script;
2225     if (!fetchScriptFromLocalFileSystem(fileName, script))
2226         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Could not open file."))));
2227
2228     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
2229     
2230     NakedPtr<Exception> evaluationException;
2231     JSValue result = evaluate(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), evaluationException);
2232     if (evaluationException)
2233         throwException(exec, scope, evaluationException);
2234     return JSValue::encode(result);
2235 }
2236
2237 EncodedJSValue JSC_HOST_CALL functionLoadString(ExecState* exec)
2238 {
2239     VM& vm = exec->vm();
2240     auto scope = DECLARE_THROW_SCOPE(vm);
2241
2242     String sourceCode = exec->argument(0).toWTFString(exec);
2243     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2244     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
2245
2246     NakedPtr<Exception> evaluationException;
2247     JSValue result = evaluate(globalObject->globalExec(), makeSource(sourceCode, exec->callerSourceOrigin()), JSValue(), evaluationException);
2248     if (evaluationException)
2249         throwException(exec, scope, evaluationException);
2250     return JSValue::encode(result);
2251 }
2252
2253 EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState* exec)
2254 {
2255     VM& vm = exec->vm();
2256     auto scope = DECLARE_THROW_SCOPE(vm);
2257
2258     String fileName = exec->argument(0).toWTFString(exec);
2259     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2260
2261     bool isBinary = false;
2262     if (exec->argumentCount() > 1) {
2263         String type = exec->argument(1).toWTFString(exec);
2264         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2265         if (type != "binary")
2266             return throwVMError(exec, scope, "Expected 'binary' as second argument.");
2267         isBinary = true;
2268     }
2269
2270     Vector<char> content;
2271     if (!fillBufferWithContentsOfFile(fileName, content))
2272         return throwVMError(exec, scope, "Could not open file.");
2273
2274     if (!isBinary)
2275         return JSValue::encode(jsString(exec, stringFromUTF(content)));
2276
2277     Structure* structure = exec->lexicalGlobalObject()->typedArrayStructure(TypeUint8);
2278     auto length = content.size();
2279     JSObject* result = createUint8TypedArray(exec, structure, ArrayBuffer::createFromBytes(content.releaseBuffer().leakPtr(), length, [] (void* p) { fastFree(p); }), 0, length);
2280     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2281
2282     return JSValue::encode(result);
2283 }
2284
2285 EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
2286 {
2287     VM& vm = exec->vm();
2288     auto scope = DECLARE_THROW_SCOPE(vm);
2289
2290     String fileName = exec->argument(0).toWTFString(exec);
2291     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2292     Vector<char> script;
2293     if (!fetchScriptFromLocalFileSystem(fileName, script))
2294         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Could not open file."))));
2295
2296     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
2297
2298     StopWatch stopWatch;
2299     stopWatch.start();
2300
2301     JSValue syntaxException;
2302     bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), &syntaxException);
2303     stopWatch.stop();
2304
2305     if (!validSyntax)
2306         throwException(exec, scope, syntaxException);
2307     return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
2308 }
2309
2310 #if ENABLE(SAMPLING_FLAGS)
2311 EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
2312 {
2313     for (unsigned i = 0; i < exec->argumentCount(); ++i) {
2314         unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
2315         if ((flag >= 1) && (flag <= 32))
2316             SamplingFlags::setFlag(flag);
2317     }
2318     return JSValue::encode(jsNull());
2319 }
2320
2321 EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
2322 {
2323     for (unsigned i = 0; i < exec->argumentCount(); ++i) {
2324         unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
2325         if ((flag >= 1) && (flag <= 32))
2326             SamplingFlags::clearFlag(flag);
2327     }
2328     return JSValue::encode(jsNull());
2329 }
2330 #endif
2331
2332 EncodedJSValue JSC_HOST_CALL functionShadowChickenFunctionsOnStack(ExecState* exec)
2333 {
2334     return JSValue::encode(exec->vm().shadowChicken().functionsOnStack(exec));
2335 }
2336
2337 EncodedJSValue JSC_HOST_CALL functionSetGlobalConstRedeclarationShouldNotThrow(ExecState* exec)
2338 {
2339     exec->vm().setGlobalConstRedeclarationShouldThrow(false);
2340     return JSValue::encode(jsUndefined());
2341 }
2342
2343 EncodedJSValue JSC_HOST_CALL functionGetRandomSeed(ExecState* exec)
2344 {
2345     return JSValue::encode(jsNumber(exec->lexicalGlobalObject()->weakRandom().seed()));
2346 }
2347
2348 EncodedJSValue JSC_HOST_CALL functionSetRandomSeed(ExecState* exec)
2349 {
2350     VM& vm = exec->vm();
2351     auto scope = DECLARE_THROW_SCOPE(vm);
2352
2353     unsigned seed = exec->argument(0).toUInt32(exec);
2354     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2355     exec->lexicalGlobalObject()->weakRandom().setSeed(seed);
2356     return JSValue::encode(jsUndefined());
2357 }
2358
2359 EncodedJSValue JSC_HOST_CALL functionIsRope(ExecState* exec)
2360 {
2361     JSValue argument = exec->argument(0);
2362     if (!argument.isString())
2363         return JSValue::encode(jsBoolean(false));
2364     const StringImpl* impl = asString(argument)->tryGetValueImpl();
2365     return JSValue::encode(jsBoolean(!impl));
2366 }
2367
2368 EncodedJSValue JSC_HOST_CALL functionCallerSourceOrigin(ExecState* state)
2369 {
2370     SourceOrigin sourceOrigin = state->callerSourceOrigin();
2371     if (sourceOrigin.isNull())
2372         return JSValue::encode(jsNull());
2373     return JSValue::encode(jsString(state, sourceOrigin.string()));
2374 }
2375
2376 EncodedJSValue JSC_HOST_CALL functionGlobalObjectForObject(ExecState* exec)
2377 {
2378     JSValue value = exec->argument(0);
2379     RELEASE_ASSERT(value.isObject());
2380     JSGlobalObject* globalObject = jsCast<JSObject*>(value)->globalObject();
2381     RELEASE_ASSERT(globalObject);
2382     return JSValue::encode(globalObject);
2383 }
2384
2385 EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
2386 {
2387     Vector<char, 256> line;
2388     int c;
2389     while ((c = getchar()) != EOF) {
2390         // FIXME: Should we also break on \r? 
2391         if (c == '\n')
2392             break;
2393         line.append(c);
2394     }
2395     line.append('\0');
2396     return JSValue::encode(jsString(exec, line.data()));
2397 }
2398
2399 EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
2400 {
2401     return JSValue::encode(jsNumber(currentTime()));
2402 }
2403
2404 EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState* exec)
2405 {
2406     return JSValue::encode(setNeverInline(exec));
2407 }
2408
2409 EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState* exec)
2410 {
2411     return JSValue::encode(setNeverOptimize(exec));
2412 }
2413
2414 EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState* exec)
2415 {
2416     VM& vm = exec->vm();
2417     if (JSFunction* function = jsDynamicCast<JSFunction*>(vm, exec->argument(0))) {
2418         FunctionExecutable* executable = function->jsExecutable();
2419         executable->setNeverFTLOptimize(true);
2420     }
2421
2422     return JSValue::encode(jsUndefined());
2423 }
2424
2425 EncodedJSValue JSC_HOST_CALL functionNoOSRExitFuzzing(ExecState* exec)
2426 {
2427     return JSValue::encode(setCannotUseOSRExitFuzzing(exec));
2428 }
2429
2430 EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState* exec)
2431 {
2432     return JSValue::encode(optimizeNextInvocation(exec));
2433 }
2434
2435 EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState* exec)
2436 {
2437     return JSValue::encode(numberOfDFGCompiles(exec));
2438 }
2439
2440 Message::Message(ArrayBufferContents&& contents, int32_t index)
2441     : m_contents(WTFMove(contents))
2442     , m_index(index)
2443 {
2444 }
2445
2446 Message::~Message()
2447 {
2448 }
2449
2450 Worker::Worker(Workers& workers)
2451     : m_workers(workers)
2452 {
2453     auto locker = holdLock(m_workers.m_lock);
2454     m_workers.m_workers.append(this);
2455     
2456     *currentWorker() = this;
2457 }
2458
2459 Worker::~Worker()
2460 {
2461     auto locker = holdLock(m_workers.m_lock);
2462     RELEASE_ASSERT(isOnList());
2463     remove();
2464 }
2465
2466 void Worker::enqueue(const AbstractLocker&, RefPtr<Message> message)
2467 {
2468     m_messages.append(message);
2469 }
2470
2471 RefPtr<Message> Worker::dequeue()
2472 {
2473     auto locker = holdLock(m_workers.m_lock);
2474     while (m_messages.isEmpty())
2475         m_workers.m_condition.wait(m_workers.m_lock);
2476     return m_messages.takeFirst();
2477 }
2478
2479 Worker& Worker::current()
2480 {
2481     return **currentWorker();
2482 }
2483
2484 ThreadSpecific<Worker*>& Worker::currentWorker()
2485 {
2486     static ThreadSpecific<Worker*>* result;
2487     static std::once_flag flag;
2488     std::call_once(
2489         flag,
2490         [] () {
2491             result = new ThreadSpecific<Worker*>();
2492         });
2493     return *result;
2494 }
2495
2496 Workers::Workers()
2497 {
2498 }
2499
2500 Workers::~Workers()
2501 {
2502     UNREACHABLE_FOR_PLATFORM();
2503 }
2504
2505 template<typename Func>
2506 void Workers::broadcast(const Func& func)
2507 {
2508     auto locker = holdLock(m_lock);
2509     for (Worker* worker = m_workers.begin(); worker != m_workers.end(); worker = worker->next()) {
2510         if (worker != &Worker::current())
2511             func(locker, *worker);
2512     }
2513     m_condition.notifyAll();
2514 }
2515
2516 void Workers::report(String string)
2517 {
2518     auto locker = holdLock(m_lock);
2519     m_reports.append(string.isolatedCopy());
2520     m_condition.notifyAll();
2521 }
2522
2523 String Workers::tryGetReport()
2524 {
2525     auto locker = holdLock(m_lock);
2526     if (m_reports.isEmpty())
2527         return String();
2528     return m_reports.takeFirst();
2529 }
2530
2531 String Workers::getReport()
2532 {
2533     auto locker = holdLock(m_lock);
2534     while (m_reports.isEmpty())
2535         m_condition.wait(m_lock);
2536     return m_reports.takeFirst();
2537 }
2538
2539 Workers& Workers::singleton()
2540 {
2541     static Workers* result;
2542     static std::once_flag flag;
2543     std::call_once(
2544         flag,
2545         [] {
2546             result = new Workers();
2547         });
2548     return *result;
2549 }
2550
2551 EncodedJSValue JSC_HOST_CALL functionDollarCreateRealm(ExecState* exec)
2552 {
2553     VM& vm = exec->vm();
2554     GlobalObject* result = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
2555     return JSValue::encode(result->getDirect(vm, Identifier::fromString(exec, "$")));
2556 }
2557
2558 EncodedJSValue JSC_HOST_CALL functionDollarDetachArrayBuffer(ExecState* exec)
2559 {
2560     return functionTransferArrayBuffer(exec);
2561 }
2562
2563 EncodedJSValue JSC_HOST_CALL functionDollarEvalScript(ExecState* exec)
2564 {
2565     VM& vm = exec->vm();
2566     auto scope = DECLARE_THROW_SCOPE(vm);
2567
2568     String sourceCode = exec->argument(0).toWTFString(exec);
2569     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2570     
2571     GlobalObject* globalObject = jsDynamicCast<GlobalObject*>(vm,
2572         exec->thisValue().get(exec, Identifier::fromString(exec, "global")));
2573     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2574     if (!globalObject)
2575         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Expected global to point to a global object"))));
2576     
2577     NakedPtr<Exception> evaluationException;
2578     JSValue result = evaluate(globalObject->globalExec(), makeSource(sourceCode, exec->callerSourceOrigin()), JSValue(), evaluationException);
2579     if (evaluationException)
2580         throwException(exec, scope, evaluationException);
2581     return JSValue::encode(result);
2582 }
2583
2584 EncodedJSValue JSC_HOST_CALL functionDollarAgentStart(ExecState* exec)
2585 {
2586     VM& vm = exec->vm();
2587     auto scope = DECLARE_THROW_SCOPE(vm);
2588
2589     String sourceCode = exec->argument(0).toWTFString(exec).isolatedCopy();
2590     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2591     
2592     Lock didStartLock;
2593     Condition didStartCondition;
2594     bool didStart = false;
2595     
2596     RefPtr<Thread> thread = Thread::create(
2597         "JSC Agent",
2598         [sourceCode, &didStartLock, &didStartCondition, &didStart] () {
2599             CommandLine commandLine(0, nullptr);
2600             commandLine.m_interactive = false;
2601             runJSC(
2602                 commandLine, true,
2603                 [&] (VM&, GlobalObject* globalObject) {
2604                     // Notify the thread that started us that we have registered a worker.
2605                     {
2606                         auto locker = holdLock(didStartLock);
2607                         didStart = true;
2608                         didStartCondition.notifyOne();
2609                     }
2610                     
2611                     NakedPtr<Exception> evaluationException;
2612                     bool success = true;
2613                     JSValue result;
2614                     result = evaluate(globalObject->globalExec(), makeSource(sourceCode, SourceOrigin(ASCIILiteral("worker"))), JSValue(), evaluationException);
2615                     if (evaluationException)
2616                         result = evaluationException->value();
2617                     checkException(globalObject, true, evaluationException, result, String(), false, false, success);
2618                     if (!success)
2619                         exit(1);
2620                     return success;
2621                 });
2622         });
2623     thread->detach();
2624     
2625     {
2626         auto locker = holdLock(didStartLock);
2627         while (!didStart)
2628             didStartCondition.wait(didStartLock);
2629     }
2630     
2631     return JSValue::encode(jsUndefined());
2632 }
2633
2634 EncodedJSValue JSC_HOST_CALL functionDollarAgentReceiveBroadcast(ExecState* exec)
2635 {
2636     VM& vm = exec->vm();
2637     auto scope = DECLARE_THROW_SCOPE(vm);
2638
2639     JSValue callback = exec->argument(0);
2640     CallData callData;
2641     CallType callType = getCallData(callback, callData);
2642     if (callType == CallType::None)
2643         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Expected callback"))));
2644     
2645     RefPtr<Message> message;
2646     {
2647         ReleaseHeapAccessScope releaseAccess(vm.heap);
2648         message = Worker::current().dequeue();
2649     }
2650     
2651     RefPtr<ArrayBuffer> nativeBuffer = ArrayBuffer::create(message->releaseContents());
2652     ArrayBufferSharingMode sharingMode = nativeBuffer->sharingMode();
2653     JSArrayBuffer* jsBuffer = JSArrayBuffer::create(vm, exec->lexicalGlobalObject()->arrayBufferStructure(sharingMode), WTFMove(nativeBuffer));
2654     
2655     MarkedArgumentBuffer args;
2656     args.append(jsBuffer);
2657     args.append(jsNumber(message->index()));
2658     return JSValue::encode(call(exec, callback, callType, callData, jsNull(), args));
2659 }
2660
2661 EncodedJSValue JSC_HOST_CALL functionDollarAgentReport(ExecState* exec)
2662 {
2663     VM& vm = exec->vm();
2664     auto scope = DECLARE_THROW_SCOPE(vm);
2665
2666     String report = exec->argument(0).toWTFString(exec);
2667     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2668     
2669     Workers::singleton().report(report);
2670     
2671     return JSValue::encode(jsUndefined());
2672 }
2673
2674 EncodedJSValue JSC_HOST_CALL functionDollarAgentSleep(ExecState* exec)
2675 {
2676     VM& vm = exec->vm();
2677     auto scope = DECLARE_THROW_SCOPE(vm);
2678
2679     if (exec->argumentCount() >= 1) {
2680         Seconds seconds = Seconds::fromMilliseconds(exec->argument(0).toNumber(exec));
2681         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2682         sleep(seconds);
2683     }
2684     return JSValue::encode(jsUndefined());
2685 }
2686
2687 EncodedJSValue JSC_HOST_CALL functionDollarAgentBroadcast(ExecState* exec)
2688 {
2689     VM& vm = exec->vm();
2690     auto scope = DECLARE_THROW_SCOPE(vm);
2691
2692     JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(vm, exec->argument(0));
2693     if (!jsBuffer || !jsBuffer->isShared())
2694         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Expected SharedArrayBuffer"))));
2695     
2696     int32_t index = exec->argument(1).toInt32(exec);
2697     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2698     
2699     Workers::singleton().broadcast(
2700         [&] (const AbstractLocker& locker, Worker& worker) {
2701             ArrayBuffer* nativeBuffer = jsBuffer->impl();
2702             ArrayBufferContents contents;
2703             nativeBuffer->transferTo(vm, contents); // "transferTo" means "share" if the buffer is shared.
2704             RefPtr<Message> message = adoptRef(new Message(WTFMove(contents), index));
2705             worker.enqueue(locker, message);
2706         });
2707     
2708     return JSValue::encode(jsUndefined());
2709 }
2710
2711 EncodedJSValue JSC_HOST_CALL functionDollarAgentGetReport(ExecState* exec)
2712 {
2713     VM& vm = exec->vm();
2714
2715     String string = Workers::singleton().tryGetReport();
2716     if (!string)
2717         return JSValue::encode(jsNull());
2718     
2719     return JSValue::encode(jsString(&vm, string));
2720 }
2721
2722 EncodedJSValue JSC_HOST_CALL functionDollarAgentLeaving(ExecState*)
2723 {
2724     return JSValue::encode(jsUndefined());
2725 }
2726
2727 EncodedJSValue JSC_HOST_CALL functionWaitForReport(ExecState* exec)
2728 {
2729     VM& vm = exec->vm();
2730
2731     String string;
2732     {
2733         ReleaseHeapAccessScope releaseAccess(vm.heap);
2734         string = Workers::singleton().getReport();
2735     }
2736     if (!string)
2737         return JSValue::encode(jsNull());
2738     
2739     return JSValue::encode(jsString(&vm, string));
2740 }
2741
2742 EncodedJSValue JSC_HOST_CALL functionHeapCapacity(ExecState* exec)
2743 {
2744     VM& vm = exec->vm();
2745     return JSValue::encode(jsNumber(vm.heap.capacity()));
2746 }
2747
2748 EncodedJSValue JSC_HOST_CALL functionFlashHeapAccess(ExecState* exec)
2749 {
2750     VM& vm = exec->vm();
2751     auto scope = DECLARE_THROW_SCOPE(vm);
2752     
2753     vm.heap.releaseAccess();
2754     if (exec->argumentCount() >= 1) {
2755         double ms = exec->argument(0).toNumber(exec);
2756         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2757         sleep(Seconds::fromMilliseconds(ms));
2758     }
2759     vm.heap.acquireAccess();
2760     return JSValue::encode(jsUndefined());
2761 }
2762
2763 template<typename ValueType>
2764 typename std::enable_if<!std::is_fundamental<ValueType>::value>::type addOption(VM&, JSObject*, Identifier, ValueType) { }
2765
2766 template<typename ValueType>
2767 typename std::enable_if<std::is_fundamental<ValueType>::value>::type addOption(VM& vm, JSObject* optionsObject, Identifier identifier, ValueType value)
2768 {
2769     optionsObject->putDirect(vm, identifier, JSValue(value));
2770 }
2771
2772 EncodedJSValue JSC_HOST_CALL functionJSCOptions(ExecState* exec)
2773 {
2774     JSObject* optionsObject = constructEmptyObject(exec);
2775 #define FOR_EACH_OPTION(type_, name_, defaultValue_, availability_, description_) \
2776     addOption(exec->vm(), optionsObject, Identifier::fromString(exec, #name_), Options::name_());
2777     JSC_OPTIONS(FOR_EACH_OPTION)
2778 #undef FOR_EACH_OPTION
2779     return JSValue::encode(optionsObject);
2780 }
2781
2782 EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState* exec)
2783 {
2784     if (exec->argumentCount() < 1)
2785         return JSValue::encode(jsUndefined());
2786     
2787     CodeBlock* block = getSomeBaselineCodeBlockForFunction(exec->argument(0));
2788     if (!block)
2789         return JSValue::encode(jsNumber(0));
2790     
2791     return JSValue::encode(jsNumber(block->reoptimizationRetryCounter()));
2792 }
2793
2794 EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState* exec)
2795 {
2796     VM& vm = exec->vm();
2797     auto scope = DECLARE_THROW_SCOPE(vm);
2798
2799     if (exec->argumentCount() < 1)
2800         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Not enough arguments"))));
2801     
2802     JSArrayBuffer* buffer = jsDynamicCast<JSArrayBuffer*>(vm, exec->argument(0));
2803     if (!buffer)
2804         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Expected an array buffer"))));
2805     
2806     ArrayBufferContents dummyContents;
2807     buffer->impl()->transferTo(vm, dummyContents);
2808     
2809     return JSValue::encode(jsUndefined());
2810 }
2811
2812 EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState* exec)
2813 {
2814     exec->vm().setFailNextNewCodeBlock();
2815     return JSValue::encode(jsUndefined());
2816 }
2817
2818 EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*)
2819 {
2820     jscExit(EXIT_SUCCESS);
2821
2822 #if COMPILER(MSVC)
2823     // Without this, Visual Studio will complain that this method does not return a value.
2824     return JSValue::encode(jsUndefined());
2825 #endif
2826 }
2827
2828 EncodedJSValue JSC_HOST_CALL functionAbort(ExecState*)
2829 {
2830     CRASH();
2831 }
2832
2833 EncodedJSValue JSC_HOST_CALL functionFalse1(ExecState*) { return JSValue::encode(jsBoolean(false)); }
2834 EncodedJSValue JSC_HOST_CALL functionFalse2(ExecState*) { return JSValue::encode(jsBoolean(false)); }
2835
2836 EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*) { return JSValue::encode(jsUndefined()); }
2837 EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*) { return JSValue::encode(jsUndefined()); }
2838 EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState* exec)
2839 {
2840     for (size_t i = 0; i < exec->argumentCount(); ++i) {
2841         if (!exec->argument(i).isInt32())
2842             return JSValue::encode(jsBoolean(false));
2843     }
2844     return JSValue::encode(jsBoolean(true));
2845 }
2846
2847 EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState* exec) { return JSValue::encode(exec->argument(0)); }
2848
2849 EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*)
2850 {
2851     return JSValue::encode(jsNumber(42));
2852 }
2853
2854 EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState* exec)
2855 {
2856     return JSValue::encode(Masquerader::create(exec->vm(), exec->lexicalGlobalObject()));
2857 }
2858
2859 EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState* exec)
2860 {
2861     JSValue value = exec->argument(0);
2862     if (value.isObject())
2863         return JSValue::encode(jsBoolean(asObject(value)->hasCustomProperties()));
2864     return JSValue::encode(jsBoolean(false));
2865 }
2866
2867 EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState* exec)
2868 {
2869     exec->vm().dumpTypeProfilerData();
2870     return JSValue::encode(jsUndefined());
2871 }
2872
2873 EncodedJSValue JSC_HOST_CALL functionFindTypeForExpression(ExecState* exec)
2874 {
2875     VM& vm = exec->vm();
2876     RELEASE_ASSERT(exec->vm().typeProfiler());
2877     vm.typeProfilerLog()->processLogEntries(ASCIILiteral("jsc Testing API: functionFindTypeForExpression"));
2878
2879     JSValue functionValue = exec->argument(0);
2880     RELEASE_ASSERT(functionValue.isFunction());
2881     FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(vm, functionValue.asCell()->getObject()))->jsExecutable();
2882
2883     RELEASE_ASSERT(exec->argument(1).isString());
2884     String substring = asString(exec->argument(1))->value(exec);
2885     String sourceCodeText = executable->source().view().toString();
2886     unsigned offset = static_cast<unsigned>(sourceCodeText.find(substring) + executable->source().startOffset());
2887     
2888     String jsonString = exec->vm().typeProfiler()->typeInformationForExpressionAtOffset(TypeProfilerSearchDescriptorNormal, offset, executable->sourceID(), exec->vm());
2889     return JSValue::encode(JSONParse(exec, jsonString));
2890 }
2891
2892 EncodedJSValue JSC_HOST_CALL functionReturnTypeFor(ExecState* exec)
2893 {
2894     VM& vm = exec->vm();
2895     RELEASE_ASSERT(exec->vm().typeProfiler());
2896     vm.typeProfilerLog()->processLogEntries(ASCIILiteral("jsc Testing API: functionReturnTypeFor"));
2897
2898     JSValue functionValue = exec->argument(0);
2899     RELEASE_ASSERT(functionValue.isFunction());
2900     FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(vm, functionValue.asCell()->getObject()))->jsExecutable();
2901
2902     unsigned offset = executable->typeProfilingStartOffset();
2903     String jsonString = exec->vm().typeProfiler()->typeInformationForExpressionAtOffset(TypeProfilerSearchDescriptorFunctionReturn, offset, executable->sourceID(), exec->vm());
2904     return JSValue::encode(JSONParse(exec, jsonString));
2905 }
2906
2907 EncodedJSValue JSC_HOST_CALL functionDumpBasicBlockExecutionRanges(ExecState* exec)
2908 {
2909     RELEASE_ASSERT(exec->vm().controlFlowProfiler());
2910     exec->vm().controlFlowProfiler()->dumpData();
2911     return JSValue::encode(jsUndefined());
2912 }
2913
2914 EncodedJSValue JSC_HOST_CALL functionHasBasicBlockExecuted(ExecState* exec)
2915 {
2916     VM& vm = exec->vm();
2917     RELEASE_ASSERT(vm.controlFlowProfiler());
2918
2919     JSValue functionValue = exec->argument(0);
2920     RELEASE_ASSERT(functionValue.isFunction());
2921     FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(vm, functionValue.asCell()->getObject()))->jsExecutable();
2922
2923     RELEASE_ASSERT(exec->argument(1).isString());
2924     String substring = asString(exec->argument(1))->value(exec);
2925     String sourceCodeText = executable->source().view().toString();
2926     RELEASE_ASSERT(sourceCodeText.contains(substring));
2927     int offset = sourceCodeText.find(substring) + executable->source().startOffset();
2928     
2929     bool hasExecuted = vm.controlFlowProfiler()->hasBasicBlockAtTextOffsetBeenExecuted(offset, executable->sourceID(), vm);
2930     return JSValue::encode(jsBoolean(hasExecuted));
2931 }
2932
2933 EncodedJSValue JSC_HOST_CALL functionBasicBlockExecutionCount(ExecState* exec)
2934 {
2935     VM& vm = exec->vm();
2936     RELEASE_ASSERT(vm.controlFlowProfiler());
2937
2938     JSValue functionValue = exec->argument(0);
2939     RELEASE_ASSERT(functionValue.isFunction());
2940     FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(vm, functionValue.asCell()->getObject()))->jsExecutable();
2941
2942     RELEASE_ASSERT(exec->argument(1).isString());
2943     String substring = asString(exec->argument(1))->value(exec);
2944     String sourceCodeText = executable->source().view().toString();
2945     RELEASE_ASSERT(sourceCodeText.contains(substring));
2946     int offset = sourceCodeText.find(substring) + executable->source().startOffset();
2947     
2948     size_t executionCount = vm.controlFlowProfiler()->basicBlockExecutionCountAtTextOffset(offset, executable->sourceID(), exec->vm());
2949     return JSValue::encode(JSValue(executionCount));
2950 }
2951
2952 EncodedJSValue JSC_HOST_CALL functionEnableExceptionFuzz(ExecState*)
2953 {
2954     Options::useExceptionFuzz() = true;
2955     return JSValue::encode(jsUndefined());
2956 }
2957
2958 EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState* exec)
2959 {
2960     exec->vm().drainMicrotasks();
2961     return JSValue::encode(jsUndefined());
2962 }
2963
2964 EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*)
2965 {
2966 #if USE(JSVALUE64)
2967     return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
2968 #else
2969     return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
2970 #endif
2971 }
2972
2973 EncodedJSValue JSC_HOST_CALL functionLoadModule(ExecState* exec)
2974 {
2975     VM& vm = exec->vm();
2976     auto scope = DECLARE_THROW_SCOPE(vm);
2977
2978     String fileName = exec->argument(0).toWTFString(exec);
2979     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2980     Vector<char> script;
2981     if (!fetchScriptFromLocalFileSystem(fileName, script))
2982         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Could not open file."))));
2983
2984     JSInternalPromise* promise = loadAndEvaluateModule(exec, fileName);
2985     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2986
2987     JSValue error;
2988     JSFunction* errorHandler = JSNativeStdFunction::create(vm, exec->lexicalGlobalObject(), 1, String(), [&](ExecState* exec) {
2989         error = exec->argument(0);
2990         return JSValue::encode(jsUndefined());
2991     });
2992
2993     promise->then(exec, nullptr, errorHandler);
2994     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2995     vm.drainMicrotasks();
2996     if (error)
2997         return JSValue::encode(throwException(exec, scope, error));
2998     return JSValue::encode(jsUndefined());
2999 }
3000
3001 EncodedJSValue JSC_HOST_CALL functionCreateBuiltin(ExecState* exec)
3002 {
3003     VM& vm = exec->vm();
3004     auto scope = DECLARE_THROW_SCOPE(vm);
3005
3006     if (exec->argumentCount() < 1 || !exec->argument(0).isString())
3007         return JSValue::encode(jsUndefined());
3008
3009     String functionText = asString(exec->argument(0))->value(exec);
3010     RETURN_IF_EXCEPTION(scope, encodedJSValue());
3011
3012     const SourceCode& source = makeSource(functionText, { });
3013     JSFunction* func = JSFunction::createBuiltinFunction(vm, createBuiltinExecutable(vm, source, Identifier::fromString(&vm, "foo"), ConstructorKind::None, ConstructAbility::CannotConstruct)->link(vm, source), exec->lexicalGlobalObject());
3014
3015     return JSValue::encode(func);
3016 }
3017
3018 EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState* exec)
3019 {
3020     VM& vm = exec->vm();
3021     return JSValue::encode(GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>()));
3022 }
3023
3024 EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState* exec)
3025 {
3026     VM& vm = exec->vm();
3027     auto scope = DECLARE_THROW_SCOPE(vm);
3028
3029     String source = exec->argument(0).toWTFString(exec);
3030     RETURN_IF_EXCEPTION(scope, encodedJSValue());
3031
3032     StopWatch stopWatch;
3033     stopWatch.start();
3034
3035     ParserError error;
3036     bool validSyntax = checkModuleSyntax(exec, makeSource(source, { }, String(), TextPosition(), SourceProviderSourceType::Module), error);
3037     RETURN_IF_EXCEPTION(scope, encodedJSValue());
3038     stopWatch.stop();
3039
3040     if (!validSyntax)
3041         throwException(exec, scope, jsNontrivialString(exec, toString("SyntaxError: ", error.message(), ":", error.line())));
3042     return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
3043 }
3044
3045 EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*)
3046 {
3047 #if ENABLE(SAMPLING_PROFILER)
3048     return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
3049 #else
3050     return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
3051 #endif
3052 }
3053
3054 EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState* exec)
3055 {
3056     VM& vm = exec->vm();
3057     JSLockHolder lock(vm);
3058     auto scope = DECLARE_THROW_SCOPE(vm);
3059
3060     HeapSnapshotBuilder snapshotBuilder(exec->vm().ensureHeapProfiler());
3061     snapshotBuilder.buildSnapshot();
3062
3063     String jsonString = snapshotBuilder.json();
3064     EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
3065     scope.releaseAssertNoException();
3066     return result;
3067 }
3068
3069 EncodedJSValue JSC_HOST_CALL functionResetSuperSamplerState(ExecState*)
3070 {
3071     resetSuperSamplerState();
3072     return JSValue::encode(jsUndefined());
3073 }
3074
3075 EncodedJSValue JSC_HOST_CALL functionEnsureArrayStorage(ExecState* exec)
3076 {
3077     VM& vm = exec->vm();
3078     for (unsigned i = 0; i < exec->argumentCount(); ++i) {
3079         if (JSObject* object = jsDynamicCast<JSObject*>(vm, exec->argument(0)))
3080             object->ensureArrayStorage(exec->vm());
3081     }
3082     return JSValue::encode(jsUndefined());
3083 }
3084
3085 #if ENABLE(SAMPLING_PROFILER)
3086 EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState* exec)
3087 {
3088     SamplingProfiler& samplingProfiler = exec->vm().ensureSamplingProfiler(WTF::Stopwatch::create());
3089     samplingProfiler.noticeCurrentThreadAsJSCExecutionThread();
3090     samplingProfiler.start();
3091     return JSValue::encode(jsUndefined());
3092 }
3093
3094 EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState* exec)
3095 {
3096     VM& vm = exec->vm();
3097     auto scope = DECLARE_THROW_SCOPE(vm);
3098
3099     if (!vm.samplingProfiler())
3100         return JSValue::encode(throwException(exec, scope, createError(exec, ASCIILiteral("Sampling profiler was never started"))));
3101
3102     String jsonString = vm.samplingProfiler()->stackTracesAsJSON();
3103     EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
3104     scope.releaseAssertNoException();
3105     return result;
3106 }
3107 #endif // ENABLE(SAMPLING_PROFILER)
3108
3109 EncodedJSValue JSC_HOST_CALL functionMaxArguments(ExecState*)
3110 {
3111     return JSValue::encode(jsNumber(JSC::maxArguments));
3112 }
3113
3114 EncodedJSValue JSC_HOST_CALL functionAsyncTestStart(ExecState* exec)
3115 {
3116     VM& vm = exec->vm();
3117     auto scope = DECLARE_THROW_SCOPE(vm);
3118
3119     JSValue numberOfAsyncPasses = exec->argument(0);
3120     if (!numberOfAsyncPasses.isUInt32())
3121         return throwVMError(exec, scope, ASCIILiteral("Expected first argument to a uint32"));
3122
3123     asyncTestExpectedPasses += numberOfAsyncPasses.asUInt32();
3124     return encodedJSUndefined();
3125 }
3126
3127 EncodedJSValue JSC_HOST_CALL functionAsyncTestPassed(ExecState*)
3128 {
3129     asyncTestPasses++;
3130     return encodedJSUndefined();
3131 }
3132
3133 #if ENABLE(WEBASSEMBLY)
3134
3135 static EncodedJSValue JSC_HOST_CALL functionWebAssemblyMemoryMode(ExecState* exec)
3136 {
3137     VM& vm = exec->vm();
3138     auto scope = DECLARE_THROW_SCOPE(vm);
3139     
3140     if (!Options::useWebAssembly())
3141         return throwVMTypeError(exec, scope, ASCIILiteral("WebAssemblyMemoryMode should only be called if the useWebAssembly option is set"));
3142
3143     if (JSObject* object = exec->argument(0).getObject()) {
3144         if (auto* memory = jsDynamicCast<JSWebAssemblyMemory*>(vm, object))
3145             return JSValue::encode(jsString(&vm, makeString(memory->memory().mode())));
3146         if (auto* instance = jsDynamicCast<JSWebAssemblyInstance*>(vm, object))
3147             return JSValue::encode(jsString(&vm, makeString(instance->memoryMode())));
3148     }
3149
3150     return throwVMTypeError(exec, scope, ASCIILiteral("WebAssemblyMemoryMode expects either a WebAssembly.Memory or WebAssembly.Instance"));
3151 }
3152
3153 #endif // ENABLE(WEBASSEBLY)
3154
3155 // Use SEH for Release builds only to get rid of the crash report dialog
3156 // (luckily the same tests fail in Release and Debug builds so far). Need to
3157 // be in a separate main function because the jscmain function requires object
3158 // unwinding.
3159
3160 #if COMPILER(MSVC) && !defined(_DEBUG)
3161 #define TRY       __try {
3162 #define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
3163 #else
3164 #define TRY
3165 #define EXCEPT(x)
3166 #endif
3167
3168 int jscmain(int argc, char** argv);
3169
3170 static double s_desiredTimeout;
3171 static double s_timeoutMultiplier = 1.0;
3172
3173 static NO_RETURN_DUE_TO_CRASH void timeoutThreadMain(void*)
3174 {
3175     Seconds timeoutDuration(s_desiredTimeout * s_timeoutMultiplier);
3176     sleep(timeoutDuration);
3177     dataLog("Timed out after ", timeoutDuration, " seconds!\n");
3178     CRASH();
3179 }
3180
3181 static void startTimeoutThreadIfNeeded()
3182 {
3183     if (char* timeoutString = getenv("JSCTEST_timeout")) {
3184         if (sscanf(timeoutString, "%lf", &s_desiredTimeout) != 1) {
3185             dataLog("WARNING: timeout string is malformed, got ", timeoutString,
3186                 " but expected a number. Not using a timeout.\n");
3187         } else
3188             Thread::create(timeoutThreadMain, 0, "jsc Timeout Thread");
3189     }
3190 }
3191
3192 int main(int argc, char** argv)
3193 {
3194 #if PLATFORM(IOS) && CPU(ARM_THUMB2)
3195     // Enabled IEEE754 denormal support.
3196     fenv_t env;
3197     fegetenv( &env );
3198     env.__fpscr &= ~0x01000000u;
3199     fesetenv( &env );
3200 #endif
3201
3202 #if OS(WINDOWS)
3203     // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
3204     // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
3205     // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
3206     ::SetErrorMode(0);
3207
3208 #if defined(_DEBUG)
3209     _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
3210     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
3211     _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
3212     _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
3213     _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
3214     _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
3215 #endif
3216
3217     timeBeginPeriod(1);
3218 #endif
3219
3220 #if PLATFORM(GTK)
3221     if (!setlocale(LC_ALL, ""))
3222         WTFLogAlways("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
3223 #endif
3224
3225     // Need to initialize WTF threading before we start any threads. Cannot initialize JSC
3226     // threading yet, since that would do somethings that we'd like to defer until after we
3227     // have a chance to parse options.
3228     WTF::initializeThreading();
3229
3230 #if PLATFORM(IOS)
3231     Options::crashIfCantAllocateJITMemory() = true;
3232 #endif
3233
3234     // We can't use destructors in the following code because it uses Windows
3235     // Structured Exception Handling
3236     int res = 0;
3237     TRY
3238         res = jscmain(argc, argv);
3239     EXCEPT(res = 3)
3240     finalizeStatsAtEndOfTesting();
3241
3242     jscExit(res);
3243 }
3244
3245 static void dumpException(GlobalObject* globalObject, JSValue exception)
3246 {
3247     VM& vm = globalObject->vm();
3248     auto scope = DECLARE_CATCH_SCOPE(vm);
3249
3250 #define CHECK_EXCEPTION() do { \
3251         if (scope.exception()) { \
3252             scope.clearException(); \
3253             return; \
3254         } \
3255     } while (false)
3256
3257     printf("Exception: %s\n", exception.toWTFString(globalObject->globalExec()).utf8().data());
3258
3259     Identifier nameID = Identifier::fromString(globalObject->globalExec(), "name");
3260     CHECK_EXCEPTION();
3261     Identifier fileNameID = Identifier::fromString(globalObject->globalExec(), "sourceURL");
3262     CHECK_EXCEPTION();
3263     Identifier lineNumberID = Identifier::fromString(globalObject->globalExec(), "line");
3264     CHECK_EXCEPTION();
3265     Identifier stackID = Identifier::fromString(globalObject->globalExec(), "stack");
3266     CHECK_EXCEPTION();
3267
3268     JSValue nameValue = exception.get(globalObject->globalExec(), nameID);
3269     CHECK_EXCEPTION();
3270     JSValue fileNameValue = exception.get(globalObject->globalExec(), fileNameID);
3271     CHECK_EXCEPTION();
3272     JSValue lineNumberValue = exception.get(globalObject->globalExec(), lineNumberID);
3273     CHECK_EXCEPTION();
3274     JSValue stackValue = exception.get(globalObject->globalExec(), stackID);
3275     CHECK_EXCEPTION();
3276     
3277     if (nameValue.toWTFString(globalObject->globalExec()) == "SyntaxError"
3278         && (!fileNameValue.isUndefinedOrNull() || !lineNumberValue.isUndefinedOrNull())) {
3279         printf(
3280             "at %s:%s\n",
3281             fileNameValue.toWTFString(globalObject->globalExec()).utf8().data(),
3282             lineNumberValue.toWTFString(globalObject->globalExec()).utf8().data());
3283     }
3284     
3285     if (!stackValue.isUndefinedOrNull()) {
3286         auto stackString = stackValue.toWTFString(globalObject->globalExec());
3287         if (stackString.length())
3288             printf("%s\n", stackString.utf8().data());
3289     }
3290
3291 #undef CHECK_EXCEPTION
3292 }
3293
3294 static bool checkUncaughtException(VM& vm, GlobalObject* globalObject, JSValue exception, const String& expectedExceptionName, bool alwaysDumpException)
3295 {
3296     auto scope = DECLARE_CATCH_SCOPE(vm);
3297     scope.clearException();
3298     if (!exception) {
3299         printf("Expected uncaught exception with name '%s' but none was thrown\n", expectedExceptionName.utf8().data());
3300         return false;
3301     }
3302
3303     ExecState* exec = globalObject->globalExec();
3304     JSValue exceptionClass = globalObject->get(exec, Identifier::fromString(exec, expectedExceptionName));
3305     if (!exceptionClass.isObject() || scope.exception()) {
3306         printf("Expected uncaught exception with name '%s' but given exception class is not defined\n", expectedExceptionName.utf8().data());
3307         return false;
3308     }
3309
3310     bool isInstanceOfExpectedException = jsCast<JSObject*>(exceptionClass)->hasInstance(exec, exception);
3311     if (scope.exception()) {
3312         printf("Expected uncaught exception with name '%s' but given exception class fails performing hasInstance\n", expectedExceptionName.utf8().data());
3313         return false;
3314     }
3315     if (isInstanceOfExpectedException) {
3316         if (alwaysDumpException)
3317             dumpException(globalObject, exception);
3318         return true;
3319     }
3320
3321     printf("Expected uncaught exception with name '%s' but exception value is not instance of this exception class\n", expectedExceptionName.utf8().data());
3322     dumpException(globalObject, exception);
3323     return false;
3324 }
3325
3326 static void checkException(GlobalObject* globalObject, bool isLastFile, bool hasException, JSValue value, const String& uncaughtExceptionName, bool alwaysDumpUncaughtException, bool dump, bool& success)
3327 {
3328     VM& vm = globalObject->vm();
3329     if (!uncaughtExceptionName || !isLastFile) {
3330         success = success && !hasException;
3331         if (dump && !hasException)
3332             printf("End: %s\n", value.toWTFString(globalObject->globalExec()).utf8().data());
3333         if (hasException)
3334             dumpException(globalObject, value);
3335     } else
3336         success = success && checkUncaughtException(vm, globalObject, (hasException) ? value : JSValue(), uncaughtExceptionName, alwaysDumpUncaughtException);
3337 }
3338
3339 static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, const String& uncaughtExceptionName, bool alwaysDumpUncaughtException, bool dump, bool module)
3340 {
3341     String fileName;
3342     Vector<char> scriptBuffer;
3343
3344     if (dump)
3345         JSC::Options::dumpGeneratedBytecodes() = true;
3346
3347     VM& vm = globalObject->vm();
3348     auto scope = DECLARE_CATCH_SCOPE(vm);
3349     bool success = true;
3350
3351 #if ENABLE(SAMPLING_FLAGS)
3352     SamplingFlags::start();
3353 #endif
3354
3355     for (size_t i = 0; i < scripts.size(); i++) {
3356         JSInternalPromise* promise = nullptr;
3357         bool isModule = module || scripts[i].scriptType == Script::ScriptType::Module;
3358         if (scripts[i].codeSource == Script::CodeSource::File) {
3359             fileName = scripts[i].argument;
3360             if (scripts[i].strictMode == Script::StrictMode::Strict)
3361                 scriptBuffer.append("\"use strict\";\n", strlen("\"use strict\";\n"));
3362
3363             if (isModule) {
3364                 promise = loadAndEvaluateModule(globalObject->globalExec(), fileName);
3365                 scope.releaseAssertNoException();
3366             } else {
3367                 if (!fetchScriptFromLocalFileSystem(fileName, scriptBuffer))
3368                     return false; // fail early so we can catch missing files
3369             }
3370         } else {
3371             size_t commandLineLength = strlen(scripts[i].argument);
3372             scriptBuffer.resize(commandLineLength);
3373             std::copy(scripts[i].argument, scripts[i].argument + commandLineLength, scriptBuffer.begin());
3374             fileName = ASCIILiteral("[Command Line]");
3375         }
3376
3377         bool isLastFile = i == scripts.size() - 1;
3378         if (isModule) {
3379             if (!promise)
3380                 promise = loadAndEvaluateModule(globalObject->globalExec(), makeSource(stringFromUTF(scriptBuffer), SourceOrigin { absolutePath(fileName) }, fileName, TextPosition(), SourceProviderSourceType::Module));
3381             scope.clearException();
3382
3383             JSFunction* fulfillHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&, isLastFile](ExecState* exec) {
3384                 checkException(globalObject, isLastFile, false, exec->argument(0), uncaughtExceptionName, alwaysDumpUncaughtException, dump, success);
3385                 return JSValue::encode(jsUndefined());
3386             });
3387
3388             JSFunction* rejectHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&, isLastFile](ExecState* exec) {
3389                 checkException(globalObject, isLastFile, true, exec->argument(0), uncaughtExceptionName, alwaysDumpUncaughtException, dump, success);
3390                 return JSValue::encode(jsUndefined());
3391             });
3392
3393             promise->then(globalObject->globalExec(), fulfillHandler, rejectHandler);
3394             scope.releaseAssertNoException();
3395             vm.drainMicrotasks();
3396         } else {
3397             NakedPtr<Exception> evaluationException;
3398             JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(scriptBuffer, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), evaluationException);
3399             scope.assertNoException();
3400             if (evaluationException)
3401                 returnValue = evaluationException->value();
3402             checkException(globalObject, isLastFile, evaluationException, returnValue, uncaughtExceptionName, alwaysDumpUncaughtException, dump, success);
3403         }
3404
3405         scriptBuffer.clear();
3406         scope.clearException();
3407     }
3408
3409 #if ENABLE(REGEXP_TRACING)
3410     vm.dumpRegExpTrace();
3411 #endif
3412     return success;
3413 }
3414
3415 #define RUNNING_FROM_XCODE 0
3416
3417 static void runInteractive(GlobalObject* globalObject)
3418 {
3419     VM& vm = globalObject->vm();
3420     auto scope = DECLARE_CATCH_SCOPE(vm);
3421
3422     std::optional<DirectoryName> directoryName = currentWorkingDirectory();
3423     if (!directoryName)
3424         return;
3425     SourceOrigin sourceOrigin(resolvePath(directoryName.value(), ModuleName("interpreter")));
3426     
3427     bool shouldQuit = false;
3428     while (!shouldQuit) {
3429 #if HAVE(READLINE) && !RUNNING_FROM_XCODE
3430         ParserError error;
3431         String source;
3432         do {
3433             error = ParserError();
3434             char* line = readline(source.isEmpty() ? interactivePrompt : "... ");
3435             shouldQuit = !line;
3436             if (!line)
3437                 break;
3438             source = source + line;
3439             source = source + '\n';
3440             checkSyntax(globalObject->vm(), makeSource(source, sourceOrigin), error);
3441             if (!line[0]) {
3442                 free(line);
3443                 break;
3444             }
3445             add_history(line);
3446             free(line);
3447         } while (error.syntaxErrorType() == ParserError::SyntaxErrorRecoverable);
3448         
3449         if (error.isValid()) {
3450             printf("%s:%d\n", error.message().utf8().data(), error.line());
3451             continue;
3452         }
3453         
3454         
3455         NakedPtr<Exception> evaluationException;
3456         JSValue returnValue = evaluate(globalObject->globalExec(), makeSource(source, sourceOrigin), JSValue(), evaluationException);
3457 #else
3458         printf("%s", interactivePrompt);
3459         Vector<char, 256> line;
3460         int c;
3461         while ((c = getchar()) != EOF) {
3462             // FIXME: Should we also break on \r? 
3463             if (c == '\n')
3464                 break;
3465             line.append(c);
3466         }
3467         if (line.isEmpty())
3468             break;
3469
3470         NakedPtr<Exception> evaluationException;
3471         JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(line, sourceOrigin, sourceOrigin.string()), JSValue(), evaluationException);
3472 #endif
3473         if (evaluationException)
3474             printf("Exception: %s\n", evaluationException->value().toWTFString(globalObject->globalExec()).utf8().data());
3475         else
3476             printf("%s\n", returnValue.toWTFString(globalObject->globalExec()).utf8().data());
3477
3478         scope.clearException();
3479         globalObject->vm().drainMicrotasks();
3480     }
3481     printf("\n");
3482 }
3483
3484 static NO_RETURN void printUsageStatement(bool help = false)
3485 {
3486     fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
3487     fprintf(stderr, "  -d         Dumps bytecode (debug builds only)\n");
3488     fprintf(stderr, "  -e         Evaluate argument as script code\n");
3489     fprintf(stderr, "  -f         Specifies a source file (deprecated)\n");
3490     fprintf(stderr, "  -h|--help  Prints this help message\n");
3491     fprintf(stderr, "  -i         Enables interactive mode (default if no files are specified)\n");
3492     fprintf(stderr, "  -m         Execute as a module\n");
3493 #if HAVE(SIGNAL_H)
3494     fprintf(stderr, "  -s         Installs signal handlers that exit on a crash (Unix platforms only)\n");
3495 #endif
3496     fprintf(stderr, "  -p <file>  Outputs profiling data to a file\n");
3497     fprintf(stderr, "  -x         Output exit code before terminating\n");
3498     fprintf(stderr, "\n");
3499     fprintf(stderr, "  --sample                   Collects and outputs sampling profiler data\n");
3500     fprintf(stderr, "  --test262-async            Check that some script calls the print function with the string 'Test262:AsyncTestComplete'\n");
3501     fprintf(stderr, "  --strict-file=<file>       Parse the given file as if it were in strict mode (this option may be passed more than once)\n");
3502     fprintf(stderr, "  --module-file=<file>       Parse and evaluate the given file as module (this option may be passed more than once)\n");
3503     fprintf(stderr, "  --exception=<name>         Check the last script exits with an uncaught exception with the specified name\n");
3504     fprintf(stderr, "  --dumpException            Dump uncaught exception text\n");
3505     fprintf(stderr, "  --options                  Dumps all JSC VM options and exits\n");
3506     fprintf(stderr, "  --dumpOptions              Dumps all non-default JSC VM options before continuing\n");
3507     fprintf(stderr, "  --<jsc VM option>=<value>  Sets the specified JSC VM option\n");
3508     fprintf(stderr, "\n");
3509
3510     jscExit(help ? EXIT_SUCCESS : EXIT_FAILURE);
3511 }
3512
3513 void CommandLine::parseArguments(int argc, char** argv)
3514 {
3515     Options::initialize();
3516     
3517     int i = 1;
3518     JSC::Options::DumpLevel dumpOptionsLevel = JSC::Options::DumpLevel::None;
3519     bool needToExit = false;
3520
3521     bool hasBadJSCOptions = false;
3522     for (; i < argc; ++i) {
3523         const char* arg = argv[i];
3524         if (!strcmp(arg, "-f")) {
3525             if (++i == argc)
3526                 printUsageStatement();
3527             m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Script, argv[i]));
3528             continue;
3529         }
3530         if (!strcmp(arg, "-e")) {
3531             if (++i == argc)
3532                 printUsageStatement();
3533             m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::CommandLine, Script::ScriptType::Script, argv[i]));
3534             continue;
3535         }
3536         if (!strcmp(arg, "-i")) {
3537             m_interactive = true;
3538             continue;
3539         }
3540         if (!strcmp(arg, "-d")) {
3541             m_dump = true;
3542             continue;
3543         }
3544         if (!strcmp(arg, "-p")) {
3545             if (++i == argc)
3546                 printUsageStatement();
3547             m_profile = true;
3548             m_profilerOutput = argv[i];
3549             continue;
3550         }
3551         if (!strcmp(arg, "-m")) {
3552             m_module = true;
3553             continue;
3554         }
3555         if (!strcmp(arg, "-s")) {
3556 #if HAVE(SIGNAL_H)
3557             signal(SIGILL, _exit);
3558             signal(SIGFPE, _exit);
3559             signal(SIGBUS, _exit);
3560             signal(SIGSEGV, _exit);
3561 #endif
3562             continue;
3563         }
3564         if (!strcmp(arg, "-x")) {
3565             m_exitCode = true;
3566             continue;
3567         }
3568         if (!strcmp(arg, "--")) {
3569             ++i;
3570             break;
3571         }
3572         if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
3573             printUsageStatement(true);
3574
3575         if (!strcmp(arg, "--options")) {
3576             dumpOptionsLevel = JSC::Options::DumpLevel::Verbose;
3577             needToExit = true;
3578             continue;
3579         }
3580         if (!strcmp(arg, "--dumpOptions")) {
3581             dumpOptionsLevel = JSC::Options::DumpLevel::Overridden;
3582             continue;
3583         }
3584         if (!strcmp(arg, "--sample")) {
3585             JSC::Options::useSamplingProfiler() = true;
3586             JSC::Options::collectSamplingProfilerDataForJSCShell() = true;
3587             m_dumpSamplingProfilerData = true;
3588             continue;
3589         }
3590
3591         static const char* timeoutMultiplierOptStr = "--timeoutMultiplier=";
3592         static const unsigned timeoutMultiplierOptStrLength = strlen(timeoutMultiplierOptStr);
3593         if (!strncmp(arg, timeoutMultiplierOptStr, timeoutMultiplierOptStrLength)) {
3594             const char* valueStr = &arg[timeoutMultiplierOptStrLength];
3595             if (sscanf(valueStr, "%lf", &s_timeoutMultiplier) != 1)
3596                 dataLog("WARNING: --timeoutMultiplier=", valueStr, " is invalid. Expects a numeric ratio.\n");
3597             continue;
3598         }
3599
3600         if (!strcmp(arg, "--test262-async")) {
3601             asyncTestExpectedPasses++;
3602             continue;
3603         }
3604
3605         if (!strcmp(arg, "--remote-debug")) {
3606             m_enableRemoteDebugging = true;
3607             continue;
3608         }
3609
3610         static const unsigned strictFileStrLength = strlen("--strict-file=");
3611         if (!strncmp(arg, "--strict-file=", strictFileStrLength)) {
3612             m_scripts.append(Script(Script::StrictMode::Strict, Script::CodeSource::File, Script::ScriptType::Script, argv[i] + strictFileStrLength));
3613             continue;
3614         }
3615
3616         static const unsigned moduleFileStrLength = strlen("--module-file=");
3617         if (!strncmp(arg, "--module-file=", moduleFileStrLength)) {
3618             m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Module, argv[i] + moduleFileStrLength));
3619             continue;
3620         }
3621
3622         if (!strcmp(arg, "--dumpException")) {
3623             m_alwaysDumpUncaughtException = true;
3624             continue;
3625         }
3626
3627         static const unsigned exceptionStrLength = strlen("--exception=");
3628         if (!strncmp(arg, "--exception=", exceptionStrLength)) {
3629             m_uncaughtExceptionName = String(arg + exceptionStrLength);
3630             continue;
3631         }
3632
3633         // See if the -- option is a JSC VM option.
3634         if (strstr(arg, "--") == arg) {
3635             if (!JSC::Options::setOption(&arg[2])) {
3636                 hasBadJSCOptions = true;
3637                 dataLog("ERROR: invalid option: ", arg, "\n");
3638             }
3639             continue;
3640         }
3641
3642         // This arg is not recognized by the VM nor by jsc. Pass it on to the
3643         // script.
3644         m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Script, argv[i]));
3645     }
3646
3647     if (hasBadJSCOptions && JSC::Options::validateOptions())
3648         CRASH();
3649
3650     if (m_scripts.isEmpty())
3651         m_interactive = true;
3652
3653     for (; i < argc; ++i)
3654         m_arguments.append(argv[i]);
3655
3656     if (dumpOptionsLevel != JSC::Options::DumpLevel::None) {
3657         const char* optionsTitle = (dumpOptionsLevel == JSC::Options::DumpLevel::Overridden)
3658             ? "Modified JSC runtime options:"
3659             : "All JSC runtime options:";
3660         JSC::Options::dumpAllOptions(stderr, dumpOptionsLevel, optionsTitle);
3661     }
3662     JSC::Options::ensureOptionsAreCoherent();
3663     if (needToExit)
3664         jscExit(EXIT_SUCCESS);
3665 }
3666
3667 template<typename Func>
3668 int runJSC(CommandLine options, bool isWorker, const Func& func)
3669 {
3670     Worker worker(Workers::singleton());
3671     
3672     VM& vm = VM::create(LargeHeap).leakRef();
3673     int result;
3674     bool success;
3675     {
3676         JSLockHolder locker(vm);
3677
3678         if (options.m_profile && !vm.m_perBytecodeProfiler)
3679             vm.m_perBytecodeProfiler = std::make_unique<Profiler::Database>(vm);
3680
3681         GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), options.m_arguments);
3682         globalObject->setRemoteDebuggingEnabled(options.m_enableRemoteDebugging);
3683         success = func(vm, globalObject);
3684         if (options.m_interactive && success)
3685             runInteractive(globalObject);
3686
3687         vm.drainMicrotasks();
3688     }
3689     vm.promiseDeferredTimer->runRunLoop();
3690
3691     result = success && (asyncTestExpectedPasses == asyncTestPasses) ? 0 : 3;
3692
3693     if (options.m_exitCode) {
3694         printf("jsc exiting %d", result);
3695         if (asyncTestExpectedPasses != asyncTestPasses)
3696             printf(" because expected: %d async test passes but got: %d async test passes", asyncTestExpectedPasses, asyncTestPasses);
3697         printf("\n");
3698     }
3699
3700     if (options.m_profile) {
3701         JSLockHolder locker(vm);
3702         if (!vm.m_perBytecodeProfiler->save(options.m_profilerOutput.utf8().data()))
3703             fprintf(stderr, "could not save profiler output.\n");
3704     }
3705
3706 #if ENABLE(JIT)
3707     {
3708         JSLockHolder locker(vm);
3709         if (Options::useExceptionFuzz())
3710             printf("JSC EXCEPTION FUZZ: encountered %u checks.\n", numberOfExceptionFuzzChecks());
3711         bool fireAtEnabled =
3712         Options::fireExecutableAllocationFuzzAt() || Options::fireExecutableAllocationFuzzAtOrAfter();
3713         if (Options::useExecutableAllocationFuzz() && (!fireAtEnabled || Options::verboseExecutableAllocationFuzz()))
3714             printf("JSC EXECUTABLE ALLOCATION FUZZ: encountered %u checks.\n", numberOfExecutableAllocationFuzzChecks());
3715         if (Options::useOSRExitFuzz()) {
3716             printf("JSC OSR EXIT FUZZ: encountered %u static checks.\n", numberOfStaticOSRExitFuzzChecks());
3717             printf("JSC OSR EXIT FUZZ: encountered %u dynamic checks.\n", numberOfOSRExitFuzzChecks());
3718         }
3719
3720         
3721         auto compileTimeStats = JIT::compileTimeStats();
3722         Vector<CString> compileTimeKeys;
3723         for (auto& entry : compileTimeStats)
3724             compileTimeKeys.append(entry.key);
3725         std::sort(compileTimeKeys.begin(), compileTimeKeys.end());
3726         for (CString key : compileTimeKeys)
3727             printf("%40s: %.3lf ms\n", key.data(), compileTimeStats.get(key));
3728     }
3729 #endif
3730
3731     if (Options::gcAtEnd()) {
3732         // We need to hold the API lock to do a GC.
3733         JSLockHolder locker(&vm);
3734         vm.heap.collectNow(Sync, CollectionScope::Full);
3735     }
3736
3737     if (options.m_dumpSamplingProfilerData) {
3738 #if ENABLE(SAMPLING_PROFILER)
3739         JSLockHolder locker(&vm);
3740         vm.samplingProfiler()->reportTopFunctions();
3741         vm.samplingProfiler()->reportTopBytecodes();
3742 #else
3743         dataLog("Sampling profiler is not enabled on this platform\n");
3744 #endif
3745     }
3746
3747     if (isWorker) {
3748         JSLockHolder locker(vm);
3749         // This is needed because we don't want the worker's main
3750         // thread to die before its compilation threads finish.
3751         vm.deref();
3752     }
3753
3754     return result;
3755 }
3756
3757 int jscmain(int argc, char** argv)
3758 {
3759     // Need to override and enable restricted options before we start parsing options below.
3760     Options::enableRestrictedOptions(true);
3761
3762     // Note that the options parsing can affect VM creation, and thus
3763     // comes first.
3764     CommandLine options(argc, argv);
3765
3766     processConfigFile(Options::configFile(), "jsc");
3767
3768     // Initialize JSC before getting VM.
3769     WTF::initializeMainThread();
3770     JSC::initializeThreading();
3771     startTimeoutThreadIfNeeded();
3772 #if ENABLE(WEBASSEMBLY)
3773     JSC::Wasm::enableFastMemory();
3774 #endif
3775
3776     int result;
3777     result = runJSC(
3778         options, false,
3779         [&] (VM&, GlobalObject* globalObject) {
3780             return runWithScripts(globalObject, options.m_scripts, options.m_uncaughtExceptionName, options.m_alwaysDumpUncaughtException, options.m_dump, options.m_module);
3781         });
3782
3783     printSuperSamplerState();
3784
3785     return result;
3786 }
3787
3788 #if OS(WINDOWS)
3789 extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(int argc, const char* argv[])
3790 {
3791     return main(argc, const_cast<char**>(argv));
3792 }
3793 #endif