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