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

Last change on this file since 229309 was 229309, checked in by Yusuke Suzuki, 7 years ago

Fix std::make_unique / new[] using system malloc
https://bugs.webkit.org/show_bug.cgi?id=182975

Reviewed by JF Bastien.

Source/JavaScriptCore:

Use Vector, FAST_ALLOCATED, or UniqueArray instead.

  • API/JSStringRefCF.cpp:

(JSStringCreateWithCFString):

  • bytecode/BytecodeKills.h:
  • bytecode/BytecodeLivenessAnalysis.cpp:

(JSC::BytecodeLivenessAnalysis::computeKills):

  • dfg/DFGDisassembler.cpp:

(JSC::DFG::Disassembler::dumpDisassembly):

  • jit/PolymorphicCallStubRoutine.cpp:

(JSC::PolymorphicCallStubRoutine::PolymorphicCallStubRoutine):

  • jit/PolymorphicCallStubRoutine.h:
  • jit/Repatch.cpp:

(JSC::linkPolymorphicCall):

  • jsc.cpp:

(currentWorkingDirectory):

  • llint/LLIntData.cpp:

(JSC::LLInt::initialize):

  • llint/LLIntData.h:
  • runtime/ArgList.h:
  • runtime/StructureChain.h:
  • runtime/StructureIDTable.cpp:

(JSC::StructureIDTable::StructureIDTable):
(JSC::StructureIDTable::resize):

  • runtime/StructureIDTable.h:
  • runtime/TypeProfilerLog.cpp:

(JSC::TypeProfilerLog::TypeProfilerLog):
(JSC::TypeProfilerLog::initializeLog): Deleted.

  • runtime/TypeProfilerLog.h:

(JSC::TypeProfilerLog::TypeProfilerLog): Deleted.

  • runtime/VM.cpp:

(JSC::VM::~VM):
(JSC::VM::acquireRegExpPatternContexBuffer):

  • runtime/VM.h:
  • testRegExp.cpp:

(runFromFiles):

  • tools/HeapVerifier.cpp:

(JSC::HeapVerifier::HeapVerifier):

  • tools/HeapVerifier.h:

Source/WebCore:

Use Vector, FAST_ALLOCATED, or UniqueArray instead.

  • Modules/webaudio/AudioBufferSourceNode.cpp:

(WebCore::AudioBufferSourceNode::setBuffer):

  • Modules/webaudio/AudioBufferSourceNode.h:
  • css/StyleRule.h:
  • cssjit/CompiledSelector.h:
  • html/HTMLFrameSetElement.h:
  • html/canvas/WebGLRenderingContextBase.cpp:

(WebCore::WebGLRenderingContextBase::copyTexSubImage2D):
(WebCore::WebGLRenderingContextBase::simulateVertexAttrib0):
(WebCore::WebGLRenderingContextBase::LRUImageBufferCache::LRUImageBufferCache):
(WebCore::WebGLRenderingContextBase::LRUImageBufferCache::imageBuffer):
(WebCore::WebGLRenderingContextBase::LRUImageBufferCache::bubbleToFront):

  • html/canvas/WebGLRenderingContextBase.h:
  • platform/Length.cpp:

(WebCore::newCoordsArray):
(WebCore::newLengthArray):
(): Deleted.

  • platform/Length.h:
  • platform/audio/DynamicsCompressor.cpp:

(WebCore::DynamicsCompressor::setNumberOfChannels):

  • platform/audio/DynamicsCompressor.h:
  • platform/audio/FFTFrame.h:
  • platform/audio/gstreamer/FFTFrameGStreamer.cpp:

(WebCore::FFTFrame::FFTFrame):

  • platform/graphics/FormatConverter.h:

(WebCore::FormatConverter::FormatConverter):

  • platform/graphics/GraphicsContext3D.cpp:

(WebCore::GraphicsContext3D::texImage2DResourceSafe):

  • platform/graphics/GraphicsContext3D.h:
  • platform/graphics/ca/win/CACFLayerTreeHost.cpp:

(WebCore::getDirtyRects):

  • platform/graphics/cairo/CairoUtilities.cpp:

(WebCore::flipImageSurfaceVertically):

  • platform/graphics/cg/GraphicsContext3DCG.cpp:

(WebCore::GraphicsContext3D::ImageExtractor::extractImage):

  • platform/graphics/gpu/Texture.cpp:

(WebCore::Texture::updateSubRect):

  • platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp:

(WebCore::GraphicsContext3D::paintRenderingResultsToCanvas):
(WebCore::GraphicsContext3D::compileShader):
(WebCore::GraphicsContext3D::getActiveAttribImpl):
(WebCore::GraphicsContext3D::getActiveUniformImpl):
(WebCore::GraphicsContext3D::getProgramInfoLog):
(WebCore::GraphicsContext3D::getShaderInfoLog):

  • platform/graphics/texmap/TextureMapperShaderProgram.cpp:

