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

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

Unreviewed, Revert r199397 due to PLT regressions

Source/JavaScriptCore:

  • JavaScriptCore.xcodeproj/project.pbxproj:
  • builtins/ArrayPrototype.js:

(concatSlowPath): Deleted.
(concat): Deleted.

  • bytecode/BytecodeIntrinsicRegistry.cpp:

(JSC::BytecodeIntrinsicRegistry::BytecodeIntrinsicRegistry): Deleted.

  • bytecode/BytecodeIntrinsicRegistry.h:
  • dfg/DFGAbstractInterpreterInlines.h:

(JSC::DFG::AbstractInterpreter<AbstractStateType>::executeEffects):

  • dfg/DFGByteCodeParser.cpp:

(JSC::DFG::ByteCodeParser::handleConstantInternalFunction):
(JSC::DFG::ByteCodeParser::handleIntrinsicCall): Deleted.

  • dfg/DFGClobberize.h:

(JSC::DFG::clobberize):

  • dfg/DFGDoesGC.cpp:

(JSC::DFG::doesGC): Deleted.

  • dfg/DFGFixupPhase.cpp:

(JSC::DFG::FixupPhase::fixupNode):

  • dfg/DFGNodeType.h:
  • dfg/DFGOperations.cpp:
  • dfg/DFGOperations.h:
  • dfg/DFGPredictionPropagationPhase.cpp:
  • dfg/DFGSafeToExecute.h:

(JSC::DFG::safeToExecute): Deleted.

  • dfg/DFGSpeculativeJIT.cpp:

(JSC::DFG::SpeculativeJIT::compileCurrentBlock):
(JSC::DFG::SpeculativeJIT::compileIsJSArray): Deleted.
(JSC::DFG::SpeculativeJIT::compileIsArrayObject): Deleted.
(JSC::DFG::SpeculativeJIT::compileIsArrayConstructor): Deleted.
(JSC::DFG::SpeculativeJIT::compileCallObjectConstructor): Deleted.

  • dfg/DFGSpeculativeJIT.h:

(JSC::DFG::SpeculativeJIT::callOperation): Deleted.

  • dfg/DFGSpeculativeJIT32_64.cpp:

(JSC::DFG::SpeculativeJIT::compile): Deleted.

  • dfg/DFGSpeculativeJIT64.cpp:

(JSC::DFG::SpeculativeJIT::compile):

  • ftl/FTLCapabilities.cpp:

(JSC::FTL::canCompile): Deleted.

  • ftl/FTLLowerDFGToB3.cpp:

(JSC::FTL::DFG::LowerDFGToB3::compileNode): Deleted.
(JSC::FTL::DFG::LowerDFGToB3::compileCallObjectConstructor): Deleted.
(JSC::FTL::DFG::LowerDFGToB3::compileIsArrayObject): Deleted.
(JSC::FTL::DFG::LowerDFGToB3::compileIsJSArray): Deleted.
(JSC::FTL::DFG::LowerDFGToB3::compileIsArrayConstructor): Deleted.
(JSC::FTL::DFG::LowerDFGToB3::isArray): Deleted.

  • jit/JITOperations.h:
  • jsc.cpp:

(GlobalObject::finishCreation):
(functionDataLogValue): Deleted.

  • runtime/ArrayConstructor.cpp:

(JSC::ArrayConstructor::finishCreation):
(JSC::arrayConstructorPrivateFuncIsArrayConstructor):

  • runtime/ArrayConstructor.h:

(JSC::isArrayConstructor): Deleted.

  • runtime/ArrayPrototype.cpp:

(JSC::ArrayPrototype::finishCreation):
(JSC::arrayProtoFuncConcat):
(JSC::arrayProtoPrivateFuncIsJSArray): Deleted.
(JSC::moveElements): Deleted.
(JSC::arrayProtoPrivateFuncConcatMemcpy): Deleted.
(JSC::arrayProtoPrivateFuncAppendMemcpy): Deleted.

  • runtime/ArrayPrototype.h:
  • runtime/CommonIdentifiers.h:
  • runtime/Intrinsic.h:
  • runtime/JSArray.cpp:

(JSC::JSArray::fastConcatWith):
(JSC::JSArray::appendMemcpy): Deleted.

  • runtime/JSArray.h:

(JSC::JSArray::fastConcatType):
(JSC::JSArray::createStructure):
(JSC::isJSArray):

  • runtime/JSArrayInlines.h: Removed.

(JSC::JSArray::memCopyWithIndexingType): Deleted.
(JSC::JSArray::canFastCopy): Deleted.

  • runtime/JSGlobalObject.cpp:

(JSC::JSGlobalObject::init):

  • runtime/JSType.h:
  • runtime/ObjectConstructor.h:

(JSC::constructObject): Deleted.

  • tests/es6.yaml:
  • tests/stress/array-concat-spread-object.js: Removed.

(arrayEq): Deleted.

  • tests/stress/array-concat-spread-proxy-exception-check.js: Removed.

(arrayEq): Deleted.

  • tests/stress/array-concat-spread-proxy.js: Removed.

(arrayEq): Deleted.

  • tests/stress/array-concat-with-slow-indexingtypes.js: Removed.

(arrayEq): Deleted.

  • tests/stress/array-species-config-array-constructor.js:

LayoutTests:

  • js/Object-getOwnPropertyNames-expected.txt:
  • js/dom/array-prototype-properties-expected.txt:
  • js/script-tests/Object-getOwnPropertyNames.js:
  • Property svn:eol-style set to native
