blob: 14723376152551a866fb0f6f8aaed3abc0f81089 [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"
33#include "dex_file-inl.h"
34#include "driver/compiler_driver.h"
35#include "elf_fixup.h"
36#include "elf_stripper.h"
37#include "gc/space/image_space.h"
38#include "gc/space/space-inl.h"
39#include "image_writer.h"
40#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070041#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "mirror/class-inl.h"
43#include "mirror/class_loader.h"
44#include "mirror/object-inl.h"
45#include "mirror/object_array-inl.h"
46#include "oat_writer.h"
47#include "object_utils.h"
48#include "os.h"
49#include "runtime.h"
50#include "ScopedLocalRef.h"
51#include "scoped_thread_state_change.h"
52#include "sirt_ref.h"
53#include "vector_output_stream.h"
54#include "well_known_classes.h"
55#include "zip_archive.h"
56
57namespace art {
58
59static void UsageErrorV(const char* fmt, va_list ap) {
60 std::string error;
61 StringAppendV(&error, fmt, ap);
62 LOG(ERROR) << error;
63}
64
65static void UsageError(const char* fmt, ...) {
66 va_list ap;
67 va_start(ap, fmt);
68 UsageErrorV(fmt, ap);
69 va_end(ap);
70}
71
72static void Usage(const char* fmt, ...) {
73 va_list ap;
74 va_start(ap, fmt);
75 UsageErrorV(fmt, ap);
76 va_end(ap);
77
78 UsageError("Usage: dex2oat [options]...");
79 UsageError("");
80 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
81 UsageError(" Example: --dex-file=/system/framework/core.jar");
82 UsageError("");
83 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
84 UsageError(" containing a classes.dex file to compile.");
85 UsageError(" Example: --zip-fd=5");
86 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -070087 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
88 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -070089 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
90 UsageError("");
91 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
92 UsageError(" Example: --oat-file=/system/framework/boot.oat");
93 UsageError("");
94 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
95 UsageError(" Example: --oat-file=/system/framework/boot.oat");
96 UsageError("");
97 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
98 UsageError(" to the file descriptor specified by --oat-fd.");
99 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
100 UsageError("");
101 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
102 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
103 UsageError("");
104 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
105 UsageError(" Example: --bitcode=/system/framework/boot.bc");
106 UsageError("");
107 UsageError(" --image=<file.art>: specifies the output image filename.");
108 UsageError(" Example: --image=/system/framework/boot.art");
109 UsageError("");
110 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
111 UsageError(" Example: --image=frameworks/base/preloaded-classes");
112 UsageError("");
113 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
114 UsageError(" Example: --base=0x50000000");
115 UsageError("");
116 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
117 UsageError(" Example: --boot-image=/system/framework/boot.art");
118 UsageError(" Default: <host-prefix>/system/framework/boot.art");
119 UsageError("");
120 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
121 UsageError(" cross compilation.");
122 UsageError(" Example: --host-prefix=out/target/product/crespo");
123 UsageError(" Default: $ANDROID_PRODUCT_OUT");
124 UsageError("");
125 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
126 UsageError(" Example: --android-root=out/host/linux-x86");
127 UsageError(" Default: $ANDROID_ROOT");
128 UsageError("");
129 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
130 UsageError(" set.");
131 UsageError(" Example: --instruction-set=x86");
132 UsageError(" Default: arm");
133 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700134 UsageError(" --instruction-set-features=...,: Specify instruction set features");
135 UsageError(" Example: --instruction-set-features=div");
136 UsageError(" Default: default");
137 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700138 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
139 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700140 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700141 UsageError(" Default: Quick");
142 UsageError("");
143 UsageError(" --host: used with Portable backend to link against host runtime libraries");
144 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700145 UsageError(" --dump-timing: display a breakdown of where time was spent");
146 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
148 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
149 UsageError(" Use a separate --runtime-arg switch for each argument.");
150 UsageError(" Example: --runtime-arg -Xms256m");
151 UsageError("");
152 std::cerr << "See log for usage error information\n";
153 exit(EXIT_FAILURE);
154}
155
156class Dex2Oat {
157 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700158 static bool Create(Dex2Oat** p_dex2oat,
159 Runtime::Options& options,
160 CompilerBackend compiler_backend,
161 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700162 InstructionSetFeatures instruction_set_features,
Brian Carlstrom45602482013-07-21 22:07:55 -0700163 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
165 if (!CreateRuntime(options, instruction_set)) {
166 *p_dex2oat = NULL;
167 return false;
168 }
Dave Allison70202782013-10-22 17:52:19 -0700169 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set,
170 instruction_set_features, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 return true;
172 }
173
174 ~Dex2Oat() {
175 delete runtime_;
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700176 VLOG(compiler) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700177 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 }
179
180
Brian Carlstrom45602482013-07-21 22:07:55 -0700181 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700182 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Brian Carlstrom45602482013-07-21 22:07:55 -0700183 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
184 std::ifstream::in));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 if (image_classes_file.get() == NULL) {
186 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
187 return NULL;
188 }
189 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
190 image_classes_file->close();
191 return result.release();
192 }
193
194 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
195 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
196 while (image_classes_stream.good()) {
197 std::string dot;
198 std::getline(image_classes_stream, dot);
199 if (StartsWith(dot, "#") || dot.empty()) {
200 continue;
201 }
202 std::string descriptor(DotToDescriptor(dot.c_str()));
203 image_classes->insert(descriptor);
204 }
205 return image_classes.release();
206 }
207
Brian Carlstrom45602482013-07-21 22:07:55 -0700208 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700209 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const char* zip_filename,
210 const char* image_classes_filename,
211 std::string* error_msg) {
212 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 if (zip_archive.get() == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 return NULL;
215 }
216 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
217 if (zip_entry.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700218 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
219 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 return NULL;
221 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700222 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename,
223 error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 if (image_classes_file.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700225 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
226 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 return NULL;
228 }
229 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
230 image_classes_file->Size());
231 std::istringstream image_classes_stream(image_classes_string);
232 return ReadImageClasses(image_classes_stream);
233 }
234
235 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
236 const std::string* host_prefix,
237 const std::string& android_root,
238 bool is_host,
239 const std::vector<const DexFile*>& dex_files,
240 File* oat_file,
241 const std::string& bitcode_filename,
242 bool image,
243 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
244 bool dump_stats,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700245 base::TimingLogger& timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 // SirtRef and ClassLoader creation needs to come after Runtime::Create
247 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700248 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700249 if (!boot_image_option.empty()) {
250 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
251 std::vector<const DexFile*> class_path_files(dex_files);
252 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700253 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 for (size_t i = 0; i < class_path_files.size(); i++) {
255 class_linker->RegisterDexFile(*class_path_files[i]);
256 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
258 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
259 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
260 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
261 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
262 }
263
264 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
265 instruction_set_,
Dave Allison70202782013-10-22 17:52:19 -0700266 instruction_set_features_,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700267 image,
268 image_classes.release(),
269 thread_count_,
Brian Carlstrom45602482013-07-21 22:07:55 -0700270 dump_stats));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271
272 if (compiler_backend_ == kPortable) {
273 driver->SetBitcodeFileName(bitcode_filename);
274 }
275
Brian Carlstrom45602482013-07-21 22:07:55 -0700276 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700278 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 std::string image_file_location;
280 uint32_t image_file_location_oat_checksum = 0;
281 uint32_t image_file_location_oat_data_begin = 0;
282 if (!driver->IsImage()) {
283 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
284 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
285 image_file_location_oat_data_begin =
286 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
287 image_file_location = image_space->GetImageFilename();
288 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
289 image_file_location = image_file_location.substr(host_prefix->size());
290 }
291 }
292
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700293 OatWriter oat_writer(dex_files,
294 image_file_location_oat_checksum,
295 image_file_location_oat_data_begin,
296 image_file_location,
297 driver.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700299 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
301 return NULL;
302 }
303
304 return driver.release();
305 }
306
307 bool CreateImageFile(const std::string& image_filename,
308 uintptr_t image_base,
309 const std::string& oat_filename,
310 const std::string& oat_location,
311 const CompilerDriver& compiler)
312 LOCKS_EXCLUDED(Locks::mutator_lock_) {
313 uintptr_t oat_data_begin;
314 {
315 // ImageWriter is scoped so it can free memory before doing FixupElf
316 ImageWriter image_writer(compiler);
317 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
318 LOG(ERROR) << "Failed to create image file " << image_filename;
319 return false;
320 }
321 oat_data_begin = image_writer.GetOatDataBegin();
322 }
323
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700324 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700325 if (oat_file.get() == NULL) {
326 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
327 return false;
328 }
329 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
330 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
331 return false;
332 }
333 return true;
334 }
335
336 private:
Brian Carlstrom45602482013-07-21 22:07:55 -0700337 explicit Dex2Oat(Runtime* runtime,
338 CompilerBackend compiler_backend,
339 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700340 InstructionSetFeatures instruction_set_features,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700341 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 : compiler_backend_(compiler_backend),
343 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700344 instruction_set_features_(instruction_set_features),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 runtime_(runtime),
346 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 start_ns_(NanoTime()) {
348 }
349
350 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
351 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
352 if (!Runtime::Create(options, false)) {
353 LOG(ERROR) << "Failed to create runtime";
354 return false;
355 }
356 Runtime* runtime = Runtime::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700357 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
358 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
359 if (!runtime->HasCalleeSaveMethod(type)) {
360 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
361 }
362 }
363 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
364 return true;
365 }
366
367 // Appends to dex_files any elements of class_path that it doesn't already
368 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700369 static void OpenClassPathFiles(const std::string& class_path,
370 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371 std::vector<std::string> parsed;
372 Split(class_path, ':', parsed);
373 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
374 ScopedObjectAccess soa(Thread::Current());
375 for (size_t i = 0; i < parsed.size(); ++i) {
376 if (DexFilesContains(dex_files, parsed[i])) {
377 continue;
378 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700379 std::string error_msg;
380 const DexFile* dex_file = DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700382 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700383 } else {
384 dex_files.push_back(dex_file);
385 }
386 }
387 }
388
389 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700390 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
391 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392 for (size_t i = 0; i < dex_files.size(); ++i) {
393 if (dex_files[i]->GetLocation() == location) {
394 return true;
395 }
396 }
397 return false;
398 }
399
400 const CompilerBackend compiler_backend_;
401
402 const InstructionSet instruction_set_;
Dave Allison70202782013-10-22 17:52:19 -0700403 const InstructionSetFeatures instruction_set_features_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404
405 Runtime* runtime_;
406 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407 uint64_t start_ns_;
408
409 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
410};
411
412static bool ParseInt(const char* in, int* out) {
413 char* end;
414 int result = strtol(in, &end, 10);
415 if (in == end || *end != '\0') {
416 return false;
417 }
418 *out = result;
419 return true;
420}
421
422static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
423 const std::vector<const char*>& dex_locations,
424 std::vector<const DexFile*>& dex_files) {
425 size_t failure_count = 0;
426 for (size_t i = 0; i < dex_filenames.size(); i++) {
427 const char* dex_filename = dex_filenames[i];
428 const char* dex_location = dex_locations[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429 std::string error_msg;
430 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700433 ++failure_count;
434 } else {
435 dex_files.push_back(dex_file);
436 }
437 }
438 return failure_count;
439}
440
441// The primary goal of the watchdog is to prevent stuck build servers
442// during development when fatal aborts lead to a cascade of failures
443// that result in a deadlock.
444class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
446#undef CHECK_PTHREAD_CALL
447#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
448 do { \
449 int rc = call args; \
450 if (rc != 0) { \
451 errno = rc; \
452 std::string message(# call); \
453 message += " failed for "; \
454 message += reason; \
455 Fatal(message); \
456 } \
457 } while (false)
458
459 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700460 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461 is_watch_dog_enabled_ = is_watch_dog_enabled;
462 if (!is_watch_dog_enabled_) {
463 return;
464 }
465 shutting_down_ = false;
466 const char* reason = "dex2oat watch dog thread startup";
467 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
469 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
470 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
471 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
472 }
473 ~WatchDog() {
474 if (!is_watch_dog_enabled_) {
475 return;
476 }
477 const char* reason = "dex2oat watch dog thread shutdown";
478 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
479 shutting_down_ = true;
480 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
481 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
482
483 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
484
485 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
486 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
487 }
488
489 private:
490 static void* CallBack(void* arg) {
491 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
492 ::art::SetThreadName("dex2oat watch dog");
493 self->Wait();
494 return NULL;
495 }
496
497 static void Message(char severity, const std::string& message) {
498 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
499 // cases.
500 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
501 kIsDebugBuild ? "d" : "",
502 severity,
503 getpid(),
504 GetTid(),
505 message.c_str());
506 }
507
508 static void Warn(const std::string& message) {
509 Message('W', message);
510 }
511
512 static void Fatal(const std::string& message) {
513 Message('F', message);
514 exit(1);
515 }
516
517 void Wait() {
518 bool warning = true;
519 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
520 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
521 // large.
522 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
523 timespec warning_ts;
524 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
525 timespec timeout_ts;
526 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
527 const char* reason = "dex2oat watch dog thread waiting";
528 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
529 while (!shutting_down_) {
530 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
531 warning ? &warning_ts
532 : &timeout_ts));
533 if (rc == ETIMEDOUT) {
534 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
535 warning ? kWatchDogWarningSeconds
536 : kWatchDogTimeoutSeconds));
537 if (warning) {
538 Warn(message.c_str());
539 warning = false;
540 } else {
541 Fatal(message.c_str());
542 }
543 } else if (rc != 0) {
544 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
545 strerror(errno)));
546 Fatal(message.c_str());
547 }
548 }
549 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
550 }
551
552 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
553#if ART_USE_PORTABLE_COMPILER
554 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
555 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
556#else
557 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
558 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
559#endif
560
561 bool is_watch_dog_enabled_;
562 bool shutting_down_;
563 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
564 pthread_mutex_t mutex_;
565 pthread_cond_t cond_;
566 pthread_attr_t attr_;
567 pthread_t pthread_;
568};
569const unsigned int WatchDog::kWatchDogWarningSeconds;
570const unsigned int WatchDog::kWatchDogTimeoutSeconds;
571
Dave Allison70202782013-10-22 17:52:19 -0700572// Given a set of instruction features from the build, parse it. The
573// input 'str' is a comma separated list of feature names. Parse it and
574// return the InstructionSetFeatures object.
575static InstructionSetFeatures ParseFeatureList(std::string str) {
576 InstructionSetFeatures result;
577 typedef std::vector<std::string> FeatureList;
578 FeatureList features;
579 Split(str, ',', features);
580 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
581 std::string feature = Trim(*i);
582 if (feature == "default") {
583 // Nothing to do.
584 } else if (feature == "div") {
585 // Supports divide instruction.
586 result.SetHasDivideInstruction(true);
587 } else if (feature == "nodiv") {
588 // Turn off support for divide instruction.
589 result.SetHasDivideInstruction(false);
590 } else {
591 Usage("Unknown instruction set feature: '%s'", feature.c_str());
592 }
593 }
594 // others...
595 return result;
596}
597
Brian Carlstrom7940e442013-07-12 13:46:57 -0700598static int dex2oat(int argc, char** argv) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700599 base::TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700600
Brian Carlstrom7940e442013-07-12 13:46:57 -0700601 InitLogging(argv);
602
603 // Skip over argv[0].
604 argv++;
605 argc--;
606
607 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700608 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700609 }
610
611 std::vector<const char*> dex_filenames;
612 std::vector<const char*> dex_locations;
613 int zip_fd = -1;
614 std::string zip_location;
615 std::string oat_filename;
616 std::string oat_symbols;
617 std::string oat_location;
618 int oat_fd = -1;
619 std::string bitcode_filename;
620 const char* image_classes_zip_filename = NULL;
621 const char* image_classes_filename = NULL;
622 std::string image_filename;
623 std::string boot_image_filename;
624 uintptr_t image_base = 0;
625 UniquePtr<std::string> host_prefix;
626 std::string android_root;
627 std::vector<const char*> runtime_args;
628 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700629#if defined(ART_USE_PORTABLE_COMPILER)
630 CompilerBackend compiler_backend = kPortable;
631#else
632 CompilerBackend compiler_backend = kQuick;
633#endif
Dave Allison70202782013-10-22 17:52:19 -0700634
635 // Take the default set of instruction features from the build if present.
636 InstructionSetFeatures instruction_set_features =
637#ifdef ART_DEFAULT_INSTRUCTION_SET_FEATURES
638 ParseFeatureList(STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES));
639#else
640 ParseFeatureList("default");
641#endif
642
Brian Carlstrom7940e442013-07-12 13:46:57 -0700643#if defined(__arm__)
644 InstructionSet instruction_set = kThumb2;
645#elif defined(__i386__)
646 InstructionSet instruction_set = kX86;
647#elif defined(__mips__)
648 InstructionSet instruction_set = kMips;
649#else
650#error "Unsupported architecture"
651#endif
Dave Allison70202782013-10-22 17:52:19 -0700652
653
Brian Carlstrom7940e442013-07-12 13:46:57 -0700654 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700655 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700656 bool dump_timing = false;
657 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658 bool watch_dog_enabled = !kIsTargetBuild;
659
660
661 for (int i = 0; i < argc; i++) {
662 const StringPiece option(argv[i]);
663 bool log_options = false;
664 if (log_options) {
665 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
666 }
667 if (option.starts_with("--dex-file=")) {
668 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
669 } else if (option.starts_with("--dex-location=")) {
670 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
671 } else if (option.starts_with("--zip-fd=")) {
672 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
673 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700674 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700675 }
676 } else if (option.starts_with("--zip-location=")) {
677 zip_location = option.substr(strlen("--zip-location=")).data();
678 } else if (option.starts_with("--oat-file=")) {
679 oat_filename = option.substr(strlen("--oat-file=")).data();
680 } else if (option.starts_with("--oat-symbols=")) {
681 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
682 } else if (option.starts_with("--oat-fd=")) {
683 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
684 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700685 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700686 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687 } else if (option == "--watch-dog") {
688 watch_dog_enabled = true;
689 } else if (option == "--no-watch-dog") {
690 watch_dog_enabled = false;
691 } else if (option.starts_with("-j")) {
692 const char* thread_count_str = option.substr(strlen("-j")).data();
693 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700694 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700695 }
696 } else if (option.starts_with("--oat-location=")) {
697 oat_location = option.substr(strlen("--oat-location=")).data();
698 } else if (option.starts_with("--bitcode=")) {
699 bitcode_filename = option.substr(strlen("--bitcode=")).data();
700 } else if (option.starts_with("--image=")) {
701 image_filename = option.substr(strlen("--image=")).data();
702 } else if (option.starts_with("--image-classes=")) {
703 image_classes_filename = option.substr(strlen("--image-classes=")).data();
704 } else if (option.starts_with("--image-classes-zip=")) {
705 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
706 } else if (option.starts_with("--base=")) {
707 const char* image_base_str = option.substr(strlen("--base=")).data();
708 char* end;
709 image_base = strtoul(image_base_str, &end, 16);
710 if (end == image_base_str || *end != '\0') {
711 Usage("Failed to parse hexadecimal value for option %s", option.data());
712 }
713 } else if (option.starts_with("--boot-image=")) {
714 boot_image_filename = option.substr(strlen("--boot-image=")).data();
715 } else if (option.starts_with("--host-prefix=")) {
716 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
717 } else if (option.starts_with("--android-root=")) {
718 android_root = option.substr(strlen("--android-root=")).data();
719 } else if (option.starts_with("--instruction-set=")) {
720 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
721 if (instruction_set_str == "arm") {
722 instruction_set = kThumb2;
723 } else if (instruction_set_str == "mips") {
724 instruction_set = kMips;
725 } else if (instruction_set_str == "x86") {
726 instruction_set = kX86;
727 }
Dave Allison70202782013-10-22 17:52:19 -0700728 } else if (option.starts_with("--instruction-set-features=")) {
729 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
730 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700731 } else if (option.starts_with("--compiler-backend=")) {
732 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
733 if (backend_str == "Quick") {
734 compiler_backend = kQuick;
735 } else if (backend_str == "Portable") {
736 compiler_backend = kPortable;
737 }
738 } else if (option == "--host") {
739 is_host = true;
740 } else if (option == "--runtime-arg") {
741 if (++i >= argc) {
742 Usage("Missing required argument for --runtime-arg");
743 }
744 if (log_options) {
745 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
746 }
747 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700748 } else if (option == "--dump-timing") {
749 dump_timing = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700750 } else if (option == "--dump-stats") {
751 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700752 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700753 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 }
755 }
756
757 if (oat_filename.empty() && oat_fd == -1) {
758 Usage("Output must be supplied with either --oat-file or --oat-fd");
759 }
760
761 if (!oat_filename.empty() && oat_fd != -1) {
762 Usage("--oat-file should not be used with --oat-fd");
763 }
764
765 if (!oat_symbols.empty() && oat_fd != -1) {
766 Usage("--oat-symbols should not be used with --oat-fd");
767 }
768
769 if (!oat_symbols.empty() && is_host) {
770 Usage("--oat-symbols should not be used with --host");
771 }
772
773 if (oat_fd != -1 && !image_filename.empty()) {
774 Usage("--oat-fd should not be used with --image");
775 }
776
777 if (host_prefix.get() == NULL) {
778 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
779 if (android_product_out != NULL) {
780 host_prefix.reset(new std::string(android_product_out));
781 }
782 }
783
784 if (android_root.empty()) {
785 const char* android_root_env_var = getenv("ANDROID_ROOT");
786 if (android_root_env_var == NULL) {
787 Usage("--android-root unspecified and ANDROID_ROOT not set");
788 }
789 android_root += android_root_env_var;
790 }
791
792 bool image = (!image_filename.empty());
793 if (!image && boot_image_filename.empty()) {
794 if (host_prefix.get() == NULL) {
795 boot_image_filename += GetAndroidRoot();
796 } else {
797 boot_image_filename += *host_prefix.get();
798 boot_image_filename += "/system";
799 }
800 boot_image_filename += "/framework/boot.art";
801 }
802 std::string boot_image_option;
803 if (!boot_image_filename.empty()) {
804 boot_image_option += "-Ximage:";
805 boot_image_option += boot_image_filename;
806 }
807
808 if (image_classes_filename != NULL && !image) {
809 Usage("--image-classes should only be used with --image");
810 }
811
812 if (image_classes_filename != NULL && !boot_image_option.empty()) {
813 Usage("--image-classes should not be used with --boot-image");
814 }
815
816 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
817 Usage("--image-classes-zip should be used with --image-classes");
818 }
819
820 if (dex_filenames.empty() && zip_fd == -1) {
821 Usage("Input must be supplied with either --dex-file or --zip-fd");
822 }
823
824 if (!dex_filenames.empty() && zip_fd != -1) {
825 Usage("--dex-file should not be used with --zip-fd");
826 }
827
828 if (!dex_filenames.empty() && !zip_location.empty()) {
829 Usage("--dex-file should not be used with --zip-location");
830 }
831
832 if (dex_locations.empty()) {
833 for (size_t i = 0; i < dex_filenames.size(); i++) {
834 dex_locations.push_back(dex_filenames[i]);
835 }
836 } else if (dex_locations.size() != dex_filenames.size()) {
837 Usage("--dex-location arguments do not match --dex-file arguments");
838 }
839
840 if (zip_fd != -1 && zip_location.empty()) {
841 Usage("--zip-location should be supplied with --zip-fd");
842 }
843
844 if (boot_image_option.empty()) {
845 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700846 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847 }
848 }
849
850 std::string oat_stripped(oat_filename);
851 std::string oat_unstripped;
852 if (!oat_symbols.empty()) {
853 oat_unstripped += oat_symbols;
854 } else {
855 oat_unstripped += oat_filename;
856 }
857
858 // Done with usage checks, enable watchdog if requested
859 WatchDog watch_dog(watch_dog_enabled);
860
861 // Check early that the result of compilation can be written
862 UniquePtr<File> oat_file;
863 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
864 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700865 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700866 if (oat_location.empty()) {
867 oat_location = oat_filename;
868 }
869 } else {
870 oat_file.reset(new File(oat_fd, oat_location));
871 oat_file->DisableAutoClose();
872 }
873 if (oat_file.get() == NULL) {
874 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
875 return EXIT_FAILURE;
876 }
877 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
878 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
879 return EXIT_FAILURE;
880 }
881
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700882 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700883 LOG(INFO) << "dex2oat: " << oat_location;
884
Ian Rogersf30f6da2013-08-28 17:33:30 -0700885 if (image) {
886 bool has_compiler_filter = false;
887 for (const char* r : runtime_args) {
888 if (strncmp(r, "-compiler-filter:", 17) == 0) {
889 has_compiler_filter = true;
890 break;
891 }
892 }
893 if (!has_compiler_filter) {
894 runtime_args.push_back("-compiler-filter:everything");
895 }
896 }
897
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898 Runtime::Options options;
899 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
900 std::vector<const DexFile*> boot_class_path;
901 if (boot_image_option.empty()) {
902 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
903 if (failure_count > 0) {
904 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
905 return EXIT_FAILURE;
906 }
907 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
908 } else {
909 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
910 }
911 if (host_prefix.get() != NULL) {
912 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
913 }
914 for (size_t i = 0; i < runtime_args.size(); i++) {
915 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
916 }
917
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918#ifdef ART_SEA_IR_MODE
919 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
920#endif
921
Brian Carlstrom7940e442013-07-12 13:46:57 -0700922 Dex2Oat* p_dex2oat;
Dave Allison70202782013-10-22 17:52:19 -0700923 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set,
924 instruction_set_features, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 LOG(ERROR) << "Failed to create dex2oat";
926 return EXIT_FAILURE;
927 }
928 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
929 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700930 // give it away now so that we don't starve GC.
931 Thread* self = Thread::Current();
932 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700933 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700934 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
935 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700937 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700938
939 // If --image-classes was specified, calculate the full list of classes to include in the image
940 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
941 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700942 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943 if (image_classes_zip_filename != NULL) {
944 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700945 image_classes_filename,
946 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 } else {
948 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
949 }
950 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700951 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
952 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700953 return EXIT_FAILURE;
954 }
955 }
956
957 std::vector<const DexFile*> dex_files;
958 if (boot_image_option.empty()) {
959 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
960 } else {
961 if (dex_filenames.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700962 std::string error_msg;
963 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
964 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700965 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700966 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
967 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968 return EXIT_FAILURE;
969 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700970 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700972 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
973 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974 return EXIT_FAILURE;
975 }
976 dex_files.push_back(dex_file);
977 } else {
978 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
979 if (failure_count > 0) {
980 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
981 return EXIT_FAILURE;
982 }
983 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700984
985 // Ensure opened dex files are writable for dex-to-dex transformations.
986 for (const auto& dex_file : dex_files) {
987 if (!dex_file->EnableWrite()) {
988 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
989 }
990 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700991 }
992
buzbeea024a062013-07-31 10:47:37 -0700993 /*
994 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
995 * bother to check if we're doing the image.
996 */
997 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998 size_t num_methods = 0;
999 for (size_t i = 0; i != dex_files.size(); ++i) {
1000 const DexFile* dex_file = dex_files[i];
1001 CHECK(dex_file != NULL);
1002 num_methods += dex_file->NumMethodIds();
1003 }
buzbeea024a062013-07-31 10:47:37 -07001004 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
1005 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001006 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001007 }
1008 }
1009
1010 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
1011 host_prefix.get(),
1012 android_root,
1013 is_host,
1014 dex_files,
1015 oat_file.get(),
1016 bitcode_filename,
1017 image,
1018 image_classes,
1019 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -07001020 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001021
1022 if (compiler.get() == NULL) {
1023 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1024 return EXIT_FAILURE;
1025 }
1026
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001027 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028
1029 // Notes on the interleaving of creating the image and oat file to
1030 // ensure the references between the two are correct.
1031 //
1032 // Currently we have a memory layout that looks something like this:
1033 //
1034 // +--------------+
1035 // | image |
1036 // +--------------+
1037 // | boot oat |
1038 // +--------------+
1039 // | alloc spaces |
1040 // +--------------+
1041 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001042 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001043 //
1044 // 1. The image is expected to be loaded at an absolute address and
1045 // contains Objects with absolute pointers within the image.
1046 //
1047 // 2. There are absolute pointers from Methods in the image to their
1048 // code in the oat.
1049 //
1050 // 3. There are absolute pointers from the code in the oat to Methods
1051 // in the image.
1052 //
1053 // 4. There are absolute pointers from code in the oat to other code
1054 // in the oat.
1055 //
1056 // To get this all correct, we go through several steps.
1057 //
1058 // 1. We have already created that oat file above with
1059 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001060 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001061 // file). The Compiler returned by CreateOatFile provides
1062 // PatchInformation for references to oat code and Methods that need
1063 // to be update once we know where the oat file will be located
1064 // after the image.
1065 //
1066 // 2. We create the image file. It needs to know where the oat file
1067 // will be loaded after itself. Originally when oat file was simply
1068 // memory mapped so we could predict where its contents were based
1069 // on the file size. Now that it is an ELF file, we need to inspect
1070 // the ELF file to understand the in memory segment layout including
1071 // where the oat header is located within. ImageWriter's
1072 // PatchOatCodeAndMethods uses the PatchInformation from the
1073 // Compiler to touch up absolute references in the oat file.
1074 //
1075 // 3. We fixup the ELF program headers so that dlopen will try to
1076 // load the .so at the desired location at runtime by offsetting the
1077 // Elf32_Phdr.p_vaddr values by the desired base address.
1078 //
1079 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001080 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1082 image_base,
1083 oat_unstripped,
1084 oat_location,
1085 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001086 if (!image_creation_success) {
1087 return EXIT_FAILURE;
1088 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001089 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001090 }
1091
1092 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001093 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001094 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001095 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001096 return EXIT_SUCCESS;
1097 }
1098
1099 // If we don't want to strip in place, copy from unstripped location to stripped location.
1100 // We need to strip after image creation because FixupElf needs to use .strtab.
1101 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001102 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001104 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1105 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001106 size_t buffer_size = 8192;
1107 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1108 while (true) {
1109 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1110 if (bytes_read <= 0) {
1111 break;
1112 }
1113 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1114 CHECK(write_ok);
1115 }
1116 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001117 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001118 }
1119
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001120#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001121 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001122 // Strip unneeded sections for target
1123 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1124 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001125 std::string error_msg;
1126 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001127
Brian Carlstrom7940e442013-07-12 13:46:57 -07001128
1129 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001130 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001131#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001132
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001133 timings.EndSplit();
1134
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001135 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001136 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001137 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001138
1139 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1140 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1141 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
1142 exit(EXIT_SUCCESS);
1143 }
1144
Brian Carlstrom7940e442013-07-12 13:46:57 -07001145 return EXIT_SUCCESS;
1146}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001147} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001148
1149int main(int argc, char** argv) {
1150 return art::dex2oat(argc, argv);
1151}