Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / v8 / PageScriptDebugServer.cpp
1 /*
2  * Copyright (c) 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/PageScriptDebugServer.h"
33
34
35 #include "V8Window.h"
36 #include "bindings/v8/DOMWrapperWorld.h"
37 #include "bindings/v8/ScriptController.h"
38 #include "bindings/v8/ScriptSourceCode.h"
39 #include "bindings/v8/V8Binding.h"
40 #include "bindings/v8/V8ScriptRunner.h"
41 #include "bindings/v8/V8WindowShell.h"
42 #include "core/frame/FrameConsole.h"
43 #include "core/frame/FrameHost.h"
44 #include "core/frame/LocalFrame.h"
45 #include "core/frame/UseCounter.h"
46 #include "core/inspector/InspectorInstrumentation.h"
47 #include "core/inspector/InspectorTraceEvents.h"
48 #include "core/inspector/ScriptDebugListener.h"
49 #include "core/page/Page.h"
50 #include "wtf/OwnPtr.h"
51 #include "wtf/PassOwnPtr.h"
52 #include "wtf/StdLibExtras.h"
53 #include "wtf/TemporaryChange.h"
54 #include "wtf/text/StringBuilder.h"
55
56 namespace WebCore {
57
58 static LocalFrame* retrieveFrameWithGlobalObjectCheck(v8::Handle<v8::Context> context)
59 {
60     if (context.IsEmpty())
61         return 0;
62
63     // FIXME: This is a temporary hack for crbug.com/345014.
64     // Currently it's possible that V8 can trigger Debugger::ProcessDebugEvent for a context
65     // that is being initialized (i.e., inside Context::New() of the context).
66     // We should fix the V8 side so that it won't trigger the event for a half-baked context
67     // because there is no way in the embedder side to check if the context is half-baked or not.
68     if (isMainThread() && DOMWrapperWorld::windowIsBeingInitialized())
69         return 0;
70
71     v8::Handle<v8::Value> global = V8Window::findInstanceInPrototypeChain(context->Global(), context->GetIsolate());
72     if (global.IsEmpty())
73         return 0;
74
75     return toFrameIfNotDetached(context);
76 }
77
78 void PageScriptDebugServer::setPreprocessorSource(const String& preprocessorSource)
79 {
80     if (preprocessorSource.isEmpty())
81         m_preprocessorSourceCode.clear();
82     else
83         m_preprocessorSourceCode = adoptPtr(new ScriptSourceCode(preprocessorSource));
84     m_scriptPreprocessor.clear();
85 }
86
87 PageScriptDebugServer& PageScriptDebugServer::shared()
88 {
89     DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ());
90     return server;
91 }
92
93 v8::Isolate* PageScriptDebugServer::s_mainThreadIsolate = 0;
94
95 void PageScriptDebugServer::setMainThreadIsolate(v8::Isolate* isolate)
96 {
97     s_mainThreadIsolate = isolate;
98 }
99
100 PageScriptDebugServer::PageScriptDebugServer()
101     : ScriptDebugServer(s_mainThreadIsolate)
102     , m_pausedPage(0)
103 {
104 }
105
106 PageScriptDebugServer::~PageScriptDebugServer()
107 {
108 }
109
110 void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page)
111 {
112     ScriptController& scriptController = page->mainFrame()->script();
113     if (!scriptController.canExecuteScripts(NotAboutToExecuteScript))
114         return;
115
116     v8::HandleScope scope(m_isolate);
117     v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
118     v8::Context::Scope contextScope(debuggerContext);
119
120     v8::Local<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
121     if (!m_listenersMap.size()) {
122         ensureDebuggerScriptCompiled();
123         ASSERT(!debuggerScript->IsUndefined());
124         v8::Debug::SetDebugEventListener2(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(m_isolate, this));
125     }
126     m_listenersMap.set(page, listener);
127
128     V8WindowShell* shell = scriptController.existingWindowShell(DOMWrapperWorld::mainWorld());
129     if (!shell || !shell->isContextInitialized())
130         return;
131     v8::Local<v8::Context> context = shell->context();
132     v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getScripts")));
133     v8::Handle<v8::Value> argv[] = { context->GetEmbedderData(0) };
134     v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getScriptsFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
135     if (value.IsEmpty())
136         return;
137     ASSERT(!value->IsUndefined() && value->IsArray());
138     v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value);
139     for (unsigned i = 0; i < scriptsArray->Length(); ++i)
140         dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(m_isolate, i))));
141 }
142
143 void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page)
144 {
145     if (!m_listenersMap.contains(page))
146         return;
147
148     if (m_pausedPage == page)
149         continueProgram();
150
151     m_listenersMap.remove(page);
152
153     if (m_listenersMap.isEmpty())
154         v8::Debug::SetDebugEventListener2(0);
155     // FIXME: Remove all breakpoints set by the agent.
156 }
157
158 void PageScriptDebugServer::interruptAndRun(PassOwnPtr<Task> task)
159 {
160     ScriptDebugServer::interruptAndRun(task, s_mainThreadIsolate);
161 }
162
163 void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop)
164 {
165     m_clientMessageLoop = clientMessageLoop;
166 }
167
168 void PageScriptDebugServer::compileScript(ScriptState* scriptState, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
169 {
170     ExecutionContext* executionContext = scriptState->executionContext();
171     RefPtr<LocalFrame> protect = toDocument(executionContext)->frame();
172     ScriptDebugServer::compileScript(scriptState, expression, sourceURL, scriptId, exceptionMessage);
173     if (!scriptId->isNull())
174         m_compiledScriptURLs.set(*scriptId, sourceURL);
175 }
176
177 void PageScriptDebugServer::clearCompiledScripts()
178 {
179     ScriptDebugServer::clearCompiledScripts();
180     m_compiledScriptURLs.clear();
181 }
182
183 void PageScriptDebugServer::runScript(ScriptState* scriptState, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
184 {
185     String sourceURL = m_compiledScriptURLs.take(scriptId);
186
187     ExecutionContext* executionContext = scriptState->executionContext();
188     LocalFrame* frame = toDocument(executionContext)->frame();
189     TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt()));
190     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
191     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
192     InspectorInstrumentationCookie cookie;
193     if (frame)
194         cookie = InspectorInstrumentation::willEvaluateScript(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt());
195
196     RefPtr<LocalFrame> protect = frame;
197     ScriptDebugServer::runScript(scriptState, scriptId, result, wasThrown, exceptionMessage);
198
199     if (frame)
200         InspectorInstrumentation::didEvaluateScript(cookie);
201     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());
202 }
203
204 ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context)
205 {
206     v8::HandleScope scope(m_isolate);
207     LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context);
208     if (!frame)
209         return 0;
210     return m_listenersMap.get(frame->page());
211 }
212
213 void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context)
214 {
215     v8::HandleScope scope(m_isolate);
216     LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context);
217     m_pausedPage = frame->page();
218
219     // Wait for continue or step command.
220     m_clientMessageLoop->run(m_pausedPage);
221
222     // The listener may have been removed in the nested loop.
223     if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage))
224         listener->didContinue();
225
226     m_pausedPage = 0;
227 }
228
229 void PageScriptDebugServer::quitMessageLoopOnPause()
230 {
231     m_clientMessageLoop->quitNow();
232 }
233
234 void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails)
235 {
236     v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
237     LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(eventContext);
238     if (!frame)
239         return;
240
241     if (!canPreprocess(frame))
242         return;
243
244     v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
245     v8::Local<v8::Context> debugContext = v8::Debug::GetDebugContext();
246     v8::Context::Scope contextScope(debugContext);
247     v8::TryCatch tryCatch;
248     // <script> tag source and attribute value source are preprocessed before we enter V8.
249     // Avoid preprocessing any internal scripts by processing only eval source in this V8 event handler.
250     v8::Handle<v8::Value> argvEventData[] = { eventData };
251     v8::Handle<v8::Value> v8Value = callDebuggerMethod("isEvalCompilation", WTF_ARRAY_LENGTH(argvEventData), argvEventData);
252     if (v8Value.IsEmpty() || !v8Value->ToBoolean()->Value())
253         return;
254
255     // The name and source are in the JS event data.
256     String scriptName = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptName", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
257     String script = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptSource", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
258
259     String preprocessedSource  = m_scriptPreprocessor->preprocessSourceCode(script, scriptName);
260
261     v8::Handle<v8::Value> argvPreprocessedScript[] = { eventData, v8String(debugContext->GetIsolate(), preprocessedSource) };
262     callDebuggerMethod("setScriptSource", WTF_ARRAY_LENGTH(argvPreprocessedScript), argvPreprocessedScript);
263 }
264
265 static bool isCreatingPreprocessor = false;
266
267 bool PageScriptDebugServer::canPreprocess(LocalFrame* frame)
268 {
269     ASSERT(frame);
270
271     if (!m_preprocessorSourceCode || !frame->page() || isCreatingPreprocessor)
272         return false;
273
274     // We delay the creation of the preprocessor until just before the first JS from the
275     // Web page to ensure that the debugger's console initialization code has completed.
276     if (!m_scriptPreprocessor) {
277         TemporaryChange<bool> isPreprocessing(isCreatingPreprocessor, true);
278         m_scriptPreprocessor = adoptPtr(new ScriptPreprocessor(*m_preprocessorSourceCode.get(), frame));
279     }
280
281     if (m_scriptPreprocessor->isValid())
282         return true;
283
284     m_scriptPreprocessor.clear();
285     // Don't retry the compile if we fail one time.
286     m_preprocessorSourceCode.clear();
287     return false;
288 }
289
290 // Source to Source processing iff debugger enabled and it has loaded a preprocessor.
291 PassOwnPtr<ScriptSourceCode> PageScriptDebugServer::preprocess(LocalFrame* frame, const ScriptSourceCode& sourceCode)
292 {
293     if (!canPreprocess(frame))
294         return PassOwnPtr<ScriptSourceCode>();
295
296     String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(sourceCode.source(), sourceCode.url());
297     return adoptPtr(new ScriptSourceCode(preprocessedSource, sourceCode.url()));
298 }
299
300 String PageScriptDebugServer::preprocessEventListener(LocalFrame* frame, const String& source, const String& url, const String& functionName)
301 {
302     if (!canPreprocess(frame))
303         return source;
304
305     return m_scriptPreprocessor->preprocessSourceCode(source, url, functionName);
306 }
307
308 void PageScriptDebugServer::muteWarningsAndDeprecations()
309 {
310     FrameConsole::mute();
311     UseCounter::muteForInspector();
312 }
313
314 void PageScriptDebugServer::unmuteWarningsAndDeprecations()
315 {
316     FrameConsole::unmute();
317     UseCounter::unmuteForInspector();
318 }
319
320 } // namespace WebCore