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 "bindings/core/v8/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->deprecatedLocalMainFrame()->script(); 113 if (!scriptController.canExecuteScripts(NotAboutToExecuteScript)) 114 return; 115 116 v8::HandleScope scope(m_isolate); 117 118 if (!m_listenersMap.size()) { 119 v8::Debug::SetDebugEventListener(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(m_isolate, this)); 120 ensureDebuggerScriptCompiled(); 121 } 122 123 v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext(); 124 v8::Context::Scope contextScope(debuggerContext); 125 126 v8::Local<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate); 127 ASSERT(!debuggerScript->IsUndefined()); 128 m_listenersMap.set(page, listener); 129 130 V8WindowShell* shell = scriptController.existingWindowShell(DOMWrapperWorld::mainWorld()); 131 if (!shell || !shell->isContextInitialized()) 132 return; 133 v8::Local<v8::Context> context = shell->context(); 134 v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getScripts"))); 135 v8::Handle<v8::Value> argv[] = { context->GetEmbedderData(0) }; 136 v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getScriptsFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate); 137 if (value.IsEmpty()) 138 return; 139 ASSERT(!value->IsUndefined() && value->IsArray()); 140 v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value); 141 for (unsigned i = 0; i < scriptsArray->Length(); ++i) 142 dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(m_isolate, i)))); 143 } 144 145 void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page) 146 { 147 if (!m_listenersMap.contains(page)) 148 return; 149 150 if (m_pausedPage == page) 151 continueProgram(); 152 153 m_listenersMap.remove(page); 154 155 if (m_listenersMap.isEmpty()) { 156 discardDebuggerScript(); 157 v8::Debug::SetDebugEventListener(0); 158 // FIXME: Remove all breakpoints set by the agent. 159 } 160 } 161 162 void PageScriptDebugServer::interruptAndRun(PassOwnPtr<Task> task) 163 { 164 ScriptDebugServer::interruptAndRun(task, s_mainThreadIsolate); 165 } 166 167 void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop) 168 { 169 m_clientMessageLoop = clientMessageLoop; 170 } 171 172 void PageScriptDebugServer::compileScript(ScriptState* scriptState, const String& expression, const String& sourceURL, String* scriptId, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtrWillBeRawPtr<ScriptCallStack>* stackTrace) 173 { 174 ExecutionContext* executionContext = scriptState->executionContext(); 175 RefPtr<LocalFrame> protect = toDocument(executionContext)->frame(); 176 ScriptDebugServer::compileScript(scriptState, expression, sourceURL, scriptId, exceptionDetailsText, lineNumber, columnNumber, stackTrace); 177 if (!scriptId->isNull()) 178 m_compiledScriptURLs.set(*scriptId, sourceURL); 179 } 180 181 void PageScriptDebugServer::clearCompiledScripts() 182 { 183 ScriptDebugServer::clearCompiledScripts(); 184 m_compiledScriptURLs.clear(); 185 } 186 187 void PageScriptDebugServer::runScript(ScriptState* scriptState, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtrWillBeRawPtr<ScriptCallStack>* stackTrace) 188 { 189 String sourceURL = m_compiledScriptURLs.take(scriptId); 190 191 ExecutionContext* executionContext = scriptState->executionContext(); 192 LocalFrame* frame = toDocument(executionContext)->frame(); 193 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt())); 194 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack()); 195 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing. 196 InspectorInstrumentationCookie cookie; 197 if (frame) 198 cookie = InspectorInstrumentation::willEvaluateScript(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt()); 199 200 RefPtr<LocalFrame> protect = frame; 201 ScriptDebugServer::runScript(scriptState, scriptId, result, wasThrown, exceptionDetailsText, lineNumber, columnNumber, stackTrace); 202 203 if (frame) 204 InspectorInstrumentation::didEvaluateScript(cookie); 205 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data()); 206 } 207 208 ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context) 209 { 210 v8::HandleScope scope(m_isolate); 211 LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context); 212 if (!frame) 213 return 0; 214 return m_listenersMap.get(frame->page()); 215 } 216 217 void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context) 218 { 219 v8::HandleScope scope(m_isolate); 220 LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context); 221 m_pausedPage = frame->page(); 222 223 // Wait for continue or step command. 224 m_clientMessageLoop->run(m_pausedPage); 225 226 // The listener may have been removed in the nested loop. 227 if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage)) 228 listener->didContinue(); 229 230 m_pausedPage = 0; 231 } 232 233 void PageScriptDebugServer::quitMessageLoopOnPause() 234 { 235 m_clientMessageLoop->quitNow(); 236 } 237 238 void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails) 239 { 240 v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext(); 241 LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(eventContext); 242 if (!frame) 243 return; 244 245 if (!canPreprocess(frame)) 246 return; 247 248 v8::Handle<v8::Object> eventData = eventDetails.GetEventData(); 249 v8::Local<v8::Context> debugContext = v8::Debug::GetDebugContext(); 250 v8::Context::Scope contextScope(debugContext); 251 v8::TryCatch tryCatch; 252 // <script> tag source and attribute value source are preprocessed before we enter V8. 253 // Avoid preprocessing any internal scripts by processing only eval source in this V8 event handler. 254 v8::Handle<v8::Value> argvEventData[] = { eventData }; 255 v8::Handle<v8::Value> v8Value = callDebuggerMethod("isEvalCompilation", WTF_ARRAY_LENGTH(argvEventData), argvEventData); 256 if (v8Value.IsEmpty() || !v8Value->ToBoolean()->Value()) 257 return; 258 259 // The name and source are in the JS event data. 260 String scriptName = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptName", WTF_ARRAY_LENGTH(argvEventData), argvEventData)); 261 String script = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptSource", WTF_ARRAY_LENGTH(argvEventData), argvEventData)); 262 263 String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(script, scriptName); 264 265 v8::Handle<v8::Value> argvPreprocessedScript[] = { eventData, v8String(debugContext->GetIsolate(), preprocessedSource) }; 266 callDebuggerMethod("setScriptSource", WTF_ARRAY_LENGTH(argvPreprocessedScript), argvPreprocessedScript); 267 } 268 269 static bool isCreatingPreprocessor = false; 270 271 bool PageScriptDebugServer::canPreprocess(LocalFrame* frame) 272 { 273 ASSERT(frame); 274 275 if (!m_preprocessorSourceCode || !frame->page() || isCreatingPreprocessor) 276 return false; 277 278 // We delay the creation of the preprocessor until just before the first JS from the 279 // Web page to ensure that the debugger's console initialization code has completed. 280 if (!m_scriptPreprocessor) { 281 TemporaryChange<bool> isPreprocessing(isCreatingPreprocessor, true); 282 m_scriptPreprocessor = adoptPtr(new ScriptPreprocessor(*m_preprocessorSourceCode.get(), frame)); 283 } 284 285 if (m_scriptPreprocessor->isValid()) 286 return true; 287 288 m_scriptPreprocessor.clear(); 289 // Don't retry the compile if we fail one time. 290 m_preprocessorSourceCode.clear(); 291 return false; 292 } 293 294 // Source to Source processing iff debugger enabled and it has loaded a preprocessor. 295 PassOwnPtr<ScriptSourceCode> PageScriptDebugServer::preprocess(LocalFrame* frame, const ScriptSourceCode& sourceCode) 296 { 297 if (!canPreprocess(frame)) 298 return PassOwnPtr<ScriptSourceCode>(); 299 300 String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(sourceCode.source(), sourceCode.url()); 301 return adoptPtr(new ScriptSourceCode(preprocessedSource, sourceCode.url())); 302 } 303 304 String PageScriptDebugServer::preprocessEventListener(LocalFrame* frame, const String& source, const String& url, const String& functionName) 305 { 306 if (!canPreprocess(frame)) 307 return source; 308 309 return m_scriptPreprocessor->preprocessSourceCode(source, url, functionName); 310 } 311 312 void PageScriptDebugServer::muteWarningsAndDeprecations() 313 { 314 FrameConsole::mute(); 315 UseCounter::muteForInspector(); 316 } 317 318 void PageScriptDebugServer::unmuteWarningsAndDeprecations() 319 { 320 FrameConsole::unmute(); 321 UseCounter::unmuteForInspector(); 322 } 323 324 } // namespace WebCore 325