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