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