dex2oat.cc revision 7934ac288acfb2552bb0b06ec1f61e5820d924a4
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    OatWriter oat_writer(dex_files,
286                         image_file_location_oat_checksum,
287                         image_file_location_oat_data_begin,
288                         image_file_location,
289                         driver.get());
290    timings.AddSplit("dex2oat OatWriter");
291
292    if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
293      LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
294      return NULL;
295    }
296    timings.AddSplit("dex2oat ElfWriter");
297
298    return driver.release();
299  }
300
301  bool CreateImageFile(const std::string& image_filename,
302                       uintptr_t image_base,
303                       const std::string& oat_filename,
304                       const std::string& oat_location,
305                       const CompilerDriver& compiler)
306      LOCKS_EXCLUDED(Locks::mutator_lock_) {
307    uintptr_t oat_data_begin;
308    {
309      // ImageWriter is scoped so it can free memory before doing FixupElf
310      ImageWriter image_writer(compiler);
311      if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
312        LOG(ERROR) << "Failed to create image file " << image_filename;
313        return false;
314      }
315      oat_data_begin = image_writer.GetOatDataBegin();
316    }
317
318    UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
319    if (oat_file.get() == NULL) {
320      PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
321      return false;
322    }
323    if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
324      LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
325      return false;
326    }
327    return true;
328  }
329
330 private:
331  explicit Dex2Oat(Runtime* runtime,
332                   CompilerBackend compiler_backend,
333                   InstructionSet instruction_set,
334                   size_t thread_count)
335      : compiler_backend_(compiler_backend),
336        instruction_set_(instruction_set),
337        runtime_(runtime),
338        thread_count_(thread_count),
339        start_ns_(NanoTime()) {
340  }
341
342  static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
343      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
344    if (!Runtime::Create(options, false)) {
345      LOG(ERROR) << "Failed to create runtime";
346      return false;
347    }
348    Runtime* runtime = Runtime::Current();
349    // if we loaded an existing image, we will reuse values from the image roots.
350    if (!runtime->HasResolutionMethod()) {
351      runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
352    }
353    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
354      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
355      if (!runtime->HasCalleeSaveMethod(type)) {
356        runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
357      }
358    }
359    runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
360    return true;
361  }
362
363  // Appends to dex_files any elements of class_path that it doesn't already
364  // contain. This will open those dex files as necessary.
365  static void OpenClassPathFiles(const std::string& class_path,
366                                 std::vector<const DexFile*>& dex_files) {
367    std::vector<std::string> parsed;
368    Split(class_path, ':', parsed);
369    // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
370    ScopedObjectAccess soa(Thread::Current());
371    for (size_t i = 0; i < parsed.size(); ++i) {
372      if (DexFilesContains(dex_files, parsed[i])) {
373        continue;
374      }
375      const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
376      if (dex_file == NULL) {
377        LOG(WARNING) << "Failed to open dex file " << parsed[i];
378      } else {
379        dex_files.push_back(dex_file);
380      }
381    }
382  }
383
384  // Returns true if dex_files has a dex with the named location.
385  static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
386                               const std::string& location) {
387    for (size_t i = 0; i < dex_files.size(); ++i) {
388      if (dex_files[i]->GetLocation() == location) {
389        return true;
390      }
391    }
392    return false;
393  }
394
395  const CompilerBackend compiler_backend_;
396
397  const InstructionSet instruction_set_;
398
399  Runtime* runtime_;
400  size_t thread_count_;
401  uint64_t start_ns_;
402
403  DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
404};
405
406static bool ParseInt(const char* in, int* out) {
407  char* end;
408  int result = strtol(in, &end, 10);
409  if (in == end || *end != '\0') {
410    return false;
411  }
412  *out = result;
413  return true;
414}
415
416static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
417                           const std::vector<const char*>& dex_locations,
418                           std::vector<const DexFile*>& dex_files) {
419  size_t failure_count = 0;
420  for (size_t i = 0; i < dex_filenames.size(); i++) {
421    const char* dex_filename = dex_filenames[i];
422    const char* dex_location = dex_locations[i];
423    const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
424    if (dex_file == NULL) {
425      LOG(WARNING) << "Could not open .dex from file '" << dex_filename << "'\n";
426      ++failure_count;
427    } else {
428      dex_files.push_back(dex_file);
429    }
430  }
431  return failure_count;
432}
433
434// The primary goal of the watchdog is to prevent stuck build servers
435// during development when fatal aborts lead to a cascade of failures
436// that result in a deadlock.
437class WatchDog {
438// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
439#undef CHECK_PTHREAD_CALL
440#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
441  do { \
442    int rc = call args; \
443    if (rc != 0) { \
444      errno = rc; \
445      std::string message(# call); \
446      message += " failed for "; \
447      message += reason; \
448      Fatal(message); \
449    } \
450  } while (false)
451
452 public:
453  explicit WatchDog(bool is_watch_dog_enabled) {
454    is_watch_dog_enabled_ = is_watch_dog_enabled;
455    if (!is_watch_dog_enabled_) {
456      return;
457    }
458    shutting_down_ = false;
459    const char* reason = "dex2oat watch dog thread startup";
460    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
461    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
462    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
463    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
464    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
465  }
466  ~WatchDog() {
467    if (!is_watch_dog_enabled_) {
468      return;
469    }
470    const char* reason = "dex2oat watch dog thread shutdown";
471    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
472    shutting_down_ = true;
473    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
474    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
475
476    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
477
478    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
479    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
480  }
481
482 private:
483  static void* CallBack(void* arg) {
484    WatchDog* self = reinterpret_cast<WatchDog*>(arg);
485    ::art::SetThreadName("dex2oat watch dog");
486    self->Wait();
487    return NULL;
488  }
489
490  static void Message(char severity, const std::string& message) {
491    // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
492    //       cases.
493    fprintf(stderr, "dex2oat%s %c %d %d %s\n",
494            kIsDebugBuild ? "d" : "",
495            severity,
496            getpid(),
497            GetTid(),
498            message.c_str());
499  }
500
501  static void Warn(const std::string& message) {
502    Message('W', message);
503  }
504
505  static void Fatal(const std::string& message) {
506    Message('F', message);
507    exit(1);
508  }
509
510  void Wait() {
511    bool warning = true;
512    CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
513    // TODO: tune the multiplier for GC verification, the following is just to make the timeout
514    //       large.
515    int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
516    timespec warning_ts;
517    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
518    timespec timeout_ts;
519    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
520    const char* reason = "dex2oat watch dog thread waiting";
521    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
522    while (!shutting_down_) {
523      int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
524                                                         warning ? &warning_ts
525                                                                 : &timeout_ts));
526      if (rc == ETIMEDOUT) {
527        std::string message(StringPrintf("dex2oat did not finish after %d seconds",
528                                         warning ? kWatchDogWarningSeconds
529                                                 : kWatchDogTimeoutSeconds));
530        if (warning) {
531          Warn(message.c_str());
532          warning = false;
533        } else {
534          Fatal(message.c_str());
535        }
536      } else if (rc != 0) {
537        std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
538                                         strerror(errno)));
539        Fatal(message.c_str());
540      }
541    }
542    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
543  }
544
545  // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
546#if ART_USE_PORTABLE_COMPILER
547  static const unsigned int kWatchDogWarningSeconds =  2 * 60;  // 2 minutes.
548  static const unsigned int kWatchDogTimeoutSeconds = 30 * 60;  // 25 minutes + buffer.
549#else
550  static const unsigned int kWatchDogWarningSeconds =  1 * 60;  // 1 minute.
551  static const unsigned int kWatchDogTimeoutSeconds =  6 * 60;  // 5 minutes + buffer.
552#endif
553
554  bool is_watch_dog_enabled_;
555  bool shutting_down_;
556  // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
557  pthread_mutex_t mutex_;
558  pthread_cond_t cond_;
559  pthread_attr_t attr_;
560  pthread_t pthread_;
561};
562const unsigned int WatchDog::kWatchDogWarningSeconds;
563const unsigned int WatchDog::kWatchDogTimeoutSeconds;
564
565static int dex2oat(int argc, char** argv) {
566  TimingLogger timings("compiler", false);
567
568  InitLogging(argv);
569
570  // Skip over argv[0].
571  argv++;
572  argc--;
573
574  if (argc == 0) {
575    Usage("no arguments specified");
576  }
577
578  std::vector<const char*> dex_filenames;
579  std::vector<const char*> dex_locations;
580  int zip_fd = -1;
581  std::string zip_location;
582  std::string oat_filename;
583  std::string oat_symbols;
584  std::string oat_location;
585  int oat_fd = -1;
586  std::string bitcode_filename;
587  const char* image_classes_zip_filename = NULL;
588  const char* image_classes_filename = NULL;
589  std::string image_filename;
590  std::string boot_image_filename;
591  uintptr_t image_base = 0;
592  UniquePtr<std::string> host_prefix;
593  std::string android_root;
594  std::vector<const char*> runtime_args;
595  int thread_count = sysconf(_SC_NPROCESSORS_CONF);
596#if defined(ART_USE_PORTABLE_COMPILER)
597  CompilerBackend compiler_backend = kPortable;
598#else
599  CompilerBackend compiler_backend = kQuick;
600#endif
601#if defined(__arm__)
602  InstructionSet instruction_set = kThumb2;
603#elif defined(__i386__)
604  InstructionSet instruction_set = kX86;
605#elif defined(__mips__)
606  InstructionSet instruction_set = kMips;
607#else
608#error "Unsupported architecture"
609#endif
610  bool is_host = false;
611  bool dump_stats = kIsDebugBuild;
612  bool dump_timings = kIsDebugBuild;
613  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)) {
629        Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
630      }
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)) {
640        Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
641      }
642    } 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)) {
649        Usage("could not parse -j argument '%s' as an integer", thread_count_str);
650      }
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]);
700    } else {
701      Usage("unknown argument %s", option.data());
702    }
703  }
704
705  if (oat_filename.empty() && oat_fd == -1) {
706    Usage("Output must be supplied with either --oat-file or --oat-fd");
707  }
708
709  if (!oat_filename.empty() && oat_fd != -1) {
710    Usage("--oat-file should not be used with --oat-fd");
711  }
712
713  if (!oat_symbols.empty() && oat_fd != -1) {
714    Usage("--oat-symbols should not be used with --oat-fd");
715  }
716
717  if (!oat_symbols.empty() && is_host) {
718    Usage("--oat-symbols should not be used with --host");
719  }
720
721  if (oat_fd != -1 && !image_filename.empty()) {
722    Usage("--oat-fd should not be used with --image");
723  }
724
725  if (host_prefix.get() == NULL) {
726    const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
727    if (android_product_out != NULL) {
728        host_prefix.reset(new std::string(android_product_out));
729    }
730  }
731
732  if (android_root.empty()) {
733    const char* android_root_env_var = getenv("ANDROID_ROOT");
734    if (android_root_env_var == NULL) {
735      Usage("--android-root unspecified and ANDROID_ROOT not set");
736    }
737    android_root += android_root_env_var;
738  }
739
740  bool image = (!image_filename.empty());
741  if (!image && boot_image_filename.empty()) {
742    if (host_prefix.get() == NULL) {
743      boot_image_filename += GetAndroidRoot();
744    } else {
745      boot_image_filename += *host_prefix.get();
746      boot_image_filename += "/system";
747    }
748    boot_image_filename += "/framework/boot.art";
749  }
750  std::string boot_image_option;
751  if (!boot_image_filename.empty()) {
752    boot_image_option += "-Ximage:";
753    boot_image_option += boot_image_filename;
754  }
755
756  if (image_classes_filename != NULL && !image) {
757    Usage("--image-classes should only be used with --image");
758  }
759
760  if (image_classes_filename != NULL && !boot_image_option.empty()) {
761    Usage("--image-classes should not be used with --boot-image");
762  }
763
764  if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
765    Usage("--image-classes-zip should be used with --image-classes");
766  }
767
768  if (dex_filenames.empty() && zip_fd == -1) {
769    Usage("Input must be supplied with either --dex-file or --zip-fd");
770  }
771
772  if (!dex_filenames.empty() && zip_fd != -1) {
773    Usage("--dex-file should not be used with --zip-fd");
774  }
775
776  if (!dex_filenames.empty() && !zip_location.empty()) {
777    Usage("--dex-file should not be used with --zip-location");
778  }
779
780  if (dex_locations.empty()) {
781    for (size_t i = 0; i < dex_filenames.size(); i++) {
782      dex_locations.push_back(dex_filenames[i]);
783    }
784  } else if (dex_locations.size() != dex_filenames.size()) {
785    Usage("--dex-location arguments do not match --dex-file arguments");
786  }
787
788  if (zip_fd != -1 && zip_location.empty()) {
789    Usage("--zip-location should be supplied with --zip-fd");
790  }
791
792  if (boot_image_option.empty()) {
793    if (image_base == 0) {
794      Usage("non-zero --base not specified");
795    }
796  }
797
798  std::string oat_stripped(oat_filename);
799  std::string oat_unstripped;
800  if (!oat_symbols.empty()) {
801    oat_unstripped += oat_symbols;
802  } else {
803    oat_unstripped += oat_filename;
804  }
805
806  // Done with usage checks, enable watchdog if requested
807  WatchDog watch_dog(watch_dog_enabled);
808
809  // Check early that the result of compilation can be written
810  UniquePtr<File> oat_file;
811  bool create_file = !oat_unstripped.empty();  // as opposed to using open file descriptor
812  if (create_file) {
813    oat_file.reset(OS::OpenFile(oat_unstripped.c_str(), true));
814    if (oat_location.empty()) {
815      oat_location = oat_filename;
816    }
817  } else {
818    oat_file.reset(new File(oat_fd, oat_location));
819    oat_file->DisableAutoClose();
820  }
821  if (oat_file.get() == NULL) {
822    PLOG(ERROR) << "Failed to create oat file: " << oat_location;
823    return EXIT_FAILURE;
824  }
825  if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
826    PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
827    return EXIT_FAILURE;
828  }
829
830  LOG(INFO) << "dex2oat: " << oat_location;
831
832  Runtime::Options options;
833  options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
834  std::vector<const DexFile*> boot_class_path;
835  if (boot_image_option.empty()) {
836    size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
837    if (failure_count > 0) {
838      LOG(ERROR) << "Failed to open some dex files: " << failure_count;
839      return EXIT_FAILURE;
840    }
841    options.push_back(std::make_pair("bootclasspath", &boot_class_path));
842  } else {
843    options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
844  }
845  if (host_prefix.get() != NULL) {
846    options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
847  }
848  for (size_t i = 0; i < runtime_args.size(); i++) {
849    options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
850  }
851
852#if ART_SMALL_MODE
853  options.push_back(std::make_pair("-small", reinterpret_cast<void*>(NULL)));
854#endif  // ART_SMALL_MODE
855
856
857#ifdef ART_SEA_IR_MODE
858  options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
859#endif
860
861
862  Dex2Oat* p_dex2oat;
863  if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count)) {
864    LOG(ERROR) << "Failed to create dex2oat";
865    return EXIT_FAILURE;
866  }
867  UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
868  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
869  // give it away now and then switch to a more managable ScopedObjectAccess.
870  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
871  // Whilst we're in native take the opportunity to initialize well known classes.
872  WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
873  ScopedObjectAccess soa(Thread::Current());
874
875  // If --image-classes was specified, calculate the full list of classes to include in the image
876  UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
877  if (image_classes_filename != NULL) {
878    if (image_classes_zip_filename != NULL) {
879      image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
880                                                           image_classes_filename));
881    } else {
882      image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
883    }
884    if (image_classes.get() == NULL) {
885      LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
886      return EXIT_FAILURE;
887    }
888  }
889
890  std::vector<const DexFile*> dex_files;
891  if (boot_image_option.empty()) {
892    dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
893  } else {
894    if (dex_filenames.empty()) {
895      UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
896      if (zip_archive.get() == NULL) {
897        LOG(ERROR) << "Failed to open zip from file descriptor for " << zip_location;
898        return EXIT_FAILURE;
899      }
900      const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
901      if (dex_file == NULL) {
902        LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
903        return EXIT_FAILURE;
904      }
905      dex_files.push_back(dex_file);
906    } else {
907      size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
908      if (failure_count > 0) {
909        LOG(ERROR) << "Failed to open some dex files: " << failure_count;
910        return EXIT_FAILURE;
911      }
912    }
913  }
914
915  // If we're in small mode, but the program is small, turn off small mode.
916  // It doesn't make a difference for the boot image, so let's skip the check
917  // altogether.
918  if (Runtime::Current()->IsSmallMode() && !image) {
919    size_t num_methods = 0;
920    for (size_t i = 0; i != dex_files.size(); ++i) {
921      const DexFile* dex_file = dex_files[i];
922      CHECK(dex_file != NULL);
923      num_methods += dex_file->NumMethodIds();
924    }
925    if (num_methods <= Runtime::Current()->GetSmallModeMethodThreshold()) {
926      Runtime::Current()->SetSmallMode(false);
927      LOG(INFO) << "Below method threshold, compiling anyways";
928    }
929  }
930
931  UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
932                                                                  host_prefix.get(),
933                                                                  android_root,
934                                                                  is_host,
935                                                                  dex_files,
936                                                                  oat_file.get(),
937                                                                  bitcode_filename,
938                                                                  image,
939                                                                  image_classes,
940                                                                  dump_stats,
941                                                                  timings));
942
943  if (compiler.get() == NULL) {
944    LOG(ERROR) << "Failed to create oat file: " << oat_location;
945    return EXIT_FAILURE;
946  }
947
948  LOG(INFO) << "Oat file written successfully (unstripped): " << oat_location;
949
950  // Notes on the interleaving of creating the image and oat file to
951  // ensure the references between the two are correct.
952  //
953  // Currently we have a memory layout that looks something like this:
954  //
955  // +--------------+
956  // | image        |
957  // +--------------+
958  // | boot oat     |
959  // +--------------+
960  // | alloc spaces |
961  // +--------------+
962  //
963  // There are several constraints on the loading of the image and boot.oat.
964  //
965  // 1. The image is expected to be loaded at an absolute address and
966  // contains Objects with absolute pointers within the image.
967  //
968  // 2. There are absolute pointers from Methods in the image to their
969  // code in the oat.
970  //
971  // 3. There are absolute pointers from the code in the oat to Methods
972  // in the image.
973  //
974  // 4. There are absolute pointers from code in the oat to other code
975  // in the oat.
976  //
977  // To get this all correct, we go through several steps.
978  //
979  // 1. We have already created that oat file above with
980  // CreateOatFile. Originally this was just our own proprietary file
981  // but now it is contained within an ELF dynamic object (aka an .so
982  // file). The Compiler returned by CreateOatFile provides
983  // PatchInformation for references to oat code and Methods that need
984  // to be update once we know where the oat file will be located
985  // after the image.
986  //
987  // 2. We create the image file. It needs to know where the oat file
988  // will be loaded after itself. Originally when oat file was simply
989  // memory mapped so we could predict where its contents were based
990  // on the file size. Now that it is an ELF file, we need to inspect
991  // the ELF file to understand the in memory segment layout including
992  // where the oat header is located within. ImageWriter's
993  // PatchOatCodeAndMethods uses the PatchInformation from the
994  // Compiler to touch up absolute references in the oat file.
995  //
996  // 3. We fixup the ELF program headers so that dlopen will try to
997  // load the .so at the desired location at runtime by offsetting the
998  // Elf32_Phdr.p_vaddr values by the desired base address.
999  //
1000  if (image) {
1001    Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1002    bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1003                                                           image_base,
1004                                                           oat_unstripped,
1005                                                           oat_location,
1006                                                           *compiler.get());
1007    timings.AddSplit("dex2oat ImageWriter");
1008    Thread::Current()->TransitionFromSuspendedToRunnable();
1009    if (!image_creation_success) {
1010      return EXIT_FAILURE;
1011    }
1012    LOG(INFO) << "Image written successfully: " << image_filename;
1013  }
1014
1015  if (is_host) {
1016    if (dump_timings && timings.GetTotalNs() > MsToNs(1000)) {
1017      LOG(INFO) << Dumpable<TimingLogger>(timings);
1018    }
1019    return EXIT_SUCCESS;
1020  }
1021
1022  // If we don't want to strip in place, copy from unstripped location to stripped location.
1023  // We need to strip after image creation because FixupElf needs to use .strtab.
1024  if (oat_unstripped != oat_stripped) {
1025    oat_file.reset();
1026    UniquePtr<File> in(OS::OpenFile(oat_unstripped.c_str(), false));
1027    UniquePtr<File> out(OS::OpenFile(oat_stripped.c_str(), true));
1028    size_t buffer_size = 8192;
1029    UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1030    while (true) {
1031      int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1032      if (bytes_read <= 0) {
1033        break;
1034      }
1035      bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1036      CHECK(write_ok);
1037    }
1038    oat_file.reset(out.release());
1039    timings.AddSplit("dex2oat OatFile copy");
1040    LOG(INFO) << "Oat file copied successfully (stripped): " << oat_stripped;
1041  }
1042
1043#if ART_USE_PORTABLE_COMPILER  // We currently only generate symbols on Portable
1044  // Strip unneeded sections for target
1045  off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1046  CHECK_EQ(0, seek_actual);
1047  ElfStripper::Strip(oat_file.get());
1048  timings.AddSplit("dex2oat ElfStripper");
1049
1050  // We wrote the oat file successfully, and want to keep it.
1051  LOG(INFO) << "Oat file written successfully (stripped): " << oat_location;
1052#endif  // ART_USE_PORTABLE_COMPILER
1053
1054  if (dump_timings && timings.GetTotalNs() > MsToNs(1000)) {
1055    LOG(INFO) << Dumpable<TimingLogger>(timings);
1056  }
1057  return EXIT_SUCCESS;
1058}
1059
1060
1061}  // namespace art
1062
1063int main(int argc, char** argv) {
1064  return art::dex2oat(argc, argv);
1065}
1066