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