summaryrefslogtreecommitdiff
path: root/simpleperf/cmd_inject.cpp
blob: e14e32f0072a16b2b785af4b5586137fad321b07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>

#include <memory>
#include <string>

#include "ETMDecoder.h"
#include "command.h"
#include "record_file.h"
#include "thread_tree.h"

using namespace simpleperf;

namespace {

class InjectCommand : public Command {
 public:
  InjectCommand()
      : Command("inject", "convert etm instruction tracing data into instr ranges",
                // clang-format off
"Usage: simpleperf inject [options]\n"
"-i <file>                    input perf.data, generated by recording cs-etm event type.\n"
"                             Default is perf.data.\n"
"-o <file>                    output file. Default is perf_inject.data.\n"
"--dump-etm type1,type2,...   Dump etm data. A type is one of raw, packet and element.\n"
"--symdir <dir>               Look for binaries in a directory recursively.\n"
                // clang-format on
                ),
        output_fp_(nullptr, fclose) {}

  bool Run(const std::vector<std::string>& args) override {
    if (!ParseOptions(args)) {
      return false;
    }
    record_file_reader_ = RecordFileReader::CreateInstance(input_filename_);
    if (!record_file_reader_) {
      return false;
    }
    record_file_reader_->LoadBuildIdAndFileFeatures(thread_tree_);
    output_fp_.reset(fopen(output_filename_.c_str(), "w"));
    if (!output_fp_) {
      PLOG(ERROR) << "failed to write to " << output_filename_;
      return false;
    }
    if (!record_file_reader_->ReadDataSection([this](auto r) { return ProcessRecord(r.get()); })) {
      return false;
    }
    output_fp_.reset(nullptr);
    return true;
  }

 private:
  bool ParseOptions(const std::vector<std::string>& args) {
    for (size_t i = 0; i < args.size(); i++) {
      if (args[i] == "-i") {
        if (!NextArgumentOrError(args, &i)) {
          return false;
        }
        input_filename_ = args[i];
      } else if (args[i] == "-o") {
        if (!NextArgumentOrError(args, &i)) {
          return false;
        }
        output_filename_ = args[i];
      } else if (args[i] == "--dump-etm") {
        if (!NextArgumentOrError(args, &i) || !ParseEtmDumpOption(args[i], &etm_dump_option_)) {
          return false;
        }
      } else if (args[i] == "--symdir") {
        if (!NextArgumentOrError(args, &i) || !Dso::AddSymbolDir(args[i])) {
          return false;
        }
      } else {
        ReportUnknownOption(args, i);
        return false;
      }
    }
    return true;
  }

  bool ProcessRecord(Record* r) {
    thread_tree_.Update(*r);
    if (r->type() == PERF_RECORD_AUXTRACE_INFO) {
      auto instr_range_callback = [this](auto& range) { ProcessInstrRange(range); };
      etm_decoder_ = ETMDecoder::Create(*static_cast<AuxTraceInfoRecord*>(r), thread_tree_);
      if (!etm_decoder_) {
        return false;
      }
      etm_decoder_->EnableDump(etm_dump_option_);
      etm_decoder_->RegisterCallback(instr_range_callback);
    } else if (r->type() == PERF_RECORD_AUX) {
      AuxRecord* aux = static_cast<AuxRecord*>(r);
      uint64_t aux_size = aux->data->aux_size;
      if (aux_size > 0) {
        if (aux_data_buffer_.size() < aux_size) {
          aux_data_buffer_.resize(aux_size);
        }
        if (!record_file_reader_->ReadAuxData(aux->Cpu(), aux->data->aux_offset,
                                              aux_data_buffer_.data(), aux_size)) {
          LOG(ERROR) << "failed to read aux data";
          return false;
        }
        return etm_decoder_->ProcessData(aux_data_buffer_.data(), aux_size);
      }
    }
    return true;
  }

  void ProcessInstrRange(const ETMInstrRange& instr_range) {
    fprintf(output_fp_.get(),
            "dso %s, [0x%" PRIx64 "-0x%" PRIx64 "], branch_to 0x%" PRIx64 ", taken %" PRIu64
            ", not_taken %" PRIu64 "\n",
            instr_range.dso->GetDebugFilePath().c_str(), instr_range.start_addr,
            instr_range.end_addr, instr_range.branch_to_addr, instr_range.branch_taken_count,
            instr_range.branch_not_taken_count);
  }

  std::string input_filename_ = "perf.data";
  std::string output_filename_ = "perf_inject.data";
  ThreadTree thread_tree_;
  std::unique_ptr<RecordFileReader> record_file_reader_;
  ETMDumpOption etm_dump_option_;
  std::unique_ptr<ETMDecoder> etm_decoder_;
  std::vector<uint8_t> aux_data_buffer_;
  std::unique_ptr<FILE, decltype(&fclose)> output_fp_;
};

}  // namespace

void RegisterInjectCommand() {
  return RegisterCommand("inject", [] { return std::unique_ptr<Command>(new InjectCommand); });
}