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