1/*
2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3 * Copyright (C) 2004-2019 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Bjoern Graf (bjoern.graf@gmail.com)
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#include "config.h"
24
25#include "ArrayBuffer.h"
26#include "ArrayPrototype.h"
27#include "BuiltinNames.h"
28#include "ButterflyInlines.h"
29#include "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(