1/*
2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3 * Copyright (C) 2004-2018 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Bjoern Graf (bjoern.graf@gmail.com)
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#include "config.h"
24
25#include "ArrayBuffer.h"
26#include "ArrayPrototype.h"
27#include "BuiltinNames.h"
28#include "ButterflyInlines.h"
29#include "CatchScope.h"
30#include "CodeBlock.h"
31#include "CodeCache.h"
32#include "Completion.h"
33#include "ConfigFile.h"
34#include "Disassembler.h"
35#include "Exception.h"
36#include "ExceptionHelpers.h"
37#include "HeapProfiler.h"
38#include "HeapSnapshotBuilder.h"
39#include "InitializeThreading.h"
40#include "Interpreter.h"
41#include "JIT.h"
42#include "JSArray.h"
43#include "JSArrayBuffer.h"
44#include "JSBigInt.h"
45#include "JSCInlines.h"
46#include "JSFunction.h"
47#include "JSInternalPromise.h"
48#include "JSInternalPromiseDeferred.h"
49#include "JSLock.h"
50#include "JSModuleLoader.h"
51#include "JSNativeStdFunction.h"
52#include "JSONObject.h"
53#include "JSSourceCode.h"
54#include "JSString.h"
55#include "JSTypedArrays.h"
56#include "JSWebAssemblyInstance.h"
57#include "JSWebAssemblyMemory.h"
58#include "LLIntThunks.h"
59#include "ObjectConstructor.h"
60#include "ParserError.h"
61#include "ProfilerDatabase.h"
62#include "PromiseDeferredTimer.h"
63#include "ProtoCallFrame.h"
64#include "ReleaseHeapAccessScope.h"
65#include "SamplingProfiler.h"
66#include "StackVisitor.h"
67#include "StructureInlines.h"
68#include "StructureRareDataInlines.h"
69#include "SuperSampler.h"
70#include "TestRunnerUtils.h"
71#include "TypedArrayInlines.h"
72#include "WasmCapabilities.h"
73#include "WasmContext.h"
74#include "WasmFaultSignalHandler.h"
75#include "WasmMemory.h"
76#include <locale.h>
77#include <math.h>
78#include <stdio.h>
79#include <stdlib.h>
80#include <string.h>
81#include <sys/stat.h>
82#include <sys/types.h>
83#include <thread>
84#include <type_traits>
85#include <wtf/Box.h>
86#include <wtf/CommaPrinter.h>
87#include <wtf/MainThread.h>
88#include <wtf/MemoryPressureHandler.h>
89#include <wtf/MonotonicTime.h>
90#include <wtf/NeverDestroyed.h>
91#include <wtf/Scope.h>
92#include <wtf/StringPrintStream.h>
93#include <wtf/URL.h>
94#include <wtf/WallTime.h>
95#include <wtf/text/StringBuilder.h>
96#include <wtf/text/StringConcatenateNumbers.h>
97
98#if OS(WINDOWS)
99#include <direct.h>
100#include <fcntl.h>
101#include <io.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_FAMILY) && CPU(ARM_THUMB2)
134#include <fenv.h>
135#include <arm/arch.h>
136#endif
137
138#if __has_include(<WebKitAdditions/MemoryFootprint.h>)
139#include <WebKitAdditions/MemoryFootprint.h>
140#else
141struct MemoryFootprint {
142 uint64_t current;
143 uint64_t peak;
144
145 static MemoryFootprint now()
146 {
147 return { 0L, 0L };
148 }
149
150 static void resetPeak()
151 {
152 }
153};
154#endif
155
156#if !defined(PATH_MAX)
157#define PATH_MAX 4096
158#endif
159
160using namespace JSC;
161
162namespace {
163
164NO_RETURN_WITH_VALUE static void jscExit(int status)
165{
166 waitForAsynchronousDisassembly();
167
168#if ENABLE(DFG_JIT)
169 if (DFG::isCrashing()) {
170 for (;;) {
171#if OS(WINDOWS)
172 Sleep(1000);
173#else
174 pause();
175#endif
176 }
177 }
178#endif // ENABLE(DFG_JIT)
179 exit(status);
180}
181
182class Masquerader : public JSNonFinalObject {
183public:
184 Masquerader(VM& vm, Structure* structure)
185 : Base(vm, structure)
186 {
187 }
188
189 typedef JSNonFinalObject Base;
190 static const unsigned StructureFlags = Base::StructureFlags | JSC::MasqueradesAsUndefined;
191
192 static Masquerader* create(VM& vm, JSGlobalObject* globalObject)
193 {
194 globalObject->masqueradesAsUndefinedWatchpoint()->fireAll(vm, "Masquerading object allocated");
195 Structure* structure = createStructure(vm, globalObject, jsNull());
196 Masquerader* result = new (NotNull, allocateCell<Masquerader>(vm.heap, sizeof(Masquerader))) Masquerader(vm, structure);
197 result->finishCreation(vm);
198 return result;
199 }
200
201 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
202 {
203 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
204 }
205
206 DECLARE_INFO;
207};
208
209const ClassInfo Masquerader::s_info = { "Masquerader", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(Masquerader) };
210static unsigned asyncTestPasses { 0 };
211static unsigned asyncTestExpectedPasses { 0 };
212
213}
214
215template<typename Vector>
216static bool fillBufferWithContentsOfFile(const String& fileName, Vector& buffer);
217static RefPtr<Uint8Array> fillBufferWithContentsOfFile(const String& fileName);
218
219class CommandLine;
220class GlobalObject;
221class Workers;
222
223template<typename Func>
224int runJSC(const CommandLine&, bool isWorker, const Func&);
225static void checkException(ExecState*, GlobalObject*, bool isLastFile, bool hasException, JSValue, CommandLine&, bool& success);
226
227class Message : public ThreadSafeRefCounted<Message> {
228public:
229 Message(ArrayBufferContents&&, int32_t);
230 ~Message();
231
232 ArrayBufferContents&& releaseContents() { return WTFMove(m_contents); }
233 int32_t index() const { return m_index; }
234
235private:
236 ArrayBufferContents m_contents;
237 int32_t m_index { 0 };
238};
239
240class Worker : public BasicRawSentinelNode<Worker> {
241public:
242 Worker(Workers&);
243 ~Worker();
244
245 void enqueue(const AbstractLocker&, RefPtr<Message>);
246 RefPtr<Message> dequeue();
247
248 static Worker& current();
249
250private:
251 static ThreadSpecific<Worker*>& currentWorker();
252
253 Workers& m_workers;
254 Deque<RefPtr<Message>> m_messages;
255};
256
257class Workers {
258 WTF_MAKE_FAST_ALLOCATED;
259 WTF_MAKE_NONCOPYABLE(Workers);
260public:
261 Workers();
262 ~Workers();
263
264 template<typename Func>
265 void broadcast(const Func&);
266
267 void report(const String&);
268 String tryGetReport();
269 String getReport();
270
271 static Workers& singleton();
272
273private:
274 friend class Worker;
275
276 Lock m_lock;
277 Condition m_condition;
278 SentinelLinkedList<Worker, BasicRawSentinelNode<Worker>> m_workers;
279 Deque<String> m_reports;
280};
281
282
283static EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState*);
284
285static EncodedJSValue JSC_HOST_CALL functionPrintStdOut(ExecState*);
286static EncodedJSValue JSC_HOST_CALL functionPrintStdErr(ExecState*);
287static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
288static EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState*);
289static EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState*);
290static EncodedJSValue JSC_HOST_CALL functionSleepSeconds(ExecState*);
291static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
292static EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState*);
293static EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState*);
294static EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState*);
295static EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*);
296static EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState*);
297static EncodedJSValue JSC_HOST_CALL functionCreateMemoryFootprint(ExecState*);
298static EncodedJSValue JSC_HOST_CALL functionResetMemoryPeak(ExecState*);
299static EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState*);
300static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
301static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
302static EncodedJSValue JSC_HOST_CALL functionRunString(ExecState*);
303static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
304static EncodedJSValue JSC_HOST_CALL functionLoadString(ExecState*);
305static EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState*);
306static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
307static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
308static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
309static EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState*);
310static EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState*);
311static EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState*);
312static EncodedJSValue JSC_HOST_CALL functionNoOSRExitFuzzing(ExecState*);
313static EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState*);
314static EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState*);
315static EncodedJSValue JSC_HOST_CALL functionJSCOptions(ExecState*);
316static EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState*);
317static EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState*);
318static EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState*);
319static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
320static EncodedJSValue JSC_HOST_CALL functionFalse(ExecState*);
321static EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*);
322static EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*);
323static EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState*);
324static EncodedJSValue JSC_HOST_CALL functionIsPureNaN(ExecState*);
325static EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*);
326static EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState*);
327static EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState*);
328static EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState*);
329static EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState*);
330static EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState*);
331static EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*);
332static EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState*);
333static EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*);
334static EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState*);
335static EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshotForGCDebugging(ExecState*);
336static EncodedJSValue JSC_HOST_CALL functionResetSuperSamplerState(ExecState*);
337static EncodedJSValue JSC_HOST_CALL functionEnsureArrayStorage(ExecState*);
338#if ENABLE(SAMPLING_PROFILER)
339static EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState*);
340static EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState*);
341#endif
342
343static EncodedJSValue JSC_HOST_CALL functionMaxArguments(ExecState*);
344static EncodedJSValue JSC_HOST_CALL functionAsyncTestStart(ExecState*);
345static EncodedJSValue JSC_HOST_CALL functionAsyncTestPassed(ExecState*);
346
347#if ENABLE(WEBASSEMBLY)
348static EncodedJSValue JSC_HOST_CALL functionWebAssemblyMemoryMode(ExecState*);
349#endif
350
351#if ENABLE(SAMPLING_FLAGS)
352static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
353static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
354#endif
355
356static EncodedJSValue JSC_HOST_CALL functionGetRandomSeed(ExecState*);
357static EncodedJSValue JSC_HOST_CALL functionSetRandomSeed(ExecState*);
358static EncodedJSValue JSC_HOST_CALL functionIsRope(ExecState*);
359static EncodedJSValue JSC_HOST_CALL functionCallerSourceOrigin(ExecState*);
360static EncodedJSValue JSC_HOST_CALL functionDollarCreateRealm(ExecState*);
361static EncodedJSValue JSC_HOST_CALL functionDollarDetachArrayBuffer(ExecState*);
362static EncodedJSValue JSC_HOST_CALL functionDollarEvalScript(ExecState*);
363static EncodedJSValue JSC_HOST_CALL functionDollarAgentStart(ExecState*);
364static EncodedJSValue JSC_HOST_CALL functionDollarAgentReceiveBroadcast(ExecState*);
365static EncodedJSValue JSC_HOST_CALL functionDollarAgentReport(ExecState*);
366static EncodedJSValue JSC_HOST_CALL functionDollarAgentSleep(ExecState*);
367static EncodedJSValue JSC_HOST_CALL functionDollarAgentBroadcast(ExecState*);
368static EncodedJSValue JSC_HOST_CALL functionDollarAgentGetReport(ExecState*);
369static EncodedJSValue JSC_HOST_CALL functionDollarAgentLeaving(ExecState*);
370static EncodedJSValue JSC_HOST_CALL functionDollarAgentMonotonicNow(ExecState*);
371static EncodedJSValue JSC_HOST_CALL functionWaitForReport(ExecState*);
372static EncodedJSValue JSC_HOST_CALL functionHeapCapacity(ExecState*);
373static EncodedJSValue JSC_HOST_CALL functionFlashHeapAccess(ExecState*);
374static EncodedJSValue JSC_HOST_CALL functionDisableRichSourceInfo(ExecState*);
375static EncodedJSValue JSC_HOST_CALL functionMallocInALoop(ExecState*);
376static EncodedJSValue JSC_HOST_CALL functionTotalCompileTime(ExecState*);
377
378struct Script {
379 enum class StrictMode {
380 Strict,
381 Sloppy
382 };
383
384 enum class ScriptType {
385 Script,
386 Module
387 };
388
389 enum class CodeSource {
390 File,
391 CommandLine
392 };
393
394 StrictMode strictMode;
395 CodeSource codeSource;
396 ScriptType scriptType;
397 char* argument;
398
399 Script(StrictMode strictMode, CodeSource codeSource, ScriptType scriptType, char *argument)
400 : strictMode(strictMode)
401 , codeSource(codeSource)
402 , scriptType(scriptType)
403 , argument(argument)
404 {
405 if (strictMode == StrictMode::Strict)
406 ASSERT(codeSource == CodeSource::File);
407 }
408};
409
410class CommandLine {
411public:
412 CommandLine(int argc, char** argv)
413 {
414 parseArguments(argc, argv);
415 }
416
417 Vector<Script> m_scripts;
418 Vector<String> m_arguments;
419 String m_profilerOutput;
420 String m_uncaughtExceptionName;
421 bool m_interactive { false };
422 bool m_dump { false };
423 bool m_module { false };
424 bool m_exitCode { false };
425 bool m_destroyVM { false };
426 bool m_profile { false };
427 bool m_treatWatchdogExceptionAsSuccess { false };
428 bool m_alwaysDumpUncaughtException { false };
429 bool m_dumpMemoryFootprint { false };
430 bool m_dumpSamplingProfilerData { false };
431 bool m_enableRemoteDebugging { false };
432
433 void parseArguments(int, char**);
434};
435
436static const char interactivePrompt[] = ">>> ";
437
438class StopWatch {
439public:
440 void start();
441 void stop();
442 long getElapsedMS(); // call stop() first
443
444private:
445 MonotonicTime m_startTime;
446 MonotonicTime m_stopTime;
447};
448
449void StopWatch::start()
450{
451 m_startTime = MonotonicTime::now();
452}
453
454void StopWatch::stop()
455{
456 m_stopTime = MonotonicTime::now();
457}
458
459long StopWatch::getElapsedMS()
460{
461 return (m_stopTime - m_startTime).millisecondsAs<long>();
462}
463
464template<typename Vector>
465static inline String stringFromUTF(const Vector& utf8)
466{
467 return String::fromUTF8WithLatin1Fallback(utf8.data(), utf8.size());
468}
469
470class GlobalObject : public JSGlobalObject {
471private:
472 GlobalObject(VM&, Structure*);
473
474public:
475 typedef JSGlobalObject Base;
476
477 static GlobalObject* create(VM& vm, Structure* structure, const Vector<String>& arguments)
478 {
479 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(vm.heap)) GlobalObject(vm, structure);
480 object->finishCreation(vm, arguments);
481 return object;
482 }
483
484 static const bool needsDestruction = false;
485
486 DECLARE_INFO;
487 static const GlobalObjectMethodTable s_globalObjectMethodTable;
488
489 static Structure* createStructure(VM& vm, JSValue prototype)
490 {
491 return Structure::create(vm, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
492 }
493
494 static RuntimeFlags javaScriptRuntimeFlags(const JSGlobalObject*) { return RuntimeFlags::createAllEnabled(); }
495
496protected:
497 void finishCreation(VM& vm, const Vector<String>& arguments)
498 {
499 Base::finishCreation(vm);
500
501 addFunction(vm, "debug", functionDebug, 1);
502 addFunction(vm, "describe", functionDescribe, 1);
503 addFunction(vm, "describeArray", functionDescribeArray, 1);
504 addFunction(vm, "print", functionPrintStdOut, 1);
505 addFunction(vm, "printErr", functionPrintStdErr, 1);
506 addFunction(vm, "quit", functionQuit, 0);
507 addFunction(vm, "gc", functionGCAndSweep, 0);
508 addFunction(vm, "fullGC", functionFullGC, 0);
509 addFunction(vm, "edenGC", functionEdenGC, 0);
510 addFunction(vm, "forceGCSlowPaths", functionForceGCSlowPaths, 0);
511 addFunction(vm, "gcHeapSize", functionHeapSize, 0);
512 addFunction(vm, "MemoryFootprint", functionCreateMemoryFootprint, 0);
513 addFunction(vm, "resetMemoryPeak", functionResetMemoryPeak, 0);
514 addFunction(vm, "addressOf", functionAddressOf, 1);
515 addFunction(vm, "version", functionVersion, 1);
516 addFunction(vm, "run", functionRun, 1);
517 addFunction(vm, "runString", functionRunString, 1);
518 addFunction(vm, "load", functionLoad, 1);
519 addFunction(vm, "loadString", functionLoadString, 1);
520 addFunction(vm, "readFile", functionReadFile, 2);
521 addFunction(vm, "read", functionReadFile, 2);
522 addFunction(vm, "checkSyntax", functionCheckSyntax, 1);
523 addFunction(vm, "sleepSeconds", functionSleepSeconds, 1);
524 addFunction(vm, "jscStack", functionJSCStack, 1);
525 addFunction(vm, "readline", functionReadline, 0);
526 addFunction(vm, "preciseTime", functionPreciseTime, 0);
527 addFunction(vm, "neverInlineFunction", functionNeverInlineFunction, 1);
528 addFunction(vm, "noInline", functionNeverInlineFunction, 1);
529 addFunction(vm, "noDFG", functionNoDFG, 1);
530 addFunction(vm, "noFTL", functionNoFTL, 1);
531 addFunction(vm, "noOSRExitFuzzing", functionNoOSRExitFuzzing, 1);
532 addFunction(vm, "numberOfDFGCompiles", functionNumberOfDFGCompiles, 1);
533 addFunction(vm, "jscOptions", functionJSCOptions, 0);
534 addFunction(vm, "optimizeNextInvocation", functionOptimizeNextInvocation, 1);
535 addFunction(vm, "reoptimizationRetryCount", functionReoptimizationRetryCount, 1);
536 addFunction(vm, "transferArrayBuffer", functionTransferArrayBuffer, 1);
537 addFunction(vm, "failNextNewCodeBlock", functionFailNextNewCodeBlock, 1);
538#if ENABLE(SAMPLING_FLAGS)
539 addFunction(vm, "setSamplingFlags", functionSetSamplingFlags, 1);
540 addFunction(vm, "clearSamplingFlags", functionClearSamplingFlags, 1);
541#endif
542
543 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "OSRExit"), 0, functionUndefined1, OSRExitIntrinsic, static_cast<unsigned>(PropertyAttribute::DontEnum));
544 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isFinalTier"), 0, functionFalse, IsFinalTierIntrinsic, static_cast<unsigned>(PropertyAttribute::DontEnum));
545 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "predictInt32"), 0, functionUndefined2, SetInt32HeapPredictionIntrinsic, static_cast<unsigned>(PropertyAttribute::DontEnum));
546 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isInt32"), 0, functionIsInt32, CheckInt32Intrinsic, static_cast<unsigned>(PropertyAttribute::DontEnum));
547 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isPureNaN"), 0, functionIsPureNaN, CheckInt32Intrinsic, static_cast<unsigned>(PropertyAttribute::DontEnum));
548 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "fiatInt52"), 0, functionIdentity, FiatInt52Intrinsic, static_cast<unsigned>(PropertyAttribute::DontEnum));
549
550 addFunction(vm, "effectful42", functionEffectful42, 0);
551 addFunction(vm, "makeMasquerader", functionMakeMasquerader, 0);
552 addFunction(vm, "hasCustomProperties", functionHasCustomProperties, 0);
553
554 addFunction(vm, "createGlobalObject", functionCreateGlobalObject, 0);
555
556 addFunction(vm, "dumpTypesForAllVariables", functionDumpTypesForAllVariables , 0);
557
558 addFunction(vm, "drainMicrotasks", functionDrainMicrotasks, 0);
559
560 addFunction(vm, "getRandomSeed", functionGetRandomSeed, 0);
561 addFunction(vm, "setRandomSeed", functionSetRandomSeed, 1);
562 addFunction(vm, "isRope", functionIsRope, 1);
563 addFunction(vm, "callerSourceOrigin", functionCallerSourceOrigin, 0);
564
565 addFunction(vm, "is32BitPlatform", functionIs32BitPlatform, 0);
566
567 addFunction(vm, "checkModuleSyntax", functionCheckModuleSyntax, 1);
568
569 addFunction(vm, "platformSupportsSamplingProfiler", functionPlatformSupportsSamplingProfiler, 0);
570 addFunction(vm, "generateHeapSnapshot", functionGenerateHeapSnapshot, 0);
571 addFunction(vm, "generateHeapSnapshotForGCDebugging", functionGenerateHeapSnapshotForGCDebugging, 0);
572 addFunction(vm, "resetSuperSamplerState", functionResetSuperSamplerState, 0);
573 addFunction(vm, "ensureArrayStorage", functionEnsureArrayStorage, 0);
574#if ENABLE(SAMPLING_PROFILER)
575 addFunction(vm, "startSamplingProfiler", functionStartSamplingProfiler, 0);
576 addFunction(vm, "samplingProfilerStackTraces", functionSamplingProfilerStackTraces, 0);
577#endif
578
579 addFunction(vm, "maxArguments", functionMaxArguments, 0);
580
581 addFunction(vm, "asyncTestStart", functionAsyncTestStart, 1);
582 addFunction(vm, "asyncTestPassed", functionAsyncTestPassed, 1);
583
584#if ENABLE(WEBASSEMBLY)
585 addFunction(vm, "WebAssemblyMemoryMode", functionWebAssemblyMemoryMode, 1);
586#endif
587
588 if (!arguments.isEmpty()) {
589 JSArray* array = constructEmptyArray(globalExec(), 0);
590 for (size_t i = 0; i < arguments.size(); ++i)
591 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]));
592 putDirect(vm, Identifier::fromString(globalExec(), "arguments"), array);
593 }
594
595 putDirect(vm, Identifier::fromString(globalExec(), "console"), jsUndefined());
596
597 Structure* plainObjectStructure = JSFinalObject::createStructure(vm, this, objectPrototype(), 0);
598
599 JSObject* dollar = JSFinalObject::create(vm, plainObjectStructure);
600 putDirect(vm, Identifier::fromString(globalExec(), "$"), dollar);
601 putDirect(vm, Identifier::fromString(globalExec(), "$262"), dollar);
602
603 addFunction(vm, dollar, "createRealm", functionDollarCreateRealm, 0);
604 addFunction(vm, dollar, "detachArrayBuffer", functionDollarDetachArrayBuffer, 1);
605 addFunction(vm, dollar, "evalScript", functionDollarEvalScript, 1);
606
607 dollar->putDirect(vm, Identifier::fromString(globalExec(), "global"), this);
608
609 JSObject* agent = JSFinalObject::create(vm, plainObjectStructure);
610 dollar->putDirect(vm, Identifier::fromString(globalExec(), "agent"), agent);
611
612 // The test262 INTERPRETING.md document says that some of these functions are just in the main
613 // thread and some are in the other threads. We just put them in all threads.
614 addFunction(vm, agent, "start", functionDollarAgentStart, 1);
615 addFunction(vm, agent, "receiveBroadcast", functionDollarAgentReceiveBroadcast, 1);
616 addFunction(vm, agent, "report", functionDollarAgentReport, 1);
617 addFunction(vm, agent, "sleep", functionDollarAgentSleep, 1);
618 addFunction(vm, agent, "broadcast", functionDollarAgentBroadcast, 1);
619 addFunction(vm, agent, "getReport", functionDollarAgentGetReport, 0);
620 addFunction(vm, agent, "leaving", functionDollarAgentLeaving, 0);
621 addFunction(vm, agent, "monotonicNow", functionDollarAgentMonotonicNow, 0);
622
623 addFunction(vm, "waitForReport", functionWaitForReport, 0);
624
625 addFunction(vm, "heapCapacity", functionHeapCapacity, 0);
626 addFunction(vm, "flashHeapAccess", functionFlashHeapAccess, 0);
627
628 addFunction(vm, "disableRichSourceInfo", functionDisableRichSourceInfo, 0);
629 addFunction(vm, "mallocInALoop", functionMallocInALoop, 0);
630 addFunction(vm, "totalCompileTime", functionTotalCompileTime, 0);
631 }
632
633 void addFunction(VM& vm, JSObject* object, const char* name, NativeFunction function, unsigned arguments)
634 {
635 Identifier identifier = Identifier::fromString(&vm, name);
636 object->putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function));
637 }
638
639 void addFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
640 {
641 addFunction(vm, this, name, function, arguments);
642 }
643
644 static JSInternalPromise* moduleLoaderImportModule(JSGlobalObject*, ExecState*, JSModuleLoader*, JSString*, JSValue, const SourceOrigin&);
645 static Identifier moduleLoaderResolve(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSValue, JSValue);
646 static JSInternalPromise* moduleLoaderFetch(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSValue, JSValue);
647 static JSObject* moduleLoaderCreateImportMetaProperties(JSGlobalObject*, ExecState*, JSModuleLoader*, JSValue, JSModuleRecord*, JSValue);
648};
649
650static bool supportsRichSourceInfo = true;
651static bool shellSupportsRichSourceInfo(const JSGlobalObject*)
652{
653 return supportsRichSourceInfo;
654}
655
656const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(GlobalObject) };
657const GlobalObjectMethodTable GlobalObject::s_globalObjectMethodTable = {
658 &shellSupportsRichSourceInfo,
659 &shouldInterruptScript,
660 &javaScriptRuntimeFlags,
661 nullptr, // queueTaskToEventLoop
662 &shouldInterruptScriptBeforeTimeout,
663 &moduleLoaderImportModule,
664 &moduleLoaderResolve,
665 &moduleLoaderFetch,
666 &moduleLoaderCreateImportMetaProperties,
667 nullptr, // moduleLoaderEvaluate
668 nullptr, // promiseRejectionTracker
669 nullptr, // defaultLanguage
670 nullptr, // compileStreaming
671 nullptr, // instantinateStreaming
672};
673
674GlobalObject::GlobalObject(VM& vm, Structure* structure)
675 : JSGlobalObject(vm, structure, &s_globalObjectMethodTable)
676{
677}
678
679static UChar pathSeparator()
680{
681#if OS(WINDOWS)
682 return '\\';
683#else
684 return '/';
685#endif
686}
687
688struct DirectoryName {
689 // In unix, it is "/". In Windows, it becomes a drive letter like "C:\"
690 String rootName;
691
692 // If the directory name is "/home/WebKit", this becomes "home/WebKit". If the directory name is "/", this becomes "".
693 String queryName;
694};
695
696struct ModuleName {
697 ModuleName(const String& moduleName);
698
699 bool startsWithRoot() const
700 {
701 return !queries.isEmpty() && queries[0].isEmpty();
702 }
703
704 Vector<String> queries;
705};
706
707ModuleName::ModuleName(const String& moduleName)
708{
709 // A module name given from code is represented as the UNIX style path. Like, `./A/B.js`.
710 queries = moduleName.splitAllowingEmptyEntries('/');
711}
712
713static Optional<DirectoryName> extractDirectoryName(const String& absolutePathToFile)
714{
715 size_t firstSeparatorPosition = absolutePathToFile.find(pathSeparator());
716 if (firstSeparatorPosition == notFound)
717 return WTF::nullopt;
718 DirectoryName directoryName;
719 directoryName.rootName = absolutePathToFile.substring(0, firstSeparatorPosition + 1); // Include the separator.
720 size_t lastSeparatorPosition = absolutePathToFile.reverseFind(pathSeparator());
721 ASSERT_WITH_MESSAGE(lastSeparatorPosition != notFound, "If the separator is not found, this function already returns when performing the forward search.");
722 if (firstSeparatorPosition == lastSeparatorPosition)
723 directoryName.queryName = StringImpl::empty();
724 else {
725 size_t queryStartPosition = firstSeparatorPosition + 1;
726 size_t queryLength = lastSeparatorPosition - queryStartPosition; // Not include the last separator.
727 directoryName.queryName = absolutePathToFile.substring(queryStartPosition, queryLength);
728 }
729 return directoryName;
730}
731
732static Optional<DirectoryName> currentWorkingDirectory()
733{
734#if OS(WINDOWS)
735 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364934.aspx
736 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
737 // The _MAX_PATH in Windows is 260. If the path of the current working directory is longer than that, _getcwd truncates the result.
738 // And other I/O functions taking a path name also truncate it. To avoid this situation,
739 //
740 // (1). When opening the file in Windows for modules, we always use the abosolute path and add "\\?\" prefix to the path name.
741 // (2). When retrieving the current working directory, use GetCurrentDirectory instead of _getcwd.
742 //
743 // In the path utility functions inside the JSC shell, we does not handle the UNC and UNCW including the network host name.
744 DWORD bufferLength = ::GetCurrentDirectoryW(0, nullptr);
745 if (!bufferLength)
746 return WTF::nullopt;
747 // In Windows, wchar_t is the UTF-16LE.
748 // https://msdn.microsoft.com/en-us/library/dd374081.aspx
749 // https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407.aspx
750 Vector<wchar_t> buffer(bufferLength);
751 DWORD lengthNotIncludingNull = ::GetCurrentDirectoryW(bufferLength, buffer.data());
752 String directoryString(buffer.data(), lengthNotIncludingNull);
753 // We don't support network path like \\host\share\<path name>.
754 if (directoryString.startsWith("\\\\"))
755 return WTF::nullopt;
756#else
757 Vector<char> buffer(PATH_MAX);
758 if (!getcwd(buffer.data(), PATH_MAX))
759 return WTF::nullopt;
760 String directoryString = String::fromUTF8(buffer.data());
761#endif
762 if (directoryString.isEmpty())
763 return WTF::nullopt;
764
765 if (directoryString[directoryString.length() - 1] == pathSeparator())
766 return extractDirectoryName(directoryString);
767 // Append the seperator to represents the file name. extractDirectoryName only accepts the absolute file name.
768 return extractDirectoryName(makeString(directoryString, pathSeparator()));
769}
770
771static String resolvePath(const DirectoryName& directoryName, const ModuleName& moduleName)
772{
773 Vector<String> directoryPieces = directoryName.queryName.split(pathSeparator());
774
775 // Only first '/' is recognized as the path from the root.
776 if (moduleName.startsWithRoot())
777 directoryPieces.clear();
778
779 for (const auto& query : moduleName.queries) {
780 if (query == String(".."_s)) {
781 if (!directoryPieces.isEmpty())
782 directoryPieces.removeLast();
783 } else if (!query.isEmpty() && query != String("."_s))
784 directoryPieces.append(query);
785 }
786
787 StringBuilder builder;
788 builder.append(directoryName.rootName);
789 for (size_t i = 0; i < directoryPieces.size(); ++i) {
790 builder.append(directoryPieces[i]);
791 if (i + 1 != directoryPieces.size())
792 builder.append(pathSeparator());
793 }
794 return builder.toString();
795}
796
797static String absolutePath(const String& fileName)
798{
799 auto directoryName = currentWorkingDirectory();
800 if (!directoryName)
801 return fileName;
802 return resolvePath(directoryName.value(), ModuleName(fileName.impl()));
803}
804
805JSInternalPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSString* moduleNameValue, JSValue parameters, const SourceOrigin& sourceOrigin)
806{
807 VM& vm = globalObject->vm();
808 auto throwScope = DECLARE_THROW_SCOPE(vm);
809
810 auto* deferred = JSInternalPromiseDeferred::tryCreate(exec, globalObject);
811 RETURN_IF_EXCEPTION(throwScope, nullptr);
812
813 auto catchScope = DECLARE_CATCH_SCOPE(vm);
814 auto reject = [&] (JSValue rejectionReason) {
815 catchScope.clearException();
816 auto result = deferred->reject(exec, rejectionReason);
817 catchScope.clearException();
818 return result;
819 };
820
821 if (sourceOrigin.isNull())
822 return reject(createError(exec, "Could not resolve the module specifier."_s));
823
824 const auto& referrer = sourceOrigin.string();
825 const auto& moduleName = moduleNameValue->value(exec);
826 if (UNLIKELY(catchScope.exception()))
827 return reject(catchScope.exception());
828
829 auto directoryName = extractDirectoryName(referrer.impl());
830 if (!directoryName)
831 return reject(createError(exec, makeString("Could not resolve the referrer name '", String(referrer.impl()), "'.")));
832
833 auto result = JSC::importModule(exec, Identifier::fromString(&vm, resolvePath(directoryName.value(), ModuleName(moduleName))), parameters, jsUndefined());
834 if (UNLIKELY(catchScope.exception()))
835 return reject(catchScope.exception());
836 return result;
837}
838
839Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue keyValue, JSValue referrerValue, JSValue)
840{
841 VM& vm = globalObject->vm();
842 auto scope = DECLARE_THROW_SCOPE(vm);
843
844 scope.releaseAssertNoException();
845 const Identifier key = keyValue.toPropertyKey(exec);
846 RETURN_IF_EXCEPTION(scope, { });
847
848 if (key.isSymbol())
849 return key;
850
851 if (referrerValue.isUndefined()) {
852 auto directoryName = currentWorkingDirectory();
853 if (!directoryName) {
854 throwException(exec, scope, createError(exec, "Could not resolve the current working directory."_s));
855 return { };
856 }
857 return Identifier::fromString(&vm, resolvePath(directoryName.value(), ModuleName(key.impl())));
858 }
859
860 const Identifier referrer = referrerValue.toPropertyKey(exec);
861 RETURN_IF_EXCEPTION(scope, { });
862
863 if (referrer.isSymbol()) {
864 auto directoryName = currentWorkingDirectory();
865 if (!directoryName) {
866 throwException(exec, scope, createError(exec, "Could not resolve the current working directory."_s));
867 return { };
868 }
869 return Identifier::fromString(&vm, resolvePath(directoryName.value(), ModuleName(key.impl())));
870 }
871
872 // If the referrer exists, we assume that the referrer is the correct absolute path.
873 auto directoryName = extractDirectoryName(referrer.impl());
874 if (!directoryName) {
875 throwException(exec, scope, createError(exec, makeString("Could not resolve the referrer name '", String(referrer.impl()), "'.")));
876 return { };
877 }
878 return Identifier::fromString(&vm, resolvePath(directoryName.value(), ModuleName(key.impl())));
879}
880
881template<typename Vector>
882static void convertShebangToJSComment(Vector& buffer)
883{
884 if (buffer.size() >= 2) {
885 if (buffer[0] == '#' && buffer[1] == '!')
886 buffer[0] = buffer[1] = '/';
887 }
888}
889
890static RefPtr<Uint8Array> fillBufferWithContentsOfFile(FILE* file)
891{
892 if (fseek(file, 0, SEEK_END) == -1)
893 return nullptr;
894 long bufferCapacity = ftell(file);
895 if (bufferCapacity == -1)
896 return nullptr;
897 if (fseek(file, 0, SEEK_SET) == -1)
898 return nullptr;
899 auto result = Uint8Array::tryCreate(bufferCapacity);
900 if (!result)
901 return nullptr;
902 size_t readSize = fread(result->data(), 1, bufferCapacity, file);
903 if (readSize != static_cast<size_t>(bufferCapacity))
904 return nullptr;
905 return result;
906}
907
908static RefPtr<Uint8Array> fillBufferWithContentsOfFile(const String& fileName)
909{
910 FILE* f = fopen(fileName.utf8().data(), "rb");
911 if (!f) {
912 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
913 return nullptr;
914 }
915
916 RefPtr<Uint8Array> result = fillBufferWithContentsOfFile(f);
917 fclose(f);
918
919 return result;
920}
921
922template<typename Vector>
923static bool fillBufferWithContentsOfFile(FILE* file, Vector& buffer)
924{
925 // We might have injected "use strict"; at the top.
926 size_t initialSize = buffer.size();
927 if (fseek(file, 0, SEEK_END) == -1)
928 return false;
929 long bufferCapacity = ftell(file);
930 if (bufferCapacity == -1)
931 return false;
932 if (fseek(file, 0, SEEK_SET) == -1)
933 return false;
934 buffer.resize(bufferCapacity + initialSize);
935 size_t readSize = fread(buffer.data() + initialSize, 1, buffer.size(), file);
936 return readSize == buffer.size() - initialSize;
937}
938
939static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer)
940{
941 FILE* f = fopen(fileName.utf8().data(), "rb");
942 if (!f) {
943 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
944 return false;
945 }
946
947 bool result = fillBufferWithContentsOfFile(f, buffer);
948 fclose(f);
949
950 return result;
951}
952
953static bool fetchScriptFromLocalFileSystem(const String& fileName, Vector<char>& buffer)
954{
955 if (!fillBufferWithContentsOfFile(fileName, buffer))
956 return false;
957 convertShebangToJSComment(buffer);
958 return true;
959}
960
961class ShellSourceProvider : public StringSourceProvider {
962public:
963 static Ref<ShellSourceProvider> create(const String& source, const SourceOrigin& sourceOrigin, URL&& url, const TextPosition& startPosition, SourceProviderSourceType sourceType)
964 {
965 return adoptRef(*new ShellSourceProvider(source, sourceOrigin, WTFMove(url), startPosition, sourceType));
966 }
967
968 ~ShellSourceProvider()
969 {
970#if OS(DARWIN)
971 if (m_cachedBytecode.size())
972 munmap(const_cast<void*>(m_cachedBytecode.data()), m_cachedBytecode.size());
973#endif
974 }
975
976 const CachedBytecode* cachedBytecode() const override
977 {
978 return &m_cachedBytecode;
979 }
980
981 void cacheBytecode(const BytecodeCacheGenerator& generator) const override
982 {
983#if OS(DARWIN)
984 String filename = cachePath();
985 if (filename.isNull())
986 return;
987 int fd = open(filename.utf8().data(), O_CREAT | O_WRONLY | O_TRUNC | O_EXLOCK | O_NONBLOCK, 0666);
988 if (fd == -1)
989 return;
990 CachedBytecode cachedBytecode = generator();
991 write(fd, cachedBytecode.data(), cachedBytecode.size());
992 close(fd);
993#else
994 UNUSED_PARAM(generator);
995#endif
996 }
997
998private:
999 String cachePath() const
1000 {
1001 const char* cachePath = Options::diskCachePath();
1002 if (!cachePath)
1003 return static_cast<const char*>(nullptr);
1004 String filename = sourceOrigin().string();
1005 filename.replace('/', '_');
1006 return makeString(cachePath, '/', source().toString().hash(), '-', filename, ".bytecode-cache");
1007 }
1008
1009 void loadBytecode()
1010 {
1011#if OS(DARWIN)
1012 String filename = cachePath();
1013 if (filename.isNull())
1014 return;
1015
1016 int fd = open(filename.utf8().data(), O_RDONLY | O_SHLOCK | O_NONBLOCK);
1017 if (fd == -1)
1018 return;
1019
1020 auto closeFD = makeScopeExit([&] {
1021 close(fd);
1022 });
1023
1024 struct stat sb;
1025 int res = fstat(fd, &sb);
1026 size_t size = static_cast<size_t>(sb.st_size);
1027 if (res || !size)
1028 return;
1029
1030 void* buffer = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
1031 if (buffer == MAP_FAILED)
1032 return;
1033 m_cachedBytecode = CachedBytecode { buffer, size };
1034#endif
1035 }
1036
1037 ShellSourceProvider(const String& source, const SourceOrigin& sourceOrigin, URL&& url, const TextPosition& startPosition, SourceProviderSourceType sourceType)
1038 : StringSourceProvider(source, sourceOrigin, WTFMove(url), startPosition, sourceType)
1039 {
1040 loadBytecode();
1041 }
1042
1043 CachedBytecode m_cachedBytecode;
1044};
1045
1046static inline SourceCode jscSource(const String& source, const SourceOrigin& sourceOrigin, URL&& url = URL(), const TextPosition& startPosition = TextPosition(), SourceProviderSourceType sourceType = SourceProviderSourceType::Program)
1047{
1048 return SourceCode(ShellSourceProvider::create(source, sourceOrigin, WTFMove(url), startPosition, sourceType), startPosition.m_line.oneBasedInt(), startPosition.m_column.oneBasedInt());
1049}
1050
1051template<typename Vector>
1052static inline SourceCode jscSource(const Vector& utf8, const SourceOrigin& sourceOrigin, const String& filename)
1053{
1054 // FIXME: This should use an absolute file URL https://bugs.webkit.org/show_bug.cgi?id=193077
1055 String str = stringFromUTF(utf8);
1056 return jscSource(str, sourceOrigin, URL({ }, filename));
1057}
1058
1059template<typename Vector>
1060static bool fetchModuleFromLocalFileSystem(const String& fileName, Vector& buffer)
1061{
1062 // We assume that fileName is always an absolute path.
1063#if OS(WINDOWS)
1064 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
1065 // Use long UNC to pass the long path name to the Windows APIs.
1066 auto pathName = makeString("\\\\?\\", fileName).wideCharacters();
1067 struct _stat status { };
1068 if (_wstat(pathName.data(), &status))
1069 return false;
1070 if ((status.st_mode & S_IFMT) != S_IFREG)
1071 return false;
1072
1073 FILE* f = _wfopen(pathName.data(), L"rb");
1074#else
1075 auto pathName = fileName.utf8();
1076 struct stat status { };
1077 if (stat(pathName.data(), &status))
1078 return false;
1079 if ((status.st_mode & S_IFMT) != S_IFREG)
1080 return false;
1081
1082 FILE* f = fopen(pathName.data(), "r");
1083#endif
1084 if (!f) {
1085 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1086 return false;
1087 }
1088
1089 bool result = fillBufferWithContentsOfFile(f, buffer);
1090 if (result)
1091 convertShebangToJSComment(buffer);
1092 fclose(f);
1093
1094 return result;
1095}
1096
1097JSInternalPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue key, JSValue, JSValue)
1098{
1099 VM& vm = globalObject->vm();
1100 auto throwScope = DECLARE_THROW_SCOPE(vm);
1101 JSInternalPromiseDeferred* deferred = JSInternalPromiseDeferred::tryCreate(exec, globalObject);
1102 RETURN_IF_EXCEPTION(throwScope, nullptr);
1103
1104 auto catchScope = DECLARE_CATCH_SCOPE(vm);
1105 auto reject = [&] (JSValue rejectionReason) {
1106 catchScope.clearException();
1107 auto result = deferred->reject(exec, rejectionReason);
1108 catchScope.clearException();
1109 return result;
1110 };
1111
1112 String moduleKey = key.toWTFString(exec);
1113 if (UNLIKELY(catchScope.exception()))
1114 return reject(catchScope.exception());
1115
1116 // Here, now we consider moduleKey as the fileName.
1117 Vector<uint8_t> buffer;
1118 if (!fetchModuleFromLocalFileSystem(moduleKey, buffer))
1119 return reject(createError(exec, makeString("Could not open file '", moduleKey, "'.")));
1120
1121
1122 URL moduleURL = URL({ }, moduleKey);
1123#if ENABLE(WEBASSEMBLY)
1124 // FileSystem does not have mime-type header. The JSC shell recognizes WebAssembly's magic header.
1125 if (buffer.size() >= 4) {
1126 if (buffer[0] == '\0' && buffer[1] == 'a' && buffer[2] == 's' && buffer[3] == 'm') {
1127 auto source = SourceCode(WebAssemblySourceProvider::create(WTFMove(buffer), SourceOrigin { moduleKey }, WTFMove(moduleURL)));
1128 catchScope.releaseAssertNoException();
1129 auto sourceCode = JSSourceCode::create(vm, WTFMove(source));
1130 catchScope.releaseAssertNoException();
1131 auto result = deferred->resolve(exec, sourceCode);
1132 catchScope.clearException();
1133 return result;
1134 }
1135 }
1136#endif
1137
1138 auto sourceCode = JSSourceCode::create(vm, jscSource(stringFromUTF(buffer), SourceOrigin { moduleKey }, WTFMove(moduleURL), TextPosition(), SourceProviderSourceType::Module));
1139 catchScope.releaseAssertNoException();
1140 auto result = deferred->resolve(exec, sourceCode);
1141 catchScope.clearException();
1142 return result;
1143}
1144
1145JSObject* GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue key, JSModuleRecord*, JSValue)
1146{
1147 VM& vm = exec->vm();
1148 auto scope = DECLARE_THROW_SCOPE(vm);
1149
1150 JSObject* metaProperties = constructEmptyObject(exec, globalObject->nullPrototypeObjectStructure());
1151 RETURN_IF_EXCEPTION(scope, nullptr);
1152
1153 metaProperties->putDirect(vm, Identifier::fromString(&vm, "filename"), key);
1154 RETURN_IF_EXCEPTION(scope, nullptr);
1155
1156 return metaProperties;
1157}
1158
1159static CString cStringFromViewWithString(ExecState* exec, ThrowScope& scope, StringViewWithUnderlyingString& viewWithString)
1160{
1161 Expected<CString, UTF8ConversionError> expectedString = viewWithString.view.tryGetUtf8();
1162 if (expectedString)
1163 return expectedString.value();
1164 switch (expectedString.error()) {
1165 case UTF8ConversionError::OutOfMemory:
1166 throwOutOfMemoryError(exec, scope);
1167 break;
1168 case UTF8ConversionError::IllegalSource:
1169 scope.throwException(exec, createError(exec, "Illegal source encountered during UTF8 conversion"));
1170 break;
1171 case UTF8ConversionError::SourceExhausted:
1172 scope.throwException(exec, createError(exec, "Source exhausted during UTF8 conversion"));
1173 break;
1174 default:
1175 RELEASE_ASSERT_NOT_REACHED();
1176 }
1177 return { };
1178}
1179
1180static EncodedJSValue printInternal(ExecState* exec, FILE* out)
1181{
1182 VM& vm = exec->vm();
1183 auto scope = DECLARE_THROW_SCOPE(vm);
1184
1185 if (asyncTestExpectedPasses) {
1186 JSValue value = exec->argument(0);
1187 if (value.isString() && WTF::equal(asString(value)->value(exec).impl(), "Test262:AsyncTestComplete")) {
1188 asyncTestPasses++;
1189 return JSValue::encode(jsUndefined());
1190 }
1191 }
1192
1193 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1194 if (i)
1195 if (EOF == fputc(' ', out))
1196 goto fail;
1197
1198 auto viewWithString = exec->uncheckedArgument(i).toString(exec)->viewWithUnderlyingString(exec);
1199 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1200 auto string = cStringFromViewWithString(exec, scope, viewWithString);
1201 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1202 if (fprintf(out, "%s", string.data()) < 0)
1203 goto fail;
1204 }
1205
1206 fputc('\n', out);
1207fail:
1208 fflush(out);
1209 return JSValue::encode(jsUndefined());
1210}
1211
1212EncodedJSValue JSC_HOST_CALL functionPrintStdOut(ExecState* exec) { return printInternal(exec, stdout); }
1213EncodedJSValue JSC_HOST_CALL functionPrintStdErr(ExecState* exec) { return printInternal(exec, stderr); }
1214
1215EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
1216{
1217 VM& vm = exec->vm();
1218 auto scope = DECLARE_THROW_SCOPE(vm);
1219 auto viewWithString = exec->argument(0).toString(exec)->viewWithUnderlyingString(exec);
1220 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1221 auto string = cStringFromViewWithString(exec, scope, viewWithString);
1222 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1223 fprintf(stderr, "--> %s\n", string.data());
1224 return JSValue::encode(jsUndefined());
1225}
1226
1227EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState* exec)
1228{
1229 if (exec->argumentCount() < 1)
1230 return JSValue::encode(jsUndefined());
1231 return JSValue::encode(jsString(exec, toString(exec->argument(0))));
1232}
1233
1234EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState* exec)
1235{
1236 if (exec->argumentCount() < 1)
1237 return JSValue::encode(jsUndefined());
1238 VM& vm = exec->vm();
1239 JSObject* object = jsDynamicCast<JSObject*>(vm, exec->argument(0));
1240 if (!object)
1241 return JSValue::encode(jsNontrivialString(exec, "<not object>"_s));
1242 return JSValue::encode(jsNontrivialString(exec, toString("<Butterfly: ", RawPointer(object->butterfly()), "; public length: ", object->getArrayLength(), "; vector length: ", object->getVectorLength(), ">")));
1243}
1244
1245EncodedJSValue JSC_HOST_CALL functionSleepSeconds(ExecState* exec)
1246{
1247 VM& vm = exec->vm();
1248 auto scope = DECLARE_THROW_SCOPE(vm);
1249
1250 if (exec->argumentCount() >= 1) {
1251 Seconds seconds = Seconds(exec->argument(0).toNumber(exec));
1252 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1253 sleep(seconds);
1254 }
1255
1256 return JSValue::encode(jsUndefined());
1257}
1258
1259class FunctionJSCStackFunctor {
1260public:
1261 FunctionJSCStackFunctor(StringBuilder& trace)
1262 : m_trace(trace)
1263 {
1264 }
1265
1266 StackVisitor::Status operator()(StackVisitor& visitor) const
1267 {
1268 m_trace.append(makeString(" ", visitor->index(), " ", visitor->toString(), '\n'));
1269 return StackVisitor::Continue;
1270 }
1271
1272private:
1273 StringBuilder& m_trace;
1274};
1275
1276EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
1277{
1278 StringBuilder trace;
1279 trace.appendLiteral("--> Stack trace:\n");
1280
1281 FunctionJSCStackFunctor functor(trace);
1282 exec->iterate(functor);
1283 fprintf(stderr, "%s", trace.toString().utf8().data());
1284 return JSValue::encode(jsUndefined());
1285}
1286
1287EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState* exec)
1288{
1289 VM& vm = exec->vm();
1290 JSLockHolder lock(vm);
1291 vm.heap.collectNow(Sync, CollectionScope::Full);
1292 return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection()));
1293}
1294
1295EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState* exec)
1296{
1297 VM& vm = exec->vm();
1298 JSLockHolder lock(vm);
1299 vm.heap.collectSync(CollectionScope::Full);
1300 return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection()));
1301}
1302
1303EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState* exec)
1304{
1305 VM& vm = exec->vm();
1306 JSLockHolder lock(vm);
1307 vm.heap.collectSync(CollectionScope::Eden);
1308 return JSValue::encode(jsNumber(vm.heap.sizeAfterLastEdenCollection()));
1309}
1310
1311EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*)
1312{
1313 // It's best for this to be the first thing called in the
1314 // JS program so the option is set to true before we JIT.
1315 Options::forceGCSlowPaths() = true;
1316 return JSValue::encode(jsUndefined());
1317}
1318
1319EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState* exec)
1320{
1321 VM& vm = exec->vm();
1322 JSLockHolder lock(vm);
1323 return JSValue::encode(jsNumber(vm.heap.size()));
1324}
1325
1326class JSCMemoryFootprint : public JSDestructibleObject {
1327 using Base = JSDestructibleObject;
1328public:
1329 JSCMemoryFootprint(VM& vm, Structure* structure)
1330 : Base(vm, structure)
1331 { }
1332
1333 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1334 {
1335 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
1336 }
1337
1338 static JSCMemoryFootprint* create(VM& vm, JSGlobalObject* globalObject)
1339 {
1340 Structure* structure = createStructure(vm, globalObject, jsNull());
1341 JSCMemoryFootprint* footprint = new (NotNull, allocateCell<JSCMemoryFootprint>(vm.heap, sizeof(JSCMemoryFootprint))) JSCMemoryFootprint(vm, structure);
1342 footprint->finishCreation(vm);
1343 return footprint;
1344 }
1345
1346 void finishCreation(VM& vm)
1347 {
1348 Base::finishCreation(vm);
1349
1350 auto addProperty = [&] (VM& vm, const char* name, JSValue value) {
1351 JSCMemoryFootprint::addProperty(vm, name, value);
1352 };
1353
1354 MemoryFootprint footprint = MemoryFootprint::now();
1355
1356 addProperty(vm, "current", jsNumber(footprint.current));
1357 addProperty(vm, "peak", jsNumber(footprint.peak));
1358 }
1359
1360 DECLARE_INFO;
1361
1362private:
1363 void addProperty(VM& vm, const char* name, JSValue value)
1364 {
1365 Identifier identifier = Identifier::fromString(&vm, name);
1366 putDirect(vm, identifier, value);
1367 }
1368};
1369
1370const ClassInfo JSCMemoryFootprint::s_info = { "MemoryFootprint", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSCMemoryFootprint) };
1371
1372EncodedJSValue JSC_HOST_CALL functionCreateMemoryFootprint(ExecState* exec)
1373{
1374 VM& vm = exec->vm();
1375 JSLockHolder lock(vm);
1376 return JSValue::encode(JSCMemoryFootprint::create(vm, exec->lexicalGlobalObject()));
1377}
1378
1379EncodedJSValue JSC_HOST_CALL functionResetMemoryPeak(ExecState*)
1380{
1381 MemoryFootprint::resetPeak();
1382 return JSValue::encode(jsUndefined());
1383}
1384
1385// This function is not generally very helpful in 64-bit code as the tag and payload
1386// share a register. But in 32-bit JITed code the tag may not be checked if an
1387// optimization removes type checking requirements, such as in ===.
1388EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState* exec)
1389{
1390 JSValue value = exec->argument(0);
1391 if (!value.isCell())
1392 return JSValue::encode(jsUndefined());
1393 // Need to cast to uint64_t so bitwise_cast will play along.
1394 uint64_t asNumber = reinterpret_cast<uint64_t>(value.asCell());
1395 EncodedJSValue returnValue = JSValue::encode(jsNumber(bitwise_cast<double>(asNumber)));
1396 return returnValue;
1397}
1398
1399EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
1400{
1401 // We need this function for compatibility with the Mozilla JS tests but for now
1402 // we don't actually do any version-specific handling
1403 return JSValue::encode(jsUndefined());
1404}
1405
1406EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
1407{
1408 VM& vm = exec->vm();
1409 auto scope = DECLARE_THROW_SCOPE(vm);
1410
1411 String fileName = exec->argument(0).toWTFString(exec);
1412 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1413 Vector<char> script;
1414 if (!fetchScriptFromLocalFileSystem(fileName, script))
1415 return JSValue::encode(throwException(exec, scope, createError(exec, "Could not open file."_s)));
1416
1417 GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
1418
1419 JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
1420 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1421 for (unsigned i = 1; i < exec->argumentCount(); ++i) {
1422 array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
1423 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1424 }
1425 globalObject->putDirect(
1426 vm, Identifier::fromString(globalObject->globalExec(), "arguments"), array);
1427
1428 NakedPtr<Exception> exception;
1429 StopWatch stopWatch;
1430 stopWatch.start();
1431 evaluate(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), exception);
1432 stopWatch.stop();
1433
1434 if (exception) {
1435 throwException(globalObject->globalExec(), scope, exception);
1436 return JSValue::encode(jsUndefined());
1437 }
1438
1439 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1440}
1441
1442EncodedJSValue JSC_HOST_CALL functionRunString(ExecState* exec)
1443{
1444 VM& vm = exec->vm();
1445 auto scope = DECLARE_THROW_SCOPE(vm);
1446
1447 String source = exec->argument(0).toWTFString(exec);
1448 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1449
1450 GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
1451
1452 JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
1453 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1454 for (unsigned i = 1; i < exec->argumentCount(); ++i) {
1455 array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
1456 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1457 }
1458 globalObject->putDirect(
1459 vm, Identifier::fromString(globalObject->globalExec(), "arguments"), array);
1460
1461 NakedPtr<Exception> exception;
1462 evaluate(globalObject->globalExec(), jscSource(source, exec->callerSourceOrigin()), JSValue(), exception);
1463
1464 if (exception) {
1465 scope.throwException(globalObject->globalExec(), exception);
1466 return JSValue::encode(jsUndefined());
1467 }
1468
1469 return JSValue::encode(globalObject);
1470}
1471
1472EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
1473{
1474 VM& vm = exec->vm();
1475 auto scope = DECLARE_THROW_SCOPE(vm);
1476
1477 String fileName = exec->argument(0).toWTFString(exec);
1478 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1479 Vector<char> script;
1480 if (!fetchScriptFromLocalFileSystem(fileName, script))
1481 return JSValue::encode(throwException(exec, scope, createError(exec, "Could not open file."_s)));
1482
1483 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1484
1485 NakedPtr<Exception> evaluationException;
1486 JSValue result = evaluate(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), evaluationException);
1487 if (evaluationException)
1488 throwException(exec, scope, evaluationException);
1489 return JSValue::encode(result);
1490}
1491
1492EncodedJSValue JSC_HOST_CALL functionLoadString(ExecState* exec)
1493{
1494 VM& vm = exec->vm();
1495 auto scope = DECLARE_THROW_SCOPE(vm);
1496
1497 String sourceCode = exec->argument(0).toWTFString(exec);
1498 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1499 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1500
1501 NakedPtr<Exception> evaluationException;
1502 JSValue result = evaluate(globalObject->globalExec(), jscSource(sourceCode, exec->callerSourceOrigin()), JSValue(), evaluationException);
1503 if (evaluationException)
1504 throwException(exec, scope, evaluationException);
1505 return JSValue::encode(result);
1506}
1507
1508EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState* exec)
1509{
1510 VM& vm = exec->vm();
1511 auto scope = DECLARE_THROW_SCOPE(vm);
1512
1513 String fileName = exec->argument(0).toWTFString(exec);
1514 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1515
1516 bool isBinary = false;
1517 if (exec->argumentCount() > 1) {
1518 String type = exec->argument(1).toWTFString(exec);
1519 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1520 if (type != "binary")
1521 return throwVMError(exec, scope, "Expected 'binary' as second argument.");
1522 isBinary = true;
1523 }
1524
1525 RefPtr<Uint8Array> content = fillBufferWithContentsOfFile(fileName);
1526 if (!content)
1527 return throwVMError(exec, scope, "Could not open file.");
1528
1529 if (!isBinary)
1530 return JSValue::encode(jsString(exec, String::fromUTF8WithLatin1Fallback(content->data(), content->length())));
1531
1532 Structure* structure = exec->lexicalGlobalObject()->typedArrayStructure(TypeUint8);
1533 JSObject* result = JSUint8Array::create(vm, structure, WTFMove(content));
1534 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1535
1536 return JSValue::encode(result);
1537}
1538
1539EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
1540{
1541 VM& vm = exec->vm();
1542 auto scope = DECLARE_THROW_SCOPE(vm);
1543
1544 String fileName = exec->argument(0).toWTFString(exec);
1545 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1546 Vector<char> script;
1547 if (!fetchScriptFromLocalFileSystem(fileName, script))
1548 return JSValue::encode(throwException(exec, scope, createError(exec, "Could not open file."_s)));
1549
1550 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1551
1552 StopWatch stopWatch;
1553 stopWatch.start();
1554
1555 JSValue syntaxException;
1556 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), &syntaxException);
1557 stopWatch.stop();
1558
1559 if (!validSyntax)
1560 throwException(exec, scope, syntaxException);
1561 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1562}
1563
1564#if ENABLE(SAMPLING_FLAGS)
1565EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
1566{
1567 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1568 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
1569 if ((flag >= 1) && (flag <= 32))
1570 SamplingFlags::setFlag(flag);
1571 }
1572 return JSValue::encode(jsNull());
1573}
1574
1575EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
1576{
1577 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1578 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
1579 if ((flag >= 1) && (flag <= 32))
1580 SamplingFlags::clearFlag(flag);
1581 }
1582 return JSValue::encode(jsNull());
1583}
1584#endif
1585
1586EncodedJSValue JSC_HOST_CALL functionGetRandomSeed(ExecState* exec)
1587{
1588 return JSValue::encode(jsNumber(exec->lexicalGlobalObject()->weakRandom().seed()));
1589}
1590
1591EncodedJSValue JSC_HOST_CALL functionSetRandomSeed(ExecState* exec)
1592{
1593 VM& vm = exec->vm();
1594 auto scope = DECLARE_THROW_SCOPE(vm);
1595
1596 unsigned seed = exec->argument(0).toUInt32(exec);
1597 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1598 exec->lexicalGlobalObject()->weakRandom().setSeed(seed);
1599 return JSValue::encode(jsUndefined());
1600}
1601
1602EncodedJSValue JSC_HOST_CALL functionIsRope(ExecState* exec)
1603{
1604 JSValue argument = exec->argument(0);
1605 if (!argument.isString())
1606 return JSValue::encode(jsBoolean(false));
1607 const StringImpl* impl = asString(argument)->tryGetValueImpl();
1608 return JSValue::encode(jsBoolean(!impl));
1609}
1610
1611EncodedJSValue JSC_HOST_CALL functionCallerSourceOrigin(ExecState* state)
1612{
1613 SourceOrigin sourceOrigin = state->callerSourceOrigin();
1614 if (sourceOrigin.isNull())
1615 return JSValue::encode(jsNull());
1616 return JSValue::encode(jsString(state, sourceOrigin.string()));
1617}
1618
1619EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
1620{
1621 Vector<char, 256> line;
1622 int c;
1623 while ((c = getchar()) != EOF) {
1624 // FIXME: Should we also break on \r?
1625 if (c == '\n')
1626 break;
1627 line.append(c);
1628 }
1629 line.append('\0');
1630 return JSValue::encode(jsString(exec, line.data()));
1631}
1632
1633EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
1634{
1635 return JSValue::encode(jsNumber(WallTime::now().secondsSinceEpoch().value()));
1636}
1637
1638EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState* exec)
1639{
1640 return JSValue::encode(setNeverInline(exec));
1641}
1642
1643EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState* exec)
1644{
1645 return JSValue::encode(setNeverOptimize(exec));
1646}
1647
1648EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState* exec)
1649{
1650 if (exec->argumentCount()) {
1651 FunctionExecutable* executable = getExecutableForFunction(exec->argument(0));
1652 if (executable)
1653 executable->setNeverFTLOptimize(true);
1654 }
1655 return JSValue::encode(jsUndefined());
1656}
1657
1658EncodedJSValue JSC_HOST_CALL functionNoOSRExitFuzzing(ExecState* exec)
1659{
1660 return JSValue::encode(setCannotUseOSRExitFuzzing(exec));
1661}
1662
1663EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState* exec)
1664{
1665 return JSValue::encode(optimizeNextInvocation(exec));
1666}
1667
1668EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState* exec)
1669{
1670 return JSValue::encode(numberOfDFGCompiles(exec));
1671}
1672
1673Message::Message(ArrayBufferContents&& contents, int32_t index)
1674 : m_contents(WTFMove(contents))
1675 , m_index(index)
1676{
1677}
1678
1679Message::~Message()
1680{
1681}
1682
1683Worker::Worker(Workers& workers)
1684 : m_workers(workers)
1685{
1686 auto locker = holdLock(m_workers.m_lock);
1687 m_workers.m_workers.append(this);
1688
1689 *currentWorker() = this;
1690}
1691
1692Worker::~Worker()
1693{
1694 auto locker = holdLock(m_workers.m_lock);
1695 RELEASE_ASSERT(isOnList());
1696 remove();
1697}
1698
1699void Worker::enqueue(const AbstractLocker&, RefPtr<Message> message)
1700{
1701 m_messages.append(message);
1702}
1703
1704RefPtr<Message> Worker::dequeue()
1705{
1706 auto locker = holdLock(m_workers.m_lock);
1707 while (m_messages.isEmpty())
1708 m_workers.m_condition.wait(m_workers.m_lock);
1709 return m_messages.takeFirst();
1710}
1711
1712Worker& Worker::current()
1713{
1714 return **currentWorker();
1715}
1716
1717ThreadSpecific<Worker*>& Worker::currentWorker()
1718{
1719 static ThreadSpecific<Worker*>* result;
1720 static std::once_flag flag;
1721 std::call_once(
1722 flag,
1723 [] () {
1724 result = new ThreadSpecific<Worker*>();
1725 });
1726 return *result;
1727}
1728
1729Workers::Workers()
1730{
1731}
1732
1733Workers::~Workers()
1734{
1735 UNREACHABLE_FOR_PLATFORM();
1736}
1737
1738template<typename Func>
1739void Workers::broadcast(const Func& func)
1740{
1741 auto locker = holdLock(m_lock);
1742 for (Worker* worker = m_workers.begin(); worker != m_workers.end(); worker = worker->next()) {
1743 if (worker != &Worker::current())
1744 func(locker, *worker);
1745 }
1746 m_condition.notifyAll();
1747}
1748
1749void Workers::report(const String& string)
1750{
1751 auto locker = holdLock(m_lock);
1752 m_reports.append(string.isolatedCopy());
1753 m_condition.notifyAll();
1754}
1755
1756String Workers::tryGetReport()
1757{
1758 auto locker = holdLock(m_lock);
1759 if (m_reports.isEmpty())
1760 return String();
1761 return m_reports.takeFirst();
1762}
1763
1764String Workers::getReport()
1765{
1766 auto locker = holdLock(m_lock);
1767 while (m_reports.isEmpty())
1768 m_condition.wait(m_lock);
1769 return m_reports.takeFirst();
1770}
1771
1772Workers& Workers::singleton()
1773{
1774 static Workers* result;
1775 static std::once_flag flag;
1776 std::call_once(
1777 flag,
1778 [] {
1779 result = new Workers();
1780 });
1781 return *result;
1782}
1783
1784EncodedJSValue JSC_HOST_CALL functionDollarCreateRealm(ExecState* exec)
1785{
1786 VM& vm = exec->vm();
1787 GlobalObject* result = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
1788 return JSValue::encode(result->getDirect(vm, Identifier::fromString(exec, "$")));
1789}
1790
1791EncodedJSValue JSC_HOST_CALL functionDollarDetachArrayBuffer(ExecState* exec)
1792{
1793 return functionTransferArrayBuffer(exec);
1794}
1795
1796EncodedJSValue JSC_HOST_CALL functionDollarEvalScript(ExecState* exec)
1797{
1798 VM& vm = exec->vm();
1799 auto scope = DECLARE_THROW_SCOPE(vm);
1800
1801 String sourceCode = exec->argument(0).toWTFString(exec);
1802 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1803
1804 GlobalObject* globalObject = jsDynamicCast<GlobalObject*>(vm,
1805 exec->thisValue().get(exec, Identifier::fromString(exec, "global")));
1806 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1807 if (!globalObject)
1808 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected global to point to a global object"_s)));
1809
1810 NakedPtr<Exception> evaluationException;
1811 JSValue result = evaluate(globalObject->globalExec(), jscSource(sourceCode, exec->callerSourceOrigin()), JSValue(), evaluationException);
1812 if (evaluationException)
1813 throwException(exec, scope, evaluationException);
1814 return JSValue::encode(result);
1815}
1816
1817EncodedJSValue JSC_HOST_CALL functionDollarAgentStart(ExecState* exec)
1818{
1819 VM& vm = exec->vm();
1820 auto scope = DECLARE_THROW_SCOPE(vm);
1821
1822 String sourceCode = exec->argument(0).toWTFString(exec).isolatedCopy();
1823 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1824
1825 Lock didStartLock;
1826 Condition didStartCondition;
1827 bool didStart = false;
1828
1829 Thread::create(
1830 "JSC Agent",
1831 [sourceCode, &didStartLock, &didStartCondition, &didStart] () {
1832 CommandLine commandLine(0, nullptr);
1833 commandLine.m_interactive = false;
1834 runJSC(
1835 commandLine, true,
1836 [&] (VM&, GlobalObject* globalObject, bool& success) {
1837 // Notify the thread that started us that we have registered a worker.
1838 {
1839 auto locker = holdLock(didStartLock);
1840 didStart = true;
1841 didStartCondition.notifyOne();
1842 }
1843
1844 NakedPtr<Exception> evaluationException;
1845 JSValue result;
1846 result = evaluate(globalObject->globalExec(), jscSource(sourceCode, SourceOrigin("worker"_s)), JSValue(), evaluationException);
1847 if (evaluationException)
1848 result = evaluationException->value();
1849 checkException(globalObject->globalExec(), globalObject, true, evaluationException, result, commandLine, success);
1850 if (!success)
1851 exit(1);
1852 });
1853 })->detach();
1854
1855 {
1856 auto locker = holdLock(didStartLock);
1857 while (!didStart)
1858 didStartCondition.wait(didStartLock);
1859 }
1860
1861 return JSValue::encode(jsUndefined());
1862}
1863
1864EncodedJSValue JSC_HOST_CALL functionDollarAgentReceiveBroadcast(ExecState* exec)
1865{
1866 VM& vm = exec->vm();
1867 auto scope = DECLARE_THROW_SCOPE(vm);
1868
1869 JSValue callback = exec->argument(0);
1870 CallData callData;
1871 CallType callType = getCallData(vm, callback, callData);
1872 if (callType == CallType::None)
1873 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected callback"_s)));
1874
1875 RefPtr<Message> message;
1876 {
1877 ReleaseHeapAccessScope releaseAccess(vm.heap);
1878 message = Worker::current().dequeue();
1879 }
1880
1881 auto nativeBuffer = ArrayBuffer::create(message->releaseContents());
1882 ArrayBufferSharingMode sharingMode = nativeBuffer->sharingMode();
1883 JSArrayBuffer* jsBuffer = JSArrayBuffer::create(vm, exec->lexicalGlobalObject()->arrayBufferStructure(sharingMode), WTFMove(nativeBuffer));
1884
1885 MarkedArgumentBuffer args;
1886 args.append(jsBuffer);
1887 args.append(jsNumber(message->index()));
1888 if (UNLIKELY(args.hasOverflowed()))
1889 return JSValue::encode(throwOutOfMemoryError(exec, scope));
1890 RELEASE_AND_RETURN(scope, JSValue::encode(call(exec, callback, callType, callData, jsNull(), args)));
1891}
1892
1893EncodedJSValue JSC_HOST_CALL functionDollarAgentReport(ExecState* exec)
1894{
1895 VM& vm = exec->vm();
1896 auto scope = DECLARE_THROW_SCOPE(vm);
1897
1898 String report = exec->argument(0).toWTFString(exec);
1899 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1900
1901 Workers::singleton().report(report);
1902
1903 return JSValue::encode(jsUndefined());
1904}
1905
1906EncodedJSValue JSC_HOST_CALL functionDollarAgentSleep(ExecState* exec)
1907{
1908 VM& vm = exec->vm();
1909 auto scope = DECLARE_THROW_SCOPE(vm);
1910
1911 if (exec->argumentCount() >= 1) {
1912 Seconds seconds = Seconds::fromMilliseconds(exec->argument(0).toNumber(exec));
1913 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1914 sleep(seconds);
1915 }
1916 return JSValue::encode(jsUndefined());
1917}
1918
1919EncodedJSValue JSC_HOST_CALL functionDollarAgentBroadcast(ExecState* exec)
1920{
1921 VM& vm = exec->vm();
1922 auto scope = DECLARE_THROW_SCOPE(vm);
1923
1924 JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(vm, exec->argument(0));
1925 if (!jsBuffer || !jsBuffer->isShared())
1926 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected SharedArrayBuffer"_s)));
1927
1928 int32_t index = exec->argument(1).toInt32(exec);
1929 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1930
1931 Workers::singleton().broadcast(
1932 [&] (const AbstractLocker& locker, Worker& worker) {
1933 ArrayBuffer* nativeBuffer = jsBuffer->impl();
1934 ArrayBufferContents contents;
1935 nativeBuffer->transferTo(vm, contents); // "transferTo" means "share" if the buffer is shared.
1936 RefPtr<Message> message = adoptRef(new Message(WTFMove(contents), index));
1937 worker.enqueue(locker, message);
1938 });
1939
1940 return JSValue::encode(jsUndefined());
1941}
1942
1943EncodedJSValue JSC_HOST_CALL functionDollarAgentGetReport(ExecState* exec)
1944{
1945 VM& vm = exec->vm();
1946
1947 String string = Workers::singleton().tryGetReport();
1948 if (!string)
1949 return JSValue::encode(jsNull());
1950
1951 return JSValue::encode(jsString(&vm, string));
1952}
1953
1954EncodedJSValue JSC_HOST_CALL functionDollarAgentLeaving(ExecState*)
1955{
1956 return JSValue::encode(jsUndefined());
1957}
1958
1959EncodedJSValue JSC_HOST_CALL functionDollarAgentMonotonicNow(ExecState*)
1960{
1961 return JSValue::encode(jsNumber(MonotonicTime::now().secondsSinceEpoch().milliseconds()));
1962}
1963
1964EncodedJSValue JSC_HOST_CALL functionWaitForReport(ExecState* exec)
1965{
1966 VM& vm = exec->vm();
1967
1968 String string;
1969 {
1970 ReleaseHeapAccessScope releaseAccess(vm.heap);
1971 string = Workers::singleton().getReport();
1972 }
1973 if (!string)
1974 return JSValue::encode(jsNull());
1975
1976 return JSValue::encode(jsString(&vm, string));
1977}
1978
1979EncodedJSValue JSC_HOST_CALL functionHeapCapacity(ExecState* exec)
1980{
1981 VM& vm = exec->vm();
1982 return JSValue::encode(jsNumber(vm.heap.capacity()));
1983}
1984
1985EncodedJSValue JSC_HOST_CALL functionFlashHeapAccess(ExecState* exec)
1986{
1987 VM& vm = exec->vm();
1988 auto scope = DECLARE_THROW_SCOPE(vm);
1989
1990 double sleepTimeMs = 0;
1991 if (exec->argumentCount() >= 1) {
1992 sleepTimeMs = exec->argument(0).toNumber(exec);
1993 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1994 }
1995
1996 vm.heap.releaseAccess();
1997 if (sleepTimeMs)
1998 sleep(Seconds::fromMilliseconds(sleepTimeMs));
1999 vm.heap.acquireAccess();
2000 return JSValue::encode(jsUndefined());
2001}
2002
2003EncodedJSValue JSC_HOST_CALL functionDisableRichSourceInfo(ExecState*)
2004{
2005 supportsRichSourceInfo = false;
2006 return JSValue::encode(jsUndefined());
2007}
2008
2009EncodedJSValue JSC_HOST_CALL functionMallocInALoop(ExecState*)
2010{
2011 Vector<void*> ptrs;
2012 for (unsigned i = 0; i < 5000; ++i)
2013 ptrs.append(fastMalloc(1024 * 2));
2014 for (void* ptr : ptrs)
2015 fastFree(ptr);
2016 return JSValue::encode(jsUndefined());
2017}
2018
2019EncodedJSValue JSC_HOST_CALL functionTotalCompileTime(ExecState*)
2020{
2021#if ENABLE(JIT)
2022 return JSValue::encode(jsNumber(JIT::totalCompileTime().milliseconds()));
2023#else
2024 return JSValue::encode(jsNumber(0));
2025#endif
2026}
2027
2028template<typename ValueType>
2029typename std::enable_if<!std::is_fundamental<ValueType>::value>::type addOption(VM&, JSObject*, const Identifier&, ValueType) { }
2030
2031template<typename ValueType>
2032typename std::enable_if<std::is_fundamental<ValueType>::value>::type addOption(VM& vm, JSObject* optionsObject, const Identifier& identifier, ValueType value)
2033{
2034 optionsObject->putDirect(vm, identifier, JSValue(value));
2035}
2036
2037EncodedJSValue JSC_HOST_CALL functionJSCOptions(ExecState* exec)
2038{
2039 VM& vm = exec->vm();
2040 JSObject* optionsObject = constructEmptyObject(exec);
2041#define FOR_EACH_OPTION(type_, name_, defaultValue_, availability_, description_) \
2042 addOption(vm, optionsObject, Identifier::fromString(exec, #name_), Options::name_());
2043 JSC_OPTIONS(FOR_EACH_OPTION)
2044#undef FOR_EACH_OPTION
2045 return JSValue::encode(optionsObject);
2046}
2047
2048EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState* exec)
2049{
2050 if (exec->argumentCount() < 1)
2051 return JSValue::encode(jsUndefined());
2052
2053 CodeBlock* block = getSomeBaselineCodeBlockForFunction(exec->argument(0));
2054 if (!block)
2055 return JSValue::encode(jsNumber(0));
2056
2057 return JSValue::encode(jsNumber(block->reoptimizationRetryCounter()));
2058}
2059
2060EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState* exec)
2061{
2062 VM& vm = exec->vm();
2063 auto scope = DECLARE_THROW_SCOPE(vm);
2064
2065 if (exec->argumentCount() < 1)
2066 return JSValue::encode(throwException(exec, scope, createError(exec, "Not enough arguments"_s)));
2067
2068 JSArrayBuffer* buffer = jsDynamicCast<JSArrayBuffer*>(vm, exec->argument(0));
2069 if (!buffer)
2070 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected an array buffer"_s)));
2071
2072 ArrayBufferContents dummyContents;
2073 buffer->impl()->transferTo(vm, dummyContents);
2074
2075 return JSValue::encode(jsUndefined());
2076}
2077
2078EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState* exec)
2079{
2080 VM& vm = exec->vm();
2081 vm.setFailNextNewCodeBlock();
2082 return JSValue::encode(jsUndefined());
2083}
2084
2085EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
2086{
2087 VM& vm = exec->vm();
2088 vm.codeCache()->write(vm);
2089
2090 jscExit(EXIT_SUCCESS);
2091
2092#if COMPILER(MSVC)
2093 // Without this, Visual Studio will complain that this method does not return a value.
2094 return JSValue::encode(jsUndefined());
2095#endif
2096}
2097
2098EncodedJSValue JSC_HOST_CALL functionFalse(ExecState*) { return JSValue::encode(jsBoolean(false)); }
2099
2100EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*) { return JSValue::encode(jsUndefined()); }
2101EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*) { return JSValue::encode(jsUndefined()); }
2102EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState* exec)
2103{
2104 for (size_t i = 0; i < exec->argumentCount(); ++i) {
2105 if (!exec->argument(i).isInt32())
2106 return JSValue::encode(jsBoolean(false));
2107 }
2108 return JSValue::encode(jsBoolean(true));
2109}
2110
2111EncodedJSValue JSC_HOST_CALL functionIsPureNaN(ExecState* exec)
2112{
2113 for (size_t i = 0; i < exec->argumentCount(); ++i) {
2114 JSValue value = exec->argument(i);
2115 if (!value.isNumber())
2116 return JSValue::encode(jsBoolean(false));
2117 double number = value.asNumber();
2118 if (!std::isnan(number))
2119 return JSValue::encode(jsBoolean(false));
2120 if (isImpureNaN(number))
2121 return JSValue::encode(jsBoolean(false));
2122 }
2123 return JSValue::encode(jsBoolean(true));
2124}
2125
2126EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState* exec) { return JSValue::encode(exec->argument(0)); }
2127
2128EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*)
2129{
2130 return JSValue::encode(jsNumber(42));
2131}
2132
2133EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState* exec)
2134{
2135 VM& vm = exec->vm();
2136 return JSValue::encode(Masquerader::create(vm, exec->lexicalGlobalObject()));
2137}
2138
2139EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState* exec)
2140{
2141 JSValue value = exec->argument(0);
2142 if (value.isObject())
2143 return JSValue::encode(jsBoolean(asObject(value)->hasCustomProperties(exec->vm())));
2144 return JSValue::encode(jsBoolean(false));
2145}
2146
2147EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState* exec)
2148{
2149 VM& vm = exec->vm();
2150 vm.dumpTypeProfilerData();
2151 return JSValue::encode(jsUndefined());
2152}
2153
2154EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState* exec)
2155{
2156 VM& vm = exec->vm();
2157 vm.drainMicrotasks();
2158 return JSValue::encode(jsUndefined());
2159}
2160
2161EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*)
2162{
2163#if USE(JSVALUE64)
2164 return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
2165#else
2166 return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
2167#endif
2168}
2169
2170EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState* exec)
2171{
2172 VM& vm = exec->vm();
2173 return JSValue::encode(GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>()));
2174}
2175
2176EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState* exec)
2177{
2178 VM& vm = exec->vm();
2179 auto scope = DECLARE_THROW_SCOPE(vm);
2180
2181 String source = exec->argument(0).toWTFString(exec);
2182 RETURN_IF_EXCEPTION(scope, encodedJSValue());
2183
2184 StopWatch stopWatch;
2185 stopWatch.start();
2186
2187 ParserError error;
2188 bool validSyntax = checkModuleSyntax(exec, jscSource(source, { }, URL(), TextPosition(), SourceProviderSourceType::Module), error);
2189 RETURN_IF_EXCEPTION(scope, encodedJSValue());
2190 stopWatch.stop();
2191
2192 if (!validSyntax)
2193 throwException(exec, scope, jsNontrivialString(exec, toString("SyntaxError: ", error.message(), ":", error.line())));
2194 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
2195}
2196
2197EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*)
2198{
2199#if ENABLE(SAMPLING_PROFILER)
2200 return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
2201#else
2202 return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
2203#endif
2204}
2205
2206EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState* exec)
2207{
2208 VM& vm = exec->vm();
2209 JSLockHolder lock(vm);
2210 auto scope = DECLARE_THROW_SCOPE(vm);
2211
2212 HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler());
2213 snapshotBuilder.buildSnapshot();
2214
2215 String jsonString = snapshotBuilder.json();
2216 EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
2217 scope.releaseAssertNoException();
2218 return result;
2219}
2220
2221EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshotForGCDebugging(ExecState* exec)
2222{
2223 VM& vm = exec->vm();
2224 JSLockHolder lock(vm);
2225 auto scope = DECLARE_THROW_SCOPE(vm);
2226 String jsonString;
2227 {
2228 DeferGCForAWhile deferGC(vm.heap); // Prevent concurrent GC from interfering with the full GC that the snapshot does.
2229
2230 HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler(), HeapSnapshotBuilder::SnapshotType::GCDebuggingSnapshot);
2231 snapshotBuilder.buildSnapshot();
2232
2233 jsonString = snapshotBuilder.json();
2234 }
2235 scope.releaseAssertNoException();
2236 return JSValue::encode(jsString(&vm, jsonString));
2237}
2238
2239EncodedJSValue JSC_HOST_CALL functionResetSuperSamplerState(ExecState*)
2240{
2241 resetSuperSamplerState();
2242 return JSValue::encode(jsUndefined());
2243}
2244
2245EncodedJSValue JSC_HOST_CALL functionEnsureArrayStorage(ExecState* exec)
2246{
2247 VM& vm = exec->vm();
2248 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
2249 if (JSObject* object = jsDynamicCast<JSObject*>(vm, exec->argument(i)))
2250 object->ensureArrayStorage(vm);
2251 }
2252 return JSValue::encode(jsUndefined());
2253}
2254
2255#if ENABLE(SAMPLING_PROFILER)
2256EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState* exec)
2257{
2258 VM& vm = exec->vm();
2259 SamplingProfiler& samplingProfiler = vm.ensureSamplingProfiler(WTF::Stopwatch::create());
2260 samplingProfiler.noticeCurrentThreadAsJSCExecutionThread();
2261 samplingProfiler.start();
2262 return JSValue::encode(jsUndefined());
2263}
2264
2265EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState* exec)
2266{
2267 VM& vm = exec->vm();
2268 auto scope = DECLARE_THROW_SCOPE(vm);
2269
2270 if (!vm.samplingProfiler())
2271 return JSValue::encode(throwException(exec, scope, createError(exec, "Sampling profiler was never started"_s)));
2272
2273 String jsonString = vm.samplingProfiler()->stackTracesAsJSON();
2274 EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
2275 scope.releaseAssertNoException();
2276 return result;
2277}
2278#endif // ENABLE(SAMPLING_PROFILER)
2279
2280EncodedJSValue JSC_HOST_CALL functionMaxArguments(ExecState*)
2281{
2282 return JSValue::encode(jsNumber(JSC::maxArguments));
2283}
2284
2285EncodedJSValue JSC_HOST_CALL functionAsyncTestStart(ExecState* exec)
2286{
2287 VM& vm = exec->vm();
2288 auto scope = DECLARE_THROW_SCOPE(vm);
2289
2290 JSValue numberOfAsyncPasses = exec->argument(0);
2291 if (!numberOfAsyncPasses.isUInt32())
2292 return throwVMError(exec, scope, "Expected first argument to a uint32"_s);
2293
2294 asyncTestExpectedPasses += numberOfAsyncPasses.asUInt32();
2295 return encodedJSUndefined();
2296}
2297
2298EncodedJSValue JSC_HOST_CALL functionAsyncTestPassed(ExecState*)
2299{
2300 asyncTestPasses++;
2301 return encodedJSUndefined();
2302}
2303
2304#if ENABLE(WEBASSEMBLY)
2305
2306static EncodedJSValue JSC_HOST_CALL functionWebAssemblyMemoryMode(ExecState* exec)
2307{
2308 VM& vm = exec->vm();
2309 auto scope = DECLARE_THROW_SCOPE(vm);
2310
2311 if (!Wasm::isSupported())
2312 return throwVMTypeError(exec, scope, "WebAssemblyMemoryMode should only be called if the useWebAssembly option is set"_s);
2313
2314 if (JSObject* object = exec->argument(0).getObject()) {
2315 if (auto* memory = jsDynamicCast<JSWebAssemblyMemory*>(vm, object))
2316 return JSValue::encode(jsString(&vm, makeString(memory->memory().mode())));
2317 if (auto* instance = jsDynamicCast<JSWebAssemblyInstance*>(vm, object))
2318 return JSValue::encode(jsString(&vm, makeString(instance->memoryMode())));
2319 }
2320
2321 return throwVMTypeError(exec, scope, "WebAssemblyMemoryMode expects either a WebAssembly.Memory or WebAssembly.Instance"_s);
2322}
2323
2324#endif // ENABLE(WEBASSEMBLY)
2325
2326// Use SEH for Release builds only to get rid of the crash report dialog
2327// (luckily the same tests fail in Release and Debug builds so far). Need to
2328// be in a separate main function because the jscmain function requires object
2329// unwinding.
2330
2331#if COMPILER(MSVC) && !defined(_DEBUG)
2332#define TRY __try {
2333#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
2334#else
2335#define TRY
2336#define EXCEPT(x)
2337#endif
2338
2339int jscmain(int argc, char** argv);
2340
2341static double s_desiredTimeout;
2342static double s_timeoutMultiplier = 1.0;
2343
2344static void startTimeoutThreadIfNeeded()
2345{
2346 if (char* timeoutString = getenv("JSCTEST_timeout")) {
2347 if (sscanf(timeoutString, "%lf", &s_desiredTimeout) != 1) {
2348 dataLog("WARNING: timeout string is malformed, got ", timeoutString,
2349 " but expected a number. Not using a timeout.\n");
2350 } else {
2351 Thread::create("jsc Timeout Thread", [] () {
2352 Seconds timeoutDuration(s_desiredTimeout * s_timeoutMultiplier);
2353 sleep(timeoutDuration);
2354 dataLog("Timed out after ", timeoutDuration, " seconds!\n");
2355 CRASH();
2356 });
2357 }
2358 }
2359}
2360
2361int main(int argc, char** argv)
2362{
2363#if PLATFORM(IOS_FAMILY) && CPU(ARM_THUMB2)
2364 // Enabled IEEE754 denormal support.
2365 fenv_t env;
2366 fegetenv( &env );
2367 env.__fpscr &= ~0x01000000u;
2368 fesetenv( &env );
2369#endif
2370
2371#if OS(WINDOWS)
2372 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
2373 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
2374 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
2375 ::SetErrorMode(0);
2376
2377 _setmode(_fileno(stdout), _O_BINARY);
2378 _setmode(_fileno(stderr), _O_BINARY);
2379
2380#if defined(_DEBUG)
2381 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
2382 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2383 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
2384 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
2385 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
2386 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
2387#endif
2388
2389 timeBeginPeriod(1);
2390#endif
2391
2392#if PLATFORM(GTK)
2393 if (!setlocale(LC_ALL, ""))
2394 WTFLogAlways("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
2395#endif
2396
2397 // Need to initialize WTF threading before we start any threads. Cannot initialize JSC
2398 // threading yet, since that would do somethings that we'd like to defer until after we
2399 // have a chance to parse options.
2400 WTF::initializeThreading();
2401
2402#if PLATFORM(IOS_FAMILY)
2403 Options::crashIfCantAllocateJITMemory() = true;
2404#endif
2405
2406 // We can't use destructors in the following code because it uses Windows
2407 // Structured Exception Handling
2408 int res = 0;
2409 TRY
2410 res = jscmain(argc, argv);
2411 EXCEPT(res = 3)
2412 finalizeStatsAtEndOfTesting();
2413
2414 jscExit(res);
2415}
2416
2417static void dumpException(GlobalObject* globalObject, JSValue exception)
2418{
2419 VM& vm = globalObject->vm();
2420 auto scope = DECLARE_CATCH_SCOPE(vm);
2421
2422#define CHECK_EXCEPTION() do { \
2423 if (scope.exception()) { \
2424 scope.clearException(); \
2425 return; \
2426 } \
2427 } while (false)
2428
2429 auto exceptionString = exception.toWTFString(globalObject->globalExec());
2430 Expected<CString, UTF8ConversionError> expectedCString = exceptionString.tryGetUtf8();
2431 if (expectedCString)
2432 printf("Exception: %s\n", expectedCString.value().data());
2433 else
2434 printf("Exception: <out of memory while extracting exception string>\n");
2435
2436 Identifier nameID = Identifier::fromString(globalObject->globalExec(), "name");
2437 CHECK_EXCEPTION();
2438 Identifier fileNameID = Identifier::fromString(globalObject->globalExec(), "sourceURL");
2439 CHECK_EXCEPTION();
2440 Identifier lineNumberID = Identifier::fromString(globalObject->globalExec(), "line");
2441 CHECK_EXCEPTION();
2442 Identifier stackID = Identifier::fromString(globalObject->globalExec(), "stack");
2443 CHECK_EXCEPTION();
2444
2445 JSValue nameValue = exception.get(globalObject->globalExec(), nameID);
2446 CHECK_EXCEPTION();
2447 JSValue fileNameValue = exception.get(globalObject->globalExec(), fileNameID);
2448 CHECK_EXCEPTION();
2449 JSValue lineNumberValue = exception.get(globalObject->globalExec(), lineNumberID);
2450 CHECK_EXCEPTION();
2451 JSValue stackValue = exception.get(globalObject->globalExec(), stackID);
2452 CHECK_EXCEPTION();
2453
2454 if (nameValue.toWTFString(globalObject->globalExec()) == "SyntaxError"
2455 && (!fileNameValue.isUndefinedOrNull() || !lineNumberValue.isUndefinedOrNull())) {
2456 printf(
2457 "at %s:%s\n",
2458 fileNameValue.toWTFString(globalObject->globalExec()).utf8().data(),
2459 lineNumberValue.toWTFString(globalObject->globalExec()).utf8().data());
2460 }
2461
2462 if (!stackValue.isUndefinedOrNull()) {
2463 auto stackString = stackValue.toWTFString(globalObject->globalExec());
2464 if (stackString.length())
2465 printf("%s\n", stackString.utf8().data());
2466 }
2467
2468#undef CHECK_EXCEPTION
2469}
2470
2471static bool checkUncaughtException(VM& vm, GlobalObject* globalObject, JSValue exception, CommandLine& options)
2472{
2473 const String& expectedExceptionName = options.m_uncaughtExceptionName;
2474 auto scope = DECLARE_CATCH_SCOPE(vm);
2475 scope.clearException();
2476 if (!exception) {
2477 printf("Expected uncaught exception with name '%s' but none was thrown\n", expectedExceptionName.utf8().data());
2478 return false;
2479 }
2480
2481 ExecState* exec = globalObject->globalExec();
2482 JSValue exceptionClass = globalObject->get(exec, Identifier::fromString(exec, expectedExceptionName));
2483 if (!exceptionClass.isObject() || scope.exception()) {
2484 printf("Expected uncaught exception with name '%s' but given exception class is not defined\n", expectedExceptionName.utf8().data());
2485 return false;
2486 }
2487
2488 bool isInstanceOfExpectedException = jsCast<JSObject*>(exceptionClass)->hasInstance(exec, exception);
2489 if (scope.exception()) {
2490 printf("Expected uncaught exception with name '%s' but given exception class fails performing hasInstance\n", expectedExceptionName.utf8().data());
2491 return false;
2492 }
2493 if (isInstanceOfExpectedException) {
2494 if (options.m_alwaysDumpUncaughtException)
2495 dumpException(globalObject, exception);
2496 return true;
2497 }
2498
2499 printf("Expected uncaught exception with name '%s' but exception value is not instance of this exception class\n", expectedExceptionName.utf8().data());
2500 dumpException(globalObject, exception);
2501 return false;
2502}
2503
2504static void checkException(ExecState* exec, GlobalObject* globalObject, bool isLastFile, bool hasException, JSValue value, CommandLine& options, bool& success)
2505{
2506 VM& vm = globalObject->vm();
2507
2508 if (options.m_treatWatchdogExceptionAsSuccess && value.inherits<TerminatedExecutionError>(vm)) {
2509 ASSERT(hasException);
2510 return;
2511 }
2512
2513 if (!options.m_uncaughtExceptionName || !isLastFile) {
2514 success = success && !hasException;
2515 if (options.m_dump && !hasException)
2516 printf("End: %s\n", value.toWTFString(exec).utf8().data());
2517 if (hasException)
2518 dumpException(globalObject, value);
2519 } else
2520 success = success && checkUncaughtException(vm, globalObject, (hasException) ? value : JSValue(), options);
2521}
2522
2523static void runWithOptions(GlobalObject* globalObject, CommandLine& options, bool& success)
2524{
2525 Vector<Script>& scripts = options.m_scripts;
2526 String fileName;
2527 Vector<char> scriptBuffer;
2528
2529 if (options.m_dump)
2530 JSC::Options::dumpGeneratedBytecodes() = true;
2531
2532 VM& vm = globalObject->vm();
2533 auto scope = DECLARE_CATCH_SCOPE(vm);
2534
2535#if ENABLE(SAMPLING_FLAGS)
2536 SamplingFlags::start();
2537#endif
2538
2539 for (size_t i = 0; i < scripts.size(); i++) {
2540 JSInternalPromise* promise = nullptr;
2541 bool isModule = options.m_module || scripts[i].scriptType == Script::ScriptType::Module;
2542 if (scripts[i].codeSource == Script::CodeSource::File) {
2543 fileName = scripts[i].argument;
2544 if (scripts[i].strictMode == Script::StrictMode::Strict)
2545 scriptBuffer.append("\"use strict\";\n", strlen("\"use strict\";\n"));
2546
2547 if (isModule) {
2548 promise = loadAndEvaluateModule(globalObject->globalExec(), fileName, jsUndefined(), jsUndefined());
2549 scope.releaseAssertNoException();
2550 } else {
2551 if (!fetchScriptFromLocalFileSystem(fileName, scriptBuffer)) {
2552 success = false; // fail early so we can catch missing files
2553 return;
2554 }
2555 }
2556 } else {
2557 size_t commandLineLength = strlen(scripts[i].argument);
2558 scriptBuffer.resize(commandLineLength);
2559 std::copy(scripts[i].argument, scripts[i].argument + commandLineLength, scriptBuffer.begin());
2560 fileName = "[Command Line]"_s;
2561 }
2562
2563 bool isLastFile = i == scripts.size() - 1;
2564 if (isModule) {
2565 if (!promise) {
2566 // FIXME: This should use an absolute file URL https://bugs.webkit.org/show_bug.cgi?id=193077
2567 promise = loadAndEvaluateModule(globalObject->globalExec(), jscSource(stringFromUTF(scriptBuffer), SourceOrigin { absolutePath(fileName) }, URL({ }, fileName), TextPosition(), SourceProviderSourceType::Module), jsUndefined());
2568 }
2569 scope.clearException();
2570
2571 JSFunction* fulfillHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&success, &options, isLastFile](ExecState* exec) {
2572 checkException(exec, jsCast<GlobalObject*>(exec->lexicalGlobalObject()), isLastFile, false, exec->argument(0), options, success);
2573 return JSValue::encode(jsUndefined());
2574 });
2575
2576 JSFunction* rejectHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&success, &options, isLastFile](ExecState* exec) {
2577 checkException(exec, jsCast<GlobalObject*>(exec->lexicalGlobalObject()), isLastFile, true, exec->argument(0), options, success);
2578 return JSValue::encode(jsUndefined());
2579 });
2580
2581 promise->then(globalObject->globalExec(), fulfillHandler, rejectHandler);
2582 scope.releaseAssertNoException();
2583 vm.drainMicrotasks();
2584 } else {
2585 NakedPtr<Exception> evaluationException;
2586 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(scriptBuffer, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), evaluationException);
2587 scope.assertNoException();
2588 if (evaluationException)
2589 returnValue = evaluationException->value();
2590 checkException(globalObject->globalExec(), globalObject, isLastFile, evaluationException, returnValue, options, success);
2591 }
2592
2593 scriptBuffer.clear();
2594 scope.clearException();
2595 }
2596
2597#if ENABLE(REGEXP_TRACING)
2598 vm.dumpRegExpTrace();
2599#endif
2600}
2601
2602#define RUNNING_FROM_XCODE 0
2603
2604static void runInteractive(GlobalObject* globalObject)
2605{
2606 VM& vm = globalObject->vm();
2607 auto scope = DECLARE_CATCH_SCOPE(vm);
2608
2609 Optional<DirectoryName> directoryName = currentWorkingDirectory();
2610 if (!directoryName)
2611 return;
2612 SourceOrigin sourceOrigin(resolvePath(directoryName.value(), ModuleName("interpreter")));
2613
2614 bool shouldQuit = false;
2615 while (!shouldQuit) {
2616#if HAVE(READLINE) && !RUNNING_FROM_XCODE
2617 ParserError error;
2618 String source;
2619 do {
2620 error = ParserError();
2621 char* line = readline(source.isEmpty() ? interactivePrompt : "... ");
2622 shouldQuit = !line;
2623 if (!line)
2624 break;
2625 source = source + String::fromUTF8(line);
2626 source = source + '\n';
2627 checkSyntax(vm, jscSource(source, sourceOrigin), error);
2628 if (!line[0]) {
2629 free(line);
2630 break;
2631 }
2632 add_history(line);
2633 free(line);
2634 } while (error.syntaxErrorType() == ParserError::SyntaxErrorRecoverable);
2635
2636 if (error.isValid()) {
2637 printf("%s:%d\n", error.message().utf8().data(), error.line());
2638 continue;
2639 }
2640
2641
2642 NakedPtr<Exception> evaluationException;
2643 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(source, sourceOrigin), JSValue(), evaluationException);
2644#else
2645 printf("%s", interactivePrompt);
2646 Vector<char, 256> line;
2647 int c;
2648 while ((c = getchar()) != EOF) {
2649 // FIXME: Should we also break on \r?
2650 if (c == '\n')
2651 break;
2652 line.append(c);
2653 }
2654 if (line.isEmpty())
2655 break;
2656
2657 NakedPtr<Exception> evaluationException;
2658 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(line, sourceOrigin, sourceOrigin.string()), JSValue(), evaluationException);
2659#endif
2660 if (evaluationException)
2661 printf("Exception: %s\n", evaluationException->value().toWTFString(globalObject->globalExec()).utf8().data());
2662 else
2663 printf("%s\n", returnValue.toWTFString(globalObject->globalExec()).utf8().data());
2664
2665 scope.clearException();
2666 vm.drainMicrotasks();
2667 }
2668 printf("\n");
2669}
2670
2671static NO_RETURN void printUsageStatement(bool help = false)
2672{
2673 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
2674 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
2675 fprintf(stderr, " -e Evaluate argument as script code\n");
2676 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
2677 fprintf(stderr, " -h|--help Prints this help message\n");
2678 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
2679 fprintf(stderr, " -m Execute as a module\n");
2680#if HAVE(SIGNAL_H)
2681 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
2682#endif
2683 fprintf(stderr, " -p <file> Outputs profiling data to a file\n");
2684 fprintf(stderr, " -x Output exit code before terminating\n");
2685 fprintf(stderr, "\n");
2686 fprintf(stderr, " --sample Collects and outputs sampling profiler data\n");
2687 fprintf(stderr, " --test262-async Check that some script calls the print function with the string 'Test262:AsyncTestComplete'\n");
2688 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");
2689 fprintf(stderr, " --module-file=<file> Parse and evaluate the given file as module (this option may be passed more than once)\n");
2690 fprintf(stderr, " --exception=<name> Check the last script exits with an uncaught exception with the specified name\n");
2691 fprintf(stderr, " --watchdog-exception-ok Uncaught watchdog exceptions exit with success\n");
2692 fprintf(stderr, " --dumpException Dump uncaught exception text\n");
2693 fprintf(stderr, " --footprint Dump memory footprint after done executing\n");
2694 fprintf(stderr, " --options Dumps all JSC VM options and exits\n");
2695 fprintf(stderr, " --dumpOptions Dumps all non-default JSC VM options before continuing\n");
2696 fprintf(stderr, " --<jsc VM option>=<value> Sets the specified JSC VM option\n");
2697 fprintf(stderr, " --destroy-vm Destroy VM before exiting\n");
2698 fprintf(stderr, "\n");
2699 fprintf(stderr, "Files with a .mjs extension will always be evaluated as modules.\n");
2700 fprintf(stderr, "\n");
2701
2702 jscExit(help ? EXIT_SUCCESS : EXIT_FAILURE);
2703}
2704
2705static bool isMJSFile(char *filename)
2706{
2707 filename = strrchr(filename, '.');
2708
2709 if (filename)
2710 return !strcmp(filename, ".mjs");
2711
2712 return false;
2713}
2714
2715void CommandLine::parseArguments(int argc, char** argv)
2716{
2717 Options::initialize();
2718
2719 if (Options::dumpOptions()) {
2720 printf("Command line:");
2721#if PLATFORM(COCOA)
2722 for (char** envp = *_NSGetEnviron(); *envp; envp++) {
2723 const char* env = *envp;
2724 if (!strncmp("JSC_", env, 4))
2725 printf(" %s", env);
2726 }
2727#endif // PLATFORM(COCOA)
2728 for (int i = 0; i < argc; ++i)
2729 printf(" %s", argv[i]);
2730 printf("\n");
2731 }
2732
2733 int i = 1;
2734 JSC::Options::DumpLevel dumpOptionsLevel = JSC::Options::DumpLevel::None;
2735 bool needToExit = false;
2736
2737 bool hasBadJSCOptions = false;
2738 for (; i < argc; ++i) {
2739 const char* arg = argv[i];
2740 if (!strcmp(arg, "-f")) {
2741 if (++i == argc)
2742 printUsageStatement();
2743 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Script, argv[i]));
2744 continue;
2745 }
2746 if (!strcmp(arg, "-e")) {
2747 if (++i == argc)
2748 printUsageStatement();
2749 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::CommandLine, Script::ScriptType::Script, argv[i]));
2750 continue;
2751 }
2752 if (!strcmp(arg, "-i")) {
2753 m_interactive = true;
2754 continue;
2755 }
2756 if (!strcmp(arg, "-d")) {
2757 m_dump = true;
2758 continue;
2759 }
2760 if (!strcmp(arg, "-p")) {
2761 if (++i == argc)
2762 printUsageStatement();
2763 m_profile = true;
2764 m_profilerOutput = argv[i];
2765 continue;
2766 }
2767 if (!strcmp(arg, "-m")) {
2768 m_module = true;
2769 continue;
2770 }
2771 if (!strcmp(arg, "-s")) {
2772#if HAVE(SIGNAL_H)
2773 signal(SIGILL, _exit);
2774 signal(SIGFPE, _exit);
2775 signal(SIGBUS, _exit);
2776 signal(SIGSEGV, _exit);
2777#endif
2778 continue;
2779 }
2780 if (!strcmp(arg, "-x")) {
2781 m_exitCode = true;
2782 continue;
2783 }
2784 if (!strcmp(arg, "--")) {
2785 ++i;
2786 break;
2787 }
2788 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
2789 printUsageStatement(true);
2790
2791 if (!strcmp(arg, "--options")) {
2792 dumpOptionsLevel = JSC::Options::DumpLevel::Verbose;
2793 needToExit = true;
2794 continue;
2795 }
2796 if (!strcmp(arg, "--dumpOptions")) {
2797 dumpOptionsLevel = JSC::Options::DumpLevel::Overridden;
2798 continue;
2799 }
2800 if (!strcmp(arg, "--sample")) {
2801 JSC::Options::useSamplingProfiler() = true;
2802 JSC::Options::collectSamplingProfilerDataForJSCShell() = true;
2803 m_dumpSamplingProfilerData = true;
2804 continue;
2805 }
2806 if (!strcmp(arg, "--destroy-vm")) {
2807 m_destroyVM = true;
2808 continue;
2809 }
2810
2811 static const char* timeoutMultiplierOptStr = "--timeoutMultiplier=";
2812 static const unsigned timeoutMultiplierOptStrLength = strlen(timeoutMultiplierOptStr);
2813 if (!strncmp(arg, timeoutMultiplierOptStr, timeoutMultiplierOptStrLength)) {
2814 const char* valueStr = &arg[timeoutMultiplierOptStrLength];
2815 if (sscanf(valueStr, "%lf", &s_timeoutMultiplier) != 1)
2816 dataLog("WARNING: --timeoutMultiplier=", valueStr, " is invalid. Expects a numeric ratio.\n");
2817 continue;
2818 }
2819
2820 if (!strcmp(arg, "--test262-async")) {
2821 asyncTestExpectedPasses++;
2822 continue;
2823 }
2824
2825 if (!strcmp(arg, "--remote-debug")) {
2826 m_enableRemoteDebugging = true;
2827 continue;
2828 }
2829
2830 static const unsigned strictFileStrLength = strlen("--strict-file=");
2831 if (!strncmp(arg, "--strict-file=", strictFileStrLength)) {
2832 m_scripts.append(Script(Script::StrictMode::Strict, Script::CodeSource::File, Script::ScriptType::Script, argv[i] + strictFileStrLength));
2833 continue;
2834 }
2835
2836 static const unsigned moduleFileStrLength = strlen("--module-file=");
2837 if (!strncmp(arg, "--module-file=", moduleFileStrLength)) {
2838 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Module, argv[i] + moduleFileStrLength));
2839 continue;
2840 }
2841
2842 if (!strcmp(arg, "--dumpException")) {
2843 m_alwaysDumpUncaughtException = true;
2844 continue;
2845 }
2846
2847 if (!strcmp(arg, "--footprint")) {
2848 m_dumpMemoryFootprint = true;
2849 continue;
2850 }
2851
2852 static const unsigned exceptionStrLength = strlen("--exception=");
2853 if (!strncmp(arg, "--exception=", exceptionStrLength)) {
2854 m_uncaughtExceptionName = String(arg + exceptionStrLength);
2855 continue;
2856 }
2857
2858 if (!strcmp(arg, "--watchdog-exception-ok")) {
2859 m_treatWatchdogExceptionAsSuccess = true;
2860 continue;
2861 }
2862
2863 // See if the -- option is a JSC VM option.
2864 if (strstr(arg, "--") == arg) {
2865 if (!JSC::Options::setOption(&arg[2])) {
2866 hasBadJSCOptions = true;
2867 dataLog("ERROR: invalid option: ", arg, "\n");
2868 }
2869 continue;
2870 }
2871
2872 // This arg is not recognized by the VM nor by jsc. Pass it on to the
2873 // script.
2874 Script::ScriptType scriptType = isMJSFile(argv[i]) ? Script::ScriptType::Module : Script::ScriptType::Script;
2875 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, scriptType, argv[i]));
2876 }
2877
2878 if (hasBadJSCOptions && JSC::Options::validateOptions())
2879 CRASH();
2880
2881 if (m_scripts.isEmpty())
2882 m_interactive = true;
2883
2884 for (; i < argc; ++i)
2885 m_arguments.append(argv[i]);
2886
2887 if (dumpOptionsLevel != JSC::Options::DumpLevel::None) {
2888 const char* optionsTitle = (dumpOptionsLevel == JSC::Options::DumpLevel::Overridden)
2889 ? "Modified JSC runtime options:"
2890 : "All JSC runtime options:";
2891 JSC::Options::dumpAllOptions(stderr, dumpOptionsLevel, optionsTitle);
2892 }
2893 JSC::Options::ensureOptionsAreCoherent();
2894 if (needToExit)
2895 jscExit(EXIT_SUCCESS);
2896}
2897
2898template<typename Func>
2899int runJSC(const CommandLine& options, bool isWorker, const Func& func)
2900{
2901 Worker worker(Workers::singleton());
2902
2903 VM& vm = VM::create(LargeHeap).leakRef();
2904 int result;
2905 bool success = true;
2906 GlobalObject* globalObject = nullptr;
2907 {
2908 JSLockHolder locker(vm);
2909
2910 if (options.m_profile && !vm.m_perBytecodeProfiler)
2911 vm.m_perBytecodeProfiler = std::make_unique<Profiler::Database>(vm);
2912
2913 globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), options.m_arguments);
2914 globalObject->setRemoteDebuggingEnabled(options.m_enableRemoteDebugging);
2915 func(vm, globalObject, success);
2916 vm.drainMicrotasks();
2917 }
2918 vm.promiseDeferredTimer->runRunLoop();
2919 {
2920 JSLockHolder locker(vm);
2921 if (options.m_interactive && success)
2922 runInteractive(globalObject);
2923 }
2924
2925 result = success && (asyncTestExpectedPasses == asyncTestPasses) ? 0 : 3;
2926
2927 if (options.m_exitCode) {
2928 printf("jsc exiting %d", result);
2929 if (asyncTestExpectedPasses != asyncTestPasses)
2930 printf(" because expected: %d async test passes but got: %d async test passes", asyncTestExpectedPasses, asyncTestPasses);
2931 printf("\n");
2932 }
2933
2934 if (options.m_profile) {
2935 JSLockHolder locker(vm);
2936 if (!vm.m_perBytecodeProfiler->save(options.m_profilerOutput.utf8().data()))
2937 fprintf(stderr, "could not save profiler output.\n");
2938 }
2939
2940#if ENABLE(JIT)
2941 {
2942 JSLockHolder locker(vm);
2943 if (Options::useExceptionFuzz())
2944 printf("JSC EXCEPTION FUZZ: encountered %u checks.\n", numberOfExceptionFuzzChecks());
2945 bool fireAtEnabled =
2946 Options::fireExecutableAllocationFuzzAt() || Options::fireExecutableAllocationFuzzAtOrAfter();
2947 if (Options::useExecutableAllocationFuzz() && (!fireAtEnabled || Options::verboseExecutableAllocationFuzz()))
2948 printf("JSC EXECUTABLE ALLOCATION FUZZ: encountered %u checks.\n", numberOfExecutableAllocationFuzzChecks());
2949 if (Options::useOSRExitFuzz()) {
2950 printf("JSC OSR EXIT FUZZ: encountered %u static checks.\n", numberOfStaticOSRExitFuzzChecks());
2951 printf("JSC OSR EXIT FUZZ: encountered %u dynamic checks.\n", numberOfOSRExitFuzzChecks());
2952 }
2953
2954
2955 auto compileTimeStats = JIT::compileTimeStats();
2956 Vector<CString> compileTimeKeys;
2957 for (auto& entry : compileTimeStats)
2958 compileTimeKeys.append(entry.key);
2959 std::sort(compileTimeKeys.begin(), compileTimeKeys.end());
2960 for (const CString& key : compileTimeKeys)
2961 printf("%40s: %.3lf ms\n", key.data(), compileTimeStats.get(key).milliseconds());
2962 }
2963#endif
2964
2965 if (Options::gcAtEnd()) {
2966 // We need to hold the API lock to do a GC.
2967 JSLockHolder locker(&vm);
2968 vm.heap.collectNow(Sync, CollectionScope::Full);
2969 }
2970
2971 if (options.m_dumpSamplingProfilerData) {
2972#if ENABLE(SAMPLING_PROFILER)
2973 JSLockHolder locker(&vm);
2974 vm.samplingProfiler()->reportTopFunctions();
2975 vm.samplingProfiler()->reportTopBytecodes();
2976#else
2977 dataLog("Sampling profiler is not enabled on this platform\n");
2978#endif
2979 }
2980
2981 vm.codeCache()->write(vm);
2982
2983 if (options.m_destroyVM || isWorker) {
2984 JSLockHolder locker(vm);
2985 // This is needed because we don't want the worker's main
2986 // thread to die before its compilation threads finish.
2987 vm.deref();
2988 }
2989
2990 return result;
2991}
2992
2993int jscmain(int argc, char** argv)
2994{
2995 // Need to override and enable restricted options before we start parsing options below.
2996 Options::enableRestrictedOptions(true);
2997
2998 // Note that the options parsing can affect VM creation, and thus
2999 // comes first.
3000 CommandLine options(argc, argv);
3001
3002 processConfigFile(Options::configFile(), "jsc");
3003
3004 // Initialize JSC before getting VM.
3005 WTF::initializeMainThread();
3006 JSC::initializeThreading();
3007 startTimeoutThreadIfNeeded();
3008#if ENABLE(WEBASSEMBLY)
3009 JSC::Wasm::enableFastMemory();
3010#endif
3011 Gigacage::disableDisablingPrimitiveGigacageIfShouldBeEnabled();
3012
3013#if PLATFORM(COCOA)
3014 auto& memoryPressureHandler = MemoryPressureHandler::singleton();
3015 {
3016 dispatch_queue_t queue = dispatch_queue_create("jsc shell memory pressure handler", DISPATCH_QUEUE_SERIAL);
3017 memoryPressureHandler.setDispatchQueue(queue);
3018 dispatch_release(queue);
3019 }
3020 Box<Critical> memoryPressureCriticalState = Box<Critical>::create(Critical::No);
3021 Box<Synchronous> memoryPressureSynchronousState = Box<Synchronous>::create(Synchronous::No);
3022 memoryPressureHandler.setLowMemoryHandler([=] (Critical critical, Synchronous synchronous) {
3023 // We set these racily with respect to reading them from the JS execution thread.
3024 *memoryPressureCriticalState = critical;
3025 *memoryPressureSynchronousState = synchronous;
3026 });
3027 memoryPressureHandler.setShouldLogMemoryMemoryPressureEvents(false);
3028 memoryPressureHandler.install();
3029
3030 auto onEachMicrotaskTick = [&] (VM& vm) {
3031 if (*memoryPressureCriticalState == Critical::No)
3032 return;
3033
3034 *memoryPressureCriticalState = Critical::No;
3035 bool isSynchronous = *memoryPressureSynchronousState == Synchronous::Yes;
3036
3037 WTF::releaseFastMallocFreeMemory();
3038 vm.deleteAllCode(DeleteAllCodeIfNotCollecting);
3039
3040 if (!vm.heap.isCurrentThreadBusy()) {
3041 if (isSynchronous) {
3042 vm.heap.collectNow(Sync, CollectionScope::Full);
3043 WTF::releaseFastMallocFreeMemory();
3044 } else
3045 vm.heap.collectNowFullIfNotDoneRecently(Async);
3046 }
3047 };
3048#endif
3049
3050 int result = runJSC(
3051 options, false,
3052 [&] (VM& vm, GlobalObject* globalObject, bool& success) {
3053 UNUSED_PARAM(vm);
3054#if PLATFORM(COCOA)
3055 vm.setOnEachMicrotaskTick(WTFMove(onEachMicrotaskTick));
3056#endif
3057 runWithOptions(globalObject, options, success);
3058 });
3059
3060 printSuperSamplerState();
3061
3062 if (options.m_dumpMemoryFootprint) {
3063 MemoryFootprint footprint = MemoryFootprint::now();
3064
3065 printf("Memory Footprint:\n Current Footprint: %" PRIu64 "\n Peak Footprint: %" PRIu64 "\n", footprint.current, footprint.peak);
3066 }
3067
3068 return result;
3069}
3070
3071#if OS(WINDOWS)
3072extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(int argc, const char* argv[])
3073{
3074 return main(argc, const_cast<char**>(argv));
3075}
3076#endif
3077