(WebCore::getShaderLog):
(WebCore::getProgramLog):

  • platform/graphics/win/ImageBufferDataDirect2D.cpp:

(WebCore::ImageBufferData::putData):

  • platform/image-decoders/png/PNGImageDecoder.cpp:

(WebCore::PNGImageReader::PNGImageReader):
(WebCore::PNGImageReader::close):
(WebCore::PNGImageReader::interlaceBuffer const):
(WebCore::PNGImageReader::createInterlaceBuffer):

  • platform/image-decoders/webp/WEBPImageDecoder.cpp:

(WebCore::WEBPImageDecoder::decodeFrame):

  • platform/network/curl/SocketStreamHandleImpl.h:

(WebCore::SocketStreamHandleImpl::SocketData::SocketData):

  • platform/network/curl/SocketStreamHandleImplCurl.cpp:

(WebCore::createCopy):
(WebCore::SocketStreamHandleImpl::readData):
(): Deleted.

  • platform/network/soup/SocketStreamHandleImpl.h:
  • platform/network/soup/SocketStreamHandleImplSoup.cpp:

(WebCore::SocketStreamHandleImpl::connected):

  • platform/win/LoggingWin.cpp:

(WebCore::logLevelString):

Source/WebCore/PAL:

Use Vector instead.

  • pal/win/LoggingWin.cpp:

(PAL::logLevelString):

Source/WebKit:

Use Vector instead.

  • NetworkProcess/win/SystemProxyWin.cpp:

(WindowsSystemProxy::getSystemHttpProxy):

  • Platform/IPC/unix/ConnectionUnix.cpp:

(IPC::Connection::processMessage):
(IPC::Connection::sendOutputMessage):

  • Platform/win/LoggingWin.cpp:

(WebKit::logLevelString):

  • Shared/SandboxExtension.h:
  • Shared/mac/SandboxExtensionMac.mm:

(WebKit::SandboxExtension::HandleArray::allocate):
(WebKit::SandboxExtension::HandleArray::operator[]):
(WebKit::SandboxExtension::HandleArray::operator[] const):
(WebKit::SandboxExtension::HandleArray::size const):
(WebKit::SandboxExtension::HandleArray::encode const):

Source/WebKitLegacy/win:

Use Vector instead.

  • MarshallingHelpers.cpp:

(MarshallingHelpers::safeArrayToStringArray):
(MarshallingHelpers::safeArrayToIntArray):

  • Plugins/PluginPackageWin.cpp:

(WebCore::PluginPackage::fetchInfo):

  • WebPreferences.cpp:

(WebPreferences::copyWebKitPreferencesToCFPreferences):

  • WebView.cpp:

(WebView::onMenuCommand):

Source/WTF:

If we use make_unique<char[]>(num) or new char[num], allocation is
done by the system malloc instead of bmalloc. This patch fixes this issue
by following three changes.

  1. Introduce UniqueArray<T>. It allocates memory from FastMalloc. While C++

array with new need to hold the size to call destructor correctly, our
UniqueArray only supports type T which does not have a non trivial destructor.
It reduces the allocation size since we do not need to track the size of the
array compared to standard new T[]. This is basically usable if we want to
have raw array which pointer won't be changed even if the container is moved.
In addition, we also extend UniqueArray<T> for types which have non trivial
destructors.

  1. Use Vector<T> instead.
  1. Annotate allocated types with MAKE_FAST_ALLOCATED. Since it introduces

new[] and delete[] operators, make_unique<T[]>(num) will allocate memory
from FastMalloc.

  • WTF.xcodeproj/project.pbxproj:
  • wtf/Assertions.cpp:
  • wtf/CMakeLists.txt:
  • wtf/FastMalloc.h:

(WTF::FastFree::operator() const):
(WTF::FastFree<T::operator() const):

  • wtf/MallocPtr.h:

(WTF::MallocPtr::operator bool const):

  • wtf/StackShot.h:

(WTF::StackShot::StackShot):
(WTF::StackShot::operator=):

  • wtf/SystemFree.h:

(WTF::SystemFree<T::operator() const):

  • wtf/UniqueArray.h: Copied from Source/WebKit/Platform/win/LoggingWin.cpp.

(WTF::makeUniqueArray):

  • wtf/Vector.h:

(WTF::VectorTypeOperations::forceInitialize):

Tools:

  • TestWebKitAPI/CMakeLists.txt:
  • TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
  • TestWebKitAPI/Tests/WTF/UniqueArray.cpp: Copied from Source/WebKit/Platform/win/LoggingWin.cpp.

(TestWebKitAPI::NonTrivialDestructor::NonTrivialDestructor):
(TestWebKitAPI::NonTrivialDestructor::~NonTrivialDestructor):
(TestWebKitAPI::NonTrivialDestructor::setLog):
(TestWebKitAPI::TEST):

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