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/utils.h"
31 #include "class_linker.h"
32 #include "class_loader_context.h"
33 #include "dex/dex_file.h"
34 #include "gc/heap.h"
35 #include "gc/space/image_space.h"
36 #include "noop_compiler_callbacks.h"
37 #include "oat/oat.h"
38 #include "oat/oat_file_assistant.h"
39 #include "runtime.h"
40 #include "thread-inl.h"
41 #include "vdex_file.h"
42 
43 namespace art {
44 namespace dexoptanalyzer {
45 
46 static int original_argc;
47 static char** original_argv;
48 
CommandLine()49 static std::string CommandLine() {
50   std::vector<std::string> command;
51   command.reserve(original_argc);
52   for (int i = 0; i < original_argc; ++i) {
53     command.push_back(original_argv[i]);
54   }
55   return android::base::Join(command, ' ');
56 }
57 
UsageErrorV(const char * fmt,va_list ap)58 static void UsageErrorV(const char* fmt, va_list ap) {
59   std::string error;
60   android::base::StringAppendV(&error, fmt, ap);
61   LOG(ERROR) << error;
62 }
63 
UsageError(const char * fmt,...)64 static void UsageError(const char* fmt, ...) {
65   va_list ap;
66   va_start(ap, fmt);
67   UsageErrorV(fmt, ap);
68   va_end(ap);
69 }
70 
Usage(const char * fmt,...)71 NO_RETURN static void Usage(const char *fmt, ...) {
72   va_list ap;
73   va_start(ap, fmt);
74   UsageErrorV(fmt, ap);
75   va_end(ap);
76 
77   UsageError("Command: %s", CommandLine().c_str());
78   UsageError("  Performs a dexopt analysis on the given dex file and returns whether or not");
79   UsageError("  the dex file needs to be dexopted.");
80   UsageError("Usage: dexoptanalyzer [options]...");
81   UsageError("");
82   UsageError("  --dex-file=<filename>: the dex file which should be analyzed.");
83   UsageError("");
84   UsageError("  --isa=<string>: the instruction set for which the analysis should be performed.");
85   UsageError("");
86   UsageError("  --compiler-filter=<string>: the target compiler filter to be used as reference");
87   UsageError("       when deciding if the dex file needs to be optimized.");
88   UsageError("");
89   UsageError("  --profile_analysis_result=<int>: the result of the profile analysis, used in");
90   UsageError("       deciding if the dex file needs to be optimized.");
91   UsageError("");
92   UsageError("  --image=<filename>: optional, the image to be used to decide if the associated");
93   UsageError("       oat file is up to date. Defaults to $ANDROID_ROOT/framework/boot.art.");
94   UsageError("       Example: --image=/system/framework/boot.art");
95   UsageError("");
96   UsageError("  --runtime-arg <argument>: used to specify various arguments for the runtime,");
97   UsageError("      such as initial heap size, maximum heap size, and verbose output.");
98   UsageError("      Use a separate --runtime-arg switch for each argument.");
99   UsageError("      Example: --runtime-arg -Xms256m");
100   UsageError("");
101   UsageError("  --android-data=<directory>: optional, the directory which should be used as");
102   UsageError("       android-data. By default ANDROID_DATA env variable is used.");
103   UsageError("");
104   UsageError("  --oat-fd=number: file descriptor of the oat file which should be analyzed");
105   UsageError("");
106   UsageError("  --vdex-fd=number: file descriptor of the vdex file corresponding to the oat file");
107   UsageError("");
108   UsageError("  --zip-fd=number: specifies a file descriptor corresponding to the dex file.");
109   UsageError("");
110   UsageError("  --downgrade: optional, if the purpose of dexopt is to downgrade the dex file");
111   UsageError("       By default, dexopt considers upgrade case.");
112   UsageError("");
113   UsageError("  --class-loader-context=<string spec>: a string specifying the intended");
114   UsageError("      runtime loading context for the compiled dex files.");
115   UsageError("");
116   UsageError("  --class-loader-context-fds=<fds>: a colon-separated list of file descriptors");
117   UsageError("      for dex files in --class-loader-context. Their order must be the same as");
118   UsageError("      dex files in flattened class loader context.");
119   UsageError("");
120   UsageError("  --flatten-class-loader-context: parse --class-loader-context, flatten it and");
121   UsageError("      print a colon-separated list of its dex files to standard output. Dexopt");
122   UsageError("      needed analysis is not performed when this option is set.");
123   UsageError("");
124   UsageError("Return code:");
125   UsageError("  To make it easier to integrate with the internal tools this command will make");
126   UsageError("    available its result (dexoptNeeded) as the exit/return code. i.e. it will not");
127   UsageError("    return 0 for success and a non zero values for errors as the conventional");
128   UsageError("    commands. The following return codes are possible:");
129   UsageError("        kNoDexOptNeeded = 0");
130   UsageError("        kDex2OatFromScratch = 1");
131   UsageError("        kDex2OatForBootImageOat = 2");
132   UsageError("        kDex2OatForFilterOat = 3");
133   UsageError("        kDex2OatForBootImageOdex = 4");
134   UsageError("        kDex2OatForFilterOdex = 5");
135 
136   UsageError("        kErrorInvalidArguments = 101");
137   UsageError("        kErrorCannotCreateRuntime = 102");
138   UsageError("        kErrorUnknownDexOptNeeded = 103");
139   UsageError("");
140 
141   exit(static_cast<int>(ReturnCode::kErrorInvalidArguments));
142 }
143 
144 class DexoptAnalyzer final {
145  public:
DexoptAnalyzer()146   DexoptAnalyzer() : only_flatten_context_(false), downgrade_(false) {}
147 
ParseArgs(int argc,char ** argv)148   void ParseArgs(int argc, char **argv) {
149     original_argc = argc;
150     original_argv = argv;
151 
152     Locks::Init();
153     InitLogging(argv, Runtime::Abort);
154     // Skip over the command name.
155     argv++;
156     argc--;
157 
158     if (argc == 0) {
159       Usage("No arguments specified");
160     }
161 
162     for (int i = 0; i < argc; ++i) {
163       const char* raw_option = argv[i];
164       const std::string_view option(raw_option);
165 
166       if (option.starts_with("--profile-analysis-result=")) {
167         int parse_result = std::stoi(std::string(
168             option.substr(strlen("--profile-analysis-result="))), nullptr, 0);
169         if (parse_result != static_cast<int>(ProfileAnalysisResult::kOptimize) &&
170             parse_result != static_cast<int>(ProfileAnalysisResult::kDontOptimizeSmallDelta) &&
171             parse_result != static_cast<int>(ProfileAnalysisResult::kDontOptimizeEmptyProfiles)) {
172           Usage("Invalid --profile-analysis-result= %d", parse_result);
173         }
174         profile_analysis_result_ = static_cast<ProfileAnalysisResult>(parse_result);
175       } else if (option.starts_with("--dex-file=")) {
176         dex_file_ = std::string(option.substr(strlen("--dex-file=")));
177       } else if (option.starts_with("--compiler-filter=")) {
178         const char* filter_str = raw_option + strlen("--compiler-filter=");
179         if (!CompilerFilter::ParseCompilerFilter(filter_str, &compiler_filter_)) {
180           Usage("Invalid compiler filter '%s'", raw_option);
181         }
182       } else if (option.starts_with("--isa=")) {
183         const char* isa_str = raw_option + strlen("--isa=");
184         isa_ = GetInstructionSetFromString(isa_str);
185         if (isa_ == InstructionSet::kNone) {
186           Usage("Invalid isa '%s'", raw_option);
187         }
188       } else if (option.starts_with("--image=")) {
189         image_ = std::string(option.substr(strlen("--image=")));
190       } else if (option == "--runtime-arg") {
191         if (i + 1 == argc) {
192           Usage("Missing argument for --runtime-arg\n");
193         }
194         ++i;
195         runtime_args_.push_back(argv[i]);
196       } else if (option.starts_with("--android-data=")) {
197         // Overwrite android-data if needed (oat file assistant relies on a valid directory to
198         // compute dalvik-cache folder). This is mostly used in tests.
199         const char* new_android_data = raw_option + strlen("--android-data=");
200         setenv("ANDROID_DATA", new_android_data, 1);
201       } else if (option == "--downgrade") {
202         downgrade_ = true;
203       } else if (option.starts_with("--oat-fd=")) {
204         oat_fd_ = std::stoi(std::string(option.substr(strlen("--oat-fd="))), nullptr, 0);
205         if (oat_fd_ < 0) {
206           Usage("Invalid --oat-fd %d", oat_fd_);
207         }
208       } else if (option.starts_with("--vdex-fd=")) {
209         vdex_fd_ = std::stoi(std::string(option.substr(strlen("--vdex-fd="))), nullptr, 0);
210         if (vdex_fd_ < 0) {
211           Usage("Invalid --vdex-fd %d", vdex_fd_);
212         }
213       } else if (option.starts_with("--zip-fd=")) {
214         zip_fd_ = std::stoi(std::string(option.substr(strlen("--zip-fd="))), nullptr, 0);
215         if (zip_fd_ < 0) {
216           Usage("Invalid --zip-fd %d", zip_fd_);
217         }
218       } else if (option.starts_with("--class-loader-context=")) {
219         context_str_ = std::string(option.substr(strlen("--class-loader-context=")));
220       } else if (option.starts_with("--class-loader-context-fds=")) {
221         std::string str_context_fds_arg =
222             std::string(option.substr(strlen("--class-loader-context-fds=")));
223         std::vector<std::string> str_fds = android::base::Split(str_context_fds_arg, ":");
224         for (const std::string& str_fd : str_fds) {
225           context_fds_.push_back(std::stoi(str_fd, nullptr, 0));
226           if (context_fds_.back() < 0) {
227             Usage("Invalid --class-loader-context-fds %s", str_context_fds_arg.c_str());
228           }
229         }
230       } else if (option == "--flatten-class-loader-context") {
231         only_flatten_context_ = true;
232       } else {
233         Usage("Unknown argument '%s'", raw_option);
234       }
235     }
236 
237     if (image_.empty()) {
238       // If we don't receive the image, try to use the default one.
239       // Tests may specify a different image (e.g. core image).
240       std::string error_msg;
241       std::string android_root = GetAndroidRootSafe(&error_msg);
242       if (android_root.empty()) {
243         LOG(ERROR) << error_msg;
244         Usage("--image unspecified and ANDROID_ROOT not set.");
245       }
246       image_ = GetDefaultBootImageLocationSafe(
247           android_root, /*deny_art_apex_data_files=*/false, &error_msg);
248       if (image_.empty()) {
249         LOG(ERROR) << error_msg;
250         Usage("--image unspecified and failed to get default boot image location.");
251       }
252     }
253   }
254 
CreateRuntime() const255   bool CreateRuntime() const {
256     RuntimeOptions options;
257     // The image could be custom, so make sure we explicitly pass it.
258     std::string img = "-Ximage:" + image_;
259     options.push_back(std::make_pair(img, nullptr));
260     // The instruction set of the image should match the instruction set we will test.
261     const void* isa_opt = reinterpret_cast<const void*>(GetInstructionSetString(isa_));
262     options.push_back(std::make_pair("imageinstructionset", isa_opt));
263     // Explicit runtime args.
264     for (const char* runtime_arg : runtime_args_) {
265       options.push_back(std::make_pair(runtime_arg, nullptr));
266     }
267      // Disable libsigchain. We don't don't need it to evaluate DexOptNeeded status.
268     options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
269     // Pretend we are a compiler so that we can re-use the same infrastructure to load a different
270     // ISA image and minimize the amount of things that get started.
271     NoopCompilerCallbacks callbacks;
272     options.push_back(std::make_pair("compilercallbacks", &callbacks));
273     // Make sure we don't attempt to relocate. The tool should only retrieve the DexOptNeeded
274     // status and not attempt to relocate the boot image.
275     options.push_back(std::make_pair("-Xnorelocate", nullptr));
276 
277     if (!Runtime::Create(options, false)) {
278       LOG(ERROR) << "Unable to initialize runtime";
279       return false;
280     }
281     // Runtime::Create acquired the mutator_lock_ that is normally given away when we
282     // Runtime::Start. Give it away now.
283     Thread::Current()->TransitionFromRunnableToSuspended(ThreadState::kNative);
284 
285     return true;
286   }
287 
GetDexOptNeeded() const288   ReturnCode GetDexOptNeeded() const {
289     if (!CreateRuntime()) {
290       return ReturnCode::kErrorCannotCreateRuntime;
291     }
292     std::unique_ptr<Runtime> runtime(Runtime::Current());
293 
294     // Only when the runtime is created can we create the class loader context: the
295     // class loader context will open dex file and use the MemMap global lock that the
296     // runtime owns.
297     std::unique_ptr<ClassLoaderContext> class_loader_context;
298     if (!context_str_.empty()) {
299       class_loader_context = ClassLoaderContext::Create(context_str_);
300       if (class_loader_context == nullptr) {
301         Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
302       }
303     }
304     if (class_loader_context != nullptr) {
305       size_t dir_index = dex_file_.rfind('/');
306       std::string classpath_dir = (dir_index != std::string::npos)
307           ? dex_file_.substr(0, dir_index)
308           : "";
309 
310       if (!class_loader_context->OpenDexFiles(classpath_dir,
311                                               context_fds_,
312                                               /*only_read_checksums=*/ true)) {
313         return ReturnCode::kDex2OatFromScratch;
314       }
315     }
316 
317     std::unique_ptr<OatFileAssistant> oat_file_assistant;
318     oat_file_assistant = std::make_unique<OatFileAssistant>(dex_file_.c_str(),
319                                                             isa_,
320                                                             class_loader_context.get(),
321                                                             /*load_executable=*/ false,
322                                                             /*only_load_trusted_executable=*/ false,
323                                                             /*runtime_options=*/ nullptr,
324                                                             vdex_fd_,
325                                                             oat_fd_,
326                                                             zip_fd_);
327     // Always treat elements of the bootclasspath as up-to-date.
328     // TODO(calin): this check should be in OatFileAssistant.
329     if (oat_file_assistant->IsInBootClassPath()) {
330       return ReturnCode::kNoDexOptNeeded;
331     }
332 
333     // If the compiler filter depends on profiles but the profiles are empty,
334     // change the test filter to kVerify. It's what dex2oat also does.
335     CompilerFilter::Filter actual_compiler_filter = compiler_filter_;
336     if (CompilerFilter::DependsOnProfile(compiler_filter_) &&
337         profile_analysis_result_ == ProfileAnalysisResult::kDontOptimizeEmptyProfiles) {
338       actual_compiler_filter = CompilerFilter::kVerify;
339     }
340 
341     // TODO: GetDexOptNeeded should get the raw analysis result instead of assume_profile_changed.
342     bool assume_profile_changed = profile_analysis_result_ == ProfileAnalysisResult::kOptimize;
343     int dexoptNeeded = oat_file_assistant->GetDexOptNeeded(actual_compiler_filter,
344                                                            assume_profile_changed,
345                                                            downgrade_);
346 
347     // Convert OatFileAssistant codes to dexoptanalyzer codes.
348     switch (dexoptNeeded) {
349       case OatFileAssistant::kNoDexOptNeeded: return ReturnCode::kNoDexOptNeeded;
350       case OatFileAssistant::kDex2OatFromScratch: return ReturnCode::kDex2OatFromScratch;
351       case OatFileAssistant::kDex2OatForBootImage: return ReturnCode::kDex2OatForBootImageOat;
352       case OatFileAssistant::kDex2OatForFilter: return ReturnCode::kDex2OatForFilterOat;
353 
354       case -OatFileAssistant::kDex2OatForBootImage: return ReturnCode::kDex2OatForBootImageOdex;
355       case -OatFileAssistant::kDex2OatForFilter: return ReturnCode::kDex2OatForFilterOdex;
356       default:
357         LOG(ERROR) << "Unknown dexoptNeeded " << dexoptNeeded;
358         return ReturnCode::kErrorUnknownDexOptNeeded;
359     }
360   }
361 
FlattenClassLoaderContext() const362   ReturnCode FlattenClassLoaderContext() const {
363     DCHECK(only_flatten_context_);
364     if (context_str_.empty()) {
365       return ReturnCode::kErrorInvalidArguments;
366     }
367 
368     std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::Create(context_str_);
369     if (context == nullptr) {
370       Usage("Invalid --class-loader-context '%s'", context_str_.c_str());
371     }
372 
373     std::cout << android::base::Join(context->FlattenDexPaths(), ':') << std::flush;
374     return ReturnCode::kFlattenClassLoaderContextSuccess;
375   }
376 
Run() const377   ReturnCode Run() const {
378     if (only_flatten_context_) {
379       return FlattenClassLoaderContext();
380     } else {
381       return GetDexOptNeeded();
382     }
383   }
384 
385  private:
386   std::string dex_file_;
387   InstructionSet isa_;
388   CompilerFilter::Filter compiler_filter_;
389   std::string context_str_;
390   bool only_flatten_context_;
391   ProfileAnalysisResult profile_analysis_result_;
392   bool downgrade_;
393   std::string image_;
394   std::vector<const char*> runtime_args_;
395   int oat_fd_ = -1;
396   int vdex_fd_ = -1;
397   // File descriptor corresponding to apk, dex_file, or zip.
398   int zip_fd_ = -1;
399   std::vector<int> context_fds_;
400 };
401 
dexoptAnalyze(int argc,char ** argv)402 static ReturnCode dexoptAnalyze(int argc, char** argv) {
403   DexoptAnalyzer analyzer;
404 
405   // Parse arguments. Argument mistakes will lead to exit(kErrorInvalidArguments) in UsageError.
406   analyzer.ParseArgs(argc, argv);
407   return analyzer.Run();
408 }
409 
410 }  // namespace dexoptanalyzer
411 }  // namespace art
412 
main(int argc,char ** argv)413 int main(int argc, char **argv) {
414   art::dexoptanalyzer::ReturnCode return_code = art::dexoptanalyzer::dexoptAnalyze(argc, argv);
415   return static_cast<int>(return_code);
416 }
417