Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / core / v8 / ScriptDebugServer.cpp
1 /*
2  * Copyright (c) 2010-2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "bindings/core/v8/ScriptDebugServer.h"
33
34 #include "bindings/core/v8/ScopedPersistent.h"
35 #include "bindings/core/v8/ScriptCallStackFactory.h"
36 #include "bindings/core/v8/ScriptController.h"
37 #include "bindings/core/v8/ScriptSourceCode.h"
38 #include "bindings/core/v8/ScriptValue.h"
39 #include "bindings/core/v8/V8Binding.h"
40 #include "bindings/core/v8/V8JavaScriptCallFrame.h"
41 #include "bindings/core/v8/V8ScriptRunner.h"
42 #include "core/inspector/JavaScriptCallFrame.h"
43 #include "core/inspector/ScriptDebugListener.h"
44 #include "platform/JSONValues.h"
45 #include "public/platform/Platform.h"
46 #include "public/platform/WebData.h"
47 #include "wtf/StdLibExtras.h"
48 #include "wtf/Vector.h"
49 #include "wtf/dtoa/utils.h"
50 #include "wtf/text/CString.h"
51
52 namespace blink {
53
54 namespace {
55
56 class ClientDataImpl : public v8::Debug::ClientData {
57 public:
58     ClientDataImpl(PassOwnPtr<ScriptDebugServer::Task> task) : m_task(task) { }
59     virtual ~ClientDataImpl() { }
60     ScriptDebugServer::Task* task() const { return m_task.get(); }
61 private:
62     OwnPtr<ScriptDebugServer::Task> m_task;
63 };
64
65 const char stepIntoV8MethodName[] = "stepIntoStatement";
66 const char stepOutV8MethodName[] = "stepOutOfFunction";
67 }
68
69 v8::Local<v8::Value> ScriptDebugServer::callDebuggerMethod(const char* functionName, int argc, v8::Handle<v8::Value> argv[])
70 {
71     v8::Handle<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
72     v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, functionName)));
73     ASSERT(m_isolate->InContext());
74     return V8ScriptRunner::callInternalFunction(function, debuggerScript, argc, argv, m_isolate);
75 }
76
77 ScriptDebugServer::ScriptDebugServer(v8::Isolate* isolate)
78     : m_pauseOnExceptionsState(DontPauseOnExceptions)
79     , m_breakpointsActivated(true)
80     , m_isolate(isolate)
81     , m_runningNestedMessageLoop(false)
82 {
83 }
84
85 ScriptDebugServer::~ScriptDebugServer()
86 {
87 }
88
89 String ScriptDebugServer::setBreakpoint(const String& sourceID, const ScriptBreakpoint& scriptBreakpoint, int* actualLineNumber, int* actualColumnNumber, bool interstatementLocation)
90 {
91     v8::HandleScope scope(m_isolate);
92     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
93     v8::Context::Scope contextScope(debuggerContext);
94
95     v8::Local<v8::Object> info = v8::Object::New(m_isolate);
96     info->Set(v8AtomicString(m_isolate, "sourceID"), v8String(debuggerContext->GetIsolate(), sourceID));
97     info->Set(v8AtomicString(m_isolate, "lineNumber"), v8::Integer::New(debuggerContext->GetIsolate(), scriptBreakpoint.lineNumber));
98     info->Set(v8AtomicString(m_isolate, "columnNumber"), v8::Integer::New(debuggerContext->GetIsolate(), scriptBreakpoint.columnNumber));
99     info->Set(v8AtomicString(m_isolate, "interstatementLocation"), v8Boolean(interstatementLocation, debuggerContext->GetIsolate()));
100     info->Set(v8AtomicString(m_isolate, "condition"), v8String(debuggerContext->GetIsolate(), scriptBreakpoint.condition));
101
102     v8::Handle<v8::Function> setBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "setBreakpoint")));
103     v8::Handle<v8::Value> breakpointId = v8::Debug::Call(setBreakpointFunction, info);
104     if (breakpointId.IsEmpty() || !breakpointId->IsString())
105         return "";
106     *actualLineNumber = info->Get(v8AtomicString(m_isolate, "lineNumber"))->Int32Value();
107     *actualColumnNumber = info->Get(v8AtomicString(m_isolate, "columnNumber"))->Int32Value();
108     return toCoreString(breakpointId.As<v8::String>());
109 }
110
111 void ScriptDebugServer::removeBreakpoint(const String& breakpointId)
112 {
113     v8::HandleScope scope(m_isolate);
114     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
115     v8::Context::Scope contextScope(debuggerContext);
116
117     v8::Local<v8::Object> info = v8::Object::New(m_isolate);
118     info->Set(v8AtomicString(m_isolate, "breakpointId"), v8String(debuggerContext->GetIsolate(), breakpointId));
119
120     v8::Handle<v8::Function> removeBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "removeBreakpoint")));
121     v8::Debug::Call(removeBreakpointFunction, info);
122 }
123
124 void ScriptDebugServer::clearBreakpoints()
125 {
126     ensureDebuggerScriptCompiled();
127     v8::HandleScope scope(m_isolate);
128     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
129     v8::Context::Scope contextScope(debuggerContext);
130
131     v8::Handle<v8::Function> clearBreakpoints = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "clearBreakpoints")));
132     v8::Debug::Call(clearBreakpoints);
133 }
134
135 void ScriptDebugServer::setBreakpointsActivated(bool activated)
136 {
137     ensureDebuggerScriptCompiled();
138     v8::HandleScope scope(m_isolate);
139     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
140     v8::Context::Scope contextScope(debuggerContext);
141
142     v8::Local<v8::Object> info = v8::Object::New(m_isolate);
143     info->Set(v8AtomicString(m_isolate, "enabled"), v8::Boolean::New(m_isolate, activated));
144     v8::Handle<v8::Function> setBreakpointsActivated = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "setBreakpointsActivated")));
145     v8::Debug::Call(setBreakpointsActivated, info);
146
147     m_breakpointsActivated = activated;
148 }
149
150 ScriptDebugServer::PauseOnExceptionsState ScriptDebugServer::pauseOnExceptionsState()
151 {
152     ensureDebuggerScriptCompiled();
153     v8::HandleScope scope(m_isolate);
154     v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
155
156     v8::Handle<v8::Value> argv[] = { v8Undefined() };
157     v8::Handle<v8::Value> result = callDebuggerMethod("pauseOnExceptionsState", 0, argv);
158     return static_cast<ScriptDebugServer::PauseOnExceptionsState>(result->Int32Value());
159 }
160
161 void ScriptDebugServer::setPauseOnExceptionsState(PauseOnExceptionsState pauseOnExceptionsState)
162 {
163     ensureDebuggerScriptCompiled();
164     v8::HandleScope scope(m_isolate);
165     v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
166
167     v8::Handle<v8::Value> argv[] = { v8::Int32::New(m_isolate, pauseOnExceptionsState) };
168     callDebuggerMethod("setPauseOnExceptionsState", 1, argv);
169 }
170
171 void ScriptDebugServer::setPauseOnNextStatement(bool pause)
172 {
173     ASSERT(!isPaused());
174     if (pause)
175         v8::Debug::DebugBreak(m_isolate);
176     else
177         v8::Debug::CancelDebugBreak(m_isolate);
178 }
179
180 bool ScriptDebugServer::canBreakProgram()
181 {
182     if (!m_breakpointsActivated)
183         return false;
184     return m_isolate->InContext();
185 }
186
187 void ScriptDebugServer::breakProgram()
188 {
189     if (!canBreakProgram())
190         return;
191
192     v8::HandleScope scope(m_isolate);
193     if (m_breakProgramCallbackTemplate.isEmpty()) {
194         v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(m_isolate);
195         templ->SetCallHandler(&ScriptDebugServer::breakProgramCallback, v8::External::New(m_isolate, this));
196         m_breakProgramCallbackTemplate.set(m_isolate, templ);
197     }
198
199     v8::Handle<v8::Function> breakProgramFunction = m_breakProgramCallbackTemplate.newLocal(m_isolate)->GetFunction();
200     v8::Debug::Call(breakProgramFunction);
201 }
202
203 void ScriptDebugServer::continueProgram()
204 {
205     if (isPaused())
206         quitMessageLoopOnPause();
207     m_pausedScriptState.clear();
208     m_executionState.Clear();
209 }
210
211 void ScriptDebugServer::stepIntoStatement()
212 {
213     ASSERT(isPaused());
214     ASSERT(!m_executionState.IsEmpty());
215     v8::HandleScope handleScope(m_isolate);
216     v8::Handle<v8::Value> argv[] = { m_executionState };
217     callDebuggerMethod(stepIntoV8MethodName, 1, argv);
218     continueProgram();
219 }
220
221 void ScriptDebugServer::stepOverStatement()
222 {
223     ASSERT(isPaused());
224     ASSERT(!m_executionState.IsEmpty());
225     v8::HandleScope handleScope(m_isolate);
226     v8::Handle<v8::Value> argv[] = { m_executionState };
227     callDebuggerMethod("stepOverStatement", 1, argv);
228     continueProgram();
229 }
230
231 void ScriptDebugServer::stepOutOfFunction()
232 {
233     ASSERT(isPaused());
234     ASSERT(!m_executionState.IsEmpty());
235     v8::HandleScope handleScope(m_isolate);
236     v8::Handle<v8::Value> argv[] = { m_executionState };
237     callDebuggerMethod(stepOutV8MethodName, 1, argv);
238     continueProgram();
239 }
240
241 bool ScriptDebugServer::setScriptSource(const String& sourceID, const String& newContent, bool preview, String* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, ScriptValue* newCallFrames, RefPtr<JSONObject>* result)
242 {
243     class EnableLiveEditScope {
244     public:
245         explicit EnableLiveEditScope(v8::Isolate* isolate) : m_isolate(isolate) { v8::Debug::SetLiveEditEnabled(m_isolate, true); }
246         ~EnableLiveEditScope() { v8::Debug::SetLiveEditEnabled(m_isolate, false); }
247     private:
248         v8::Isolate* m_isolate;
249     };
250
251     ensureDebuggerScriptCompiled();
252     v8::HandleScope scope(m_isolate);
253
254     OwnPtr<v8::Context::Scope> contextScope;
255     v8::Handle<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
256     if (!isPaused())
257         contextScope = adoptPtr(new v8::Context::Scope(debuggerContext));
258
259     v8::Handle<v8::Value> argv[] = { v8String(m_isolate, sourceID), v8String(m_isolate, newContent), v8Boolean(preview, m_isolate) };
260
261     v8::Local<v8::Value> v8result;
262     {
263         EnableLiveEditScope enableLiveEditScope(m_isolate);
264         v8::TryCatch tryCatch;
265         tryCatch.SetVerbose(false);
266         v8result = callDebuggerMethod("liveEditScriptSource", 3, argv);
267         if (tryCatch.HasCaught()) {
268             v8::Local<v8::Message> message = tryCatch.Message();
269             if (!message.IsEmpty())
270                 *error = toCoreStringWithUndefinedOrNullCheck(message->Get());
271             else
272                 *error = "Unknown error.";
273             return false;
274         }
275     }
276     ASSERT(!v8result.IsEmpty());
277     v8::Local<v8::Object> resultTuple = v8result->ToObject();
278     int code = static_cast<int>(resultTuple->Get(0)->ToInteger()->Value());
279     switch (code) {
280     case 0:
281         {
282             v8::Local<v8::Value> normalResult = resultTuple->Get(1);
283             RefPtr<JSONValue> jsonResult = v8ToJSONValue(m_isolate, normalResult, JSONValue::maxDepth);
284             if (jsonResult)
285                 *result = jsonResult->asObject();
286             // Call stack may have changed after if the edited function was on the stack.
287             if (!preview && isPaused())
288                 *newCallFrames = currentCallFrames();
289             return true;
290         }
291     // Compile error.
292     case 1:
293         {
294             RefPtr<TypeBuilder::Debugger::SetScriptSourceError::CompileError> compileError =
295                 TypeBuilder::Debugger::SetScriptSourceError::CompileError::create()
296                     .setMessage(toCoreStringWithUndefinedOrNullCheck(resultTuple->Get(2)))
297                     .setLineNumber(resultTuple->Get(3)->ToInteger()->Value())
298                     .setColumnNumber(resultTuple->Get(4)->ToInteger()->Value());
299
300             *error = toCoreStringWithUndefinedOrNullCheck(resultTuple->Get(1));
301             errorData = TypeBuilder::Debugger::SetScriptSourceError::create();
302             errorData->setCompileError(compileError);
303             return false;
304         }
305     }
306     *error = "Unknown error.";
307     return false;
308 }
309
310 int ScriptDebugServer::frameCount()
311 {
312     ASSERT(isPaused());
313     ASSERT(!m_executionState.IsEmpty());
314     v8::Handle<v8::Value> argv[] = { m_executionState };
315     v8::Handle<v8::Value> result = callDebuggerMethod("frameCount", WTF_ARRAY_LENGTH(argv), argv);
316     if (result->IsInt32())
317         return result->Int32Value();
318     return 0;
319 }
320
321 PassRefPtrWillBeRawPtr<JavaScriptCallFrame> ScriptDebugServer::toJavaScriptCallFrameUnsafe(const ScriptValue& value)
322 {
323     if (value.isEmpty())
324         return nullptr;
325     ASSERT(value.isObject());
326     return V8JavaScriptCallFrame::toNative(v8::Handle<v8::Object>::Cast(value.v8ValueUnsafe()));
327 }
328
329 PassRefPtrWillBeRawPtr<JavaScriptCallFrame> ScriptDebugServer::wrapCallFrames(int maximumLimit, ScopeInfoDetails scopeDetails)
330 {
331     const int scopeBits = 2;
332     COMPILE_ASSERT(NoScopes < (1 << scopeBits), not_enough_bits_to_encode_ScopeInfoDetails);
333
334     ASSERT(maximumLimit >= 0);
335     int data = (maximumLimit << scopeBits) | scopeDetails;
336     v8::Handle<v8::Value> currentCallFrameV8;
337     if (m_executionState.IsEmpty()) {
338         v8::Handle<v8::Function> currentCallFrameFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "currentCallFrame")));
339         currentCallFrameV8 = v8::Debug::Call(currentCallFrameFunction, v8::Integer::New(m_isolate, data));
340     } else {
341         v8::Handle<v8::Value> argv[] = { m_executionState, v8::Integer::New(m_isolate, data) };
342         currentCallFrameV8 = callDebuggerMethod("currentCallFrame", WTF_ARRAY_LENGTH(argv), argv);
343     }
344     ASSERT(!currentCallFrameV8.IsEmpty());
345     if (!currentCallFrameV8->IsObject())
346         return nullptr;
347     return JavaScriptCallFrame::create(v8::Debug::GetDebugContext(), v8::Handle<v8::Object>::Cast(currentCallFrameV8));
348 }
349
350 ScriptValue ScriptDebugServer::currentCallFramesInner(ScopeInfoDetails scopeDetails)
351 {
352     if (!m_isolate->InContext())
353         return ScriptValue();
354     v8::HandleScope handleScope(m_isolate);
355
356     // Filter out stack traces entirely consisting of V8's internal scripts.
357     v8::Local<v8::StackTrace> stackTrace = v8::StackTrace::CurrentStackTrace(m_isolate, 1);
358     if (!stackTrace->GetFrameCount())
359         return ScriptValue();
360
361     RefPtrWillBeRawPtr<JavaScriptCallFrame> currentCallFrame = wrapCallFrames(0, scopeDetails);
362     if (!currentCallFrame)
363         return ScriptValue();
364
365     ScriptState* scriptState = m_pausedScriptState ? m_pausedScriptState.get() : ScriptState::current(m_isolate);
366     ScriptState::Scope scope(scriptState);
367     return ScriptValue(scriptState, toV8(currentCallFrame.release(), scriptState->context()->Global(), m_isolate));
368 }
369
370 ScriptValue ScriptDebugServer::currentCallFrames()
371 {
372     return currentCallFramesInner(AllScopes);
373 }
374
375 ScriptValue ScriptDebugServer::currentCallFramesForAsyncStack()
376 {
377     return currentCallFramesInner(FastAsyncScopes);
378 }
379
380 PassRefPtrWillBeRawPtr<JavaScriptCallFrame> ScriptDebugServer::callFrameNoScopes(int index)
381 {
382     v8::Handle<v8::Value> currentCallFrameV8;
383     if (m_executionState.IsEmpty()) {
384         v8::Handle<v8::Function> currentCallFrameFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "currentCallFrameByIndex")));
385         currentCallFrameV8 = v8::Debug::Call(currentCallFrameFunction, v8::Integer::New(m_isolate, index));
386     } else {
387         v8::Handle<v8::Value> argv[] = { m_executionState, v8::Integer::New(m_isolate, index) };
388         currentCallFrameV8 = callDebuggerMethod("currentCallFrameByIndex", WTF_ARRAY_LENGTH(argv), argv);
389     }
390     ASSERT(!currentCallFrameV8.IsEmpty());
391     if (!currentCallFrameV8->IsObject())
392         return nullptr;
393     return JavaScriptCallFrame::create(v8::Debug::GetDebugContext(), v8::Handle<v8::Object>::Cast(currentCallFrameV8));
394 }
395
396 void ScriptDebugServer::interruptAndRun(PassOwnPtr<Task> task, v8::Isolate* isolate)
397 {
398     v8::Debug::DebugBreakForCommand(isolate, new ClientDataImpl(task));
399 }
400
401 void ScriptDebugServer::runPendingTasks()
402 {
403     v8::Debug::ProcessDebugMessages();
404 }
405
406 static ScriptDebugServer* toScriptDebugServer(v8::Handle<v8::Value> data)
407 {
408     void* p = v8::Handle<v8::External>::Cast(data)->Value();
409     return static_cast<ScriptDebugServer*>(p);
410 }
411
412 void ScriptDebugServer::breakProgramCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
413 {
414     ASSERT(2 == info.Length());
415     ScriptDebugServer* thisPtr = toScriptDebugServer(info.Data());
416     ScriptState* pausedScriptState = ScriptState::current(thisPtr->m_isolate);
417     v8::Handle<v8::Value> exception;
418     v8::Handle<v8::Array> hitBreakpoints;
419     thisPtr->handleProgramBreak(pausedScriptState, v8::Handle<v8::Object>::Cast(info[0]), exception, hitBreakpoints);
420 }
421
422 void ScriptDebugServer::handleProgramBreak(ScriptState* pausedScriptState, v8::Handle<v8::Object> executionState, v8::Handle<v8::Value> exception, v8::Handle<v8::Array> hitBreakpointNumbers)
423 {
424     // Don't allow nested breaks.
425     if (isPaused())
426         return;
427
428     ScriptDebugListener* listener = getDebugListenerForContext(pausedScriptState->context());
429     if (!listener)
430         return;
431
432     Vector<String> breakpointIds;
433     if (!hitBreakpointNumbers.IsEmpty()) {
434         breakpointIds.resize(hitBreakpointNumbers->Length());
435         for (size_t i = 0; i < hitBreakpointNumbers->Length(); i++) {
436             v8::Handle<v8::Value> hitBreakpointNumber = hitBreakpointNumbers->Get(i);
437             ASSERT(!hitBreakpointNumber.IsEmpty() && hitBreakpointNumber->IsInt32());
438             breakpointIds[i] = String::number(hitBreakpointNumber->Int32Value());
439         }
440     }
441
442     m_pausedScriptState = pausedScriptState;
443     m_executionState = executionState;
444     ScriptDebugListener::SkipPauseRequest result = listener->didPause(pausedScriptState, currentCallFrames(), ScriptValue(pausedScriptState, exception), breakpointIds);
445     if (result == ScriptDebugListener::NoSkip) {
446         m_runningNestedMessageLoop = true;
447         runMessageLoopOnPause(pausedScriptState->context());
448         m_runningNestedMessageLoop = false;
449     }
450     m_pausedScriptState.clear();
451     m_executionState.Clear();
452
453     if (result == ScriptDebugListener::StepInto) {
454         v8::Handle<v8::Value> argv[] = { executionState };
455         callDebuggerMethod(stepIntoV8MethodName, 1, argv);
456     } else if (result == ScriptDebugListener::StepOut) {
457         v8::Handle<v8::Value> argv[] = { executionState };
458         callDebuggerMethod(stepOutV8MethodName, 1, argv);
459     }
460 }
461
462 void ScriptDebugServer::v8DebugEventCallback(const v8::Debug::EventDetails& eventDetails)
463 {
464     ScriptDebugServer* thisPtr = toScriptDebugServer(eventDetails.GetCallbackData());
465     thisPtr->handleV8DebugEvent(eventDetails);
466 }
467
468 static v8::Handle<v8::Value> callInternalGetterFunction(v8::Handle<v8::Object> object, const char* functionName, v8::Isolate* isolate)
469 {
470     v8::Handle<v8::Value> getterValue = object->Get(v8AtomicString(isolate, functionName));
471     ASSERT(!getterValue.IsEmpty() && getterValue->IsFunction());
472     return V8ScriptRunner::callInternalFunction(v8::Handle<v8::Function>::Cast(getterValue), object, 0, 0, isolate);
473 }
474
475 void ScriptDebugServer::handleV8DebugEvent(const v8::Debug::EventDetails& eventDetails)
476 {
477     v8::DebugEvent event = eventDetails.GetEvent();
478
479     if (event == v8::BreakForCommand) {
480         ClientDataImpl* data = static_cast<ClientDataImpl*>(eventDetails.GetClientData());
481         data->task()->run();
482         return;
483     }
484
485     if (event != v8::AsyncTaskEvent && event != v8::Break && event != v8::Exception && event != v8::AfterCompile && event != v8::BeforeCompile && event != v8::CompileError)
486         return;
487
488     v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
489     ASSERT(!eventContext.IsEmpty());
490
491     ScriptDebugListener* listener = getDebugListenerForContext(eventContext);
492     if (listener) {
493         v8::HandleScope scope(m_isolate);
494         v8::Handle<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
495         if (event == v8::BeforeCompile) {
496             preprocessBeforeCompile(eventDetails);
497         } else if (event == v8::AfterCompile || event == v8::CompileError) {
498             v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
499             v8::Handle<v8::Function> getAfterCompileScript = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getAfterCompileScript")));
500             v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
501             v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getAfterCompileScript, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
502             ASSERT(value->IsObject());
503             v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
504             dispatchDidParseSource(listener, object, event != v8::AfterCompile ? CompileError : CompileSuccess);
505         } else if (event == v8::Exception) {
506             v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
507             v8::Handle<v8::Value> exception = callInternalGetterFunction(eventData, "exception", m_isolate);
508             handleProgramBreak(ScriptState::from(eventContext), eventDetails.GetExecutionState(), exception, v8::Handle<v8::Array>());
509         } else if (event == v8::Break) {
510             v8::Handle<v8::Function> getBreakpointNumbersFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getBreakpointNumbers")));
511             v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
512             v8::Handle<v8::Value> hitBreakpoints = V8ScriptRunner::callInternalFunction(getBreakpointNumbersFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
513             ASSERT(hitBreakpoints->IsArray());
514             handleProgramBreak(ScriptState::from(eventContext), eventDetails.GetExecutionState(), v8::Handle<v8::Value>(), hitBreakpoints.As<v8::Array>());
515         } else if (event == v8::AsyncTaskEvent) {
516             handleV8AsyncTaskEvent(listener, ScriptState::from(eventContext), eventDetails.GetExecutionState(), eventDetails.GetEventData());
517         }
518     }
519 }
520
521 void ScriptDebugServer::handleV8AsyncTaskEvent(ScriptDebugListener* listener, ScriptState* pausedScriptState, v8::Handle<v8::Object> executionState, v8::Handle<v8::Object> eventData)
522 {
523     String type = toCoreStringWithUndefinedOrNullCheck(callInternalGetterFunction(eventData, "type", m_isolate));
524     String name = toCoreStringWithUndefinedOrNullCheck(callInternalGetterFunction(eventData, "name", m_isolate));
525     int id = callInternalGetterFunction(eventData, "id", m_isolate)->ToInteger()->Value();
526
527     m_pausedScriptState = pausedScriptState;
528     m_executionState = executionState;
529     listener->didReceiveV8AsyncTaskEvent(pausedScriptState->executionContext(), type, name, id);
530     m_pausedScriptState.clear();
531     m_executionState.Clear();
532 }
533
534 void ScriptDebugServer::dispatchDidParseSource(ScriptDebugListener* listener, v8::Handle<v8::Object> object, CompileResult compileResult)
535 {
536     v8::Handle<v8::Value> id = object->Get(v8AtomicString(m_isolate, "id"));
537     ASSERT(!id.IsEmpty() && id->IsInt32());
538     String sourceID = String::number(id->Int32Value());
539
540     ScriptDebugListener::Script script;
541     script.url = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "name")));
542     script.sourceURL = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "sourceURL")));
543     script.sourceMappingURL = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "sourceMappingURL")));
544     script.source = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "source")));
545     script.startLine = object->Get(v8AtomicString(m_isolate, "startLine"))->ToInteger()->Value();
546     script.startColumn = object->Get(v8AtomicString(m_isolate, "startColumn"))->ToInteger()->Value();
547     script.endLine = object->Get(v8AtomicString(m_isolate, "endLine"))->ToInteger()->Value();
548     script.endColumn = object->Get(v8AtomicString(m_isolate, "endColumn"))->ToInteger()->Value();
549     script.isContentScript = object->Get(v8AtomicString(m_isolate, "isContentScript"))->ToBoolean()->Value();
550
551     listener->didParseSource(sourceID, script, compileResult);
552 }
553
554 void ScriptDebugServer::ensureDebuggerScriptCompiled()
555 {
556     if (!m_debuggerScript.isEmpty())
557         return;
558
559     v8::HandleScope scope(m_isolate);
560     v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
561     const blink::WebData& debuggerScriptSourceResource = blink::Platform::current()->loadResource("DebuggerScriptSource.js");
562     v8::Handle<v8::String> source = v8String(m_isolate, String(debuggerScriptSourceResource.data(), debuggerScriptSourceResource.size()));
563     v8::Local<v8::Value> value = V8ScriptRunner::compileAndRunInternalScript(source, m_isolate);
564     ASSERT(!value.IsEmpty());
565     ASSERT(value->IsObject());
566     m_debuggerScript.set(m_isolate, v8::Handle<v8::Object>::Cast(value));
567 }
568
569 void ScriptDebugServer::discardDebuggerScript()
570 {
571     ASSERT(!m_debuggerScript.isEmpty());
572     m_debuggerScript.clear();
573 }
574
575 v8::Local<v8::Value> ScriptDebugServer::functionScopes(v8::Handle<v8::Function> function)
576 {
577     ensureDebuggerScriptCompiled();
578
579     v8::Handle<v8::Value> argv[] = { function };
580     return callDebuggerMethod("getFunctionScopes", 1, argv);
581 }
582
583 v8::Local<v8::Value> ScriptDebugServer::getInternalProperties(v8::Handle<v8::Object>& object)
584 {
585     if (m_debuggerScript.isEmpty())
586         return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
587
588     v8::Handle<v8::Value> argv[] = { object };
589     return callDebuggerMethod("getInternalProperties", 1, argv);
590 }
591
592 v8::Handle<v8::Value> ScriptDebugServer::setFunctionVariableValue(v8::Handle<v8::Value> functionValue, int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue)
593 {
594     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
595     if (m_debuggerScript.isEmpty())
596         return m_isolate->ThrowException(v8::String::NewFromUtf8(m_isolate, "Debugging is not enabled."));
597
598     v8::Handle<v8::Value> argv[] = {
599         functionValue,
600         v8::Handle<v8::Value>(v8::Integer::New(debuggerContext->GetIsolate(), scopeNumber)),
601         v8String(debuggerContext->GetIsolate(), variableName),
602         newValue
603     };
604     return callDebuggerMethod("setFunctionVariableValue", 4, argv);
605 }
606
607
608 bool ScriptDebugServer::isPaused()
609 {
610     return m_pausedScriptState;
611 }
612
613 void ScriptDebugServer::compileScript(ScriptState* scriptState, const String& expression, const String& sourceURL, String* scriptId, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtrWillBeRawPtr<ScriptCallStack>* stackTrace)
614 {
615     if (scriptState->contextIsEmpty())
616         return;
617     ScriptState::Scope scope(scriptState);
618
619     v8::Handle<v8::String> source = v8String(m_isolate, expression);
620     v8::TryCatch tryCatch;
621     v8::Local<v8::Script> script = V8ScriptRunner::compileScript(source, sourceURL, TextPosition(), 0, m_isolate);
622     if (tryCatch.HasCaught()) {
623         v8::Local<v8::Message> message = tryCatch.Message();
624         if (!message.IsEmpty()) {
625             *exceptionDetailsText = toCoreStringWithUndefinedOrNullCheck(message->Get());
626             *lineNumber = message->GetLineNumber();
627             *columnNumber = message->GetStartColumn();
628             *stackTrace = createScriptCallStack(message->GetStackTrace(), message->GetStackTrace()->GetFrameCount(), m_isolate);
629         }
630         return;
631     }
632     if (script.IsEmpty())
633         return;
634
635     *scriptId = String::number(script->GetUnboundScript()->GetId());
636     m_compiledScripts.set(*scriptId, adoptPtr(new ScopedPersistent<v8::Script>(m_isolate, script)));
637 }
638
639 void ScriptDebugServer::clearCompiledScripts()
640 {
641     m_compiledScripts.clear();
642 }
643
644 void ScriptDebugServer::runScript(ScriptState* scriptState, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtrWillBeRawPtr<ScriptCallStack>* stackTrace)
645 {
646     if (!m_compiledScripts.contains(scriptId))
647         return;
648     v8::HandleScope handleScope(m_isolate);
649     ScopedPersistent<v8::Script>* scriptHandle = m_compiledScripts.get(scriptId);
650     v8::Local<v8::Script> script = scriptHandle->newLocal(m_isolate);
651     m_compiledScripts.remove(scriptId);
652     if (script.IsEmpty())
653         return;
654
655     if (scriptState->contextIsEmpty())
656         return;
657     ScriptState::Scope scope(scriptState);
658     v8::TryCatch tryCatch;
659     v8::Local<v8::Value> value = V8ScriptRunner::runCompiledScript(script, scriptState->executionContext(), m_isolate);
660     *wasThrown = false;
661     if (tryCatch.HasCaught()) {
662         *wasThrown = true;
663         *result = ScriptValue(scriptState, tryCatch.Exception());
664         v8::Local<v8::Message> message = tryCatch.Message();
665         if (!message.IsEmpty()) {
666             *exceptionDetailsText = toCoreStringWithUndefinedOrNullCheck(message->Get());
667             *lineNumber = message->GetLineNumber();
668             *columnNumber = message->GetStartColumn();
669             *stackTrace = createScriptCallStack(message->GetStackTrace(), message->GetStackTrace()->GetFrameCount(), m_isolate);
670         }
671     } else {
672         *result = ScriptValue(scriptState, value);
673     }
674 }
675
676 PassOwnPtr<ScriptSourceCode> ScriptDebugServer::preprocess(LocalFrame*, const ScriptSourceCode&)
677 {
678     return PassOwnPtr<ScriptSourceCode>();
679 }
680
681 String ScriptDebugServer::preprocessEventListener(LocalFrame*, const String& source, const String& url, const String& functionName)
682 {
683     return source;
684 }
685
686 } // namespace blink