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