OSDN Git Service

am a0a0ebc5: am 65df483a: Don\'t encrypt lost+found
[android-x86/system-extras.git] / simpleperf / record_file_writer.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 <sys/mman.h>
22 #include <unistd.h>
23 #include <set>
24 #include <vector>
25
26 #include <base/logging.h>
27
28 #include "event_fd.h"
29 #include "perf_event.h"
30 #include "record.h"
31 #include "utils.h"
32
33 using namespace PerfFileFormat;
34
35 std::unique_ptr<RecordFileWriter> RecordFileWriter::CreateInstance(
36     const std::string& filename, const perf_event_attr& event_attr,
37     const std::vector<std::unique_ptr<EventFd>>& event_fds) {
38   // Remove old perf.data to avoid file ownership problems.
39   if (!RemovePossibleFile(filename)) {
40     return nullptr;
41   }
42   FILE* fp = fopen(filename.c_str(), "web+");
43   if (fp == nullptr) {
44     PLOG(ERROR) << "failed to open record file '" << filename << "'";
45     return nullptr;
46   }
47
48   auto writer = std::unique_ptr<RecordFileWriter>(new RecordFileWriter(filename, fp));
49   if (!writer->WriteAttrSection(event_attr, event_fds)) {
50     return nullptr;
51   }
52   return writer;
53 }
54
55 RecordFileWriter::RecordFileWriter(const std::string& filename, FILE* fp)
56     : filename_(filename),
57       record_fp_(fp),
58       attr_section_offset_(0),
59       attr_section_size_(0),
60       data_section_offset_(0),
61       data_section_size_(0),
62       feature_count_(0),
63       current_feature_index_(0) {
64 }
65
66 RecordFileWriter::~RecordFileWriter() {
67   if (record_fp_ != nullptr) {
68     Close();
69   }
70 }
71
72 bool RecordFileWriter::WriteAttrSection(const perf_event_attr& event_attr,
73                                         const std::vector<std::unique_ptr<EventFd>>& event_fds) {
74   // Skip file header part.
75   if (fseek(record_fp_, sizeof(FileHeader), SEEK_SET) == -1) {
76     return false;
77   }
78
79   // Write id section.
80   std::vector<uint64_t> ids;
81   for (auto& event_fd : event_fds) {
82     ids.push_back(event_fd->Id());
83   }
84   long id_section_offset = ftell(record_fp_);
85   if (id_section_offset == -1) {
86     return false;
87   }
88   if (!Write(ids.data(), ids.size() * sizeof(uint64_t))) {
89     return false;
90   }
91
92   // Write attr section.
93   FileAttr attr;
94   attr.attr = event_attr;
95   attr.ids.offset = id_section_offset;
96   attr.ids.size = ids.size() * sizeof(uint64_t);
97
98   long attr_section_offset = ftell(record_fp_);
99   if (attr_section_offset == -1) {
100     return false;
101   }
102   if (!Write(&attr, sizeof(attr))) {
103     return false;
104   }
105
106   long data_section_offset = ftell(record_fp_);
107   if (data_section_offset == -1) {
108     return false;
109   }
110
111   attr_section_offset_ = attr_section_offset;
112   attr_section_size_ = sizeof(attr);
113   data_section_offset_ = data_section_offset;
114
115   // Save event_attr for use when reading records.
116   event_attr_ = event_attr;
117   return true;
118 }
119
120 bool RecordFileWriter::WriteData(const void* buf, size_t len) {
121   if (!Write(buf, len)) {
122     return false;
123   }
124   data_section_size_ += len;
125   return true;
126 }
127
128 bool RecordFileWriter::Write(const void* buf, size_t len) {
129   if (fwrite(buf, len, 1, record_fp_) != 1) {
130     PLOG(ERROR) << "failed to write to record file '" << filename_ << "'";
131     return false;
132   }
133   return true;
134 }
135
136 void RecordFileWriter::GetHitModulesInBuffer(const char* p, const char* end,
137                                              std::vector<std::string>* hit_kernel_modules,
138                                              std::vector<std::string>* hit_user_files) {
139   std::vector<std::unique_ptr<const Record>> kernel_mmaps;
140   std::vector<std::unique_ptr<const Record>> user_mmaps;
141   std::set<std::string> hit_kernel_set;
142   std::set<std::string> hit_user_set;
143
144   while (p < end) {
145     auto header = reinterpret_cast<const perf_event_header*>(p);
146     CHECK_LE(p + header->size, end);
147     p += header->size;
148     std::unique_ptr<const Record> record = ReadRecordFromBuffer(event_attr_, header);
149     CHECK(record != nullptr);
150     if (record->header.type == PERF_RECORD_MMAP) {
151       if (record->header.misc & PERF_RECORD_MISC_KERNEL) {
152         kernel_mmaps.push_back(std::move(record));
153       } else {
154         user_mmaps.push_back(std::move(record));
155       }
156     } else if (record->header.type == PERF_RECORD_SAMPLE) {
157       auto& r = *static_cast<const SampleRecord*>(record.get());
158       if (!(r.sample_type & PERF_SAMPLE_IP) || !(r.sample_type & PERF_SAMPLE_TID)) {
159         continue;
160       }
161       uint32_t pid = r.tid_data.pid;
162       uint64_t ip = r.ip_data.ip;
163       if (r.header.misc & PERF_RECORD_MISC_KERNEL) {
164         // Loop from back to front, because new MmapRecords are inserted at the end of the mmaps,
165         // and we want to match the newest one.
166         for (auto it = kernel_mmaps.rbegin(); it != kernel_mmaps.rend(); ++it) {
167           auto& m_record = *reinterpret_cast<const MmapRecord*>(it->get());
168           if (ip >= m_record.data.addr && ip < m_record.data.addr + m_record.data.len) {
169             hit_kernel_set.insert(m_record.filename);
170             break;
171           }
172         }
173       } else {
174         for (auto it = user_mmaps.rbegin(); it != user_mmaps.rend(); ++it) {
175           auto& m_record = *reinterpret_cast<const MmapRecord*>(it->get());
176           if (pid == m_record.data.pid && ip >= m_record.data.addr &&
177               ip < m_record.data.addr + m_record.data.len) {
178             hit_user_set.insert(m_record.filename);
179             break;
180           }
181         }
182       }
183     }
184   }
185   hit_kernel_modules->clear();
186   hit_kernel_modules->insert(hit_kernel_modules->begin(), hit_kernel_set.begin(),
187                              hit_kernel_set.end());
188   hit_user_files->clear();
189   hit_user_files->insert(hit_user_files->begin(), hit_user_set.begin(), hit_user_set.end());
190 }
191
192 bool RecordFileWriter::GetHitModules(std::vector<std::string>* hit_kernel_modules,
193                                      std::vector<std::string>* hit_user_files) {
194   if (fflush(record_fp_) != 0) {
195     PLOG(ERROR) << "fflush() failed";
196     return false;
197   }
198   uint64_t file_size;
199   if (!SeekFileEnd(&file_size)) {
200     return false;
201   }
202   size_t mmap_len = static_cast<size_t>(file_size);
203   void* mmap_addr = mmap(nullptr, mmap_len, PROT_READ, MAP_SHARED, fileno(record_fp_), 0);
204   if (mmap_addr == MAP_FAILED) {
205     PLOG(ERROR) << "mmap() failed";
206     return false;
207   }
208   const char* data_section_p = reinterpret_cast<const char*>(mmap_addr) + data_section_offset_;
209   const char* data_section_end = data_section_p + data_section_size_;
210   GetHitModulesInBuffer(data_section_p, data_section_end, hit_kernel_modules, hit_user_files);
211
212   if (munmap(mmap_addr, mmap_len) == -1) {
213     PLOG(ERROR) << "munmap() failed";
214     return false;
215   }
216   return true;
217 }
218
219 bool RecordFileWriter::SeekFileEnd(uint64_t* file_end) {
220   if (fseek(record_fp_, 0, SEEK_END) == -1) {
221     PLOG(ERROR) << "fseek() failed";
222     return false;
223   }
224   long offset = ftell(record_fp_);
225   if (offset == -1) {
226     PLOG(ERROR) << "ftell() failed";
227     return false;
228   }
229   *file_end = static_cast<uint64_t>(offset);
230   return true;
231 }
232
233 bool RecordFileWriter::WriteFeatureHeader(size_t feature_count) {
234   feature_count_ = feature_count;
235   current_feature_index_ = 0;
236   uint64_t feature_header_size = feature_count * sizeof(SectionDesc);
237
238   // Reserve enough space in the record file for the feature header.
239   std::vector<unsigned char> zero_data(feature_header_size);
240   if (fseek(record_fp_, data_section_offset_ + data_section_size_, SEEK_SET) == -1) {
241     PLOG(ERROR) << "fseek() failed";
242     return false;
243   }
244   return Write(zero_data.data(), zero_data.size());
245 }
246
247 bool RecordFileWriter::WriteBuildIdFeature(const std::vector<BuildIdRecord>& build_id_records) {
248   uint64_t start_offset;
249   if (!WriteFeatureBegin(&start_offset)) {
250     return false;
251   }
252   for (auto& record : build_id_records) {
253     std::vector<char> data = record.BinaryFormat();
254     if (!Write(data.data(), data.size())) {
255       return false;
256     }
257   }
258   return WriteFeatureEnd(FEAT_BUILD_ID, start_offset);
259 }
260
261 bool RecordFileWriter::WriteFeatureString(int feature, const std::string& s) {
262   uint64_t start_offset;
263   if (!WriteFeatureBegin(&start_offset)) {
264     return false;
265   }
266   uint32_t len = static_cast<uint32_t>(ALIGN(s.size() + 1, 64));
267   if (!Write(&len, sizeof(len))) {
268     return false;
269   }
270   std::vector<char> v(len, '\0');
271   std::copy(s.begin(), s.end(), v.begin());
272   if (!Write(v.data(), v.size())) {
273     return false;
274   }
275   return WriteFeatureEnd(feature, start_offset);
276 }
277
278 bool RecordFileWriter::WriteCmdlineFeature(const std::vector<std::string>& cmdline) {
279   uint64_t start_offset;
280   if (!WriteFeatureBegin(&start_offset)) {
281     return false;
282   }
283   uint32_t arg_count = cmdline.size();
284   if (!Write(&arg_count, sizeof(arg_count))) {
285     return false;
286   }
287   for (auto& arg : cmdline) {
288     uint32_t len = static_cast<uint32_t>(ALIGN(arg.size() + 1, 64));
289     if (!Write(&len, sizeof(len))) {
290       return false;
291     }
292     std::vector<char> array(len, '\0');
293     std::copy(arg.begin(), arg.end(), array.begin());
294     if (!Write(array.data(), array.size())) {
295       return false;
296     }
297   }
298   return WriteFeatureEnd(FEAT_CMDLINE, start_offset);
299 }
300
301 bool RecordFileWriter::WriteBranchStackFeature() {
302   uint64_t start_offset;
303   if (!WriteFeatureBegin(&start_offset)) {
304     return false;
305   }
306   return WriteFeatureEnd(FEAT_BRANCH_STACK, start_offset);
307 }
308
309 bool RecordFileWriter::WriteFeatureBegin(uint64_t* start_offset) {
310   CHECK_LT(current_feature_index_, feature_count_);
311   if (!SeekFileEnd(start_offset)) {
312     return false;
313   }
314   return true;
315 }
316
317 bool RecordFileWriter::WriteFeatureEnd(int feature, uint64_t start_offset) {
318   uint64_t end_offset;
319   if (!SeekFileEnd(&end_offset)) {
320     return false;
321   }
322   SectionDesc desc;
323   desc.offset = start_offset;
324   desc.size = end_offset - start_offset;
325   uint64_t feature_offset = data_section_offset_ + data_section_size_;
326   if (fseek(record_fp_, feature_offset + current_feature_index_ * sizeof(SectionDesc), SEEK_SET) ==
327       -1) {
328     PLOG(ERROR) << "fseek() failed";
329     return false;
330   }
331   if (!Write(&desc, sizeof(SectionDesc))) {
332     return false;
333   }
334   ++current_feature_index_;
335   features_.push_back(feature);
336   return true;
337 }
338
339 bool RecordFileWriter::WriteFileHeader() {
340   FileHeader header;
341   memset(&header, 0, sizeof(header));
342   memcpy(header.magic, PERF_MAGIC, sizeof(header.magic));
343   header.header_size = sizeof(header);
344   header.attr_size = sizeof(FileAttr);
345   header.attrs.offset = attr_section_offset_;
346   header.attrs.size = attr_section_size_;
347   header.data.offset = data_section_offset_;
348   header.data.size = data_section_size_;
349   for (auto& feature : features_) {
350     int i = feature / 8;
351     int j = feature % 8;
352     header.features[i] |= (1 << j);
353   }
354
355   if (fseek(record_fp_, 0, SEEK_SET) == -1) {
356     return false;
357   }
358   if (!Write(&header, sizeof(header))) {
359     return false;
360   }
361   return true;
362 }
363
364 bool RecordFileWriter::Close() {
365   CHECK(record_fp_ != nullptr);
366   bool result = true;
367
368   // Write file header. We gather enough information to write file header only after
369   // writing data section and feature section.
370   if (!WriteFileHeader()) {
371     result = false;
372   }
373
374   if (fclose(record_fp_) != 0) {
375     PLOG(ERROR) << "failed to close record file '" << filename_ << "'";
376     result = false;
377   }
378   record_fp_ = nullptr;
379   return result;
380 }