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