• 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_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                                                      record_buf.data() + header.size);
215     CHECK(r);
216     if (r->type() == PERF_RECORD_AUXTRACE) {
217       auto auxtrace = static_cast<AuxTraceRecord*>(r.get());
218       auxtrace->location.file_offset = data_section_offset_ + read_pos;
219       if (fseek(record_fp_, auxtrace->data->aux_size, SEEK_CUR) != 0) {
220         PLOG(ERROR) << "fseek() failed";
221         return false;
222       }
223       read_pos += auxtrace->data->aux_size;
224     }
225     callback(r.get());
226   }
227   return true;
228 }
229 
GetFilePos(uint64_t * file_pos)230 bool RecordFileWriter::GetFilePos(uint64_t* file_pos) {
231   off_t offset = ftello(record_fp_);
232   if (offset == -1) {
233     PLOG(ERROR) << "ftello() failed";
234     return false;
235   }
236   *file_pos = static_cast<uint64_t>(offset);
237   return true;
238 }
239 
BeginWriteFeatures(size_t feature_count)240 bool RecordFileWriter::BeginWriteFeatures(size_t feature_count) {
241   feature_section_offset_ = data_section_offset_ + data_section_size_;
242   feature_count_ = feature_count;
243   uint64_t feature_header_size = feature_count * sizeof(SectionDesc);
244 
245   // Reserve enough space in the record file for the feature header.
246   std::vector<unsigned char> zero_data(feature_header_size);
247   if (fseek(record_fp_, feature_section_offset_, SEEK_SET) == -1) {
248     PLOG(ERROR) << "fseek() failed";
249     return false;
250   }
251   return Write(zero_data.data(), zero_data.size());
252 }
253 
WriteBuildIdFeature(const std::vector<BuildIdRecord> & build_id_records)254 bool RecordFileWriter::WriteBuildIdFeature(const std::vector<BuildIdRecord>& build_id_records) {
255   if (!WriteFeatureBegin(FEAT_BUILD_ID)) {
256     return false;
257   }
258   for (auto& record : build_id_records) {
259     if (!Write(record.Binary(), record.size())) {
260       return false;
261     }
262   }
263   return WriteFeatureEnd(FEAT_BUILD_ID);
264 }
265 
WriteStringWithLength(const std::string & s)266 bool RecordFileWriter::WriteStringWithLength(const std::string& s) {
267   uint32_t len = static_cast<uint32_t>(Align(s.size() + 1, 64));
268   if (!Write(&len, sizeof(len))) {
269     return false;
270   }
271   if (!Write(&s[0], s.size() + 1)) {
272     return false;
273   }
274   size_t pad_size = Align(s.size() + 1, 64) - s.size() - 1;
275   if (pad_size > 0u) {
276     char align_buf[pad_size];
277     memset(align_buf, '\0', pad_size);
278     if (!Write(align_buf, pad_size)) {
279       return false;
280     }
281   }
282   return true;
283 }
284 
WriteFeatureString(int feature,const std::string & s)285 bool RecordFileWriter::WriteFeatureString(int feature, const std::string& s) {
286   if (!WriteFeatureBegin(feature)) {
287     return false;
288   }
289   if (!WriteStringWithLength(s)) {
290     return false;
291   }
292   return WriteFeatureEnd(feature);
293 }
294 
WriteCmdlineFeature(const std::vector<std::string> & cmdline)295 bool RecordFileWriter::WriteCmdlineFeature(const std::vector<std::string>& cmdline) {
296   if (!WriteFeatureBegin(FEAT_CMDLINE)) {
297     return false;
298   }
299   uint32_t arg_count = cmdline.size();
300   if (!Write(&arg_count, sizeof(arg_count))) {
301     return false;
302   }
303   for (auto& arg : cmdline) {
304     if (!WriteStringWithLength(arg)) {
305       return false;
306     }
307   }
308   return WriteFeatureEnd(FEAT_CMDLINE);
309 }
310 
WriteBranchStackFeature()311 bool RecordFileWriter::WriteBranchStackFeature() {
312   if (!WriteFeatureBegin(FEAT_BRANCH_STACK)) {
313     return false;
314   }
315   return WriteFeatureEnd(FEAT_BRANCH_STACK);
316 }
317 
WriteAuxTraceFeature(const std::vector<uint64_t> & auxtrace_offset)318 bool RecordFileWriter::WriteAuxTraceFeature(const std::vector<uint64_t>& auxtrace_offset) {
319   std::vector<uint64_t> data;
320   for (auto offset : auxtrace_offset) {
321     data.push_back(offset);
322     data.push_back(AuxTraceRecord::Size());
323   }
324   return WriteFeature(FEAT_AUXTRACE, reinterpret_cast<char*>(data.data()),
325                       data.size() * sizeof(uint64_t));
326 }
327 
WriteFileFeatures(const std::vector<Dso * > & dsos)328 bool RecordFileWriter::WriteFileFeatures(const std::vector<Dso*>& dsos) {
329   for (Dso* dso : dsos) {
330     // Always want to dump dex file offsets for DSO_DEX_FILE type.
331     if (!dso->HasDumpId() && dso->type() != DSO_DEX_FILE) {
332       continue;
333     }
334     FileFeature file;
335     file.path = dso->Path();
336     file.type = dso->type();
337     dso->GetMinExecutableVaddr(&file.min_vaddr, &file.file_offset_of_min_vaddr);
338 
339     // Dumping all symbols in hit files takes too much space, so only dump
340     // needed symbols.
341     const std::vector<Symbol>& symbols = dso->GetSymbols();
342     for (const auto& sym : symbols) {
343       if (sym.HasDumpId()) {
344         file.symbol_ptrs.emplace_back(&sym);
345       }
346     }
347     std::sort(file.symbol_ptrs.begin(), file.symbol_ptrs.end(), Symbol::CompareByAddr);
348 
349     if (const auto dex_file_offsets = dso->DexFileOffsets(); dex_file_offsets != nullptr) {
350       file.dex_file_offsets = *dex_file_offsets;
351     }
352     if (!WriteFileFeature(file)) {
353       return false;
354     }
355   }
356   return true;
357 }
358 
WriteFileFeature(const FileFeature & file)359 bool RecordFileWriter::WriteFileFeature(const FileFeature& file) {
360   proto::FileFeature proto_file;
361   proto_file.set_path(file.path);
362   proto_file.set_type(static_cast<uint32_t>(file.type));
363   proto_file.set_min_vaddr(file.min_vaddr);
364   auto write_symbol = [&](const Symbol& symbol) {
365     proto::FileFeature::Symbol* proto_symbol = proto_file.add_symbol();
366     proto_symbol->set_vaddr(symbol.addr);
367     proto_symbol->set_len(symbol.len);
368     proto_symbol->set_name(symbol.Name());
369   };
370   for (const Symbol& symbol : file.symbols) {
371     write_symbol(symbol);
372   }
373   for (const Symbol* symbol_ptr : file.symbol_ptrs) {
374     write_symbol(*symbol_ptr);
375   }
376   if (file.type == DSO_DEX_FILE) {
377     proto::FileFeature::DexFile* proto_dex_file = proto_file.mutable_dex_file();
378     proto_dex_file->mutable_dex_file_offset()->Add(file.dex_file_offsets.begin(),
379                                                    file.dex_file_offsets.end());
380   } else if (file.type == DSO_ELF_FILE) {
381     proto::FileFeature::ElfFile* proto_elf_file = proto_file.mutable_elf_file();
382     proto_elf_file->set_file_offset_of_min_vaddr(file.file_offset_of_min_vaddr);
383   } else if (file.type == DSO_KERNEL_MODULE) {
384     proto::FileFeature::KernelModule* proto_kernel_module = proto_file.mutable_kernel_module();
385     proto_kernel_module->set_memory_offset_of_min_vaddr(file.file_offset_of_min_vaddr);
386   }
387   std::string s;
388   if (!proto_file.SerializeToString(&s)) {
389     LOG(ERROR) << "SerializeToString() failed";
390     return false;
391   }
392   uint32_t msg_size = s.size();
393   return WriteFeatureBegin(FEAT_FILE2) && Write(&msg_size, sizeof(uint32_t)) &&
394          Write(s.data(), s.size()) && WriteFeatureEnd(FEAT_FILE2);
395 }
396 
WriteMetaInfoFeature(const std::unordered_map<std::string,std::string> & info_map)397 bool RecordFileWriter::WriteMetaInfoFeature(
398     const std::unordered_map<std::string, std::string>& info_map) {
399   uint32_t size = 0u;
400   for (auto& pair : info_map) {
401     size += pair.first.size() + 1;
402     size += pair.second.size() + 1;
403   }
404   std::vector<char> buf(size);
405   char* p = buf.data();
406   for (auto& pair : info_map) {
407     MoveToBinaryFormat(pair.first.c_str(), pair.first.size() + 1, p);
408     MoveToBinaryFormat(pair.second.c_str(), pair.second.size() + 1, p);
409   }
410   return WriteFeature(FEAT_META_INFO, buf.data(), buf.size());
411 }
412 
WriteDebugUnwindFeature(const DebugUnwindFeature & debug_unwind)413 bool RecordFileWriter::WriteDebugUnwindFeature(const DebugUnwindFeature& debug_unwind) {
414   GOOGLE_PROTOBUF_VERIFY_VERSION;
415   proto::DebugUnwindFeature proto_debug_unwind;
416   for (auto& file : debug_unwind) {
417     auto proto_file = proto_debug_unwind.add_file();
418     proto_file->set_path(file.path);
419     proto_file->set_size(file.size);
420   }
421   std::string s;
422   if (!proto_debug_unwind.SerializeToString(&s)) {
423     LOG(ERROR) << "SerializeToString() failed";
424     return false;
425   }
426   return WriteFeature(FEAT_DEBUG_UNWIND, s.data(), s.size());
427 }
428 
WriteFeature(int feature,const char * data,size_t size)429 bool RecordFileWriter::WriteFeature(int feature, const char* data, size_t size) {
430   return WriteFeatureBegin(feature) && Write(data, size) && WriteFeatureEnd(feature);
431 }
432 
WriteFeatureBegin(int feature)433 bool RecordFileWriter::WriteFeatureBegin(int feature) {
434   auto it = features_.find(feature);
435   if (it == features_.end()) {
436     CHECK_LT(features_.size(), feature_count_);
437     auto& sec = features_[feature];
438     if (!GetFilePos(&sec.offset)) {
439       return false;
440     }
441     sec.size = 0;
442   }
443   return true;
444 }
445 
WriteFeatureEnd(int feature)446 bool RecordFileWriter::WriteFeatureEnd(int feature) {
447   auto it = features_.find(feature);
448   if (it == features_.end()) {
449     return false;
450   }
451   uint64_t offset;
452   if (!GetFilePos(&offset)) {
453     return false;
454   }
455   it->second.size = offset - it->second.offset;
456   return true;
457 }
458 
EndWriteFeatures()459 bool RecordFileWriter::EndWriteFeatures() {
460   // Used features (features_.size()) should be <= allocated feature space.
461   CHECK_LE(features_.size(), feature_count_);
462   if (fseek(record_fp_, feature_section_offset_, SEEK_SET) == -1) {
463     PLOG(ERROR) << "fseek() failed";
464     return false;
465   }
466   for (const auto& pair : features_) {
467     if (!Write(&pair.second, sizeof(SectionDesc))) {
468       return false;
469     }
470   }
471   return true;
472 }
473 
WriteFileHeader()474 bool RecordFileWriter::WriteFileHeader() {
475   FileHeader header;
476   memset(&header, 0, sizeof(header));
477   memcpy(header.magic, PERF_MAGIC, sizeof(header.magic));
478   header.header_size = sizeof(header);
479   header.attr_size = sizeof(FileAttr);
480   header.attrs.offset = attr_section_offset_;
481   header.attrs.size = attr_section_size_;
482   header.data.offset = data_section_offset_;
483   header.data.size = data_section_size_;
484   for (const auto& pair : features_) {
485     int i = pair.first / 8;
486     int j = pair.first % 8;
487     header.features[i] |= (1 << j);
488   }
489 
490   if (fseek(record_fp_, 0, SEEK_SET) == -1) {
491     return false;
492   }
493   if (!Write(&header, sizeof(header))) {
494     return false;
495   }
496   return true;
497 }
498 
Close()499 bool RecordFileWriter::Close() {
500   CHECK(record_fp_ != nullptr);
501   bool result = true;
502 
503   // Write file header. We gather enough information to write file header only after
504   // writing data section and feature section.
505   if (!WriteFileHeader()) {
506     result = false;
507   }
508 
509   if (own_fp_ && fclose(record_fp_) != 0) {
510     PLOG(ERROR) << "failed to close record file '" << filename_ << "'";
511     result = false;
512   }
513   record_fp_ = nullptr;
514   return result;
515 }
516 
517 }  // namespace simpleperf
518