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