• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
186 extern void RegisterBootRecordCommand();
187 extern void RegisterDumpRecordCommand();
188 extern void RegisterHelpCommand();
189 extern void RegisterInjectCommand();
190 extern void RegisterListCommand();
191 extern void RegisterKmemCommand();
192 extern void RegisterMergeCommand();
193 extern void RegisterRecordCommand();
194 extern void RegisterReportCommand();
195 extern void RegisterReportSampleCommand();
196 extern void RegisterStatCommand();
197 extern void RegisterDebugUnwindCommand();
198 extern void RegisterTraceSchedCommand();
199 extern void RegisterAPICommands();
200 extern void RegisterMonitorCommand();
201 
202 class CommandRegister {
203  public:
CommandRegister()204   CommandRegister() {
205     RegisterDumpRecordCommand();
206     RegisterHelpCommand();
207     RegisterInjectCommand();
208     RegisterKmemCommand();
209     RegisterMergeCommand();
210     RegisterReportCommand();
211     RegisterReportSampleCommand();
212 #if defined(__linux__)
213     RegisterListCommand();
214     RegisterRecordCommand();
215     RegisterStatCommand();
216     RegisterDebugUnwindCommand();
217     RegisterTraceSchedCommand();
218     RegisterMonitorCommand();
219 #if defined(__ANDROID__)
220     RegisterAPICommands();
221     RegisterBootRecordCommand();
222 #endif
223 #endif
224   }
225 };
226 
227 CommandRegister command_register;
228 
StderrLogger(android::base::LogId,android::base::LogSeverity severity,const char *,const char * file,unsigned int line,const char * message)229 static void StderrLogger(android::base::LogId, android::base::LogSeverity severity, const char*,
230                          const char* file, unsigned int line, const char* message) {
231   static const char log_characters[] = "VDIWEFF";
232   char severity_char = log_characters[severity];
233   fprintf(stderr, "simpleperf %c %s:%u] %s\n", severity_char, file, line, message);
234 }
235 
236 bool log_to_android_buffer = false;
237 
RunSimpleperfCmd(int argc,char ** argv)238 bool RunSimpleperfCmd(int argc, char** argv) {
239   android::base::InitLogging(argv, StderrLogger);
240   std::vector<std::string> args;
241   android::base::LogSeverity log_severity = android::base::INFO;
242   log_to_android_buffer = false;
243   const OptionFormatMap& common_option_formats = GetCommonOptionFormatMap();
244 
245   int i;
246   for (i = 1; i < argc && strcmp(argv[i], "--") != 0; ++i) {
247     std::string option_name = argv[i];
248     auto it = common_option_formats.find(option_name);
249     if (it == common_option_formats.end()) {
250       args.emplace_back(std::move(option_name));
251       continue;
252     }
253     if (it->second.value_type != OptionValueType::NONE && i + 1 == argc) {
254       LOG(ERROR) << "Missing argument for " << option_name;
255       return false;
256     }
257     if (option_name == "-h" || option_name == "--help") {
258       args.insert(args.begin(), "help");
259     } else if (option_name == "--log") {
260       if (!GetLogSeverity(argv[i + 1], &log_severity)) {
261         LOG(ERROR) << "Unknown log severity: " << argv[i + 1];
262       }
263       ++i;
264 #if defined(__ANDROID__)
265     } else if (option_name == "--log-to-android-buffer") {
266       android::base::SetLogger(android::base::LogdLogger());
267       log_to_android_buffer = true;
268 #endif
269     } else if (option_name == "--version") {
270       LOG(INFO) << "Simpleperf version " << GetSimpleperfVersion();
271       return true;
272     } else {
273       CHECK(false) << "Unreachable code";
274     }
275   }
276   while (i < argc) {
277     args.emplace_back(argv[i++]);
278   }
279 
280   android::base::ScopedLogSeverity severity(log_severity);
281 
282   if (args.empty()) {
283     args.push_back("help");
284   }
285   std::unique_ptr<Command> command = CreateCommandInstance(args[0]);
286   if (command == nullptr) {
287     LOG(ERROR) << "malformed command line: unknown command " << args[0];
288     return false;
289   }
290   std::string command_name = args[0];
291   args.erase(args.begin());
292 
293   LOG(DEBUG) << "command '" << command_name << "' starts running";
294   int exit_code;
295   command->Run(args, &exit_code);
296   LOG(DEBUG) << "command '" << command_name << "' "
297              << (exit_code == 0 ? "finished successfully" : "failed");
298   // Quick exit to avoid the cost of freeing memory and closing files.
299   fflush(stdout);
300   fflush(stderr);
301   _Exit(exit_code);
302   return exit_code == 0;
303 }
304 
305 }  // namespace simpleperf
306