blob: 9631e2df67d80507266f127e8187d711f5185cb2 [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
Brian Carlstromeb4d2ae2013-11-08 18:25:47 -0800422static void OpenDexFiles(const std::vector<const char*>& dex_filenames,
423 const std::vector<const char*>& dex_locations,
424 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425 for (size_t i = 0; i < dex_filenames.size(); i++) {
426 const char* dex_filename = dex_filenames[i];
427 const char* dex_location = dex_locations[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700428 std::string error_msg;
429 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700431 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700432 } else {
433 dex_files.push_back(dex_file);
434 }
435 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436}
437
438// The primary goal of the watchdog is to prevent stuck build servers
439// during development when fatal aborts lead to a cascade of failures
440// that result in a deadlock.
441class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700442// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
443#undef CHECK_PTHREAD_CALL
444#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
445 do { \
446 int rc = call args; \
447 if (rc != 0) { \
448 errno = rc; \
449 std::string message(# call); \
450 message += " failed for "; \
451 message += reason; \
452 Fatal(message); \
453 } \
454 } while (false)
455
456 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700457 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 is_watch_dog_enabled_ = is_watch_dog_enabled;
459 if (!is_watch_dog_enabled_) {
460 return;
461 }
462 shutting_down_ = false;
463 const char* reason = "dex2oat watch dog thread startup";
464 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
465 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
466 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
467 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
469 }
470 ~WatchDog() {
471 if (!is_watch_dog_enabled_) {
472 return;
473 }
474 const char* reason = "dex2oat watch dog thread shutdown";
475 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
476 shutting_down_ = true;
477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
478 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
479
480 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
481
482 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
483 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
484 }
485
486 private:
487 static void* CallBack(void* arg) {
488 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
489 ::art::SetThreadName("dex2oat watch dog");
490 self->Wait();
491 return NULL;
492 }
493
494 static void Message(char severity, const std::string& message) {
495 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
496 // cases.
497 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
498 kIsDebugBuild ? "d" : "",
499 severity,
500 getpid(),
501 GetTid(),
502 message.c_str());
503 }
504
505 static void Warn(const std::string& message) {
506 Message('W', message);
507 }
508
509 static void Fatal(const std::string& message) {
510 Message('F', message);
511 exit(1);
512 }
513
514 void Wait() {
515 bool warning = true;
516 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
517 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
518 // large.
519 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
520 timespec warning_ts;
521 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
522 timespec timeout_ts;
523 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
524 const char* reason = "dex2oat watch dog thread waiting";
525 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
526 while (!shutting_down_) {
527 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
528 warning ? &warning_ts
529 : &timeout_ts));
530 if (rc == ETIMEDOUT) {
531 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
532 warning ? kWatchDogWarningSeconds
533 : kWatchDogTimeoutSeconds));
534 if (warning) {
535 Warn(message.c_str());
536 warning = false;
537 } else {
538 Fatal(message.c_str());
539 }
540 } else if (rc != 0) {
541 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
542 strerror(errno)));
543 Fatal(message.c_str());
544 }
545 }
546 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
547 }
548
549 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
550#if ART_USE_PORTABLE_COMPILER
551 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
552 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
553#else
554 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
555 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
556#endif
557
558 bool is_watch_dog_enabled_;
559 bool shutting_down_;
560 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
561 pthread_mutex_t mutex_;
562 pthread_cond_t cond_;
563 pthread_attr_t attr_;
564 pthread_t pthread_;
565};
566const unsigned int WatchDog::kWatchDogWarningSeconds;
567const unsigned int WatchDog::kWatchDogTimeoutSeconds;
568
Dave Allison70202782013-10-22 17:52:19 -0700569// Given a set of instruction features from the build, parse it. The
570// input 'str' is a comma separated list of feature names. Parse it and
571// return the InstructionSetFeatures object.
572static InstructionSetFeatures ParseFeatureList(std::string str) {
573 InstructionSetFeatures result;
574 typedef std::vector<std::string> FeatureList;
575 FeatureList features;
576 Split(str, ',', features);
577 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
578 std::string feature = Trim(*i);
579 if (feature == "default") {
580 // Nothing to do.
581 } else if (feature == "div") {
582 // Supports divide instruction.
583 result.SetHasDivideInstruction(true);
584 } else if (feature == "nodiv") {
585 // Turn off support for divide instruction.
586 result.SetHasDivideInstruction(false);
587 } else {
588 Usage("Unknown instruction set feature: '%s'", feature.c_str());
589 }
590 }
591 // others...
592 return result;
593}
594
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595static int dex2oat(int argc, char** argv) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700596 base::TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700597
Brian Carlstrom7940e442013-07-12 13:46:57 -0700598 InitLogging(argv);
599
600 // Skip over argv[0].
601 argv++;
602 argc--;
603
604 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700605 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700606 }
607
608 std::vector<const char*> dex_filenames;
609 std::vector<const char*> dex_locations;
610 int zip_fd = -1;
611 std::string zip_location;
612 std::string oat_filename;
613 std::string oat_symbols;
614 std::string oat_location;
615 int oat_fd = -1;
616 std::string bitcode_filename;
617 const char* image_classes_zip_filename = NULL;
618 const char* image_classes_filename = NULL;
619 std::string image_filename;
620 std::string boot_image_filename;
621 uintptr_t image_base = 0;
622 UniquePtr<std::string> host_prefix;
623 std::string android_root;
624 std::vector<const char*> runtime_args;
625 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700626#if defined(ART_USE_PORTABLE_COMPILER)
627 CompilerBackend compiler_backend = kPortable;
628#else
629 CompilerBackend compiler_backend = kQuick;
630#endif
Dave Allison70202782013-10-22 17:52:19 -0700631
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800632 // Take the default set of instruction features from the build.
Dave Allison70202782013-10-22 17:52:19 -0700633 InstructionSetFeatures instruction_set_features =
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800634 ParseFeatureList(STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES));
Dave Allison70202782013-10-22 17:52:19 -0700635
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636#if defined(__arm__)
637 InstructionSet instruction_set = kThumb2;
638#elif defined(__i386__)
639 InstructionSet instruction_set = kX86;
640#elif defined(__mips__)
641 InstructionSet instruction_set = kMips;
642#else
643#error "Unsupported architecture"
644#endif
Dave Allison70202782013-10-22 17:52:19 -0700645
646
Brian Carlstrom7940e442013-07-12 13:46:57 -0700647 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700648 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700649 bool dump_timing = false;
650 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700651 bool watch_dog_enabled = !kIsTargetBuild;
652
653
654 for (int i = 0; i < argc; i++) {
655 const StringPiece option(argv[i]);
656 bool log_options = false;
657 if (log_options) {
658 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
659 }
660 if (option.starts_with("--dex-file=")) {
661 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
662 } else if (option.starts_with("--dex-location=")) {
663 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
664 } else if (option.starts_with("--zip-fd=")) {
665 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
666 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700667 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668 }
669 } else if (option.starts_with("--zip-location=")) {
670 zip_location = option.substr(strlen("--zip-location=")).data();
671 } else if (option.starts_with("--oat-file=")) {
672 oat_filename = option.substr(strlen("--oat-file=")).data();
673 } else if (option.starts_with("--oat-symbols=")) {
674 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
675 } else if (option.starts_with("--oat-fd=")) {
676 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
677 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700678 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700679 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 } else if (option == "--watch-dog") {
681 watch_dog_enabled = true;
682 } else if (option == "--no-watch-dog") {
683 watch_dog_enabled = false;
684 } else if (option.starts_with("-j")) {
685 const char* thread_count_str = option.substr(strlen("-j")).data();
686 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700687 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688 }
689 } else if (option.starts_with("--oat-location=")) {
690 oat_location = option.substr(strlen("--oat-location=")).data();
691 } else if (option.starts_with("--bitcode=")) {
692 bitcode_filename = option.substr(strlen("--bitcode=")).data();
693 } else if (option.starts_with("--image=")) {
694 image_filename = option.substr(strlen("--image=")).data();
695 } else if (option.starts_with("--image-classes=")) {
696 image_classes_filename = option.substr(strlen("--image-classes=")).data();
697 } else if (option.starts_with("--image-classes-zip=")) {
698 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
699 } else if (option.starts_with("--base=")) {
700 const char* image_base_str = option.substr(strlen("--base=")).data();
701 char* end;
702 image_base = strtoul(image_base_str, &end, 16);
703 if (end == image_base_str || *end != '\0') {
704 Usage("Failed to parse hexadecimal value for option %s", option.data());
705 }
706 } else if (option.starts_with("--boot-image=")) {
707 boot_image_filename = option.substr(strlen("--boot-image=")).data();
708 } else if (option.starts_with("--host-prefix=")) {
709 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
710 } else if (option.starts_with("--android-root=")) {
711 android_root = option.substr(strlen("--android-root=")).data();
712 } else if (option.starts_with("--instruction-set=")) {
713 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
714 if (instruction_set_str == "arm") {
715 instruction_set = kThumb2;
716 } else if (instruction_set_str == "mips") {
717 instruction_set = kMips;
718 } else if (instruction_set_str == "x86") {
719 instruction_set = kX86;
720 }
Dave Allison70202782013-10-22 17:52:19 -0700721 } else if (option.starts_with("--instruction-set-features=")) {
722 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
723 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724 } else if (option.starts_with("--compiler-backend=")) {
725 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
726 if (backend_str == "Quick") {
727 compiler_backend = kQuick;
728 } else if (backend_str == "Portable") {
729 compiler_backend = kPortable;
730 }
731 } else if (option == "--host") {
732 is_host = true;
733 } else if (option == "--runtime-arg") {
734 if (++i >= argc) {
735 Usage("Missing required argument for --runtime-arg");
736 }
737 if (log_options) {
738 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
739 }
740 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700741 } else if (option == "--dump-timing") {
742 dump_timing = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700743 } else if (option == "--dump-stats") {
744 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700745 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700746 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700747 }
748 }
749
750 if (oat_filename.empty() && oat_fd == -1) {
751 Usage("Output must be supplied with either --oat-file or --oat-fd");
752 }
753
754 if (!oat_filename.empty() && oat_fd != -1) {
755 Usage("--oat-file should not be used with --oat-fd");
756 }
757
758 if (!oat_symbols.empty() && oat_fd != -1) {
759 Usage("--oat-symbols should not be used with --oat-fd");
760 }
761
762 if (!oat_symbols.empty() && is_host) {
763 Usage("--oat-symbols should not be used with --host");
764 }
765
766 if (oat_fd != -1 && !image_filename.empty()) {
767 Usage("--oat-fd should not be used with --image");
768 }
769
770 if (host_prefix.get() == NULL) {
771 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
772 if (android_product_out != NULL) {
773 host_prefix.reset(new std::string(android_product_out));
774 }
775 }
776
777 if (android_root.empty()) {
778 const char* android_root_env_var = getenv("ANDROID_ROOT");
779 if (android_root_env_var == NULL) {
780 Usage("--android-root unspecified and ANDROID_ROOT not set");
781 }
782 android_root += android_root_env_var;
783 }
784
785 bool image = (!image_filename.empty());
786 if (!image && boot_image_filename.empty()) {
787 if (host_prefix.get() == NULL) {
788 boot_image_filename += GetAndroidRoot();
789 } else {
790 boot_image_filename += *host_prefix.get();
791 boot_image_filename += "/system";
792 }
793 boot_image_filename += "/framework/boot.art";
794 }
795 std::string boot_image_option;
796 if (!boot_image_filename.empty()) {
797 boot_image_option += "-Ximage:";
798 boot_image_option += boot_image_filename;
799 }
800
801 if (image_classes_filename != NULL && !image) {
802 Usage("--image-classes should only be used with --image");
803 }
804
805 if (image_classes_filename != NULL && !boot_image_option.empty()) {
806 Usage("--image-classes should not be used with --boot-image");
807 }
808
809 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
810 Usage("--image-classes-zip should be used with --image-classes");
811 }
812
813 if (dex_filenames.empty() && zip_fd == -1) {
814 Usage("Input must be supplied with either --dex-file or --zip-fd");
815 }
816
817 if (!dex_filenames.empty() && zip_fd != -1) {
818 Usage("--dex-file should not be used with --zip-fd");
819 }
820
821 if (!dex_filenames.empty() && !zip_location.empty()) {
822 Usage("--dex-file should not be used with --zip-location");
823 }
824
825 if (dex_locations.empty()) {
826 for (size_t i = 0; i < dex_filenames.size(); i++) {
827 dex_locations.push_back(dex_filenames[i]);
828 }
829 } else if (dex_locations.size() != dex_filenames.size()) {
830 Usage("--dex-location arguments do not match --dex-file arguments");
831 }
832
833 if (zip_fd != -1 && zip_location.empty()) {
834 Usage("--zip-location should be supplied with --zip-fd");
835 }
836
837 if (boot_image_option.empty()) {
838 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700839 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840 }
841 }
842
843 std::string oat_stripped(oat_filename);
844 std::string oat_unstripped;
845 if (!oat_symbols.empty()) {
846 oat_unstripped += oat_symbols;
847 } else {
848 oat_unstripped += oat_filename;
849 }
850
851 // Done with usage checks, enable watchdog if requested
852 WatchDog watch_dog(watch_dog_enabled);
853
854 // Check early that the result of compilation can be written
855 UniquePtr<File> oat_file;
856 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
857 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700858 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700859 if (oat_location.empty()) {
860 oat_location = oat_filename;
861 }
862 } else {
863 oat_file.reset(new File(oat_fd, oat_location));
864 oat_file->DisableAutoClose();
865 }
866 if (oat_file.get() == NULL) {
867 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
868 return EXIT_FAILURE;
869 }
870 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
871 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
872 return EXIT_FAILURE;
873 }
874
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700875 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700876 LOG(INFO) << "dex2oat: " << oat_location;
877
Ian Rogersf30f6da2013-08-28 17:33:30 -0700878 if (image) {
879 bool has_compiler_filter = false;
880 for (const char* r : runtime_args) {
881 if (strncmp(r, "-compiler-filter:", 17) == 0) {
882 has_compiler_filter = true;
883 break;
884 }
885 }
886 if (!has_compiler_filter) {
887 runtime_args.push_back("-compiler-filter:everything");
888 }
889 }
890
Brian Carlstrom7940e442013-07-12 13:46:57 -0700891 Runtime::Options options;
892 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
893 std::vector<const DexFile*> boot_class_path;
894 if (boot_image_option.empty()) {
Brian Carlstromeb4d2ae2013-11-08 18:25:47 -0800895 OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700896 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
897 } else {
898 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
899 }
900 if (host_prefix.get() != NULL) {
901 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
902 }
903 for (size_t i = 0; i < runtime_args.size(); i++) {
904 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
905 }
906
Brian Carlstrom7940e442013-07-12 13:46:57 -0700907#ifdef ART_SEA_IR_MODE
908 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
909#endif
910
Brian Carlstrom7940e442013-07-12 13:46:57 -0700911 Dex2Oat* p_dex2oat;
Dave Allison70202782013-10-22 17:52:19 -0700912 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set,
913 instruction_set_features, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700914 LOG(ERROR) << "Failed to create dex2oat";
915 return EXIT_FAILURE;
916 }
917 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
918 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700919 // give it away now so that we don't starve GC.
920 Thread* self = Thread::Current();
921 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700922 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700923 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
924 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700926 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927
928 // If --image-classes was specified, calculate the full list of classes to include in the image
929 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
930 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700931 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700932 if (image_classes_zip_filename != NULL) {
933 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700934 image_classes_filename,
935 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936 } else {
937 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
938 }
939 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700940 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
941 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942 return EXIT_FAILURE;
943 }
944 }
945
946 std::vector<const DexFile*> dex_files;
947 if (boot_image_option.empty()) {
948 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
949 } else {
950 if (dex_filenames.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700951 std::string error_msg;
952 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
953 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700955 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
956 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700957 return EXIT_FAILURE;
958 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700959 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700961 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
962 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963 return EXIT_FAILURE;
964 }
965 dex_files.push_back(dex_file);
966 } else {
Brian Carlstromeb4d2ae2013-11-08 18:25:47 -0800967 OpenDexFiles(dex_filenames, dex_locations, dex_files);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700969
970 // Ensure opened dex files are writable for dex-to-dex transformations.
971 for (const auto& dex_file : dex_files) {
972 if (!dex_file->EnableWrite()) {
973 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
974 }
975 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 }
977
buzbeea024a062013-07-31 10:47:37 -0700978 /*
979 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
980 * bother to check if we're doing the image.
981 */
982 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700983 size_t num_methods = 0;
984 for (size_t i = 0; i != dex_files.size(); ++i) {
985 const DexFile* dex_file = dex_files[i];
986 CHECK(dex_file != NULL);
987 num_methods += dex_file->NumMethodIds();
988 }
buzbeea024a062013-07-31 10:47:37 -0700989 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
990 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700991 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700992 }
993 }
994
995 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
996 host_prefix.get(),
997 android_root,
998 is_host,
999 dex_files,
1000 oat_file.get(),
1001 bitcode_filename,
1002 image,
1003 image_classes,
1004 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -07001005 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006
1007 if (compiler.get() == NULL) {
1008 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1009 return EXIT_FAILURE;
1010 }
1011
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001012 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013
1014 // Notes on the interleaving of creating the image and oat file to
1015 // ensure the references between the two are correct.
1016 //
1017 // Currently we have a memory layout that looks something like this:
1018 //
1019 // +--------------+
1020 // | image |
1021 // +--------------+
1022 // | boot oat |
1023 // +--------------+
1024 // | alloc spaces |
1025 // +--------------+
1026 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001027 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028 //
1029 // 1. The image is expected to be loaded at an absolute address and
1030 // contains Objects with absolute pointers within the image.
1031 //
1032 // 2. There are absolute pointers from Methods in the image to their
1033 // code in the oat.
1034 //
1035 // 3. There are absolute pointers from the code in the oat to Methods
1036 // in the image.
1037 //
1038 // 4. There are absolute pointers from code in the oat to other code
1039 // in the oat.
1040 //
1041 // To get this all correct, we go through several steps.
1042 //
1043 // 1. We have already created that oat file above with
1044 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001045 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046 // file). The Compiler returned by CreateOatFile provides
1047 // PatchInformation for references to oat code and Methods that need
1048 // to be update once we know where the oat file will be located
1049 // after the image.
1050 //
1051 // 2. We create the image file. It needs to know where the oat file
1052 // will be loaded after itself. Originally when oat file was simply
1053 // memory mapped so we could predict where its contents were based
1054 // on the file size. Now that it is an ELF file, we need to inspect
1055 // the ELF file to understand the in memory segment layout including
1056 // where the oat header is located within. ImageWriter's
1057 // PatchOatCodeAndMethods uses the PatchInformation from the
1058 // Compiler to touch up absolute references in the oat file.
1059 //
1060 // 3. We fixup the ELF program headers so that dlopen will try to
1061 // load the .so at the desired location at runtime by offsetting the
1062 // Elf32_Phdr.p_vaddr values by the desired base address.
1063 //
1064 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001065 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001066 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1067 image_base,
1068 oat_unstripped,
1069 oat_location,
1070 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001071 if (!image_creation_success) {
1072 return EXIT_FAILURE;
1073 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001074 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001075 }
1076
1077 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001078 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001079 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001080 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 return EXIT_SUCCESS;
1082 }
1083
1084 // If we don't want to strip in place, copy from unstripped location to stripped location.
1085 // We need to strip after image creation because FixupElf needs to use .strtab.
1086 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001087 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001088 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001089 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1090 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001091 size_t buffer_size = 8192;
1092 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1093 while (true) {
1094 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1095 if (bytes_read <= 0) {
1096 break;
1097 }
1098 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1099 CHECK(write_ok);
1100 }
1101 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001102 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103 }
1104
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001105#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001106 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 // Strip unneeded sections for target
1108 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1109 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001110 std::string error_msg;
1111 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001112
Brian Carlstrom7940e442013-07-12 13:46:57 -07001113
1114 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001115 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001116#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001117
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001118 timings.EndSplit();
1119
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001120 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001121 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001122 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001123
1124 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1125 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1126 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
1127 exit(EXIT_SUCCESS);
1128 }
1129
Brian Carlstrom7940e442013-07-12 13:46:57 -07001130 return EXIT_SUCCESS;
1131}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001132} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001133
1134int main(int argc, char** argv) {
1135 return art::dex2oat(argc, argv);
1136}