blob: 7f8847154adad15d7273c9c1b1b92e91c6527a61 [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 Geoffrayf5df8972014-02-14 18:37:08 +0000290 if (compiler_backend_ == CompilerBackend::kPortable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 driver->SetBitcodeFileName(bitcode_filename);
292 }
293
Brian Carlstrom45602482013-07-21 22:07:55 -0700294 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700295
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700296 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297 std::string image_file_location;
298 uint32_t image_file_location_oat_checksum = 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800299 uintptr_t image_file_location_oat_data_begin = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300 if (!driver->IsImage()) {
Ian Rogersca368cb2013-11-15 15:52:08 -0800301 TimingLogger::ScopedSplit split("Loading image checksum", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700302 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
303 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
304 image_file_location_oat_data_begin =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800305 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700306 image_file_location = image_space->GetImageFilename();
307 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
308 image_file_location = image_file_location.substr(host_prefix->size());
309 }
310 }
311
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700312 OatWriter oat_writer(dex_files,
313 image_file_location_oat_checksum,
314 image_file_location_oat_data_begin,
315 image_file_location,
Ian Rogersca368cb2013-11-15 15:52:08 -0800316 driver.get(),
317 &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700318
Ian Rogersca368cb2013-11-15 15:52:08 -0800319 TimingLogger::ScopedSplit split("Writing ELF", &timings);
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700320 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700321 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
322 return NULL;
323 }
324
325 return driver.release();
326 }
327
328 bool CreateImageFile(const std::string& image_filename,
329 uintptr_t image_base,
330 const std::string& oat_filename,
331 const std::string& oat_location,
332 const CompilerDriver& compiler)
333 LOCKS_EXCLUDED(Locks::mutator_lock_) {
334 uintptr_t oat_data_begin;
335 {
336 // ImageWriter is scoped so it can free memory before doing FixupElf
337 ImageWriter image_writer(compiler);
338 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
339 LOG(ERROR) << "Failed to create image file " << image_filename;
340 return false;
341 }
342 oat_data_begin = image_writer.GetOatDataBegin();
343 }
344
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700345 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700346 if (oat_file.get() == NULL) {
347 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
348 return false;
349 }
350 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
351 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
352 return false;
353 }
354 return true;
355 }
356
357 private:
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000358 class Dex2OatCompilerCallbacks : public CompilerCallbacks {
359 public:
Vladimir Markoc7f83202014-01-24 17:55:18 +0000360 Dex2OatCompilerCallbacks(VerificationResults* verification_results,
Vladimir Marko5816ed42013-11-27 17:04:20 +0000361 DexFileToMethodInlinerMap* method_inliner_map)
Vladimir Markoc7f83202014-01-24 17:55:18 +0000362 : verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000363 method_inliner_map_(method_inliner_map) { }
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000364 virtual ~Dex2OatCompilerCallbacks() { }
365
366 virtual bool MethodVerified(verifier::MethodVerifier* verifier)
367 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Vladimir Markoc7f83202014-01-24 17:55:18 +0000368 bool result = verification_results_->ProcessVerifiedMethod(verifier);
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000369 if (result) {
Vladimir Marko5816ed42013-11-27 17:04:20 +0000370 MethodReference ref = verifier->GetMethodReference();
371 method_inliner_map_->GetMethodInliner(ref.dex_file)
Vladimir Marko2bc47802014-02-10 09:43:07 +0000372 ->AnalyseMethodCode(verifier);
Vladimir Marko5816ed42013-11-27 17:04:20 +0000373 }
374 return result;
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000375 }
376 virtual void ClassRejected(ClassReference ref) {
Vladimir Markoc7f83202014-01-24 17:55:18 +0000377 verification_results_->AddRejectedClass(ref);
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000378 }
379
380 private:
Vladimir Markoc7f83202014-01-24 17:55:18 +0000381 VerificationResults* verification_results_;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000382 DexFileToMethodInlinerMap* method_inliner_map_;
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000383 };
384
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000385 explicit Dex2Oat(CompilerBackend::Kind compiler_backend,
Brian Carlstrom45602482013-07-21 22:07:55 -0700386 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700387 InstructionSetFeatures instruction_set_features,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700388 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389 : compiler_backend_(compiler_backend),
390 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700391 instruction_set_features_(instruction_set_features),
Vladimir Markoc7f83202014-01-24 17:55:18 +0000392 verification_results_(new VerificationResults),
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000393 method_inliner_map_(new DexFileToMethodInlinerMap),
Vladimir Markoc7f83202014-01-24 17:55:18 +0000394 callbacks_(verification_results_.get(), method_inliner_map_.get()),
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000395 runtime_(nullptr),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 start_ns_(NanoTime()) {
398 }
399
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000400 bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000402 options.push_back(
403 std::make_pair("compilercallbacks", static_cast<CompilerCallbacks*>(&callbacks_)));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 if (!Runtime::Create(options, false)) {
405 LOG(ERROR) << "Failed to create runtime";
406 return false;
407 }
408 Runtime* runtime = Runtime::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700409 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
410 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
411 if (!runtime->HasCalleeSaveMethod(type)) {
412 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
413 }
414 }
415 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000416 runtime_ = runtime;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700417 return true;
418 }
419
420 // Appends to dex_files any elements of class_path that it doesn't already
421 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700422 static void OpenClassPathFiles(const std::string& class_path,
423 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 std::vector<std::string> parsed;
425 Split(class_path, ':', parsed);
426 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
427 ScopedObjectAccess soa(Thread::Current());
428 for (size_t i = 0; i < parsed.size(); ++i) {
429 if (DexFilesContains(dex_files, parsed[i])) {
430 continue;
431 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432 std::string error_msg;
433 const DexFile* dex_file = DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700434 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700435 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 } else {
437 dex_files.push_back(dex_file);
438 }
439 }
440 }
441
442 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700443 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
444 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445 for (size_t i = 0; i < dex_files.size(); ++i) {
446 if (dex_files[i]->GetLocation() == location) {
447 return true;
448 }
449 }
450 return false;
451 }
452
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000453 const CompilerBackend::Kind compiler_backend_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454
455 const InstructionSet instruction_set_;
Dave Allison70202782013-10-22 17:52:19 -0700456 const InstructionSetFeatures instruction_set_features_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457
Vladimir Markoc7f83202014-01-24 17:55:18 +0000458 UniquePtr<VerificationResults> verification_results_;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000459 UniquePtr<DexFileToMethodInlinerMap> method_inliner_map_;
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000460 Dex2OatCompilerCallbacks callbacks_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461 Runtime* runtime_;
462 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463 uint64_t start_ns_;
464
465 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
466};
467
468static bool ParseInt(const char* in, int* out) {
469 char* end;
470 int result = strtol(in, &end, 10);
471 if (in == end || *end != '\0') {
472 return false;
473 }
474 *out = result;
475 return true;
476}
477
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800478static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
479 const std::vector<const char*>& dex_locations,
480 std::vector<const DexFile*>& dex_files) {
481 size_t failure_count = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482 for (size_t i = 0; i < dex_filenames.size(); i++) {
483 const char* dex_filename = dex_filenames[i];
484 const char* dex_location = dex_locations[i];
Ian Rogers740a11d2014-01-14 10:11:25 -0800485 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700486 std::string error_msg;
Brian Carlstromd5aba592013-11-12 01:52:44 -0800487 if (!OS::FileExists(dex_filename)) {
488 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
489 continue;
490 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700491 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700492 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700493 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800494 ++failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700495 } else {
496 dex_files.push_back(dex_file);
497 }
Ian Rogers740a11d2014-01-14 10:11:25 -0800498 ATRACE_END();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700499 }
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800500 return failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700501}
502
503// The primary goal of the watchdog is to prevent stuck build servers
504// during development when fatal aborts lead to a cascade of failures
505// that result in a deadlock.
506class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700507// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
508#undef CHECK_PTHREAD_CALL
509#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
510 do { \
511 int rc = call args; \
512 if (rc != 0) { \
513 errno = rc; \
514 std::string message(# call); \
515 message += " failed for "; \
516 message += reason; \
517 Fatal(message); \
518 } \
519 } while (false)
520
521 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700522 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700523 is_watch_dog_enabled_ = is_watch_dog_enabled;
524 if (!is_watch_dog_enabled_) {
525 return;
526 }
527 shutting_down_ = false;
528 const char* reason = "dex2oat watch dog thread startup";
529 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
530 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
531 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
532 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
533 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
534 }
535 ~WatchDog() {
536 if (!is_watch_dog_enabled_) {
537 return;
538 }
539 const char* reason = "dex2oat watch dog thread shutdown";
540 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
541 shutting_down_ = true;
542 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
543 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
544
545 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
546
547 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
548 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
549 }
550
551 private:
552 static void* CallBack(void* arg) {
553 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
554 ::art::SetThreadName("dex2oat watch dog");
555 self->Wait();
556 return NULL;
557 }
558
559 static void Message(char severity, const std::string& message) {
560 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
561 // cases.
562 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
563 kIsDebugBuild ? "d" : "",
564 severity,
565 getpid(),
566 GetTid(),
567 message.c_str());
568 }
569
570 static void Warn(const std::string& message) {
571 Message('W', message);
572 }
573
574 static void Fatal(const std::string& message) {
575 Message('F', message);
576 exit(1);
577 }
578
579 void Wait() {
580 bool warning = true;
581 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
582 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
583 // large.
584 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
585 timespec warning_ts;
586 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
587 timespec timeout_ts;
588 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
589 const char* reason = "dex2oat watch dog thread waiting";
590 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
591 while (!shutting_down_) {
592 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
593 warning ? &warning_ts
594 : &timeout_ts));
595 if (rc == ETIMEDOUT) {
596 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
597 warning ? kWatchDogWarningSeconds
598 : kWatchDogTimeoutSeconds));
599 if (warning) {
600 Warn(message.c_str());
601 warning = false;
602 } else {
603 Fatal(message.c_str());
604 }
605 } else if (rc != 0) {
606 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
607 strerror(errno)));
608 Fatal(message.c_str());
609 }
610 }
611 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
612 }
613
614 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
615#if ART_USE_PORTABLE_COMPILER
616 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
617 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
618#else
619 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
620 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
621#endif
622
623 bool is_watch_dog_enabled_;
624 bool shutting_down_;
625 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
626 pthread_mutex_t mutex_;
627 pthread_cond_t cond_;
628 pthread_attr_t attr_;
629 pthread_t pthread_;
630};
631const unsigned int WatchDog::kWatchDogWarningSeconds;
632const unsigned int WatchDog::kWatchDogTimeoutSeconds;
633
Dave Allison70202782013-10-22 17:52:19 -0700634// Given a set of instruction features from the build, parse it. The
635// input 'str' is a comma separated list of feature names. Parse it and
636// return the InstructionSetFeatures object.
637static InstructionSetFeatures ParseFeatureList(std::string str) {
638 InstructionSetFeatures result;
639 typedef std::vector<std::string> FeatureList;
640 FeatureList features;
641 Split(str, ',', features);
642 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
643 std::string feature = Trim(*i);
644 if (feature == "default") {
645 // Nothing to do.
646 } else if (feature == "div") {
647 // Supports divide instruction.
648 result.SetHasDivideInstruction(true);
649 } else if (feature == "nodiv") {
650 // Turn off support for divide instruction.
651 result.SetHasDivideInstruction(false);
652 } else {
653 Usage("Unknown instruction set feature: '%s'", feature.c_str());
654 }
655 }
656 // others...
657 return result;
658}
659
Brian Carlstrom7940e442013-07-12 13:46:57 -0700660static int dex2oat(int argc, char** argv) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800661 TimingLogger timings("compiler", false, false);
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000662 CumulativeLogger compiler_phases_timings("compilation times");
Brian Carlstrom45602482013-07-21 22:07:55 -0700663
Brian Carlstrom7940e442013-07-12 13:46:57 -0700664 InitLogging(argv);
665
666 // Skip over argv[0].
667 argv++;
668 argc--;
669
670 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700671 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700672 }
673
674 std::vector<const char*> dex_filenames;
675 std::vector<const char*> dex_locations;
676 int zip_fd = -1;
677 std::string zip_location;
678 std::string oat_filename;
679 std::string oat_symbols;
680 std::string oat_location;
681 int oat_fd = -1;
682 std::string bitcode_filename;
683 const char* image_classes_zip_filename = NULL;
684 const char* image_classes_filename = NULL;
685 std::string image_filename;
686 std::string boot_image_filename;
687 uintptr_t image_base = 0;
688 UniquePtr<std::string> host_prefix;
689 std::string android_root;
690 std::vector<const char*> runtime_args;
691 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000692 CompilerBackend::Kind compiler_backend = kUsePortableCompiler
693 ? CompilerBackend::kPortable
694 : CompilerBackend::kQuick;
Dave Allison70202782013-10-22 17:52:19 -0700695
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800696 // Take the default set of instruction features from the build.
Dave Allison70202782013-10-22 17:52:19 -0700697 InstructionSetFeatures instruction_set_features =
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800698 ParseFeatureList(STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES));
Dave Allison70202782013-10-22 17:52:19 -0700699
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700#if defined(__arm__)
701 InstructionSet instruction_set = kThumb2;
702#elif defined(__i386__)
703 InstructionSet instruction_set = kX86;
704#elif defined(__mips__)
705 InstructionSet instruction_set = kMips;
706#else
Ian Rogersef7d42f2014-01-06 12:55:46 -0800707 InstructionSet instruction_set = kNone;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700708#endif
Dave Allison70202782013-10-22 17:52:19 -0700709
710
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700712 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700713 bool dump_timing = false;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000714 bool dump_passes = false;
Ian Rogers46398602013-08-20 07:50:36 -0700715 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700716 bool watch_dog_enabled = !kIsTargetBuild;
717
718
719 for (int i = 0; i < argc; i++) {
720 const StringPiece option(argv[i]);
721 bool log_options = false;
722 if (log_options) {
723 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
724 }
725 if (option.starts_with("--dex-file=")) {
726 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
727 } else if (option.starts_with("--dex-location=")) {
728 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
729 } else if (option.starts_with("--zip-fd=")) {
730 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
731 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700732 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733 }
734 } else if (option.starts_with("--zip-location=")) {
735 zip_location = option.substr(strlen("--zip-location=")).data();
736 } else if (option.starts_with("--oat-file=")) {
737 oat_filename = option.substr(strlen("--oat-file=")).data();
738 } else if (option.starts_with("--oat-symbols=")) {
739 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
740 } else if (option.starts_with("--oat-fd=")) {
741 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
742 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700743 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700745 } else if (option == "--watch-dog") {
746 watch_dog_enabled = true;
747 } else if (option == "--no-watch-dog") {
748 watch_dog_enabled = false;
749 } else if (option.starts_with("-j")) {
750 const char* thread_count_str = option.substr(strlen("-j")).data();
751 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700752 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 }
754 } else if (option.starts_with("--oat-location=")) {
755 oat_location = option.substr(strlen("--oat-location=")).data();
756 } else if (option.starts_with("--bitcode=")) {
757 bitcode_filename = option.substr(strlen("--bitcode=")).data();
758 } else if (option.starts_with("--image=")) {
759 image_filename = option.substr(strlen("--image=")).data();
760 } else if (option.starts_with("--image-classes=")) {
761 image_classes_filename = option.substr(strlen("--image-classes=")).data();
762 } else if (option.starts_with("--image-classes-zip=")) {
763 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
764 } else if (option.starts_with("--base=")) {
765 const char* image_base_str = option.substr(strlen("--base=")).data();
766 char* end;
767 image_base = strtoul(image_base_str, &end, 16);
768 if (end == image_base_str || *end != '\0') {
769 Usage("Failed to parse hexadecimal value for option %s", option.data());
770 }
771 } else if (option.starts_with("--boot-image=")) {
772 boot_image_filename = option.substr(strlen("--boot-image=")).data();
773 } else if (option.starts_with("--host-prefix=")) {
774 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
775 } else if (option.starts_with("--android-root=")) {
776 android_root = option.substr(strlen("--android-root=")).data();
777 } else if (option.starts_with("--instruction-set=")) {
778 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
779 if (instruction_set_str == "arm") {
780 instruction_set = kThumb2;
781 } else if (instruction_set_str == "mips") {
782 instruction_set = kMips;
783 } else if (instruction_set_str == "x86") {
784 instruction_set = kX86;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800785 } else if (instruction_set_str == "x86_64") {
786 instruction_set = kX86_64;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 }
Dave Allison70202782013-10-22 17:52:19 -0700788 } else if (option.starts_with("--instruction-set-features=")) {
789 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
790 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700791 } else if (option.starts_with("--compiler-backend=")) {
792 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
793 if (backend_str == "Quick") {
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000794 compiler_backend = CompilerBackend::kQuick;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700795 } else if (backend_str == "Portable") {
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000796 compiler_backend = CompilerBackend::kPortable;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700797 }
798 } else if (option == "--host") {
799 is_host = true;
800 } else if (option == "--runtime-arg") {
801 if (++i >= argc) {
802 Usage("Missing required argument for --runtime-arg");
803 }
804 if (log_options) {
805 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
806 }
807 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700808 } else if (option == "--dump-timing") {
809 dump_timing = true;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000810 } else if (option == "--dump-passes") {
811 dump_passes = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700812 } else if (option == "--dump-stats") {
813 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700814 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700815 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700816 }
817 }
818
819 if (oat_filename.empty() && oat_fd == -1) {
820 Usage("Output must be supplied with either --oat-file or --oat-fd");
821 }
822
823 if (!oat_filename.empty() && oat_fd != -1) {
824 Usage("--oat-file should not be used with --oat-fd");
825 }
826
827 if (!oat_symbols.empty() && oat_fd != -1) {
828 Usage("--oat-symbols should not be used with --oat-fd");
829 }
830
831 if (!oat_symbols.empty() && is_host) {
832 Usage("--oat-symbols should not be used with --host");
833 }
834
835 if (oat_fd != -1 && !image_filename.empty()) {
836 Usage("--oat-fd should not be used with --image");
837 }
838
839 if (host_prefix.get() == NULL) {
840 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
841 if (android_product_out != NULL) {
842 host_prefix.reset(new std::string(android_product_out));
843 }
844 }
845
846 if (android_root.empty()) {
847 const char* android_root_env_var = getenv("ANDROID_ROOT");
848 if (android_root_env_var == NULL) {
849 Usage("--android-root unspecified and ANDROID_ROOT not set");
850 }
851 android_root += android_root_env_var;
852 }
853
854 bool image = (!image_filename.empty());
855 if (!image && boot_image_filename.empty()) {
856 if (host_prefix.get() == NULL) {
857 boot_image_filename += GetAndroidRoot();
858 } else {
859 boot_image_filename += *host_prefix.get();
860 boot_image_filename += "/system";
861 }
862 boot_image_filename += "/framework/boot.art";
863 }
864 std::string boot_image_option;
865 if (!boot_image_filename.empty()) {
866 boot_image_option += "-Ximage:";
867 boot_image_option += boot_image_filename;
868 }
869
870 if (image_classes_filename != NULL && !image) {
871 Usage("--image-classes should only be used with --image");
872 }
873
874 if (image_classes_filename != NULL && !boot_image_option.empty()) {
875 Usage("--image-classes should not be used with --boot-image");
876 }
877
878 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
879 Usage("--image-classes-zip should be used with --image-classes");
880 }
881
882 if (dex_filenames.empty() && zip_fd == -1) {
883 Usage("Input must be supplied with either --dex-file or --zip-fd");
884 }
885
886 if (!dex_filenames.empty() && zip_fd != -1) {
887 Usage("--dex-file should not be used with --zip-fd");
888 }
889
890 if (!dex_filenames.empty() && !zip_location.empty()) {
891 Usage("--dex-file should not be used with --zip-location");
892 }
893
894 if (dex_locations.empty()) {
895 for (size_t i = 0; i < dex_filenames.size(); i++) {
896 dex_locations.push_back(dex_filenames[i]);
897 }
898 } else if (dex_locations.size() != dex_filenames.size()) {
899 Usage("--dex-location arguments do not match --dex-file arguments");
900 }
901
902 if (zip_fd != -1 && zip_location.empty()) {
903 Usage("--zip-location should be supplied with --zip-fd");
904 }
905
906 if (boot_image_option.empty()) {
907 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700908 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700909 }
910 }
911
912 std::string oat_stripped(oat_filename);
913 std::string oat_unstripped;
914 if (!oat_symbols.empty()) {
915 oat_unstripped += oat_symbols;
916 } else {
917 oat_unstripped += oat_filename;
918 }
919
920 // Done with usage checks, enable watchdog if requested
921 WatchDog watch_dog(watch_dog_enabled);
922
923 // Check early that the result of compilation can be written
924 UniquePtr<File> oat_file;
925 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
926 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700927 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 if (oat_location.empty()) {
929 oat_location = oat_filename;
930 }
931 } else {
932 oat_file.reset(new File(oat_fd, oat_location));
933 oat_file->DisableAutoClose();
934 }
935 if (oat_file.get() == NULL) {
936 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
937 return EXIT_FAILURE;
938 }
939 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
940 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
941 return EXIT_FAILURE;
942 }
943
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700944 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700945 LOG(INFO) << "dex2oat: " << oat_location;
946
Ian Rogersf30f6da2013-08-28 17:33:30 -0700947 if (image) {
948 bool has_compiler_filter = false;
949 for (const char* r : runtime_args) {
950 if (strncmp(r, "-compiler-filter:", 17) == 0) {
951 has_compiler_filter = true;
952 break;
953 }
954 }
955 if (!has_compiler_filter) {
956 runtime_args.push_back("-compiler-filter:everything");
957 }
958 }
959
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 Runtime::Options options;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700961 std::vector<const DexFile*> boot_class_path;
962 if (boot_image_option.empty()) {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800963 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
964 if (failure_count > 0) {
965 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
966 return EXIT_FAILURE;
967 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
969 } else {
970 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
971 }
972 if (host_prefix.get() != NULL) {
973 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
974 }
975 for (size_t i = 0; i < runtime_args.size(); i++) {
976 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
977 }
978
Brian Carlstrom7940e442013-07-12 13:46:57 -0700979#ifdef ART_SEA_IR_MODE
980 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
981#endif
982
Brian Carlstrom7940e442013-07-12 13:46:57 -0700983 Dex2Oat* p_dex2oat;
Dave Allison70202782013-10-22 17:52:19 -0700984 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set,
985 instruction_set_features, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700986 LOG(ERROR) << "Failed to create dex2oat";
987 return EXIT_FAILURE;
988 }
989 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
990 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700991 // give it away now so that we don't starve GC.
992 Thread* self = Thread::Current();
993 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700994 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700995 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
996 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700997 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700998 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700999
1000 // If --image-classes was specified, calculate the full list of classes to include in the image
1001 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
1002 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001003 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 if (image_classes_zip_filename != NULL) {
1005 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001006 image_classes_filename,
1007 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001008 } else {
1009 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
1010 }
1011 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001012 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
1013 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 return EXIT_FAILURE;
1015 }
1016 }
1017
1018 std::vector<const DexFile*> dex_files;
1019 if (boot_image_option.empty()) {
1020 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1021 } else {
1022 if (dex_filenames.empty()) {
Ian Rogers740a11d2014-01-14 10:11:25 -08001023 ATRACE_BEGIN("Opening zip archive from file descriptor");
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001024 std::string error_msg;
1025 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
1026 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001028 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
1029 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030 return EXIT_FAILURE;
1031 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001032 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001033 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001034 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
1035 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001036 return EXIT_FAILURE;
1037 }
1038 dex_files.push_back(dex_file);
Ian Rogers740a11d2014-01-14 10:11:25 -08001039 ATRACE_END();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001040 } else {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001041 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
1042 if (failure_count > 0) {
1043 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1044 return EXIT_FAILURE;
1045 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001047
1048 // Ensure opened dex files are writable for dex-to-dex transformations.
1049 for (const auto& dex_file : dex_files) {
1050 if (!dex_file->EnableWrite()) {
1051 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1052 }
1053 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054 }
1055
buzbeea024a062013-07-31 10:47:37 -07001056 /*
1057 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
1058 * bother to check if we're doing the image.
1059 */
1060 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001061 size_t num_methods = 0;
1062 for (size_t i = 0; i != dex_files.size(); ++i) {
1063 const DexFile* dex_file = dex_files[i];
1064 CHECK(dex_file != NULL);
1065 num_methods += dex_file->NumMethodIds();
1066 }
buzbeea024a062013-07-31 10:47:37 -07001067 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
1068 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001069 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001070 }
1071 }
1072
1073 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
1074 host_prefix.get(),
1075 android_root,
1076 is_host,
1077 dex_files,
1078 oat_file.get(),
1079 bitcode_filename,
1080 image,
1081 image_classes,
1082 dump_stats,
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001083 dump_passes,
1084 timings,
1085 compiler_phases_timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001086
1087 if (compiler.get() == NULL) {
1088 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1089 return EXIT_FAILURE;
1090 }
1091
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001092 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001093
1094 // Notes on the interleaving of creating the image and oat file to
1095 // ensure the references between the two are correct.
1096 //
1097 // Currently we have a memory layout that looks something like this:
1098 //
1099 // +--------------+
1100 // | image |
1101 // +--------------+
1102 // | boot oat |
1103 // +--------------+
1104 // | alloc spaces |
1105 // +--------------+
1106 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001107 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001108 //
1109 // 1. The image is expected to be loaded at an absolute address and
1110 // contains Objects with absolute pointers within the image.
1111 //
1112 // 2. There are absolute pointers from Methods in the image to their
1113 // code in the oat.
1114 //
1115 // 3. There are absolute pointers from the code in the oat to Methods
1116 // in the image.
1117 //
1118 // 4. There are absolute pointers from code in the oat to other code
1119 // in the oat.
1120 //
1121 // To get this all correct, we go through several steps.
1122 //
1123 // 1. We have already created that oat file above with
1124 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001125 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001126 // file). The Compiler returned by CreateOatFile provides
1127 // PatchInformation for references to oat code and Methods that need
1128 // to be update once we know where the oat file will be located
1129 // after the image.
1130 //
1131 // 2. We create the image file. It needs to know where the oat file
1132 // will be loaded after itself. Originally when oat file was simply
1133 // memory mapped so we could predict where its contents were based
1134 // on the file size. Now that it is an ELF file, we need to inspect
1135 // the ELF file to understand the in memory segment layout including
1136 // where the oat header is located within. ImageWriter's
1137 // PatchOatCodeAndMethods uses the PatchInformation from the
1138 // Compiler to touch up absolute references in the oat file.
1139 //
1140 // 3. We fixup the ELF program headers so that dlopen will try to
1141 // load the .so at the desired location at runtime by offsetting the
1142 // Elf32_Phdr.p_vaddr values by the desired base address.
1143 //
1144 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001145 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001146 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1147 image_base,
1148 oat_unstripped,
1149 oat_location,
1150 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001151 if (!image_creation_success) {
1152 return EXIT_FAILURE;
1153 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001154 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155 }
1156
1157 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001158 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001159 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001160 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001161 if (dump_passes) {
1162 LOG(INFO) << Dumpable<CumulativeLogger>(compiler.get()->GetTimingsLogger());
1163 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001164 return EXIT_SUCCESS;
1165 }
1166
1167 // If we don't want to strip in place, copy from unstripped location to stripped location.
1168 // We need to strip after image creation because FixupElf needs to use .strtab.
1169 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001170 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001171 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001172 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1173 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001174 size_t buffer_size = 8192;
1175 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1176 while (true) {
1177 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1178 if (bytes_read <= 0) {
1179 break;
1180 }
1181 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1182 CHECK(write_ok);
1183 }
1184 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001185 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001186 }
1187
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001188#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001189 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001190 // Strip unneeded sections for target
1191 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1192 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001193 std::string error_msg;
1194 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001195
Brian Carlstrom7940e442013-07-12 13:46:57 -07001196
1197 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001198 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001199#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001200
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001201 timings.EndSplit();
1202
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001203 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001204 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001205 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001206 if (dump_passes) {
1207 LOG(INFO) << Dumpable<CumulativeLogger>(compiler_phases_timings);
1208 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001209
1210 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1211 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1212 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
Brian Carlstrom65c23bb2014-02-01 22:12:39 -08001213 dex2oat->LogCompletionTime();
Ian Rogers2672a9f2013-09-05 17:24:22 -07001214 exit(EXIT_SUCCESS);
1215 }
1216
Brian Carlstrom7940e442013-07-12 13:46:57 -07001217 return EXIT_SUCCESS;
1218}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001219} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001220
1221int main(int argc, char** argv) {
1222 return art::dex2oat(argc, argv);
1223}