blob: a8bd74cfc62800064a0a20af586fd0111d00d1bb [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 Rogers51db7be2013-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;)
203 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const std::string& zip_filename,
204 const char* image_classes_filename) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename));
206 if (zip_archive.get() == NULL) {
207 LOG(ERROR) << "Failed to open zip file " << zip_filename;
208 return NULL;
209 }
210 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
211 if (zip_entry.get() == NULL) {
212 LOG(ERROR) << "Failed to find " << image_classes_filename << " within " << zip_filename;
213 return NULL;
214 }
215 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename));
216 if (image_classes_file.get() == NULL) {
217 LOG(ERROR) << "Failed to extract " << image_classes_filename << " from " << zip_filename;
218 return NULL;
219 }
220 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
221 image_classes_file->Size());
222 std::istringstream image_classes_stream(image_classes_string);
223 return ReadImageClasses(image_classes_stream);
224 }
225
226 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
227 const std::string* host_prefix,
228 const std::string& android_root,
229 bool is_host,
230 const std::vector<const DexFile*>& dex_files,
231 File* oat_file,
232 const std::string& bitcode_filename,
233 bool image,
234 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
235 bool dump_stats,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700236 base::TimingLogger& timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 // SirtRef and ClassLoader creation needs to come after Runtime::Create
238 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700239 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 if (!boot_image_option.empty()) {
241 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
242 std::vector<const DexFile*> class_path_files(dex_files);
243 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700244 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700245 for (size_t i = 0; i < class_path_files.size(); i++) {
246 class_linker->RegisterDexFile(*class_path_files[i]);
247 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
249 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
250 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
251 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
252 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
253 }
254
255 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
256 instruction_set_,
257 image,
258 image_classes.release(),
259 thread_count_,
Brian Carlstrom45602482013-07-21 22:07:55 -0700260 dump_stats));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261
262 if (compiler_backend_ == kPortable) {
263 driver->SetBitcodeFileName(bitcode_filename);
264 }
265
Brian Carlstrom45602482013-07-21 22:07:55 -0700266 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700267
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700268 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700269 std::string image_file_location;
270 uint32_t image_file_location_oat_checksum = 0;
271 uint32_t image_file_location_oat_data_begin = 0;
272 if (!driver->IsImage()) {
273 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
274 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
275 image_file_location_oat_data_begin =
276 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
277 image_file_location = image_space->GetImageFilename();
278 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
279 image_file_location = image_file_location.substr(host_prefix->size());
280 }
281 }
282
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700283 OatWriter oat_writer(dex_files,
284 image_file_location_oat_checksum,
285 image_file_location_oat_data_begin,
286 image_file_location,
287 driver.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700288
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700289 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700290 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
291 return NULL;
292 }
293
294 return driver.release();
295 }
296
297 bool CreateImageFile(const std::string& image_filename,
298 uintptr_t image_base,
299 const std::string& oat_filename,
300 const std::string& oat_location,
301 const CompilerDriver& compiler)
302 LOCKS_EXCLUDED(Locks::mutator_lock_) {
303 uintptr_t oat_data_begin;
304 {
305 // ImageWriter is scoped so it can free memory before doing FixupElf
306 ImageWriter image_writer(compiler);
307 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
308 LOG(ERROR) << "Failed to create image file " << image_filename;
309 return false;
310 }
311 oat_data_begin = image_writer.GetOatDataBegin();
312 }
313
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700314 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700315 if (oat_file.get() == NULL) {
316 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
317 return false;
318 }
319 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
320 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
321 return false;
322 }
323 return true;
324 }
325
326 private:
Brian Carlstrom45602482013-07-21 22:07:55 -0700327 explicit Dex2Oat(Runtime* runtime,
328 CompilerBackend compiler_backend,
329 InstructionSet instruction_set,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700330 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 : compiler_backend_(compiler_backend),
332 instruction_set_(instruction_set),
333 runtime_(runtime),
334 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 start_ns_(NanoTime()) {
336 }
337
338 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
339 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
340 if (!Runtime::Create(options, false)) {
341 LOG(ERROR) << "Failed to create runtime";
342 return false;
343 }
344 Runtime* runtime = Runtime::Current();
345 // if we loaded an existing image, we will reuse values from the image roots.
346 if (!runtime->HasResolutionMethod()) {
347 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
348 }
349 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
350 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
351 if (!runtime->HasCalleeSaveMethod(type)) {
352 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
353 }
354 }
355 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
356 return true;
357 }
358
359 // Appends to dex_files any elements of class_path that it doesn't already
360 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700361 static void OpenClassPathFiles(const std::string& class_path,
362 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700363 std::vector<std::string> parsed;
364 Split(class_path, ':', parsed);
365 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
366 ScopedObjectAccess soa(Thread::Current());
367 for (size_t i = 0; i < parsed.size(); ++i) {
368 if (DexFilesContains(dex_files, parsed[i])) {
369 continue;
370 }
371 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
372 if (dex_file == NULL) {
373 LOG(WARNING) << "Failed to open dex file " << parsed[i];
374 } else {
375 dex_files.push_back(dex_file);
376 }
377 }
378 }
379
380 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700381 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
382 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700383 for (size_t i = 0; i < dex_files.size(); ++i) {
384 if (dex_files[i]->GetLocation() == location) {
385 return true;
386 }
387 }
388 return false;
389 }
390
391 const CompilerBackend compiler_backend_;
392
393 const InstructionSet instruction_set_;
394
395 Runtime* runtime_;
396 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 uint64_t start_ns_;
398
399 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
400};
401
402static bool ParseInt(const char* in, int* out) {
403 char* end;
404 int result = strtol(in, &end, 10);
405 if (in == end || *end != '\0') {
406 return false;
407 }
408 *out = result;
409 return true;
410}
411
Brian Carlstromeb4d2ae2013-11-08 18:25:47 -0800412static void OpenDexFiles(const std::vector<const char*>& dex_filenames,
413 const std::vector<const char*>& dex_locations,
414 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700415 for (size_t i = 0; i < dex_filenames.size(); i++) {
416 const char* dex_filename = dex_filenames[i];
417 const char* dex_location = dex_locations[i];
418 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
419 if (dex_file == NULL) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700420 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "'\n";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421 } else {
422 dex_files.push_back(dex_file);
423 }
424 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425}
426
427// The primary goal of the watchdog is to prevent stuck build servers
428// during development when fatal aborts lead to a cascade of failures
429// that result in a deadlock.
430class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
432#undef CHECK_PTHREAD_CALL
433#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
434 do { \
435 int rc = call args; \
436 if (rc != 0) { \
437 errno = rc; \
438 std::string message(# call); \
439 message += " failed for "; \
440 message += reason; \
441 Fatal(message); \
442 } \
443 } while (false)
444
445 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700446 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447 is_watch_dog_enabled_ = is_watch_dog_enabled;
448 if (!is_watch_dog_enabled_) {
449 return;
450 }
451 shutting_down_ = false;
452 const char* reason = "dex2oat watch dog thread startup";
453 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
454 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
455 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
456 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
457 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
458 }
459 ~WatchDog() {
460 if (!is_watch_dog_enabled_) {
461 return;
462 }
463 const char* reason = "dex2oat watch dog thread shutdown";
464 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
465 shutting_down_ = true;
466 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
467 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
468
469 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
470
471 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
472 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
473 }
474
475 private:
476 static void* CallBack(void* arg) {
477 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
478 ::art::SetThreadName("dex2oat watch dog");
479 self->Wait();
480 return NULL;
481 }
482
483 static void Message(char severity, const std::string& message) {
484 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
485 // cases.
486 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
487 kIsDebugBuild ? "d" : "",
488 severity,
489 getpid(),
490 GetTid(),
491 message.c_str());
492 }
493
494 static void Warn(const std::string& message) {
495 Message('W', message);
496 }
497
498 static void Fatal(const std::string& message) {
499 Message('F', message);
500 exit(1);
501 }
502
503 void Wait() {
504 bool warning = true;
505 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
506 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
507 // large.
508 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
509 timespec warning_ts;
510 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
511 timespec timeout_ts;
512 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
513 const char* reason = "dex2oat watch dog thread waiting";
514 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
515 while (!shutting_down_) {
516 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
517 warning ? &warning_ts
518 : &timeout_ts));
519 if (rc == ETIMEDOUT) {
520 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
521 warning ? kWatchDogWarningSeconds
522 : kWatchDogTimeoutSeconds));
523 if (warning) {
524 Warn(message.c_str());
525 warning = false;
526 } else {
527 Fatal(message.c_str());
528 }
529 } else if (rc != 0) {
530 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
531 strerror(errno)));
532 Fatal(message.c_str());
533 }
534 }
535 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
536 }
537
538 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
539#if ART_USE_PORTABLE_COMPILER
540 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
541 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
542#else
543 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
544 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
545#endif
546
547 bool is_watch_dog_enabled_;
548 bool shutting_down_;
549 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
550 pthread_mutex_t mutex_;
551 pthread_cond_t cond_;
552 pthread_attr_t attr_;
553 pthread_t pthread_;
554};
555const unsigned int WatchDog::kWatchDogWarningSeconds;
556const unsigned int WatchDog::kWatchDogTimeoutSeconds;
557
558static int dex2oat(int argc, char** argv) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700559 base::TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700560
Brian Carlstrom7940e442013-07-12 13:46:57 -0700561 InitLogging(argv);
562
563 // Skip over argv[0].
564 argv++;
565 argc--;
566
567 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700568 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700569 }
570
571 std::vector<const char*> dex_filenames;
572 std::vector<const char*> dex_locations;
573 int zip_fd = -1;
574 std::string zip_location;
575 std::string oat_filename;
576 std::string oat_symbols;
577 std::string oat_location;
578 int oat_fd = -1;
579 std::string bitcode_filename;
580 const char* image_classes_zip_filename = NULL;
581 const char* image_classes_filename = NULL;
582 std::string image_filename;
583 std::string boot_image_filename;
584 uintptr_t image_base = 0;
585 UniquePtr<std::string> host_prefix;
586 std::string android_root;
587 std::vector<const char*> runtime_args;
588 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700589#if defined(ART_USE_PORTABLE_COMPILER)
590 CompilerBackend compiler_backend = kPortable;
591#else
592 CompilerBackend compiler_backend = kQuick;
593#endif
594#if defined(__arm__)
595 InstructionSet instruction_set = kThumb2;
596#elif defined(__i386__)
597 InstructionSet instruction_set = kX86;
598#elif defined(__mips__)
599 InstructionSet instruction_set = kMips;
600#else
601#error "Unsupported architecture"
602#endif
603 bool is_host = false;
604 bool dump_stats = kIsDebugBuild;
Ian Rogers46398602013-08-20 07:50:36 -0700605 bool dump_timing = false;
606 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700607 bool watch_dog_enabled = !kIsTargetBuild;
608
609
610 for (int i = 0; i < argc; i++) {
611 const StringPiece option(argv[i]);
612 bool log_options = false;
613 if (log_options) {
614 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
615 }
616 if (option.starts_with("--dex-file=")) {
617 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
618 } else if (option.starts_with("--dex-location=")) {
619 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
620 } else if (option.starts_with("--zip-fd=")) {
621 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
622 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700623 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700624 }
625 } else if (option.starts_with("--zip-location=")) {
626 zip_location = option.substr(strlen("--zip-location=")).data();
627 } else if (option.starts_with("--oat-file=")) {
628 oat_filename = option.substr(strlen("--oat-file=")).data();
629 } else if (option.starts_with("--oat-symbols=")) {
630 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
631 } else if (option.starts_with("--oat-fd=")) {
632 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
633 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700634 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700635 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636 } else if (option == "--watch-dog") {
637 watch_dog_enabled = true;
638 } else if (option == "--no-watch-dog") {
639 watch_dog_enabled = false;
640 } else if (option.starts_with("-j")) {
641 const char* thread_count_str = option.substr(strlen("-j")).data();
642 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700643 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700644 }
645 } else if (option.starts_with("--oat-location=")) {
646 oat_location = option.substr(strlen("--oat-location=")).data();
647 } else if (option.starts_with("--bitcode=")) {
648 bitcode_filename = option.substr(strlen("--bitcode=")).data();
649 } else if (option.starts_with("--image=")) {
650 image_filename = option.substr(strlen("--image=")).data();
651 } else if (option.starts_with("--image-classes=")) {
652 image_classes_filename = option.substr(strlen("--image-classes=")).data();
653 } else if (option.starts_with("--image-classes-zip=")) {
654 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
655 } else if (option.starts_with("--base=")) {
656 const char* image_base_str = option.substr(strlen("--base=")).data();
657 char* end;
658 image_base = strtoul(image_base_str, &end, 16);
659 if (end == image_base_str || *end != '\0') {
660 Usage("Failed to parse hexadecimal value for option %s", option.data());
661 }
662 } else if (option.starts_with("--boot-image=")) {
663 boot_image_filename = option.substr(strlen("--boot-image=")).data();
664 } else if (option.starts_with("--host-prefix=")) {
665 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
666 } else if (option.starts_with("--android-root=")) {
667 android_root = option.substr(strlen("--android-root=")).data();
668 } else if (option.starts_with("--instruction-set=")) {
669 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
670 if (instruction_set_str == "arm") {
671 instruction_set = kThumb2;
672 } else if (instruction_set_str == "mips") {
673 instruction_set = kMips;
674 } else if (instruction_set_str == "x86") {
675 instruction_set = kX86;
676 }
677 } else if (option.starts_with("--compiler-backend=")) {
678 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
679 if (backend_str == "Quick") {
680 compiler_backend = kQuick;
681 } else if (backend_str == "Portable") {
682 compiler_backend = kPortable;
683 }
684 } else if (option == "--host") {
685 is_host = true;
686 } else if (option == "--runtime-arg") {
687 if (++i >= argc) {
688 Usage("Missing required argument for --runtime-arg");
689 }
690 if (log_options) {
691 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
692 }
693 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700694 } else if (option == "--dump-timing") {
695 dump_timing = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700696 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700697 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 }
699 }
700
701 if (oat_filename.empty() && oat_fd == -1) {
702 Usage("Output must be supplied with either --oat-file or --oat-fd");
703 }
704
705 if (!oat_filename.empty() && oat_fd != -1) {
706 Usage("--oat-file should not be used with --oat-fd");
707 }
708
709 if (!oat_symbols.empty() && oat_fd != -1) {
710 Usage("--oat-symbols should not be used with --oat-fd");
711 }
712
713 if (!oat_symbols.empty() && is_host) {
714 Usage("--oat-symbols should not be used with --host");
715 }
716
717 if (oat_fd != -1 && !image_filename.empty()) {
718 Usage("--oat-fd should not be used with --image");
719 }
720
721 if (host_prefix.get() == NULL) {
722 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
723 if (android_product_out != NULL) {
724 host_prefix.reset(new std::string(android_product_out));
725 }
726 }
727
728 if (android_root.empty()) {
729 const char* android_root_env_var = getenv("ANDROID_ROOT");
730 if (android_root_env_var == NULL) {
731 Usage("--android-root unspecified and ANDROID_ROOT not set");
732 }
733 android_root += android_root_env_var;
734 }
735
736 bool image = (!image_filename.empty());
737 if (!image && boot_image_filename.empty()) {
738 if (host_prefix.get() == NULL) {
739 boot_image_filename += GetAndroidRoot();
740 } else {
741 boot_image_filename += *host_prefix.get();
742 boot_image_filename += "/system";
743 }
744 boot_image_filename += "/framework/boot.art";
745 }
746 std::string boot_image_option;
747 if (!boot_image_filename.empty()) {
748 boot_image_option += "-Ximage:";
749 boot_image_option += boot_image_filename;
750 }
751
752 if (image_classes_filename != NULL && !image) {
753 Usage("--image-classes should only be used with --image");
754 }
755
756 if (image_classes_filename != NULL && !boot_image_option.empty()) {
757 Usage("--image-classes should not be used with --boot-image");
758 }
759
760 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
761 Usage("--image-classes-zip should be used with --image-classes");
762 }
763
764 if (dex_filenames.empty() && zip_fd == -1) {
765 Usage("Input must be supplied with either --dex-file or --zip-fd");
766 }
767
768 if (!dex_filenames.empty() && zip_fd != -1) {
769 Usage("--dex-file should not be used with --zip-fd");
770 }
771
772 if (!dex_filenames.empty() && !zip_location.empty()) {
773 Usage("--dex-file should not be used with --zip-location");
774 }
775
776 if (dex_locations.empty()) {
777 for (size_t i = 0; i < dex_filenames.size(); i++) {
778 dex_locations.push_back(dex_filenames[i]);
779 }
780 } else if (dex_locations.size() != dex_filenames.size()) {
781 Usage("--dex-location arguments do not match --dex-file arguments");
782 }
783
784 if (zip_fd != -1 && zip_location.empty()) {
785 Usage("--zip-location should be supplied with --zip-fd");
786 }
787
788 if (boot_image_option.empty()) {
789 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700790 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700791 }
792 }
793
794 std::string oat_stripped(oat_filename);
795 std::string oat_unstripped;
796 if (!oat_symbols.empty()) {
797 oat_unstripped += oat_symbols;
798 } else {
799 oat_unstripped += oat_filename;
800 }
801
802 // Done with usage checks, enable watchdog if requested
803 WatchDog watch_dog(watch_dog_enabled);
804
805 // Check early that the result of compilation can be written
806 UniquePtr<File> oat_file;
807 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
808 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700809 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700810 if (oat_location.empty()) {
811 oat_location = oat_filename;
812 }
813 } else {
814 oat_file.reset(new File(oat_fd, oat_location));
815 oat_file->DisableAutoClose();
816 }
817 if (oat_file.get() == NULL) {
818 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
819 return EXIT_FAILURE;
820 }
821 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
822 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
823 return EXIT_FAILURE;
824 }
825
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700826 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700827 LOG(INFO) << "dex2oat: " << oat_location;
828
Ian Rogersf30f6da2013-08-28 17:33:30 -0700829 if (image) {
830 bool has_compiler_filter = false;
831 for (const char* r : runtime_args) {
832 if (strncmp(r, "-compiler-filter:", 17) == 0) {
833 has_compiler_filter = true;
834 break;
835 }
836 }
837 if (!has_compiler_filter) {
838 runtime_args.push_back("-compiler-filter:everything");
839 }
840 }
841
Brian Carlstrom7940e442013-07-12 13:46:57 -0700842 Runtime::Options options;
843 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
844 std::vector<const DexFile*> boot_class_path;
845 if (boot_image_option.empty()) {
Brian Carlstromeb4d2ae2013-11-08 18:25:47 -0800846 OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
848 } else {
849 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
850 }
851 if (host_prefix.get() != NULL) {
852 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
853 }
854 for (size_t i = 0; i < runtime_args.size(); i++) {
855 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
856 }
857
Brian Carlstrom7940e442013-07-12 13:46:57 -0700858#ifdef ART_SEA_IR_MODE
859 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
860#endif
861
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862 Dex2Oat* p_dex2oat;
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700863 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700864 LOG(ERROR) << "Failed to create dex2oat";
865 return EXIT_FAILURE;
866 }
867 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
868 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700869 // give it away now so that we don't starve GC.
870 Thread* self = Thread::Current();
871 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700872 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700873 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
874 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700876 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700877
878 // If --image-classes was specified, calculate the full list of classes to include in the image
879 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
880 if (image_classes_filename != NULL) {
881 if (image_classes_zip_filename != NULL) {
882 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
883 image_classes_filename));
884 } else {
885 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
886 }
887 if (image_classes.get() == NULL) {
888 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
889 return EXIT_FAILURE;
890 }
891 }
892
893 std::vector<const DexFile*> dex_files;
894 if (boot_image_option.empty()) {
895 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
896 } else {
897 if (dex_filenames.empty()) {
898 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
899 if (zip_archive.get() == NULL) {
900 LOG(ERROR) << "Failed to open zip from file descriptor for " << zip_location;
901 return EXIT_FAILURE;
902 }
903 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
904 if (dex_file == NULL) {
905 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
906 return EXIT_FAILURE;
907 }
908 dex_files.push_back(dex_file);
909 } else {
Brian Carlstromeb4d2ae2013-11-08 18:25:47 -0800910 OpenDexFiles(dex_filenames, dex_locations, dex_files);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700911 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700912
913 // Ensure opened dex files are writable for dex-to-dex transformations.
914 for (const auto& dex_file : dex_files) {
915 if (!dex_file->EnableWrite()) {
916 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
917 }
918 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700919 }
920
buzbeea024a062013-07-31 10:47:37 -0700921 /*
922 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
923 * bother to check if we're doing the image.
924 */
925 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 size_t num_methods = 0;
927 for (size_t i = 0; i != dex_files.size(); ++i) {
928 const DexFile* dex_file = dex_files[i];
929 CHECK(dex_file != NULL);
930 num_methods += dex_file->NumMethodIds();
931 }
buzbeea024a062013-07-31 10:47:37 -0700932 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
933 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700934 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700935 }
936 }
937
938 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
939 host_prefix.get(),
940 android_root,
941 is_host,
942 dex_files,
943 oat_file.get(),
944 bitcode_filename,
945 image,
946 image_classes,
947 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -0700948 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700949
950 if (compiler.get() == NULL) {
951 LOG(ERROR) << "Failed to create oat file: " << oat_location;
952 return EXIT_FAILURE;
953 }
954
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700955 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700956
957 // Notes on the interleaving of creating the image and oat file to
958 // ensure the references between the two are correct.
959 //
960 // Currently we have a memory layout that looks something like this:
961 //
962 // +--------------+
963 // | image |
964 // +--------------+
965 // | boot oat |
966 // +--------------+
967 // | alloc spaces |
968 // +--------------+
969 //
Brian Carlstrom45602482013-07-21 22:07:55 -0700970 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971 //
972 // 1. The image is expected to be loaded at an absolute address and
973 // contains Objects with absolute pointers within the image.
974 //
975 // 2. There are absolute pointers from Methods in the image to their
976 // code in the oat.
977 //
978 // 3. There are absolute pointers from the code in the oat to Methods
979 // in the image.
980 //
981 // 4. There are absolute pointers from code in the oat to other code
982 // in the oat.
983 //
984 // To get this all correct, we go through several steps.
985 //
986 // 1. We have already created that oat file above with
987 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -0700988 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -0700989 // file). The Compiler returned by CreateOatFile provides
990 // PatchInformation for references to oat code and Methods that need
991 // to be update once we know where the oat file will be located
992 // after the image.
993 //
994 // 2. We create the image file. It needs to know where the oat file
995 // will be loaded after itself. Originally when oat file was simply
996 // memory mapped so we could predict where its contents were based
997 // on the file size. Now that it is an ELF file, we need to inspect
998 // the ELF file to understand the in memory segment layout including
999 // where the oat header is located within. ImageWriter's
1000 // PatchOatCodeAndMethods uses the PatchInformation from the
1001 // Compiler to touch up absolute references in the oat file.
1002 //
1003 // 3. We fixup the ELF program headers so that dlopen will try to
1004 // load the .so at the desired location at runtime by offsetting the
1005 // Elf32_Phdr.p_vaddr values by the desired base address.
1006 //
1007 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001008 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1010 image_base,
1011 oat_unstripped,
1012 oat_location,
1013 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 if (!image_creation_success) {
1015 return EXIT_FAILURE;
1016 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001017 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 }
1019
1020 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001021 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001022 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001023 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024 return EXIT_SUCCESS;
1025 }
1026
1027 // If we don't want to strip in place, copy from unstripped location to stripped location.
1028 // We need to strip after image creation because FixupElf needs to use .strtab.
1029 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001030 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001031 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001032 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1033 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001034 size_t buffer_size = 8192;
1035 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1036 while (true) {
1037 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1038 if (bytes_read <= 0) {
1039 break;
1040 }
1041 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1042 CHECK(write_ok);
1043 }
1044 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001045 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046 }
1047
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001048#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001049 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001050 // Strip unneeded sections for target
1051 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1052 CHECK_EQ(0, seek_actual);
1053 ElfStripper::Strip(oat_file.get());
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001054
Brian Carlstrom7940e442013-07-12 13:46:57 -07001055
1056 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001057 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001058#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001059
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001060 timings.EndSplit();
1061
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001062 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001063 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001064 }
Ian Rogers51db7be2013-09-05 17:24:22 -07001065
1066 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1067 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1068 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
1069 exit(EXIT_SUCCESS);
1070 }
1071
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072 return EXIT_SUCCESS;
1073}
1074
Brian Carlstrom45602482013-07-21 22:07:55 -07001075
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001076} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001077
1078int main(int argc, char** argv) {
1079 return art::dex2oat(argc, argv);
1080}