source: webkit/trunk/Source/JavaScriptCore/jsc.cpp@ 221878

Last change on this file since 221878 was 221878, checked in by [email protected], 8 years ago

Make jsc dump the command line if JSC_dumpOption environment variable is set with a non-zero value.
https://bugs.webkit.org/show_bug.cgi?id=176722

Reviewed by Saam Barati.

For PLATFORM(COCOA), I also dumped the JSC_* environmental variables that are
in effect when jsc is invoked.

  • jsc.cpp:

(CommandLine::parseArguments):

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