blob: d8112ea7082c38b59ea18bd80274b7c1cb869f4c [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("");
134 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
135 UsageError(" set.");
136 UsageError(" Example: --instruction-set=Portable");
137 UsageError(" Default: Quick");
138 UsageError("");
139 UsageError(" --host: used with Portable backend to link against host runtime libraries");
140 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700141 UsageError(" --dump-timing: display a breakdown of where time was spent");
142 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700143 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
144 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
145 UsageError(" Use a separate --runtime-arg switch for each argument.");
146 UsageError(" Example: --runtime-arg -Xms256m");
147 UsageError("");
148 std::cerr << "See log for usage error information\n";
149 exit(EXIT_FAILURE);
150}
151
152class Dex2Oat {
153 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700154 static bool Create(Dex2Oat** p_dex2oat,
155 Runtime::Options& options,
156 CompilerBackend compiler_backend,
157 InstructionSet instruction_set,
158 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
160 if (!CreateRuntime(options, instruction_set)) {
161 *p_dex2oat = NULL;
162 return false;
163 }
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700164 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 return true;
166 }
167
168 ~Dex2Oat() {
169 delete runtime_;
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700170 VLOG(compiler) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700171 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 }
173
174
Brian Carlstrom45602482013-07-21 22:07:55 -0700175 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Brian Carlstrom45602482013-07-21 22:07:55 -0700177 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
178 std::ifstream::in));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 if (image_classes_file.get() == NULL) {
180 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
181 return NULL;
182 }
183 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
184 image_classes_file->close();
185 return result.release();
186 }
187
188 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
189 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
190 while (image_classes_stream.good()) {
191 std::string dot;
192 std::getline(image_classes_stream, dot);
193 if (StartsWith(dot, "#") || dot.empty()) {
194 continue;
195 }
196 std::string descriptor(DotToDescriptor(dot.c_str()));
197 image_classes->insert(descriptor);
198 }
199 return image_classes.release();
200 }
201
Brian Carlstrom45602482013-07-21 22:07:55 -0700202 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700203 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const char* zip_filename,
204 const char* image_classes_filename,
205 std::string* error_msg) {
206 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700207 if (zip_archive.get() == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 return NULL;
209 }
210 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
211 if (zip_entry.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700212 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
213 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 return NULL;
215 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700216 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename,
217 error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 if (image_classes_file.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700219 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
220 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700221 return NULL;
222 }
223 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
224 image_classes_file->Size());
225 std::istringstream image_classes_stream(image_classes_string);
226 return ReadImageClasses(image_classes_stream);
227 }
228
229 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
230 const std::string* host_prefix,
231 const std::string& android_root,
232 bool is_host,
233 const std::vector<const DexFile*>& dex_files,
234 File* oat_file,
235 const std::string& bitcode_filename,
236 bool image,
237 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
238 bool dump_stats,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700239 base::TimingLogger& timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 // SirtRef and ClassLoader creation needs to come after Runtime::Create
241 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700242 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 if (!boot_image_option.empty()) {
244 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
245 std::vector<const DexFile*> class_path_files(dex_files);
246 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700247 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 for (size_t i = 0; i < class_path_files.size(); i++) {
249 class_linker->RegisterDexFile(*class_path_files[i]);
250 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
252 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
253 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
254 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
255 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
256 }
257
258 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
259 instruction_set_,
260 image,
261 image_classes.release(),
262 thread_count_,
Brian Carlstrom45602482013-07-21 22:07:55 -0700263 dump_stats));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700264
265 if (compiler_backend_ == kPortable) {
266 driver->SetBitcodeFileName(bitcode_filename);
267 }
268
Brian Carlstrom45602482013-07-21 22:07:55 -0700269 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700271 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700272 std::string image_file_location;
273 uint32_t image_file_location_oat_checksum = 0;
274 uint32_t image_file_location_oat_data_begin = 0;
275 if (!driver->IsImage()) {
276 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
277 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
278 image_file_location_oat_data_begin =
279 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
280 image_file_location = image_space->GetImageFilename();
281 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
282 image_file_location = image_file_location.substr(host_prefix->size());
283 }
284 }
285
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700286 OatWriter oat_writer(dex_files,
287 image_file_location_oat_checksum,
288 image_file_location_oat_data_begin,
289 image_file_location,
290 driver.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700292 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
294 return NULL;
295 }
296
297 return driver.release();
298 }
299
300 bool CreateImageFile(const std::string& image_filename,
301 uintptr_t image_base,
302 const std::string& oat_filename,
303 const std::string& oat_location,
304 const CompilerDriver& compiler)
305 LOCKS_EXCLUDED(Locks::mutator_lock_) {
306 uintptr_t oat_data_begin;
307 {
308 // ImageWriter is scoped so it can free memory before doing FixupElf
309 ImageWriter image_writer(compiler);
310 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
311 LOG(ERROR) << "Failed to create image file " << image_filename;
312 return false;
313 }
314 oat_data_begin = image_writer.GetOatDataBegin();
315 }
316
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700317 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700318 if (oat_file.get() == NULL) {
319 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
320 return false;
321 }
322 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
323 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
324 return false;
325 }
326 return true;
327 }
328
329 private:
Brian Carlstrom45602482013-07-21 22:07:55 -0700330 explicit Dex2Oat(Runtime* runtime,
331 CompilerBackend compiler_backend,
332 InstructionSet instruction_set,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700333 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 : compiler_backend_(compiler_backend),
335 instruction_set_(instruction_set),
336 runtime_(runtime),
337 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 start_ns_(NanoTime()) {
339 }
340
341 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
342 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
343 if (!Runtime::Create(options, false)) {
344 LOG(ERROR) << "Failed to create runtime";
345 return false;
346 }
347 Runtime* runtime = Runtime::Current();
348 // if we loaded an existing image, we will reuse values from the image roots.
349 if (!runtime->HasResolutionMethod()) {
350 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
351 }
352 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
353 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
354 if (!runtime->HasCalleeSaveMethod(type)) {
355 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
356 }
357 }
358 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
359 return true;
360 }
361
362 // Appends to dex_files any elements of class_path that it doesn't already
363 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700364 static void OpenClassPathFiles(const std::string& class_path,
365 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366 std::vector<std::string> parsed;
367 Split(class_path, ':', parsed);
368 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
369 ScopedObjectAccess soa(Thread::Current());
370 for (size_t i = 0; i < parsed.size(); ++i) {
371 if (DexFilesContains(dex_files, parsed[i])) {
372 continue;
373 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700374 std::string error_msg;
375 const DexFile* dex_file = DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700377 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 } else {
379 dex_files.push_back(dex_file);
380 }
381 }
382 }
383
384 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700385 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
386 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 for (size_t i = 0; i < dex_files.size(); ++i) {
388 if (dex_files[i]->GetLocation() == location) {
389 return true;
390 }
391 }
392 return false;
393 }
394
395 const CompilerBackend compiler_backend_;
396
397 const InstructionSet instruction_set_;
398
399 Runtime* runtime_;
400 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401 uint64_t start_ns_;
402
403 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
404};
405
406static bool ParseInt(const char* in, int* out) {
407 char* end;
408 int result = strtol(in, &end, 10);
409 if (in == end || *end != '\0') {
410 return false;
411 }
412 *out = result;
413 return true;
414}
415
416static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
417 const std::vector<const char*>& dex_locations,
418 std::vector<const DexFile*>& dex_files) {
419 size_t failure_count = 0;
420 for (size_t i = 0; i < dex_filenames.size(); i++) {
421 const char* dex_filename = dex_filenames[i];
422 const char* dex_location = dex_locations[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700423 std::string error_msg;
424 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700426 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 ++failure_count;
428 } else {
429 dex_files.push_back(dex_file);
430 }
431 }
432 return failure_count;
433}
434
435// The primary goal of the watchdog is to prevent stuck build servers
436// during development when fatal aborts lead to a cascade of failures
437// that result in a deadlock.
438class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
440#undef CHECK_PTHREAD_CALL
441#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
442 do { \
443 int rc = call args; \
444 if (rc != 0) { \
445 errno = rc; \
446 std::string message(# call); \
447 message += " failed for "; \
448 message += reason; \
449 Fatal(message); \
450 } \
451 } while (false)
452
453 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700454 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700455 is_watch_dog_enabled_ = is_watch_dog_enabled;
456 if (!is_watch_dog_enabled_) {
457 return;
458 }
459 shutting_down_ = false;
460 const char* reason = "dex2oat watch dog thread startup";
461 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
462 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
463 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
464 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
465 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
466 }
467 ~WatchDog() {
468 if (!is_watch_dog_enabled_) {
469 return;
470 }
471 const char* reason = "dex2oat watch dog thread shutdown";
472 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
473 shutting_down_ = true;
474 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
475 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
476
477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
478
479 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
480 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
481 }
482
483 private:
484 static void* CallBack(void* arg) {
485 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
486 ::art::SetThreadName("dex2oat watch dog");
487 self->Wait();
488 return NULL;
489 }
490
491 static void Message(char severity, const std::string& message) {
492 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
493 // cases.
494 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
495 kIsDebugBuild ? "d" : "",
496 severity,
497 getpid(),
498 GetTid(),
499 message.c_str());
500 }
501
502 static void Warn(const std::string& message) {
503 Message('W', message);
504 }
505
506 static void Fatal(const std::string& message) {
507 Message('F', message);
508 exit(1);
509 }
510
511 void Wait() {
512 bool warning = true;
513 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
514 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
515 // large.
516 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
517 timespec warning_ts;
518 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
519 timespec timeout_ts;
520 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
521 const char* reason = "dex2oat watch dog thread waiting";
522 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
523 while (!shutting_down_) {
524 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
525 warning ? &warning_ts
526 : &timeout_ts));
527 if (rc == ETIMEDOUT) {
528 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
529 warning ? kWatchDogWarningSeconds
530 : kWatchDogTimeoutSeconds));
531 if (warning) {
532 Warn(message.c_str());
533 warning = false;
534 } else {
535 Fatal(message.c_str());
536 }
537 } else if (rc != 0) {
538 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
539 strerror(errno)));
540 Fatal(message.c_str());
541 }
542 }
543 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
544 }
545
546 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
547#if ART_USE_PORTABLE_COMPILER
548 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
549 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
550#else
551 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
552 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
553#endif
554
555 bool is_watch_dog_enabled_;
556 bool shutting_down_;
557 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
558 pthread_mutex_t mutex_;
559 pthread_cond_t cond_;
560 pthread_attr_t attr_;
561 pthread_t pthread_;
562};
563const unsigned int WatchDog::kWatchDogWarningSeconds;
564const unsigned int WatchDog::kWatchDogTimeoutSeconds;
565
566static int dex2oat(int argc, char** argv) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700567 base::TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700568
Brian Carlstrom7940e442013-07-12 13:46:57 -0700569 InitLogging(argv);
570
571 // Skip over argv[0].
572 argv++;
573 argc--;
574
575 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700576 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577 }
578
579 std::vector<const char*> dex_filenames;
580 std::vector<const char*> dex_locations;
581 int zip_fd = -1;
582 std::string zip_location;
583 std::string oat_filename;
584 std::string oat_symbols;
585 std::string oat_location;
586 int oat_fd = -1;
587 std::string bitcode_filename;
588 const char* image_classes_zip_filename = NULL;
589 const char* image_classes_filename = NULL;
590 std::string image_filename;
591 std::string boot_image_filename;
592 uintptr_t image_base = 0;
593 UniquePtr<std::string> host_prefix;
594 std::string android_root;
595 std::vector<const char*> runtime_args;
596 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700597#if defined(ART_USE_PORTABLE_COMPILER)
598 CompilerBackend compiler_backend = kPortable;
599#else
600 CompilerBackend compiler_backend = kQuick;
601#endif
602#if defined(__arm__)
603 InstructionSet instruction_set = kThumb2;
604#elif defined(__i386__)
605 InstructionSet instruction_set = kX86;
606#elif defined(__mips__)
607 InstructionSet instruction_set = kMips;
608#else
609#error "Unsupported architecture"
610#endif
611 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700612 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700613 bool dump_timing = false;
614 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700615 bool watch_dog_enabled = !kIsTargetBuild;
616
617
618 for (int i = 0; i < argc; i++) {
619 const StringPiece option(argv[i]);
620 bool log_options = false;
621 if (log_options) {
622 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
623 }
624 if (option.starts_with("--dex-file=")) {
625 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
626 } else if (option.starts_with("--dex-location=")) {
627 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
628 } else if (option.starts_with("--zip-fd=")) {
629 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
630 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700631 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700632 }
633 } else if (option.starts_with("--zip-location=")) {
634 zip_location = option.substr(strlen("--zip-location=")).data();
635 } else if (option.starts_with("--oat-file=")) {
636 oat_filename = option.substr(strlen("--oat-file=")).data();
637 } else if (option.starts_with("--oat-symbols=")) {
638 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
639 } else if (option.starts_with("--oat-fd=")) {
640 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
641 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700642 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700643 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700644 } else if (option == "--watch-dog") {
645 watch_dog_enabled = true;
646 } else if (option == "--no-watch-dog") {
647 watch_dog_enabled = false;
648 } else if (option.starts_with("-j")) {
649 const char* thread_count_str = option.substr(strlen("-j")).data();
650 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700651 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 }
653 } else if (option.starts_with("--oat-location=")) {
654 oat_location = option.substr(strlen("--oat-location=")).data();
655 } else if (option.starts_with("--bitcode=")) {
656 bitcode_filename = option.substr(strlen("--bitcode=")).data();
657 } else if (option.starts_with("--image=")) {
658 image_filename = option.substr(strlen("--image=")).data();
659 } else if (option.starts_with("--image-classes=")) {
660 image_classes_filename = option.substr(strlen("--image-classes=")).data();
661 } else if (option.starts_with("--image-classes-zip=")) {
662 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
663 } else if (option.starts_with("--base=")) {
664 const char* image_base_str = option.substr(strlen("--base=")).data();
665 char* end;
666 image_base = strtoul(image_base_str, &end, 16);
667 if (end == image_base_str || *end != '\0') {
668 Usage("Failed to parse hexadecimal value for option %s", option.data());
669 }
670 } else if (option.starts_with("--boot-image=")) {
671 boot_image_filename = option.substr(strlen("--boot-image=")).data();
672 } else if (option.starts_with("--host-prefix=")) {
673 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
674 } else if (option.starts_with("--android-root=")) {
675 android_root = option.substr(strlen("--android-root=")).data();
676 } else if (option.starts_with("--instruction-set=")) {
677 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
678 if (instruction_set_str == "arm") {
679 instruction_set = kThumb2;
680 } else if (instruction_set_str == "mips") {
681 instruction_set = kMips;
682 } else if (instruction_set_str == "x86") {
683 instruction_set = kX86;
684 }
685 } else if (option.starts_with("--compiler-backend=")) {
686 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
687 if (backend_str == "Quick") {
688 compiler_backend = kQuick;
689 } else if (backend_str == "Portable") {
690 compiler_backend = kPortable;
691 }
692 } else if (option == "--host") {
693 is_host = true;
694 } else if (option == "--runtime-arg") {
695 if (++i >= argc) {
696 Usage("Missing required argument for --runtime-arg");
697 }
698 if (log_options) {
699 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
700 }
701 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700702 } else if (option == "--dump-timing") {
703 dump_timing = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700704 } else if (option == "--dump-stats") {
705 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700707 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700708 }
709 }
710
711 if (oat_filename.empty() && oat_fd == -1) {
712 Usage("Output must be supplied with either --oat-file or --oat-fd");
713 }
714
715 if (!oat_filename.empty() && oat_fd != -1) {
716 Usage("--oat-file should not be used with --oat-fd");
717 }
718
719 if (!oat_symbols.empty() && oat_fd != -1) {
720 Usage("--oat-symbols should not be used with --oat-fd");
721 }
722
723 if (!oat_symbols.empty() && is_host) {
724 Usage("--oat-symbols should not be used with --host");
725 }
726
727 if (oat_fd != -1 && !image_filename.empty()) {
728 Usage("--oat-fd should not be used with --image");
729 }
730
731 if (host_prefix.get() == NULL) {
732 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
733 if (android_product_out != NULL) {
734 host_prefix.reset(new std::string(android_product_out));
735 }
736 }
737
738 if (android_root.empty()) {
739 const char* android_root_env_var = getenv("ANDROID_ROOT");
740 if (android_root_env_var == NULL) {
741 Usage("--android-root unspecified and ANDROID_ROOT not set");
742 }
743 android_root += android_root_env_var;
744 }
745
746 bool image = (!image_filename.empty());
747 if (!image && boot_image_filename.empty()) {
748 if (host_prefix.get() == NULL) {
749 boot_image_filename += GetAndroidRoot();
750 } else {
751 boot_image_filename += *host_prefix.get();
752 boot_image_filename += "/system";
753 }
754 boot_image_filename += "/framework/boot.art";
755 }
756 std::string boot_image_option;
757 if (!boot_image_filename.empty()) {
758 boot_image_option += "-Ximage:";
759 boot_image_option += boot_image_filename;
760 }
761
762 if (image_classes_filename != NULL && !image) {
763 Usage("--image-classes should only be used with --image");
764 }
765
766 if (image_classes_filename != NULL && !boot_image_option.empty()) {
767 Usage("--image-classes should not be used with --boot-image");
768 }
769
770 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
771 Usage("--image-classes-zip should be used with --image-classes");
772 }
773
774 if (dex_filenames.empty() && zip_fd == -1) {
775 Usage("Input must be supplied with either --dex-file or --zip-fd");
776 }
777
778 if (!dex_filenames.empty() && zip_fd != -1) {
779 Usage("--dex-file should not be used with --zip-fd");
780 }
781
782 if (!dex_filenames.empty() && !zip_location.empty()) {
783 Usage("--dex-file should not be used with --zip-location");
784 }
785
786 if (dex_locations.empty()) {
787 for (size_t i = 0; i < dex_filenames.size(); i++) {
788 dex_locations.push_back(dex_filenames[i]);
789 }
790 } else if (dex_locations.size() != dex_filenames.size()) {
791 Usage("--dex-location arguments do not match --dex-file arguments");
792 }
793
794 if (zip_fd != -1 && zip_location.empty()) {
795 Usage("--zip-location should be supplied with --zip-fd");
796 }
797
798 if (boot_image_option.empty()) {
799 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700800 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700801 }
802 }
803
804 std::string oat_stripped(oat_filename);
805 std::string oat_unstripped;
806 if (!oat_symbols.empty()) {
807 oat_unstripped += oat_symbols;
808 } else {
809 oat_unstripped += oat_filename;
810 }
811
812 // Done with usage checks, enable watchdog if requested
813 WatchDog watch_dog(watch_dog_enabled);
814
815 // Check early that the result of compilation can be written
816 UniquePtr<File> oat_file;
817 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
818 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700819 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700820 if (oat_location.empty()) {
821 oat_location = oat_filename;
822 }
823 } else {
824 oat_file.reset(new File(oat_fd, oat_location));
825 oat_file->DisableAutoClose();
826 }
827 if (oat_file.get() == NULL) {
828 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
829 return EXIT_FAILURE;
830 }
831 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
832 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
833 return EXIT_FAILURE;
834 }
835
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700836 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837 LOG(INFO) << "dex2oat: " << oat_location;
838
Ian Rogersf30f6da2013-08-28 17:33:30 -0700839 if (image) {
840 bool has_compiler_filter = false;
841 for (const char* r : runtime_args) {
842 if (strncmp(r, "-compiler-filter:", 17) == 0) {
843 has_compiler_filter = true;
844 break;
845 }
846 }
847 if (!has_compiler_filter) {
848 runtime_args.push_back("-compiler-filter:everything");
849 }
850 }
851
Brian Carlstrom7940e442013-07-12 13:46:57 -0700852 Runtime::Options options;
853 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
854 std::vector<const DexFile*> boot_class_path;
855 if (boot_image_option.empty()) {
856 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
857 if (failure_count > 0) {
858 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
859 return EXIT_FAILURE;
860 }
861 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
862 } else {
863 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
864 }
865 if (host_prefix.get() != NULL) {
866 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
867 }
868 for (size_t i = 0; i < runtime_args.size(); i++) {
869 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
870 }
871
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872#ifdef ART_SEA_IR_MODE
873 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
874#endif
875
Brian Carlstrom7940e442013-07-12 13:46:57 -0700876 Dex2Oat* p_dex2oat;
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700877 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878 LOG(ERROR) << "Failed to create dex2oat";
879 return EXIT_FAILURE;
880 }
881 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
882 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700883 // give it away now so that we don't starve GC.
884 Thread* self = Thread::Current();
885 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700886 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700887 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
888 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700889 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700890 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700891
892 // If --image-classes was specified, calculate the full list of classes to include in the image
893 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
894 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700895 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700896 if (image_classes_zip_filename != NULL) {
897 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700898 image_classes_filename,
899 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700900 } else {
901 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
902 }
903 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700904 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
905 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700906 return EXIT_FAILURE;
907 }
908 }
909
910 std::vector<const DexFile*> dex_files;
911 if (boot_image_option.empty()) {
912 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
913 } else {
914 if (dex_filenames.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700915 std::string error_msg;
916 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
917 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700919 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
920 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921 return EXIT_FAILURE;
922 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700923 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700925 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
926 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927 return EXIT_FAILURE;
928 }
929 dex_files.push_back(dex_file);
930 } else {
931 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
932 if (failure_count > 0) {
933 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
934 return EXIT_FAILURE;
935 }
936 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700937
938 // Ensure opened dex files are writable for dex-to-dex transformations.
939 for (const auto& dex_file : dex_files) {
940 if (!dex_file->EnableWrite()) {
941 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
942 }
943 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700944 }
945
buzbeea024a062013-07-31 10:47:37 -0700946 /*
947 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
948 * bother to check if we're doing the image.
949 */
950 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700951 size_t num_methods = 0;
952 for (size_t i = 0; i != dex_files.size(); ++i) {
953 const DexFile* dex_file = dex_files[i];
954 CHECK(dex_file != NULL);
955 num_methods += dex_file->NumMethodIds();
956 }
buzbeea024a062013-07-31 10:47:37 -0700957 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
958 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700959 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 }
961 }
962
963 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
964 host_prefix.get(),
965 android_root,
966 is_host,
967 dex_files,
968 oat_file.get(),
969 bitcode_filename,
970 image,
971 image_classes,
972 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -0700973 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974
975 if (compiler.get() == NULL) {
976 LOG(ERROR) << "Failed to create oat file: " << oat_location;
977 return EXIT_FAILURE;
978 }
979
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700980 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700981
982 // Notes on the interleaving of creating the image and oat file to
983 // ensure the references between the two are correct.
984 //
985 // Currently we have a memory layout that looks something like this:
986 //
987 // +--------------+
988 // | image |
989 // +--------------+
990 // | boot oat |
991 // +--------------+
992 // | alloc spaces |
993 // +--------------+
994 //
Brian Carlstrom45602482013-07-21 22:07:55 -0700995 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996 //
997 // 1. The image is expected to be loaded at an absolute address and
998 // contains Objects with absolute pointers within the image.
999 //
1000 // 2. There are absolute pointers from Methods in the image to their
1001 // code in the oat.
1002 //
1003 // 3. There are absolute pointers from the code in the oat to Methods
1004 // in the image.
1005 //
1006 // 4. There are absolute pointers from code in the oat to other code
1007 // in the oat.
1008 //
1009 // To get this all correct, we go through several steps.
1010 //
1011 // 1. We have already created that oat file above with
1012 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001013 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 // file). The Compiler returned by CreateOatFile provides
1015 // PatchInformation for references to oat code and Methods that need
1016 // to be update once we know where the oat file will be located
1017 // after the image.
1018 //
1019 // 2. We create the image file. It needs to know where the oat file
1020 // will be loaded after itself. Originally when oat file was simply
1021 // memory mapped so we could predict where its contents were based
1022 // on the file size. Now that it is an ELF file, we need to inspect
1023 // the ELF file to understand the in memory segment layout including
1024 // where the oat header is located within. ImageWriter's
1025 // PatchOatCodeAndMethods uses the PatchInformation from the
1026 // Compiler to touch up absolute references in the oat file.
1027 //
1028 // 3. We fixup the ELF program headers so that dlopen will try to
1029 // load the .so at the desired location at runtime by offsetting the
1030 // Elf32_Phdr.p_vaddr values by the desired base address.
1031 //
1032 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001033 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001034 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1035 image_base,
1036 oat_unstripped,
1037 oat_location,
1038 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039 if (!image_creation_success) {
1040 return EXIT_FAILURE;
1041 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001042 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001043 }
1044
1045 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001046 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001047 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001048 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001049 return EXIT_SUCCESS;
1050 }
1051
1052 // If we don't want to strip in place, copy from unstripped location to stripped location.
1053 // We need to strip after image creation because FixupElf needs to use .strtab.
1054 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001055 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001056 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001057 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1058 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001059 size_t buffer_size = 8192;
1060 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1061 while (true) {
1062 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1063 if (bytes_read <= 0) {
1064 break;
1065 }
1066 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1067 CHECK(write_ok);
1068 }
1069 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001070 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001071 }
1072
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001073#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001074 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001075 // Strip unneeded sections for target
1076 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1077 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001078 std::string error_msg;
1079 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001080
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081
1082 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001083 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001084#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001085
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001086 timings.EndSplit();
1087
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001088 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001089 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001090 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001091
1092 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1093 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1094 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
1095 exit(EXIT_SUCCESS);
1096 }
1097
Brian Carlstrom7940e442013-07-12 13:46:57 -07001098 return EXIT_SUCCESS;
1099}
1100
Brian Carlstrom45602482013-07-21 22:07:55 -07001101
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001102} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103
1104int main(int argc, char** argv) {
1105 return art::dex2oat(argc, argv);
1106}