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

Last change on this file since 235627 was 235627, checked in by [email protected], 7 years ago

Make the jsc shell print, printErr, and debug functions more robust.
https://bugs.webkit.org/show_bug.cgi?id=189268
<rdar://problem/41192690>

Reviewed by Keith Miller.

We'll now check for UTF8 conversion errors.

  • jsc.cpp:

(cStringFromViewWithString):
(printInternal):
(functionDebug):

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