OSDN Git Service

e835acd6ca78b339c6f00ea85e03e7d8c0174f77
[android-x86/system-extras.git] / simpleperf / cmd_record.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 <poll.h>
18 #include <signal.h>
19 #include <string>
20 #include <vector>
21
22 #include <base/logging.h>
23
24 #include "command.h"
25 #include "environment.h"
26 #include "event_selection_set.h"
27 #include "event_type.h"
28 #include "record_file.h"
29 #include "utils.h"
30 #include "workload.h"
31
32 static std::string default_measured_event_type = "cpu-cycles";
33
34 class RecordCommandImpl {
35  public:
36   RecordCommandImpl()
37       : use_sample_freq_(true),
38         sample_freq_(1000),
39         system_wide_collection_(false),
40         measured_event_type_(nullptr),
41         perf_mmap_pages_(256),
42         record_filename_("perf.data") {
43     // We need signal SIGCHLD to break poll().
44     saved_sigchild_handler_ = signal(SIGCHLD, [](int) {});
45   }
46
47   ~RecordCommandImpl() {
48     signal(SIGCHLD, saved_sigchild_handler_);
49   }
50
51   bool Run(const std::vector<std::string>& args);
52
53   static bool ReadMmapDataCallback(const char* data, size_t size);
54
55  private:
56   bool ParseOptions(const std::vector<std::string>& args, std::vector<std::string>* non_option_args);
57   bool SetMeasuredEventType(const std::string& event_type_name);
58   void SetEventSelection();
59   bool WriteData(const char* data, size_t size);
60
61   bool use_sample_freq_;    // Use sample_freq_ when true, otherwise using sample_period_.
62   uint64_t sample_freq_;    // Sample 'sample_freq_' times per second.
63   uint64_t sample_period_;  // Sample once when 'sample_period_' events occur.
64
65   bool system_wide_collection_;
66   const EventType* measured_event_type_;
67   EventSelectionSet event_selection_set_;
68
69   // mmap pages used by each perf event file, should be power of 2.
70   const size_t perf_mmap_pages_;
71
72   std::string record_filename_;
73   std::unique_ptr<RecordFileWriter> record_file_writer_;
74
75   sighandler_t saved_sigchild_handler_;
76 };
77
78 bool RecordCommandImpl::Run(const std::vector<std::string>& args) {
79   // 1. Parse options, and use default measured event type if not given.
80   std::vector<std::string> workload_args;
81   if (!ParseOptions(args, &workload_args)) {
82     return false;
83   }
84   if (measured_event_type_ == nullptr) {
85     if (!SetMeasuredEventType(default_measured_event_type)) {
86       return false;
87     }
88   }
89   SetEventSelection();
90
91   // 2. Create workload.
92   if (workload_args.empty()) {
93     // TODO: change default workload to sleep 99999, and run record until Ctrl-C.
94     workload_args = std::vector<std::string>({"sleep", "1"});
95   }
96   std::unique_ptr<Workload> workload = Workload::CreateWorkload(workload_args);
97   if (workload == nullptr) {
98     return false;
99   }
100
101   // 3. Open perf_event_files, create memory mapped buffers for perf_event_files, add prepare poll
102   //    for perf_event_files.
103   if (system_wide_collection_) {
104     if (!event_selection_set_.OpenEventFilesForAllCpus()) {
105       return false;
106     }
107   } else {
108     event_selection_set_.EnableOnExec();
109     if (!event_selection_set_.OpenEventFilesForProcess(workload->GetPid())) {
110       return false;
111     }
112   }
113   if (!event_selection_set_.MmapEventFiles(perf_mmap_pages_)) {
114     return false;
115   }
116   std::vector<pollfd> pollfds;
117   event_selection_set_.PreparePollForEventFiles(&pollfds);
118
119   // 4. Open record file writer.
120   record_file_writer_ = RecordFileWriter::CreateInstance(
121       record_filename_, event_selection_set_.FindEventAttrByType(*measured_event_type_),
122       event_selection_set_.FindEventFdsByType(*measured_event_type_));
123   if (record_file_writer_ == nullptr) {
124     return false;
125   }
126
127   // 5. Dump records in mmap buffers of perf_event_files to output file while workload is running.
128
129   // If monitoring only one process, we use the enable_on_exec flag, and don't need to start
130   // recording manually.
131   if (system_wide_collection_) {
132     if (!event_selection_set_.EnableEvents()) {
133       return false;
134     }
135   }
136   if (!workload->Start()) {
137     return false;
138   }
139   auto callback =
140       std::bind(&RecordCommandImpl::WriteData, this, std::placeholders::_1, std::placeholders::_2);
141   while (true) {
142     if (!event_selection_set_.ReadMmapEventData(callback)) {
143       return false;
144     }
145     if (workload->IsFinished()) {
146       break;
147     }
148     poll(&pollfds[0], pollfds.size(), -1);
149   }
150
151   // 6. Close record file.
152   if (!record_file_writer_->Close()) {
153     return false;
154   }
155   return true;
156 }
157
158 bool RecordCommandImpl::ParseOptions(const std::vector<std::string>& args,
159                                      std::vector<std::string>* non_option_args) {
160   size_t i;
161   for (i = 1; i < args.size() && args[i].size() > 0 && args[i][0] == '-'; ++i) {
162     if (args[i] == "-a") {
163       system_wide_collection_ = true;
164     } else if (args[i] == "-c") {
165       if (!NextArgumentOrError(args, &i)) {
166         return false;
167       }
168       char* endptr;
169       sample_period_ = strtoull(args[i].c_str(), &endptr, 0);
170       if (*endptr != '\0' || sample_period_ == 0) {
171         LOG(ERROR) << "Invalid sample period: '" << args[i] << "'";
172         return false;
173       }
174       use_sample_freq_ = false;
175     } else if (args[i] == "-e") {
176       if (!NextArgumentOrError(args, &i)) {
177         return false;
178       }
179       if (!SetMeasuredEventType(args[i])) {
180         return false;
181       }
182     } else if (args[i] == "-f" || args[i] == "-F") {
183       if (!NextArgumentOrError(args, &i)) {
184         return false;
185       }
186       char* endptr;
187       sample_freq_ = strtoull(args[i].c_str(), &endptr, 0);
188       if (*endptr != '\0' || sample_freq_ == 0) {
189         LOG(ERROR) << "Invalid sample frequency: '" << args[i] << "'";
190         return false;
191       }
192       use_sample_freq_ = true;
193     } else if (args[i] == "-o") {
194       if (!NextArgumentOrError(args, &i)) {
195         return false;
196       }
197       record_filename_ = args[i];
198     } else {
199       LOG(ERROR) << "Unknown option for record command: '" << args[i] << "'\n";
200       LOG(ERROR) << "Try `simpleperf help record`";
201       return false;
202     }
203   }
204
205   if (non_option_args != nullptr) {
206     non_option_args->clear();
207     for (; i < args.size(); ++i) {
208       non_option_args->push_back(args[i]);
209     }
210   }
211   return true;
212 }
213
214 bool RecordCommandImpl::SetMeasuredEventType(const std::string& event_type_name) {
215   const EventType* event_type = EventTypeFactory::FindEventTypeByName(event_type_name);
216   if (event_type == nullptr) {
217     return false;
218   }
219   measured_event_type_ = event_type;
220   return true;
221 }
222
223 void RecordCommandImpl::SetEventSelection() {
224   event_selection_set_.AddEventType(*measured_event_type_);
225   if (use_sample_freq_) {
226     event_selection_set_.SetSampleFreq(sample_freq_);
227   } else {
228     event_selection_set_.SetSamplePeriod(sample_period_);
229   }
230   event_selection_set_.SampleIdAll();
231 }
232
233 bool RecordCommandImpl::WriteData(const char* data, size_t size) {
234   return record_file_writer_->WriteData(data, size);
235 }
236
237 class RecordCommand : public Command {
238  public:
239   RecordCommand()
240       : Command("record", "record sampling info in perf.data",
241                 "Usage: simpleperf record [options] [command [command-args]]\n"
242                 "    Gather sampling information when running [command]. If [command]\n"
243                 "    is not specified, sleep 1 is used instead.\n"
244                 "    -a           System-wide collection.\n"
245                 "    -c count     Set event sample period.\n"
246                 "    -e event     Select the event to sample (Use `simpleperf list`)\n"
247                 "                 to find all possible event names.\n"
248                 "    -f freq      Set event sample frequency.\n"
249                 "    -F freq      Same as '-f freq'.\n"
250                 "    -o record_file_name    Set record file name, default is perf.data.\n") {
251   }
252
253   bool Run(const std::vector<std::string>& args) override {
254     RecordCommandImpl impl;
255     return impl.Run(args);
256   }
257 };
258
259 RecordCommand record_command;