OSDN Git Service

Merge "simpleperf: fix two errors."
[android-x86/system-extras.git] / simpleperf / record_file_reader.cpp
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_file.h"
18
19 #include <fcntl.h>
20 #include <string.h>
21 #include <set>
22 #include <vector>
23
24 #include <android-base/logging.h>
25
26 #include "event_attr.h"
27 #include "record.h"
28 #include "utils.h"
29
30 using namespace PerfFileFormat;
31
32 std::unique_ptr<RecordFileReader> RecordFileReader::CreateInstance(const std::string& filename) {
33   std::string mode = std::string("rb") + CLOSE_ON_EXEC_MODE;
34   FILE* fp = fopen(filename.c_str(), mode.c_str());
35   if (fp == nullptr) {
36     PLOG(ERROR) << "failed to open record file '" << filename << "'";
37     return nullptr;
38   }
39   auto reader = std::unique_ptr<RecordFileReader>(new RecordFileReader(filename, fp));
40   if (!reader->ReadHeader() || !reader->ReadAttrSection() ||
41       !reader->ReadFeatureSectionDescriptors()) {
42     return nullptr;
43   }
44   return reader;
45 }
46
47 RecordFileReader::RecordFileReader(const std::string& filename, FILE* fp)
48     : filename_(filename), record_fp_(fp), event_id_pos_in_sample_records_(0),
49       event_id_reverse_pos_in_non_sample_records_(0) {
50 }
51
52 RecordFileReader::~RecordFileReader() {
53   if (record_fp_ != nullptr) {
54     Close();
55   }
56 }
57
58 bool RecordFileReader::Close() {
59   bool result = true;
60   if (fclose(record_fp_) != 0) {
61     PLOG(ERROR) << "failed to close record file '" << filename_ << "'";
62     result = false;
63   }
64   record_fp_ = nullptr;
65   return result;
66 }
67
68 bool RecordFileReader::ReadHeader() {
69   return Read(&header_, sizeof(header_));
70 }
71
72 bool RecordFileReader::ReadAttrSection() {
73   size_t attr_count = header_.attrs.size / header_.attr_size;
74   if (header_.attr_size != sizeof(FileAttr)) {
75     LOG(DEBUG) << "attr size (" << header_.attr_size << ") in " << filename_
76                  << " doesn't match expected size (" << sizeof(FileAttr) << ")";
77   }
78   if (attr_count == 0) {
79     LOG(ERROR) << "no attr in file " << filename_;
80     return false;
81   }
82   if (fseek(record_fp_, header_.attrs.offset, SEEK_SET) != 0) {
83     PLOG(ERROR) << "fseek() failed";
84     return false;
85   }
86   for (size_t i = 0; i < attr_count; ++i) {
87     std::vector<char> buf(header_.attr_size);
88     if (!Read(buf.data(), buf.size())) {
89       return false;
90     }
91     // The size of perf_event_attr is changing between different linux kernel versions.
92     // Make sure we copy correct data to memory.
93     FileAttr attr;
94     memset(&attr, 0, sizeof(attr));
95     size_t section_desc_size = sizeof(attr.ids);
96     size_t perf_event_attr_size = header_.attr_size - section_desc_size;
97     memcpy(&attr.attr, &buf[0], std::min(sizeof(attr.attr), perf_event_attr_size));
98     memcpy(&attr.ids, &buf[perf_event_attr_size], section_desc_size);
99     file_attrs_.push_back(attr);
100   }
101   if (file_attrs_.size() > 1) {
102     std::vector<perf_event_attr> attrs;
103     for (const auto& file_attr : file_attrs_) {
104       attrs.push_back(file_attr.attr);
105     }
106     if (!GetCommonEventIdPositionsForAttrs(attrs, &event_id_pos_in_sample_records_,
107                                                &event_id_reverse_pos_in_non_sample_records_)) {
108       return false;
109     }
110   }
111   for (size_t i = 0; i < file_attrs_.size(); ++i) {
112     std::vector<uint64_t> ids;
113     if (!ReadIdsForAttr(file_attrs_[i], &ids)) {
114       return false;
115     }
116     event_ids_for_file_attrs_.push_back(ids);
117     for (auto id : ids) {
118       event_id_to_attr_map_[id] = &file_attrs_[i].attr;
119     }
120   }
121   return true;
122 }
123
124 bool RecordFileReader::ReadFeatureSectionDescriptors() {
125   std::vector<int> features;
126   for (size_t i = 0; i < sizeof(header_.features); ++i) {
127     for (size_t j = 0; j < 8; ++j) {
128       if (header_.features[i] & (1 << j)) {
129         features.push_back(i * 8 + j);
130       }
131     }
132   }
133   uint64_t feature_section_offset = header_.data.offset + header_.data.size;
134   if (fseek(record_fp_, feature_section_offset, SEEK_SET) != 0) {
135     PLOG(ERROR) << "fseek() failed";
136     return false;
137   }
138   for (const auto& id : features) {
139     SectionDesc desc;
140     if (!Read(&desc, sizeof(desc))) {
141       return false;
142     }
143     feature_section_descriptors_.emplace(id, desc);
144   }
145   return true;
146 }
147
148 bool RecordFileReader::ReadIdsForAttr(const FileAttr& attr, std::vector<uint64_t>* ids) {
149   size_t id_count = attr.ids.size / sizeof(uint64_t);
150   if (fseek(record_fp_, attr.ids.offset, SEEK_SET) != 0) {
151     PLOG(ERROR) << "fseek() failed";
152     return false;
153   }
154   ids->resize(id_count);
155   if (!Read(ids->data(), attr.ids.size)) {
156     return false;
157   }
158   return true;
159 }
160
161 bool RecordFileReader::ReadDataSection(
162     const std::function<bool(std::unique_ptr<Record>)>& callback, bool sorted) {
163   if (fseek(record_fp_, header_.data.offset, SEEK_SET) != 0) {
164     PLOG(ERROR) << "fseek() failed";
165     return false;
166   }
167   bool has_timestamp = true;
168   for (const auto& attr : file_attrs_) {
169     if (!IsTimestampSupported(attr.attr)) {
170       has_timestamp = false;
171       break;
172     }
173   }
174   RecordCache cache(has_timestamp);
175   for (size_t nbytes_read = 0; nbytes_read < header_.data.size;) {
176     std::unique_ptr<Record> record = ReadRecord(&nbytes_read);
177     if (record == nullptr) {
178       return false;
179     }
180     if (record->type() == SIMPLE_PERF_RECORD_EVENT_ID) {
181       ProcessEventIdRecord(*static_cast<EventIdRecord*>(record.get()));
182     }
183     if (sorted) {
184       cache.Push(std::move(record));
185       record = cache.Pop();
186       if (record != nullptr) {
187         if (!callback(std::move(record))) {
188           return false;
189         }
190       }
191     } else {
192       if (!callback(std::move(record))) {
193         return false;
194       }
195     }
196   }
197   std::vector<std::unique_ptr<Record>> records = cache.PopAll();
198   for (auto& record : records) {
199     if (!callback(std::move(record))) {
200       return false;
201     }
202   }
203   return true;
204 }
205
206 std::unique_ptr<Record> RecordFileReader::ReadRecord(size_t* nbytes_read) {
207   char header_buf[Record::header_size()];
208   if (!Read(header_buf, Record::header_size())) {
209     return nullptr;
210   }
211   RecordHeader header(header_buf);
212   std::unique_ptr<char[]> p;
213   if (header.type == SIMPLE_PERF_RECORD_SPLIT) {
214     // Read until meeting a RECORD_SPLIT_END record.
215     std::vector<char> buf;
216     size_t cur_size = 0;
217     char header_buf[Record::header_size()];
218     while (header.type == SIMPLE_PERF_RECORD_SPLIT) {
219       size_t bytes_to_read = header.size - Record::header_size();
220       buf.resize(cur_size + bytes_to_read);
221       if (!Read(&buf[cur_size], bytes_to_read)) {
222         return nullptr;
223       }
224       cur_size += bytes_to_read;
225       *nbytes_read += header.size;
226       if (!Read(header_buf, Record::header_size())) {
227         return nullptr;
228       }
229       header = RecordHeader(header_buf);
230     }
231     if (header.type != SIMPLE_PERF_RECORD_SPLIT_END) {
232       LOG(ERROR) << "SPLIT records are not followed by a SPLIT_END record.";
233       return nullptr;
234     }
235     *nbytes_read += header.size;
236     header = RecordHeader(buf.data());
237     p.reset(new char[header.size]);
238     memcpy(p.get(), buf.data(), buf.size());
239   } else {
240     p.reset(new char[header.size]);
241     memcpy(p.get(), header_buf, Record::header_size());
242     if (header.size > Record::header_size()) {
243       if (!Read(p.get() + Record::header_size(), header.size - Record::header_size())) {
244         return nullptr;
245       }
246     }
247     *nbytes_read += header.size;
248   }
249
250   const perf_event_attr* attr = &file_attrs_[0].attr;
251   if (file_attrs_.size() > 1 && header.type < PERF_RECORD_USER_DEFINED_TYPE_START) {
252     bool has_event_id = false;
253     uint64_t event_id;
254     if (header.type == PERF_RECORD_SAMPLE) {
255       if (header.size > event_id_pos_in_sample_records_ + sizeof(uint64_t)) {
256         has_event_id = true;
257         event_id = *reinterpret_cast<uint64_t*>(p.get() + event_id_pos_in_sample_records_);
258       }
259     } else {
260       if (header.size > event_id_reverse_pos_in_non_sample_records_) {
261         has_event_id = true;
262         event_id = *reinterpret_cast<uint64_t*>(p.get() + header.size - event_id_reverse_pos_in_non_sample_records_);
263       }
264     }
265     if (has_event_id) {
266       auto it = event_id_to_attr_map_.find(event_id);
267       if (it != event_id_to_attr_map_.end()) {
268         attr = it->second;
269       }
270     }
271   }
272   return ReadRecordFromOwnedBuffer(*attr, header.type, p.release());
273 }
274
275 bool RecordFileReader::Read(void* buf, size_t len) {
276   if (len != 0 && fread(buf, len, 1, record_fp_) != 1) {
277     PLOG(FATAL) << "failed to read file " << filename_;
278     return false;
279   }
280   return true;
281 }
282
283 void RecordFileReader::ProcessEventIdRecord(const EventIdRecord& r) {
284   for (size_t i = 0; i < r.count; ++i) {
285     event_ids_for_file_attrs_[r.data[i].attr_id].push_back(r.data[i].event_id);
286     event_id_to_attr_map_[r.data[i].event_id] =
287         &file_attrs_[r.data[i].attr_id].attr;
288   }
289 }
290
291 bool RecordFileReader::ReadFeatureSection(int feature, std::vector<char>* data) {
292   const std::map<int, SectionDesc>& section_map = FeatureSectionDescriptors();
293   auto it = section_map.find(feature);
294   if (it == section_map.end()) {
295     return false;
296   }
297   SectionDesc section = it->second;
298   data->resize(section.size);
299   if (section.size == 0) {
300     return true;
301   }
302   if (fseek(record_fp_, section.offset, SEEK_SET) != 0) {
303     PLOG(ERROR) << "fseek() failed";
304     return false;
305   }
306   if (!Read(data->data(), data->size())) {
307     return false;
308   }
309   return true;
310 }
311
312 std::vector<std::string> RecordFileReader::ReadCmdlineFeature() {
313   std::vector<char> buf;
314   if (!ReadFeatureSection(FEAT_CMDLINE, &buf)) {
315     return std::vector<std::string>();
316   }
317   const char* p = buf.data();
318   const char* end = buf.data() + buf.size();
319   std::vector<std::string> cmdline;
320   uint32_t arg_count;
321   MoveFromBinaryFormat(arg_count, p);
322   CHECK_LE(p, end);
323   for (size_t i = 0; i < arg_count; ++i) {
324     uint32_t len;
325     MoveFromBinaryFormat(len, p);
326     CHECK_LE(p + len, end);
327     cmdline.push_back(p);
328     p += len;
329   }
330   return cmdline;
331 }
332
333 std::vector<BuildIdRecord> RecordFileReader::ReadBuildIdFeature() {
334   std::vector<char> buf;
335   if (!ReadFeatureSection(FEAT_BUILD_ID, &buf)) {
336     return std::vector<BuildIdRecord>();
337   }
338   const char* p = buf.data();
339   const char* end = buf.data() + buf.size();
340   std::vector<BuildIdRecord> result;
341   while (p < end) {
342     BuildIdRecord record(p);
343     // Set type explicitly as the perf.data produced by perf doesn't set it.
344     record.SetTypeAndMisc(PERF_RECORD_BUILD_ID, record.misc());
345     CHECK_LE(p + record.size(), end);
346     p += record.size();
347     result.push_back(std::move(record));
348   }
349   return result;
350 }
351
352 std::string RecordFileReader::ReadFeatureString(int feature) {
353   std::vector<char> buf;
354   if (!ReadFeatureSection(feature, &buf)) {
355     return std::string();
356   }
357   const char* p = buf.data();
358   const char* end = buf.data() + buf.size();
359   uint32_t len;
360   MoveFromBinaryFormat(len, p);
361   CHECK_LE(p + len, end);
362   return p;
363 }
364
365 std::vector<std::unique_ptr<Record>> RecordFileReader::DataSection() {
366   std::vector<std::unique_ptr<Record>> records;
367   ReadDataSection([&](std::unique_ptr<Record> record) {
368     records.push_back(std::move(record));
369     return true;
370   });
371   return records;
372 }