blob: 80e77245fc1400cbfca10967c2e95230d80aed24 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 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 <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
Ian Rogers2672a9f2013-09-05 17:24:22 -070020#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
Vladimir Markof94b7812014-06-05 15:48:04 +010028#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "base/stl_util.h"
34#include "base/stringpiece.h"
35#include "base/timing_logger.h"
36#include "base/unix_file/fd_file.h"
37#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000038#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000039#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070041#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000042#include "dex/verification_results.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080043#include "driver/compiler_callbacks_impl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080045#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "elf_fixup.h"
47#include "elf_stripper.h"
48#include "gc/space/image_space.h"
49#include "gc/space/space-inl.h"
50#include "image_writer.h"
51#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070052#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
55#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
57#include "oat_writer.h"
58#include "object_utils.h"
59#include "os.h"
60#include "runtime.h"
61#include "ScopedLocalRef.h"
62#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070063#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "vector_output_stream.h"
65#include "well_known_classes.h"
66#include "zip_archive.h"
67
68namespace art {
69
Brian Carlstrom6449c622014-02-10 23:48:36 -080070static int original_argc;
71static char** original_argv;
72
73static std::string CommandLine() {
74 std::vector<std::string> command;
75 for (int i = 0; i < original_argc; ++i) {
76 command.push_back(original_argv[i]);
77 }
78 return Join(command, ' ');
79}
80
Brian Carlstrom7940e442013-07-12 13:46:57 -070081static void UsageErrorV(const char* fmt, va_list ap) {
82 std::string error;
83 StringAppendV(&error, fmt, ap);
84 LOG(ERROR) << error;
85}
86
87static void UsageError(const char* fmt, ...) {
88 va_list ap;
89 va_start(ap, fmt);
90 UsageErrorV(fmt, ap);
91 va_end(ap);
92}
93
94static void Usage(const char* fmt, ...) {
95 va_list ap;
96 va_start(ap, fmt);
97 UsageErrorV(fmt, ap);
98 va_end(ap);
99
Brian Carlstrom6449c622014-02-10 23:48:36 -0800100 UsageError("Command: %s", CommandLine().c_str());
101
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102 UsageError("Usage: dex2oat [options]...");
103 UsageError("");
104 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
105 UsageError(" Example: --dex-file=/system/framework/core.jar");
106 UsageError("");
107 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
108 UsageError(" containing a classes.dex file to compile.");
109 UsageError(" Example: --zip-fd=5");
110 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700111 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
112 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700113 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
114 UsageError("");
115 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
116 UsageError(" Example: --oat-file=/system/framework/boot.oat");
117 UsageError("");
118 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900119 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700120 UsageError("");
121 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
122 UsageError(" to the file descriptor specified by --oat-fd.");
123 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
124 UsageError("");
125 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
126 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
127 UsageError("");
128 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
129 UsageError(" Example: --bitcode=/system/framework/boot.bc");
130 UsageError("");
131 UsageError(" --image=<file.art>: specifies the output image filename.");
132 UsageError(" Example: --image=/system/framework/boot.art");
133 UsageError("");
134 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
135 UsageError(" Example: --image=frameworks/base/preloaded-classes");
136 UsageError("");
137 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
138 UsageError(" Example: --base=0x50000000");
139 UsageError("");
140 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
141 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000142 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700143 UsageError("");
144 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
145 UsageError(" Example: --android-root=out/host/linux-x86");
146 UsageError(" Default: $ANDROID_ROOT");
147 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700148 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
149 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700150 UsageError(" Example: --instruction-set=x86");
151 UsageError(" Default: arm");
152 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700153 UsageError(" --instruction-set-features=...,: Specify instruction set features");
154 UsageError(" Example: --instruction-set-features=div");
155 UsageError(" Default: default");
156 UsageError("");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000157 UsageError(" --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700158 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700159 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160 UsageError(" Default: Quick");
161 UsageError("");
Jeff Hao4a200f52014-04-01 14:58:49 -0700162 UsageError(" --compiler-filter=(verify-none|interpret-only|space|balanced|speed|everything):");
163 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800164 UsageError(" Example: --compiler-filter=everything");
165#if ART_SMALL_MODE
166 UsageError(" Default: interpret-only");
167#else
168 UsageError(" Default: speed");
169#endif
170 UsageError("");
171 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
172 UsageError(" method for compiler filter tuning.");
173 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
174 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
175 UsageError("");
176 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
177 UsageError(" method for compiler filter tuning.");
178 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
179 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
180 UsageError("");
181 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
182 UsageError(" method for compiler filter tuning.");
183 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
184 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
185 UsageError("");
186 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
187 UsageError(" method for compiler filter tuning.");
188 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
189 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
190 UsageError("");
191 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
192 UsageError(" method for compiler filter tuning.");
193 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
194 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
195 UsageError("");
196 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
197 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700198 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
199 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800200 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
201 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
202 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError(" --host: used with Portable backend to link against host runtime libraries");
204 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700205 UsageError(" --dump-timing: display a breakdown of where time was spent");
206 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700207 UsageError(" --include-patch-information: Include patching information so the generated code");
208 UsageError(" can have its base address moved without full recompilation.");
209 UsageError("");
210 UsageError(" --no-include-patch-information: Do not include patching information.");
211 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700212 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
213 UsageError("");
214 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
215 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
217 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
218 UsageError(" Use a separate --runtime-arg switch for each argument.");
219 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700220 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000221 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700222 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700223 UsageError(" --print-pass-names: print a list of pass names");
224 UsageError("");
225 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
226 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
227 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 std::cerr << "See log for usage error information\n";
229 exit(EXIT_FAILURE);
230}
231
232class Dex2Oat {
233 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700234 static bool Create(Dex2Oat** p_dex2oat,
Brian Carlstrom6449c622014-02-10 23:48:36 -0800235 const Runtime::Options& runtime_options,
236 const CompilerOptions& compiler_options,
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000237 Compiler::Kind compiler_kind,
Brian Carlstrom45602482013-07-21 22:07:55 -0700238 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700239 InstructionSetFeatures instruction_set_features,
Brian Carlstrom6449c622014-02-10 23:48:36 -0800240 VerificationResults* verification_results,
241 DexFileToMethodInlinerMap* method_inliner_map,
Brian Carlstrom45602482013-07-21 22:07:55 -0700242 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800244 CHECK(verification_results != nullptr);
245 CHECK(method_inliner_map != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700246 std::unique_ptr<Dex2Oat> dex2oat(new Dex2Oat(&compiler_options,
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000247 compiler_kind,
Brian Carlstrom6449c622014-02-10 23:48:36 -0800248 instruction_set,
249 instruction_set_features,
250 verification_results,
251 method_inliner_map,
252 thread_count));
253 if (!dex2oat->CreateRuntime(runtime_options, instruction_set)) {
Kenny Root51316382014-05-13 14:59:37 -0700254 *p_dex2oat = nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 return false;
256 }
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000257 *p_dex2oat = dex2oat.release();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700258 return true;
259 }
260
261 ~Dex2Oat() {
262 delete runtime_;
Brian Carlstrom65c23bb2014-02-01 22:12:39 -0800263 LogCompletionTime();
264 }
265
266 void LogCompletionTime() {
267 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700268 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700269 }
270
271
Brian Carlstrom45602482013-07-21 22:07:55 -0700272 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700273 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Ian Rogers700a4022014-05-19 16:49:03 -0700274 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
Brian Carlstrom45602482013-07-21 22:07:55 -0700275 std::ifstream::in));
Kenny Root51316382014-05-13 14:59:37 -0700276 if (image_classes_file.get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
Kenny Root51316382014-05-13 14:59:37 -0700278 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 }
Alex Light53cb16b2014-06-12 11:26:29 -0700280 std::unique_ptr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700281 image_classes_file->close();
282 return result.release();
283 }
284
285 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
Ian Rogers700a4022014-05-19 16:49:03 -0700286 std::unique_ptr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700287 while (image_classes_stream.good()) {
288 std::string dot;
289 std::getline(image_classes_stream, dot);
290 if (StartsWith(dot, "#") || dot.empty()) {
291 continue;
292 }
293 std::string descriptor(DotToDescriptor(dot.c_str()));
294 image_classes->insert(descriptor);
295 }
296 return image_classes.release();
297 }
298
Brian Carlstrom45602482013-07-21 22:07:55 -0700299 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700300 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const char* zip_filename,
301 const char* image_classes_filename,
302 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700303 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
Kenny Root51316382014-05-13 14:59:37 -0700304 if (zip_archive.get() == nullptr) {
305 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700306 }
Ian Rogers700a4022014-05-19 16:49:03 -0700307 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
Kenny Root51316382014-05-13 14:59:37 -0700308 if (zip_entry.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700309 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
310 zip_filename, error_msg->c_str());
Kenny Root51316382014-05-13 14:59:37 -0700311 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700312 }
Brian Carlstrom0aa504b2014-05-23 02:47:28 -0700313 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
314 image_classes_filename,
315 error_msg));
Kenny Root51316382014-05-13 14:59:37 -0700316 if (image_classes_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700317 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
318 zip_filename, error_msg->c_str());
Kenny Root51316382014-05-13 14:59:37 -0700319 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700320 }
321 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
322 image_classes_file->Size());
323 std::istringstream image_classes_stream(image_classes_string);
324 return ReadImageClasses(image_classes_stream);
325 }
326
327 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328 const std::string& android_root,
329 bool is_host,
330 const std::vector<const DexFile*>& dex_files,
331 File* oat_file,
332 const std::string& bitcode_filename,
333 bool image,
Ian Rogers700a4022014-05-19 16:49:03 -0700334 std::unique_ptr<CompilerDriver::DescriptorSet>& image_classes,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 bool dump_stats,
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000336 bool dump_passes,
337 TimingLogger& timings,
Dave Allison39c3bfb2014-01-28 18:33:52 -0800338 CumulativeLogger& compiler_phases_timings,
Nicolas Geoffray452bee52014-07-09 07:58:10 +0000339 std::string profile_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700340 // Handle and ClassLoader creation needs to come after Runtime::Create
Kenny Root51316382014-05-13 14:59:37 -0700341 jobject class_loader = nullptr;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700342 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 if (!boot_image_option.empty()) {
344 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
345 std::vector<const DexFile*> class_path_files(dex_files);
346 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700347 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348 for (size_t i = 0; i < class_path_files.size(); i++) {
349 class_linker->RegisterDexFile(*class_path_files[i]);
350 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700351 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
352 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
353 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
354 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
355 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
356 }
357
Ian Rogers700a4022014-05-19 16:49:03 -0700358 std::unique_ptr<CompilerDriver> driver(new CompilerDriver(compiler_options_,
Nicolas Geoffray452bee52014-07-09 07:58:10 +0000359 verification_results_,
360 method_inliner_map_,
361 compiler_kind_,
362 instruction_set_,
363 instruction_set_features_,
364 image,
365 image_classes.release(),
366 thread_count_,
367 dump_stats,
368 dump_passes,
369 &compiler_phases_timings,
370 profile_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000372 driver->GetCompiler()->SetBitcodeFileName(*driver.get(), bitcode_filename);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373
Ian Rogers3d504072014-03-01 09:16:49 -0800374 driver->CompileAll(class_loader, dex_files, &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700375
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700376 TimingLogger::ScopedTiming t2("dex2oat OatWriter", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377 std::string image_file_location;
378 uint32_t image_file_location_oat_checksum = 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800379 uintptr_t image_file_location_oat_data_begin = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380 if (!driver->IsImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700381 TimingLogger::ScopedTiming t3("Loading image checksum", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
383 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
384 image_file_location_oat_data_begin =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800385 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386 image_file_location = image_space->GetImageFilename();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 }
388
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700389 OatWriter oat_writer(dex_files, image_file_location_oat_checksum,
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700390 image_file_location_oat_data_begin,
Nicolas Geoffray452bee52014-07-09 07:58:10 +0000391 image_file_location,
Ian Rogersca368cb2013-11-15 15:52:08 -0800392 driver.get(),
Nicolas Geoffray452bee52014-07-09 07:58:10 +0000393 &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700394
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700395 t2.NewTiming("Writing ELF");
Ian Rogers3d504072014-03-01 09:16:49 -0800396 if (!driver->WriteElf(android_root, is_host, dex_files, &oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
Kenny Root51316382014-05-13 14:59:37 -0700398 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 }
400
401 return driver.release();
402 }
403
404 bool CreateImageFile(const std::string& image_filename,
405 uintptr_t image_base,
406 const std::string& oat_filename,
407 const std::string& oat_location,
408 const CompilerDriver& compiler)
409 LOCKS_EXCLUDED(Locks::mutator_lock_) {
410 uintptr_t oat_data_begin;
411 {
412 // ImageWriter is scoped so it can free memory before doing FixupElf
413 ImageWriter image_writer(compiler);
414 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
415 LOG(ERROR) << "Failed to create image file " << image_filename;
416 return false;
417 }
418 oat_data_begin = image_writer.GetOatDataBegin();
419 }
420
Ian Rogers700a4022014-05-19 16:49:03 -0700421 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Kenny Root51316382014-05-13 14:59:37 -0700422 if (oat_file.get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700423 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
424 return false;
425 }
426 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
427 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
428 return false;
429 }
430 return true;
431 }
432
433 private:
Brian Carlstrom6449c622014-02-10 23:48:36 -0800434 explicit Dex2Oat(const CompilerOptions* compiler_options,
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000435 Compiler::Kind compiler_kind,
Brian Carlstrom45602482013-07-21 22:07:55 -0700436 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700437 InstructionSetFeatures instruction_set_features,
Brian Carlstrom6449c622014-02-10 23:48:36 -0800438 VerificationResults* verification_results,
439 DexFileToMethodInlinerMap* method_inliner_map,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700440 size_t thread_count)
Brian Carlstrom6449c622014-02-10 23:48:36 -0800441 : compiler_options_(compiler_options),
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000442 compiler_kind_(compiler_kind),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700444 instruction_set_features_(instruction_set_features),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800445 verification_results_(verification_results),
446 method_inliner_map_(method_inliner_map),
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000447 runtime_(nullptr),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700448 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700449 start_ns_(NanoTime()) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800450 CHECK(compiler_options != nullptr);
451 CHECK(verification_results != nullptr);
452 CHECK(method_inliner_map != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700453 }
454
Brian Carlstrom6449c622014-02-10 23:48:36 -0800455 bool CreateRuntime(const Runtime::Options& runtime_options, InstructionSet instruction_set)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700456 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800457 if (!Runtime::Create(runtime_options, false)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 LOG(ERROR) << "Failed to create runtime";
459 return false;
460 }
461 Runtime* runtime = Runtime::Current();
Vladimir Marko7624d252014-05-02 14:40:15 +0100462 runtime->SetInstructionSet(instruction_set);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
464 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
465 if (!runtime->HasCalleeSaveMethod(type)) {
Vladimir Marko7624d252014-05-02 14:40:15 +0100466 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(type), type);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700467 }
468 }
469 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000470 runtime_ = runtime;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700471 return true;
472 }
473
474 // Appends to dex_files any elements of class_path that it doesn't already
475 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700476 static void OpenClassPathFiles(const std::string& class_path,
477 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700478 std::vector<std::string> parsed;
479 Split(class_path, ':', parsed);
480 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
481 ScopedObjectAccess soa(Thread::Current());
482 for (size_t i = 0; i < parsed.size(); ++i) {
483 if (DexFilesContains(dex_files, parsed[i])) {
484 continue;
485 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700486 std::string error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700487 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700488 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700489 }
490 }
491 }
492
493 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700494 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
495 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700496 for (size_t i = 0; i < dex_files.size(); ++i) {
497 if (dex_files[i]->GetLocation() == location) {
498 return true;
499 }
500 }
501 return false;
502 }
503
Brian Carlstromae7083d2014-02-24 21:56:02 -0800504 const CompilerOptions* const compiler_options_;
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000505 const Compiler::Kind compiler_kind_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700506
507 const InstructionSet instruction_set_;
Dave Allison70202782013-10-22 17:52:19 -0700508 const InstructionSetFeatures instruction_set_features_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700509
Brian Carlstromae7083d2014-02-24 21:56:02 -0800510 VerificationResults* const verification_results_;
511 DexFileToMethodInlinerMap* const method_inliner_map_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700512 Runtime* runtime_;
513 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700514 uint64_t start_ns_;
515
516 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
517};
518
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800519static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
520 const std::vector<const char*>& dex_locations,
521 std::vector<const DexFile*>& dex_files) {
522 size_t failure_count = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700523 for (size_t i = 0; i < dex_filenames.size(); i++) {
524 const char* dex_filename = dex_filenames[i];
525 const char* dex_location = dex_locations[i];
Ian Rogers740a11d2014-01-14 10:11:25 -0800526 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700527 std::string error_msg;
Brian Carlstromd5aba592013-11-12 01:52:44 -0800528 if (!OS::FileExists(dex_filename)) {
529 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
530 continue;
531 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700532 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700533 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800534 ++failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535 }
Ian Rogers740a11d2014-01-14 10:11:25 -0800536 ATRACE_END();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700537 }
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800538 return failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539}
540
541// The primary goal of the watchdog is to prevent stuck build servers
542// during development when fatal aborts lead to a cascade of failures
543// that result in a deadlock.
544class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
546#undef CHECK_PTHREAD_CALL
547#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
548 do { \
549 int rc = call args; \
550 if (rc != 0) { \
551 errno = rc; \
552 std::string message(# call); \
553 message += " failed for "; \
554 message += reason; \
555 Fatal(message); \
556 } \
557 } while (false)
558
559 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700560 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700561 is_watch_dog_enabled_ = is_watch_dog_enabled;
562 if (!is_watch_dog_enabled_) {
563 return;
564 }
565 shutting_down_ = false;
566 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700567 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
568 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700569 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
570 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
571 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
572 }
573 ~WatchDog() {
574 if (!is_watch_dog_enabled_) {
575 return;
576 }
577 const char* reason = "dex2oat watch dog thread shutdown";
578 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
579 shutting_down_ = true;
580 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
581 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
582
Kenny Root51316382014-05-13 14:59:37 -0700583 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700584
585 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
586 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
587 }
588
589 private:
590 static void* CallBack(void* arg) {
591 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
592 ::art::SetThreadName("dex2oat watch dog");
593 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700594 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595 }
596
597 static void Message(char severity, const std::string& message) {
598 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
599 // cases.
600 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
601 kIsDebugBuild ? "d" : "",
602 severity,
603 getpid(),
604 GetTid(),
605 message.c_str());
606 }
607
608 static void Warn(const std::string& message) {
609 Message('W', message);
610 }
611
612 static void Fatal(const std::string& message) {
613 Message('F', message);
614 exit(1);
615 }
616
617 void Wait() {
618 bool warning = true;
619 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
620 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
621 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800622 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700623 timespec warning_ts;
624 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
625 timespec timeout_ts;
626 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
627 const char* reason = "dex2oat watch dog thread waiting";
628 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
629 while (!shutting_down_) {
630 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
631 warning ? &warning_ts
632 : &timeout_ts));
633 if (rc == ETIMEDOUT) {
634 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
635 warning ? kWatchDogWarningSeconds
636 : kWatchDogTimeoutSeconds));
637 if (warning) {
638 Warn(message.c_str());
639 warning = false;
640 } else {
641 Fatal(message.c_str());
642 }
643 } else if (rc != 0) {
644 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
645 strerror(errno)));
646 Fatal(message.c_str());
647 }
648 }
649 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
650 }
651
652 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
653#if ART_USE_PORTABLE_COMPILER
654 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
655 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
656#else
657 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
658 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
659#endif
660
661 bool is_watch_dog_enabled_;
662 bool shutting_down_;
663 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
664 pthread_mutex_t mutex_;
665 pthread_cond_t cond_;
666 pthread_attr_t attr_;
667 pthread_t pthread_;
668};
669const unsigned int WatchDog::kWatchDogWarningSeconds;
670const unsigned int WatchDog::kWatchDogTimeoutSeconds;
671
Dave Allison70202782013-10-22 17:52:19 -0700672// Given a set of instruction features from the build, parse it. The
673// input 'str' is a comma separated list of feature names. Parse it and
674// return the InstructionSetFeatures object.
675static InstructionSetFeatures ParseFeatureList(std::string str) {
676 InstructionSetFeatures result;
677 typedef std::vector<std::string> FeatureList;
678 FeatureList features;
679 Split(str, ',', features);
680 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
681 std::string feature = Trim(*i);
682 if (feature == "default") {
683 // Nothing to do.
684 } else if (feature == "div") {
685 // Supports divide instruction.
686 result.SetHasDivideInstruction(true);
687 } else if (feature == "nodiv") {
688 // Turn off support for divide instruction.
689 result.SetHasDivideInstruction(false);
Vladimir Marko674744e2014-04-24 15:18:26 +0100690 } else if (feature == "lpae") {
691 // Supports Large Physical Address Extension.
692 result.SetHasLpae(true);
693 } else if (feature == "nolpae") {
694 // Turn off support for Large Physical Address Extension.
695 result.SetHasLpae(false);
Dave Allison70202782013-10-22 17:52:19 -0700696 } else {
697 Usage("Unknown instruction set feature: '%s'", feature.c_str());
698 }
699 }
700 // others...
701 return result;
702}
703
Calin Juravlec1b643c2014-05-30 23:44:11 +0100704void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
705 std::string::size_type colon = s.find(c);
706 if (colon == std::string::npos) {
707 Usage("Missing char %c in option %s\n", c, s.c_str());
708 }
709 // Add one to remove the char we were trimming until.
710 *parsed_value = s.substr(colon + 1);
711}
712
713void ParseDouble(const std::string& option, char after_char,
714 double min, double max, double* parsed_value) {
715 std::string substring;
716 ParseStringAfterChar(option, after_char, &substring);
717 bool sane_val = true;
718 double value;
719 if (false) {
720 // TODO: this doesn't seem to work on the emulator. b/15114595
721 std::stringstream iss(substring);
722 iss >> value;
723 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
724 sane_val = iss.eof() && (value >= min) && (value <= max);
725 } else {
726 char* end = nullptr;
727 value = strtod(substring.c_str(), &end);
728 sane_val = *end == '\0' && value >= min && value <= max;
729 }
730 if (!sane_val) {
731 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
732 }
733 *parsed_value = value;
734}
735
Andreas Gampe5655e842014-06-17 16:36:07 -0700736void CheckExplicitCheckOptions(InstructionSet isa, bool* explicit_null_checks,
737 bool* explicit_so_checks, bool* explicit_suspend_checks) {
738 switch (isa) {
739 case kArm:
Dave Allisonca3aaba2014-06-23 14:46:53 -0700740 case kThumb2:
Andreas Gampe5655e842014-06-17 16:36:07 -0700741 break; // All checks implemented, leave as is.
742
743 default: // No checks implemented, reset all to explicit checks.
744 *explicit_null_checks = true;
745 *explicit_so_checks = true;
746 *explicit_suspend_checks = true;
747 }
748}
749
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750static int dex2oat(int argc, char** argv) {
Vladimir Markof94b7812014-06-05 15:48:04 +0100751#if defined(__linux__) && defined(__arm__)
752 int major, minor;
753 struct utsname uts;
754 if (uname(&uts) != -1 &&
755 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
756 ((major < 3) || ((major == 3) && (minor < 4)))) {
757 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
758 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
759 int old_personality = personality(0xffffffff);
760 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
761 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
762 if (new_personality == -1) {
763 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
764 }
765 }
766 }
767#endif
768
Brian Carlstrom6449c622014-02-10 23:48:36 -0800769 original_argc = argc;
770 original_argv = argv;
771
Ian Rogers5fe9af72013-11-14 00:17:20 -0800772 TimingLogger timings("compiler", false, false);
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000773 CumulativeLogger compiler_phases_timings("compilation times");
Brian Carlstrom45602482013-07-21 22:07:55 -0700774
Brian Carlstrom7940e442013-07-12 13:46:57 -0700775 InitLogging(argv);
776
777 // Skip over argv[0].
778 argv++;
779 argc--;
780
781 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700782 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783 }
784
785 std::vector<const char*> dex_filenames;
786 std::vector<const char*> dex_locations;
787 int zip_fd = -1;
788 std::string zip_location;
789 std::string oat_filename;
790 std::string oat_symbols;
791 std::string oat_location;
792 int oat_fd = -1;
793 std::string bitcode_filename;
Kenny Root51316382014-05-13 14:59:37 -0700794 const char* image_classes_zip_filename = nullptr;
795 const char* image_classes_filename = nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700796 std::string image_filename;
797 std::string boot_image_filename;
798 uintptr_t image_base = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700799 std::string android_root;
800 std::vector<const char*> runtime_args;
801 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000802 Compiler::Kind compiler_kind = kUsePortableCompiler
803 ? Compiler::kPortable
804 : Compiler::kQuick;
Kenny Root51316382014-05-13 14:59:37 -0700805 const char* compiler_filter_string = nullptr;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800806 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
807 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
808 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
809 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
810 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
Dave Allison70202782013-10-22 17:52:19 -0700811
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800812 // Take the default set of instruction features from the build.
Dave Allison70202782013-10-22 17:52:19 -0700813 InstructionSetFeatures instruction_set_features =
Ian Rogers8afeb852014-04-02 14:55:49 -0700814 ParseFeatureList(Runtime::GetDefaultInstructionSetFeatures());
Dave Allison70202782013-10-22 17:52:19 -0700815
Andreas Gampe91268c12014-04-03 17:50:24 -0700816 InstructionSet instruction_set = kRuntimeISA;
Dave Allison70202782013-10-22 17:52:19 -0700817
Dave Allison39c3bfb2014-01-28 18:33:52 -0800818 // Profile file to use
819 std::string profile_file;
Calin Juravlec1b643c2014-05-30 23:44:11 +0100820 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
Dave Allison70202782013-10-22 17:52:19 -0700821
Brian Carlstrom7940e442013-07-12 13:46:57 -0700822 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700823 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700824 bool dump_timing = false;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000825 bool dump_passes = false;
Alex Light53cb16b2014-06-12 11:26:29 -0700826 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
827 bool explicit_include_patch_information = false;
Alex Light78382fa2014-06-06 15:45:32 -0700828 bool include_debug_symbols = kIsDebugBuild;
Ian Rogers46398602013-08-20 07:50:36 -0700829 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700830 bool watch_dog_enabled = !kIsTargetBuild;
Mark Mendellae9fd932014-02-10 16:14:35 -0800831 bool generate_gdb_information = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700832
Andreas Gampe5655e842014-06-17 16:36:07 -0700833 bool explicit_null_checks = true;
834 bool explicit_so_checks = true;
835 bool explicit_suspend_checks = true;
836 bool has_explicit_checks_options = false;
837
Brian Carlstrom7940e442013-07-12 13:46:57 -0700838 for (int i = 0; i < argc; i++) {
839 const StringPiece option(argv[i]);
Ian Rogersb9beb2e2014-05-09 16:57:40 -0700840 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700841 if (log_options) {
842 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
843 }
844 if (option.starts_with("--dex-file=")) {
845 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
846 } else if (option.starts_with("--dex-location=")) {
847 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
848 } else if (option.starts_with("--zip-fd=")) {
849 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
850 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700851 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700852 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800853 if (zip_fd < 0) {
854 Usage("--zip-fd passed a negative value %d", zip_fd);
855 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700856 } else if (option.starts_with("--zip-location=")) {
857 zip_location = option.substr(strlen("--zip-location=")).data();
858 } else if (option.starts_with("--oat-file=")) {
859 oat_filename = option.substr(strlen("--oat-file=")).data();
860 } else if (option.starts_with("--oat-symbols=")) {
861 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
862 } else if (option.starts_with("--oat-fd=")) {
863 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
864 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700865 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700866 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800867 if (oat_fd < 0) {
868 Usage("--oat-fd passed a negative value %d", oat_fd);
869 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700870 } else if (option == "--watch-dog") {
871 watch_dog_enabled = true;
872 } else if (option == "--no-watch-dog") {
873 watch_dog_enabled = false;
Mark Mendellae9fd932014-02-10 16:14:35 -0800874 } else if (option == "--gen-gdb-info") {
875 generate_gdb_information = true;
Alex Light3470ab42014-06-18 10:35:45 -0700876 // Debug symbols are needed for gdb information.
877 include_debug_symbols = true;
Mark Mendellae9fd932014-02-10 16:14:35 -0800878 } else if (option == "--no-gen-gdb-info") {
879 generate_gdb_information = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880 } else if (option.starts_with("-j")) {
881 const char* thread_count_str = option.substr(strlen("-j")).data();
882 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700883 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700884 }
885 } else if (option.starts_with("--oat-location=")) {
886 oat_location = option.substr(strlen("--oat-location=")).data();
887 } else if (option.starts_with("--bitcode=")) {
888 bitcode_filename = option.substr(strlen("--bitcode=")).data();
889 } else if (option.starts_with("--image=")) {
890 image_filename = option.substr(strlen("--image=")).data();
891 } else if (option.starts_with("--image-classes=")) {
892 image_classes_filename = option.substr(strlen("--image-classes=")).data();
893 } else if (option.starts_with("--image-classes-zip=")) {
894 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
895 } else if (option.starts_with("--base=")) {
896 const char* image_base_str = option.substr(strlen("--base=")).data();
897 char* end;
898 image_base = strtoul(image_base_str, &end, 16);
899 if (end == image_base_str || *end != '\0') {
900 Usage("Failed to parse hexadecimal value for option %s", option.data());
901 }
902 } else if (option.starts_with("--boot-image=")) {
903 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700904 } else if (option.starts_with("--android-root=")) {
905 android_root = option.substr(strlen("--android-root=")).data();
906 } else if (option.starts_with("--instruction-set=")) {
907 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
908 if (instruction_set_str == "arm") {
909 instruction_set = kThumb2;
Stuart Monteithb95a5342014-03-12 13:32:32 +0000910 } else if (instruction_set_str == "arm64") {
911 instruction_set = kArm64;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700912 } else if (instruction_set_str == "mips") {
913 instruction_set = kMips;
914 } else if (instruction_set_str == "x86") {
915 instruction_set = kX86;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800916 } else if (instruction_set_str == "x86_64") {
917 instruction_set = kX86_64;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918 }
Dave Allison70202782013-10-22 17:52:19 -0700919 } else if (option.starts_with("--instruction-set-features=")) {
920 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
921 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700922 } else if (option.starts_with("--compiler-backend=")) {
923 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
924 if (backend_str == "Quick") {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000925 compiler_kind = Compiler::kQuick;
926 } else if (backend_str == "Optimizing") {
927 compiler_kind = Compiler::kOptimizing;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 } else if (backend_str == "Portable") {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000929 compiler_kind = Compiler::kPortable;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700930 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800931 } else if (option.starts_with("--compiler-filter=")) {
932 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
933 } else if (option.starts_with("--huge-method-max=")) {
934 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
935 if (!ParseInt(threshold, &huge_method_threshold)) {
936 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
937 }
938 if (huge_method_threshold < 0) {
939 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
940 }
941 } else if (option.starts_with("--large-method-max=")) {
942 const char* threshold = option.substr(strlen("--large-method-max=")).data();
943 if (!ParseInt(threshold, &large_method_threshold)) {
944 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
945 }
946 if (large_method_threshold < 0) {
947 Usage("--large-method-max passed a negative value %s", large_method_threshold);
948 }
949 } else if (option.starts_with("--small-method-max=")) {
950 const char* threshold = option.substr(strlen("--small-method-max=")).data();
951 if (!ParseInt(threshold, &small_method_threshold)) {
952 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
953 }
954 if (small_method_threshold < 0) {
955 Usage("--small-method-max passed a negative value %s", small_method_threshold);
956 }
957 } else if (option.starts_with("--tiny-method-max=")) {
958 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
959 if (!ParseInt(threshold, &tiny_method_threshold)) {
960 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
961 }
962 if (tiny_method_threshold < 0) {
963 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
964 }
965 } else if (option.starts_with("--num-dex-methods=")) {
966 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
967 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
968 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
969 }
970 if (num_dex_methods_threshold < 0) {
971 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
972 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 } else if (option == "--host") {
974 is_host = true;
975 } else if (option == "--runtime-arg") {
976 if (++i >= argc) {
977 Usage("Missing required argument for --runtime-arg");
978 }
979 if (log_options) {
980 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
981 }
982 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700983 } else if (option == "--dump-timing") {
984 dump_timing = true;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000985 } else if (option == "--dump-passes") {
986 dump_passes = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700987 } else if (option == "--dump-stats") {
988 dump_stats = true;
Alex Light78382fa2014-06-06 15:45:32 -0700989 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
990 include_debug_symbols = true;
991 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
992 include_debug_symbols = false;
Dave Allison39c3bfb2014-01-28 18:33:52 -0800993 } else if (option.starts_with("--profile-file=")) {
994 profile_file = option.substr(strlen("--profile-file=")).data();
995 VLOG(compiler) << "dex2oat: profile file is " << profile_file;
996 } else if (option == "--no-profile-file") {
Dave Allison39c3bfb2014-01-28 18:33:52 -0800997 // No profile
Calin Juravlec1b643c2014-05-30 23:44:11 +0100998 } else if (option.starts_with("--top-k-profile-threshold=")) {
Calin Juravle44c5ee72014-07-02 14:00:33 +0100999 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
Chao-ying Fucd8ce662014-03-11 14:57:19 -07001000 } else if (option == "--print-pass-names") {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001001 PassDriverMEOpts::PrintPassNames();
Chao-ying Fucd8ce662014-03-11 14:57:19 -07001002 } else if (option.starts_with("--disable-passes=")) {
1003 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001004 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
Jean Christophe Beyler8bcecce2014-04-29 13:42:08 -07001005 } else if (option.starts_with("--print-passes=")) {
1006 std::string print_passes = option.substr(strlen("--print-passes=")).data();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001007 PassDriverMEOpts::SetPrintPassList(print_passes);
Jean Christophe Beyler8bcecce2014-04-29 13:42:08 -07001008 } else if (option == "--print-all-passes") {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001009 PassDriverMEOpts::SetPrintAllPasses();
Jean Christophe Beyler8bcecce2014-04-29 13:42:08 -07001010 } else if (option.starts_with("--dump-cfg-passes=")) {
1011 std::string dump_passes = option.substr(strlen("--dump-cfg-passes=")).data();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001012 PassDriverMEOpts::SetDumpPassList(dump_passes);
Andreas Gampe5655e842014-06-17 16:36:07 -07001013 } else if (option.starts_with("--implicit-checks=")) {
1014 std::string checks = option.substr(strlen("--implicit-checks=")).data();
1015 std::vector<std::string> checkvec;
1016 Split(checks, ',', checkvec);
1017 for (auto& str : checkvec) {
1018 std::string val = Trim(str);
1019 if (val == "none") {
1020 explicit_null_checks = true;
1021 explicit_so_checks = true;
1022 explicit_suspend_checks = true;
1023 } else if (val == "null") {
1024 explicit_null_checks = false;
1025 } else if (val == "suspend") {
1026 explicit_suspend_checks = false;
1027 } else if (val == "stack") {
1028 explicit_so_checks = false;
1029 } else if (val == "all") {
1030 explicit_null_checks = false;
1031 explicit_so_checks = false;
1032 explicit_suspend_checks = false;
1033 } else {
1034 Usage("--implicit-checks passed non-recognized value %s", val.c_str());
1035 }
Andreas Gampe5655e842014-06-17 16:36:07 -07001036 }
Dave Allisonca3aaba2014-06-23 14:46:53 -07001037 has_explicit_checks_options = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001038 } else if (option == "--include-patch-information") {
1039 include_patch_information = true;
1040 explicit_include_patch_information = true;
1041 } else if (option == "--no-include-patch-information") {
1042 include_patch_information = false;
1043 explicit_include_patch_information = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -07001045 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046 }
1047 }
1048
1049 if (oat_filename.empty() && oat_fd == -1) {
1050 Usage("Output must be supplied with either --oat-file or --oat-fd");
1051 }
1052
1053 if (!oat_filename.empty() && oat_fd != -1) {
1054 Usage("--oat-file should not be used with --oat-fd");
1055 }
1056
1057 if (!oat_symbols.empty() && oat_fd != -1) {
1058 Usage("--oat-symbols should not be used with --oat-fd");
1059 }
1060
1061 if (!oat_symbols.empty() && is_host) {
1062 Usage("--oat-symbols should not be used with --host");
1063 }
1064
1065 if (oat_fd != -1 && !image_filename.empty()) {
1066 Usage("--oat-fd should not be used with --image");
1067 }
1068
Brian Carlstrom7940e442013-07-12 13:46:57 -07001069 if (android_root.empty()) {
1070 const char* android_root_env_var = getenv("ANDROID_ROOT");
Kenny Root51316382014-05-13 14:59:37 -07001071 if (android_root_env_var == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072 Usage("--android-root unspecified and ANDROID_ROOT not set");
1073 }
1074 android_root += android_root_env_var;
1075 }
1076
1077 bool image = (!image_filename.empty());
1078 if (!image && boot_image_filename.empty()) {
Ian Rogers88723582014-06-13 11:38:54 -07001079 boot_image_filename += android_root;
Brian Carlstrom3ac05bb2014-05-13 19:31:38 -07001080 boot_image_filename += "/framework/boot.art";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 }
1082 std::string boot_image_option;
1083 if (!boot_image_filename.empty()) {
1084 boot_image_option += "-Ximage:";
1085 boot_image_option += boot_image_filename;
1086 }
1087
Kenny Root51316382014-05-13 14:59:37 -07001088 if (image_classes_filename != nullptr && !image) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089 Usage("--image-classes should only be used with --image");
1090 }
1091
Kenny Root51316382014-05-13 14:59:37 -07001092 if (image_classes_filename != nullptr && !boot_image_option.empty()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001093 Usage("--image-classes should not be used with --boot-image");
1094 }
1095
Kenny Root51316382014-05-13 14:59:37 -07001096 if (image_classes_zip_filename != nullptr && image_classes_filename == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001097 Usage("--image-classes-zip should be used with --image-classes");
1098 }
1099
1100 if (dex_filenames.empty() && zip_fd == -1) {
1101 Usage("Input must be supplied with either --dex-file or --zip-fd");
1102 }
1103
1104 if (!dex_filenames.empty() && zip_fd != -1) {
1105 Usage("--dex-file should not be used with --zip-fd");
1106 }
1107
1108 if (!dex_filenames.empty() && !zip_location.empty()) {
1109 Usage("--dex-file should not be used with --zip-location");
1110 }
1111
1112 if (dex_locations.empty()) {
1113 for (size_t i = 0; i < dex_filenames.size(); i++) {
1114 dex_locations.push_back(dex_filenames[i]);
1115 }
1116 } else if (dex_locations.size() != dex_filenames.size()) {
1117 Usage("--dex-location arguments do not match --dex-file arguments");
1118 }
1119
1120 if (zip_fd != -1 && zip_location.empty()) {
1121 Usage("--zip-location should be supplied with --zip-fd");
1122 }
1123
1124 if (boot_image_option.empty()) {
1125 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -07001126 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001127 }
1128 }
1129
1130 std::string oat_stripped(oat_filename);
1131 std::string oat_unstripped;
1132 if (!oat_symbols.empty()) {
1133 oat_unstripped += oat_symbols;
1134 } else {
1135 oat_unstripped += oat_filename;
1136 }
1137
Kenny Root51316382014-05-13 14:59:37 -07001138 if (compiler_filter_string == nullptr) {
Douglas Leung2db3e262014-06-25 16:02:55 -07001139 if (instruction_set == kMips64) {
1140 // TODO: fix compiler for Mips64.
Ian Rogersbefbd572014-03-06 01:13:39 -08001141 compiler_filter_string = "interpret-only";
1142 } else if (image) {
Brian Carlstrom5e754d82014-03-05 10:59:04 -08001143 compiler_filter_string = "speed";
Brian Carlstrom6449c622014-02-10 23:48:36 -08001144 } else {
1145#if ART_SMALL_MODE
1146 compiler_filter_string = "interpret-only";
1147#else
1148 compiler_filter_string = "speed";
1149#endif
1150 }
1151 }
1152 CHECK(compiler_filter_string != nullptr);
1153 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
Jeff Hao4a200f52014-04-01 14:58:49 -07001154 if (strcmp(compiler_filter_string, "verify-none") == 0) {
1155 compiler_filter = CompilerOptions::kVerifyNone;
1156 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
Brian Carlstrom6449c622014-02-10 23:48:36 -08001157 compiler_filter = CompilerOptions::kInterpretOnly;
1158 } else if (strcmp(compiler_filter_string, "space") == 0) {
1159 compiler_filter = CompilerOptions::kSpace;
1160 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
1161 compiler_filter = CompilerOptions::kBalanced;
1162 } else if (strcmp(compiler_filter_string, "speed") == 0) {
1163 compiler_filter = CompilerOptions::kSpeed;
1164 } else if (strcmp(compiler_filter_string, "everything") == 0) {
1165 compiler_filter = CompilerOptions::kEverything;
1166 } else {
1167 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
1168 }
1169
Nicolas Geoffray452bee52014-07-09 07:58:10 +00001170 CheckExplicitCheckOptions(instruction_set, &explicit_null_checks, &explicit_so_checks,
1171 &explicit_suspend_checks);
Andreas Gampe5655e842014-06-17 16:36:07 -07001172
Alex Light53cb16b2014-06-12 11:26:29 -07001173 if (!explicit_include_patch_information) {
1174 include_patch_information =
1175 (compiler_kind == Compiler::kQuick && CompilerOptions::kDefaultIncludePatchInformation);
1176 }
1177
Brian Carlstrom6449c622014-02-10 23:48:36 -08001178 CompilerOptions compiler_options(compiler_filter,
1179 huge_method_threshold,
1180 large_method_threshold,
1181 small_method_threshold,
1182 tiny_method_threshold,
Mark Mendellae9fd932014-02-10 16:14:35 -08001183 num_dex_methods_threshold,
Calin Juravlec1b643c2014-05-30 23:44:11 +01001184 generate_gdb_information,
Alex Light53cb16b2014-06-12 11:26:29 -07001185 include_patch_information,
Alex Light78382fa2014-06-06 15:45:32 -07001186 top_k_profile_threshold,
Andreas Gampe5655e842014-06-17 16:36:07 -07001187 include_debug_symbols,
1188 explicit_null_checks,
1189 explicit_so_checks,
1190 explicit_suspend_checks
Brian Carlstrom6449c622014-02-10 23:48:36 -08001191#ifdef ART_SEA_IR_MODE
1192 , compiler_options.sea_ir_ = true;
1193#endif
1194 ); // NOLINT(whitespace/parens)
1195
Brian Carlstrom7940e442013-07-12 13:46:57 -07001196 // Done with usage checks, enable watchdog if requested
1197 WatchDog watch_dog(watch_dog_enabled);
1198
1199 // Check early that the result of compilation can be written
Ian Rogers700a4022014-05-19 16:49:03 -07001200 std::unique_ptr<File> oat_file;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001201 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
1202 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001203 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204 if (oat_location.empty()) {
1205 oat_location = oat_filename;
1206 }
1207 } else {
1208 oat_file.reset(new File(oat_fd, oat_location));
1209 oat_file->DisableAutoClose();
1210 }
Kenny Root51316382014-05-13 14:59:37 -07001211 if (oat_file.get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001212 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
1213 return EXIT_FAILURE;
1214 }
1215 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1216 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
1217 return EXIT_FAILURE;
1218 }
1219
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001220 timings.StartTiming("dex2oat Setup");
Brian Carlstrom09881a82014-04-18 17:44:01 -07001221 LOG(INFO) << CommandLine();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001222
Brian Carlstrom6449c622014-02-10 23:48:36 -08001223 Runtime::Options runtime_options;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001224 std::vector<const DexFile*> boot_class_path;
1225 if (boot_image_option.empty()) {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001226 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
1227 if (failure_count > 0) {
1228 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1229 return EXIT_FAILURE;
1230 }
Brian Carlstrom6449c622014-02-10 23:48:36 -08001231 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001232 } else {
Kenny Root51316382014-05-13 14:59:37 -07001233 runtime_options.push_back(std::make_pair(boot_image_option.c_str(), nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001234 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001235 for (size_t i = 0; i < runtime_args.size(); i++) {
Kenny Root51316382014-05-13 14:59:37 -07001236 runtime_options.push_back(std::make_pair(runtime_args[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001237 }
1238
Brian Carlstrom6449c622014-02-10 23:48:36 -08001239 VerificationResults verification_results(&compiler_options);
1240 DexFileToMethodInlinerMap method_inliner_map;
1241 CompilerCallbacksImpl callbacks(&verification_results, &method_inliner_map);
1242 runtime_options.push_back(std::make_pair("compilercallbacks", &callbacks));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001243 runtime_options.push_back(
1244 std::make_pair("imageinstructionset",
1245 reinterpret_cast<const void*>(GetInstructionSetString(instruction_set))));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001246
Brian Carlstrom7940e442013-07-12 13:46:57 -07001247 Dex2Oat* p_dex2oat;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001248 if (!Dex2Oat::Create(&p_dex2oat,
1249 runtime_options,
1250 compiler_options,
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001251 compiler_kind,
Brian Carlstrom6449c622014-02-10 23:48:36 -08001252 instruction_set,
1253 instruction_set_features,
1254 &verification_results,
1255 &method_inliner_map,
1256 thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001257 LOG(ERROR) << "Failed to create dex2oat";
1258 return EXIT_FAILURE;
1259 }
Ian Rogers700a4022014-05-19 16:49:03 -07001260 std::unique_ptr<Dex2Oat> dex2oat(p_dex2oat);
Andreas Gampe5655e842014-06-17 16:36:07 -07001261
1262 // TODO: Not sure whether it's a good idea to allow anything else but the runtime option in
1263 // this case at all, as we'll have to throw away produced code for a mismatch.
1264 if (!has_explicit_checks_options) {
Nicolas Geoffray452bee52014-07-09 07:58:10 +00001265 bool cross_compiling = true;
1266 switch (kRuntimeISA) {
1267 case kArm:
1268 case kThumb2:
1269 cross_compiling = instruction_set != kArm && instruction_set != kThumb2;
1270 break;
1271 default:
1272 cross_compiling = instruction_set != kRuntimeISA;
1273 break;
1274 }
1275 if (!cross_compiling) {
1276 Runtime* runtime = Runtime::Current();
1277 compiler_options.SetExplicitNullChecks(runtime->ExplicitNullChecks());
1278 compiler_options.SetExplicitStackOverflowChecks(runtime->ExplicitStackOverflowChecks());
1279 compiler_options.SetExplicitSuspendChecks(runtime->ExplicitSuspendChecks());
Andreas Gampe5655e842014-06-17 16:36:07 -07001280 }
1281 }
1282
Brian Carlstrom7940e442013-07-12 13:46:57 -07001283 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -07001284 // give it away now so that we don't starve GC.
1285 Thread* self = Thread::Current();
1286 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -07001287 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -07001288 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1289 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001290 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -07001291 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001292
1293 // If --image-classes was specified, calculate the full list of classes to include in the image
Ian Rogers700a4022014-05-19 16:49:03 -07001294 std::unique_ptr<CompilerDriver::DescriptorSet> image_classes(nullptr);
Kenny Rootd5185342014-05-13 14:47:05 -07001295 if (image_classes_filename != nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001296 std::string error_msg;
Kenny Rootd5185342014-05-13 14:47:05 -07001297 if (image_classes_zip_filename != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001298 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001299 image_classes_filename,
1300 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001301 } else {
1302 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
1303 }
Kenny Rootd5185342014-05-13 14:47:05 -07001304 if (image_classes.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001305 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
1306 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001307 return EXIT_FAILURE;
1308 }
Kenny Rootd5185342014-05-13 14:47:05 -07001309 } else if (image) {
1310 image_classes.reset(new CompilerDriver::DescriptorSet);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001311 }
1312
1313 std::vector<const DexFile*> dex_files;
1314 if (boot_image_option.empty()) {
1315 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1316 } else {
1317 if (dex_filenames.empty()) {
Ian Rogers740a11d2014-01-14 10:11:25 -08001318 ATRACE_BEGIN("Opening zip archive from file descriptor");
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001319 std::string error_msg;
Ian Rogers700a4022014-05-19 16:49:03 -07001320 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001321 &error_msg));
Kenny Root51316382014-05-13 14:59:37 -07001322 if (zip_archive.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001323 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
1324 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001325 return EXIT_FAILURE;
1326 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001327 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location, &error_msg, &dex_files)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001328 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
1329 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001330 return EXIT_FAILURE;
1331 }
Ian Rogers740a11d2014-01-14 10:11:25 -08001332 ATRACE_END();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001333 } else {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001334 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
1335 if (failure_count > 0) {
1336 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1337 return EXIT_FAILURE;
1338 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001339 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001340
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001341 const bool kSaveDexInput = false;
1342 if (kSaveDexInput) {
1343 for (size_t i = 0; i < dex_files.size(); ++i) {
1344 const DexFile* dex_file = dex_files[i];
Ian Rogers5180cc12014-02-21 13:34:16 -08001345 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
Ian Rogers700a4022014-05-19 16:49:03 -07001346 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001347 if (tmp_file.get() == nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -08001348 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1349 << ". Try: adb shell chmod 777 /data/local/tmp";
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001350 continue;
1351 }
1352 tmp_file->WriteFully(dex_file->Begin(), dex_file->Size());
1353 LOG(INFO) << "Wrote input to " << tmp_file_name;
1354 }
1355 }
Brian Carlstrom2ec65202014-03-03 15:16:37 -08001356 }
1357 // Ensure opened dex files are writable for dex-to-dex transformations.
1358 for (const auto& dex_file : dex_files) {
1359 if (!dex_file->EnableWrite()) {
1360 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Brian Carlstromd76e0832013-08-29 15:17:42 -07001361 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001362 }
1363
buzbeea024a062013-07-31 10:47:37 -07001364 /*
Jeff Hao4a200f52014-04-01 14:58:49 -07001365 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1366 * Don't bother to check if we're doing the image.
buzbeea024a062013-07-31 10:47:37 -07001367 */
Jeff Hao4a200f52014-04-01 14:58:49 -07001368 if (!image && compiler_options.IsCompilationEnabled()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001369 size_t num_methods = 0;
1370 for (size_t i = 0; i != dex_files.size(); ++i) {
1371 const DexFile* dex_file = dex_files[i];
Kenny Root51316382014-05-13 14:59:37 -07001372 CHECK(dex_file != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001373 num_methods += dex_file->NumMethodIds();
1374 }
Brian Carlstrom6449c622014-02-10 23:48:36 -08001375 if (num_methods <= compiler_options.GetNumDexMethodsThreshold()) {
1376 compiler_options.SetCompilerFilter(CompilerOptions::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001377 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378 }
1379 }
1380
Ian Rogers700a4022014-05-19 16:49:03 -07001381 std::unique_ptr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
Nicolas Geoffray452bee52014-07-09 07:58:10 +00001382 android_root,
1383 is_host,
1384 dex_files,
1385 oat_file.get(),
1386 bitcode_filename,
1387 image,
1388 image_classes,
1389 dump_stats,
1390 dump_passes,
1391 timings,
1392 compiler_phases_timings,
1393 profile_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001394
Kenny Root51316382014-05-13 14:59:37 -07001395 if (compiler.get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1397 return EXIT_FAILURE;
1398 }
1399
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001400 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001401
1402 // Notes on the interleaving of creating the image and oat file to
1403 // ensure the references between the two are correct.
1404 //
1405 // Currently we have a memory layout that looks something like this:
1406 //
1407 // +--------------+
1408 // | image |
1409 // +--------------+
1410 // | boot oat |
1411 // +--------------+
1412 // | alloc spaces |
1413 // +--------------+
1414 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001415 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001416 //
1417 // 1. The image is expected to be loaded at an absolute address and
1418 // contains Objects with absolute pointers within the image.
1419 //
1420 // 2. There are absolute pointers from Methods in the image to their
1421 // code in the oat.
1422 //
1423 // 3. There are absolute pointers from the code in the oat to Methods
1424 // in the image.
1425 //
1426 // 4. There are absolute pointers from code in the oat to other code
1427 // in the oat.
1428 //
1429 // To get this all correct, we go through several steps.
1430 //
1431 // 1. We have already created that oat file above with
1432 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001433 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001434 // file). The Compiler returned by CreateOatFile provides
1435 // PatchInformation for references to oat code and Methods that need
1436 // to be update once we know where the oat file will be located
1437 // after the image.
1438 //
1439 // 2. We create the image file. It needs to know where the oat file
1440 // will be loaded after itself. Originally when oat file was simply
1441 // memory mapped so we could predict where its contents were based
1442 // on the file size. Now that it is an ELF file, we need to inspect
1443 // the ELF file to understand the in memory segment layout including
1444 // where the oat header is located within. ImageWriter's
1445 // PatchOatCodeAndMethods uses the PatchInformation from the
1446 // Compiler to touch up absolute references in the oat file.
1447 //
1448 // 3. We fixup the ELF program headers so that dlopen will try to
1449 // load the .so at the desired location at runtime by offsetting the
1450 // Elf32_Phdr.p_vaddr values by the desired base address.
1451 //
1452 if (image) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001453 TimingLogger::ScopedTiming t("dex2oat ImageWriter", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001454 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1455 image_base,
1456 oat_unstripped,
1457 oat_location,
1458 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001459 if (!image_creation_success) {
1460 return EXIT_FAILURE;
1461 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001462 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001463 }
1464
1465 if (is_host) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001466 timings.EndTiming();
Ian Rogers46398602013-08-20 07:50:36 -07001467 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001468 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001469 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001470 if (dump_passes) {
Ian Rogers3d504072014-03-01 09:16:49 -08001471 LOG(INFO) << Dumpable<CumulativeLogger>(*compiler.get()->GetTimingsLogger());
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001472 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001473 return EXIT_SUCCESS;
1474 }
1475
1476 // If we don't want to strip in place, copy from unstripped location to stripped location.
1477 // We need to strip after image creation because FixupElf needs to use .strtab.
1478 if (oat_unstripped != oat_stripped) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001479 TimingLogger::ScopedTiming t("dex2oat OatFile copy", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001480 oat_file.reset();
Ian Rogers700a4022014-05-19 16:49:03 -07001481 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1482 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001483 size_t buffer_size = 8192;
Ian Rogers700a4022014-05-19 16:49:03 -07001484 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001485 while (true) {
1486 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1487 if (bytes_read <= 0) {
1488 break;
1489 }
1490 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1491 CHECK(write_ok);
1492 }
1493 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001494 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001495 }
1496
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001497#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Alex Light78382fa2014-06-06 15:45:32 -07001498 if (!compiler_options.GetIncludeDebugSymbols()) {
1499 timings.NewSplit("dex2oat ElfStripper");
1500 // Strip unneeded sections for target
1501 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1502 CHECK_EQ(0, seek_actual);
1503 std::string error_msg;
1504 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001505
Brian Carlstrom7940e442013-07-12 13:46:57 -07001506
Alex Light78382fa2014-06-06 15:45:32 -07001507 // We wrote the oat file successfully, and want to keep it.
1508 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
1509 } else {
1510 VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location;
1511 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001512#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001513
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001514 timings.EndTiming();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001515
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001516 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001517 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001518 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001519 if (dump_passes) {
1520 LOG(INFO) << Dumpable<CumulativeLogger>(compiler_phases_timings);
1521 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001522
1523 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1524 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
Brian Carlstrom6449c622014-02-10 23:48:36 -08001525 if (!kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
Brian Carlstrom65c23bb2014-02-01 22:12:39 -08001526 dex2oat->LogCompletionTime();
Ian Rogers2672a9f2013-09-05 17:24:22 -07001527 exit(EXIT_SUCCESS);
1528 }
1529
Brian Carlstrom7940e442013-07-12 13:46:57 -07001530 return EXIT_SUCCESS;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001531} // NOLINT(readability/fn_size)
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001532} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001533
1534int main(int argc, char** argv) {
1535 return art::dex2oat(argc, argv);
1536}