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