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 <string.h>
18 
19 #include <string>
20 #include <vector>
21 
22 #include <android-base/logging.h>
23 
24 #include "command.h"
25 #include "utils.h"
26 
27 constexpr int SIMPLEPERF_VERSION = 1;
28 
main(int argc,char ** argv)29 int main(int argc, char** argv) {
30   android::base::InitLogging(argv, android::base::StderrLogger);
31   std::vector<std::string> args;
32   android::base::LogSeverity log_severity = android::base::INFO;
33 
34   for (int i = 1; i < argc; ++i) {
35     if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
36       args.insert(args.begin(), "help");
37     } else if (strcmp(argv[i], "--log") == 0) {
38       if (i + 1 < argc) {
39         ++i;
40         if (!GetLogSeverity(argv[i], &log_severity)) {
41           LOG(ERROR) << "Unknown log severity: " << argv[i];
42           return 1;
43         }
44       } else {
45         LOG(ERROR) << "Missing argument for --log option.\n";
46         return 1;
47       }
48     } else if (strcmp(argv[i], "--version") == 0) {
49       LOG(INFO) << "Simpleperf version " << SIMPLEPERF_VERSION << ", revision "
50                 << SIMPLEPERF_REVISION;
51       return 0;
52     } else {
53       args.push_back(argv[i]);
54     }
55   }
56   android::base::ScopedLogSeverity severity(log_severity);
57 
58   if (args.empty()) {
59     args.push_back("help");
60   }
61   std::unique_ptr<Command> command = CreateCommandInstance(args[0]);
62   if (command == nullptr) {
63     LOG(ERROR) << "malformed command line: unknown command " << args[0];
64     return 1;
65   }
66   std::string command_name = args[0];
67   args.erase(args.begin());
68 
69   LOG(DEBUG) << "command '" << command_name << "' starts running";
70   bool result = command->Run(args);
71   LOG(DEBUG) << "command '" << command_name << "' "
72              << (result ? "finished successfully" : "failed");
73   return result ? 0 : 1;
74 }
75