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