blob: b4111186c550cf94d33d5c1ad9942dfa238c17e2 [file] [log] [blame]
Calin Juravle36eb3132017-01-13 16:32:38 -08001/*
2 * Copyright (C) 2017 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
David Brazdil89821862019-03-19 13:57:43 +000017#include <iostream>
Calin Juravle36eb3132017-01-13 16:32:38 -080018#include <string>
Vladimir Markoe5125562019-02-06 17:38:26 +000019#include <string_view>
Calin Juravle36eb3132017-01-13 16:32:38 -080020
21#include "android-base/stringprintf.h"
22#include "android-base/strings.h"
David Sehr891a50e2017-10-27 17:01:07 -070023#include "base/file_utils.h"
Vladimir Markoe5125562019-02-06 17:38:26 +000024#include "base/logging.h" // For InitLogging.
25#include "base/mutex.h"
26#include "base/os.h"
27#include "base/string_view_cpp20.h"
28#include "base/utils.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080029#include "compiler_filter.h"
Calin Juravle20c46442017-09-12 00:54:26 -070030#include "class_loader_context.h"
David Sehr9e734c72018-01-04 17:56:19 -080031#include "dex/dex_file.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080032#include "noop_compiler_callbacks.h"
33#include "oat_file_assistant.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080034#include "runtime.h"
35#include "thread-inl.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080036
37namespace art {
38
39// See OatFileAssistant docs for the meaning of the valid return codes.
40enum ReturnCodes {
41 kNoDexOptNeeded = 0,
42 kDex2OatFromScratch = 1,
43 kDex2OatForBootImageOat = 2,
44 kDex2OatForFilterOat = 3,
Vladimir Markoe0669322018-09-03 15:44:54 +010045 kDex2OatForBootImageOdex = 4,
46 kDex2OatForFilterOdex = 5,
Calin Juravle36eb3132017-01-13 16:32:38 -080047
David Brazdil89821862019-03-19 13:57:43 +000048 // Success return code when executed with --flatten-class-loader-context.
49 // Success is typically signalled with a zero but we use a non-colliding
50 // code to communicate that the flattening code path was taken.
51 kFlattenClassLoaderContextSuccess = 50,
52
Calin Juravle36eb3132017-01-13 16:32:38 -080053 kErrorInvalidArguments = 101,
54 kErrorCannotCreateRuntime = 102,
55 kErrorUnknownDexOptNeeded = 103
56};
57
58static int original_argc;
59static char** original_argv;
60
61static std::string CommandLine() {
62 std::vector<std::string> command;
Andreas Gampe2a487eb2018-11-19 11:41:22 -080063 command.reserve(original_argc);
Calin Juravle36eb3132017-01-13 16:32:38 -080064 for (int i = 0; i < original_argc; ++i) {
65 command.push_back(original_argv[i]);
66 }
67 return android::base::Join(command, ' ');
68}
69
70static void UsageErrorV(const char* fmt, va_list ap) {
71 std::string error;
72 android::base::StringAppendV(&error, fmt, ap);
73 LOG(ERROR) << error;
74}
75
76static void UsageError(const char* fmt, ...) {
77 va_list ap;
78 va_start(ap, fmt);
79 UsageErrorV(fmt, ap);
80 va_end(ap);
81}
82
83NO_RETURN static void Usage(const char *fmt, ...) {
84 va_list ap;
85 va_start(ap, fmt);
86 UsageErrorV(fmt, ap);
87 va_end(ap);
88
89 UsageError("Command: %s", CommandLine().c_str());
90 UsageError(" Performs a dexopt analysis on the given dex file and returns whether or not");
91 UsageError(" the dex file needs to be dexopted.");
92 UsageError("Usage: dexoptanalyzer [options]...");
93 UsageError("");
94 UsageError(" --dex-file=<filename>: the dex file which should be analyzed.");
95 UsageError("");
96 UsageError(" --isa=<string>: the instruction set for which the analysis should be performed.");
97 UsageError("");
98 UsageError(" --compiler-filter=<string>: the target compiler filter to be used as reference");
99 UsageError(" when deciding if the dex file needs to be optimized.");
100 UsageError("");
101 UsageError(" --assume-profile-changed: assumes the profile information has changed");
102 UsageError(" when deciding if the dex file needs to be optimized.");
103 UsageError("");
104 UsageError(" --image=<filename>: optional, the image to be used to decide if the associated");
105 UsageError(" oat file is up to date. Defaults to $ANDROID_ROOT/framework/boot.art.");
106 UsageError(" Example: --image=/system/framework/boot.art");
107 UsageError("");
Vladimir Marko813b9142018-11-29 11:20:07 +0000108 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
109 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
110 UsageError(" Use a separate --runtime-arg switch for each argument.");
111 UsageError(" Example: --runtime-arg -Xms256m");
112 UsageError("");
Calin Juravle36eb3132017-01-13 16:32:38 -0800113 UsageError(" --android-data=<directory>: optional, the directory which should be used as");
114 UsageError(" android-data. By default ANDROID_DATA env variable is used.");
115 UsageError("");
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700116 UsageError(" --oat-fd=number: file descriptor of the oat file which should be analyzed");
117 UsageError("");
118 UsageError(" --vdex-fd=number: file descriptor of the vdex file corresponding to the oat file");
119 UsageError("");
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700120 UsageError(" --zip-fd=number: specifies a file descriptor corresponding to the dex file.");
121 UsageError("");
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700122 UsageError(" --downgrade: optional, if the purpose of dexopt is to downgrade the dex file");
123 UsageError(" By default, dexopt considers upgrade case.");
124 UsageError("");
David Brazdil89821862019-03-19 13:57:43 +0000125 UsageError(" --class-loader-context=<string spec>: a string specifying the intended");
126 UsageError(" runtime loading context for the compiled dex files.");
127 UsageError("");
128 UsageError(" --class-loader-context-fds=<fds>: a colon-separated list of file descriptors");
129 UsageError(" for dex files in --class-loader-context. Their order must be the same as");
130 UsageError(" dex files in flattened class loader context.");
131 UsageError("");
132 UsageError(" --flatten-class-loader-context: parse --class-loader-context, flatten it and");
133 UsageError(" print a colon-separated list of its dex files to standard output. Dexopt");
134 UsageError(" needed analysis is not performed when this option is set.");
135 UsageError("");
Calin Juravle36eb3132017-01-13 16:32:38 -0800136 UsageError("Return code:");
137 UsageError(" To make it easier to integrate with the internal tools this command will make");
138 UsageError(" available its result (dexoptNeeded) as the exit/return code. i.e. it will not");
139 UsageError(" return 0 for success and a non zero values for errors as the conventional");
140 UsageError(" commands. The following return codes are possible:");
141 UsageError(" kNoDexOptNeeded = 0");
142 UsageError(" kDex2OatFromScratch = 1");
143 UsageError(" kDex2OatForBootImageOat = 2");
144 UsageError(" kDex2OatForFilterOat = 3");
Vladimir Markoe0669322018-09-03 15:44:54 +0100145 UsageError(" kDex2OatForBootImageOdex = 4");
146 UsageError(" kDex2OatForFilterOdex = 5");
Calin Juravle36eb3132017-01-13 16:32:38 -0800147
148 UsageError(" kErrorInvalidArguments = 101");
149 UsageError(" kErrorCannotCreateRuntime = 102");
150 UsageError(" kErrorUnknownDexOptNeeded = 103");
151 UsageError("");
152
153 exit(kErrorInvalidArguments);
154}
155
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100156class DexoptAnalyzer final {
Calin Juravle36eb3132017-01-13 16:32:38 -0800157 public:
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700158 DexoptAnalyzer() :
David Brazdil89821862019-03-19 13:57:43 +0000159 only_flatten_context_(false),
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700160 assume_profile_changed_(false),
161 downgrade_(false) {}
Calin Juravle36eb3132017-01-13 16:32:38 -0800162
163 void ParseArgs(int argc, char **argv) {
164 original_argc = argc;
165 original_argv = argv;
166
David Sehrc431b9d2018-03-02 12:01:51 -0800167 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700168 InitLogging(argv, Runtime::Abort);
Calin Juravle36eb3132017-01-13 16:32:38 -0800169 // Skip over the command name.
170 argv++;
171 argc--;
172
173 if (argc == 0) {
174 Usage("No arguments specified");
175 }
176
177 for (int i = 0; i < argc; ++i) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000178 const char* raw_option = argv[i];
179 const std::string_view option(raw_option);
Calin Juravle36eb3132017-01-13 16:32:38 -0800180 if (option == "--assume-profile-changed") {
181 assume_profile_changed_ = true;
Vladimir Markoe5125562019-02-06 17:38:26 +0000182 } else if (StartsWith(option, "--dex-file=")) {
183 dex_file_ = std::string(option.substr(strlen("--dex-file=")));
184 } else if (StartsWith(option, "--compiler-filter=")) {
185 const char* filter_str = raw_option + strlen("--compiler-filter=");
186 if (!CompilerFilter::ParseCompilerFilter(filter_str, &compiler_filter_)) {
187 Usage("Invalid compiler filter '%s'", raw_option);
Calin Juravle36eb3132017-01-13 16:32:38 -0800188 }
Vladimir Markoe5125562019-02-06 17:38:26 +0000189 } else if (StartsWith(option, "--isa=")) {
190 const char* isa_str = raw_option + strlen("--isa=");
191 isa_ = GetInstructionSetFromString(isa_str);
Vladimir Marko33bff252017-11-01 14:35:42 +0000192 if (isa_ == InstructionSet::kNone) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000193 Usage("Invalid isa '%s'", raw_option);
Calin Juravle36eb3132017-01-13 16:32:38 -0800194 }
Vladimir Markoe5125562019-02-06 17:38:26 +0000195 } else if (StartsWith(option, "--image=")) {
196 image_ = std::string(option.substr(strlen("--image=")));
Vladimir Marko813b9142018-11-29 11:20:07 +0000197 } else if (option == "--runtime-arg") {
198 if (i + 1 == argc) {
199 Usage("Missing argument for --runtime-arg\n");
200 }
201 ++i;
202 runtime_args_.push_back(argv[i]);
Vladimir Markoe5125562019-02-06 17:38:26 +0000203 } else if (StartsWith(option, "--android-data=")) {
Calin Juravle36eb3132017-01-13 16:32:38 -0800204 // Overwrite android-data if needed (oat file assistant relies on a valid directory to
205 // compute dalvik-cache folder). This is mostly used in tests.
Vladimir Markoe5125562019-02-06 17:38:26 +0000206 const char* new_android_data = raw_option + strlen("--android-data=");
207 setenv("ANDROID_DATA", new_android_data, 1);
208 } else if (option == "--downgrade") {
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700209 downgrade_ = true;
Vladimir Markoe5125562019-02-06 17:38:26 +0000210 } else if (StartsWith(option, "--oat-fd=")) {
211 oat_fd_ = std::stoi(std::string(option.substr(strlen("--oat-fd="))), nullptr, 0);
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700212 if (oat_fd_ < 0) {
213 Usage("Invalid --oat-fd %d", oat_fd_);
214 }
Vladimir Markoe5125562019-02-06 17:38:26 +0000215 } else if (StartsWith(option, "--vdex-fd=")) {
216 vdex_fd_ = std::stoi(std::string(option.substr(strlen("--vdex-fd="))), nullptr, 0);
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700217 if (vdex_fd_ < 0) {
218 Usage("Invalid --vdex-fd %d", vdex_fd_);
219 }
Vladimir Markoe5125562019-02-06 17:38:26 +0000220 } else if (StartsWith(option, "--zip-fd=")) {
221 zip_fd_ = std::stoi(std::string(option.substr(strlen("--zip-fd="))), nullptr, 0);
222 if (zip_fd_ < 0) {
223 Usage("Invalid --zip-fd %d", zip_fd_);
224 }
225 } else if (StartsWith(option, "--class-loader-context=")) {
226 context_str_ = std::string(option.substr(strlen("--class-loader-context=")));
David Brazdil89821862019-03-19 13:57:43 +0000227 } else if (StartsWith(option, "--class-loader-context-fds=")) {
228 std::string str_context_fds_arg =
229 std::string(option.substr(strlen("--class-loader-context-fds=")));
230 std::vector<std::string> str_fds = android::base::Split(str_context_fds_arg, ":");
231 for (const std::string& str_fd : str_fds) {
232 context_fds_.push_back(std::stoi(str_fd, nullptr, 0));
233 if (context_fds_.back() < 0) {
234 Usage("Invalid --class-loader-context-fds %s", str_context_fds_arg.c_str());
235 }
236 }
237 } else if (option == "--flatten-class-loader-context") {
238 only_flatten_context_ = true;
Calin Juravle20c46442017-09-12 00:54:26 -0700239 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000240 Usage("Unknown argument '%s'", raw_option);
Calin Juravle20c46442017-09-12 00:54:26 -0700241 }
Calin Juravle36eb3132017-01-13 16:32:38 -0800242 }
243
244 if (image_.empty()) {
245 // If we don't receive the image, try to use the default one.
246 // Tests may specify a different image (e.g. core image).
247 std::string error_msg;
248 image_ = GetDefaultBootImageLocation(&error_msg);
249
250 if (image_.empty()) {
251 LOG(ERROR) << error_msg;
252 Usage("--image unspecified and ANDROID_ROOT not set or image file does not exist.");
253 }
254 }
255 }
256
David Brazdil89821862019-03-19 13:57:43 +0000257 bool CreateRuntime() const {
Calin Juravle36eb3132017-01-13 16:32:38 -0800258 RuntimeOptions options;
259 // The image could be custom, so make sure we explicitly pass it.
260 std::string img = "-Ximage:" + image_;
Vladimir Marko813b9142018-11-29 11:20:07 +0000261 options.push_back(std::make_pair(img, nullptr));
Calin Juravle36eb3132017-01-13 16:32:38 -0800262 // The instruction set of the image should match the instruction set we will test.
263 const void* isa_opt = reinterpret_cast<const void*>(GetInstructionSetString(isa_));
264 options.push_back(std::make_pair("imageinstructionset", isa_opt));
Vladimir Marko813b9142018-11-29 11:20:07 +0000265 // Explicit runtime args.
266 for (const char* runtime_arg : runtime_args_) {
267 options.push_back(std::make_pair(runtime_arg, nullptr));
268 }
Calin Juravle36eb3132017-01-13 16:32:38 -0800269 // Disable libsigchain. We don't don't need it to evaluate DexOptNeeded status.
270 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
271 // Pretend we are a compiler so that we can re-use the same infrastructure to load a different
272 // ISA image and minimize the amount of things that get started.
273 NoopCompilerCallbacks callbacks;
274 options.push_back(std::make_pair("compilercallbacks", &callbacks));
275 // Make sure we don't attempt to relocate. The tool should only retrieve the DexOptNeeded
276 // status and not attempt to relocate the boot image.
277 options.push_back(std::make_pair("-Xnorelocate", nullptr));
278
279 if (!Runtime::Create(options, false)) {
280 LOG(ERROR) << "Unable to initialize runtime";
281 return false;
282 }
283 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
284 // Runtime::Start. Give it away now.
285 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
286
287 return true;
288 }
289
David Brazdil89821862019-03-19 13:57:43 +0000290 int GetDexOptNeeded() const {
Calin Juravle36eb3132017-01-13 16:32:38 -0800291 if (!CreateRuntime()) {
292 return kErrorCannotCreateRuntime;
293 }
Andreas Gampe39f44b72017-04-26 22:00:04 -0700294 std::unique_ptr<Runtime> runtime(Runtime::Current());
295
Nicolas Geoffray35de14b2019-01-10 13:10:36 +0000296 // Only when the runtime is created can we create the class loader context: the
297 // class loader context will open dex file and use the MemMap global lock that the
298 // runtime owns.
299 std::unique_ptr<ClassLoaderContext> class_loader_context;
300 if (!context_str_.empty()) {
301 class_loader_context = ClassLoaderContext::Create(context_str_);
302 if (class_loader_context == nullptr) {
303 Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
304 }
305 }
306
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700307 std::unique_ptr<OatFileAssistant> oat_file_assistant;
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700308 oat_file_assistant = std::make_unique<OatFileAssistant>(dex_file_.c_str(),
309 isa_,
Andreas Gampe9b031f72018-10-04 11:03:34 -0700310 /*load_executable=*/ false,
311 /*only_load_system_executable=*/ false,
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700312 vdex_fd_,
313 oat_fd_,
314 zip_fd_);
Calin Juravle36eb3132017-01-13 16:32:38 -0800315 // Always treat elements of the bootclasspath as up-to-date.
316 // TODO(calin): this check should be in OatFileAssistant.
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700317 if (oat_file_assistant->IsInBootClassPath()) {
Calin Juravle36eb3132017-01-13 16:32:38 -0800318 return kNoDexOptNeeded;
319 }
Calin Juravle44e5efa2017-09-12 00:54:26 -0700320
David Brazdil89821862019-03-19 13:57:43 +0000321 int dexoptNeeded = oat_file_assistant->GetDexOptNeeded(compiler_filter_,
322 assume_profile_changed_,
323 downgrade_,
324 class_loader_context.get(),
325 context_fds_);
Calin Juravle36eb3132017-01-13 16:32:38 -0800326
327 // Convert OatFileAssitant codes to dexoptanalyzer codes.
328 switch (dexoptNeeded) {
329 case OatFileAssistant::kNoDexOptNeeded: return kNoDexOptNeeded;
330 case OatFileAssistant::kDex2OatFromScratch: return kDex2OatFromScratch;
331 case OatFileAssistant::kDex2OatForBootImage: return kDex2OatForBootImageOat;
332 case OatFileAssistant::kDex2OatForFilter: return kDex2OatForFilterOat;
Calin Juravle36eb3132017-01-13 16:32:38 -0800333
334 case -OatFileAssistant::kDex2OatForBootImage: return kDex2OatForBootImageOdex;
335 case -OatFileAssistant::kDex2OatForFilter: return kDex2OatForFilterOdex;
Calin Juravle36eb3132017-01-13 16:32:38 -0800336 default:
337 LOG(ERROR) << "Unknown dexoptNeeded " << dexoptNeeded;
338 return kErrorUnknownDexOptNeeded;
339 }
340 }
341
David Brazdil89821862019-03-19 13:57:43 +0000342 int FlattenClassLoaderContext() const {
343 DCHECK(only_flatten_context_);
344 if (context_str_.empty()) {
345 return kErrorInvalidArguments;
346 }
347
348 std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::Create(context_str_);
349 if (context == nullptr) {
350 Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
351 }
352
353 std::cout << context->FlattenDexPaths() << std::flush;
354 return kFlattenClassLoaderContextSuccess;
355 }
356
357 int Run() const {
358 if (only_flatten_context_) {
359 return FlattenClassLoaderContext();
360 } else {
361 return GetDexOptNeeded();
362 }
363 }
364
Calin Juravle36eb3132017-01-13 16:32:38 -0800365 private:
366 std::string dex_file_;
367 InstructionSet isa_;
368 CompilerFilter::Filter compiler_filter_;
Nicolas Geoffray35de14b2019-01-10 13:10:36 +0000369 std::string context_str_;
David Brazdil89821862019-03-19 13:57:43 +0000370 bool only_flatten_context_;
Calin Juravle36eb3132017-01-13 16:32:38 -0800371 bool assume_profile_changed_;
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700372 bool downgrade_;
Calin Juravle36eb3132017-01-13 16:32:38 -0800373 std::string image_;
Vladimir Marko813b9142018-11-29 11:20:07 +0000374 std::vector<const char*> runtime_args_;
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700375 int oat_fd_ = -1;
376 int vdex_fd_ = -1;
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700377 // File descriptor corresponding to apk, dex_file, or zip.
378 int zip_fd_ = -1;
David Brazdil89821862019-03-19 13:57:43 +0000379 std::vector<int> context_fds_;
Calin Juravle36eb3132017-01-13 16:32:38 -0800380};
381
382static int dexoptAnalyze(int argc, char** argv) {
383 DexoptAnalyzer analyzer;
384
385 // Parse arguments. Argument mistakes will lead to exit(kErrorInvalidArguments) in UsageError.
386 analyzer.ParseArgs(argc, argv);
David Brazdil89821862019-03-19 13:57:43 +0000387 return analyzer.Run();
Calin Juravle36eb3132017-01-13 16:32:38 -0800388}
389
390} // namespace art
391
392int main(int argc, char **argv) {
393 return art::dexoptAnalyze(argc, argv);
394}