1 /*
2 * Copyright (C) 2018 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 <cstdint>
18 #include <iostream>
19 #include <set>
20 #include <sstream>
21
22 #include <android-base/file.h>
23
24 #include "dexanalyze_bytecode.h"
25 #include "dexanalyze_experiments.h"
26 #include "dexanalyze_strings.h"
27 #include "dex/code_item_accessors-inl.h"
28 #include "dex/dex_file.h"
29 #include "dex/dex_file_loader.h"
30 #include "dex/dex_instruction-inl.h"
31
32 namespace art {
33 namespace dexanalyze {
34
35 class DexAnalyze {
36 static constexpr int kExitCodeUsageError = 1;
37 static constexpr int kExitCodeFailedToOpenFile = 2;
38 static constexpr int kExitCodeFailedToOpenDex = 3;
39 static constexpr int kExitCodeFailedToProcessDex = 4;
40
StdoutLogger(android::base::LogId,android::base::LogSeverity,const char *,const char *,unsigned int,const char * message)41 static void StdoutLogger(android::base::LogId,
42 android::base::LogSeverity,
43 const char*,
44 const char*,
45 unsigned int,
46 const char* message) {
47 std::cout << message << std::endl;
48 }
49
Usage(char ** argv)50 static int Usage(char** argv) {
51 LOG(ERROR)
52 << "Usage " << argv[0] << " [options] <dex files>\n"
53 << " [options] is a combination of the following\n"
54 << " -count_indices (Count dex indices accessed from code items)\n"
55 << " -analyze-strings (Analyze string data)\n"
56 << " -analyze-debug-info (Analyze debug info)\n"
57 << " -new-bytecode (Bytecode optimizations)\n"
58 << " -i (Ignore Dex checksum and verification failures)\n"
59 << " -a (Run all experiments)\n"
60 << " -n <int> (run experiment with 1 .. n as argument)\n"
61 << " -d (Dump on per Dex basis)\n"
62 << " -v (quiet(0) to everything(2))\n";
63 return kExitCodeUsageError;
64 }
65
66 struct Options {
Parseart::dexanalyze::DexAnalyze::Options67 int Parse(int argc, char** argv) {
68 int i;
69 for (i = 1; i < argc; ++i) {
70 const std::string arg = argv[i];
71 if (arg == "-i") {
72 verify_checksum_ = false;
73 run_dex_file_verifier_ = false;
74 } else if (arg == "-v") {
75 if (i + 1 >= argc) {
76 return Usage(argv);
77 }
78 std::istringstream iss(argv[i + 1]);
79 size_t verbose_level = 0u;
80 iss >> verbose_level;
81 if (verbose_level > static_cast<size_t>(VerboseLevel::kEverything)) {
82 return Usage(argv);
83 }
84 ++i;
85 verbose_level_ = static_cast<VerboseLevel>(verbose_level);
86 } else if (arg == "-a") {
87 run_all_experiments_ = true;
88 } else if (arg == "-n") {
89 if (i + 1 >= argc) {
90 return Usage(argv);
91 }
92 std::istringstream iss(argv[i + 1]);
93 iss >> experiment_max_;
94 ++i;
95 } else if (arg == "-count-indices") {
96 exp_count_indices_ = true;
97 } else if (arg == "-analyze-strings") {
98 exp_analyze_strings_ = true;
99 } else if (arg == "-analyze-debug-info") {
100 exp_debug_info_ = true;
101 } else if (arg == "-new-bytecode") {
102 exp_bytecode_ = true;
103 } else if (arg == "-d") {
104 dump_per_input_dex_ = true;
105 } else if (!arg.empty() && arg[0] == '-') {
106 return Usage(argv);
107 } else {
108 break;
109 }
110 }
111 filenames_.insert(filenames_.end(), argv + i, argv + argc);
112 if (filenames_.empty()) {
113 return Usage(argv);
114 }
115 return 0;
116 }
117
118 VerboseLevel verbose_level_ = VerboseLevel::kNormal;
119 bool verify_checksum_ = true;
120 bool run_dex_file_verifier_ = true;
121 bool dump_per_input_dex_ = false;
122 bool exp_count_indices_ = false;
123 bool exp_code_metrics_ = false;
124 bool exp_analyze_strings_ = false;
125 bool exp_debug_info_ = false;
126 bool exp_bytecode_ = false;
127 bool run_all_experiments_ = false;
128 uint64_t experiment_max_ = 1u;
129 std::vector<std::string> filenames_;
130 };
131
132 class Analysis {
133 public:
Analysis(const Options * options)134 explicit Analysis(const Options* options) : options_(options) {
135 if (options->run_all_experiments_ || options->exp_count_indices_) {
136 experiments_.emplace_back(new CountDexIndices);
137 }
138 if (options->run_all_experiments_ || options->exp_analyze_strings_) {
139 experiments_.emplace_back(new AnalyzeStrings);
140 }
141 if (options->run_all_experiments_ || options->exp_code_metrics_) {
142 experiments_.emplace_back(new CodeMetrics);
143 }
144 if (options->run_all_experiments_ || options->exp_debug_info_) {
145 experiments_.emplace_back(new AnalyzeDebugInfo);
146 }
147 if (options->run_all_experiments_ || options->exp_bytecode_) {
148 for (size_t i = 0; i < options->experiment_max_; ++i) {
149 uint64_t exp_value = 0u;
150 if (i == 0) {
151 exp_value = std::numeric_limits<uint64_t>::max();
152 } else if (i == 1) {
153 exp_value = 0u;
154 } else {
155 exp_value = 1u << (i - 2);
156 }
157 experiments_.emplace_back(new NewRegisterInstructions(exp_value));
158 }
159 }
160 for (const std::unique_ptr<Experiment>& experiment : experiments_) {
161 experiment->verbose_level_ = options->verbose_level_;
162 }
163 }
164
ProcessDexFiles(const std::vector<std::unique_ptr<const DexFile>> & dex_files)165 bool ProcessDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
166 for (std::unique_ptr<Experiment>& experiment : experiments_) {
167 experiment->ProcessDexFiles(dex_files);
168 }
169 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
170 total_size_ += dex_file->Size();
171 }
172 dex_count_ += dex_files.size();
173 return true;
174 }
175
Dump(std::ostream & os)176 void Dump(std::ostream& os) {
177 for (std::unique_ptr<Experiment>& experiment : experiments_) {
178 experiment->Dump(os, total_size_);
179 os << "\n";
180 }
181 }
182
183 const Options* const options_;
184 std::vector<std::unique_ptr<Experiment>> experiments_;
185 size_t dex_count_ = 0;
186 uint64_t total_size_ = 0u;
187 };
188
189 public:
Run(int argc,char ** argv)190 static int Run(int argc, char** argv) {
191 android::base::SetLogger(StdoutLogger);
192
193 Options options;
194 int result = options.Parse(argc, argv);
195 if (result != 0) {
196 return result;
197 }
198
199 DexFileLoaderErrorCode error_code;
200 std::string error_msg;
201 Analysis cumulative(&options);
202 for (const std::string& filename : options.filenames_) {
203 std::string content;
204 // TODO: once added, use an API to android::base to read a std::vector<uint8_t>.
205 if (!android::base::ReadFileToString(filename.c_str(), &content)) {
206 LOG(ERROR) << "ReadFileToString failed for " + filename << std::endl;
207 return kExitCodeFailedToOpenFile;
208 }
209 std::vector<std::unique_ptr<const DexFile>> dex_files;
210 const DexFileLoader dex_file_loader;
211 if (!dex_file_loader.OpenAll(reinterpret_cast<const uint8_t*>(content.data()),
212 content.size(),
213 filename.c_str(),
214 options.run_dex_file_verifier_,
215 options.verify_checksum_,
216 &error_code,
217 &error_msg,
218 &dex_files)) {
219 LOG(ERROR) << "OpenAll failed for " + filename << " with " << error_msg << std::endl;
220 return kExitCodeFailedToOpenDex;
221 }
222 if (options.dump_per_input_dex_) {
223 Analysis current(&options);
224 if (!current.ProcessDexFiles(dex_files)) {
225 LOG(ERROR) << "Failed to process " << filename << " with error " << error_msg;
226 return kExitCodeFailedToProcessDex;
227 }
228 LOG(INFO) << "Analysis for " << filename << std::endl;
229 current.Dump(LOG_STREAM(INFO));
230 }
231 cumulative.ProcessDexFiles(dex_files);
232 }
233 LOG(INFO) << "Cumulative analysis for " << cumulative.dex_count_ << " DEX files" << std::endl;
234 cumulative.Dump(LOG_STREAM(INFO));
235 return 0;
236 }
237 };
238
239 } // namespace dexanalyze
240 } // namespace art
241
main(int argc,char ** argv)242 int main(int argc, char** argv) {
243 return art::dexanalyze::DexAnalyze::Run(argc, argv);
244 }
245
246