trace_event_analyzer.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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/memory/raw_ptr.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. [[nodiscard]] bool SetFromJSON(const base::Value* event_value);
  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& arg_name, std::string* arg) const;
  136. // Return the argument value if it exists and it is a number.
  137. bool GetArgAsNumber(const std::string& arg_name, double* arg) const;
  138. // Return the argument value if it exists and is a dictionary.
  139. bool GetArgAsDict(const std::string& arg_name, base::Value::Dict* arg) const;
  140. // Check if argument exists and is string.
  141. bool HasStringArg(const std::string& arg_name) const;
  142. // Check if argument exists and is number (double, int or bool).
  143. bool HasNumberArg(const std::string& arg_name) const;
  144. // Check if argument exists and is a dictionary.
  145. bool HasDictArg(const std::string& arg_name) const;
  146. // Get known existing arguments as specific types.
  147. // Useful when you have already queried the argument with
  148. // Query(HAS_NUMBER_ARG) or Query(HAS_STRING_ARG).
  149. std::string GetKnownArgAsString(const std::string& arg_name) const;
  150. double GetKnownArgAsDouble(const std::string& arg_name) const;
  151. int GetKnownArgAsInt(const std::string& arg_name) const;
  152. bool GetKnownArgAsBool(const std::string& arg_name) const;
  153. base::Value::Dict GetKnownArgAsDict(const std::string& arg_name) const;
  154. // Process ID and Thread ID.
  155. ProcessThreadID thread;
  156. // Time since epoch in microseconds.
  157. // Stored as double to match its JSON representation.
  158. double timestamp = 0.0;
  159. double duration = 0.0;
  160. char phase = TRACE_EVENT_PHASE_BEGIN;
  161. std::string category;
  162. std::string name;
  163. std::string id;
  164. double thread_duration = 0.0;
  165. double thread_timestamp = 0.0;
  166. std::string scope;
  167. std::string bind_id;
  168. bool flow_out = false;
  169. bool flow_in = false;
  170. std::string global_id2;
  171. std::string local_id2;
  172. // All numbers and bool values from TraceEvent args are cast to double.
  173. // bool becomes 1.0 (true) or 0.0 (false).
  174. std::map<std::string, double> arg_numbers;
  175. std::map<std::string, std::string> arg_strings;
  176. std::map<std::string, base::Value::Dict> arg_dicts;
  177. // The other event associated with this event (or NULL).
  178. raw_ptr<const TraceEvent> other_event = nullptr;
  179. // A back-link for |other_event|. That is, if other_event is not null, then
  180. // |event->other_event->prev_event == event| is always true.
  181. raw_ptr<const TraceEvent> prev_event;
  182. };
  183. typedef std::vector<const TraceEvent*> TraceEventVector;
  184. class Query {
  185. public:
  186. Query(const Query& query);
  187. ~Query();
  188. ////////////////////////////////////////////////////////////////
  189. // Query literal values
  190. // Compare with the given string.
  191. static Query String(const std::string& str);
  192. // Compare with the given number.
  193. static Query Double(double num);
  194. static Query Int(int32_t num);
  195. static Query Uint(uint32_t num);
  196. // Compare with the given bool.
  197. static Query Bool(bool boolean);
  198. // Compare with the given phase.
  199. static Query Phase(char phase);
  200. // Compare with the given string pattern. Only works with == and != operators.
  201. // Example: Query(EVENT_NAME) == Query::Pattern("MyEvent*")
  202. static Query Pattern(const std::string& pattern);
  203. ////////////////////////////////////////////////////////////////
  204. // Query event members
  205. static Query EventPid() { return Query(EVENT_PID); }
  206. static Query EventTid() { return Query(EVENT_TID); }
  207. // Return the timestamp of the event in microseconds since epoch.
  208. static Query EventTime() { return Query(EVENT_TIME); }
  209. // Return the absolute time between event and other event in microseconds.
  210. // Only works if Query::EventHasOther() == true.
  211. static Query EventDuration() { return Query(EVENT_DURATION); }
  212. // Return the duration of a COMPLETE event.
  213. static Query EventCompleteDuration() {
  214. return Query(EVENT_COMPLETE_DURATION);
  215. }
  216. static Query EventPhase() { return Query(EVENT_PHASE); }
  217. static Query EventCategory() { return Query(EVENT_CATEGORY); }
  218. static Query EventName() { return Query(EVENT_NAME); }
  219. static Query EventId() { return Query(EVENT_ID); }
  220. static Query EventPidIs(int process_id) {
  221. return Query(EVENT_PID) == Query::Int(process_id);
  222. }
  223. static Query EventTidIs(int thread_id) {
  224. return Query(EVENT_TID) == Query::Int(thread_id);
  225. }
  226. static Query EventThreadIs(const TraceEvent::ProcessThreadID& thread) {
  227. return EventPidIs(thread.process_id) && EventTidIs(thread.thread_id);
  228. }
  229. static Query EventTimeIs(double timestamp) {
  230. return Query(EVENT_TIME) == Query::Double(timestamp);
  231. }
  232. static Query EventDurationIs(double duration) {
  233. return Query(EVENT_DURATION) == Query::Double(duration);
  234. }
  235. static Query EventPhaseIs(char phase) {
  236. return Query(EVENT_PHASE) == Query::Phase(phase);
  237. }
  238. static Query EventCategoryIs(const std::string& category) {
  239. return Query(EVENT_CATEGORY) == Query::String(category);
  240. }
  241. static Query EventNameIs(const std::string& name) {
  242. return Query(EVENT_NAME) == Query::String(name);
  243. }
  244. static Query EventIdIs(const std::string& id) {
  245. return Query(EVENT_ID) == Query::String(id);
  246. }
  247. // Evaluates to true if arg exists and is a string.
  248. static Query EventHasStringArg(const std::string& arg_name) {
  249. return Query(EVENT_HAS_STRING_ARG, arg_name);
  250. }
  251. // Evaluates to true if arg exists and is a number.
  252. // Number arguments include types double, int and bool.
  253. static Query EventHasNumberArg(const std::string& arg_name) {
  254. return Query(EVENT_HAS_NUMBER_ARG, arg_name);
  255. }
  256. // Evaluates to arg value (string or number).
  257. static Query EventArg(const std::string& arg_name) {
  258. return Query(EVENT_ARG, arg_name);
  259. }
  260. // Return true if associated event exists.
  261. static Query EventHasOther() { return Query(EVENT_HAS_OTHER); }
  262. // Access the associated other_event's members:
  263. static Query OtherPid() { return Query(OTHER_PID); }
  264. static Query OtherTid() { return Query(OTHER_TID); }
  265. static Query OtherTime() { return Query(OTHER_TIME); }
  266. static Query OtherPhase() { return Query(OTHER_PHASE); }
  267. static Query OtherCategory() { return Query(OTHER_CATEGORY); }
  268. static Query OtherName() { return Query(OTHER_NAME); }
  269. static Query OtherId() { return Query(OTHER_ID); }
  270. static Query OtherPidIs(int process_id) {
  271. return Query(OTHER_PID) == Query::Int(process_id);
  272. }
  273. static Query OtherTidIs(int thread_id) {
  274. return Query(OTHER_TID) == Query::Int(thread_id);
  275. }
  276. static Query OtherThreadIs(const TraceEvent::ProcessThreadID& thread) {
  277. return OtherPidIs(thread.process_id) && OtherTidIs(thread.thread_id);
  278. }
  279. static Query OtherTimeIs(double timestamp) {
  280. return Query(OTHER_TIME) == Query::Double(timestamp);
  281. }
  282. static Query OtherPhaseIs(char phase) {
  283. return Query(OTHER_PHASE) == Query::Phase(phase);
  284. }
  285. static Query OtherCategoryIs(const std::string& category) {
  286. return Query(OTHER_CATEGORY) == Query::String(category);
  287. }
  288. static Query OtherNameIs(const std::string& name) {
  289. return Query(OTHER_NAME) == Query::String(name);
  290. }
  291. static Query OtherIdIs(const std::string& id) {
  292. return Query(OTHER_ID) == Query::String(id);
  293. }
  294. // Evaluates to true if arg exists and is a string.
  295. static Query OtherHasStringArg(const std::string& arg_name) {
  296. return Query(OTHER_HAS_STRING_ARG, arg_name);
  297. }
  298. // Evaluates to true if arg exists and is a number.
  299. // Number arguments include types double, int and bool.
  300. static Query OtherHasNumberArg(const std::string& arg_name) {
  301. return Query(OTHER_HAS_NUMBER_ARG, arg_name);
  302. }
  303. // Evaluates to arg value (string or number).
  304. static Query OtherArg(const std::string& arg_name) {
  305. return Query(OTHER_ARG, arg_name);
  306. }
  307. // Access the associated prev_event's members:
  308. static Query PrevPid() { return Query(PREV_PID); }
  309. static Query PrevTid() { return Query(PREV_TID); }
  310. static Query PrevTime() { return Query(PREV_TIME); }
  311. static Query PrevPhase() { return Query(PREV_PHASE); }
  312. static Query PrevCategory() { return Query(PREV_CATEGORY); }
  313. static Query PrevName() { return Query(PREV_NAME); }
  314. static Query PrevId() { return Query(PREV_ID); }
  315. static Query PrevPidIs(int process_id) {
  316. return Query(PREV_PID) == Query::Int(process_id);
  317. }
  318. static Query PrevTidIs(int thread_id) {
  319. return Query(PREV_TID) == Query::Int(thread_id);
  320. }
  321. static Query PrevThreadIs(const TraceEvent::ProcessThreadID& thread) {
  322. return PrevPidIs(thread.process_id) && PrevTidIs(thread.thread_id);
  323. }
  324. static Query PrevTimeIs(double timestamp) {
  325. return Query(PREV_TIME) == Query::Double(timestamp);
  326. }
  327. static Query PrevPhaseIs(char phase) {
  328. return Query(PREV_PHASE) == Query::Phase(phase);
  329. }
  330. static Query PrevCategoryIs(const std::string& category) {
  331. return Query(PREV_CATEGORY) == Query::String(category);
  332. }
  333. static Query PrevNameIs(const std::string& name) {
  334. return Query(PREV_NAME) == Query::String(name);
  335. }
  336. static Query PrevIdIs(const std::string& id) {
  337. return Query(PREV_ID) == Query::String(id);
  338. }
  339. // Evaluates to true if arg exists and is a string.
  340. static Query PrevHasStringArg(const std::string& arg_name) {
  341. return Query(PREV_HAS_STRING_ARG, arg_name);
  342. }
  343. // Evaluates to true if arg exists and is a number.
  344. // Number arguments include types double, int and bool.
  345. static Query PrevHasNumberArg(const std::string& arg_name) {
  346. return Query(PREV_HAS_NUMBER_ARG, arg_name);
  347. }
  348. // Evaluates to arg value (string or number).
  349. static Query PrevArg(const std::string& arg_name) {
  350. return Query(PREV_ARG, arg_name);
  351. }
  352. ////////////////////////////////////////////////////////////////
  353. // Common queries:
  354. // Find BEGIN events that have a corresponding END event.
  355. static Query MatchBeginWithEnd() {
  356. return (Query(EVENT_PHASE) == Query::Phase(TRACE_EVENT_PHASE_BEGIN)) &&
  357. Query(EVENT_HAS_OTHER);
  358. }
  359. // Find COMPLETE events.
  360. static Query MatchComplete() {
  361. return (Query(EVENT_PHASE) == Query::Phase(TRACE_EVENT_PHASE_COMPLETE));
  362. }
  363. // Find ASYNC_BEGIN events that have a corresponding ASYNC_END event.
  364. static Query MatchAsyncBeginWithNext() {
  365. return (Query(EVENT_PHASE) ==
  366. Query::Phase(TRACE_EVENT_PHASE_ASYNC_BEGIN)) &&
  367. Query(EVENT_HAS_OTHER);
  368. }
  369. // Find BEGIN events of given |name| which also have associated END events.
  370. static Query MatchBeginName(const std::string& name) {
  371. return (Query(EVENT_NAME) == Query(name)) && MatchBeginWithEnd();
  372. }
  373. // Find COMPLETE events of given |name|.
  374. static Query MatchCompleteName(const std::string& name) {
  375. return (Query(EVENT_NAME) == Query(name)) && MatchComplete();
  376. }
  377. // Match given Process ID and Thread ID.
  378. static Query MatchThread(const TraceEvent::ProcessThreadID& thread) {
  379. return (Query(EVENT_PID) == Query::Int(thread.process_id)) &&
  380. (Query(EVENT_TID) == Query::Int(thread.thread_id));
  381. }
  382. // Match event pair that spans multiple threads.
  383. static Query MatchCrossThread() {
  384. return (Query(EVENT_PID) != Query(OTHER_PID)) ||
  385. (Query(EVENT_TID) != Query(OTHER_TID));
  386. }
  387. ////////////////////////////////////////////////////////////////
  388. // Operators:
  389. // Boolean operators:
  390. Query operator==(const Query& rhs) const;
  391. Query operator!=(const Query& rhs) const;
  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;
  399. // Arithmetic operators:
  400. // Following operators are applied to double arguments:
  401. Query operator+(const Query& rhs) const;
  402. Query operator-(const Query& rhs) const;
  403. Query operator*(const Query& rhs) const;
  404. Query operator/(const Query& rhs) const;
  405. Query operator-() const;
  406. // Mod operates on int64_t args (doubles are casted to int64_t beforehand):
  407. Query operator%(const Query& rhs) const;
  408. // Return true if the given event matches this query tree.
  409. // This is a recursive method that walks the query tree.
  410. bool Evaluate(const TraceEvent& event) const;
  411. enum TraceEventMember {
  412. EVENT_INVALID,
  413. EVENT_PID,
  414. EVENT_TID,
  415. EVENT_TIME,
  416. EVENT_DURATION,
  417. EVENT_COMPLETE_DURATION,
  418. EVENT_PHASE,
  419. EVENT_CATEGORY,
  420. EVENT_NAME,
  421. EVENT_ID,
  422. EVENT_HAS_STRING_ARG,
  423. EVENT_HAS_NUMBER_ARG,
  424. EVENT_ARG,
  425. EVENT_HAS_OTHER,
  426. EVENT_HAS_PREV,
  427. OTHER_PID,
  428. OTHER_TID,
  429. OTHER_TIME,
  430. OTHER_PHASE,
  431. OTHER_CATEGORY,
  432. OTHER_NAME,
  433. OTHER_ID,
  434. OTHER_HAS_STRING_ARG,
  435. OTHER_HAS_NUMBER_ARG,
  436. OTHER_ARG,
  437. PREV_PID,
  438. PREV_TID,
  439. PREV_TIME,
  440. PREV_PHASE,
  441. PREV_CATEGORY,
  442. PREV_NAME,
  443. PREV_ID,
  444. PREV_HAS_STRING_ARG,
  445. PREV_HAS_NUMBER_ARG,
  446. PREV_ARG,
  447. OTHER_FIRST_MEMBER = OTHER_PID,
  448. OTHER_LAST_MEMBER = OTHER_ARG,
  449. PREV_FIRST_MEMBER = PREV_PID,
  450. PREV_LAST_MEMBER = PREV_ARG,
  451. };
  452. enum Operator {
  453. OP_INVALID,
  454. // Boolean operators:
  455. OP_EQ,
  456. OP_NE,
  457. OP_LT,
  458. OP_LE,
  459. OP_GT,
  460. OP_GE,
  461. OP_AND,
  462. OP_OR,
  463. OP_NOT,
  464. // Arithmetic operators:
  465. OP_ADD,
  466. OP_SUB,
  467. OP_MUL,
  468. OP_DIV,
  469. OP_MOD,
  470. OP_NEGATE
  471. };
  472. enum QueryType {
  473. QUERY_BOOLEAN_OPERATOR,
  474. QUERY_ARITHMETIC_OPERATOR,
  475. QUERY_EVENT_MEMBER,
  476. QUERY_NUMBER,
  477. QUERY_STRING
  478. };
  479. // Compare with the given member.
  480. explicit Query(TraceEventMember member);
  481. // Compare with the given member argument value.
  482. Query(TraceEventMember member, const std::string& arg_name);
  483. // Compare with the given string.
  484. explicit Query(const std::string& str);
  485. // Compare with the given number.
  486. explicit Query(double num);
  487. // Construct a boolean Query that returns (left <binary_op> right).
  488. Query(const Query& left, const Query& right, Operator binary_op);
  489. // Construct a boolean Query that returns (<binary_op> left).
  490. Query(const Query& left, Operator unary_op);
  491. // Try to compare left_ against right_ based on operator_.
  492. // If either left or right does not convert to double, false is returned.
  493. // Otherwise, true is returned and |result| is set to the comparison result.
  494. bool CompareAsDouble(const TraceEvent& event, bool* result) const;
  495. // Try to compare left_ against right_ based on operator_.
  496. // If either left or right does not convert to string, false is returned.
  497. // Otherwise, true is returned and |result| is set to the comparison result.
  498. bool CompareAsString(const TraceEvent& event, bool* result) const;
  499. // Attempt to convert this Query to a double. On success, true is returned
  500. // and the double value is stored in |num|.
  501. bool GetAsDouble(const TraceEvent& event, double* num) const;
  502. // Attempt to convert this Query to a string. On success, true is returned
  503. // and the string value is stored in |str|.
  504. bool GetAsString(const TraceEvent& event, std::string* str) const;
  505. // Evaluate this Query as an arithmetic operator on left_ and right_.
  506. bool EvaluateArithmeticOperator(const TraceEvent& event,
  507. double* num) const;
  508. // For QUERY_EVENT_MEMBER Query: attempt to get the double value of the Query.
  509. bool GetMemberValueAsDouble(const TraceEvent& event, double* num) const;
  510. // For QUERY_EVENT_MEMBER Query: attempt to get the string value of the Query.
  511. bool GetMemberValueAsString(const TraceEvent& event, std::string* num) const;
  512. // Does this Query represent a value?
  513. bool is_value() const { return type_ != QUERY_BOOLEAN_OPERATOR; }
  514. bool is_unary_operator() const {
  515. return operator_ == OP_NOT || operator_ == OP_NEGATE;
  516. }
  517. bool is_comparison_operator() const {
  518. return operator_ != OP_INVALID && operator_ < OP_AND;
  519. }
  520. static const TraceEvent* SelectTargetEvent(const TraceEvent* ev,
  521. TraceEventMember member);
  522. const Query& left() const;
  523. const Query& right() const;
  524. private:
  525. QueryType type_;
  526. Operator operator_;
  527. scoped_refptr<QueryNode> left_;
  528. scoped_refptr<QueryNode> right_;
  529. TraceEventMember member_;
  530. double number_;
  531. std::string string_;
  532. bool is_pattern_;
  533. };
  534. // Implementation detail:
  535. // QueryNode allows Query to store a ref-counted query tree.
  536. class QueryNode : public base::RefCounted<QueryNode> {
  537. public:
  538. explicit QueryNode(const Query& query);
  539. const Query& query() const { return query_; }
  540. private:
  541. friend class base::RefCounted<QueryNode>;
  542. ~QueryNode();
  543. Query query_;
  544. };
  545. // TraceAnalyzer helps tests search for trace events.
  546. class TraceAnalyzer {
  547. public:
  548. TraceAnalyzer(const TraceAnalyzer&) = delete;
  549. TraceAnalyzer& operator=(const TraceAnalyzer&) = delete;
  550. ~TraceAnalyzer();
  551. // Use trace events from JSON string generated by tracing API.
  552. // Returns non-NULL if the JSON is successfully parsed.
  553. [[nodiscard]] static std::unique_ptr<TraceAnalyzer> Create(
  554. const std::string& json_events);
  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. [[nodiscard]] bool SetEvents(const std::string& json_events);
  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. };
  620. // Utility functions for collecting process-local traces and creating a
  621. // |TraceAnalyzer| from the result. Please see comments in trace_config.h to
  622. // understand how the |category_filter_string| works. Use "*" to enable all
  623. // default categories.
  624. void Start(const std::string& category_filter_string);
  625. std::unique_ptr<TraceAnalyzer> Stop();
  626. // Utility functions for TraceEventVector.
  627. struct RateStats {
  628. double min_us;
  629. double max_us;
  630. double mean_us;
  631. double standard_deviation_us;
  632. };
  633. struct RateStatsOptions {
  634. RateStatsOptions() : trim_min(0u), trim_max(0u) {}
  635. // After the times between events are sorted, the number of specified elements
  636. // will be trimmed before calculating the RateStats. This is useful in cases
  637. // where extreme outliers are tolerable and should not skew the overall
  638. // average.
  639. size_t trim_min; // Trim this many minimum times.
  640. size_t trim_max; // Trim this many maximum times.
  641. };
  642. // Calculate min/max/mean and standard deviation from the times between
  643. // adjacent events.
  644. bool GetRateStats(const TraceEventVector& events,
  645. RateStats* stats,
  646. const RateStatsOptions* options);
  647. // Starting from |position|, find the first event that matches |query|.
  648. // Returns true if found, false otherwise.
  649. bool FindFirstOf(const TraceEventVector& events,
  650. const Query& query,
  651. size_t position,
  652. size_t* return_index);
  653. // Starting from |position|, find the last event that matches |query|.
  654. // Returns true if found, false otherwise.
  655. bool FindLastOf(const TraceEventVector& events,
  656. const Query& query,
  657. size_t position,
  658. size_t* return_index);
  659. // Find the closest events to |position| in time that match |query|.
  660. // return_second_closest may be NULL. Closeness is determined by comparing
  661. // with the event timestamp.
  662. // Returns true if found, false otherwise. If both return parameters are
  663. // requested, both must be found for a successful result.
  664. bool FindClosest(const TraceEventVector& events,
  665. const Query& query,
  666. size_t position,
  667. size_t* return_closest,
  668. size_t* return_second_closest);
  669. // Count matches, inclusive of |begin_position|, exclusive of |end_position|.
  670. size_t CountMatches(const TraceEventVector& events,
  671. const Query& query,
  672. size_t begin_position,
  673. size_t end_position);
  674. // Count all matches.
  675. inline size_t CountMatches(const TraceEventVector& events, const Query& query) {
  676. return CountMatches(events, query, 0u, events.size());
  677. }
  678. } // namespace trace_analyzer
  679. #endif // BASE_TEST_TRACE_EVENT_ANALYZER_H_