• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "record.h"
18 
19 #include <inttypes.h>
20 #include <algorithm>
21 #include <unordered_map>
22 
23 #include <android-base/logging.h>
24 #include <android-base/macros.h>
25 #include <android-base/stringprintf.h>
26 
27 #include "OfflineUnwinder.h"
28 #include "dso.h"
29 #include "perf_regs.h"
30 #include "tracing.h"
31 #include "utils.h"
32 
33 namespace simpleperf {
34 
35 #define CHECK_SIZE(p, end, size)          \
36   do {                                    \
37     if (UNLIKELY((end) - (p) < (size))) { \
38       return false;                       \
39     }                                     \
40   } while (0)
41 
42 #define CHECK_SIZE_U64(p, end, u64_count)                           \
43   do {                                                              \
44     if (UNLIKELY(((end) - (p)) / sizeof(uint64_t) < (u64_count))) { \
45       return false;                                                 \
46     }                                                               \
47   } while (0)
48 
RecordTypeToString(int record_type)49 static std::string RecordTypeToString(int record_type) {
50   static std::unordered_map<int, std::string> record_type_names = {
51       {PERF_RECORD_MMAP, "mmap"},
52       {PERF_RECORD_LOST, "lost"},
53       {PERF_RECORD_COMM, "comm"},
54       {PERF_RECORD_EXIT, "exit"},
55       {PERF_RECORD_THROTTLE, "throttle"},
56       {PERF_RECORD_UNTHROTTLE, "unthrottle"},
57       {PERF_RECORD_FORK, "fork"},
58       {PERF_RECORD_READ, "read"},
59       {PERF_RECORD_SAMPLE, "sample"},
60       {PERF_RECORD_BUILD_ID, "build_id"},
61       {PERF_RECORD_MMAP2, "mmap2"},
62       {PERF_RECORD_AUX, "aux"},
63       {PERF_RECORD_SWITCH, "switch"},
64       {PERF_RECORD_SWITCH_CPU_WIDE, "switch_cpu_wide"},
65       {PERF_RECORD_TRACING_DATA, "tracing_data"},
66       {PERF_RECORD_AUXTRACE_INFO, "auxtrace_info"},
67       {PERF_RECORD_AUXTRACE, "auxtrace"},
68       {SIMPLE_PERF_RECORD_KERNEL_SYMBOL, "kernel_symbol"},
69       {SIMPLE_PERF_RECORD_DSO, "dso"},
70       {SIMPLE_PERF_RECORD_SYMBOL, "symbol"},
71       {SIMPLE_PERF_RECORD_EVENT_ID, "event_id"},
72       {SIMPLE_PERF_RECORD_CALLCHAIN, "callchain"},
73       {SIMPLE_PERF_RECORD_UNWINDING_RESULT, "unwinding_result"},
74       {SIMPLE_PERF_RECORD_TRACING_DATA, "tracing_data"},
75       {SIMPLE_PERF_RECORD_DEBUG, "debug"},
76   };
77 
78   auto it = record_type_names.find(record_type);
79   if (it != record_type_names.end()) {
80     return it->second;
81   }
82   return android::base::StringPrintf("unknown(%d)", record_type);
83 }
84 
85 template <>
MoveToBinaryFormat(const RecordHeader & data,char * & p)86 void MoveToBinaryFormat(const RecordHeader& data, char*& p) {
87   data.MoveToBinaryFormat(p);
88 }
89 
SampleId()90 SampleId::SampleId() {
91   memset(this, 0, sizeof(SampleId));
92 }
93 
94 // Return sample_id size in binary format.
CreateContent(const perf_event_attr & attr,uint64_t event_id)95 size_t SampleId::CreateContent(const perf_event_attr& attr, uint64_t event_id) {
96   sample_id_all = attr.sample_id_all;
97   sample_type = attr.sample_type;
98   id_data.id = event_id;
99   // Other data are not necessary. TODO: Set missing SampleId data.
100   return Size();
101 }
102 
ReadFromBinaryFormat(const perf_event_attr & attr,const char * p,const char * end)103 bool SampleId::ReadFromBinaryFormat(const perf_event_attr& attr, const char* p, const char* end) {
104   sample_id_all = attr.sample_id_all;
105   sample_type = attr.sample_type;
106   if (sample_id_all) {
107     const uint64_t sample_id_mask = PERF_SAMPLE_TID | PERF_SAMPLE_TIME | PERF_SAMPLE_ID |
108                                     PERF_SAMPLE_STREAM_ID | PERF_SAMPLE_CPU |
109                                     PERF_SAMPLE_IDENTIFIER;
110     CHECK_SIZE_U64(p, end, __builtin_popcountll(sample_type & sample_id_mask));
111     if (sample_type & PERF_SAMPLE_TID) {
112       MoveFromBinaryFormat(tid_data, p);
113     }
114     if (sample_type & PERF_SAMPLE_TIME) {
115       MoveFromBinaryFormat(time_data, p);
116     }
117     if (sample_type & PERF_SAMPLE_ID) {
118       MoveFromBinaryFormat(id_data, p);
119     }
120     if (sample_type & PERF_SAMPLE_STREAM_ID) {
121       MoveFromBinaryFormat(stream_id_data, p);
122     }
123     if (sample_type & PERF_SAMPLE_CPU) {
124       MoveFromBinaryFormat(cpu_data, p);
125     }
126     if (sample_type & PERF_SAMPLE_IDENTIFIER) {
127       MoveFromBinaryFormat(id_data, p);
128     }
129   }
130   if (UNLIKELY(p < end)) {
131     LOG(DEBUG) << "Record SampleId part has " << end - p << " bytes left\n";
132   }
133   return true;
134 }
135 
WriteToBinaryFormat(char * & p) const136 void SampleId::WriteToBinaryFormat(char*& p) const {
137   if (sample_id_all) {
138     if (sample_type & PERF_SAMPLE_TID) {
139       MoveToBinaryFormat(tid_data, p);
140     }
141     if (sample_type & PERF_SAMPLE_TIME) {
142       MoveToBinaryFormat(time_data, p);
143     }
144     if (sample_type & PERF_SAMPLE_ID) {
145       MoveToBinaryFormat(id_data, p);
146     }
147     if (sample_type & PERF_SAMPLE_STREAM_ID) {
148       MoveToBinaryFormat(stream_id_data, p);
149     }
150     if (sample_type & PERF_SAMPLE_CPU) {
151       MoveToBinaryFormat(cpu_data, p);
152     }
153   }
154 }
155 
Dump(size_t indent) const156 void SampleId::Dump(size_t indent) const {
157   if (sample_id_all) {
158     if (sample_type & PERF_SAMPLE_TID) {
159       PrintIndented(indent, "sample_id: pid %u, tid %u\n", tid_data.pid, tid_data.tid);
160     }
161     if (sample_type & PERF_SAMPLE_TIME) {
162       PrintIndented(indent, "sample_id: time %" PRId64 "\n", time_data.time);
163     }
164     if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) {
165       PrintIndented(indent, "sample_id: id %" PRId64 "\n", id_data.id);
166     }
167     if (sample_type & PERF_SAMPLE_STREAM_ID) {
168       PrintIndented(indent, "sample_id: stream_id %" PRId64 "\n", stream_id_data.stream_id);
169     }
170     if (sample_type & PERF_SAMPLE_CPU) {
171       PrintIndented(indent, "sample_id: cpu %u, res %u\n", cpu_data.cpu, cpu_data.res);
172     }
173   }
174 }
175 
Size() const176 size_t SampleId::Size() const {
177   size_t size = 0;
178   if (sample_id_all) {
179     if (sample_type & PERF_SAMPLE_TID) {
180       size += sizeof(PerfSampleTidType);
181     }
182     if (sample_type & PERF_SAMPLE_TIME) {
183       size += sizeof(PerfSampleTimeType);
184     }
185     if (sample_type & PERF_SAMPLE_ID) {
186       size += sizeof(PerfSampleIdType);
187     }
188     if (sample_type & PERF_SAMPLE_STREAM_ID) {
189       size += sizeof(PerfSampleStreamIdType);
190     }
191     if (sample_type & PERF_SAMPLE_CPU) {
192       size += sizeof(PerfSampleCpuType);
193     }
194     if (sample_type & PERF_SAMPLE_IDENTIFIER) {
195       size += sizeof(PerfSampleIdType);
196     }
197   }
198   return size;
199 }
200 
Record(Record && other)201 Record::Record(Record&& other) noexcept {
202   header = other.header;
203   sample_id = other.sample_id;
204   binary_ = other.binary_;
205   own_binary_ = other.own_binary_;
206   other.binary_ = nullptr;
207   other.own_binary_ = false;
208 }
209 
ParseHeader(char * & p,char * & end)210 bool Record::ParseHeader(char*& p, char*& end) {
211   binary_ = p;
212   CHECK(end != nullptr);
213   CHECK_SIZE(p, end, sizeof(perf_event_header));
214   if (!header.Parse(p)) {
215     return false;
216   }
217   CHECK_SIZE(p, end, header.size);
218   end = p + header.size;
219   p += sizeof(perf_event_header);
220   return true;
221 }
222 
Dump(size_t indent) const223 void Record::Dump(size_t indent) const {
224   PrintIndented(indent, "record %s: type %u, misc 0x%x, size %u\n",
225                 RecordTypeToString(type()).c_str(), type(), misc(), size());
226   DumpData(indent + 1);
227   sample_id.Dump(indent + 1);
228 }
229 
Timestamp() const230 uint64_t Record::Timestamp() const {
231   return sample_id.time_data.time;
232 }
Cpu() const233 uint32_t Record::Cpu() const {
234   return sample_id.cpu_data.cpu;
235 }
Id() const236 uint64_t Record::Id() const {
237   return sample_id.id_data.id;
238 }
239 
UpdateBinary(char * new_binary)240 void Record::UpdateBinary(char* new_binary) {
241   if (own_binary_) {
242     delete[] binary_;
243   }
244   own_binary_ = true;
245   binary_ = new_binary;
246 }
247 
Parse(const perf_event_attr & attr,char * p,char * end)248 bool MmapRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
249   if (!ParseHeader(p, end)) {
250     return false;
251   }
252   data = reinterpret_cast<const MmapRecordDataType*>(p);
253   CHECK_SIZE(p, end, sizeof(*data));
254   p += sizeof(*data);
255   size_t size = Align(SafeStrlen(p, end) + 1, 8);
256   CHECK_SIZE(p, end, size);
257   filename = p;
258   p += size;
259   return sample_id.ReadFromBinaryFormat(attr, p, end);
260 }
261 
MmapRecord(const perf_event_attr & attr,bool in_kernel,uint32_t pid,uint32_t tid,uint64_t addr,uint64_t len,uint64_t pgoff,const std::string & filename,uint64_t event_id,uint64_t time)262 MmapRecord::MmapRecord(const perf_event_attr& attr, bool in_kernel, uint32_t pid, uint32_t tid,
263                        uint64_t addr, uint64_t len, uint64_t pgoff, const std::string& filename,
264                        uint64_t event_id, uint64_t time) {
265   SetTypeAndMisc(PERF_RECORD_MMAP, in_kernel ? PERF_RECORD_MISC_KERNEL : PERF_RECORD_MISC_USER);
266   sample_id.CreateContent(attr, event_id);
267   sample_id.time_data.time = time;
268   MmapRecordDataType data;
269   data.pid = pid;
270   data.tid = tid;
271   data.addr = addr;
272   data.len = len;
273   data.pgoff = pgoff;
274   SetDataAndFilename(data, filename);
275 }
276 
SetDataAndFilename(const MmapRecordDataType & data,const std::string & filename)277 void MmapRecord::SetDataAndFilename(const MmapRecordDataType& data, const std::string& filename) {
278   SetSize(header_size() + sizeof(data) + Align(filename.size() + 1, 8) + sample_id.Size());
279   char* new_binary = new char[size()];
280   char* p = new_binary;
281   MoveToBinaryFormat(header, p);
282   this->data = reinterpret_cast<MmapRecordDataType*>(p);
283   MoveToBinaryFormat(data, p);
284   this->filename = p;
285   strcpy(p, filename.c_str());
286   p += Align(filename.size() + 1, 8);
287   sample_id.WriteToBinaryFormat(p);
288   UpdateBinary(new_binary);
289 }
290 
DumpData(size_t indent) const291 void MmapRecord::DumpData(size_t indent) const {
292   PrintIndented(indent, "pid %u, tid %u, addr 0x%" PRIx64 ", len 0x%" PRIx64 "\n", data->pid,
293                 data->tid, data->addr, data->len);
294   PrintIndented(indent, "pgoff 0x%" PRIx64 ", filename %s\n", data->pgoff, filename);
295 }
296 
Parse(const perf_event_attr & attr,char * p,char * end)297 bool Mmap2Record::Parse(const perf_event_attr& attr, char* p, char* end) {
298   if (!ParseHeader(p, end)) {
299     return false;
300   }
301   data = reinterpret_cast<const Mmap2RecordDataType*>(p);
302   CHECK_SIZE(p, end, sizeof(*data));
303   p += sizeof(*data);
304   size_t size = Align(SafeStrlen(p, end) + 1, 8);
305   CHECK_SIZE(p, end, size);
306   filename = p;
307   p += size;
308   return sample_id.ReadFromBinaryFormat(attr, p, end);
309 }
310 
Mmap2Record(const perf_event_attr & attr,bool in_kernel,uint32_t pid,uint32_t tid,uint64_t addr,uint64_t len,uint64_t pgoff,uint32_t prot,const std::string & filename,uint64_t event_id,uint64_t time)311 Mmap2Record::Mmap2Record(const perf_event_attr& attr, bool in_kernel, uint32_t pid, uint32_t tid,
312                          uint64_t addr, uint64_t len, uint64_t pgoff, uint32_t prot,
313                          const std::string& filename, uint64_t event_id, uint64_t time) {
314   SetTypeAndMisc(PERF_RECORD_MMAP2, in_kernel ? PERF_RECORD_MISC_KERNEL : PERF_RECORD_MISC_USER);
315   sample_id.CreateContent(attr, event_id);
316   sample_id.time_data.time = time;
317   Mmap2RecordDataType data;
318   data.pid = pid;
319   data.tid = tid;
320   data.addr = addr;
321   data.len = len;
322   data.pgoff = pgoff;
323   data.prot = prot;
324   SetDataAndFilename(data, filename);
325 }
326 
SetDataAndFilename(const Mmap2RecordDataType & data,const std::string & filename)327 void Mmap2Record::SetDataAndFilename(const Mmap2RecordDataType& data, const std::string& filename) {
328   SetSize(header_size() + sizeof(data) + Align(filename.size() + 1, 8) + sample_id.Size());
329   char* new_binary = new char[size()];
330   char* p = new_binary;
331   MoveToBinaryFormat(header, p);
332   this->data = reinterpret_cast<Mmap2RecordDataType*>(p);
333   MoveToBinaryFormat(data, p);
334   this->filename = p;
335   strcpy(p, filename.c_str());
336   p += Align(filename.size() + 1, 8);
337   sample_id.WriteToBinaryFormat(p);
338   UpdateBinary(new_binary);
339 }
340 
DumpData(size_t indent) const341 void Mmap2Record::DumpData(size_t indent) const {
342   PrintIndented(indent, "pid %u, tid %u, addr 0x%" PRIx64 ", len 0x%" PRIx64 "\n", data->pid,
343                 data->tid, data->addr, data->len);
344   PrintIndented(
345       indent, "pgoff 0x%" PRIx64 ", maj %u, min %u, ino %" PRId64 ", ino_generation %" PRIu64 "\n",
346       data->pgoff, data->maj, data->min, data->ino, data->ino_generation);
347   PrintIndented(indent, "prot %u, flags %u, filename %s\n", data->prot, data->flags, filename);
348 }
349 
Parse(const perf_event_attr & attr,char * p,char * end)350 bool CommRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
351   if (!ParseHeader(p, end)) {
352     return false;
353   }
354   data = reinterpret_cast<const CommRecordDataType*>(p);
355   CHECK_SIZE(p, end, sizeof(*data));
356   p += sizeof(*data);
357   size_t size = Align(SafeStrlen(p, end) + 1, 8);
358   CHECK_SIZE(p, end, size);
359   comm = p;
360   p += size;
361   return sample_id.ReadFromBinaryFormat(attr, p, end);
362 }
363 
CommRecord(const perf_event_attr & attr,uint32_t pid,uint32_t tid,const std::string & comm,uint64_t event_id,uint64_t time)364 CommRecord::CommRecord(const perf_event_attr& attr, uint32_t pid, uint32_t tid,
365                        const std::string& comm, uint64_t event_id, uint64_t time) {
366   SetTypeAndMisc(PERF_RECORD_COMM, 0);
367   CommRecordDataType data;
368   data.pid = pid;
369   data.tid = tid;
370   size_t sample_id_size = sample_id.CreateContent(attr, event_id);
371   sample_id.time_data.time = time;
372   SetSize(header_size() + sizeof(data) + Align(comm.size() + 1, 8) + sample_id_size);
373   char* new_binary = new char[size()];
374   char* p = new_binary;
375   MoveToBinaryFormat(header, p);
376   this->data = reinterpret_cast<CommRecordDataType*>(p);
377   MoveToBinaryFormat(data, p);
378   this->comm = p;
379   strcpy(p, comm.c_str());
380   p += Align(comm.size() + 1, 8);
381   sample_id.WriteToBinaryFormat(p);
382   UpdateBinary(new_binary);
383 }
384 
SetCommandName(const std::string & name)385 void CommRecord::SetCommandName(const std::string& name) {
386   if (name.compare(comm) == 0) {
387     return;
388   }
389   // The kernel uses a 8-byte aligned space to store command name. Follow it here to allow the same
390   // reading code.
391   size_t old_name_len = Align(strlen(comm) + 1, 8);
392   size_t new_name_len = Align(name.size() + 1, 8);
393   size_t new_size = size() - old_name_len + new_name_len;
394   char* new_binary = new char[new_size];
395   char* p = new_binary;
396   header.size = new_size;
397   MoveToBinaryFormat(header, p);
398   MoveToBinaryFormat(*data, p);
399   data = reinterpret_cast<CommRecordDataType*>(p - sizeof(CommRecordDataType));
400   comm = p;
401   strcpy(p, name.c_str());
402   p += new_name_len;
403   sample_id.WriteToBinaryFormat(p);
404   CHECK_EQ(p, new_binary + new_size);
405   UpdateBinary(new_binary);
406 }
407 
DumpData(size_t indent) const408 void CommRecord::DumpData(size_t indent) const {
409   PrintIndented(indent, "pid %u, tid %u, comm %s\n", data->pid, data->tid, comm);
410 }
411 
Parse(const perf_event_attr & attr,char * p,char * end)412 bool ExitOrForkRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
413   if (!ParseHeader(p, end)) {
414     return false;
415   }
416   data = reinterpret_cast<const ExitOrForkRecordDataType*>(p);
417   CHECK_SIZE(p, end, sizeof(*data));
418   p += sizeof(*data);
419   return sample_id.ReadFromBinaryFormat(attr, p, end);
420 }
421 
DumpData(size_t indent) const422 void ExitOrForkRecord::DumpData(size_t indent) const {
423   PrintIndented(indent, "pid %u, ppid %u, tid %u, ptid %u\n", data->pid, data->ppid, data->tid,
424                 data->ptid);
425 }
426 
ForkRecord(const perf_event_attr & attr,uint32_t pid,uint32_t tid,uint32_t ppid,uint32_t ptid,uint64_t event_id)427 ForkRecord::ForkRecord(const perf_event_attr& attr, uint32_t pid, uint32_t tid, uint32_t ppid,
428                        uint32_t ptid, uint64_t event_id) {
429   SetTypeAndMisc(PERF_RECORD_FORK, 0);
430   ExitOrForkRecordDataType data;
431   data.pid = pid;
432   data.ppid = ppid;
433   data.tid = tid;
434   data.ptid = ptid;
435   data.time = 0;
436   size_t sample_id_size = sample_id.CreateContent(attr, event_id);
437   SetSize(header_size() + sizeof(data) + sample_id_size);
438   char* new_binary = new char[size()];
439   char* p = new_binary;
440   MoveToBinaryFormat(header, p);
441   this->data = reinterpret_cast<ExitOrForkRecordDataType*>(p);
442   MoveToBinaryFormat(data, p);
443   sample_id.WriteToBinaryFormat(p);
444   UpdateBinary(new_binary);
445 }
446 
Parse(const perf_event_attr & attr,char * p,char * end)447 bool LostRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
448   if (!ParseHeader(p, end)) {
449     return false;
450   }
451   CHECK_SIZE_U64(p, end, 2);
452   MoveFromBinaryFormat(id, p);
453   MoveFromBinaryFormat(lost, p);
454   return sample_id.ReadFromBinaryFormat(attr, p, end);
455 }
456 
DumpData(size_t indent) const457 void LostRecord::DumpData(size_t indent) const {
458   PrintIndented(indent, "id %" PRIu64 ", lost %" PRIu64 "\n", id, lost);
459 }
460 
Parse(const perf_event_attr & attr,char * p,char * end)461 bool SampleRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
462   if (!ParseHeader(p, end)) {
463     return false;
464   }
465   sample_type = attr.sample_type;
466   read_format = attr.read_format;
467   const uint64_t sample_mask = PERF_SAMPLE_IDENTIFIER | PERF_SAMPLE_IP | PERF_SAMPLE_TID |
468                                PERF_SAMPLE_TIME | PERF_SAMPLE_ADDR | PERF_SAMPLE_ID |
469                                PERF_SAMPLE_STREAM_ID | PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD;
470   CHECK_SIZE_U64(p, end, __builtin_popcountll(sample_type & sample_mask));
471 
472   // Set a default id value to report correctly even if ID is not recorded.
473   id_data.id = 0;
474   if (sample_type & PERF_SAMPLE_IDENTIFIER) {
475     MoveFromBinaryFormat(id_data, p);
476   }
477   if (sample_type & PERF_SAMPLE_IP) {
478     MoveFromBinaryFormat(ip_data, p);
479   }
480   if (sample_type & PERF_SAMPLE_TID) {
481     MoveFromBinaryFormat(tid_data, p);
482   }
483   if (sample_type & PERF_SAMPLE_TIME) {
484     MoveFromBinaryFormat(time_data, p);
485   }
486   if (sample_type & PERF_SAMPLE_ADDR) {
487     MoveFromBinaryFormat(addr_data, p);
488   }
489   if (sample_type & PERF_SAMPLE_ID) {
490     MoveFromBinaryFormat(id_data, p);
491   }
492   if (sample_type & PERF_SAMPLE_STREAM_ID) {
493     MoveFromBinaryFormat(stream_id_data, p);
494   }
495   if (sample_type & PERF_SAMPLE_CPU) {
496     MoveFromBinaryFormat(cpu_data, p);
497   }
498   if (sample_type & PERF_SAMPLE_PERIOD) {
499     MoveFromBinaryFormat(period_data, p);
500   }
501   if (sample_type & PERF_SAMPLE_READ) {
502     uint64_t nr = 1;
503     if (read_format & PERF_FORMAT_GROUP) {
504       CHECK_SIZE_U64(p, end, 1);
505       MoveFromBinaryFormat(nr, p);
506     }
507     uint64_t u64_count = (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) ? 1 : 0;
508     u64_count += (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) ? 1 : 0;
509     if (__builtin_add_overflow(u64_count, nr, &u64_count)) {
510       return false;
511     }
512     if (read_format & PERF_FORMAT_ID) {
513       if (__builtin_add_overflow(u64_count, nr, &u64_count)) {
514         return false;
515       }
516     }
517     CHECK_SIZE_U64(p, end, u64_count);
518     if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
519       MoveFromBinaryFormat(read_data.time_enabled, p);
520     }
521     if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
522       MoveFromBinaryFormat(read_data.time_running, p);
523     }
524     read_data.counts.resize(nr);
525     if (read_format & PERF_FORMAT_ID) {
526       read_data.ids.resize(nr);
527     }
528     for (uint64_t i = 0; i < nr; i++) {
529       MoveFromBinaryFormat(read_data.counts[i], p);
530       if (read_format & PERF_FORMAT_ID) {
531         MoveFromBinaryFormat(read_data.ids[i], p);
532       }
533     }
534   }
535   if (sample_type & PERF_SAMPLE_CALLCHAIN) {
536     CHECK_SIZE_U64(p, end, 1);
537     MoveFromBinaryFormat(callchain_data.ip_nr, p);
538     CHECK_SIZE_U64(p, end, callchain_data.ip_nr);
539     callchain_data.ips = reinterpret_cast<uint64_t*>(p);
540     p += callchain_data.ip_nr * sizeof(uint64_t);
541   }
542   if (sample_type & PERF_SAMPLE_RAW) {
543     CHECK_SIZE(p, end, sizeof(uint32_t));
544     MoveFromBinaryFormat(raw_data.size, p);
545     CHECK_SIZE(p, end, raw_data.size);
546     raw_data.data = p;
547     p += raw_data.size;
548   }
549   if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
550     CHECK_SIZE_U64(p, end, 1);
551     MoveFromBinaryFormat(branch_stack_data.stack_nr, p);
552     CHECK_SIZE(p, end, branch_stack_data.stack_nr * sizeof(BranchStackItemType));
553     branch_stack_data.stack = reinterpret_cast<BranchStackItemType*>(p);
554     p += branch_stack_data.stack_nr * sizeof(BranchStackItemType);
555   }
556   if (sample_type & PERF_SAMPLE_REGS_USER) {
557     CHECK_SIZE_U64(p, end, 1);
558     MoveFromBinaryFormat(regs_user_data.abi, p);
559     if (regs_user_data.abi == 0) {
560       regs_user_data.reg_mask = 0;
561       regs_user_data.reg_nr = 0;
562       regs_user_data.regs = nullptr;
563     } else {
564       regs_user_data.reg_mask = attr.sample_regs_user;
565       size_t bit_nr = __builtin_popcountll(regs_user_data.reg_mask);
566       CHECK_SIZE_U64(p, end, bit_nr);
567       regs_user_data.reg_nr = bit_nr;
568       regs_user_data.regs = reinterpret_cast<uint64_t*>(p);
569       p += bit_nr * sizeof(uint64_t);
570     }
571   }
572   if (sample_type & PERF_SAMPLE_STACK_USER) {
573     CHECK_SIZE_U64(p, end, 1);
574     MoveFromBinaryFormat(stack_user_data.size, p);
575     if (stack_user_data.size == 0) {
576       stack_user_data.dyn_size = 0;
577     } else {
578       CHECK_SIZE(p, end, stack_user_data.size + sizeof(uint64_t));
579       stack_user_data.data = p;
580       p += stack_user_data.size;
581       MoveFromBinaryFormat(stack_user_data.dyn_size, p);
582     }
583   }
584   // TODO: Add parsing of other PERF_SAMPLE_*.
585   if (UNLIKELY(p < end)) {
586     LOG(DEBUG) << "Sample (" << time_data.time << ") has " << end - p << " bytes left";
587   }
588   return true;
589 }
590 
SampleRecord(const perf_event_attr & attr,uint64_t id,uint64_t ip,uint32_t pid,uint32_t tid,uint64_t time,uint32_t cpu,uint64_t period,const PerfSampleReadType & read_data,const std::vector<uint64_t> & ips,const std::vector<char> & stack,uint64_t dyn_stack_size)591 SampleRecord::SampleRecord(const perf_event_attr& attr, uint64_t id, uint64_t ip, uint32_t pid,
592                            uint32_t tid, uint64_t time, uint32_t cpu, uint64_t period,
593                            const PerfSampleReadType& read_data, const std::vector<uint64_t>& ips,
594                            const std::vector<char>& stack, uint64_t dyn_stack_size) {
595   SetTypeAndMisc(PERF_RECORD_SAMPLE, PERF_RECORD_MISC_USER);
596   sample_type = attr.sample_type;
597   read_format = attr.read_format;
598   CHECK_EQ(0u,
599            sample_type & ~(PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_TIME | PERF_SAMPLE_ID |
600                            PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD | PERF_SAMPLE_READ |
601                            PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER));
602   ip_data.ip = ip;
603   tid_data.pid = pid;
604   tid_data.tid = tid;
605   time_data.time = time;
606   id_data.id = id;
607   cpu_data.cpu = cpu;
608   cpu_data.res = 0;
609   period_data.period = period;
610   this->read_data = read_data;
611   callchain_data.ip_nr = ips.size();
612   raw_data.size = 0;
613   branch_stack_data.stack_nr = 0;
614   regs_user_data.abi = 0;
615   regs_user_data.reg_mask = 0;
616   regs_user_data.reg_nr = 0;
617   stack_user_data.size = stack.size();
618   stack_user_data.dyn_size = dyn_stack_size;
619 
620   uint32_t size = header_size();
621   if (sample_type & PERF_SAMPLE_IP) {
622     size += sizeof(ip_data);
623   }
624   if (sample_type & PERF_SAMPLE_TID) {
625     size += sizeof(tid_data);
626   }
627   if (sample_type & PERF_SAMPLE_TIME) {
628     size += sizeof(time_data);
629   }
630   if (sample_type & PERF_SAMPLE_ID) {
631     size += sizeof(id_data);
632   }
633   if (sample_type & PERF_SAMPLE_CPU) {
634     size += sizeof(cpu_data);
635   }
636   if (sample_type & PERF_SAMPLE_PERIOD) {
637     size += sizeof(period_data);
638   }
639   if (sample_type & PERF_SAMPLE_READ) {
640     size_t u64_count = (read_format & PERF_FORMAT_GROUP) ? 1 : 0;
641     u64_count += (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) ? 1 : 0;
642     u64_count += (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) ? 1 : 0;
643     u64_count += read_data.counts.size() + read_data.ids.size();
644     size += sizeof(uint64_t) * u64_count;
645   }
646   if (sample_type & PERF_SAMPLE_CALLCHAIN) {
647     size += sizeof(uint64_t) * (ips.size() + 1);
648   }
649   if (sample_type & PERF_SAMPLE_REGS_USER) {
650     size += sizeof(uint64_t);
651   }
652   if (sample_type & PERF_SAMPLE_STACK_USER) {
653     size += sizeof(uint64_t) + (stack.empty() ? 0 : stack.size() + sizeof(uint64_t));
654   }
655 
656   SetSize(size);
657   char* new_binary = new char[size];
658   char* p = new_binary;
659   MoveToBinaryFormat(header, p);
660   if (sample_type & PERF_SAMPLE_IP) {
661     MoveToBinaryFormat(ip_data, p);
662   }
663   if (sample_type & PERF_SAMPLE_TID) {
664     MoveToBinaryFormat(tid_data, p);
665   }
666   if (sample_type & PERF_SAMPLE_TIME) {
667     MoveToBinaryFormat(time_data, p);
668   }
669   if (sample_type & PERF_SAMPLE_ID) {
670     MoveToBinaryFormat(id_data, p);
671   }
672   if (sample_type & PERF_SAMPLE_CPU) {
673     MoveToBinaryFormat(cpu_data, p);
674   }
675   if (sample_type & PERF_SAMPLE_PERIOD) {
676     MoveToBinaryFormat(period_data, p);
677   }
678   if (sample_type & PERF_SAMPLE_READ) {
679     if (read_format & PERF_FORMAT_GROUP) {
680       uint64_t nr = read_data.counts.size();
681       MoveToBinaryFormat(nr, p);
682     }
683     if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
684       MoveToBinaryFormat(read_data.time_enabled, p);
685     }
686     if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
687       MoveToBinaryFormat(read_data.time_running, p);
688     }
689     for (size_t i = 0; i < read_data.counts.size(); i++) {
690       MoveToBinaryFormat(read_data.counts[i], p);
691       if (read_format & PERF_FORMAT_ID) {
692         MoveToBinaryFormat(read_data.ids[i], p);
693       }
694     }
695   }
696   if (sample_type & PERF_SAMPLE_CALLCHAIN) {
697     MoveToBinaryFormat(callchain_data.ip_nr, p);
698     callchain_data.ips = reinterpret_cast<uint64_t*>(p);
699     MoveToBinaryFormat(ips.data(), ips.size(), p);
700   }
701   if (sample_type & PERF_SAMPLE_REGS_USER) {
702     MoveToBinaryFormat(regs_user_data.abi, p);
703   }
704   if (sample_type & PERF_SAMPLE_STACK_USER) {
705     MoveToBinaryFormat(stack_user_data.size, p);
706     if (stack_user_data.size > 0) {
707       stack_user_data.data = p;
708       MoveToBinaryFormat(stack.data(), stack_user_data.size, p);
709       MoveToBinaryFormat(stack_user_data.dyn_size, p);
710     }
711   }
712   CHECK_EQ(p, new_binary + size);
713   UpdateBinary(new_binary);
714 }
715 
ReplaceRegAndStackWithCallChain(const std::vector<uint64_t> & ips)716 void SampleRecord::ReplaceRegAndStackWithCallChain(const std::vector<uint64_t>& ips) {
717   uint32_t add_size_in_callchain = ips.empty() ? 0 : sizeof(uint64_t) * (ips.size() + 1);
718   uint32_t reduce_size_in_reg = (regs_user_data.reg_nr + 1) * sizeof(uint64_t);
719   uint32_t reduce_size_in_stack =
720       stack_user_data.size == 0 ? sizeof(uint64_t) : (stack_user_data.size + 2 * sizeof(uint64_t));
721   uint32_t reduce_size = reduce_size_in_reg + reduce_size_in_stack;
722 
723   uint32_t new_size = size() + add_size_in_callchain;
724   CHECK_GT(new_size, reduce_size);
725   new_size -= reduce_size;
726   sample_type &= ~(PERF_SAMPLE_STACK_USER | PERF_SAMPLE_REGS_USER);
727   BuildBinaryWithNewCallChain(new_size, ips);
728 }
729 
ExcludeKernelCallChain()730 bool SampleRecord::ExcludeKernelCallChain() {
731   if (!(sample_type & PERF_SAMPLE_CALLCHAIN)) {
732     return true;
733   }
734   size_t i;
735   for (i = 0; i < callchain_data.ip_nr; ++i) {
736     if (callchain_data.ips[i] == PERF_CONTEXT_USER) {
737       break;
738     }
739     // Erase kernel callchain.
740     callchain_data.ips[i] = PERF_CONTEXT_USER;
741   }
742   while (++i < callchain_data.ip_nr) {
743     if (callchain_data.ips[i] < PERF_CONTEXT_MAX) {
744       // Change the sample to make it hit the user space ip address.
745       ip_data.ip = callchain_data.ips[i];
746       if (sample_type & PERF_SAMPLE_IP) {
747         *reinterpret_cast<uint64_t*>(binary_ + header_size()) = ip_data.ip;
748       }
749       header.misc = (header.misc & ~PERF_RECORD_MISC_CPUMODE_MASK) | PERF_RECORD_MISC_USER;
750       reinterpret_cast<perf_event_header*>(binary_)->misc = header.misc;
751       return true;
752     }
753   }
754   return false;
755 }
756 
HasUserCallChain() const757 bool SampleRecord::HasUserCallChain() const {
758   if ((sample_type & PERF_SAMPLE_CALLCHAIN) == 0) {
759     return false;
760   }
761   bool in_user_context = !InKernel();
762   for (size_t i = 0; i < callchain_data.ip_nr; ++i) {
763     if (in_user_context && callchain_data.ips[i] < PERF_CONTEXT_MAX) {
764       return true;
765     }
766     if (callchain_data.ips[i] == PERF_CONTEXT_USER) {
767       in_user_context = true;
768     }
769   }
770   return false;
771 }
772 
UpdateUserCallChain(const std::vector<uint64_t> & user_ips)773 void SampleRecord::UpdateUserCallChain(const std::vector<uint64_t>& user_ips) {
774   size_t kernel_ip_count = 0;
775   for (size_t i = 0; i < callchain_data.ip_nr; ++i) {
776     if (callchain_data.ips[i] == PERF_CONTEXT_USER) {
777       break;
778     }
779     kernel_ip_count++;
780   }
781   if (kernel_ip_count + 1 + user_ips.size() <= callchain_data.ip_nr) {
782     // Callchain isn't changed.
783     return;
784   }
785   size_t new_size =
786       size() + (kernel_ip_count + 1 + user_ips.size() - callchain_data.ip_nr) * sizeof(uint64_t);
787   callchain_data.ip_nr = kernel_ip_count;
788   BuildBinaryWithNewCallChain(new_size, user_ips);
789 }
790 
BuildBinaryWithNewCallChain(uint32_t new_size,const std::vector<uint64_t> & ips)791 void SampleRecord::BuildBinaryWithNewCallChain(uint32_t new_size,
792                                                const std::vector<uint64_t>& ips) {
793   size_t callchain_pos = reinterpret_cast<char*>(callchain_data.ips) - binary_ - sizeof(uint64_t);
794   char* new_binary = binary_;
795   if (new_size > size()) {
796     new_binary = new char[new_size];
797     memcpy(new_binary, binary_, callchain_pos);
798   }
799   char* p = new_binary;
800   SetSize(new_size);
801   MoveToBinaryFormat(header, p);
802   p = new_binary + new_size;
803   if (sample_type & PERF_SAMPLE_STACK_USER) {
804     stack_user_data.size = 0;
805     p -= sizeof(uint64_t);
806     memcpy(p, &stack_user_data.size, sizeof(uint64_t));
807   }
808   if (sample_type & PERF_SAMPLE_REGS_USER) {
809     regs_user_data.abi = 0;
810     p -= sizeof(uint64_t);
811     memcpy(p, &regs_user_data.abi, sizeof(uint64_t));
812   }
813   if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
814     p -= branch_stack_data.stack_nr * sizeof(BranchStackItemType);
815     memcpy(p, branch_stack_data.stack, branch_stack_data.stack_nr * sizeof(BranchStackItemType));
816     branch_stack_data.stack = reinterpret_cast<BranchStackItemType*>(p);
817     p -= sizeof(uint64_t);
818     memcpy(p, &branch_stack_data.stack_nr, sizeof(uint64_t));
819   }
820   if (sample_type & PERF_SAMPLE_RAW) {
821     p -= raw_data.size;
822     memcpy(p, raw_data.data, raw_data.size);
823     raw_data.data = p;
824     p -= sizeof(uint32_t);
825     memcpy(p, &raw_data.size, sizeof(uint32_t));
826   }
827   uint64_t* p64 = reinterpret_cast<uint64_t*>(p);
828   if (!ips.empty()) {
829     p64 -= ips.size();
830     memcpy(p64, ips.data(), ips.size() * sizeof(uint64_t));
831     *--p64 = PERF_CONTEXT_USER;
832   }
833   p64 -= callchain_data.ip_nr;
834   if (p64 != callchain_data.ips) {
835     memcpy(p64, callchain_data.ips, callchain_data.ip_nr * sizeof(uint64_t));
836     callchain_data.ips = p64;
837   }
838   p64--;
839   if (!ips.empty()) {
840     callchain_data.ip_nr += 1 + ips.size();
841     *p64 = callchain_data.ip_nr;
842   }
843   CHECK_EQ(callchain_pos, static_cast<size_t>(reinterpret_cast<char*>(p64) - new_binary))
844       << "record time " << time_data.time;
845   if (new_binary != binary_) {
846     UpdateBinary(new_binary);
847   }
848 }
849 
DumpData(size_t indent) const850 void SampleRecord::DumpData(size_t indent) const {
851   PrintIndented(indent, "sample_type: 0x%" PRIx64 "\n", sample_type);
852   if (sample_type & PERF_SAMPLE_IP) {
853     PrintIndented(indent, "ip %p\n", reinterpret_cast<void*>(ip_data.ip));
854   }
855   if (sample_type & PERF_SAMPLE_TID) {
856     PrintIndented(indent, "pid %u, tid %u\n", tid_data.pid, tid_data.tid);
857   }
858   if (sample_type & PERF_SAMPLE_TIME) {
859     PrintIndented(indent, "time %" PRId64 "\n", time_data.time);
860   }
861   if (sample_type & PERF_SAMPLE_ADDR) {
862     PrintIndented(indent, "addr %p\n", reinterpret_cast<void*>(addr_data.addr));
863   }
864   if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) {
865     PrintIndented(indent, "id %" PRId64 "\n", id_data.id);
866   }
867   if (sample_type & PERF_SAMPLE_STREAM_ID) {
868     PrintIndented(indent, "stream_id %" PRId64 "\n", stream_id_data.stream_id);
869   }
870   if (sample_type & PERF_SAMPLE_CPU) {
871     PrintIndented(indent, "cpu %u, res %u\n", cpu_data.cpu, cpu_data.res);
872   }
873   if (sample_type & PERF_SAMPLE_PERIOD) {
874     PrintIndented(indent, "period %" PRId64 "\n", period_data.period);
875   }
876   if (sample_type & PERF_SAMPLE_READ) {
877     PrintIndented(indent, "read nr=%zu\n", read_data.counts.size());
878     if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
879       PrintIndented(indent + 1, "time_enabled %" PRIu64 "\n", read_data.time_enabled);
880     }
881     if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
882       PrintIndented(indent + 1, "time_running %" PRIu64 "\n", read_data.time_running);
883     }
884     for (size_t i = 0; i < read_data.counts.size(); i++) {
885       PrintIndented(indent + 1, "count[%zu] %" PRIu64 "\n", i, read_data.counts[i]);
886       if (read_format & PERF_FORMAT_ID) {
887         PrintIndented(indent + 1, "id[%zu] %" PRIu64 "\n", i, read_data.ids[i]);
888       }
889     }
890   }
891   if (sample_type & PERF_SAMPLE_CALLCHAIN) {
892     PrintIndented(indent, "callchain nr=%" PRIu64 "\n", callchain_data.ip_nr);
893     for (uint64_t i = 0; i < callchain_data.ip_nr; ++i) {
894       PrintIndented(indent + 1, "0x%" PRIx64 "\n", callchain_data.ips[i]);
895     }
896   }
897   if (sample_type & PERF_SAMPLE_RAW) {
898     PrintIndented(indent, "raw size=%zu\n", raw_data.size);
899     const uint32_t* data = reinterpret_cast<const uint32_t*>(raw_data.data);
900     size_t size = raw_data.size / sizeof(uint32_t);
901     for (size_t i = 0; i < size; ++i) {
902       PrintIndented(indent + 1, "0x%08x (%zu)\n", data[i], data[i]);
903     }
904   }
905   if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
906     PrintIndented(indent, "branch_stack nr=%" PRIu64 "\n", branch_stack_data.stack_nr);
907     for (uint64_t i = 0; i < branch_stack_data.stack_nr; ++i) {
908       auto& item = branch_stack_data.stack[i];
909       PrintIndented(indent + 1, "from 0x%" PRIx64 ", to 0x%" PRIx64 ", flags 0x%" PRIx64 "\n",
910                     item.from, item.to, item.flags);
911     }
912   }
913   if (sample_type & PERF_SAMPLE_REGS_USER) {
914     PrintIndented(indent, "user regs: abi=%" PRId64 "\n", regs_user_data.abi);
915     RegSet regs(regs_user_data.abi, regs_user_data.reg_mask, regs_user_data.regs);
916     for (size_t i = 0; i < 64; ++i) {
917       uint64_t value;
918       if (regs.GetRegValue(i, &value)) {
919         PrintIndented(indent + 1, "reg (%s) 0x%016" PRIx64 "\n", GetRegName(i, regs.arch).c_str(),
920                       value);
921       }
922     }
923   }
924   if (sample_type & PERF_SAMPLE_STACK_USER) {
925     PrintIndented(indent, "user stack: size %zu dyn_size %" PRIu64 "\n", stack_user_data.size,
926                   stack_user_data.dyn_size);
927     const uint64_t* p = reinterpret_cast<const uint64_t*>(stack_user_data.data);
928     const uint64_t* end = p + (stack_user_data.size / sizeof(uint64_t));
929     while (p < end) {
930       PrintIndented(indent + 1, "");
931       for (size_t i = 0; i < 4 && p < end; ++i, ++p) {
932         printf(" %016" PRIx64, *p);
933       }
934       printf("\n");
935     }
936     printf("\n");
937   }
938 }
939 
Timestamp() const940 uint64_t SampleRecord::Timestamp() const {
941   return time_data.time;
942 }
Cpu() const943 uint32_t SampleRecord::Cpu() const {
944   return cpu_data.cpu;
945 }
Id() const946 uint64_t SampleRecord::Id() const {
947   return id_data.id;
948 }
949 
AdjustCallChainGeneratedByKernel()950 void SampleRecord::AdjustCallChainGeneratedByKernel() {
951   // The kernel stores return addrs in the callchain, but we want the addrs of call instructions
952   // along the callchain.
953   uint64_t* ips = callchain_data.ips;
954   uint64_t context =
955       header.misc == PERF_RECORD_MISC_KERNEL ? PERF_CONTEXT_KERNEL : PERF_CONTEXT_USER;
956   bool first_frame = true;
957   for (size_t i = 0; i < callchain_data.ip_nr; ++i) {
958     if (ips[i] < PERF_CONTEXT_MAX) {
959       if (first_frame) {
960         first_frame = false;
961       } else {
962         if (ips[i] < 2) {
963           // A wrong ip address, erase it.
964           ips[i] = context;
965         } else {
966           // Here we want to change the return addr to the addr of the previous instruction. We
967           // don't need to find the exact start addr of the previous instruction. A location in
968           // [start_addr_of_call_inst, start_addr_of_next_inst) is enough.
969 #if defined(__arm__) || defined(__aarch64__)
970           // If we are built for arm/aarch64, this may be a callchain of thumb code. For thumb code,
971           // the real instruction addr is (ip & ~1), and ip - 2 can used to hit the address range
972           // of the previous instruction. For non thumb code, any addr in [ip - 4, ip - 1] is fine.
973           ips[i] -= 2;
974 #else
975           ips[i]--;
976 #endif
977         }
978       }
979     } else {
980       context = ips[i];
981     }
982   }
983 }
984 
GetCallChain(size_t * kernel_ip_count) const985 std::vector<uint64_t> SampleRecord::GetCallChain(size_t* kernel_ip_count) const {
986   std::vector<uint64_t> ips;
987   bool in_kernel = InKernel();
988   ips.push_back(ip_data.ip);
989   *kernel_ip_count = in_kernel ? 1 : 0;
990   if ((sample_type & PERF_SAMPLE_CALLCHAIN) == 0) {
991     return ips;
992   }
993   bool first_ip = true;
994   for (uint64_t i = 0; i < callchain_data.ip_nr; ++i) {
995     uint64_t ip = callchain_data.ips[i];
996     if (ip >= PERF_CONTEXT_MAX) {
997       switch (ip) {
998         case PERF_CONTEXT_KERNEL:
999           in_kernel = true;
1000           break;
1001         case PERF_CONTEXT_USER:
1002           in_kernel = false;
1003           break;
1004         default:
1005           LOG(DEBUG) << "Unexpected perf_context in callchain: " << std::hex << ip << std::dec;
1006       }
1007     } else {
1008       if (first_ip) {
1009         first_ip = false;
1010         // Remove duplication with sample ip.
1011         if (ip == ip_data.ip) {
1012           continue;
1013         }
1014       }
1015       ips.push_back(ip);
1016       if (in_kernel) {
1017         ++*kernel_ip_count;
1018       }
1019     }
1020   }
1021   return ips;
1022 }
1023 
Parse(const perf_event_attr & attr,char * p,char * end)1024 bool AuxRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
1025   if (!ParseHeader(p, end)) {
1026     return false;
1027   }
1028   data = reinterpret_cast<DataType*>(p);
1029   CHECK_SIZE(p, end, sizeof(*data));
1030   p += sizeof(*data);
1031   return sample_id.ReadFromBinaryFormat(attr, p, end);
1032 }
1033 
DumpData(size_t indent) const1034 void AuxRecord::DumpData(size_t indent) const {
1035   PrintIndented(indent, "aux_offset %" PRIu64 "\n", data->aux_offset);
1036   PrintIndented(indent, "aux_size %" PRIu64 "\n", data->aux_size);
1037   PrintIndented(indent, "flags 0x%" PRIx64 "\n", data->flags);
1038 }
1039 
Parse(const perf_event_attr & attr,char * p,char * end)1040 bool SwitchRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
1041   if (!ParseHeader(p, end)) {
1042     return false;
1043   }
1044   return sample_id.ReadFromBinaryFormat(attr, p, end);
1045 }
1046 
Parse(const perf_event_attr & attr,char * p,char * end)1047 bool SwitchCpuWideRecord::Parse(const perf_event_attr& attr, char* p, char* end) {
1048   if (!ParseHeader(p, end)) {
1049     return false;
1050   }
1051   CHECK_SIZE(p, end, sizeof(tid_data));
1052   MoveFromBinaryFormat(tid_data, p);
1053   return sample_id.ReadFromBinaryFormat(attr, p, end);
1054 }
1055 
DumpData(size_t indent) const1056 void SwitchCpuWideRecord::DumpData(size_t indent) const {
1057   if (header.misc & PERF_RECORD_MISC_SWITCH_OUT) {
1058     PrintIndented(indent, "next_pid %u, next_tid %u\n", tid_data.pid, tid_data.tid);
1059   } else {
1060     PrintIndented(indent, "prev_pid %u, prev_tid %u\n", tid_data.pid, tid_data.tid);
1061   }
1062 }
1063 
Parse(const perf_event_attr &,char * p,char * end)1064 bool BuildIdRecord::Parse(const perf_event_attr&, char* p, char* end) {
1065   if (!ParseHeader(p, end)) {
1066     return false;
1067   }
1068   size_t size = Align(BUILD_ID_SIZE, 8);
1069   CHECK_SIZE(p, end, sizeof(uint32_t) + size);
1070   MoveFromBinaryFormat(pid, p);
1071   build_id = BuildId(p, BUILD_ID_SIZE);
1072   p += size;
1073   size = Align(SafeStrlen(p, end) + 1, 64);
1074   CHECK_SIZE(p, end, size);
1075   filename = p;
1076   p += size;
1077   return p == end;
1078 }
1079 
DumpData(size_t indent) const1080 void BuildIdRecord::DumpData(size_t indent) const {
1081   PrintIndented(indent, "pid %u\n", pid);
1082   PrintIndented(indent, "build_id %s\n", build_id.ToString().c_str());
1083   PrintIndented(indent, "filename %s\n", filename);
1084 }
1085 
BuildIdRecord(bool in_kernel,uint32_t pid,const BuildId & build_id,const std::string & filename)1086 BuildIdRecord::BuildIdRecord(bool in_kernel, uint32_t pid, const BuildId& build_id,
1087                              const std::string& filename) {
1088   SetTypeAndMisc(PERF_RECORD_BUILD_ID, in_kernel ? PERF_RECORD_MISC_KERNEL : PERF_RECORD_MISC_USER);
1089   this->pid = pid;
1090   this->build_id = build_id;
1091   SetSize(header_size() + sizeof(this->pid) + Align(build_id.Size(), 8) +
1092           Align(filename.size() + 1, 64));
1093   char* new_binary = new char[size()];
1094   char* p = new_binary;
1095   MoveToBinaryFormat(header, p);
1096   MoveToBinaryFormat(this->pid, p);
1097   memcpy(p, build_id.Data(), build_id.Size());
1098   p += Align(build_id.Size(), 8);
1099   this->filename = p;
1100   strcpy(p, filename.c_str());
1101   UpdateBinary(new_binary);
1102 }
1103 
Parse(const perf_event_attr &,char * p,char * end)1104 bool AuxTraceInfoRecord::Parse(const perf_event_attr&, char* p, char* end) {
1105   if (!ParseHeader(p, end)) {
1106     return false;
1107   }
1108   data = reinterpret_cast<DataType*>(p);
1109   CHECK_SIZE(p, end, sizeof(*data));
1110   p += sizeof(*data);
1111   if (data->aux_type != AUX_TYPE_ETM || data->version != 1) {
1112     return false;
1113   }
1114   for (uint32_t i = 0; i < data->nr_cpu; ++i) {
1115     CHECK_SIZE(p, end, sizeof(uint64_t));
1116     uint64_t magic = *reinterpret_cast<uint64_t*>(p);
1117     if (magic == MAGIC_ETM4) {
1118       CHECK_SIZE(p, end, sizeof(ETM4Info));
1119       p += sizeof(ETM4Info);
1120     } else if (magic == MAGIC_ETE) {
1121       CHECK_SIZE(p, end, sizeof(ETEInfo));
1122       p += sizeof(ETEInfo);
1123     } else {
1124       return false;
1125     }
1126   }
1127   return p == end;
1128 }
1129 
AuxTraceInfoRecord(const DataType & data,const std::vector<ETEInfo> & ete_info)1130 AuxTraceInfoRecord::AuxTraceInfoRecord(const DataType& data, const std::vector<ETEInfo>& ete_info) {
1131   SetTypeAndMisc(PERF_RECORD_AUXTRACE_INFO, 0);
1132 
1133   uint32_t size = header_size() + sizeof(DataType);
1134   for (auto& ete : ete_info) {
1135     size += (ete.trcdevarch == 0) ? sizeof(ETM4Info) : sizeof(ETEInfo);
1136   }
1137   SetSize(size);
1138   char* new_binary = new char[size];
1139   char* p = new_binary;
1140   MoveToBinaryFormat(header, p);
1141   this->data = reinterpret_cast<DataType*>(p);
1142   MoveToBinaryFormat(data, p);
1143   for (auto& ete : ete_info) {
1144     if (ete.trcdevarch == 0) {
1145       ETM4Info etm4;
1146       static_assert(sizeof(ETM4Info) + sizeof(uint64_t) == sizeof(ETEInfo));
1147       memcpy(&etm4, &ete, sizeof(ETM4Info));
1148       MoveToBinaryFormat(etm4, p);
1149     } else {
1150       MoveToBinaryFormat(ete, p);
1151     }
1152   }
1153   UpdateBinary(new_binary);
1154 }
1155 
DumpData(size_t indent) const1156 void AuxTraceInfoRecord::DumpData(size_t indent) const {
1157   PrintIndented(indent, "aux_type %u\n", data->aux_type);
1158   PrintIndented(indent, "version %" PRIu64 "\n", data->version);
1159   PrintIndented(indent, "nr_cpu %u\n", data->nr_cpu);
1160   PrintIndented(indent, "pmu_type %u\n", data->pmu_type);
1161   PrintIndented(indent, "snapshot %" PRIu64 "\n", data->snapshot);
1162   indent++;
1163   uint64_t* info = data->info;
1164 
1165   for (int i = 0; i < data->nr_cpu; i++) {
1166     if (info[0] == MAGIC_ETM4) {
1167       ETM4Info& e = *reinterpret_cast<ETM4Info*>(info);
1168       PrintIndented(indent, "magic 0x%" PRIx64 "\n", e.magic);
1169       PrintIndented(indent, "cpu %" PRIu64 "\n", e.cpu);
1170       PrintIndented(indent, "nrtrcparams %" PRIu64 "\n", e.nrtrcparams);
1171       PrintIndented(indent, "trcconfigr 0x%" PRIx64 "\n", e.trcconfigr);
1172       PrintIndented(indent, "trctraceidr 0x%" PRIx64 "\n", e.trctraceidr);
1173       PrintIndented(indent, "trcidr0 0x%" PRIx64 "\n", e.trcidr0);
1174       PrintIndented(indent, "trcidr1 0x%" PRIx64 "\n", e.trcidr1);
1175       PrintIndented(indent, "trcidr2 0x%" PRIx64 "\n", e.trcidr2);
1176       PrintIndented(indent, "trcidr8 0x%" PRIx64 "\n", e.trcidr8);
1177       PrintIndented(indent, "trcauthstatus 0x%" PRIx64 "\n", e.trcauthstatus);
1178       info = reinterpret_cast<uint64_t*>(&e + 1);
1179     } else {
1180       CHECK_EQ(info[0], MAGIC_ETE);
1181       ETEInfo& e = *reinterpret_cast<ETEInfo*>(info);
1182       PrintIndented(indent, "magic 0x%" PRIx64 "\n", e.magic);
1183       PrintIndented(indent, "cpu %" PRIu64 "\n", e.cpu);
1184       PrintIndented(indent, "nrtrcparams %" PRIu64 "\n", e.nrtrcparams);
1185       PrintIndented(indent, "trcconfigr 0x%" PRIx64 "\n", e.trcconfigr);
1186       PrintIndented(indent, "trctraceidr 0x%" PRIx64 "\n", e.trctraceidr);
1187       PrintIndented(indent, "trcidr0 0x%" PRIx64 "\n", e.trcidr0);
1188       PrintIndented(indent, "trcidr1 0x%" PRIx64 "\n", e.trcidr1);
1189       PrintIndented(indent, "trcidr2 0x%" PRIx64 "\n", e.trcidr2);
1190       PrintIndented(indent, "trcidr8 0x%" PRIx64 "\n", e.trcidr8);
1191       PrintIndented(indent, "trcauthstatus 0x%" PRIx64 "\n", e.trcauthstatus);
1192       PrintIndented(indent, "trcdevarch 0x%" PRIx64 "\n", e.trcdevarch);
1193       info = reinterpret_cast<uint64_t*>(&e + 1);
1194     }
1195   }
1196 }
1197 
Parse(const perf_event_attr &,char * p,char * end)1198 bool AuxTraceRecord::Parse(const perf_event_attr&, char* p, char* end) {
1199   if (!ParseHeader(p, end)) {
1200     return false;
1201   }
1202   data = reinterpret_cast<DataType*>(p);
1203   CHECK_SIZE(p, end, sizeof(*data));
1204   p += sizeof(*data);
1205   return p == end;
1206 }
1207 
AuxTraceRecord(uint64_t aux_size,uint64_t offset,uint32_t idx,uint32_t tid,uint32_t cpu)1208 AuxTraceRecord::AuxTraceRecord(uint64_t aux_size, uint64_t offset, uint32_t idx, uint32_t tid,
1209                                uint32_t cpu) {
1210   SetTypeAndMisc(PERF_RECORD_AUXTRACE, 0);
1211   SetSize(header_size() + sizeof(DataType));
1212   char* new_binary = new char[size()];
1213   char* p = new_binary;
1214   MoveToBinaryFormat(header, p);
1215   data = reinterpret_cast<DataType*>(p);
1216   data->aux_size = aux_size;
1217   data->offset = offset;
1218   data->reserved0 = 0;
1219   data->idx = idx;
1220   data->tid = tid;
1221   data->cpu = cpu;
1222   data->reserved1 = 0;
1223   UpdateBinary(new_binary);
1224 }
1225 
DumpData(size_t indent) const1226 void AuxTraceRecord::DumpData(size_t indent) const {
1227   PrintIndented(indent, "aux_size %" PRIu64 "\n", data->aux_size);
1228   PrintIndented(indent, "offset %" PRIu64 "\n", data->offset);
1229   PrintIndented(indent, "idx %u\n", data->idx);
1230   PrintIndented(indent, "tid %u\n", data->tid);
1231   PrintIndented(indent, "cpu %u\n", data->cpu);
1232   PrintIndented(indent, "location.file_offset %" PRIu64 "\n", location.file_offset);
1233 }
1234 
Parse(const perf_event_attr &,char * p,char * end)1235 bool KernelSymbolRecord::Parse(const perf_event_attr&, char* p, char* end) {
1236   if (!ParseHeader(p, end)) {
1237     return false;
1238   }
1239   CHECK_SIZE(p, end, sizeof(uint32_t));
1240   MoveFromBinaryFormat(kallsyms_size, p);
1241   size_t size = Align(kallsyms_size, 8);
1242   CHECK_SIZE(p, end, size);
1243   kallsyms = p;
1244   p += size;
1245   return p == end;
1246 }
1247 
DumpData(size_t indent) const1248 void KernelSymbolRecord::DumpData(size_t indent) const {
1249   PrintIndented(indent, "kallsyms: %s\n", std::string(kallsyms, kallsyms + kallsyms_size).c_str());
1250 }
1251 
KernelSymbolRecord(const std::string & kallsyms)1252 KernelSymbolRecord::KernelSymbolRecord(const std::string& kallsyms) {
1253   SetTypeAndMisc(SIMPLE_PERF_RECORD_KERNEL_SYMBOL, 0);
1254   kallsyms_size = kallsyms.size();
1255   SetSize(header_size() + 4 + Align(kallsyms.size(), 8));
1256   char* new_binary = new char[size()];
1257   char* p = new_binary;
1258   MoveToBinaryFormat(header, p);
1259   MoveToBinaryFormat(kallsyms_size, p);
1260   this->kallsyms = p;
1261   memcpy(p, kallsyms.data(), kallsyms_size);
1262   UpdateBinary(new_binary);
1263 }
1264 
Parse(const perf_event_attr &,char * p,char * end)1265 bool DsoRecord::Parse(const perf_event_attr&, char* p, char* end) {
1266   if (!ParseHeader(p, end)) {
1267     return false;
1268   }
1269   CHECK_SIZE_U64(p, end, 3);
1270   MoveFromBinaryFormat(dso_type, p);
1271   MoveFromBinaryFormat(dso_id, p);
1272   MoveFromBinaryFormat(min_vaddr, p);
1273   size_t size = Align(SafeStrlen(p, end) + 1, 8);
1274   dso_name = p;
1275   p += size;
1276   return p == end;
1277 }
1278 
DsoRecord(uint64_t dso_type,uint64_t dso_id,const std::string & dso_name,uint64_t min_vaddr)1279 DsoRecord::DsoRecord(uint64_t dso_type, uint64_t dso_id, const std::string& dso_name,
1280                      uint64_t min_vaddr) {
1281   SetTypeAndMisc(SIMPLE_PERF_RECORD_DSO, 0);
1282   this->dso_type = dso_type;
1283   this->dso_id = dso_id;
1284   this->min_vaddr = min_vaddr;
1285   SetSize(header_size() + 3 * sizeof(uint64_t) + Align(dso_name.size() + 1, 8));
1286   char* new_binary = new char[size()];
1287   char* p = new_binary;
1288   MoveToBinaryFormat(header, p);
1289   MoveToBinaryFormat(dso_type, p);
1290   MoveToBinaryFormat(dso_id, p);
1291   MoveToBinaryFormat(min_vaddr, p);
1292   this->dso_name = p;
1293   strcpy(p, dso_name.c_str());
1294   UpdateBinary(new_binary);
1295 }
1296 
DumpData(size_t indent) const1297 void DsoRecord::DumpData(size_t indent) const {
1298   PrintIndented(indent, "dso_type: %s(%" PRIu64 ")\n",
1299                 DsoTypeToString(static_cast<DsoType>(dso_type)), dso_type);
1300   PrintIndented(indent, "dso_id: %" PRIu64 "\n", dso_id);
1301   PrintIndented(indent, "min_vaddr: 0x%" PRIx64 "\n", min_vaddr);
1302   PrintIndented(indent, "dso_name: %s\n", dso_name);
1303 }
1304 
Parse(const perf_event_attr &,char * p,char * end)1305 bool SymbolRecord::Parse(const perf_event_attr&, char* p, char* end) {
1306   if (!ParseHeader(p, end)) {
1307     return false;
1308   }
1309   CHECK_SIZE_U64(p, end, 3);
1310   MoveFromBinaryFormat(addr, p);
1311   MoveFromBinaryFormat(len, p);
1312   MoveFromBinaryFormat(dso_id, p);
1313   size_t size = Align(SafeStrlen(p, end) + 1, 8);
1314   name = p;
1315   p += size;
1316   return p == end;
1317 }
1318 
SymbolRecord(uint64_t addr,uint64_t len,const std::string & name,uint64_t dso_id)1319 SymbolRecord::SymbolRecord(uint64_t addr, uint64_t len, const std::string& name, uint64_t dso_id) {
1320   SetTypeAndMisc(SIMPLE_PERF_RECORD_SYMBOL, 0);
1321   this->addr = addr;
1322   this->len = len;
1323   this->dso_id = dso_id;
1324   SetSize(header_size() + 3 * sizeof(uint64_t) + Align(name.size() + 1, 8));
1325   char* new_binary = new char[size()];
1326   char* p = new_binary;
1327   MoveToBinaryFormat(header, p);
1328   MoveToBinaryFormat(addr, p);
1329   MoveToBinaryFormat(len, p);
1330   MoveToBinaryFormat(dso_id, p);
1331   this->name = p;
1332   strcpy(p, name.c_str());
1333   UpdateBinary(new_binary);
1334 }
1335 
DumpData(size_t indent) const1336 void SymbolRecord::DumpData(size_t indent) const {
1337   PrintIndented(indent, "name: %s\n", name);
1338   PrintIndented(indent, "addr: 0x%" PRIx64 "\n", addr);
1339   PrintIndented(indent, "len: 0x%" PRIx64 "\n", len);
1340   PrintIndented(indent, "dso_id: %" PRIu64 "\n", dso_id);
1341 }
1342 
Parse(const perf_event_attr &,char * p,char * end)1343 bool TracingDataRecord::Parse(const perf_event_attr&, char* p, char* end) {
1344   if (!ParseHeader(p, end)) {
1345     return false;
1346   }
1347   CHECK_SIZE(p, end, sizeof(uint32_t));
1348   MoveFromBinaryFormat(data_size, p);
1349   size_t size = Align(data_size, 64);
1350   CHECK_SIZE(p, end, size);
1351   data = p;
1352   p += size;
1353   return p == end;
1354 }
1355 
TracingDataRecord(const std::vector<char> & tracing_data)1356 TracingDataRecord::TracingDataRecord(const std::vector<char>& tracing_data) {
1357   SetTypeAndMisc(SIMPLE_PERF_RECORD_TRACING_DATA, 0);
1358   data_size = tracing_data.size();
1359   SetSize(header_size() + sizeof(uint32_t) + Align(tracing_data.size(), 64));
1360   char* new_binary = new char[size()];
1361   char* p = new_binary;
1362   MoveToBinaryFormat(header, p);
1363   MoveToBinaryFormat(data_size, p);
1364   data = p;
1365   memcpy(p, tracing_data.data(), data_size);
1366   UpdateBinary(new_binary);
1367 }
1368 
DumpData(size_t indent) const1369 void TracingDataRecord::DumpData(size_t indent) const {
1370   auto tracing = Tracing::Create(std::vector<char>(data, data + data_size));
1371   if (tracing) {
1372     tracing->Dump(indent);
1373   }
1374 }
1375 
Parse(const perf_event_attr &,char * p,char * end)1376 bool EventIdRecord::Parse(const perf_event_attr&, char* p, char* end) {
1377   if (!ParseHeader(p, end)) {
1378     return false;
1379   }
1380   CHECK_SIZE_U64(p, end, 1);
1381   MoveFromBinaryFormat(count, p);
1382   data = reinterpret_cast<const EventIdData*>(p);
1383   CHECK_SIZE(p, end, sizeof(data[0]) * count);
1384   p += sizeof(data[0]) * count;
1385   return p == end;
1386 }
1387 
EventIdRecord(const std::vector<uint64_t> & data)1388 EventIdRecord::EventIdRecord(const std::vector<uint64_t>& data) {
1389   SetTypeAndMisc(SIMPLE_PERF_RECORD_EVENT_ID, 0);
1390   SetSize(header_size() + sizeof(uint64_t) * (1 + data.size()));
1391   char* new_binary = new char[size()];
1392   char* p = new_binary;
1393   MoveToBinaryFormat(header, p);
1394   count = data.size() / 2;
1395   MoveToBinaryFormat(count, p);
1396   this->data = reinterpret_cast<EventIdData*>(p);
1397   memcpy(p, data.data(), sizeof(uint64_t) * data.size());
1398   UpdateBinary(new_binary);
1399 }
1400 
DumpData(size_t indent) const1401 void EventIdRecord::DumpData(size_t indent) const {
1402   PrintIndented(indent, "count: %" PRIu64 "\n", count);
1403   for (size_t i = 0; i < count; ++i) {
1404     PrintIndented(indent, "attr_id[%" PRIu64 "]: %" PRIu64 "\n", i, data[i].attr_id);
1405     PrintIndented(indent, "event_id[%" PRIu64 "]: %" PRIu64 "\n", i, data[i].event_id);
1406   }
1407 }
1408 
Parse(const perf_event_attr &,char * p,char * end)1409 bool CallChainRecord::Parse(const perf_event_attr&, char* p, char* end) {
1410   if (!ParseHeader(p, end)) {
1411     return false;
1412   }
1413   CHECK_SIZE_U64(p, end, 4);
1414   MoveFromBinaryFormat(pid, p);
1415   MoveFromBinaryFormat(tid, p);
1416   MoveFromBinaryFormat(chain_type, p);
1417   MoveFromBinaryFormat(time, p);
1418   MoveFromBinaryFormat(ip_nr, p);
1419   CHECK_SIZE_U64(p, end, ip_nr * 2);
1420   ips = reinterpret_cast<uint64_t*>(p);
1421   p += ip_nr * sizeof(uint64_t);
1422   sps = reinterpret_cast<uint64_t*>(p);
1423   p += ip_nr * sizeof(uint64_t);
1424   return p == end;
1425 }
1426 
CallChainRecord(pid_t pid,pid_t tid,CallChainJoiner::ChainType type,uint64_t time,const std::vector<uint64_t> & ips,const std::vector<uint64_t> & sps)1427 CallChainRecord::CallChainRecord(pid_t pid, pid_t tid, CallChainJoiner::ChainType type,
1428                                  uint64_t time, const std::vector<uint64_t>& ips,
1429                                  const std::vector<uint64_t>& sps) {
1430   CHECK_EQ(ips.size(), sps.size());
1431   SetTypeAndMisc(SIMPLE_PERF_RECORD_CALLCHAIN, 0);
1432   this->pid = pid;
1433   this->tid = tid;
1434   this->chain_type = static_cast<int>(type);
1435   this->time = time;
1436   this->ip_nr = ips.size();
1437   SetSize(header_size() + (4 + ips.size() * 2) * sizeof(uint64_t));
1438   char* new_binary = new char[size()];
1439   char* p = new_binary;
1440   MoveToBinaryFormat(header, p);
1441   MoveToBinaryFormat(this->pid, p);
1442   MoveToBinaryFormat(this->tid, p);
1443   MoveToBinaryFormat(this->chain_type, p);
1444   MoveToBinaryFormat(this->time, p);
1445   MoveToBinaryFormat(this->ip_nr, p);
1446   this->ips = reinterpret_cast<uint64_t*>(p);
1447   MoveToBinaryFormat(ips.data(), ips.size(), p);
1448   this->sps = reinterpret_cast<uint64_t*>(p);
1449   MoveToBinaryFormat(sps.data(), sps.size(), p);
1450   UpdateBinary(new_binary);
1451 }
1452 
DumpData(size_t indent) const1453 void CallChainRecord::DumpData(size_t indent) const {
1454   const char* type_name = "";
1455   switch (chain_type) {
1456     case CallChainJoiner::ORIGINAL_OFFLINE:
1457       type_name = "ORIGINAL_OFFLINE";
1458       break;
1459     case CallChainJoiner::ORIGINAL_REMOTE:
1460       type_name = "ORIGINAL_REMOTE";
1461       break;
1462     case CallChainJoiner::JOINED_OFFLINE:
1463       type_name = "JOINED_OFFLINE";
1464       break;
1465     case CallChainJoiner::JOINED_REMOTE:
1466       type_name = "JOINED_REMOTE";
1467       break;
1468   }
1469   PrintIndented(indent, "pid %u\n", pid);
1470   PrintIndented(indent, "tid %u\n", tid);
1471   PrintIndented(indent, "chain_type %s\n", type_name);
1472   PrintIndented(indent, "time %" PRIu64 "\n", time);
1473   PrintIndented(indent, "ip_nr %" PRIu64 "\n", ip_nr);
1474   for (size_t i = 0; i < ip_nr; ++i) {
1475     PrintIndented(indent + 1, "ip 0x%" PRIx64 ", sp 0x%" PRIx64 "\n", ips[i], sps[i]);
1476   }
1477 }
1478 
Parse(const perf_event_attr &,char * p,char * end)1479 bool UnwindingResultRecord::Parse(const perf_event_attr&, char* p, char* end) {
1480   if (!ParseHeader(p, end)) {
1481     return false;
1482   }
1483   CHECK_SIZE_U64(p, end, 8);
1484   MoveFromBinaryFormat(time, p);
1485   MoveFromBinaryFormat(unwinding_result.used_time, p);
1486   MoveFromBinaryFormat(unwinding_result.error_code, p);
1487   MoveFromBinaryFormat(unwinding_result.error_addr, p);
1488   MoveFromBinaryFormat(unwinding_result.stack_start, p);
1489   MoveFromBinaryFormat(unwinding_result.stack_end, p);
1490 
1491   // regs_user_data
1492   MoveFromBinaryFormat(regs_user_data.abi, p);
1493   MoveFromBinaryFormat(regs_user_data.reg_mask, p);
1494   size_t bit_nr = __builtin_popcountll(regs_user_data.reg_mask);
1495   CHECK_SIZE_U64(p, end, bit_nr);
1496   regs_user_data.reg_nr = bit_nr;
1497   regs_user_data.regs = reinterpret_cast<uint64_t*>(p);
1498   p += bit_nr * sizeof(uint64_t);
1499 
1500   // stack_user_data
1501   CHECK_SIZE_U64(p, end, 1);
1502   MoveFromBinaryFormat(stack_user_data.size, p);
1503   if (stack_user_data.size == 0) {
1504     stack_user_data.dyn_size = 0;
1505   } else {
1506     CHECK_SIZE(p, end, stack_user_data.size + sizeof(uint64_t));
1507     stack_user_data.data = p;
1508     p += stack_user_data.size;
1509     MoveFromBinaryFormat(stack_user_data.dyn_size, p);
1510   }
1511 
1512   // callchain
1513   if (p < end) {
1514     CHECK_SIZE_U64(p, end, 1);
1515     MoveFromBinaryFormat(callchain.length, p);
1516     CHECK_SIZE_U64(p, end, callchain.length * 2);
1517     callchain.ips = reinterpret_cast<uint64_t*>(p);
1518     p += callchain.length * sizeof(uint64_t);
1519     callchain.sps = reinterpret_cast<uint64_t*>(p);
1520     p += callchain.length * sizeof(uint64_t);
1521   }
1522   return true;
1523 }
1524 
UnwindingResultRecord(uint64_t time,const UnwindingResult & unwinding_result,const PerfSampleRegsUserType & regs_user_data,const PerfSampleStackUserType & stack_user_data,const std::vector<uint64_t> & ips,const std::vector<uint64_t> & sps)1525 UnwindingResultRecord::UnwindingResultRecord(uint64_t time, const UnwindingResult& unwinding_result,
1526                                              const PerfSampleRegsUserType& regs_user_data,
1527                                              const PerfSampleStackUserType& stack_user_data,
1528                                              const std::vector<uint64_t>& ips,
1529                                              const std::vector<uint64_t>& sps) {
1530   SetTypeAndMisc(SIMPLE_PERF_RECORD_UNWINDING_RESULT, 0);
1531   uint32_t size = header_size() + 6 * sizeof(uint64_t);
1532   size += (2 + regs_user_data.reg_nr) * sizeof(uint64_t);
1533   size +=
1534       stack_user_data.size == 0 ? sizeof(uint64_t) : (2 * sizeof(uint64_t) + stack_user_data.size);
1535   CHECK_EQ(ips.size(), sps.size());
1536   size += (1 + ips.size() * 2) * sizeof(uint64_t);
1537   SetSize(size);
1538   this->time = time;
1539   this->unwinding_result = unwinding_result;
1540   char* new_binary = new char[size];
1541   char* p = new_binary;
1542   MoveToBinaryFormat(header, p);
1543   MoveToBinaryFormat(this->time, p);
1544   MoveToBinaryFormat(unwinding_result.used_time, p);
1545   MoveToBinaryFormat(unwinding_result.error_code, p);
1546   MoveToBinaryFormat(unwinding_result.error_addr, p);
1547   MoveToBinaryFormat(unwinding_result.stack_start, p);
1548   MoveToBinaryFormat(unwinding_result.stack_end, p);
1549   MoveToBinaryFormat(regs_user_data.abi, p);
1550   MoveToBinaryFormat(regs_user_data.reg_mask, p);
1551   if (regs_user_data.reg_nr > 0) {
1552     MoveToBinaryFormat(regs_user_data.regs, regs_user_data.reg_nr, p);
1553   }
1554   MoveToBinaryFormat(stack_user_data.size, p);
1555   if (stack_user_data.size > 0) {
1556     MoveToBinaryFormat(stack_user_data.data, stack_user_data.size, p);
1557     MoveToBinaryFormat(stack_user_data.dyn_size, p);
1558   }
1559   MoveToBinaryFormat(static_cast<uint64_t>(ips.size()), p);
1560   MoveToBinaryFormat(ips.data(), ips.size(), p);
1561   MoveToBinaryFormat(sps.data(), sps.size(), p);
1562   CHECK_EQ(p, new_binary + size);
1563   UpdateBinary(new_binary);
1564 }
1565 
DumpData(size_t indent) const1566 void UnwindingResultRecord::DumpData(size_t indent) const {
1567   PrintIndented(indent, "time %" PRIu64 "\n", time);
1568   PrintIndented(indent, "used_time %" PRIu64 "\n", unwinding_result.used_time);
1569   PrintIndented(indent, "error_code %" PRIu64 "\n", unwinding_result.error_code);
1570   PrintIndented(indent, "error_addr 0x%" PRIx64 "\n", unwinding_result.error_addr);
1571   PrintIndented(indent, "stack_start 0x%" PRIx64 "\n", unwinding_result.stack_start);
1572   PrintIndented(indent, "stack_end 0x%" PRIx64 "\n", unwinding_result.stack_end);
1573   if (regs_user_data.reg_nr > 0) {
1574     PrintIndented(indent, "user regs: abi=%" PRId64 "\n", regs_user_data.abi);
1575     RegSet regs(regs_user_data.abi, regs_user_data.reg_mask, regs_user_data.regs);
1576     for (size_t i = 0; i < 64; ++i) {
1577       uint64_t value;
1578       if (regs.GetRegValue(i, &value)) {
1579         PrintIndented(indent + 1, "reg (%s) 0x%016" PRIx64 "\n", GetRegName(i, regs.arch).c_str(),
1580                       value);
1581       }
1582     }
1583   }
1584   if (stack_user_data.size > 0) {
1585     PrintIndented(indent, "user stack: size %zu dyn_size %" PRIu64 "\n", stack_user_data.size,
1586                   stack_user_data.dyn_size);
1587     const uint64_t* p = reinterpret_cast<const uint64_t*>(stack_user_data.data);
1588     const uint64_t* end = p + (stack_user_data.size / sizeof(uint64_t));
1589     while (p < end) {
1590       PrintIndented(indent + 1, "");
1591       for (size_t i = 0; i < 4 && p < end; ++i, ++p) {
1592         printf(" %016" PRIx64, *p);
1593       }
1594       printf("\n");
1595     }
1596     printf("\n");
1597   }
1598   if (callchain.length > 0) {
1599     PrintIndented(indent, "callchain length=%" PRIu64 ":\n", callchain.length);
1600     for (uint64_t i = 0; i < callchain.length; i++) {
1601       PrintIndented(indent + 1, "ip_%" PRIu64 ": 0x%" PRIx64 "\n", i + 1, callchain.ips[i]);
1602       PrintIndented(indent + 1, "sp_%" PRIu64 ": 0x%" PRIx64 "\n", i + 1, callchain.sps[i]);
1603     }
1604   }
1605 }
1606 
DebugRecord(uint64_t time,const std::string & s)1607 DebugRecord::DebugRecord(uint64_t time, const std::string& s) {
1608   SetTypeAndMisc(SIMPLE_PERF_RECORD_DEBUG, 0);
1609   uint32_t size = header_size() + sizeof(uint64_t) + Align(strlen(s.c_str()) + 1, sizeof(uint64_t));
1610   SetSize(size);
1611   char* new_binary = new char[size];
1612   char* p = new_binary;
1613   MoveToBinaryFormat(header, p);
1614   MoveToBinaryFormat(time, p);
1615   this->time = time;
1616   this->s = p;
1617   MoveToBinaryFormat(s.c_str(), strlen(s.c_str()) + 1, p);
1618   CHECK_LE(p, new_binary + size);
1619   UpdateBinary(new_binary);
1620 }
1621 
Parse(const perf_event_attr &,char * p,char * end)1622 bool DebugRecord::Parse(const perf_event_attr&, char* p, char* end) {
1623   if (!ParseHeader(p, end)) {
1624     return false;
1625   }
1626   CHECK_SIZE_U64(p, end, 1);
1627   MoveFromBinaryFormat(time, p);
1628   if (memchr(p, '\0', end - p) == nullptr) {
1629     return false;
1630   }
1631   s = p;
1632   return true;
1633 }
1634 
DumpData(size_t indent) const1635 void DebugRecord::DumpData(size_t indent) const {
1636   PrintIndented(indent, "s %s\n", s);
1637 }
1638 
Parse(const perf_event_attr &,char * p,char * end)1639 bool UnknownRecord::Parse(const perf_event_attr&, char* p, char* end) {
1640   if (!ParseHeader(p, end)) {
1641     return false;
1642   }
1643   data = p;
1644   return true;
1645 }
1646 
DumpData(size_t) const1647 void UnknownRecord::DumpData(size_t) const {}
1648 
ReadRecordFromBuffer(const perf_event_attr & attr,uint32_t type,char * p,char * end)1649 std::unique_ptr<Record> ReadRecordFromBuffer(const perf_event_attr& attr, uint32_t type, char* p,
1650                                              char* end) {
1651   std::unique_ptr<Record> r;
1652   switch (type) {
1653     case PERF_RECORD_MMAP:
1654       r.reset(new MmapRecord);
1655       break;
1656     case PERF_RECORD_MMAP2:
1657       r.reset(new Mmap2Record);
1658       break;
1659     case PERF_RECORD_COMM:
1660       r.reset(new CommRecord);
1661       break;
1662     case PERF_RECORD_EXIT:
1663       r.reset(new ExitRecord);
1664       break;
1665     case PERF_RECORD_FORK:
1666       r.reset(new ForkRecord);
1667       break;
1668     case PERF_RECORD_LOST:
1669       r.reset(new LostRecord);
1670       break;
1671     case PERF_RECORD_SAMPLE:
1672       r.reset(new SampleRecord);
1673       break;
1674     case PERF_RECORD_AUX:
1675       r.reset(new AuxRecord);
1676       break;
1677     case PERF_RECORD_SWITCH:
1678       r.reset(new SwitchRecord);
1679       break;
1680     case PERF_RECORD_SWITCH_CPU_WIDE:
1681       r.reset(new SwitchCpuWideRecord);
1682       break;
1683     case PERF_RECORD_TRACING_DATA:
1684       r.reset(new TracingDataRecord);
1685       break;
1686     case PERF_RECORD_AUXTRACE_INFO:
1687       r.reset(new AuxTraceInfoRecord);
1688       break;
1689     case PERF_RECORD_AUXTRACE:
1690       r.reset(new AuxTraceRecord);
1691       break;
1692     case SIMPLE_PERF_RECORD_KERNEL_SYMBOL:
1693       r.reset(new KernelSymbolRecord);
1694       break;
1695     case SIMPLE_PERF_RECORD_DSO:
1696       r.reset(new DsoRecord);
1697       break;
1698     case SIMPLE_PERF_RECORD_SYMBOL:
1699       r.reset(new SymbolRecord);
1700       break;
1701     case SIMPLE_PERF_RECORD_EVENT_ID:
1702       r.reset(new EventIdRecord);
1703       break;
1704     case SIMPLE_PERF_RECORD_CALLCHAIN:
1705       r.reset(new CallChainRecord);
1706       break;
1707     case SIMPLE_PERF_RECORD_UNWINDING_RESULT:
1708       r.reset(new UnwindingResultRecord);
1709       break;
1710     case SIMPLE_PERF_RECORD_TRACING_DATA:
1711       r.reset(new TracingDataRecord);
1712       break;
1713     case SIMPLE_PERF_RECORD_DEBUG:
1714       r.reset(new DebugRecord);
1715       break;
1716     default:
1717       r.reset(new UnknownRecord);
1718       break;
1719   }
1720   if (UNLIKELY(!r->Parse(attr, p, end))) {
1721     LOG(ERROR) << "failed to parse record " << RecordTypeToString(type);
1722     return nullptr;
1723   }
1724   return r;
1725 }
1726 
ReadRecordsFromBuffer(const perf_event_attr & attr,char * buf,size_t buf_size)1727 std::vector<std::unique_ptr<Record>> ReadRecordsFromBuffer(const perf_event_attr& attr, char* buf,
1728                                                            size_t buf_size) {
1729   std::vector<std::unique_ptr<Record>> result;
1730   char* p = buf;
1731   char* end = buf + buf_size;
1732   while (p < end) {
1733     std::unique_ptr<Record> r = ReadRecordFromBuffer(attr, p, end);
1734     if (!r) {
1735       return {};
1736     }
1737     p += r->size();
1738     result.emplace_back(std::move(r));
1739   }
1740   return result;
1741 }
1742 
ReadRecordFromBuffer(const perf_event_attr & attr,char * p,char * end)1743 std::unique_ptr<Record> ReadRecordFromBuffer(const perf_event_attr& attr, char* p, char* end) {
1744   auto header = reinterpret_cast<const perf_event_header*>(p);
1745   return ReadRecordFromBuffer(attr, header->type, p, end);
1746 }
1747 
1748 }  // namespace simpleperf
1749