File size: 83.3 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2004-2008, 2012-2013, 2015-2016 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 "ArrayPrototype.h"
26#include "BuiltinExecutableCreator.h"
27#include "ButterflyInlines.h"
28#include "BytecodeGenerator.h"
29#include "CodeBlock.h"
30#include "Completion.h"
31#include "CopiedSpaceInlines.h"
32#include "DFGPlan.h"
33#include "Disassembler.h"
34#include "Exception.h"
35#include "ExceptionHelpers.h"
36#include "GetterSetter.h"
37#include "HeapProfiler.h"
38#include "HeapSnapshotBuilder.h"
39#include "HeapStatistics.h"
40#include "InitializeThreading.h"
41#include "Interpreter.h"
42#include "JSArray.h"
43#include "JSArrayBuffer.h"
44#include "JSCInlines.h"
45#include "JSFunction.h"
46#include "JSInternalPromise.h"
47#include "JSInternalPromiseDeferred.h"
48#include "JSLock.h"
49#include "JSNativeStdFunction.h"
50#include "JSONObject.h"
51#include "JSProxy.h"
52#include "JSString.h"
53#include "JSWASMModule.h"
54#include "ProfilerDatabase.h"
55#include "SamplingProfiler.h"
56#include "ShadowChicken.h"
57#include "StackVisitor.h"
58#include "StructureInlines.h"
59#include "StructureRareDataInlines.h"
60#include "SuperSampler.h"
61#include "TestRunnerUtils.h"
62#include "TypeProfilerLog.h"
63#include "WASMModuleParser.h"
64#include <math.h>
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#include <thread>
69#include <wtf/CurrentTime.h>
70#include <wtf/MainThread.h>
71#include <wtf/StringPrintStream.h>
72#include <wtf/text/StringBuilder.h>
73
74#if OS(WINDOWS)
75#include <direct.h>
76#else
77#include <unistd.h>
78#endif
79
80#if HAVE(READLINE)
81// readline/history.h has a Function typedef which conflicts with the WTF::Function template from WTF/Forward.h
82// We #define it to something else to avoid this conflict.
83#define Function ReadlineFunction
84#include <readline/history.h>
85#include <readline/readline.h>
86#undef Function
87#endif
88
89#if HAVE(SYS_TIME_H)
90#include <sys/time.h>
91#endif
92
93#if HAVE(SIGNAL_H)
94#include <signal.h>
95#endif
96
97#if COMPILER(MSVC)
98#include <crtdbg.h>
99#include <mmsystem.h>
100#include <windows.h>
101#endif
102
103#if PLATFORM(IOS) && CPU(ARM_THUMB2)
104#include <fenv.h>
105#include <arm/arch.h>
106#endif
107
108#if PLATFORM(EFL)
109#include <Ecore.h>
110#endif
111
112#if !defined(PATH_MAX)
113#define PATH_MAX 4096
114#endif
115
116using namespace JSC;
117using namespace WTF;
118
119namespace {
120
121NO_RETURN_WITH_VALUE static void jscExit(int status)
122{
123 waitForAsynchronousDisassembly();
124
125#if ENABLE(DFG_JIT)
126 if (DFG::isCrashing()) {
127 for (;;) {
128#if OS(WINDOWS)
129 Sleep(1000);
130#else
131 pause();
132#endif
133 }
134 }
135#endif // ENABLE(DFG_JIT)
136 exit(status);
137}
138
139class Element;
140class ElementHandleOwner;
141class Masuqerader;
142class Root;
143class RuntimeArray;
144
145class Element : public JSNonFinalObject {
146public:
147 Element(VM& vm, Structure* structure)
148 : Base(vm, structure)
149 {
150 }
151
152 typedef JSNonFinalObject Base;
153 static const bool needsDestruction = false;
154
155 Root* root() const { return m_root.get(); }
156 void setRoot(VM& vm, Root* root) { m_root.set(vm, this, root); }
157
158 static Element* create(VM& vm, JSGlobalObject* globalObject, Root* root)
159 {
160 Structure* structure = createStructure(vm, globalObject, jsNull());
161 Element* element = new (NotNull, allocateCell<Element>(vm.heap, sizeof(Element))) Element(vm, structure);
162 element->finishCreation(vm, root);
163 return element;
164 }
165
166 void finishCreation(VM&, Root*);
167
168 static void visitChildren(JSCell* cell, SlotVisitor& visitor)
169 {
170 Element* thisObject = jsCast<Element*>(cell);
171 ASSERT_GC_OBJECT_INHERITS(thisObject, info());
172 Base::visitChildren(thisObject, visitor);
173 visitor.append(&thisObject->m_root);
174 }
175
176 static ElementHandleOwner* handleOwner();
177
178 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
179 {
180 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
181 }
182
183 DECLARE_INFO;
184
185private:
186 WriteBarrier<Root> m_root;
187};
188
189class ElementHandleOwner : public WeakHandleOwner {
190public:
191 virtual bool isReachableFromOpaqueRoots(Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)
192 {
193 Element* element = jsCast<Element*>(handle.slot()->asCell());
194 return visitor.containsOpaqueRoot(element->root());
195 }
196};
197
198class Masquerader : public JSNonFinalObject {
199public:
200 Masquerader(VM& vm, Structure* structure)
201 : Base(vm, structure)
202 {
203 }
204
205 typedef JSNonFinalObject Base;
206 static const unsigned StructureFlags = Base::StructureFlags | JSC::MasqueradesAsUndefined;
207
208 static Masquerader* create(VM& vm, JSGlobalObject* globalObject)
209 {
210 globalObject->masqueradesAsUndefinedWatchpoint()->fireAll("Masquerading object allocated");
211 Structure* structure = createStructure(vm, globalObject, jsNull());
212 Masquerader* result = new (NotNull, allocateCell<Masquerader>(vm.heap, sizeof(Masquerader))) Masquerader(vm, structure);
213 result->finishCreation(vm);
214 return result;
215 }
216
217 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
218 {
219 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
220 }
221
222 DECLARE_INFO;
223};
224
225class Root : public JSDestructibleObject {
226public:
227 Root(VM& vm, Structure* structure)
228 : Base(vm, structure)
229 {
230 }
231
232 Element* element()
233 {
234 return m_element.get();
235 }
236
237 void setElement(Element* element)
238 {
239 Weak<Element> newElement(element, Element::handleOwner());
240 m_element.swap(newElement);
241 }
242
243 static Root* create(VM& vm, JSGlobalObject* globalObject)
244 {
245 Structure* structure = createStructure(vm, globalObject, jsNull());
246 Root* root = new (NotNull, allocateCell<Root>(vm.heap, sizeof(Root))) Root(vm, structure);
247 root->finishCreation(vm);
248 return root;
249 }
250
251 typedef JSDestructibleObject Base;
252
253 DECLARE_INFO;
254 static const bool needsDestruction = true;
255
256 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
257 {
258 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
259 }
260
261 static void visitChildren(JSCell* thisObject, SlotVisitor& visitor)
262 {
263 Base::visitChildren(thisObject, visitor);
264 visitor.addOpaqueRoot(thisObject);
265 }
266
267private:
268 Weak<Element> m_element;
269};
270
271class ImpureGetter : public JSNonFinalObject {
272public:
273 ImpureGetter(VM& vm, Structure* structure)
274 : Base(vm, structure)
275 {
276 }
277
278 DECLARE_INFO;
279 typedef JSNonFinalObject Base;
280 static const unsigned StructureFlags = Base::StructureFlags | JSC::GetOwnPropertySlotIsImpure | JSC::OverridesGetOwnPropertySlot;
281
282 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
283 {
284 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
285 }
286
287 static ImpureGetter* create(VM& vm, Structure* structure, JSObject* delegate)
288 {
289 ImpureGetter* getter = new (NotNull, allocateCell<ImpureGetter>(vm.heap, sizeof(ImpureGetter))) ImpureGetter(vm, structure);
290 getter->finishCreation(vm, delegate);
291 return getter;
292 }
293
294 void finishCreation(VM& vm, JSObject* delegate)
295 {
296 Base::finishCreation(vm);
297 if (delegate)
298 m_delegate.set(vm, this, delegate);
299 }
300
301 static bool getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName name, PropertySlot& slot)
302 {
303 ImpureGetter* thisObject = jsCast<ImpureGetter*>(object);
304
305 if (thisObject->m_delegate && thisObject->m_delegate->getPropertySlot(exec, name, slot))
306 return true;
307
308 return Base::getOwnPropertySlot(object, exec, name, slot);
309 }
310
311 static void visitChildren(JSCell* cell, SlotVisitor& visitor)
312 {
313 Base::visitChildren(cell, visitor);
314 ImpureGetter* thisObject = jsCast<ImpureGetter*>(cell);
315 visitor.append(&thisObject->m_delegate);
316 }
317
318 void setDelegate(VM& vm, JSObject* delegate)
319 {
320 m_delegate.set(vm, this, delegate);
321 }
322
323private:
324 WriteBarrier<JSObject> m_delegate;
325};
326
327class CustomGetter : public JSNonFinalObject {
328public:
329 CustomGetter(VM& vm, Structure* structure)
330 : Base(vm, structure)
331 {
332 }
333
334 DECLARE_INFO;
335 typedef JSNonFinalObject Base;
336 static const unsigned StructureFlags = Base::StructureFlags | JSC::OverridesGetOwnPropertySlot;
337
338 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
339 {
340 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
341 }
342
343 static CustomGetter* create(VM& vm, Structure* structure)
344 {
345 CustomGetter* getter = new (NotNull, allocateCell<CustomGetter>(vm.heap, sizeof(CustomGetter))) CustomGetter(vm, structure);
346 getter->finishCreation(vm);
347 return getter;
348 }
349
350 static bool getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
351 {
352 CustomGetter* thisObject = jsCast<CustomGetter*>(object);
353 if (propertyName == PropertyName(Identifier::fromString(exec, "customGetter"))) {
354 slot.setCacheableCustom(thisObject, DontDelete | ReadOnly | DontEnum, thisObject->customGetter);
355 return true;
356 }
357 return JSObject::getOwnPropertySlot(thisObject, exec, propertyName, slot);
358 }
359
360private:
361 static EncodedJSValue customGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName)
362 {
363 CustomGetter* thisObject = jsDynamicCast<CustomGetter*>(JSValue::decode(thisValue));
364 if (!thisObject)
365 return throwVMTypeError(exec);
366 bool shouldThrow = thisObject->get(exec, PropertyName(Identifier::fromString(exec, "shouldThrow"))).toBoolean(exec);
367 if (shouldThrow)
368 return throwVMTypeError(exec);
369 return JSValue::encode(jsNumber(100));
370 }
371};
372
373class RuntimeArray : public JSArray {
374public:
375 typedef JSArray Base;
376 static const unsigned StructureFlags = Base::StructureFlags | OverridesGetOwnPropertySlot | InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero | OverridesGetPropertyNames;
377
378 static RuntimeArray* create(ExecState* exec)
379 {
380 VM& vm = exec->vm();
381 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
382 Structure* structure = createStructure(vm, globalObject, createPrototype(vm, globalObject));
383 RuntimeArray* runtimeArray = new (NotNull, allocateCell<RuntimeArray>(*exec->heap())) RuntimeArray(exec, structure);
384 runtimeArray->finishCreation(exec);
385 vm.heap.addFinalizer(runtimeArray, destroy);
386 return runtimeArray;
387 }
388
389 ~RuntimeArray() { }
390
391 static void destroy(JSCell* cell)
392 {
393 static_cast<RuntimeArray*>(cell)->RuntimeArray::~RuntimeArray();
394 }
395
396 static const bool needsDestruction = false;
397
398 static bool getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
399 {
400 RuntimeArray* thisObject = jsCast<RuntimeArray*>(object);
401 if (propertyName == exec->propertyNames().length) {
402 slot.setCacheableCustom(thisObject, DontDelete | ReadOnly | DontEnum, thisObject->lengthGetter);
403 return true;
404 }
405
406 Optional<uint32_t> index = parseIndex(propertyName);
407 if (index && index.value() < thisObject->getLength()) {
408 slot.setValue(thisObject, DontDelete | DontEnum, jsNumber(thisObject->m_vector[index.value()]));
409 return true;
410 }
411
412 return JSObject::getOwnPropertySlot(thisObject, exec, propertyName, slot);
413 }
414
415 static bool getOwnPropertySlotByIndex(JSObject* object, ExecState* exec, unsigned index, PropertySlot& slot)
416 {
417 RuntimeArray* thisObject = jsCast<RuntimeArray*>(object);
418 if (index < thisObject->getLength()) {
419 slot.setValue(thisObject, DontDelete | DontEnum, jsNumber(thisObject->m_vector[index]));
420 return true;
421 }
422
423 return JSObject::getOwnPropertySlotByIndex(thisObject, exec, index, slot);
424 }
425
426 static NO_RETURN_DUE_TO_CRASH bool put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&)
427 {
428 RELEASE_ASSERT_NOT_REACHED();
429 }
430
431 static NO_RETURN_DUE_TO_CRASH bool deleteProperty(JSCell*, ExecState*, PropertyName)
432 {
433 RELEASE_ASSERT_NOT_REACHED();
434 }
435
436 unsigned getLength() const { return m_vector.size(); }
437
438 DECLARE_INFO;
439
440 static ArrayPrototype* createPrototype(VM&, JSGlobalObject* globalObject)
441 {
442 return globalObject->arrayPrototype();
443 }
444
445 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
446 {
447 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info(), ArrayClass);
448 }
449
450protected:
451 void finishCreation(ExecState* exec)
452 {
453 Base::finishCreation(exec->vm());
454 ASSERT(inherits(info()));
455
456 for (size_t i = 0; i < exec->argumentCount(); i++)
457 m_vector.append(exec->argument(i).toInt32(exec));
458 }
459
460private:
461 RuntimeArray(ExecState* exec, Structure* structure)
462 : JSArray(exec->vm(), structure, 0)
463 {
464 }
465
466 static EncodedJSValue lengthGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName)
467 {
468 RuntimeArray* thisObject = jsDynamicCast<RuntimeArray*>(JSValue::decode(thisValue));
469 if (!thisObject)
470 return throwVMTypeError(exec);
471 return JSValue::encode(jsNumber(thisObject->getLength()));
472 }
473
474 Vector<int> m_vector;
475};
476
477class SimpleObject : public JSNonFinalObject {
478public:
479 SimpleObject(VM& vm, Structure* structure)
480 : Base(vm, structure)
481 {
482 }
483
484 typedef JSNonFinalObject Base;
485 static const bool needsDestruction = false;
486
487 static SimpleObject* create(VM& vm, JSGlobalObject* globalObject)
488 {
489 Structure* structure = createStructure(vm, globalObject, jsNull());
490 SimpleObject* simpleObject = new (NotNull, allocateCell<SimpleObject>(vm.heap, sizeof(SimpleObject))) SimpleObject(vm, structure);
491 simpleObject->finishCreation(vm);
492 return simpleObject;
493 }
494
495 static void visitChildren(JSCell* cell, SlotVisitor& visitor)
496 {
497 SimpleObject* thisObject = jsCast<SimpleObject*>(cell);
498 ASSERT_GC_OBJECT_INHERITS(thisObject, info());
499 Base::visitChildren(thisObject, visitor);
500 visitor.append(&thisObject->m_hiddenValue);
501 }
502
503 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
504 {
505 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
506 }
507
508 JSValue hiddenValue()
509 {
510 return m_hiddenValue.get();
511 }
512
513 void setHiddenValue(VM& vm, JSValue value)
514 {
515 ASSERT(value.isCell());
516 m_hiddenValue.set(vm, this, value);
517 }
518
519 DECLARE_INFO;
520
521private:
522 WriteBarrier<JSC::Unknown> m_hiddenValue;
523};
524
525
526const ClassInfo Element::s_info = { "Element", &Base::s_info, 0, CREATE_METHOD_TABLE(Element) };
527const ClassInfo Masquerader::s_info = { "Masquerader", &Base::s_info, 0, CREATE_METHOD_TABLE(Masquerader) };
528const ClassInfo Root::s_info = { "Root", &Base::s_info, 0, CREATE_METHOD_TABLE(Root) };
529const ClassInfo ImpureGetter::s_info = { "ImpureGetter", &Base::s_info, 0, CREATE_METHOD_TABLE(ImpureGetter) };
530const ClassInfo CustomGetter::s_info = { "CustomGetter", &Base::s_info, 0, CREATE_METHOD_TABLE(CustomGetter) };
531const ClassInfo RuntimeArray::s_info = { "RuntimeArray", &Base::s_info, 0, CREATE_METHOD_TABLE(RuntimeArray) };
532const ClassInfo SimpleObject::s_info = { "SimpleObject", &Base::s_info, 0, CREATE_METHOD_TABLE(SimpleObject) };
533
534ElementHandleOwner* Element::handleOwner()
535{
536 static ElementHandleOwner* owner = 0;
537 if (!owner)
538 owner = new ElementHandleOwner();
539 return owner;
540}
541
542void Element::finishCreation(VM& vm, Root* root)
543{
544 Base::finishCreation(vm);
545 setRoot(vm, root);
546 m_root->setElement(this);
547}
548
549}
550
551static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer);
552
553static EncodedJSValue JSC_HOST_CALL functionCreateProxy(ExecState*);
554static EncodedJSValue JSC_HOST_CALL functionCreateRuntimeArray(ExecState*);
555static EncodedJSValue JSC_HOST_CALL functionCreateImpureGetter(ExecState*);
556static EncodedJSValue JSC_HOST_CALL functionCreateCustomGetterObject(ExecState*);
557static EncodedJSValue JSC_HOST_CALL functionCreateBuiltin(ExecState*);
558static EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState*);
559static EncodedJSValue JSC_HOST_CALL functionSetImpureGetterDelegate(ExecState*);
560
561static EncodedJSValue JSC_HOST_CALL functionSetElementRoot(ExecState*);
562static EncodedJSValue JSC_HOST_CALL functionCreateRoot(ExecState*);
563static EncodedJSValue JSC_HOST_CALL functionCreateElement(ExecState*);
564static EncodedJSValue JSC_HOST_CALL functionGetElement(ExecState*);
565static EncodedJSValue JSC_HOST_CALL functionCreateSimpleObject(ExecState*);
566static EncodedJSValue JSC_HOST_CALL functionGetHiddenValue(ExecState*);
567static EncodedJSValue JSC_HOST_CALL functionSetHiddenValue(ExecState*);
568static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
569static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
570static EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState*);
571static EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState*);
572static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
573static EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState*);
574static EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState*);
575static EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState*);
576static EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*);
577static EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState*);
578static EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState*);
579static EncodedJSValue JSC_HOST_CALL functionGetGetterSetter(ExecState*);
580#ifndef NDEBUG
581static EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState*);
582#endif
583static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
584static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
585static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
586static EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState*);
587static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
588static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
589static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
590static EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState*);
591static EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState*);
592static EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState*);
593static EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState*);
594static EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState*);
595static EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState*);
596static EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState*);
597static EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState*);
598static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
599static NO_RETURN_DUE_TO_CRASH EncodedJSValue JSC_HOST_CALL functionAbort(ExecState*);
600static EncodedJSValue JSC_HOST_CALL functionFalse1(ExecState*);
601static EncodedJSValue JSC_HOST_CALL functionFalse2(ExecState*);
602static EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*);
603static EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*);
604static EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState*);
605static EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*);
606static EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState*);
607static EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState*);
608static EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState*);
609static EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState*);
610static EncodedJSValue JSC_HOST_CALL functionFindTypeForExpression(ExecState*);
611static EncodedJSValue JSC_HOST_CALL functionReturnTypeFor(ExecState*);
612static EncodedJSValue JSC_HOST_CALL functionDumpBasicBlockExecutionRanges(ExecState*);
613static EncodedJSValue JSC_HOST_CALL functionHasBasicBlockExecuted(ExecState*);
614static EncodedJSValue JSC_HOST_CALL functionBasicBlockExecutionCount(ExecState*);
615static EncodedJSValue JSC_HOST_CALL functionEnableExceptionFuzz(ExecState*);
616static EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState*);
617static EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*);
618#if ENABLE(WEBASSEMBLY)
619static EncodedJSValue JSC_HOST_CALL functionLoadWebAssembly(ExecState*);
620#endif
621static EncodedJSValue JSC_HOST_CALL functionLoadModule(ExecState*);
622static EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState*);
623static EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*);
624static EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState*);
625#if ENABLE(SAMPLING_PROFILER)
626static EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState*);
627static EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState*);
628#endif
629
630#if ENABLE(SAMPLING_FLAGS)
631static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
632static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
633#endif
634
635static EncodedJSValue JSC_HOST_CALL functionShadowChickenFunctionsOnStack(ExecState*);
636static EncodedJSValue JSC_HOST_CALL functionSetGlobalConstRedeclarationShouldNotThrow(ExecState*);
637
638struct Script {
639 bool isFile;
640 char* argument;
641
642 Script(bool isFile, char *argument)
643 : isFile(isFile)
644 , argument(argument)
645 {
646 }
647};
648
649class CommandLine {
650public:
651 CommandLine(int argc, char** argv)
652 {
653 parseArguments(argc, argv);
654 }
655
656 bool m_interactive { false };
657 bool m_dump { false };
658 bool m_module { false };
659 bool m_exitCode { false };
660 Vector<Script> m_scripts;
661 Vector<String> m_arguments;
662 bool m_profile { false };
663 String m_profilerOutput;
664 bool m_dumpSamplingProfilerData { false };
665
666 void parseArguments(int, char**);
667};
668
669static const char interactivePrompt[] = ">>> ";
670
671class StopWatch {
672public:
673 void start();
674 void stop();
675 long getElapsedMS(); // call stop() first
676
677private:
678 double m_startTime;
679 double m_stopTime;
680};
681
682void StopWatch::start()
683{
684 m_startTime = monotonicallyIncreasingTime();
685}
686
687void StopWatch::stop()
688{
689 m_stopTime = monotonicallyIncreasingTime();
690}
691
692long StopWatch::getElapsedMS()
693{
694 return static_cast<long>((m_stopTime - m_startTime) * 1000);
695}
696
697template<typename Vector>
698static inline String stringFromUTF(const Vector& utf8)
699{
700 return String::fromUTF8WithLatin1Fallback(utf8.data(), utf8.size());
701}
702
703template<typename Vector>
704static inline SourceCode jscSource(const Vector& utf8, const String& filename)
705{
706 String str = stringFromUTF(utf8);
707 return makeSource(str, filename);
708}
709
710class GlobalObject : public JSGlobalObject {
711private:
712 GlobalObject(VM&, Structure*);
713
714public:
715 typedef JSGlobalObject Base;
716
717 static GlobalObject* create(VM& vm, Structure* structure, const Vector<String>& arguments)
718 {
719 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(vm.heap)) GlobalObject(vm, structure);
720 object->finishCreation(vm, arguments);
721 vm.heap.addFinalizer(object, destroy);
722 return object;
723 }
724
725 static const bool needsDestruction = false;
726
727 DECLARE_INFO;
728 static const GlobalObjectMethodTable s_globalObjectMethodTable;
729
730 static Structure* createStructure(VM& vm, JSValue prototype)
731 {
732 return Structure::create(vm, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
733 }
734
735 static RuntimeFlags javaScriptRuntimeFlags(const JSGlobalObject*) { return RuntimeFlags::createAllEnabled(); }
736
737protected:
738 void finishCreation(VM& vm, const Vector<String>& arguments)
739 {
740 Base::finishCreation(vm);
741
742 addFunction(vm, "debug", functionDebug, 1);
743 addFunction(vm, "describe", functionDescribe, 1);
744 addFunction(vm, "describeArray", functionDescribeArray, 1);
745 addFunction(vm, "print", functionPrint, 1);
746 addFunction(vm, "quit", functionQuit, 0);
747 addFunction(vm, "abort", functionAbort, 0);
748 addFunction(vm, "gc", functionGCAndSweep, 0);
749 addFunction(vm, "fullGC", functionFullGC, 0);
750 addFunction(vm, "edenGC", functionEdenGC, 0);
751 addFunction(vm, "forceGCSlowPaths", functionForceGCSlowPaths, 0);
752 addFunction(vm, "gcHeapSize", functionHeapSize, 0);
753 addFunction(vm, "addressOf", functionAddressOf, 1);
754 addFunction(vm, "getGetterSetter", functionGetGetterSetter, 2);
755#ifndef NDEBUG
756 addFunction(vm, "dumpCallFrame", functionDumpCallFrame, 0);
757#endif
758 addFunction(vm, "version", functionVersion, 1);
759 addFunction(vm, "run", functionRun, 1);
760 addFunction(vm, "load", functionLoad, 1);
761 addFunction(vm, "readFile", functionReadFile, 1);
762 addFunction(vm, "checkSyntax", functionCheckSyntax, 1);
763 addFunction(vm, "jscStack", functionJSCStack, 1);
764 addFunction(vm, "readline", functionReadline, 0);
765 addFunction(vm, "preciseTime", functionPreciseTime, 0);
766 addFunction(vm, "neverInlineFunction", functionNeverInlineFunction, 1);
767 addFunction(vm, "noInline", functionNeverInlineFunction, 1);
768 addFunction(vm, "noDFG", functionNoDFG, 1);
769 addFunction(vm, "noFTL", functionNoFTL, 1);
770 addFunction(vm, "numberOfDFGCompiles", functionNumberOfDFGCompiles, 1);
771 addFunction(vm, "optimizeNextInvocation", functionOptimizeNextInvocation, 1);
772 addFunction(vm, "reoptimizationRetryCount", functionReoptimizationRetryCount, 1);
773 addFunction(vm, "transferArrayBuffer", functionTransferArrayBuffer, 1);
774 addFunction(vm, "failNextNewCodeBlock", functionFailNextNewCodeBlock, 1);
775#if ENABLE(SAMPLING_FLAGS)
776 addFunction(vm, "setSamplingFlags", functionSetSamplingFlags, 1);
777 addFunction(vm, "clearSamplingFlags", functionClearSamplingFlags, 1);
778#endif
779 addFunction(vm, "shadowChickenFunctionsOnStack", functionShadowChickenFunctionsOnStack, 0);
780 addFunction(vm, "setGlobalConstRedeclarationShouldNotThrow", functionSetGlobalConstRedeclarationShouldNotThrow, 0);
781 addConstructableFunction(vm, "Root", functionCreateRoot, 0);
782 addConstructableFunction(vm, "Element", functionCreateElement, 1);
783 addFunction(vm, "getElement", functionGetElement, 1);
784 addFunction(vm, "setElementRoot", functionSetElementRoot, 2);
785
786 addConstructableFunction(vm, "SimpleObject", functionCreateSimpleObject, 0);
787 addFunction(vm, "getHiddenValue", functionGetHiddenValue, 1);
788 addFunction(vm, "setHiddenValue", functionSetHiddenValue, 2);
789
790 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "DFGTrue"), 0, functionFalse1, DFGTrueIntrinsic, DontEnum);
791 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "OSRExit"), 0, functionUndefined1, OSRExitIntrinsic, DontEnum);
792 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isFinalTier"), 0, functionFalse2, IsFinalTierIntrinsic, DontEnum);
793 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "predictInt32"), 0, functionUndefined2, SetInt32HeapPredictionIntrinsic, DontEnum);
794 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "isInt32"), 0, functionIsInt32, CheckInt32Intrinsic, DontEnum);
795 putDirectNativeFunction(vm, this, Identifier::fromString(&vm, "fiatInt52"), 0, functionIdentity, FiatInt52Intrinsic, DontEnum);
796
797 addFunction(vm, "effectful42", functionEffectful42, 0);
798 addFunction(vm, "makeMasquerader", functionMakeMasquerader, 0);
799 addFunction(vm, "hasCustomProperties", functionHasCustomProperties, 0);
800
801 addFunction(vm, "createProxy", functionCreateProxy, 1);
802 addFunction(vm, "createRuntimeArray", functionCreateRuntimeArray, 0);
803
804 addFunction(vm, "createImpureGetter", functionCreateImpureGetter, 1);
805 addFunction(vm, "createCustomGetterObject", functionCreateCustomGetterObject, 0);
806 addFunction(vm, "createBuiltin", functionCreateBuiltin, 2);
807 addFunction(vm, "createGlobalObject", functionCreateGlobalObject, 0);
808 addFunction(vm, "setImpureGetterDelegate", functionSetImpureGetterDelegate, 2);
809
810 addFunction(vm, "dumpTypesForAllVariables", functionDumpTypesForAllVariables , 0);
811 addFunction(vm, "findTypeForExpression", functionFindTypeForExpression, 2);
812 addFunction(vm, "returnTypeFor", functionReturnTypeFor, 1);
813
814 addFunction(vm, "dumpBasicBlockExecutionRanges", functionDumpBasicBlockExecutionRanges , 0);
815 addFunction(vm, "hasBasicBlockExecuted", functionHasBasicBlockExecuted, 2);
816 addFunction(vm, "basicBlockExecutionCount", functionBasicBlockExecutionCount, 2);
817
818 addFunction(vm, "enableExceptionFuzz", functionEnableExceptionFuzz, 0);
819
820 addFunction(vm, "drainMicrotasks", functionDrainMicrotasks, 0);
821
822 addFunction(vm, "is32BitPlatform", functionIs32BitPlatform, 0);
823
824#if ENABLE(WEBASSEMBLY)
825 addFunction(vm, "loadWebAssembly", functionLoadWebAssembly, 3);
826#endif
827 addFunction(vm, "loadModule", functionLoadModule, 1);
828 addFunction(vm, "checkModuleSyntax", functionCheckModuleSyntax, 1);
829
830 addFunction(vm, "platformSupportsSamplingProfiler", functionPlatformSupportsSamplingProfiler, 0);
831 addFunction(vm, "generateHeapSnapshot", functionGenerateHeapSnapshot, 0);
832#if ENABLE(SAMPLING_PROFILER)
833 addFunction(vm, "startSamplingProfiler", functionStartSamplingProfiler, 0);
834 addFunction(vm, "samplingProfilerStackTraces", functionSamplingProfilerStackTraces, 0);
835#endif
836
837 if (!arguments.isEmpty()) {
838 JSArray* array = constructEmptyArray(globalExec(), 0);
839 for (size_t i = 0; i < arguments.size(); ++i)
840 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]));
841 putDirect(vm, Identifier::fromString(globalExec(), "arguments"), array);
842 }
843
844 putDirect(vm, Identifier::fromString(globalExec(), "console"), jsUndefined());
845 }
846
847 void addFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
848 {
849 Identifier identifier = Identifier::fromString(&vm, name);
850 putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function));
851 }
852
853 void addConstructableFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
854 {
855 Identifier identifier = Identifier::fromString(&vm, name);
856 putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function, NoIntrinsic, function));
857 }
858
859 static JSInternalPromise* moduleLoaderResolve(JSGlobalObject*, ExecState*, JSValue, JSValue);
860 static JSInternalPromise* moduleLoaderFetch(JSGlobalObject*, ExecState*, JSValue);
861};
862
863const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, nullptr, CREATE_METHOD_TABLE(GlobalObject) };
864const GlobalObjectMethodTable GlobalObject::s_globalObjectMethodTable = { &allowsAccessFrom, &supportsLegacyProfiling, &supportsRichSourceInfo, &shouldInterruptScript, &javaScriptRuntimeFlags, 0, &shouldInterruptScriptBeforeTimeout, &moduleLoaderResolve, &moduleLoaderFetch, nullptr, nullptr, nullptr, nullptr };
865
866
867GlobalObject::GlobalObject(VM& vm, Structure* structure)
868 : JSGlobalObject(vm, structure, &s_globalObjectMethodTable)
869{
870}
871
872static UChar pathSeparator()
873{
874#if OS(WINDOWS)
875 return '\\';
876#else
877 return '/';
878#endif
879}
880
881struct DirectoryName {
882 // In unix, it is "/". In Windows, it becomes a drive letter like "C:\"
883 String rootName;
884
885 // If the directory name is "/home/WebKit", this becomes "home/WebKit". If the directory name is "/", this becomes "".
886 String queryName;
887};
888
889struct ModuleName {
890 ModuleName(const String& moduleName);
891
892 bool startsWithRoot() const
893 {
894 return !queries.isEmpty() && queries[0].isEmpty();
895 }
896
897 Vector<String> queries;
898};
899
900ModuleName::ModuleName(const String& moduleName)
901{
902 // A module name given from code is represented as the UNIX style path. Like, `./A/B.js`.
903 moduleName.split('/', true, queries);
904}
905
906static bool extractDirectoryName(const String& absolutePathToFile, DirectoryName& directoryName)
907{
908 size_t firstSeparatorPosition = absolutePathToFile.find(pathSeparator());
909 if (firstSeparatorPosition == notFound)
910 return false;
911 directoryName.rootName = absolutePathToFile.substring(0, firstSeparatorPosition + 1); // Include the separator.
912 size_t lastSeparatorPosition = absolutePathToFile.reverseFind(pathSeparator());
913 ASSERT_WITH_MESSAGE(lastSeparatorPosition != notFound, "If the separator is not found, this function already returns when performing the forward search.");
914 if (firstSeparatorPosition == lastSeparatorPosition)
915 directoryName.queryName = StringImpl::empty();
916 else {
917 size_t queryStartPosition = firstSeparatorPosition + 1;
918 size_t queryLength = lastSeparatorPosition - queryStartPosition; // Not include the last separator.
919 directoryName.queryName = absolutePathToFile.substring(queryStartPosition, queryLength);
920 }
921 return true;
922}
923
924static bool currentWorkingDirectory(DirectoryName& directoryName)
925{
926#if OS(WINDOWS)
927 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364934.aspx
928 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
929 // The _MAX_PATH in Windows is 260. If the path of the current working directory is longer than that, _getcwd truncates the result.
930 // And other I/O functions taking a path name also truncate it. To avoid this situation,
931 //
932 // (1). When opening the file in Windows for modules, we always use the abosolute path and add "\\?\" prefix to the path name.
933 // (2). When retrieving the current working directory, use GetCurrentDirectory instead of _getcwd.
934 //
935 // In the path utility functions inside the JSC shell, we does not handle the UNC and UNCW including the network host name.
936 DWORD bufferLength = ::GetCurrentDirectoryW(0, nullptr);
937 if (!bufferLength)
938 return false;
939 // In Windows, wchar_t is the UTF-16LE.
940 // https://msdn.microsoft.com/en-us/library/dd374081.aspx
941 // https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407.aspx
942 auto buffer = std::make_unique<wchar_t[]>(bufferLength);
943 DWORD lengthNotIncludingNull = ::GetCurrentDirectoryW(bufferLength, buffer.get());
944 static_assert(sizeof(wchar_t) == sizeof(UChar), "In Windows, both are UTF-16LE");
945 String directoryString = String(reinterpret_cast<UChar*>(buffer.get()));
946 // We don't support network path like \\host\share\<path name>.
947 if (directoryString.startsWith("\\\\"))
948 return false;
949#else
950 auto buffer = std::make_unique<char[]>(PATH_MAX);
951 if (!getcwd(buffer.get(), PATH_MAX))
952 return false;
953 String directoryString = String::fromUTF8(buffer.get());
954#endif
955 if (directoryString.isEmpty())
956 return false;
957
958 if (directoryString[directoryString.length() - 1] == pathSeparator())
959 return extractDirectoryName(directoryString, directoryName);
960 // Append the seperator to represents the file name. extractDirectoryName only accepts the absolute file name.
961 return extractDirectoryName(makeString(directoryString, pathSeparator()), directoryName);
962}
963
964static String resolvePath(const DirectoryName& directoryName, const ModuleName& moduleName)
965{
966 Vector<String> directoryPieces;
967 directoryName.queryName.split(pathSeparator(), false, directoryPieces);
968
969 // Only first '/' is recognized as the path from the root.
970 if (moduleName.startsWithRoot())
971 directoryPieces.clear();
972
973 for (const auto& query : moduleName.queries) {
974 if (query == String(ASCIILiteral(".."))) {
975 if (!directoryPieces.isEmpty())
976 directoryPieces.removeLast();
977 } else if (!query.isEmpty() && query != String(ASCIILiteral(".")))
978 directoryPieces.append(query);
979 }
980
981 StringBuilder builder;
982 builder.append(directoryName.rootName);
983 for (size_t i = 0; i < directoryPieces.size(); ++i) {
984 builder.append(directoryPieces[i]);
985 if (i + 1 != directoryPieces.size())
986 builder.append(pathSeparator());
987 }
988 return builder.toString();
989}
990
991JSInternalPromise* GlobalObject::moduleLoaderResolve(JSGlobalObject* globalObject, ExecState* exec, JSValue keyValue, JSValue referrerValue)
992{
993 JSInternalPromiseDeferred* deferred = JSInternalPromiseDeferred::create(exec, globalObject);
994 const Identifier key = keyValue.toPropertyKey(exec);
995 if (exec->hadException()) {
996 JSValue exception = exec->exception();
997 exec->clearException();
998 return deferred->reject(exec, exception);
999 }
1000
1001 if (key.isSymbol())
1002 return deferred->resolve(exec, keyValue);
1003
1004 DirectoryName directoryName;
1005 if (referrerValue.isUndefined()) {
1006 if (!currentWorkingDirectory(directoryName))
1007 return deferred->reject(exec, createError(exec, ASCIILiteral("Could not resolve the current working directory.")));
1008 } else {
1009 const Identifier referrer = referrerValue.toPropertyKey(exec);
1010 if (exec->hadException()) {
1011 JSValue exception = exec->exception();
1012 exec->clearException();
1013 return deferred->reject(exec, exception);
1014 }
1015 if (referrer.isSymbol()) {
1016 if (!currentWorkingDirectory(directoryName))
1017 return deferred->reject(exec, createError(exec, ASCIILiteral("Could not resolve the current working directory.")));
1018 } else {
1019 // If the referrer exists, we assume that the referrer is the correct absolute path.
1020 if (!extractDirectoryName(referrer.impl(), directoryName))
1021 return deferred->reject(exec, createError(exec, makeString("Could not resolve the referrer name '", String(referrer.impl()), "'.")));
1022 }
1023 }
1024
1025 return deferred->resolve(exec, jsString(exec, resolvePath(directoryName, ModuleName(key.impl()))));
1026}
1027
1028static void convertShebangToJSComment(Vector<char>& buffer)
1029{
1030 if (buffer.size() >= 2) {
1031 if (buffer[0] == '#' && buffer[1] == '!')
1032 buffer[0] = buffer[1] = '/';
1033 }
1034}
1035
1036static bool fillBufferWithContentsOfFile(FILE* file, Vector<char>& buffer)
1037{
1038 fseek(file, 0, SEEK_END);
1039 size_t bufferCapacity = ftell(file);
1040 fseek(file, 0, SEEK_SET);
1041 buffer.resize(bufferCapacity);
1042 size_t readSize = fread(buffer.data(), 1, buffer.size(), file);
1043 return readSize == buffer.size();
1044}
1045
1046static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer)
1047{
1048 FILE* f = fopen(fileName.utf8().data(), "rb");
1049 if (!f) {
1050 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1051 return false;
1052 }
1053
1054 bool result = fillBufferWithContentsOfFile(f, buffer);
1055 fclose(f);
1056
1057 return result;
1058}
1059
1060static bool fetchScriptFromLocalFileSystem(const String& fileName, Vector<char>& buffer)
1061{
1062 if (!fillBufferWithContentsOfFile(fileName, buffer))
1063 return false;
1064 convertShebangToJSComment(buffer);
1065 return true;
1066}
1067
1068static bool fetchModuleFromLocalFileSystem(const String& fileName, Vector<char>& buffer)
1069{
1070 // We assume that fileName is always an absolute path.
1071#if OS(WINDOWS)
1072 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#maxpath
1073 // Use long UNC to pass the long path name to the Windows APIs.
1074 String longUNCPathName = WTF::makeString("\\\\?\\", fileName);
1075 static_assert(sizeof(wchar_t) == sizeof(UChar), "In Windows, both are UTF-16LE");
1076 auto utf16Vector = longUNCPathName.charactersWithNullTermination();
1077 FILE* f = _wfopen(reinterpret_cast<wchar_t*>(utf16Vector.data()), L"rb");
1078#else
1079 FILE* f = fopen(fileName.utf8().data(), "r");
1080#endif
1081 if (!f) {
1082 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1083 return false;
1084 }
1085
1086 bool result = fillBufferWithContentsOfFile(f, buffer);
1087 if (result)
1088 convertShebangToJSComment(buffer);
1089 fclose(f);
1090
1091 return result;
1092}
1093
1094JSInternalPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalObject, ExecState* exec, JSValue key)
1095{
1096 JSInternalPromiseDeferred* deferred = JSInternalPromiseDeferred::create(exec, globalObject);
1097 String moduleKey = key.toString(exec)->value(exec);
1098 if (exec->hadException()) {
1099 JSValue exception = exec->exception();
1100 exec->clearException();
1101 return deferred->reject(exec, exception);
1102 }
1103
1104 // Here, now we consider moduleKey as the fileName.
1105 Vector<char> utf8;
1106 if (!fetchModuleFromLocalFileSystem(moduleKey, utf8))
1107 return deferred->reject(exec, createError(exec, makeString("Could not open file '", moduleKey, "'.")));
1108
1109 return deferred->resolve(exec, jsString(exec, stringFromUTF(utf8)));
1110}
1111
1112
1113EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
1114{
1115 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1116 if (i)
1117 putchar(' ');
1118
1119 printf("%s", exec->uncheckedArgument(i).toString(exec)->view(exec).get().utf8().data());
1120 }
1121
1122 putchar('\n');
1123 fflush(stdout);
1124 return JSValue::encode(jsUndefined());
1125}
1126
1127#ifndef NDEBUG
1128EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState* exec)
1129{
1130 VMEntryFrame* topVMEntryFrame = exec->vm().topVMEntryFrame;
1131 ExecState* callerFrame = exec->callerFrame(topVMEntryFrame);
1132 if (callerFrame)
1133 exec->vm().interpreter->dumpCallFrame(callerFrame);
1134 return JSValue::encode(jsUndefined());
1135}
1136#endif
1137
1138EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
1139{
1140 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec)->view(exec).get().utf8().data());
1141 return JSValue::encode(jsUndefined());
1142}
1143
1144EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState* exec)
1145{
1146 if (exec->argumentCount() < 1)
1147 return JSValue::encode(jsUndefined());
1148 return JSValue::encode(jsString(exec, toString(exec->argument(0))));
1149}
1150
1151EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState* exec)
1152{
1153 if (exec->argumentCount() < 1)
1154 return JSValue::encode(jsUndefined());
1155 JSObject* object = jsDynamicCast<JSObject*>(exec->argument(0));
1156 if (!object)
1157 return JSValue::encode(jsNontrivialString(exec, ASCIILiteral("<not object>")));
1158 return JSValue::encode(jsNontrivialString(exec, toString("<Public length: ", object->getArrayLength(), "; vector length: ", object->getVectorLength(), ">")));
1159}
1160
1161class FunctionJSCStackFunctor {
1162public:
1163 FunctionJSCStackFunctor(StringBuilder& trace)
1164 : m_trace(trace)
1165 {
1166 }
1167
1168 StackVisitor::Status operator()(StackVisitor& visitor) const
1169 {
1170 m_trace.append(String::format(" %zu %s\n", visitor->index(), visitor->toString().utf8().data()));
1171 return StackVisitor::Continue;
1172 }
1173
1174private:
1175 StringBuilder& m_trace;
1176};
1177
1178EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
1179{
1180 StringBuilder trace;
1181 trace.appendLiteral("--> Stack trace:\n");
1182
1183 FunctionJSCStackFunctor functor(trace);
1184 exec->iterate(functor);
1185 fprintf(stderr, "%s", trace.toString().utf8().data());
1186 return JSValue::encode(jsUndefined());
1187}
1188
1189EncodedJSValue JSC_HOST_CALL functionCreateRoot(ExecState* exec)
1190{
1191 JSLockHolder lock(exec);
1192 return JSValue::encode(Root::create(exec->vm(), exec->lexicalGlobalObject()));
1193}
1194
1195EncodedJSValue JSC_HOST_CALL functionCreateElement(ExecState* exec)
1196{
1197 JSLockHolder lock(exec);
1198 Root* root = jsDynamicCast<Root*>(exec->argument(0));
1199 if (!root)
1200 return JSValue::encode(jsUndefined());
1201 return JSValue::encode(Element::create(exec->vm(), exec->lexicalGlobalObject(), root));
1202}
1203
1204EncodedJSValue JSC_HOST_CALL functionGetElement(ExecState* exec)
1205{
1206 JSLockHolder lock(exec);
1207 Root* root = jsDynamicCast<Root*>(exec->argument(0));
1208 if (!root)
1209 return JSValue::encode(jsUndefined());
1210 Element* result = root->element();
1211 return JSValue::encode(result ? result : jsUndefined());
1212}
1213
1214EncodedJSValue JSC_HOST_CALL functionSetElementRoot(ExecState* exec)
1215{
1216 JSLockHolder lock(exec);
1217 Element* element = jsDynamicCast<Element*>(exec->argument(0));
1218 Root* root = jsDynamicCast<Root*>(exec->argument(1));
1219 if (element && root)
1220 element->setRoot(exec->vm(), root);
1221 return JSValue::encode(jsUndefined());
1222}
1223
1224EncodedJSValue JSC_HOST_CALL functionCreateSimpleObject(ExecState* exec)
1225{
1226 JSLockHolder lock(exec);
1227 return JSValue::encode(SimpleObject::create(exec->vm(), exec->lexicalGlobalObject()));
1228}
1229
1230EncodedJSValue JSC_HOST_CALL functionGetHiddenValue(ExecState* exec)
1231{
1232 JSLockHolder lock(exec);
1233 SimpleObject* simpleObject = jsCast<SimpleObject*>(exec->argument(0).asCell());
1234 return JSValue::encode(simpleObject->hiddenValue());
1235}
1236
1237EncodedJSValue JSC_HOST_CALL functionSetHiddenValue(ExecState* exec)
1238{
1239 JSLockHolder lock(exec);
1240 SimpleObject* simpleObject = jsCast<SimpleObject*>(exec->argument(0).asCell());
1241 JSValue value = exec->argument(1);
1242 simpleObject->setHiddenValue(exec->vm(), value);
1243 return JSValue::encode(jsUndefined());
1244}
1245
1246EncodedJSValue JSC_HOST_CALL functionCreateProxy(ExecState* exec)
1247{
1248 JSLockHolder lock(exec);
1249 JSValue target = exec->argument(0);
1250 if (!target.isObject())
1251 return JSValue::encode(jsUndefined());
1252 JSObject* jsTarget = asObject(target.asCell());
1253 Structure* structure = JSProxy::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsTarget->getPrototypeDirect(), ImpureProxyType);
1254 JSProxy* proxy = JSProxy::create(exec->vm(), structure, jsTarget);
1255 return JSValue::encode(proxy);
1256}
1257
1258EncodedJSValue JSC_HOST_CALL functionCreateRuntimeArray(ExecState* exec)
1259{
1260 JSLockHolder lock(exec);
1261 RuntimeArray* array = RuntimeArray::create(exec);
1262 return JSValue::encode(array);
1263}
1264
1265EncodedJSValue JSC_HOST_CALL functionCreateImpureGetter(ExecState* exec)
1266{
1267 JSLockHolder lock(exec);
1268 JSValue target = exec->argument(0);
1269 JSObject* delegate = nullptr;
1270 if (target.isObject())
1271 delegate = asObject(target.asCell());
1272 Structure* structure = ImpureGetter::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
1273 ImpureGetter* result = ImpureGetter::create(exec->vm(), structure, delegate);
1274 return JSValue::encode(result);
1275}
1276
1277EncodedJSValue JSC_HOST_CALL functionCreateCustomGetterObject(ExecState* exec)
1278{
1279 JSLockHolder lock(exec);
1280 Structure* structure = CustomGetter::createStructure(exec->vm(), exec->lexicalGlobalObject(), jsNull());
1281 CustomGetter* result = CustomGetter::create(exec->vm(), structure);
1282 return JSValue::encode(result);
1283}
1284
1285EncodedJSValue JSC_HOST_CALL functionSetImpureGetterDelegate(ExecState* exec)
1286{
1287 JSLockHolder lock(exec);
1288 JSValue base = exec->argument(0);
1289 if (!base.isObject())
1290 return JSValue::encode(jsUndefined());
1291 JSValue delegate = exec->argument(1);
1292 if (!delegate.isObject())
1293 return JSValue::encode(jsUndefined());
1294 ImpureGetter* impureGetter = jsCast<ImpureGetter*>(asObject(base.asCell()));
1295 impureGetter->setDelegate(exec->vm(), asObject(delegate.asCell()));
1296 return JSValue::encode(jsUndefined());
1297}
1298
1299EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState* exec)
1300{
1301 JSLockHolder lock(exec);
1302 exec->heap()->collectAllGarbage();
1303 return JSValue::encode(jsNumber(exec->heap()->sizeAfterLastFullCollection()));
1304}
1305
1306EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState* exec)
1307{
1308 JSLockHolder lock(exec);
1309 exec->heap()->collect(FullCollection);
1310 return JSValue::encode(jsNumber(exec->heap()->sizeAfterLastFullCollection()));
1311}
1312
1313EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState* exec)
1314{
1315 JSLockHolder lock(exec);
1316 exec->heap()->collect(EdenCollection);
1317 return JSValue::encode(jsNumber(exec->heap()->sizeAfterLastEdenCollection()));
1318}
1319
1320EncodedJSValue JSC_HOST_CALL functionForceGCSlowPaths(ExecState*)
1321{
1322 // It's best for this to be the first thing called in the
1323 // JS program so the option is set to true before we JIT.
1324 Options::forceGCSlowPaths() = true;
1325 return JSValue::encode(jsUndefined());
1326}
1327
1328EncodedJSValue JSC_HOST_CALL functionHeapSize(ExecState* exec)
1329{
1330 JSLockHolder lock(exec);
1331 return JSValue::encode(jsNumber(exec->heap()->size()));
1332}
1333
1334// This function is not generally very helpful in 64-bit code as the tag and payload
1335// share a register. But in 32-bit JITed code the tag may not be checked if an
1336// optimization removes type checking requirements, such as in ===.
1337EncodedJSValue JSC_HOST_CALL functionAddressOf(ExecState* exec)
1338{
1339 JSValue value = exec->argument(0);
1340 if (!value.isCell())
1341 return JSValue::encode(jsUndefined());
1342 // Need to cast to uint64_t so bitwise_cast will play along.
1343 uint64_t asNumber = reinterpret_cast<uint64_t>(value.asCell());
1344 EncodedJSValue returnValue = JSValue::encode(jsNumber(bitwise_cast<double>(asNumber)));
1345 return returnValue;
1346}
1347
1348static EncodedJSValue JSC_HOST_CALL functionGetGetterSetter(ExecState* exec)
1349{
1350 JSValue value = exec->argument(0);
1351 if (!value.isObject())
1352 return JSValue::encode(jsUndefined());
1353
1354 JSValue property = exec->argument(1);
1355 if (!property.isString())
1356 return JSValue::encode(jsUndefined());
1357
1358 Identifier ident = Identifier::fromString(&exec->vm(), property.toString(exec)->value(exec));
1359
1360 PropertySlot slot(value, PropertySlot::InternalMethodType::VMInquiry);
1361 value.getPropertySlot(exec, ident, slot);
1362
1363 JSValue result;
1364 if (slot.isCacheableGetter())
1365 result = slot.getterSetter();
1366 else
1367 result = jsNull();
1368
1369 return JSValue::encode(result);
1370}
1371
1372EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
1373{
1374 // We need this function for compatibility with the Mozilla JS tests but for now
1375 // we don't actually do any version-specific handling
1376 return JSValue::encode(jsUndefined());
1377}
1378
1379EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
1380{
1381 String fileName = exec->argument(0).toString(exec)->value(exec);
1382 if (exec->hadException())
1383 return JSValue::encode(jsUndefined());
1384 Vector<char> script;
1385 if (!fetchScriptFromLocalFileSystem(fileName, script))
1386 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Could not open file."))));
1387
1388 GlobalObject* globalObject = GlobalObject::create(exec->vm(), GlobalObject::createStructure(exec->vm(), jsNull()), Vector<String>());
1389
1390 JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
1391 for (unsigned i = 1; i < exec->argumentCount(); ++i)
1392 array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
1393 globalObject->putDirect(
1394 exec->vm(), Identifier::fromString(globalObject->globalExec(), "arguments"), array);
1395
1396 NakedPtr<Exception> exception;
1397 StopWatch stopWatch;
1398 stopWatch.start();
1399 evaluate(globalObject->globalExec(), jscSource(script, fileName), JSValue(), exception);
1400 stopWatch.stop();
1401
1402 if (exception) {
1403 exec->vm().throwException(globalObject->globalExec(), exception);
1404 return JSValue::encode(jsUndefined());
1405 }
1406
1407 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1408}
1409
1410EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
1411{
1412 String fileName = exec->argument(0).toString(exec)->value(exec);
1413 if (exec->hadException())
1414 return JSValue::encode(jsUndefined());
1415 Vector<char> script;
1416 if (!fetchScriptFromLocalFileSystem(fileName, script))
1417 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Could not open file."))));
1418
1419 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1420
1421 NakedPtr<Exception> evaluationException;
1422 JSValue result = evaluate(globalObject->globalExec(), jscSource(script, fileName), JSValue(), evaluationException);
1423 if (evaluationException)
1424 exec->vm().throwException(exec, evaluationException);
1425 return JSValue::encode(result);
1426}
1427
1428EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState* exec)
1429{
1430 String fileName = exec->argument(0).toString(exec)->value(exec);
1431 if (exec->hadException())
1432 return JSValue::encode(jsUndefined());
1433 Vector<char> script;
1434 if (!fillBufferWithContentsOfFile(fileName, script))
1435 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Could not open file."))));
1436
1437 return JSValue::encode(jsString(exec, stringFromUTF(script)));
1438}
1439
1440EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
1441{
1442 String fileName = exec->argument(0).toString(exec)->value(exec);
1443 if (exec->hadException())
1444 return JSValue::encode(jsUndefined());
1445 Vector<char> script;
1446 if (!fetchScriptFromLocalFileSystem(fileName, script))
1447 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Could not open file."))));
1448
1449 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
1450
1451 StopWatch stopWatch;
1452 stopWatch.start();
1453
1454 JSValue syntaxException;
1455 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script, fileName), &syntaxException);
1456 stopWatch.stop();
1457
1458 if (!validSyntax)
1459 exec->vm().throwException(exec, syntaxException);
1460 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1461}
1462
1463#if ENABLE(SAMPLING_FLAGS)
1464EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
1465{
1466 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1467 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
1468 if ((flag >= 1) && (flag <= 32))
1469 SamplingFlags::setFlag(flag);
1470 }
1471 return JSValue::encode(jsNull());
1472}
1473
1474EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
1475{
1476 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
1477 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
1478 if ((flag >= 1) && (flag <= 32))
1479 SamplingFlags::clearFlag(flag);
1480 }
1481 return JSValue::encode(jsNull());
1482}
1483#endif
1484
1485EncodedJSValue JSC_HOST_CALL functionShadowChickenFunctionsOnStack(ExecState* exec)
1486{
1487 return JSValue::encode(exec->vm().shadowChicken().functionsOnStack(exec));
1488}
1489
1490EncodedJSValue JSC_HOST_CALL functionSetGlobalConstRedeclarationShouldNotThrow(ExecState* exec)
1491{
1492 exec->vm().setGlobalConstRedeclarationShouldThrow(false);
1493 return JSValue::encode(jsUndefined());
1494}
1495
1496EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
1497{
1498 Vector<char, 256> line;
1499 int c;
1500 while ((c = getchar()) != EOF) {
1501 // FIXME: Should we also break on \r?
1502 if (c == '\n')
1503 break;
1504 line.append(c);
1505 }
1506 line.append('\0');
1507 return JSValue::encode(jsString(exec, line.data()));
1508}
1509
1510EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
1511{
1512 return JSValue::encode(jsNumber(currentTime()));
1513}
1514
1515EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState* exec)
1516{
1517 return JSValue::encode(setNeverInline(exec));
1518}
1519
1520EncodedJSValue JSC_HOST_CALL functionNoDFG(ExecState* exec)
1521{
1522 return JSValue::encode(setNeverOptimize(exec));
1523}
1524
1525EncodedJSValue JSC_HOST_CALL functionNoFTL(ExecState* exec)
1526{
1527 if (JSFunction* function = jsDynamicCast<JSFunction*>(exec->argument(0))) {
1528 FunctionExecutable* executable = function->jsExecutable();
1529 executable->setNeverFTLOptimize(true);
1530 }
1531
1532 return JSValue::encode(jsUndefined());
1533}
1534
1535EncodedJSValue JSC_HOST_CALL functionOptimizeNextInvocation(ExecState* exec)
1536{
1537 return JSValue::encode(optimizeNextInvocation(exec));
1538}
1539
1540EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState* exec)
1541{
1542 return JSValue::encode(numberOfDFGCompiles(exec));
1543}
1544
1545EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState* exec)
1546{
1547 if (exec->argumentCount() < 1)
1548 return JSValue::encode(jsUndefined());
1549
1550 CodeBlock* block = getSomeBaselineCodeBlockForFunction(exec->argument(0));
1551 if (!block)
1552 return JSValue::encode(jsNumber(0));
1553
1554 return JSValue::encode(jsNumber(block->reoptimizationRetryCounter()));
1555}
1556
1557EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState* exec)
1558{
1559 if (exec->argumentCount() < 1)
1560 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Not enough arguments"))));
1561
1562 JSArrayBuffer* buffer = jsDynamicCast<JSArrayBuffer*>(exec->argument(0));
1563 if (!buffer)
1564 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Expected an array buffer"))));
1565
1566 ArrayBufferContents dummyContents;
1567 buffer->impl()->transfer(dummyContents);
1568
1569 return JSValue::encode(jsUndefined());
1570}
1571
1572EncodedJSValue JSC_HOST_CALL functionFailNextNewCodeBlock(ExecState* exec)
1573{
1574 exec->vm().setFailNextNewCodeBlock();
1575 return JSValue::encode(jsUndefined());
1576}
1577
1578EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*)
1579{
1580 jscExit(EXIT_SUCCESS);
1581
1582#if COMPILER(MSVC)
1583 // Without this, Visual Studio will complain that this method does not return a value.
1584 return JSValue::encode(jsUndefined());
1585#endif
1586}
1587
1588EncodedJSValue JSC_HOST_CALL functionAbort(ExecState*)
1589{
1590 CRASH();
1591}
1592
1593EncodedJSValue JSC_HOST_CALL functionFalse1(ExecState*) { return JSValue::encode(jsBoolean(false)); }
1594EncodedJSValue JSC_HOST_CALL functionFalse2(ExecState*) { return JSValue::encode(jsBoolean(false)); }
1595
1596EncodedJSValue JSC_HOST_CALL functionUndefined1(ExecState*) { return JSValue::encode(jsUndefined()); }
1597EncodedJSValue JSC_HOST_CALL functionUndefined2(ExecState*) { return JSValue::encode(jsUndefined()); }
1598EncodedJSValue JSC_HOST_CALL functionIsInt32(ExecState* exec)
1599{
1600 for (size_t i = 0; i < exec->argumentCount(); ++i) {
1601 if (!exec->argument(i).isInt32())
1602 return JSValue::encode(jsBoolean(false));
1603 }
1604 return JSValue::encode(jsBoolean(true));
1605}
1606
1607EncodedJSValue JSC_HOST_CALL functionIdentity(ExecState* exec) { return JSValue::encode(exec->argument(0)); }
1608
1609EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*)
1610{
1611 return JSValue::encode(jsNumber(42));
1612}
1613
1614EncodedJSValue JSC_HOST_CALL functionMakeMasquerader(ExecState* exec)
1615{
1616 return JSValue::encode(Masquerader::create(exec->vm(), exec->lexicalGlobalObject()));
1617}
1618
1619EncodedJSValue JSC_HOST_CALL functionHasCustomProperties(ExecState* exec)
1620{
1621 JSValue value = exec->argument(0);
1622 if (value.isObject())
1623 return JSValue::encode(jsBoolean(asObject(value)->hasCustomProperties()));
1624 return JSValue::encode(jsBoolean(false));
1625}
1626
1627EncodedJSValue JSC_HOST_CALL functionDumpTypesForAllVariables(ExecState* exec)
1628{
1629 exec->vm().dumpTypeProfilerData();
1630 return JSValue::encode(jsUndefined());
1631}
1632
1633EncodedJSValue JSC_HOST_CALL functionFindTypeForExpression(ExecState* exec)
1634{
1635 RELEASE_ASSERT(exec->vm().typeProfiler());
1636 exec->vm().typeProfilerLog()->processLogEntries(ASCIILiteral("jsc Testing API: functionFindTypeForExpression"));
1637
1638 JSValue functionValue = exec->argument(0);
1639 RELEASE_ASSERT(functionValue.isFunction());
1640 FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(functionValue.asCell()->getObject()))->jsExecutable();
1641
1642 RELEASE_ASSERT(exec->argument(1).isString());
1643 String substring = exec->argument(1).getString(exec);
1644 String sourceCodeText = executable->source().view().toString();
1645 unsigned offset = static_cast<unsigned>(sourceCodeText.find(substring) + executable->source().startOffset());
1646
1647 String jsonString = exec->vm().typeProfiler()->typeInformationForExpressionAtOffset(TypeProfilerSearchDescriptorNormal, offset, executable->sourceID(), exec->vm());
1648 return JSValue::encode(JSONParse(exec, jsonString));
1649}
1650
1651EncodedJSValue JSC_HOST_CALL functionReturnTypeFor(ExecState* exec)
1652{
1653 RELEASE_ASSERT(exec->vm().typeProfiler());
1654 exec->vm().typeProfilerLog()->processLogEntries(ASCIILiteral("jsc Testing API: functionReturnTypeFor"));
1655
1656 JSValue functionValue = exec->argument(0);
1657 RELEASE_ASSERT(functionValue.isFunction());
1658 FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(functionValue.asCell()->getObject()))->jsExecutable();
1659
1660 unsigned offset = executable->typeProfilingStartOffset();
1661 String jsonString = exec->vm().typeProfiler()->typeInformationForExpressionAtOffset(TypeProfilerSearchDescriptorFunctionReturn, offset, executable->sourceID(), exec->vm());
1662 return JSValue::encode(JSONParse(exec, jsonString));
1663}
1664
1665EncodedJSValue JSC_HOST_CALL functionDumpBasicBlockExecutionRanges(ExecState* exec)
1666{
1667 RELEASE_ASSERT(exec->vm().controlFlowProfiler());
1668 exec->vm().controlFlowProfiler()->dumpData();
1669 return JSValue::encode(jsUndefined());
1670}
1671
1672EncodedJSValue JSC_HOST_CALL functionHasBasicBlockExecuted(ExecState* exec)
1673{
1674 RELEASE_ASSERT(exec->vm().controlFlowProfiler());
1675
1676 JSValue functionValue = exec->argument(0);
1677 RELEASE_ASSERT(functionValue.isFunction());
1678 FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(functionValue.asCell()->getObject()))->jsExecutable();
1679
1680 RELEASE_ASSERT(exec->argument(1).isString());
1681 String substring = exec->argument(1).getString(exec);
1682 String sourceCodeText = executable->source().view().toString();
1683 RELEASE_ASSERT(sourceCodeText.contains(substring));
1684 int offset = sourceCodeText.find(substring) + executable->source().startOffset();
1685
1686 bool hasExecuted = exec->vm().controlFlowProfiler()->hasBasicBlockAtTextOffsetBeenExecuted(offset, executable->sourceID(), exec->vm());
1687 return JSValue::encode(jsBoolean(hasExecuted));
1688}
1689
1690EncodedJSValue JSC_HOST_CALL functionBasicBlockExecutionCount(ExecState* exec)
1691{
1692 RELEASE_ASSERT(exec->vm().controlFlowProfiler());
1693
1694 JSValue functionValue = exec->argument(0);
1695 RELEASE_ASSERT(functionValue.isFunction());
1696 FunctionExecutable* executable = (jsDynamicCast<JSFunction*>(functionValue.asCell()->getObject()))->jsExecutable();
1697
1698 RELEASE_ASSERT(exec->argument(1).isString());
1699 String substring = exec->argument(1).getString(exec);
1700 String sourceCodeText = executable->source().view().toString();
1701 RELEASE_ASSERT(sourceCodeText.contains(substring));
1702 int offset = sourceCodeText.find(substring) + executable->source().startOffset();
1703
1704 size_t executionCount = exec->vm().controlFlowProfiler()->basicBlockExecutionCountAtTextOffset(offset, executable->sourceID(), exec->vm());
1705 return JSValue::encode(JSValue(executionCount));
1706}
1707
1708EncodedJSValue JSC_HOST_CALL functionEnableExceptionFuzz(ExecState*)
1709{
1710 Options::useExceptionFuzz() = true;
1711 return JSValue::encode(jsUndefined());
1712}
1713
1714EncodedJSValue JSC_HOST_CALL functionDrainMicrotasks(ExecState* exec)
1715{
1716 exec->vm().drainMicrotasks();
1717 return JSValue::encode(jsUndefined());
1718}
1719
1720EncodedJSValue JSC_HOST_CALL functionIs32BitPlatform(ExecState*)
1721{
1722#if USE(JSVALUE64)
1723 return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
1724#else
1725 return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
1726#endif
1727}
1728
1729#if ENABLE(WEBASSEMBLY)
1730EncodedJSValue JSC_HOST_CALL functionLoadWebAssembly(ExecState* exec)
1731{
1732 String fileName = exec->argument(0).toString(exec)->value(exec);
1733 if (exec->hadException())
1734 return JSValue::encode(jsUndefined());
1735 Vector<char> buffer;
1736 if (!fillBufferWithContentsOfFile(fileName, buffer))
1737 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Could not open file."))));
1738 RefPtr<WebAssemblySourceProvider> sourceProvider = WebAssemblySourceProvider::create(reinterpret_cast<Vector<uint8_t>&>(buffer), fileName);
1739 SourceCode source(sourceProvider);
1740 JSObject* imports = exec->argument(1).getObject();
1741 JSArrayBuffer* arrayBuffer = jsDynamicCast<JSArrayBuffer*>(exec->argument(2));
1742
1743 String errorMessage;
1744 JSWASMModule* module = parseWebAssembly(exec, source, imports, arrayBuffer, errorMessage);
1745 if (!module)
1746 return JSValue::encode(exec->vm().throwException(exec, createSyntaxError(exec, errorMessage)));
1747 return JSValue::encode(module);
1748}
1749#endif
1750
1751EncodedJSValue JSC_HOST_CALL functionLoadModule(ExecState* exec)
1752{
1753 String fileName = exec->argument(0).toString(exec)->value(exec);
1754 if (exec->hadException())
1755 return JSValue::encode(jsUndefined());
1756 Vector<char> script;
1757 if (!fetchScriptFromLocalFileSystem(fileName, script))
1758 return JSValue::encode(exec->vm().throwException(exec, createError(exec, ASCIILiteral("Could not open file."))));
1759
1760 JSInternalPromise* promise = loadAndEvaluateModule(exec, fileName);
1761 if (exec->hadException())
1762 return JSValue::encode(jsUndefined());
1763
1764 JSValue error;
1765 JSFunction* errorHandler = JSNativeStdFunction::create(exec->vm(), exec->lexicalGlobalObject(), 1, String(), [&](ExecState* exec) {
1766 error = exec->argument(0);
1767 return JSValue::encode(jsUndefined());
1768 });
1769
1770 promise->then(exec, nullptr, errorHandler);
1771 exec->vm().drainMicrotasks();
1772 if (error)
1773 return JSValue::encode(exec->vm().throwException(exec, error));
1774 return JSValue::encode(jsUndefined());
1775}
1776
1777EncodedJSValue JSC_HOST_CALL functionCreateBuiltin(ExecState* exec)
1778{
1779 if (exec->argumentCount() < 1 || !exec->argument(0).isString())
1780 return JSValue::encode(jsUndefined());
1781
1782 String functionText = exec->argument(0).toString(exec)->value(exec);
1783 if (exec->hadException())
1784 return JSValue::encode(JSValue());
1785
1786 VM& vm = exec->vm();
1787 const SourceCode& source = makeSource(functionText);
1788 JSFunction* func = JSFunction::createBuiltinFunction(vm, createBuiltinExecutable(vm, source, Identifier::fromString(&vm, "foo"), ConstructorKind::None, ConstructAbility::CannotConstruct)->link(vm, source), exec->lexicalGlobalObject());
1789
1790 return JSValue::encode(func);
1791}
1792
1793EncodedJSValue JSC_HOST_CALL functionCreateGlobalObject(ExecState* exec)
1794{
1795 VM& vm = exec->vm();
1796 return JSValue::encode(GlobalObject::create(vm, GlobalObject::createStructure(vm, jsNull()), Vector<String>()));
1797}
1798
1799EncodedJSValue JSC_HOST_CALL functionCheckModuleSyntax(ExecState* exec)
1800{
1801 String source = exec->argument(0).toString(exec)->value(exec);
1802 if (exec->hadException())
1803 return JSValue::encode(jsUndefined());
1804
1805 StopWatch stopWatch;
1806 stopWatch.start();
1807
1808 ParserError error;
1809 bool validSyntax = checkModuleSyntax(exec, makeSource(source), error);
1810 stopWatch.stop();
1811
1812 if (!validSyntax)
1813 exec->vm().throwException(exec, jsNontrivialString(exec, toString("SyntaxError: ", error.message(), ":", error.line())));
1814 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
1815}
1816
1817EncodedJSValue JSC_HOST_CALL functionPlatformSupportsSamplingProfiler(ExecState*)
1818{
1819#if ENABLE(SAMPLING_PROFILER)
1820 return JSValue::encode(JSValue(JSC::JSValue::JSTrue));
1821#else
1822 return JSValue::encode(JSValue(JSC::JSValue::JSFalse));
1823#endif
1824}
1825
1826EncodedJSValue JSC_HOST_CALL functionGenerateHeapSnapshot(ExecState* exec)
1827{
1828 JSLockHolder lock(exec);
1829
1830 HeapSnapshotBuilder snapshotBuilder(exec->vm().ensureHeapProfiler());
1831 snapshotBuilder.buildSnapshot();
1832
1833 String jsonString = snapshotBuilder.json();
1834 EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
1835 RELEASE_ASSERT(!exec->hadException());
1836 return result;
1837}
1838
1839#if ENABLE(SAMPLING_PROFILER)
1840EncodedJSValue JSC_HOST_CALL functionStartSamplingProfiler(ExecState* exec)
1841{
1842 exec->vm().ensureSamplingProfiler(WTF::Stopwatch::create());
1843 exec->vm().samplingProfiler()->noticeCurrentThreadAsJSCExecutionThread();
1844 exec->vm().samplingProfiler()->start();
1845 return JSValue::encode(jsUndefined());
1846}
1847
1848EncodedJSValue JSC_HOST_CALL functionSamplingProfilerStackTraces(ExecState* exec)
1849{
1850 RELEASE_ASSERT(exec->vm().samplingProfiler());
1851 String jsonString = exec->vm().samplingProfiler()->stackTracesAsJSON();
1852 EncodedJSValue result = JSValue::encode(JSONParse(exec, jsonString));
1853 RELEASE_ASSERT(!exec->hadException());
1854 return result;
1855}
1856#endif // ENABLE(SAMPLING_PROFILER)
1857
1858// Use SEH for Release builds only to get rid of the crash report dialog
1859// (luckily the same tests fail in Release and Debug builds so far). Need to
1860// be in a separate main function because the jscmain function requires object
1861// unwinding.
1862
1863#if COMPILER(MSVC) && !defined(_DEBUG)
1864#define TRY __try {
1865#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
1866#else
1867#define TRY
1868#define EXCEPT(x)
1869#endif
1870
1871int jscmain(int argc, char** argv);
1872
1873static double s_desiredTimeout;
1874
1875static NO_RETURN_DUE_TO_CRASH void timeoutThreadMain(void*)
1876{
1877 auto timeout = std::chrono::microseconds(static_cast<std::chrono::microseconds::rep>(s_desiredTimeout * 1000000));
1878 std::this_thread::sleep_for(timeout);
1879
1880 dataLog("Timed out after ", s_desiredTimeout, " seconds!\n");
1881 CRASH();
1882}
1883
1884int main(int argc, char** argv)
1885{
1886#if PLATFORM(IOS) && CPU(ARM_THUMB2)
1887 // Enabled IEEE754 denormal support.
1888 fenv_t env;
1889 fegetenv( &env );
1890 env.__fpscr &= ~0x01000000u;
1891 fesetenv( &env );
1892#endif
1893
1894#if OS(WINDOWS)
1895 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
1896 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
1897 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
1898 ::SetErrorMode(0);
1899
1900#if defined(_DEBUG)
1901 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1902 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1903 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1904 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
1905 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1906 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
1907#endif
1908
1909 timeBeginPeriod(1);
1910#endif
1911
1912#if PLATFORM(EFL)
1913 ecore_init();
1914#endif
1915
1916 // Need to initialize WTF threading before we start any threads. Cannot initialize JSC
1917 // threading yet, since that would do somethings that we'd like to defer until after we
1918 // have a chance to parse options.
1919 WTF::initializeThreading();
1920
1921 if (char* timeoutString = getenv("JSCTEST_timeout")) {
1922 if (sscanf(timeoutString, "%lf", &s_desiredTimeout) != 1) {
1923 dataLog(
1924 "WARNING: timeout string is malformed, got ", timeoutString,
1925 " but expected a number. Not using a timeout.\n");
1926 } else
1927 createThread(timeoutThreadMain, 0, "jsc Timeout Thread");
1928 }
1929
1930#if PLATFORM(IOS)
1931 Options::crashIfCantAllocateJITMemory() = true;
1932#endif
1933
1934 // We can't use destructors in the following code because it uses Windows
1935 // Structured Exception Handling
1936 int res = 0;
1937 TRY
1938 res = jscmain(argc, argv);
1939 EXCEPT(res = 3)
1940 if (Options::logHeapStatisticsAtExit())
1941 HeapStatistics::reportSuccess();
1942
1943#if PLATFORM(EFL)
1944 ecore_shutdown();
1945#endif
1946
1947 jscExit(res);
1948}
1949
1950static void dumpException(GlobalObject* globalObject, JSValue exception)
1951{
1952 printf("Exception: %s\n", exception.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
1953 Identifier stackID = Identifier::fromString(globalObject->globalExec(), "stack");
1954 JSValue stackValue = exception.get(globalObject->globalExec(), stackID);
1955 if (!stackValue.isUndefinedOrNull())
1956 printf("%s\n", stackValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
1957}
1958
1959static void dumpException(GlobalObject* globalObject, NakedPtr<Exception> evaluationException)
1960{
1961 if (evaluationException)
1962 dumpException(globalObject, evaluationException->value());
1963}
1964
1965static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump, bool module)
1966{
1967 String fileName;
1968 Vector<char> scriptBuffer;
1969
1970 if (dump)
1971 JSC::Options::dumpGeneratedBytecodes() = true;
1972
1973 VM& vm = globalObject->vm();
1974 bool success = true;
1975
1976 JSFunction* errorHandler = JSNativeStdFunction::create(vm, globalObject, 1, String(), [&](ExecState* exec) {
1977 success = false;
1978 dumpException(globalObject, exec->argument(0));
1979 return JSValue::encode(jsUndefined());
1980 });
1981
1982#if ENABLE(SAMPLING_FLAGS)
1983 SamplingFlags::start();
1984#endif
1985
1986 for (size_t i = 0; i < scripts.size(); i++) {
1987 JSInternalPromise* promise = nullptr;
1988 if (scripts[i].isFile) {
1989 fileName = scripts[i].argument;
1990 if (module)
1991 promise = loadAndEvaluateModule(globalObject->globalExec(), fileName);
1992 else {
1993 if (!fetchScriptFromLocalFileSystem(fileName, scriptBuffer))
1994 return false; // fail early so we can catch missing files
1995 }
1996 } else {
1997 size_t commandLineLength = strlen(scripts[i].argument);
1998 scriptBuffer.resize(commandLineLength);
1999 std::copy(scripts[i].argument, scripts[i].argument + commandLineLength, scriptBuffer.begin());
2000 fileName = ASCIILiteral("[Command Line]");
2001 }
2002
2003 if (module) {
2004 if (!promise)
2005 promise = loadAndEvaluateModule(globalObject->globalExec(), jscSource(scriptBuffer, fileName));
2006 globalObject->globalExec()->clearException();
2007 promise->then(globalObject->globalExec(), nullptr, errorHandler);
2008 globalObject->vm().drainMicrotasks();
2009 } else {
2010 NakedPtr<Exception> evaluationException;
2011 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(scriptBuffer, fileName), JSValue(), evaluationException);
2012 success = success && !evaluationException;
2013 if (dump && !evaluationException)
2014 printf("End: %s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
2015 dumpException(globalObject, evaluationException);
2016 }
2017
2018 globalObject->globalExec()->clearException();
2019 }
2020
2021#if ENABLE(REGEXP_TRACING)
2022 vm.dumpRegExpTrace();
2023#endif
2024 return success;
2025}
2026
2027#define RUNNING_FROM_XCODE 0
2028
2029static void runInteractive(GlobalObject* globalObject)
2030{
2031 String interpreterName(ASCIILiteral("Interpreter"));
2032
2033 bool shouldQuit = false;
2034 while (!shouldQuit) {
2035#if HAVE(READLINE) && !RUNNING_FROM_XCODE
2036 ParserError error;
2037 String source;
2038 do {
2039 error = ParserError();
2040 char* line = readline(source.isEmpty() ? interactivePrompt : "... ");
2041 shouldQuit = !line;
2042 if (!line)
2043 break;
2044 source = source + line;
2045 source = source + '\n';
2046 checkSyntax(globalObject->vm(), makeSource(source, interpreterName), error);
2047 if (!line[0])
2048 break;
2049 add_history(line);
2050 } while (error.syntaxErrorType() == ParserError::SyntaxErrorRecoverable);
2051
2052 if (error.isValid()) {
2053 printf("%s:%d\n", error.message().utf8().data(), error.line());
2054 continue;
2055 }
2056
2057
2058 NakedPtr<Exception> evaluationException;
2059 JSValue returnValue = evaluate(globalObject->globalExec(), makeSource(source, interpreterName), JSValue(), evaluationException);
2060#else
2061 printf("%s", interactivePrompt);
2062 Vector<char, 256> line;
2063 int c;
2064 while ((c = getchar()) != EOF) {
2065 // FIXME: Should we also break on \r?
2066 if (c == '\n')
2067 break;
2068 line.append(c);
2069 }
2070 if (line.isEmpty())
2071 break;
2072
2073 NakedPtr<Exception> evaluationException;
2074 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(line, interpreterName), JSValue(), evaluationException);
2075#endif
2076 if (evaluationException)
2077 printf("Exception: %s\n", evaluationException->value().toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
2078 else
2079 printf("%s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
2080
2081 globalObject->globalExec()->clearException();
2082 globalObject->vm().drainMicrotasks();
2083 }
2084 printf("\n");
2085}
2086
2087static NO_RETURN void printUsageStatement(bool help = false)
2088{
2089 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
2090 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
2091 fprintf(stderr, " -e Evaluate argument as script code\n");
2092 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
2093 fprintf(stderr, " -h|--help Prints this help message\n");
2094 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
2095 fprintf(stderr, " -m Execute as a module\n");
2096#if HAVE(SIGNAL_H)
2097 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
2098#endif
2099 fprintf(stderr, " -p <file> Outputs profiling data to a file\n");
2100 fprintf(stderr, " -x Output exit code before terminating\n");
2101 fprintf(stderr, "\n");
2102 fprintf(stderr, " --sample Collects and outputs sampling profiler data\n");
2103 fprintf(stderr, " --options Dumps all JSC VM options and exits\n");
2104 fprintf(stderr, " --dumpOptions Dumps all non-default JSC VM options before continuing\n");
2105 fprintf(stderr, " --<jsc VM option>=<value> Sets the specified JSC VM option\n");
2106 fprintf(stderr, "\n");
2107
2108 jscExit(help ? EXIT_SUCCESS : EXIT_FAILURE);
2109}
2110
2111void CommandLine::parseArguments(int argc, char** argv)
2112{
2113 Options::initialize();
2114
2115 int i = 1;
2116 JSC::Options::DumpLevel dumpOptionsLevel = JSC::Options::DumpLevel::None;
2117 bool needToExit = false;
2118
2119 bool hasBadJSCOptions = false;
2120 for (; i < argc; ++i) {
2121 const char* arg = argv[i];
2122 if (!strcmp(arg, "-f")) {
2123 if (++i == argc)
2124 printUsageStatement();
2125 m_scripts.append(Script(true, argv[i]));
2126 continue;
2127 }
2128 if (!strcmp(arg, "-e")) {
2129 if (++i == argc)
2130 printUsageStatement();
2131 m_scripts.append(Script(false, argv[i]));
2132 continue;
2133 }
2134 if (!strcmp(arg, "-i")) {
2135 m_interactive = true;
2136 continue;
2137 }
2138 if (!strcmp(arg, "-d")) {
2139 m_dump = true;
2140 continue;
2141 }
2142 if (!strcmp(arg, "-p")) {
2143 if (++i == argc)
2144 printUsageStatement();
2145 m_profile = true;
2146 m_profilerOutput = argv[i];
2147 continue;
2148 }
2149 if (!strcmp(arg, "-m")) {
2150 m_module = true;
2151 continue;
2152 }
2153 if (!strcmp(arg, "-s")) {
2154#if HAVE(SIGNAL_H)
2155 signal(SIGILL, _exit);
2156 signal(SIGFPE, _exit);
2157 signal(SIGBUS, _exit);
2158 signal(SIGSEGV, _exit);
2159#endif
2160 continue;
2161 }
2162 if (!strcmp(arg, "-x")) {
2163 m_exitCode = true;
2164 continue;
2165 }
2166 if (!strcmp(arg, "--")) {
2167 ++i;
2168 break;
2169 }
2170 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
2171 printUsageStatement(true);
2172
2173 if (!strcmp(arg, "--options")) {
2174 dumpOptionsLevel = JSC::Options::DumpLevel::Verbose;
2175 needToExit = true;
2176 continue;
2177 }
2178 if (!strcmp(arg, "--dumpOptions")) {
2179 dumpOptionsLevel = JSC::Options::DumpLevel::Overridden;
2180 continue;
2181 }
2182 if (!strcmp(arg, "--sample")) {
2183 JSC::Options::useSamplingProfiler() = true;
2184 JSC::Options::collectSamplingProfilerDataForJSCShell() = true;
2185 m_dumpSamplingProfilerData = true;
2186 continue;
2187 }
2188
2189 // See if the -- option is a JSC VM option.
2190 if (strstr(arg, "--") == arg) {
2191 if (!JSC::Options::setOption(&arg[2])) {
2192 hasBadJSCOptions = true;
2193 dataLog("ERROR: invalid option: ", arg, "\n");
2194 }
2195 continue;
2196 }
2197
2198 // This arg is not recognized by the VM nor by jsc. Pass it on to the
2199 // script.
2200 m_scripts.append(Script(true, argv[i]));
2201 }
2202
2203 if (hasBadJSCOptions && JSC::Options::validateOptions())
2204 CRASH();
2205
2206 if (m_scripts.isEmpty())
2207 m_interactive = true;
2208
2209 for (; i < argc; ++i)
2210 m_arguments.append(argv[i]);
2211
2212 if (dumpOptionsLevel != JSC::Options::DumpLevel::None) {
2213 const char* optionsTitle = (dumpOptionsLevel == JSC::Options::DumpLevel::Overridden)
2214 ? "Modified JSC runtime options:"
2215 : "All JSC runtime options:";
2216 JSC::Options::dumpAllOptions(stderr, dumpOptionsLevel, optionsTitle);
2217 }
2218 JSC::Options::ensureOptionsAreCoherent();
2219 if (needToExit)
2220 jscExit(EXIT_SUCCESS);
2221}
2222
2223// We make this function no inline so that globalObject won't be on the stack if we do a GC in jscmain.
2224static int NEVER_INLINE runJSC(VM* vm, CommandLine options)
2225{
2226 JSLockHolder locker(vm);
2227
2228 int result;
2229 if (options.m_profile && !vm->m_perBytecodeProfiler)
2230 vm->m_perBytecodeProfiler = std::make_unique<Profiler::Database>(*vm);
2231
2232 GlobalObject* globalObject = GlobalObject::create(*vm, GlobalObject::createStructure(*vm, jsNull()), options.m_arguments);
2233 bool success = runWithScripts(globalObject, options.m_scripts, options.m_dump, options.m_module);
2234 if (options.m_interactive && success)
2235 runInteractive(globalObject);
2236
2237 result = success ? 0 : 3;
2238
2239 if (options.m_exitCode)
2240 printf("jsc exiting %d\n", result);
2241
2242 if (options.m_profile) {
2243 if (!vm->m_perBytecodeProfiler->save(options.m_profilerOutput.utf8().data()))
2244 fprintf(stderr, "could not save profiler output.\n");
2245 }
2246
2247#if ENABLE(JIT)
2248 if (Options::useExceptionFuzz())
2249 printf("JSC EXCEPTION FUZZ: encountered %u checks.\n", numberOfExceptionFuzzChecks());
2250 bool fireAtEnabled =
2251 Options::fireExecutableAllocationFuzzAt() || Options::fireExecutableAllocationFuzzAtOrAfter();
2252 if (Options::useExecutableAllocationFuzz() && (!fireAtEnabled || Options::verboseExecutableAllocationFuzz()))
2253 printf("JSC EXECUTABLE ALLOCATION FUZZ: encountered %u checks.\n", numberOfExecutableAllocationFuzzChecks());
2254 if (Options::useOSRExitFuzz()) {
2255 printf("JSC OSR EXIT FUZZ: encountered %u static checks.\n", numberOfStaticOSRExitFuzzChecks());
2256 printf("JSC OSR EXIT FUZZ: encountered %u dynamic checks.\n", numberOfOSRExitFuzzChecks());
2257 }
2258#endif
2259 auto compileTimeStats = DFG::Plan::compileTimeStats();
2260 Vector<CString> compileTimeKeys;
2261 for (auto& entry : compileTimeStats)
2262 compileTimeKeys.append(entry.key);
2263 std::sort(compileTimeKeys.begin(), compileTimeKeys.end());
2264 for (CString key : compileTimeKeys)
2265 printf("%40s: %.3lf ms\n", key.data(), compileTimeStats.get(key));
2266
2267 return result;
2268}
2269
2270int jscmain(int argc, char** argv)
2271{
2272 // Note that the options parsing can affect VM creation, and thus
2273 // comes first.
2274 CommandLine options(argc, argv);
2275
2276 // Initialize JSC before getting VM.
2277#if ENABLE(SAMPLING_REGIONS)
2278 WTF::initializeMainThread();
2279#endif
2280 JSC::initializeThreading();
2281
2282 VM* vm = &VM::create(LargeHeap).leakRef();
2283 int result;
2284 result = runJSC(vm, options);
2285
2286 if (Options::gcAtEnd()) {
2287 // We need to hold the API lock to do a GC.
2288 JSLockHolder locker(vm);
2289 vm->heap.collectAllGarbage();
2290 }
2291
2292 if (options.m_dumpSamplingProfilerData) {
2293#if ENABLE(SAMPLING_PROFILER)
2294 JSLockHolder locker(vm);
2295 vm->samplingProfiler()->reportTopFunctions();
2296 vm->samplingProfiler()->reportTopBytecodes();
2297#else
2298 dataLog("Sampling profiler is not enabled on this platform\n");
2299#endif
2300 }
2301
2302 printSuperSamplerState();
2303
2304 return result;
2305}
2306
2307#if OS(WINDOWS)
2308extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(int argc, const char* argv[])
2309{
2310 return main(argc, const_cast<char**>(argv));
2311}
2312#endif
Note: See TracBrowser for help on using the repository browser.