File: arc_tracing_model.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (749 lines) | stat: -rw-r--r-- 26,401 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/arc/tracing/arc_tracing_model.h"

#include <inttypes.h>

#include "base/compiler_specific.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/notreached.h"
#include "base/strings/string_split.h"
#include "base/trace_event/common/trace_event_common.h"
#include "chrome/browser/ash/arc/tracing/arc_tracing_event.h"
#include "chrome/browser/ash/arc/tracing/arc_tracing_event_matcher.h"

namespace arc {

namespace {

constexpr char kAndroidCategory[] = "android";
constexpr char kTracingMarkWrite[] = ": tracing_mark_write: ";
constexpr int kTracingMarkWriteLength = sizeof(kTracingMarkWrite) - 1;
constexpr char kCpuIdle[] = ": cpu_idle: ";
constexpr int kCpuIdleLength = sizeof(kCpuIdle) - 1;
constexpr char kIntelGpuFreqChange[] = ": intel_gpu_freq_change: ";
constexpr int kIntelGpuFreqChangeLength = sizeof(kIntelGpuFreqChange) - 1;
constexpr char kMsmGpuFreqChange[] = ": msm_gpu_freq_change: ";
constexpr int kMsmGpuFreqChangeLength = sizeof(kMsmGpuFreqChange) - 1;
constexpr char kSchedWakeUp[] = ": sched_wakeup: ";
constexpr int kSchedWakeUpLength = sizeof(kSchedWakeUp) - 1;
constexpr char kSchedSwitch[] = ": sched_switch: ";
constexpr int kSchedSwitchLength = sizeof(kSchedSwitch) - 1;
constexpr char kTraceEventClockSync[] = "trace_event_clock_sync: ";
constexpr int kTraceEventClockSyncLength = sizeof(kTraceEventClockSync) - 1;

// Helper function that converts a portion of string to uint32_t value. |pos|
// specifies the position in string to parse. |end_char| specifies expected
// character at the end. \0 means parse to the end. Returns the position of
// the next character after parsed digits or std::string::npos in case parsing
// failed. This is performance oriented and main idea is to avoid extra memory
// allocations due to sub-string extractions.
size_t ParseUint32(const std::string& str,
                   size_t pos,
                   char end_char,
                   uint32_t* res) {
  *res = 0;
  const size_t len = str.length();
  while (true) {
    const char& c = str[pos];
    if (c != ' ') {
      break;
    }
    if (++pos == len) {
      return std::string::npos;
    }
  }

  while (true) {
    const char& c = str[pos];
    if (c < '0' || c > '9') {
      return std::string::npos;
    }
    const uint32_t prev = *res;
    *res = *res * 10 + c - '0';
    if (prev != (*res - c + '0') / 10) {
      return std::string::npos;  // overflow
    }
    if (++pos == len || str[pos] == end_char) {
      break;
    }
  }

  return pos;
}

std::vector<std::unique_ptr<ArcTracingEventMatcher>> BuildSelector(
    const std::string& query) {
  std::vector<std::unique_ptr<ArcTracingEventMatcher>> result;
  for (const std::string& segment : base::SplitString(
           query, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
    result.emplace_back(std::make_unique<ArcTracingEventMatcher>(segment));
  }
  return result;
}

void SelectRecursively(
    size_t level,
    const ArcTracingEvent* event,
    const std::vector<std::unique_ptr<ArcTracingEventMatcher>>& selector,
    ArcTracingModel::TracingEventPtrs* collector) {
  if (level >= selector.size()) {
    return;
  }
  if (!selector[level]->Match(*event)) {
    return;
  }
  if (level == selector.size() - 1) {
    // Last segment
    collector->push_back(event);
  } else {
    for (const auto& child : event->children()) {
      SelectRecursively(level + 1, child.get(), selector, collector);
    }
  }
}

struct GraphicsEventsContext {
  // To keep in correct order of creation. This converts pair of 'B' and 'E'
  // events to the completed event, 'X'.
  ArcTracingModel::TracingEvents converted_events;
  std::map<uint32_t, std::vector<raw_ptr<ArcTracingEvent, VectorExperimental>>>
      per_thread_pending_events_stack;

  std::map<std::pair<char, std::string>, std::unique_ptr<ArcTracingEvent>>
      pending_asynchronous_events;
};

bool HandleGraphicsEvent(GraphicsEventsContext* context,
                         uint64_t timestamp,
                         uint32_t tid,
                         const std::string& line,
                         size_t event_position) {
  if (event_position + kTraceEventClockSyncLength < line.length() &&
      UNSAFE_TODO(!strncmp(&line[event_position], kTraceEventClockSync,
                           kTraceEventClockSyncLength))) {
    // Ignore this service message.
    return true;
  }

  if (line[event_position + 1] != '|') {
    LOG(ERROR) << "Cannot recognize trace marker event: " << line;
    return false;
  }

  const char phase = line[event_position];

  uint32_t pid;
  switch (phase) {
    case TRACE_EVENT_PHASE_BEGIN:
    case TRACE_EVENT_PHASE_COUNTER: {
      const size_t name_pos = ParseUint32(line, event_position + 2, '|', &pid);
      if (name_pos == std::string::npos) {
        LOG(ERROR) << "Cannot parse pid of trace event: " << line;
        return false;
      }
      const std::string name = line.substr(name_pos + 1);
      std::unique_ptr<ArcTracingEvent> event =
          std::make_unique<ArcTracingEvent>(base::Value::Dict());
      event->SetPid(pid);
      event->SetTid(tid);
      event->SetTimestamp(timestamp);
      event->SetCategory(kAndroidCategory);
      event->SetName(name);
      if (phase == TRACE_EVENT_PHASE_BEGIN) {
        context->per_thread_pending_events_stack[tid].push_back(event.get());
      } else {
        event->SetPhase(TRACE_EVENT_PHASE_COUNTER);
      }
      context->converted_events.push_back(std::move(event));
    } break;
    case TRACE_EVENT_PHASE_END: {
      // Beginning event may not exist.
      if (context->per_thread_pending_events_stack[tid].empty()) {
        return true;
      }
      if (ParseUint32(line, event_position + 2, '\0', &pid) ==
          std::string::npos) {
        LOG(ERROR) << "Cannot parse pid of trace event: " << line;
        return false;
      }
      ArcTracingEvent* completed_event =
          context->per_thread_pending_events_stack[tid].back();
      context->per_thread_pending_events_stack[tid].pop_back();
      completed_event->SetPhase(TRACE_EVENT_PHASE_COMPLETE);
      completed_event->SetDuration(timestamp - completed_event->GetTimestamp());
    } break;
    case TRACE_EVENT_PHASE_ASYNC_BEGIN:
    case TRACE_EVENT_PHASE_ASYNC_END: {
      const size_t name_pos = ParseUint32(line, event_position + 2, '|', &pid);
      if (name_pos == std::string::npos) {
        LOG(ERROR) << "Cannot parse pid of trace event: " << line;
        return false;
      }
      const size_t id_pos = line.find('|', name_pos + 2);
      if (id_pos == std::string::npos) {
        LOG(ERROR) << "Cannot parse name|id of trace event: " << line;
        return false;
      }
      const std::string name = line.substr(name_pos + 1, id_pos - name_pos - 1);
      const std::string id = line.substr(id_pos + 1);
      std::unique_ptr<ArcTracingEvent> event =
          std::make_unique<ArcTracingEvent>(base::Value::Dict());
      event->SetPhase(phase);
      event->SetPid(pid);
      event->SetTid(tid);
      event->SetTimestamp(timestamp);
      event->SetCategory(kAndroidCategory);
      event->SetName(name);
      // Id here is weak and theoretically can be replicated in another
      // processes or for different event names.
      const std::string full_id = line.substr(event_position + 2);
      event->SetId(id);
      if (context->pending_asynchronous_events.find({phase, full_id}) !=
          context->pending_asynchronous_events.end()) {
        LOG(ERROR) << "Found duplicated asynchronous event " << line;
        // That could be the real case from Android framework, for example
        // animator:opacity trace. Ignore these duplicate events.
        return true;
      }
      context->pending_asynchronous_events[{phase, full_id}] = std::move(event);
    } break;
    default:
      LOG(ERROR) << "Unsupported type of trace event: " << line;
      return false;
  }
  return true;
}

bool HandleCpuIdle(AllCpuEvents* all_cpu_events,
                   uint64_t timestamp,
                   uint32_t cpu_id,
                   uint32_t tid,
                   const std::string& line,
                   size_t event_position) {
  if (tid) {
    LOG(ERROR) << "cpu_idle belongs to non-idle thread: " << line;
    return false;
  }
  uint32_t state;
  uint32_t cpu_id_from_event;
  if (UNSAFE_TODO(sscanf(&line[event_position],
                         "state=%" SCNu32 " cpu_id=%" SCNu32, &state,
                         &cpu_id_from_event)) != 2 ||
      cpu_id != cpu_id_from_event) {
    LOG(ERROR) << "Failed to parse cpu_idle event: " << line;
    return false;
  }

  return AddAllCpuEvent(all_cpu_events, cpu_id, timestamp,
                        state == 0xffffffff ? ArcCpuEvent::Type::kIdleOut
                                            : ArcCpuEvent::Type::kIdleIn,
                        0 /* tid */);
}

bool HandleSchedWakeUp(AllCpuEvents* all_cpu_events,
                       uint64_t timestamp,
                       uint32_t cpu_id,
                       uint32_t tid,
                       const std::string& line,
                       size_t event_position) {
  const char* data = UNSAFE_TODO(strstr(&line[event_position], " pid="));
  uint32_t target_tid;
  uint32_t target_priority;
  uint32_t success;
  uint32_t target_cpu_id;
  if (!data) {
    LOG(ERROR) << "Failed to parse sched_wakeup event: " << line;
    return false;
  }

  bool parsed = false;

  // Try different kernel formats. In case one does not match, don't attempt to
  // use it in the future.
  {
    static bool use_this = true;
    if (!parsed && use_this) {
      parsed =
          UNSAFE_TODO(sscanf(
              data, " pid=%" SCNu32 " prio=%" SCNu32 " target_cpu=%" SCNu32,
              &target_tid, &target_priority, &target_cpu_id)) == 3;
      use_this = parsed;
    }
  }

  {
    static bool use_this = true;
    if (!parsed && use_this) {
      parsed = UNSAFE_TODO(sscanf(data,
                                  " pid=%" SCNu32 " prio=%" SCNu32
                                  " success=%" SCNu32 " target_cpu=%" SCNu32,
                                  &target_tid, &target_priority, &success,
                                  &target_cpu_id)) == 4;
      use_this = parsed;
    }
  }

  if (!parsed) {
    LOG(ERROR) << "Failed to parse sched_wakeup event: " << line;
    return false;
  }

  if (!target_tid) {
    LOG(ERROR) << "Cannot wake-up idle thread: " << line;
    return false;
  }

  return AddAllCpuEvent(all_cpu_events, target_cpu_id, timestamp,
                        ArcCpuEvent::Type::kWakeUp, target_tid);
}

bool HandleSchedSwitch(AllCpuEvents* all_cpu_events,
                       uint64_t timestamp,
                       uint32_t cpu_id,
                       uint32_t tid,
                       const std::string& line,
                       size_t event_position) {
  const char* data = UNSAFE_TODO(strstr(&line[event_position], " next_pid="));
  uint32_t next_tid;
  uint32_t next_priority;
  if (!data || UNSAFE_TODO(sscanf(data, " next_pid=%d next_prio=%d", &next_tid,
                                  &next_priority)) != 2) {
    LOG(ERROR) << "Failed to parse sched_switch event: " << line;
    return false;
  }

  return AddAllCpuEvent(all_cpu_events, cpu_id, timestamp,
                        ArcCpuEvent::Type::kActive, next_tid);
}

bool HandleGpuFreq(ValueEvents* value_events,
                   uint64_t timestamp,
                   const std::string& line,
                   size_t event_position) {
  int new_freq = -1;
  if (UNSAFE_TODO(sscanf(&line[event_position], "new_freq=%d", &new_freq)) !=
      1) {
    LOG(ERROR) << "Failed to parse GPU freq event: " << line;
    return false;
  }

  value_events->emplace_back(timestamp, ArcValueEvent::Type::kGpuFrequency,
                             new_freq);
  return true;
}

bool SortByTimestampPred(const std::unique_ptr<ArcTracingEvent>& lhs,
                         const std::unique_ptr<ArcTracingEvent>& rhs) {
  const uint64_t lhs_timestamp = lhs->GetTimestamp();
  const uint64_t rhs_timestamp = rhs->GetTimestamp();
  if (lhs_timestamp != rhs_timestamp) {
    return lhs_timestamp < rhs_timestamp;
  }
  return lhs->GetDuration() > rhs->GetDuration();
}

}  // namespace

ArcTracingModel::ArcTracingModel() = default;

ArcTracingModel::~ArcTracingModel() = default;

void ArcTracingModel::SetMinMaxTime(uint64_t min_timestamp,
                                    uint64_t max_timestamp) {
  DCHECK_LT(min_timestamp, max_timestamp);
  min_timestamp_ = min_timestamp;
  max_timestamp_ = max_timestamp;
}

bool ArcTracingModel::Build(const std::string& data) {
  std::optional<base::Value> value = base::JSONReader::Read(data);
  if (!value) {
    LOG(ERROR) << "Cannot parse trace data";
    return false;
  }

  base::Value::Dict* dictionary = value->GetIfDict();
  if (!dictionary) {
    LOG(ERROR) << "Trace data is not dictionary";
    return false;
  }

  const std::string* sys_traces = dictionary->FindString("systemTraceEvents");
  if (sys_traces) {
    if (!ConvertSysTraces(*sys_traces)) {
      LOG(ERROR) << "Failed to convert systrace data";
      return false;
    }
  }

  base::Value::List* events = dictionary->FindList("traceEvents");
  if (!events) {
    LOG(ERROR) << "No trace events";
    return false;
  }

  if (!ProcessEvent(events)) {
    LOG(ERROR) << "Failed to process events";
    return false;
  }

  for (auto& group_events : group_events_) {
    std::sort(group_events.second.begin(), group_events.second.end(),
              SortByTimestampPred);
  }
  std::sort(nongroup_events_.begin(), nongroup_events_.end(),
            SortByTimestampPred);

  return true;
}

ArcTracingModel::TracingEventPtrs ArcTracingModel::GetRoots() const {
  ArcTracingModel::TracingEventPtrs result;
  for (auto& gr : group_events_) {
    for (const auto& event : gr.second) {
      result.emplace_back(event.get());
    }
  }

  for (const auto& gr : per_thread_events_) {
    for (const auto& event : gr.second) {
      result.emplace_back(event.get());
    }
  }

  for (const auto& event : nongroup_events_) {
    result.emplace_back(event.get());
  }

  return result;
}

ArcTracingModel::TracingEventPtrs ArcTracingModel::Select(
    const std::string& query) const {
  ArcTracingModel::TracingEventPtrs collector;
  const std::vector<std::unique_ptr<ArcTracingEventMatcher>> selector =
      BuildSelector(query);
  for (const ArcTracingEvent* root : GetRoots()) {
    SelectRecursively(0, root, selector, &collector);
  }

  return collector;
}

ArcTracingModel::TracingEventPtrs ArcTracingModel::Select(
    const ArcTracingEvent* event,
    const std::string& query) const {
  ArcTracingModel::TracingEventPtrs collector;
  for (const auto& child : event->children()) {
    SelectRecursively(0, child.get(), BuildSelector(query), &collector);
  }
  return collector;
}

ArcTracingModel::TracingEventPtrs ArcTracingModel::GetGroupEvents(
    const std::string& id) const {
  TracingEventPtrs result;
  const auto& it = group_events_.find(id);
  if (it == group_events_.end()) {
    return result;
  }
  for (const auto& group_event : it->second) {
    result.emplace_back(group_event.get());
  }
  return result;
}

bool ArcTracingModel::ProcessEvent(base::Value::List* events) {
  std::vector<std::unique_ptr<ArcTracingEvent>> parsed_events;
  for (auto& it : *events) {
    base::Value event_data = std::move(it);
    if (!event_data.is_dict()) {
      LOG(ERROR) << "Event is not a dictionary";
      return false;
    }

    std::unique_ptr<ArcTracingEvent> event =
        std::make_unique<ArcTracingEvent>(std::move(event_data).TakeDict());
    const uint64_t timestamp = event->GetTimestamp();
    if (timestamp < min_timestamp_ || timestamp >= max_timestamp_) {
      continue;
    }

    switch (event->GetPhase()) {
      case TRACE_EVENT_PHASE_METADATA:
      case TRACE_EVENT_PHASE_COMPLETE:
      case TRACE_EVENT_PHASE_COUNTER:
      case TRACE_EVENT_PHASE_ASYNC_BEGIN:
      case TRACE_EVENT_PHASE_ASYNC_STEP_INTO:
      case TRACE_EVENT_PHASE_ASYNC_END:
      case TRACE_EVENT_PHASE_INSTANT:
        break;
      default:
        // Ignore at this moment. They are not currently used.
        continue;
    }

    if (!event->Validate()) {
      LOG(ERROR) << "Invalid event found " << event->ToString();
      return false;
    }

    parsed_events.emplace_back(std::move(event));
  }

  // Events may come by closure that means event started earlier as a root event
  // for others may appear after children. Sort by ts time.
  std::sort(parsed_events.begin(), parsed_events.end(), SortByTimestampPred);

  for (auto& event : parsed_events) {
    switch (event->GetPhase()) {
      case TRACE_EVENT_PHASE_METADATA:
      case TRACE_EVENT_PHASE_ASYNC_BEGIN:
      case TRACE_EVENT_PHASE_ASYNC_STEP_INTO:
      case TRACE_EVENT_PHASE_ASYNC_END:
        break;
      case TRACE_EVENT_PHASE_INSTANT:
        nongroup_events_.push_back(std::move(event));
        break;
      case TRACE_EVENT_PHASE_COMPLETE:
      case TRACE_EVENT_PHASE_COUNTER:
        if (!AddToThread(std::move(event))) {
          LOG(ERROR) << "Cannot add event to threads";
          return false;
        }
        break;
      default:
        NOTREACHED();
    }
  }

  return true;
}

bool ArcTracingModel::ConvertSysTraces(const std::string& sys_traces) {
  size_t new_line_pos = 0;

  GraphicsEventsContext graphics_events_context;

  // Trace events have the following format depending on whether TGID is used.
  // TGID support can be added to trace_options as an optional param (see
  // /src/third_party/kernel/<version>/kernel/trace/trace.c for details).
  // Without TGID:
  //                               _-----=> irqs-off
  //                              / _----=> need-resched
  //                             | / _---=> hardirq/softirq
  //                             || / _--=> preempt-depth
  //                             ||| /      delay
  //            TASK-PID   CPU#  ||||    TIMESTAMP  FUNCTION
  //               | |       |   ||||       |         |
  //           <...>-32043 [000] ...1 14196.099290: tracing_mark_write
  //
  // With TGID (max digits allowed may vary depending on kernel version):
  //                                       _-----=> irqs-off
  //                                      / _----=> need-resched
  //                                     | / _---=> hardirq/softirq
  //                                     || / _--=> preempt-depth
  //                                     ||| /      delay
  //            TASK-PID    TGID   CPU#  ||||    TIMESTAMP  FUNCTION
  //               | |        |      |   ||||       |         |
  //           <...>-32043 (-----) [000] ...1 14196.099290: tracing_mark_write
  //
  // From kernel 5.15, there is a fifth 1-character value "migrate-disable,"
  // right after preempt-depth.
  constexpr int kPidPosition = 16;

  // Position of the '[' before the CPU#
  size_t cpu_pos = 0;
  bool cpu_pos_found = false;

  while (true) {
    // Get end of line.
    size_t end_line_pos = sys_traces.find('\n', new_line_pos);
    if (end_line_pos == std::string::npos) {
      break;
    }

    const std::string line =
        sys_traces.substr(new_line_pos, end_line_pos - new_line_pos);
    new_line_pos = end_line_pos + 1;

    // Skip comments and empty lines.
    if (line.empty() || line[0] == '#') {
      continue;
    }

    // Spacing between TASK-PID and CPU# can vary between kernel versions
    // and depending on whether TGID option is enabled in trace_options.
    if (!cpu_pos_found) {
      cpu_pos = line.find('[', kPidPosition + 1);
      if (cpu_pos == std::string::npos) {
        LOG(ERROR) << "Cannot find CPU id in trace event: " << line;
        return false;
      }
      cpu_pos_found = true;
    }

    // CPU# is always in the form [###] (3 digits) followed by a space followed
    // by the start of the flags (irqs-off etc).
    size_t space_before_flags = cpu_pos + 5;
    if (line.length() < (cpu_pos + 12) || line[kPidPosition] != '-' ||
        line[cpu_pos - 1] != ' ' || line[cpu_pos + 4] != ']' ||
        line[space_before_flags] != ' ') {
      LOG(ERROR) << "Cannot recognize trace event: " << line;
      return false;
    }
    size_t space_after_flags = line.find(' ', space_before_flags + 1);
    // Expect at least 4 flags (kernel <= 5.10), so 5 slots from preceding
    // space to following space.
    if (space_after_flags - space_before_flags < 5) {
      LOG(ERROR) << "Fewer than 4 flags after CPU#: " << line;
      return false;
    }

    uint32_t tid;
    if (ParseUint32(line, kPidPosition + 1, ' ', &tid) == std::string::npos) {
      LOG(ERROR) << "Cannot parse tid in trace event: " << line;
      return false;
    }

    if (system_model_.thread_map().find(tid) ==
        system_model_.thread_map().end()) {
      int thread_name_start = 0;
      while (line[thread_name_start] == ' ') {
        ++thread_name_start;
      }
      system_model_.thread_map()[tid] = ArcSystemModel::ThreadInfo(
          ArcSystemModel::kUnknownPid,
          line.substr(thread_name_start, kPidPosition - thread_name_start));
    }

    uint32_t cpu_id;
    if (ParseUint32(line, cpu_pos + 1, ']', &cpu_id) == std::string::npos) {
      LOG(ERROR) << "Cannot parse CPU id in trace event: " << line;
      return false;
    }

    uint32_t timestamp_high;
    uint32_t timestamp_low;
    const size_t pos_dot =
        ParseUint32(line, space_after_flags + 1, '.', &timestamp_high);
    if (pos_dot == std::string::npos) {
      LOG(ERROR) << "Cannot parse timestamp in trace event: " << line;
      return false;
    }
    const size_t separator_position =
        ParseUint32(line, pos_dot + 1, ':', &timestamp_low);
    // We expect to have parsed exactly six digits after the decimal point, to
    // match the scaling factor used just below.
    if (separator_position != pos_dot + 7) {
      LOG(ERROR) << "Cannot parse timestamp in trace event: " << line;
      return false;
    }

    const uint64_t timestamp = 1000000LL * timestamp_high + timestamp_low;
    if (timestamp < min_timestamp_ || timestamp >= max_timestamp_) {
      continue;
    }

    if (UNSAFE_TODO(!strncmp(&line[separator_position], kTracingMarkWrite,
                             kTracingMarkWriteLength))) {
      if (!HandleGraphicsEvent(&graphics_events_context, timestamp, tid, line,
                               separator_position + kTracingMarkWriteLength)) {
        return false;
      }
    } else if (UNSAFE_TODO(!strncmp(&line[separator_position], kCpuIdle,
                                    kCpuIdleLength))) {
      if (!HandleCpuIdle(&system_model_.all_cpu_events(), timestamp, cpu_id,
                         tid, line, separator_position + kCpuIdleLength)) {
        return false;
      }
    } else if (UNSAFE_TODO(!strncmp(&line[separator_position], kSchedWakeUp,
                                    kSchedWakeUpLength))) {
      if (!HandleSchedWakeUp(&system_model_.all_cpu_events(), timestamp, cpu_id,
                             tid, line,
                             separator_position + kSchedWakeUpLength)) {
        return false;
      }
    } else if (UNSAFE_TODO(!strncmp(&line[separator_position], kSchedSwitch,
                                    kSchedSwitchLength))) {
      if (!HandleSchedSwitch(&system_model_.all_cpu_events(), timestamp, cpu_id,
                             tid, line,
                             separator_position + kSchedSwitchLength)) {
        return false;
      }
    } else if (UNSAFE_TODO(!strncmp(&line[separator_position],
                                    kIntelGpuFreqChange,
                                    kIntelGpuFreqChangeLength))) {
      if (!HandleGpuFreq(&system_model_.memory_events(), timestamp, line,
                         separator_position + kIntelGpuFreqChangeLength)) {
        return false;
      }
    } else if (UNSAFE_TODO(!strncmp(&line[separator_position],
                                    kMsmGpuFreqChange,
                                    kMsmGpuFreqChangeLength))) {
      // msm_gpu_freq_change event has same format as intel_gpu_freq_change:
      if (!HandleGpuFreq(&system_model_.memory_events(), timestamp, line,
                         separator_position + kMsmGpuFreqChangeLength)) {
        return false;
      }
    }
  }

  for (auto& asyncronous_event :
       graphics_events_context.pending_asynchronous_events) {
    group_events_[asyncronous_event.second->GetId()].emplace_back(
        std::move(asyncronous_event.second));
  }

  // Close all pending tracing event, assuming last event is 0 duration.
  for (auto& pending_events :
       graphics_events_context.per_thread_pending_events_stack) {
    if (pending_events.second.empty()) {
      continue;
    }
    const double last_timestamp = pending_events.second.back()->GetTimestamp();
    for (ArcTracingEvent* pending_event : pending_events.second) {
      pending_event->SetDuration(last_timestamp -
                                 pending_event->GetTimestamp());
      pending_event->SetPhase(TRACE_EVENT_PHASE_COMPLETE);
    }
  }

  // Now put events to the thread models.
  for (auto& converted_event : graphics_events_context.converted_events) {
    if (!AddToThread(std::move(converted_event))) {
      LOG(ERROR) << "Cannot add systrace event to threads";
      return false;
    }
  }

  return true;
}

bool ArcTracingModel::AddToThread(std::unique_ptr<ArcTracingEvent> event) {
  const uint64_t full_id = event->GetPid() * 0x100000000L + event->GetTid();
  std::vector<std::unique_ptr<ArcTracingEvent>>& thread_roots =
      per_thread_events_[full_id];
  if (thread_roots.empty() || thread_roots.back()->ClassifyPositionOf(*event) ==
                                  ArcTracingEvent::Position::kAfter) {
    // First event for the thread or event is after already existing last root
    // event. Add as a new root.
    thread_roots.emplace_back(std::move(event));
    return true;
  }

  return thread_roots.back()->AppendChild(std::move(event));
}

void ArcTracingModel::Dump(std::ostream& stream) const {
  for (const ArcTracingEvent* root : GetRoots()) {
    root->Dump("", stream);
  }
}

}  // namespace arc