blob: ce339bfc5151c3e8fe407f134ec534f4b21ec627 [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
28#include "base/stl_util.h"
29#include "base/stringpiece.h"
30#include "base/timing_logger.h"
31#include "base/unix_file/fd_file.h"
32#include "class_linker.h"
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +000033#include "compiler_backend.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000036#include "dex/verification_results.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "driver/compiler_driver.h"
38#include "elf_fixup.h"
39#include "elf_stripper.h"
40#include "gc/space/image_space.h"
41#include "gc/space/space-inl.h"
42#include "image_writer.h"
43#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "mirror/class-inl.h"
46#include "mirror/class_loader.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
49#include "oat_writer.h"
50#include "object_utils.h"
51#include "os.h"
52#include "runtime.h"
53#include "ScopedLocalRef.h"
54#include "scoped_thread_state_change.h"
55#include "sirt_ref.h"
56#include "vector_output_stream.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000057#include "verifier/method_verifier.h"
58#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "well_known_classes.h"
60#include "zip_archive.h"
61
Vladimir Marko5816ed42013-11-27 17:04:20 +000062#include "dex/quick/dex_file_to_method_inliner_map.h"
63
Brian Carlstrom7940e442013-07-12 13:46:57 -070064namespace art {
65
66static void UsageErrorV(const char* fmt, va_list ap) {
67 std::string error;
68 StringAppendV(&error, fmt, ap);
69 LOG(ERROR) << error;
70}
71
72static void UsageError(const char* fmt, ...) {
73 va_list ap;
74 va_start(ap, fmt);
75 UsageErrorV(fmt, ap);
76 va_end(ap);
77}
78
79static void Usage(const char* fmt, ...) {
80 va_list ap;
81 va_start(ap, fmt);
82 UsageErrorV(fmt, ap);
83 va_end(ap);
84
85 UsageError("Usage: dex2oat [options]...");
86 UsageError("");
87 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
88 UsageError(" Example: --dex-file=/system/framework/core.jar");
89 UsageError("");
90 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
91 UsageError(" containing a classes.dex file to compile.");
92 UsageError(" Example: --zip-fd=5");
93 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -070094 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
95 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -070096 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
97 UsageError("");
98 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
99 UsageError(" Example: --oat-file=/system/framework/boot.oat");
100 UsageError("");
101 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
102 UsageError(" Example: --oat-file=/system/framework/boot.oat");
103 UsageError("");
104 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
105 UsageError(" to the file descriptor specified by --oat-fd.");
106 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
107 UsageError("");
108 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
109 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
110 UsageError("");
111 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
112 UsageError(" Example: --bitcode=/system/framework/boot.bc");
113 UsageError("");
114 UsageError(" --image=<file.art>: specifies the output image filename.");
115 UsageError(" Example: --image=/system/framework/boot.art");
116 UsageError("");
117 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
118 UsageError(" Example: --image=frameworks/base/preloaded-classes");
119 UsageError("");
120 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
121 UsageError(" Example: --base=0x50000000");
122 UsageError("");
123 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
124 UsageError(" Example: --boot-image=/system/framework/boot.art");
125 UsageError(" Default: <host-prefix>/system/framework/boot.art");
126 UsageError("");
127 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
128 UsageError(" cross compilation.");
129 UsageError(" Example: --host-prefix=out/target/product/crespo");
130 UsageError(" Default: $ANDROID_PRODUCT_OUT");
131 UsageError("");
132 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
133 UsageError(" Example: --android-root=out/host/linux-x86");
134 UsageError(" Default: $ANDROID_ROOT");
135 UsageError("");
136 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
137 UsageError(" set.");
138 UsageError(" Example: --instruction-set=x86");
139 UsageError(" Default: arm");
140 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700141 UsageError(" --instruction-set-features=...,: Specify instruction set features");
142 UsageError(" Example: --instruction-set-features=div");
143 UsageError(" Default: default");
144 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
146 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700147 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 UsageError(" Default: Quick");
149 UsageError("");
150 UsageError(" --host: used with Portable backend to link against host runtime libraries");
151 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700152 UsageError(" --dump-timing: display a breakdown of where time was spent");
153 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
155 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
156 UsageError(" Use a separate --runtime-arg switch for each argument.");
157 UsageError(" Example: --runtime-arg -Xms256m");
158 UsageError("");
159 std::cerr << "See log for usage error information\n";
160 exit(EXIT_FAILURE);
161}
162
163class Dex2Oat {
164 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700165 static bool Create(Dex2Oat** p_dex2oat,
166 Runtime::Options& options,
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000167 CompilerBackend::Kind compiler_backend,
Brian Carlstrom45602482013-07-21 22:07:55 -0700168 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700169 InstructionSetFeatures instruction_set_features,
Brian Carlstrom45602482013-07-21 22:07:55 -0700170 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000172 UniquePtr<Dex2Oat> dex2oat(new Dex2Oat(compiler_backend, instruction_set,
173 instruction_set_features, thread_count));
174 if (!dex2oat->CreateRuntime(options, instruction_set)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 *p_dex2oat = NULL;
176 return false;
177 }
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000178 *p_dex2oat = dex2oat.release();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 return true;
180 }
181
182 ~Dex2Oat() {
183 delete runtime_;
Brian Carlstrom65c23bb2014-02-01 22:12:39 -0800184 LogCompletionTime();
185 }
186
187 void LogCompletionTime() {
188 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700189 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 }
191
192
Brian Carlstrom45602482013-07-21 22:07:55 -0700193 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Brian Carlstrom45602482013-07-21 22:07:55 -0700195 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
196 std::ifstream::in));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197 if (image_classes_file.get() == NULL) {
198 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
199 return NULL;
200 }
201 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
202 image_classes_file->close();
203 return result.release();
204 }
205
206 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
207 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
208 while (image_classes_stream.good()) {
209 std::string dot;
210 std::getline(image_classes_stream, dot);
211 if (StartsWith(dot, "#") || dot.empty()) {
212 continue;
213 }
214 std::string descriptor(DotToDescriptor(dot.c_str()));
215 image_classes->insert(descriptor);
216 }
217 return image_classes.release();
218 }
219
Brian Carlstrom45602482013-07-21 22:07:55 -0700220 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700221 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const char* zip_filename,
222 const char* image_classes_filename,
223 std::string* error_msg) {
224 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 if (zip_archive.get() == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700226 return NULL;
227 }
Narayan Kamath92572be2013-11-28 14:06:24 +0000228 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700229 if (zip_entry.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700230 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
231 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 return NULL;
233 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700234 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename,
235 error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 if (image_classes_file.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700237 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
238 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 return NULL;
240 }
241 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
242 image_classes_file->Size());
243 std::istringstream image_classes_stream(image_classes_string);
244 return ReadImageClasses(image_classes_stream);
245 }
246
247 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
248 const std::string* host_prefix,
249 const std::string& android_root,
250 bool is_host,
251 const std::vector<const DexFile*>& dex_files,
252 File* oat_file,
253 const std::string& bitcode_filename,
254 bool image,
255 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
256 bool dump_stats,
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000257 bool dump_passes,
258 TimingLogger& timings,
259 CumulativeLogger& compiler_phases_timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 // SirtRef and ClassLoader creation needs to come after Runtime::Create
261 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700262 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700263 if (!boot_image_option.empty()) {
264 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
265 std::vector<const DexFile*> class_path_files(dex_files);
266 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700267 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268 for (size_t i = 0; i < class_path_files.size(); i++) {
269 class_linker->RegisterDexFile(*class_path_files[i]);
270 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
272 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
273 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
274 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
275 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
276 }
277
Vladimir Markoc7f83202014-01-24 17:55:18 +0000278 UniquePtr<CompilerDriver> driver(new CompilerDriver(verification_results_.get(),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000279 method_inliner_map_.get(),
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000280 compiler_backend_,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700281 instruction_set_,
Dave Allison70202782013-10-22 17:52:19 -0700282 instruction_set_features_,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700283 image,
284 image_classes.release(),
285 thread_count_,
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000286 dump_stats,
287 dump_passes,
288 &compiler_phases_timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +0000290 driver->GetCompilerBackend()->SetBitcodeFileName(bitcode_filename);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291
Brian Carlstrom45602482013-07-21 22:07:55 -0700292 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700294 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700295 std::string image_file_location;
296 uint32_t image_file_location_oat_checksum = 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800297 uintptr_t image_file_location_oat_data_begin = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298 if (!driver->IsImage()) {
Ian Rogersca368cb2013-11-15 15:52:08 -0800299 TimingLogger::ScopedSplit split("Loading image checksum", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
301 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
302 image_file_location_oat_data_begin =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800303 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700304 image_file_location = image_space->GetImageFilename();
305 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
306 image_file_location = image_file_location.substr(host_prefix->size());
307 }
308 }
309
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700310 OatWriter oat_writer(dex_files,
311 image_file_location_oat_checksum,
312 image_file_location_oat_data_begin,
313 image_file_location,
Ian Rogersca368cb2013-11-15 15:52:08 -0800314 driver.get(),
315 &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700316
Ian Rogersca368cb2013-11-15 15:52:08 -0800317 TimingLogger::ScopedSplit split("Writing ELF", &timings);
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700318 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700319 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
320 return NULL;
321 }
322
323 return driver.release();
324 }
325
326 bool CreateImageFile(const std::string& image_filename,
327 uintptr_t image_base,
328 const std::string& oat_filename,
329 const std::string& oat_location,
330 const CompilerDriver& compiler)
331 LOCKS_EXCLUDED(Locks::mutator_lock_) {
332 uintptr_t oat_data_begin;
333 {
334 // ImageWriter is scoped so it can free memory before doing FixupElf
335 ImageWriter image_writer(compiler);
336 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
337 LOG(ERROR) << "Failed to create image file " << image_filename;
338 return false;
339 }
340 oat_data_begin = image_writer.GetOatDataBegin();
341 }
342
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700343 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 if (oat_file.get() == NULL) {
345 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
346 return false;
347 }
348 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
349 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
350 return false;
351 }
352 return true;
353 }
354
355 private:
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000356 class Dex2OatCompilerCallbacks : public CompilerCallbacks {
357 public:
Vladimir Markoc7f83202014-01-24 17:55:18 +0000358 Dex2OatCompilerCallbacks(VerificationResults* verification_results,
Vladimir Marko5816ed42013-11-27 17:04:20 +0000359 DexFileToMethodInlinerMap* method_inliner_map)
Vladimir Markoc7f83202014-01-24 17:55:18 +0000360 : verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000361 method_inliner_map_(method_inliner_map) { }
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000362 virtual ~Dex2OatCompilerCallbacks() { }
363
364 virtual bool MethodVerified(verifier::MethodVerifier* verifier)
365 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Vladimir Markoc7f83202014-01-24 17:55:18 +0000366 bool result = verification_results_->ProcessVerifiedMethod(verifier);
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000367 if (result) {
Vladimir Marko5816ed42013-11-27 17:04:20 +0000368 MethodReference ref = verifier->GetMethodReference();
369 method_inliner_map_->GetMethodInliner(ref.dex_file)
Vladimir Marko2bc47802014-02-10 09:43:07 +0000370 ->AnalyseMethodCode(verifier);
Vladimir Marko5816ed42013-11-27 17:04:20 +0000371 }
372 return result;
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000373 }
374 virtual void ClassRejected(ClassReference ref) {
Vladimir Markoc7f83202014-01-24 17:55:18 +0000375 verification_results_->AddRejectedClass(ref);
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000376 }
377
378 private:
Vladimir Markoc7f83202014-01-24 17:55:18 +0000379 VerificationResults* verification_results_;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000380 DexFileToMethodInlinerMap* method_inliner_map_;
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000381 };
382
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000383 explicit Dex2Oat(CompilerBackend::Kind compiler_backend,
Brian Carlstrom45602482013-07-21 22:07:55 -0700384 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700385 InstructionSetFeatures instruction_set_features,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700386 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 : compiler_backend_(compiler_backend),
388 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700389 instruction_set_features_(instruction_set_features),
Vladimir Markoc7f83202014-01-24 17:55:18 +0000390 verification_results_(new VerificationResults),
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000391 method_inliner_map_(new DexFileToMethodInlinerMap),
Vladimir Markoc7f83202014-01-24 17:55:18 +0000392 callbacks_(verification_results_.get(), method_inliner_map_.get()),
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000393 runtime_(nullptr),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700394 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700395 start_ns_(NanoTime()) {
396 }
397
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000398 bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000400 options.push_back(
401 std::make_pair("compilercallbacks", static_cast<CompilerCallbacks*>(&callbacks_)));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700402 if (!Runtime::Create(options, false)) {
403 LOG(ERROR) << "Failed to create runtime";
404 return false;
405 }
406 Runtime* runtime = Runtime::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
408 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
409 if (!runtime->HasCalleeSaveMethod(type)) {
410 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
411 }
412 }
413 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000414 runtime_ = runtime;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700415 return true;
416 }
417
418 // Appends to dex_files any elements of class_path that it doesn't already
419 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700420 static void OpenClassPathFiles(const std::string& class_path,
421 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700422 std::vector<std::string> parsed;
423 Split(class_path, ':', parsed);
424 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
425 ScopedObjectAccess soa(Thread::Current());
426 for (size_t i = 0; i < parsed.size(); ++i) {
427 if (DexFilesContains(dex_files, parsed[i])) {
428 continue;
429 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700430 std::string error_msg;
431 const DexFile* dex_file = DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700432 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700433 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700434 } else {
435 dex_files.push_back(dex_file);
436 }
437 }
438 }
439
440 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700441 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
442 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 for (size_t i = 0; i < dex_files.size(); ++i) {
444 if (dex_files[i]->GetLocation() == location) {
445 return true;
446 }
447 }
448 return false;
449 }
450
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000451 const CompilerBackend::Kind compiler_backend_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700452
453 const InstructionSet instruction_set_;
Dave Allison70202782013-10-22 17:52:19 -0700454 const InstructionSetFeatures instruction_set_features_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700455
Vladimir Markoc7f83202014-01-24 17:55:18 +0000456 UniquePtr<VerificationResults> verification_results_;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000457 UniquePtr<DexFileToMethodInlinerMap> method_inliner_map_;
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000458 Dex2OatCompilerCallbacks callbacks_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 Runtime* runtime_;
460 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461 uint64_t start_ns_;
462
463 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
464};
465
466static bool ParseInt(const char* in, int* out) {
467 char* end;
468 int result = strtol(in, &end, 10);
469 if (in == end || *end != '\0') {
470 return false;
471 }
472 *out = result;
473 return true;
474}
475
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800476static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
477 const std::vector<const char*>& dex_locations,
478 std::vector<const DexFile*>& dex_files) {
479 size_t failure_count = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480 for (size_t i = 0; i < dex_filenames.size(); i++) {
481 const char* dex_filename = dex_filenames[i];
482 const char* dex_location = dex_locations[i];
Ian Rogers740a11d2014-01-14 10:11:25 -0800483 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700484 std::string error_msg;
Brian Carlstromd5aba592013-11-12 01:52:44 -0800485 if (!OS::FileExists(dex_filename)) {
486 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
487 continue;
488 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700489 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700490 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700491 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800492 ++failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700493 } else {
494 dex_files.push_back(dex_file);
495 }
Ian Rogers740a11d2014-01-14 10:11:25 -0800496 ATRACE_END();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700497 }
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800498 return failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700499}
500
501// The primary goal of the watchdog is to prevent stuck build servers
502// during development when fatal aborts lead to a cascade of failures
503// that result in a deadlock.
504class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700505// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
506#undef CHECK_PTHREAD_CALL
507#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
508 do { \
509 int rc = call args; \
510 if (rc != 0) { \
511 errno = rc; \
512 std::string message(# call); \
513 message += " failed for "; \
514 message += reason; \
515 Fatal(message); \
516 } \
517 } while (false)
518
519 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700520 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700521 is_watch_dog_enabled_ = is_watch_dog_enabled;
522 if (!is_watch_dog_enabled_) {
523 return;
524 }
525 shutting_down_ = false;
526 const char* reason = "dex2oat watch dog thread startup";
527 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
528 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
529 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
530 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
531 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
532 }
533 ~WatchDog() {
534 if (!is_watch_dog_enabled_) {
535 return;
536 }
537 const char* reason = "dex2oat watch dog thread shutdown";
538 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
539 shutting_down_ = true;
540 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
541 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
542
543 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
544
545 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
546 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
547 }
548
549 private:
550 static void* CallBack(void* arg) {
551 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
552 ::art::SetThreadName("dex2oat watch dog");
553 self->Wait();
554 return NULL;
555 }
556
557 static void Message(char severity, const std::string& message) {
558 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
559 // cases.
560 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
561 kIsDebugBuild ? "d" : "",
562 severity,
563 getpid(),
564 GetTid(),
565 message.c_str());
566 }
567
568 static void Warn(const std::string& message) {
569 Message('W', message);
570 }
571
572 static void Fatal(const std::string& message) {
573 Message('F', message);
574 exit(1);
575 }
576
577 void Wait() {
578 bool warning = true;
579 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
580 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
581 // large.
582 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
583 timespec warning_ts;
584 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
585 timespec timeout_ts;
586 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
587 const char* reason = "dex2oat watch dog thread waiting";
588 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
589 while (!shutting_down_) {
590 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
591 warning ? &warning_ts
592 : &timeout_ts));
593 if (rc == ETIMEDOUT) {
594 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
595 warning ? kWatchDogWarningSeconds
596 : kWatchDogTimeoutSeconds));
597 if (warning) {
598 Warn(message.c_str());
599 warning = false;
600 } else {
601 Fatal(message.c_str());
602 }
603 } else if (rc != 0) {
604 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
605 strerror(errno)));
606 Fatal(message.c_str());
607 }
608 }
609 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
610 }
611
612 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
613#if ART_USE_PORTABLE_COMPILER
614 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
615 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
616#else
617 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
618 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
619#endif
620
621 bool is_watch_dog_enabled_;
622 bool shutting_down_;
623 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
624 pthread_mutex_t mutex_;
625 pthread_cond_t cond_;
626 pthread_attr_t attr_;
627 pthread_t pthread_;
628};
629const unsigned int WatchDog::kWatchDogWarningSeconds;
630const unsigned int WatchDog::kWatchDogTimeoutSeconds;
631
Dave Allison70202782013-10-22 17:52:19 -0700632// Given a set of instruction features from the build, parse it. The
633// input 'str' is a comma separated list of feature names. Parse it and
634// return the InstructionSetFeatures object.
635static InstructionSetFeatures ParseFeatureList(std::string str) {
636 InstructionSetFeatures result;
637 typedef std::vector<std::string> FeatureList;
638 FeatureList features;
639 Split(str, ',', features);
640 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
641 std::string feature = Trim(*i);
642 if (feature == "default") {
643 // Nothing to do.
644 } else if (feature == "div") {
645 // Supports divide instruction.
646 result.SetHasDivideInstruction(true);
647 } else if (feature == "nodiv") {
648 // Turn off support for divide instruction.
649 result.SetHasDivideInstruction(false);
650 } else {
651 Usage("Unknown instruction set feature: '%s'", feature.c_str());
652 }
653 }
654 // others...
655 return result;
656}
657
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658static int dex2oat(int argc, char** argv) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800659 TimingLogger timings("compiler", false, false);
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000660 CumulativeLogger compiler_phases_timings("compilation times");
Brian Carlstrom45602482013-07-21 22:07:55 -0700661
Brian Carlstrom7940e442013-07-12 13:46:57 -0700662 InitLogging(argv);
663
664 // Skip over argv[0].
665 argv++;
666 argc--;
667
668 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700669 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700670 }
671
672 std::vector<const char*> dex_filenames;
673 std::vector<const char*> dex_locations;
674 int zip_fd = -1;
675 std::string zip_location;
676 std::string oat_filename;
677 std::string oat_symbols;
678 std::string oat_location;
679 int oat_fd = -1;
680 std::string bitcode_filename;
681 const char* image_classes_zip_filename = NULL;
682 const char* image_classes_filename = NULL;
683 std::string image_filename;
684 std::string boot_image_filename;
685 uintptr_t image_base = 0;
686 UniquePtr<std::string> host_prefix;
687 std::string android_root;
688 std::vector<const char*> runtime_args;
689 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000690 CompilerBackend::Kind compiler_backend = kUsePortableCompiler
691 ? CompilerBackend::kPortable
692 : CompilerBackend::kQuick;
Dave Allison70202782013-10-22 17:52:19 -0700693
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800694 // Take the default set of instruction features from the build.
Dave Allison70202782013-10-22 17:52:19 -0700695 InstructionSetFeatures instruction_set_features =
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800696 ParseFeatureList(STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES));
Dave Allison70202782013-10-22 17:52:19 -0700697
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698#if defined(__arm__)
699 InstructionSet instruction_set = kThumb2;
700#elif defined(__i386__)
701 InstructionSet instruction_set = kX86;
702#elif defined(__mips__)
703 InstructionSet instruction_set = kMips;
704#else
Ian Rogersef7d42f2014-01-06 12:55:46 -0800705 InstructionSet instruction_set = kNone;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706#endif
Dave Allison70202782013-10-22 17:52:19 -0700707
708
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700710 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700711 bool dump_timing = false;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000712 bool dump_passes = false;
Ian Rogers46398602013-08-20 07:50:36 -0700713 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714 bool watch_dog_enabled = !kIsTargetBuild;
715
716
717 for (int i = 0; i < argc; i++) {
718 const StringPiece option(argv[i]);
719 bool log_options = false;
720 if (log_options) {
721 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
722 }
723 if (option.starts_with("--dex-file=")) {
724 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
725 } else if (option.starts_with("--dex-location=")) {
726 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
727 } else if (option.starts_with("--zip-fd=")) {
728 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
729 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700730 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700731 }
732 } else if (option.starts_with("--zip-location=")) {
733 zip_location = option.substr(strlen("--zip-location=")).data();
734 } else if (option.starts_with("--oat-file=")) {
735 oat_filename = option.substr(strlen("--oat-file=")).data();
736 } else if (option.starts_with("--oat-symbols=")) {
737 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
738 } else if (option.starts_with("--oat-fd=")) {
739 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
740 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700741 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700742 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700743 } else if (option == "--watch-dog") {
744 watch_dog_enabled = true;
745 } else if (option == "--no-watch-dog") {
746 watch_dog_enabled = false;
747 } else if (option.starts_with("-j")) {
748 const char* thread_count_str = option.substr(strlen("-j")).data();
749 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700750 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700751 }
752 } else if (option.starts_with("--oat-location=")) {
753 oat_location = option.substr(strlen("--oat-location=")).data();
754 } else if (option.starts_with("--bitcode=")) {
755 bitcode_filename = option.substr(strlen("--bitcode=")).data();
756 } else if (option.starts_with("--image=")) {
757 image_filename = option.substr(strlen("--image=")).data();
758 } else if (option.starts_with("--image-classes=")) {
759 image_classes_filename = option.substr(strlen("--image-classes=")).data();
760 } else if (option.starts_with("--image-classes-zip=")) {
761 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
762 } else if (option.starts_with("--base=")) {
763 const char* image_base_str = option.substr(strlen("--base=")).data();
764 char* end;
765 image_base = strtoul(image_base_str, &end, 16);
766 if (end == image_base_str || *end != '\0') {
767 Usage("Failed to parse hexadecimal value for option %s", option.data());
768 }
769 } else if (option.starts_with("--boot-image=")) {
770 boot_image_filename = option.substr(strlen("--boot-image=")).data();
771 } else if (option.starts_with("--host-prefix=")) {
772 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
773 } else if (option.starts_with("--android-root=")) {
774 android_root = option.substr(strlen("--android-root=")).data();
775 } else if (option.starts_with("--instruction-set=")) {
776 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
777 if (instruction_set_str == "arm") {
778 instruction_set = kThumb2;
779 } else if (instruction_set_str == "mips") {
780 instruction_set = kMips;
781 } else if (instruction_set_str == "x86") {
782 instruction_set = kX86;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800783 } else if (instruction_set_str == "x86_64") {
784 instruction_set = kX86_64;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700785 }
Dave Allison70202782013-10-22 17:52:19 -0700786 } else if (option.starts_with("--instruction-set-features=")) {
787 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
788 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700789 } else if (option.starts_with("--compiler-backend=")) {
790 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
791 if (backend_str == "Quick") {
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000792 compiler_backend = CompilerBackend::kQuick;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700793 } else if (backend_str == "Portable") {
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000794 compiler_backend = CompilerBackend::kPortable;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700795 }
796 } else if (option == "--host") {
797 is_host = true;
798 } else if (option == "--runtime-arg") {
799 if (++i >= argc) {
800 Usage("Missing required argument for --runtime-arg");
801 }
802 if (log_options) {
803 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
804 }
805 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700806 } else if (option == "--dump-timing") {
807 dump_timing = true;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000808 } else if (option == "--dump-passes") {
809 dump_passes = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700810 } else if (option == "--dump-stats") {
811 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700812 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700813 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700814 }
815 }
816
817 if (oat_filename.empty() && oat_fd == -1) {
818 Usage("Output must be supplied with either --oat-file or --oat-fd");
819 }
820
821 if (!oat_filename.empty() && oat_fd != -1) {
822 Usage("--oat-file should not be used with --oat-fd");
823 }
824
825 if (!oat_symbols.empty() && oat_fd != -1) {
826 Usage("--oat-symbols should not be used with --oat-fd");
827 }
828
829 if (!oat_symbols.empty() && is_host) {
830 Usage("--oat-symbols should not be used with --host");
831 }
832
833 if (oat_fd != -1 && !image_filename.empty()) {
834 Usage("--oat-fd should not be used with --image");
835 }
836
837 if (host_prefix.get() == NULL) {
838 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
839 if (android_product_out != NULL) {
840 host_prefix.reset(new std::string(android_product_out));
841 }
842 }
843
844 if (android_root.empty()) {
845 const char* android_root_env_var = getenv("ANDROID_ROOT");
846 if (android_root_env_var == NULL) {
847 Usage("--android-root unspecified and ANDROID_ROOT not set");
848 }
849 android_root += android_root_env_var;
850 }
851
852 bool image = (!image_filename.empty());
853 if (!image && boot_image_filename.empty()) {
854 if (host_prefix.get() == NULL) {
855 boot_image_filename += GetAndroidRoot();
856 } else {
857 boot_image_filename += *host_prefix.get();
858 boot_image_filename += "/system";
859 }
860 boot_image_filename += "/framework/boot.art";
861 }
862 std::string boot_image_option;
863 if (!boot_image_filename.empty()) {
864 boot_image_option += "-Ximage:";
865 boot_image_option += boot_image_filename;
866 }
867
868 if (image_classes_filename != NULL && !image) {
869 Usage("--image-classes should only be used with --image");
870 }
871
872 if (image_classes_filename != NULL && !boot_image_option.empty()) {
873 Usage("--image-classes should not be used with --boot-image");
874 }
875
876 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
877 Usage("--image-classes-zip should be used with --image-classes");
878 }
879
880 if (dex_filenames.empty() && zip_fd == -1) {
881 Usage("Input must be supplied with either --dex-file or --zip-fd");
882 }
883
884 if (!dex_filenames.empty() && zip_fd != -1) {
885 Usage("--dex-file should not be used with --zip-fd");
886 }
887
888 if (!dex_filenames.empty() && !zip_location.empty()) {
889 Usage("--dex-file should not be used with --zip-location");
890 }
891
892 if (dex_locations.empty()) {
893 for (size_t i = 0; i < dex_filenames.size(); i++) {
894 dex_locations.push_back(dex_filenames[i]);
895 }
896 } else if (dex_locations.size() != dex_filenames.size()) {
897 Usage("--dex-location arguments do not match --dex-file arguments");
898 }
899
900 if (zip_fd != -1 && zip_location.empty()) {
901 Usage("--zip-location should be supplied with --zip-fd");
902 }
903
904 if (boot_image_option.empty()) {
905 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700906 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700907 }
908 }
909
910 std::string oat_stripped(oat_filename);
911 std::string oat_unstripped;
912 if (!oat_symbols.empty()) {
913 oat_unstripped += oat_symbols;
914 } else {
915 oat_unstripped += oat_filename;
916 }
917
918 // Done with usage checks, enable watchdog if requested
919 WatchDog watch_dog(watch_dog_enabled);
920
921 // Check early that the result of compilation can be written
922 UniquePtr<File> oat_file;
923 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
924 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700925 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 if (oat_location.empty()) {
927 oat_location = oat_filename;
928 }
929 } else {
930 oat_file.reset(new File(oat_fd, oat_location));
931 oat_file->DisableAutoClose();
932 }
933 if (oat_file.get() == NULL) {
934 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
935 return EXIT_FAILURE;
936 }
937 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
938 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
939 return EXIT_FAILURE;
940 }
941
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700942 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943 LOG(INFO) << "dex2oat: " << oat_location;
944
Ian Rogersf30f6da2013-08-28 17:33:30 -0700945 if (image) {
946 bool has_compiler_filter = false;
947 for (const char* r : runtime_args) {
948 if (strncmp(r, "-compiler-filter:", 17) == 0) {
949 has_compiler_filter = true;
950 break;
951 }
952 }
953 if (!has_compiler_filter) {
954 runtime_args.push_back("-compiler-filter:everything");
955 }
956 }
957
Brian Carlstrom7940e442013-07-12 13:46:57 -0700958 Runtime::Options options;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700959 std::vector<const DexFile*> boot_class_path;
960 if (boot_image_option.empty()) {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800961 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
962 if (failure_count > 0) {
963 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
964 return EXIT_FAILURE;
965 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
967 } else {
968 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
969 }
970 if (host_prefix.get() != NULL) {
971 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
972 }
973 for (size_t i = 0; i < runtime_args.size(); i++) {
974 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
975 }
976
Brian Carlstrom7940e442013-07-12 13:46:57 -0700977#ifdef ART_SEA_IR_MODE
978 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
979#endif
980
Brian Carlstrom7940e442013-07-12 13:46:57 -0700981 Dex2Oat* p_dex2oat;
Dave Allison70202782013-10-22 17:52:19 -0700982 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set,
983 instruction_set_features, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700984 LOG(ERROR) << "Failed to create dex2oat";
985 return EXIT_FAILURE;
986 }
987 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
988 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700989 // give it away now so that we don't starve GC.
990 Thread* self = Thread::Current();
991 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700992 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700993 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
994 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700996 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700997
998 // If --image-classes was specified, calculate the full list of classes to include in the image
999 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
1000 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001001 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001002 if (image_classes_zip_filename != NULL) {
1003 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001004 image_classes_filename,
1005 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 } else {
1007 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
1008 }
1009 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001010 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
1011 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001012 return EXIT_FAILURE;
1013 }
1014 }
1015
1016 std::vector<const DexFile*> dex_files;
1017 if (boot_image_option.empty()) {
1018 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1019 } else {
1020 if (dex_filenames.empty()) {
Ian Rogers740a11d2014-01-14 10:11:25 -08001021 ATRACE_BEGIN("Opening zip archive from file descriptor");
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001022 std::string error_msg;
1023 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
1024 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001026 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
1027 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028 return EXIT_FAILURE;
1029 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001030 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001031 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001032 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
1033 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001034 return EXIT_FAILURE;
1035 }
1036 dex_files.push_back(dex_file);
Ian Rogers740a11d2014-01-14 10:11:25 -08001037 ATRACE_END();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 } else {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001039 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
1040 if (failure_count > 0) {
1041 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1042 return EXIT_FAILURE;
1043 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001045
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001046 const bool kSaveDexInput = false;
1047 if (kSaveDexInput) {
1048 for (size_t i = 0; i < dex_files.size(); ++i) {
1049 const DexFile* dex_file = dex_files[i];
1050 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%d.dex", getpid(), i));
1051 UniquePtr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1052 if (tmp_file.get() == nullptr) {
1053 PLOG(ERROR) << "Failed to open file " << tmp_file_name << ". Try: adb shell chmod 777 /data/local/tmp";
1054 continue;
1055 }
1056 tmp_file->WriteFully(dex_file->Begin(), dex_file->Size());
1057 LOG(INFO) << "Wrote input to " << tmp_file_name;
1058 }
1059 }
1060
Brian Carlstromd76e0832013-08-29 15:17:42 -07001061 // Ensure opened dex files are writable for dex-to-dex transformations.
1062 for (const auto& dex_file : dex_files) {
1063 if (!dex_file->EnableWrite()) {
1064 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1065 }
1066 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001067 }
1068
buzbeea024a062013-07-31 10:47:37 -07001069 /*
1070 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
1071 * bother to check if we're doing the image.
1072 */
1073 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001074 size_t num_methods = 0;
1075 for (size_t i = 0; i != dex_files.size(); ++i) {
1076 const DexFile* dex_file = dex_files[i];
1077 CHECK(dex_file != NULL);
1078 num_methods += dex_file->NumMethodIds();
1079 }
buzbeea024a062013-07-31 10:47:37 -07001080 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
1081 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001082 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001083 }
1084 }
1085
1086 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
1087 host_prefix.get(),
1088 android_root,
1089 is_host,
1090 dex_files,
1091 oat_file.get(),
1092 bitcode_filename,
1093 image,
1094 image_classes,
1095 dump_stats,
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001096 dump_passes,
1097 timings,
1098 compiler_phases_timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099
1100 if (compiler.get() == NULL) {
1101 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1102 return EXIT_FAILURE;
1103 }
1104
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001105 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001106
1107 // Notes on the interleaving of creating the image and oat file to
1108 // ensure the references between the two are correct.
1109 //
1110 // Currently we have a memory layout that looks something like this:
1111 //
1112 // +--------------+
1113 // | image |
1114 // +--------------+
1115 // | boot oat |
1116 // +--------------+
1117 // | alloc spaces |
1118 // +--------------+
1119 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001120 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001121 //
1122 // 1. The image is expected to be loaded at an absolute address and
1123 // contains Objects with absolute pointers within the image.
1124 //
1125 // 2. There are absolute pointers from Methods in the image to their
1126 // code in the oat.
1127 //
1128 // 3. There are absolute pointers from the code in the oat to Methods
1129 // in the image.
1130 //
1131 // 4. There are absolute pointers from code in the oat to other code
1132 // in the oat.
1133 //
1134 // To get this all correct, we go through several steps.
1135 //
1136 // 1. We have already created that oat file above with
1137 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001138 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001139 // file). The Compiler returned by CreateOatFile provides
1140 // PatchInformation for references to oat code and Methods that need
1141 // to be update once we know where the oat file will be located
1142 // after the image.
1143 //
1144 // 2. We create the image file. It needs to know where the oat file
1145 // will be loaded after itself. Originally when oat file was simply
1146 // memory mapped so we could predict where its contents were based
1147 // on the file size. Now that it is an ELF file, we need to inspect
1148 // the ELF file to understand the in memory segment layout including
1149 // where the oat header is located within. ImageWriter's
1150 // PatchOatCodeAndMethods uses the PatchInformation from the
1151 // Compiler to touch up absolute references in the oat file.
1152 //
1153 // 3. We fixup the ELF program headers so that dlopen will try to
1154 // load the .so at the desired location at runtime by offsetting the
1155 // Elf32_Phdr.p_vaddr values by the desired base address.
1156 //
1157 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001158 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1160 image_base,
1161 oat_unstripped,
1162 oat_location,
1163 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001164 if (!image_creation_success) {
1165 return EXIT_FAILURE;
1166 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001167 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001168 }
1169
1170 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001171 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001172 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001173 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001174 if (dump_passes) {
1175 LOG(INFO) << Dumpable<CumulativeLogger>(compiler.get()->GetTimingsLogger());
1176 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001177 return EXIT_SUCCESS;
1178 }
1179
1180 // If we don't want to strip in place, copy from unstripped location to stripped location.
1181 // We need to strip after image creation because FixupElf needs to use .strtab.
1182 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001183 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001184 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001185 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1186 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001187 size_t buffer_size = 8192;
1188 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1189 while (true) {
1190 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1191 if (bytes_read <= 0) {
1192 break;
1193 }
1194 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1195 CHECK(write_ok);
1196 }
1197 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001198 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001199 }
1200
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001201#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001202 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001203 // Strip unneeded sections for target
1204 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1205 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001206 std::string error_msg;
1207 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001208
Brian Carlstrom7940e442013-07-12 13:46:57 -07001209
1210 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001211 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001212#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001213
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001214 timings.EndSplit();
1215
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001216 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001217 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001218 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001219 if (dump_passes) {
1220 LOG(INFO) << Dumpable<CumulativeLogger>(compiler_phases_timings);
1221 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001222
1223 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1224 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1225 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
Brian Carlstrom65c23bb2014-02-01 22:12:39 -08001226 dex2oat->LogCompletionTime();
Ian Rogers2672a9f2013-09-05 17:24:22 -07001227 exit(EXIT_SUCCESS);
1228 }
1229
Brian Carlstrom7940e442013-07-12 13:46:57 -07001230 return EXIT_SUCCESS;
1231}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001232} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001233
1234int main(int argc, char** argv) {
1235 return art::dex2oat(argc, argv);
1236}