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