Renamed StackIterator to StackVisitor.
[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 UnwindFunctor {
570 public:
571     UnwindFunctor(CallFrame*& callFrame, JSValue& exceptionValue, bool isTermination, CodeBlock*& codeBlock, HandlerInfo*& handler)
572         : m_callFrame(callFrame)
573         , m_exceptionValue(exceptionValue)
574         , m_isTermination(isTermination)
575         , m_codeBlock(codeBlock)
576         , m_handler(handler)
577     {
578     }
579
580     StackVisitor::Status operator()(StackVisitor& visitor)
581     {
582         VM& vm = m_callFrame->vm();
583         m_callFrame = visitor->callFrame();
584         m_codeBlock = visitor->codeBlock();
585         unsigned bytecodeOffset = visitor->bytecodeOffset();
586
587         if (m_isTermination || !(m_handler = m_codeBlock->handlerForBytecodeOffset(bytecodeOffset))) {
588         if (!unwindCallFrame(visitor, m_exceptionValue)) {
589             if (LegacyProfiler* profiler = vm.enabledProfiler())
590                 profiler->exceptionUnwind(m_callFrame);
591             return StackVisitor::Done;
592         }
593     } else
594         return StackVisitor::Done;
595
596     return StackVisitor::Continue;
597 }
598
599 private:
600     CallFrame*& m_callFrame;
601     JSValue& m_exceptionValue;
602     bool m_isTermination;
603     CodeBlock*& m_codeBlock;
604     HandlerInfo*& m_handler;
605 };
606
607 NEVER_INLINE HandlerInfo* Interpreter::unwind(CallFrame*& callFrame, JSValue& exceptionValue, unsigned bytecodeOffset)
608 {
609     CodeBlock* codeBlock = callFrame->codeBlock();
610     bool isTermination = false;
611
612     ASSERT(!exceptionValue.isEmpty());
613     ASSERT(!exceptionValue.isCell() || exceptionValue.asCell());
614     // This shouldn't be possible (hence the assertions), but we're already in the slowest of
615     // slow cases, so let's harden against it anyway to be safe.
616     if (exceptionValue.isEmpty() || (exceptionValue.isCell() && !exceptionValue.asCell()))
617         exceptionValue = jsNull();
618
619     if (exceptionValue.isObject()) {
620         isTermination = isTerminatedExecutionException(asObject(exceptionValue));
621     }
622
623     ASSERT(callFrame->vm().exceptionStack().size());
624     ASSERT(!exceptionValue.isObject() || asObject(exceptionValue)->hasProperty(callFrame, callFrame->vm().propertyNames->stack));
625
626     if (Debugger* debugger = callFrame->dynamicGlobalObject()->debugger()) {
627         // We need to clear the exception and the exception stack here in order to see if a new exception happens.
628         // Afterwards, the values are put back to continue processing this error.
629         ClearExceptionScope scope(&callFrame->vm());
630         
631         DebuggerCallFrame debuggerCallFrame(callFrame, exceptionValue);
632         bool hasHandler = codeBlock->handlerForBytecodeOffset(bytecodeOffset);
633         debugger->exception(debuggerCallFrame, codeBlock->ownerExecutable()->sourceID(), codeBlock->lineNumberForBytecodeOffset(bytecodeOffset), 0, hasHandler);
634     }
635
636     // Calculate an exception handler vPC, unwinding call frames as necessary.
637     HandlerInfo* handler = 0;
638     VM& vm = callFrame->vm();
639     ASSERT(callFrame == vm.topCallFrame);
640     UnwindFunctor functor(callFrame, exceptionValue, isTermination, codeBlock, handler);
641     callFrame->iterate(functor);
642     if (!handler)
643         return 0;
644
645     if (LegacyProfiler* profiler = vm.enabledProfiler())
646         profiler->exceptionUnwind(callFrame);
647
648     // Unwind the scope chain within the exception handler's call frame.
649     int targetScopeDepth = handler->scopeDepth;
650     if (codeBlock->needsActivation() && callFrame->uncheckedR(codeBlock->activationRegister()).jsValue())
651         ++targetScopeDepth;
652
653     JSScope* scope = callFrame->scope();
654     int scopeDelta = scope->depth() - targetScopeDepth;
655     RELEASE_ASSERT(scopeDelta >= 0);
656
657     while (scopeDelta--)
658         scope = scope->next();
659     callFrame->setScope(scope);
660
661     return handler;
662 }
663
664 static inline JSValue checkedReturn(JSValue returnValue)
665 {
666     ASSERT(returnValue);
667     return returnValue;
668 }
669
670 static inline JSObject* checkedReturn(JSObject* returnValue)
671 {
672     ASSERT(returnValue);
673     return returnValue;
674 }
675
676 class SamplingScope {
677 public:
678     SamplingScope(Interpreter* interpreter)
679         : m_interpreter(interpreter)
680     {
681         interpreter->startSampling();
682     }
683     ~SamplingScope()
684     {
685         m_interpreter->stopSampling();
686     }
687 private:
688     Interpreter* m_interpreter;
689 };
690
691 JSValue Interpreter::execute(ProgramExecutable* program, CallFrame* callFrame, JSObject* thisObj)
692 {
693     SamplingScope samplingScope(this);
694     
695     JSScope* scope = callFrame->scope();
696     VM& vm = *scope->vm();
697
698     ASSERT(!vm.exception());
699     ASSERT(!vm.isCollectorBusy());
700     if (vm.isCollectorBusy())
701         return jsNull();
702
703     StackStats::CheckPoint stackCheckPoint;
704     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
705     if (!vmStackBounds.isSafeToRecurse())
706         return checkedReturn(throwStackOverflowError(callFrame));
707
708     // First check if the "program" is actually just a JSON object. If so,
709     // we'll handle the JSON object here. Else, we'll handle real JS code
710     // below at failedJSONP.
711     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
712     Vector<JSONPData> JSONPData;
713     bool parseResult;
714     const String programSource = program->source().toString();
715     if (programSource.isNull())
716         return jsUndefined();
717     if (programSource.is8Bit()) {
718         LiteralParser<LChar> literalParser(callFrame, programSource.characters8(), programSource.length(), JSONP);
719         parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
720     } else {
721         LiteralParser<UChar> literalParser(callFrame, programSource.characters16(), programSource.length(), JSONP);
722         parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
723     }
724
725     if (parseResult) {
726         JSGlobalObject* globalObject = scope->globalObject();
727         JSValue result;
728         for (unsigned entry = 0; entry < JSONPData.size(); entry++) {
729             Vector<JSONPPathEntry> JSONPPath;
730             JSONPPath.swap(JSONPData[entry].m_path);
731             JSValue JSONPValue = JSONPData[entry].m_value.get();
732             if (JSONPPath.size() == 1 && JSONPPath[0].m_type == JSONPPathEntryTypeDeclare) {
733                 globalObject->addVar(callFrame, JSONPPath[0].m_pathEntryName);
734                 PutPropertySlot slot;
735                 globalObject->methodTable()->put(globalObject, callFrame, JSONPPath[0].m_pathEntryName, JSONPValue, slot);
736                 result = jsUndefined();
737                 continue;
738             }
739             JSValue baseObject(globalObject);
740             for (unsigned i = 0; i < JSONPPath.size() - 1; i++) {
741                 ASSERT(JSONPPath[i].m_type != JSONPPathEntryTypeDeclare);
742                 switch (JSONPPath[i].m_type) {
743                 case JSONPPathEntryTypeDot: {
744                     if (i == 0) {
745                         PropertySlot slot(globalObject);
746                         if (!globalObject->getPropertySlot(callFrame, JSONPPath[i].m_pathEntryName, slot)) {
747                             if (entry)
748                                 return callFrame->vm().throwException(callFrame, createUndefinedVariableError(globalObject->globalExec(), JSONPPath[i].m_pathEntryName));
749                             goto failedJSONP;
750                         }
751                         baseObject = slot.getValue(callFrame, JSONPPath[i].m_pathEntryName);
752                     } else
753                         baseObject = baseObject.get(callFrame, JSONPPath[i].m_pathEntryName);
754                     if (callFrame->hadException())
755                         return jsUndefined();
756                     continue;
757                 }
758                 case JSONPPathEntryTypeLookup: {
759                     baseObject = baseObject.get(callFrame, JSONPPath[i].m_pathIndex);
760                     if (callFrame->hadException())
761                         return jsUndefined();
762                     continue;
763                 }
764                 default:
765                     RELEASE_ASSERT_NOT_REACHED();
766                     return jsUndefined();
767                 }
768             }
769             PutPropertySlot slot;
770             switch (JSONPPath.last().m_type) {
771             case JSONPPathEntryTypeCall: {
772                 JSValue function = baseObject.get(callFrame, JSONPPath.last().m_pathEntryName);
773                 if (callFrame->hadException())
774                     return jsUndefined();
775                 CallData callData;
776                 CallType callType = getCallData(function, callData);
777                 if (callType == CallTypeNone)
778                     return callFrame->vm().throwException(callFrame, createNotAFunctionError(callFrame, function));
779                 MarkedArgumentBuffer jsonArg;
780                 jsonArg.append(JSONPValue);
781                 JSValue thisValue = JSONPPath.size() == 1 ? jsUndefined(): baseObject;
782                 JSONPValue = JSC::call(callFrame, function, callType, callData, thisValue, jsonArg);
783                 if (callFrame->hadException())
784                     return jsUndefined();
785                 break;
786             }
787             case JSONPPathEntryTypeDot: {
788                 baseObject.put(callFrame, JSONPPath.last().m_pathEntryName, JSONPValue, slot);
789                 if (callFrame->hadException())
790                     return jsUndefined();
791                 break;
792             }
793             case JSONPPathEntryTypeLookup: {
794                 baseObject.putByIndex(callFrame, JSONPPath.last().m_pathIndex, JSONPValue, slot.isStrictMode());
795                 if (callFrame->hadException())
796                     return jsUndefined();
797                 break;
798             }
799             default:
800                 RELEASE_ASSERT_NOT_REACHED();
801                     return jsUndefined();
802             }
803             result = JSONPValue;
804         }
805         return result;
806     }
807 failedJSONP:
808     // If we get here, then we have already proven that the script is not a JSON
809     // object.
810
811     // Compile source to bytecode if necessary:
812     if (JSObject* error = program->initializeGlobalProperties(vm, callFrame, scope))
813         return checkedReturn(callFrame->vm().throwException(callFrame, error));
814
815     if (JSObject* error = program->prepareForExecution(callFrame, scope, CodeForCall))
816         return checkedReturn(callFrame->vm().throwException(callFrame, error));
817
818     ProgramCodeBlock* codeBlock = program->codeBlock();
819
820     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
821         return throwTerminatedExecutionException(callFrame);
822
823     // Push the call frame for this invocation:
824     ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.
825     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, codeBlock, scope, 1, 0);
826     if (UNLIKELY(!newCallFrame))
827         return checkedReturn(throwStackOverflowError(callFrame));
828
829     // Set the arguments for the callee:
830     newCallFrame->setThisValue(thisObj);
831
832     if (LegacyProfiler* profiler = vm.enabledProfiler())
833         profiler->willExecute(callFrame, program->sourceURL(), program->lineNo());
834
835     // Execute the code:
836     JSValue result;
837     {
838         SamplingTool::CallRecord callRecord(m_sampler.get());
839         Watchdog::Scope watchdogScope(vm.watchdog);
840
841 #if ENABLE(LLINT_C_LOOP)
842         result = LLInt::CLoop::execute(newCallFrame, llint_program_prologue);
843 #elif ENABLE(JIT)
844         result = program->generatedJITCode()->execute(&m_stack, newCallFrame, &vm);
845 #endif // ENABLE(JIT)
846     }
847
848     if (LegacyProfiler* profiler = vm.enabledProfiler())
849         profiler->didExecute(callFrame, program->sourceURL(), program->lineNo());
850
851     m_stack.popFrame(newCallFrame);
852
853     return checkedReturn(result);
854 }
855
856 JSValue Interpreter::executeCall(CallFrame* callFrame, JSObject* function, CallType callType, const CallData& callData, JSValue thisValue, const ArgList& args)
857 {
858     VM& vm = callFrame->vm();
859     ASSERT(!callFrame->hadException());
860     ASSERT(!vm.isCollectorBusy());
861     if (vm.isCollectorBusy())
862         return jsNull();
863
864     StackStats::CheckPoint stackCheckPoint;
865     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
866     if (!vmStackBounds.isSafeToRecurse())
867         return checkedReturn(throwStackOverflowError(callFrame));
868
869     bool isJSCall = (callType == CallTypeJS);
870     JSScope* scope;
871     CodeBlock* newCodeBlock;
872     size_t argsCount = 1 + args.size(); // implicit "this" parameter
873
874     if (isJSCall)
875         scope = callData.js.scope;
876     else {
877         ASSERT(callType == CallTypeHost);
878         scope = callFrame->scope();
879     }
880     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
881
882     if (isJSCall) {
883         // Compile the callee:
884         JSObject* compileError = callData.js.functionExecutable->prepareForExecution(callFrame, scope, CodeForCall);
885         if (UNLIKELY(!!compileError)) {
886             return checkedReturn(callFrame->vm().throwException(callFrame, compileError));
887         }
888         newCodeBlock = callData.js.functionExecutable->codeBlockForCall();
889         ASSERT(!!newCodeBlock);
890         newCodeBlock->m_shouldAlwaysBeInlined = false;
891     } else
892         newCodeBlock = 0;
893
894     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
895         return throwTerminatedExecutionException(callFrame);
896
897     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, function);
898     if (UNLIKELY(!newCallFrame))
899         return checkedReturn(throwStackOverflowError(callFrame));
900
901     // Set the arguments for the callee:
902     newCallFrame->setThisValue(thisValue);
903     for (size_t i = 0; i < args.size(); ++i)
904         newCallFrame->setArgument(i, args.at(i));
905
906     if (LegacyProfiler* profiler = vm.enabledProfiler())
907         profiler->willExecute(callFrame, function);
908
909     JSValue result;
910     {
911         SamplingTool::CallRecord callRecord(m_sampler.get(), !isJSCall);
912         Watchdog::Scope watchdogScope(vm.watchdog);
913
914         // Execute the code:
915         if (isJSCall) {
916 #if ENABLE(LLINT_C_LOOP)
917             result = LLInt::CLoop::execute(newCallFrame, llint_function_for_call_prologue);
918 #elif ENABLE(JIT)
919             result = callData.js.functionExecutable->generatedJITCodeForCall()->execute(&m_stack, newCallFrame, &vm);
920 #endif // ENABLE(JIT)
921         } else
922             result = JSValue::decode(callData.native.function(newCallFrame));
923     }
924
925     if (LegacyProfiler* profiler = vm.enabledProfiler())
926         profiler->didExecute(callFrame, function);
927
928     m_stack.popFrame(newCallFrame);
929     return checkedReturn(result);
930 }
931
932 JSObject* Interpreter::executeConstruct(CallFrame* callFrame, JSObject* constructor, ConstructType constructType, const ConstructData& constructData, const ArgList& args)
933 {
934     VM& vm = callFrame->vm();
935     ASSERT(!callFrame->hadException());
936     ASSERT(!vm.isCollectorBusy());
937     // We throw in this case because we have to return something "valid" but we're
938     // already in an invalid state.
939     if (vm.isCollectorBusy())
940         return checkedReturn(throwStackOverflowError(callFrame));
941
942     StackStats::CheckPoint stackCheckPoint;
943     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
944     if (!vmStackBounds.isSafeToRecurse())
945         return checkedReturn(throwStackOverflowError(callFrame));
946
947     bool isJSConstruct = (constructType == ConstructTypeJS);
948     JSScope* scope;
949     CodeBlock* newCodeBlock;
950     size_t argsCount = 1 + args.size(); // implicit "this" parameter
951
952     if (isJSConstruct)
953         scope = constructData.js.scope;
954     else {
955         ASSERT(constructType == ConstructTypeHost);
956         scope = callFrame->scope();
957     }
958
959     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
960
961     if (isJSConstruct) {
962         // Compile the callee:
963         JSObject* compileError = constructData.js.functionExecutable->prepareForExecution(callFrame, scope, CodeForConstruct);
964         if (UNLIKELY(!!compileError)) {
965             return checkedReturn(callFrame->vm().throwException(callFrame, compileError));
966         }
967         newCodeBlock = constructData.js.functionExecutable->codeBlockForConstruct();
968         ASSERT(!!newCodeBlock);
969         newCodeBlock->m_shouldAlwaysBeInlined = false;
970     } else
971         newCodeBlock = 0;
972
973     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
974         return throwTerminatedExecutionException(callFrame);
975
976     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, constructor);
977     if (UNLIKELY(!newCallFrame))
978         return checkedReturn(throwStackOverflowError(callFrame));
979
980     // Set the arguments for the callee:
981     newCallFrame->setThisValue(jsUndefined());
982     for (size_t i = 0; i < args.size(); ++i)
983         newCallFrame->setArgument(i, args.at(i));
984
985     if (LegacyProfiler* profiler = vm.enabledProfiler())
986         profiler->willExecute(callFrame, constructor);
987
988     JSValue result;
989     {
990         SamplingTool::CallRecord callRecord(m_sampler.get(), !isJSConstruct);
991         Watchdog::Scope watchdogScope(vm.watchdog);
992
993         // Execute the code.
994         if (isJSConstruct) {
995 #if ENABLE(LLINT_C_LOOP)
996             result = LLInt::CLoop::execute(newCallFrame, llint_function_for_construct_prologue);
997 #elif ENABLE(JIT)
998             result = constructData.js.functionExecutable->generatedJITCodeForConstruct()->execute(&m_stack, newCallFrame, &vm);
999 #endif // ENABLE(JIT)
1000         } else {
1001             result = JSValue::decode(constructData.native.function(newCallFrame));
1002             if (!callFrame->hadException()) {
1003                 ASSERT_WITH_MESSAGE(result.isObject(), "Host constructor returned non object.");
1004                 if (!result.isObject())
1005                     throwTypeError(newCallFrame);
1006             }
1007         }
1008     }
1009
1010     if (LegacyProfiler* profiler = vm.enabledProfiler())
1011         profiler->didExecute(callFrame, constructor);
1012
1013     m_stack.popFrame(newCallFrame);
1014
1015     if (callFrame->hadException())
1016         return 0;
1017     ASSERT(result.isObject());
1018     return checkedReturn(asObject(result));
1019 }
1020
1021 CallFrameClosure Interpreter::prepareForRepeatCall(FunctionExecutable* functionExecutable, CallFrame* callFrame, JSFunction* function, int argumentCountIncludingThis, JSScope* scope)
1022 {
1023     VM& vm = *scope->vm();
1024     ASSERT(!vm.exception());
1025     
1026     if (vm.isCollectorBusy())
1027         return CallFrameClosure();
1028
1029     StackStats::CheckPoint stackCheckPoint;
1030     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
1031     if (!vmStackBounds.isSafeToRecurse()) {
1032         throwStackOverflowError(callFrame);
1033         return CallFrameClosure();
1034     }
1035
1036     // Compile the callee:
1037     JSObject* error = functionExecutable->prepareForExecution(callFrame, scope, CodeForCall);
1038     if (error) {
1039         callFrame->vm().throwException(callFrame, error);
1040         return CallFrameClosure();
1041     }
1042     CodeBlock* newCodeBlock = functionExecutable->codeBlockForCall();
1043     newCodeBlock->m_shouldAlwaysBeInlined = false;
1044
1045     size_t argsCount = argumentCountIncludingThis;
1046
1047     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, function);  
1048     if (UNLIKELY(!newCallFrame)) {
1049         throwStackOverflowError(callFrame);
1050         return CallFrameClosure();
1051     }
1052
1053     if (UNLIKELY(!newCallFrame)) {
1054         throwStackOverflowError(callFrame);
1055         return CallFrameClosure();
1056     }
1057
1058     // Return the successful closure:
1059     CallFrameClosure result = { callFrame, newCallFrame, function, functionExecutable, &vm, scope, newCodeBlock->numParameters(), argumentCountIncludingThis };
1060     return result;
1061 }
1062
1063 JSValue Interpreter::execute(CallFrameClosure& closure) 
1064 {
1065     VM& vm = *closure.vm;
1066     SamplingScope samplingScope(this);
1067     
1068     ASSERT(!vm.isCollectorBusy());
1069     if (vm.isCollectorBusy())
1070         return jsNull();
1071
1072     StackStats::CheckPoint stackCheckPoint;
1073     m_stack.validateFence(closure.newCallFrame, "BEFORE");
1074     closure.resetCallFrame();
1075     m_stack.validateFence(closure.newCallFrame, "STEP 1");
1076
1077     if (LegacyProfiler* profiler = vm.enabledProfiler())
1078         profiler->willExecute(closure.oldCallFrame, closure.function);
1079
1080     if (UNLIKELY(vm.watchdog.didFire(closure.oldCallFrame)))
1081         return throwTerminatedExecutionException(closure.oldCallFrame);
1082
1083     // The code execution below may push more frames and point the topCallFrame
1084     // to those newer frames, or it may pop to the top frame to the caller of
1085     // the current repeat frame, or it may leave the top frame pointing to the
1086     // current repeat frame.
1087     //
1088     // Hence, we need to preserve the topCallFrame here ourselves before
1089     // repeating this call on a second callback function.
1090
1091     TopCallFrameSetter topCallFrame(vm, closure.newCallFrame);
1092
1093     // Execute the code:
1094     JSValue result;
1095     {
1096         SamplingTool::CallRecord callRecord(m_sampler.get());
1097         Watchdog::Scope watchdogScope(vm.watchdog);
1098
1099 #if ENABLE(LLINT_C_LOOP)
1100         result = LLInt::CLoop::execute(closure.newCallFrame, llint_function_for_call_prologue);
1101 #elif ENABLE(JIT)
1102         result = closure.functionExecutable->generatedJITCodeForCall()->execute(&m_stack, closure.newCallFrame, &vm);
1103 #endif // ENABLE(JIT)
1104     }
1105
1106     if (LegacyProfiler* profiler = vm.enabledProfiler())
1107         profiler->didExecute(closure.oldCallFrame, closure.function);
1108
1109     m_stack.validateFence(closure.newCallFrame, "AFTER");
1110     return checkedReturn(result);
1111 }
1112
1113 void Interpreter::endRepeatCall(CallFrameClosure& closure)
1114 {
1115     m_stack.popFrame(closure.newCallFrame);
1116 }
1117
1118 JSValue Interpreter::execute(EvalExecutable* eval, CallFrame* callFrame, JSValue thisValue, JSScope* scope)
1119 {
1120     VM& vm = *scope->vm();
1121     SamplingScope samplingScope(this);
1122     
1123     ASSERT(scope->vm() == &callFrame->vm());
1124     ASSERT(!vm.exception());
1125     ASSERT(!vm.isCollectorBusy());
1126     if (vm.isCollectorBusy())
1127         return jsNull();
1128
1129     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
1130
1131     StackStats::CheckPoint stackCheckPoint;
1132     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
1133     if (!vmStackBounds.isSafeToRecurse())
1134         return checkedReturn(throwStackOverflowError(callFrame));
1135
1136     unsigned numVariables = eval->numVariables();
1137     int numFunctions = eval->numberOfFunctionDecls();
1138
1139     JSScope* variableObject;
1140     if ((numVariables || numFunctions) && eval->isStrictMode()) {
1141         scope = StrictEvalActivation::create(callFrame);
1142         variableObject = scope;
1143     } else {
1144         for (JSScope* node = scope; ; node = node->next()) {
1145             RELEASE_ASSERT(node);
1146             if (node->isVariableObject() && !node->isNameScopeObject()) {
1147                 variableObject = node;
1148                 break;
1149             }
1150         }
1151     }
1152
1153     JSObject* compileError = eval->prepareForExecution(callFrame, scope, CodeForCall);
1154     if (UNLIKELY(!!compileError))
1155         return checkedReturn(callFrame->vm().throwException(callFrame, compileError));
1156     EvalCodeBlock* codeBlock = eval->codeBlock();
1157
1158     if (numVariables || numFunctions) {
1159         BatchedTransitionOptimizer optimizer(vm, variableObject);
1160         if (variableObject->next())
1161             variableObject->globalObject()->varInjectionWatchpoint()->notifyWrite();
1162
1163         for (unsigned i = 0; i < numVariables; ++i) {
1164             const Identifier& ident = codeBlock->variable(i);
1165             if (!variableObject->hasProperty(callFrame, ident)) {
1166                 PutPropertySlot slot;
1167                 variableObject->methodTable()->put(variableObject, callFrame, ident, jsUndefined(), slot);
1168             }
1169         }
1170
1171         for (int i = 0; i < numFunctions; ++i) {
1172             FunctionExecutable* function = codeBlock->functionDecl(i);
1173             PutPropertySlot slot;
1174             variableObject->methodTable()->put(variableObject, callFrame, function->name(), JSFunction::create(callFrame, function, scope), slot);
1175         }
1176     }
1177
1178     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
1179         return throwTerminatedExecutionException(callFrame);
1180
1181     // Push the frame:
1182     ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.
1183     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, codeBlock, scope, 1, 0);
1184     if (UNLIKELY(!newCallFrame))
1185         return checkedReturn(throwStackOverflowError(callFrame));
1186
1187     // Set the arguments for the callee:
1188     newCallFrame->setThisValue(thisValue);
1189
1190     if (LegacyProfiler* profiler = vm.enabledProfiler())
1191         profiler->willExecute(callFrame, eval->sourceURL(), eval->lineNo());
1192
1193     // Execute the code:
1194     JSValue result;
1195     {
1196         SamplingTool::CallRecord callRecord(m_sampler.get());
1197         Watchdog::Scope watchdogScope(vm.watchdog);
1198
1199 #if ENABLE(LLINT_C_LOOP)
1200         result = LLInt::CLoop::execute(newCallFrame, llint_eval_prologue);
1201 #elif ENABLE(JIT)
1202         result = eval->generatedJITCode()->execute(&m_stack, newCallFrame, &vm);
1203 #endif // ENABLE(JIT)
1204     }
1205
1206     if (LegacyProfiler* profiler = vm.enabledProfiler())
1207         profiler->didExecute(callFrame, eval->sourceURL(), eval->lineNo());
1208
1209     m_stack.popFrame(newCallFrame);
1210     return checkedReturn(result);
1211 }
1212
1213 NEVER_INLINE void Interpreter::debug(CallFrame* callFrame, DebugHookID debugHookID, int firstLine, int lastLine, int column)
1214 {
1215     Debugger* debugger = callFrame->dynamicGlobalObject()->debugger();
1216     if (!debugger)
1217         return;
1218
1219     switch (debugHookID) {
1220         case DidEnterCallFrame:
1221             debugger->callEvent(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), firstLine, column);
1222             return;
1223         case WillLeaveCallFrame:
1224             debugger->returnEvent(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), lastLine, column);
1225             return;
1226         case WillExecuteStatement:
1227             debugger->atStatement(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), firstLine, column);
1228             return;
1229         case WillExecuteProgram:
1230             debugger->willExecuteProgram(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), firstLine, column);
1231             return;
1232         case DidExecuteProgram:
1233             debugger->didExecuteProgram(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), lastLine, column);
1234             return;
1235         case DidReachBreakpoint:
1236             debugger->didReachBreakpoint(callFrame, callFrame->codeBlock()->ownerExecutable()->sourceID(), lastLine, column);
1237             return;
1238     }
1239 }    
1240
1241 void Interpreter::enableSampler()
1242 {
1243 #if ENABLE(OPCODE_SAMPLING)
1244     if (!m_sampler) {
1245         m_sampler = adoptPtr(new SamplingTool(this));
1246         m_sampler->setup();
1247     }
1248 #endif
1249 }
1250 void Interpreter::dumpSampleData(ExecState* exec)
1251 {
1252 #if ENABLE(OPCODE_SAMPLING)
1253     if (m_sampler)
1254         m_sampler->dump(exec);
1255 #else
1256     UNUSED_PARAM(exec);
1257 #endif
1258 }
1259 void Interpreter::startSampling()
1260 {
1261 #if ENABLE(SAMPLING_THREAD)
1262     if (!m_sampleEntryDepth)
1263         SamplingThread::start();
1264
1265     m_sampleEntryDepth++;
1266 #endif
1267 }
1268 void Interpreter::stopSampling()
1269 {
1270 #if ENABLE(SAMPLING_THREAD)
1271     m_sampleEntryDepth--;
1272     if (!m_sampleEntryDepth)
1273         SamplingThread::stop();
1274 #endif
1275 }
1276
1277 } // namespace JSC