• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <string>
18 
19 #include "base/logging.h"  // For InitLogging.
20 #include "base/mutex.h"
21 #include "base/os.h"
22 #include "base/utils.h"
23 #include "android-base/stringprintf.h"
24 #include "android-base/strings.h"
25 #include "base/file_utils.h"
26 #include "compiler_filter.h"
27 #include "class_loader_context.h"
28 #include "dex/dex_file.h"
29 #include "noop_compiler_callbacks.h"
30 #include "oat_file_assistant.h"
31 #include "runtime.h"
32 #include "thread-inl.h"
33 
34 namespace art {
35 
36 // See OatFileAssistant docs for the meaning of the valid return codes.
37 enum ReturnCodes {
38   kNoDexOptNeeded = 0,
39   kDex2OatFromScratch = 1,
40   kDex2OatForBootImageOat = 2,
41   kDex2OatForFilterOat = 3,
42   kDex2OatForRelocationOat = 4,
43   kDex2OatForBootImageOdex = 5,
44   kDex2OatForFilterOdex = 6,
45   kDex2OatForRelocationOdex = 7,
46 
47   kErrorInvalidArguments = 101,
48   kErrorCannotCreateRuntime = 102,
49   kErrorUnknownDexOptNeeded = 103
50 };
51 
52 static int original_argc;
53 static char** original_argv;
54 
CommandLine()55 static std::string CommandLine() {
56   std::vector<std::string> command;
57   for (int i = 0; i < original_argc; ++i) {
58     command.push_back(original_argv[i]);
59   }
60   return android::base::Join(command, ' ');
61 }
62 
UsageErrorV(const char * fmt,va_list ap)63 static void UsageErrorV(const char* fmt, va_list ap) {
64   std::string error;
65   android::base::StringAppendV(&error, fmt, ap);
66   LOG(ERROR) << error;
67 }
68 
UsageError(const char * fmt,...)69 static void UsageError(const char* fmt, ...) {
70   va_list ap;
71   va_start(ap, fmt);
72   UsageErrorV(fmt, ap);
73   va_end(ap);
74 }
75 
Usage(const char * fmt,...)76 NO_RETURN static void Usage(const char *fmt, ...) {
77   va_list ap;
78   va_start(ap, fmt);
79   UsageErrorV(fmt, ap);
80   va_end(ap);
81 
82   UsageError("Command: %s", CommandLine().c_str());
83   UsageError("  Performs a dexopt analysis on the given dex file and returns whether or not");
84   UsageError("  the dex file needs to be dexopted.");
85   UsageError("Usage: dexoptanalyzer [options]...");
86   UsageError("");
87   UsageError("  --dex-file=<filename>: the dex file which should be analyzed.");
88   UsageError("");
89   UsageError("  --isa=<string>: the instruction set for which the analysis should be performed.");
90   UsageError("");
91   UsageError("  --compiler-filter=<string>: the target compiler filter to be used as reference");
92   UsageError("       when deciding if the dex file needs to be optimized.");
93   UsageError("");
94   UsageError("  --assume-profile-changed: assumes the profile information has changed");
95   UsageError("       when deciding if the dex file needs to be optimized.");
96   UsageError("");
97   UsageError("  --image=<filename>: optional, the image to be used to decide if the associated");
98   UsageError("       oat file is up to date. Defaults to $ANDROID_ROOT/framework/boot.art.");
99   UsageError("       Example: --image=/system/framework/boot.art");
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("Return code:");
114   UsageError("  To make it easier to integrate with the internal tools this command will make");
115   UsageError("    available its result (dexoptNeeded) as the exit/return code. i.e. it will not");
116   UsageError("    return 0 for success and a non zero values for errors as the conventional");
117   UsageError("    commands. The following return codes are possible:");
118   UsageError("        kNoDexOptNeeded = 0");
119   UsageError("        kDex2OatFromScratch = 1");
120   UsageError("        kDex2OatForBootImageOat = 2");
121   UsageError("        kDex2OatForFilterOat = 3");
122   UsageError("        kDex2OatForRelocationOat = 4");
123   UsageError("        kDex2OatForBootImageOdex = 5");
124   UsageError("        kDex2OatForFilterOdex = 6");
125   UsageError("        kDex2OatForRelocationOdex = 7");
126 
127   UsageError("        kErrorInvalidArguments = 101");
128   UsageError("        kErrorCannotCreateRuntime = 102");
129   UsageError("        kErrorUnknownDexOptNeeded = 103");
130   UsageError("");
131 
132   exit(kErrorInvalidArguments);
133 }
134 
135 class DexoptAnalyzer FINAL {
136  public:
DexoptAnalyzer()137   DexoptAnalyzer() :
138       assume_profile_changed_(false),
139       downgrade_(false) {}
140 
ParseArgs(int argc,char ** argv)141   void ParseArgs(int argc, char **argv) {
142     original_argc = argc;
143     original_argv = argv;
144 
145     Locks::Init();
146     InitLogging(argv, Runtime::Abort);
147     // Skip over the command name.
148     argv++;
149     argc--;
150 
151     if (argc == 0) {
152       Usage("No arguments specified");
153     }
154 
155     for (int i = 0; i < argc; ++i) {
156       const StringPiece option(argv[i]);
157       if (option == "--assume-profile-changed") {
158         assume_profile_changed_ = true;
159       } else if (option.starts_with("--dex-file=")) {
160         dex_file_ = option.substr(strlen("--dex-file=")).ToString();
161       } else if (option.starts_with("--compiler-filter=")) {
162         std::string filter_str = option.substr(strlen("--compiler-filter=")).ToString();
163         if (!CompilerFilter::ParseCompilerFilter(filter_str.c_str(), &compiler_filter_)) {
164           Usage("Invalid compiler filter '%s'", option.data());
165         }
166       } else if (option.starts_with("--isa=")) {
167         std::string isa_str = option.substr(strlen("--isa=")).ToString();
168         isa_ = GetInstructionSetFromString(isa_str.c_str());
169         if (isa_ == InstructionSet::kNone) {
170           Usage("Invalid isa '%s'", option.data());
171         }
172       } else if (option.starts_with("--image=")) {
173         image_ = option.substr(strlen("--image=")).ToString();
174       } else if (option.starts_with("--android-data=")) {
175         // Overwrite android-data if needed (oat file assistant relies on a valid directory to
176         // compute dalvik-cache folder). This is mostly used in tests.
177         std::string new_android_data = option.substr(strlen("--android-data=")).ToString();
178         setenv("ANDROID_DATA", new_android_data.c_str(), 1);
179       } else if (option.starts_with("--downgrade")) {
180         downgrade_ = true;
181       } else if (option.starts_with("--oat-fd")) {
182         oat_fd_ = std::stoi(option.substr(strlen("--oat-fd=")).ToString(), nullptr, 0);
183         if (oat_fd_ < 0) {
184           Usage("Invalid --oat-fd %d", oat_fd_);
185         }
186       } else if (option.starts_with("--vdex-fd")) {
187         vdex_fd_ = std::stoi(option.substr(strlen("--vdex-fd=")).ToString(), nullptr, 0);
188         if (vdex_fd_ < 0) {
189           Usage("Invalid --vdex-fd %d", vdex_fd_);
190         }
191       } else if (option.starts_with("--zip-fd")) {
192           zip_fd_ = std::stoi(option.substr(strlen("--zip-fd=")).ToString(), nullptr, 0);
193           if (zip_fd_ < 0) {
194             Usage("Invalid --zip-fd %d", zip_fd_);
195           }
196       } else if (option.starts_with("--class-loader-context=")) {
197         std::string context_str = option.substr(strlen("--class-loader-context=")).ToString();
198         class_loader_context_ = ClassLoaderContext::Create(context_str);
199         if (class_loader_context_ == nullptr) {
200           Usage("Invalid --class-loader-context '%s'", context_str.c_str());
201         }
202       } else {
203         Usage("Unknown argument '%s'", option.data());
204       }
205     }
206 
207     if (image_.empty()) {
208       // If we don't receive the image, try to use the default one.
209       // Tests may specify a different image (e.g. core image).
210       std::string error_msg;
211       image_ = GetDefaultBootImageLocation(&error_msg);
212 
213       if (image_.empty()) {
214         LOG(ERROR) << error_msg;
215         Usage("--image unspecified and ANDROID_ROOT not set or image file does not exist.");
216       }
217     }
218   }
219 
CreateRuntime()220   bool CreateRuntime() {
221     RuntimeOptions options;
222     // The image could be custom, so make sure we explicitly pass it.
223     std::string img = "-Ximage:" + image_;
224     options.push_back(std::make_pair(img.c_str(), nullptr));
225     // The instruction set of the image should match the instruction set we will test.
226     const void* isa_opt = reinterpret_cast<const void*>(GetInstructionSetString(isa_));
227     options.push_back(std::make_pair("imageinstructionset", isa_opt));
228      // Disable libsigchain. We don't don't need it to evaluate DexOptNeeded status.
229     options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
230     // Pretend we are a compiler so that we can re-use the same infrastructure to load a different
231     // ISA image and minimize the amount of things that get started.
232     NoopCompilerCallbacks callbacks;
233     options.push_back(std::make_pair("compilercallbacks", &callbacks));
234     // Make sure we don't attempt to relocate. The tool should only retrieve the DexOptNeeded
235     // status and not attempt to relocate the boot image.
236     options.push_back(std::make_pair("-Xnorelocate", nullptr));
237 
238     if (!Runtime::Create(options, false)) {
239       LOG(ERROR) << "Unable to initialize runtime";
240       return false;
241     }
242     // Runtime::Create acquired the mutator_lock_ that is normally given away when we
243     // Runtime::Start. Give it away now.
244     Thread::Current()->TransitionFromRunnableToSuspended(kNative);
245 
246     return true;
247   }
248 
GetDexOptNeeded()249   int GetDexOptNeeded() {
250     if (!CreateRuntime()) {
251       return kErrorCannotCreateRuntime;
252     }
253     std::unique_ptr<Runtime> runtime(Runtime::Current());
254 
255     std::unique_ptr<OatFileAssistant> oat_file_assistant;
256     oat_file_assistant = std::make_unique<OatFileAssistant>(dex_file_.c_str(),
257                                                             isa_,
258                                                             false /*load_executable*/,
259                                                             false /*only_load_system_executable*/,
260                                                             vdex_fd_,
261                                                             oat_fd_,
262                                                             zip_fd_);
263     // Always treat elements of the bootclasspath as up-to-date.
264     // TODO(calin): this check should be in OatFileAssistant.
265     if (oat_file_assistant->IsInBootClassPath()) {
266       return kNoDexOptNeeded;
267     }
268 
269     int dexoptNeeded = oat_file_assistant->GetDexOptNeeded(
270         compiler_filter_, assume_profile_changed_, downgrade_, class_loader_context_.get());
271 
272     // Convert OatFileAssitant codes to dexoptanalyzer codes.
273     switch (dexoptNeeded) {
274       case OatFileAssistant::kNoDexOptNeeded: return kNoDexOptNeeded;
275       case OatFileAssistant::kDex2OatFromScratch: return kDex2OatFromScratch;
276       case OatFileAssistant::kDex2OatForBootImage: return kDex2OatForBootImageOat;
277       case OatFileAssistant::kDex2OatForFilter: return kDex2OatForFilterOat;
278       case OatFileAssistant::kDex2OatForRelocation: return kDex2OatForRelocationOat;
279 
280       case -OatFileAssistant::kDex2OatForBootImage: return kDex2OatForBootImageOdex;
281       case -OatFileAssistant::kDex2OatForFilter: return kDex2OatForFilterOdex;
282       case -OatFileAssistant::kDex2OatForRelocation: return kDex2OatForRelocationOdex;
283       default:
284         LOG(ERROR) << "Unknown dexoptNeeded " << dexoptNeeded;
285         return kErrorUnknownDexOptNeeded;
286     }
287   }
288 
289  private:
290   std::string dex_file_;
291   InstructionSet isa_;
292   CompilerFilter::Filter compiler_filter_;
293   std::unique_ptr<ClassLoaderContext> class_loader_context_;
294   bool assume_profile_changed_;
295   bool downgrade_;
296   std::string image_;
297   int oat_fd_ = -1;
298   int vdex_fd_ = -1;
299   // File descriptor corresponding to apk, dex_file, or zip.
300   int zip_fd_ = -1;
301 };
302 
dexoptAnalyze(int argc,char ** argv)303 static int dexoptAnalyze(int argc, char** argv) {
304   DexoptAnalyzer analyzer;
305 
306   // Parse arguments. Argument mistakes will lead to exit(kErrorInvalidArguments) in UsageError.
307   analyzer.ParseArgs(argc, argv);
308   return analyzer.GetDexOptNeeded();
309 }
310 
311 }  // namespace art
312 
main(int argc,char ** argv)313 int main(int argc, char **argv) {
314   return art::dexoptAnalyze(argc, argv);
315 }
316