blob: 0cc2cdb03add260642ac86c2fe291fa6b471eca1 [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
Orion Hodsona4731bd2020-11-16 14:56:50 +000017#include "dexoptanalyzer.h"
18
David Brazdil89821862019-03-19 13:57:43 +000019#include <iostream>
Calin Juravle36eb3132017-01-13 16:32:38 -080020#include <string>
Vladimir Markoe5125562019-02-06 17:38:26 +000021#include <string_view>
Calin Juravle36eb3132017-01-13 16:32:38 -080022
23#include "android-base/stringprintf.h"
24#include "android-base/strings.h"
Eric Holkc7ac91b2021-02-04 21:44:01 +000025#include "base/compiler_filter.h"
David Sehr891a50e2017-10-27 17:01:07 -070026#include "base/file_utils.h"
Vladimir Markoe5125562019-02-06 17:38:26 +000027#include "base/logging.h" // For InitLogging.
28#include "base/mutex.h"
29#include "base/os.h"
30#include "base/string_view_cpp20.h"
31#include "base/utils.h"
Orion Hodson1da77262021-02-10 14:03:59 +000032#include "class_linker.h"
Calin Juravle20c46442017-09-12 00:54:26 -070033#include "class_loader_context.h"
David Sehr9e734c72018-01-04 17:56:19 -080034#include "dex/dex_file.h"
Orion Hodson1da77262021-02-10 14:03:59 +000035#include "gc/heap.h"
36#include "gc/space/image_space.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080037#include "noop_compiler_callbacks.h"
Orion Hodson0a737622021-02-26 13:10:10 +000038#include "oat.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080039#include "oat_file_assistant.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080040#include "runtime.h"
41#include "thread-inl.h"
Orion Hodson1da77262021-02-10 14:03:59 +000042#include "vdex_file.h"
Calin Juravle36eb3132017-01-13 16:32:38 -080043
44namespace art {
Orion Hodsona4731bd2020-11-16 14:56:50 +000045namespace dexoptanalyzer {
Calin Juravle36eb3132017-01-13 16:32:38 -080046
47static int original_argc;
48static char** original_argv;
49
50static std::string CommandLine() {
51 std::vector<std::string> command;
Andreas Gampe2a487eb2018-11-19 11:41:22 -080052 command.reserve(original_argc);
Calin Juravle36eb3132017-01-13 16:32:38 -080053 for (int i = 0; i < original_argc; ++i) {
54 command.push_back(original_argv[i]);
55 }
56 return android::base::Join(command, ' ');
57}
58
59static void UsageErrorV(const char* fmt, va_list ap) {
60 std::string error;
61 android::base::StringAppendV(&error, fmt, ap);
62 LOG(ERROR) << error;
63}
64
65static void UsageError(const char* fmt, ...) {
66 va_list ap;
67 va_start(ap, fmt);
68 UsageErrorV(fmt, ap);
69 va_end(ap);
70}
71
72NO_RETURN static void Usage(const char *fmt, ...) {
73 va_list ap;
74 va_start(ap, fmt);
75 UsageErrorV(fmt, ap);
76 va_end(ap);
77
78 UsageError("Command: %s", CommandLine().c_str());
79 UsageError(" Performs a dexopt analysis on the given dex file and returns whether or not");
80 UsageError(" the dex file needs to be dexopted.");
81 UsageError("Usage: dexoptanalyzer [options]...");
82 UsageError("");
83 UsageError(" --dex-file=<filename>: the dex file which should be analyzed.");
84 UsageError("");
85 UsageError(" --isa=<string>: the instruction set for which the analysis should be performed.");
86 UsageError("");
87 UsageError(" --compiler-filter=<string>: the target compiler filter to be used as reference");
88 UsageError(" when deciding if the dex file needs to be optimized.");
89 UsageError("");
Calin Juravle17374092021-06-08 13:45:09 -070090 UsageError(" --profile_analysis_result=<int>: the result of the profile analysis, used in");
91 UsageError(" deciding if the dex file needs to be optimized.");
Calin Juravle36eb3132017-01-13 16:32:38 -080092 UsageError("");
93 UsageError(" --image=<filename>: optional, the image to be used to decide if the associated");
94 UsageError(" oat file is up to date. Defaults to $ANDROID_ROOT/framework/boot.art.");
95 UsageError(" Example: --image=/system/framework/boot.art");
96 UsageError("");
Vladimir Marko813b9142018-11-29 11:20:07 +000097 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
98 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
99 UsageError(" Use a separate --runtime-arg switch for each argument.");
100 UsageError(" Example: --runtime-arg -Xms256m");
101 UsageError("");
Calin Juravle36eb3132017-01-13 16:32:38 -0800102 UsageError(" --android-data=<directory>: optional, the directory which should be used as");
103 UsageError(" android-data. By default ANDROID_DATA env variable is used.");
104 UsageError("");
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700105 UsageError(" --oat-fd=number: file descriptor of the oat file which should be analyzed");
106 UsageError("");
107 UsageError(" --vdex-fd=number: file descriptor of the vdex file corresponding to the oat file");
108 UsageError("");
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700109 UsageError(" --zip-fd=number: specifies a file descriptor corresponding to the dex file.");
110 UsageError("");
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700111 UsageError(" --downgrade: optional, if the purpose of dexopt is to downgrade the dex file");
112 UsageError(" By default, dexopt considers upgrade case.");
113 UsageError("");
David Brazdil89821862019-03-19 13:57:43 +0000114 UsageError(" --class-loader-context=<string spec>: a string specifying the intended");
115 UsageError(" runtime loading context for the compiled dex files.");
116 UsageError("");
117 UsageError(" --class-loader-context-fds=<fds>: a colon-separated list of file descriptors");
118 UsageError(" for dex files in --class-loader-context. Their order must be the same as");
119 UsageError(" dex files in flattened class loader context.");
120 UsageError("");
121 UsageError(" --flatten-class-loader-context: parse --class-loader-context, flatten it and");
122 UsageError(" print a colon-separated list of its dex files to standard output. Dexopt");
123 UsageError(" needed analysis is not performed when this option is set.");
124 UsageError("");
Orion Hodson1da77262021-02-10 14:03:59 +0000125 UsageError(" --validate-bcp: validates the boot class path files (.art, .oat, .vdex).");
126 UsageError(" Requires --isa and --image options to locate artifacts.");
127 UsageError("");
Calin Juravle36eb3132017-01-13 16:32:38 -0800128 UsageError("Return code:");
129 UsageError(" To make it easier to integrate with the internal tools this command will make");
130 UsageError(" available its result (dexoptNeeded) as the exit/return code. i.e. it will not");
131 UsageError(" return 0 for success and a non zero values for errors as the conventional");
132 UsageError(" commands. The following return codes are possible:");
133 UsageError(" kNoDexOptNeeded = 0");
134 UsageError(" kDex2OatFromScratch = 1");
135 UsageError(" kDex2OatForBootImageOat = 2");
136 UsageError(" kDex2OatForFilterOat = 3");
Vladimir Markoe0669322018-09-03 15:44:54 +0100137 UsageError(" kDex2OatForBootImageOdex = 4");
138 UsageError(" kDex2OatForFilterOdex = 5");
Calin Juravle36eb3132017-01-13 16:32:38 -0800139
140 UsageError(" kErrorInvalidArguments = 101");
141 UsageError(" kErrorCannotCreateRuntime = 102");
142 UsageError(" kErrorUnknownDexOptNeeded = 103");
143 UsageError("");
144
Orion Hodsona4731bd2020-11-16 14:56:50 +0000145 exit(static_cast<int>(ReturnCode::kErrorInvalidArguments));
Calin Juravle36eb3132017-01-13 16:32:38 -0800146}
147
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100148class DexoptAnalyzer final {
Calin Juravle36eb3132017-01-13 16:32:38 -0800149 public:
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700150 DexoptAnalyzer() :
David Brazdil89821862019-03-19 13:57:43 +0000151 only_flatten_context_(false),
Greg Kaiser9ca1e102021-02-19 07:50:24 -0800152 only_validate_bcp_(false),
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700153 downgrade_(false) {}
Calin Juravle36eb3132017-01-13 16:32:38 -0800154
155 void ParseArgs(int argc, char **argv) {
156 original_argc = argc;
157 original_argv = argv;
158
David Sehrc431b9d2018-03-02 12:01:51 -0800159 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700160 InitLogging(argv, Runtime::Abort);
Calin Juravle36eb3132017-01-13 16:32:38 -0800161 // Skip over the command name.
162 argv++;
163 argc--;
164
165 if (argc == 0) {
166 Usage("No arguments specified");
167 }
168
169 for (int i = 0; i < argc; ++i) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000170 const char* raw_option = argv[i];
171 const std::string_view option(raw_option);
Calin Juravle17374092021-06-08 13:45:09 -0700172
173 if (StartsWith(option, "--profile-analysis-result=")) {
174 int parse_result = std::stoi(std::string(
175 option.substr(strlen("--profile-analysis-result="))), nullptr, 0);
176 if (parse_result != static_cast<int>(ProfileAnalysisResult::kOptimize) &&
177 parse_result != static_cast<int>(ProfileAnalysisResult::kDontOptimizeSmallDelta) &&
178 parse_result != static_cast<int>(ProfileAnalysisResult::kDontOptimizeEmptyProfiles)) {
179 Usage("Invalid --profile-analysis-result= %d", parse_result);
180 }
181 profile_analysis_result_ = static_cast<ProfileAnalysisResult>(parse_result);
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;
Orion Hodson1da77262021-02-10 14:03:59 +0000239 } else if (option == "--validate-bcp") {
240 only_validate_bcp_ = true;
Calin Juravle20c46442017-09-12 00:54:26 -0700241 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000242 Usage("Unknown argument '%s'", raw_option);
Calin Juravle20c46442017-09-12 00:54:26 -0700243 }
Calin Juravle36eb3132017-01-13 16:32:38 -0800244 }
245
246 if (image_.empty()) {
247 // If we don't receive the image, try to use the default one.
248 // Tests may specify a different image (e.g. core image).
249 std::string error_msg;
250 image_ = GetDefaultBootImageLocation(&error_msg);
251
252 if (image_.empty()) {
253 LOG(ERROR) << error_msg;
254 Usage("--image unspecified and ANDROID_ROOT not set or image file does not exist.");
255 }
256 }
257 }
258
David Brazdil89821862019-03-19 13:57:43 +0000259 bool CreateRuntime() const {
Calin Juravle36eb3132017-01-13 16:32:38 -0800260 RuntimeOptions options;
261 // The image could be custom, so make sure we explicitly pass it.
262 std::string img = "-Ximage:" + image_;
Vladimir Marko813b9142018-11-29 11:20:07 +0000263 options.push_back(std::make_pair(img, nullptr));
Calin Juravle36eb3132017-01-13 16:32:38 -0800264 // The instruction set of the image should match the instruction set we will test.
265 const void* isa_opt = reinterpret_cast<const void*>(GetInstructionSetString(isa_));
266 options.push_back(std::make_pair("imageinstructionset", isa_opt));
Vladimir Marko813b9142018-11-29 11:20:07 +0000267 // Explicit runtime args.
268 for (const char* runtime_arg : runtime_args_) {
269 options.push_back(std::make_pair(runtime_arg, nullptr));
270 }
Calin Juravle36eb3132017-01-13 16:32:38 -0800271 // Disable libsigchain. We don't don't need it to evaluate DexOptNeeded status.
272 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
273 // Pretend we are a compiler so that we can re-use the same infrastructure to load a different
274 // ISA image and minimize the amount of things that get started.
275 NoopCompilerCallbacks callbacks;
276 options.push_back(std::make_pair("compilercallbacks", &callbacks));
277 // Make sure we don't attempt to relocate. The tool should only retrieve the DexOptNeeded
278 // status and not attempt to relocate the boot image.
279 options.push_back(std::make_pair("-Xnorelocate", nullptr));
280
281 if (!Runtime::Create(options, false)) {
282 LOG(ERROR) << "Unable to initialize runtime";
283 return false;
284 }
285 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
286 // Runtime::Start. Give it away now.
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000287 Thread::Current()->TransitionFromRunnableToSuspended(ThreadState::kNative);
Calin Juravle36eb3132017-01-13 16:32:38 -0800288
289 return true;
290 }
291
Orion Hodsona4731bd2020-11-16 14:56:50 +0000292 ReturnCode GetDexOptNeeded() const {
Calin Juravle36eb3132017-01-13 16:32:38 -0800293 if (!CreateRuntime()) {
Orion Hodsona4731bd2020-11-16 14:56:50 +0000294 return ReturnCode::kErrorCannotCreateRuntime;
Calin Juravle36eb3132017-01-13 16:32:38 -0800295 }
Andreas Gampe39f44b72017-04-26 22:00:04 -0700296 std::unique_ptr<Runtime> runtime(Runtime::Current());
297
Nicolas Geoffray35de14b2019-01-10 13:10:36 +0000298 // Only when the runtime is created can we create the class loader context: the
299 // class loader context will open dex file and use the MemMap global lock that the
300 // runtime owns.
301 std::unique_ptr<ClassLoaderContext> class_loader_context;
302 if (!context_str_.empty()) {
303 class_loader_context = ClassLoaderContext::Create(context_str_);
304 if (class_loader_context == nullptr) {
305 Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
306 }
307 }
Nicolas Geoffray525fa422021-04-19 07:50:35 +0000308 if (class_loader_context != nullptr) {
309 size_t dir_index = dex_file_.rfind('/');
310 std::string classpath_dir = (dir_index != std::string::npos)
311 ? dex_file_.substr(0, dir_index)
312 : "";
313
314 if (!class_loader_context->OpenDexFiles(classpath_dir,
315 context_fds_,
316 /*only_read_checksums=*/ true)) {
317 return ReturnCode::kDex2OatFromScratch;
318 }
319 }
Nicolas Geoffray35de14b2019-01-10 13:10:36 +0000320
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700321 std::unique_ptr<OatFileAssistant> oat_file_assistant;
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700322 oat_file_assistant = std::make_unique<OatFileAssistant>(dex_file_.c_str(),
323 isa_,
Nicolas Geoffray525fa422021-04-19 07:50:35 +0000324 class_loader_context.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700325 /*load_executable=*/ false,
Orion Hodson094b1cf2021-06-08 09:28:28 +0100326 /*only_load_trusted_executable=*/ false,
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700327 vdex_fd_,
328 oat_fd_,
329 zip_fd_);
Calin Juravle36eb3132017-01-13 16:32:38 -0800330 // Always treat elements of the bootclasspath as up-to-date.
331 // TODO(calin): this check should be in OatFileAssistant.
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700332 if (oat_file_assistant->IsInBootClassPath()) {
Orion Hodsona4731bd2020-11-16 14:56:50 +0000333 return ReturnCode::kNoDexOptNeeded;
Calin Juravle36eb3132017-01-13 16:32:38 -0800334 }
Calin Juravle44e5efa2017-09-12 00:54:26 -0700335
Calin Juravle17374092021-06-08 13:45:09 -0700336 // If the compiler filter depends on profiles but the profiles are empty,
337 // change the test filter to kVerify. It's what dex2oat also does.
338 CompilerFilter::Filter actual_compiler_filter = compiler_filter_;
339 if (CompilerFilter::DependsOnProfile(compiler_filter_) &&
340 profile_analysis_result_ == ProfileAnalysisResult::kDontOptimizeEmptyProfiles) {
341 actual_compiler_filter = CompilerFilter::kVerify;
342 }
343
344 // TODO: GetDexOptNeeded should get the raw analysis result instead of assume_profile_changed.
345 bool assume_profile_changed = profile_analysis_result_ == ProfileAnalysisResult::kOptimize;
346 int dexoptNeeded = oat_file_assistant->GetDexOptNeeded(actual_compiler_filter,
347 assume_profile_changed,
Calin Juravle0a5cad32020-02-14 20:29:26 +0000348 downgrade_);
Calin Juravle36eb3132017-01-13 16:32:38 -0800349
Orion Hodson1da77262021-02-10 14:03:59 +0000350 // Convert OatFileAssistant codes to dexoptanalyzer codes.
Calin Juravle36eb3132017-01-13 16:32:38 -0800351 switch (dexoptNeeded) {
Orion Hodsona4731bd2020-11-16 14:56:50 +0000352 case OatFileAssistant::kNoDexOptNeeded: return ReturnCode::kNoDexOptNeeded;
353 case OatFileAssistant::kDex2OatFromScratch: return ReturnCode::kDex2OatFromScratch;
354 case OatFileAssistant::kDex2OatForBootImage: return ReturnCode::kDex2OatForBootImageOat;
355 case OatFileAssistant::kDex2OatForFilter: return ReturnCode::kDex2OatForFilterOat;
Calin Juravle36eb3132017-01-13 16:32:38 -0800356
Orion Hodsona4731bd2020-11-16 14:56:50 +0000357 case -OatFileAssistant::kDex2OatForBootImage: return ReturnCode::kDex2OatForBootImageOdex;
358 case -OatFileAssistant::kDex2OatForFilter: return ReturnCode::kDex2OatForFilterOdex;
Calin Juravle36eb3132017-01-13 16:32:38 -0800359 default:
360 LOG(ERROR) << "Unknown dexoptNeeded " << dexoptNeeded;
Orion Hodsona4731bd2020-11-16 14:56:50 +0000361 return ReturnCode::kErrorUnknownDexOptNeeded;
Calin Juravle36eb3132017-01-13 16:32:38 -0800362 }
363 }
364
Orion Hodson1da77262021-02-10 14:03:59 +0000365 // Validates the boot classpath and boot classpath extensions by checking the image checksums,
366 // the oat files and the vdex files.
367 //
368 // Returns `ReturnCode::kNoDexOptNeeded` when all the files are up-to-date,
369 // `ReturnCode::kDex2OatFromScratch` if any of the files are missing or out-of-date, and
370 // `ReturnCode::kErrorCannotCreateRuntime` if the files could not be tested due to problem
371 // creating a runtime.
372 ReturnCode ValidateBcp() const {
373 using ImageSpace = gc::space::ImageSpace;
374
375 if (!CreateRuntime()) {
376 return ReturnCode::kErrorCannotCreateRuntime;
377 }
378 std::unique_ptr<Runtime> runtime(Runtime::Current());
379
380 auto dex_files = ArrayRef<const DexFile* const>(runtime->GetClassLinker()->GetBootClassPath());
381 auto boot_image_spaces = ArrayRef<ImageSpace* const>(runtime->GetHeap()->GetBootImageSpaces());
382 const std::string checksums = ImageSpace::GetBootClassPathChecksums(boot_image_spaces,
383 dex_files);
384
385 std::string error_msg;
386 const std::vector<std::string>& bcp = runtime->GetBootClassPath();
387 const std::vector<std::string>& bcp_locations = runtime->GetBootClassPathLocations();
Victor Hsieha09d8b72021-05-24 14:21:55 -0700388 const std::vector<int>& bcp_fds = runtime->GetBootClassPathFds();
Victor Hsieh61ffd042021-05-20 15:14:25 -0700389 const std::vector<std::string>& image_locations = runtime->GetImageLocations();
Orion Hodson1da77262021-02-10 14:03:59 +0000390 const std::string bcp_locations_path = android::base::Join(bcp_locations, ':');
391 if (!ImageSpace::VerifyBootClassPathChecksums(checksums,
392 bcp_locations_path,
Victor Hsieh61ffd042021-05-20 15:14:25 -0700393 ArrayRef<const std::string>(image_locations),
Orion Hodson1da77262021-02-10 14:03:59 +0000394 ArrayRef<const std::string>(bcp_locations),
395 ArrayRef<const std::string>(bcp),
Victor Hsieha09d8b72021-05-24 14:21:55 -0700396 ArrayRef<const int>(bcp_fds),
Orion Hodson1da77262021-02-10 14:03:59 +0000397 runtime->GetInstructionSet(),
398 &error_msg)) {
Orion Hodson0a737622021-02-26 13:10:10 +0000399 LOG(INFO) << "Failed to verify boot class path checksums: " << error_msg;
Orion Hodson1da77262021-02-10 14:03:59 +0000400 return ReturnCode::kDex2OatFromScratch;
401 }
402
403 const auto& image_spaces = runtime->GetHeap()->GetBootImageSpaces();
Orion Hodson0a737622021-02-26 13:10:10 +0000404 size_t bcp_component_count = 0;
Orion Hodson1da77262021-02-10 14:03:59 +0000405 for (const auto& image_space : image_spaces) {
Orion Hodson0a737622021-02-26 13:10:10 +0000406 if (!image_space->GetImageHeader().IsValid()) {
407 LOG(INFO) << "Image header is not valid: " << image_space->GetImageFilename();
George Burgess IV27b8cb72021-02-21 15:44:27 -0800408 return ReturnCode::kDex2OatFromScratch;
409 }
Orion Hodson0a737622021-02-26 13:10:10 +0000410 const OatFile* oat_file = image_space->GetOatFile();
411 if (oat_file == nullptr) {
412 const std::string oat_path = ReplaceFileExtension(image_space->GetImageFilename(), "oat");
413 LOG(INFO) << "Oat file missing: " << oat_path;
414 return ReturnCode::kDex2OatFromScratch;
415 }
416 if (!oat_file->GetOatHeader().IsValid() ||
417 !ImageSpace::ValidateOatFile(*oat_file, &error_msg)) {
418 LOG(INFO) << "Oat file is not valid: " << oat_file->GetLocation() << " " << error_msg;
Orion Hodson1da77262021-02-10 14:03:59 +0000419 return ReturnCode::kDex2OatFromScratch;
420 }
421 const VdexFile* vdex_file = oat_file->GetVdexFile();
422 if (vdex_file == nullptr || !vdex_file->IsValid()) {
Orion Hodson0a737622021-02-26 13:10:10 +0000423 LOG(INFO) << "Vdex file is not valid : " << oat_file->GetLocation();
Orion Hodson1da77262021-02-10 14:03:59 +0000424 return ReturnCode::kDex2OatFromScratch;
425 }
Orion Hodson0a737622021-02-26 13:10:10 +0000426 bcp_component_count += image_space->GetComponentCount();
427 }
428
429 // If the number of components encountered in the image spaces does not match the number
430 // of components expected from the boot classpath locations then something is missing.
431 if (bcp_component_count != bcp_locations.size()) {
432 for (size_t i = bcp_component_count; i < bcp_locations.size(); ++i) {
433 LOG(INFO) << "Missing image file for " << bcp_locations[i];
434 }
435 return ReturnCode::kDex2OatFromScratch;
Orion Hodson1da77262021-02-10 14:03:59 +0000436 }
437
438 return ReturnCode::kNoDexOptNeeded;
439 }
440
Orion Hodsona4731bd2020-11-16 14:56:50 +0000441 ReturnCode FlattenClassLoaderContext() const {
David Brazdil89821862019-03-19 13:57:43 +0000442 DCHECK(only_flatten_context_);
443 if (context_str_.empty()) {
Orion Hodsona4731bd2020-11-16 14:56:50 +0000444 return ReturnCode::kErrorInvalidArguments;
David Brazdil89821862019-03-19 13:57:43 +0000445 }
446
447 std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::Create(context_str_);
448 if (context == nullptr) {
449 Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
450 }
451
452 std::cout << context->FlattenDexPaths() << std::flush;
Orion Hodsona4731bd2020-11-16 14:56:50 +0000453 return ReturnCode::kFlattenClassLoaderContextSuccess;
David Brazdil89821862019-03-19 13:57:43 +0000454 }
455
Orion Hodsona4731bd2020-11-16 14:56:50 +0000456 ReturnCode Run() const {
David Brazdil89821862019-03-19 13:57:43 +0000457 if (only_flatten_context_) {
458 return FlattenClassLoaderContext();
Orion Hodson1da77262021-02-10 14:03:59 +0000459 } else if (only_validate_bcp_) {
460 return ValidateBcp();
David Brazdil89821862019-03-19 13:57:43 +0000461 } else {
462 return GetDexOptNeeded();
463 }
464 }
465
Calin Juravle36eb3132017-01-13 16:32:38 -0800466 private:
467 std::string dex_file_;
468 InstructionSet isa_;
469 CompilerFilter::Filter compiler_filter_;
Nicolas Geoffray35de14b2019-01-10 13:10:36 +0000470 std::string context_str_;
David Brazdil89821862019-03-19 13:57:43 +0000471 bool only_flatten_context_;
Orion Hodson1da77262021-02-10 14:03:59 +0000472 bool only_validate_bcp_;
Calin Juravle17374092021-06-08 13:45:09 -0700473 ProfileAnalysisResult profile_analysis_result_;
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700474 bool downgrade_;
Calin Juravle36eb3132017-01-13 16:32:38 -0800475 std::string image_;
Vladimir Marko813b9142018-11-29 11:20:07 +0000476 std::vector<const char*> runtime_args_;
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700477 int oat_fd_ = -1;
478 int vdex_fd_ = -1;
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -0700479 // File descriptor corresponding to apk, dex_file, or zip.
480 int zip_fd_ = -1;
David Brazdil89821862019-03-19 13:57:43 +0000481 std::vector<int> context_fds_;
Calin Juravle36eb3132017-01-13 16:32:38 -0800482};
483
Orion Hodsona4731bd2020-11-16 14:56:50 +0000484static ReturnCode dexoptAnalyze(int argc, char** argv) {
Calin Juravle36eb3132017-01-13 16:32:38 -0800485 DexoptAnalyzer analyzer;
486
487 // Parse arguments. Argument mistakes will lead to exit(kErrorInvalidArguments) in UsageError.
488 analyzer.ParseArgs(argc, argv);
David Brazdil89821862019-03-19 13:57:43 +0000489 return analyzer.Run();
Calin Juravle36eb3132017-01-13 16:32:38 -0800490}
491
Orion Hodsona4731bd2020-11-16 14:56:50 +0000492} // namespace dexoptanalyzer
Calin Juravle36eb3132017-01-13 16:32:38 -0800493} // namespace art
494
495int main(int argc, char **argv) {
Orion Hodsona4731bd2020-11-16 14:56:50 +0000496 art::dexoptanalyzer::ReturnCode return_code = art::dexoptanalyzer::dexoptAnalyze(argc, argv);
497 return static_cast<int>(return_code);
Calin Juravle36eb3132017-01-13 16:32:38 -0800498}