2 * Copyright (C) 2018 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <unordered_map>
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/parseint.h>
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
29 #include "CallChainJoiner.h"
31 #include "environment.h"
32 #include "OfflineUnwinder.h"
33 #include "perf_regs.h"
34 #include "record_file.h"
35 #include "thread_tree.h"
39 using namespace simpleperf;
41 // Cache size used by CallChainJoiner to cache call chains in memory.
42 constexpr size_t DEFAULT_CALL_CHAIN_JOINER_CACHE_SIZE = 8 * 1024 * 1024;
50 std::string ToString() const {
51 return android::base::StringPrintf("VmPeak:%s;VmSize:%s;VmHWM:%s;VmRSS:%s", vm_peak.c_str(),
52 vm_size.c_str(), vm_hwm.c_str(), vm_rss.c_str());
56 static bool GetMemStat(MemStat* stat) {
58 if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/status", getpid()),
60 PLOG(ERROR) << "Failed to read process status";
63 std::vector<std::string> lines = android::base::Split(s, "\n");
64 for (auto& line : lines) {
65 if (android::base::StartsWith(line, "VmPeak:")) {
66 stat->vm_peak = android::base::Trim(line.substr(strlen("VmPeak:")));
67 } else if (android::base::StartsWith(line, "VmSize:")) {
68 stat->vm_size = android::base::Trim(line.substr(strlen("VmSize:")));
69 } else if (android::base::StartsWith(line, "VmHWM:")) {
70 stat->vm_hwm = android::base::Trim(line.substr(strlen("VmHWM:")));
71 } else if (android::base::StartsWith(line, "VmRSS:")) {
72 stat->vm_rss = android::base::Trim(line.substr(strlen("VmRSS:")));
78 class DebugUnwindCommand : public Command {
81 : Command("debug-unwind", "Debug/test offline unwinding.",
83 "Usage: simpleperf debug-unwind [options]\n"
84 " Given a perf.data generated with \"-g --no-unwind\", it converts\n"
85 " regs/stack data of samples into callchains, and write result into\n"
86 " a new perf.data. The new perf.data can be passed to\n"
87 " unwind_result_reporter.py to generate a text report.\n"
88 "-i <file> The path of record file generated with \"-g --no-unwind\".\n"
89 " Default is perf.data.\n"
90 "-o <file> The path ot write new perf.data. Default is perf.data.debug.\n"
91 "--symfs <dir> Look for files with symbols relative to this directory.\n"
92 "--time time Only unwind samples recorded at selected time.\n"
95 input_filename_("perf.data"),
96 output_filename_("perf.data.debug"),
97 offline_unwinder_(true),
98 callchain_joiner_(DEFAULT_CALL_CHAIN_JOINER_CACHE_SIZE, 1, true),
102 bool Run(const std::vector<std::string>& args);
105 bool ParseOptions(const std::vector<std::string>& args);
106 bool UnwindRecordFile();
107 bool ProcessRecord(Record* record);
108 void CollectHitFileInfo(const SampleRecord& r, const std::vector<uint64_t>& ips);
109 bool JoinCallChains();
110 bool WriteFeatureSections();
114 // For testing unwinding performance.
115 uint64_t unwinding_sample_count = 0u;
116 uint64_t total_unwinding_time_in_ns = 0u;
117 uint64_t max_unwinding_time_in_ns = 0u;
119 // For memory consumption.
120 MemStat mem_before_unwinding;
121 MemStat mem_after_unwinding;
124 std::string input_filename_;
125 std::string output_filename_;
126 std::unique_ptr<RecordFileReader> reader_;
127 std::unique_ptr<RecordFileWriter> writer_;
128 ThreadTree thread_tree_;
129 OfflineUnwinder offline_unwinder_;
130 CallChainJoiner callchain_joiner_;
132 uint64_t selected_time_;
135 bool DebugUnwindCommand::Run(const std::vector<std::string>& args) {
137 if (!ParseOptions(args)) {
141 // 2. Read input perf.data, and generate new perf.data.
142 if (!UnwindRecordFile()) {
146 // 3. Show stat of unwinding.
151 bool DebugUnwindCommand::ParseOptions(const std::vector<std::string>& args) {
152 for (size_t i = 0; i < args.size(); ++i) {
153 if (args[i] == "-i") {
154 if (!NextArgumentOrError(args, &i)) {
157 input_filename_ = args[i];
158 } else if (args[i] == "-o") {
159 if (!NextArgumentOrError(args, &i)) {
162 output_filename_ = args[i];
163 } else if (args[i] == "--symfs") {
164 if (!NextArgumentOrError(args, &i)) {
167 if (!Dso::SetSymFsDir(args[i])) {
170 } else if (args[i] == "--time") {
171 if (!NextArgumentOrError(args, &i)) {
174 if (!android::base::ParseUint(args[i].c_str(), &selected_time_)) {
175 LOG(ERROR) << "Invalid option for " << args[i-1] << ": " << args[i];
179 ReportUnknownOption(args, i);
183 SetTempDirectoryUsedInRecording(android::base::Dirname(output_filename_));
187 bool DebugUnwindCommand::UnwindRecordFile() {
188 // 1. Check input file.
189 reader_ = RecordFileReader::CreateInstance(input_filename_);
193 std::string record_cmd = android::base::Join(reader_->ReadCmdlineFeature(), " ");
194 if (record_cmd.find("--no-unwind") == std::string::npos ||
195 (record_cmd.find("-g") == std::string::npos &&
196 record_cmd.find("--call-graph dwarf") == std::string::npos)) {
197 LOG(ERROR) << input_filename_ << " isn't recorded with \"-g --no-unwind\"";
200 ScopedCurrentArch scoped_arch(GetArchType(reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH)));
202 // 2. Copy attr section.
203 writer_ = RecordFileWriter::CreateInstance(output_filename_);
204 if (!writer_ || !writer_->WriteAttrSection(reader_->AttrSection())) {
208 // 3. Process records in data section.
209 if (!GetMemStat(&stat_.mem_before_unwinding)) {
212 auto callback = [this](std::unique_ptr<Record> record) {
213 return ProcessRecord(record.get());
215 if (!reader_->ReadDataSection(callback)) {
218 if (!JoinCallChains()) {
221 if (!GetMemStat(&stat_.mem_after_unwinding)) {
225 // 4. Write feature sections.
226 return WriteFeatureSections();
229 bool DebugUnwindCommand::ProcessRecord(Record* record) {
230 if (record->type() == PERF_RECORD_SAMPLE) {
231 auto& r = *static_cast<SampleRecord*>(record);
232 if (selected_time_ != 0u && r.Timestamp() != selected_time_) {
235 r.AdjustCallChainGeneratedByKernel();
236 r.RemoveInvalidStackData();
237 uint64_t need_type = PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER;
238 if ((r.sample_type & need_type) == need_type && r.regs_user_data.reg_mask != 0 &&
239 r.GetValidStackSize() > 0) {
240 ThreadEntry* thread = thread_tree_.FindThreadOrNew(r.tid_data.pid, r.tid_data.tid);
241 RegSet regs(r.regs_user_data.abi, r.regs_user_data.reg_mask, r.regs_user_data.regs);
242 std::vector<uint64_t> ips;
243 std::vector<uint64_t> sps;
244 if (!offline_unwinder_.UnwindCallChain(*thread, regs, r.stack_user_data.data,
245 r.GetValidStackSize(), &ips, &sps)) {
249 const UnwindingResult& unwinding_result = offline_unwinder_.GetUnwindingResult();
250 stat_.unwinding_sample_count++;
251 stat_.total_unwinding_time_in_ns += unwinding_result.used_time;
252 stat_.max_unwinding_time_in_ns = std::max(stat_.max_unwinding_time_in_ns,
253 unwinding_result.used_time);
254 if (!writer_->WriteRecord(UnwindingResultRecord(r.time_data.time, unwinding_result))) {
257 // We want to keep both reg/stack data and callchain of a sample. However, storing both
258 // can exceed the size limit of a SampleRecord. So instead we store one sample with reg/stack
259 // data and one sample with callchain.
260 if (!writer_->WriteRecord(r)) {
263 r.ReplaceRegAndStackWithCallChain(ips);
264 if (!callchain_joiner_.AddCallChain(r.tid_data.pid, r.tid_data.tid,
265 CallChainJoiner::ORIGINAL_OFFLINE, ips, sps)) {
268 CollectHitFileInfo(r, ips);
271 thread_tree_.Update(*record);
273 return writer_->WriteRecord(*record);
276 void DebugUnwindCommand::CollectHitFileInfo(const SampleRecord& r,
277 const std::vector<uint64_t>& ips) {
278 const ThreadEntry* thread = thread_tree_.FindThreadOrNew(r.tid_data.pid, r.tid_data.tid);
279 for (auto ip : ips) {
280 const MapEntry* map = thread_tree_.FindMap(thread, ip, false);
282 if (!dso->HasDumpId()) {
285 const Symbol* symbol = thread_tree_.FindSymbol(map, ip, nullptr, &dso);
286 if (!symbol->HasDumpId()) {
287 dso->CreateSymbolDumpId(symbol);
292 bool DebugUnwindCommand::JoinCallChains() {
293 // 1. Prepare joined callchains.
294 if (!callchain_joiner_.JoinCallChains()) {
297 // 2. Move records from record_filename_ to a temporary file.
298 if (!writer_->Close()) {
302 std::unique_ptr<TemporaryFile> tmpfile = CreateTempFileUsedInRecording();
303 if (!Workload::RunCmd({"mv", output_filename_, tmpfile->path})) {
307 // 3. Read records from the temporary file, and write records with joined call chains back
308 // to record_filename_.
309 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile->path);
313 writer_ = RecordFileWriter::CreateInstance(output_filename_);
314 if (!writer_ || !writer_->WriteAttrSection(reader->AttrSection())) {
318 auto record_callback = [&](std::unique_ptr<Record> r) {
319 if (r->type() != PERF_RECORD_SAMPLE) {
320 return writer_->WriteRecord(*r);
322 SampleRecord& sr = *static_cast<SampleRecord*>(r.get());
323 if (!sr.HasUserCallChain()) {
324 return writer_->WriteRecord(sr);
328 CallChainJoiner::ChainType type;
329 std::vector<uint64_t> ips;
330 std::vector<uint64_t> sps;
332 if (!callchain_joiner_.GetNextCallChain(pid, tid, type, ips, sps)) {
335 if (!writer_->WriteRecord(CallChainRecord(pid, tid, type, sr.Timestamp(), ips, sps))) {
338 } while (type != CallChainJoiner::JOINED_OFFLINE);
339 CHECK_EQ(pid, static_cast<pid_t>(sr.tid_data.pid));
340 CHECK_EQ(tid, static_cast<pid_t>(sr.tid_data.tid));
341 sr.UpdateUserCallChain(ips);
342 return writer_->WriteRecord(sr);
344 return reader->ReadDataSection(record_callback, false);
347 bool DebugUnwindCommand::WriteFeatureSections() {
348 // Add debug_unwind info in META_INFO section, and add symbol info in FILE section.
349 const std::map<int, PerfFileFormat::SectionDesc>& features = reader_->FeatureSectionDescriptors();
350 size_t new_feature_count = features.size();
351 for (int feature : {PerfFileFormat::FEAT_FILE, PerfFileFormat::FEAT_META_INFO}) {
352 if (features.find(feature) == features.end()) {
356 if (!writer_->BeginWriteFeatures(new_feature_count)) {
360 auto it = features.begin();
361 // Copy all feature sections except FEAT_FILE and FEAT_META_INFO, which require special handling.
362 while (it != features.end() && it->first < PerfFileFormat::FEAT_FILE) {
363 std::vector<char> data;
364 if (!reader_->ReadFeatureSection(it->first, &data) || !writer_->WriteFeature(it->first, data)) {
369 // Write a new file section.
370 if (it != features.end() && it->first == PerfFileFormat::FEAT_FILE) {
373 if (!writer_->WriteFileFeatures(thread_tree_.GetAllDsos())) {
376 // Write meta_info section.
377 std::unordered_map<std::string, std::string> info_map;
378 if (it != features.end() && it->first == PerfFileFormat::FEAT_META_INFO) {
379 if (!reader_->ReadMetaInfoFeature(&info_map)) {
384 info_map["debug_unwind"] = "true";
385 info_map["debug_unwind_mem_before"] = stat_.mem_before_unwinding.ToString();
386 info_map["debug_unwind_mem_after"] = stat_.mem_after_unwinding.ToString();
387 if (!writer_->WriteMetaInfoFeature(info_map)) {
390 CHECK(it == features.end());
391 return writer_->EndWriteFeatures() && writer_->Close();
394 void DebugUnwindCommand::PrintStat() {
395 printf("Unwinding sample count: %" PRIu64 "\n", stat_.unwinding_sample_count);
396 if (stat_.unwinding_sample_count > 0u) {
397 printf("Average unwinding time: %f us\n", static_cast<double>(stat_.total_unwinding_time_in_ns)
398 / 1000 / stat_.unwinding_sample_count);
399 printf("Max unwinding time: %f us\n", static_cast<double>(stat_.max_unwinding_time_in_ns)
402 printf("Memory change:\n");
403 PrintIndented(1, "VmPeak: %s -> %s\n", stat_.mem_before_unwinding.vm_peak.c_str(),
404 stat_.mem_after_unwinding.vm_peak.c_str());
405 PrintIndented(1, "VmSize: %s -> %s\n", stat_.mem_before_unwinding.vm_size.c_str(),
406 stat_.mem_after_unwinding.vm_size.c_str());
407 PrintIndented(1, "VmHWM: %s -> %s\n", stat_.mem_before_unwinding.vm_hwm.c_str(),
408 stat_.mem_after_unwinding.vm_hwm.c_str());
409 PrintIndented(1, "VmRSS: %s -> %s\n", stat_.mem_before_unwinding.vm_rss.c_str(),
410 stat_.mem_after_unwinding.vm_rss.c_str());
411 callchain_joiner_.DumpStat();
412 printf("Please use debug_unwind_reporter.py to get a report in details.\n");
415 void RegisterDebugUnwindCommand() {
416 RegisterCommand("debug-unwind",
417 []{ return std::unique_ptr<Command>(new DebugUnwindCommand()); });