2 * Copyright (c) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "bindings/v8/PageScriptDebugServer.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"
58 static LocalFrame* retrieveFrameWithGlobalObjectCheck(v8::Handle<v8::Context> context)
60 if (context.IsEmpty())
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())
71 v8::Handle<v8::Value> global = V8Window::findInstanceInPrototypeChain(context->Global(), context->GetIsolate());
75 return toFrameIfNotDetached(context);
78 void PageScriptDebugServer::setPreprocessorSource(const String& preprocessorSource)
80 if (preprocessorSource.isEmpty())
81 m_preprocessorSourceCode.clear();
83 m_preprocessorSourceCode = adoptPtr(new ScriptSourceCode(preprocessorSource));
84 m_scriptPreprocessor.clear();
87 PageScriptDebugServer& PageScriptDebugServer::shared()
89 DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ());
93 v8::Isolate* PageScriptDebugServer::s_mainThreadIsolate = 0;
95 void PageScriptDebugServer::setMainThreadIsolate(v8::Isolate* isolate)
97 s_mainThreadIsolate = isolate;
100 PageScriptDebugServer::PageScriptDebugServer()
101 : ScriptDebugServer(s_mainThreadIsolate)
106 PageScriptDebugServer::~PageScriptDebugServer()
110 void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page)
112 ScriptController& scriptController = page->mainFrame()->script();
113 if (!scriptController.canExecuteScripts(NotAboutToExecuteScript))
116 v8::HandleScope scope(m_isolate);
117 v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
118 v8::Context::Scope contextScope(debuggerContext);
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));
126 m_listenersMap.set(page, listener);
128 V8WindowShell* shell = scriptController.existingWindowShell(DOMWrapperWorld::mainWorld());
129 if (!shell || !shell->isContextInitialized())
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);
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))));
143 void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page)
145 if (!m_listenersMap.contains(page))
148 if (m_pausedPage == page)
151 m_listenersMap.remove(page);
153 if (m_listenersMap.isEmpty())
154 v8::Debug::SetDebugEventListener2(0);
155 // FIXME: Remove all breakpoints set by the agent.
158 void PageScriptDebugServer::interruptAndRun(PassOwnPtr<Task> task)
160 ScriptDebugServer::interruptAndRun(task, s_mainThreadIsolate);
163 void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop)
165 m_clientMessageLoop = clientMessageLoop;
168 void PageScriptDebugServer::compileScript(ScriptState* scriptState, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
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);
177 void PageScriptDebugServer::clearCompiledScripts()
179 ScriptDebugServer::clearCompiledScripts();
180 m_compiledScriptURLs.clear();
183 void PageScriptDebugServer::runScript(ScriptState* scriptState, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
185 String sourceURL = m_compiledScriptURLs.take(scriptId);
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;
194 cookie = InspectorInstrumentation::willEvaluateScript(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt());
196 RefPtr<LocalFrame> protect = frame;
197 ScriptDebugServer::runScript(scriptState, scriptId, result, wasThrown, exceptionMessage);
200 InspectorInstrumentation::didEvaluateScript(cookie);
201 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());
204 ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context)
206 v8::HandleScope scope(m_isolate);
207 LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context);
210 return m_listenersMap.get(frame->page());
213 void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context)
215 v8::HandleScope scope(m_isolate);
216 LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context);
217 m_pausedPage = frame->page();
219 // Wait for continue or step command.
220 m_clientMessageLoop->run(m_pausedPage);
222 // The listener may have been removed in the nested loop.
223 if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage))
224 listener->didContinue();
229 void PageScriptDebugServer::quitMessageLoopOnPause()
231 m_clientMessageLoop->quitNow();
234 void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails)
236 v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
237 LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(eventContext);
241 if (!canPreprocess(frame))
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())
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));
259 String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(script, scriptName);
261 v8::Handle<v8::Value> argvPreprocessedScript[] = { eventData, v8String(debugContext->GetIsolate(), preprocessedSource) };
262 callDebuggerMethod("setScriptSource", WTF_ARRAY_LENGTH(argvPreprocessedScript), argvPreprocessedScript);
265 static bool isCreatingPreprocessor = false;
267 bool PageScriptDebugServer::canPreprocess(LocalFrame* frame)
271 if (!m_preprocessorSourceCode || !frame->page() || isCreatingPreprocessor)
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));
281 if (m_scriptPreprocessor->isValid())
284 m_scriptPreprocessor.clear();
285 // Don't retry the compile if we fail one time.
286 m_preprocessorSourceCode.clear();
290 // Source to Source processing iff debugger enabled and it has loaded a preprocessor.
291 PassOwnPtr<ScriptSourceCode> PageScriptDebugServer::preprocess(LocalFrame* frame, const ScriptSourceCode& sourceCode)
293 if (!canPreprocess(frame))
294 return PassOwnPtr<ScriptSourceCode>();
296 String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(sourceCode.source(), sourceCode.url());
297 return adoptPtr(new ScriptSourceCode(preprocessedSource, sourceCode.url()));
300 String PageScriptDebugServer::preprocessEventListener(LocalFrame* frame, const String& source, const String& url, const String& functionName)
302 if (!canPreprocess(frame))
305 return m_scriptPreprocessor->preprocessSourceCode(source, url, functionName);
308 void PageScriptDebugServer::muteWarningsAndDeprecations()
310 FrameConsole::mute();
311 UseCounter::muteForInspector();
314 void PageScriptDebugServer::unmuteWarningsAndDeprecations()
316 FrameConsole::unmute();
317 UseCounter::unmuteForInspector();
320 } // namespace WebCore