2 * Copyright (C) 2015 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.
22 #include <base/logging.h>
25 #include "environment.h"
26 #include "event_selection_set.h"
27 #include "event_type.h"
28 #include "record_file.h"
32 static std::string default_measured_event_type = "cpu-cycles";
34 class RecordCommandImpl {
37 : use_sample_freq_(true),
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) {});
47 ~RecordCommandImpl() {
48 signal(SIGCHLD, saved_sigchild_handler_);
51 bool Run(const std::vector<std::string>& args);
53 static bool ReadMmapDataCallback(const char* data, size_t size);
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);
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.
65 bool system_wide_collection_;
66 const EventType* measured_event_type_;
67 EventSelectionSet event_selection_set_;
69 // mmap pages used by each perf event file, should be power of 2.
70 const size_t perf_mmap_pages_;
72 std::string record_filename_;
73 std::unique_ptr<RecordFileWriter> record_file_writer_;
75 sighandler_t saved_sigchild_handler_;
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)) {
84 if (measured_event_type_ == nullptr) {
85 if (!SetMeasuredEventType(default_measured_event_type)) {
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"});
96 std::unique_ptr<Workload> workload = Workload::CreateWorkload(workload_args);
97 if (workload == nullptr) {
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()) {
108 event_selection_set_.EnableOnExec();
109 if (!event_selection_set_.OpenEventFilesForProcess(workload->GetPid())) {
113 if (!event_selection_set_.MmapEventFiles(perf_mmap_pages_)) {
116 std::vector<pollfd> pollfds;
117 event_selection_set_.PreparePollForEventFiles(&pollfds);
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) {
127 // 5. Dump records in mmap buffers of perf_event_files to output file while workload is running.
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()) {
136 if (!workload->Start()) {
140 std::bind(&RecordCommandImpl::WriteData, this, std::placeholders::_1, std::placeholders::_2);
142 if (!event_selection_set_.ReadMmapEventData(callback)) {
145 if (workload->IsFinished()) {
148 poll(&pollfds[0], pollfds.size(), -1);
151 // 6. Close record file.
152 if (!record_file_writer_->Close()) {
158 bool RecordCommandImpl::ParseOptions(const std::vector<std::string>& args,
159 std::vector<std::string>* non_option_args) {
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)) {
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] << "'";
174 use_sample_freq_ = false;
175 } else if (args[i] == "-e") {
176 if (!NextArgumentOrError(args, &i)) {
179 if (!SetMeasuredEventType(args[i])) {
182 } else if (args[i] == "-f" || args[i] == "-F") {
183 if (!NextArgumentOrError(args, &i)) {
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] << "'";
192 use_sample_freq_ = true;
193 } else if (args[i] == "-o") {
194 if (!NextArgumentOrError(args, &i)) {
197 record_filename_ = args[i];
199 LOG(ERROR) << "Unknown option for record command: '" << args[i] << "'\n";
200 LOG(ERROR) << "Try `simpleperf help record`";
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]);
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) {
219 measured_event_type_ = event_type;
223 void RecordCommandImpl::SetEventSelection() {
224 event_selection_set_.AddEventType(*measured_event_type_);
225 if (use_sample_freq_) {
226 event_selection_set_.SetSampleFreq(sample_freq_);
228 event_selection_set_.SetSamplePeriod(sample_period_);
230 event_selection_set_.SampleIdAll();
233 bool RecordCommandImpl::WriteData(const char* data, size_t size) {
234 return record_file_writer_->WriteData(data, size);
237 class RecordCommand : public Command {
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") {
253 bool Run(const std::vector<std::string>& args) override {
254 RecordCommandImpl impl;
255 return impl.Run(args);
259 RecordCommand record_command;