blob: 8b232700b080475d06777d54d46297ac70f3b858 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
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>
Ian Rogers2672a9f2013-09-05 17:24:22 -070020#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
28#include "base/stl_util.h"
29#include "base/stringpiece.h"
30#include "base/timing_logger.h"
31#include "base/unix_file/fd_file.h"
32#include "class_linker.h"
33#include "dex_file-inl.h"
34#include "driver/compiler_driver.h"
35#include "elf_fixup.h"
36#include "elf_stripper.h"
37#include "gc/space/image_space.h"
38#include "gc/space/space-inl.h"
39#include "image_writer.h"
40#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070041#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "mirror/class-inl.h"
43#include "mirror/class_loader.h"
44#include "mirror/object-inl.h"
45#include "mirror/object_array-inl.h"
46#include "oat_writer.h"
47#include "object_utils.h"
48#include "os.h"
49#include "runtime.h"
50#include "ScopedLocalRef.h"
51#include "scoped_thread_state_change.h"
52#include "sirt_ref.h"
53#include "vector_output_stream.h"
54#include "well_known_classes.h"
55#include "zip_archive.h"
56
57namespace art {
58
59static void UsageErrorV(const char* fmt, va_list ap) {
60 std::string error;
61 StringAppendV(&error, fmt, ap);
62 LOG(ERROR) << error;
63}
64
65static void UsageError(const char* fmt, ...) {
66 va_list ap;
67 va_start(ap, fmt);
68 UsageErrorV(fmt, ap);
69 va_end(ap);
70}
71
72static void Usage(const char* fmt, ...) {
73 va_list ap;
74 va_start(ap, fmt);
75 UsageErrorV(fmt, ap);
76 va_end(ap);
77
78 UsageError("Usage: dex2oat [options]...");
79 UsageError("");
80 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
81 UsageError(" Example: --dex-file=/system/framework/core.jar");
82 UsageError("");
83 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
84 UsageError(" containing a classes.dex file to compile.");
85 UsageError(" Example: --zip-fd=5");
86 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -070087 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
88 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -070089 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
90 UsageError("");
91 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
92 UsageError(" Example: --oat-file=/system/framework/boot.oat");
93 UsageError("");
94 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
95 UsageError(" Example: --oat-file=/system/framework/boot.oat");
96 UsageError("");
97 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
98 UsageError(" to the file descriptor specified by --oat-fd.");
99 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
100 UsageError("");
101 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
102 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
103 UsageError("");
104 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
105 UsageError(" Example: --bitcode=/system/framework/boot.bc");
106 UsageError("");
107 UsageError(" --image=<file.art>: specifies the output image filename.");
108 UsageError(" Example: --image=/system/framework/boot.art");
109 UsageError("");
110 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
111 UsageError(" Example: --image=frameworks/base/preloaded-classes");
112 UsageError("");
113 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
114 UsageError(" Example: --base=0x50000000");
115 UsageError("");
116 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
117 UsageError(" Example: --boot-image=/system/framework/boot.art");
118 UsageError(" Default: <host-prefix>/system/framework/boot.art");
119 UsageError("");
120 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
121 UsageError(" cross compilation.");
122 UsageError(" Example: --host-prefix=out/target/product/crespo");
123 UsageError(" Default: $ANDROID_PRODUCT_OUT");
124 UsageError("");
125 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
126 UsageError(" Example: --android-root=out/host/linux-x86");
127 UsageError(" Default: $ANDROID_ROOT");
128 UsageError("");
129 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
130 UsageError(" set.");
131 UsageError(" Example: --instruction-set=x86");
132 UsageError(" Default: arm");
133 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700134 UsageError(" --instruction-set-features=...,: Specify instruction set features");
135 UsageError(" Example: --instruction-set-features=div");
136 UsageError(" Default: default");
137 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700138 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
139 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700140 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700141 UsageError(" Default: Quick");
142 UsageError("");
143 UsageError(" --host: used with Portable backend to link against host runtime libraries");
144 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700145 UsageError(" --dump-timing: display a breakdown of where time was spent");
146 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
148 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
149 UsageError(" Use a separate --runtime-arg switch for each argument.");
150 UsageError(" Example: --runtime-arg -Xms256m");
151 UsageError("");
152 std::cerr << "See log for usage error information\n";
153 exit(EXIT_FAILURE);
154}
155
156class Dex2Oat {
157 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700158 static bool Create(Dex2Oat** p_dex2oat,
159 Runtime::Options& options,
160 CompilerBackend compiler_backend,
161 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700162 InstructionSetFeatures instruction_set_features,
Brian Carlstrom45602482013-07-21 22:07:55 -0700163 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
165 if (!CreateRuntime(options, instruction_set)) {
166 *p_dex2oat = NULL;
167 return false;
168 }
Dave Allison70202782013-10-22 17:52:19 -0700169 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set,
170 instruction_set_features, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 return true;
172 }
173
174 ~Dex2Oat() {
175 delete runtime_;
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700176 VLOG(compiler) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700177 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 }
179
180
Brian Carlstrom45602482013-07-21 22:07:55 -0700181 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700182 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Brian Carlstrom45602482013-07-21 22:07:55 -0700183 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
184 std::ifstream::in));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 if (image_classes_file.get() == NULL) {
186 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
187 return NULL;
188 }
189 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
190 image_classes_file->close();
191 return result.release();
192 }
193
194 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
195 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
196 while (image_classes_stream.good()) {
197 std::string dot;
198 std::getline(image_classes_stream, dot);
199 if (StartsWith(dot, "#") || dot.empty()) {
200 continue;
201 }
202 std::string descriptor(DotToDescriptor(dot.c_str()));
203 image_classes->insert(descriptor);
204 }
205 return image_classes.release();
206 }
207
Brian Carlstrom45602482013-07-21 22:07:55 -0700208 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700209 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const char* zip_filename,
210 const char* image_classes_filename,
211 std::string* error_msg) {
212 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 if (zip_archive.get() == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 return NULL;
215 }
216 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename));
217 if (zip_entry.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700218 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
219 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 return NULL;
221 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700222 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename,
223 error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 if (image_classes_file.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700225 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
226 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 return NULL;
228 }
229 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
230 image_classes_file->Size());
231 std::istringstream image_classes_stream(image_classes_string);
232 return ReadImageClasses(image_classes_stream);
233 }
234
235 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
236 const std::string* host_prefix,
237 const std::string& android_root,
238 bool is_host,
239 const std::vector<const DexFile*>& dex_files,
240 File* oat_file,
241 const std::string& bitcode_filename,
242 bool image,
243 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
244 bool dump_stats,
Ian Rogers5fe9af72013-11-14 00:17:20 -0800245 TimingLogger& timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 // SirtRef and ClassLoader creation needs to come after Runtime::Create
247 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700248 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700249 if (!boot_image_option.empty()) {
250 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
251 std::vector<const DexFile*> class_path_files(dex_files);
252 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700253 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 for (size_t i = 0; i < class_path_files.size(); i++) {
255 class_linker->RegisterDexFile(*class_path_files[i]);
256 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
258 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
259 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
260 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
261 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
262 }
263
264 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
265 instruction_set_,
Dave Allison70202782013-10-22 17:52:19 -0700266 instruction_set_features_,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700267 image,
268 image_classes.release(),
269 thread_count_,
Brian Carlstrom45602482013-07-21 22:07:55 -0700270 dump_stats));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271
272 if (compiler_backend_ == kPortable) {
273 driver->SetBitcodeFileName(bitcode_filename);
274 }
275
Brian Carlstrom45602482013-07-21 22:07:55 -0700276 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700278 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 std::string image_file_location;
280 uint32_t image_file_location_oat_checksum = 0;
281 uint32_t image_file_location_oat_data_begin = 0;
282 if (!driver->IsImage()) {
Ian Rogersca368cb2013-11-15 15:52:08 -0800283 TimingLogger::ScopedSplit split("Loading image checksum", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700284 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
285 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
286 image_file_location_oat_data_begin =
287 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
288 image_file_location = image_space->GetImageFilename();
289 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
290 image_file_location = image_file_location.substr(host_prefix->size());
291 }
292 }
293
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700294 OatWriter oat_writer(dex_files,
295 image_file_location_oat_checksum,
296 image_file_location_oat_data_begin,
297 image_file_location,
Ian Rogersca368cb2013-11-15 15:52:08 -0800298 driver.get(),
299 &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300
Ian Rogersca368cb2013-11-15 15:52:08 -0800301 TimingLogger::ScopedSplit split("Writing ELF", &timings);
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700302 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700303 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
304 return NULL;
305 }
306
307 return driver.release();
308 }
309
310 bool CreateImageFile(const std::string& image_filename,
311 uintptr_t image_base,
312 const std::string& oat_filename,
313 const std::string& oat_location,
314 const CompilerDriver& compiler)
315 LOCKS_EXCLUDED(Locks::mutator_lock_) {
316 uintptr_t oat_data_begin;
317 {
318 // ImageWriter is scoped so it can free memory before doing FixupElf
319 ImageWriter image_writer(compiler);
320 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
321 LOG(ERROR) << "Failed to create image file " << image_filename;
322 return false;
323 }
324 oat_data_begin = image_writer.GetOatDataBegin();
325 }
326
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700327 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328 if (oat_file.get() == NULL) {
329 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
330 return false;
331 }
332 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
333 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
334 return false;
335 }
336 return true;
337 }
338
339 private:
Brian Carlstrom45602482013-07-21 22:07:55 -0700340 explicit Dex2Oat(Runtime* runtime,
341 CompilerBackend compiler_backend,
342 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700343 InstructionSetFeatures instruction_set_features,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700344 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 : compiler_backend_(compiler_backend),
346 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700347 instruction_set_features_(instruction_set_features),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348 runtime_(runtime),
349 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700350 start_ns_(NanoTime()) {
351 }
352
353 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
354 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
355 if (!Runtime::Create(options, false)) {
356 LOG(ERROR) << "Failed to create runtime";
357 return false;
358 }
359 Runtime* runtime = Runtime::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
361 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
362 if (!runtime->HasCalleeSaveMethod(type)) {
363 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
364 }
365 }
366 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
367 return true;
368 }
369
370 // Appends to dex_files any elements of class_path that it doesn't already
371 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700372 static void OpenClassPathFiles(const std::string& class_path,
373 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700374 std::vector<std::string> parsed;
375 Split(class_path, ':', parsed);
376 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
377 ScopedObjectAccess soa(Thread::Current());
378 for (size_t i = 0; i < parsed.size(); ++i) {
379 if (DexFilesContains(dex_files, parsed[i])) {
380 continue;
381 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700382 std::string error_msg;
383 const DexFile* dex_file = DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700384 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700385 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386 } else {
387 dex_files.push_back(dex_file);
388 }
389 }
390 }
391
392 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700393 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
394 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700395 for (size_t i = 0; i < dex_files.size(); ++i) {
396 if (dex_files[i]->GetLocation() == location) {
397 return true;
398 }
399 }
400 return false;
401 }
402
403 const CompilerBackend compiler_backend_;
404
405 const InstructionSet instruction_set_;
Dave Allison70202782013-10-22 17:52:19 -0700406 const InstructionSetFeatures instruction_set_features_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407
408 Runtime* runtime_;
409 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410 uint64_t start_ns_;
411
412 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
413};
414
415static bool ParseInt(const char* in, int* out) {
416 char* end;
417 int result = strtol(in, &end, 10);
418 if (in == end || *end != '\0') {
419 return false;
420 }
421 *out = result;
422 return true;
423}
424
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800425static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
426 const std::vector<const char*>& dex_locations,
427 std::vector<const DexFile*>& dex_files) {
428 size_t failure_count = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700429 for (size_t i = 0; i < dex_filenames.size(); i++) {
430 const char* dex_filename = dex_filenames[i];
431 const char* dex_location = dex_locations[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432 std::string error_msg;
Brian Carlstromd5aba592013-11-12 01:52:44 -0800433 if (!OS::FileExists(dex_filename)) {
434 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
435 continue;
436 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700437 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800440 ++failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700441 } else {
442 dex_files.push_back(dex_file);
443 }
444 }
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800445 return failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446}
447
448// The primary goal of the watchdog is to prevent stuck build servers
449// during development when fatal aborts lead to a cascade of failures
450// that result in a deadlock.
451class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700452// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
453#undef CHECK_PTHREAD_CALL
454#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
455 do { \
456 int rc = call args; \
457 if (rc != 0) { \
458 errno = rc; \
459 std::string message(# call); \
460 message += " failed for "; \
461 message += reason; \
462 Fatal(message); \
463 } \
464 } while (false)
465
466 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700467 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700468 is_watch_dog_enabled_ = is_watch_dog_enabled;
469 if (!is_watch_dog_enabled_) {
470 return;
471 }
472 shutting_down_ = false;
473 const char* reason = "dex2oat watch dog thread startup";
474 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
475 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
476 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
478 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
479 }
480 ~WatchDog() {
481 if (!is_watch_dog_enabled_) {
482 return;
483 }
484 const char* reason = "dex2oat watch dog thread shutdown";
485 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
486 shutting_down_ = true;
487 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
488 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
489
490 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
491
492 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
493 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
494 }
495
496 private:
497 static void* CallBack(void* arg) {
498 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
499 ::art::SetThreadName("dex2oat watch dog");
500 self->Wait();
501 return NULL;
502 }
503
504 static void Message(char severity, const std::string& message) {
505 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
506 // cases.
507 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
508 kIsDebugBuild ? "d" : "",
509 severity,
510 getpid(),
511 GetTid(),
512 message.c_str());
513 }
514
515 static void Warn(const std::string& message) {
516 Message('W', message);
517 }
518
519 static void Fatal(const std::string& message) {
520 Message('F', message);
521 exit(1);
522 }
523
524 void Wait() {
525 bool warning = true;
526 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
527 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
528 // large.
529 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
530 timespec warning_ts;
531 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
532 timespec timeout_ts;
533 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
534 const char* reason = "dex2oat watch dog thread waiting";
535 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
536 while (!shutting_down_) {
537 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
538 warning ? &warning_ts
539 : &timeout_ts));
540 if (rc == ETIMEDOUT) {
541 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
542 warning ? kWatchDogWarningSeconds
543 : kWatchDogTimeoutSeconds));
544 if (warning) {
545 Warn(message.c_str());
546 warning = false;
547 } else {
548 Fatal(message.c_str());
549 }
550 } else if (rc != 0) {
551 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
552 strerror(errno)));
553 Fatal(message.c_str());
554 }
555 }
556 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
557 }
558
559 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
560#if ART_USE_PORTABLE_COMPILER
561 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
562 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
563#else
564 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
565 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
566#endif
567
568 bool is_watch_dog_enabled_;
569 bool shutting_down_;
570 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
571 pthread_mutex_t mutex_;
572 pthread_cond_t cond_;
573 pthread_attr_t attr_;
574 pthread_t pthread_;
575};
576const unsigned int WatchDog::kWatchDogWarningSeconds;
577const unsigned int WatchDog::kWatchDogTimeoutSeconds;
578
Dave Allison70202782013-10-22 17:52:19 -0700579// Given a set of instruction features from the build, parse it. The
580// input 'str' is a comma separated list of feature names. Parse it and
581// return the InstructionSetFeatures object.
582static InstructionSetFeatures ParseFeatureList(std::string str) {
583 InstructionSetFeatures result;
584 typedef std::vector<std::string> FeatureList;
585 FeatureList features;
586 Split(str, ',', features);
587 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
588 std::string feature = Trim(*i);
589 if (feature == "default") {
590 // Nothing to do.
591 } else if (feature == "div") {
592 // Supports divide instruction.
593 result.SetHasDivideInstruction(true);
594 } else if (feature == "nodiv") {
595 // Turn off support for divide instruction.
596 result.SetHasDivideInstruction(false);
597 } else {
598 Usage("Unknown instruction set feature: '%s'", feature.c_str());
599 }
600 }
601 // others...
602 return result;
603}
604
Brian Carlstrom7940e442013-07-12 13:46:57 -0700605static int dex2oat(int argc, char** argv) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800606 TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700607
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608 InitLogging(argv);
609
610 // Skip over argv[0].
611 argv++;
612 argc--;
613
614 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700615 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700616 }
617
618 std::vector<const char*> dex_filenames;
619 std::vector<const char*> dex_locations;
620 int zip_fd = -1;
621 std::string zip_location;
622 std::string oat_filename;
623 std::string oat_symbols;
624 std::string oat_location;
625 int oat_fd = -1;
626 std::string bitcode_filename;
627 const char* image_classes_zip_filename = NULL;
628 const char* image_classes_filename = NULL;
629 std::string image_filename;
630 std::string boot_image_filename;
631 uintptr_t image_base = 0;
632 UniquePtr<std::string> host_prefix;
633 std::string android_root;
634 std::vector<const char*> runtime_args;
635 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636#if defined(ART_USE_PORTABLE_COMPILER)
637 CompilerBackend compiler_backend = kPortable;
638#else
639 CompilerBackend compiler_backend = kQuick;
640#endif
Dave Allison70202782013-10-22 17:52:19 -0700641
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800642 // Take the default set of instruction features from the build.
Dave Allison70202782013-10-22 17:52:19 -0700643 InstructionSetFeatures instruction_set_features =
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800644 ParseFeatureList(STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES));
Dave Allison70202782013-10-22 17:52:19 -0700645
Brian Carlstrom7940e442013-07-12 13:46:57 -0700646#if defined(__arm__)
647 InstructionSet instruction_set = kThumb2;
648#elif defined(__i386__)
649 InstructionSet instruction_set = kX86;
650#elif defined(__mips__)
651 InstructionSet instruction_set = kMips;
652#else
653#error "Unsupported architecture"
654#endif
Dave Allison70202782013-10-22 17:52:19 -0700655
656
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700658 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700659 bool dump_timing = false;
660 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700661 bool watch_dog_enabled = !kIsTargetBuild;
662
663
664 for (int i = 0; i < argc; i++) {
665 const StringPiece option(argv[i]);
666 bool log_options = false;
667 if (log_options) {
668 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
669 }
670 if (option.starts_with("--dex-file=")) {
671 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
672 } else if (option.starts_with("--dex-location=")) {
673 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
674 } else if (option.starts_with("--zip-fd=")) {
675 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
676 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700677 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700678 }
679 } else if (option.starts_with("--zip-location=")) {
680 zip_location = option.substr(strlen("--zip-location=")).data();
681 } else if (option.starts_with("--oat-file=")) {
682 oat_filename = option.substr(strlen("--oat-file=")).data();
683 } else if (option.starts_with("--oat-symbols=")) {
684 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
685 } else if (option.starts_with("--oat-fd=")) {
686 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
687 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700688 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700690 } else if (option == "--watch-dog") {
691 watch_dog_enabled = true;
692 } else if (option == "--no-watch-dog") {
693 watch_dog_enabled = false;
694 } else if (option.starts_with("-j")) {
695 const char* thread_count_str = option.substr(strlen("-j")).data();
696 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700697 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 }
699 } else if (option.starts_with("--oat-location=")) {
700 oat_location = option.substr(strlen("--oat-location=")).data();
701 } else if (option.starts_with("--bitcode=")) {
702 bitcode_filename = option.substr(strlen("--bitcode=")).data();
703 } else if (option.starts_with("--image=")) {
704 image_filename = option.substr(strlen("--image=")).data();
705 } else if (option.starts_with("--image-classes=")) {
706 image_classes_filename = option.substr(strlen("--image-classes=")).data();
707 } else if (option.starts_with("--image-classes-zip=")) {
708 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
709 } else if (option.starts_with("--base=")) {
710 const char* image_base_str = option.substr(strlen("--base=")).data();
711 char* end;
712 image_base = strtoul(image_base_str, &end, 16);
713 if (end == image_base_str || *end != '\0') {
714 Usage("Failed to parse hexadecimal value for option %s", option.data());
715 }
716 } else if (option.starts_with("--boot-image=")) {
717 boot_image_filename = option.substr(strlen("--boot-image=")).data();
718 } else if (option.starts_with("--host-prefix=")) {
719 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
720 } else if (option.starts_with("--android-root=")) {
721 android_root = option.substr(strlen("--android-root=")).data();
722 } else if (option.starts_with("--instruction-set=")) {
723 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
724 if (instruction_set_str == "arm") {
725 instruction_set = kThumb2;
726 } else if (instruction_set_str == "mips") {
727 instruction_set = kMips;
728 } else if (instruction_set_str == "x86") {
729 instruction_set = kX86;
730 }
Dave Allison70202782013-10-22 17:52:19 -0700731 } else if (option.starts_with("--instruction-set-features=")) {
732 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
733 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734 } else if (option.starts_with("--compiler-backend=")) {
735 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
736 if (backend_str == "Quick") {
737 compiler_backend = kQuick;
738 } else if (backend_str == "Portable") {
739 compiler_backend = kPortable;
740 }
741 } else if (option == "--host") {
742 is_host = true;
743 } else if (option == "--runtime-arg") {
744 if (++i >= argc) {
745 Usage("Missing required argument for --runtime-arg");
746 }
747 if (log_options) {
748 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
749 }
750 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700751 } else if (option == "--dump-timing") {
752 dump_timing = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700753 } else if (option == "--dump-stats") {
754 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700755 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700756 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 }
758 }
759
760 if (oat_filename.empty() && oat_fd == -1) {
761 Usage("Output must be supplied with either --oat-file or --oat-fd");
762 }
763
764 if (!oat_filename.empty() && oat_fd != -1) {
765 Usage("--oat-file should not be used with --oat-fd");
766 }
767
768 if (!oat_symbols.empty() && oat_fd != -1) {
769 Usage("--oat-symbols should not be used with --oat-fd");
770 }
771
772 if (!oat_symbols.empty() && is_host) {
773 Usage("--oat-symbols should not be used with --host");
774 }
775
776 if (oat_fd != -1 && !image_filename.empty()) {
777 Usage("--oat-fd should not be used with --image");
778 }
779
780 if (host_prefix.get() == NULL) {
781 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
782 if (android_product_out != NULL) {
783 host_prefix.reset(new std::string(android_product_out));
784 }
785 }
786
787 if (android_root.empty()) {
788 const char* android_root_env_var = getenv("ANDROID_ROOT");
789 if (android_root_env_var == NULL) {
790 Usage("--android-root unspecified and ANDROID_ROOT not set");
791 }
792 android_root += android_root_env_var;
793 }
794
795 bool image = (!image_filename.empty());
796 if (!image && boot_image_filename.empty()) {
797 if (host_prefix.get() == NULL) {
798 boot_image_filename += GetAndroidRoot();
799 } else {
800 boot_image_filename += *host_prefix.get();
801 boot_image_filename += "/system";
802 }
803 boot_image_filename += "/framework/boot.art";
804 }
805 std::string boot_image_option;
806 if (!boot_image_filename.empty()) {
807 boot_image_option += "-Ximage:";
808 boot_image_option += boot_image_filename;
809 }
810
811 if (image_classes_filename != NULL && !image) {
812 Usage("--image-classes should only be used with --image");
813 }
814
815 if (image_classes_filename != NULL && !boot_image_option.empty()) {
816 Usage("--image-classes should not be used with --boot-image");
817 }
818
819 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
820 Usage("--image-classes-zip should be used with --image-classes");
821 }
822
823 if (dex_filenames.empty() && zip_fd == -1) {
824 Usage("Input must be supplied with either --dex-file or --zip-fd");
825 }
826
827 if (!dex_filenames.empty() && zip_fd != -1) {
828 Usage("--dex-file should not be used with --zip-fd");
829 }
830
831 if (!dex_filenames.empty() && !zip_location.empty()) {
832 Usage("--dex-file should not be used with --zip-location");
833 }
834
835 if (dex_locations.empty()) {
836 for (size_t i = 0; i < dex_filenames.size(); i++) {
837 dex_locations.push_back(dex_filenames[i]);
838 }
839 } else if (dex_locations.size() != dex_filenames.size()) {
840 Usage("--dex-location arguments do not match --dex-file arguments");
841 }
842
843 if (zip_fd != -1 && zip_location.empty()) {
844 Usage("--zip-location should be supplied with --zip-fd");
845 }
846
847 if (boot_image_option.empty()) {
848 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700849 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700850 }
851 }
852
853 std::string oat_stripped(oat_filename);
854 std::string oat_unstripped;
855 if (!oat_symbols.empty()) {
856 oat_unstripped += oat_symbols;
857 } else {
858 oat_unstripped += oat_filename;
859 }
860
861 // Done with usage checks, enable watchdog if requested
862 WatchDog watch_dog(watch_dog_enabled);
863
864 // Check early that the result of compilation can be written
865 UniquePtr<File> oat_file;
866 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
867 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700868 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700869 if (oat_location.empty()) {
870 oat_location = oat_filename;
871 }
872 } else {
873 oat_file.reset(new File(oat_fd, oat_location));
874 oat_file->DisableAutoClose();
875 }
876 if (oat_file.get() == NULL) {
877 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
878 return EXIT_FAILURE;
879 }
880 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
881 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
882 return EXIT_FAILURE;
883 }
884
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700885 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700886 LOG(INFO) << "dex2oat: " << oat_location;
887
Ian Rogersf30f6da2013-08-28 17:33:30 -0700888 if (image) {
889 bool has_compiler_filter = false;
890 for (const char* r : runtime_args) {
891 if (strncmp(r, "-compiler-filter:", 17) == 0) {
892 has_compiler_filter = true;
893 break;
894 }
895 }
896 if (!has_compiler_filter) {
897 runtime_args.push_back("-compiler-filter:everything");
898 }
899 }
900
Brian Carlstrom7940e442013-07-12 13:46:57 -0700901 Runtime::Options options;
902 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
903 std::vector<const DexFile*> boot_class_path;
904 if (boot_image_option.empty()) {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800905 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
906 if (failure_count > 0) {
907 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
908 return EXIT_FAILURE;
909 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700910 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
911 } else {
912 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
913 }
914 if (host_prefix.get() != NULL) {
915 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
916 }
917 for (size_t i = 0; i < runtime_args.size(); i++) {
918 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
919 }
920
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921#ifdef ART_SEA_IR_MODE
922 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
923#endif
924
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 Dex2Oat* p_dex2oat;
Dave Allison70202782013-10-22 17:52:19 -0700926 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set,
927 instruction_set_features, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 LOG(ERROR) << "Failed to create dex2oat";
929 return EXIT_FAILURE;
930 }
931 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
932 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700933 // give it away now so that we don't starve GC.
934 Thread* self = Thread::Current();
935 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700936 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700937 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
938 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700939 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700940 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941
942 // If --image-classes was specified, calculate the full list of classes to include in the image
943 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
944 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700945 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700946 if (image_classes_zip_filename != NULL) {
947 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700948 image_classes_filename,
949 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700950 } else {
951 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
952 }
953 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700954 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
955 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700956 return EXIT_FAILURE;
957 }
958 }
959
960 std::vector<const DexFile*> dex_files;
961 if (boot_image_option.empty()) {
962 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
963 } else {
964 if (dex_filenames.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700965 std::string error_msg;
966 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
967 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700969 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
970 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971 return EXIT_FAILURE;
972 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700973 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700975 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
976 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700977 return EXIT_FAILURE;
978 }
979 dex_files.push_back(dex_file);
980 } else {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800981 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
982 if (failure_count > 0) {
983 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
984 return EXIT_FAILURE;
985 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700986 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700987
988 // Ensure opened dex files are writable for dex-to-dex transformations.
989 for (const auto& dex_file : dex_files) {
990 if (!dex_file->EnableWrite()) {
991 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
992 }
993 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994 }
995
buzbeea024a062013-07-31 10:47:37 -0700996 /*
997 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
998 * bother to check if we're doing the image.
999 */
1000 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001 size_t num_methods = 0;
1002 for (size_t i = 0; i != dex_files.size(); ++i) {
1003 const DexFile* dex_file = dex_files[i];
1004 CHECK(dex_file != NULL);
1005 num_methods += dex_file->NumMethodIds();
1006 }
buzbeea024a062013-07-31 10:47:37 -07001007 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
1008 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001009 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001010 }
1011 }
1012
1013 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
1014 host_prefix.get(),
1015 android_root,
1016 is_host,
1017 dex_files,
1018 oat_file.get(),
1019 bitcode_filename,
1020 image,
1021 image_classes,
1022 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -07001023 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024
1025 if (compiler.get() == NULL) {
1026 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1027 return EXIT_FAILURE;
1028 }
1029
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001030 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001031
1032 // Notes on the interleaving of creating the image and oat file to
1033 // ensure the references between the two are correct.
1034 //
1035 // Currently we have a memory layout that looks something like this:
1036 //
1037 // +--------------+
1038 // | image |
1039 // +--------------+
1040 // | boot oat |
1041 // +--------------+
1042 // | alloc spaces |
1043 // +--------------+
1044 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001045 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046 //
1047 // 1. The image is expected to be loaded at an absolute address and
1048 // contains Objects with absolute pointers within the image.
1049 //
1050 // 2. There are absolute pointers from Methods in the image to their
1051 // code in the oat.
1052 //
1053 // 3. There are absolute pointers from the code in the oat to Methods
1054 // in the image.
1055 //
1056 // 4. There are absolute pointers from code in the oat to other code
1057 // in the oat.
1058 //
1059 // To get this all correct, we go through several steps.
1060 //
1061 // 1. We have already created that oat file above with
1062 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001063 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001064 // file). The Compiler returned by CreateOatFile provides
1065 // PatchInformation for references to oat code and Methods that need
1066 // to be update once we know where the oat file will be located
1067 // after the image.
1068 //
1069 // 2. We create the image file. It needs to know where the oat file
1070 // will be loaded after itself. Originally when oat file was simply
1071 // memory mapped so we could predict where its contents were based
1072 // on the file size. Now that it is an ELF file, we need to inspect
1073 // the ELF file to understand the in memory segment layout including
1074 // where the oat header is located within. ImageWriter's
1075 // PatchOatCodeAndMethods uses the PatchInformation from the
1076 // Compiler to touch up absolute references in the oat file.
1077 //
1078 // 3. We fixup the ELF program headers so that dlopen will try to
1079 // load the .so at the desired location at runtime by offsetting the
1080 // Elf32_Phdr.p_vaddr values by the desired base address.
1081 //
1082 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001083 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001084 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1085 image_base,
1086 oat_unstripped,
1087 oat_location,
1088 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089 if (!image_creation_success) {
1090 return EXIT_FAILURE;
1091 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001092 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001093 }
1094
1095 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001096 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001097 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001098 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099 return EXIT_SUCCESS;
1100 }
1101
1102 // If we don't want to strip in place, copy from unstripped location to stripped location.
1103 // We need to strip after image creation because FixupElf needs to use .strtab.
1104 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001105 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001106 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001107 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1108 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109 size_t buffer_size = 8192;
1110 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1111 while (true) {
1112 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1113 if (bytes_read <= 0) {
1114 break;
1115 }
1116 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1117 CHECK(write_ok);
1118 }
1119 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001120 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001121 }
1122
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001123#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001124 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001125 // Strip unneeded sections for target
1126 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1127 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001128 std::string error_msg;
1129 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001130
Brian Carlstrom7940e442013-07-12 13:46:57 -07001131
1132 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001133 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001134#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001135
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001136 timings.EndSplit();
1137
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001138 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001139 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001140 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001141
1142 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1143 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1144 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
1145 exit(EXIT_SUCCESS);
1146 }
1147
Brian Carlstrom7940e442013-07-12 13:46:57 -07001148 return EXIT_SUCCESS;
1149}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001150} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001151
1152int main(int argc, char** argv) {
1153 return art::dex2oat(argc, argv);
1154}