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 <unistd.h>
22
23 #include <algorithm>
24 #include <set>
25 #include <string>
26 #include <unordered_map>
27 #include <vector>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31
32 #include "dso.h"
33 #include "event_attr.h"
34 #include "perf_event.h"
35 #include "record.h"
36 #include "system/extras/simpleperf/record_file.pb.h"
37 #include "utils.h"
38
39 namespace simpleperf {
40
41 using namespace PerfFileFormat;
42
CreateInstance(const std::string & filename)43 std::unique_ptr<RecordFileWriter> RecordFileWriter::CreateInstance(const std::string& filename) {
44 // Remove old perf.data to avoid file ownership problems.
45 std::string err;
46 if (!android::base::RemoveFileIfExists(filename, &err)) {
47 LOG(ERROR) << "failed to remove file " << filename << ": " << err;
48 return nullptr;
49 }
50 FILE* fp = fopen(filename.c_str(), "web+");
51 if (fp == nullptr) {
52 PLOG(ERROR) << "failed to open record file '" << filename << "'";
53 return nullptr;
54 }
55
56 return std::unique_ptr<RecordFileWriter>(new RecordFileWriter(filename, fp, true));
57 }
58
RecordFileWriter(const std::string & filename,FILE * fp,bool own_fp)59 RecordFileWriter::RecordFileWriter(const std::string& filename, FILE* fp, bool own_fp)
60 : filename_(filename),
61 record_fp_(fp),
62 own_fp_(own_fp),
63 attr_section_offset_(0),
64 attr_section_size_(0),
65 data_section_offset_(0),
66 data_section_size_(0),
67 feature_section_offset_(0),
68 feature_count_(0) {}
69
~RecordFileWriter()70 RecordFileWriter::~RecordFileWriter() {
71 if (record_fp_ != nullptr && own_fp_) {
72 fclose(record_fp_);
73 unlink(filename_.c_str());
74 }
75 }
76
WriteAttrSection(const std::vector<EventAttrWithId> & attr_ids)77 bool RecordFileWriter::WriteAttrSection(const std::vector<EventAttrWithId>& attr_ids) {
78 if (attr_ids.empty()) {
79 return false;
80 }
81
82 // Skip file header part.
83 if (fseek(record_fp_, sizeof(FileHeader), SEEK_SET) == -1) {
84 return false;
85 }
86
87 // Write id section.
88 uint64_t id_section_offset;
89 if (!GetFilePos(&id_section_offset)) {
90 return false;
91 }
92 for (auto& attr_id : attr_ids) {
93 if (!Write(attr_id.ids.data(), attr_id.ids.size() * sizeof(uint64_t))) {
94 return false;
95 }
96 }
97
98 // Write attr section.
99 uint64_t attr_section_offset;
100 if (!GetFilePos(&attr_section_offset)) {
101 return false;
102 }
103 for (auto& attr_id : attr_ids) {
104 FileAttr file_attr;
105 file_attr.attr = *attr_id.attr;
106 file_attr.ids.offset = id_section_offset;
107 file_attr.ids.size = attr_id.ids.size() * sizeof(uint64_t);
108 id_section_offset += file_attr.ids.size;
109 if (!Write(&file_attr, sizeof(file_attr))) {
110 return false;
111 }
112 }
113
114 uint64_t data_section_offset;
115 if (!GetFilePos(&data_section_offset)) {
116 return false;
117 }
118
119 attr_section_offset_ = attr_section_offset;
120 attr_section_size_ = data_section_offset - attr_section_offset;
121 data_section_offset_ = data_section_offset;
122
123 // Save event_attr for use when reading records.
124 event_attr_ = *attr_ids[0].attr;
125 return true;
126 }
127
WriteRecord(const Record & record)128 bool RecordFileWriter::WriteRecord(const Record& record) {
129 // linux-tools-perf only accepts records with size <= 65535 bytes. To make
130 // perf.data generated by simpleperf be able to be parsed by linux-tools-perf,
131 // Split simpleperf custom records which are > 65535 into a bunch of
132 // RECORD_SPLIT records, followed by a RECORD_SPLIT_END record.
133 constexpr uint32_t RECORD_SIZE_LIMIT = 65535;
134 if (record.size() <= RECORD_SIZE_LIMIT) {
135 bool result = WriteData(record.Binary(), record.size());
136 if (result && record.type() == PERF_RECORD_AUXTRACE) {
137 auto auxtrace = static_cast<const AuxTraceRecord*>(&record);
138 result = WriteData(auxtrace->location.addr, auxtrace->data->aux_size);
139 }
140 return result;
141 }
142 CHECK_GT(record.type(), SIMPLE_PERF_RECORD_TYPE_START);
143 const char* p = record.Binary();
144 uint32_t left_bytes = static_cast<uint32_t>(record.size());
145 RecordHeader header;
146 header.type = SIMPLE_PERF_RECORD_SPLIT;
147 char header_buf[Record::header_size()];
148 char* header_p;
149 while (left_bytes > 0) {
150 uint32_t bytes_to_write = std::min(RECORD_SIZE_LIMIT - Record::header_size(), left_bytes);
151 header.size = bytes_to_write + Record::header_size();
152 header_p = header_buf;
153 header.MoveToBinaryFormat(header_p);
154 if (!WriteData(header_buf, Record::header_size())) {
155 return false;
156 }
157 if (!WriteData(p, bytes_to_write)) {
158 return false;
159 }
160 p += bytes_to_write;
161 left_bytes -= bytes_to_write;
162 }
163 header.type = SIMPLE_PERF_RECORD_SPLIT_END;
164 header.size = Record::header_size();
165 header_p = header_buf;
166 header.MoveToBinaryFormat(header_p);
167 return WriteData(header_buf, Record::header_size());
168 }
169
WriteData(const void * buf,size_t len)170 bool RecordFileWriter::WriteData(const void* buf, size_t len) {
171 if (!Write(buf, len)) {
172 return false;
173 }
174 data_section_size_ += len;
175 return true;
176 }
177
Write(const void * buf,size_t len)178 bool RecordFileWriter::Write(const void* buf, size_t len) {
179 if (len != 0u && fwrite(buf, len, 1, record_fp_) != 1) {
180 PLOG(ERROR) << "failed to write to record file '" << filename_ << "'";
181 return false;
182 }
183 return true;
184 }
185
Read(void * buf,size_t len)186 bool RecordFileWriter::Read(void* buf, size_t len) {
187 if (len != 0u && fread(buf, len, 1, record_fp_) != 1) {
188 PLOG(ERROR) << "failed to read record file '" << filename_ << "'";
189 return false;
190 }
191 return true;
192 }
193
ReadDataSection(const std::function<void (const Record *)> & callback)194 bool RecordFileWriter::ReadDataSection(const std::function<void(const Record*)>& callback) {
195 if (fseek(record_fp_, data_section_offset_, SEEK_SET) == -1) {
196 PLOG(ERROR) << "fseek() failed";
197 return false;
198 }
199 std::vector<char> record_buf(512);
200 uint64_t read_pos = 0;
201 while (read_pos < data_section_size_) {
202 if (!Read(record_buf.data(), Record::header_size())) {
203 return false;
204 }
205 RecordHeader header(record_buf.data());
206 if (record_buf.size() < header.size) {
207 record_buf.resize(header.size);
208 }
209 if (!Read(record_buf.data() + Record::header_size(), header.size - Record::header_size())) {
210 return false;
211 }
212 read_pos += header.size;
213 std::unique_ptr<Record> r = ReadRecordFromBuffer(event_attr_, header.type, record_buf.data());
214 if (r->type() == PERF_RECORD_AUXTRACE) {
215 auto auxtrace = static_cast<AuxTraceRecord*>(r.get());
216 auxtrace->location.file_offset = data_section_offset_ + read_pos;
217 if (fseek(record_fp_, auxtrace->data->aux_size, SEEK_CUR) != 0) {
218 PLOG(ERROR) << "fseek() failed";
219 return false;
220 }
221 read_pos += auxtrace->data->aux_size;
222 }
223 callback(r.get());
224 }
225 return true;
226 }
227
GetFilePos(uint64_t * file_pos)228 bool RecordFileWriter::GetFilePos(uint64_t* file_pos) {
229 off_t offset = ftello(record_fp_);
230 if (offset == -1) {
231 PLOG(ERROR) << "ftello() failed";
232 return false;
233 }
234 *file_pos = static_cast<uint64_t>(offset);
235 return true;
236 }
237
BeginWriteFeatures(size_t feature_count)238 bool RecordFileWriter::BeginWriteFeatures(size_t feature_count) {
239 feature_section_offset_ = data_section_offset_ + data_section_size_;
240 feature_count_ = feature_count;
241 uint64_t feature_header_size = feature_count * sizeof(SectionDesc);
242
243 // Reserve enough space in the record file for the feature header.
244 std::vector<unsigned char> zero_data(feature_header_size);
245 if (fseek(record_fp_, feature_section_offset_, SEEK_SET) == -1) {
246 PLOG(ERROR) << "fseek() failed";
247 return false;
248 }
249 return Write(zero_data.data(), zero_data.size());
250 }
251
WriteBuildIdFeature(const std::vector<BuildIdRecord> & build_id_records)252 bool RecordFileWriter::WriteBuildIdFeature(const std::vector<BuildIdRecord>& build_id_records) {
253 if (!WriteFeatureBegin(FEAT_BUILD_ID)) {
254 return false;
255 }
256 for (auto& record : build_id_records) {
257 if (!Write(record.Binary(), record.size())) {
258 return false;
259 }
260 }
261 return WriteFeatureEnd(FEAT_BUILD_ID);
262 }
263
WriteStringWithLength(const std::string & s)264 bool RecordFileWriter::WriteStringWithLength(const std::string& s) {
265 uint32_t len = static_cast<uint32_t>(Align(s.size() + 1, 64));
266 if (!Write(&len, sizeof(len))) {
267 return false;
268 }
269 if (!Write(&s[0], s.size() + 1)) {
270 return false;
271 }
272 size_t pad_size = Align(s.size() + 1, 64) - s.size() - 1;
273 if (pad_size > 0u) {
274 char align_buf[pad_size];
275 memset(align_buf, '\0', pad_size);
276 if (!Write(align_buf, pad_size)) {
277 return false;
278 }
279 }
280 return true;
281 }
282
WriteFeatureString(int feature,const std::string & s)283 bool RecordFileWriter::WriteFeatureString(int feature, const std::string& s) {
284 if (!WriteFeatureBegin(feature)) {
285 return false;
286 }
287 if (!WriteStringWithLength(s)) {
288 return false;
289 }
290 return WriteFeatureEnd(feature);
291 }
292
WriteCmdlineFeature(const std::vector<std::string> & cmdline)293 bool RecordFileWriter::WriteCmdlineFeature(const std::vector<std::string>& cmdline) {
294 if (!WriteFeatureBegin(FEAT_CMDLINE)) {
295 return false;
296 }
297 uint32_t arg_count = cmdline.size();
298 if (!Write(&arg_count, sizeof(arg_count))) {
299 return false;
300 }
301 for (auto& arg : cmdline) {
302 if (!WriteStringWithLength(arg)) {
303 return false;
304 }
305 }
306 return WriteFeatureEnd(FEAT_CMDLINE);
307 }
308
WriteBranchStackFeature()309 bool RecordFileWriter::WriteBranchStackFeature() {
310 if (!WriteFeatureBegin(FEAT_BRANCH_STACK)) {
311 return false;
312 }
313 return WriteFeatureEnd(FEAT_BRANCH_STACK);
314 }
315
WriteAuxTraceFeature(const std::vector<uint64_t> & auxtrace_offset)316 bool RecordFileWriter::WriteAuxTraceFeature(const std::vector<uint64_t>& auxtrace_offset) {
317 std::vector<uint64_t> data;
318 for (auto offset : auxtrace_offset) {
319 data.push_back(offset);
320 data.push_back(AuxTraceRecord::Size());
321 }
322 return WriteFeature(FEAT_AUXTRACE, reinterpret_cast<char*>(data.data()),
323 data.size() * sizeof(uint64_t));
324 }
325
WriteFileFeatures(const std::vector<Dso * > & dsos)326 bool RecordFileWriter::WriteFileFeatures(const std::vector<Dso*>& dsos) {
327 for (Dso* dso : dsos) {
328 // Always want to dump dex file offsets for DSO_DEX_FILE type.
329 if (!dso->HasDumpId() && dso->type() != DSO_DEX_FILE) {
330 continue;
331 }
332 FileFeature file;
333 file.path = dso->Path();
334 file.type = dso->type();
335 dso->GetMinExecutableVaddr(&file.min_vaddr, &file.file_offset_of_min_vaddr);
336
337 // Dumping all symbols in hit files takes too much space, so only dump
338 // needed symbols.
339 const std::vector<Symbol>& symbols = dso->GetSymbols();
340 for (const auto& sym : symbols) {
341 if (sym.HasDumpId()) {
342 file.symbol_ptrs.emplace_back(&sym);
343 }
344 }
345 std::sort(file.symbol_ptrs.begin(), file.symbol_ptrs.end(), Symbol::CompareByAddr);
346
347 if (const auto dex_file_offsets = dso->DexFileOffsets(); dex_file_offsets != nullptr) {
348 file.dex_file_offsets = *dex_file_offsets;
349 }
350 if (!WriteFileFeature(file)) {
351 return false;
352 }
353 }
354 return true;
355 }
356
WriteFileFeature(const FileFeature & file)357 bool RecordFileWriter::WriteFileFeature(const FileFeature& file) {
358 uint32_t symbol_count = file.symbols.size() + file.symbol_ptrs.size();
359 uint32_t size = file.path.size() + 1 + sizeof(uint32_t) * 2 + sizeof(uint64_t) +
360 symbol_count * (sizeof(uint64_t) + sizeof(uint32_t));
361 for (const auto& symbol : file.symbols) {
362 size += strlen(symbol.Name()) + 1;
363 }
364 for (const auto& symbol : file.symbol_ptrs) {
365 size += strlen(symbol->Name()) + 1;
366 }
367 if (file.type == DSO_DEX_FILE) {
368 size += sizeof(uint32_t) + sizeof(uint64_t) * file.dex_file_offsets.size();
369 }
370 if (file.type == DSO_ELF_FILE || file.type == DSO_KERNEL_MODULE) {
371 size += sizeof(uint64_t);
372 }
373 std::vector<char> buf(sizeof(uint32_t) + size);
374 char* p = buf.data();
375 MoveToBinaryFormat(size, p);
376 MoveToBinaryFormat(file.path.c_str(), file.path.size() + 1, p);
377 MoveToBinaryFormat(static_cast<uint32_t>(file.type), p);
378 MoveToBinaryFormat(file.min_vaddr, p);
379 MoveToBinaryFormat(symbol_count, p);
380
381 auto write_symbol = [&](const Symbol* symbol) {
382 MoveToBinaryFormat(symbol->addr, p);
383 uint32_t len = symbol->len;
384 MoveToBinaryFormat(len, p);
385 MoveToBinaryFormat(symbol->Name(), strlen(symbol->Name()) + 1, p);
386 };
387 for (const auto& symbol : file.symbols) {
388 write_symbol(&symbol);
389 }
390 for (const auto& symbol : file.symbol_ptrs) {
391 write_symbol(symbol);
392 }
393 if (file.type == DSO_DEX_FILE) {
394 uint32_t offset_count = file.dex_file_offsets.size();
395 MoveToBinaryFormat(offset_count, p);
396 MoveToBinaryFormat(file.dex_file_offsets.data(), offset_count, p);
397 }
398 if (file.type == DSO_ELF_FILE || file.type == DSO_KERNEL_MODULE) {
399 MoveToBinaryFormat(file.file_offset_of_min_vaddr, p);
400 }
401 CHECK_EQ(buf.size(), static_cast<size_t>(p - buf.data()));
402
403 return WriteFeature(FEAT_FILE, buf.data(), buf.size());
404 }
405
WriteMetaInfoFeature(const std::unordered_map<std::string,std::string> & info_map)406 bool RecordFileWriter::WriteMetaInfoFeature(
407 const std::unordered_map<std::string, std::string>& info_map) {
408 uint32_t size = 0u;
409 for (auto& pair : info_map) {
410 size += pair.first.size() + 1;
411 size += pair.second.size() + 1;
412 }
413 std::vector<char> buf(size);
414 char* p = buf.data();
415 for (auto& pair : info_map) {
416 MoveToBinaryFormat(pair.first.c_str(), pair.first.size() + 1, p);
417 MoveToBinaryFormat(pair.second.c_str(), pair.second.size() + 1, p);
418 }
419 return WriteFeature(FEAT_META_INFO, buf.data(), buf.size());
420 }
421
WriteDebugUnwindFeature(const DebugUnwindFeature & debug_unwind)422 bool RecordFileWriter::WriteDebugUnwindFeature(const DebugUnwindFeature& debug_unwind) {
423 GOOGLE_PROTOBUF_VERIFY_VERSION;
424 proto::DebugUnwindFeature proto_debug_unwind;
425 for (auto& file : debug_unwind) {
426 auto proto_file = proto_debug_unwind.add_file();
427 proto_file->set_path(file.path);
428 proto_file->set_size(file.size);
429 }
430 std::string s;
431 if (!proto_debug_unwind.SerializeToString(&s)) {
432 LOG(ERROR) << "SerializeToString() failed";
433 return false;
434 }
435 return WriteFeature(FEAT_DEBUG_UNWIND, s.data(), s.size());
436 }
437
WriteFeature(int feature,const char * data,size_t size)438 bool RecordFileWriter::WriteFeature(int feature, const char* data, size_t size) {
439 return WriteFeatureBegin(feature) && Write(data, size) && WriteFeatureEnd(feature);
440 }
441
WriteFeatureBegin(int feature)442 bool RecordFileWriter::WriteFeatureBegin(int feature) {
443 auto it = features_.find(feature);
444 if (it == features_.end()) {
445 CHECK_LT(features_.size(), feature_count_);
446 auto& sec = features_[feature];
447 if (!GetFilePos(&sec.offset)) {
448 return false;
449 }
450 sec.size = 0;
451 }
452 return true;
453 }
454
WriteFeatureEnd(int feature)455 bool RecordFileWriter::WriteFeatureEnd(int feature) {
456 auto it = features_.find(feature);
457 if (it == features_.end()) {
458 return false;
459 }
460 uint64_t offset;
461 if (!GetFilePos(&offset)) {
462 return false;
463 }
464 it->second.size = offset - it->second.offset;
465 return true;
466 }
467
EndWriteFeatures()468 bool RecordFileWriter::EndWriteFeatures() {
469 // Used features (features_.size()) should be <= allocated feature space.
470 CHECK_LE(features_.size(), feature_count_);
471 if (fseek(record_fp_, feature_section_offset_, SEEK_SET) == -1) {
472 PLOG(ERROR) << "fseek() failed";
473 return false;
474 }
475 for (const auto& pair : features_) {
476 if (!Write(&pair.second, sizeof(SectionDesc))) {
477 return false;
478 }
479 }
480 return true;
481 }
482
WriteFileHeader()483 bool RecordFileWriter::WriteFileHeader() {
484 FileHeader header;
485 memset(&header, 0, sizeof(header));
486 memcpy(header.magic, PERF_MAGIC, sizeof(header.magic));
487 header.header_size = sizeof(header);
488 header.attr_size = sizeof(FileAttr);
489 header.attrs.offset = attr_section_offset_;
490 header.attrs.size = attr_section_size_;
491 header.data.offset = data_section_offset_;
492 header.data.size = data_section_size_;
493 for (const auto& pair : features_) {
494 int i = pair.first / 8;
495 int j = pair.first % 8;
496 header.features[i] |= (1 << j);
497 }
498
499 if (fseek(record_fp_, 0, SEEK_SET) == -1) {
500 return false;
501 }
502 if (!Write(&header, sizeof(header))) {
503 return false;
504 }
505 return true;
506 }
507
Close()508 bool RecordFileWriter::Close() {
509 CHECK(record_fp_ != nullptr);
510 bool result = true;
511
512 // Write file header. We gather enough information to write file header only after
513 // writing data section and feature section.
514 if (!WriteFileHeader()) {
515 result = false;
516 }
517
518 if (own_fp_ && fclose(record_fp_) != 0) {
519 PLOG(ERROR) << "failed to close record file '" << filename_ << "'";
520 result = false;
521 }
522 record_fp_ = nullptr;
523 return result;
524 }
525
526 } // namespace simpleperf
527