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