InspectorProfilerAgent.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * Copyright (C) 2010 Apple Inc. All rights reserved.
  3. * Copyright (C) 2010 Google Inc. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  15. * its contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include "config.h"
  30. #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
  31. #include "InspectorProfilerAgent.h"
  32. #include "Console.h"
  33. #include "ConsoleAPITypes.h"
  34. #include "ConsoleTypes.h"
  35. #include "InjectedScript.h"
  36. #include "InjectedScriptHost.h"
  37. #include "InspectorConsoleAgent.h"
  38. #include "InspectorFrontend.h"
  39. #include "InspectorState.h"
  40. #include "InspectorValues.h"
  41. #include "InstrumentingAgents.h"
  42. #include "KURL.h"
  43. #include "Page.h"
  44. #include "PageScriptDebugServer.h"
  45. #include "ScriptHeapSnapshot.h"
  46. #include "ScriptObject.h"
  47. #include "ScriptProfile.h"
  48. #include "ScriptProfiler.h"
  49. #include "WorkerScriptDebugServer.h"
  50. #include <wtf/CurrentTime.h>
  51. #include <wtf/OwnPtr.h>
  52. #include <wtf/text/StringConcatenate.h>
  53. namespace WebCore {
  54. namespace ProfilerAgentState {
  55. static const char userInitiatedProfiling[] = "userInitiatedProfiling";
  56. static const char profilerEnabled[] = "profilerEnabled";
  57. static const char profileHeadersRequested[] = "profileHeadersRequested";
  58. }
  59. static const char* const UserInitiatedProfileName = "org.webkit.profiles.user-initiated";
  60. static const char* const CPUProfileType = "CPU";
  61. static const char* const HeapProfileType = "HEAP";
  62. class PageProfilerAgent : public InspectorProfilerAgent {
  63. public:
  64. PageProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, Page* inspectedPage, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
  65. : InspectorProfilerAgent(instrumentingAgents, consoleAgent, state, injectedScriptManager), m_inspectedPage(inspectedPage) { }
  66. virtual ~PageProfilerAgent() { }
  67. private:
  68. virtual void recompileScript()
  69. {
  70. PageScriptDebugServer::shared().recompileAllJSFunctionsSoon();
  71. }
  72. virtual void startProfiling(const String& title)
  73. {
  74. ScriptProfiler::startForPage(m_inspectedPage, title);
  75. }
  76. virtual PassRefPtr<ScriptProfile> stopProfiling(const String& title)
  77. {
  78. return ScriptProfiler::stopForPage(m_inspectedPage, title);
  79. }
  80. Page* m_inspectedPage;
  81. };
  82. PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, Page* inspectedPage, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
  83. {
  84. return adoptPtr(new PageProfilerAgent(instrumentingAgents, consoleAgent, inspectedPage, inspectorState, injectedScriptManager));
  85. }
  86. #if ENABLE(WORKERS)
  87. class WorkerProfilerAgent : public InspectorProfilerAgent {
  88. public:
  89. WorkerProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, WorkerContext* workerContext, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
  90. : InspectorProfilerAgent(instrumentingAgents, consoleAgent, state, injectedScriptManager), m_workerContext(workerContext) { }
  91. virtual ~WorkerProfilerAgent() { }
  92. private:
  93. virtual void recompileScript() { }
  94. virtual void startProfiling(const String& title)
  95. {
  96. ScriptProfiler::startForWorkerContext(m_workerContext, title);
  97. }
  98. virtual PassRefPtr<ScriptProfile> stopProfiling(const String& title)
  99. {
  100. return ScriptProfiler::stopForWorkerContext(m_workerContext, title);
  101. }
  102. WorkerContext* m_workerContext;
  103. };
  104. PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, WorkerContext* workerContext, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
  105. {
  106. return adoptPtr(new WorkerProfilerAgent(instrumentingAgents, consoleAgent, workerContext, inspectorState, injectedScriptManager));
  107. }
  108. #endif
  109. InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
  110. : InspectorBaseAgent<InspectorProfilerAgent>("Profiler", instrumentingAgents, inspectorState)
  111. , m_consoleAgent(consoleAgent)
  112. , m_injectedScriptManager(injectedScriptManager)
  113. , m_frontend(0)
  114. , m_enabled(false)
  115. , m_recordingCPUProfile(false)
  116. , m_currentUserInitiatedProfileNumber(-1)
  117. , m_nextUserInitiatedProfileNumber(1)
  118. , m_nextUserInitiatedHeapSnapshotNumber(1)
  119. , m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
  120. , m_previousTaskEndTime(0.0)
  121. {
  122. m_instrumentingAgents->setInspectorProfilerAgent(this);
  123. }
  124. InspectorProfilerAgent::~InspectorProfilerAgent()
  125. {
  126. m_instrumentingAgents->setInspectorProfilerAgent(0);
  127. }
  128. void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, unsigned columnNumber, const String& sourceURL)
  129. {
  130. RefPtr<ScriptProfile> profile = prpProfile;
  131. m_profiles.add(profile->uid(), profile);
  132. if (m_frontend && m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
  133. m_frontend->addProfileHeader(createProfileHeader(*profile));
  134. addProfileFinishedMessageToConsole(profile, lineNumber, columnNumber, sourceURL);
  135. }
  136. void InspectorProfilerAgent::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, unsigned columnNumber, const String& sourceURL)
  137. {
  138. if (!m_frontend)
  139. return;
  140. RefPtr<ScriptProfile> profile = prpProfile;
  141. String message = makeString(profile->title(), '#', String::number(profile->uid()));
  142. m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileEndMessageType, DebugMessageLevel, message, sourceURL, lineNumber, columnNumber);
  143. }
  144. void InspectorProfilerAgent::addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, unsigned columnNumber, const String& sourceURL)
  145. {
  146. if (!m_frontend)
  147. return;
  148. m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileMessageType, DebugMessageLevel, title, sourceURL, lineNumber, columnNumber);
  149. }
  150. void InspectorProfilerAgent::collectGarbage(WebCore::ErrorString*)
  151. {
  152. ScriptProfiler::collectGarbage();
  153. }
  154. PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createProfileHeader(const ScriptProfile& profile)
  155. {
  156. return TypeBuilder::Profiler::ProfileHeader::create()
  157. .setTypeId(TypeBuilder::Profiler::ProfileHeader::TypeId::CPU)
  158. .setUid(profile.uid())
  159. .setTitle(profile.title())
  160. .release();
  161. }
  162. PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createSnapshotHeader(const ScriptHeapSnapshot& snapshot)
  163. {
  164. RefPtr<TypeBuilder::Profiler::ProfileHeader> header = TypeBuilder::Profiler::ProfileHeader::create()
  165. .setTypeId(TypeBuilder::Profiler::ProfileHeader::TypeId::HEAP)
  166. .setUid(snapshot.uid())
  167. .setTitle(snapshot.title());
  168. header->setMaxJSObjectId(snapshot.maxSnapshotJSObjectId());
  169. return header.release();
  170. }
  171. void InspectorProfilerAgent::causesRecompilation(ErrorString*, bool* result)
  172. {
  173. *result = ScriptProfiler::causesRecompilation();
  174. }
  175. void InspectorProfilerAgent::isSampling(ErrorString*, bool* result)
  176. {
  177. *result = ScriptProfiler::isSampling();
  178. }
  179. void InspectorProfilerAgent::hasHeapProfiler(ErrorString*, bool* result)
  180. {
  181. *result = ScriptProfiler::hasHeapProfiler();
  182. }
  183. void InspectorProfilerAgent::enable(ErrorString*)
  184. {
  185. if (enabled())
  186. return;
  187. m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
  188. enable(false);
  189. }
  190. void InspectorProfilerAgent::disable(ErrorString*)
  191. {
  192. m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
  193. disable();
  194. }
  195. void InspectorProfilerAgent::disable()
  196. {
  197. if (!m_enabled)
  198. return;
  199. m_enabled = false;
  200. m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, false);
  201. recompileScript();
  202. }
  203. void InspectorProfilerAgent::enable(bool skipRecompile)
  204. {
  205. if (m_enabled)
  206. return;
  207. m_enabled = true;
  208. if (!skipRecompile)
  209. recompileScript();
  210. }
  211. String InspectorProfilerAgent::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
  212. {
  213. if (incrementProfileNumber)
  214. m_currentUserInitiatedProfileNumber = m_nextUserInitiatedProfileNumber++;
  215. return makeString(UserInitiatedProfileName, '.', String::number(m_currentUserInitiatedProfileNumber));
  216. }
  217. void InspectorProfilerAgent::getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader> >& headers)
  218. {
  219. m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, true);
  220. headers = TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader>::create();
  221. ProfilesMap::iterator profilesEnd = m_profiles.end();
  222. for (ProfilesMap::iterator it = m_profiles.begin(); it != profilesEnd; ++it)
  223. headers->addItem(createProfileHeader(*it->value));
  224. HeapSnapshotsMap::iterator snapshotsEnd = m_snapshots.end();
  225. for (HeapSnapshotsMap::iterator it = m_snapshots.begin(); it != snapshotsEnd; ++it)
  226. headers->addItem(createSnapshotHeader(*it->value));
  227. }
  228. namespace {
  229. class OutputStream : public ScriptHeapSnapshot::OutputStream {
  230. public:
  231. OutputStream(InspectorFrontend::Profiler* frontend, unsigned uid)
  232. : m_frontend(frontend), m_uid(uid) { }
  233. void Write(const String& chunk) { m_frontend->addHeapSnapshotChunk(m_uid, chunk); }
  234. void Close() { m_frontend->finishHeapSnapshot(m_uid); }
  235. private:
  236. InspectorFrontend::Profiler* m_frontend;
  237. int m_uid;
  238. };
  239. } // namespace
  240. void InspectorProfilerAgent::getCPUProfile(ErrorString* errorString, int rawUid, RefPtr<TypeBuilder::Profiler::CPUProfile>& profileObject)
  241. {
  242. unsigned uid = static_cast<unsigned>(rawUid);
  243. ProfilesMap::iterator it = m_profiles.find(uid);
  244. if (it == m_profiles.end()) {
  245. *errorString = "Profile wasn't found";
  246. return;
  247. }
  248. profileObject = TypeBuilder::Profiler::CPUProfile::create();
  249. profileObject->setHead(it->value->buildInspectorObjectForHead());
  250. profileObject->setIdleTime(it->value->idleTime());
  251. }
  252. void InspectorProfilerAgent::getHeapSnapshot(ErrorString* errorString, int rawUid)
  253. {
  254. unsigned uid = static_cast<unsigned>(rawUid);
  255. HeapSnapshotsMap::iterator it = m_snapshots.find(uid);
  256. if (it == m_snapshots.end()) {
  257. *errorString = "Profile wasn't found";
  258. return;
  259. }
  260. RefPtr<ScriptHeapSnapshot> snapshot = it->value;
  261. if (m_frontend) {
  262. OutputStream stream(m_frontend, uid);
  263. snapshot->writeJSON(&stream);
  264. }
  265. }
  266. void InspectorProfilerAgent::removeProfile(ErrorString*, const String& type, int rawUid)
  267. {
  268. unsigned uid = static_cast<unsigned>(rawUid);
  269. if (type == CPUProfileType) {
  270. if (m_profiles.contains(uid))
  271. m_profiles.remove(uid);
  272. } else if (type == HeapProfileType) {
  273. if (m_snapshots.contains(uid))
  274. m_snapshots.remove(uid);
  275. }
  276. }
  277. void InspectorProfilerAgent::resetState()
  278. {
  279. stop();
  280. m_profiles.clear();
  281. m_snapshots.clear();
  282. m_currentUserInitiatedProfileNumber = 1;
  283. m_nextUserInitiatedProfileNumber = 1;
  284. m_nextUserInitiatedHeapSnapshotNumber = 1;
  285. resetFrontendProfiles();
  286. m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
  287. }
  288. void InspectorProfilerAgent::resetFrontendProfiles()
  289. {
  290. if (!m_frontend)
  291. return;
  292. if (!m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
  293. return;
  294. if (m_profiles.isEmpty() && m_snapshots.isEmpty())
  295. m_frontend->resetProfiles();
  296. }
  297. void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
  298. {
  299. m_frontend = frontend->profiler();
  300. }
  301. void InspectorProfilerAgent::clearFrontend()
  302. {
  303. m_frontend = 0;
  304. stop();
  305. ErrorString error;
  306. disable(&error);
  307. }
  308. void InspectorProfilerAgent::restore()
  309. {
  310. // Need to restore enablement state here as in setFrontend m_state wasn't loaded yet.
  311. restoreEnablement();
  312. resetFrontendProfiles();
  313. if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling))
  314. start();
  315. }
  316. void InspectorProfilerAgent::restoreEnablement()
  317. {
  318. if (m_state->getBoolean(ProfilerAgentState::profilerEnabled)) {
  319. ErrorString error;
  320. enable(&error);
  321. }
  322. }
  323. void InspectorProfilerAgent::start(ErrorString*)
  324. {
  325. if (m_recordingCPUProfile)
  326. return;
  327. if (!enabled()) {
  328. enable(true);
  329. PageScriptDebugServer::shared().recompileAllJSFunctions(0);
  330. }
  331. m_recordingCPUProfile = true;
  332. String title = getCurrentUserInitiatedProfileName(true);
  333. startProfiling(title);
  334. addStartProfilingMessageToConsole(title, 0, 0, String());
  335. toggleRecordButton(true);
  336. m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
  337. }
  338. void InspectorProfilerAgent::stop(ErrorString*)
  339. {
  340. if (!m_recordingCPUProfile)
  341. return;
  342. m_recordingCPUProfile = false;
  343. String title = getCurrentUserInitiatedProfileName();
  344. RefPtr<ScriptProfile> profile = stopProfiling(title);
  345. if (profile)
  346. addProfile(profile, 0, 0, String());
  347. toggleRecordButton(false);
  348. m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
  349. }
  350. namespace {
  351. class HeapSnapshotProgress: public ScriptProfiler::HeapSnapshotProgress {
  352. public:
  353. explicit HeapSnapshotProgress(InspectorFrontend::Profiler* frontend)
  354. : m_frontend(frontend) { }
  355. void Start(int totalWork)
  356. {
  357. m_totalWork = totalWork;
  358. }
  359. void Worked(int workDone)
  360. {
  361. if (m_frontend)
  362. m_frontend->reportHeapSnapshotProgress(workDone, m_totalWork);
  363. }
  364. void Done() { }
  365. bool isCanceled() { return false; }
  366. private:
  367. InspectorFrontend::Profiler* m_frontend;
  368. int m_totalWork;
  369. };
  370. };
  371. void InspectorProfilerAgent::takeHeapSnapshot(ErrorString*, const bool* reportProgress)
  372. {
  373. String title = makeString(UserInitiatedProfileName, '.', String::number(m_nextUserInitiatedHeapSnapshotNumber));
  374. ++m_nextUserInitiatedHeapSnapshotNumber;
  375. HeapSnapshotProgress progress(reportProgress && *reportProgress ? m_frontend : 0);
  376. RefPtr<ScriptHeapSnapshot> snapshot = ScriptProfiler::takeHeapSnapshot(title, &progress);
  377. if (snapshot) {
  378. m_snapshots.add(snapshot->uid(), snapshot);
  379. if (m_frontend)
  380. m_frontend->addProfileHeader(createSnapshotHeader(*snapshot));
  381. }
  382. }
  383. void InspectorProfilerAgent::toggleRecordButton(bool isProfiling)
  384. {
  385. if (m_frontend)
  386. m_frontend->setRecordingProfile(isProfiling);
  387. }
  388. void InspectorProfilerAgent::getObjectByHeapObjectId(ErrorString* error, const String& heapSnapshotObjectId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result)
  389. {
  390. bool ok;
  391. unsigned id = heapSnapshotObjectId.toUInt(&ok);
  392. if (!ok) {
  393. *error = "Invalid heap snapshot object id";
  394. return;
  395. }
  396. ScriptObject heapObject = ScriptProfiler::objectByHeapObjectId(id);
  397. if (heapObject.hasNoValue()) {
  398. *error = "Object is not available";
  399. return;
  400. }
  401. InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(heapObject.scriptState());
  402. if (injectedScript.hasNoValue()) {
  403. *error = "Object is not available. Inspected context is gone";
  404. return;
  405. }
  406. result = injectedScript.wrapObject(heapObject, objectGroup ? *objectGroup : "");
  407. if (!result)
  408. *error = "Failed to wrap object";
  409. }
  410. void InspectorProfilerAgent::getHeapObjectId(ErrorString* errorString, const String& objectId, String* heapSnapshotObjectId)
  411. {
  412. InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(objectId);
  413. if (injectedScript.hasNoValue()) {
  414. *errorString = "Inspected context has gone";
  415. return;
  416. }
  417. ScriptValue value = injectedScript.findObjectById(objectId);
  418. if (value.hasNoValue() || value.isUndefined()) {
  419. *errorString = "Object with given id not found";
  420. return;
  421. }
  422. unsigned id = ScriptProfiler::getHeapObjectId(value);
  423. *heapSnapshotObjectId = String::number(id);
  424. }
  425. void InspectorProfilerAgent::willProcessTask()
  426. {
  427. if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
  428. return;
  429. if (!m_previousTaskEndTime)
  430. return;
  431. double idleTime = WTF::monotonicallyIncreasingTime() - m_previousTaskEndTime;
  432. m_previousTaskEndTime = 0.0;
  433. ProfileNameIdleTimeMap::iterator end = m_profileNameIdleTimeMap->end();
  434. for (ProfileNameIdleTimeMap::iterator it = m_profileNameIdleTimeMap->begin(); it != end; ++it)
  435. it->value += idleTime;
  436. }
  437. void InspectorProfilerAgent::didProcessTask()
  438. {
  439. if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
  440. return;
  441. m_previousTaskEndTime = WTF::monotonicallyIncreasingTime();
  442. }
  443. } // namespace WebCore
  444. #endif // ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)