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