blob: 541c916936df43ca03bda5da27b645ce3ba63c88 [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"
40#include "mirror/abstract_method-inl.h"
41#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("");
86 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file corresponding");
87 UsageError(" to the file descriptor specified by --zip-fd.");
88 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("");
140 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
141 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
142 UsageError(" Use a separate --runtime-arg switch for each argument.");
143 UsageError(" Example: --runtime-arg -Xms256m");
144 UsageError("");
145 std::cerr << "See log for usage error information\n";
146 exit(EXIT_FAILURE);
147}
148
149class Dex2Oat {
150 public:
151 static bool Create(Dex2Oat** p_dex2oat, Runtime::Options& options, CompilerBackend compiler_backend,
152 InstructionSet instruction_set, size_t thread_count, bool support_debugging)
153 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
154 if (!CreateRuntime(options, instruction_set)) {
155 *p_dex2oat = NULL;
156 return false;
157 }
158 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count,
159 support_debugging);
160 return true;
161 }
162
163 ~Dex2Oat() {
164 delete runtime_;
165 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) << " (threads: " << thread_count_ << ")";
166 }
167
168
169 // Reads the class names (java.lang.Object) and returns as set of class descriptors (Ljava/lang/Object;)
170 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
171 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
172 if (image_classes_file.get() == NULL) {
173 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
174 return NULL;
175 }
176 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
177 image_classes_file->close();
178 return result.release();
179 }
180
181 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
182 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
183 while (image_classes_stream.good()) {
184 std::string dot;
185 std::getline(image_classes_stream, dot);
186 if (StartsWith(dot, "#") || dot.empty()) {
187 continue;
188 }
189 std::string descriptor(DotToDescriptor(dot.c_str()));
190 image_classes->insert(descriptor);
191 }
192 return image_classes.release();
193 }
194
195 // Reads the class names (java.lang.Object) and returns as set of class descriptors (Ljava/lang/Object;)
196 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const std::string& zip_filename, const char* image_classes_filename) {
197 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename));
198 if (zip_archive.get() == NULL) {
199 LOG(ERROR) << "Failed to open zip file " << zip_filename;
200 return NULL;
201 }
202 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
203 if (zip_entry.get() == NULL) {
204 LOG(ERROR) << "Failed to find " << image_classes_filename << " within " << zip_filename;
205 return NULL;
206 }
207 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename));
208 if (image_classes_file.get() == NULL) {
209 LOG(ERROR) << "Failed to extract " << image_classes_filename << " from " << zip_filename;
210 return NULL;
211 }
212 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
213 image_classes_file->Size());
214 std::istringstream image_classes_stream(image_classes_string);
215 return ReadImageClasses(image_classes_stream);
216 }
217
218 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
219 const std::string* host_prefix,
220 const std::string& android_root,
221 bool is_host,
222 const std::vector<const DexFile*>& dex_files,
223 File* oat_file,
224 const std::string& bitcode_filename,
225 bool image,
226 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
227 bool dump_stats,
228 bool dump_timings)
229 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
230 // SirtRef and ClassLoader creation needs to come after Runtime::Create
231 jobject class_loader = NULL;
232 if (!boot_image_option.empty()) {
233 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
234 std::vector<const DexFile*> class_path_files(dex_files);
235 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
236 for (size_t i = 0; i < class_path_files.size(); i++) {
237 class_linker->RegisterDexFile(*class_path_files[i]);
238 }
239 ScopedObjectAccessUnchecked soa(Thread::Current());
240 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
241 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
242 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
243 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
244 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
245 }
246
247 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
248 instruction_set_,
249 image,
250 image_classes.release(),
251 thread_count_,
252 support_debugging_,
253 dump_stats,
254 dump_timings));
255
256 if (compiler_backend_ == kPortable) {
257 driver->SetBitcodeFileName(bitcode_filename);
258 }
259
260
261 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
262
263 driver->CompileAll(class_loader, dex_files);
264
265 Thread::Current()->TransitionFromSuspendedToRunnable();
266
267 std::string image_file_location;
268 uint32_t image_file_location_oat_checksum = 0;
269 uint32_t image_file_location_oat_data_begin = 0;
270 if (!driver->IsImage()) {
271 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
272 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
273 image_file_location_oat_data_begin =
274 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
275 image_file_location = image_space->GetImageFilename();
276 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
277 image_file_location = image_file_location.substr(host_prefix->size());
278 }
279 }
280
281 std::vector<uint8_t> oat_contents;
282 // TODO: change ElfWriterQuick to not require the creation of oat_contents. The old pre-mclinker
283 // OatWriter streamed directly to disk. The new could can be adapted to do it as follows:
284 // 1.) use first pass of OatWriter to calculate size of oat structure,
285 // 2.) call ElfWriterQuick with pointer to OatWriter instead of contents,
286 // 3.) have ElfWriterQuick call back to OatWriter to stream generate the output directly in
287 // place in the elf file.
288 oat_contents.reserve(5 * MB);
289 VectorOutputStream vector_output_stream(oat_file->GetPath(), oat_contents);
290 if (!OatWriter::Create(vector_output_stream,
291 dex_files,
292 image_file_location_oat_checksum,
293 image_file_location_oat_data_begin,
294 image_file_location,
295 *driver.get())) {
296 LOG(ERROR) << "Failed to create oat file " << oat_file->GetPath();
297 return NULL;
298 }
299
300 if (!driver->WriteElf(android_root, is_host, dex_files, oat_contents, oat_file)) {
301 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
302 return NULL;
303 }
304
305 return driver.release();
306 }
307
308 bool CreateImageFile(const std::string& image_filename,
309 uintptr_t image_base,
310 const std::string& oat_filename,
311 const std::string& oat_location,
312 const CompilerDriver& compiler)
313 LOCKS_EXCLUDED(Locks::mutator_lock_) {
314 uintptr_t oat_data_begin;
315 {
316 // ImageWriter is scoped so it can free memory before doing FixupElf
317 ImageWriter image_writer(compiler);
318 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
319 LOG(ERROR) << "Failed to create image file " << image_filename;
320 return false;
321 }
322 oat_data_begin = image_writer.GetOatDataBegin();
323 }
324
325 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
326 if (oat_file.get() == NULL) {
327 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
328 return false;
329 }
330 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
331 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
332 return false;
333 }
334 return true;
335 }
336
337 private:
338 explicit Dex2Oat(Runtime* runtime, CompilerBackend compiler_backend, InstructionSet instruction_set,
339 size_t thread_count, bool support_debugging)
340 : compiler_backend_(compiler_backend),
341 instruction_set_(instruction_set),
342 runtime_(runtime),
343 thread_count_(thread_count),
344 support_debugging_(support_debugging),
345 start_ns_(NanoTime()) {
346 }
347
348 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
349 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
350 if (!Runtime::Create(options, false)) {
351 LOG(ERROR) << "Failed to create runtime";
352 return false;
353 }
354 Runtime* runtime = Runtime::Current();
355 // if we loaded an existing image, we will reuse values from the image roots.
356 if (!runtime->HasResolutionMethod()) {
357 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
358 }
359 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
360 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
361 if (!runtime->HasCalleeSaveMethod(type)) {
362 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
363 }
364 }
365 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
366 return true;
367 }
368
369 // Appends to dex_files any elements of class_path that it doesn't already
370 // contain. This will open those dex files as necessary.
371 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
372 std::vector<std::string> parsed;
373 Split(class_path, ':', parsed);
374 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
375 ScopedObjectAccess soa(Thread::Current());
376 for (size_t i = 0; i < parsed.size(); ++i) {
377 if (DexFilesContains(dex_files, parsed[i])) {
378 continue;
379 }
380 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
381 if (dex_file == NULL) {
382 LOG(WARNING) << "Failed to open dex file " << parsed[i];
383 } else {
384 dex_files.push_back(dex_file);
385 }
386 }
387 }
388
389 // Returns true if dex_files has a dex with the named location.
390 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
391 for (size_t i = 0; i < dex_files.size(); ++i) {
392 if (dex_files[i]->GetLocation() == location) {
393 return true;
394 }
395 }
396 return false;
397 }
398
399 const CompilerBackend compiler_backend_;
400
401 const InstructionSet instruction_set_;
402
403 Runtime* runtime_;
404 size_t thread_count_;
405 bool support_debugging_;
406 uint64_t start_ns_;
407
408 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
409};
410
411static bool ParseInt(const char* in, int* out) {
412 char* end;
413 int result = strtol(in, &end, 10);
414 if (in == end || *end != '\0') {
415 return false;
416 }
417 *out = result;
418 return true;
419}
420
421static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
422 const std::vector<const char*>& dex_locations,
423 std::vector<const DexFile*>& dex_files) {
424 size_t failure_count = 0;
425 for (size_t i = 0; i < dex_filenames.size(); i++) {
426 const char* dex_filename = dex_filenames[i];
427 const char* dex_location = dex_locations[i];
428 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
429 if (dex_file == NULL) {
430 LOG(WARNING) << "Could not open .dex from file '" << dex_filename << "'\n";
431 ++failure_count;
432 } else {
433 dex_files.push_back(dex_file);
434 }
435 }
436 return failure_count;
437}
438
439// The primary goal of the watchdog is to prevent stuck build servers
440// during development when fatal aborts lead to a cascade of failures
441// that result in a deadlock.
442class WatchDog {
443
444// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
445#undef CHECK_PTHREAD_CALL
446#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
447 do { \
448 int rc = call args; \
449 if (rc != 0) { \
450 errno = rc; \
451 std::string message(# call); \
452 message += " failed for "; \
453 message += reason; \
454 Fatal(message); \
455 } \
456 } while (false)
457
458 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700459 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 is_watch_dog_enabled_ = is_watch_dog_enabled;
461 if (!is_watch_dog_enabled_) {
462 return;
463 }
464 shutting_down_ = false;
465 const char* reason = "dex2oat watch dog thread startup";
466 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
467 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
469 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
470 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
471 }
472 ~WatchDog() {
473 if (!is_watch_dog_enabled_) {
474 return;
475 }
476 const char* reason = "dex2oat watch dog thread shutdown";
477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
478 shutting_down_ = true;
479 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
480 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
481
482 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
483
484 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
485 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
486 }
487
488 private:
489 static void* CallBack(void* arg) {
490 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
491 ::art::SetThreadName("dex2oat watch dog");
492 self->Wait();
493 return NULL;
494 }
495
496 static void Message(char severity, const std::string& message) {
497 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
498 // cases.
499 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
500 kIsDebugBuild ? "d" : "",
501 severity,
502 getpid(),
503 GetTid(),
504 message.c_str());
505 }
506
507 static void Warn(const std::string& message) {
508 Message('W', message);
509 }
510
511 static void Fatal(const std::string& message) {
512 Message('F', message);
513 exit(1);
514 }
515
516 void Wait() {
517 bool warning = true;
518 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
519 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
520 // large.
521 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
522 timespec warning_ts;
523 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
524 timespec timeout_ts;
525 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
526 const char* reason = "dex2oat watch dog thread waiting";
527 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
528 while (!shutting_down_) {
529 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
530 warning ? &warning_ts
531 : &timeout_ts));
532 if (rc == ETIMEDOUT) {
533 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
534 warning ? kWatchDogWarningSeconds
535 : kWatchDogTimeoutSeconds));
536 if (warning) {
537 Warn(message.c_str());
538 warning = false;
539 } else {
540 Fatal(message.c_str());
541 }
542 } else if (rc != 0) {
543 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
544 strerror(errno)));
545 Fatal(message.c_str());
546 }
547 }
548 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
549 }
550
551 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
552#if ART_USE_PORTABLE_COMPILER
553 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
554 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
555#else
556 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
557 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
558#endif
559
560 bool is_watch_dog_enabled_;
561 bool shutting_down_;
562 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
563 pthread_mutex_t mutex_;
564 pthread_cond_t cond_;
565 pthread_attr_t attr_;
566 pthread_t pthread_;
567};
568const unsigned int WatchDog::kWatchDogWarningSeconds;
569const unsigned int WatchDog::kWatchDogTimeoutSeconds;
570
571static int dex2oat(int argc, char** argv) {
572 InitLogging(argv);
573
574 // Skip over argv[0].
575 argv++;
576 argc--;
577
578 if (argc == 0) {
579 Usage("no arguments specified");
580 }
581
582 std::vector<const char*> dex_filenames;
583 std::vector<const char*> dex_locations;
584 int zip_fd = -1;
585 std::string zip_location;
586 std::string oat_filename;
587 std::string oat_symbols;
588 std::string oat_location;
589 int oat_fd = -1;
590 std::string bitcode_filename;
591 const char* image_classes_zip_filename = NULL;
592 const char* image_classes_filename = NULL;
593 std::string image_filename;
594 std::string boot_image_filename;
595 uintptr_t image_base = 0;
596 UniquePtr<std::string> host_prefix;
597 std::string android_root;
598 std::vector<const char*> runtime_args;
599 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
600 bool support_debugging = false;
601#if defined(ART_USE_PORTABLE_COMPILER)
602 CompilerBackend compiler_backend = kPortable;
603#else
604 CompilerBackend compiler_backend = kQuick;
605#endif
606#if defined(__arm__)
607 InstructionSet instruction_set = kThumb2;
608#elif defined(__i386__)
609 InstructionSet instruction_set = kX86;
610#elif defined(__mips__)
611 InstructionSet instruction_set = kMips;
612#else
613#error "Unsupported architecture"
614#endif
615 bool is_host = false;
616 bool dump_stats = kIsDebugBuild;
617 bool dump_timings = kIsDebugBuild;
618 bool watch_dog_enabled = !kIsTargetBuild;
619
620
621 for (int i = 0; i < argc; i++) {
622 const StringPiece option(argv[i]);
623 bool log_options = false;
624 if (log_options) {
625 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
626 }
627 if (option.starts_with("--dex-file=")) {
628 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
629 } else if (option.starts_with("--dex-location=")) {
630 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
631 } else if (option.starts_with("--zip-fd=")) {
632 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
633 if (!ParseInt(zip_fd_str, &zip_fd)) {
634 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
635 }
636 } else if (option.starts_with("--zip-location=")) {
637 zip_location = option.substr(strlen("--zip-location=")).data();
638 } else if (option.starts_with("--oat-file=")) {
639 oat_filename = option.substr(strlen("--oat-file=")).data();
640 } else if (option.starts_with("--oat-symbols=")) {
641 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
642 } else if (option.starts_with("--oat-fd=")) {
643 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
644 if (!ParseInt(oat_fd_str, &oat_fd)) {
645 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
646 }
647 } else if (option == "-g") {
648 support_debugging = true;
649 } else if (option == "--watch-dog") {
650 watch_dog_enabled = true;
651 } else if (option == "--no-watch-dog") {
652 watch_dog_enabled = false;
653 } else if (option.starts_with("-j")) {
654 const char* thread_count_str = option.substr(strlen("-j")).data();
655 if (!ParseInt(thread_count_str, &thread_count)) {
656 Usage("could not parse -j argument '%s' as an integer", thread_count_str);
657 }
658 } else if (option.starts_with("--oat-location=")) {
659 oat_location = option.substr(strlen("--oat-location=")).data();
660 } else if (option.starts_with("--bitcode=")) {
661 bitcode_filename = option.substr(strlen("--bitcode=")).data();
662 } else if (option.starts_with("--image=")) {
663 image_filename = option.substr(strlen("--image=")).data();
664 } else if (option.starts_with("--image-classes=")) {
665 image_classes_filename = option.substr(strlen("--image-classes=")).data();
666 } else if (option.starts_with("--image-classes-zip=")) {
667 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
668 } else if (option.starts_with("--base=")) {
669 const char* image_base_str = option.substr(strlen("--base=")).data();
670 char* end;
671 image_base = strtoul(image_base_str, &end, 16);
672 if (end == image_base_str || *end != '\0') {
673 Usage("Failed to parse hexadecimal value for option %s", option.data());
674 }
675 } else if (option.starts_with("--boot-image=")) {
676 boot_image_filename = option.substr(strlen("--boot-image=")).data();
677 } else if (option.starts_with("--host-prefix=")) {
678 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
679 } else if (option.starts_with("--android-root=")) {
680 android_root = option.substr(strlen("--android-root=")).data();
681 } else if (option.starts_with("--instruction-set=")) {
682 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
683 if (instruction_set_str == "arm") {
684 instruction_set = kThumb2;
685 } else if (instruction_set_str == "mips") {
686 instruction_set = kMips;
687 } else if (instruction_set_str == "x86") {
688 instruction_set = kX86;
689 }
690 } else if (option.starts_with("--compiler-backend=")) {
691 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
692 if (backend_str == "Quick") {
693 compiler_backend = kQuick;
694 } else if (backend_str == "Portable") {
695 compiler_backend = kPortable;
696 }
697 } else if (option == "--host") {
698 is_host = true;
699 } else if (option == "--runtime-arg") {
700 if (++i >= argc) {
701 Usage("Missing required argument for --runtime-arg");
702 }
703 if (log_options) {
704 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
705 }
706 runtime_args.push_back(argv[i]);
707 } else {
708 Usage("unknown argument %s", option.data());
709 }
710 }
711
712 if (oat_filename.empty() && oat_fd == -1) {
713 Usage("Output must be supplied with either --oat-file or --oat-fd");
714 }
715
716 if (!oat_filename.empty() && oat_fd != -1) {
717 Usage("--oat-file should not be used with --oat-fd");
718 }
719
720 if (!oat_symbols.empty() && oat_fd != -1) {
721 Usage("--oat-symbols should not be used with --oat-fd");
722 }
723
724 if (!oat_symbols.empty() && is_host) {
725 Usage("--oat-symbols should not be used with --host");
726 }
727
728 if (oat_fd != -1 && !image_filename.empty()) {
729 Usage("--oat-fd should not be used with --image");
730 }
731
732 if (host_prefix.get() == NULL) {
733 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
734 if (android_product_out != NULL) {
735 host_prefix.reset(new std::string(android_product_out));
736 }
737 }
738
739 if (android_root.empty()) {
740 const char* android_root_env_var = getenv("ANDROID_ROOT");
741 if (android_root_env_var == NULL) {
742 Usage("--android-root unspecified and ANDROID_ROOT not set");
743 }
744 android_root += android_root_env_var;
745 }
746
747 bool image = (!image_filename.empty());
748 if (!image && boot_image_filename.empty()) {
749 if (host_prefix.get() == NULL) {
750 boot_image_filename += GetAndroidRoot();
751 } else {
752 boot_image_filename += *host_prefix.get();
753 boot_image_filename += "/system";
754 }
755 boot_image_filename += "/framework/boot.art";
756 }
757 std::string boot_image_option;
758 if (!boot_image_filename.empty()) {
759 boot_image_option += "-Ximage:";
760 boot_image_option += boot_image_filename;
761 }
762
763 if (image_classes_filename != NULL && !image) {
764 Usage("--image-classes should only be used with --image");
765 }
766
767 if (image_classes_filename != NULL && !boot_image_option.empty()) {
768 Usage("--image-classes should not be used with --boot-image");
769 }
770
771 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
772 Usage("--image-classes-zip should be used with --image-classes");
773 }
774
775 if (dex_filenames.empty() && zip_fd == -1) {
776 Usage("Input must be supplied with either --dex-file or --zip-fd");
777 }
778
779 if (!dex_filenames.empty() && zip_fd != -1) {
780 Usage("--dex-file should not be used with --zip-fd");
781 }
782
783 if (!dex_filenames.empty() && !zip_location.empty()) {
784 Usage("--dex-file should not be used with --zip-location");
785 }
786
787 if (dex_locations.empty()) {
788 for (size_t i = 0; i < dex_filenames.size(); i++) {
789 dex_locations.push_back(dex_filenames[i]);
790 }
791 } else if (dex_locations.size() != dex_filenames.size()) {
792 Usage("--dex-location arguments do not match --dex-file arguments");
793 }
794
795 if (zip_fd != -1 && zip_location.empty()) {
796 Usage("--zip-location should be supplied with --zip-fd");
797 }
798
799 if (boot_image_option.empty()) {
800 if (image_base == 0) {
801 Usage("non-zero --base not specified");
802 }
803 }
804
805 std::string oat_stripped(oat_filename);
806 std::string oat_unstripped;
807 if (!oat_symbols.empty()) {
808 oat_unstripped += oat_symbols;
809 } else {
810 oat_unstripped += oat_filename;
811 }
812
813 // Done with usage checks, enable watchdog if requested
814 WatchDog watch_dog(watch_dog_enabled);
815
816 // Check early that the result of compilation can be written
817 UniquePtr<File> oat_file;
818 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
819 if (create_file) {
820 oat_file.reset(OS::OpenFile(oat_unstripped.c_str(), true));
821 if (oat_location.empty()) {
822 oat_location = oat_filename;
823 }
824 } else {
825 oat_file.reset(new File(oat_fd, oat_location));
826 oat_file->DisableAutoClose();
827 }
828 if (oat_file.get() == NULL) {
829 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
830 return EXIT_FAILURE;
831 }
832 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
833 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
834 return EXIT_FAILURE;
835 }
836
837 LOG(INFO) << "dex2oat: " << oat_location;
838
839 Runtime::Options options;
840 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
841 std::vector<const DexFile*> boot_class_path;
842 if (boot_image_option.empty()) {
843 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
844 if (failure_count > 0) {
845 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
846 return EXIT_FAILURE;
847 }
848 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
849 } else {
850 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
851 }
852 if (host_prefix.get() != NULL) {
853 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
854 }
855 for (size_t i = 0; i < runtime_args.size(); i++) {
856 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
857 }
858
859#if ART_SMALL_MODE
860 options.push_back(std::make_pair("-small", reinterpret_cast<void*>(NULL)));
861#endif // ART_SMALL_MODE
862
863
864#ifdef ART_SEA_IR_MODE
865 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
866#endif
867
868
869 Dex2Oat* p_dex2oat;
870 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count,
871 support_debugging)) {
872 LOG(ERROR) << "Failed to create dex2oat";
873 return EXIT_FAILURE;
874 }
875 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
876 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
877 // give it away now and then switch to a more managable ScopedObjectAccess.
878 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
879 // Whilst we're in native take the opportunity to initialize well known classes.
880 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
881 ScopedObjectAccess soa(Thread::Current());
882
883 // If --image-classes was specified, calculate the full list of classes to include in the image
884 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
885 if (image_classes_filename != NULL) {
886 if (image_classes_zip_filename != NULL) {
887 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
888 image_classes_filename));
889 } else {
890 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
891 }
892 if (image_classes.get() == NULL) {
893 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
894 return EXIT_FAILURE;
895 }
896 }
897
898 std::vector<const DexFile*> dex_files;
899 if (boot_image_option.empty()) {
900 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
901 } else {
902 if (dex_filenames.empty()) {
903 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
904 if (zip_archive.get() == NULL) {
905 LOG(ERROR) << "Failed to open zip from file descriptor for " << zip_location;
906 return EXIT_FAILURE;
907 }
908 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
909 if (dex_file == NULL) {
910 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
911 return EXIT_FAILURE;
912 }
913 dex_files.push_back(dex_file);
914 } else {
915 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
916 if (failure_count > 0) {
917 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
918 return EXIT_FAILURE;
919 }
920 }
921 }
922
923 // If we're in small mode, but the program is small, turn off small mode.
924 // It doesn't make a difference for the boot image, so let's skip the check
925 // altogether.
926 if (Runtime::Current()->IsSmallMode() && !image) {
927 size_t num_methods = 0;
928 for (size_t i = 0; i != dex_files.size(); ++i) {
929 const DexFile* dex_file = dex_files[i];
930 CHECK(dex_file != NULL);
931 num_methods += dex_file->NumMethodIds();
932 }
933 if (num_methods <= Runtime::Current()->GetSmallModeMethodThreshold()) {
934 Runtime::Current()->SetSmallMode(false);
935 LOG(INFO) << "Below method threshold, compiling anyways";
936 }
937 }
938
939 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
940 host_prefix.get(),
941 android_root,
942 is_host,
943 dex_files,
944 oat_file.get(),
945 bitcode_filename,
946 image,
947 image_classes,
948 dump_stats,
949 dump_timings));
950
951 if (compiler.get() == NULL) {
952 LOG(ERROR) << "Failed to create oat file: " << oat_location;
953 return EXIT_FAILURE;
954 }
955
956 LOG(INFO) << "Oat file written successfully (unstripped): " << oat_location;
957
958 // Notes on the interleaving of creating the image and oat file to
959 // ensure the references between the two are correct.
960 //
961 // Currently we have a memory layout that looks something like this:
962 //
963 // +--------------+
964 // | image |
965 // +--------------+
966 // | boot oat |
967 // +--------------+
968 // | alloc spaces |
969 // +--------------+
970 //
971 // There are several constraints on the loading of the imag and boot.oat.
972 //
973 // 1. The image is expected to be loaded at an absolute address and
974 // contains Objects with absolute pointers within the image.
975 //
976 // 2. There are absolute pointers from Methods in the image to their
977 // code in the oat.
978 //
979 // 3. There are absolute pointers from the code in the oat to Methods
980 // in the image.
981 //
982 // 4. There are absolute pointers from code in the oat to other code
983 // in the oat.
984 //
985 // To get this all correct, we go through several steps.
986 //
987 // 1. We have already created that oat file above with
988 // CreateOatFile. Originally this was just our own proprietary file
989 // but now it is contained within an ELF dynamic object (aka .so
990 // file). The Compiler returned by CreateOatFile provides
991 // PatchInformation for references to oat code and Methods that need
992 // to be update once we know where the oat file will be located
993 // after the image.
994 //
995 // 2. We create the image file. It needs to know where the oat file
996 // will be loaded after itself. Originally when oat file was simply
997 // memory mapped so we could predict where its contents were based
998 // on the file size. Now that it is an ELF file, we need to inspect
999 // the ELF file to understand the in memory segment layout including
1000 // where the oat header is located within. ImageWriter's
1001 // PatchOatCodeAndMethods uses the PatchInformation from the
1002 // Compiler to touch up absolute references in the oat file.
1003 //
1004 // 3. We fixup the ELF program headers so that dlopen will try to
1005 // load the .so at the desired location at runtime by offsetting the
1006 // Elf32_Phdr.p_vaddr values by the desired base address.
1007 //
1008 if (image) {
1009 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1010 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1011 image_base,
1012 oat_unstripped,
1013 oat_location,
1014 *compiler.get());
1015 Thread::Current()->TransitionFromSuspendedToRunnable();
1016 LOG(INFO) << "Image written successfully: " << image_filename;
1017 if (!image_creation_success) {
1018 return EXIT_FAILURE;
1019 }
1020 }
1021
1022 if (is_host) {
1023 return EXIT_SUCCESS;
1024 }
1025
1026 // If we don't want to strip in place, copy from unstripped location to stripped location.
1027 // We need to strip after image creation because FixupElf needs to use .strtab.
1028 if (oat_unstripped != oat_stripped) {
1029 oat_file.reset();
1030 UniquePtr<File> in(OS::OpenFile(oat_unstripped.c_str(), false));
1031 UniquePtr<File> out(OS::OpenFile(oat_stripped.c_str(), true));
1032 size_t buffer_size = 8192;
1033 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1034 while (true) {
1035 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1036 if (bytes_read <= 0) {
1037 break;
1038 }
1039 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1040 CHECK(write_ok);
1041 }
1042 oat_file.reset(out.release());
1043 LOG(INFO) << "Oat file copied successfully (stripped): " << oat_stripped;
1044 }
1045
1046 // Strip unneeded sections for target
1047 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1048 CHECK_EQ(0, seek_actual);
1049 ElfStripper::Strip(oat_file.get());
1050
1051 // We wrote the oat file successfully, and want to keep it.
1052 LOG(INFO) << "Oat file written successfully (stripped): " << oat_location;
1053 return EXIT_SUCCESS;
1054}
1055
1056} // namespace art
1057
1058int main(int argc, char** argv) {
1059 return art::dex2oat(argc, argv);
1060}