Fix the non-DFG build.
[WebKit-https.git] / Source / JavaScriptCore / interpreter / Interpreter.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "Interpreter.h"
32
33 #include "Arguments.h"
34 #include "BatchedTransitionOptimizer.h"
35 #include "CallFrame.h"
36 #include "CallFrameClosure.h"
37 #include "CallFrameInlines.h"
38 #include "CodeBlock.h"
39 #include "Heap.h"
40 #include "Debugger.h"
41 #include "DebuggerCallFrame.h"
42 #include "ErrorInstance.h"
43 #include "EvalCodeCache.h"
44 #include "ExceptionHelpers.h"
45 #include "GetterSetter.h"
46 #include "JSActivation.h"
47 #include "JSArray.h"
48 #include "JSBoundFunction.h"
49 #include "JSNameScope.h"
50 #include "JSNotAnObject.h"
51 #include "JSPropertyNameIterator.h"
52 #include "JSStackInlines.h"
53 #include "JSString.h"
54 #include "JSWithScope.h"
55 #include "LLIntCLoop.h"
56 #include "LegacyProfiler.h"
57 #include "LiteralParser.h"
58 #include "NameInstance.h"
59 #include "ObjectPrototype.h"
60 #include "Operations.h"
61 #include "Parser.h"
62 #include "RegExpObject.h"
63 #include "RegExpPrototype.h"
64 #include "Register.h"
65 #include "SamplingTool.h"
66 #include "StackVisitor.h"
67 #include "StrictEvalActivation.h"
68 #include "StrongInlines.h"
69 #include "VMStackBounds.h"
70 #include <limits.h>
71 #include <stdio.h>
72 #include <wtf/StackStats.h>
73 #include <wtf/StringPrintStream.h>
74 #include <wtf/Threading.h>
75 #include <wtf/WTFThreadData.h>
76 #include <wtf/text/StringBuilder.h>
77
78 #if ENABLE(JIT)
79 #include "JIT.h"
80 #endif
81
82 #define WTF_USE_GCC_COMPUTED_GOTO_WORKAROUND (ENABLE(LLINT) && !defined(__llvm__))
83
84 using namespace std;
85
86 namespace JSC {
87
88 Interpreter::ErrorHandlingMode::ErrorHandlingMode(ExecState *exec)
89     : m_interpreter(*exec->interpreter())
90 {
91     if (!m_interpreter.m_errorHandlingModeReentry)
92         m_interpreter.stack().enableErrorStackReserve();
93     m_interpreter.m_errorHandlingModeReentry++;
94 }
95
96 Interpreter::ErrorHandlingMode::~ErrorHandlingMode()
97 {
98     m_interpreter.m_errorHandlingModeReentry--;
99     ASSERT(m_interpreter.m_errorHandlingModeReentry >= 0);
100     if (!m_interpreter.m_errorHandlingModeReentry)
101         m_interpreter.stack().disableErrorStackReserve();
102 }
103
104 JSValue eval(CallFrame* callFrame)
105 {
106     if (!callFrame->argumentCount())
107         return jsUndefined();
108
109     JSValue program = callFrame->argument(0);
110     if (!program.isString())
111         return program;
112     
113     TopCallFrameSetter topCallFrame(callFrame->vm(), callFrame);
114     String programSource = asString(program)->value(callFrame);
115     if (callFrame->hadException())
116         return JSValue();
117     
118     CallFrame* callerFrame = callFrame->callerFrame();
119     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
120     JSScope* callerScopeChain = callerFrame->scope();
121     EvalExecutable* eval = callerCodeBlock->evalCodeCache().tryGet(callerCodeBlock->isStrictMode(), programSource, callerScopeChain);
122
123     if (!eval) {
124         if (!callerCodeBlock->isStrictMode()) {
125             // FIXME: We can use the preparser in strict mode, we just need additional logic
126             // to prevent duplicates.
127             if (programSource.is8Bit()) {
128                 LiteralParser<LChar> preparser(callFrame, programSource.characters8(), programSource.length(), NonStrictJSON);
129                 if (JSValue parsedObject = preparser.tryLiteralParse())
130                     return parsedObject;
131             } else {
132                 LiteralParser<UChar> preparser(callFrame, programSource.characters16(), programSource.length(), NonStrictJSON);
133                 if (JSValue parsedObject = preparser.tryLiteralParse())
134                     return parsedObject;                
135             }
136         }
137         
138         // If the literal parser bailed, it should not have thrown exceptions.
139         ASSERT(!callFrame->vm().exception());
140
141         eval = callerCodeBlock->evalCodeCache().getSlow(callFrame, callerCodeBlock->ownerExecutable(), callerCodeBlock->isStrictMode(), programSource, callerScopeChain);
142         if (!eval)
143             return jsUndefined();
144     }
145
146     JSValue thisValue = callerFrame->thisValue();
147     Interpreter* interpreter = callFrame->vm().interpreter;
148     return interpreter->execute(eval, callFrame, thisValue, callerScopeChain);
149 }
150
151 CallFrame* loadVarargs(CallFrame* callFrame, JSStack* stack, JSValue thisValue, JSValue arguments, int firstFreeRegister)
152 {
153     if (!arguments) { // f.apply(x, arguments), with arguments unmodified.
154         unsigned argumentCountIncludingThis = callFrame->argumentCountIncludingThis();
155         CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister - argumentCountIncludingThis - JSStack::CallFrameHeaderSize);
156         if (argumentCountIncludingThis > Arguments::MaxArguments + 1 || !stack->grow(newCallFrame->registers())) {
157             callFrame->vm().throwException(callFrame, createStackOverflowError(callFrame));
158             return 0;
159         }
160
161         newCallFrame->setArgumentCountIncludingThis(argumentCountIncludingThis);
162         newCallFrame->setThisValue(thisValue);
163         for (size_t i = 0; i < callFrame->argumentCount(); ++i)
164             newCallFrame->setArgument(i, callFrame->argumentAfterCapture(i));
165         return newCallFrame;
166     }
167
168     if (arguments.isUndefinedOrNull()) {
169         CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister - 1 - JSStack::CallFrameHeaderSize);
170         if (!stack->grow(newCallFrame->registers())) {
171             callFrame->vm().throwException(callFrame, createStackOverflowError(callFrame));
172             return 0;
173         }
174         newCallFrame->setArgumentCountIncludingThis(1);
175         newCallFrame->setThisValue(thisValue);
176         return newCallFrame;
177     }
178
179     if (!arguments.isObject()) {
180         callFrame->vm().throwException(callFrame, createInvalidParameterError(callFrame, "Function.prototype.apply", arguments));
181         return 0;
182     }
183
184     if (asObject(arguments)->classInfo() == Arguments::info()) {
185         Arguments* argsObject = asArguments(arguments);
186         unsigned argCount = argsObject->length(callFrame);
187         CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister - CallFrame::offsetFor(argCount + 1));
188         if (argCount > Arguments::MaxArguments || !stack->grow(newCallFrame->registers())) {
189             callFrame->vm().throwException(callFrame, createStackOverflowError(callFrame));
190             return 0;
191         }
192         newCallFrame->setArgumentCountIncludingThis(argCount + 1);
193         newCallFrame->setThisValue(thisValue);
194         argsObject->copyToArguments(callFrame, newCallFrame, argCount);
195         return newCallFrame;
196     }
197
198     if (isJSArray(arguments)) {
199         JSArray* array = asArray(arguments);
200         unsigned argCount = array->length();
201         CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister - CallFrame::offsetFor(argCount + 1));
202         if (argCount > Arguments::MaxArguments || !stack->grow(newCallFrame->registers())) {
203             callFrame->vm().throwException(callFrame, createStackOverflowError(callFrame));
204             return 0;
205         }
206         newCallFrame->setArgumentCountIncludingThis(argCount + 1);
207         newCallFrame->setThisValue(thisValue);
208         array->copyToArguments(callFrame, newCallFrame, argCount);
209         return newCallFrame;
210     }
211
212     JSObject* argObject = asObject(arguments);
213     unsigned argCount = argObject->get(callFrame, callFrame->propertyNames().length).toUInt32(callFrame);
214     CallFrame* newCallFrame = CallFrame::create(callFrame->registers() + firstFreeRegister - CallFrame::offsetFor(argCount + 1));
215     if (argCount > Arguments::MaxArguments || !stack->grow(newCallFrame->registers())) {
216         callFrame->vm().throwException(callFrame,  createStackOverflowError(callFrame));
217         return 0;
218     }
219     newCallFrame->setArgumentCountIncludingThis(argCount + 1);
220     newCallFrame->setThisValue(thisValue);
221     for (size_t i = 0; i < argCount; ++i) {
222         newCallFrame->setArgument(i, asObject(arguments)->get(callFrame, i));
223         if (UNLIKELY(callFrame->vm().exception()))
224             return 0;
225     }
226     return newCallFrame;
227 }
228
229 Interpreter::Interpreter(VM& vm)
230     : m_sampleEntryDepth(0)
231     , m_vm(vm)
232     , m_stack(vm)
233     , m_errorHandlingModeReentry(0)
234 #if !ASSERT_DISABLED
235     , m_initialized(false)
236 #endif
237 {
238 }
239
240 Interpreter::~Interpreter()
241 {
242 }
243
244 void Interpreter::initialize(bool canUseJIT)
245 {
246     UNUSED_PARAM(canUseJIT);
247
248 #if ENABLE(COMPUTED_GOTO_OPCODES) && ENABLE(LLINT)
249     m_opcodeTable = LLInt::opcodeMap();
250     for (int i = 0; i < numOpcodeIDs; ++i)
251         m_opcodeIDTable.add(m_opcodeTable[i], static_cast<OpcodeID>(i));
252 #endif
253
254 #if !ASSERT_DISABLED
255     m_initialized = true;
256 #endif
257
258 #if ENABLE(OPCODE_SAMPLING)
259     enableSampler();
260 #endif
261 }
262
263 #ifdef NDEBUG
264
265 void Interpreter::dumpCallFrame(CallFrame*)
266 {
267 }
268
269 #else
270
271 void Interpreter::dumpCallFrame(CallFrame* callFrame)
272 {
273     callFrame->codeBlock()->dumpBytecode();
274     dumpRegisters(callFrame);
275 }
276
277 class DumpRegisterFunctor {
278 public:
279     DumpRegisterFunctor(const Register*& it)
280         : m_hasSkippedFirstFrame(false)
281         , m_it(it)
282     {
283     }
284
285     StackVisitor::Status operator()(StackVisitor& visitor)
286     {
287         if (!m_hasSkippedFirstFrame) {
288             m_hasSkippedFirstFrame = true;
289             return StackVisitor::Continue;
290         }
291
292         unsigned line = 0;
293         unsigned unusedColumn = 0;
294         visitor->computeLineAndColumn(line, unusedColumn);
295         dataLogF("[ReturnVPC]                | %10p | %d (line %d)\n", m_it, visitor->bytecodeOffset(), line);
296         ++m_it;
297         return StackVisitor::Done;
298     }
299
300 private:
301     bool m_hasSkippedFirstFrame;
302     const Register*& m_it;
303 };
304
305 void Interpreter::dumpRegisters(CallFrame* callFrame)
306 {
307     dataLogF("Register frame: \n\n");
308     dataLogF("-----------------------------------------------------------------------------\n");
309     dataLogF("            use            |   address  |                value               \n");
310     dataLogF("-----------------------------------------------------------------------------\n");
311
312     CodeBlock* codeBlock = callFrame->codeBlock();
313     const Register* it;
314     const Register* end;
315
316     it = callFrame->registers() + JSStack::CallFrameHeaderSize + callFrame->argumentCountIncludingThis();
317     end = callFrame->registers() + JSStack::CallFrameHeaderSize;
318     while (it > end) {
319         JSValue v = it->jsValue();
320         int registerNumber = it - callFrame->registers();
321         String name = codeBlock->nameForRegister(registerNumber);
322         dataLogF("[r% 3d %14s]      | %10p | %-16s 0x%lld \n", registerNumber, name.ascii().data(), it, toCString(v).data(), (long long)JSValue::encode(v));
323         it++;
324     }
325     
326     dataLogF("-----------------------------------------------------------------------------\n");
327     dataLogF("[ArgumentCount]            | %10p | %lu \n", it, (unsigned long) callFrame->argumentCount());
328     --it;
329     dataLogF("[CallerFrame]              | %10p | %p \n", it, callFrame->callerFrame());
330     --it;
331     dataLogF("[Callee]                   | %10p | %p \n", it, callFrame->callee());
332     --it;
333     dataLogF("[ScopeChain]               | %10p | %p \n", it, callFrame->scope());
334     --it;
335 #if ENABLE(JIT)
336     AbstractPC pc = callFrame->abstractReturnPC(callFrame->vm());
337     if (pc.hasJITReturnAddress())
338         dataLogF("[ReturnJITPC]              | %10p | %p \n", it, pc.jitReturnAddress().value());
339 #endif
340
341     DumpRegisterFunctor functor(it);
342     callFrame->iterate(functor);
343
344     dataLogF("[CodeBlock]                | %10p | %p \n", it, callFrame->codeBlock());
345     --it;
346     dataLogF("-----------------------------------------------------------------------------\n");
347
348     int registerCount = 0;
349
350     end = it - codeBlock->m_numVars;
351     if (it != end) {
352         do {
353             JSValue v = it->jsValue();
354             int registerNumber = it - callFrame->registers();
355             String name = codeBlock->nameForRegister(registerNumber);
356             dataLogF("[r% 3d %14s]      | %10p | %-16s 0x%lld \n", registerNumber, name.ascii().data(), it, toCString(v).data(), (long long)JSValue::encode(v));
357             --it;
358             --registerCount;
359         } while (it != end);
360     }
361     dataLogF("-----------------------------------------------------------------------------\n");
362
363     end = it + codeBlock->m_numCalleeRegisters - codeBlock->m_numVars;
364     if (it != end) {
365         do {
366             JSValue v = (*it).jsValue();
367             dataLogF("[r% 3d]                     | %10p | %-16s 0x%lld \n", registerCount, it, toCString(v).data(), (long long)JSValue::encode(v));
368             ++it;
369             ++registerCount;
370         } while (it != end);
371     }
372     dataLogF("-----------------------------------------------------------------------------\n");
373 }
374
375 #endif
376
377 bool Interpreter::isOpcode(Opcode opcode)
378 {
379 #if ENABLE(COMPUTED_GOTO_OPCODES)
380 #if !ENABLE(LLINT)
381     return static_cast<OpcodeID>(bitwise_cast<uintptr_t>(opcode)) <= op_end;
382 #else
383     return opcode != HashTraits<Opcode>::emptyValue()
384         && !HashTraits<Opcode>::isDeletedValue(opcode)
385         && m_opcodeIDTable.contains(opcode);
386 #endif
387 #else
388     return opcode >= 0 && opcode <= op_end;
389 #endif
390 }
391
392 static bool unwindCallFrame(StackVisitor& visitor, JSValue exceptionValue)
393 {
394     CallFrame* callFrame = visitor->callFrame();
395     CodeBlock* codeBlock = visitor->codeBlock();
396     CodeBlock* oldCodeBlock = codeBlock;
397     JSScope* scope = callFrame->scope();
398
399     if (Debugger* debugger = callFrame->dynamicGlobalObject()->debugger()) {
400         int line = codeBlock->ownerExecutable()->lastLine();
401         DebuggerCallFrame debuggerCallFrame(callFrame, line, 0, exceptionValue);
402         if (callFrame->callee())
403             debugger->returnEvent(debuggerCallFrame);
404         else
405             debugger->didExecuteProgram(debuggerCallFrame);
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()).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())).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, JSValue& exceptionValue, bool isTermination, CodeBlock*& codeBlock, HandlerInfo*& handler)
607         : m_callFrame(callFrame)
608         , m_exceptionValue(exceptionValue)
609         , m_isTermination(isTermination)
610         , m_codeBlock(codeBlock)
611         , m_handler(handler)
612     {
613     }
614
615     StackVisitor::Status operator()(StackVisitor& visitor)
616     {
617         VM& vm = m_callFrame->vm();
618         m_callFrame = visitor->callFrame();
619         m_codeBlock = visitor->codeBlock();
620         unsigned bytecodeOffset = visitor->bytecodeOffset();
621
622         if (m_isTermination || !(m_handler = m_codeBlock->handlerForBytecodeOffset(bytecodeOffset))) {
623             if (!unwindCallFrame(visitor, m_exceptionValue)) {
624                 if (LegacyProfiler* profiler = vm.enabledProfiler())
625                     profiler->exceptionUnwind(m_callFrame);
626                 return StackVisitor::Done;
627             }
628         } else
629             return StackVisitor::Done;
630
631         return StackVisitor::Continue;
632     }
633
634 private:
635     CallFrame*& m_callFrame;
636     JSValue& m_exceptionValue;
637     bool m_isTermination;
638     CodeBlock*& m_codeBlock;
639     HandlerInfo*& m_handler;
640 };
641
642 NEVER_INLINE HandlerInfo* Interpreter::unwind(CallFrame*& callFrame, JSValue& exceptionValue, unsigned bytecodeOffset)
643 {
644     CodeBlock* codeBlock = callFrame->codeBlock();
645     bool isTermination = false;
646
647     ASSERT(!exceptionValue.isEmpty());
648     ASSERT(!exceptionValue.isCell() || exceptionValue.asCell());
649     // This shouldn't be possible (hence the assertions), but we're already in the slowest of
650     // slow cases, so let's harden against it anyway to be safe.
651     if (exceptionValue.isEmpty() || (exceptionValue.isCell() && !exceptionValue.asCell()))
652         exceptionValue = jsNull();
653
654     if (exceptionValue.isObject()) {
655         isTermination = isTerminatedExecutionException(asObject(exceptionValue));
656     }
657
658     ASSERT(callFrame->vm().exceptionStack().size());
659     ASSERT(!exceptionValue.isObject() || asObject(exceptionValue)->hasProperty(callFrame, callFrame->vm().propertyNames->stack));
660
661     if (Debugger* debugger = callFrame->dynamicGlobalObject()->debugger()) {
662         // We need to clear the exception and the exception stack here in order to see if a new exception happens.
663         // Afterwards, the values are put back to continue processing this error.
664         ClearExceptionScope scope(&callFrame->vm());
665         int line = codeBlock->lineNumberForBytecodeOffset(bytecodeOffset);
666         int column = codeBlock->columnNumberForBytecodeOffset(bytecodeOffset);
667         DebuggerCallFrame debuggerCallFrame(callFrame, line, column, exceptionValue);
668
669         bool hasHandler;
670         if (isTermination)
671             hasHandler = false;
672         else {
673             GetExceptionHandlerFunctor functor;
674             callFrame->iterate(functor);
675             hasHandler = !!functor.handler();
676         }
677
678         debugger->exception(debuggerCallFrame, hasHandler);
679     }
680
681     // Calculate an exception handler vPC, unwinding call frames as necessary.
682     HandlerInfo* handler = 0;
683     VM& vm = callFrame->vm();
684     ASSERT(callFrame == vm.topCallFrame);
685     UnwindFunctor functor(callFrame, exceptionValue, isTermination, codeBlock, handler);
686     callFrame->iterate(functor);
687     if (!handler)
688         return 0;
689
690     if (LegacyProfiler* profiler = vm.enabledProfiler())
691         profiler->exceptionUnwind(callFrame);
692
693     // Unwind the scope chain within the exception handler's call frame.
694     int targetScopeDepth = handler->scopeDepth;
695     if (codeBlock->needsActivation() && callFrame->uncheckedR(codeBlock->activationRegister()).jsValue())
696         ++targetScopeDepth;
697
698     JSScope* scope = callFrame->scope();
699     int scopeDelta = scope->depth() - targetScopeDepth;
700     RELEASE_ASSERT(scopeDelta >= 0);
701
702     while (scopeDelta--)
703         scope = scope->next();
704     callFrame->setScope(scope);
705
706     return handler;
707 }
708
709 static inline JSValue checkedReturn(JSValue returnValue)
710 {
711     ASSERT(returnValue);
712     return returnValue;
713 }
714
715 static inline JSObject* checkedReturn(JSObject* returnValue)
716 {
717     ASSERT(returnValue);
718     return returnValue;
719 }
720
721 class SamplingScope {
722 public:
723     SamplingScope(Interpreter* interpreter)
724         : m_interpreter(interpreter)
725     {
726         interpreter->startSampling();
727     }
728     ~SamplingScope()
729     {
730         m_interpreter->stopSampling();
731     }
732 private:
733     Interpreter* m_interpreter;
734 };
735
736 JSValue Interpreter::execute(ProgramExecutable* program, CallFrame* callFrame, JSObject* thisObj)
737 {
738     SamplingScope samplingScope(this);
739     
740     JSScope* scope = callFrame->scope();
741     VM& vm = *scope->vm();
742
743     ASSERT(!vm.exception());
744     ASSERT(!vm.isCollectorBusy());
745     if (vm.isCollectorBusy())
746         return jsNull();
747
748     StackStats::CheckPoint stackCheckPoint;
749     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
750     if (!vmStackBounds.isSafeToRecurse())
751         return checkedReturn(throwStackOverflowError(callFrame));
752
753     // First check if the "program" is actually just a JSON object. If so,
754     // we'll handle the JSON object here. Else, we'll handle real JS code
755     // below at failedJSONP.
756     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
757     Vector<JSONPData> JSONPData;
758     bool parseResult;
759     const String programSource = program->source().toString();
760     if (programSource.isNull())
761         return jsUndefined();
762     if (programSource.is8Bit()) {
763         LiteralParser<LChar> literalParser(callFrame, programSource.characters8(), programSource.length(), JSONP);
764         parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
765     } else {
766         LiteralParser<UChar> literalParser(callFrame, programSource.characters16(), programSource.length(), JSONP);
767         parseResult = literalParser.tryJSONPParse(JSONPData, scope->globalObject()->globalObjectMethodTable()->supportsRichSourceInfo(scope->globalObject()));
768     }
769
770     if (parseResult) {
771         JSGlobalObject* globalObject = scope->globalObject();
772         JSValue result;
773         for (unsigned entry = 0; entry < JSONPData.size(); entry++) {
774             Vector<JSONPPathEntry> JSONPPath;
775             JSONPPath.swap(JSONPData[entry].m_path);
776             JSValue JSONPValue = JSONPData[entry].m_value.get();
777             if (JSONPPath.size() == 1 && JSONPPath[0].m_type == JSONPPathEntryTypeDeclare) {
778                 globalObject->addVar(callFrame, JSONPPath[0].m_pathEntryName);
779                 PutPropertySlot slot;
780                 globalObject->methodTable()->put(globalObject, callFrame, JSONPPath[0].m_pathEntryName, JSONPValue, slot);
781                 result = jsUndefined();
782                 continue;
783             }
784             JSValue baseObject(globalObject);
785             for (unsigned i = 0; i < JSONPPath.size() - 1; i++) {
786                 ASSERT(JSONPPath[i].m_type != JSONPPathEntryTypeDeclare);
787                 switch (JSONPPath[i].m_type) {
788                 case JSONPPathEntryTypeDot: {
789                     if (i == 0) {
790                         PropertySlot slot(globalObject);
791                         if (!globalObject->getPropertySlot(callFrame, JSONPPath[i].m_pathEntryName, slot)) {
792                             if (entry)
793                                 return callFrame->vm().throwException(callFrame, createUndefinedVariableError(globalObject->globalExec(), JSONPPath[i].m_pathEntryName));
794                             goto failedJSONP;
795                         }
796                         baseObject = slot.getValue(callFrame, JSONPPath[i].m_pathEntryName);
797                     } else
798                         baseObject = baseObject.get(callFrame, JSONPPath[i].m_pathEntryName);
799                     if (callFrame->hadException())
800                         return jsUndefined();
801                     continue;
802                 }
803                 case JSONPPathEntryTypeLookup: {
804                     baseObject = baseObject.get(callFrame, JSONPPath[i].m_pathIndex);
805                     if (callFrame->hadException())
806                         return jsUndefined();
807                     continue;
808                 }
809                 default:
810                     RELEASE_ASSERT_NOT_REACHED();
811                     return jsUndefined();
812                 }
813             }
814             PutPropertySlot slot;
815             switch (JSONPPath.last().m_type) {
816             case JSONPPathEntryTypeCall: {
817                 JSValue function = baseObject.get(callFrame, JSONPPath.last().m_pathEntryName);
818                 if (callFrame->hadException())
819                     return jsUndefined();
820                 CallData callData;
821                 CallType callType = getCallData(function, callData);
822                 if (callType == CallTypeNone)
823                     return callFrame->vm().throwException(callFrame, createNotAFunctionError(callFrame, function));
824                 MarkedArgumentBuffer jsonArg;
825                 jsonArg.append(JSONPValue);
826                 JSValue thisValue = JSONPPath.size() == 1 ? jsUndefined(): baseObject;
827                 JSONPValue = JSC::call(callFrame, function, callType, callData, thisValue, jsonArg);
828                 if (callFrame->hadException())
829                     return jsUndefined();
830                 break;
831             }
832             case JSONPPathEntryTypeDot: {
833                 baseObject.put(callFrame, JSONPPath.last().m_pathEntryName, JSONPValue, slot);
834                 if (callFrame->hadException())
835                     return jsUndefined();
836                 break;
837             }
838             case JSONPPathEntryTypeLookup: {
839                 baseObject.putByIndex(callFrame, JSONPPath.last().m_pathIndex, JSONPValue, slot.isStrictMode());
840                 if (callFrame->hadException())
841                     return jsUndefined();
842                 break;
843             }
844             default:
845                 RELEASE_ASSERT_NOT_REACHED();
846                     return jsUndefined();
847             }
848             result = JSONPValue;
849         }
850         return result;
851     }
852 failedJSONP:
853     // If we get here, then we have already proven that the script is not a JSON
854     // object.
855
856     // Compile source to bytecode if necessary:
857     if (JSObject* error = program->initializeGlobalProperties(vm, callFrame, scope))
858         return checkedReturn(callFrame->vm().throwException(callFrame, error));
859
860     if (JSObject* error = program->prepareForExecution(callFrame, scope, CodeForCall))
861         return checkedReturn(callFrame->vm().throwException(callFrame, error));
862
863     ProgramCodeBlock* codeBlock = program->codeBlock();
864
865     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
866         return throwTerminatedExecutionException(callFrame);
867
868     // Push the call frame for this invocation:
869     ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.
870     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, codeBlock, scope, 1, 0);
871     if (UNLIKELY(!newCallFrame))
872         return checkedReturn(throwStackOverflowError(callFrame));
873
874     // Set the arguments for the callee:
875     newCallFrame->setThisValue(thisObj);
876
877     if (LegacyProfiler* profiler = vm.enabledProfiler())
878         profiler->willExecute(callFrame, program->sourceURL(), program->lineNo());
879
880     // Execute the code:
881     JSValue result;
882     {
883         SamplingTool::CallRecord callRecord(m_sampler.get());
884         Watchdog::Scope watchdogScope(vm.watchdog);
885
886 #if ENABLE(LLINT_C_LOOP)
887         result = LLInt::CLoop::execute(newCallFrame, llint_program_prologue);
888 #elif ENABLE(JIT)
889         result = program->generatedJITCode()->execute(&m_stack, newCallFrame, &vm);
890 #endif // ENABLE(JIT)
891     }
892
893     if (LegacyProfiler* profiler = vm.enabledProfiler())
894         profiler->didExecute(callFrame, program->sourceURL(), program->lineNo());
895
896     m_stack.popFrame(newCallFrame);
897
898     return checkedReturn(result);
899 }
900
901 JSValue Interpreter::executeCall(CallFrame* callFrame, JSObject* function, CallType callType, const CallData& callData, JSValue thisValue, const ArgList& args)
902 {
903     VM& vm = callFrame->vm();
904     ASSERT(!callFrame->hadException());
905     ASSERT(!vm.isCollectorBusy());
906     if (vm.isCollectorBusy())
907         return jsNull();
908
909     StackStats::CheckPoint stackCheckPoint;
910     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
911     if (!vmStackBounds.isSafeToRecurse())
912         return checkedReturn(throwStackOverflowError(callFrame));
913
914     bool isJSCall = (callType == CallTypeJS);
915     JSScope* scope;
916     CodeBlock* newCodeBlock;
917     size_t argsCount = 1 + args.size(); // implicit "this" parameter
918
919     if (isJSCall)
920         scope = callData.js.scope;
921     else {
922         ASSERT(callType == CallTypeHost);
923         scope = callFrame->scope();
924     }
925     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
926
927     if (isJSCall) {
928         // Compile the callee:
929         JSObject* compileError = callData.js.functionExecutable->prepareForExecution(callFrame, scope, CodeForCall);
930         if (UNLIKELY(!!compileError)) {
931             return checkedReturn(callFrame->vm().throwException(callFrame, compileError));
932         }
933         newCodeBlock = callData.js.functionExecutable->codeBlockForCall();
934         ASSERT(!!newCodeBlock);
935         newCodeBlock->m_shouldAlwaysBeInlined = false;
936     } else
937         newCodeBlock = 0;
938
939     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
940         return throwTerminatedExecutionException(callFrame);
941
942     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, function);
943     if (UNLIKELY(!newCallFrame))
944         return checkedReturn(throwStackOverflowError(callFrame));
945
946     // Set the arguments for the callee:
947     newCallFrame->setThisValue(thisValue);
948     for (size_t i = 0; i < args.size(); ++i)
949         newCallFrame->setArgument(i, args.at(i));
950
951     if (LegacyProfiler* profiler = vm.enabledProfiler())
952         profiler->willExecute(callFrame, function);
953
954     JSValue result;
955     {
956         SamplingTool::CallRecord callRecord(m_sampler.get(), !isJSCall);
957         Watchdog::Scope watchdogScope(vm.watchdog);
958
959         // Execute the code:
960         if (isJSCall) {
961 #if ENABLE(LLINT_C_LOOP)
962             result = LLInt::CLoop::execute(newCallFrame, llint_function_for_call_prologue);
963 #elif ENABLE(JIT)
964             result = callData.js.functionExecutable->generatedJITCodeForCall()->execute(&m_stack, newCallFrame, &vm);
965 #endif // ENABLE(JIT)
966         } else
967             result = JSValue::decode(callData.native.function(newCallFrame));
968     }
969
970     if (LegacyProfiler* profiler = vm.enabledProfiler())
971         profiler->didExecute(callFrame, function);
972
973     m_stack.popFrame(newCallFrame);
974     return checkedReturn(result);
975 }
976
977 JSObject* Interpreter::executeConstruct(CallFrame* callFrame, JSObject* constructor, ConstructType constructType, const ConstructData& constructData, const ArgList& args)
978 {
979     VM& vm = callFrame->vm();
980     ASSERT(!callFrame->hadException());
981     ASSERT(!vm.isCollectorBusy());
982     // We throw in this case because we have to return something "valid" but we're
983     // already in an invalid state.
984     if (vm.isCollectorBusy())
985         return checkedReturn(throwStackOverflowError(callFrame));
986
987     StackStats::CheckPoint stackCheckPoint;
988     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
989     if (!vmStackBounds.isSafeToRecurse())
990         return checkedReturn(throwStackOverflowError(callFrame));
991
992     bool isJSConstruct = (constructType == ConstructTypeJS);
993     JSScope* scope;
994     CodeBlock* newCodeBlock;
995     size_t argsCount = 1 + args.size(); // implicit "this" parameter
996
997     if (isJSConstruct)
998         scope = constructData.js.scope;
999     else {
1000         ASSERT(constructType == ConstructTypeHost);
1001         scope = callFrame->scope();
1002     }
1003
1004     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
1005
1006     if (isJSConstruct) {
1007         // Compile the callee:
1008         JSObject* compileError = constructData.js.functionExecutable->prepareForExecution(callFrame, scope, CodeForConstruct);
1009         if (UNLIKELY(!!compileError)) {
1010             return checkedReturn(callFrame->vm().throwException(callFrame, compileError));
1011         }
1012         newCodeBlock = constructData.js.functionExecutable->codeBlockForConstruct();
1013         ASSERT(!!newCodeBlock);
1014         newCodeBlock->m_shouldAlwaysBeInlined = false;
1015     } else
1016         newCodeBlock = 0;
1017
1018     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
1019         return throwTerminatedExecutionException(callFrame);
1020
1021     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, constructor);
1022     if (UNLIKELY(!newCallFrame))
1023         return checkedReturn(throwStackOverflowError(callFrame));
1024
1025     // Set the arguments for the callee:
1026     newCallFrame->setThisValue(jsUndefined());
1027     for (size_t i = 0; i < args.size(); ++i)
1028         newCallFrame->setArgument(i, args.at(i));
1029
1030     if (LegacyProfiler* profiler = vm.enabledProfiler())
1031         profiler->willExecute(callFrame, constructor);
1032
1033     JSValue result;
1034     {
1035         SamplingTool::CallRecord callRecord(m_sampler.get(), !isJSConstruct);
1036         Watchdog::Scope watchdogScope(vm.watchdog);
1037
1038         // Execute the code.
1039         if (isJSConstruct) {
1040 #if ENABLE(LLINT_C_LOOP)
1041             result = LLInt::CLoop::execute(newCallFrame, llint_function_for_construct_prologue);
1042 #elif ENABLE(JIT)
1043             result = constructData.js.functionExecutable->generatedJITCodeForConstruct()->execute(&m_stack, newCallFrame, &vm);
1044 #endif // ENABLE(JIT)
1045         } else {
1046             result = JSValue::decode(constructData.native.function(newCallFrame));
1047             if (!callFrame->hadException()) {
1048                 ASSERT_WITH_MESSAGE(result.isObject(), "Host constructor returned non object.");
1049                 if (!result.isObject())
1050                     throwTypeError(newCallFrame);
1051             }
1052         }
1053     }
1054
1055     if (LegacyProfiler* profiler = vm.enabledProfiler())
1056         profiler->didExecute(callFrame, constructor);
1057
1058     m_stack.popFrame(newCallFrame);
1059
1060     if (callFrame->hadException())
1061         return 0;
1062     ASSERT(result.isObject());
1063     return checkedReturn(asObject(result));
1064 }
1065
1066 CallFrameClosure Interpreter::prepareForRepeatCall(FunctionExecutable* functionExecutable, CallFrame* callFrame, JSFunction* function, int argumentCountIncludingThis, JSScope* scope)
1067 {
1068     VM& vm = *scope->vm();
1069     ASSERT(!vm.exception());
1070     
1071     if (vm.isCollectorBusy())
1072         return CallFrameClosure();
1073
1074     StackStats::CheckPoint stackCheckPoint;
1075     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
1076     if (!vmStackBounds.isSafeToRecurse()) {
1077         throwStackOverflowError(callFrame);
1078         return CallFrameClosure();
1079     }
1080
1081     // Compile the callee:
1082     JSObject* error = functionExecutable->prepareForExecution(callFrame, scope, CodeForCall);
1083     if (error) {
1084         callFrame->vm().throwException(callFrame, error);
1085         return CallFrameClosure();
1086     }
1087     CodeBlock* newCodeBlock = functionExecutable->codeBlockForCall();
1088     newCodeBlock->m_shouldAlwaysBeInlined = false;
1089
1090     size_t argsCount = argumentCountIncludingThis;
1091
1092     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, newCodeBlock, scope, argsCount, function);  
1093     if (UNLIKELY(!newCallFrame)) {
1094         throwStackOverflowError(callFrame);
1095         return CallFrameClosure();
1096     }
1097
1098     if (UNLIKELY(!newCallFrame)) {
1099         throwStackOverflowError(callFrame);
1100         return CallFrameClosure();
1101     }
1102
1103     // Return the successful closure:
1104     CallFrameClosure result = { callFrame, newCallFrame, function, functionExecutable, &vm, scope, newCodeBlock->numParameters(), argumentCountIncludingThis };
1105     return result;
1106 }
1107
1108 JSValue Interpreter::execute(CallFrameClosure& closure) 
1109 {
1110     VM& vm = *closure.vm;
1111     SamplingScope samplingScope(this);
1112     
1113     ASSERT(!vm.isCollectorBusy());
1114     if (vm.isCollectorBusy())
1115         return jsNull();
1116
1117     StackStats::CheckPoint stackCheckPoint;
1118     m_stack.validateFence(closure.newCallFrame, "BEFORE");
1119     closure.resetCallFrame();
1120     m_stack.validateFence(closure.newCallFrame, "STEP 1");
1121
1122     if (LegacyProfiler* profiler = vm.enabledProfiler())
1123         profiler->willExecute(closure.oldCallFrame, closure.function);
1124
1125     if (UNLIKELY(vm.watchdog.didFire(closure.oldCallFrame)))
1126         return throwTerminatedExecutionException(closure.oldCallFrame);
1127
1128     // The code execution below may push more frames and point the topCallFrame
1129     // to those newer frames, or it may pop to the top frame to the caller of
1130     // the current repeat frame, or it may leave the top frame pointing to the
1131     // current repeat frame.
1132     //
1133     // Hence, we need to preserve the topCallFrame here ourselves before
1134     // repeating this call on a second callback function.
1135
1136     TopCallFrameSetter topCallFrame(vm, closure.newCallFrame);
1137
1138     // Execute the code:
1139     JSValue result;
1140     {
1141         SamplingTool::CallRecord callRecord(m_sampler.get());
1142         Watchdog::Scope watchdogScope(vm.watchdog);
1143
1144 #if ENABLE(LLINT_C_LOOP)
1145         result = LLInt::CLoop::execute(closure.newCallFrame, llint_function_for_call_prologue);
1146 #elif ENABLE(JIT)
1147         result = closure.functionExecutable->generatedJITCodeForCall()->execute(&m_stack, closure.newCallFrame, &vm);
1148 #endif // ENABLE(JIT)
1149     }
1150
1151     if (LegacyProfiler* profiler = vm.enabledProfiler())
1152         profiler->didExecute(closure.oldCallFrame, closure.function);
1153
1154     m_stack.validateFence(closure.newCallFrame, "AFTER");
1155     return checkedReturn(result);
1156 }
1157
1158 void Interpreter::endRepeatCall(CallFrameClosure& closure)
1159 {
1160     m_stack.popFrame(closure.newCallFrame);
1161 }
1162
1163 JSValue Interpreter::execute(EvalExecutable* eval, CallFrame* callFrame, JSValue thisValue, JSScope* scope)
1164 {
1165     VM& vm = *scope->vm();
1166     SamplingScope samplingScope(this);
1167     
1168     ASSERT(scope->vm() == &callFrame->vm());
1169     ASSERT(!vm.exception());
1170     ASSERT(!vm.isCollectorBusy());
1171     if (vm.isCollectorBusy())
1172         return jsNull();
1173
1174     DynamicGlobalObjectScope globalObjectScope(vm, scope->globalObject());
1175
1176     StackStats::CheckPoint stackCheckPoint;
1177     const VMStackBounds vmStackBounds(vm, wtfThreadData().stack());
1178     if (!vmStackBounds.isSafeToRecurse())
1179         return checkedReturn(throwStackOverflowError(callFrame));
1180
1181     unsigned numVariables = eval->numVariables();
1182     int numFunctions = eval->numberOfFunctionDecls();
1183
1184     JSScope* variableObject;
1185     if ((numVariables || numFunctions) && eval->isStrictMode()) {
1186         scope = StrictEvalActivation::create(callFrame);
1187         variableObject = scope;
1188     } else {
1189         for (JSScope* node = scope; ; node = node->next()) {
1190             RELEASE_ASSERT(node);
1191             if (node->isVariableObject() && !node->isNameScopeObject()) {
1192                 variableObject = node;
1193                 break;
1194             }
1195         }
1196     }
1197
1198     JSObject* compileError = eval->prepareForExecution(callFrame, scope, CodeForCall);
1199     if (UNLIKELY(!!compileError))
1200         return checkedReturn(callFrame->vm().throwException(callFrame, compileError));
1201     EvalCodeBlock* codeBlock = eval->codeBlock();
1202
1203     if (numVariables || numFunctions) {
1204         BatchedTransitionOptimizer optimizer(vm, variableObject);
1205         if (variableObject->next())
1206             variableObject->globalObject()->varInjectionWatchpoint()->notifyWrite();
1207
1208         for (unsigned i = 0; i < numVariables; ++i) {
1209             const Identifier& ident = codeBlock->variable(i);
1210             if (!variableObject->hasProperty(callFrame, ident)) {
1211                 PutPropertySlot slot;
1212                 variableObject->methodTable()->put(variableObject, callFrame, ident, jsUndefined(), slot);
1213             }
1214         }
1215
1216         for (int i = 0; i < numFunctions; ++i) {
1217             FunctionExecutable* function = codeBlock->functionDecl(i);
1218             PutPropertySlot slot;
1219             variableObject->methodTable()->put(variableObject, callFrame, function->name(), JSFunction::create(callFrame, function, scope), slot);
1220         }
1221     }
1222
1223     if (UNLIKELY(vm.watchdog.didFire(callFrame)))
1224         return throwTerminatedExecutionException(callFrame);
1225
1226     // Push the frame:
1227     ASSERT(codeBlock->numParameters() == 1); // 1 parameter for 'this'.
1228     CallFrame* newCallFrame = m_stack.pushFrame(callFrame, codeBlock, scope, 1, 0);
1229     if (UNLIKELY(!newCallFrame))
1230         return checkedReturn(throwStackOverflowError(callFrame));
1231
1232     // Set the arguments for the callee:
1233     newCallFrame->setThisValue(thisValue);
1234
1235     if (LegacyProfiler* profiler = vm.enabledProfiler())
1236         profiler->willExecute(callFrame, eval->sourceURL(), eval->lineNo());
1237
1238     // Execute the code:
1239     JSValue result;
1240     {
1241         SamplingTool::CallRecord callRecord(m_sampler.get());
1242         Watchdog::Scope watchdogScope(vm.watchdog);
1243
1244 #if ENABLE(LLINT_C_LOOP)
1245         result = LLInt::CLoop::execute(newCallFrame, llint_eval_prologue);
1246 #elif ENABLE(JIT)
1247         result = eval->generatedJITCode()->execute(&m_stack, newCallFrame, &vm);
1248 #endif // ENABLE(JIT)
1249     }
1250
1251     if (LegacyProfiler* profiler = vm.enabledProfiler())
1252         profiler->didExecute(callFrame, eval->sourceURL(), eval->lineNo());
1253
1254     m_stack.popFrame(newCallFrame);
1255     return checkedReturn(result);
1256 }
1257
1258 NEVER_INLINE void Interpreter::debug(CallFrame* callFrame, DebugHookID debugHookID, int firstLine, int lastLine, int column)
1259 {
1260     Debugger* debugger = callFrame->dynamicGlobalObject()->debugger();
1261     if (!debugger)
1262         return;
1263
1264     switch (debugHookID) {
1265         case DidEnterCallFrame:
1266             debugger->callEvent(DebuggerCallFrame(callFrame, firstLine, column));
1267             return;
1268         case WillLeaveCallFrame:
1269             debugger->returnEvent(DebuggerCallFrame(callFrame, lastLine, column));
1270             return;
1271         case WillExecuteStatement:
1272             debugger->atStatement(DebuggerCallFrame(callFrame, firstLine, column));
1273             return;
1274         case WillExecuteProgram:
1275             debugger->willExecuteProgram(DebuggerCallFrame(callFrame, firstLine, column));
1276             return;
1277         case DidExecuteProgram:
1278             debugger->didExecuteProgram(DebuggerCallFrame(callFrame, lastLine, column));
1279             return;
1280         case DidReachBreakpoint:
1281             debugger->didReachBreakpoint(DebuggerCallFrame(callFrame, lastLine, column));
1282             return;
1283     }
1284 }    
1285
1286 void Interpreter::enableSampler()
1287 {
1288 #if ENABLE(OPCODE_SAMPLING)
1289     if (!m_sampler) {
1290         m_sampler = adoptPtr(new SamplingTool(this));
1291         m_sampler->setup();
1292     }
1293 #endif
1294 }
1295 void Interpreter::dumpSampleData(ExecState* exec)
1296 {
1297 #if ENABLE(OPCODE_SAMPLING)
1298     if (m_sampler)
1299         m_sampler->dump(exec);
1300 #else
1301     UNUSED_PARAM(exec);
1302 #endif
1303 }
1304 void Interpreter::startSampling()
1305 {
1306 #if ENABLE(SAMPLING_THREAD)
1307     if (!m_sampleEntryDepth)
1308         SamplingThread::start();
1309
1310     m_sampleEntryDepth++;
1311 #endif
1312 }
1313 void Interpreter::stopSampling()
1314 {
1315 #if ENABLE(SAMPLING_THREAD)
1316     m_sampleEntryDepth--;
1317     if (!m_sampleEntryDepth)
1318         SamplingThread::stop();
1319 #endif
1320 }
1321
1322 } // namespace JSC