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