1 /*
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 
17 #include "dexoptanalyzer.h"
18 
19 #include <iostream>
20 #include <string>
21 #include <string_view>
22 
23 #include "android-base/stringprintf.h"
24 #include "android-base/strings.h"
25 #include "base/compiler_filter.h"
26 #include "base/file_utils.h"
27 #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"
32 #include "class_linker.h"
33 #include "class_loader_context.h"
34 #include "dex/dex_file.h"
35 #include "gc/heap.h"
36 #include "gc/space/image_space.h"
37 #include "noop_compiler_callbacks.h"
38 #include "oat.h"
39 #include "oat_file_assistant.h"
40 #include "runtime.h"
41 #include "thread-inl.h"
42 #include "vdex_file.h"
43 
44 namespace art {
45 namespace dexoptanalyzer {
46 
47 static int original_argc;
48 static char** original_argv;
49 
CommandLine()50 static std::string CommandLine() {
51   std::vector<std::string> command;
52   command.reserve(original_argc);
53   for (int i = 0; i < original_argc; ++i) {
54     command.push_back(original_argv[i]);
55   }
56   return android::base::Join(command, ' ');
57 }
58 
UsageErrorV(const char * fmt,va_list ap)59 static 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 
UsageError(const char * fmt,...)65 static void UsageError(const char* fmt, ...) {
66   va_list ap;
67   va_start(ap, fmt);
68   UsageErrorV(fmt, ap);
69   va_end(ap);
70 }
71 
Usage(const char * fmt,...)72 NO_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("");
90   UsageError("  --profile_analysis_result=<int>: the result of the profile analysis, used in");
91   UsageError("       deciding if the dex file needs to be optimized.");
92   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("");
97   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("");
102   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("");
105   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("");
109   UsageError("  --zip-fd=number: specifies a file descriptor corresponding to the dex file.");
110   UsageError("");
111   UsageError("  --downgrade: optional, if the purpose of dexopt is to downgrade the dex file");
112   UsageError("       By default, dexopt considers upgrade case.");
113   UsageError("");
114   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("");
125   UsageError("  --validate-bcp: validates the boot class path files (.art, .oat, .vdex).");
126   UsageError("      Requires --isa and --image options to locate artifacts.");
127   UsageError("");
128   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");
137   UsageError("        kDex2OatForBootImageOdex = 4");
138   UsageError("        kDex2OatForFilterOdex = 5");
139 
140   UsageError("        kErrorInvalidArguments = 101");
141   UsageError("        kErrorCannotCreateRuntime = 102");
142   UsageError("        kErrorUnknownDexOptNeeded = 103");
143   UsageError("");
144 
145   exit(static_cast<int>(ReturnCode::kErrorInvalidArguments));
146 }
147 
148 class DexoptAnalyzer final {
149  public:
DexoptAnalyzer()150   DexoptAnalyzer() :
151       only_flatten_context_(false),
152       only_validate_bcp_(false),
153       downgrade_(false) {}
154 
ParseArgs(int argc,char ** argv)155   void ParseArgs(int argc, char **argv) {
156     original_argc = argc;
157     original_argv = argv;
158 
159     Locks::Init();
160     InitLogging(argv, Runtime::Abort);
161     // 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) {
170       const char* raw_option = argv[i];
171       const std::string_view option(raw_option);
172 
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);
182       } 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);
188         }
189       } else if (StartsWith(option, "--isa=")) {
190         const char* isa_str = raw_option + strlen("--isa=");
191         isa_ = GetInstructionSetFromString(isa_str);
192         if (isa_ == InstructionSet::kNone) {
193           Usage("Invalid isa '%s'", raw_option);
194         }
195       } else if (StartsWith(option, "--image=")) {
196         image_ = std::string(option.substr(strlen("--image=")));
197       } 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]);
203       } else if (StartsWith(option, "--android-data=")) {
204         // 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.
206         const char* new_android_data = raw_option + strlen("--android-data=");
207         setenv("ANDROID_DATA", new_android_data, 1);
208       } else if (option == "--downgrade") {
209         downgrade_ = true;
210       } else if (StartsWith(option, "--oat-fd=")) {
211         oat_fd_ = std::stoi(std::string(option.substr(strlen("--oat-fd="))), nullptr, 0);
212         if (oat_fd_ < 0) {
213           Usage("Invalid --oat-fd %d", oat_fd_);
214         }
215       } else if (StartsWith(option, "--vdex-fd=")) {
216         vdex_fd_ = std::stoi(std::string(option.substr(strlen("--vdex-fd="))), nullptr, 0);
217         if (vdex_fd_ < 0) {
218           Usage("Invalid --vdex-fd %d", vdex_fd_);
219         }
220       } 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=")));
227       } 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;
239       } else if (option == "--validate-bcp") {
240         only_validate_bcp_ = true;
241       } else {
242         Usage("Unknown argument '%s'", raw_option);
243       }
244     }
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 
CreateRuntime() const259   bool CreateRuntime() const {
260     RuntimeOptions options;
261     // The image could be custom, so make sure we explicitly pass it.
262     std::string img = "-Ximage:" + image_;
263     options.push_back(std::make_pair(img, nullptr));
264     // 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));
267     // Explicit runtime args.
268     for (const char* runtime_arg : runtime_args_) {
269       options.push_back(std::make_pair(runtime_arg, nullptr));
270     }
271      // 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.
287     Thread::Current()->TransitionFromRunnableToSuspended(kNative);
288 
289     return true;
290   }
291 
GetDexOptNeeded() const292   ReturnCode GetDexOptNeeded() const {
293     if (!CreateRuntime()) {
294       return ReturnCode::kErrorCannotCreateRuntime;
295     }
296     std::unique_ptr<Runtime> runtime(Runtime::Current());
297 
298     // 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     }
308     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     }
320 
321     std::unique_ptr<OatFileAssistant> oat_file_assistant;
322     oat_file_assistant = std::make_unique<OatFileAssistant>(dex_file_.c_str(),
323                                                             isa_,
324                                                             class_loader_context.get(),
325                                                             /*load_executable=*/ false,
326                                                             /*only_load_trusted_executable=*/ false,
327                                                             vdex_fd_,
328                                                             oat_fd_,
329                                                             zip_fd_);
330     // Always treat elements of the bootclasspath as up-to-date.
331     // TODO(calin): this check should be in OatFileAssistant.
332     if (oat_file_assistant->IsInBootClassPath()) {
333       return ReturnCode::kNoDexOptNeeded;
334     }
335 
336     // 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,
348                                                            downgrade_);
349 
350     // Convert OatFileAssistant codes to dexoptanalyzer codes.
351     switch (dexoptNeeded) {
352       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;
356 
357       case -OatFileAssistant::kDex2OatForBootImage: return ReturnCode::kDex2OatForBootImageOdex;
358       case -OatFileAssistant::kDex2OatForFilter: return ReturnCode::kDex2OatForFilterOdex;
359       default:
360         LOG(ERROR) << "Unknown dexoptNeeded " << dexoptNeeded;
361         return ReturnCode::kErrorUnknownDexOptNeeded;
362     }
363   }
364 
365   // 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.
ValidateBcp() const372   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();
388     const std::string bcp_locations_path = android::base::Join(bcp_locations, ':');
389     if (!ImageSpace::VerifyBootClassPathChecksums(checksums,
390                                                   bcp_locations_path,
391                                                   runtime->GetImageLocation(),
392                                                   ArrayRef<const std::string>(bcp_locations),
393                                                   ArrayRef<const std::string>(bcp),
394                                                   runtime->GetInstructionSet(),
395                                                   &error_msg)) {
396       LOG(INFO) << "Failed to verify boot class path checksums: " << error_msg;
397       return ReturnCode::kDex2OatFromScratch;
398     }
399 
400     const auto& image_spaces = runtime->GetHeap()->GetBootImageSpaces();
401     size_t bcp_component_count = 0;
402     for (const auto& image_space : image_spaces) {
403       if (!image_space->GetImageHeader().IsValid()) {
404         LOG(INFO) << "Image header is not valid: " << image_space->GetImageFilename();
405         return ReturnCode::kDex2OatFromScratch;
406       }
407       const OatFile* oat_file = image_space->GetOatFile();
408       if (oat_file == nullptr) {
409         const std::string oat_path = ReplaceFileExtension(image_space->GetImageFilename(), "oat");
410         LOG(INFO) << "Oat file missing: " << oat_path;
411         return ReturnCode::kDex2OatFromScratch;
412       }
413       if (!oat_file->GetOatHeader().IsValid() ||
414           !ImageSpace::ValidateOatFile(*oat_file, &error_msg)) {
415         LOG(INFO) << "Oat file is not valid: " << oat_file->GetLocation() << " " << error_msg;
416         return ReturnCode::kDex2OatFromScratch;
417       }
418       const VdexFile* vdex_file = oat_file->GetVdexFile();
419       if (vdex_file == nullptr || !vdex_file->IsValid()) {
420         LOG(INFO) << "Vdex file is not valid : " << oat_file->GetLocation();
421         return ReturnCode::kDex2OatFromScratch;
422       }
423       bcp_component_count += image_space->GetComponentCount();
424     }
425 
426     // If the number of components encountered in the image spaces does not match the number
427     // of components expected from the boot classpath locations then something is missing.
428     if (bcp_component_count != bcp_locations.size()) {
429       for (size_t i = bcp_component_count; i < bcp_locations.size(); ++i) {
430         LOG(INFO) << "Missing image file for " << bcp_locations[i];
431       }
432       return ReturnCode::kDex2OatFromScratch;
433     }
434 
435     return ReturnCode::kNoDexOptNeeded;
436   }
437 
FlattenClassLoaderContext() const438   ReturnCode FlattenClassLoaderContext() const {
439     DCHECK(only_flatten_context_);
440     if (context_str_.empty()) {
441       return ReturnCode::kErrorInvalidArguments;
442     }
443 
444     std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::Create(context_str_);
445     if (context == nullptr) {
446       Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
447     }
448 
449     std::cout << context->FlattenDexPaths() << std::flush;
450     return ReturnCode::kFlattenClassLoaderContextSuccess;
451   }
452 
Run() const453   ReturnCode Run() const {
454     if (only_flatten_context_) {
455       return FlattenClassLoaderContext();
456     } else if (only_validate_bcp_) {
457       return ValidateBcp();
458     } else {
459       return GetDexOptNeeded();
460     }
461   }
462 
463  private:
464   std::string dex_file_;
465   InstructionSet isa_;
466   CompilerFilter::Filter compiler_filter_;
467   std::string context_str_;
468   bool only_flatten_context_;
469   bool only_validate_bcp_;
470   ProfileAnalysisResult profile_analysis_result_;
471   bool downgrade_;
472   std::string image_;
473   std::vector<const char*> runtime_args_;
474   int oat_fd_ = -1;
475   int vdex_fd_ = -1;
476   // File descriptor corresponding to apk, dex_file, or zip.
477   int zip_fd_ = -1;
478   std::vector<int> context_fds_;
479 };
480 
dexoptAnalyze(int argc,char ** argv)481 static ReturnCode dexoptAnalyze(int argc, char** argv) {
482   DexoptAnalyzer analyzer;
483 
484   // Parse arguments. Argument mistakes will lead to exit(kErrorInvalidArguments) in UsageError.
485   analyzer.ParseArgs(argc, argv);
486   return analyzer.Run();
487 }
488 
489 }  // namespace dexoptanalyzer
490 }  // namespace art
491 
main(int argc,char ** argv)492 int main(int argc, char **argv) {
493   art::dexoptanalyzer::ReturnCode return_code = art::dexoptanalyzer::dexoptAnalyze(argc, argv);
494   return static_cast<int>(return_code);
495 }
496