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