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 commitCachedBytecode();
971 }
972
973 RefPtr<CachedBytecode> cachedBytecode() const override
974 {
975 if (!m_cachedBytecode)
976 loadBytecode();
977 return m_cachedBytecode.copyRef();
978 }
979
980 void updateCache(const UnlinkedFunctionExecutable* executable, const SourceCode&, CodeSpecializationKind kind, const UnlinkedFunctionCodeBlock* codeBlock) const override
981 {
982 if (!cacheEnabled() || !m_cachedBytecode)
983 return;
984 Ref<CachedBytecode> cachedBytecode = encodeFunctionCodeBlock(*executable->vm(), codeBlock);
985 m_cachedBytecode->addFunctionUpdate(executable, kind, WTFMove(cachedBytecode));
986 }
987
988 void cacheBytecode(const BytecodeCacheGenerator& generator) const override
989 {
990 if (!cacheEnabled())
991 return;
992 if (!m_cachedBytecode)
993 m_cachedBytecode = CachedBytecode::create();
994 m_cachedBytecode->addGlobalUpdate(generator());
995 }
996
997 void commitCachedBytecode() const override
998 {
999#if OS(DARWIN)
1000 if (!cacheEnabled() || !m_cachedBytecode || !m_cachedBytecode->hasUpdates())
1001 return;
1002
1003 auto clearBytecode = makeScopeExit([&] {
1004 m_cachedBytecode = nullptr;
1005 });
1006
1007 String filename = cachePath();
1008 int fd = open(filename.utf8().data(), O_CREAT | O_WRONLY | O_TRUNC | O_EXLOCK | O_NONBLOCK, 0666);
1009 if (fd == -1)
1010 return;
1011
1012 auto closeFD = makeScopeExit([&] {
1013 close(fd);
1014 });
1015
1016 struct stat sb;
1017 int res = fstat(fd, &sb);
1018 size_t size = static_cast<size_t>(sb.st_size);
1019 if (res || size != m_cachedBytecode->size()) {
1020 // The bytecode cache has already been updated
1021 return;
1022 }
1023
1024 if (ftruncate(fd, m_cachedBytecode->sizeForUpdate()))
1025 return;
1026
1027 m_cachedBytecode->commitUpdates([&] (off_t offset, const void* data, size_t size) {
1028 off_t result = lseek(fd, offset, SEEK_SET);
1029 ASSERT_UNUSED(result, result != -1);
1030 size_t bytesWritten = static_cast<size_t>(write(fd, data, size));
1031 ASSERT_UNUSED(bytesWritten, bytesWritten == size);
1032 });
1033#endif
1034 }
1035
1036private:
1037 String cachePath() const
1038 {
1039 if (!cacheEnabled())
1040 return static_cast<const char*>(nullptr);
1041 const char* cachePath = Options::diskCachePath();
1042 String filename = sourceOrigin().string();
1043 filename.replace('/', '_');
1044 return makeString(cachePath, '/', source().toString().hash(), '-', filename, ".bytecode-cache");
1045 }
1046
1047 void loadBytecode() const
1048 {
1049#if OS(DARWIN)
1050 if (!cacheEnabled())
1051 return;
1052
1053 String filename = cachePath();
1054 if (filename.isNull())
1055 return;
1056
1057 int fd = open(filename.utf8().data(), O_RDONLY | O_SHLOCK | O_NONBLOCK);
1058 if (fd == -1)
1059 return;
1060
1061 auto closeFD = makeScopeExit([&] {
1062 close(fd);
1063 });
1064
1065 struct stat sb;
1066 int res = fstat(fd, &sb);
1067 size_t size = static_cast<size_t>(sb.st_size);
1068 if (res || !size)
1069 return;
1070
1071 void* buffer = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
1072 if (buffer == MAP_FAILED)
1073 return;
1074 m_cachedBytecode = CachedBytecode::create(buffer, size);
1075#endif
1076 }
1077
1078 ShellSourceProvider(const String& source, const SourceOrigin& sourceOrigin, URL&& url, const TextPosition& startPosition, SourceProviderSourceType sourceType)
1079 : StringSourceProvider(source, sourceOrigin, WTFMove(url), startPosition, sourceType)
1080 {
1081 }
1082
1083 static bool cacheEnabled()
1084 {
1085 static bool enabled = !!Options::diskCachePath();
1086 return enabled;
1087 }
1088
1089 mutable RefPtr<CachedBytecode> m_cachedBytecode;
1090};
1091
1092static inline SourceCode jscSource(const String& source, const SourceOrigin& sourceOrigin, URL&& url = URL(), const TextPosition& startPosition = TextPosition(), SourceProviderSourceType sourceType = SourceProviderSourceType::Program)
1093{
1094 return SourceCode(ShellSourceProvider::create(source, sourceOrigin, WTFMove(url), startPosition, sourceType), startPosition.m_line.oneBasedInt(), startPosition.m_column.oneBasedInt());
1095}
1096
1097template<typename Vector>
1098static inline SourceCode jscSource(const Vector& utf8, const SourceOrigin& sourceOrigin, const String& filename)
1099{
1100 // FIXME: This should use an absolute file URL https://bugs.webkit.org/show_bug.cgi?id=193077
1101 String str = stringFromUTF(utf8);
1102 return jscSource(str, sourceOrigin, URL({ }, filename));
1103}
1104
1105template<typename Vector>
1106static bool fetchModuleFromLocalFileSystem(const String& fileName, Vector& buffer)
1107{
1108 // We assume that fileName is always an absolute path.
1109#if OS(WINDOWS)
1110 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
1111 // Use long UNC to pass the long path name to the Windows APIs.
1112 auto pathName = makeString("\\\\?\\", fileName).wideCharacters();
1113 struct _stat status { };
1114 if (_wstat(pathName.data(), &status))
1115 return false;
1116 if ((status.st_mode & S_IFMT) != S_IFREG)
1117 return false;
1118
1119 FILE* f = _wfopen(pathName.data(), L"rb");
1120#else
1121 auto pathName = fileName.utf8();
1122 struct stat status { };
1123 if (stat(pathName.data(), &status))
1124 return false;
1125 if ((status.st_mode & S_IFMT) != S_IFREG)
1126 return false;
1127
1128 FILE* f = fopen(pathName.data(), "r");
1129#endif
1130 if (!f) {
1131 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1132 return false;
1133 }
1134
1135 bool result = fillBufferWithContentsOfFile(f, buffer);
1136 if (result)
1137 convertShebangToJSComment(buffer);
1138 fclose(f);
1139
1140 return result;
1141}
1142
1143JSInternalPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue key, JSValue, JSValue)
1144{
1145 VM& vm = globalObject->vm();
1146 auto throwScope = DECLARE_THROW_SCOPE(vm);
1147 JSInternalPromiseDeferred* deferred = JSInternalPromiseDeferred::tryCreate(exec, globalObject);
1148 RETURN_IF_EXCEPTION(throwScope, nullptr);
1149
1150 auto catchScope = DECLARE_CATCH_SCOPE(vm);
1151 auto reject = [&] (JSValue rejectionReason) {
1152 catchScope.clearException();
1153 auto result = deferred->reject(exec, rejectionReason);
1154 catchScope.clearException();
1155 return result;
1156 };
1157
1158 String moduleKey = key.toWTFString(exec);
1159 if (UNLIKELY(catchScope.exception()))
1160 return reject(catchScope.exception());
1161
1162 // Here, now we consider moduleKey as the fileName.
1163 Vector<uint8_t> buffer;
1164 if (!fetchModuleFromLocalFileSystem(moduleKey, buffer))
1165 return reject(createError(exec, makeString("Could not open file '", moduleKey, "'.")));
1166
1167
1168 URL moduleURL = URL({ }, moduleKey);
1169#if ENABLE(WEBASSEMBLY)
1170 // FileSystem does not have mime-type header. The JSC shell recognizes WebAssembly's magic header.
1171 if (buffer.size() >= 4) {
1172 if (buffer[0] == '\0' && buffer[1] == 'a' && buffer[2] == 's' && buffer[3] == 'm') {
1173 auto source = SourceCode(WebAssemblySourceProvider::create(WTFMove(buffer), SourceOrigin { moduleKey }, WTFMove(moduleURL)));
1174 catchScope.releaseAssertNoException();
1175 auto sourceCode = JSSourceCode::create(vm, WTFMove(source));
1176 catchScope.releaseAssertNoException();
1177 auto result = deferred->resolve(exec, sourceCode);
1178 catchScope.clearException();
1179 return result;
1180 }
1181 }
1182#endif
1183
1184 auto sourceCode = JSSourceCode::create(vm, jscSource(stringFromUTF(buffer), SourceOrigin { moduleKey }, WTFMove(moduleURL), TextPosition(), SourceProviderSourceType::Module));
1185 catchScope.releaseAssertNoException();
1186 auto result = deferred->resolve(exec, sourceCode);
1187 catchScope.clearException();
1188 return result;
1189}
1190
1191JSObject* GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObject* globalObject, ExecState* exec, JSModuleLoader*, JSValue key, JSModuleRecord*, JSValue)
1192{
1193 VM& vm = exec->vm();
1194 auto scope = DECLARE_THROW_SCOPE(vm);
1195
1196 JSObject* metaProperties = constructEmptyObject(exec, globalObject->nullPrototypeObjectStructure());
1197 RETURN_IF_EXCEPTION(scope, nullptr);
1198
1199 metaProperties->putDirect(vm, Identifier::fromString(&vm, "filename"), key);
1200 RETURN_IF_EXCEPTION(scope, nullptr);
1201
1202 return metaProperties;
1203}
1204
1205static CString cStringFromViewWithString(ExecState* exec, ThrowScope& scope, StringViewWithUnderlyingString& viewWithString)
1206{
1207 Expected<CString, UTF8ConversionError> expectedString = viewWithString.view.tryGetUtf8();
1208 if (expectedString)
1209 return expectedString.value();
1210 switch (expectedString.error()) {
1211 case UTF8ConversionError::OutOfMemory:
1212 throwOutOfMemoryError(exec, scope);
1213 break;
1214 case UTF8ConversionError::IllegalSource:
1215 scope.throwException(exec, createError(exec, "Illegal source encountered during UTF8 conversion"));
1216 break;
1217 case UTF8ConversionError::SourceExhausted:
1218 scope.throwException(exec, createError(exec, "Source exhausted during UTF8 conversion"));
1219 break;
1220 default:
1221 RELEASE_ASSERT_NOT_REACHED();
1222 }
1223 return { };
1224}
1225
1226static EncodedJSValue printInternal(ExecState* exec, FILE* out)
1227{
1228 VM& vm = exec->vm();
1229 auto scope = DECLARE_THROW_SCOPE(vm);
1230
1231 if (asyncTestExpectedPasses) {
1232 JSValue value = exec->argument(0);
1233 if (value.isString() && WTF::equal(asString(value)->value(exec).impl(), "Test262:AsyncTestComplete")) {
1234 asyncTestPasses++;
1235 return JSValue::encode(jsUndefined());
1236 }
1237 }
1238
1239 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1240 if (i)
1241 if (EOF == fputc(' ', out))
1242 goto fail;
1243
1244 auto viewWithString = exec->uncheckedArgument(i).toString(exec)->viewWithUnderlyingString(exec);
1245 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1246 auto string = cStringFromViewWithString(exec, scope, viewWithString);
1247 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1248 if (fprintf(out, "%s", string.data()) < 0)
1249 goto fail;
1250 }
1251
1252 fputc('\n', out);
1253fail:
1254 fflush(out);
1255 return JSValue::encode(jsUndefined());
1256}
1257
1258EncodedJSValue JSC_HOST_CALL functionPrintStdOut(ExecState* exec) { return printInternal(exec, stdout); }
1259EncodedJSValue JSC_HOST_CALL functionPrintStdErr(ExecState* exec) { return printInternal(exec, stderr); }
1260
1261EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
1262{
1263 VM& vm = exec->vm();
1264 auto scope = DECLARE_THROW_SCOPE(vm);
1265 auto viewWithString = exec->argument(0).toString(exec)->viewWithUnderlyingString(exec);
1266 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1267 auto string = cStringFromViewWithString(exec, scope, viewWithString);
1268 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1269 fprintf(stderr, "--> %s\n", string.data());
1270 return JSValue::encode(jsUndefined());
1271}
1272
1273EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState* exec)
1274{
1275 if (exec->argumentCount() < 1)
1276 return JSValue::encode(jsUndefined());
1277 return JSValue::encode(jsString(exec, toString(exec->argument(0))));
1278}
1279
1280EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState* exec)
1281{
1282 if (exec->argumentCount() < 1)
1283 return JSValue::encode(jsUndefined());
1284 VM& vm = exec->vm();
1285 JSObject* object = jsDynamicCast<JSObject*>(vm, exec->argument(0));
1286 if (!object)
1287 return JSValue::encode(jsNontrivialString(exec, "<not object>"_s));
1288 return JSValue::encode(jsNontrivialString(exec, toString("<Butterfly: ", RawPointer(object->butterfly()), "; public length: ", object->getArrayLength(), "; vector length: ", object->getVectorLength(), ">")));
1289}
1290
1291EncodedJSValue JSC_HOST_CALL functionSleepSeconds(ExecState* exec)
1292{
1293 VM& vm = exec->vm();
1294 auto scope = DECLARE_THROW_SCOPE(vm);
1295
1296 if (exec->argumentCount() >= 1) {
1297 Seconds seconds = Seconds(exec->argument(0).toNumber(exec));
1298 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1299 sleep(seconds);
1300 }
1301
1302 return JSValue::encode(jsUndefined());
1303}
1304
1305class FunctionJSCStackFunctor {
1306public:
1307 FunctionJSCStackFunctor(StringBuilder& trace)
1308 : m_trace(trace)
1309 {
1310 }
1311
1312 StackVisitor::Status operator()(StackVisitor& visitor) const
1313 {
1314 m_trace.append(makeString(" ", visitor->index(), " ", visitor->toString(), '\n'));
1315 return StackVisitor::Continue;
1316 }
1317
1318private:
1319 StringBuilder& m_trace;
1320};
1321
1322EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
1323{
1324 StringBuilder trace;
1325 trace.appendLiteral("--> Stack trace:\n");
1326
1327 FunctionJSCStackFunctor functor(trace);
1328 exec->iterate(functor);
1329 fprintf(stderr, "%s", trace.toString().utf8().data());
1330 return JSValue::encode(jsUndefined());
1331}
1332
1333EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState* exec)
1334{
1335 VM& vm = exec->vm();
1336 JSLockHolder lock(vm);
1337 vm.heap.collectNow(Sync, CollectionScope::Full);
1338 return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection()));
1339}
1340
1341EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState* exec)
1342{
1343 VM& vm = exec->vm();
1344 JSLockHolder lock(vm);
1345 vm.heap.collectSync(CollectionScope::Full);
1346 return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection()));
1347}
1348
1349EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState* exec)
1350{
1351 VM& vm = exec->vm();
1352 JSLockHolder lock(vm);
1353 vm.heap.collectSync(CollectionScope::Eden);
1354 return JSValue::encode(jsNumber(vm.heap.sizeAfterLastEdenCollection()));
1355}
1356
1357EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*)
1358{
1359 // It's best for this to be the first thing called in the
1360 // JS program so the option is set to true before we JIT.
1361 Options::forceGCSlowPaths() = true;
1362 return JSValue::encode(jsUndefined());
1363}
1364
1365EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState* exec)
1366{
1367 VM& vm = exec->vm();
1368 JSLockHolder lock(vm);
1369 return JSValue::encode(jsNumber(vm.heap.size()));
1370}
1371
1372class JSCMemoryFootprint : public JSDestructibleObject {
1373 using Base = JSDestructibleObject;
1374public:
1375 JSCMemoryFootprint(VM& vm, Structure* structure)
1376 : Base(vm, structure)
1377 { }
1378
1379 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1380 {
1381 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
1382 }
1383
1384 static JSCMemoryFootprint* create(VM& vm, JSGlobalObject* globalObject)
1385 {
1386 Structure* structure = createStructure(vm, globalObject, jsNull());
1387 JSCMemoryFootprint* footprint = new (NotNull, allocateCell<JSCMemoryFootprint>(vm.heap, sizeof(JSCMemoryFootprint))) JSCMemoryFootprint(vm, structure);
1388 footprint->finishCreation(vm);
1389 return footprint;
1390 }
1391
1392 void finishCreation(VM& vm)
1393 {
1394 Base::finishCreation(vm);
1395
1396 auto addProperty = [&] (VM& vm, const char* name, JSValue value) {
1397 JSCMemoryFootprint::addProperty(vm, name, value);
1398 };
1399
1400 MemoryFootprint footprint = MemoryFootprint::now();
1401
1402 addProperty(vm, "current", jsNumber(footprint.current));
1403 addProperty(vm, "peak", jsNumber(footprint.peak));
1404 }
1405
1406 DECLARE_INFO;
1407
1408private:
1409 void addProperty(VM& vm, const char* name, JSValue value)
1410 {
1411 Identifier identifier = Identifier::fromString(&vm, name);
1412 putDirect(vm, identifier, value);
1413 }
1414};
1415
1416const ClassInfo JSCMemoryFootprint::s_info = { "MemoryFootprint", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSCMemoryFootprint) };
1417
1418EncodedJSValue JSC_HOST_CALL functionCreateMemoryFootprint(ExecState* exec)
1419{
1420 VM& vm = exec->vm();
1421 JSLockHolder lock(vm);
1422 return JSValue::encode(JSCMemoryFootprint::create(vm, exec->lexicalGlobalObject()));
1423}
1424
1425EncodedJSValue JSC_HOST_CALL functionResetMemoryPeak(ExecState*)
1426{
1427 MemoryFootprint::resetPeak();
1428 return JSValue::encode(jsUndefined());
1429}
1430
1431// This function is not generally very helpful in 64-bit code as the tag and payload
1432// share a register. But in 32-bit JITed code the tag may not be checked if an
1433// optimization removes type checking requirements, such as in ===.
1434EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState* exec)
1435{
1436 JSValue value = exec->argument(0);
1437 if (!value.isCell())
1438 return JSValue::encode(jsUndefined());
1439 // Need to cast to uint64_t so bitwise_cast will play along.
1440 uint64_t asNumber = reinterpret_cast<uint64_t>(value.asCell());
1441 EncodedJSValue returnValue = JSValue::encode(jsNumber(bitwise_cast<double>(asNumber)));
1442 return returnValue;
1443}
1444
1445EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
1446{
1447 // We need this function for compatibility with the Mozilla JS tests but for now
1448 // we don't actually do any version-specific handling
1449 return JSValue::encode(jsUndefined());
1450}
1451
1452EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
1453{
1454 VM& vm = exec->vm();
1455 auto scope = DECLARE_THROW_SCOPE(vm);
1456
1457 String fileName = exec->argument(0).toWTFString(exec);
1458 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1459 Vector<char> script;
1460 if (!fetchScriptFromLocalFileSystem(fileName, script))
1461 return JSValue::encode(throwException(exec, scope, createError(exec, "Could not open file."_s)));
1462
1463 GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
1464
1465 JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
1466 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1467 for (unsigned i = 1; i < exec->argumentCount(); ++i) {
1468 array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
1469 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1470 }
1471 globalObject->putDirect(
1472 vm, Identifier::fromString(globalObject->globalExec(), "arguments"), array);
1473
1474 NakedPtr<Exception> exception;
1475 StopWatch stopWatch;
1476 stopWatch.start();
1477 evaluate(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), exception);
1478 stopWatch.stop();
1479
1480 if (exception) {
1481 throwException(globalObject->globalExec(), scope, exception);
1482 return JSValue::encode(jsUndefined());
1483 }
1484
1485 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1486}
1487
1488EncodedJSValue JSC_HOST_CALL functionRunString(ExecState* exec)
1489{
1490 VM& vm = exec->vm();
1491 auto scope = DECLARE_THROW_SCOPE(vm);
1492
1493 String source = exec->argument(0).toWTFString(exec);
1494 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1495
1496 GlobalObject* globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
1497
1498 JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
1499 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1500 for (unsigned i = 1; i < exec->argumentCount(); ++i) {
1501 array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
1502 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1503 }
1504 globalObject->putDirect(
1505 vm, Identifier::fromString(globalObject->globalExec(), "arguments"), array);
1506
1507 NakedPtr<Exception> exception;
1508 evaluate(globalObject->globalExec(), jscSource(source, exec->callerSourceOrigin()), JSValue(), exception);
1509
1510 if (exception) {
1511 scope.throwException(globalObject->globalExec(), exception);
1512 return JSValue::encode(jsUndefined());
1513 }
1514
1515 return JSValue::encode(globalObject);
1516}
1517
1518EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
1519{
1520 VM& vm = exec->vm();
1521 auto scope = DECLARE_THROW_SCOPE(vm);
1522
1523 String fileName = exec->argument(0).toWTFString(exec);
1524 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1525 Vector<char> script;
1526 if (!fetchScriptFromLocalFileSystem(fileName, script))
1527 return JSValue::encode(throwException(exec, scope, createError(exec, "Could not open file."_s)));
1528
1529 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1530
1531 NakedPtr<Exception> evaluationException;
1532 JSValue result = evaluate(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), evaluationException);
1533 if (evaluationException)
1534 throwException(exec, scope, evaluationException);
1535 return JSValue::encode(result);
1536}
1537
1538EncodedJSValue JSC_HOST_CALL functionLoadString(ExecState* exec)
1539{
1540 VM& vm = exec->vm();
1541 auto scope = DECLARE_THROW_SCOPE(vm);
1542
1543 String sourceCode = exec->argument(0).toWTFString(exec);
1544 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1545 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1546
1547 NakedPtr<Exception> evaluationException;
1548 JSValue result = evaluate(globalObject->globalExec(), jscSource(sourceCode, exec->callerSourceOrigin()), JSValue(), evaluationException);
1549 if (evaluationException)
1550 throwException(exec, scope, evaluationException);
1551 return JSValue::encode(result);
1552}
1553
1554EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState* exec)
1555{
1556 VM& vm = exec->vm();
1557 auto scope = DECLARE_THROW_SCOPE(vm);
1558
1559 String fileName = exec->argument(0).toWTFString(exec);
1560 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1561
1562 bool isBinary = false;
1563 if (exec->argumentCount() > 1) {
1564 String type = exec->argument(1).toWTFString(exec);
1565 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1566 if (type != "binary")
1567 return throwVMError(exec, scope, "Expected 'binary' as second argument.");
1568 isBinary = true;
1569 }
1570
1571 RefPtr<Uint8Array> content = fillBufferWithContentsOfFile(fileName);
1572 if (!content)
1573 return throwVMError(exec, scope, "Could not open file.");
1574
1575 if (!isBinary)
1576 return JSValue::encode(jsString(exec, String::fromUTF8WithLatin1Fallback(content->data(), content->length())));
1577
1578 Structure* structure = exec->lexicalGlobalObject()->typedArrayStructure(TypeUint8);
1579 JSObject* result = JSUint8Array::create(vm, structure, WTFMove(content));
1580 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1581
1582 return JSValue::encode(result);
1583}
1584
1585EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
1586{
1587 VM& vm = exec->vm();
1588 auto scope = DECLARE_THROW_SCOPE(vm);
1589
1590 String fileName = exec->argument(0).toWTFString(exec);
1591 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1592 Vector<char> script;
1593 if (!fetchScriptFromLocalFileSystem(fileName, script))
1594 return JSValue::encode(throwException(exec, scope, createError(exec, "Could not open file."_s)));
1595
1596 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1597
1598 StopWatch stopWatch;
1599 stopWatch.start();
1600
1601 JSValue syntaxException;
1602 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script, SourceOrigin { absolutePath(fileName) }, fileName), &syntaxException);
1603 stopWatch.stop();
1604
1605 if (!validSyntax)
1606 throwException(exec, scope, syntaxException);
1607 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1608}
1609
1610#if ENABLE(SAMPLING_FLAGS)
1611EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
1612{
1613 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1614 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
1615 if ((flag >= 1) && (flag <= 32))
1616 SamplingFlags::setFlag(flag);
1617 }
1618 return JSValue::encode(jsNull());
1619}
1620
1621EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
1622{
1623 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1624 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
1625 if ((flag >= 1) && (flag <= 32))
1626 SamplingFlags::clearFlag(flag);
1627 }
1628 return JSValue::encode(jsNull());
1629}
1630#endif
1631
1632EncodedJSValue JSC_HOST_CALL functionGetRandomSeed(ExecState* exec)
1633{
1634 return JSValue::encode(jsNumber(exec->lexicalGlobalObject()->weakRandom().seed()));
1635}
1636
1637EncodedJSValue JSC_HOST_CALL functionSetRandomSeed(ExecState* exec)
1638{
1639 VM& vm = exec->vm();
1640 auto scope = DECLARE_THROW_SCOPE(vm);
1641
1642 unsigned seed = exec->argument(0).toUInt32(exec);
1643 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1644 exec->lexicalGlobalObject()->weakRandom().setSeed(seed);
1645 return JSValue::encode(jsUndefined());
1646}
1647
1648EncodedJSValue JSC_HOST_CALL functionIsRope(ExecState* exec)
1649{
1650 JSValue argument = exec->argument(0);
1651 if (!argument.isString())
1652 return JSValue::encode(jsBoolean(false));
1653 const StringImpl* impl = asString(argument)->tryGetValueImpl();
1654 return JSValue::encode(jsBoolean(!impl));
1655}
1656
1657EncodedJSValue JSC_HOST_CALL functionCallerSourceOrigin(ExecState* state)
1658{
1659 SourceOrigin sourceOrigin = state->callerSourceOrigin();
1660 if (sourceOrigin.isNull())
1661 return JSValue::encode(jsNull());
1662 return JSValue::encode(jsString(state, sourceOrigin.string()));
1663}
1664
1665EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
1666{
1667 Vector<char, 256> line;
1668 int c;
1669 while ((c = getchar()) != EOF) {
1670 // FIXME: Should we also break on \r?
1671 if (c == '\n')
1672 break;
1673 line.append(c);
1674 }
1675 line.append('\0');
1676 return JSValue::encode(jsString(exec, line.data()));
1677}
1678
1679EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
1680{
1681 return JSValue::encode(jsNumber(WallTime::now().secondsSinceEpoch().value()));
1682}
1683
1684EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState* exec)
1685{
1686 return JSValue::encode(setNeverInline(exec));
1687}
1688
1689EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState* exec)
1690{
1691 return JSValue::encode(setNeverOptimize(exec));
1692}
1693
1694EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState* exec)
1695{
1696 if (exec->argumentCount()) {
1697 FunctionExecutable* executable = getExecutableForFunction(exec->argument(0));
1698 if (executable)
1699 executable->setNeverFTLOptimize(true);
1700 }
1701 return JSValue::encode(jsUndefined());
1702}
1703
1704EncodedJSValue JSC_HOST_CALL functionNoOSRExitFuzzing(ExecState* exec)
1705{
1706 return JSValue::encode(setCannotUseOSRExitFuzzing(exec));
1707}
1708
1709EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState* exec)
1710{
1711 return JSValue::encode(optimizeNextInvocation(exec));
1712}
1713
1714EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState* exec)
1715{
1716 return JSValue::encode(numberOfDFGCompiles(exec));
1717}
1718
1719Message::Message(ArrayBufferContents&& contents, int32_t index)
1720 : m_contents(WTFMove(contents))
1721 , m_index(index)
1722{
1723}
1724
1725Message::~Message()
1726{
1727}
1728
1729Worker::Worker(Workers& workers)
1730 : m_workers(workers)
1731{
1732 auto locker = holdLock(m_workers.m_lock);
1733 m_workers.m_workers.append(this);
1734
1735 *currentWorker() = this;
1736}
1737
1738Worker::~Worker()
1739{
1740 auto locker = holdLock(m_workers.m_lock);
1741 RELEASE_ASSERT(isOnList());
1742 remove();
1743}
1744
1745void Worker::enqueue(const AbstractLocker&, RefPtr<Message> message)
1746{
1747 m_messages.append(message);
1748}
1749
1750RefPtr<Message> Worker::dequeue()
1751{
1752 auto locker = holdLock(m_workers.m_lock);
1753 while (m_messages.isEmpty())
1754 m_workers.m_condition.wait(m_workers.m_lock);
1755 return m_messages.takeFirst();
1756}
1757
1758Worker& Worker::current()
1759{
1760 return **currentWorker();
1761}
1762
1763ThreadSpecific<Worker*>& Worker::currentWorker()
1764{
1765 static ThreadSpecific<Worker*>* result;
1766 static std::once_flag flag;
1767 std::call_once(
1768 flag,
1769 [] () {
1770 result = new ThreadSpecific<Worker*>();
1771 });
1772 return *result;
1773}
1774
1775Workers::Workers()
1776{
1777}
1778
1779Workers::~Workers()
1780{
1781 UNREACHABLE_FOR_PLATFORM();
1782}
1783
1784template<typename Func>
1785void Workers::broadcast(const Func& func)
1786{
1787 auto locker = holdLock(m_lock);
1788 for (Worker* worker = m_workers.begin(); worker != m_workers.end(); worker = worker->next()) {
1789 if (worker != &Worker::current())
1790 func(locker, *worker);
1791 }
1792 m_condition.notifyAll();
1793}
1794
1795void Workers::report(const String& string)
1796{
1797 auto locker = holdLock(m_lock);
1798 m_reports.append(string.isolatedCopy());
1799 m_condition.notifyAll();
1800}
1801
1802String Workers::tryGetReport()
1803{
1804 auto locker = holdLock(m_lock);
1805 if (m_reports.isEmpty())
1806 return String();
1807 return m_reports.takeFirst();
1808}
1809
1810String Workers::getReport()
1811{
1812 auto locker = holdLock(m_lock);
1813 while (m_reports.isEmpty())
1814 m_condition.wait(m_lock);
1815 return m_reports.takeFirst();
1816}
1817
1818Workers& Workers::singleton()
1819{
1820 static Workers* result;
1821 static std::once_flag flag;
1822 std::call_once(
1823 flag,
1824 [] {
1825 result = new Workers();
1826 });
1827 return *result;
1828}
1829
1830EncodedJSValue JSC_HOST_CALL functionDollarCreateRealm(ExecState* exec)
1831{
1832 VM& vm = exec->vm();
1833 GlobalObject* result = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>());
1834 return JSValue::encode(result->getDirect(vm, Identifier::fromString(exec, "$")));
1835}
1836
1837EncodedJSValue JSC_HOST_CALL functionDollarDetachArrayBuffer(ExecState* exec)
1838{
1839 return functionTransferArrayBuffer(exec);
1840}
1841
1842EncodedJSValue JSC_HOST_CALL functionDollarEvalScript(ExecState* exec)
1843{
1844 VM& vm = exec->vm();
1845 auto scope = DECLARE_THROW_SCOPE(vm);
1846
1847 String sourceCode = exec->argument(0).toWTFString(exec);
1848 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1849
1850 GlobalObject* globalObject = jsDynamicCast<GlobalObject*>(vm,
1851 exec->thisValue().get(exec, Identifier::fromString(exec, "global")));
1852 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1853 if (!globalObject)
1854 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected global to point to a global object"_s)));
1855
1856 NakedPtr<Exception> evaluationException;
1857 JSValue result = evaluate(globalObject->globalExec(), jscSource(sourceCode, exec->callerSourceOrigin()), JSValue(), evaluationException);
1858 if (evaluationException)
1859 throwException(exec, scope, evaluationException);
1860 return JSValue::encode(result);
1861}
1862
1863EncodedJSValue JSC_HOST_CALL functionDollarAgentStart(ExecState* exec)
1864{
1865 VM& vm = exec->vm();
1866 auto scope = DECLARE_THROW_SCOPE(vm);
1867
1868 String sourceCode = exec->argument(0).toWTFString(exec).isolatedCopy();
1869 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1870
1871 Lock didStartLock;
1872 Condition didStartCondition;
1873 bool didStart = false;
1874
1875 Thread::create(
1876 "JSC Agent",
1877 [sourceCode, &didStartLock, &didStartCondition, &didStart] () {
1878 CommandLine commandLine(0, nullptr);
1879 commandLine.m_interactive = false;
1880 runJSC(
1881 commandLine, true,
1882 [&] (VM&, GlobalObject* globalObject, bool& success) {
1883 // Notify the thread that started us that we have registered a worker.
1884 {
1885 auto locker = holdLock(didStartLock);
1886 didStart = true;
1887 didStartCondition.notifyOne();
1888 }
1889
1890 NakedPtr<Exception> evaluationException;
1891 JSValue result;
1892 result = evaluate(globalObject->globalExec(), jscSource(sourceCode, SourceOrigin("worker"_s)), JSValue(), evaluationException);
1893 if (evaluationException)
1894 result = evaluationException->value();
1895 checkException(globalObject->globalExec(), globalObject, true, evaluationException, result, commandLine, success);
1896 if (!success)
1897 exit(1);
1898 });
1899 })->detach();
1900
1901 {
1902 auto locker = holdLock(didStartLock);
1903 while (!didStart)
1904 didStartCondition.wait(didStartLock);
1905 }
1906
1907 return JSValue::encode(jsUndefined());
1908}
1909
1910EncodedJSValue JSC_HOST_CALL functionDollarAgentReceiveBroadcast(ExecState* exec)
1911{
1912 VM& vm = exec->vm();
1913 auto scope = DECLARE_THROW_SCOPE(vm);
1914
1915 JSValue callback = exec->argument(0);
1916 CallData callData;
1917 CallType callType = getCallData(vm, callback, callData);
1918 if (callType == CallType::None)
1919 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected callback"_s)));
1920
1921 RefPtr<Message> message;
1922 {
1923 ReleaseHeapAccessScope releaseAccess(vm.heap);
1924 message = Worker::current().dequeue();
1925 }
1926
1927 auto nativeBuffer = ArrayBuffer::create(message->releaseContents());
1928 ArrayBufferSharingMode sharingMode = nativeBuffer->sharingMode();
1929 JSArrayBuffer* jsBuffer = JSArrayBuffer::create(vm, exec->lexicalGlobalObject()->arrayBufferStructure(sharingMode), WTFMove(nativeBuffer));
1930
1931 MarkedArgumentBuffer args;
1932 args.append(jsBuffer);
1933 args.append(jsNumber(message->index()));
1934 if (UNLIKELY(args.hasOverflowed()))
1935 return JSValue::encode(throwOutOfMemoryError(exec, scope));
1936 RELEASE_AND_RETURN(scope, JSValue::encode(call(exec, callback, callType, callData, jsNull(), args)));
1937}
1938
1939EncodedJSValue JSC_HOST_CALL functionDollarAgentReport(ExecState* exec)
1940{
1941 VM& vm = exec->vm();
1942 auto scope = DECLARE_THROW_SCOPE(vm);
1943
1944 String report = exec->argument(0).toWTFString(exec);
1945 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1946
1947 Workers::singleton().report(report);
1948
1949 return JSValue::encode(jsUndefined());
1950}
1951
1952EncodedJSValue JSC_HOST_CALL functionDollarAgentSleep(ExecState* exec)
1953{
1954 VM& vm = exec->vm();
1955 auto scope = DECLARE_THROW_SCOPE(vm);
1956
1957 if (exec->argumentCount() >= 1) {
1958 Seconds seconds = Seconds::fromMilliseconds(exec->argument(0).toNumber(exec));
1959 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1960 sleep(seconds);
1961 }
1962 return JSValue::encode(jsUndefined());
1963}
1964
1965EncodedJSValue JSC_HOST_CALL functionDollarAgentBroadcast(ExecState* exec)
1966{
1967 VM& vm = exec->vm();
1968 auto scope = DECLARE_THROW_SCOPE(vm);
1969
1970 JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(vm, exec->argument(0));
1971 if (!jsBuffer || !jsBuffer->isShared())
1972 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected SharedArrayBuffer"_s)));
1973
1974 int32_t index = exec->argument(1).toInt32(exec);
1975 RETURN_IF_EXCEPTION(scope, encodedJSValue());
1976
1977 Workers::singleton().broadcast(
1978 [&] (const AbstractLocker& locker, Worker& worker) {
1979 ArrayBuffer* nativeBuffer = jsBuffer->impl();
1980 ArrayBufferContents contents;
1981 nativeBuffer->transferTo(vm, contents); // "transferTo" means "share" if the buffer is shared.
1982 RefPtr<Message> message = adoptRef(new Message(WTFMove(contents), index));
1983 worker.enqueue(locker, message);
1984 });
1985
1986 return JSValue::encode(jsUndefined());
1987}
1988
1989EncodedJSValue JSC_HOST_CALL functionDollarAgentGetReport(ExecState* exec)
1990{
1991 VM& vm = exec->vm();
1992
1993 String string = Workers::singleton().tryGetReport();
1994 if (!string)
1995 return JSValue::encode(jsNull());
1996
1997 return JSValue::encode(jsString(&vm, string));
1998}
1999
2000EncodedJSValue JSC_HOST_CALL functionDollarAgentLeaving(ExecState*)
2001{
2002 return JSValue::encode(jsUndefined());
2003}
2004
2005EncodedJSValue JSC_HOST_CALL functionDollarAgentMonotonicNow(ExecState*)
2006{
2007 return JSValue::encode(jsNumber(MonotonicTime::now().secondsSinceEpoch().milliseconds()));
2008}
2009
2010EncodedJSValue JSC_HOST_CALL functionWaitForReport(ExecState* exec)
2011{
2012 VM& vm = exec->vm();
2013
2014 String string;
2015 {
2016 ReleaseHeapAccessScope releaseAccess(vm.heap);
2017 string = Workers::singleton().getReport();
2018 }
2019 if (!string)
2020 return JSValue::encode(jsNull());
2021
2022 return JSValue::encode(jsString(&vm, string));
2023}
2024
2025EncodedJSValue JSC_HOST_CALL functionHeapCapacity(ExecState* exec)
2026{
2027 VM& vm = exec->vm();
2028 return JSValue::encode(jsNumber(vm.heap.capacity()));
2029}
2030
2031EncodedJSValue JSC_HOST_CALL functionFlashHeapAccess(ExecState* exec)
2032{
2033 VM& vm = exec->vm();
2034 auto scope = DECLARE_THROW_SCOPE(vm);
2035
2036 double sleepTimeMs = 0;
2037 if (exec->argumentCount() >= 1) {
2038 sleepTimeMs = exec->argument(0).toNumber(exec);
2039 RETURN_IF_EXCEPTION(scope, encodedJSValue());
2040 }
2041
2042 vm.heap.releaseAccess();
2043 if (sleepTimeMs)
2044 sleep(Seconds::fromMilliseconds(sleepTimeMs));
2045 vm.heap.acquireAccess();
2046 return JSValue::encode(jsUndefined());
2047}
2048
2049EncodedJSValue JSC_HOST_CALL functionDisableRichSourceInfo(ExecState*)
2050{
2051 supportsRichSourceInfo = false;
2052 return JSValue::encode(jsUndefined());
2053}
2054
2055EncodedJSValue JSC_HOST_CALL functionMallocInALoop(ExecState*)
2056{
2057 Vector<void*> ptrs;
2058 for (unsigned i = 0; i < 5000; ++i)
2059 ptrs.append(fastMalloc(1024 * 2));
2060 for (void* ptr : ptrs)
2061 fastFree(ptr);
2062 return JSValue::encode(jsUndefined());
2063}
2064
2065EncodedJSValue JSC_HOST_CALL functionTotalCompileTime(ExecState*)
2066{
2067#if ENABLE(JIT)
2068 return JSValue::encode(jsNumber(JIT::totalCompileTime().milliseconds()));
2069#else
2070 return JSValue::encode(jsNumber(0));
2071#endif
2072}
2073
2074template<typename ValueType>
2075typename std::enable_if<!std::is_fundamental<ValueType>::value>::type addOption(VM&, JSObject*, const Identifier&, ValueType) { }
2076
2077template<typename ValueType>
2078typename std::enable_if<std::is_fundamental<ValueType>::value>::type addOption(VM& vm, JSObject* optionsObject, const Identifier& identifier, ValueType value)
2079{
2080 optionsObject->putDirect(vm, identifier, JSValue(value));
2081}
2082
2083EncodedJSValue JSC_HOST_CALL functionJSCOptions(ExecState* exec)
2084{
2085 VM& vm = exec->vm();
2086 JSObject* optionsObject = constructEmptyObject(exec);
2087#define FOR_EACH_OPTION(type_, name_, defaultValue_, availability_, description_) \
2088 addOption(vm, optionsObject, Identifier::fromString(exec, #name_), Options::name_());
2089 JSC_OPTIONS(FOR_EACH_OPTION)
2090#undef FOR_EACH_OPTION
2091 return JSValue::encode(optionsObject);
2092}
2093
2094EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState* exec)
2095{
2096 if (exec->argumentCount() < 1)
2097 return JSValue::encode(jsUndefined());
2098
2099 CodeBlock* block = getSomeBaselineCodeBlockForFunction(exec->argument(0));
2100 if (!block)
2101 return JSValue::encode(jsNumber(0));
2102
2103 return JSValue::encode(jsNumber(block->reoptimizationRetryCounter()));
2104}
2105
2106EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState* exec)
2107{
2108 VM& vm = exec->vm();
2109 auto scope = DECLARE_THROW_SCOPE(vm);
2110
2111 if (exec->argumentCount() < 1)
2112 return JSValue::encode(throwException(exec, scope, createError(exec, "Not enough arguments"_s)));
2113
2114 JSArrayBuffer* buffer = jsDynamicCast<JSArrayBuffer*>(vm, exec->argument(0));
2115 if (!buffer)
2116 return JSValue::encode(throwException(exec, scope, createError(exec, "Expected an array buffer"_s)));
2117
2118 ArrayBufferContents dummyContents;
2119 buffer->impl()->transferTo(vm, dummyContents);
2120
2121 return JSValue::encode(jsUndefined());
2122}
2123
2124EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState* exec)
2125{
2126 VM& vm = exec->vm();
2127 vm.setFailNextNewCodeBlock();
2128 return JSValue::encode(jsUndefined());
2129}
2130
2131EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
2132{
2133 VM& vm = exec->vm();
2134 vm.codeCache()->write(vm);
2135
2136 jscExit(EXIT_SUCCESS);
2137
2138#if COMPILER(MSVC)
2139 // Without this, Visual Studio will complain that this method does not return a value.
2140 return JSValue::encode(jsUndefined());
2141#endif
2142}
2143
2144EncodedJSValue JSC_HOST_CALL functionFalse(ExecState*) { return JSValue::encode(jsBoolean(false)); }
2145
2146EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*) { return JSValue::encode(jsUndefined()); }
2147EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*) { return JSValue::encode(jsUndefined()); }
2148EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState* exec)
2149{
2150 for (size_t i = 0; i < exec->argumentCount(); ++i) {
2151 if (!exec->argument(i).isInt32())
2152 return JSValue::encode(jsBoolean(false));
2153 }
2154 return JSValue::encode(jsBoolean(true));
2155}
2156
2157EncodedJSValue JSC_HOST_CALL functionIsPureNaN(ExecState* exec)
2158{
2159 for (size_t i = 0; i < exec->argumentCount(); ++i) {
2160 JSValue value = exec->argument(i);
2161 if (!value.isNumber())
2162 return JSValue::encode(jsBoolean(false));
2163 double number = value.asNumber();
2164 if (!std::isnan(number))
2165 return JSValue::encode(jsBoolean(false));
2166 if (isImpureNaN(number))
2167 return JSValue::encode(jsBoolean(false));
2168 }
2169 return JSValue::encode(jsBoolean(true));
2170}
2171
2172EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState* exec) { return JSValue::encode(exec->argument(0)); }
2173
2174EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*)
2175{
2176 return JSValue::encode(jsNumber(42));
2177}
2178
2179EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState* exec)
2180{
2181 VM& vm = exec->vm();
2182 return JSValue::encode(Masquerader::create(vm, exec->lexicalGlobalObject()));
2183}
2184
2185EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState* exec)
2186{
2187 JSValue value = exec->argument(0);
2188 if (value.isObject())
2189 return JSValue::encode(jsBoolean(asObject(value)->hasCustomProperties(exec->vm())));
2190 return JSValue::encode(jsBoolean(false));
2191}
2192
2193EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState* exec)
2194{
2195 VM& vm = exec->vm();
2196 vm.dumpTypeProfilerData();
2197 return JSValue::encode(jsUndefined());
2198}
2199
2200EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState* exec)
2201{
2202 VM& vm = exec->vm();
2203 vm.drainMicrotasks();
2204 return JSValue::encode(jsUndefined());
2205}
2206
2207EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*)
2208{
2209#if USE(JSVALUE64)
2210 return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
2211#else
2212 return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
2213#endif
2214}
2215
2216EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState* exec)
2217{
2218 VM& vm = exec->vm();
2219 return JSValue::encode(GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>()));
2220}
2221
2222EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState* exec)
2223{
2224 VM& vm = exec->vm();
2225 auto scope = DECLARE_THROW_SCOPE(vm);
2226
2227 String source = exec->argument(0).toWTFString(exec);
2228 RETURN_IF_EXCEPTION(scope, encodedJSValue());
2229
2230 StopWatch stopWatch;
2231 stopWatch.start();
2232
2233 ParserError error;
2234 bool validSyntax = checkModuleSyntax(exec, jscSource(source, { }, URL(), TextPosition(), SourceProviderSourceType::Module), error);
2235 RETURN_IF_EXCEPTION(scope, encodedJSValue());
2236 stopWatch.stop();
2237
2238 if (!validSyntax)
2239 throwException(exec, scope, jsNontrivialString(exec, toString("SyntaxError: ", error.message(), ":", error.line())));
2240 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
2241}
2242
2243EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*)
2244{
2245#if ENABLE(SAMPLING_PROFILER)
2246 return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
2247#else
2248 return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
2249#endif
2250}
2251
2252EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState* exec)
2253{
2254 VM& vm = exec->vm();
2255 JSLockHolder lock(vm);
2256 auto scope = DECLARE_THROW_SCOPE(vm);
2257
2258 HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler());
2259 snapshotBuilder.buildSnapshot();
2260
2261 String jsonString = snapshotBuilder.json();
2262 EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
2263 scope.releaseAssertNoException();
2264 return result;
2265}
2266
2267EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshotForGCDebugging(ExecState* exec)
2268{
2269 VM& vm = exec->vm();
2270 JSLockHolder lock(vm);
2271 auto scope = DECLARE_THROW_SCOPE(vm);
2272 String jsonString;
2273 {
2274 DeferGCForAWhile deferGC(vm.heap); // Prevent concurrent GC from interfering with the full GC that the snapshot does.
2275
2276 HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler(), HeapSnapshotBuilder::SnapshotType::GCDebuggingSnapshot);
2277 snapshotBuilder.buildSnapshot();
2278
2279 jsonString = snapshotBuilder.json();
2280 }
2281 scope.releaseAssertNoException();
2282 return JSValue::encode(jsString(&vm, jsonString));
2283}
2284
2285EncodedJSValue JSC_HOST_CALL functionResetSuperSamplerState(ExecState*)
2286{
2287 resetSuperSamplerState();
2288 return JSValue::encode(jsUndefined());
2289}
2290
2291EncodedJSValue JSC_HOST_CALL functionEnsureArrayStorage(ExecState* exec)
2292{
2293 VM& vm = exec->vm();
2294 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
2295 if (JSObject* object = jsDynamicCast<JSObject*>(vm, exec->argument(i)))
2296 object->ensureArrayStorage(vm);
2297 }
2298 return JSValue::encode(jsUndefined());
2299}
2300
2301#if ENABLE(SAMPLING_PROFILER)
2302EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState* exec)
2303{
2304 VM& vm = exec->vm();
2305 SamplingProfiler& samplingProfiler = vm.ensureSamplingProfiler(WTF::Stopwatch::create());
2306 samplingProfiler.noticeCurrentThreadAsJSCExecutionThread();
2307 samplingProfiler.start();
2308 return JSValue::encode(jsUndefined());
2309}
2310
2311EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState* exec)
2312{
2313 VM& vm = exec->vm();
2314 auto scope = DECLARE_THROW_SCOPE(vm);
2315
2316 if (!vm.samplingProfiler())
2317 return JSValue::encode(throwException(exec, scope, createError(exec, "Sampling profiler was never started"_s)));
2318
2319 String jsonString = vm.samplingProfiler()->stackTracesAsJSON();
2320 EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
2321 scope.releaseAssertNoException();
2322 return result;
2323}
2324#endif // ENABLE(SAMPLING_PROFILER)
2325
2326EncodedJSValue JSC_HOST_CALL functionMaxArguments(ExecState*)
2327{
2328 return JSValue::encode(jsNumber(JSC::maxArguments));
2329}
2330
2331EncodedJSValue JSC_HOST_CALL functionAsyncTestStart(ExecState* exec)
2332{
2333 VM& vm = exec->vm();
2334 auto scope = DECLARE_THROW_SCOPE(vm);
2335
2336 JSValue numberOfAsyncPasses = exec->argument(0);
2337 if (!numberOfAsyncPasses.isUInt32())
2338 return throwVMError(exec, scope, "Expected first argument to a uint32"_s);
2339
2340 asyncTestExpectedPasses += numberOfAsyncPasses.asUInt32();
2341 return encodedJSUndefined();
2342}
2343
2344EncodedJSValue JSC_HOST_CALL functionAsyncTestPassed(ExecState*)
2345{
2346 asyncTestPasses++;
2347 return encodedJSUndefined();
2348}
2349
2350#if ENABLE(WEBASSEMBLY)
2351
2352static EncodedJSValue JSC_HOST_CALL functionWebAssemblyMemoryMode(ExecState* exec)
2353{
2354 VM& vm = exec->vm();
2355 auto scope = DECLARE_THROW_SCOPE(vm);
2356
2357 if (!Wasm::isSupported())
2358 return throwVMTypeError(exec, scope, "WebAssemblyMemoryMode should only be called if the useWebAssembly option is set"_s);
2359
2360 if (JSObject* object = exec->argument(0).getObject()) {
2361 if (auto* memory = jsDynamicCast<JSWebAssemblyMemory*>(vm, object))
2362 return JSValue::encode(jsString(&vm, makeString(memory->memory().mode())));
2363 if (auto* instance = jsDynamicCast<JSWebAssemblyInstance*>(vm, object))
2364 return JSValue::encode(jsString(&vm, makeString(instance->memoryMode())));
2365 }
2366
2367 return throwVMTypeError(exec, scope, "WebAssemblyMemoryMode expects either a WebAssembly.Memory or WebAssembly.Instance"_s);
2368}
2369
2370#endif // ENABLE(WEBASSEMBLY)
2371
2372// Use SEH for Release builds only to get rid of the crash report dialog
2373// (luckily the same tests fail in Release and Debug builds so far). Need to
2374// be in a separate main function because the jscmain function requires object
2375// unwinding.
2376
2377#if COMPILER(MSVC) && !defined(_DEBUG)
2378#define TRY __try {
2379#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
2380#else
2381#define TRY
2382#define EXCEPT(x)
2383#endif
2384
2385int jscmain(int argc, char** argv);
2386
2387static double s_desiredTimeout;
2388static double s_timeoutMultiplier = 1.0;
2389
2390static void startTimeoutThreadIfNeeded()
2391{
2392 if (char* timeoutString = getenv("JSCTEST_timeout")) {
2393 if (sscanf(timeoutString, "%lf", &s_desiredTimeout) != 1) {
2394 dataLog("WARNING: timeout string is malformed, got ", timeoutString,
2395 " but expected a number. Not using a timeout.\n");
2396 } else {
2397 Thread::create("jsc Timeout Thread", [] () {
2398 Seconds timeoutDuration(s_desiredTimeout * s_timeoutMultiplier);
2399 sleep(timeoutDuration);
2400 dataLog("Timed out after ", timeoutDuration, " seconds!\n");
2401 CRASH();
2402 });
2403 }
2404 }
2405}
2406
2407int main(int argc, char** argv)
2408{
2409#if PLATFORM(IOS_FAMILY) && CPU(ARM_THUMB2)
2410 // Enabled IEEE754 denormal support.
2411 fenv_t env;
2412 fegetenv( &env );
2413 env.__fpscr &= ~0x01000000u;
2414 fesetenv( &env );
2415#endif
2416
2417#if OS(WINDOWS)
2418 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
2419 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
2420 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
2421 ::SetErrorMode(0);
2422
2423 _setmode(_fileno(stdout), _O_BINARY);
2424 _setmode(_fileno(stderr), _O_BINARY);
2425
2426#if defined(_DEBUG)
2427 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
2428 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2429 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
2430 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
2431 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
2432 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
2433#endif
2434
2435 timeBeginPeriod(1);
2436#endif
2437
2438#if PLATFORM(GTK)
2439 if (!setlocale(LC_ALL, ""))
2440 WTFLogAlways("Locale not supported by C library.\n\tUsing the fallback 'C' locale.");
2441#endif
2442
2443 // Need to initialize WTF threading before we start any threads. Cannot initialize JSC
2444 // threading yet, since that would do somethings that we'd like to defer until after we
2445 // have a chance to parse options.
2446 WTF::initializeThreading();
2447
2448#if PLATFORM(IOS_FAMILY)
2449 Options::crashIfCantAllocateJITMemory() = true;
2450#endif
2451
2452 // We can't use destructors in the following code because it uses Windows
2453 // Structured Exception Handling
2454 int res = 0;
2455 TRY
2456 res = jscmain(argc, argv);
2457 EXCEPT(res = 3)
2458 finalizeStatsAtEndOfTesting();
2459
2460 jscExit(res);
2461}
2462
2463static void dumpException(GlobalObject* globalObject, JSValue exception)
2464{
2465 VM& vm = globalObject->vm();
2466 auto scope = DECLARE_CATCH_SCOPE(vm);
2467
2468#define CHECK_EXCEPTION() do { \
2469 if (scope.exception()) { \
2470 scope.clearException(); \
2471 return; \
2472 } \
2473 } while (false)
2474
2475 auto exceptionString = exception.toWTFString(globalObject->globalExec());
2476 Expected<CString, UTF8ConversionError> expectedCString = exceptionString.tryGetUtf8();
2477 if (expectedCString)
2478 printf("Exception: %s\n", expectedCString.value().data());
2479 else
2480 printf("Exception: <out of memory while extracting exception string>\n");
2481
2482 Identifier nameID = Identifier::fromString(globalObject->globalExec(), "name");
2483 CHECK_EXCEPTION();
2484 Identifier fileNameID = Identifier::fromString(globalObject->globalExec(), "sourceURL");
2485 CHECK_EXCEPTION();
2486 Identifier lineNumberID = Identifier::fromString(globalObject->globalExec(), "line");
2487 CHECK_EXCEPTION();
2488 Identifier stackID = Identifier::fromString(globalObject->globalExec(), "stack");
2489 CHECK_EXCEPTION();
2490
2491 JSValue nameValue = exception.get(globalObject->globalExec(), nameID);
2492 CHECK_EXCEPTION();
2493 JSValue fileNameValue = exception.get(globalObject->globalExec(), fileNameID);
2494 CHECK_EXCEPTION();
2495 JSValue lineNumberValue = exception.get(globalObject->globalExec(), lineNumberID);
2496 CHECK_EXCEPTION();
2497 JSValue stackValue = exception.get(globalObject->globalExec(), stackID);
2498 CHECK_EXCEPTION();
2499
2500 if (nameValue.toWTFString(globalObject->globalExec()) == "SyntaxError"
2501 && (!fileNameValue.isUndefinedOrNull() || !lineNumberValue.isUndefinedOrNull())) {
2502 printf(
2503 "at %s:%s\n",
2504 fileNameValue.toWTFString(globalObject->globalExec()).utf8().data(),
2505 lineNumberValue.toWTFString(globalObject->globalExec()).utf8().data());
2506 }
2507
2508 if (!stackValue.isUndefinedOrNull()) {
2509 auto stackString = stackValue.toWTFString(globalObject->globalExec());
2510 if (stackString.length())
2511 printf("%s\n", stackString.utf8().data());
2512 }
2513
2514#undef CHECK_EXCEPTION
2515}
2516
2517static bool checkUncaughtException(VM& vm, GlobalObject* globalObject, JSValue exception, CommandLine& options)
2518{
2519 const String& expectedExceptionName = options.m_uncaughtExceptionName;
2520 auto scope = DECLARE_CATCH_SCOPE(vm);
2521 scope.clearException();
2522 if (!exception) {
2523 printf("Expected uncaught exception with name '%s' but none was thrown\n", expectedExceptionName.utf8().data());
2524 return false;
2525 }
2526
2527 ExecState* exec = globalObject->globalExec();
2528 JSValue exceptionClass = globalObject->get(exec, Identifier::fromString(exec, expectedExceptionName));
2529 if (!exceptionClass.isObject() || scope.exception()) {
2530 printf("Expected uncaught exception with name '%s' but given exception class is not defined\n", expectedExceptionName.utf8().data());
2531 return false;
2532 }
2533
2534 bool isInstanceOfExpectedException = jsCast<JSObject*>(exceptionClass)->hasInstance(exec, exception);
2535 if (scope.exception()) {
2536 printf("Expected uncaught exception with name '%s' but given exception class fails performing hasInstance\n", expectedExceptionName.utf8().data());
2537 return false;
2538 }
2539 if (isInstanceOfExpectedException) {
2540 if (options.m_alwaysDumpUncaughtException)
2541 dumpException(globalObject, exception);
2542 return true;
2543 }
2544
2545 printf("Expected uncaught exception with name '%s' but exception value is not instance of this exception class\n", expectedExceptionName.utf8().data());
2546 dumpException(globalObject, exception);
2547 return false;
2548}
2549
2550static void checkException(ExecState* exec, GlobalObject* globalObject, bool isLastFile, bool hasException, JSValue value, CommandLine& options, bool& success)
2551{
2552 VM& vm = globalObject->vm();
2553
2554 if (options.m_treatWatchdogExceptionAsSuccess && value.inherits<TerminatedExecutionError>(vm)) {
2555 ASSERT(hasException);
2556 return;
2557 }
2558
2559 if (!options.m_uncaughtExceptionName || !isLastFile) {
2560 success = success && !hasException;
2561 if (options.m_dump && !hasException)
2562 printf("End: %s\n", value.toWTFString(exec).utf8().data());
2563 if (hasException)
2564 dumpException(globalObject, value);
2565 } else
2566 success = success && checkUncaughtException(vm, globalObject, (hasException) ? value : JSValue(), options);
2567}
2568
2569static void runWithOptions(GlobalObject* globalObject, CommandLine& options, bool& success)
2570{
2571 Vector<Script>& scripts = options.m_scripts;
2572 String fileName;
2573 Vector<char> scriptBuffer;
2574
2575 if (options.m_dump)
2576 JSC::Options::dumpGeneratedBytecodes() = true;
2577
2578 VM& vm = globalObject->vm();
2579 auto scope = DECLARE_CATCH_SCOPE(vm);
2580
2581#if ENABLE(SAMPLING_FLAGS)
2582 SamplingFlags::start();
2583#endif
2584
2585 for (size_t i = 0; i < scripts.size(); i++) {
2586 JSInternalPromise* promise = nullptr;
2587 bool isModule = options.m_module || scripts[i].scriptType == Script::ScriptType::Module;
2588 if (scripts[i].codeSource == Script::CodeSource::File) {
2589 fileName = scripts[i].argument;
2590 if (scripts[i].strictMode == Script::StrictMode::Strict)
2591 scriptBuffer.append("\"use strict\";\n", strlen("\"use strict\";\n"));
2592
2593 if (isModule) {
2594 promise = loadAndEvaluateModule(globalObject->globalExec(), fileName, jsUndefined(), jsUndefined());
2595 scope.releaseAssertNoException();
2596 } else {
2597 if (!fetchScriptFromLocalFileSystem(fileName, scriptBuffer)) {
2598 success = false; // fail early so we can catch missing files
2599 return;
2600 }
2601 }
2602 } else {
2603 size_t commandLineLength = strlen(scripts[i].argument);
2604 scriptBuffer.resize(commandLineLength);
2605 std::copy(scripts[i].argument, scripts[i].argument + commandLineLength, scriptBuffer.begin());
2606 fileName = "[Command Line]"_s;
2607 }
2608
2609 bool isLastFile = i == scripts.size() - 1;
2610 if (isModule) {
2611 if (!promise) {
2612 // FIXME: This should use an absolute file URL https://bugs.webkit.org/show_bug.cgi?id=193077
2613 promise = loadAndEvaluateModule(globalObject->globalExec(), jscSource(stringFromUTF(scriptBuffer), SourceOrigin { absolutePath(fileName) }, URL({ }, fileName), TextPosition(), SourceProviderSourceType::Module), jsUndefined());
2614 }
2615 scope.clearException();
2616
2617 JSFunction* fulfillHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&success, &options, isLastFile](ExecState* exec) {
2618 checkException(exec, jsCast<GlobalObject*>(exec->lexicalGlobalObject()), isLastFile, false, exec->argument(0), options, success);
2619 return JSValue::encode(jsUndefined());
2620 });
2621
2622 JSFunction* rejectHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&success, &options, isLastFile](ExecState* exec) {
2623 checkException(exec, jsCast<GlobalObject*>(exec->lexicalGlobalObject()), isLastFile, true, exec->argument(0), options, success);
2624 return JSValue::encode(jsUndefined());
2625 });
2626
2627 promise->then(globalObject->globalExec(), fulfillHandler, rejectHandler);
2628 scope.releaseAssertNoException();
2629 vm.drainMicrotasks();
2630 } else {
2631 NakedPtr<Exception> evaluationException;
2632 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(scriptBuffer, SourceOrigin { absolutePath(fileName) }, fileName), JSValue(), evaluationException);
2633 scope.assertNoException();
2634 if (evaluationException)
2635 returnValue = evaluationException->value();
2636 checkException(globalObject->globalExec(), globalObject, isLastFile, evaluationException, returnValue, options, success);
2637 }
2638
2639 scriptBuffer.clear();
2640 scope.clearException();
2641 }
2642
2643#if ENABLE(REGEXP_TRACING)
2644 vm.dumpRegExpTrace();
2645#endif
2646}
2647
2648#define RUNNING_FROM_XCODE 0
2649
2650static void runInteractive(GlobalObject* globalObject)
2651{
2652 VM& vm = globalObject->vm();
2653 auto scope = DECLARE_CATCH_SCOPE(vm);
2654
2655 Optional<DirectoryName> directoryName = currentWorkingDirectory();
2656 if (!directoryName)
2657 return;
2658 SourceOrigin sourceOrigin(resolvePath(directoryName.value(), ModuleName("interpreter")));
2659
2660 bool shouldQuit = false;
2661 while (!shouldQuit) {
2662#if HAVE(READLINE) && !RUNNING_FROM_XCODE
2663 ParserError error;
2664 String source;
2665 do {
2666 error = ParserError();
2667 char* line = readline(source.isEmpty() ? interactivePrompt : "... ");
2668 shouldQuit = !line;
2669 if (!line)
2670 break;
2671 source = source + String::fromUTF8(line);
2672 source = source + '\n';
2673 checkSyntax(vm, jscSource(source, sourceOrigin), error);
2674 if (!line[0]) {
2675 free(line);
2676 break;
2677 }
2678 add_history(line);
2679 free(line);
2680 } while (error.syntaxErrorType() == ParserError::SyntaxErrorRecoverable);
2681
2682 if (error.isValid()) {
2683 printf("%s:%d\n", error.message().utf8().data(), error.line());
2684 continue;
2685 }
2686
2687
2688 NakedPtr<Exception> evaluationException;
2689 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(source, sourceOrigin), JSValue(), evaluationException);
2690#else
2691 printf("%s", interactivePrompt);
2692 Vector<char, 256> line;
2693 int c;
2694 while ((c = getchar()) != EOF) {
2695 // FIXME: Should we also break on \r?
2696 if (c == '\n')
2697 break;
2698 line.append(c);
2699 }
2700 if (line.isEmpty())
2701 break;
2702
2703 NakedPtr<Exception> evaluationException;
2704 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(line, sourceOrigin, sourceOrigin.string()), JSValue(), evaluationException);
2705#endif
2706 if (evaluationException)
2707 printf("Exception: %s\n", evaluationException->value().toWTFString(globalObject->globalExec()).utf8().data());
2708 else
2709 printf("%s\n", returnValue.toWTFString(globalObject->globalExec()).utf8().data());
2710
2711 scope.clearException();
2712 vm.drainMicrotasks();
2713 }
2714 printf("\n");
2715}
2716
2717static NO_RETURN void printUsageStatement(bool help = false)
2718{
2719 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
2720 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
2721 fprintf(stderr, " -e Evaluate argument as script code\n");
2722 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
2723 fprintf(stderr, " -h|--help Prints this help message\n");
2724 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
2725 fprintf(stderr, " -m Execute as a module\n");
2726#if HAVE(SIGNAL_H)
2727 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
2728#endif
2729 fprintf(stderr, " -p <file> Outputs profiling data to a file\n");
2730 fprintf(stderr, " -x Output exit code before terminating\n");
2731 fprintf(stderr, "\n");
2732 fprintf(stderr, " --sample Collects and outputs sampling profiler data\n");
2733 fprintf(stderr, " --test262-async Check that some script calls the print function with the string 'Test262:AsyncTestComplete'\n");
2734 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");
2735 fprintf(stderr, " --module-file=<file> Parse and evaluate the given file as module (this option may be passed more than once)\n");
2736 fprintf(stderr, " --exception=<name> Check the last script exits with an uncaught exception with the specified name\n");
2737 fprintf(stderr, " --watchdog-exception-ok Uncaught watchdog exceptions exit with success\n");
2738 fprintf(stderr, " --dumpException Dump uncaught exception text\n");
2739 fprintf(stderr, " --footprint Dump memory footprint after done executing\n");
2740 fprintf(stderr, " --options Dumps all JSC VM options and exits\n");
2741 fprintf(stderr, " --dumpOptions Dumps all non-default JSC VM options before continuing\n");
2742 fprintf(stderr, " --<jsc VM option>=<value> Sets the specified JSC VM option\n");
2743 fprintf(stderr, " --destroy-vm Destroy VM before exiting\n");
2744 fprintf(stderr, "\n");
2745 fprintf(stderr, "Files with a .mjs extension will always be evaluated as modules.\n");
2746 fprintf(stderr, "\n");
2747
2748 jscExit(help ? EXIT_SUCCESS : EXIT_FAILURE);
2749}
2750
2751static bool isMJSFile(char *filename)
2752{
2753 filename = strrchr(filename, '.');
2754
2755 if (filename)
2756 return !strcmp(filename, ".mjs");
2757
2758 return false;
2759}
2760
2761void CommandLine::parseArguments(int argc, char** argv)
2762{
2763 Options::initialize();
2764
2765 if (Options::dumpOptions()) {
2766 printf("Command line:");
2767#if PLATFORM(COCOA)
2768 for (char** envp = *_NSGetEnviron(); *envp; envp++) {
2769 const char* env = *envp;
2770 if (!strncmp("JSC_", env, 4))
2771 printf(" %s", env);
2772 }
2773#endif // PLATFORM(COCOA)
2774 for (int i = 0; i < argc; ++i)
2775 printf(" %s", argv[i]);
2776 printf("\n");
2777 }
2778
2779 int i = 1;
2780 JSC::Options::DumpLevel dumpOptionsLevel = JSC::Options::DumpLevel::None;
2781 bool needToExit = false;
2782
2783 bool hasBadJSCOptions = false;
2784 for (; i < argc; ++i) {
2785 const char* arg = argv[i];
2786 if (!strcmp(arg, "-f")) {
2787 if (++i == argc)
2788 printUsageStatement();
2789 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Script, argv[i]));
2790 continue;
2791 }
2792 if (!strcmp(arg, "-e")) {
2793 if (++i == argc)
2794 printUsageStatement();
2795 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::CommandLine, Script::ScriptType::Script, argv[i]));
2796 continue;
2797 }
2798 if (!strcmp(arg, "-i")) {
2799 m_interactive = true;
2800 continue;
2801 }
2802 if (!strcmp(arg, "-d")) {
2803 m_dump = true;
2804 continue;
2805 }
2806 if (!strcmp(arg, "-p")) {
2807 if (++i == argc)
2808 printUsageStatement();
2809 m_profile = true;
2810 m_profilerOutput = argv[i];
2811 continue;
2812 }
2813 if (!strcmp(arg, "-m")) {
2814 m_module = true;
2815 continue;
2816 }
2817 if (!strcmp(arg, "-s")) {
2818#if HAVE(SIGNAL_H)
2819 signal(SIGILL, _exit);
2820 signal(SIGFPE, _exit);
2821 signal(SIGBUS, _exit);
2822 signal(SIGSEGV, _exit);
2823#endif
2824 continue;
2825 }
2826 if (!strcmp(arg, "-x")) {
2827 m_exitCode = true;
2828 continue;
2829 }
2830 if (!strcmp(arg, "--")) {
2831 ++i;
2832 break;
2833 }
2834 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
2835 printUsageStatement(true);
2836
2837 if (!strcmp(arg, "--options")) {
2838 dumpOptionsLevel = JSC::Options::DumpLevel::Verbose;
2839 needToExit = true;
2840 continue;
2841 }
2842 if (!strcmp(arg, "--dumpOptions")) {
2843 dumpOptionsLevel = JSC::Options::DumpLevel::Overridden;
2844 continue;
2845 }
2846 if (!strcmp(arg, "--sample")) {
2847 JSC::Options::useSamplingProfiler() = true;
2848 JSC::Options::collectSamplingProfilerDataForJSCShell() = true;
2849 m_dumpSamplingProfilerData = true;
2850 continue;
2851 }
2852 if (!strcmp(arg, "--destroy-vm")) {
2853 m_destroyVM = true;
2854 continue;
2855 }
2856
2857 static const char* timeoutMultiplierOptStr = "--timeoutMultiplier=";
2858 static const unsigned timeoutMultiplierOptStrLength = strlen(timeoutMultiplierOptStr);
2859 if (!strncmp(arg, timeoutMultiplierOptStr, timeoutMultiplierOptStrLength)) {
2860 const char* valueStr = &arg[timeoutMultiplierOptStrLength];
2861 if (sscanf(valueStr, "%lf", &s_timeoutMultiplier) != 1)
2862 dataLog("WARNING: --timeoutMultiplier=", valueStr, " is invalid. Expects a numeric ratio.\n");
2863 continue;
2864 }
2865
2866 if (!strcmp(arg, "--test262-async")) {
2867 asyncTestExpectedPasses++;
2868 continue;
2869 }
2870
2871 if (!strcmp(arg, "--remote-debug")) {
2872 m_enableRemoteDebugging = true;
2873 continue;
2874 }
2875
2876 static const unsigned strictFileStrLength = strlen("--strict-file=");
2877 if (!strncmp(arg, "--strict-file=", strictFileStrLength)) {
2878 m_scripts.append(Script(Script::StrictMode::Strict, Script::CodeSource::File, Script::ScriptType::Script, argv[i] + strictFileStrLength));
2879 continue;
2880 }
2881
2882 static const unsigned moduleFileStrLength = strlen("--module-file=");
2883 if (!strncmp(arg, "--module-file=", moduleFileStrLength)) {
2884 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, Script::ScriptType::Module, argv[i] + moduleFileStrLength));
2885 continue;
2886 }
2887
2888 if (!strcmp(arg, "--dumpException")) {
2889 m_alwaysDumpUncaughtException = true;
2890 continue;
2891 }
2892
2893 if (!strcmp(arg, "--footprint")) {
2894 m_dumpMemoryFootprint = true;
2895 continue;
2896 }
2897
2898 static const unsigned exceptionStrLength = strlen("--exception=");
2899 if (!strncmp(arg, "--exception=", exceptionStrLength)) {
2900 m_uncaughtExceptionName = String(arg + exceptionStrLength);
2901 continue;
2902 }
2903
2904 if (!strcmp(arg, "--watchdog-exception-ok")) {
2905 m_treatWatchdogExceptionAsSuccess = true;
2906 continue;
2907 }
2908
2909 // See if the -- option is a JSC VM option.
2910 if (strstr(arg, "--") == arg) {
2911 if (!JSC::Options::setOption(&arg[2])) {
2912 hasBadJSCOptions = true;
2913 dataLog("ERROR: invalid option: ", arg, "\n");
2914 }
2915 continue;
2916 }
2917
2918 // This arg is not recognized by the VM nor by jsc. Pass it on to the
2919 // script.
2920 Script::ScriptType scriptType = isMJSFile(argv[i]) ? Script::ScriptType::Module : Script::ScriptType::Script;
2921 m_scripts.append(Script(Script::StrictMode::Sloppy, Script::CodeSource::File, scriptType, argv[i]));
2922 }
2923
2924 if (hasBadJSCOptions && JSC::Options::validateOptions())
2925 CRASH();
2926
2927 if (m_scripts.isEmpty())
2928 m_interactive = true;
2929
2930 for (; i < argc; ++i)
2931 m_arguments.append(argv[i]);
2932
2933 if (dumpOptionsLevel != JSC::Options::DumpLevel::None) {
2934 const char* optionsTitle = (dumpOptionsLevel == JSC::Options::DumpLevel::Overridden)
2935 ? "Modified JSC runtime options:"
2936 : "All JSC runtime options:";
2937 JSC::Options::dumpAllOptions(stderr, dumpOptionsLevel, optionsTitle);
2938 }
2939 JSC::Options::ensureOptionsAreCoherent();
2940 if (needToExit)
2941 jscExit(EXIT_SUCCESS);
2942}
2943
2944template<typename Func>
2945int runJSC(const CommandLine& options, bool isWorker, const Func& func)
2946{
2947 Worker worker(Workers::singleton());
2948
2949 VM& vm = VM::create(LargeHeap).leakRef();
2950 int result;
2951 bool success = true;
2952 GlobalObject* globalObject = nullptr;
2953 {
2954 JSLockHolder locker(vm);
2955
2956 if (options.m_profile && !vm.m_perBytecodeProfiler)
2957 vm.m_perBytecodeProfiler = std::make_unique<Profiler::Database>(vm);
2958
2959 globalObject = GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), options.m_arguments);
2960 globalObject->setRemoteDebuggingEnabled(options.m_enableRemoteDebugging);
2961 func(vm, globalObject, success);
2962 vm.drainMicrotasks();
2963 }
2964 vm.promiseDeferredTimer->runRunLoop();
2965 {
2966 JSLockHolder locker(vm);
2967 if (options.m_interactive && success)
2968 runInteractive(globalObject);
2969 }
2970
2971 result = success && (asyncTestExpectedPasses == asyncTestPasses) ? 0 : 3;
2972
2973 if (options.m_exitCode) {
2974 printf("jsc exiting %d", result);
2975 if (asyncTestExpectedPasses != asyncTestPasses)
2976 printf(" because expected: %d async test passes but got: %d async test passes", asyncTestExpectedPasses, asyncTestPasses);
2977 printf("\n");
2978 }
2979
2980 if (options.m_profile) {
2981 JSLockHolder locker(vm);
2982 if (!vm.m_perBytecodeProfiler->save(options.m_profilerOutput.utf8().data()))
2983 fprintf(stderr, "could not save profiler output.\n");
2984 }
2985
2986#if ENABLE(JIT)
2987 {
2988 JSLockHolder locker(vm);
2989 if (Options::useExceptionFuzz())
2990 printf("JSC EXCEPTION FUZZ: encountered %u checks.\n", numberOfExceptionFuzzChecks());
2991 bool fireAtEnabled =
2992 Options::fireExecutableAllocationFuzzAt() || Options::fireExecutableAllocationFuzzAtOrAfter();
2993 if (Options::useExecutableAllocationFuzz() && (!fireAtEnabled || Options::verboseExecutableAllocationFuzz()))
2994 printf("JSC EXECUTABLE ALLOCATION FUZZ: encountered %u checks.\n", numberOfExecutableAllocationFuzzChecks());
2995 if (Options::useOSRExitFuzz()) {
2996 printf("JSC OSR EXIT FUZZ: encountered %u static checks.\n", numberOfStaticOSRExitFuzzChecks());
2997 printf("JSC OSR EXIT FUZZ: encountered %u dynamic checks.\n", numberOfOSRExitFuzzChecks());
2998 }
2999
3000
3001 auto compileTimeStats = JIT::compileTimeStats();
3002 Vector<CString> compileTimeKeys;
3003 for (auto& entry : compileTimeStats)
3004 compileTimeKeys.append(entry.key);
3005 std::sort(compileTimeKeys.begin(), compileTimeKeys.end());
3006 for (const CString& key : compileTimeKeys)
3007 printf("%40s: %.3lf ms\n", key.data(), compileTimeStats.get(key).milliseconds());
3008 }
3009#endif
3010
3011 if (Options::gcAtEnd()) {
3012 // We need to hold the API lock to do a GC.
3013 JSLockHolder locker(&vm);
3014 vm.heap.collectNow(Sync, CollectionScope::Full);
3015 }
3016
3017 if (options.m_dumpSamplingProfilerData) {
3018#if ENABLE(SAMPLING_PROFILER)
3019 JSLockHolder locker(&vm);
3020 vm.samplingProfiler()->reportTopFunctions();
3021 vm.samplingProfiler()->reportTopBytecodes();
3022#else
3023 dataLog("Sampling profiler is not enabled on this platform\n");
3024#endif
3025 }
3026
3027 vm.codeCache()->write(vm);
3028
3029 if (options.m_destroyVM || isWorker) {
3030 JSLockHolder locker(vm);
3031 // This is needed because we don't want the worker's main
3032 // thread to die before its compilation threads finish.
3033 vm.deref();
3034 }
3035
3036 return result;
3037}
3038
3039int jscmain(int argc, char** argv)
3040{
3041 // Need to override and enable restricted options before we start parsing options below.
3042 Options::enableRestrictedOptions(true);
3043
3044 // Note that the options parsing can affect VM creation, and thus
3045 // comes first.
3046 CommandLine options(argc, argv);
3047
3048 processConfigFile(Options::configFile(), "jsc");
3049
3050 // Initialize JSC before getting VM.
3051 WTF::initializeMainThread();
3052 JSC::initializeThreading();
3053 startTimeoutThreadIfNeeded();
3054#if ENABLE(WEBASSEMBLY)
3055 JSC::Wasm::enableFastMemory();
3056#endif
3057 Gigacage::disableDisablingPrimitiveGigacageIfShouldBeEnabled();
3058
3059#if PLATFORM(COCOA)
3060 auto& memoryPressureHandler = MemoryPressureHandler::singleton();
3061 {
3062 dispatch_queue_t queue = dispatch_queue_create("jsc shell memory pressure handler", DISPATCH_QUEUE_SERIAL);
3063 memoryPressureHandler.setDispatchQueue(queue);
3064 dispatch_release(queue);
3065 }
3066 Box<Critical> memoryPressureCriticalState = Box<Critical>::create(Critical::No);
3067 Box<Synchronous> memoryPressureSynchronousState = Box<Synchronous>::create(Synchronous::No);
3068 memoryPressureHandler.setLowMemoryHandler([=] (Critical critical, Synchronous synchronous) {
3069 // We set these racily with respect to reading them from the JS execution thread.
3070 *memoryPressureCriticalState = critical;
3071 *memoryPressureSynchronousState = synchronous;
3072 });
3073 memoryPressureHandler.setShouldLogMemoryMemoryPressureEvents(false);
3074 memoryPressureHandler.install();
3075
3076 auto onEachMicrotaskTick = [&] (VM& vm) {
3077 if (*memoryPressureCriticalState == Critical::No)
3078 return;
3079
3080 *memoryPressureCriticalState = Critical::No;
3081 bool isSynchronous = *memoryPressureSynchronousState == Synchronous::Yes;
3082
3083 WTF::releaseFastMallocFreeMemory();
3084 vm.deleteAllCode(DeleteAllCodeIfNotCollecting);
3085
3086 if (!vm.heap.isCurrentThreadBusy()) {
3087 if (isSynchronous) {
3088 vm.heap.collectNow(Sync, CollectionScope::Full);
3089 WTF::releaseFastMallocFreeMemory();
3090 } else
3091 vm.heap.collectNowFullIfNotDoneRecently(Async);
3092 }
3093 };
3094#endif
3095
3096 int result = runJSC(
3097 options, false,
3098 [&] (VM& vm, GlobalObject* globalObject, bool& success) {
3099 UNUSED_PARAM(vm);
3100#if PLATFORM(COCOA)
3101 vm.setOnEachMicrotaskTick(WTFMove(onEachMicrotaskTick));
3102#endif
3103 runWithOptions(globalObject, options, success);
3104 });
3105
3106 printSuperSamplerState();
3107
3108 if (options.m_dumpMemoryFootprint) {
3109 MemoryFootprint footprint = MemoryFootprint::now();
3110
3111 printf("Memory Footprint:\n Current Footprint: %" PRIu64 "\n Peak Footprint: %" PRIu64 "\n", footprint.current, footprint.peak);
3112 }
3113
3114 return result;
3115}
3116
3117#if OS(WINDOWS)
3118extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(int argc, const char* argv[])
3119{
3120 return main(argc, const_cast<char**>(argv));
3121}
3122#endif
3123