dex2oat.cc revision fe9ca4028f379688ecba6132ac3738171176b3e4
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/art_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("  --dump-timing: display a breakdown of where time was spent");
141  UsageError("");
142  UsageError("  --runtime-arg <argument>: used to specify various arguments for the runtime,");
143  UsageError("      such as initial heap size, maximum heap size, and verbose output.");
144  UsageError("      Use a separate --runtime-arg switch for each argument.");
145  UsageError("      Example: --runtime-arg -Xms256m");
146  UsageError("");
147  std::cerr << "See log for usage error information\n";
148  exit(EXIT_FAILURE);
149}
150
151class Dex2Oat {
152 public:
153  static bool Create(Dex2Oat** p_dex2oat,
154                     Runtime::Options& options,
155                     CompilerBackend compiler_backend,
156                     InstructionSet instruction_set,
157                     size_t thread_count)
158      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
159    if (!CreateRuntime(options, instruction_set)) {
160      *p_dex2oat = NULL;
161      return false;
162    }
163    *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count);
164    return true;
165  }
166
167  ~Dex2Oat() {
168    delete runtime_;
169    VLOG(compiler) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
170              << " (threads: " << thread_count_ << ")";
171  }
172
173
174  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
175  CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
176    UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
177                                                                  std::ifstream::in));
178    if (image_classes_file.get() == NULL) {
179      LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
180      return NULL;
181    }
182    UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
183    image_classes_file->close();
184    return result.release();
185  }
186
187  CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
188    UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
189    while (image_classes_stream.good()) {
190      std::string dot;
191      std::getline(image_classes_stream, dot);
192      if (StartsWith(dot, "#") || dot.empty()) {
193        continue;
194      }
195      std::string descriptor(DotToDescriptor(dot.c_str()));
196      image_classes->insert(descriptor);
197    }
198    return image_classes.release();
199  }
200
201  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
202  CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const std::string& zip_filename,
203                                                         const char* image_classes_filename) {
204    UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename));
205    if (zip_archive.get() == NULL) {
206      LOG(ERROR) << "Failed to open zip file " << zip_filename;
207      return NULL;
208    }
209    UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
210    if (zip_entry.get() == NULL) {
211      LOG(ERROR) << "Failed to find " << image_classes_filename << " within " << zip_filename;
212      return NULL;
213    }
214    UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename));
215    if (image_classes_file.get() == NULL) {
216      LOG(ERROR) << "Failed to extract " << image_classes_filename << " from " << zip_filename;
217      return NULL;
218    }
219    const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
220                                           image_classes_file->Size());
221    std::istringstream image_classes_stream(image_classes_string);
222    return ReadImageClasses(image_classes_stream);
223  }
224
225  const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
226                                      const std::string* host_prefix,
227                                      const std::string& android_root,
228                                      bool is_host,
229                                      const std::vector<const DexFile*>& dex_files,
230                                      File* oat_file,
231                                      const std::string& bitcode_filename,
232                                      bool image,
233                                      UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
234                                      bool dump_stats,
235                                      base::TimingLogger& timings)
236      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
237    // SirtRef and ClassLoader creation needs to come after Runtime::Create
238    jobject class_loader = NULL;
239    if (!boot_image_option.empty()) {
240      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
241      std::vector<const DexFile*> class_path_files(dex_files);
242      OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
243      for (size_t i = 0; i < class_path_files.size(); i++) {
244        class_linker->RegisterDexFile(*class_path_files[i]);
245      }
246      ScopedObjectAccessUnchecked soa(Thread::Current());
247      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
248      ScopedLocalRef<jobject> class_loader_local(soa.Env(),
249          soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
250      class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
251      Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
252    }
253
254    UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
255                                                        instruction_set_,
256                                                        image,
257                                                        image_classes.release(),
258                                                        thread_count_,
259                                                        dump_stats));
260
261    if (compiler_backend_ == kPortable) {
262      driver->SetBitcodeFileName(bitcode_filename);
263    }
264
265
266    Thread::Current()->TransitionFromRunnableToSuspended(kNative);
267
268    driver->CompileAll(class_loader, dex_files, timings);
269
270    Thread::Current()->TransitionFromSuspendedToRunnable();
271
272    timings.NewSplit("dex2oat OatWriter");
273    std::string image_file_location;
274    uint32_t image_file_location_oat_checksum = 0;
275    uint32_t image_file_location_oat_data_begin = 0;
276    if (!driver->IsImage()) {
277      gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
278      image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
279      image_file_location_oat_data_begin =
280          reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
281      image_file_location = image_space->GetImageFilename();
282      if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
283        image_file_location = image_file_location.substr(host_prefix->size());
284      }
285    }
286
287    OatWriter oat_writer(dex_files,
288                         image_file_location_oat_checksum,
289                         image_file_location_oat_data_begin,
290                         image_file_location,
291                         driver.get());
292
293    if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
294      LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
295      return NULL;
296    }
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::OpenFileReadWrite(oat_filename.c_str()));
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  base::TimingLogger timings("compiler", false, 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_timing = false;
613  bool dump_slow_timing = kIsDebugBuild;
614  bool watch_dog_enabled = !kIsTargetBuild;
615
616
617  for (int i = 0; i < argc; i++) {
618    const StringPiece option(argv[i]);
619    bool log_options = false;
620    if (log_options) {
621      LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
622    }
623    if (option.starts_with("--dex-file=")) {
624      dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
625    } else if (option.starts_with("--dex-location=")) {
626      dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
627    } else if (option.starts_with("--zip-fd=")) {
628      const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
629      if (!ParseInt(zip_fd_str, &zip_fd)) {
630        Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
631      }
632    } else if (option.starts_with("--zip-location=")) {
633      zip_location = option.substr(strlen("--zip-location=")).data();
634    } else if (option.starts_with("--oat-file=")) {
635      oat_filename = option.substr(strlen("--oat-file=")).data();
636    } else if (option.starts_with("--oat-symbols=")) {
637      oat_symbols = option.substr(strlen("--oat-symbols=")).data();
638    } else if (option.starts_with("--oat-fd=")) {
639      const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
640      if (!ParseInt(oat_fd_str, &oat_fd)) {
641        Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
642      }
643    } else if (option == "--watch-dog") {
644      watch_dog_enabled = true;
645    } else if (option == "--no-watch-dog") {
646      watch_dog_enabled = false;
647    } else if (option.starts_with("-j")) {
648      const char* thread_count_str = option.substr(strlen("-j")).data();
649      if (!ParseInt(thread_count_str, &thread_count)) {
650        Usage("could not parse -j argument '%s' as an integer", thread_count_str);
651      }
652    } else if (option.starts_with("--oat-location=")) {
653      oat_location = option.substr(strlen("--oat-location=")).data();
654    } else if (option.starts_with("--bitcode=")) {
655      bitcode_filename = option.substr(strlen("--bitcode=")).data();
656    } else if (option.starts_with("--image=")) {
657      image_filename = option.substr(strlen("--image=")).data();
658    } else if (option.starts_with("--image-classes=")) {
659      image_classes_filename = option.substr(strlen("--image-classes=")).data();
660    } else if (option.starts_with("--image-classes-zip=")) {
661      image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
662    } else if (option.starts_with("--base=")) {
663      const char* image_base_str = option.substr(strlen("--base=")).data();
664      char* end;
665      image_base = strtoul(image_base_str, &end, 16);
666      if (end == image_base_str || *end != '\0') {
667        Usage("Failed to parse hexadecimal value for option %s", option.data());
668      }
669    } else if (option.starts_with("--boot-image=")) {
670      boot_image_filename = option.substr(strlen("--boot-image=")).data();
671    } else if (option.starts_with("--host-prefix=")) {
672      host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
673    } else if (option.starts_with("--android-root=")) {
674      android_root = option.substr(strlen("--android-root=")).data();
675    } else if (option.starts_with("--instruction-set=")) {
676      StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
677      if (instruction_set_str == "arm") {
678        instruction_set = kThumb2;
679      } else if (instruction_set_str == "mips") {
680        instruction_set = kMips;
681      } else if (instruction_set_str == "x86") {
682        instruction_set = kX86;
683      }
684    } else if (option.starts_with("--compiler-backend=")) {
685      StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
686      if (backend_str == "Quick") {
687        compiler_backend = kQuick;
688      } else if (backend_str == "Portable") {
689        compiler_backend = kPortable;
690      }
691    } else if (option == "--host") {
692      is_host = true;
693    } else if (option == "--runtime-arg") {
694      if (++i >= argc) {
695        Usage("Missing required argument for --runtime-arg");
696      }
697      if (log_options) {
698        LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
699      }
700      runtime_args.push_back(argv[i]);
701    } else if (option == "--dump-timing") {
702      dump_timing = true;
703    } else {
704      Usage("unknown argument %s", option.data());
705    }
706  }
707
708  if (oat_filename.empty() && oat_fd == -1) {
709    Usage("Output must be supplied with either --oat-file or --oat-fd");
710  }
711
712  if (!oat_filename.empty() && oat_fd != -1) {
713    Usage("--oat-file should not be used with --oat-fd");
714  }
715
716  if (!oat_symbols.empty() && oat_fd != -1) {
717    Usage("--oat-symbols should not be used with --oat-fd");
718  }
719
720  if (!oat_symbols.empty() && is_host) {
721    Usage("--oat-symbols should not be used with --host");
722  }
723
724  if (oat_fd != -1 && !image_filename.empty()) {
725    Usage("--oat-fd should not be used with --image");
726  }
727
728  if (host_prefix.get() == NULL) {
729    const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
730    if (android_product_out != NULL) {
731        host_prefix.reset(new std::string(android_product_out));
732    }
733  }
734
735  if (android_root.empty()) {
736    const char* android_root_env_var = getenv("ANDROID_ROOT");
737    if (android_root_env_var == NULL) {
738      Usage("--android-root unspecified and ANDROID_ROOT not set");
739    }
740    android_root += android_root_env_var;
741  }
742
743  bool image = (!image_filename.empty());
744  if (!image && boot_image_filename.empty()) {
745    if (host_prefix.get() == NULL) {
746      boot_image_filename += GetAndroidRoot();
747    } else {
748      boot_image_filename += *host_prefix.get();
749      boot_image_filename += "/system";
750    }
751    boot_image_filename += "/framework/boot.art";
752  }
753  std::string boot_image_option;
754  if (!boot_image_filename.empty()) {
755    boot_image_option += "-Ximage:";
756    boot_image_option += boot_image_filename;
757  }
758
759  if (image_classes_filename != NULL && !image) {
760    Usage("--image-classes should only be used with --image");
761  }
762
763  if (image_classes_filename != NULL && !boot_image_option.empty()) {
764    Usage("--image-classes should not be used with --boot-image");
765  }
766
767  if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
768    Usage("--image-classes-zip should be used with --image-classes");
769  }
770
771  if (dex_filenames.empty() && zip_fd == -1) {
772    Usage("Input must be supplied with either --dex-file or --zip-fd");
773  }
774
775  if (!dex_filenames.empty() && zip_fd != -1) {
776    Usage("--dex-file should not be used with --zip-fd");
777  }
778
779  if (!dex_filenames.empty() && !zip_location.empty()) {
780    Usage("--dex-file should not be used with --zip-location");
781  }
782
783  if (dex_locations.empty()) {
784    for (size_t i = 0; i < dex_filenames.size(); i++) {
785      dex_locations.push_back(dex_filenames[i]);
786    }
787  } else if (dex_locations.size() != dex_filenames.size()) {
788    Usage("--dex-location arguments do not match --dex-file arguments");
789  }
790
791  if (zip_fd != -1 && zip_location.empty()) {
792    Usage("--zip-location should be supplied with --zip-fd");
793  }
794
795  if (boot_image_option.empty()) {
796    if (image_base == 0) {
797      Usage("non-zero --base not specified");
798    }
799  }
800
801  std::string oat_stripped(oat_filename);
802  std::string oat_unstripped;
803  if (!oat_symbols.empty()) {
804    oat_unstripped += oat_symbols;
805  } else {
806    oat_unstripped += oat_filename;
807  }
808
809  // Done with usage checks, enable watchdog if requested
810  WatchDog watch_dog(watch_dog_enabled);
811
812  // Check early that the result of compilation can be written
813  UniquePtr<File> oat_file;
814  bool create_file = !oat_unstripped.empty();  // as opposed to using open file descriptor
815  if (create_file) {
816    oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
817    if (oat_location.empty()) {
818      oat_location = oat_filename;
819    }
820  } else {
821    oat_file.reset(new File(oat_fd, oat_location));
822    oat_file->DisableAutoClose();
823  }
824  if (oat_file.get() == NULL) {
825    PLOG(ERROR) << "Failed to create oat file: " << oat_location;
826    return EXIT_FAILURE;
827  }
828  if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
829    PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
830    return EXIT_FAILURE;
831  }
832
833  timings.StartSplit("dex2oat Setup");
834  LOG(INFO) << "dex2oat: " << oat_location;
835
836  Runtime::Options options;
837  options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
838  std::vector<const DexFile*> boot_class_path;
839  if (boot_image_option.empty()) {
840    size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
841    if (failure_count > 0) {
842      LOG(ERROR) << "Failed to open some dex files: " << failure_count;
843      return EXIT_FAILURE;
844    }
845    options.push_back(std::make_pair("bootclasspath", &boot_class_path));
846  } else {
847    options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
848  }
849  if (host_prefix.get() != NULL) {
850    options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
851  }
852  for (size_t i = 0; i < runtime_args.size(); i++) {
853    options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
854  }
855
856#ifdef ART_SEA_IR_MODE
857  options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
858#endif
859
860  Dex2Oat* p_dex2oat;
861  if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count)) {
862    LOG(ERROR) << "Failed to create dex2oat";
863    return EXIT_FAILURE;
864  }
865  UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
866  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
867  // give it away now and then switch to a more managable ScopedObjectAccess.
868  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
869  // If we're doing the image, override the compiler filter to force full compilation. Must be
870  // done ahead of WellKnownClasses::Init that causes verification.  Note: doesn't force
871  // compilation of class initializers.
872  if (image) {
873    Runtime::Current()->SetCompilerFilter(Runtime::kEverything);
874  }
875  // Whilst we're in native take the opportunity to initialize well known classes.
876  WellKnownClasses::Init(Thread::Current()->GetJniEnv());
877  ScopedObjectAccess soa(Thread::Current());
878
879  // If --image-classes was specified, calculate the full list of classes to include in the image
880  UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
881  if (image_classes_filename != NULL) {
882    if (image_classes_zip_filename != NULL) {
883      image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
884                                                           image_classes_filename));
885    } else {
886      image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
887    }
888    if (image_classes.get() == NULL) {
889      LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
890      return EXIT_FAILURE;
891    }
892  }
893
894  std::vector<const DexFile*> dex_files;
895  if (boot_image_option.empty()) {
896    dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
897  } else {
898    if (dex_filenames.empty()) {
899      UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
900      if (zip_archive.get() == NULL) {
901        LOG(ERROR) << "Failed to open zip from file descriptor for " << zip_location;
902        return EXIT_FAILURE;
903      }
904      const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
905      if (dex_file == NULL) {
906        LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
907        return EXIT_FAILURE;
908      }
909      dex_files.push_back(dex_file);
910    } else {
911      size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
912      if (failure_count > 0) {
913        LOG(ERROR) << "Failed to open some dex files: " << failure_count;
914        return EXIT_FAILURE;
915      }
916    }
917  }
918
919  /*
920   * If we're not in interpret-only mode, go ahead and compile small applications. Don't
921   * bother to check if we're doing the image.
922   */
923  if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
924    size_t num_methods = 0;
925    for (size_t i = 0; i != dex_files.size(); ++i) {
926      const DexFile* dex_file = dex_files[i];
927      CHECK(dex_file != NULL);
928      num_methods += dex_file->NumMethodIds();
929    }
930    if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
931      Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
932      VLOG(compiler) << "Below method threshold, compiling anyways";
933    }
934  }
935
936  UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
937                                                                  host_prefix.get(),
938                                                                  android_root,
939                                                                  is_host,
940                                                                  dex_files,
941                                                                  oat_file.get(),
942                                                                  bitcode_filename,
943                                                                  image,
944                                                                  image_classes,
945                                                                  dump_stats,
946                                                                  timings));
947
948  if (compiler.get() == NULL) {
949    LOG(ERROR) << "Failed to create oat file: " << oat_location;
950    return EXIT_FAILURE;
951  }
952
953  VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
954
955  // Notes on the interleaving of creating the image and oat file to
956  // ensure the references between the two are correct.
957  //
958  // Currently we have a memory layout that looks something like this:
959  //
960  // +--------------+
961  // | image        |
962  // +--------------+
963  // | boot oat     |
964  // +--------------+
965  // | alloc spaces |
966  // +--------------+
967  //
968  // There are several constraints on the loading of the image and boot.oat.
969  //
970  // 1. The image is expected to be loaded at an absolute address and
971  // contains Objects with absolute pointers within the image.
972  //
973  // 2. There are absolute pointers from Methods in the image to their
974  // code in the oat.
975  //
976  // 3. There are absolute pointers from the code in the oat to Methods
977  // in the image.
978  //
979  // 4. There are absolute pointers from code in the oat to other code
980  // in the oat.
981  //
982  // To get this all correct, we go through several steps.
983  //
984  // 1. We have already created that oat file above with
985  // CreateOatFile. Originally this was just our own proprietary file
986  // but now it is contained within an ELF dynamic object (aka an .so
987  // file). The Compiler returned by CreateOatFile provides
988  // PatchInformation for references to oat code and Methods that need
989  // to be update once we know where the oat file will be located
990  // after the image.
991  //
992  // 2. We create the image file. It needs to know where the oat file
993  // will be loaded after itself. Originally when oat file was simply
994  // memory mapped so we could predict where its contents were based
995  // on the file size. Now that it is an ELF file, we need to inspect
996  // the ELF file to understand the in memory segment layout including
997  // where the oat header is located within. ImageWriter's
998  // PatchOatCodeAndMethods uses the PatchInformation from the
999  // Compiler to touch up absolute references in the oat file.
1000  //
1001  // 3. We fixup the ELF program headers so that dlopen will try to
1002  // load the .so at the desired location at runtime by offsetting the
1003  // Elf32_Phdr.p_vaddr values by the desired base address.
1004  //
1005  if (image) {
1006    timings.NewSplit("dex2oat ImageWriter");
1007    Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1008    bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1009                                                           image_base,
1010                                                           oat_unstripped,
1011                                                           oat_location,
1012                                                           *compiler.get());
1013    Thread::Current()->TransitionFromSuspendedToRunnable();
1014    if (!image_creation_success) {
1015      return EXIT_FAILURE;
1016    }
1017    VLOG(compiler) << "Image written successfully: " << image_filename;
1018  }
1019
1020  if (is_host) {
1021    if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
1022      LOG(INFO) << Dumpable<base::TimingLogger>(timings);
1023    }
1024    return EXIT_SUCCESS;
1025  }
1026
1027  // If we don't want to strip in place, copy from unstripped location to stripped location.
1028  // We need to strip after image creation because FixupElf needs to use .strtab.
1029  if (oat_unstripped != oat_stripped) {
1030    timings.NewSplit("dex2oat OatFile copy");
1031    oat_file.reset();
1032     UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1033    UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
1034    size_t buffer_size = 8192;
1035    UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1036    while (true) {
1037      int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1038      if (bytes_read <= 0) {
1039        break;
1040      }
1041      bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1042      CHECK(write_ok);
1043    }
1044    oat_file.reset(out.release());
1045    VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
1046  }
1047
1048#if ART_USE_PORTABLE_COMPILER  // We currently only generate symbols on Portable
1049  timings.NewSplit("dex2oat ElfStripper");
1050  // Strip unneeded sections for target
1051  off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1052  CHECK_EQ(0, seek_actual);
1053  ElfStripper::Strip(oat_file.get());
1054
1055
1056  // We wrote the oat file successfully, and want to keep it.
1057  VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
1058#endif  // ART_USE_PORTABLE_COMPILER
1059
1060  timings.EndSplit();
1061
1062  if (dump_timing && timings.GetTotalNs() > MsToNs(1000)) {
1063    LOG(INFO) << Dumpable<base::TimingLogger>(timings);
1064  }
1065  return EXIT_SUCCESS;
1066}
1067
1068
1069}  // namespace art
1070
1071int main(int argc, char** argv) {
1072  return art::dex2oat(argc, argv);
1073}
1074