blob: b6a7683a54d3ea37a7ec30e00dd130512be409be [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>
20
21#include <fstream>
22#include <iostream>
23#include <sstream>
24#include <string>
25#include <vector>
26
27#include "base/stl_util.h"
28#include "base/stringpiece.h"
29#include "base/timing_logger.h"
30#include "base/unix_file/fd_file.h"
31#include "class_linker.h"
32#include "dex_file-inl.h"
33#include "driver/compiler_driver.h"
34#include "elf_fixup.h"
35#include "elf_stripper.h"
36#include "gc/space/image_space.h"
37#include "gc/space/space-inl.h"
38#include "image_writer.h"
39#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070040#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "mirror/class-inl.h"
42#include "mirror/class_loader.h"
43#include "mirror/object-inl.h"
44#include "mirror/object_array-inl.h"
45#include "oat_writer.h"
46#include "object_utils.h"
47#include "os.h"
48#include "runtime.h"
49#include "ScopedLocalRef.h"
50#include "scoped_thread_state_change.h"
51#include "sirt_ref.h"
52#include "vector_output_stream.h"
53#include "well_known_classes.h"
54#include "zip_archive.h"
55
56namespace art {
57
58static void UsageErrorV(const char* fmt, va_list ap) {
59 std::string error;
60 StringAppendV(&error, fmt, ap);
61 LOG(ERROR) << error;
62}
63
64static void UsageError(const char* fmt, ...) {
65 va_list ap;
66 va_start(ap, fmt);
67 UsageErrorV(fmt, ap);
68 va_end(ap);
69}
70
71static void Usage(const char* fmt, ...) {
72 va_list ap;
73 va_start(ap, fmt);
74 UsageErrorV(fmt, ap);
75 va_end(ap);
76
77 UsageError("Usage: dex2oat [options]...");
78 UsageError("");
79 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
80 UsageError(" Example: --dex-file=/system/framework/core.jar");
81 UsageError("");
82 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
83 UsageError(" containing a classes.dex file to compile.");
84 UsageError(" Example: --zip-fd=5");
85 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -070086 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
87 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -070088 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
89 UsageError("");
90 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
91 UsageError(" Example: --oat-file=/system/framework/boot.oat");
92 UsageError("");
93 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
94 UsageError(" Example: --oat-file=/system/framework/boot.oat");
95 UsageError("");
96 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
97 UsageError(" to the file descriptor specified by --oat-fd.");
98 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
99 UsageError("");
100 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
101 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
102 UsageError("");
103 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
104 UsageError(" Example: --bitcode=/system/framework/boot.bc");
105 UsageError("");
106 UsageError(" --image=<file.art>: specifies the output image filename.");
107 UsageError(" Example: --image=/system/framework/boot.art");
108 UsageError("");
109 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
110 UsageError(" Example: --image=frameworks/base/preloaded-classes");
111 UsageError("");
112 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
113 UsageError(" Example: --base=0x50000000");
114 UsageError("");
115 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
116 UsageError(" Example: --boot-image=/system/framework/boot.art");
117 UsageError(" Default: <host-prefix>/system/framework/boot.art");
118 UsageError("");
119 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
120 UsageError(" cross compilation.");
121 UsageError(" Example: --host-prefix=out/target/product/crespo");
122 UsageError(" Default: $ANDROID_PRODUCT_OUT");
123 UsageError("");
124 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
125 UsageError(" Example: --android-root=out/host/linux-x86");
126 UsageError(" Default: $ANDROID_ROOT");
127 UsageError("");
128 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
129 UsageError(" set.");
130 UsageError(" Example: --instruction-set=x86");
131 UsageError(" Default: arm");
132 UsageError("");
133 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
134 UsageError(" set.");
135 UsageError(" Example: --instruction-set=Portable");
136 UsageError(" Default: Quick");
137 UsageError("");
138 UsageError(" --host: used with Portable backend to link against host runtime libraries");
139 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700140 UsageError(" --dump-timing: display a breakdown of where time was spent");
141 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700142 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
143 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
144 UsageError(" Use a separate --runtime-arg switch for each argument.");
145 UsageError(" Example: --runtime-arg -Xms256m");
146 UsageError("");
147 std::cerr << "See log for usage error information\n";
148 exit(EXIT_FAILURE);
149}
150
151class Dex2Oat {
152 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700153 static bool Create(Dex2Oat** p_dex2oat,
154 Runtime::Options& options,
155 CompilerBackend compiler_backend,
156 InstructionSet instruction_set,
157 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700158 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
159 if (!CreateRuntime(options, instruction_set)) {
160 *p_dex2oat = NULL;
161 return false;
162 }
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700163 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 return true;
165 }
166
167 ~Dex2Oat() {
168 delete runtime_;
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700169 VLOG(compiler) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700170 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 }
172
173
Brian Carlstrom45602482013-07-21 22:07:55 -0700174 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Brian Carlstrom45602482013-07-21 22:07:55 -0700176 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
177 std::ifstream::in));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 if (image_classes_file.get() == NULL) {
179 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
180 return NULL;
181 }
182 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
183 image_classes_file->close();
184 return result.release();
185 }
186
187 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
188 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
189 while (image_classes_stream.good()) {
190 std::string dot;
191 std::getline(image_classes_stream, dot);
192 if (StartsWith(dot, "#") || dot.empty()) {
193 continue;
194 }
195 std::string descriptor(DotToDescriptor(dot.c_str()));
196 image_classes->insert(descriptor);
197 }
198 return image_classes.release();
199 }
200
Brian Carlstrom45602482013-07-21 22:07:55 -0700201 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
202 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const std::string& zip_filename,
203 const char* image_classes_filename) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700204 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename));
205 if (zip_archive.get() == NULL) {
206 LOG(ERROR) << "Failed to open zip file " << zip_filename;
207 return NULL;
208 }
209 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
210 if (zip_entry.get() == NULL) {
211 LOG(ERROR) << "Failed to find " << image_classes_filename << " within " << zip_filename;
212 return NULL;
213 }
214 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename));
215 if (image_classes_file.get() == NULL) {
216 LOG(ERROR) << "Failed to extract " << image_classes_filename << " from " << zip_filename;
217 return NULL;
218 }
219 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
220 image_classes_file->Size());
221 std::istringstream image_classes_stream(image_classes_string);
222 return ReadImageClasses(image_classes_stream);
223 }
224
225 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
226 const std::string* host_prefix,
227 const std::string& android_root,
228 bool is_host,
229 const std::vector<const DexFile*>& dex_files,
230 File* oat_file,
231 const std::string& bitcode_filename,
232 bool image,
233 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
234 bool dump_stats,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700235 base::TimingLogger& timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 // SirtRef and ClassLoader creation needs to come after Runtime::Create
237 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700238 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 if (!boot_image_option.empty()) {
240 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
241 std::vector<const DexFile*> class_path_files(dex_files);
242 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700243 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700244 for (size_t i = 0; i < class_path_files.size(); i++) {
245 class_linker->RegisterDexFile(*class_path_files[i]);
246 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
248 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
249 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
250 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
251 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
252 }
253
254 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
255 instruction_set_,
256 image,
257 image_classes.release(),
258 thread_count_,
Brian Carlstrom45602482013-07-21 22:07:55 -0700259 dump_stats));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260
261 if (compiler_backend_ == kPortable) {
262 driver->SetBitcodeFileName(bitcode_filename);
263 }
264
Brian Carlstrom45602482013-07-21 22:07:55 -0700265 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700266
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700267 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268 std::string image_file_location;
269 uint32_t image_file_location_oat_checksum = 0;
270 uint32_t image_file_location_oat_data_begin = 0;
271 if (!driver->IsImage()) {
272 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
273 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
274 image_file_location_oat_data_begin =
275 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
276 image_file_location = image_space->GetImageFilename();
277 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
278 image_file_location = image_file_location.substr(host_prefix->size());
279 }
280 }
281
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700282 OatWriter oat_writer(dex_files,
283 image_file_location_oat_checksum,
284 image_file_location_oat_data_begin,
285 image_file_location,
286 driver.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700287
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700288 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
290 return NULL;
291 }
292
293 return driver.release();
294 }
295
296 bool CreateImageFile(const std::string& image_filename,
297 uintptr_t image_base,
298 const std::string& oat_filename,
299 const std::string& oat_location,
300 const CompilerDriver& compiler)
301 LOCKS_EXCLUDED(Locks::mutator_lock_) {
302 uintptr_t oat_data_begin;
303 {
304 // ImageWriter is scoped so it can free memory before doing FixupElf
305 ImageWriter image_writer(compiler);
306 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
307 LOG(ERROR) << "Failed to create image file " << image_filename;
308 return false;
309 }
310 oat_data_begin = image_writer.GetOatDataBegin();
311 }
312
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700313 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700314 if (oat_file.get() == NULL) {
315 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
316 return false;
317 }
318 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
319 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
320 return false;
321 }
322 return true;
323 }
324
325 private:
Brian Carlstrom45602482013-07-21 22:07:55 -0700326 explicit Dex2Oat(Runtime* runtime,
327 CompilerBackend compiler_backend,
328 InstructionSet instruction_set,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700329 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700330 : compiler_backend_(compiler_backend),
331 instruction_set_(instruction_set),
332 runtime_(runtime),
333 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 start_ns_(NanoTime()) {
335 }
336
337 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
338 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
339 if (!Runtime::Create(options, false)) {
340 LOG(ERROR) << "Failed to create runtime";
341 return false;
342 }
343 Runtime* runtime = Runtime::Current();
344 // if we loaded an existing image, we will reuse values from the image roots.
345 if (!runtime->HasResolutionMethod()) {
346 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
347 }
348 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
349 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
350 if (!runtime->HasCalleeSaveMethod(type)) {
351 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
352 }
353 }
354 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
355 return true;
356 }
357
358 // Appends to dex_files any elements of class_path that it doesn't already
359 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700360 static void OpenClassPathFiles(const std::string& class_path,
361 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700362 std::vector<std::string> parsed;
363 Split(class_path, ':', parsed);
364 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
365 ScopedObjectAccess soa(Thread::Current());
366 for (size_t i = 0; i < parsed.size(); ++i) {
367 if (DexFilesContains(dex_files, parsed[i])) {
368 continue;
369 }
370 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
371 if (dex_file == NULL) {
372 LOG(WARNING) << "Failed to open dex file " << parsed[i];
373 } else {
374 dex_files.push_back(dex_file);
375 }
376 }
377 }
378
379 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700380 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
381 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382 for (size_t i = 0; i < dex_files.size(); ++i) {
383 if (dex_files[i]->GetLocation() == location) {
384 return true;
385 }
386 }
387 return false;
388 }
389
390 const CompilerBackend compiler_backend_;
391
392 const InstructionSet instruction_set_;
393
394 Runtime* runtime_;
395 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396 uint64_t start_ns_;
397
398 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
399};
400
401static bool ParseInt(const char* in, int* out) {
402 char* end;
403 int result = strtol(in, &end, 10);
404 if (in == end || *end != '\0') {
405 return false;
406 }
407 *out = result;
408 return true;
409}
410
411static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
412 const std::vector<const char*>& dex_locations,
413 std::vector<const DexFile*>& dex_files) {
414 size_t failure_count = 0;
415 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 ++failure_count;
422 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700423 // Ensure writable for dex-to-dex transformations.
424 if (!dex_file->EnableWrite()) {
425 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_filename << "'\n";
426 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 dex_files.push_back(dex_file);
428 }
429 }
430 return failure_count;
431}
432
433// The primary goal of the watchdog is to prevent stuck build servers
434// during development when fatal aborts lead to a cascade of failures
435// that result in a deadlock.
436class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
438#undef CHECK_PTHREAD_CALL
439#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
440 do { \
441 int rc = call args; \
442 if (rc != 0) { \
443 errno = rc; \
444 std::string message(# call); \
445 message += " failed for "; \
446 message += reason; \
447 Fatal(message); \
448 } \
449 } while (false)
450
451 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700452 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700453 is_watch_dog_enabled_ = is_watch_dog_enabled;
454 if (!is_watch_dog_enabled_) {
455 return;
456 }
457 shutting_down_ = false;
458 const char* reason = "dex2oat watch dog thread startup";
459 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
460 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
461 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
462 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
463 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
464 }
465 ~WatchDog() {
466 if (!is_watch_dog_enabled_) {
467 return;
468 }
469 const char* reason = "dex2oat watch dog thread shutdown";
470 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
471 shutting_down_ = true;
472 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
473 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
474
475 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
476
477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
478 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
479 }
480
481 private:
482 static void* CallBack(void* arg) {
483 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
484 ::art::SetThreadName("dex2oat watch dog");
485 self->Wait();
486 return NULL;
487 }
488
489 static void Message(char severity, const std::string& message) {
490 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
491 // cases.
492 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
493 kIsDebugBuild ? "d" : "",
494 severity,
495 getpid(),
496 GetTid(),
497 message.c_str());
498 }
499
500 static void Warn(const std::string& message) {
501 Message('W', message);
502 }
503
504 static void Fatal(const std::string& message) {
505 Message('F', message);
506 exit(1);
507 }
508
509 void Wait() {
510 bool warning = true;
511 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
512 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
513 // large.
514 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
515 timespec warning_ts;
516 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
517 timespec timeout_ts;
518 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
519 const char* reason = "dex2oat watch dog thread waiting";
520 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
521 while (!shutting_down_) {
522 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
523 warning ? &warning_ts
524 : &timeout_ts));
525 if (rc == ETIMEDOUT) {
526 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
527 warning ? kWatchDogWarningSeconds
528 : kWatchDogTimeoutSeconds));
529 if (warning) {
530 Warn(message.c_str());
531 warning = false;
532 } else {
533 Fatal(message.c_str());
534 }
535 } else if (rc != 0) {
536 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
537 strerror(errno)));
538 Fatal(message.c_str());
539 }
540 }
541 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
542 }
543
544 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
545#if ART_USE_PORTABLE_COMPILER
546 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
547 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
548#else
549 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
550 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
551#endif
552
553 bool is_watch_dog_enabled_;
554 bool shutting_down_;
555 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
556 pthread_mutex_t mutex_;
557 pthread_cond_t cond_;
558 pthread_attr_t attr_;
559 pthread_t pthread_;
560};
561const unsigned int WatchDog::kWatchDogWarningSeconds;
562const unsigned int WatchDog::kWatchDogTimeoutSeconds;
563
564static int dex2oat(int argc, char** argv) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700565 base::TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700566
Brian Carlstrom7940e442013-07-12 13:46:57 -0700567 InitLogging(argv);
568
569 // Skip over argv[0].
570 argv++;
571 argc--;
572
573 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700574 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700575 }
576
577 std::vector<const char*> dex_filenames;
578 std::vector<const char*> dex_locations;
579 int zip_fd = -1;
580 std::string zip_location;
581 std::string oat_filename;
582 std::string oat_symbols;
583 std::string oat_location;
584 int oat_fd = -1;
585 std::string bitcode_filename;
586 const char* image_classes_zip_filename = NULL;
587 const char* image_classes_filename = NULL;
588 std::string image_filename;
589 std::string boot_image_filename;
590 uintptr_t image_base = 0;
591 UniquePtr<std::string> host_prefix;
592 std::string android_root;
593 std::vector<const char*> runtime_args;
594 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595#if defined(ART_USE_PORTABLE_COMPILER)
596 CompilerBackend compiler_backend = kPortable;
597#else
598 CompilerBackend compiler_backend = kQuick;
599#endif
600#if defined(__arm__)
601 InstructionSet instruction_set = kThumb2;
602#elif defined(__i386__)
603 InstructionSet instruction_set = kX86;
604#elif defined(__mips__)
605 InstructionSet instruction_set = kMips;
606#else
607#error "Unsupported architecture"
608#endif
609 bool is_host = false;
610 bool dump_stats = kIsDebugBuild;
Ian Rogers46398602013-08-20 07:50:36 -0700611 bool dump_timing = false;
612 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700613 bool watch_dog_enabled = !kIsTargetBuild;
614
615
616 for (int i = 0; i < argc; i++) {
617 const StringPiece option(argv[i]);
618 bool log_options = false;
619 if (log_options) {
620 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
621 }
622 if (option.starts_with("--dex-file=")) {
623 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
624 } else if (option.starts_with("--dex-location=")) {
625 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
626 } else if (option.starts_with("--zip-fd=")) {
627 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
628 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700629 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700630 }
631 } else if (option.starts_with("--zip-location=")) {
632 zip_location = option.substr(strlen("--zip-location=")).data();
633 } else if (option.starts_with("--oat-file=")) {
634 oat_filename = option.substr(strlen("--oat-file=")).data();
635 } else if (option.starts_with("--oat-symbols=")) {
636 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
637 } else if (option.starts_with("--oat-fd=")) {
638 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
639 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700640 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700641 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642 } else if (option == "--watch-dog") {
643 watch_dog_enabled = true;
644 } else if (option == "--no-watch-dog") {
645 watch_dog_enabled = false;
646 } else if (option.starts_with("-j")) {
647 const char* thread_count_str = option.substr(strlen("-j")).data();
648 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700649 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700650 }
651 } else if (option.starts_with("--oat-location=")) {
652 oat_location = option.substr(strlen("--oat-location=")).data();
653 } else if (option.starts_with("--bitcode=")) {
654 bitcode_filename = option.substr(strlen("--bitcode=")).data();
655 } else if (option.starts_with("--image=")) {
656 image_filename = option.substr(strlen("--image=")).data();
657 } else if (option.starts_with("--image-classes=")) {
658 image_classes_filename = option.substr(strlen("--image-classes=")).data();
659 } else if (option.starts_with("--image-classes-zip=")) {
660 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
661 } else if (option.starts_with("--base=")) {
662 const char* image_base_str = option.substr(strlen("--base=")).data();
663 char* end;
664 image_base = strtoul(image_base_str, &end, 16);
665 if (end == image_base_str || *end != '\0') {
666 Usage("Failed to parse hexadecimal value for option %s", option.data());
667 }
668 } else if (option.starts_with("--boot-image=")) {
669 boot_image_filename = option.substr(strlen("--boot-image=")).data();
670 } else if (option.starts_with("--host-prefix=")) {
671 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
672 } else if (option.starts_with("--android-root=")) {
673 android_root = option.substr(strlen("--android-root=")).data();
674 } else if (option.starts_with("--instruction-set=")) {
675 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
676 if (instruction_set_str == "arm") {
677 instruction_set = kThumb2;
678 } else if (instruction_set_str == "mips") {
679 instruction_set = kMips;
680 } else if (instruction_set_str == "x86") {
681 instruction_set = kX86;
682 }
683 } else if (option.starts_with("--compiler-backend=")) {
684 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
685 if (backend_str == "Quick") {
686 compiler_backend = kQuick;
687 } else if (backend_str == "Portable") {
688 compiler_backend = kPortable;
689 }
690 } else if (option == "--host") {
691 is_host = true;
692 } else if (option == "--runtime-arg") {
693 if (++i >= argc) {
694 Usage("Missing required argument for --runtime-arg");
695 }
696 if (log_options) {
697 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
698 }
699 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700700 } else if (option == "--dump-timing") {
701 dump_timing = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700703 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700704 }
705 }
706
707 if (oat_filename.empty() && oat_fd == -1) {
708 Usage("Output must be supplied with either --oat-file or --oat-fd");
709 }
710
711 if (!oat_filename.empty() && oat_fd != -1) {
712 Usage("--oat-file should not be used with --oat-fd");
713 }
714
715 if (!oat_symbols.empty() && oat_fd != -1) {
716 Usage("--oat-symbols should not be used with --oat-fd");
717 }
718
719 if (!oat_symbols.empty() && is_host) {
720 Usage("--oat-symbols should not be used with --host");
721 }
722
723 if (oat_fd != -1 && !image_filename.empty()) {
724 Usage("--oat-fd should not be used with --image");
725 }
726
727 if (host_prefix.get() == NULL) {
728 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
729 if (android_product_out != NULL) {
730 host_prefix.reset(new std::string(android_product_out));
731 }
732 }
733
734 if (android_root.empty()) {
735 const char* android_root_env_var = getenv("ANDROID_ROOT");
736 if (android_root_env_var == NULL) {
737 Usage("--android-root unspecified and ANDROID_ROOT not set");
738 }
739 android_root += android_root_env_var;
740 }
741
742 bool image = (!image_filename.empty());
743 if (!image && boot_image_filename.empty()) {
744 if (host_prefix.get() == NULL) {
745 boot_image_filename += GetAndroidRoot();
746 } else {
747 boot_image_filename += *host_prefix.get();
748 boot_image_filename += "/system";
749 }
750 boot_image_filename += "/framework/boot.art";
751 }
752 std::string boot_image_option;
753 if (!boot_image_filename.empty()) {
754 boot_image_option += "-Ximage:";
755 boot_image_option += boot_image_filename;
756 }
757
758 if (image_classes_filename != NULL && !image) {
759 Usage("--image-classes should only be used with --image");
760 }
761
762 if (image_classes_filename != NULL && !boot_image_option.empty()) {
763 Usage("--image-classes should not be used with --boot-image");
764 }
765
766 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
767 Usage("--image-classes-zip should be used with --image-classes");
768 }
769
770 if (dex_filenames.empty() && zip_fd == -1) {
771 Usage("Input must be supplied with either --dex-file or --zip-fd");
772 }
773
774 if (!dex_filenames.empty() && zip_fd != -1) {
775 Usage("--dex-file should not be used with --zip-fd");
776 }
777
778 if (!dex_filenames.empty() && !zip_location.empty()) {
779 Usage("--dex-file should not be used with --zip-location");
780 }
781
782 if (dex_locations.empty()) {
783 for (size_t i = 0; i < dex_filenames.size(); i++) {
784 dex_locations.push_back(dex_filenames[i]);
785 }
786 } else if (dex_locations.size() != dex_filenames.size()) {
787 Usage("--dex-location arguments do not match --dex-file arguments");
788 }
789
790 if (zip_fd != -1 && zip_location.empty()) {
791 Usage("--zip-location should be supplied with --zip-fd");
792 }
793
794 if (boot_image_option.empty()) {
795 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700796 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700797 }
798 }
799
800 std::string oat_stripped(oat_filename);
801 std::string oat_unstripped;
802 if (!oat_symbols.empty()) {
803 oat_unstripped += oat_symbols;
804 } else {
805 oat_unstripped += oat_filename;
806 }
807
808 // Done with usage checks, enable watchdog if requested
809 WatchDog watch_dog(watch_dog_enabled);
810
811 // Check early that the result of compilation can be written
812 UniquePtr<File> oat_file;
813 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
814 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700815 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700816 if (oat_location.empty()) {
817 oat_location = oat_filename;
818 }
819 } else {
820 oat_file.reset(new File(oat_fd, oat_location));
821 oat_file->DisableAutoClose();
822 }
823 if (oat_file.get() == NULL) {
824 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
825 return EXIT_FAILURE;
826 }
827 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
828 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
829 return EXIT_FAILURE;
830 }
831
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700832 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700833 LOG(INFO) << "dex2oat: " << oat_location;
834
Ian Rogersf30f6da2013-08-28 17:33:30 -0700835 if (image) {
836 bool has_compiler_filter = false;
837 for (const char* r : runtime_args) {
838 if (strncmp(r, "-compiler-filter:", 17) == 0) {
839 has_compiler_filter = true;
840 break;
841 }
842 }
843 if (!has_compiler_filter) {
844 runtime_args.push_back("-compiler-filter:everything");
845 }
846 }
847
Brian Carlstrom7940e442013-07-12 13:46:57 -0700848 Runtime::Options options;
849 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
850 std::vector<const DexFile*> boot_class_path;
851 if (boot_image_option.empty()) {
852 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
853 if (failure_count > 0) {
854 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
855 return EXIT_FAILURE;
856 }
857 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
858 } else {
859 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
860 }
861 if (host_prefix.get() != NULL) {
862 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
863 }
864 for (size_t i = 0; i < runtime_args.size(); i++) {
865 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
866 }
867
Brian Carlstrom7940e442013-07-12 13:46:57 -0700868#ifdef ART_SEA_IR_MODE
869 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
870#endif
871
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872 Dex2Oat* p_dex2oat;
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700873 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700874 LOG(ERROR) << "Failed to create dex2oat";
875 return EXIT_FAILURE;
876 }
877 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
878 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700879 // give it away now so that we don't starve GC.
880 Thread* self = Thread::Current();
881 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700882 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700883 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
884 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700886 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700887
888 // If --image-classes was specified, calculate the full list of classes to include in the image
889 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
890 if (image_classes_filename != NULL) {
891 if (image_classes_zip_filename != NULL) {
892 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
893 image_classes_filename));
894 } else {
895 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
896 }
897 if (image_classes.get() == NULL) {
898 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
899 return EXIT_FAILURE;
900 }
901 }
902
903 std::vector<const DexFile*> dex_files;
904 if (boot_image_option.empty()) {
905 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
906 } else {
907 if (dex_filenames.empty()) {
908 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
909 if (zip_archive.get() == NULL) {
910 LOG(ERROR) << "Failed to open zip from file descriptor for " << zip_location;
911 return EXIT_FAILURE;
912 }
913 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
914 if (dex_file == NULL) {
915 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
916 return EXIT_FAILURE;
917 }
918 dex_files.push_back(dex_file);
919 } else {
920 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
921 if (failure_count > 0) {
922 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
923 return EXIT_FAILURE;
924 }
925 }
926 }
927
buzbeea024a062013-07-31 10:47:37 -0700928 /*
929 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
930 * bother to check if we're doing the image.
931 */
932 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933 size_t num_methods = 0;
934 for (size_t i = 0; i != dex_files.size(); ++i) {
935 const DexFile* dex_file = dex_files[i];
936 CHECK(dex_file != NULL);
937 num_methods += dex_file->NumMethodIds();
938 }
buzbeea024a062013-07-31 10:47:37 -0700939 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
940 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700941 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942 }
943 }
944
945 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
946 host_prefix.get(),
947 android_root,
948 is_host,
949 dex_files,
950 oat_file.get(),
951 bitcode_filename,
952 image,
953 image_classes,
954 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -0700955 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700956
957 if (compiler.get() == NULL) {
958 LOG(ERROR) << "Failed to create oat file: " << oat_location;
959 return EXIT_FAILURE;
960 }
961
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700962 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963
964 // Notes on the interleaving of creating the image and oat file to
965 // ensure the references between the two are correct.
966 //
967 // Currently we have a memory layout that looks something like this:
968 //
969 // +--------------+
970 // | image |
971 // +--------------+
972 // | boot oat |
973 // +--------------+
974 // | alloc spaces |
975 // +--------------+
976 //
Brian Carlstrom45602482013-07-21 22:07:55 -0700977 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978 //
979 // 1. The image is expected to be loaded at an absolute address and
980 // contains Objects with absolute pointers within the image.
981 //
982 // 2. There are absolute pointers from Methods in the image to their
983 // code in the oat.
984 //
985 // 3. There are absolute pointers from the code in the oat to Methods
986 // in the image.
987 //
988 // 4. There are absolute pointers from code in the oat to other code
989 // in the oat.
990 //
991 // To get this all correct, we go through several steps.
992 //
993 // 1. We have already created that oat file above with
994 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -0700995 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996 // file). The Compiler returned by CreateOatFile provides
997 // PatchInformation for references to oat code and Methods that need
998 // to be update once we know where the oat file will be located
999 // after the image.
1000 //
1001 // 2. We create the image file. It needs to know where the oat file
1002 // will be loaded after itself. Originally when oat file was simply
1003 // memory mapped so we could predict where its contents were based
1004 // on the file size. Now that it is an ELF file, we need to inspect
1005 // the ELF file to understand the in memory segment layout including
1006 // where the oat header is located within. ImageWriter's
1007 // PatchOatCodeAndMethods uses the PatchInformation from the
1008 // Compiler to touch up absolute references in the oat file.
1009 //
1010 // 3. We fixup the ELF program headers so that dlopen will try to
1011 // load the .so at the desired location at runtime by offsetting the
1012 // Elf32_Phdr.p_vaddr values by the desired base address.
1013 //
1014 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001015 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001016 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1017 image_base,
1018 oat_unstripped,
1019 oat_location,
1020 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001021 if (!image_creation_success) {
1022 return EXIT_FAILURE;
1023 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001024 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 }
1026
1027 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001028 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001029 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001030 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001031 return EXIT_SUCCESS;
1032 }
1033
1034 // If we don't want to strip in place, copy from unstripped location to stripped location.
1035 // We need to strip after image creation because FixupElf needs to use .strtab.
1036 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001037 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001039 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1040 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001041 size_t buffer_size = 8192;
1042 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1043 while (true) {
1044 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1045 if (bytes_read <= 0) {
1046 break;
1047 }
1048 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1049 CHECK(write_ok);
1050 }
1051 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001052 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001053 }
1054
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001055#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001056 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001057 // Strip unneeded sections for target
1058 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1059 CHECK_EQ(0, seek_actual);
1060 ElfStripper::Strip(oat_file.get());
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001061
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062
1063 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001064 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001065#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001066
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001067 timings.EndSplit();
1068
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001069 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001070 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001071 }
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}