Upstream version 5.34.98.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / 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/v8/ScriptDebugServer.h"
33
34 #include "DebuggerScriptSource.h"
35 #include "V8JavaScriptCallFrame.h"
36 #include "bindings/v8/ScopedPersistent.h"
37 #include "bindings/v8/ScriptController.h"
38 #include "bindings/v8/ScriptObject.h"
39 #include "bindings/v8/ScriptSourceCode.h"
40 #include "bindings/v8/V8Binding.h"
41 #include "bindings/v8/V8ScriptRunner.h"
42 #include "core/inspector/JavaScriptCallFrame.h"
43 #include "core/inspector/ScriptDebugListener.h"
44 #include "wtf/StdLibExtras.h"
45 #include "wtf/Vector.h"
46 #include "wtf/dtoa/utils.h"
47 #include "wtf/text/CString.h"
48
49 namespace WebCore {
50
51 namespace {
52
53 class ClientDataImpl : public v8::Debug::ClientData {
54 public:
55     ClientDataImpl(PassOwnPtr<ScriptDebugServer::Task> task) : m_task(task) { }
56     virtual ~ClientDataImpl() { }
57     ScriptDebugServer::Task* task() const { return m_task.get(); }
58 private:
59     OwnPtr<ScriptDebugServer::Task> m_task;
60 };
61
62 const char stepIntoV8MethodName[] = "stepIntoStatement";
63 const char stepOutV8MethodName[] = "stepOutOfFunction";
64 }
65
66 v8::Local<v8::Value> ScriptDebugServer::callDebuggerMethod(const char* functionName, int argc, v8::Handle<v8::Value> argv[])
67 {
68     v8::Handle<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
69     v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, functionName)));
70     ASSERT(m_isolate->InContext());
71     return V8ScriptRunner::callInternalFunction(function, debuggerScript, argc, argv, m_isolate);
72 }
73
74 ScriptDebugServer::ScriptDebugServer(v8::Isolate* isolate)
75     : m_pauseOnExceptionsState(DontPauseOnExceptions)
76     , m_breakpointsActivated(true)
77     , m_isolate(isolate)
78     , m_runningNestedMessageLoop(false)
79 {
80 }
81
82 ScriptDebugServer::~ScriptDebugServer()
83 {
84 }
85
86 String ScriptDebugServer::setBreakpoint(const String& sourceID, const ScriptBreakpoint& scriptBreakpoint, int* actualLineNumber, int* actualColumnNumber, bool interstatementLocation)
87 {
88     v8::HandleScope scope(m_isolate);
89     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
90     v8::Context::Scope contextScope(debuggerContext);
91
92     v8::Local<v8::Object> info = v8::Object::New(m_isolate);
93     info->Set(v8AtomicString(m_isolate, "sourceID"), v8String(debuggerContext->GetIsolate(), sourceID));
94     info->Set(v8AtomicString(m_isolate, "lineNumber"), v8::Integer::New(debuggerContext->GetIsolate(), scriptBreakpoint.lineNumber));
95     info->Set(v8AtomicString(m_isolate, "columnNumber"), v8::Integer::New(debuggerContext->GetIsolate(), scriptBreakpoint.columnNumber));
96     info->Set(v8AtomicString(m_isolate, "interstatementLocation"), v8Boolean(interstatementLocation, debuggerContext->GetIsolate()));
97     info->Set(v8AtomicString(m_isolate, "condition"), v8String(debuggerContext->GetIsolate(), scriptBreakpoint.condition));
98
99     v8::Handle<v8::Function> setBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "setBreakpoint")));
100     v8::Handle<v8::Value> breakpointId = v8::Debug::Call(setBreakpointFunction, info);
101     if (!breakpointId->IsString())
102         return "";
103     *actualLineNumber = info->Get(v8AtomicString(m_isolate, "lineNumber"))->Int32Value();
104     *actualColumnNumber = info->Get(v8AtomicString(m_isolate, "columnNumber"))->Int32Value();
105     return toCoreString(breakpointId.As<v8::String>());
106 }
107
108 void ScriptDebugServer::removeBreakpoint(const String& breakpointId)
109 {
110     v8::HandleScope scope(m_isolate);
111     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
112     v8::Context::Scope contextScope(debuggerContext);
113
114     v8::Local<v8::Object> info = v8::Object::New(m_isolate);
115     info->Set(v8AtomicString(m_isolate, "breakpointId"), v8String(debuggerContext->GetIsolate(), breakpointId));
116
117     v8::Handle<v8::Function> removeBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "removeBreakpoint")));
118     v8::Debug::Call(removeBreakpointFunction, info);
119 }
120
121 void ScriptDebugServer::clearBreakpoints()
122 {
123     ensureDebuggerScriptCompiled();
124     v8::HandleScope scope(m_isolate);
125     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
126     v8::Context::Scope contextScope(debuggerContext);
127
128     v8::Handle<v8::Function> clearBreakpoints = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "clearBreakpoints")));
129     v8::Debug::Call(clearBreakpoints);
130 }
131
132 void ScriptDebugServer::setBreakpointsActivated(bool activated)
133 {
134     ensureDebuggerScriptCompiled();
135     v8::HandleScope scope(m_isolate);
136     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
137     v8::Context::Scope contextScope(debuggerContext);
138
139     v8::Local<v8::Object> info = v8::Object::New(m_isolate);
140     info->Set(v8AtomicString(m_isolate, "enabled"), v8::Boolean::New(m_isolate, activated));
141     v8::Handle<v8::Function> setBreakpointsActivated = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "setBreakpointsActivated")));
142     v8::Debug::Call(setBreakpointsActivated, info);
143
144     m_breakpointsActivated = activated;
145 }
146
147 ScriptDebugServer::PauseOnExceptionsState ScriptDebugServer::pauseOnExceptionsState()
148 {
149     ensureDebuggerScriptCompiled();
150     v8::HandleScope scope(m_isolate);
151     v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
152
153     v8::Handle<v8::Value> argv[] = { v8Undefined() };
154     v8::Handle<v8::Value> result = callDebuggerMethod("pauseOnExceptionsState", 0, argv);
155     return static_cast<ScriptDebugServer::PauseOnExceptionsState>(result->Int32Value());
156 }
157
158 void ScriptDebugServer::setPauseOnExceptionsState(PauseOnExceptionsState pauseOnExceptionsState)
159 {
160     ensureDebuggerScriptCompiled();
161     v8::HandleScope scope(m_isolate);
162     v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
163
164     v8::Handle<v8::Value> argv[] = { v8::Int32::New(m_isolate, pauseOnExceptionsState) };
165     callDebuggerMethod("setPauseOnExceptionsState", 1, argv);
166 }
167
168 void ScriptDebugServer::setPauseOnNextStatement(bool pause)
169 {
170     if (isPaused())
171         return;
172     if (pause)
173         v8::Debug::DebugBreak(m_isolate);
174     else
175         v8::Debug::CancelDebugBreak(m_isolate);
176 }
177
178 bool ScriptDebugServer::canBreakProgram()
179 {
180     if (!m_breakpointsActivated)
181         return false;
182     v8::HandleScope scope(m_isolate);
183     return !m_isolate->GetCurrentContext().IsEmpty();
184 }
185
186 void ScriptDebugServer::breakProgram()
187 {
188     if (!canBreakProgram())
189         return;
190
191     v8::HandleScope scope(m_isolate);
192     if (m_breakProgramCallbackTemplate.isEmpty()) {
193         v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(m_isolate);
194         templ->SetCallHandler(&ScriptDebugServer::breakProgramCallback, v8::External::New(m_isolate, this));
195         m_breakProgramCallbackTemplate.set(m_isolate, templ);
196     }
197
198     m_pausedContext = m_isolate->GetCurrentContext();
199     v8::Handle<v8::Function> breakProgramFunction = m_breakProgramCallbackTemplate.newLocal(m_isolate)->GetFunction();
200     v8::Debug::Call(breakProgramFunction);
201     m_pausedContext.Clear();
202 }
203
204 void ScriptDebugServer::continueProgram()
205 {
206     if (isPaused())
207         quitMessageLoopOnPause();
208     m_executionState.clear();
209 }
210
211 void ScriptDebugServer::stepIntoStatement()
212 {
213     ASSERT(isPaused());
214     v8::HandleScope handleScope(m_isolate);
215     v8::Handle<v8::Value> argv[] = { m_executionState.newLocal(m_isolate) };
216     callDebuggerMethod(stepIntoV8MethodName, 1, argv);
217     continueProgram();
218 }
219
220 void ScriptDebugServer::stepCommandWithFrame(const char* functionName, const ScriptValue& frame)
221 {
222     ASSERT(isPaused());
223     v8::HandleScope handleScope(m_isolate);
224     v8::Handle<v8::Value> callFrame;
225     if (frame.hasNoValue()) {
226         callFrame = v8::Undefined(m_isolate);
227     } else {
228         JavaScriptCallFrame* impl = V8JavaScriptCallFrame::toNative(v8::Handle<v8::Object>::Cast(frame.v8Value()));
229         callFrame = impl->innerCallFrame();
230     }
231
232     v8::Handle<v8::Value> argv[] = {
233         m_executionState.newLocal(m_isolate),
234         callFrame
235     };
236
237     callDebuggerMethod(functionName, 2, argv);
238     continueProgram();
239 }
240
241 void ScriptDebugServer::stepOverStatement(const ScriptValue& frame)
242 {
243     stepCommandWithFrame("stepOverStatement", frame);
244 }
245
246 void ScriptDebugServer::stepOutOfFunction(const ScriptValue& frame)
247 {
248     stepCommandWithFrame(stepOutV8MethodName, frame);
249 }
250
251 bool ScriptDebugServer::setScriptSource(const String& sourceID, const String& newContent, bool preview, String* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, ScriptValue* newCallFrames, ScriptObject* result)
252 {
253     class EnableLiveEditScope {
254     public:
255         EnableLiveEditScope() { v8::Debug::SetLiveEditEnabled(true); }
256         ~EnableLiveEditScope() { v8::Debug::SetLiveEditEnabled(false); }
257     };
258
259     ensureDebuggerScriptCompiled();
260     v8::HandleScope scope(m_isolate);
261
262     OwnPtr<v8::Context::Scope> contextScope;
263     v8::Handle<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
264     if (!isPaused())
265         contextScope = adoptPtr(new v8::Context::Scope(debuggerContext));
266
267     v8::Handle<v8::Value> argv[] = { v8String(debuggerContext->GetIsolate(), sourceID), v8String(debuggerContext->GetIsolate(), newContent), v8Boolean(preview, debuggerContext->GetIsolate()) };
268
269     v8::Local<v8::Value> v8result;
270     {
271         EnableLiveEditScope enableLiveEditScope;
272         v8::TryCatch tryCatch;
273         tryCatch.SetVerbose(false);
274         v8result = callDebuggerMethod("liveEditScriptSource", 3, argv);
275         if (tryCatch.HasCaught()) {
276             v8::Local<v8::Message> message = tryCatch.Message();
277             if (!message.IsEmpty())
278                 *error = toCoreStringWithUndefinedOrNullCheck(message->Get());
279             else
280                 *error = "Unknown error.";
281             return false;
282         }
283     }
284     ASSERT(!v8result.IsEmpty());
285     v8::Local<v8::Object> resultTuple = v8result->ToObject();
286     int code = static_cast<int>(resultTuple->Get(0)->ToInteger()->Value());
287     switch (code) {
288     case 0:
289         {
290             v8::Local<v8::Value> normalResult = resultTuple->Get(1);
291             if (normalResult->IsObject())
292                 *result = ScriptObject(ScriptState::current(), normalResult->ToObject());
293             // Call stack may have changed after if the edited function was on the stack.
294             if (!preview && isPaused())
295                 *newCallFrames = currentCallFrames();
296             return true;
297         }
298     // Compile error.
299     case 1:
300         {
301             RefPtr<TypeBuilder::Debugger::SetScriptSourceError::CompileError> compileError =
302                 TypeBuilder::Debugger::SetScriptSourceError::CompileError::create()
303                     .setMessage(toCoreStringWithUndefinedOrNullCheck(resultTuple->Get(2)))
304                     .setLineNumber(resultTuple->Get(3)->ToInteger()->Value())
305                     .setColumnNumber(resultTuple->Get(4)->ToInteger()->Value());
306
307             *error = toCoreStringWithUndefinedOrNullCheck(resultTuple->Get(1));
308             errorData = TypeBuilder::Debugger::SetScriptSourceError::create();
309             errorData->setCompileError(compileError);
310             return false;
311         }
312     }
313     *error = "Unknown error.";
314     return false;
315 }
316
317 PassRefPtr<JavaScriptCallFrame> ScriptDebugServer::wrapCallFrames(v8::Handle<v8::Object> executionState, int maximumLimit)
318 {
319     v8::Handle<v8::Value> currentCallFrameV8;
320     if (executionState.IsEmpty()) {
321         v8::Handle<v8::Function> currentCallFrameFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "currentCallFrame")));
322         currentCallFrameV8 = v8::Debug::Call(currentCallFrameFunction, v8::Integer::New(m_isolate, maximumLimit));
323     } else {
324         v8::Handle<v8::Value> argv[] = { executionState, v8::Integer::New(m_isolate, maximumLimit) };
325         currentCallFrameV8 = callDebuggerMethod("currentCallFrame", 2, argv);
326     }
327     ASSERT(!currentCallFrameV8.IsEmpty());
328     if (!currentCallFrameV8->IsObject())
329         return PassRefPtr<JavaScriptCallFrame>();
330     return JavaScriptCallFrame::create(v8::Debug::GetDebugContext(), v8::Handle<v8::Object>::Cast(currentCallFrameV8));
331 }
332
333 ScriptValue ScriptDebugServer::currentCallFrames()
334 {
335     v8::HandleScope scope(m_isolate);
336     v8::Handle<v8::Context> pausedContext = m_pausedContext.IsEmpty() ? m_isolate->GetCurrentContext() : m_pausedContext;
337     if (pausedContext.IsEmpty())
338         return ScriptValue();
339
340     RefPtr<JavaScriptCallFrame> currentCallFrame = wrapCallFrames(m_executionState.newLocal(m_isolate), -1);
341     if (!currentCallFrame)
342         return ScriptValue();
343
344     v8::Context::Scope contextScope(pausedContext);
345     return ScriptValue(toV8(currentCallFrame.release(), v8::Handle<v8::Object>(), pausedContext->GetIsolate()), pausedContext->GetIsolate());
346 }
347
348 void ScriptDebugServer::interruptAndRun(PassOwnPtr<Task> task, v8::Isolate* isolate)
349 {
350     v8::Debug::DebugBreakForCommand(new ClientDataImpl(task), isolate);
351 }
352
353 void ScriptDebugServer::runPendingTasks()
354 {
355     v8::Debug::ProcessDebugMessages();
356 }
357
358 static ScriptDebugServer* toScriptDebugServer(v8::Handle<v8::Value> data)
359 {
360     void* p = v8::Handle<v8::External>::Cast(data)->Value();
361     return static_cast<ScriptDebugServer*>(p);
362 }
363
364 void ScriptDebugServer::breakProgramCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
365 {
366     ASSERT(2 == info.Length());
367     ScriptDebugServer* thisPtr = toScriptDebugServer(info.Data());
368     v8::Handle<v8::Value> exception;
369     v8::Handle<v8::Array> hitBreakpoints;
370     thisPtr->handleProgramBreak(v8::Handle<v8::Object>::Cast(info[0]), exception, hitBreakpoints);
371 }
372
373 void ScriptDebugServer::handleProgramBreak(v8::Handle<v8::Object> executionState, v8::Handle<v8::Value> exception, v8::Handle<v8::Array> hitBreakpointNumbers)
374 {
375     // Don't allow nested breaks.
376     if (isPaused())
377         return;
378
379     ScriptDebugListener* listener = getDebugListenerForContext(m_pausedContext);
380     if (!listener)
381         return;
382
383     Vector<String> breakpointIds;
384     if (!hitBreakpointNumbers.IsEmpty()) {
385         breakpointIds.resize(hitBreakpointNumbers->Length());
386         for (size_t i = 0; i < hitBreakpointNumbers->Length(); i++) {
387             v8::Handle<v8::Value> hitBreakpointNumber = hitBreakpointNumbers->Get(i);
388             ASSERT(!hitBreakpointNumber.IsEmpty() && hitBreakpointNumber->IsInt32());
389             breakpointIds[i] = String::number(hitBreakpointNumber->Int32Value());
390         }
391     }
392
393     m_executionState.set(m_isolate, executionState);
394     ScriptState* currentCallFrameState = ScriptState::forContext(m_pausedContext);
395     listener->didPause(currentCallFrameState, currentCallFrames(), ScriptValue(exception, currentCallFrameState->isolate()), breakpointIds);
396
397     m_runningNestedMessageLoop = true;
398     runMessageLoopOnPause(m_pausedContext);
399     m_runningNestedMessageLoop = false;
400 }
401
402 void ScriptDebugServer::handleProgramBreak(const v8::Debug::EventDetails& eventDetails, v8::Handle<v8::Value> exception, v8::Handle<v8::Array> hitBreakpointNumbers)
403 {
404     m_pausedContext = eventDetails.GetEventContext();
405     handleProgramBreak(eventDetails.GetExecutionState(), exception, hitBreakpointNumbers);
406     m_pausedContext.Clear();
407 }
408
409 void ScriptDebugServer::v8DebugEventCallback(const v8::Debug::EventDetails& eventDetails)
410 {
411     ScriptDebugServer* thisPtr = toScriptDebugServer(eventDetails.GetCallbackData());
412     thisPtr->handleV8DebugEvent(eventDetails);
413 }
414
415 bool ScriptDebugServer::executeSkipPauseRequest(ScriptDebugListener::SkipPauseRequest request, v8::Handle<v8::Object> executionState)
416 {
417     switch (request) {
418     case ScriptDebugListener::NoSkip:
419         return false;
420     case ScriptDebugListener::Continue:
421         return true;
422     case ScriptDebugListener::StepInto:
423     case ScriptDebugListener::StepOut:
424         break;
425     }
426     v8::Handle<v8::Value> argv[] = { executionState };
427     callDebuggerMethod(stepIntoV8MethodName, 1, argv);
428     return true;
429 }
430
431 void ScriptDebugServer::handleV8DebugEvent(const v8::Debug::EventDetails& eventDetails)
432 {
433     v8::DebugEvent event = eventDetails.GetEvent();
434
435     if (event == v8::BreakForCommand) {
436         ClientDataImpl* data = static_cast<ClientDataImpl*>(eventDetails.GetClientData());
437         data->task()->run();
438         return;
439     }
440
441     if (event != v8::Break && event != v8::Exception && event != v8::AfterCompile && event != v8::BeforeCompile)
442         return;
443
444     v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
445     ASSERT(!eventContext.IsEmpty());
446
447     ScriptDebugListener* listener = getDebugListenerForContext(eventContext);
448     if (listener) {
449         v8::HandleScope scope(m_isolate);
450         v8::Handle<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
451         if (event == v8::BeforeCompile) {
452             preprocessBeforeCompile(eventDetails);
453         } else if (event == v8::AfterCompile) {
454             v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
455             v8::Handle<v8::Function> getAfterCompileScript = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getAfterCompileScript")));
456             v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
457             v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getAfterCompileScript, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
458             ASSERT(value->IsObject());
459             v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
460             dispatchDidParseSource(listener, object);
461         } else if (event == v8::Exception) {
462             v8::Local<v8::StackTrace> stackTrace = v8::StackTrace::CurrentStackTrace(m_isolate, 1);
463             // Stack trace is empty in case of syntax error. Silently continue execution in such cases.
464             if (!stackTrace->GetFrameCount())
465                 return;
466             RefPtr<JavaScriptCallFrame> topFrame = wrapCallFrames(eventDetails.GetExecutionState(), 1);
467             if (executeSkipPauseRequest(listener->shouldSkipExceptionPause(topFrame), eventDetails.GetExecutionState()))
468                 return;
469             v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
470             v8::Handle<v8::Value> exceptionGetterValue = eventData->Get(v8AtomicString(m_isolate, "exception"));
471             ASSERT(!exceptionGetterValue.IsEmpty() && exceptionGetterValue->IsFunction());
472             v8::Handle<v8::Value> exception = V8ScriptRunner::callInternalFunction(v8::Handle<v8::Function>::Cast(exceptionGetterValue), eventData, 0, 0, m_isolate);
473             handleProgramBreak(eventDetails, exception, v8::Handle<v8::Array>());
474         } else if (event == v8::Break) {
475             v8::Handle<v8::Function> getBreakpointNumbersFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getBreakpointNumbers")));
476             v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
477             v8::Handle<v8::Value> hitBreakpoints = V8ScriptRunner::callInternalFunction(getBreakpointNumbersFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
478             ASSERT(hitBreakpoints->IsArray());
479             RefPtr<JavaScriptCallFrame> topFrame = wrapCallFrames(eventDetails.GetExecutionState(), 1);
480             ScriptDebugListener::SkipPauseRequest skipRequest;
481             if (v8::Handle<v8::Array>::Cast(hitBreakpoints)->Length())
482                 skipRequest = listener->shouldSkipBreakpointPause(topFrame);
483             else
484                 skipRequest = listener->shouldSkipStepPause(topFrame);
485             if (executeSkipPauseRequest(skipRequest, eventDetails.GetExecutionState()))
486                 return;
487             handleProgramBreak(eventDetails, v8::Handle<v8::Value>(), hitBreakpoints.As<v8::Array>());
488         }
489     }
490 }
491
492 void ScriptDebugServer::dispatchDidParseSource(ScriptDebugListener* listener, v8::Handle<v8::Object> object)
493 {
494     v8::Handle<v8::Value> id = object->Get(v8AtomicString(m_isolate, "id"));
495     ASSERT(!id.IsEmpty() && id->IsInt32());
496     String sourceID = String::number(id->Int32Value());
497
498     ScriptDebugListener::Script script;
499     script.url = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "name")));
500     script.source = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "source")));
501     script.sourceMappingURL = toCoreStringWithUndefinedOrNullCheck(object->Get(v8AtomicString(m_isolate, "sourceMappingURL")));
502     script.startLine = object->Get(v8AtomicString(m_isolate, "startLine"))->ToInteger()->Value();
503     script.startColumn = object->Get(v8AtomicString(m_isolate, "startColumn"))->ToInteger()->Value();
504     script.endLine = object->Get(v8AtomicString(m_isolate, "endLine"))->ToInteger()->Value();
505     script.endColumn = object->Get(v8AtomicString(m_isolate, "endColumn"))->ToInteger()->Value();
506     script.isContentScript = object->Get(v8AtomicString(m_isolate, "isContentScript"))->ToBoolean()->Value();
507
508     listener->didParseSource(sourceID, script);
509 }
510
511 void ScriptDebugServer::ensureDebuggerScriptCompiled()
512 {
513     if (!m_debuggerScript.isEmpty())
514         return;
515
516     v8::HandleScope scope(m_isolate);
517     v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
518     v8::Handle<v8::String> source = v8String(m_isolate, String(reinterpret_cast<const char*>(DebuggerScriptSource_js), sizeof(DebuggerScriptSource_js)));
519     v8::Local<v8::Value> value = V8ScriptRunner::compileAndRunInternalScript(source, m_isolate);
520     ASSERT(!value.IsEmpty());
521     ASSERT(value->IsObject());
522     m_debuggerScript.set(m_isolate, v8::Handle<v8::Object>::Cast(value));
523 }
524
525 v8::Local<v8::Value> ScriptDebugServer::functionScopes(v8::Handle<v8::Function> function)
526 {
527     ensureDebuggerScriptCompiled();
528
529     v8::Handle<v8::Value> argv[] = { function };
530     return callDebuggerMethod("getFunctionScopes", 1, argv);
531 }
532
533 v8::Local<v8::Value> ScriptDebugServer::getInternalProperties(v8::Handle<v8::Object>& object)
534 {
535     if (m_debuggerScript.isEmpty())
536         return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
537
538     v8::Handle<v8::Value> argv[] = { object };
539     return callDebuggerMethod("getInternalProperties", 1, argv);
540 }
541
542 v8::Handle<v8::Value> ScriptDebugServer::setFunctionVariableValue(v8::Handle<v8::Value> functionValue, int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue)
543 {
544     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
545     if (m_debuggerScript.isEmpty())
546         return m_isolate->ThrowException(v8::String::NewFromUtf8(m_isolate, "Debugging is not enabled."));
547
548     v8::Handle<v8::Value> argv[] = {
549         functionValue,
550         v8::Handle<v8::Value>(v8::Integer::New(debuggerContext->GetIsolate(), scopeNumber)),
551         v8String(debuggerContext->GetIsolate(), variableName),
552         newValue
553     };
554     return callDebuggerMethod("setFunctionVariableValue", 4, argv);
555 }
556
557
558 bool ScriptDebugServer::isPaused()
559 {
560     return !m_executionState.isEmpty();
561 }
562
563 void ScriptDebugServer::compileScript(ScriptState* state, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
564 {
565     v8::HandleScope handleScope(m_isolate);
566     v8::Handle<v8::Context> context = state->context();
567     if (context.IsEmpty())
568         return;
569     v8::Context::Scope contextScope(context);
570
571     v8::Handle<v8::String> source = v8String(m_isolate, expression);
572     v8::TryCatch tryCatch;
573     v8::Local<v8::Script> script = V8ScriptRunner::compileScript(source, sourceURL, TextPosition(), 0, m_isolate);
574     if (tryCatch.HasCaught()) {
575         v8::Local<v8::Message> message = tryCatch.Message();
576         if (!message.IsEmpty())
577             *exceptionMessage = toCoreStringWithUndefinedOrNullCheck(message->Get());
578         return;
579     }
580     if (script.IsEmpty())
581         return;
582
583     *scriptId = String::number(script->GetId());
584     m_compiledScripts.set(*scriptId, adoptPtr(new ScopedPersistent<v8::Script>(m_isolate, script)));
585 }
586
587 void ScriptDebugServer::clearCompiledScripts()
588 {
589     m_compiledScripts.clear();
590 }
591
592 void ScriptDebugServer::runScript(ScriptState* state, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
593 {
594     if (!m_compiledScripts.contains(scriptId))
595         return;
596     v8::HandleScope handleScope(m_isolate);
597     ScopedPersistent<v8::Script>* scriptHandle = m_compiledScripts.get(scriptId);
598     v8::Local<v8::Script> script = scriptHandle->newLocal(m_isolate);
599     m_compiledScripts.remove(scriptId);
600     if (script.IsEmpty())
601         return;
602
603     v8::Handle<v8::Context> context = state->context();
604     if (context.IsEmpty())
605         return;
606     v8::Context::Scope contextScope(context);
607     v8::TryCatch tryCatch;
608     v8::Local<v8::Value> value = V8ScriptRunner::runCompiledScript(script, state->executionContext(), m_isolate);
609     *wasThrown = false;
610     if (tryCatch.HasCaught()) {
611         *wasThrown = true;
612         *result = ScriptValue(tryCatch.Exception(), m_isolate);
613         v8::Local<v8::Message> message = tryCatch.Message();
614         if (!message.IsEmpty())
615             *exceptionMessage = toCoreStringWithUndefinedOrNullCheck(message->Get());
616     } else {
617         *result = ScriptValue(value, m_isolate);
618     }
619 }
620
621 PassOwnPtr<ScriptSourceCode> ScriptDebugServer::preprocess(Frame*, const ScriptSourceCode&)
622 {
623     return PassOwnPtr<ScriptSourceCode>();
624 }
625
626 String ScriptDebugServer::preprocessEventListener(Frame*, const String& source, const String& url, const String& functionName)
627 {
628     return source;
629 }
630
631 } // namespace WebCore