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

Last change on this file since 261755 was 261755, checked in by Ross Kirsling, 5 years ago

[IWYU] Remove unnecessary includes from JSC implementation files
https://bugs.webkit.org/show_bug.cgi?id=211867

Reviewed by Keith Miller.

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