Interpreter.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. /*
  2. * Copyright (C) 2008, 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
  3. * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  15. * its contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include "config.h"
  30. #include "Interpreter.h"
  31. #include "Arguments.h"
  32. #include "BatchedTransitionOptimizer.h"
  33. #include "CallFrame.h"
  34. #include "CallFrameClosure.h"
  35. #include "CodeBlock.h"
  36. #include "Heap.h"
  37. #include "Debugger.h"
  38. #include "DebuggerCallFrame.h"
  39. #include "ErrorInstance.h"
  40. #include "EvalCodeCache.h"
  41. #include "ExceptionHelpers.h"
  42. #include "GetterSetter.h"
  43. #include "JSActivation.h"
  44. #include "JSArray.h"
  45. #include "JSBoundFunction.h"
  46. #include "JSNameScope.h"
  47. #include "JSNotAnObject.h"
  48. #include "JSPropertyNameIterator.h"
  49. #include "JSStackInlines.h"
  50. #include "JSString.h"
  51. #include "JSWithScope.h"
  52. #include "LLIntCLoop.h"
  53. #include "LegacyProfiler.h"
  54. #include "LiteralParser.h"
  55. #include "NameInstance.h"
  56. #include "ObjectPrototype.h"
  57. #include "Operations.h"
  58. #include "Parser.h"
  59. #include "RegExpObject.h"
  60. #include "RegExpPrototype.h"
  61. #include "Register.h"
  62. #include "SamplingTool.h"
  63. #include "StrictEvalActivation.h"
  64. #include "StrongInlines.h"
  65. #include <limits.h>
  66. #include <stdio.h>
  67. #include <wtf/StackStats.h>
  68. #include <wtf/StringPrintStream.h>
  69. #include <wtf/Threading.h>
  70. #include <wtf/WTFThreadData.h>
  71. #include <wtf/text/StringBuilder.h>
  72. #if ENABLE(JIT)
  73. #include "JIT.h"
  74. #endif
  75. #define WTF_USE_GCC_COMPUTED_GOTO_WORKAROUND (ENABLE(LLINT) && !defined(__llvm__))
  76. using namespace std;
  77. namespace JSC {
  78. #if !(ENABLE(DETACHED_JIT) && BUILDING_DETACHED_JIT)
  79. Interpreter::ErrorHandlingMode::ErrorHandlingMode(ExecState *exec)
  80. : m_interpreter(*exec->interpreter())
  81. {
  82. if (!m_interpreter.m_errorHandlingModeReentry)
  83. m_interpreter.stack().enableErrorStackReserve();
  84. m_interpreter.m_errorHandlingModeReentry++;
  85. }
  86. Interpreter::ErrorHandlingMode::~ErrorHandlingMode()
  87. {
  88. m_interpreter.m_errorHandlingModeReentry--;
  89. ASSERT(m_interpreter.m_errorHandlingModeReentry >= 0);
  90. if (!m_interpreter.m_errorHandlingModeReentry)
  91. m_interpreter.stack().disableErrorStackReserve();
  92. }
  93. // The Interpreter::StackPolicy class is used to compute a stack capacity
  94. // requirement to ensure that we have enough room on the native stack for:
  95. // 1. the max cumulative stack used by the interpreter and all code
  96. // paths sub of it up till leaf functions.
  97. // 2. the max cumulative stack used by the interpreter before it reaches
  98. // the next checkpoint (execute...() function) in the interpreter.
  99. //
  100. // The interpreter can be run on different threads and hence, different
  101. // native stacks (with different sizes) before exiting out of the first
  102. // frame. Hence, the required capacity needs to be re-computed on every
  103. // entry into the interpreter.
  104. //
  105. // Currently the requiredStack is computed based on a policy. See comments
  106. // in StackPolicy::StackPolicy() for details.
  107. Interpreter::StackPolicy::StackPolicy(Interpreter& interpreter, const StackBounds& stack)
  108. : m_interpreter(interpreter)
  109. {
  110. const size_t size = stack.size();
  111. // We have two separate stack limits, one for regular JS execution, and one
  112. // for when we're handling errors. We need the error stack to be smaller
  113. // otherwise there would obviously not be any stack left to execute JS in when
  114. // there's a stack overflow.
  115. //
  116. // These sizes were derived from the stack usage of a number of sites when
  117. // layout occurs when we've already consumed most of the C stack.
  118. const size_t requiredStack = 256 * KB;
  119. const size_t errorModeRequiredStack = 64 * KB;
  120. size_t requiredCapacity = m_interpreter.m_errorHandlingModeReentry ? errorModeRequiredStack : requiredStack;
  121. RELEASE_ASSERT(size > requiredCapacity);
  122. m_requiredCapacity = requiredCapacity;
  123. }
  124. static CallFrame* getCallerInfo(VM*, CallFrame*, unsigned& bytecodeOffset, CodeBlock*& callerOut);
  125. // Returns the depth of the scope chain within a given call frame.
  126. static int depth(CodeBlock* codeBlock, JSScope* sc)
  127. {
  128. if (!codeBlock->needsFullScopeChain())
  129. return 0;
  130. return sc->localDepth();
  131. }
  132. JSValue eval(CallFrame* callFrame)
  133. {
  134. if (!callFrame->argumentCount())
  135. return jsUndefined();
  136. JSValue program = callFrame->argument(0);
  137. if (!program.isString())
  138. return program;
  139. TopCallFrameSetter topCallFrame(callFrame->vm(), callFrame);
  140. String programSource = asString(program)->value(callFrame);
  141. if (callFrame->hadException())
  142. return JSValue();
  143. CallFrame* callerFrame = callFrame->callerFrame();
  144. CodeBlock* callerCodeBlock = callerFrame->codeBlock();
  145. JSScope* callerScopeChain = callerFrame->scope();
  146. EvalExecutable* eval = callerCodeBlock->evalCodeCache().tryGet(callerCodeBlock->isStrictMode(), programSource, callerScopeChain);
  147. if (!eval) {
  148. if (!callerCodeBlock->isStrictMode()) {
  149. // FIXME: We can use the preparser in strict mode, we just need additional logic
  150. // to prevent duplicates.
  151. if (programSource.is8Bit()) {
  152. LiteralParser<LChar> preparser(callFrame, programSource.characters8(), programSource.length(), NonStrictJSON);
  153. if (JSValue parsedObject = preparser.tryLiteralParse())
  154. return parsedObject;
  155. } else {
  156. LiteralParser<UChar> preparser(callFrame, programSource.characters16(), programSource.length(), NonStrictJSON);
  157. if (JSValue parsedObject = preparser.tryLiteralParse())
  158. return parsedObject;
  159. }
  160. }
  161. // If the literal parser bailed, it should not have thrown exceptions.
  162. ASSERT(!callFrame->vm().exception);
  163. JSValue exceptionValue;
  164. eval = callerCodeBlock->evalCodeCache().getSlow(callFrame, callerCodeBlock->unlinkedCodeBlock()->codeCacheForEval().get(), callerCodeBlock->ownerExecutable(), callerCodeBlock->isStrictMode(), programSource, callerScopeChain, exceptionValue);
  165. ASSERT(!(bool)eval == exceptionValue);
  166. if (UNLIKELY(!eval))
  167. return throwError(callFrame, exceptionValue);
  168. }
  169. JSValue thisValue = callerFrame->thisValue();
  170. ASSERT(isValidThisObject(thisValue, callFrame));
  171. Interpreter* interpreter = callFrame->vm().interpreter;
  172. return interpreter->execute(eval, callFrame, thisValue, callerScopeChain);
  173. }
  174. CallFrame* loadVarargs(CallFrame* callFrame, JSStack* stack, JSValue thisValue, JSValue arguments, int firstFreeRegister)
  175. {
  176. if (!arguments) { // f.apply(x, arguments), with arguments unmodified.
  177. unsigned argumentCountIncludingThis = callFrame->argumentCountIncludingThis();
  178. CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister + argumentCountIncludingThis + JSStack::CallFrameHeaderSize);
  179. if (argumentCountIncludingThis > Arguments::MaxArguments + 1 || !stack->grow(newCallFrame->registers())) {
  180. callFrame->vm().exception = createStackOverflowError(callFrame);
  181. return 0;
  182. }
  183. newCallFrame->setArgumentCountIncludingThis(argumentCountIncludingThis);
  184. newCallFrame->setThisValue(thisValue);
  185. for (size_t i = 0; i < callFrame->argumentCount(); ++i)
  186. newCallFrame->setArgument(i, callFrame->argumentAfterCapture(i));
  187. return newCallFrame;
  188. }
  189. if (arguments.isUndefinedOrNull()) {
  190. CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister + 1 + JSStack::CallFrameHeaderSize);
  191. if (!stack->grow(newCallFrame->registers())) {
  192. callFrame->vm().exception = createStackOverflowError(callFrame);
  193. return 0;
  194. }
  195. newCallFrame->setArgumentCountIncludingThis(1);
  196. newCallFrame->setThisValue(thisValue);
  197. return newCallFrame;
  198. }
  199. if (!arguments.isObject()) {
  200. callFrame->vm().exception = createInvalidParamError(callFrame, "Function.prototype.apply", arguments);
  201. return 0;
  202. }
  203. if (asObject(arguments)->classInfo() == &Arguments::s_info) {
  204. Arguments* argsObject = asArguments(arguments);
  205. unsigned argCount = argsObject->length(callFrame);
  206. CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister + CallFrame::offsetFor(argCount + 1));
  207. if (argCount > Arguments::MaxArguments || !stack->grow(newCallFrame->registers())) {
  208. callFrame->vm().exception = createStackOverflowError(callFrame);
  209. return 0;
  210. }
  211. newCallFrame->setArgumentCountIncludingThis(argCount + 1);
  212. newCallFrame->setThisValue(thisValue);
  213. argsObject->copyToArguments(callFrame, newCallFrame, argCount);
  214. return newCallFrame;
  215. }
  216. if (isJSArray(arguments)) {
  217. JSArray* array = asArray(arguments);
  218. unsigned argCount = array->length();
  219. CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister + CallFrame::offsetFor(argCount + 1));
  220. if (argCount > Arguments::MaxArguments || !stack->grow(newCallFrame->registers())) {
  221. callFrame->vm().exception = createStackOverflowError(callFrame);
  222. return 0;
  223. }
  224. newCallFrame->setArgumentCountIncludingThis(argCount + 1);
  225. newCallFrame->setThisValue(thisValue);
  226. array->copyToArguments(callFrame, newCallFrame, argCount);
  227. return newCallFrame;
  228. }
  229. JSObject* argObject = asObject(arguments);
  230. unsigned argCount = argObject->get(callFrame, callFrame->propertyNames().length).toUInt32(callFrame);
  231. CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister + CallFrame::offsetFor(argCount + 1));
  232. if (argCount > Arguments::MaxArguments || !stack->grow(newCallFrame->registers())) {
  233. callFrame->vm().exception = createStackOverflowError(callFrame);
  234. return 0;
  235. }
  236. newCallFrame->setArgumentCountIncludingThis(argCount + 1);
  237. newCallFrame->setThisValue(thisValue);
  238. for (size_t i = 0; i < argCount; ++i) {
  239. newCallFrame->setArgument(i, asObject(arguments)->get(callFrame, i));
  240. if (UNLIKELY(callFrame->vm().exception))
  241. return 0;
  242. }
  243. return newCallFrame;
  244. }
  245. Interpreter::Interpreter(VM& vm)
  246. : m_sampleEntryDepth(0)
  247. , m_stack(vm)
  248. , m_errorHandlingModeReentry(0)
  249. #if !ASSERT_DISABLED
  250. , m_initialized(false)
  251. #endif
  252. {
  253. }
  254. Interpreter::~Interpreter()
  255. {
  256. }
  257. void Interpreter::initialize(bool canUseJIT)
  258. {
  259. UNUSED_PARAM(canUseJIT);
  260. #if ENABLE(COMPUTED_GOTO_OPCODES) && ENABLE(LLINT)
  261. m_opcodeTable = LLInt::opcodeMap();
  262. for (int i = 0; i < numOpcodeIDs; ++i)
  263. m_opcodeIDTable.add(m_opcodeTable[i], static_cast<OpcodeID>(i));
  264. #endif
  265. #if !ASSERT_DISABLED
  266. m_initialized = true;
  267. #endif
  268. #if ENABLE(OPCODE_SAMPLING)
  269. enableSampler();
  270. #endif
  271. }
  272. #ifdef NDEBUG
  273. void Interpreter::dumpCallFrame(CallFrame*)
  274. {
  275. }
  276. #else
  277. void Interpreter::dumpCallFrame(CallFrame* callFrame)
  278. {
  279. callFrame->codeBlock()->dumpBytecode();
  280. dumpRegisters(callFrame);
  281. }
  282. void Interpreter::dumpRegisters(CallFrame* callFrame)
  283. {
  284. dataLogF("Register frame: \n\n");
  285. dataLogF("-----------------------------------------------------------------------------\n");
  286. dataLogF(" use | address | value \n");
  287. dataLogF("-----------------------------------------------------------------------------\n");
  288. CodeBlock* codeBlock = callFrame->codeBlock();
  289. const Register* it;
  290. const Register* end;
  291. it = callFrame->registers() - JSStack::CallFrameHeaderSize - callFrame->argumentCountIncludingThis();
  292. end = callFrame->registers() - JSStack::CallFrameHeaderSize;
  293. while (it < end) {
  294. JSValue v = it->jsValue();
  295. int registerNumber = it - callFrame->registers();
  296. String name = codeBlock->nameForRegister(registerNumber);
  297. dataLogF("[r% 3d %14s] | %10p | %-16s 0x%lld \n", registerNumber, name.ascii().data(), it, toCString(v).data(), (long long)JSValue::encode(v));
  298. it++;
  299. }
  300. dataLogF("-----------------------------------------------------------------------------\n");
  301. dataLogF("[ArgumentCount] | %10p | %lu \n", it, (unsigned long) callFrame->argumentCount());
  302. ++it;
  303. dataLogF("[CallerFrame] | %10p | %p \n", it, callFrame->callerFrame());
  304. ++it;
  305. dataLogF("[Callee] | %10p | %p \n", it, callFrame->callee());
  306. ++it;
  307. dataLogF("[ScopeChain] | %10p | %p \n", it, callFrame->scope());
  308. ++it;
  309. #if ENABLE(JIT)
  310. AbstractPC pc = callFrame->abstractReturnPC(callFrame->vm());
  311. if (pc.hasJITReturnAddress())
  312. dataLogF("[ReturnJITPC] | %10p | %p \n", it, pc.jitReturnAddress().value());
  313. #endif
  314. unsigned bytecodeOffset = 0;
  315. int line = 0;
  316. CodeBlock* callerCodeBlock = 0;
  317. getCallerInfo(&callFrame->vm(), callFrame, bytecodeOffset, callerCodeBlock);
  318. line = callerCodeBlock->lineNumberForBytecodeOffset(bytecodeOffset);
  319. dataLogF("[ReturnVPC] | %10p | %d (line %d)\n", it, bytecodeOffset, line);
  320. ++it;
  321. dataLogF("[CodeBlock] | %10p | %p \n", it, callFrame->codeBlock());
  322. ++it;
  323. dataLogF("-----------------------------------------------------------------------------\n");
  324. int registerCount = 0;
  325. end = it + codeBlock->m_numVars;
  326. if (it != end) {
  327. do {
  328. JSValue v = it->jsValue();
  329. int registerNumber = it - callFrame->registers();
  330. String name = codeBlock->nameForRegister(registerNumber);
  331. dataLogF("[r% 3d %14s] | %10p | %-16s 0x%lld \n", registerNumber, name.ascii().data(), it, toCString(v).data(), (long long)JSValue::encode(v));
  332. ++it;
  333. ++registerCount;
  334. } while (it != end);
  335. }
  336. dataLogF("-----------------------------------------------------------------------------\n");
  337. end = it + codeBlock->m_numCalleeRegisters - codeBlock->m_numVars;
  338. if (it != end) {
  339. do {
  340. JSValue v = (*it).jsValue();
  341. dataLogF("[r% 3d] | %10p | %-16s 0x%lld \n", registerCount, it, toCString(v).data(), (long long)JSValue::encode(v));
  342. ++it;
  343. ++registerCount;
  344. } while (it != end);
  345. }
  346. dataLogF("-----------------------------------------------------------------------------\n");
  347. }
  348. #endif
  349. #endif // #if !(ENABLE(DETACHED_JIT) && BUILDING_DETACHED_JIT)
  350. bool Interpreter::isOpcode(Opcode opcode)
  351. {
  352. #if ENABLE(COMPUTED_GOTO_OPCODES)
  353. #if !ENABLE(LLINT)
  354. return static_cast<OpcodeID>(bitwise_cast<uintptr_t>(opcode)) <= op_end;
  355. #else
  356. return opcode != HashTraits<Opcode>::emptyValue()
  357. && !HashTraits<Opcode>::isDeletedValue(opcode)
  358. && m_opcodeIDTable.contains(opcode);
  359. #endif
  360. #else
  361. return opcode >= 0 && opcode <= op_end;
  362. #endif
  363. }
  364. #if !(ENABLE(DETACHED_JIT) && BUILDING_DETACHED_JIT)
  365. NEVER_INLINE bool Interpreter::unwindCallFrame(CallFrame*& callFrame, JSValue exceptionValue, unsigned& bytecodeOffset, CodeBlock*& codeBlock)
  366. {
  367. CodeBlock* oldCodeBlock = codeBlock;
  368. JSScope* scope = callFrame->scope();
  369. if (Debugger* debugger = callFrame->dynamicGlobalObject()->debugger()) {
  370. DebuggerCallFrame debuggerCallFrame(callFrame, exceptionValue);
  371. if (callFrame->callee())
  372. debugger->returnEvent(debuggerCallFrame, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->lastLine(), 0);
  373. else
  374. debugger->didExecuteProgram(debuggerCallFrame, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->lastLine(), 0);
  375. }
  376. JSValue activation;
  377. if (oldCodeBlock->codeType() == FunctionCode && oldCodeBlock->needsActivation()) {
  378. activation = callFrame->uncheckedR(oldCodeBlock->activationRegister()).jsValue();
  379. if (activation)
  380. jsCast<JSActivation*>(activation)->tearOff(*scope->vm());
  381. }
  382. if (oldCodeBlock->codeType() == FunctionCode && oldCodeBlock->usesArguments()) {
  383. if (JSValue arguments = callFrame->uncheckedR(unmodifiedArgumentsRegister(oldCodeBlock->argumentsRegister())).jsValue()) {
  384. if (activation)
  385. jsCast<Arguments*>(arguments)->didTearOffActivation(callFrame, jsCast<JSActivation*>(activation));
  386. else
  387. jsCast<Arguments*>(arguments)->tearOff(callFrame);
  388. }
  389. }
  390. CallFrame* callerFrame = callFrame->callerFrame();
  391. callFrame->vm().topCallFrame = callerFrame;
  392. if (callerFrame->hasHostCallFrameFlag())
  393. return false;
  394. callFrame = getCallerInfo(&callFrame->vm(), callFrame, bytecodeOffset, codeBlock);
  395. return true;
  396. }
  397. static void appendSourceToError(CallFrame* callFrame, ErrorInstance* exception, unsigned bytecodeOffset)
  398. {
  399. exception->clearAppendSourceToMessage();
  400. if (!callFrame->codeBlock()->hasExpressionInfo())
  401. return;
  402. int startOffset = 0;
  403. int endOffset = 0;
  404. int divotPoint = 0;
  405. unsigned line = 0;
  406. unsigned column = 0;
  407. CodeBlock* codeBlock = callFrame->codeBlock();
  408. codeBlock->expressionRangeForBytecodeOffset(bytecodeOffset, divotPoint, startOffset, endOffset, line, column);
  409. int expressionStart = divotPoint - startOffset;
  410. int expressionStop = divotPoint + endOffset;
  411. const String& sourceString = codeBlock->source()->source();
  412. if (!expressionStop || expressionStart > static_cast<int>(sourceString.length()))
  413. return;
  414. VM* vm = &callFrame->vm();
  415. JSValue jsMessage = exception->getDirect(*vm, vm->propertyNames->message);
  416. if (!jsMessage || !jsMessage.isString())
  417. return;
  418. String message = asString(jsMessage)->value(callFrame);
  419. if (expressionStart < expressionStop)
  420. message = makeString(message, " (evaluating '", codeBlock->source()->getRange(expressionStart, expressionStop), "')");
  421. else {
  422. // No range information, so give a few characters of context
  423. const StringImpl* data = sourceString.impl();
  424. int dataLength = sourceString.length();
  425. int start = expressionStart;
  426. int stop = expressionStart;
  427. // Get up to 20 characters of context to the left and right of the divot, clamping to the line.
  428. // then strip whitespace.
  429. while (start > 0 && (expressionStart - start < 20) && (*data)[start - 1] != '\n')
  430. start--;
  431. while (start < (expressionStart - 1) && isStrWhiteSpace((*data)[start]))
  432. start++;
  433. while (stop < dataLength && (stop - expressionStart < 20) && (*data)[stop] != '\n')
  434. stop++;
  435. while (stop > expressionStart && isStrWhiteSpace((*data)[stop - 1]))
  436. stop--;
  437. message = makeString(message, " (near '...", codeBlock->source()->getRange(start, stop), "...')");
  438. }
  439. exception->putDirect(*vm, vm->propertyNames->message, jsString(vm, message));
  440. }
  441. static unsigned getBytecodeOffsetForCallFrame(CallFrame* callFrame)
  442. {
  443. callFrame = callFrame->removeHostCallFrameFlag();
  444. CodeBlock* codeBlock = callFrame->codeBlock();
  445. if (!codeBlock)
  446. return 0;
  447. #if ENABLE(DFG_JIT)
  448. if (codeBlock->getJITType() == JITCode::DFGJIT)
  449. return codeBlock->codeOrigin(callFrame->codeOriginIndexForDFG()).bytecodeIndex;
  450. #endif
  451. return callFrame->bytecodeOffsetForNonDFGCode();
  452. }
  453. static CallFrame* getCallerInfo(VM* vm, CallFrame* callFrame, unsigned& bytecodeOffset, CodeBlock*& caller)
  454. {
  455. ASSERT_UNUSED(vm, vm);
  456. bytecodeOffset = 0;
  457. ASSERT(!callFrame->hasHostCallFrameFlag());
  458. CallFrame* trueCallerFrame = callFrame->trueCallerFrame();
  459. bool wasCalledByHost = callFrame->callerFrame()->hasHostCallFrameFlag();
  460. ASSERT(!trueCallerFrame->hasHostCallFrameFlag());
  461. if (trueCallerFrame == CallFrame::noCaller() || !trueCallerFrame || !trueCallerFrame->codeBlock()) {
  462. caller = 0;
  463. return trueCallerFrame;
  464. }
  465. CodeBlock* callerCodeBlock = trueCallerFrame->codeBlock();
  466. if (!callFrame->hasReturnPC())
  467. wasCalledByHost = true;
  468. if (wasCalledByHost) {
  469. #if ENABLE(DFG_JIT)
  470. if (callerCodeBlock && callerCodeBlock->getJITType() == JITCode::DFGJIT) {
  471. unsigned codeOriginIndex = callFrame->callerFrame()->removeHostCallFrameFlag()->codeOriginIndexForDFG();
  472. CodeOrigin origin = callerCodeBlock->codeOrigin(codeOriginIndex);
  473. bytecodeOffset = origin.bytecodeIndex;
  474. if (InlineCallFrame* inlineCallFrame = origin.inlineCallFrame)
  475. callerCodeBlock = inlineCallFrame->baselineCodeBlock();
  476. } else
  477. #endif
  478. bytecodeOffset = trueCallerFrame->bytecodeOffsetForNonDFGCode();
  479. } else {
  480. #if ENABLE(DFG_JIT)
  481. if (callFrame->isInlineCallFrame()) {
  482. InlineCallFrame* icf = callFrame->inlineCallFrame();
  483. bytecodeOffset = icf->caller.bytecodeIndex;
  484. if (InlineCallFrame* parentCallFrame = icf->caller.inlineCallFrame) {
  485. FunctionExecutable* executable = static_cast<FunctionExecutable*>(parentCallFrame->executable.get());
  486. CodeBlock* newCodeBlock = executable->baselineCodeBlockFor(parentCallFrame->isCall ? CodeForCall : CodeForConstruct);
  487. ASSERT(newCodeBlock);
  488. ASSERT(newCodeBlock->instructionCount() > bytecodeOffset);
  489. callerCodeBlock = newCodeBlock;
  490. }
  491. } else if (callerCodeBlock && callerCodeBlock->getJITType() == JITCode::DFGJIT) {
  492. CodeOrigin origin;
  493. if (!callerCodeBlock->codeOriginForReturn(callFrame->returnPC(), origin)) {
  494. // This should not be possible, but we're seeing cases where it does happen
  495. // CallFrame already has robustness against bogus stack walks, so
  496. // we'll extend that to here as well.
  497. ASSERT_NOT_REACHED();
  498. caller = 0;
  499. return 0;
  500. }
  501. bytecodeOffset = origin.bytecodeIndex;
  502. if (InlineCallFrame* icf = origin.inlineCallFrame) {
  503. FunctionExecutable* executable = static_cast<FunctionExecutable*>(icf->executable.get());
  504. CodeBlock* newCodeBlock = executable->baselineCodeBlockFor(icf->isCall ? CodeForCall : CodeForConstruct);
  505. ASSERT(newCodeBlock);
  506. ASSERT(newCodeBlock->instructionCount() > bytecodeOffset);
  507. callerCodeBlock = newCodeBlock;
  508. }
  509. } else
  510. #endif
  511. {
  512. RELEASE_ASSERT(callerCodeBlock);
  513. bytecodeOffset = callerCodeBlock->bytecodeOffset(trueCallerFrame, callFrame->returnPC());
  514. }
  515. }
  516. RELEASE_ASSERT(callerCodeBlock);
  517. caller = callerCodeBlock;
  518. return trueCallerFrame;
  519. }
  520. static ALWAYS_INLINE const String getSourceURLFromCallFrame(CallFrame* callFrame)
  521. {
  522. ASSERT(!callFrame->hasHostCallFrameFlag());
  523. return callFrame->codeBlock()->ownerExecutable()->sourceURL();
  524. }
  525. static StackFrameCodeType getStackFrameCodeType(CallFrame* callFrame)
  526. {
  527. ASSERT(!callFrame->hasHostCallFrameFlag());
  528. switch (callFrame->codeBlock()->codeType()) {
  529. case EvalCode:
  530. return StackFrameEvalCode;
  531. case FunctionCode:
  532. return StackFrameFunctionCode;
  533. case GlobalCode:
  534. return StackFrameGlobalCode;
  535. }
  536. RELEASE_ASSERT_NOT_REACHED();
  537. return StackFrameGlobalCode;
  538. }
  539. void StackFrame::computeLineAndColumn(unsigned& line, unsigned& column)
  540. {
  541. if (!codeBlock) {
  542. line = 0;
  543. column = 0;
  544. return;
  545. }
  546. int divot = 0;
  547. int unusedStartOffset = 0;
  548. int unusedEndOffset = 0;
  549. unsigned divotLine = 0;
  550. unsigned divotColumn = 0;
  551. expressionInfo(divot, unusedStartOffset, unusedEndOffset, divotLine, divotColumn);
  552. line = divotLine + lineOffset;
  553. column = divotColumn + (divotLine ? 1 : firstLineColumnOffset);
  554. }
  555. void StackFrame::expressionInfo(int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
  556. {
  557. codeBlock->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
  558. divot += characterOffset;
  559. }
  560. String StackFrame::toString(CallFrame* callFrame)
  561. {
  562. StringBuilder traceBuild;
  563. String functionName = friendlyFunctionName(callFrame);
  564. String sourceURL = friendlySourceURL();
  565. traceBuild.append(functionName);
  566. if (!sourceURL.isEmpty()) {
  567. if (!functionName.isEmpty())
  568. traceBuild.append('@');
  569. traceBuild.append(sourceURL);
  570. if (codeType != StackFrameNativeCode) {
  571. unsigned line;
  572. unsigned column;
  573. computeLineAndColumn(line, column);
  574. traceBuild.append(':');
  575. traceBuild.appendNumber(line);
  576. traceBuild.append(':');
  577. traceBuild.appendNumber(column);
  578. }
  579. }
  580. return traceBuild.toString().impl();
  581. }
  582. void Interpreter::getStackTrace(VM* vm, Vector<StackFrame>& results, size_t maxStackSize)
  583. {
  584. CallFrame* callFrame = vm->topCallFrame->removeHostCallFrameFlag();
  585. if (!callFrame || callFrame == CallFrame::noCaller())
  586. return;
  587. unsigned bytecodeOffset = getBytecodeOffsetForCallFrame(callFrame);
  588. callFrame = callFrame->trueCallFrameFromVMCode();
  589. if (!callFrame)
  590. return;
  591. CodeBlock* callerCodeBlock = callFrame->codeBlock();
  592. while (callFrame && callFrame != CallFrame::noCaller() && maxStackSize--) {
  593. String sourceURL;
  594. if (callerCodeBlock) {
  595. sourceURL = getSourceURLFromCallFrame(callFrame);
  596. StackFrame s = {
  597. Strong<JSObject>(*vm, callFrame->callee()),
  598. getStackFrameCodeType(callFrame),
  599. Strong<ExecutableBase>(*vm, callerCodeBlock->ownerExecutable()),
  600. Strong<UnlinkedCodeBlock>(*vm, callerCodeBlock->unlinkedCodeBlock()),
  601. callerCodeBlock->source(),
  602. callerCodeBlock->ownerExecutable()->lineNo(),
  603. callerCodeBlock->firstLineColumnOffset(),
  604. callerCodeBlock->sourceOffset(),
  605. bytecodeOffset,
  606. sourceURL
  607. };
  608. results.append(s);
  609. } else {
  610. StackFrame s = { Strong<JSObject>(*vm, callFrame->callee()), StackFrameNativeCode, Strong<ExecutableBase>(), Strong<UnlinkedCodeBlock>(), 0, 0, 0, 0, 0, String()};
  611. results.append(s);
  612. }
  613. callFrame = getCallerInfo(vm, callFrame, bytecodeOffset, callerCodeBlock);
  614. }
  615. }
  616. void Interpreter::addStackTraceIfNecessary(CallFrame* callFrame, JSValue error)
  617. {
  618. VM* vm = &callFrame->vm();
  619. ASSERT(callFrame == vm->topCallFrame || callFrame == callFrame->lexicalGlobalObject()->globalExec() || callFrame == callFrame->dynamicGlobalObject()->globalExec());
  620. Vector<StackFrame> stackTrace;
  621. getStackTrace(&callFrame->vm(), stackTrace);
  622. vm->exceptionStack() = RefCountedArray<StackFrame>(stackTrace);
  623. if (stackTrace.isEmpty() || !error.isObject())
  624. return;
  625. JSObject* errorObject = asObject(error);
  626. JSGlobalObject* globalObject = 0;
  627. if (isTerminatedExecutionException(error))
  628. globalObject = vm->dynamicGlobalObject;
  629. else
  630. globalObject = errorObject->globalObject();
  631. // FIXME: JSStringJoiner could be more efficient than StringBuilder here.
  632. StringBuilder builder;
  633. for (unsigned i = 0; i < stackTrace.size(); i++) {
  634. builder.append(String(stackTrace[i].toString(globalObject->globalExec()).impl()));
  635. if (i != stackTrace.size() - 1)
  636. builder.append('\n');
  637. }
  638. if (errorObject->hasProperty(callFrame, vm->propertyNames->stack))
  639. return;
  640. errorObject->putDirect(*vm, vm->propertyNames->stack, jsString(vm, builder.toString()), ReadOnly | DontDelete);
  641. }
  642. NEVER_INLINE HandlerInfo* Interpreter::throwException(CallFrame*& callFrame, JSValue& exceptionValue, unsigned bytecodeOffset)
  643. {
  644. CodeBlock* codeBlock = callFrame->codeBlock();
  645. bool isTermination = false;
  646. ASSERT(!exceptionValue.isEmpty());
  647. ASSERT(!exceptionValue.isCell() || exceptionValue.asCell());
  648. // This shouldn't be possible (hence the assertions), but we're already in the slowest of
  649. // slow cases, so let's harden against it anyway to be safe.
  650. if (exceptionValue.isEmpty() || (exceptionValue.isCell() && !exceptionValue.asCell()))
  651. exceptionValue = jsNull();
  652. // Set up the exception object
  653. if (exceptionValue.isObject()) {
  654. JSObject* exception = asObject(exceptionValue);
  655. if (exception->isErrorInstance() && static_cast<ErrorInstance*>(exception)->appendSourceToMessage())
  656. appendSourceToError(callFrame, static_cast<ErrorInstance*>(exception), bytecodeOffset);
  657. if (!hasErrorInfo(callFrame, exception)) {
  658. // FIXME: should only really be adding these properties to VM generated exceptions,
  659. // but the inspector currently requires these for all thrown objects.
  660. addErrorInfo(callFrame, exception, codeBlock->lineNumberForBytecodeOffset(bytecodeOffset), codeBlock->ownerExecutable()->source());
  661. }
  662. isTermination = isTerminatedExecutionException(exception);
  663. } else {
  664. if (!callFrame->vm().exceptionStack().size()) {
  665. Vector<StackFrame> stack;
  666. Interpreter::getStackTrace(&callFrame->vm(), stack);
  667. callFrame->vm().exceptionStack() = RefCountedArray<StackFrame>(stack);
  668. }
  669. }
  670. if (Debugger* debugger = callFrame->dynamicGlobalObject()->debugger()) {
  671. DebuggerCallFrame debuggerCallFrame(callFrame, exceptionValue);
  672. bool hasHandler = codeBlock->handlerForBytecodeOffset(bytecodeOffset);
  673. debugger->exception(debuggerCallFrame, codeBlock->ownerExecutable()->sourceID(), codeBlock->lineNumberForBytecodeOffset(bytecodeOffset), 0, hasHandler);
  674. }
  675. // Calculate an exception handler vPC, unwinding call frames as necessary.
  676. HandlerInfo* handler = 0;
  677. while (isTermination || !(handler = codeBlock->handlerForBytecodeOffset(bytecodeOffset))) {
  678. if (!unwindCallFrame(callFrame, exceptionValue, bytecodeOffset, codeBlock)) {
  679. if (LegacyProfiler* profiler = callFrame->vm().enabledProfiler())
  680. profiler->exceptionUnwind(callFrame);
  681. return 0;
  682. }
  683. }
  684. if (LegacyProfiler* profiler = callFrame->vm().enabledProfiler())
  685. profiler->exceptionUnwind(callFrame);
  686. // Unwind the scope chain within the exception handler's call frame.
  687. JSScope* scope = callFrame->scope();
  688. int scopeDelta = 0;
  689. if (!codeBlock->needsFullScopeChain() || codeBlock->codeType() != FunctionCode
  690. || callFrame->uncheckedR(codeBlock->activationRegister()).jsValue()) {
  691. int currentDepth = depth(codeBlock, scope);
  692. int targetDepth = handler->scopeDepth;
  693. scopeDelta = currentDepth - targetDepth;
  694. RELEASE_ASSERT(scopeDelta >= 0);
  695. }
  696. while (scopeDelta--)
  697. scope = scope->next();
  698. callFrame->setScope(scope);
  699. return handler;
  700. }
  701. static inline JSValue checkedReturn(JSValue returnValue)
  702. {
  703. ASSERT(returnValue);
  704. return returnValue;
  705. }
  706. static inline JSObject* checkedReturn(JSObject* returnValue)
  707. {
  708. ASSERT(returnValue);
  709. return returnValue;
  710. }
  711. class SamplingScope {
  712. public:
  713. SamplingScope(Interpreter* interpreter)
  714. : m_interpreter(interpreter)
  715. {
  716. interpreter->startSampling();
  717. }
  718. ~SamplingScope()
  719. {
  720. m_interpreter->stopSampling();
  721. }
  722. private:
  723. Interpreter* m_interpreter;
  724. };
  725. JSValue Interpreter::execute(ProgramExecutable* program, CallFrame* callFrame, JSObject* thisObj)
  726. {
  727. SamplingScope samplingScope(this);
  728. JSScope* scope = callFrame->scope();
  729. VM& vm = *scope->vm();
  730. ASSERT(isValidThisObject(thisObj, callFrame));
  731. ASSERT(!vm.exception);
  732. ASSERT(!vm.isCollectorBusy());
  733. if (vm.isCollectorBusy())
  734. return jsNull();
  735. StackStats::CheckPoint stackCheckPoint;
  736. const StackBounds& nativeStack = wtfThreadData().stack();
  737. StackPolicy policy(*this, nativeStack);
  738. if (!nativeStack.isSafeToRecurse(policy.requiredCapacity()))
  739. return checkedReturn(throwStackOverflowError(callFrame));
  740. // First check if the "program" is actually just a JSON object. If so,
  741. // we'll handle the JSON object here. Else, we'll handle real JS code
  742. // below at failedJSONP.
  743. DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
  744. Vector<JSONPData> JSONPData;
  745. bool parseResult;
  746. const String programSource = program->source().toString();
  747. if (programSource.isNull())
  748. return jsUndefined();
  749. if (programSource.is8Bit()) {
  750. LiteralParser<LChar> literalParser(callFrame, programSource.characters8(), programSource.length(), JSONP);
  751. parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
  752. } else {
  753. LiteralParser<UChar> literalParser(callFrame, programSource.characters16(), programSource.length(), JSONP);
  754. parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
  755. }
  756. if (parseResult) {
  757. JSGlobalObject* globalObject = scope->globalObject();
  758. JSValue result;
  759. for (unsigned entry = 0; entry < JSONPData.size(); entry++) {
  760. Vector<JSONPPathEntry> JSONPPath;
  761. JSONPPath.swap(JSONPData[entry].m_path);
  762. JSValue JSONPValue = JSONPData[entry].m_value.get();
  763. if (JSONPPath.size() == 1 && JSONPPath[0].m_type == JSONPPathEntryTypeDeclare) {
  764. if (globalObject->hasProperty(callFrame, JSONPPath[0].m_pathEntryName)) {
  765. PutPropertySlot slot;
  766. globalObject->methodTable()->put(globalObject, callFrame, JSONPPath[0].m_pathEntryName, JSONPValue, slot);
  767. } else
  768. globalObject->methodTable()->putDirectVirtual(globalObject, callFrame, JSONPPath[0].m_pathEntryName, JSONPValue, DontEnum | DontDelete);
  769. // var declarations return undefined
  770. result = jsUndefined();
  771. continue;
  772. }
  773. JSValue baseObject(globalObject);
  774. for (unsigned i = 0; i < JSONPPath.size() - 1; i++) {
  775. ASSERT(JSONPPath[i].m_type != JSONPPathEntryTypeDeclare);
  776. switch (JSONPPath[i].m_type) {
  777. case JSONPPathEntryTypeDot: {
  778. if (i == 0) {
  779. PropertySlot slot(globalObject);
  780. if (!globalObject->getPropertySlot(callFrame, JSONPPath[i].m_pathEntryName, slot)) {
  781. if (entry)
  782. return throwError(callFrame, createUndefinedVariableError(globalObject->globalExec(), JSONPPath[i].m_pathEntryName));
  783. goto failedJSONP;
  784. }
  785. baseObject = slot.getValue(callFrame, JSONPPath[i].m_pathEntryName);
  786. } else
  787. baseObject = baseObject.get(callFrame, JSONPPath[i].m_pathEntryName);
  788. if (callFrame->hadException())
  789. return jsUndefined();
  790. continue;
  791. }
  792. case JSONPPathEntryTypeLookup: {
  793. baseObject = baseObject.get(callFrame, JSONPPath[i].m_pathIndex);
  794. if (callFrame->hadException())
  795. return jsUndefined();
  796. continue;
  797. }
  798. default:
  799. RELEASE_ASSERT_NOT_REACHED();
  800. return jsUndefined();
  801. }
  802. }
  803. PutPropertySlot slot;
  804. switch (JSONPPath.last().m_type) {
  805. case JSONPPathEntryTypeCall: {
  806. JSValue function = baseObject.get(callFrame, JSONPPath.last().m_pathEntryName);
  807. if (callFrame->hadException())
  808. return jsUndefined();
  809. CallData callData;
  810. CallType callType = getCallData(function, callData);
  811. if (callType == CallTypeNone)
  812. return throwError(callFrame, createNotAFunctionError(callFrame, function));
  813. MarkedArgumentBuffer jsonArg;
  814. jsonArg.append(JSONPValue);
  815. JSValue thisValue = JSONPPath.size() == 1 ? jsUndefined(): baseObject;
  816. JSONPValue = JSC::call(callFrame, function, callType, callData, thisValue, jsonArg);
  817. if (callFrame->hadException())
  818. return jsUndefined();
  819. break;
  820. }
  821. case JSONPPathEntryTypeDot: {
  822. baseObject.put(callFrame, JSONPPath.last().m_pathEntryName, JSONPValue, slot);
  823. if (callFrame->hadException())
  824. return jsUndefined();
  825. break;
  826. }
  827. case JSONPPathEntryTypeLookup: {
  828. baseObject.putByIndex(callFrame, JSONPPath.last().m_pathIndex, JSONPValue, slot.isStrictMode());
  829. if (callFrame->hadException())
  830. return jsUndefined();
  831. break;
  832. }
  833. default:
  834. RELEASE_ASSERT_NOT_REACHED();
  835. return jsUndefined();
  836. }
  837. result = JSONPValue;
  838. }
  839. return result;
  840. }
  841. failedJSONP:
  842. // If we get here, then we have already proven that the script is not a JSON
  843. // object.
  844. // Compile source to bytecode if necessary:
  845. if (JSObject* error = program->initializeGlobalProperties(vm, callFrame, scope))
  846. return checkedReturn(throwError(callFrame, error));
  847. if (JSObject* error = program->compile(callFrame, scope))
  848. return checkedReturn(throwError(callFrame, error));
  849. ProgramCodeBlock* codeBlock = &program->generatedBytecode();
  850. if (UNLIKELY(vm.watchdog.didFire(callFrame)))
  851. return throwTerminatedExecutionException(callFrame);
  852. // Push the call frame for this invocation:
  853. ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.
  854. CallFrame* newCallFrame = m_stack.pushFrame(callFrame, codeBlock, scope, 1, 0);
  855. if (UNLIKELY(!newCallFrame))
  856. return checkedReturn(throwStackOverflowError(callFrame));
  857. // Set the arguments for the callee:
  858. newCallFrame->setThisValue(thisObj);
  859. if (LegacyProfiler* profiler = vm.enabledProfiler())
  860. profiler->willExecute(callFrame, program->sourceURL(), program->lineNo());
  861. // Execute the code:
  862. JSValue result;
  863. {
  864. SamplingTool::CallRecord callRecord(m_sampler.get());
  865. Watchdog::Scope watchdogScope(vm.watchdog);
  866. #if ENABLE(LLINT_C_LOOP)
  867. result = LLInt::CLoop::execute(newCallFrame, llint_program_prologue);
  868. #elif ENABLE(JIT)
  869. result = program->generatedJITCode().execute(&m_stack, newCallFrame, &vm);
  870. #endif // ENABLE(JIT)
  871. }
  872. if (LegacyProfiler* profiler = vm.enabledProfiler())
  873. profiler->didExecute(callFrame, program->sourceURL(), program->lineNo());
  874. m_stack.popFrame(newCallFrame);
  875. return checkedReturn(result);
  876. }
  877. JSValue Interpreter::executeCall(CallFrame* callFrame, JSObject* function, CallType callType, const CallData& callData, JSValue thisValue, const ArgList& args)
  878. {
  879. VM& vm = callFrame->vm();
  880. ASSERT(isValidThisObject(thisValue, callFrame));
  881. ASSERT(!callFrame->hadException());
  882. ASSERT(!vm.isCollectorBusy());
  883. if (vm.isCollectorBusy())
  884. return jsNull();
  885. StackStats::CheckPoint stackCheckPoint;
  886. const StackBounds& nativeStack = wtfThreadData().stack();
  887. StackPolicy policy(*this, nativeStack);
  888. if (!nativeStack.isSafeToRecurse(policy.requiredCapacity()))
  889. return checkedReturn(throwStackOverflowError(callFrame));
  890. bool isJSCall = (callType == CallTypeJS);
  891. JSScope* scope;
  892. CodeBlock* newCodeBlock;
  893. size_t argsCount = 1 + args.size(); // implicit "this" parameter
  894. if (isJSCall)
  895. scope = callData.js.scope;
  896. else {
  897. ASSERT(callType == CallTypeHost);
  898. scope = callFrame->scope();
  899. }
  900. DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
  901. if (isJSCall) {
  902. // Compile the callee:
  903. JSObject* compileError = callData.js.functionExecutable->compileForCall(callFrame, scope);
  904. if (UNLIKELY(!!compileError)) {
  905. return checkedReturn(throwError(callFrame, compileError));
  906. }
  907. newCodeBlock = &callData.js.functionExecutable->generatedBytecodeForCall();
  908. ASSERT(!!newCodeBlock);
  909. } else
  910. newCodeBlock = 0;
  911. if (UNLIKELY(vm.watchdog.didFire(callFrame)))
  912. return throwTerminatedExecutionException(callFrame);
  913. CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, function);
  914. if (UNLIKELY(!newCallFrame))
  915. return checkedReturn(throwStackOverflowError(callFrame));
  916. // Set the arguments for the callee:
  917. newCallFrame->setThisValue(thisValue);
  918. for (size_t i = 0; i < args.size(); ++i)
  919. newCallFrame->setArgument(i, args.at(i));
  920. if (LegacyProfiler* profiler = vm.enabledProfiler())
  921. profiler->willExecute(callFrame, function);
  922. JSValue result;
  923. {
  924. SamplingTool::CallRecord callRecord(m_sampler.get(), !isJSCall);
  925. Watchdog::Scope watchdogScope(vm.watchdog);
  926. // Execute the code:
  927. if (isJSCall) {
  928. #if ENABLE(LLINT_C_LOOP)
  929. result = LLInt::CLoop::execute(newCallFrame, llint_function_for_call_prologue);
  930. #elif ENABLE(JIT)
  931. result = callData.js.functionExecutable->generatedJITCodeForCall().execute(&m_stack, newCallFrame, &vm);
  932. #endif // ENABLE(JIT)
  933. } else
  934. result = JSValue::decode(callData.native.function(newCallFrame));
  935. }
  936. if (LegacyProfiler* profiler = vm.enabledProfiler())
  937. profiler->didExecute(callFrame, function);
  938. m_stack.popFrame(newCallFrame);
  939. return checkedReturn(result);
  940. }
  941. JSObject* Interpreter::executeConstruct(CallFrame* callFrame, JSObject* constructor, ConstructType constructType, const ConstructData& constructData, const ArgList& args)
  942. {
  943. VM& vm = callFrame->vm();
  944. ASSERT(!callFrame->hadException());
  945. ASSERT(!vm.isCollectorBusy());
  946. // We throw in this case because we have to return something "valid" but we're
  947. // already in an invalid state.
  948. if (vm.isCollectorBusy())
  949. return checkedReturn(throwStackOverflowError(callFrame));
  950. StackStats::CheckPoint stackCheckPoint;
  951. const StackBounds& nativeStack = wtfThreadData().stack();
  952. StackPolicy policy(*this, nativeStack);
  953. if (!nativeStack.isSafeToRecurse(policy.requiredCapacity()))
  954. return checkedReturn(throwStackOverflowError(callFrame));
  955. bool isJSConstruct = (constructType == ConstructTypeJS);
  956. JSScope* scope;
  957. CodeBlock* newCodeBlock;
  958. size_t argsCount = 1 + args.size(); // implicit "this" parameter
  959. if (isJSConstruct)
  960. scope = constructData.js.scope;
  961. else {
  962. ASSERT(constructType == ConstructTypeHost);
  963. scope = callFrame->scope();
  964. }
  965. DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
  966. if (isJSConstruct) {
  967. // Compile the callee:
  968. JSObject* compileError = constructData.js.functionExecutable->compileForConstruct(callFrame, scope);
  969. if (UNLIKELY(!!compileError)) {
  970. return checkedReturn(throwError(callFrame, compileError));
  971. }
  972. newCodeBlock = &constructData.js.functionExecutable->generatedBytecodeForConstruct();
  973. ASSERT(!!newCodeBlock);
  974. } else
  975. newCodeBlock = 0;
  976. if (UNLIKELY(vm.watchdog.didFire(callFrame)))
  977. return throwTerminatedExecutionException(callFrame);
  978. CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, constructor);
  979. if (UNLIKELY(!newCallFrame))
  980. return checkedReturn(throwStackOverflowError(callFrame));
  981. // Set the arguments for the callee:
  982. newCallFrame->setThisValue(jsUndefined());
  983. for (size_t i = 0; i < args.size(); ++i)
  984. newCallFrame->setArgument(i, args.at(i));
  985. if (LegacyProfiler* profiler = vm.enabledProfiler())
  986. profiler->willExecute(callFrame, constructor);
  987. JSValue result;
  988. {
  989. SamplingTool::CallRecord callRecord(m_sampler.get(), !isJSConstruct);
  990. Watchdog::Scope watchdogScope(vm.watchdog);
  991. // Execute the code.
  992. if (isJSConstruct) {
  993. #if ENABLE(LLINT_C_LOOP)
  994. result = LLInt::CLoop::execute(newCallFrame, llint_function_for_construct_prologue);
  995. #elif ENABLE(JIT)
  996. result = constructData.js.functionExecutable->generatedJITCodeForConstruct().execute(&m_stack, newCallFrame, &vm);
  997. #endif // ENABLE(JIT)
  998. } else
  999. result = JSValue::decode(constructData.native.function(newCallFrame));
  1000. }
  1001. if (LegacyProfiler* profiler = vm.enabledProfiler())
  1002. profiler->didExecute(callFrame, constructor);
  1003. m_stack.popFrame(newCallFrame);
  1004. if (callFrame->hadException())
  1005. return 0;
  1006. ASSERT(result.isObject());
  1007. return checkedReturn(asObject(result));
  1008. }
  1009. CallFrameClosure Interpreter::prepareForRepeatCall(FunctionExecutable* functionExecutable, CallFrame* callFrame, JSFunction* function, int argumentCountIncludingThis, JSScope* scope)
  1010. {
  1011. VM& vm = *scope->vm();
  1012. ASSERT(!vm.exception);
  1013. if (vm.isCollectorBusy())
  1014. return CallFrameClosure();
  1015. StackStats::CheckPoint stackCheckPoint;
  1016. const StackBounds& nativeStack = wtfThreadData().stack();
  1017. StackPolicy policy(*this, nativeStack);
  1018. if (!nativeStack.isSafeToRecurse(policy.requiredCapacity())) {
  1019. throwStackOverflowError(callFrame);
  1020. return CallFrameClosure();
  1021. }
  1022. // Compile the callee:
  1023. JSObject* error = functionExecutable->compileForCall(callFrame, scope);
  1024. if (error) {
  1025. throwError(callFrame, error);
  1026. return CallFrameClosure();
  1027. }
  1028. CodeBlock* newCodeBlock = &functionExecutable->generatedBytecodeForCall();
  1029. size_t argsCount = argumentCountIncludingThis;
  1030. CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, function);
  1031. if (UNLIKELY(!newCallFrame)) {
  1032. throwStackOverflowError(callFrame);
  1033. return CallFrameClosure();
  1034. }
  1035. if (UNLIKELY(!newCallFrame)) {
  1036. throwStackOverflowError(callFrame);
  1037. return CallFrameClosure();
  1038. }
  1039. // Return the successful closure:
  1040. CallFrameClosure result = { callFrame, newCallFrame, function, functionExecutable, &vm, scope, newCodeBlock->numParameters(), argumentCountIncludingThis };
  1041. return result;
  1042. }
  1043. JSValue Interpreter::execute(CallFrameClosure& closure)
  1044. {
  1045. VM& vm = *closure.vm;
  1046. SamplingScope samplingScope(this);
  1047. ASSERT(!vm.isCollectorBusy());
  1048. if (vm.isCollectorBusy())
  1049. return jsNull();
  1050. StackStats::CheckPoint stackCheckPoint;
  1051. m_stack.validateFence(closure.newCallFrame, "BEFORE");
  1052. closure.resetCallFrame();
  1053. m_stack.validateFence(closure.newCallFrame, "STEP 1");
  1054. if (LegacyProfiler* profiler = vm.enabledProfiler())
  1055. profiler->willExecute(closure.oldCallFrame, closure.function);
  1056. if (UNLIKELY(vm.watchdog.didFire(closure.oldCallFrame)))
  1057. return throwTerminatedExecutionException(closure.oldCallFrame);
  1058. // The code execution below may push more frames and point the topCallFrame
  1059. // to those newer frames, or it may pop to the top frame to the caller of
  1060. // the current repeat frame, or it may leave the top frame pointing to the
  1061. // current repeat frame.
  1062. //
  1063. // Hence, we need to preserve the topCallFrame here ourselves before
  1064. // repeating this call on a second callback function.
  1065. TopCallFrameSetter topCallFrame(vm, closure.newCallFrame);
  1066. // Execute the code:
  1067. JSValue result;
  1068. {
  1069. SamplingTool::CallRecord callRecord(m_sampler.get());
  1070. Watchdog::Scope watchdogScope(vm.watchdog);
  1071. #if ENABLE(LLINT_C_LOOP)
  1072. result = LLInt::CLoop::execute(closure.newCallFrame, llint_function_for_call_prologue);
  1073. #elif ENABLE(JIT)
  1074. result = closure.functionExecutable->generatedJITCodeForCall().execute(&m_stack, closure.newCallFrame, &vm);
  1075. #endif // ENABLE(JIT)
  1076. }
  1077. if (LegacyProfiler* profiler = vm.enabledProfiler())
  1078. profiler->didExecute(closure.oldCallFrame, closure.function);
  1079. m_stack.validateFence(closure.newCallFrame, "AFTER");
  1080. return checkedReturn(result);
  1081. }
  1082. void Interpreter::endRepeatCall(CallFrameClosure& closure)
  1083. {
  1084. m_stack.popFrame(closure.newCallFrame);
  1085. }
  1086. JSValue Interpreter::execute(EvalExecutable* eval, CallFrame* callFrame, JSValue thisValue, JSScope* scope)
  1087. {
  1088. VM& vm = *scope->vm();
  1089. SamplingScope samplingScope(this);
  1090. ASSERT(scope->vm() == &callFrame->vm());
  1091. ASSERT(isValidThisObject(thisValue, callFrame));
  1092. ASSERT(!vm.exception);
  1093. ASSERT(!vm.isCollectorBusy());
  1094. if (vm.isCollectorBusy())
  1095. return jsNull();
  1096. DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
  1097. StackStats::CheckPoint stackCheckPoint;
  1098. const StackBounds& nativeStack = wtfThreadData().stack();
  1099. StackPolicy policy(*this, nativeStack);
  1100. if (!nativeStack.isSafeToRecurse(policy.requiredCapacity()))
  1101. return checkedReturn(throwStackOverflowError(callFrame));
  1102. // Compile the callee:
  1103. JSObject* compileError = eval->compile(callFrame, scope);
  1104. if (UNLIKELY(!!compileError))
  1105. return checkedReturn(throwError(callFrame, compileError));
  1106. EvalCodeBlock* codeBlock = &eval->generatedBytecode();
  1107. JSObject* variableObject;
  1108. for (JSScope* node = scope; ; node = node->next()) {
  1109. RELEASE_ASSERT(node);
  1110. if (node->isVariableObject() && !node->isNameScopeObject()) {
  1111. variableObject = node;
  1112. break;
  1113. }
  1114. }
  1115. unsigned numVariables = codeBlock->numVariables();
  1116. int numFunctions = codeBlock->numberOfFunctionDecls();
  1117. if (numVariables || numFunctions) {
  1118. if (codeBlock->isStrictMode()) {
  1119. scope = StrictEvalActivation::create(callFrame);
  1120. variableObject = scope;
  1121. }
  1122. // Scope for BatchedTransitionOptimizer
  1123. BatchedTransitionOptimizer optimizer(vm, variableObject);
  1124. for (unsigned i = 0; i < numVariables; ++i) {
  1125. const Identifier& ident = codeBlock->variable(i);
  1126. if (!variableObject->hasProperty(callFrame, ident)) {
  1127. PutPropertySlot slot;
  1128. variableObject->methodTable()->put(variableObject, callFrame, ident, jsUndefined(), slot);
  1129. }
  1130. }
  1131. for (int i = 0; i < numFunctions; ++i) {
  1132. FunctionExecutable* function = codeBlock->functionDecl(i);
  1133. PutPropertySlot slot;
  1134. variableObject->methodTable()->put(variableObject, callFrame, function->name(), JSFunction::create(callFrame, function, scope), slot);
  1135. }
  1136. }
  1137. if (UNLIKELY(vm.watchdog.didFire(callFrame)))
  1138. return throwTerminatedExecutionException(callFrame);
  1139. // Push the frame:
  1140. ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.
  1141. CallFrame* newCallFrame = m_stack.pushFrame(callFrame, codeBlock, scope, 1, 0);
  1142. if (UNLIKELY(!newCallFrame))
  1143. return checkedReturn(throwStackOverflowError(callFrame));
  1144. // Set the arguments for the callee:
  1145. newCallFrame->setThisValue(thisValue);
  1146. if (LegacyProfiler* profiler = vm.enabledProfiler())
  1147. profiler->willExecute(callFrame, eval->sourceURL(), eval->lineNo());
  1148. // Execute the code:
  1149. JSValue result;
  1150. {
  1151. SamplingTool::CallRecord callRecord(m_sampler.get());
  1152. Watchdog::Scope watchdogScope(vm.watchdog);
  1153. #if ENABLE(LLINT_C_LOOP)
  1154. result = LLInt::CLoop::execute(newCallFrame, llint_eval_prologue);
  1155. #elif ENABLE(JIT)
  1156. result = eval->generatedJITCode().execute(&m_stack, newCallFrame, &vm);
  1157. #endif // ENABLE(JIT)
  1158. }
  1159. if (LegacyProfiler* profiler = vm.enabledProfiler())
  1160. profiler->didExecute(callFrame, eval->sourceURL(), eval->lineNo());
  1161. m_stack.popFrame(newCallFrame);
  1162. return checkedReturn(result);
  1163. }
  1164. NEVER_INLINE void Interpreter::debug(CallFrame* callFrame, DebugHookID debugHookID, int firstLine, int lastLine, int column)
  1165. {
  1166. Debugger* debugger = callFrame->dynamicGlobalObject()->debugger();
  1167. if (!debugger)
  1168. return;
  1169. switch (debugHookID) {
  1170. case DidEnterCallFrame:
  1171. debugger->callEvent(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), firstLine, column);
  1172. return;
  1173. case WillLeaveCallFrame:
  1174. debugger->returnEvent(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), lastLine, column);
  1175. return;
  1176. case WillExecuteStatement:
  1177. debugger->atStatement(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), firstLine, column);
  1178. return;
  1179. case WillExecuteProgram:
  1180. debugger->willExecuteProgram(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), firstLine, column);
  1181. return;
  1182. case DidExecuteProgram:
  1183. debugger->didExecuteProgram(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), lastLine, column);
  1184. return;
  1185. case DidReachBreakpoint:
  1186. debugger->didReachBreakpoint(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), lastLine, column);
  1187. return;
  1188. }
  1189. }
  1190. JSValue Interpreter::retrieveArgumentsFromVMCode(CallFrame* callFrame, JSFunction* function) const
  1191. {
  1192. CallFrame* functionCallFrame = findFunctionCallFrameFromVMCode(callFrame, function);
  1193. if (!functionCallFrame)
  1194. return jsNull();
  1195. Arguments* arguments = Arguments::create(functionCallFrame->vm(), functionCallFrame);
  1196. arguments->tearOff(functionCallFrame);
  1197. return JSValue(arguments);
  1198. }
  1199. JSValue Interpreter::retrieveCallerFromVMCode(CallFrame* callFrame, JSFunction* function) const
  1200. {
  1201. CallFrame* functionCallFrame = findFunctionCallFrameFromVMCode(callFrame, function);
  1202. if (!functionCallFrame)
  1203. return jsNull();
  1204. unsigned bytecodeOffset;
  1205. CodeBlock* unusedCallerCodeBlock = 0;
  1206. CallFrame* callerFrame = getCallerInfo(&callFrame->vm(), functionCallFrame, bytecodeOffset, unusedCallerCodeBlock);
  1207. if (!callerFrame)
  1208. return jsNull();
  1209. JSValue caller = callerFrame->callee();
  1210. if (!caller)
  1211. return jsNull();
  1212. // Skip over function bindings.
  1213. ASSERT(caller.isObject());
  1214. while (asObject(caller)->inherits(&JSBoundFunction::s_info)) {
  1215. callerFrame = getCallerInfo(&callFrame->vm(), callerFrame, bytecodeOffset, unusedCallerCodeBlock);
  1216. if (!callerFrame)
  1217. return jsNull();
  1218. caller = callerFrame->callee();
  1219. if (!caller)
  1220. return jsNull();
  1221. }
  1222. return caller;
  1223. }
  1224. void Interpreter::retrieveLastCaller(CallFrame* callFrame, int& lineNumber, intptr_t& sourceID, String& sourceURL, JSValue& function) const
  1225. {
  1226. function = JSValue();
  1227. lineNumber = -1;
  1228. sourceURL = String();
  1229. CallFrame* callerFrame = callFrame->callerFrame();
  1230. if (callerFrame->hasHostCallFrameFlag())
  1231. return;
  1232. CodeBlock* callerCodeBlock = callerFrame->codeBlock();
  1233. if (!callerCodeBlock)
  1234. return;
  1235. unsigned bytecodeOffset = 0;
  1236. bytecodeOffset = callerCodeBlock->bytecodeOffset(callerFrame, callFrame->returnPC());
  1237. lineNumber = callerCodeBlock->lineNumberForBytecodeOffset(bytecodeOffset - 1);
  1238. sourceID = callerCodeBlock->ownerExecutable()->sourceID();
  1239. sourceURL = callerCodeBlock->ownerExecutable()->sourceURL();
  1240. function = callerFrame->callee();
  1241. }
  1242. CallFrame* Interpreter::findFunctionCallFrameFromVMCode(CallFrame* callFrame, JSFunction* function)
  1243. {
  1244. for (CallFrame* candidate = callFrame->trueCallFrameFromVMCode(); candidate; candidate = candidate->trueCallerFrame()) {
  1245. if (candidate->callee() == function)
  1246. return candidate;
  1247. }
  1248. return 0;
  1249. }
  1250. void Interpreter::enableSampler()
  1251. {
  1252. #if ENABLE(OPCODE_SAMPLING)
  1253. if (!m_sampler) {
  1254. m_sampler = adoptPtr(new SamplingTool(this));
  1255. m_sampler->setup();
  1256. }
  1257. #endif
  1258. }
  1259. void Interpreter::dumpSampleData(ExecState* exec)
  1260. {
  1261. #if ENABLE(OPCODE_SAMPLING)
  1262. if (m_sampler)
  1263. m_sampler->dump(exec);
  1264. #else
  1265. UNUSED_PARAM(exec);
  1266. #endif
  1267. }
  1268. void Interpreter::startSampling()
  1269. {
  1270. #if ENABLE(SAMPLING_THREAD)
  1271. if (!m_sampleEntryDepth)
  1272. SamplingThread::start();
  1273. m_sampleEntryDepth++;
  1274. #endif
  1275. }
  1276. void Interpreter::stopSampling()
  1277. {
  1278. #if ENABLE(SAMPLING_THREAD)
  1279. m_sampleEntryDepth--;
  1280. if (!m_sampleEntryDepth)
  1281. SamplingThread::stop();
  1282. #endif
  1283. }
  1284. #endif // #if !(ENABLE(DETACHED_JIT) && BUILDING_DETACHED_JIT)
  1285. } // namespace JSC