trace_event_analyzer.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // Use trace_analyzer::Query and trace_analyzer::TraceAnalyzer to search for
  5. // specific trace events that were generated by the trace_event.h API.
  6. //
  7. // Basic procedure:
  8. // - Get trace events JSON string from base::trace_event::TraceLog.
  9. // - Create TraceAnalyzer with JSON string.
  10. // - Call TraceAnalyzer::AssociateBeginEndEvents (optional).
  11. // - Call TraceAnalyzer::AssociateEvents (zero or more times).
  12. // - Call TraceAnalyzer::FindEvents with queries to find specific events.
  13. //
  14. // A Query is a boolean expression tree that evaluates to true or false for a
  15. // given trace event. Queries can be combined into a tree using boolean,
  16. // arithmetic and comparison operators that refer to data of an individual trace
  17. // event.
  18. //
  19. // The events are returned as trace_analyzer::TraceEvent objects.
  20. // TraceEvent contains a single trace event's data, as well as a pointer to
  21. // a related trace event. The related trace event is typically the matching end
  22. // of a begin event or the matching begin of an end event.
  23. //
  24. // The following examples use this basic setup code to construct TraceAnalyzer
  25. // with the json trace string retrieved from TraceLog and construct an event
  26. // vector for retrieving events:
  27. //
  28. // TraceAnalyzer analyzer(json_events);
  29. // TraceEventVector events;
  30. //
  31. // EXAMPLE 1: Find events named "my_event".
  32. //
  33. // analyzer.FindEvents(Query(EVENT_NAME) == "my_event", &events);
  34. //
  35. // EXAMPLE 2: Find begin events named "my_event" with duration > 1 second.
  36. //
  37. // Query q = (Query(EVENT_NAME) == Query::String("my_event") &&
  38. // Query(EVENT_PHASE) == Query::Phase(TRACE_EVENT_PHASE_BEGIN) &&
  39. // Query(EVENT_DURATION) > Query::Double(1000000.0));
  40. // analyzer.FindEvents(q, &events);
  41. //
  42. // EXAMPLE 3: Associating event pairs across threads.
  43. //
  44. // If the test needs to analyze something that starts and ends on different
  45. // threads, the test needs to use INSTANT events. The typical procedure is to
  46. // specify the same unique ID as a TRACE_EVENT argument on both the start and
  47. // finish INSTANT events. Then use the following procedure to associate those
  48. // events.
  49. //
  50. // Step 1: instrument code with custom begin/end trace events.
  51. // [Thread 1 tracing code]
  52. // TRACE_EVENT_INSTANT1("test_latency", "timing1_begin", "id", 3);
  53. // [Thread 2 tracing code]
  54. // TRACE_EVENT_INSTANT1("test_latency", "timing1_end", "id", 3);
  55. //
  56. // Step 2: associate these custom begin/end pairs.
  57. // Query begin(Query(EVENT_NAME) == Query::String("timing1_begin"));
  58. // Query end(Query(EVENT_NAME) == Query::String("timing1_end"));
  59. // Query match(Query(EVENT_ARG, "id") == Query(OTHER_ARG, "id"));
  60. // analyzer.AssociateEvents(begin, end, match);
  61. //
  62. // Step 3: search for "timing1_begin" events with existing other event.
  63. // Query q = (Query(EVENT_NAME) == Query::String("timing1_begin") &&
  64. // Query(EVENT_HAS_OTHER));
  65. // analyzer.FindEvents(q, &events);
  66. //
  67. // Step 4: analyze events, such as checking durations.
  68. // for (size_t i = 0; i < events.size(); ++i) {
  69. // double duration;
  70. // EXPECT_TRUE(events[i].GetAbsTimeToOtherEvent(&duration));
  71. // EXPECT_LT(duration, 1000000.0/60.0); // expect less than 1/60 second.
  72. // }
  73. //
  74. // There are two helper functions, Start(category_filter_string) and Stop(), for
  75. // facilitating the collection of process-local traces and building a
  76. // TraceAnalyzer from them. A typical test, that uses the helper functions,
  77. // looks like the following:
  78. //
  79. // TEST_F(...) {
  80. // Start("*");
  81. // [Invoke the functions you want to test their traces]
  82. // auto analyzer = Stop();
  83. //
  84. // [Use the analyzer to verify produced traces, as explained above]
  85. // }
  86. //
  87. // Note: The Stop() function needs a SingleThreadTaskRunner.
  88. #ifndef BASE_TEST_TRACE_EVENT_ANALYZER_H_
  89. #define BASE_TEST_TRACE_EVENT_ANALYZER_H_
  90. #include <stddef.h>
  91. #include <stdint.h>
  92. #include <map>
  93. #include <memory>
  94. #include <string>
  95. #include <vector>
  96. #include "base/macros.h"
  97. #include "base/memory/ref_counted.h"
  98. #include "base/trace_event/base_tracing.h"
  99. namespace base {
  100. class Value;
  101. }
  102. namespace trace_analyzer {
  103. class QueryNode;
  104. // trace_analyzer::TraceEvent is a more convenient form of the
  105. // base::trace_event::TraceEvent class to make tracing-based tests easier to
  106. // write.
  107. struct TraceEvent {
  108. // ProcessThreadID contains a Process ID and Thread ID.
  109. struct ProcessThreadID {
  110. ProcessThreadID() : process_id(0), thread_id(0) {}
  111. ProcessThreadID(int process_id, int thread_id)
  112. : process_id(process_id), thread_id(thread_id) {}
  113. bool operator< (const ProcessThreadID& rhs) const {
  114. if (process_id != rhs.process_id)
  115. return process_id < rhs.process_id;
  116. return thread_id < rhs.thread_id;
  117. }
  118. int process_id;
  119. int thread_id;
  120. };
  121. TraceEvent();
  122. TraceEvent(TraceEvent&& other);
  123. ~TraceEvent();
  124. bool SetFromJSON(const base::Value* event_value) WARN_UNUSED_RESULT;
  125. bool operator< (const TraceEvent& rhs) const {
  126. return timestamp < rhs.timestamp;
  127. }
  128. TraceEvent& operator=(TraceEvent&& rhs);
  129. bool has_other_event() const { return other_event; }
  130. // Returns absolute duration in microseconds between this event and other
  131. // event. Must have already verified that other_event exists by
  132. // Query(EVENT_HAS_OTHER) or by calling has_other_event().
  133. double GetAbsTimeToOtherEvent() const;
  134. // Return the argument value if it exists and it is a string.
  135. bool GetArgAsString(const std::string& name, std::string* arg) const;
  136. // Return the argument value if it exists and it is a number.
  137. bool GetArgAsNumber(const std::string& name, double* arg) const;
  138. // Return the argument value if it exists.
  139. bool GetArgAsValue(const std::string& name,
  140. std::unique_ptr<base::Value>* arg) const;
  141. // Check if argument exists and is string.
  142. bool HasStringArg(const std::string& name) const;
  143. // Check if argument exists and is number (double, int or bool).
  144. bool HasNumberArg(const std::string& name) const;
  145. // Check if argument exists.
  146. bool HasArg(const std::string& name) const;
  147. // Get known existing arguments as specific types.
  148. // Useful when you have already queried the argument with
  149. // Query(HAS_NUMBER_ARG) or Query(HAS_STRING_ARG).
  150. std::string GetKnownArgAsString(const std::string& name) const;
  151. double GetKnownArgAsDouble(const std::string& name) const;
  152. int GetKnownArgAsInt(const std::string& name) const;
  153. bool GetKnownArgAsBool(const std::string& name) const;
  154. std::unique_ptr<base::Value> GetKnownArgAsValue(
  155. const std::string& name) const;
  156. // Process ID and Thread ID.
  157. ProcessThreadID thread;
  158. // Time since epoch in microseconds.
  159. // Stored as double to match its JSON representation.
  160. double timestamp;
  161. double duration;
  162. char phase;
  163. std::string category;
  164. std::string name;
  165. std::string id;
  166. double thread_duration = 0.0;
  167. double thread_timestamp = 0.0;
  168. std::string scope;
  169. std::string bind_id;
  170. bool flow_out = false;
  171. bool flow_in = false;
  172. std::string global_id2;
  173. std::string local_id2;
  174. // All numbers and bool values from TraceEvent args are cast to double.
  175. // bool becomes 1.0 (true) or 0.0 (false).
  176. std::map<std::string, double> arg_numbers;
  177. std::map<std::string, std::string> arg_strings;
  178. std::map<std::string, std::unique_ptr<base::Value>> arg_values;
  179. // The other event associated with this event (or NULL).
  180. const TraceEvent* other_event;
  181. // A back-link for |other_event|. That is, if other_event is not null, then
  182. // |event->other_event->prev_event == event| is always true.
  183. const TraceEvent* prev_event;
  184. };
  185. typedef std::vector<const TraceEvent*> TraceEventVector;
  186. class Query {
  187. public:
  188. Query(const Query& query);
  189. ~Query();
  190. ////////////////////////////////////////////////////////////////
  191. // Query literal values
  192. // Compare with the given string.
  193. static Query String(const std::string& str);
  194. // Compare with the given number.
  195. static Query Double(double num);
  196. static Query Int(int32_t num);
  197. static Query Uint(uint32_t num);
  198. // Compare with the given bool.
  199. static Query Bool(bool boolean);
  200. // Compare with the given phase.
  201. static Query Phase(char phase);
  202. // Compare with the given string pattern. Only works with == and != operators.
  203. // Example: Query(EVENT_NAME) == Query::Pattern("MyEvent*")
  204. static Query Pattern(const std::string& pattern);
  205. ////////////////////////////////////////////////////////////////
  206. // Query event members
  207. static Query EventPid() { return Query(EVENT_PID); }
  208. static Query EventTid() { return Query(EVENT_TID); }
  209. // Return the timestamp of the event in microseconds since epoch.
  210. static Query EventTime() { return Query(EVENT_TIME); }
  211. // Return the absolute time between event and other event in microseconds.
  212. // Only works if Query::EventHasOther() == true.
  213. static Query EventDuration() { return Query(EVENT_DURATION); }
  214. // Return the duration of a COMPLETE event.
  215. static Query EventCompleteDuration() {
  216. return Query(EVENT_COMPLETE_DURATION);
  217. }
  218. static Query EventPhase() { return Query(EVENT_PHASE); }
  219. static Query EventCategory() { return Query(EVENT_CATEGORY); }
  220. static Query EventName() { return Query(EVENT_NAME); }
  221. static Query EventId() { return Query(EVENT_ID); }
  222. static Query EventPidIs(int process_id) {
  223. return Query(EVENT_PID) == Query::Int(process_id);
  224. }
  225. static Query EventTidIs(int thread_id) {
  226. return Query(EVENT_TID) == Query::Int(thread_id);
  227. }
  228. static Query EventThreadIs(const TraceEvent::ProcessThreadID& thread) {
  229. return EventPidIs(thread.process_id) && EventTidIs(thread.thread_id);
  230. }
  231. static Query EventTimeIs(double timestamp) {
  232. return Query(EVENT_TIME) == Query::Double(timestamp);
  233. }
  234. static Query EventDurationIs(double duration) {
  235. return Query(EVENT_DURATION) == Query::Double(duration);
  236. }
  237. static Query EventPhaseIs(char phase) {
  238. return Query(EVENT_PHASE) == Query::Phase(phase);
  239. }
  240. static Query EventCategoryIs(const std::string& category) {
  241. return Query(EVENT_CATEGORY) == Query::String(category);
  242. }
  243. static Query EventNameIs(const std::string& name) {
  244. return Query(EVENT_NAME) == Query::String(name);
  245. }
  246. static Query EventIdIs(const std::string& id) {
  247. return Query(EVENT_ID) == Query::String(id);
  248. }
  249. // Evaluates to true if arg exists and is a string.
  250. static Query EventHasStringArg(const std::string& arg_name) {
  251. return Query(EVENT_HAS_STRING_ARG, arg_name);
  252. }
  253. // Evaluates to true if arg exists and is a number.
  254. // Number arguments include types double, int and bool.
  255. static Query EventHasNumberArg(const std::string& arg_name) {
  256. return Query(EVENT_HAS_NUMBER_ARG, arg_name);
  257. }
  258. // Evaluates to arg value (string or number).
  259. static Query EventArg(const std::string& arg_name) {
  260. return Query(EVENT_ARG, arg_name);
  261. }
  262. // Return true if associated event exists.
  263. static Query EventHasOther() { return Query(EVENT_HAS_OTHER); }
  264. // Access the associated other_event's members:
  265. static Query OtherPid() { return Query(OTHER_PID); }
  266. static Query OtherTid() { return Query(OTHER_TID); }
  267. static Query OtherTime() { return Query(OTHER_TIME); }
  268. static Query OtherPhase() { return Query(OTHER_PHASE); }
  269. static Query OtherCategory() { return Query(OTHER_CATEGORY); }
  270. static Query OtherName() { return Query(OTHER_NAME); }
  271. static Query OtherId() { return Query(OTHER_ID); }
  272. static Query OtherPidIs(int process_id) {
  273. return Query(OTHER_PID) == Query::Int(process_id);
  274. }
  275. static Query OtherTidIs(int thread_id) {
  276. return Query(OTHER_TID) == Query::Int(thread_id);
  277. }
  278. static Query OtherThreadIs(const TraceEvent::ProcessThreadID& thread) {
  279. return OtherPidIs(thread.process_id) && OtherTidIs(thread.thread_id);
  280. }
  281. static Query OtherTimeIs(double timestamp) {
  282. return Query(OTHER_TIME) == Query::Double(timestamp);
  283. }
  284. static Query OtherPhaseIs(char phase) {
  285. return Query(OTHER_PHASE) == Query::Phase(phase);
  286. }
  287. static Query OtherCategoryIs(const std::string& category) {
  288. return Query(OTHER_CATEGORY) == Query::String(category);
  289. }
  290. static Query OtherNameIs(const std::string& name) {
  291. return Query(OTHER_NAME) == Query::String(name);
  292. }
  293. static Query OtherIdIs(const std::string& id) {
  294. return Query(OTHER_ID) == Query::String(id);
  295. }
  296. // Evaluates to true if arg exists and is a string.
  297. static Query OtherHasStringArg(const std::string& arg_name) {
  298. return Query(OTHER_HAS_STRING_ARG, arg_name);
  299. }
  300. // Evaluates to true if arg exists and is a number.
  301. // Number arguments include types double, int and bool.
  302. static Query OtherHasNumberArg(const std::string& arg_name) {
  303. return Query(OTHER_HAS_NUMBER_ARG, arg_name);
  304. }
  305. // Evaluates to arg value (string or number).
  306. static Query OtherArg(const std::string& arg_name) {
  307. return Query(OTHER_ARG, arg_name);
  308. }
  309. // Access the associated prev_event's members:
  310. static Query PrevPid() { return Query(PREV_PID); }
  311. static Query PrevTid() { return Query(PREV_TID); }
  312. static Query PrevTime() { return Query(PREV_TIME); }
  313. static Query PrevPhase() { return Query(PREV_PHASE); }
  314. static Query PrevCategory() { return Query(PREV_CATEGORY); }
  315. static Query PrevName() { return Query(PREV_NAME); }
  316. static Query PrevId() { return Query(PREV_ID); }
  317. static Query PrevPidIs(int process_id) {
  318. return Query(PREV_PID) == Query::Int(process_id);
  319. }
  320. static Query PrevTidIs(int thread_id) {
  321. return Query(PREV_TID) == Query::Int(thread_id);
  322. }
  323. static Query PrevThreadIs(const TraceEvent::ProcessThreadID& thread) {
  324. return PrevPidIs(thread.process_id) && PrevTidIs(thread.thread_id);
  325. }
  326. static Query PrevTimeIs(double timestamp) {
  327. return Query(PREV_TIME) == Query::Double(timestamp);
  328. }
  329. static Query PrevPhaseIs(char phase) {
  330. return Query(PREV_PHASE) == Query::Phase(phase);
  331. }
  332. static Query PrevCategoryIs(const std::string& category) {
  333. return Query(PREV_CATEGORY) == Query::String(category);
  334. }
  335. static Query PrevNameIs(const std::string& name) {
  336. return Query(PREV_NAME) == Query::String(name);
  337. }
  338. static Query PrevIdIs(const std::string& id) {
  339. return Query(PREV_ID) == Query::String(id);
  340. }
  341. // Evaluates to true if arg exists and is a string.
  342. static Query PrevHasStringArg(const std::string& arg_name) {
  343. return Query(PREV_HAS_STRING_ARG, arg_name);
  344. }
  345. // Evaluates to true if arg exists and is a number.
  346. // Number arguments include types double, int and bool.
  347. static Query PrevHasNumberArg(const std::string& arg_name) {
  348. return Query(PREV_HAS_NUMBER_ARG, arg_name);
  349. }
  350. // Evaluates to arg value (string or number).
  351. static Query PrevArg(const std::string& arg_name) {
  352. return Query(PREV_ARG, arg_name);
  353. }
  354. ////////////////////////////////////////////////////////////////
  355. // Common queries:
  356. // Find BEGIN events that have a corresponding END event.
  357. static Query MatchBeginWithEnd() {
  358. return (Query(EVENT_PHASE) == Query::Phase(TRACE_EVENT_PHASE_BEGIN)) &&
  359. Query(EVENT_HAS_OTHER);
  360. }
  361. // Find COMPLETE events.
  362. static Query MatchComplete() {
  363. return (Query(EVENT_PHASE) == Query::Phase(TRACE_EVENT_PHASE_COMPLETE));
  364. }
  365. // Find ASYNC_BEGIN events that have a corresponding ASYNC_END event.
  366. static Query MatchAsyncBeginWithNext() {
  367. return (Query(EVENT_PHASE) ==
  368. Query::Phase(TRACE_EVENT_PHASE_ASYNC_BEGIN)) &&
  369. Query(EVENT_HAS_OTHER);
  370. }
  371. // Find BEGIN events of given |name| which also have associated END events.
  372. static Query MatchBeginName(const std::string& name) {
  373. return (Query(EVENT_NAME) == Query(name)) && MatchBeginWithEnd();
  374. }
  375. // Find COMPLETE events of given |name|.
  376. static Query MatchCompleteName(const std::string& name) {
  377. return (Query(EVENT_NAME) == Query(name)) && MatchComplete();
  378. }
  379. // Match given Process ID and Thread ID.
  380. static Query MatchThread(const TraceEvent::ProcessThreadID& thread) {
  381. return (Query(EVENT_PID) == Query::Int(thread.process_id)) &&
  382. (Query(EVENT_TID) == Query::Int(thread.thread_id));
  383. }
  384. // Match event pair that spans multiple threads.
  385. static Query MatchCrossThread() {
  386. return (Query(EVENT_PID) != Query(OTHER_PID)) ||
  387. (Query(EVENT_TID) != Query(OTHER_TID));
  388. }
  389. ////////////////////////////////////////////////////////////////
  390. // Operators:
  391. // Boolean operators:
  392. Query operator==(const Query& rhs) const;
  393. Query operator!=(const Query& rhs) const;
  394. Query operator< (const Query& rhs) const;
  395. Query operator<=(const Query& rhs) const;
  396. Query operator> (const Query& rhs) const;
  397. Query operator>=(const Query& rhs) const;
  398. Query operator&&(const Query& rhs) const;
  399. Query operator||(const Query& rhs) const;
  400. Query operator!() const;
  401. // Arithmetic operators:
  402. // Following operators are applied to double arguments:
  403. Query operator+(const Query& rhs) const;
  404. Query operator-(const Query& rhs) const;
  405. Query operator*(const Query& rhs) const;
  406. Query operator/(const Query& rhs) const;
  407. Query operator-() const;
  408. // Mod operates on int64_t args (doubles are casted to int64_t beforehand):
  409. Query operator%(const Query& rhs) const;
  410. // Return true if the given event matches this query tree.
  411. // This is a recursive method that walks the query tree.
  412. bool Evaluate(const TraceEvent& event) const;
  413. enum TraceEventMember {
  414. EVENT_INVALID,
  415. EVENT_PID,
  416. EVENT_TID,
  417. EVENT_TIME,
  418. EVENT_DURATION,
  419. EVENT_COMPLETE_DURATION,
  420. EVENT_PHASE,
  421. EVENT_CATEGORY,
  422. EVENT_NAME,
  423. EVENT_ID,
  424. EVENT_HAS_STRING_ARG,
  425. EVENT_HAS_NUMBER_ARG,
  426. EVENT_ARG,
  427. EVENT_HAS_OTHER,
  428. EVENT_HAS_PREV,
  429. OTHER_PID,
  430. OTHER_TID,
  431. OTHER_TIME,
  432. OTHER_PHASE,
  433. OTHER_CATEGORY,
  434. OTHER_NAME,
  435. OTHER_ID,
  436. OTHER_HAS_STRING_ARG,
  437. OTHER_HAS_NUMBER_ARG,
  438. OTHER_ARG,
  439. PREV_PID,
  440. PREV_TID,
  441. PREV_TIME,
  442. PREV_PHASE,
  443. PREV_CATEGORY,
  444. PREV_NAME,
  445. PREV_ID,
  446. PREV_HAS_STRING_ARG,
  447. PREV_HAS_NUMBER_ARG,
  448. PREV_ARG,
  449. OTHER_FIRST_MEMBER = OTHER_PID,
  450. OTHER_LAST_MEMBER = OTHER_ARG,
  451. PREV_FIRST_MEMBER = PREV_PID,
  452. PREV_LAST_MEMBER = PREV_ARG,
  453. };
  454. enum Operator {
  455. OP_INVALID,
  456. // Boolean operators:
  457. OP_EQ,
  458. OP_NE,
  459. OP_LT,
  460. OP_LE,
  461. OP_GT,
  462. OP_GE,
  463. OP_AND,
  464. OP_OR,
  465. OP_NOT,
  466. // Arithmetic operators:
  467. OP_ADD,
  468. OP_SUB,
  469. OP_MUL,
  470. OP_DIV,
  471. OP_MOD,
  472. OP_NEGATE
  473. };
  474. enum QueryType {
  475. QUERY_BOOLEAN_OPERATOR,
  476. QUERY_ARITHMETIC_OPERATOR,
  477. QUERY_EVENT_MEMBER,
  478. QUERY_NUMBER,
  479. QUERY_STRING
  480. };
  481. // Compare with the given member.
  482. explicit Query(TraceEventMember member);
  483. // Compare with the given member argument value.
  484. Query(TraceEventMember member, const std::string& arg_name);
  485. // Compare with the given string.
  486. explicit Query(const std::string& str);
  487. // Compare with the given number.
  488. explicit Query(double num);
  489. // Construct a boolean Query that returns (left <binary_op> right).
  490. Query(const Query& left, const Query& right, Operator binary_op);
  491. // Construct a boolean Query that returns (<binary_op> left).
  492. Query(const Query& left, Operator unary_op);
  493. // Try to compare left_ against right_ based on operator_.
  494. // If either left or right does not convert to double, false is returned.
  495. // Otherwise, true is returned and |result| is set to the comparison result.
  496. bool CompareAsDouble(const TraceEvent& event, bool* result) const;
  497. // Try to compare left_ against right_ based on operator_.
  498. // If either left or right does not convert to string, false is returned.
  499. // Otherwise, true is returned and |result| is set to the comparison result.
  500. bool CompareAsString(const TraceEvent& event, bool* result) const;
  501. // Attempt to convert this Query to a double. On success, true is returned
  502. // and the double value is stored in |num|.
  503. bool GetAsDouble(const TraceEvent& event, double* num) const;
  504. // Attempt to convert this Query to a string. On success, true is returned
  505. // and the string value is stored in |str|.
  506. bool GetAsString(const TraceEvent& event, std::string* str) const;
  507. // Evaluate this Query as an arithmetic operator on left_ and right_.
  508. bool EvaluateArithmeticOperator(const TraceEvent& event,
  509. double* num) const;
  510. // For QUERY_EVENT_MEMBER Query: attempt to get the double value of the Query.
  511. bool GetMemberValueAsDouble(const TraceEvent& event, double* num) const;
  512. // For QUERY_EVENT_MEMBER Query: attempt to get the string value of the Query.
  513. bool GetMemberValueAsString(const TraceEvent& event, std::string* num) const;
  514. // Does this Query represent a value?
  515. bool is_value() const { return type_ != QUERY_BOOLEAN_OPERATOR; }
  516. bool is_unary_operator() const {
  517. return operator_ == OP_NOT || operator_ == OP_NEGATE;
  518. }
  519. bool is_comparison_operator() const {
  520. return operator_ != OP_INVALID && operator_ < OP_AND;
  521. }
  522. static const TraceEvent* SelectTargetEvent(const TraceEvent* ev,
  523. TraceEventMember member);
  524. const Query& left() const;
  525. const Query& right() const;
  526. private:
  527. QueryType type_;
  528. Operator operator_;
  529. scoped_refptr<QueryNode> left_;
  530. scoped_refptr<QueryNode> right_;
  531. TraceEventMember member_;
  532. double number_;
  533. std::string string_;
  534. bool is_pattern_;
  535. };
  536. // Implementation detail:
  537. // QueryNode allows Query to store a ref-counted query tree.
  538. class QueryNode : public base::RefCounted<QueryNode> {
  539. public:
  540. explicit QueryNode(const Query& query);
  541. const Query& query() const { return query_; }
  542. private:
  543. friend class base::RefCounted<QueryNode>;
  544. ~QueryNode();
  545. Query query_;
  546. };
  547. // TraceAnalyzer helps tests search for trace events.
  548. class TraceAnalyzer {
  549. public:
  550. ~TraceAnalyzer();
  551. // Use trace events from JSON string generated by tracing API.
  552. // Returns non-NULL if the JSON is successfully parsed.
  553. static TraceAnalyzer* Create(const std::string& json_events)
  554. WARN_UNUSED_RESULT;
  555. void SetIgnoreMetadataEvents(bool ignore) {
  556. ignore_metadata_events_ = ignore;
  557. }
  558. // Associate BEGIN and END events with each other. This allows Query(OTHER_*)
  559. // to access the associated event and enables Query(EVENT_DURATION).
  560. // An end event will match the most recent begin event with the same name,
  561. // category, process ID and thread ID. This matches what is shown in
  562. // about:tracing. After association, the BEGIN event will point to the
  563. // matching END event, but the END event will not point to the BEGIN event.
  564. void AssociateBeginEndEvents();
  565. // Associate ASYNC_BEGIN, ASYNC_STEP and ASYNC_END events with each other.
  566. // An ASYNC_END event will match the most recent ASYNC_BEGIN or ASYNC_STEP
  567. // event with the same name, category, and ID. This creates a singly linked
  568. // list of ASYNC_BEGIN->ASYNC_STEP...->ASYNC_END.
  569. // |match_pid| - If true, will only match async events which are running
  570. // under the same process ID, otherwise will allow linking
  571. // async events from different processes.
  572. void AssociateAsyncBeginEndEvents(bool match_pid = true);
  573. // AssociateEvents can be used to customize event associations by setting the
  574. // other_event member of TraceEvent. This should be used to associate two
  575. // INSTANT events.
  576. //
  577. // The assumptions are:
  578. // - |first| events occur before |second| events.
  579. // - the closest matching |second| event is the correct match.
  580. //
  581. // |first| - Eligible |first| events match this query.
  582. // |second| - Eligible |second| events match this query.
  583. // |match| - This query is run on the |first| event. The OTHER_* EventMember
  584. // queries will point to an eligible |second| event. The query
  585. // should evaluate to true if the |first|/|second| pair is a match.
  586. //
  587. // When a match is found, the pair will be associated by having the first
  588. // event's other_event member point to the other. AssociateEvents does not
  589. // clear previous associations, so it is possible to associate multiple pairs
  590. // of events by calling AssociateEvents more than once with different queries.
  591. //
  592. // NOTE: AssociateEvents will overwrite existing other_event associations if
  593. // the queries pass for events that already had a previous association.
  594. //
  595. // After calling any Find* method, it is not allowed to call AssociateEvents
  596. // again.
  597. void AssociateEvents(const Query& first,
  598. const Query& second,
  599. const Query& match);
  600. // For each event, copy its arguments to the other_event argument map. If
  601. // argument name already exists, it will not be overwritten.
  602. void MergeAssociatedEventArgs();
  603. // Find all events that match query and replace output vector.
  604. size_t FindEvents(const Query& query, TraceEventVector* output);
  605. // Find first event that matches query or NULL if not found.
  606. const TraceEvent* FindFirstOf(const Query& query);
  607. // Find last event that matches query or NULL if not found.
  608. const TraceEvent* FindLastOf(const Query& query);
  609. const std::string& GetThreadName(const TraceEvent::ProcessThreadID& thread);
  610. private:
  611. TraceAnalyzer();
  612. bool SetEvents(const std::string& json_events) WARN_UNUSED_RESULT;
  613. // Read metadata (thread names, etc) from events.
  614. void ParseMetadata();
  615. std::map<TraceEvent::ProcessThreadID, std::string> thread_names_;
  616. std::vector<TraceEvent> raw_events_;
  617. bool ignore_metadata_events_;
  618. bool allow_association_changes_;
  619. DISALLOW_COPY_AND_ASSIGN(TraceAnalyzer);
  620. };
  621. // Utility functions for collecting process-local traces and creating a
  622. // |TraceAnalyzer| from the result. Please see comments in trace_config.h to
  623. // understand how the |category_filter_string| works. Use "*" to enable all
  624. // default categories.
  625. void Start(const std::string& category_filter_string);
  626. std::unique_ptr<TraceAnalyzer> Stop();
  627. // Utility functions for TraceEventVector.
  628. struct RateStats {
  629. double min_us;
  630. double max_us;
  631. double mean_us;
  632. double standard_deviation_us;
  633. };
  634. struct RateStatsOptions {
  635. RateStatsOptions() : trim_min(0u), trim_max(0u) {}
  636. // After the times between events are sorted, the number of specified elements
  637. // will be trimmed before calculating the RateStats. This is useful in cases
  638. // where extreme outliers are tolerable and should not skew the overall
  639. // average.
  640. size_t trim_min; // Trim this many minimum times.
  641. size_t trim_max; // Trim this many maximum times.
  642. };
  643. // Calculate min/max/mean and standard deviation from the times between
  644. // adjacent events.
  645. bool GetRateStats(const TraceEventVector& events,
  646. RateStats* stats,
  647. const RateStatsOptions* options);
  648. // Starting from |position|, find the first event that matches |query|.
  649. // Returns true if found, false otherwise.
  650. bool FindFirstOf(const TraceEventVector& events,
  651. const Query& query,
  652. size_t position,
  653. size_t* return_index);
  654. // Starting from |position|, find the last event that matches |query|.
  655. // Returns true if found, false otherwise.
  656. bool FindLastOf(const TraceEventVector& events,
  657. const Query& query,
  658. size_t position,
  659. size_t* return_index);
  660. // Find the closest events to |position| in time that match |query|.
  661. // return_second_closest may be NULL. Closeness is determined by comparing
  662. // with the event timestamp.
  663. // Returns true if found, false otherwise. If both return parameters are
  664. // requested, both must be found for a successful result.
  665. bool FindClosest(const TraceEventVector& events,
  666. const Query& query,
  667. size_t position,
  668. size_t* return_closest,
  669. size_t* return_second_closest);
  670. // Count matches, inclusive of |begin_position|, exclusive of |end_position|.
  671. size_t CountMatches(const TraceEventVector& events,
  672. const Query& query,
  673. size_t begin_position,
  674. size_t end_position);
  675. // Count all matches.
  676. static inline size_t CountMatches(const TraceEventVector& events,
  677. const Query& query) {
  678. return CountMatches(events, query, 0u, events.size());
  679. }
  680. } // namespace trace_analyzer
  681. #endif // BASE_TEST_TRACE_EVENT_ANALYZER_H_