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 <algorithm>
20 #include <map>
21 #include <string>
22 #include <vector>
23 
24 #include <android-base/logging.h>
25 #include <android-base/parsedouble.h>
26 #include <android-base/parseint.h>
27 #include <android-base/quick_exit.h>
28 
29 #include "utils.h"
30 
NextArgumentOrError(const std::vector<std::string> & args,size_t * pi)31 bool Command::NextArgumentOrError(const std::vector<std::string>& args, size_t* pi) {
32   if (*pi + 1 == args.size()) {
33     LOG(ERROR) << "No argument following " << args[*pi] << " option. Try `simpleperf help " << name_
34                << "`";
35     return false;
36   }
37   ++*pi;
38   return true;
39 }
40 
GetDoubleOption(const std::vector<std::string> & args,size_t * pi,double * value,double min,double max)41 bool Command::GetDoubleOption(const std::vector<std::string>& args, size_t* pi, double* value,
42                               double min, double max) {
43   if (!NextArgumentOrError(args, pi)) {
44     return false;
45   }
46   if (!android::base::ParseDouble(args[*pi].c_str(), value, min, max)) {
47     LOG(ERROR) << "Invalid argument for option " << args[*pi - 1] << ": " << args[*pi];
48     return false;
49   }
50   return true;
51 }
52 
ReportUnknownOption(const std::vector<std::string> & args,size_t i)53 void Command::ReportUnknownOption(const std::vector<std::string>& args, size_t i) {
54   LOG(ERROR) << "Unknown option for " << name_ << " command: '" << args[i]
55              << "'. Try `simpleperf help " << name_ << "`";
56 }
57 
58 typedef std::function<std::unique_ptr<Command>(void)> callback_t;
59 
CommandMap()60 static std::map<std::string, callback_t>& CommandMap() {
61   // commands is used in the constructor of Command. Defining it as a static
62   // variable in a function makes sure it is initialized before use.
63   static std::map<std::string, callback_t> command_map;
64   return command_map;
65 }
66 
RegisterCommand(const std::string & cmd_name,const std::function<std::unique_ptr<Command> (void)> & callback)67 void RegisterCommand(const std::string& cmd_name,
68                      const std::function<std::unique_ptr<Command>(void)>& callback) {
69   CommandMap().insert(std::make_pair(cmd_name, callback));
70 }
71 
UnRegisterCommand(const std::string & cmd_name)72 void UnRegisterCommand(const std::string& cmd_name) {
73   CommandMap().erase(cmd_name);
74 }
75 
CreateCommandInstance(const std::string & cmd_name)76 std::unique_ptr<Command> CreateCommandInstance(const std::string& cmd_name) {
77   auto it = CommandMap().find(cmd_name);
78   return (it == CommandMap().end()) ? nullptr : (it->second)();
79 }
80 
GetAllCommandNames()81 const std::vector<std::string> GetAllCommandNames() {
82   std::vector<std::string> names;
83   for (const auto& pair : CommandMap()) {
84     names.push_back(pair.first);
85   }
86   return names;
87 }
88 
89 extern void RegisterDumpRecordCommand();
90 extern void RegisterHelpCommand();
91 extern void RegisterInjectCommand();
92 extern void RegisterListCommand();
93 extern void RegisterKmemCommand();
94 extern void RegisterRecordCommand();
95 extern void RegisterReportCommand();
96 extern void RegisterReportSampleCommand();
97 extern void RegisterStatCommand();
98 extern void RegisterDebugUnwindCommand();
99 extern void RegisterTraceSchedCommand();
100 extern void RegisterAPICommands();
101 
102 class CommandRegister {
103  public:
CommandRegister()104   CommandRegister() {
105     RegisterDumpRecordCommand();
106     RegisterHelpCommand();
107     RegisterInjectCommand();
108     RegisterKmemCommand();
109     RegisterReportCommand();
110     RegisterReportSampleCommand();
111 #if defined(__linux__)
112     RegisterListCommand();
113     RegisterRecordCommand();
114     RegisterStatCommand();
115     RegisterDebugUnwindCommand();
116     RegisterTraceSchedCommand();
117 #if defined(__ANDROID__)
118     RegisterAPICommands();
119 #endif
120 #endif
121   }
122 };
123 
124 CommandRegister command_register;
125 
StderrLogger(android::base::LogId,android::base::LogSeverity severity,const char *,const char * file,unsigned int line,const char * message)126 static void StderrLogger(android::base::LogId, android::base::LogSeverity severity,
127                          const char*, const char* file, unsigned int line, const char* message) {
128   static const char log_characters[] = "VDIWEFF";
129   char severity_char = log_characters[severity];
130   fprintf(stderr, "simpleperf %c %s:%u] %s\n", severity_char, file, line, message);
131 }
132 
RunSimpleperfCmd(int argc,char ** argv)133 bool RunSimpleperfCmd(int argc, char** argv) {
134   android::base::InitLogging(argv, StderrLogger);
135   std::vector<std::string> args;
136   android::base::LogSeverity log_severity = android::base::INFO;
137 
138   for (int i = 1; i < argc; ++i) {
139     if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
140       args.insert(args.begin(), "help");
141     } else if (strcmp(argv[i], "--log") == 0) {
142       if (i + 1 < argc) {
143         ++i;
144         if (!GetLogSeverity(argv[i], &log_severity)) {
145           LOG(ERROR) << "Unknown log severity: " << argv[i];
146           return false;
147         }
148       } else {
149         LOG(ERROR) << "Missing argument for --log option.\n";
150         return false;
151       }
152 #if defined(__ANDROID__)
153     } else if (strcmp(argv[i], "--log-to-android-buffer") == 0) {
154       android::base::SetLogger(android::base::LogdLogger());
155 #endif
156     } else if (strcmp(argv[i], "--version") == 0) {
157       LOG(INFO) << "Simpleperf version " << GetSimpleperfVersion();
158       return true;
159     } else {
160       args.push_back(argv[i]);
161     }
162   }
163   android::base::ScopedLogSeverity severity(log_severity);
164 
165   if (args.empty()) {
166     args.push_back("help");
167   }
168   std::unique_ptr<Command> command = CreateCommandInstance(args[0]);
169   if (command == nullptr) {
170     LOG(ERROR) << "malformed command line: unknown command " << args[0];
171     return false;
172   }
173   std::string command_name = args[0];
174   args.erase(args.begin());
175 
176   LOG(DEBUG) << "command '" << command_name << "' starts running";
177   bool result = command->Run(args);
178   LOG(DEBUG) << "command '" << command_name << "' "
179              << (result ? "finished successfully" : "failed");
180   // Quick exit to avoid cost freeing memory and closing files.
181   fflush(stdout);
182   fflush(stderr);
183   android::base::quick_exit(result ? 0 : 1);
184   return result;
185 }
186