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

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

Expose "$262.agent.monotonicNow()" for use in testing Atomic operation timeouts
https://bugs.webkit.org/show_bug.cgi?id=185043

Patch by Rick Waldron <[email protected]> on 2018-05-02
Reviewed by Filip Pizlo.

  • jsc.cpp:

(GlobalObject::finishCreation):
(functionDollarAgentMonotonicNow):

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