blob: b37cc544396f1c73de2a34db99d72e0d1adae2c4 [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"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000033#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070034#include "dex_file-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000035#include "dex/verified_methods_data.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "driver/compiler_driver.h"
37#include "elf_fixup.h"
38#include "elf_stripper.h"
39#include "gc/space/image_space.h"
40#include "gc/space/space-inl.h"
41#include "image_writer.h"
42#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070043#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "mirror/class-inl.h"
45#include "mirror/class_loader.h"
46#include "mirror/object-inl.h"
47#include "mirror/object_array-inl.h"
48#include "oat_writer.h"
49#include "object_utils.h"
50#include "os.h"
51#include "runtime.h"
52#include "ScopedLocalRef.h"
53#include "scoped_thread_state_change.h"
54#include "sirt_ref.h"
55#include "vector_output_stream.h"
56#include "well_known_classes.h"
57#include "zip_archive.h"
58
59namespace art {
60
61static void UsageErrorV(const char* fmt, va_list ap) {
62 std::string error;
63 StringAppendV(&error, fmt, ap);
64 LOG(ERROR) << error;
65}
66
67static void UsageError(const char* fmt, ...) {
68 va_list ap;
69 va_start(ap, fmt);
70 UsageErrorV(fmt, ap);
71 va_end(ap);
72}
73
74static void Usage(const char* fmt, ...) {
75 va_list ap;
76 va_start(ap, fmt);
77 UsageErrorV(fmt, ap);
78 va_end(ap);
79
80 UsageError("Usage: dex2oat [options]...");
81 UsageError("");
82 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
83 UsageError(" Example: --dex-file=/system/framework/core.jar");
84 UsageError("");
85 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
86 UsageError(" containing a classes.dex file to compile.");
87 UsageError(" Example: --zip-fd=5");
88 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -070089 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
90 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -070091 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
92 UsageError("");
93 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
94 UsageError(" Example: --oat-file=/system/framework/boot.oat");
95 UsageError("");
96 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
97 UsageError(" Example: --oat-file=/system/framework/boot.oat");
98 UsageError("");
99 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
100 UsageError(" to the file descriptor specified by --oat-fd.");
101 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
102 UsageError("");
103 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
104 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
105 UsageError("");
106 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
107 UsageError(" Example: --bitcode=/system/framework/boot.bc");
108 UsageError("");
109 UsageError(" --image=<file.art>: specifies the output image filename.");
110 UsageError(" Example: --image=/system/framework/boot.art");
111 UsageError("");
112 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
113 UsageError(" Example: --image=frameworks/base/preloaded-classes");
114 UsageError("");
115 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
116 UsageError(" Example: --base=0x50000000");
117 UsageError("");
118 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
119 UsageError(" Example: --boot-image=/system/framework/boot.art");
120 UsageError(" Default: <host-prefix>/system/framework/boot.art");
121 UsageError("");
122 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
123 UsageError(" cross compilation.");
124 UsageError(" Example: --host-prefix=out/target/product/crespo");
125 UsageError(" Default: $ANDROID_PRODUCT_OUT");
126 UsageError("");
127 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
128 UsageError(" Example: --android-root=out/host/linux-x86");
129 UsageError(" Default: $ANDROID_ROOT");
130 UsageError("");
131 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
132 UsageError(" set.");
133 UsageError(" Example: --instruction-set=x86");
134 UsageError(" Default: arm");
135 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700136 UsageError(" --instruction-set-features=...,: Specify instruction set features");
137 UsageError(" Example: --instruction-set-features=div");
138 UsageError(" Default: default");
139 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700140 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
141 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700142 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700143 UsageError(" Default: Quick");
144 UsageError("");
145 UsageError(" --host: used with Portable backend to link against host runtime libraries");
146 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700147 UsageError(" --dump-timing: display a breakdown of where time was spent");
148 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
150 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
151 UsageError(" Use a separate --runtime-arg switch for each argument.");
152 UsageError(" Example: --runtime-arg -Xms256m");
153 UsageError("");
154 std::cerr << "See log for usage error information\n";
155 exit(EXIT_FAILURE);
156}
157
158class Dex2Oat {
159 public:
Brian Carlstrom45602482013-07-21 22:07:55 -0700160 static bool Create(Dex2Oat** p_dex2oat,
161 Runtime::Options& options,
162 CompilerBackend compiler_backend,
163 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700164 InstructionSetFeatures instruction_set_features,
Brian Carlstrom45602482013-07-21 22:07:55 -0700165 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000167 UniquePtr<Dex2Oat> dex2oat(new Dex2Oat(compiler_backend, instruction_set,
168 instruction_set_features, thread_count));
169 if (!dex2oat->CreateRuntime(options, instruction_set)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 *p_dex2oat = NULL;
171 return false;
172 }
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000173 *p_dex2oat = dex2oat.release();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 return true;
175 }
176
177 ~Dex2Oat() {
178 delete runtime_;
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700179 VLOG(compiler) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Brian Carlstrom45602482013-07-21 22:07:55 -0700180 << " (threads: " << thread_count_ << ")";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 }
182
183
Brian Carlstrom45602482013-07-21 22:07:55 -0700184 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) {
Brian Carlstrom45602482013-07-21 22:07:55 -0700186 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
187 std::ifstream::in));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 if (image_classes_file.get() == NULL) {
189 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
190 return NULL;
191 }
192 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get()));
193 image_classes_file->close();
194 return result.release();
195 }
196
197 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) {
198 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
199 while (image_classes_stream.good()) {
200 std::string dot;
201 std::getline(image_classes_stream, dot);
202 if (StartsWith(dot, "#") || dot.empty()) {
203 continue;
204 }
205 std::string descriptor(DotToDescriptor(dot.c_str()));
206 image_classes->insert(descriptor);
207 }
208 return image_classes.release();
209 }
210
Brian Carlstrom45602482013-07-21 22:07:55 -0700211 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700212 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const char* zip_filename,
213 const char* image_classes_filename,
214 std::string* error_msg) {
215 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 if (zip_archive.get() == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 return NULL;
218 }
Narayan Kamath92572be2013-11-28 14:06:24 +0000219 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 if (zip_entry.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700221 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
222 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700223 return NULL;
224 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700225 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename,
226 error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 if (image_classes_file.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700228 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
229 zip_filename, error_msg->c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 return NULL;
231 }
232 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
233 image_classes_file->Size());
234 std::istringstream image_classes_stream(image_classes_string);
235 return ReadImageClasses(image_classes_stream);
236 }
237
238 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
239 const std::string* host_prefix,
240 const std::string& android_root,
241 bool is_host,
242 const std::vector<const DexFile*>& dex_files,
243 File* oat_file,
244 const std::string& bitcode_filename,
245 bool image,
246 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
247 bool dump_stats,
Ian Rogers5fe9af72013-11-14 00:17:20 -0800248 TimingLogger& timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700249 // SirtRef and ClassLoader creation needs to come after Runtime::Create
250 jobject class_loader = NULL;
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700251 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252 if (!boot_image_option.empty()) {
253 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
254 std::vector<const DexFile*> class_path_files(dex_files);
255 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700256 ScopedObjectAccess soa(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 for (size_t i = 0; i < class_path_files.size(); i++) {
258 class_linker->RegisterDexFile(*class_path_files[i]);
259 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
261 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
262 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
263 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
264 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
265 }
266
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000267 UniquePtr<CompilerDriver> driver(new CompilerDriver(verified_methods_data_.get(),
268 compiler_backend_,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700269 instruction_set_,
Dave Allison70202782013-10-22 17:52:19 -0700270 instruction_set_features_,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271 image,
272 image_classes.release(),
273 thread_count_,
Brian Carlstrom45602482013-07-21 22:07:55 -0700274 dump_stats));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700275
276 if (compiler_backend_ == kPortable) {
277 driver->SetBitcodeFileName(bitcode_filename);
278 }
279
Brian Carlstrom45602482013-07-21 22:07:55 -0700280 driver->CompileAll(class_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700281
Anwar Ghuloum6f28d912013-07-24 15:02:53 -0700282 timings.NewSplit("dex2oat OatWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700283 std::string image_file_location;
284 uint32_t image_file_location_oat_checksum = 0;
285 uint32_t image_file_location_oat_data_begin = 0;
286 if (!driver->IsImage()) {
Ian Rogersca368cb2013-11-15 15:52:08 -0800287 TimingLogger::ScopedSplit split("Loading image checksum", &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700288 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
289 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
290 image_file_location_oat_data_begin =
291 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
292 image_file_location = image_space->GetImageFilename();
293 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
294 image_file_location = image_file_location.substr(host_prefix->size());
295 }
296 }
297
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700298 OatWriter oat_writer(dex_files,
299 image_file_location_oat_checksum,
300 image_file_location_oat_data_begin,
301 image_file_location,
Ian Rogersca368cb2013-11-15 15:52:08 -0800302 driver.get(),
303 &timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700304
Ian Rogersca368cb2013-11-15 15:52:08 -0800305 TimingLogger::ScopedSplit split("Writing ELF", &timings);
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700306 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700307 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
308 return NULL;
309 }
310
311 return driver.release();
312 }
313
314 bool CreateImageFile(const std::string& image_filename,
315 uintptr_t image_base,
316 const std::string& oat_filename,
317 const std::string& oat_location,
318 const CompilerDriver& compiler)
319 LOCKS_EXCLUDED(Locks::mutator_lock_) {
320 uintptr_t oat_data_begin;
321 {
322 // ImageWriter is scoped so it can free memory before doing FixupElf
323 ImageWriter image_writer(compiler);
324 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
325 LOG(ERROR) << "Failed to create image file " << image_filename;
326 return false;
327 }
328 oat_data_begin = image_writer.GetOatDataBegin();
329 }
330
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700331 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700332 if (oat_file.get() == NULL) {
333 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
334 return false;
335 }
336 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
337 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
338 return false;
339 }
340 return true;
341 }
342
343 private:
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000344 class Dex2OatCompilerCallbacks : public CompilerCallbacks {
345 public:
346 explicit Dex2OatCompilerCallbacks(VerifiedMethodsData* verified_methods_data)
347 : verified_methods_data_(verified_methods_data) { }
348 virtual ~Dex2OatCompilerCallbacks() { }
349
350 virtual bool MethodVerified(verifier::MethodVerifier* verifier)
351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
352 return verified_methods_data_->ProcessVerifiedMethod(verifier);
353 }
354 virtual void ClassRejected(ClassReference ref) {
355 verified_methods_data_->AddRejectedClass(ref);
356 }
357
358 private:
359 VerifiedMethodsData* verified_methods_data_;
360 };
361
362 explicit Dex2Oat(CompilerBackend compiler_backend,
Brian Carlstrom45602482013-07-21 22:07:55 -0700363 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700364 InstructionSetFeatures instruction_set_features,
Brian Carlstrom0177fe22013-07-21 12:21:36 -0700365 size_t thread_count)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366 : compiler_backend_(compiler_backend),
367 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700368 instruction_set_features_(instruction_set_features),
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000369 verified_methods_data_(new VerifiedMethodsData),
370 callbacks_(verified_methods_data_.get()),
371 runtime_(nullptr),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700372 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373 start_ns_(NanoTime()) {
374 }
375
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000376 bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000378 options.push_back(
379 std::make_pair("compilercallbacks", static_cast<CompilerCallbacks*>(&callbacks_)));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380 if (!Runtime::Create(options, false)) {
381 LOG(ERROR) << "Failed to create runtime";
382 return false;
383 }
384 Runtime* runtime = Runtime::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
386 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
387 if (!runtime->HasCalleeSaveMethod(type)) {
388 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
389 }
390 }
391 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000392 runtime_ = runtime;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393 return true;
394 }
395
396 // Appends to dex_files any elements of class_path that it doesn't already
397 // contain. This will open those dex files as necessary.
Brian Carlstrom45602482013-07-21 22:07:55 -0700398 static void OpenClassPathFiles(const std::string& class_path,
399 std::vector<const DexFile*>& dex_files) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700400 std::vector<std::string> parsed;
401 Split(class_path, ':', parsed);
402 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
403 ScopedObjectAccess soa(Thread::Current());
404 for (size_t i = 0; i < parsed.size(); ++i) {
405 if (DexFilesContains(dex_files, parsed[i])) {
406 continue;
407 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700408 std::string error_msg;
409 const DexFile* dex_file = DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700411 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 } else {
413 dex_files.push_back(dex_file);
414 }
415 }
416 }
417
418 // Returns true if dex_files has a dex with the named location.
Brian Carlstrom45602482013-07-21 22:07:55 -0700419 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
420 const std::string& location) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421 for (size_t i = 0; i < dex_files.size(); ++i) {
422 if (dex_files[i]->GetLocation() == location) {
423 return true;
424 }
425 }
426 return false;
427 }
428
429 const CompilerBackend compiler_backend_;
430
431 const InstructionSet instruction_set_;
Dave Allison70202782013-10-22 17:52:19 -0700432 const InstructionSetFeatures instruction_set_features_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700433
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000434 UniquePtr<VerifiedMethodsData> verified_methods_data_;
435 Dex2OatCompilerCallbacks callbacks_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 Runtime* runtime_;
437 size_t thread_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 uint64_t start_ns_;
439
440 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
441};
442
443static bool ParseInt(const char* in, int* out) {
444 char* end;
445 int result = strtol(in, &end, 10);
446 if (in == end || *end != '\0') {
447 return false;
448 }
449 *out = result;
450 return true;
451}
452
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800453static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
454 const std::vector<const char*>& dex_locations,
455 std::vector<const DexFile*>& dex_files) {
456 size_t failure_count = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457 for (size_t i = 0; i < dex_filenames.size(); i++) {
458 const char* dex_filename = dex_filenames[i];
459 const char* dex_location = dex_locations[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700460 std::string error_msg;
Brian Carlstromd5aba592013-11-12 01:52:44 -0800461 if (!OS::FileExists(dex_filename)) {
462 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
463 continue;
464 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700465 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700467 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800468 ++failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 } else {
470 dex_files.push_back(dex_file);
471 }
472 }
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800473 return failure_count;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700474}
475
476// The primary goal of the watchdog is to prevent stuck build servers
477// during development when fatal aborts lead to a cascade of failures
478// that result in a deadlock.
479class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
481#undef CHECK_PTHREAD_CALL
482#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
483 do { \
484 int rc = call args; \
485 if (rc != 0) { \
486 errno = rc; \
487 std::string message(# call); \
488 message += " failed for "; \
489 message += reason; \
490 Fatal(message); \
491 } \
492 } while (false)
493
494 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700495 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700496 is_watch_dog_enabled_ = is_watch_dog_enabled;
497 if (!is_watch_dog_enabled_) {
498 return;
499 }
500 shutting_down_ = false;
501 const char* reason = "dex2oat watch dog thread startup";
502 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
503 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
504 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
505 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
506 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
507 }
508 ~WatchDog() {
509 if (!is_watch_dog_enabled_) {
510 return;
511 }
512 const char* reason = "dex2oat watch dog thread shutdown";
513 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
514 shutting_down_ = true;
515 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
516 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
517
518 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
519
520 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
521 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
522 }
523
524 private:
525 static void* CallBack(void* arg) {
526 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
527 ::art::SetThreadName("dex2oat watch dog");
528 self->Wait();
529 return NULL;
530 }
531
532 static void Message(char severity, const std::string& message) {
533 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
534 // cases.
535 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
536 kIsDebugBuild ? "d" : "",
537 severity,
538 getpid(),
539 GetTid(),
540 message.c_str());
541 }
542
543 static void Warn(const std::string& message) {
544 Message('W', message);
545 }
546
547 static void Fatal(const std::string& message) {
548 Message('F', message);
549 exit(1);
550 }
551
552 void Wait() {
553 bool warning = true;
554 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
555 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
556 // large.
557 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1;
558 timespec warning_ts;
559 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
560 timespec timeout_ts;
561 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
562 const char* reason = "dex2oat watch dog thread waiting";
563 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
564 while (!shutting_down_) {
565 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
566 warning ? &warning_ts
567 : &timeout_ts));
568 if (rc == ETIMEDOUT) {
569 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
570 warning ? kWatchDogWarningSeconds
571 : kWatchDogTimeoutSeconds));
572 if (warning) {
573 Warn(message.c_str());
574 warning = false;
575 } else {
576 Fatal(message.c_str());
577 }
578 } else if (rc != 0) {
579 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
580 strerror(errno)));
581 Fatal(message.c_str());
582 }
583 }
584 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
585 }
586
587 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
588#if ART_USE_PORTABLE_COMPILER
589 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
590 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
591#else
592 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
593 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
594#endif
595
596 bool is_watch_dog_enabled_;
597 bool shutting_down_;
598 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
599 pthread_mutex_t mutex_;
600 pthread_cond_t cond_;
601 pthread_attr_t attr_;
602 pthread_t pthread_;
603};
604const unsigned int WatchDog::kWatchDogWarningSeconds;
605const unsigned int WatchDog::kWatchDogTimeoutSeconds;
606
Dave Allison70202782013-10-22 17:52:19 -0700607// Given a set of instruction features from the build, parse it. The
608// input 'str' is a comma separated list of feature names. Parse it and
609// return the InstructionSetFeatures object.
610static InstructionSetFeatures ParseFeatureList(std::string str) {
611 InstructionSetFeatures result;
612 typedef std::vector<std::string> FeatureList;
613 FeatureList features;
614 Split(str, ',', features);
615 for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
616 std::string feature = Trim(*i);
617 if (feature == "default") {
618 // Nothing to do.
619 } else if (feature == "div") {
620 // Supports divide instruction.
621 result.SetHasDivideInstruction(true);
622 } else if (feature == "nodiv") {
623 // Turn off support for divide instruction.
624 result.SetHasDivideInstruction(false);
625 } else {
626 Usage("Unknown instruction set feature: '%s'", feature.c_str());
627 }
628 }
629 // others...
630 return result;
631}
632
Brian Carlstrom7940e442013-07-12 13:46:57 -0700633static int dex2oat(int argc, char** argv) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800634 TimingLogger timings("compiler", false, false);
Brian Carlstrom45602482013-07-21 22:07:55 -0700635
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636 InitLogging(argv);
637
638 // Skip over argv[0].
639 argv++;
640 argc--;
641
642 if (argc == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700643 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700644 }
645
646 std::vector<const char*> dex_filenames;
647 std::vector<const char*> dex_locations;
648 int zip_fd = -1;
649 std::string zip_location;
650 std::string oat_filename;
651 std::string oat_symbols;
652 std::string oat_location;
653 int oat_fd = -1;
654 std::string bitcode_filename;
655 const char* image_classes_zip_filename = NULL;
656 const char* image_classes_filename = NULL;
657 std::string image_filename;
658 std::string boot_image_filename;
659 uintptr_t image_base = 0;
660 UniquePtr<std::string> host_prefix;
661 std::string android_root;
662 std::vector<const char*> runtime_args;
663 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700664#if defined(ART_USE_PORTABLE_COMPILER)
665 CompilerBackend compiler_backend = kPortable;
666#else
667 CompilerBackend compiler_backend = kQuick;
668#endif
Dave Allison70202782013-10-22 17:52:19 -0700669
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800670 // Take the default set of instruction features from the build.
Dave Allison70202782013-10-22 17:52:19 -0700671 InstructionSetFeatures instruction_set_features =
Brian Carlstrom1bd2ceb2013-11-06 00:29:48 -0800672 ParseFeatureList(STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES));
Dave Allison70202782013-10-22 17:52:19 -0700673
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674#if defined(__arm__)
675 InstructionSet instruction_set = kThumb2;
676#elif defined(__i386__)
677 InstructionSet instruction_set = kX86;
678#elif defined(__mips__)
679 InstructionSet instruction_set = kMips;
680#else
681#error "Unsupported architecture"
682#endif
Dave Allison70202782013-10-22 17:52:19 -0700683
684
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685 bool is_host = false;
Ian Rogerse732ef12013-10-09 15:22:24 -0700686 bool dump_stats = false;
Ian Rogers46398602013-08-20 07:50:36 -0700687 bool dump_timing = false;
688 bool dump_slow_timing = kIsDebugBuild;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689 bool watch_dog_enabled = !kIsTargetBuild;
690
691
692 for (int i = 0; i < argc; i++) {
693 const StringPiece option(argv[i]);
694 bool log_options = false;
695 if (log_options) {
696 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
697 }
698 if (option.starts_with("--dex-file=")) {
699 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
700 } else if (option.starts_with("--dex-location=")) {
701 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
702 } else if (option.starts_with("--zip-fd=")) {
703 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
704 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700705 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706 }
707 } else if (option.starts_with("--zip-location=")) {
708 zip_location = option.substr(strlen("--zip-location=")).data();
709 } else if (option.starts_with("--oat-file=")) {
710 oat_filename = option.substr(strlen("--oat-file=")).data();
711 } else if (option.starts_with("--oat-symbols=")) {
712 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
713 } else if (option.starts_with("--oat-fd=")) {
714 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
715 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700716 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718 } else if (option == "--watch-dog") {
719 watch_dog_enabled = true;
720 } else if (option == "--no-watch-dog") {
721 watch_dog_enabled = false;
722 } else if (option.starts_with("-j")) {
723 const char* thread_count_str = option.substr(strlen("-j")).data();
724 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700725 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726 }
727 } else if (option.starts_with("--oat-location=")) {
728 oat_location = option.substr(strlen("--oat-location=")).data();
729 } else if (option.starts_with("--bitcode=")) {
730 bitcode_filename = option.substr(strlen("--bitcode=")).data();
731 } else if (option.starts_with("--image=")) {
732 image_filename = option.substr(strlen("--image=")).data();
733 } else if (option.starts_with("--image-classes=")) {
734 image_classes_filename = option.substr(strlen("--image-classes=")).data();
735 } else if (option.starts_with("--image-classes-zip=")) {
736 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
737 } else if (option.starts_with("--base=")) {
738 const char* image_base_str = option.substr(strlen("--base=")).data();
739 char* end;
740 image_base = strtoul(image_base_str, &end, 16);
741 if (end == image_base_str || *end != '\0') {
742 Usage("Failed to parse hexadecimal value for option %s", option.data());
743 }
744 } else if (option.starts_with("--boot-image=")) {
745 boot_image_filename = option.substr(strlen("--boot-image=")).data();
746 } else if (option.starts_with("--host-prefix=")) {
747 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
748 } else if (option.starts_with("--android-root=")) {
749 android_root = option.substr(strlen("--android-root=")).data();
750 } else if (option.starts_with("--instruction-set=")) {
751 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
752 if (instruction_set_str == "arm") {
753 instruction_set = kThumb2;
754 } else if (instruction_set_str == "mips") {
755 instruction_set = kMips;
756 } else if (instruction_set_str == "x86") {
757 instruction_set = kX86;
758 }
Dave Allison70202782013-10-22 17:52:19 -0700759 } else if (option.starts_with("--instruction-set-features=")) {
760 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
761 instruction_set_features = ParseFeatureList(str.as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700762 } else if (option.starts_with("--compiler-backend=")) {
763 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
764 if (backend_str == "Quick") {
765 compiler_backend = kQuick;
766 } else if (backend_str == "Portable") {
767 compiler_backend = kPortable;
768 }
769 } else if (option == "--host") {
770 is_host = true;
771 } else if (option == "--runtime-arg") {
772 if (++i >= argc) {
773 Usage("Missing required argument for --runtime-arg");
774 }
775 if (log_options) {
776 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
777 }
778 runtime_args.push_back(argv[i]);
Ian Rogers46398602013-08-20 07:50:36 -0700779 } else if (option == "--dump-timing") {
780 dump_timing = true;
Ian Rogerse732ef12013-10-09 15:22:24 -0700781 } else if (option == "--dump-stats") {
782 dump_stats = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700784 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700785 }
786 }
787
788 if (oat_filename.empty() && oat_fd == -1) {
789 Usage("Output must be supplied with either --oat-file or --oat-fd");
790 }
791
792 if (!oat_filename.empty() && oat_fd != -1) {
793 Usage("--oat-file should not be used with --oat-fd");
794 }
795
796 if (!oat_symbols.empty() && oat_fd != -1) {
797 Usage("--oat-symbols should not be used with --oat-fd");
798 }
799
800 if (!oat_symbols.empty() && is_host) {
801 Usage("--oat-symbols should not be used with --host");
802 }
803
804 if (oat_fd != -1 && !image_filename.empty()) {
805 Usage("--oat-fd should not be used with --image");
806 }
807
808 if (host_prefix.get() == NULL) {
809 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
810 if (android_product_out != NULL) {
811 host_prefix.reset(new std::string(android_product_out));
812 }
813 }
814
815 if (android_root.empty()) {
816 const char* android_root_env_var = getenv("ANDROID_ROOT");
817 if (android_root_env_var == NULL) {
818 Usage("--android-root unspecified and ANDROID_ROOT not set");
819 }
820 android_root += android_root_env_var;
821 }
822
823 bool image = (!image_filename.empty());
824 if (!image && boot_image_filename.empty()) {
825 if (host_prefix.get() == NULL) {
826 boot_image_filename += GetAndroidRoot();
827 } else {
828 boot_image_filename += *host_prefix.get();
829 boot_image_filename += "/system";
830 }
831 boot_image_filename += "/framework/boot.art";
832 }
833 std::string boot_image_option;
834 if (!boot_image_filename.empty()) {
835 boot_image_option += "-Ximage:";
836 boot_image_option += boot_image_filename;
837 }
838
839 if (image_classes_filename != NULL && !image) {
840 Usage("--image-classes should only be used with --image");
841 }
842
843 if (image_classes_filename != NULL && !boot_image_option.empty()) {
844 Usage("--image-classes should not be used with --boot-image");
845 }
846
847 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) {
848 Usage("--image-classes-zip should be used with --image-classes");
849 }
850
851 if (dex_filenames.empty() && zip_fd == -1) {
852 Usage("Input must be supplied with either --dex-file or --zip-fd");
853 }
854
855 if (!dex_filenames.empty() && zip_fd != -1) {
856 Usage("--dex-file should not be used with --zip-fd");
857 }
858
859 if (!dex_filenames.empty() && !zip_location.empty()) {
860 Usage("--dex-file should not be used with --zip-location");
861 }
862
863 if (dex_locations.empty()) {
864 for (size_t i = 0; i < dex_filenames.size(); i++) {
865 dex_locations.push_back(dex_filenames[i]);
866 }
867 } else if (dex_locations.size() != dex_filenames.size()) {
868 Usage("--dex-location arguments do not match --dex-file arguments");
869 }
870
871 if (zip_fd != -1 && zip_location.empty()) {
872 Usage("--zip-location should be supplied with --zip-fd");
873 }
874
875 if (boot_image_option.empty()) {
876 if (image_base == 0) {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700877 Usage("Non-zero --base not specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878 }
879 }
880
881 std::string oat_stripped(oat_filename);
882 std::string oat_unstripped;
883 if (!oat_symbols.empty()) {
884 oat_unstripped += oat_symbols;
885 } else {
886 oat_unstripped += oat_filename;
887 }
888
889 // Done with usage checks, enable watchdog if requested
890 WatchDog watch_dog(watch_dog_enabled);
891
892 // Check early that the result of compilation can be written
893 UniquePtr<File> oat_file;
894 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
895 if (create_file) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700896 oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 if (oat_location.empty()) {
898 oat_location = oat_filename;
899 }
900 } else {
901 oat_file.reset(new File(oat_fd, oat_location));
902 oat_file->DisableAutoClose();
903 }
904 if (oat_file.get() == NULL) {
905 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
906 return EXIT_FAILURE;
907 }
908 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
909 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
910 return EXIT_FAILURE;
911 }
912
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700913 timings.StartSplit("dex2oat Setup");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700914 LOG(INFO) << "dex2oat: " << oat_location;
915
Ian Rogersf30f6da2013-08-28 17:33:30 -0700916 if (image) {
917 bool has_compiler_filter = false;
918 for (const char* r : runtime_args) {
919 if (strncmp(r, "-compiler-filter:", 17) == 0) {
920 has_compiler_filter = true;
921 break;
922 }
923 }
924 if (!has_compiler_filter) {
925 runtime_args.push_back("-compiler-filter:everything");
926 }
927 }
928
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 Runtime::Options options;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700930 std::vector<const DexFile*> boot_class_path;
931 if (boot_image_option.empty()) {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800932 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
933 if (failure_count > 0) {
934 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
935 return EXIT_FAILURE;
936 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700937 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
938 } else {
939 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
940 }
941 if (host_prefix.get() != NULL) {
942 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
943 }
944 for (size_t i = 0; i < runtime_args.size(); i++) {
945 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
946 }
947
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948#ifdef ART_SEA_IR_MODE
949 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL)));
950#endif
951
Brian Carlstrom7940e442013-07-12 13:46:57 -0700952 Dex2Oat* p_dex2oat;
Dave Allison70202782013-10-22 17:52:19 -0700953 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set,
954 instruction_set_features, thread_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700955 LOG(ERROR) << "Failed to create dex2oat";
956 return EXIT_FAILURE;
957 }
958 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
959 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700960 // give it away now so that we don't starve GC.
961 Thread* self = Thread::Current();
962 self->TransitionFromRunnableToSuspended(kNative);
Ian Rogers0f40ac32013-08-13 22:10:30 -0700963 // If we're doing the image, override the compiler filter to force full compilation. Must be
buzbeefe9ca402013-08-21 09:48:11 -0700964 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
965 // compilation of class initializers.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966 // Whilst we're in native take the opportunity to initialize well known classes.
Ian Rogers3f3d22c2013-08-27 18:11:09 -0700967 WellKnownClasses::Init(self->GetJniEnv());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968
969 // If --image-classes was specified, calculate the full list of classes to include in the image
970 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
971 if (image_classes_filename != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700972 std::string error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 if (image_classes_zip_filename != NULL) {
974 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700975 image_classes_filename,
976 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700977 } else {
978 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
979 }
980 if (image_classes.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700981 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
982 "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700983 return EXIT_FAILURE;
984 }
985 }
986
987 std::vector<const DexFile*> dex_files;
988 if (boot_image_option.empty()) {
989 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
990 } else {
991 if (dex_filenames.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700992 std::string error_msg;
993 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
994 &error_msg));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995 if (zip_archive.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700996 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
997 << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998 return EXIT_FAILURE;
999 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001000 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location, &error_msg);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001 if (dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001002 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
1003 << "': " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 return EXIT_FAILURE;
1005 }
1006 dex_files.push_back(dex_file);
1007 } else {
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001008 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
1009 if (failure_count > 0) {
1010 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1011 return EXIT_FAILURE;
1012 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001014
1015 // Ensure opened dex files are writable for dex-to-dex transformations.
1016 for (const auto& dex_file : dex_files) {
1017 if (!dex_file->EnableWrite()) {
1018 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1019 }
1020 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001021 }
1022
buzbeea024a062013-07-31 10:47:37 -07001023 /*
1024 * If we're not in interpret-only mode, go ahead and compile small applications. Don't
1025 * bother to check if we're doing the image.
1026 */
1027 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028 size_t num_methods = 0;
1029 for (size_t i = 0; i != dex_files.size(); ++i) {
1030 const DexFile* dex_file = dex_files[i];
1031 CHECK(dex_file != NULL);
1032 num_methods += dex_file->NumMethodIds();
1033 }
buzbeea024a062013-07-31 10:47:37 -07001034 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) {
1035 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed);
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001036 VLOG(compiler) << "Below method threshold, compiling anyways";
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037 }
1038 }
1039
1040 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
1041 host_prefix.get(),
1042 android_root,
1043 is_host,
1044 dex_files,
1045 oat_file.get(),
1046 bitcode_filename,
1047 image,
1048 image_classes,
1049 dump_stats,
Brian Carlstrom45602482013-07-21 22:07:55 -07001050 timings));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001051
1052 if (compiler.get() == NULL) {
1053 LOG(ERROR) << "Failed to create oat file: " << oat_location;
1054 return EXIT_FAILURE;
1055 }
1056
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001057 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001058
1059 // Notes on the interleaving of creating the image and oat file to
1060 // ensure the references between the two are correct.
1061 //
1062 // Currently we have a memory layout that looks something like this:
1063 //
1064 // +--------------+
1065 // | image |
1066 // +--------------+
1067 // | boot oat |
1068 // +--------------+
1069 // | alloc spaces |
1070 // +--------------+
1071 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001072 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073 //
1074 // 1. The image is expected to be loaded at an absolute address and
1075 // contains Objects with absolute pointers within the image.
1076 //
1077 // 2. There are absolute pointers from Methods in the image to their
1078 // code in the oat.
1079 //
1080 // 3. There are absolute pointers from the code in the oat to Methods
1081 // in the image.
1082 //
1083 // 4. There are absolute pointers from code in the oat to other code
1084 // in the oat.
1085 //
1086 // To get this all correct, we go through several steps.
1087 //
1088 // 1. We have already created that oat file above with
1089 // CreateOatFile. Originally this was just our own proprietary file
Brian Carlstrom45602482013-07-21 22:07:55 -07001090 // but now it is contained within an ELF dynamic object (aka an .so
Brian Carlstrom7940e442013-07-12 13:46:57 -07001091 // file). The Compiler returned by CreateOatFile provides
1092 // PatchInformation for references to oat code and Methods that need
1093 // to be update once we know where the oat file will be located
1094 // after the image.
1095 //
1096 // 2. We create the image file. It needs to know where the oat file
1097 // will be loaded after itself. Originally when oat file was simply
1098 // memory mapped so we could predict where its contents were based
1099 // on the file size. Now that it is an ELF file, we need to inspect
1100 // the ELF file to understand the in memory segment layout including
1101 // where the oat header is located within. ImageWriter's
1102 // PatchOatCodeAndMethods uses the PatchInformation from the
1103 // Compiler to touch up absolute references in the oat file.
1104 //
1105 // 3. We fixup the ELF program headers so that dlopen will try to
1106 // load the .so at the desired location at runtime by offsetting the
1107 // Elf32_Phdr.p_vaddr values by the desired base address.
1108 //
1109 if (image) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001110 timings.NewSplit("dex2oat ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001111 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1112 image_base,
1113 oat_unstripped,
1114 oat_location,
1115 *compiler.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001116 if (!image_creation_success) {
1117 return EXIT_FAILURE;
1118 }
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001119 VLOG(compiler) << "Image written successfully: " << image_filename;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001120 }
1121
1122 if (is_host) {
Ian Rogers46398602013-08-20 07:50:36 -07001123 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001124 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001125 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001126 return EXIT_SUCCESS;
1127 }
1128
1129 // If we don't want to strip in place, copy from unstripped location to stripped location.
1130 // We need to strip after image creation because FixupElf needs to use .strtab.
1131 if (oat_unstripped != oat_stripped) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001132 timings.NewSplit("dex2oat OatFile copy");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001133 oat_file.reset();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001134 UniquePtr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1135 UniquePtr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001136 size_t buffer_size = 8192;
1137 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1138 while (true) {
1139 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1140 if (bytes_read <= 0) {
1141 break;
1142 }
1143 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1144 CHECK(write_ok);
1145 }
1146 oat_file.reset(out.release());
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001147 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001148 }
1149
Brian Carlstrom7fcba112013-07-22 10:28:48 -07001150#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001151 timings.NewSplit("dex2oat ElfStripper");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001152 // Strip unneeded sections for target
1153 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1154 CHECK_EQ(0, seek_actual);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001155 std::string error_msg;
1156 CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001157
Brian Carlstrom7940e442013-07-12 13:46:57 -07001158
1159 // We wrote the oat file successfully, and want to keep it.
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001160 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001161#endif // ART_USE_PORTABLE_COMPILER
Brian Carlstrom45602482013-07-21 22:07:55 -07001162
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001163 timings.EndSplit();
1164
Brian Carlstromc6dfdac2013-08-26 18:57:31 -07001165 if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001166 LOG(INFO) << Dumpable<TimingLogger>(timings);
Brian Carlstrom45602482013-07-21 22:07:55 -07001167 }
Ian Rogers2672a9f2013-09-05 17:24:22 -07001168
1169 // Everything was successfully written, do an explicit exit here to avoid running Runtime
1170 // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1171 if (!kIsDebugBuild || (RUNNING_ON_VALGRIND == 0)) {
1172 exit(EXIT_SUCCESS);
1173 }
1174
Brian Carlstrom7940e442013-07-12 13:46:57 -07001175 return EXIT_SUCCESS;
1176}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001177} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178
1179int main(int argc, char** argv) {
1180 return art::dex2oat(argc, argv);
1181}