InspectorConsoleAgent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. #include "config.h"
  25. #if ENABLE(INSPECTOR)
  26. #include "InspectorConsoleAgent.h"
  27. #include "InstrumentingAgents.h"
  28. #include "Console.h"
  29. #include "ConsoleMessage.h"
  30. #include "DOMWindow.h"
  31. #include "InjectedScriptHost.h"
  32. #include "InjectedScriptManager.h"
  33. #include "InspectorFrontend.h"
  34. #include "InspectorState.h"
  35. #include "ResourceError.h"
  36. #include "ResourceResponse.h"
  37. #include "ScriptArguments.h"
  38. #include "ScriptCallFrame.h"
  39. #include "ScriptCallStack.h"
  40. #include "ScriptCallStackFactory.h"
  41. #include "ScriptController.h"
  42. #include "ScriptObject.h"
  43. #include "ScriptProfiler.h"
  44. #include <wtf/CurrentTime.h>
  45. #include <wtf/OwnPtr.h>
  46. #include <wtf/PassOwnPtr.h>
  47. #include <wtf/text/StringBuilder.h>
  48. #include <wtf/text/WTFString.h>
  49. namespace WebCore {
  50. static const unsigned maximumConsoleMessages = 1000;
  51. static const int expireConsoleMessagesStep = 100;
  52. namespace ConsoleAgentState {
  53. static const char monitoringXHR[] = "monitoringXHR";
  54. static const char consoleMessagesEnabled[] = "consoleMessagesEnabled";
  55. }
  56. int InspectorConsoleAgent::s_enabledAgentCount = 0;
  57. InspectorConsoleAgent::InspectorConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
  58. : InspectorBaseAgent<InspectorConsoleAgent>("Console", instrumentingAgents, state)
  59. , m_injectedScriptManager(injectedScriptManager)
  60. , m_frontend(0)
  61. , m_previousMessage(0)
  62. , m_expiredConsoleMessageCount(0)
  63. , m_enabled(false)
  64. {
  65. m_instrumentingAgents->setInspectorConsoleAgent(this);
  66. }
  67. InspectorConsoleAgent::~InspectorConsoleAgent()
  68. {
  69. m_instrumentingAgents->setInspectorConsoleAgent(0);
  70. m_instrumentingAgents = 0;
  71. m_state = 0;
  72. m_injectedScriptManager = 0;
  73. }
  74. void InspectorConsoleAgent::enable(ErrorString*)
  75. {
  76. if (m_enabled)
  77. return;
  78. m_enabled = true;
  79. if (!s_enabledAgentCount)
  80. ScriptController::setCaptureCallStackForUncaughtExceptions(true);
  81. ++s_enabledAgentCount;
  82. m_state->setBoolean(ConsoleAgentState::consoleMessagesEnabled, true);
  83. if (m_expiredConsoleMessageCount) {
  84. ConsoleMessage expiredMessage(!isWorkerAgent(), OtherMessageSource, LogMessageType, WarningMessageLevel, String::format("%d console messages are not shown.", m_expiredConsoleMessageCount));
  85. expiredMessage.addToFrontend(m_frontend, m_injectedScriptManager, false);
  86. }
  87. size_t messageCount = m_consoleMessages.size();
  88. for (size_t i = 0; i < messageCount; ++i)
  89. m_consoleMessages[i]->addToFrontend(m_frontend, m_injectedScriptManager, false);
  90. }
  91. void InspectorConsoleAgent::disable(ErrorString*)
  92. {
  93. if (!m_enabled)
  94. return;
  95. m_enabled = false;
  96. if (!(--s_enabledAgentCount))
  97. ScriptController::setCaptureCallStackForUncaughtExceptions(false);
  98. m_state->setBoolean(ConsoleAgentState::consoleMessagesEnabled, false);
  99. }
  100. void InspectorConsoleAgent::clearMessages(ErrorString*)
  101. {
  102. m_consoleMessages.clear();
  103. m_expiredConsoleMessageCount = 0;
  104. m_previousMessage = 0;
  105. m_injectedScriptManager->releaseObjectGroup("console");
  106. if (m_frontend && m_enabled)
  107. m_frontend->messagesCleared();
  108. }
  109. void InspectorConsoleAgent::reset()
  110. {
  111. ErrorString error;
  112. clearMessages(&error);
  113. m_times.clear();
  114. m_counts.clear();
  115. }
  116. void InspectorConsoleAgent::restore()
  117. {
  118. if (m_state->getBoolean(ConsoleAgentState::consoleMessagesEnabled)) {
  119. m_frontend->messagesCleared();
  120. ErrorString error;
  121. enable(&error);
  122. }
  123. }
  124. void InspectorConsoleAgent::setFrontend(InspectorFrontend* frontend)
  125. {
  126. m_frontend = frontend->console();
  127. }
  128. void InspectorConsoleAgent::clearFrontend()
  129. {
  130. m_frontend = 0;
  131. String errorString;
  132. disable(&errorString);
  133. }
  134. void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier)
  135. {
  136. if (!developerExtrasEnabled())
  137. return;
  138. if (type == ClearMessageType) {
  139. ErrorString error;
  140. clearMessages(&error);
  141. }
  142. addConsoleMessage(adoptPtr(new ConsoleMessage(!isWorkerAgent(), source, type, level, message, callStack, requestIdentifier)));
  143. }
  144. void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, ScriptState* state, PassRefPtr<ScriptArguments> arguments, unsigned long requestIdentifier)
  145. {
  146. if (!developerExtrasEnabled())
  147. return;
  148. if (type == ClearMessageType) {
  149. ErrorString error;
  150. clearMessages(&error);
  151. }
  152. addConsoleMessage(adoptPtr(new ConsoleMessage(!isWorkerAgent(), source, type, level, message, arguments, state, requestIdentifier)));
  153. }
  154. void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber, ScriptState* state, unsigned long requestIdentifier)
  155. {
  156. if (!developerExtrasEnabled())
  157. return;
  158. if (type == ClearMessageType) {
  159. ErrorString error;
  160. clearMessages(&error);
  161. }
  162. bool canGenerateCallStack = !isWorkerAgent() && m_frontend;
  163. addConsoleMessage(adoptPtr(new ConsoleMessage(canGenerateCallStack, source, type, level, message, scriptId, lineNumber, columnNumber, state, requestIdentifier)));
  164. }
  165. Vector<unsigned> InspectorConsoleAgent::consoleMessageArgumentCounts()
  166. {
  167. Vector<unsigned> result(m_consoleMessages.size());
  168. for (size_t i = 0; i < m_consoleMessages.size(); i++)
  169. result[i] = m_consoleMessages[i]->argumentCount();
  170. return result;
  171. }
  172. void InspectorConsoleAgent::startTiming(const String& title)
  173. {
  174. // Follow Firebug's behavior of requiring a title that is not null or
  175. // undefined for timing functions
  176. if (title.isNull())
  177. return;
  178. m_times.add(title, monotonicallyIncreasingTime());
  179. }
  180. void InspectorConsoleAgent::stopTiming(const String& title, PassRefPtr<ScriptCallStack> callStack)
  181. {
  182. // Follow Firebug's behavior of requiring a title that is not null or
  183. // undefined for timing functions
  184. if (title.isNull())
  185. return;
  186. HashMap<String, double>::iterator it = m_times.find(title);
  187. if (it == m_times.end())
  188. return;
  189. double startTime = it->value;
  190. m_times.remove(it);
  191. double elapsed = monotonicallyIncreasingTime() - startTime;
  192. String message = title + String::format(": %.3fms", elapsed * 1000);
  193. addMessageToConsole(ConsoleAPIMessageSource, TimingMessageType, DebugMessageLevel, message, callStack);
  194. }
  195. void InspectorConsoleAgent::count(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
  196. {
  197. RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state));
  198. const ScriptCallFrame& lastCaller = callStack->at(0);
  199. // Follow Firebug's behavior of counting with null and undefined title in
  200. // the same bucket as no argument
  201. String title;
  202. arguments->getFirstArgumentAsString(title);
  203. String identifier = title + '@' + lastCaller.sourceURL() + ':' + String::number(lastCaller.lineNumber());
  204. HashMap<String, unsigned>::iterator it = m_counts.find(identifier);
  205. int count;
  206. if (it == m_counts.end())
  207. count = 1;
  208. else {
  209. count = it->value + 1;
  210. m_counts.remove(it);
  211. }
  212. m_counts.add(identifier, count);
  213. String message = title + ": " + String::number(count);
  214. addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, callStack);
  215. }
  216. void InspectorConsoleAgent::frameWindowDiscarded(DOMWindow* window)
  217. {
  218. size_t messageCount = m_consoleMessages.size();
  219. for (size_t i = 0; i < messageCount; ++i)
  220. m_consoleMessages[i]->windowCleared(window);
  221. m_injectedScriptManager->discardInjectedScriptsFor(window);
  222. }
  223. void InspectorConsoleAgent::didFinishXHRLoading(unsigned long requestIdentifier, const String& url, const String& sendURL, unsigned sendLineNumber)
  224. {
  225. if (!developerExtrasEnabled())
  226. return;
  227. if (m_frontend && m_state->getBoolean(ConsoleAgentState::monitoringXHR)) {
  228. String message = "XHR finished loading: \"" + url + "\".";
  229. // FIXME: <http://webkit.org/b/114316> InspectorConsoleAgent::didFinishXHRLoading ConsoleMessage should include a column number
  230. addMessageToConsole(NetworkMessageSource, LogMessageType, DebugMessageLevel, message, sendURL, sendLineNumber, 0, 0, requestIdentifier);
  231. }
  232. }
  233. void InspectorConsoleAgent::didReceiveResponse(unsigned long requestIdentifier, const ResourceResponse& response)
  234. {
  235. if (!developerExtrasEnabled())
  236. return;
  237. if (response.httpStatusCode() >= 400) {
  238. String message = "Failed to load resource: the server responded with a status of " + String::number(response.httpStatusCode()) + " (" + response.httpStatusText() + ')';
  239. addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message, response.url().string(), 0, 0, 0, requestIdentifier);
  240. }
  241. }
  242. void InspectorConsoleAgent::didFailLoading(unsigned long requestIdentifier, const ResourceError& error)
  243. {
  244. if (!developerExtrasEnabled())
  245. return;
  246. if (error.isCancellation()) // Report failures only.
  247. return;
  248. StringBuilder message;
  249. message.appendLiteral("Failed to load resource");
  250. if (!error.localizedDescription().isEmpty()) {
  251. message.appendLiteral(": ");
  252. message.append(error.localizedDescription());
  253. }
  254. addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message.toString(), error.failingURL(), 0, 0, 0, requestIdentifier);
  255. }
  256. void InspectorConsoleAgent::setMonitoringXHREnabled(ErrorString*, bool enabled)
  257. {
  258. m_state->setBoolean(ConsoleAgentState::monitoringXHR, enabled);
  259. }
  260. static bool isGroupMessage(MessageType type)
  261. {
  262. return type == StartGroupMessageType
  263. || type == StartGroupCollapsedMessageType
  264. || type == EndGroupMessageType;
  265. }
  266. void InspectorConsoleAgent::addConsoleMessage(PassOwnPtr<ConsoleMessage> consoleMessage)
  267. {
  268. ASSERT(developerExtrasEnabled());
  269. ASSERT_ARG(consoleMessage, consoleMessage);
  270. if (m_previousMessage && !isGroupMessage(m_previousMessage->type()) && m_previousMessage->isEqual(consoleMessage.get())) {
  271. m_previousMessage->incrementCount();
  272. if (m_frontend && m_enabled)
  273. m_previousMessage->updateRepeatCountInConsole(m_frontend);
  274. } else {
  275. m_previousMessage = consoleMessage.get();
  276. m_consoleMessages.append(consoleMessage);
  277. if (m_frontend && m_enabled)
  278. m_previousMessage->addToFrontend(m_frontend, m_injectedScriptManager, true);
  279. }
  280. if (!m_frontend && m_consoleMessages.size() >= maximumConsoleMessages) {
  281. m_expiredConsoleMessageCount += expireConsoleMessagesStep;
  282. m_consoleMessages.remove(0, expireConsoleMessagesStep);
  283. }
  284. }
  285. class InspectableHeapObject : public InjectedScriptHost::InspectableObject {
  286. public:
  287. explicit InspectableHeapObject(int heapObjectId) : m_heapObjectId(heapObjectId) { }
  288. virtual ScriptValue get(ScriptState*)
  289. {
  290. return ScriptProfiler::objectByHeapObjectId(m_heapObjectId);
  291. }
  292. private:
  293. int m_heapObjectId;
  294. };
  295. void InspectorConsoleAgent::addInspectedHeapObject(ErrorString*, int inspectedHeapObjectId)
  296. {
  297. m_injectedScriptManager->injectedScriptHost()->addInspectedObject(adoptPtr(new InspectableHeapObject(inspectedHeapObjectId)));
  298. }
  299. } // namespace WebCore
  300. #endif // ENABLE(INSPECTOR)