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