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 6 * are met: 7 * 1. Redistributions of source code must retain the above copyright 8 * notice, this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright 10 * notice, this list of conditions and the following disclaimer in the 11 * documentation and/or other materials provided with the distribution. 12 * 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY 14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY 17 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 */ 24 25 26 #include "config.h" 27 #include "core/inspector/InspectorConsoleAgent.h" 28 29 #include "InspectorFrontend.h" 30 #include "bindings/v8/ScriptCallStackFactory.h" 31 #include "bindings/v8/ScriptController.h" 32 #include "bindings/v8/ScriptObject.h" 33 #include "bindings/v8/ScriptProfiler.h" 34 #include "core/inspector/ConsoleMessage.h" 35 #include "core/inspector/InjectedScriptHost.h" 36 #include "core/inspector/InjectedScriptManager.h" 37 #include "core/inspector/InspectorState.h" 38 #include "core/inspector/InstrumentingAgents.h" 39 #include "core/inspector/ScriptArguments.h" 40 #include "core/inspector/ScriptCallFrame.h" 41 #include "core/inspector/ScriptCallStack.h" 42 #include "core/loader/DocumentLoader.h" 43 #include "core/page/Frame.h" 44 #include "core/page/Page.h" 45 #include "core/platform/network/ResourceError.h" 46 #include "core/platform/network/ResourceResponse.h" 47 #include "wtf/CurrentTime.h" 48 #include "wtf/OwnPtr.h" 49 #include "wtf/PassOwnPtr.h" 50 #include "wtf/text/StringBuilder.h" 51 #include "wtf/text/WTFString.h" 52 53 namespace WebCore { 54 55 static const unsigned maximumConsoleMessages = 1000; 56 static const int expireConsoleMessagesStep = 100; 57 58 namespace ConsoleAgentState { 59 static const char monitoringXHR[] = "monitoringXHR"; 60 static const char consoleMessagesEnabled[] = "consoleMessagesEnabled"; 61 } 62 63 int InspectorConsoleAgent::s_enabledAgentCount = 0; 64 65 InspectorConsoleAgent::InspectorConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager) 66 : InspectorBaseAgent<InspectorConsoleAgent>("Console", instrumentingAgents, state) 67 , m_injectedScriptManager(injectedScriptManager) 68 , m_frontend(0) 69 , m_previousMessage(0) 70 , m_expiredConsoleMessageCount(0) 71 , m_enabled(false) 72 { 73 m_instrumentingAgents->setInspectorConsoleAgent(this); 74 } 75 76 InspectorConsoleAgent::~InspectorConsoleAgent() 77 { 78 m_instrumentingAgents->setInspectorConsoleAgent(0); 79 m_instrumentingAgents = 0; 80 m_state = 0; 81 m_injectedScriptManager = 0; 82 } 83 84 void InspectorConsoleAgent::enable(ErrorString*) 85 { 86 if (m_enabled) 87 return; 88 m_enabled = true; 89 if (!s_enabledAgentCount) 90 ScriptController::setCaptureCallStackForUncaughtExceptions(true); 91 ++s_enabledAgentCount; 92 93 m_state->setBoolean(ConsoleAgentState::consoleMessagesEnabled, true); 94 95 if (m_expiredConsoleMessageCount) { 96 ConsoleMessage expiredMessage(!isWorkerAgent(), OtherMessageSource, LogMessageType, WarningMessageLevel, String::format("%d console messages are not shown.", m_expiredConsoleMessageCount)); 97 expiredMessage.setTimestamp(0); 98 expiredMessage.addToFrontend(m_frontend, m_injectedScriptManager, false); 99 } 100 101 size_t messageCount = m_consoleMessages.size(); 102 for (size_t i = 0; i < messageCount; ++i) 103 m_consoleMessages[i]->addToFrontend(m_frontend, m_injectedScriptManager, false); 104 } 105 106 void InspectorConsoleAgent::disable(ErrorString*) 107 { 108 if (!m_enabled) 109 return; 110 m_enabled = false; 111 if (!(--s_enabledAgentCount)) 112 ScriptController::setCaptureCallStackForUncaughtExceptions(false); 113 m_state->setBoolean(ConsoleAgentState::consoleMessagesEnabled, false); 114 } 115 116 void InspectorConsoleAgent::clearMessages(ErrorString*) 117 { 118 m_consoleMessages.clear(); 119 m_expiredConsoleMessageCount = 0; 120 m_previousMessage = 0; 121 m_injectedScriptManager->releaseObjectGroup("console"); 122 if (m_frontend && m_enabled) 123 m_frontend->messagesCleared(); 124 } 125 126 void InspectorConsoleAgent::reset() 127 { 128 ErrorString error; 129 clearMessages(&error); 130 m_times.clear(); 131 m_counts.clear(); 132 } 133 134 void InspectorConsoleAgent::restore() 135 { 136 if (m_state->getBoolean(ConsoleAgentState::consoleMessagesEnabled)) { 137 m_frontend->messagesCleared(); 138 ErrorString error; 139 enable(&error); 140 } 141 } 142 143 void InspectorConsoleAgent::setFrontend(InspectorFrontend* frontend) 144 { 145 m_frontend = frontend->console(); 146 } 147 148 void InspectorConsoleAgent::clearFrontend() 149 { 150 m_frontend = 0; 151 String errorString; 152 disable(&errorString); 153 } 154 155 void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier) 156 { 157 if (type == ClearMessageType) { 158 ErrorString error; 159 clearMessages(&error); 160 } 161 162 addConsoleMessage(adoptPtr(new ConsoleMessage(!isWorkerAgent(), source, type, level, message, callStack, requestIdentifier))); 163 } 164 165 void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, ScriptState* state, PassRefPtr<ScriptArguments> arguments, unsigned long requestIdentifier) 166 { 167 if (type == ClearMessageType) { 168 ErrorString error; 169 clearMessages(&error); 170 } 171 172 addConsoleMessage(adoptPtr(new ConsoleMessage(!isWorkerAgent(), source, type, level, message, arguments, state, requestIdentifier))); 173 } 174 175 void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber, ScriptState* state, unsigned long requestIdentifier) 176 { 177 if (type == ClearMessageType) { 178 ErrorString error; 179 clearMessages(&error); 180 } 181 182 bool canGenerateCallStack = !isWorkerAgent() && m_frontend; 183 addConsoleMessage(adoptPtr(new ConsoleMessage(canGenerateCallStack, source, type, level, message, scriptId, lineNumber, columnNumber, state, requestIdentifier))); 184 } 185 186 Vector<unsigned> InspectorConsoleAgent::consoleMessageArgumentCounts() 187 { 188 Vector<unsigned> result(m_consoleMessages.size()); 189 for (size_t i = 0; i < m_consoleMessages.size(); i++) 190 result[i] = m_consoleMessages[i]->argumentCount(); 191 return result; 192 } 193 194 void InspectorConsoleAgent::startConsoleTiming(Frame*, const String& title) 195 { 196 // Follow Firebug's behavior of requiring a title that is not null or 197 // undefined for timing functions 198 if (title.isNull()) 199 return; 200 201 m_times.add(title, monotonicallyIncreasingTime()); 202 } 203 204 void InspectorConsoleAgent::stopConsoleTiming(Frame*, const String& title, PassRefPtr<ScriptCallStack> callStack) 205 { 206 // Follow Firebug's behavior of requiring a title that is not null or 207 // undefined for timing functions 208 if (title.isNull()) 209 return; 210 211 HashMap<String, double>::iterator it = m_times.find(title); 212 if (it == m_times.end()) 213 return; 214 215 double startTime = it->value; 216 m_times.remove(it); 217 218 double elapsed = monotonicallyIncreasingTime() - startTime; 219 String message = title + String::format(": %.3fms", elapsed * 1000); 220 const ScriptCallFrame& lastCaller = callStack->at(0); 221 addMessageToConsole(ConsoleAPIMessageSource, TimingMessageType, DebugMessageLevel, message, lastCaller.sourceURL(), lastCaller.lineNumber(), lastCaller.columnNumber()); 222 } 223 224 void InspectorConsoleAgent::consoleCount(ScriptState* state, PassRefPtr<ScriptArguments> arguments) 225 { 226 RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state)); 227 const ScriptCallFrame& lastCaller = callStack->at(0); 228 // Follow Firebug's behavior of counting with null and undefined title in 229 // the same bucket as no argument 230 String title; 231 arguments->getFirstArgumentAsString(title); 232 String identifier = title.isEmpty() ? String(lastCaller.sourceURL() + ':' + String::number(lastCaller.lineNumber())) 233 : String(title + '@'); 234 235 HashMap<String, unsigned>::iterator it = m_counts.find(identifier); 236 int count; 237 if (it == m_counts.end()) 238 count = 1; 239 else { 240 count = it->value + 1; 241 m_counts.remove(it); 242 } 243 244 m_counts.add(identifier, count); 245 246 String message = title + ": " + String::number(count); 247 addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, callStack); 248 } 249 250 void InspectorConsoleAgent::frameWindowDiscarded(DOMWindow* window) 251 { 252 size_t messageCount = m_consoleMessages.size(); 253 for (size_t i = 0; i < messageCount; ++i) 254 m_consoleMessages[i]->windowCleared(window); 255 m_injectedScriptManager->discardInjectedScriptsFor(window); 256 } 257 258 void InspectorConsoleAgent::didCommitLoad(Frame* frame, DocumentLoader* loader) 259 { 260 if (loader->frame() != frame->page()->mainFrame()) 261 return; 262 reset(); 263 } 264 265 void InspectorConsoleAgent::didFinishXHRLoading(ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber) 266 { 267 if (m_frontend && m_state->getBoolean(ConsoleAgentState::monitoringXHR)) { 268 String message = "XHR finished loading: \"" + url + "\"."; 269 addMessageToConsole(NetworkMessageSource, LogMessageType, DebugMessageLevel, message, sendURL, sendLineNumber, 0, 0, requestIdentifier); 270 } 271 } 272 273 void InspectorConsoleAgent::didReceiveResourceResponse(unsigned long requestIdentifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader*) 274 { 275 if (!loader) 276 return; 277 if (response.httpStatusCode() >= 400) { 278 String message = "Failed to load resource: the server responded with a status of " + String::number(response.httpStatusCode()) + " (" + response.httpStatusText() + ')'; 279 addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message, response.url().string(), 0, 0, 0, requestIdentifier); 280 } 281 } 282 283 void InspectorConsoleAgent::didFailLoading(unsigned long requestIdentifier, DocumentLoader*, const ResourceError& error) 284 { 285 if (error.isCancellation()) // Report failures only. 286 return; 287 StringBuilder message; 288 message.appendLiteral("Failed to load resource"); 289 if (!error.localizedDescription().isEmpty()) { 290 message.appendLiteral(": "); 291 message.append(error.localizedDescription()); 292 } 293 addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message.toString(), error.failingURL(), 0, 0, 0, requestIdentifier); 294 } 295 296 void InspectorConsoleAgent::setMonitoringXHREnabled(ErrorString*, bool enabled) 297 { 298 m_state->setBoolean(ConsoleAgentState::monitoringXHR, enabled); 299 } 300 301 static bool isGroupMessage(MessageType type) 302 { 303 return type == StartGroupMessageType 304 || type == StartGroupCollapsedMessageType 305 || type == EndGroupMessageType; 306 } 307 308 void InspectorConsoleAgent::addConsoleMessage(PassOwnPtr<ConsoleMessage> consoleMessage) 309 { 310 ASSERT_ARG(consoleMessage, consoleMessage); 311 312 if (m_previousMessage && !isGroupMessage(m_previousMessage->type()) && m_previousMessage->isEqual(consoleMessage.get())) { 313 m_previousMessage->incrementCount(); 314 if (m_frontend && m_enabled) 315 m_previousMessage->updateRepeatCountInConsole(m_frontend); 316 } else { 317 m_previousMessage = consoleMessage.get(); 318 m_consoleMessages.append(consoleMessage); 319 if (m_frontend && m_enabled) 320 m_previousMessage->addToFrontend(m_frontend, m_injectedScriptManager, true); 321 } 322 323 if (!m_frontend && m_consoleMessages.size() >= maximumConsoleMessages) { 324 m_expiredConsoleMessageCount += expireConsoleMessagesStep; 325 m_consoleMessages.remove(0, expireConsoleMessagesStep); 326 } 327 } 328 329 class InspectableHeapObject : public InjectedScriptHost::InspectableObject { 330 public: 331 explicit InspectableHeapObject(int heapObjectId) : m_heapObjectId(heapObjectId) { } 332 virtual ScriptValue get(ScriptState*) 333 { 334 return ScriptProfiler::objectByHeapObjectId(m_heapObjectId); 335 } 336 private: 337 int m_heapObjectId; 338 }; 339 340 void InspectorConsoleAgent::addInspectedHeapObject(ErrorString*, int inspectedHeapObjectId) 341 { 342 m_injectedScriptManager->injectedScriptHost()->addInspectedObject(adoptPtr(new InspectableHeapObject(inspectedHeapObjectId))); 343 } 344 345 } // namespace WebCore 346 347