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 "command.h"
18
19 #include <string.h>
20
21 #include <algorithm>
22 #include <map>
23 #include <string>
24 #include <vector>
25
26 #include <android-base/logging.h>
27 #include <android-base/parsedouble.h>
28 #include <android-base/parseint.h>
29
30 #include "utils.h"
31
32 namespace simpleperf {
33
NextArgumentOrError(const std::vector<std::string> & args,size_t * pi)34 bool Command::NextArgumentOrError(const std::vector<std::string>& args, size_t* pi) {
35 if (*pi + 1 == args.size()) {
36 LOG(ERROR) << "No argument following " << args[*pi] << " option. Try `simpleperf help " << name_
37 << "`";
38 return false;
39 }
40 ++*pi;
41 return true;
42 }
43
ConvertArgsToOptions(const std::vector<std::string> & args,const OptionFormatMap & option_formats,const std::string & help_msg,OptionValueMap * options,std::vector<std::pair<OptionName,OptionValue>> * ordered_options,std::vector<std::string> * non_option_args)44 bool ConvertArgsToOptions(const std::vector<std::string>& args,
45 const OptionFormatMap& option_formats, const std::string& help_msg,
46 OptionValueMap* options,
47 std::vector<std::pair<OptionName, OptionValue>>* ordered_options,
48 std::vector<std::string>* non_option_args) {
49 options->values.clear();
50 ordered_options->clear();
51 size_t i;
52 for (i = 0; i < args.size() && !args[i].empty() && args[i][0] == '-'; i++) {
53 auto it = option_formats.find(args[i]);
54 if (it == option_formats.end()) {
55 if (args[i] == "--") {
56 i++;
57 break;
58 }
59 LOG(ERROR) << "Unknown option " << args[i] << "." << help_msg;
60 return false;
61 }
62 const OptionName& name = it->first;
63 const OptionFormat& format = it->second;
64 OptionValue value;
65 memset(&value, 0, sizeof(value));
66
67 if (i + 1 == args.size()) {
68 if (format.value_type != OptionValueType::NONE &&
69 format.value_type != OptionValueType::OPT_STRING) {
70 LOG(ERROR) << "No argument following " << name << " option." << help_msg;
71 return false;
72 }
73 } else {
74 switch (format.value_type) {
75 case OptionValueType::NONE:
76 break;
77 case OptionValueType::STRING:
78 value.str_value = &args[++i];
79 break;
80 case OptionValueType::OPT_STRING:
81 if (!args[i + 1].empty() && args[i + 1][0] != '-') {
82 value.str_value = &args[++i];
83 }
84 break;
85 case OptionValueType::UINT:
86 if (!android::base::ParseUint(args[++i], &value.uint_value,
87 std::numeric_limits<uint64_t>::max(), true)) {
88 LOG(ERROR) << "Invalid argument for option " << name << ": " << args[i] << "."
89 << help_msg;
90 return false;
91 }
92 break;
93 case OptionValueType::DOUBLE:
94 if (!android::base::ParseDouble(args[++i], &value.double_value)) {
95 LOG(ERROR) << "Invalid argument for option " << name << ": " << args[i] << "."
96 << help_msg;
97 return false;
98 }
99 break;
100 }
101 }
102
103 switch (format.type) {
104 case OptionType::SINGLE:
105 if (auto it = options->values.find(name); it != options->values.end()) {
106 it->second = value;
107 } else {
108 options->values.emplace(name, value);
109 }
110 break;
111 case OptionType::MULTIPLE:
112 options->values.emplace(name, value);
113 break;
114 case OptionType::ORDERED:
115 ordered_options->emplace_back(name, value);
116 break;
117 }
118 }
119 if (i < args.size()) {
120 if (non_option_args == nullptr) {
121 LOG(ERROR) << "Invalid option " << args[i] << "." << help_msg;
122 return false;
123 }
124 non_option_args->assign(args.begin() + i, args.end());
125 }
126 return true;
127 }
128
PreprocessOptions(const std::vector<std::string> & args,const OptionFormatMap & option_formats,OptionValueMap * options,std::vector<std::pair<OptionName,OptionValue>> * ordered_options,std::vector<std::string> * non_option_args)129 bool Command::PreprocessOptions(const std::vector<std::string>& args,
130 const OptionFormatMap& option_formats, OptionValueMap* options,
131 std::vector<std::pair<OptionName, OptionValue>>* ordered_options,
132 std::vector<std::string>* non_option_args) {
133 const std::string help_msg = " Try `simpleperf help " + name_ + "`.";
134 return ConvertArgsToOptions(args, option_formats, help_msg, options, ordered_options,
135 non_option_args);
136 }
137
GetDoubleOption(const std::vector<std::string> & args,size_t * pi,double * value,double min,double max)138 bool Command::GetDoubleOption(const std::vector<std::string>& args, size_t* pi, double* value,
139 double min, double max) {
140 if (!NextArgumentOrError(args, pi)) {
141 return false;
142 }
143 if (!android::base::ParseDouble(args[*pi].c_str(), value, min, max)) {
144 LOG(ERROR) << "Invalid argument for option " << args[*pi - 1] << ": " << args[*pi];
145 return false;
146 }
147 return true;
148 }
149
ReportUnknownOption(const std::vector<std::string> & args,size_t i)150 void Command::ReportUnknownOption(const std::vector<std::string>& args, size_t i) {
151 LOG(ERROR) << "Unknown option for " << name_ << " command: '" << args[i]
152 << "'. Try `simpleperf help " << name_ << "`";
153 }
154
155 typedef std::function<std::unique_ptr<Command>(void)> callback_t;
156
CommandMap()157 static std::map<std::string, callback_t>& CommandMap() {
158 // commands is used in the constructor of Command. Defining it as a static
159 // variable in a function makes sure it is initialized before use.
160 static std::map<std::string, callback_t> command_map;
161 return command_map;
162 }
163
RegisterCommand(const std::string & cmd_name,const std::function<std::unique_ptr<Command> (void)> & callback)164 void RegisterCommand(const std::string& cmd_name,
165 const std::function<std::unique_ptr<Command>(void)>& callback) {
166 CommandMap().insert(std::make_pair(cmd_name, callback));
167 }
168
UnRegisterCommand(const std::string & cmd_name)169 void UnRegisterCommand(const std::string& cmd_name) {
170 CommandMap().erase(cmd_name);
171 }
172
CreateCommandInstance(const std::string & cmd_name)173 std::unique_ptr<Command> CreateCommandInstance(const std::string& cmd_name) {
174 auto it = CommandMap().find(cmd_name);
175 return (it == CommandMap().end()) ? nullptr : (it->second)();
176 }
177
GetAllCommandNames()178 const std::vector<std::string> GetAllCommandNames() {
179 std::vector<std::string> names;
180 for (const auto& pair : CommandMap()) {
181 names.push_back(pair.first);
182 }
183 return names;
184 }
185
RegisterAllCommands()186 void RegisterAllCommands() {
187 RegisterDumpRecordCommand();
188 RegisterHelpCommand();
189 RegisterInjectCommand();
190 RegisterKmemCommand();
191 RegisterMergeCommand();
192 RegisterReportCommand();
193 RegisterReportSampleCommand();
194 #if defined(__linux__)
195 RegisterListCommand();
196 RegisterRecordCommand();
197 RegisterStatCommand();
198 RegisterDebugUnwindCommand();
199 RegisterTraceSchedCommand();
200 RegisterMonitorCommand();
201 #if defined(__ANDROID__)
202 RegisterAPICommands();
203 RegisterBootRecordCommand();
204 #endif
205 #endif
206 }
207
StderrLogger(android::base::LogId,android::base::LogSeverity severity,const char *,const char * file,unsigned int line,const char * message)208 static void StderrLogger(android::base::LogId, android::base::LogSeverity severity, const char*,
209 const char* file, unsigned int line, const char* message) {
210 static const char log_characters[] = "VDIWEFF";
211 char severity_char = log_characters[severity];
212 fprintf(stderr, "simpleperf %c %s:%u] %s\n", severity_char, file, line, message);
213 }
214
215 bool log_to_android_buffer = false;
216
RunSimpleperfCmd(int argc,char ** argv)217 bool RunSimpleperfCmd(int argc, char** argv) {
218 android::base::InitLogging(argv, StderrLogger);
219 std::vector<std::string> args;
220 android::base::LogSeverity log_severity = android::base::INFO;
221 log_to_android_buffer = false;
222 const OptionFormatMap& common_option_formats = GetCommonOptionFormatMap();
223
224 int i;
225 for (i = 1; i < argc && strcmp(argv[i], "--") != 0; ++i) {
226 std::string option_name = argv[i];
227 auto it = common_option_formats.find(option_name);
228 if (it == common_option_formats.end()) {
229 args.emplace_back(std::move(option_name));
230 continue;
231 }
232 if (it->second.value_type != OptionValueType::NONE && i + 1 == argc) {
233 LOG(ERROR) << "Missing argument for " << option_name;
234 return false;
235 }
236 if (option_name == "-h" || option_name == "--help") {
237 args.insert(args.begin(), "help");
238 } else if (option_name == "--log") {
239 if (!GetLogSeverity(argv[i + 1], &log_severity)) {
240 LOG(ERROR) << "Unknown log severity: " << argv[i + 1];
241 }
242 ++i;
243 #if defined(__ANDROID__)
244 } else if (option_name == "--log-to-android-buffer") {
245 android::base::SetLogger(android::base::LogdLogger());
246 log_to_android_buffer = true;
247 #endif
248 } else if (option_name == "--version") {
249 LOG(INFO) << "Simpleperf version " << GetSimpleperfVersion();
250 return true;
251 } else {
252 CHECK(false) << "Unreachable code";
253 }
254 }
255 while (i < argc) {
256 args.emplace_back(argv[i++]);
257 }
258
259 android::base::ScopedLogSeverity severity(log_severity);
260
261 if (args.empty()) {
262 args.push_back("help");
263 }
264 std::unique_ptr<Command> command = CreateCommandInstance(args[0]);
265 if (command == nullptr) {
266 LOG(ERROR) << "malformed command line: unknown command " << args[0];
267 return false;
268 }
269 std::string command_name = args[0];
270 args.erase(args.begin());
271
272 LOG(DEBUG) << "command '" << command_name << "' starts running";
273 int exit_code;
274 command->Run(args, &exit_code);
275 LOG(DEBUG) << "command '" << command_name << "' "
276 << (exit_code == 0 ? "finished successfully" : "failed");
277 // Quick exit to avoid the cost of freeing memory and closing files.
278 fflush(stdout);
279 fflush(stderr);
280 _Exit(exit_code);
281 return exit_code == 0;
282 }
283
284 } // namespace simpleperf
285