dex2oat.cc revision d582fa4ea62083a7598dded5b82dc2198b3daac7
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#include <valgrind.h>
21
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
28#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
33#define ATRACE_TAG ATRACE_TAG_DALVIK
34#include <cutils/trace.h>
35
36#include "arch/instruction_set_features.h"
37#include "base/dumpable.h"
38#include "base/stl_util.h"
39#include "base/stringpiece.h"
40#include "base/timing_logger.h"
41#include "base/unix_file/fd_file.h"
42#include "class_linker.h"
43#include "compiler.h"
44#include "compiler_callbacks.h"
45#include "dex_file-inl.h"
46#include "dex/pass_driver_me_opts.h"
47#include "dex/verification_results.h"
48#include "dex/quick_compiler_callbacks.h"
49#include "dex/quick/dex_file_to_method_inliner_map.h"
50#include "driver/compiler_driver.h"
51#include "driver/compiler_options.h"
52#include "elf_file.h"
53#include "elf_writer.h"
54#include "gc/space/image_space.h"
55#include "gc/space/space-inl.h"
56#include "image_writer.h"
57#include "leb128.h"
58#include "mirror/art_method-inl.h"
59#include "mirror/class-inl.h"
60#include "mirror/class_loader.h"
61#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "oat_writer.h"
64#include "os.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
68#include "utils.h"
69#include "vector_output_stream.h"
70#include "well_known_classes.h"
71#include "zip_archive.h"
72
73namespace art {
74
75static int original_argc;
76static char** original_argv;
77
78static std::string CommandLine() {
79  std::vector<std::string> command;
80  for (int i = 0; i < original_argc; ++i) {
81    command.push_back(original_argv[i]);
82  }
83  return Join(command, ' ');
84}
85
86static void UsageErrorV(const char* fmt, va_list ap) {
87  std::string error;
88  StringAppendV(&error, fmt, ap);
89  LOG(ERROR) << error;
90}
91
92static void UsageError(const char* fmt, ...) {
93  va_list ap;
94  va_start(ap, fmt);
95  UsageErrorV(fmt, ap);
96  va_end(ap);
97}
98
99[[noreturn]] static void Usage(const char* fmt, ...) {
100  va_list ap;
101  va_start(ap, fmt);
102  UsageErrorV(fmt, ap);
103  va_end(ap);
104
105  UsageError("Command: %s", CommandLine().c_str());
106
107  UsageError("Usage: dex2oat [options]...");
108  UsageError("");
109  UsageError("  --dex-file=<dex-file>: specifies a .dex file to compile.");
110  UsageError("      Example: --dex-file=/system/framework/core.jar");
111  UsageError("");
112  UsageError("  --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
113  UsageError("      containing a classes.dex file to compile.");
114  UsageError("      Example: --zip-fd=5");
115  UsageError("");
116  UsageError("  --zip-location=<zip-location>: specifies a symbolic name for the file");
117  UsageError("      corresponding to the file descriptor specified by --zip-fd.");
118  UsageError("      Example: --zip-location=/system/app/Calculator.apk");
119  UsageError("");
120  UsageError("  --oat-file=<file.oat>: specifies the oat output destination via a filename.");
121  UsageError("      Example: --oat-file=/system/framework/boot.oat");
122  UsageError("");
123  UsageError("  --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
124  UsageError("      Example: --oat-fd=6");
125  UsageError("");
126  UsageError("  --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
127  UsageError("      to the file descriptor specified by --oat-fd.");
128  UsageError("      Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
129  UsageError("");
130  UsageError("  --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
131  UsageError("      Example: --oat-symbols=/symbols/system/framework/boot.oat");
132  UsageError("");
133  UsageError("  --bitcode=<file.bc>: specifies the optional bitcode filename.");
134  UsageError("      Example: --bitcode=/system/framework/boot.bc");
135  UsageError("");
136  UsageError("  --image=<file.art>: specifies the output image filename.");
137  UsageError("      Example: --image=/system/framework/boot.art");
138  UsageError("");
139  UsageError("  --image-classes=<classname-file>: specifies classes to include in an image.");
140  UsageError("      Example: --image=frameworks/base/preloaded-classes");
141  UsageError("");
142  UsageError("  --base=<hex-address>: specifies the base address when creating a boot image.");
143  UsageError("      Example: --base=0x50000000");
144  UsageError("");
145  UsageError("  --boot-image=<file.art>: provide the image file for the boot class path.");
146  UsageError("      Example: --boot-image=/system/framework/boot.art");
147  UsageError("      Default: $ANDROID_ROOT/system/framework/boot.art");
148  UsageError("");
149  UsageError("  --android-root=<path>: used to locate libraries for portable linking.");
150  UsageError("      Example: --android-root=out/host/linux-x86");
151  UsageError("      Default: $ANDROID_ROOT");
152  UsageError("");
153  UsageError("  --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
154  UsageError("      instruction set.");
155  UsageError("      Example: --instruction-set=x86");
156  UsageError("      Default: arm");
157  UsageError("");
158  UsageError("  --instruction-set-features=...,: Specify instruction set features");
159  UsageError("      Example: --instruction-set-features=div");
160  UsageError("      Default: default");
161  UsageError("");
162  UsageError("  --compile-pic: Force indirect use of code, methods, and classes");
163  UsageError("      Default: disabled");
164  UsageError("");
165  UsageError("  --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
166  UsageError("      set.");
167  UsageError("      Example: --compiler-backend=Portable");
168  UsageError("      Default: Quick");
169  UsageError("");
170  UsageError("  --compiler-filter="
171                "(verify-none"
172                "|interpret-only"
173                "|space"
174                "|balanced"
175                "|speed"
176                "|everything"
177                "|time):");
178  UsageError("      select compiler filter.");
179  UsageError("      Example: --compiler-filter=everything");
180#if ART_SMALL_MODE
181  UsageError("      Default: interpret-only");
182#else
183  UsageError("      Default: speed");
184#endif
185  UsageError("");
186  UsageError("  --huge-method-max=<method-instruction-count>: the threshold size for a huge");
187  UsageError("      method for compiler filter tuning.");
188  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
189  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
190  UsageError("");
191  UsageError("  --huge-method-max=<method-instruction-count>: threshold size for a huge");
192  UsageError("      method for compiler filter tuning.");
193  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
194  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
195  UsageError("");
196  UsageError("  --large-method-max=<method-instruction-count>: threshold size for a large");
197  UsageError("      method for compiler filter tuning.");
198  UsageError("      Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
199  UsageError("      Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
200  UsageError("");
201  UsageError("  --small-method-max=<method-instruction-count>: threshold size for a small");
202  UsageError("      method for compiler filter tuning.");
203  UsageError("      Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
204  UsageError("      Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
205  UsageError("");
206  UsageError("  --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
207  UsageError("      method for compiler filter tuning.");
208  UsageError("      Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
209  UsageError("      Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
210  UsageError("");
211  UsageError("  --num-dex-methods=<method-count>: threshold size for a small dex file for");
212  UsageError("      compiler filter tuning. If the input has fewer than this many methods");
213  UsageError("      and the filter is not interpret-only or verify-none, overrides the");
214  UsageError("      filter to use speed");
215  UsageError("      Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216  UsageError("      Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217  UsageError("");
218  UsageError("  --host: used with Portable backend to link against host runtime libraries");
219  UsageError("");
220  UsageError("  --dump-timing: display a breakdown of where time was spent");
221  UsageError("");
222  UsageError("  --include-patch-information: Include patching information so the generated code");
223  UsageError("      can have its base address moved without full recompilation.");
224  UsageError("");
225  UsageError("  --no-include-patch-information: Do not include patching information.");
226  UsageError("");
227  UsageError("  --include-debug-symbols: Include ELF symbols in this oat file");
228  UsageError("");
229  UsageError("  --no-include-debug-symbols: Do not include ELF symbols in this oat file");
230  UsageError("");
231  UsageError("  --runtime-arg <argument>: used to specify various arguments for the runtime,");
232  UsageError("      such as initial heap size, maximum heap size, and verbose output.");
233  UsageError("      Use a separate --runtime-arg switch for each argument.");
234  UsageError("      Example: --runtime-arg -Xms256m");
235  UsageError("");
236  UsageError("  --profile-file=<filename>: specify profiler output file to use for compilation.");
237  UsageError("");
238  UsageError("  --print-pass-names: print a list of pass names");
239  UsageError("");
240  UsageError("  --disable-passes=<pass-names>:  disable one or more passes separated by comma.");
241  UsageError("      Example: --disable-passes=UseCount,BBOptimizations");
242  UsageError("");
243  UsageError("  --print-pass-options: print a list of passes that have configurable options along "
244             "with the setting.");
245  UsageError("      Will print default if no overridden setting exists.");
246  UsageError("");
247  UsageError("  --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
248             "Pass2Name:Pass2OptionName:Pass2Option#");
249  UsageError("      Used to specify a pass specific option. The setting itself must be integer.");
250  UsageError("      Separator used between options is a comma.");
251  UsageError("");
252  std::cerr << "See log for usage error information\n";
253  exit(EXIT_FAILURE);
254}
255
256// The primary goal of the watchdog is to prevent stuck build servers
257// during development when fatal aborts lead to a cascade of failures
258// that result in a deadlock.
259class WatchDog {
260// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
261#undef CHECK_PTHREAD_CALL
262#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
263  do { \
264    int rc = call args; \
265    if (rc != 0) { \
266      errno = rc; \
267      std::string message(# call); \
268      message += " failed for "; \
269      message += reason; \
270      Fatal(message); \
271    } \
272  } while (false)
273
274 public:
275  explicit WatchDog(bool is_watch_dog_enabled) {
276    is_watch_dog_enabled_ = is_watch_dog_enabled;
277    if (!is_watch_dog_enabled_) {
278      return;
279    }
280    shutting_down_ = false;
281    const char* reason = "dex2oat watch dog thread startup";
282    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
283    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
284    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
285    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
286    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
287  }
288  ~WatchDog() {
289    if (!is_watch_dog_enabled_) {
290      return;
291    }
292    const char* reason = "dex2oat watch dog thread shutdown";
293    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
294    shutting_down_ = true;
295    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
296    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
297
298    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
299
300    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
301    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
302  }
303
304 private:
305  static void* CallBack(void* arg) {
306    WatchDog* self = reinterpret_cast<WatchDog*>(arg);
307    ::art::SetThreadName("dex2oat watch dog");
308    self->Wait();
309    return nullptr;
310  }
311
312  static void Message(char severity, const std::string& message) {
313    // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
314    //       cases.
315    fprintf(stderr, "dex2oat%s %c %d %d %s\n",
316            kIsDebugBuild ? "d" : "",
317            severity,
318            getpid(),
319            GetTid(),
320            message.c_str());
321  }
322
323  static void Warn(const std::string& message) {
324    Message('W', message);
325  }
326
327  [[noreturn]] static void Fatal(const std::string& message) {
328    Message('F', message);
329    exit(1);
330  }
331
332  void Wait() {
333    bool warning = true;
334    CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
335    // TODO: tune the multiplier for GC verification, the following is just to make the timeout
336    //       large.
337    int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
338    timespec warning_ts;
339    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
340    timespec timeout_ts;
341    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
342    const char* reason = "dex2oat watch dog thread waiting";
343    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
344    while (!shutting_down_) {
345      int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
346                                                         warning ? &warning_ts
347                                                                 : &timeout_ts));
348      if (rc == ETIMEDOUT) {
349        std::string message(StringPrintf("dex2oat did not finish after %d seconds",
350                                         warning ? kWatchDogWarningSeconds
351                                                 : kWatchDogTimeoutSeconds));
352        if (warning) {
353          Warn(message.c_str());
354          warning = false;
355        } else {
356          Fatal(message.c_str());
357        }
358      } else if (rc != 0) {
359        std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
360                                         strerror(errno)));
361        Fatal(message.c_str());
362      }
363    }
364    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
365  }
366
367  // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
368  // Debug builds are slower so they have larger timeouts.
369  static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
370
371  static const unsigned int kWatchDogWarningSeconds = kUsePortableCompiler ?
372      kSlowdownFactor * 2 * 60 :   // 2 minutes scaled by kSlowdownFactor (portable).
373      kSlowdownFactor * 1 * 60;    // 1 minute scaled by kSlowdownFactor  (not-portable).
374  static const unsigned int kWatchDogTimeoutSeconds = kUsePortableCompiler ?
375      kSlowdownFactor * 30 * 60 :  // 30 minutes scaled by kSlowdownFactor (portable).
376      kSlowdownFactor * 6 * 60;    // 6 minutes scaled by kSlowdownFactor  (not-portable).
377
378  bool is_watch_dog_enabled_;
379  bool shutting_down_;
380  // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
381  pthread_mutex_t mutex_;
382  pthread_cond_t cond_;
383  pthread_attr_t attr_;
384  pthread_t pthread_;
385};
386
387static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
388  std::string::size_type colon = s.find(c);
389  if (colon == std::string::npos) {
390    Usage("Missing char %c in option %s\n", c, s.c_str());
391  }
392  // Add one to remove the char we were trimming until.
393  *parsed_value = s.substr(colon + 1);
394}
395
396static void ParseDouble(const std::string& option, char after_char, double min, double max,
397                        double* parsed_value) {
398  std::string substring;
399  ParseStringAfterChar(option, after_char, &substring);
400  bool sane_val = true;
401  double value;
402  if (false) {
403    // TODO: this doesn't seem to work on the emulator.  b/15114595
404    std::stringstream iss(substring);
405    iss >> value;
406    // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
407    sane_val = iss.eof() && (value >= min) && (value <= max);
408  } else {
409    char* end = nullptr;
410    value = strtod(substring.c_str(), &end);
411    sane_val = *end == '\0' && value >= min && value <= max;
412  }
413  if (!sane_val) {
414    Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
415  }
416  *parsed_value = value;
417}
418
419class Dex2Oat FINAL {
420 public:
421  explicit Dex2Oat(TimingLogger* timings) :
422      compiler_kind_(kUsePortableCompiler ? Compiler::kPortable : Compiler::kQuick),
423      instruction_set_(kRuntimeISA),
424      // Take the default set of instruction features from the build.
425      method_inliner_map_(),
426      runtime_(nullptr),
427      thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
428      start_ns_(NanoTime()),
429      oat_fd_(-1),
430      zip_fd_(-1),
431      image_base_(0U),
432      image_classes_zip_filename_(nullptr),
433      image_classes_filename_(nullptr),
434      compiled_classes_zip_filename_(nullptr),
435      compiled_classes_filename_(nullptr),
436      image_(false),
437      is_host_(false),
438      dump_stats_(false),
439      dump_passes_(false),
440      dump_timing_(false),
441      dump_slow_timing_(kIsDebugBuild),
442      timings_(timings) {}
443
444  ~Dex2Oat() {
445    if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
446      delete runtime_;  // See field declaration for why this is manual.
447    }
448    LogCompletionTime();
449  }
450
451  // Parse the arguments from the command line. In case of an unrecognized option or impossible
452  // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
453  // returns, arguments have been successfully parsed.
454  void ParseArgs(int argc, char** argv) {
455    original_argc = argc;
456    original_argv = argv;
457
458    InitLogging(argv);
459
460    // Skip over argv[0].
461    argv++;
462    argc--;
463
464    if (argc == 0) {
465      Usage("No arguments specified");
466    }
467
468    std::string oat_symbols;
469    std::string boot_image_filename;
470    const char* compiler_filter_string = nullptr;
471    bool compile_pic = false;
472    int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
473    int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
474    int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
475    int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
476    int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
477
478    // Profile file to use
479    double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
480
481    bool print_pass_options = false;
482    bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
483    bool include_debug_symbols = kIsDebugBuild;
484    bool watch_dog_enabled = true;
485    bool generate_gdb_information = kIsDebugBuild;
486
487    std::string error_msg;
488
489    for (int i = 0; i < argc; i++) {
490      const StringPiece option(argv[i]);
491      const bool log_options = false;
492      if (log_options) {
493        LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
494      }
495      if (option.starts_with("--dex-file=")) {
496        dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
497      } else if (option.starts_with("--dex-location=")) {
498        dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
499      } else if (option.starts_with("--zip-fd=")) {
500        const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
501        if (!ParseInt(zip_fd_str, &zip_fd_)) {
502          Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
503        }
504        if (zip_fd_ < 0) {
505          Usage("--zip-fd passed a negative value %d", zip_fd_);
506        }
507      } else if (option.starts_with("--zip-location=")) {
508        zip_location_ = option.substr(strlen("--zip-location=")).data();
509      } else if (option.starts_with("--oat-file=")) {
510        oat_filename_ = option.substr(strlen("--oat-file=")).data();
511      } else if (option.starts_with("--oat-symbols=")) {
512        oat_symbols = option.substr(strlen("--oat-symbols=")).data();
513      } else if (option.starts_with("--oat-fd=")) {
514        const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
515        if (!ParseInt(oat_fd_str, &oat_fd_)) {
516          Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
517        }
518        if (oat_fd_ < 0) {
519          Usage("--oat-fd passed a negative value %d", oat_fd_);
520        }
521      } else if (option == "--watch-dog") {
522        watch_dog_enabled = true;
523      } else if (option == "--no-watch-dog") {
524        watch_dog_enabled = false;
525      } else if (option == "--gen-gdb-info") {
526        generate_gdb_information = true;
527        // Debug symbols are needed for gdb information.
528        include_debug_symbols = true;
529      } else if (option == "--no-gen-gdb-info") {
530        generate_gdb_information = false;
531      } else if (option.starts_with("-j")) {
532        const char* thread_count_str = option.substr(strlen("-j")).data();
533        if (!ParseUint(thread_count_str, &thread_count_)) {
534          Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
535        }
536      } else if (option.starts_with("--oat-location=")) {
537        oat_location_ = option.substr(strlen("--oat-location=")).data();
538      } else if (option.starts_with("--bitcode=")) {
539        bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
540      } else if (option.starts_with("--image=")) {
541        image_filename_ = option.substr(strlen("--image=")).data();
542      } else if (option.starts_with("--image-classes=")) {
543        image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
544      } else if (option.starts_with("--image-classes-zip=")) {
545        image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
546      } else if (option.starts_with("--compiled-classes=")) {
547        compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
548      } else if (option.starts_with("--compiled-classes-zip=")) {
549        compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
550      } else if (option.starts_with("--base=")) {
551        const char* image_base_str = option.substr(strlen("--base=")).data();
552        char* end;
553        image_base_ = strtoul(image_base_str, &end, 16);
554        if (end == image_base_str || *end != '\0') {
555          Usage("Failed to parse hexadecimal value for option %s", option.data());
556        }
557      } else if (option.starts_with("--boot-image=")) {
558        boot_image_filename = option.substr(strlen("--boot-image=")).data();
559      } else if (option.starts_with("--android-root=")) {
560        android_root_ = option.substr(strlen("--android-root=")).data();
561      } else if (option.starts_with("--instruction-set=")) {
562        StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
563        // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
564        std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
565        strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
566        buf.get()[instruction_set_str.length()] = 0;
567        instruction_set_ = GetInstructionSetFromString(buf.get());
568        // arm actually means thumb2.
569        if (instruction_set_ == InstructionSet::kArm) {
570          instruction_set_ = InstructionSet::kThumb2;
571        }
572      } else if (option.starts_with("--instruction-set-variant=")) {
573        StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
574        instruction_set_features_.reset(
575            InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
576        if (instruction_set_features_.get() == nullptr) {
577          Usage("%s", error_msg.c_str());
578        }
579      } else if (option.starts_with("--instruction-set-features=")) {
580        StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
581        if (instruction_set_features_.get() == nullptr) {
582          instruction_set_features_.reset(
583              InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
584          if (instruction_set_features_.get() == nullptr) {
585            Usage("Problem initializing default instruction set features variant: %s",
586                  error_msg.c_str());
587          }
588        }
589        instruction_set_features_.reset(
590            instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
591        if (instruction_set_features_.get() == nullptr) {
592          Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
593        }
594      } else if (option.starts_with("--compiler-backend=")) {
595        StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
596        if (backend_str == "Quick") {
597          compiler_kind_ = Compiler::kQuick;
598        } else if (backend_str == "Optimizing") {
599          compiler_kind_ = Compiler::kOptimizing;
600          compile_pic = true;
601        } else if (backend_str == "Portable") {
602          compiler_kind_ = Compiler::kPortable;
603        } else {
604          Usage("Unknown compiler backend: %s", backend_str.data());
605        }
606      } else if (option.starts_with("--compiler-filter=")) {
607        compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
608      } else if (option == "--compile-pic") {
609        compile_pic = true;
610      } else if (option.starts_with("--huge-method-max=")) {
611        const char* threshold = option.substr(strlen("--huge-method-max=")).data();
612        if (!ParseInt(threshold, &huge_method_threshold)) {
613          Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
614        }
615        if (huge_method_threshold < 0) {
616          Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
617        }
618      } else if (option.starts_with("--large-method-max=")) {
619        const char* threshold = option.substr(strlen("--large-method-max=")).data();
620        if (!ParseInt(threshold, &large_method_threshold)) {
621          Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
622        }
623        if (large_method_threshold < 0) {
624          Usage("--large-method-max passed a negative value %s", large_method_threshold);
625        }
626      } else if (option.starts_with("--small-method-max=")) {
627        const char* threshold = option.substr(strlen("--small-method-max=")).data();
628        if (!ParseInt(threshold, &small_method_threshold)) {
629          Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
630        }
631        if (small_method_threshold < 0) {
632          Usage("--small-method-max passed a negative value %s", small_method_threshold);
633        }
634      } else if (option.starts_with("--tiny-method-max=")) {
635        const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
636        if (!ParseInt(threshold, &tiny_method_threshold)) {
637          Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
638        }
639        if (tiny_method_threshold < 0) {
640          Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
641        }
642      } else if (option.starts_with("--num-dex-methods=")) {
643        const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
644        if (!ParseInt(threshold, &num_dex_methods_threshold)) {
645          Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
646        }
647        if (num_dex_methods_threshold < 0) {
648          Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
649        }
650      } else if (option == "--host") {
651        is_host_ = true;
652      } else if (option == "--runtime-arg") {
653        if (++i >= argc) {
654          Usage("Missing required argument for --runtime-arg");
655        }
656        if (log_options) {
657          LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
658        }
659        runtime_args_.push_back(argv[i]);
660      } else if (option == "--dump-timing") {
661        dump_timing_ = true;
662      } else if (option == "--dump-passes") {
663        dump_passes_ = true;
664      } else if (option == "--dump-stats") {
665        dump_stats_ = true;
666      } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
667        include_debug_symbols = true;
668      } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
669        include_debug_symbols = false;
670        generate_gdb_information = false;  // Depends on debug symbols, see above.
671      } else if (option.starts_with("--profile-file=")) {
672        profile_file_ = option.substr(strlen("--profile-file=")).data();
673        VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
674      } else if (option == "--no-profile-file") {
675        // No profile
676      } else if (option.starts_with("--top-k-profile-threshold=")) {
677        ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
678      } else if (option == "--print-pass-names") {
679        PassDriverMEOpts::PrintPassNames();
680      } else if (option.starts_with("--disable-passes=")) {
681        std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
682        PassDriverMEOpts::CreateDefaultPassList(disable_passes);
683      } else if (option.starts_with("--print-passes=")) {
684        std::string print_passes = option.substr(strlen("--print-passes=")).data();
685        PassDriverMEOpts::SetPrintPassList(print_passes);
686      } else if (option == "--print-all-passes") {
687        PassDriverMEOpts::SetPrintAllPasses();
688      } else if (option.starts_with("--dump-cfg-passes=")) {
689        std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
690        PassDriverMEOpts::SetDumpPassList(dump_passes_string);
691      } else if (option == "--print-pass-options") {
692        print_pass_options = true;
693      } else if (option.starts_with("--pass-options=")) {
694        std::string options = option.substr(strlen("--pass-options=")).data();
695        PassDriverMEOpts::SetOverriddenPassOptions(options);
696      } else if (option == "--include-patch-information") {
697        include_patch_information = true;
698      } else if (option == "--no-include-patch-information") {
699        include_patch_information = false;
700      } else if (option.starts_with("--verbose-methods=")) {
701        // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
702        //       on having verbost methods.
703        gLogVerbosity.compiler = false;
704        Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
705      } else {
706        Usage("Unknown argument %s", option.data());
707      }
708    }
709
710    if (oat_filename_.empty() && oat_fd_ == -1) {
711      Usage("Output must be supplied with either --oat-file or --oat-fd");
712    }
713
714    if (!oat_filename_.empty() && oat_fd_ != -1) {
715      Usage("--oat-file should not be used with --oat-fd");
716    }
717
718    if (!oat_symbols.empty() && oat_fd_ != -1) {
719      Usage("--oat-symbols should not be used with --oat-fd");
720    }
721
722    if (!oat_symbols.empty() && is_host_) {
723      Usage("--oat-symbols should not be used with --host");
724    }
725
726    if (oat_fd_ != -1 && !image_filename_.empty()) {
727      Usage("--oat-fd should not be used with --image");
728    }
729
730    if (android_root_.empty()) {
731      const char* android_root_env_var = getenv("ANDROID_ROOT");
732      if (android_root_env_var == nullptr) {
733        Usage("--android-root unspecified and ANDROID_ROOT not set");
734      }
735      android_root_ += android_root_env_var;
736    }
737
738    image_ = (!image_filename_.empty());
739    if (!image_ && boot_image_filename.empty()) {
740      boot_image_filename += android_root_;
741      boot_image_filename += "/framework/boot.art";
742    }
743    if (!boot_image_filename.empty()) {
744      boot_image_option_ += "-Ximage:";
745      boot_image_option_ += boot_image_filename;
746    }
747
748    if (image_classes_filename_ != nullptr && !image_) {
749      Usage("--image-classes should only be used with --image");
750    }
751
752    if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
753      Usage("--image-classes should not be used with --boot-image");
754    }
755
756    if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
757      Usage("--image-classes-zip should be used with --image-classes");
758    }
759
760    if (compiled_classes_filename_ != nullptr && !image_) {
761      Usage("--compiled-classes should only be used with --image");
762    }
763
764    if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
765      Usage("--compiled-classes should not be used with --boot-image");
766    }
767
768    if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
769      Usage("--compiled-classes-zip should be used with --compiled-classes");
770    }
771
772    if (dex_filenames_.empty() && zip_fd_ == -1) {
773      Usage("Input must be supplied with either --dex-file or --zip-fd");
774    }
775
776    if (!dex_filenames_.empty() && zip_fd_ != -1) {
777      Usage("--dex-file should not be used with --zip-fd");
778    }
779
780    if (!dex_filenames_.empty() && !zip_location_.empty()) {
781      Usage("--dex-file should not be used with --zip-location");
782    }
783
784    if (dex_locations_.empty()) {
785      for (const char* dex_file_name : dex_filenames_) {
786        dex_locations_.push_back(dex_file_name);
787      }
788    } else if (dex_locations_.size() != dex_filenames_.size()) {
789      Usage("--dex-location arguments do not match --dex-file arguments");
790    }
791
792    if (zip_fd_ != -1 && zip_location_.empty()) {
793      Usage("--zip-location should be supplied with --zip-fd");
794    }
795
796    if (boot_image_option_.empty()) {
797      if (image_base_ == 0) {
798        Usage("Non-zero --base not specified");
799      }
800    }
801
802    oat_stripped_ = oat_filename_;
803    if (!oat_symbols.empty()) {
804      oat_unstripped_ = oat_symbols;
805    } else {
806      oat_unstripped_ = oat_filename_;
807    }
808
809    // If no instruction set feature was given, use the default one for the target
810    // instruction set.
811    if (instruction_set_features_.get() == nullptr) {
812      instruction_set_features_.reset(
813          InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
814      if (instruction_set_features_.get() == nullptr) {
815        Usage("Problem initializing default instruction set features variant: %s",
816              error_msg.c_str());
817      }
818    }
819
820    if (instruction_set_ == kRuntimeISA) {
821      std::unique_ptr<const InstructionSetFeatures> runtime_features(
822          InstructionSetFeatures::FromCppDefines());
823      if (!instruction_set_features_->Equals(runtime_features.get())) {
824        LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
825            << *instruction_set_features_ << ") and those of dex2oat executable ("
826            << *runtime_features <<") for the command line:\n"
827            << CommandLine();
828      }
829    }
830
831    if (compiler_filter_string == nullptr) {
832      if (instruction_set_ == kMips64) {
833        // TODO: fix compiler for Mips64.
834        compiler_filter_string = "interpret-only";
835      } else if (image_) {
836        compiler_filter_string = "speed";
837      } else {
838        // TODO: Migrate SMALL mode to command line option.
839  #if ART_SMALL_MODE
840        compiler_filter_string = "interpret-only";
841  #else
842        compiler_filter_string = "speed";
843  #endif
844      }
845    }
846    CHECK(compiler_filter_string != nullptr);
847    CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
848    if (strcmp(compiler_filter_string, "verify-none") == 0) {
849      compiler_filter = CompilerOptions::kVerifyNone;
850    } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
851      compiler_filter = CompilerOptions::kInterpretOnly;
852    } else if (strcmp(compiler_filter_string, "space") == 0) {
853      compiler_filter = CompilerOptions::kSpace;
854    } else if (strcmp(compiler_filter_string, "balanced") == 0) {
855      compiler_filter = CompilerOptions::kBalanced;
856    } else if (strcmp(compiler_filter_string, "speed") == 0) {
857      compiler_filter = CompilerOptions::kSpeed;
858    } else if (strcmp(compiler_filter_string, "everything") == 0) {
859      compiler_filter = CompilerOptions::kEverything;
860    } else if (strcmp(compiler_filter_string, "time") == 0) {
861      compiler_filter = CompilerOptions::kTime;
862    } else {
863      Usage("Unknown --compiler-filter value %s", compiler_filter_string);
864    }
865
866    // Checks are all explicit until we know the architecture.
867    bool implicit_null_checks = false;
868    bool implicit_so_checks = false;
869    bool implicit_suspend_checks = false;
870    // Set the compilation target's implicit checks options.
871    switch (instruction_set_) {
872      case kArm:
873      case kThumb2:
874      case kArm64:
875      case kX86:
876      case kX86_64:
877        implicit_null_checks = true;
878        implicit_so_checks = true;
879        break;
880
881      default:
882        // Defaults are correct.
883        break;
884    }
885
886    if (print_pass_options) {
887      PassDriverMEOpts::PrintPassOptions();
888    }
889
890    compiler_options_.reset(new CompilerOptions(compiler_filter,
891                                                huge_method_threshold,
892                                                large_method_threshold,
893                                                small_method_threshold,
894                                                tiny_method_threshold,
895                                                num_dex_methods_threshold,
896                                                generate_gdb_information,
897                                                include_patch_information,
898                                                top_k_profile_threshold,
899                                                include_debug_symbols,
900                                                implicit_null_checks,
901                                                implicit_so_checks,
902                                                implicit_suspend_checks,
903                                                compile_pic,
904  #ifdef ART_SEA_IR_MODE
905                                                true,
906  #endif
907                                                verbose_methods_.empty() ?
908                                                    nullptr :
909                                                    &verbose_methods_));
910
911    // Done with usage checks, enable watchdog if requested
912    if (watch_dog_enabled) {
913      watchdog_.reset(new WatchDog(true));
914    }
915
916    // Fill some values into the key-value store for the oat header.
917    key_value_store_.reset(new SafeMap<std::string, std::string>());
918
919    // Insert some compiler things.
920    {
921      std::ostringstream oss;
922      for (int i = 0; i < argc; ++i) {
923        if (i > 0) {
924          oss << ' ';
925        }
926        oss << argv[i];
927      }
928      key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
929      oss.str("");  // Reset.
930      oss << kRuntimeISA;
931      key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
932      key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
933    }
934  }
935
936  // Check whether the oat output file is writable, and open it for later.
937  bool OpenFile() {
938    bool create_file = !oat_unstripped_.empty();  // as opposed to using open file descriptor
939    if (create_file) {
940      oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
941      if (oat_location_.empty()) {
942        oat_location_ = oat_filename_;
943      }
944    } else {
945      oat_file_.reset(new File(oat_fd_, oat_location_));
946      oat_file_->DisableAutoClose();
947      oat_file_->SetLength(0);
948    }
949    if (oat_file_.get() == nullptr) {
950      PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
951      return false;
952    }
953    if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
954      PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
955      return false;
956    }
957    return true;
958  }
959
960  // Set up the environment for compilation. Includes starting the runtime and loading/opening the
961  // boot class path.
962  bool Setup() {
963    TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
964    RuntimeOptions runtime_options;
965    std::vector<const DexFile*> boot_class_path;
966    art::MemMap::Init();  // For ZipEntry::ExtractToMemMap.
967    if (boot_image_option_.empty()) {
968      size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
969      if (failure_count > 0) {
970        LOG(ERROR) << "Failed to open some dex files: " << failure_count;
971        return false;
972      }
973      runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
974    } else {
975      runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
976    }
977    for (size_t i = 0; i < runtime_args_.size(); i++) {
978      runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
979    }
980
981    verification_results_.reset(new VerificationResults(compiler_options_.get()));
982    callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
983    runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
984    runtime_options.push_back(
985        std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
986
987    if (!CreateRuntime(runtime_options)) {
988      return false;
989    }
990
991    // Runtime::Create acquired the mutator_lock_ that is normally given away when we
992    // Runtime::Start, give it away now so that we don't starve GC.
993    Thread* self = Thread::Current();
994    self->TransitionFromRunnableToSuspended(kNative);
995    // If we're doing the image, override the compiler filter to force full compilation. Must be
996    // done ahead of WellKnownClasses::Init that causes verification.  Note: doesn't force
997    // compilation of class initializers.
998    // Whilst we're in native take the opportunity to initialize well known classes.
999    WellKnownClasses::Init(self->GetJniEnv());
1000
1001    // If --image-classes was specified, calculate the full list of classes to include in the image
1002    if (image_classes_filename_ != nullptr) {
1003      std::string error_msg;
1004      if (image_classes_zip_filename_ != nullptr) {
1005        image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1006                                                    image_classes_filename_,
1007                                                    &error_msg));
1008      } else {
1009        image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1010      }
1011      if (image_classes_.get() == nullptr) {
1012        LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1013            "': " << error_msg;
1014        return false;
1015      }
1016    } else if (image_) {
1017      image_classes_.reset(new std::set<std::string>);
1018    }
1019    // If --compiled-classes was specified, calculate the full list of classes to compile in the
1020    // image.
1021    if (compiled_classes_filename_ != nullptr) {
1022      std::string error_msg;
1023      if (compiled_classes_zip_filename_ != nullptr) {
1024        compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1025                                                        compiled_classes_filename_,
1026                                                        &error_msg));
1027      } else {
1028        compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1029      }
1030      if (compiled_classes_.get() == nullptr) {
1031        LOG(ERROR) << "Failed to create list of compiled classes from '"
1032                   << compiled_classes_filename_ << "': " << error_msg;
1033        return false;
1034      }
1035    } else if (image_) {
1036      compiled_classes_.reset(nullptr);  // By default compile everything.
1037    }
1038
1039    if (boot_image_option_.empty()) {
1040      dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1041    } else {
1042      if (dex_filenames_.empty()) {
1043        ATRACE_BEGIN("Opening zip archive from file descriptor");
1044        std::string error_msg;
1045        std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1046                                                                       zip_location_.c_str(),
1047                                                                       &error_msg));
1048        if (zip_archive.get() == nullptr) {
1049          LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1050              << error_msg;
1051          return false;
1052        }
1053        if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1054          LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1055              << "': " << error_msg;
1056          return false;
1057        }
1058        ATRACE_END();
1059      } else {
1060        size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1061        if (failure_count > 0) {
1062          LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1063          return false;
1064        }
1065      }
1066
1067      constexpr bool kSaveDexInput = false;
1068      if (kSaveDexInput) {
1069        for (size_t i = 0; i < dex_files_.size(); ++i) {
1070          const DexFile* dex_file = dex_files_[i];
1071          std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1072          std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1073          if (tmp_file.get() == nullptr) {
1074            PLOG(ERROR) << "Failed to open file " << tmp_file_name
1075                << ". Try: adb shell chmod 777 /data/local/tmp";
1076            continue;
1077          }
1078          tmp_file->WriteFully(dex_file->Begin(), dex_file->Size());
1079          LOG(INFO) << "Wrote input to " << tmp_file_name;
1080        }
1081      }
1082    }
1083    // Ensure opened dex files are writable for dex-to-dex transformations.
1084    for (const auto& dex_file : dex_files_) {
1085      if (!dex_file->EnableWrite()) {
1086        PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1087      }
1088    }
1089
1090    /*
1091     * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1092     * Don't bother to check if we're doing the image.
1093     */
1094    if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1095      size_t num_methods = 0;
1096      for (size_t i = 0; i != dex_files_.size(); ++i) {
1097        const DexFile* dex_file = dex_files_[i];
1098        CHECK(dex_file != nullptr);
1099        num_methods += dex_file->NumMethodIds();
1100      }
1101      if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1102        compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1103        VLOG(compiler) << "Below method threshold, compiling anyways";
1104      }
1105    }
1106
1107    return true;
1108  }
1109
1110  // Create and invoke the compiler driver. This will compile all the dex files.
1111  void Compile() {
1112    TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1113    compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
1114
1115    // Handle and ClassLoader creation needs to come after Runtime::Create
1116    jobject class_loader = nullptr;
1117    Thread* self = Thread::Current();
1118    if (!boot_image_option_.empty()) {
1119      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1120      std::vector<const DexFile*> class_path_files(dex_files_);
1121      OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1122      ScopedObjectAccess soa(self);
1123      for (size_t i = 0; i < class_path_files.size(); i++) {
1124        class_linker->RegisterDexFile(*class_path_files[i]);
1125      }
1126      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1127      ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1128          soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1129      class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1130      Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1131    }
1132
1133    driver_.reset(new CompilerDriver(compiler_options_.get(),
1134                                     verification_results_.get(),
1135                                     &method_inliner_map_,
1136                                     compiler_kind_,
1137                                     instruction_set_,
1138                                     instruction_set_features_.get(),
1139                                     image_,
1140                                     image_classes_.release(),
1141                                     compiled_classes_.release(),
1142                                     thread_count_,
1143                                     dump_stats_,
1144                                     dump_passes_,
1145                                     compiler_phases_timings_.get(),
1146                                     profile_file_));
1147
1148    driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1149
1150    driver_->CompileAll(class_loader, dex_files_, timings_);
1151  }
1152
1153  // Notes on the interleaving of creating the image and oat file to
1154  // ensure the references between the two are correct.
1155  //
1156  // Currently we have a memory layout that looks something like this:
1157  //
1158  // +--------------+
1159  // | image        |
1160  // +--------------+
1161  // | boot oat     |
1162  // +--------------+
1163  // | alloc spaces |
1164  // +--------------+
1165  //
1166  // There are several constraints on the loading of the image and boot.oat.
1167  //
1168  // 1. The image is expected to be loaded at an absolute address and
1169  // contains Objects with absolute pointers within the image.
1170  //
1171  // 2. There are absolute pointers from Methods in the image to their
1172  // code in the oat.
1173  //
1174  // 3. There are absolute pointers from the code in the oat to Methods
1175  // in the image.
1176  //
1177  // 4. There are absolute pointers from code in the oat to other code
1178  // in the oat.
1179  //
1180  // To get this all correct, we go through several steps.
1181  //
1182  // 1. We prepare offsets for all data in the oat file and calculate
1183  // the oat data size and code size. During this stage, we also set
1184  // oat code offsets in methods for use by the image writer.
1185  //
1186  // 2. We prepare offsets for the objects in the image and calculate
1187  // the image size.
1188  //
1189  // 3. We create the oat file. Originally this was just our own proprietary
1190  // file but now it is contained within an ELF dynamic object (aka an .so
1191  // file). Since we know the image size and oat data size and code size we
1192  // can prepare the ELF headers and we then know the ELF memory segment
1193  // layout and we can now resolve all references. The compiler provides
1194  // LinkerPatch information in each CompiledMethod and we resolve these,
1195  // using the layout information and image object locations provided by
1196  // image writer, as we're writing the method code.
1197  //
1198  // 4. We create the image file. It needs to know where the oat file
1199  // will be loaded after itself. Originally when oat file was simply
1200  // memory mapped so we could predict where its contents were based
1201  // on the file size. Now that it is an ELF file, we need to inspect
1202  // the ELF file to understand the in memory segment layout including
1203  // where the oat header is located within.
1204  // TODO: We could just remember this information from step 3.
1205  //
1206  // 5. We fixup the ELF program headers so that dlopen will try to
1207  // load the .so at the desired location at runtime by offsetting the
1208  // Elf32_Phdr.p_vaddr values by the desired base address.
1209  // TODO: Do this in step 3. We already know the layout there.
1210  //
1211  // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1212  // are done by the CreateImageFile() below.
1213
1214
1215  // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1216  // ImageWriter, if necessary.
1217  bool CreateOatFile() {
1218    CHECK(key_value_store_.get() != nullptr);
1219
1220    TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1221
1222    std::unique_ptr<OatWriter> oat_writer;
1223    {
1224      TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1225      std::string image_file_location;
1226      uint32_t image_file_location_oat_checksum = 0;
1227      uintptr_t image_file_location_oat_data_begin = 0;
1228      int32_t image_patch_delta = 0;
1229      if (image_) {
1230        PrepareImageWriter(image_base_);
1231      } else {
1232        TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1233        gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1234        image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1235        image_file_location_oat_data_begin =
1236            reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1237        image_file_location = image_space->GetImageFilename();
1238        image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1239      }
1240
1241      if (!image_file_location.empty()) {
1242        key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1243      }
1244
1245      oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1246                                     image_file_location_oat_data_begin,
1247                                     image_patch_delta,
1248                                     driver_.get(),
1249                                     image_writer_.get(),
1250                                     timings_,
1251                                     key_value_store_.get()));
1252    }
1253
1254    if (image_) {
1255      // The OatWriter constructor has already updated offsets in methods and we need to
1256      // prepare method offsets in the image address space for direct method patching.
1257      TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1258      if (!image_writer_->PrepareImageAddressSpace()) {
1259        LOG(ERROR) << "Failed to prepare image address space.";
1260        return false;
1261      }
1262    }
1263
1264    {
1265      TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1266      if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1267                             oat_file_.get())) {
1268        LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1269        return false;
1270      }
1271    }
1272
1273    // Flush result to disk.
1274    {
1275      TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1276      if (oat_file_->Flush() != 0) {
1277        LOG(ERROR) << "Failed to flush ELF file " << oat_file_->GetPath();
1278        return false;
1279      }
1280    }
1281
1282    VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1283    return true;
1284  }
1285
1286  // If we are compiling an image, invoke the image creation routine. Else just skip.
1287  bool HandleImage() {
1288    if (image_) {
1289      TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1290      if (!CreateImageFile()) {
1291        return false;
1292      }
1293      VLOG(compiler) << "Image written successfully: " << image_filename_;
1294    }
1295    return true;
1296  }
1297
1298  // Strip the oat file, if requested. This first creates a copy from unstripped to stripped, and
1299  // then runs the ElfStripper. Currently only relevant for the portable compiler.
1300  bool Strip() {
1301    // If we don't want to strip in place, copy from unstripped location to stripped location.
1302    // We need to strip after image creation because FixupElf needs to use .strtab.
1303    if (oat_unstripped_ != oat_stripped_) {
1304      TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1305      oat_file_.reset();
1306      std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1307      std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1308      size_t buffer_size = 8192;
1309      std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1310      while (true) {
1311        int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1312        if (bytes_read <= 0) {
1313          break;
1314        }
1315        bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1316        CHECK(write_ok);
1317      }
1318      oat_file_.reset(out.release());
1319      VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
1320    }
1321
1322    if (kUsePortableCompiler) {
1323      // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1324      // strip them now. Quick generates debug symbols only when the flag(s) are set.
1325      if (!compiler_options_->GetIncludeDebugSymbols()) {
1326        TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1327        // Strip unneeded sections for target
1328        off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1329        CHECK_EQ(0, seek_actual);
1330        std::string error_msg;
1331        if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1332          LOG(ERROR) << "Failed to strip elf file: " << error_msg;
1333          return false;
1334        }
1335
1336        // We wrote the oat file successfully, and want to keep it.
1337        VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1338      } else {
1339        VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1340      }
1341    }
1342
1343    return true;
1344  }
1345
1346  void DumpTiming() {
1347    if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1348      LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1349    }
1350    if (dump_passes_) {
1351      LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1352    }
1353  }
1354
1355  CompilerOptions* GetCompilerOptions() const {
1356    return compiler_options_.get();
1357  }
1358
1359  bool IsHost() const {
1360    return is_host_;
1361  }
1362
1363 private:
1364  static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1365                             const std::vector<const char*>& dex_locations,
1366                             std::vector<const DexFile*>& dex_files) {
1367    size_t failure_count = 0;
1368    for (size_t i = 0; i < dex_filenames.size(); i++) {
1369      const char* dex_filename = dex_filenames[i];
1370      const char* dex_location = dex_locations[i];
1371      ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1372      std::string error_msg;
1373      if (!OS::FileExists(dex_filename)) {
1374        LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1375        continue;
1376      }
1377      if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1378        LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1379        ++failure_count;
1380      }
1381      ATRACE_END();
1382    }
1383    return failure_count;
1384  }
1385
1386  // Returns true if dex_files has a dex with the named location.
1387  static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1388                               const std::string& location) {
1389    for (size_t i = 0; i < dex_files.size(); ++i) {
1390      if (dex_files[i]->GetLocation() == location) {
1391        return true;
1392      }
1393    }
1394    return false;
1395  }
1396
1397  // Appends to dex_files any elements of class_path that it doesn't already
1398  // contain. This will open those dex files as necessary.
1399  static void OpenClassPathFiles(const std::string& class_path,
1400                                 std::vector<const DexFile*>& dex_files) {
1401    std::vector<std::string> parsed;
1402    Split(class_path, ':', &parsed);
1403    // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1404    ScopedObjectAccess soa(Thread::Current());
1405    for (size_t i = 0; i < parsed.size(); ++i) {
1406      if (DexFilesContains(dex_files, parsed[i])) {
1407        continue;
1408      }
1409      std::string error_msg;
1410      if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1411        LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1412      }
1413    }
1414  }
1415
1416  // Create a runtime necessary for compilation.
1417  bool CreateRuntime(const RuntimeOptions& runtime_options)
1418      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1419    if (!Runtime::Create(runtime_options, false)) {
1420      LOG(ERROR) << "Failed to create runtime";
1421      return false;
1422    }
1423    Runtime* runtime = Runtime::Current();
1424    runtime->SetInstructionSet(instruction_set_);
1425    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1426      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1427      if (!runtime->HasCalleeSaveMethod(type)) {
1428        runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1429      }
1430    }
1431    runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1432    runtime->GetClassLinker()->RunRootClinits();
1433    runtime_ = runtime;
1434    return true;
1435  }
1436
1437  void PrepareImageWriter(uintptr_t image_base) {
1438    image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1439  }
1440
1441  // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1442  bool CreateImageFile()
1443      LOCKS_EXCLUDED(Locks::mutator_lock_) {
1444    CHECK(image_writer_ != nullptr);
1445    if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1446      LOG(ERROR) << "Failed to create image file " << image_filename_;
1447      return false;
1448    }
1449    uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1450
1451    // Destroy ImageWriter before doing FixupElf.
1452    image_writer_.reset();
1453
1454    std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1455    if (oat_file.get() == nullptr) {
1456      PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1457      return false;
1458    }
1459
1460    // Do not fix up the ELF file if we are --compile-pic
1461    if (!compiler_options_->GetCompilePic()) {
1462      if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
1463        LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1464        return false;
1465      }
1466    }
1467
1468    return true;
1469  }
1470
1471  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1472  static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1473    std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1474                                                                        std::ifstream::in));
1475    if (image_classes_file.get() == nullptr) {
1476      LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1477      return nullptr;
1478    }
1479    std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1480    image_classes_file->close();
1481    return result.release();
1482  }
1483
1484  static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1485    std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1486    while (image_classes_stream.good()) {
1487      std::string dot;
1488      std::getline(image_classes_stream, dot);
1489      if (StartsWith(dot, "#") || dot.empty()) {
1490        continue;
1491      }
1492      std::string descriptor(DotToDescriptor(dot.c_str()));
1493      image_classes->insert(descriptor);
1494    }
1495    return image_classes.release();
1496  }
1497
1498  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1499  static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1500                                                        const char* image_classes_filename,
1501                                                        std::string* error_msg) {
1502    std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1503    if (zip_archive.get() == nullptr) {
1504      return nullptr;
1505    }
1506    std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1507    if (zip_entry.get() == nullptr) {
1508      *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1509                                zip_filename, error_msg->c_str());
1510      return nullptr;
1511    }
1512    std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1513                                                                          image_classes_filename,
1514                                                                          error_msg));
1515    if (image_classes_file.get() == nullptr) {
1516      *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1517                                zip_filename, error_msg->c_str());
1518      return nullptr;
1519    }
1520    const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1521                                           image_classes_file->Size());
1522    std::istringstream image_classes_stream(image_classes_string);
1523    return ReadImageClasses(image_classes_stream);
1524  }
1525
1526  void LogCompletionTime() const {
1527    LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
1528              << " (threads: " << thread_count_ << ")";
1529  }
1530
1531  std::unique_ptr<CompilerOptions> compiler_options_;
1532  Compiler::Kind compiler_kind_;
1533
1534  InstructionSet instruction_set_;
1535  std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1536
1537  std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1538
1539  std::unique_ptr<VerificationResults> verification_results_;
1540  DexFileToMethodInlinerMap method_inliner_map_;
1541  std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1542
1543  // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1544  // in an orderly fashion. The destructor takes care of deleting this.
1545  Runtime* runtime_;
1546
1547  size_t thread_count_;
1548  uint64_t start_ns_;
1549  std::unique_ptr<WatchDog> watchdog_;
1550  std::unique_ptr<File> oat_file_;
1551  std::string oat_stripped_;
1552  std::string oat_unstripped_;
1553  std::string oat_location_;
1554  std::string oat_filename_;
1555  int oat_fd_;
1556  std::string bitcode_filename_;
1557  std::vector<const char*> dex_filenames_;
1558  std::vector<const char*> dex_locations_;
1559  int zip_fd_;
1560  std::string zip_location_;
1561  std::string boot_image_option_;
1562  std::vector<const char*> runtime_args_;
1563  std::string image_filename_;
1564  uintptr_t image_base_;
1565  const char* image_classes_zip_filename_;
1566  const char* image_classes_filename_;
1567  const char* compiled_classes_zip_filename_;
1568  const char* compiled_classes_filename_;
1569  std::unique_ptr<std::set<std::string>> image_classes_;
1570  std::unique_ptr<std::set<std::string>> compiled_classes_;
1571  bool image_;
1572  std::unique_ptr<ImageWriter> image_writer_;
1573  bool is_host_;
1574  std::string android_root_;
1575  std::vector<const DexFile*> dex_files_;
1576  std::unique_ptr<CompilerDriver> driver_;
1577  std::vector<std::string> verbose_methods_;
1578  bool dump_stats_;
1579  bool dump_passes_;
1580  bool dump_timing_;
1581  bool dump_slow_timing_;
1582  std::string profile_file_;  // Profile file to use
1583  TimingLogger* timings_;
1584  std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1585
1586  DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1587};
1588
1589const unsigned int WatchDog::kWatchDogWarningSeconds;
1590const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1591
1592static void b13564922() {
1593#if defined(__linux__) && defined(__arm__)
1594  int major, minor;
1595  struct utsname uts;
1596  if (uname(&uts) != -1 &&
1597      sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1598      ((major < 3) || ((major == 3) && (minor < 4)))) {
1599    // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1600    // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1601    int old_personality = personality(0xffffffff);
1602    if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1603      int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1604      if (new_personality == -1) {
1605        LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1606      }
1607    }
1608  }
1609#endif
1610}
1611
1612static int dex2oat(int argc, char** argv) {
1613  b13564922();
1614
1615  TimingLogger timings("compiler", false, false);
1616
1617  Dex2Oat dex2oat(&timings);
1618
1619  // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1620  dex2oat.ParseArgs(argc, argv);
1621
1622  // Check early that the result of compilation can be written
1623  if (!dex2oat.OpenFile()) {
1624    return EXIT_FAILURE;
1625  }
1626
1627  LOG(INFO) << CommandLine();
1628
1629  if (!dex2oat.Setup()) {
1630    return EXIT_FAILURE;
1631  }
1632
1633  dex2oat.Compile();
1634
1635  if (!dex2oat.CreateOatFile()) {
1636    return EXIT_FAILURE;
1637  }
1638
1639  if (!dex2oat.HandleImage()) {
1640    return EXIT_FAILURE;
1641  }
1642
1643  if (dex2oat.IsHost()) {
1644    dex2oat.DumpTiming();
1645    return EXIT_SUCCESS;
1646  }
1647
1648  if (!dex2oat.Strip()) {
1649    return EXIT_FAILURE;
1650  }
1651
1652  dex2oat.DumpTiming();
1653  return EXIT_SUCCESS;
1654}
1655}  // namespace art
1656
1657int main(int argc, char** argv) {
1658  int result = art::dex2oat(argc, argv);
1659  // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1660  // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1661  // should not destruct the runtime in this case.
1662  if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1663    exit(result);
1664  }
1665  return result;
1666}
1667