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 <iostream>
18 #include <string>
19 #include <string_view>
20 
21 #include "android-base/stringprintf.h"
22 #include "android-base/strings.h"
23 #include "base/file_utils.h"
24 #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"
29 #include "compiler_filter.h"
30 #include "class_loader_context.h"
31 #include "dex/dex_file.h"
32 #include "noop_compiler_callbacks.h"
33 #include "oat_file_assistant.h"
34 #include "runtime.h"
35 #include "thread-inl.h"
36 
37 namespace art {
38 
39 // See OatFileAssistant docs for the meaning of the valid return codes.
40 enum ReturnCodes {
41   kNoDexOptNeeded = 0,
42   kDex2OatFromScratch = 1,
43   kDex2OatForBootImageOat = 2,
44   kDex2OatForFilterOat = 3,
45   kDex2OatForBootImageOdex = 4,
46   kDex2OatForFilterOdex = 5,
47 
48   // 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 
53   kErrorInvalidArguments = 101,
54   kErrorCannotCreateRuntime = 102,
55   kErrorUnknownDexOptNeeded = 103
56 };
57 
58 static int original_argc;
59 static char** original_argv;
60 
CommandLine()61 static std::string CommandLine() {
62   std::vector<std::string> command;
63   command.reserve(original_argc);
64   for (int i = 0; i < original_argc; ++i) {
65     command.push_back(original_argv[i]);
66   }
67   return android::base::Join(command, ' ');
68 }
69 
UsageErrorV(const char * fmt,va_list ap)70 static 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 
UsageError(const char * fmt,...)76 static void UsageError(const char* fmt, ...) {
77   va_list ap;
78   va_start(ap, fmt);
79   UsageErrorV(fmt, ap);
80   va_end(ap);
81 }
82 
Usage(const char * fmt,...)83 NO_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("");
108   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("");
113   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("");
116   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("");
120   UsageError("  --zip-fd=number: specifies a file descriptor corresponding to the dex file.");
121   UsageError("");
122   UsageError("  --downgrade: optional, if the purpose of dexopt is to downgrade the dex file");
123   UsageError("       By default, dexopt considers upgrade case.");
124   UsageError("");
125   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("");
136   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");
145   UsageError("        kDex2OatForBootImageOdex = 4");
146   UsageError("        kDex2OatForFilterOdex = 5");
147 
148   UsageError("        kErrorInvalidArguments = 101");
149   UsageError("        kErrorCannotCreateRuntime = 102");
150   UsageError("        kErrorUnknownDexOptNeeded = 103");
151   UsageError("");
152 
153   exit(kErrorInvalidArguments);
154 }
155 
156 class DexoptAnalyzer final {
157  public:
DexoptAnalyzer()158   DexoptAnalyzer() :
159       only_flatten_context_(false),
160       assume_profile_changed_(false),
161       downgrade_(false) {}
162 
ParseArgs(int argc,char ** argv)163   void ParseArgs(int argc, char **argv) {
164     original_argc = argc;
165     original_argv = argv;
166 
167     Locks::Init();
168     InitLogging(argv, Runtime::Abort);
169     // 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) {
178       const char* raw_option = argv[i];
179       const std::string_view option(raw_option);
180       if (option == "--assume-profile-changed") {
181         assume_profile_changed_ = true;
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 {
240         Usage("Unknown argument '%s'", raw_option);
241       }
242     }
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 
CreateRuntime() const257   bool CreateRuntime() const {
258     RuntimeOptions options;
259     // The image could be custom, so make sure we explicitly pass it.
260     std::string img = "-Ximage:" + image_;
261     options.push_back(std::make_pair(img, nullptr));
262     // 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));
265     // Explicit runtime args.
266     for (const char* runtime_arg : runtime_args_) {
267       options.push_back(std::make_pair(runtime_arg, nullptr));
268     }
269      // 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 
GetDexOptNeeded() const290   int GetDexOptNeeded() const {
291     if (!CreateRuntime()) {
292       return kErrorCannotCreateRuntime;
293     }
294     std::unique_ptr<Runtime> runtime(Runtime::Current());
295 
296     // 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 
307     std::unique_ptr<OatFileAssistant> oat_file_assistant;
308     oat_file_assistant = std::make_unique<OatFileAssistant>(dex_file_.c_str(),
309                                                             isa_,
310                                                             /*load_executable=*/ false,
311                                                             /*only_load_system_executable=*/ false,
312                                                             vdex_fd_,
313                                                             oat_fd_,
314                                                             zip_fd_);
315     // Always treat elements of the bootclasspath as up-to-date.
316     // TODO(calin): this check should be in OatFileAssistant.
317     if (oat_file_assistant->IsInBootClassPath()) {
318       return kNoDexOptNeeded;
319     }
320 
321     int dexoptNeeded = oat_file_assistant->GetDexOptNeeded(compiler_filter_,
322                                                            class_loader_context.get(),
323                                                            context_fds_,
324                                                            assume_profile_changed_,
325                                                            downgrade_);
326 
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;
333 
334       case -OatFileAssistant::kDex2OatForBootImage: return kDex2OatForBootImageOdex;
335       case -OatFileAssistant::kDex2OatForFilter: return kDex2OatForFilterOdex;
336       default:
337         LOG(ERROR) << "Unknown dexoptNeeded " << dexoptNeeded;
338         return kErrorUnknownDexOptNeeded;
339     }
340   }
341 
FlattenClassLoaderContext() const342   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 
Run() const357   int Run() const {
358     if (only_flatten_context_) {
359       return FlattenClassLoaderContext();
360     } else {
361       return GetDexOptNeeded();
362     }
363   }
364 
365  private:
366   std::string dex_file_;
367   InstructionSet isa_;
368   CompilerFilter::Filter compiler_filter_;
369   std::string context_str_;
370   bool only_flatten_context_;
371   bool assume_profile_changed_;
372   bool downgrade_;
373   std::string image_;
374   std::vector<const char*> runtime_args_;
375   int oat_fd_ = -1;
376   int vdex_fd_ = -1;
377   // File descriptor corresponding to apk, dex_file, or zip.
378   int zip_fd_ = -1;
379   std::vector<int> context_fds_;
380 };
381 
dexoptAnalyze(int argc,char ** argv)382 static 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);
387   return analyzer.Run();
388 }
389 
390 }  // namespace art
391 
main(int argc,char ** argv)392 int main(int argc, char **argv) {
393   return art::dexoptAnalyze(argc, argv);
394 }
395