blob: f678ee9438cc33cf522480b9cc30d3ce96d667a4 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070016
17#include <stdio.h>
18#include <stdlib.h>
Brian Carlstrom6cd40e52012-05-03 14:15:11 -070019#include <sys/stat.h>
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070020
Brian Carlstromae826982011-11-09 01:33:42 -080021#include <iostream>
22#include <fstream>
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070023#include <string>
24#include <vector>
25
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080027#include "base/stringpiece.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080028#include "base/timing_logger.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070030#include "class_linker.h"
Ian Rogers1212a022013-03-04 10:48:41 -080031#include "compiler/driver/compiler_driver.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "dex_file-inl.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070033#include "image_writer.h"
Ian Rogers6f1dfe42011-12-08 17:28:34 -080034#include "leb128.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/abstract_method-inl.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
38#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070040#include "oat_writer.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Ian Rogers5e863dd2011-11-02 20:00:10 -070042#include "os.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070043#include "runtime.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070044#include "ScopedLocalRef.h"
45#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "vector_output_stream.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070048#include "well_known_classes.h"
Brian Carlstroma6cc8932012-01-04 14:44:07 -080049#include "zip_archive.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070050
51namespace art {
52
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080053static void UsageErrorV(const char* fmt, va_list ap) {
54 std::string error;
55 StringAppendV(&error, fmt, ap);
56 LOG(ERROR) << error;
57}
58
59static void UsageError(const char* fmt, ...) {
60 va_list ap;
61 va_start(ap, fmt);
62 UsageErrorV(fmt, ap);
63 va_end(ap);
64}
65
66static void Usage(const char* fmt, ...) {
67 va_list ap;
68 va_start(ap, fmt);
69 UsageErrorV(fmt, ap);
70 va_end(ap);
71
72 UsageError("Usage: dex2oat [options]...");
73 UsageError("");
74 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
75 UsageError(" Example: --dex-file=/system/framework/core.jar");
76 UsageError("");
77 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
78 UsageError(" containing a classes.dex file to compile.");
79 UsageError(" Example: --zip-fd=5");
80 UsageError("");
81 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file corresponding");
82 UsageError(" to the file descriptor specified by --zip-fd.");
83 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
84 UsageError("");
Brian Carlstrom265091e2013-01-30 14:08:26 -080085 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
86 UsageError(" Example: --oat-file=/system/framework/boot.oat");
87 UsageError("");
88 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080089 UsageError(" Example: --oat-file=/system/framework/boot.oat");
90 UsageError("");
91 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
92 UsageError(" to the file descriptor specified by --oat-fd.");
Brian Carlstrom7675e162013-06-10 16:18:04 -070093 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080094 UsageError("");
Brian Carlstrom265091e2013-01-30 14:08:26 -080095 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
96 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
97 UsageError("");
Logan Chien8b977d32012-02-21 19:14:55 +080098 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
99 UsageError(" Example: --bitcode=/system/framework/boot.bc");
100 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800101 UsageError(" --image=<file.art>: specifies the output image filename.");
102 UsageError(" Example: --image=/system/framework/boot.art");
103 UsageError("");
104 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
105 UsageError(" Example: --image=frameworks/base/preloaded-classes");
106 UsageError("");
107 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
108 UsageError(" Example: --base=0x50000000");
109 UsageError("");
110 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
111 UsageError(" Example: --boot-image=/system/framework/boot.art");
112 UsageError(" Default: <host-prefix>/system/framework/boot.art");
113 UsageError("");
Brian Carlstrom265091e2013-01-30 14:08:26 -0800114 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800115 UsageError(" cross compilation.");
116 UsageError(" Example: --host-prefix=out/target/product/crespo");
117 UsageError(" Default: $ANDROID_PRODUCT_OUT");
118 UsageError("");
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800119 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
120 UsageError(" Example: --android-root=out/host/linux-x86");
121 UsageError(" Default: $ANDROID_ROOT");
122 UsageError("");
jeffhao1f71ae82012-05-24 16:08:24 -0700123 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
Ian Rogers49c48942012-03-11 15:15:37 -0700124 UsageError(" set.");
jeffhao1f71ae82012-05-24 16:08:24 -0700125 UsageError(" Example: --instruction-set=x86");
126 UsageError(" Default: arm");
Ian Rogers49c48942012-03-11 15:15:37 -0700127 UsageError("");
buzbeec531cef2012-10-18 07:09:20 -0700128 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
129 UsageError(" set.");
130 UsageError(" Example: --instruction-set=Portable");
131 UsageError(" Default: Quick");
Brian Carlstrom265091e2013-01-30 14:08:26 -0800132 UsageError("");
133 UsageError(" --host: used with Portable backend to link against host runtime libraries");
134 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800135 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
136 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
137 UsageError(" Use a separate --runtime-arg switch for each argument.");
138 UsageError(" Example: --runtime-arg -Xms256m");
139 UsageError("");
140 std::cerr << "See log for usage error information\n";
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700141 exit(EXIT_FAILURE);
142}
143
Brian Carlstromae826982011-11-09 01:33:42 -0800144class Dex2Oat {
145 public:
buzbeec531cef2012-10-18 07:09:20 -0700146 static bool Create(Dex2Oat** p_dex2oat, Runtime::Options& options, CompilerBackend compiler_backend,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700147 InstructionSet instruction_set, size_t thread_count, bool support_debugging)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700148 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700149 if (!CreateRuntime(options, instruction_set)) {
150 *p_dex2oat = NULL;
151 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800152 }
buzbeec531cef2012-10-18 07:09:20 -0700153 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700154 support_debugging);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800156 }
157
158 ~Dex2Oat() {
159 delete runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800160 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) << " (threads: " << thread_count_ << ")";
Brian Carlstromae826982011-11-09 01:33:42 -0800161 }
162
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700163
Brian Carlstrom96391602013-06-13 19:49:50 -0700164 // Reads the class names (java.lang.Object) and returns as set of class descriptors (Ljava/lang/Object;)
165 CompilerDriver::DescriptorSet* ReadImageClasses(const char* image_classes_filename) {
Brian Carlstromae826982011-11-09 01:33:42 -0800166 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
167 if (image_classes_file.get() == NULL) {
168 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
169 return NULL;
170 }
171
Brian Carlstrom96391602013-06-13 19:49:50 -0700172 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet);
Brian Carlstromae826982011-11-09 01:33:42 -0800173 while (image_classes_file->good()) {
174 std::string dot;
175 std::getline(*image_classes_file.get(), dot);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800176 if (StartsWith(dot, "#") || dot.empty()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800177 continue;
178 }
Elliott Hughes95572412011-12-13 18:14:20 -0800179 std::string descriptor(DotToDescriptor(dot.c_str()));
Brian Carlstrom96391602013-06-13 19:49:50 -0700180 image_classes->insert(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -0800181 }
182 image_classes_file->close();
Brian Carlstromae826982011-11-09 01:33:42 -0800183 return image_classes.release();
184 }
185
Ian Rogers1212a022013-03-04 10:48:41 -0800186 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800187 const std::string* host_prefix,
188 const std::string& android_root,
189 bool is_host,
190 const std::vector<const DexFile*>& dex_files,
191 File* oat_file,
192 const std::string& bitcode_filename,
193 bool image,
Brian Carlstrom96391602013-06-13 19:49:50 -0700194 UniquePtr<CompilerDriver::DescriptorSet>& image_classes,
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800195 bool dump_stats,
196 bool dump_timings)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700197 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800198 // SirtRef and ClassLoader creation needs to come after Runtime::Create
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700199 jobject class_loader = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800200 if (!boot_image_option.empty()) {
201 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromae826982011-11-09 01:33:42 -0800202 std::vector<const DexFile*> class_path_files(dex_files);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800203 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800204 for (size_t i = 0; i < class_path_files.size(); i++) {
205 class_linker->RegisterDexFile(*class_path_files[i]);
206 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700207 ScopedObjectAccessUnchecked soa(Thread::Current());
208 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
209 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
210 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
211 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
212 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800213 }
214
Ian Rogers1212a022013-03-04 10:48:41 -0800215 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
216 instruction_set_,
217 image,
Brian Carlstrom96391602013-06-13 19:49:50 -0700218 image_classes.release(),
Ian Rogers1212a022013-03-04 10:48:41 -0800219 thread_count_,
220 support_debugging_,
Ian Rogers1212a022013-03-04 10:48:41 -0800221 dump_stats,
222 dump_timings));
Logan Chien8b977d32012-02-21 19:14:55 +0800223
Ian Rogersc928de92013-02-27 14:30:44 -0800224 if (compiler_backend_ == kPortable) {
Ian Rogers1212a022013-03-04 10:48:41 -0800225 driver->SetBitcodeFileName(bitcode_filename);
buzbeec531cef2012-10-18 07:09:20 -0700226 }
Logan Chien8b977d32012-02-21 19:14:55 +0800227
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700228
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
230
Ian Rogers1212a022013-03-04 10:48:41 -0800231 driver->CompileAll(class_loader, dex_files);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700232
233 Thread::Current()->TransitionFromSuspendedToRunnable();
Brian Carlstromae826982011-11-09 01:33:42 -0800234
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700235 std::string image_file_location;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700236 uint32_t image_file_location_oat_checksum = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800237 uint32_t image_file_location_oat_data_begin = 0;
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700238 if (!driver->IsImage()) {
239 ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
Brian Carlstrom28db0122012-10-18 16:20:41 -0700240 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
Ian Rogers39ebcb82013-05-30 16:57:23 -0700241 image_file_location_oat_data_begin =
242 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700243 image_file_location = image_space->GetImageFilename();
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700244 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
245 image_file_location = image_file_location.substr(host_prefix->size());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700246 }
247 }
248
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800249 std::vector<uint8_t> oat_contents;
Ian Rogers39ebcb82013-05-30 16:57:23 -0700250 // TODO: change ElfWriterQuick to not require the creation of oat_contents. The old pre-mclinker
251 // OatWriter streamed directly to disk. The new could can be adapted to do it as follows:
252 // 1.) use first pass of OatWriter to calculate size of oat structure,
253 // 2.) call ElfWriterQuick with pointer to OatWriter instead of contents,
254 // 3.) have ElfWriterQuick call back to OatWriter to stream generate the output directly in
255 // place in the elf file.
256 oat_contents.reserve(5 * MB);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800257 VectorOutputStream vector_output_stream(oat_file->GetPath(), oat_contents);
258 if (!OatWriter::Create(vector_output_stream,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700259 dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700260 image_file_location_oat_checksum,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800261 image_file_location_oat_data_begin,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700262 image_file_location,
Ian Rogers1212a022013-03-04 10:48:41 -0800263 *driver.get())) {
Elliott Hughes76160052012-12-12 16:31:20 -0800264 LOG(ERROR) << "Failed to create oat file " << oat_file->GetPath();
Brian Carlstromf5822582012-03-19 22:34:31 -0700265 return NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800266 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800267
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800268 if (!driver->WriteElf(android_root, is_host, dex_files, oat_contents, oat_file)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800269 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
270 return NULL;
271 }
272
Ian Rogers1212a022013-03-04 10:48:41 -0800273 return driver.release();
Brian Carlstromae826982011-11-09 01:33:42 -0800274 }
275
Brian Carlstroma004aa92012-02-08 18:05:09 -0800276 bool CreateImageFile(const std::string& image_filename,
Brian Carlstromae826982011-11-09 01:33:42 -0800277 uintptr_t image_base,
Brian Carlstromae826982011-11-09 01:33:42 -0800278 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700279 const std::string& oat_location,
Ian Rogers1212a022013-03-04 10:48:41 -0800280 const CompilerDriver& compiler)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700281 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800282 uintptr_t oat_data_begin;
283 {
284 // ImageWriter is scoped so it can free memory before doing FixupElf
Brian Carlstrom96391602013-06-13 19:49:50 -0700285 ImageWriter image_writer(compiler);
286 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800287 LOG(ERROR) << "Failed to create image file " << image_filename;
288 return false;
289 }
290 oat_data_begin = image_writer.GetOatDataBegin();
291 }
292
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800293 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800294 if (oat_file.get() == NULL) {
295 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800296 return false;
297 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800298 if (!compiler.FixupElf(oat_file.get(), oat_data_begin)) {
299 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
300 return false;
301 }
Brian Carlstromae826982011-11-09 01:33:42 -0800302 return true;
303 }
304
305 private:
buzbeec531cef2012-10-18 07:09:20 -0700306 explicit Dex2Oat(Runtime* runtime, CompilerBackend compiler_backend, InstructionSet instruction_set,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700307 size_t thread_count, bool support_debugging)
buzbeec531cef2012-10-18 07:09:20 -0700308 : compiler_backend_(compiler_backend),
309 instruction_set_(instruction_set),
Ian Rogers49c48942012-03-11 15:15:37 -0700310 runtime_(runtime),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800311 thread_count_(thread_count),
312 support_debugging_(support_debugging),
313 start_ns_(NanoTime()) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800314 }
Brian Carlstromae826982011-11-09 01:33:42 -0800315
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700316 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700317 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700318 if (!Runtime::Create(options, false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800319 LOG(ERROR) << "Failed to create runtime";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700320 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800321 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700322 Runtime* runtime = Runtime::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800323 // if we loaded an existing image, we will reuse values from the image roots.
Ian Rogers19846512012-02-24 11:42:47 -0800324 if (!runtime->HasResolutionMethod()) {
325 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
326 }
Brian Carlstromae826982011-11-09 01:33:42 -0800327 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
328 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
329 if (!runtime->HasCalleeSaveMethod(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700330 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800331 }
332 }
Ian Rogers19846512012-02-24 11:42:47 -0800333 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700334 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800335 }
336
Brian Carlstromae826982011-11-09 01:33:42 -0800337 // Appends to dex_files any elements of class_path that it doesn't already
338 // contain. This will open those dex files as necessary.
339 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
340 std::vector<std::string> parsed;
341 Split(class_path, ':', parsed);
Ian Rogers33e95662013-05-20 20:29:14 -0700342 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
343 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromae826982011-11-09 01:33:42 -0800344 for (size_t i = 0; i < parsed.size(); ++i) {
345 if (DexFilesContains(dex_files, parsed[i])) {
346 continue;
347 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800348 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
Brian Carlstromae826982011-11-09 01:33:42 -0800349 if (dex_file == NULL) {
350 LOG(WARNING) << "Failed to open dex file " << parsed[i];
351 } else {
352 dex_files.push_back(dex_file);
353 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500354 }
355 }
Brian Carlstromae826982011-11-09 01:33:42 -0800356
357 // Returns true if dex_files has a dex with the named location.
358 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
359 for (size_t i = 0; i < dex_files.size(); ++i) {
360 if (dex_files[i]->GetLocation() == location) {
361 return true;
362 }
363 }
364 return false;
365 }
366
buzbeec531cef2012-10-18 07:09:20 -0700367 const CompilerBackend compiler_backend_;
368
Ian Rogers49c48942012-03-11 15:15:37 -0700369 const InstructionSet instruction_set_;
Brian Carlstromae826982011-11-09 01:33:42 -0800370
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800371 Runtime* runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800372 size_t thread_count_;
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800373 bool support_debugging_;
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800374 uint64_t start_ns_;
375
Brian Carlstromae826982011-11-09 01:33:42 -0800376 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
377};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500378
Elliott Hughes72395bf2012-04-24 13:45:26 -0700379static bool ParseInt(const char* in, int* out) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800380 char* end;
381 int result = strtol(in, &end, 10);
382 if (in == end || *end != '\0') {
383 return false;
384 }
385 *out = result;
386 return true;
387}
388
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700389static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
390 const std::vector<const char*>& dex_locations,
391 std::vector<const DexFile*>& dex_files) {
392 size_t failure_count = 0;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800393 for (size_t i = 0; i < dex_filenames.size(); i++) {
394 const char* dex_filename = dex_filenames[i];
Brian Carlstroma004aa92012-02-08 18:05:09 -0800395 const char* dex_location = dex_locations[i];
396 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800397 if (dex_file == NULL) {
Ian Rogers33e95662013-05-20 20:29:14 -0700398 LOG(WARNING) << "Could not open .dex from file '" << dex_filename << "'\n";
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700399 ++failure_count;
jeffhao60f83e32012-02-13 17:16:30 -0800400 } else {
401 dex_files.push_back(dex_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800402 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800403 }
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700404 return failure_count;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800405}
406
Brian Carlstrombcc29262012-11-02 11:36:03 -0700407// The primary goal of the watchdog is to prevent stuck build servers
408// during development when fatal aborts lead to a cascade of failures
409// that result in a deadlock.
410class WatchDog {
411
412// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
413#undef CHECK_PTHREAD_CALL
414#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
415 do { \
416 int rc = call args; \
417 if (rc != 0) { \
418 errno = rc; \
419 std::string message(# call); \
420 message += " failed for "; \
421 message += reason; \
Brian Carlstromed115642013-03-15 16:04:40 -0700422 Fatal(message); \
Brian Carlstrombcc29262012-11-02 11:36:03 -0700423 } \
424 } while (false)
425
426 public:
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800427 WatchDog(bool is_watch_dog_enabled) {
428 is_watch_dog_enabled_ = is_watch_dog_enabled;
429 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700430 return;
431 }
432 shutting_down_ = false;
433 const char* reason = "dex2oat watch dog thread startup";
434 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
435 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
436 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
437 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
438 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
439 }
440 ~WatchDog() {
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800441 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700442 return;
443 }
444 const char* reason = "dex2oat watch dog thread shutdown";
445 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
446 shutting_down_ = true;
447 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
448 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
449
450 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
451
452 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
453 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
454 }
455
456 private:
457 static void* CallBack(void* arg) {
458 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
459 self->Wait();
460 return NULL;
461 }
462
Brian Carlstromed115642013-03-15 16:04:40 -0700463 static void Message(char severity, const std::string& message) {
464 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error cases.
465 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
466 kIsDebugBuild ? "d" : "",
467 severity,
468 getpid(),
469 GetTid(),
470 message.c_str());
Ian Rogerseb5cb602013-02-25 15:06:01 -0800471 }
472
Brian Carlstromed115642013-03-15 16:04:40 -0700473 static void Warn(const std::string& message) {
474 Message('W', message);
475 }
476
477 static void Fatal(const std::string& message) {
478 Message('F', message);
Brian Carlstrombcc29262012-11-02 11:36:03 -0700479 exit(1);
480 }
481
482 void Wait() {
Ian Rogerseb5cb602013-02-25 15:06:01 -0800483 bool warning = true;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800484 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
Brian Carlstromed115642013-03-15 16:04:40 -0700485 timespec warning_ts;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800486 InitTimeSpec(true, CLOCK_REALTIME, kWatchDogWarningSeconds * 1000, 0, &warning_ts);
Brian Carlstromed115642013-03-15 16:04:40 -0700487 timespec timeout_ts;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800488 InitTimeSpec(true, CLOCK_REALTIME, kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
Brian Carlstrombcc29262012-11-02 11:36:03 -0700489 const char* reason = "dex2oat watch dog thread waiting";
490 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
491 while (!shutting_down_) {
Ian Rogerseb5cb602013-02-25 15:06:01 -0800492 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
493 warning ? &warning_ts
494 : &timeout_ts));
Brian Carlstrombcc29262012-11-02 11:36:03 -0700495 if (rc == ETIMEDOUT) {
496 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
Ian Rogerseb5cb602013-02-25 15:06:01 -0800497 warning ? kWatchDogWarningSeconds
498 : kWatchDogTimeoutSeconds));
499 if (warning) {
500 Warn(message.c_str());
501 warning = false;
502 } else {
Brian Carlstromed115642013-03-15 16:04:40 -0700503 Fatal(message.c_str());
Ian Rogerseb5cb602013-02-25 15:06:01 -0800504 }
505 } else if (rc != 0) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700506 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
507 strerror(errno)));
Brian Carlstromed115642013-03-15 16:04:40 -0700508 Fatal(message.c_str());
Brian Carlstrombcc29262012-11-02 11:36:03 -0700509 }
510 }
511 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
512 }
513
Brian Carlstromed115642013-03-15 16:04:40 -0700514 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
515#if ART_USE_PORTABLE_COMPILER
516 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
Ian Rogerseb5cb602013-02-25 15:06:01 -0800517 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
Brian Carlstrombcc29262012-11-02 11:36:03 -0700518#else
Brian Carlstromed115642013-03-15 16:04:40 -0700519 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
520 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
Brian Carlstrombcc29262012-11-02 11:36:03 -0700521#endif
522
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800523 bool is_watch_dog_enabled_;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700524 bool shutting_down_;
525 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases
526 pthread_mutex_t mutex_;
527 pthread_cond_t cond_;
528 pthread_attr_t attr_;
529 pthread_t pthread_;
530};
Ian Rogers1c653d52013-06-13 15:04:30 -0700531const unsigned int WatchDog::kWatchDogWarningSeconds;
532const unsigned int WatchDog::kWatchDogTimeoutSeconds;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700533
Elliott Hughes72395bf2012-04-24 13:45:26 -0700534static int dex2oat(int argc, char** argv) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700535 InitLogging(argv);
Elliott Hughes72395bf2012-04-24 13:45:26 -0700536
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700537 // Skip over argv[0].
538 argv++;
539 argc--;
540
541 if (argc == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800542 Usage("no arguments specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700543 }
544
545 std::vector<const char*> dex_filenames;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800546 std::vector<const char*> dex_locations;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800547 int zip_fd = -1;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800548 std::string zip_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700549 std::string oat_filename;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800550 std::string oat_symbols;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800551 std::string oat_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800552 int oat_fd = -1;
Logan Chien8b977d32012-02-21 19:14:55 +0800553 std::string bitcode_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800554 const char* image_classes_filename = NULL;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800555 std::string image_filename;
Brian Carlstromb0011262011-12-09 12:17:24 -0800556 std::string boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700557 uintptr_t image_base = 0;
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700558 UniquePtr<std::string> host_prefix;
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800559 std::string android_root;
jeffhao5d840402011-10-24 17:09:45 -0700560 std::vector<const char*> runtime_args;
Elliott Hughes5c599942012-06-13 16:45:05 -0700561 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800562 bool support_debugging = false;
buzbeec531cef2012-10-18 07:09:20 -0700563#if defined(ART_USE_PORTABLE_COMPILER)
564 CompilerBackend compiler_backend = kPortable;
buzbeec531cef2012-10-18 07:09:20 -0700565#else
566 CompilerBackend compiler_backend = kQuick;
567#endif
jeffhao9ad4f222012-05-30 18:51:19 -0700568#if defined(__arm__)
Ian Rogers49c48942012-03-11 15:15:37 -0700569 InstructionSet instruction_set = kThumb2;
jeffhao9ad4f222012-05-30 18:51:19 -0700570#elif defined(__i386__)
571 InstructionSet instruction_set = kX86;
572#elif defined(__mips__)
573 InstructionSet instruction_set = kMips;
574#else
575#error "Unsupported architecture"
576#endif
Brian Carlstrom265091e2013-01-30 14:08:26 -0800577 bool is_host = false;
Elliott Hughes67d92002012-03-26 15:08:51 -0700578 bool dump_stats = kIsDebugBuild;
579 bool dump_timings = kIsDebugBuild;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800580 bool watch_dog_enabled = !kIsTargetBuild;
Brian Carlstrom16192862011-09-12 17:50:06 -0700581
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700582
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700583 for (int i = 0; i < argc; i++) {
584 const StringPiece option(argv[i]);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800585 bool log_options = false;
586 if (log_options) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700587 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
588 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700589 if (option.starts_with("--dex-file=")) {
590 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstroma004aa92012-02-08 18:05:09 -0800591 } else if (option.starts_with("--dex-location=")) {
592 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800593 } else if (option.starts_with("--zip-fd=")) {
594 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800595 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800596 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800597 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800598 } else if (option.starts_with("--zip-location=")) {
599 zip_location = option.substr(strlen("--zip-location=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800600 } else if (option.starts_with("--oat-file=")) {
601 oat_filename = option.substr(strlen("--oat-file=")).data();
Brian Carlstrom265091e2013-01-30 14:08:26 -0800602 } else if (option.starts_with("--oat-symbols=")) {
603 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800604 } else if (option.starts_with("--oat-fd=")) {
605 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800606 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800607 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800608 }
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800609 } else if (option == "-g") {
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800610 support_debugging = true;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800611 } else if (option == "--watch-dog") {
612 watch_dog_enabled = true;
613 } else if (option == "--no-watch-dog") {
614 watch_dog_enabled = false;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800615 } else if (option.starts_with("-j")) {
Brian Carlstromb12552a2012-02-04 17:17:31 -0800616 const char* thread_count_str = option.substr(strlen("-j")).data();
Elliott Hughes5523ee02012-02-03 18:18:34 -0800617 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800618 Usage("could not parse -j argument '%s' as an integer", thread_count_str);
Elliott Hughes5523ee02012-02-03 18:18:34 -0800619 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800620 } else if (option.starts_with("--oat-location=")) {
621 oat_location = option.substr(strlen("--oat-location=")).data();
Logan Chien8b977d32012-02-21 19:14:55 +0800622 } else if (option.starts_with("--bitcode=")) {
623 bitcode_filename = option.substr(strlen("--bitcode=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700624 } else if (option.starts_with("--image=")) {
625 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800626 } else if (option.starts_with("--image-classes=")) {
627 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700628 } else if (option.starts_with("--base=")) {
629 const char* image_base_str = option.substr(strlen("--base=")).data();
630 char* end;
631 image_base = strtoul(image_base_str, &end, 16);
632 if (end == image_base_str || *end != '\0') {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800633 Usage("Failed to parse hexadecimal value for option %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700634 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700635 } else if (option.starts_with("--boot-image=")) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800636 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700637 } else if (option.starts_with("--host-prefix=")) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700638 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800639 } else if (option.starts_with("--android-root=")) {
640 android_root = option.substr(strlen("--android-root=")).data();
Ian Rogers49c48942012-03-11 15:15:37 -0700641 } else if (option.starts_with("--instruction-set=")) {
642 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
jeffhao1f71ae82012-05-24 16:08:24 -0700643 if (instruction_set_str == "arm") {
Ian Rogers49c48942012-03-11 15:15:37 -0700644 instruction_set = kThumb2;
jeffhao1f71ae82012-05-24 16:08:24 -0700645 } else if (instruction_set_str == "mips") {
Ian Rogers49c48942012-03-11 15:15:37 -0700646 instruction_set = kMips;
jeffhao1f71ae82012-05-24 16:08:24 -0700647 } else if (instruction_set_str == "x86") {
Ian Rogers49c48942012-03-11 15:15:37 -0700648 instruction_set = kX86;
649 }
buzbeec531cef2012-10-18 07:09:20 -0700650 } else if (option.starts_with("--compiler-backend=")) {
651 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
652 if (backend_str == "Quick") {
653 compiler_backend = kQuick;
buzbeec531cef2012-10-18 07:09:20 -0700654 } else if (backend_str == "Portable") {
655 compiler_backend = kPortable;
656 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800657 } else if (option == "--host") {
658 is_host = true;
jeffhao5d840402011-10-24 17:09:45 -0700659 } else if (option == "--runtime-arg") {
660 if (++i >= argc) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800661 Usage("Missing required argument for --runtime-arg");
jeffhao5d840402011-10-24 17:09:45 -0700662 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800663 if (log_options) {
664 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
665 }
jeffhao5d840402011-10-24 17:09:45 -0700666 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700667 } else {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800668 Usage("unknown argument %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700669 }
670 }
671
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800672 if (oat_filename.empty() && oat_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800673 Usage("Output must be supplied with either --oat-file or --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800674 }
675
676 if (!oat_filename.empty() && oat_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800677 Usage("--oat-file should not be used with --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800678 }
679
Brian Carlstrom265091e2013-01-30 14:08:26 -0800680 if (!oat_symbols.empty() && oat_fd != -1) {
681 Usage("--oat-symbols should not be used with --oat-fd");
682 }
683
684 if (!oat_symbols.empty() && is_host) {
685 Usage("--oat-symbols should not be used with --host");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800686 }
687
Brian Carlstroma004aa92012-02-08 18:05:09 -0800688 if (oat_fd != -1 && !image_filename.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800689 Usage("--oat-fd should not be used with --image");
Brian Carlstrome24fa612011-09-29 00:53:55 -0700690 }
691
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700692 if (host_prefix.get() == NULL) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800693 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
694 if (android_product_out != NULL) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700695 host_prefix.reset(new std::string(android_product_out));
Brian Carlstromb0011262011-12-09 12:17:24 -0800696 }
697 }
698
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800699 if (android_root.empty()) {
700 const char* android_root_env_var = getenv("ANDROID_ROOT");
701 if (android_root_env_var == NULL) {
Brian Carlstrom54d22c22013-03-13 15:14:57 -0700702 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800703 }
704 android_root += android_root_env_var;
705 }
706
Brian Carlstroma004aa92012-02-08 18:05:09 -0800707 bool image = (!image_filename.empty());
Brian Carlstromb0011262011-12-09 12:17:24 -0800708 if (!image && boot_image_filename.empty()) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700709 if (host_prefix.get() == NULL) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800710 boot_image_filename += GetAndroidRoot();
711 } else {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700712 boot_image_filename += *host_prefix.get();
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800713 boot_image_filename += "/system";
714 }
715 boot_image_filename += "/framework/boot.art";
Brian Carlstromb0011262011-12-09 12:17:24 -0800716 }
717 std::string boot_image_option;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800718 if (!boot_image_filename.empty()) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800719 boot_image_option += "-Ximage:";
720 boot_image_option += boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700721 }
722
Brian Carlstromae826982011-11-09 01:33:42 -0800723 if (image_classes_filename != NULL && !image) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800724 Usage("--image-classes should only be used with --image");
Brian Carlstromae826982011-11-09 01:33:42 -0800725 }
726
727 if (image_classes_filename != NULL && !boot_image_option.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800728 Usage("--image-classes should not be used with --boot-image");
Brian Carlstrom78128a62011-09-15 17:21:19 -0700729 }
730
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800731 if (dex_filenames.empty() && zip_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800732 Usage("Input must be supplied with either --dex-file or --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800733 }
734
735 if (!dex_filenames.empty() && zip_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800736 Usage("--dex-file should not be used with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800737 }
738
Brian Carlstroma004aa92012-02-08 18:05:09 -0800739 if (!dex_filenames.empty() && !zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800740 Usage("--dex-file should not be used with --zip-location");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800741 }
742
Brian Carlstroma004aa92012-02-08 18:05:09 -0800743 if (dex_locations.empty()) {
744 for (size_t i = 0; i < dex_filenames.size(); i++) {
745 dex_locations.push_back(dex_filenames[i]);
746 }
747 } else if (dex_locations.size() != dex_filenames.size()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800748 Usage("--dex-location arguments do not match --dex-file arguments");
Brian Carlstroma004aa92012-02-08 18:05:09 -0800749 }
750
751 if (zip_fd != -1 && zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800752 Usage("--zip-location should be supplied with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800753 }
754
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700755 if (boot_image_option.empty()) {
756 if (image_base == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800757 Usage("non-zero --base not specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700758 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700759 }
760
Brian Carlstrom265091e2013-01-30 14:08:26 -0800761 std::string oat_stripped(oat_filename);
762 std::string oat_unstripped;
763 if (!oat_symbols.empty()) {
764 oat_unstripped += oat_symbols;
765 } else {
766 oat_unstripped += oat_filename;
767 }
768
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800769 // Done with usage checks, enable watchdog if requested
770 WatchDog watch_dog(watch_dog_enabled);
771
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800772 // Check early that the result of compilation can be written
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800773 UniquePtr<File> oat_file;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800774 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700775 if (create_file) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800776 oat_file.reset(OS::OpenFile(oat_unstripped.c_str(), true));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800777 if (oat_location.empty()) {
778 oat_location = oat_filename;
779 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800780 } else {
Elliott Hughes76160052012-12-12 16:31:20 -0800781 oat_file.reset(new File(oat_fd, oat_location));
782 oat_file->DisableAutoClose();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800783 }
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800784 if (oat_file.get() == NULL) {
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700785 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
786 return EXIT_FAILURE;
787 }
788 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
789 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800790 return EXIT_FAILURE;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700791 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800792
Brian Carlstroma004aa92012-02-08 18:05:09 -0800793 LOG(INFO) << "dex2oat: " << oat_location;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700794
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700795 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700796 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800797 std::vector<const DexFile*> boot_class_path;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700798 if (boot_image_option.empty()) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700799 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
800 if (failure_count > 0) {
801 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
802 return EXIT_FAILURE;
803 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800804 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700805 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700806 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
807 }
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700808 if (host_prefix.get() != NULL) {
809 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700810 }
jeffhao5d840402011-10-24 17:09:45 -0700811 for (size_t i = 0; i < runtime_args.size(); i++) {
812 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
813 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700814
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700815#if ART_SMALL_MODE
816 options.push_back(std::make_pair("-small", reinterpret_cast<void*>(NULL)));
817#endif // ART_SMALL_MODE
818
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700819 Dex2Oat* p_dex2oat;
Brian Carlstrom96391602013-06-13 19:49:50 -0700820 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700821 support_debugging)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700822 LOG(ERROR) << "Failed to create dex2oat";
823 return EXIT_FAILURE;
824 }
825 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
826 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
827 // give it away now and then switch to a more managable ScopedObjectAccess.
828 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
829 // Whilst we're in native take the opportunity to initialize well known classes.
830 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
831 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700832
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800833 // If --image-classes was specified, calculate the full list of classes to include in the image
Brian Carlstrom96391602013-06-13 19:49:50 -0700834 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800835 if (image_classes_filename != NULL) {
Brian Carlstrom96391602013-06-13 19:49:50 -0700836 image_classes.reset(dex2oat->ReadImageClasses(image_classes_filename));
Brian Carlstromae826982011-11-09 01:33:42 -0800837 if (image_classes.get() == NULL) {
838 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
839 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700840 }
841 }
842
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800843 std::vector<const DexFile*> dex_files;
844 if (boot_image_option.empty()) {
845 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
846 } else {
847 if (dex_filenames.empty()) {
848 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
849 if (zip_archive.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800850 LOG(ERROR) << "Failed to zip from file descriptor for " << zip_location;
Brian Carlstrom2e3d1b22012-01-09 18:01:56 -0800851 return EXIT_FAILURE;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800852 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800853 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800854 if (dex_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800855 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800856 return EXIT_FAILURE;
857 }
858 dex_files.push_back(dex_file);
859 } else {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700860 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
861 if (failure_count > 0) {
862 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
863 return EXIT_FAILURE;
864 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800865 }
866 }
867
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700868 // If we're in small mode, but the program is small, turn off small mode.
869 // It doesn't make a difference for the boot image, so let's skip the check
870 // altogether.
871 if (Runtime::Current()->IsSmallMode() && !image) {
872 size_t num_methods = 0;
873 for (size_t i = 0; i != dex_files.size(); ++i) {
874 const DexFile* dex_file = dex_files[i];
875 CHECK(dex_file != NULL);
876 num_methods += dex_file->NumMethodIds();
877 }
878 if (num_methods <= Runtime::Current()->GetSmallModeMethodThreshold()) {
879 Runtime::Current()->SetSmallMode(false);
880 LOG(INFO) << "Below method threshold, compiling anyways";
881 }
882 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700883
Ian Rogers1212a022013-03-04 10:48:41 -0800884 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
885 host_prefix.get(),
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800886 android_root,
Brian Carlstrom265091e2013-01-30 14:08:26 -0800887 is_host,
Ian Rogers1212a022013-03-04 10:48:41 -0800888 dex_files,
889 oat_file.get(),
890 bitcode_filename,
891 image,
Brian Carlstrom96391602013-06-13 19:49:50 -0700892 image_classes,
Ian Rogers1212a022013-03-04 10:48:41 -0800893 dump_stats,
894 dump_timings));
Brian Carlstromf5822582012-03-19 22:34:31 -0700895
896 if (compiler.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800897 LOG(ERROR) << "Failed to create oat file: " << oat_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700898 return EXIT_FAILURE;
899 }
900
Brian Carlstrom265091e2013-01-30 14:08:26 -0800901 LOG(INFO) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700902
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800903 // Notes on the interleaving of creating the image and oat file to
904 // ensure the references between the two are correct.
905 //
906 // Currently we have a memory layout that looks something like this:
907 //
908 // +--------------+
909 // | image |
910 // +--------------+
911 // | boot oat |
912 // +--------------+
913 // | alloc spaces |
914 // +--------------+
915 //
916 // There are several constraints on the loading of the imag and boot.oat.
917 //
918 // 1. The image is expected to be loaded at an absolute address and
919 // contains Objects with absolute pointers within the image.
920 //
921 // 2. There are absolute pointers from Methods in the image to their
922 // code in the oat.
923 //
924 // 3. There are absolute pointers from the code in the oat to Methods
925 // in the image.
926 //
927 // 4. There are absolute pointers from code in the oat to other code
928 // in the oat.
929 //
930 // To get this all correct, we go through several steps.
931 //
932 // 1. We have already created that oat file above with
933 // CreateOatFile. Originally this was just our own proprietary file
934 // but now it is contained within an ELF dynamic object (aka .so
935 // file). The Compiler returned by CreateOatFile provides
936 // PatchInformation for references to oat code and Methods that need
937 // to be update once we know where the oat file will be located
938 // after the image.
939 //
940 // 2. We create the image file. It needs to know where the oat file
941 // will be loaded after itself. Originally when oat file was simply
942 // memory mapped so we could predict where its contents were based
943 // on the file size. Now that it is an ELF file, we need to inspect
944 // the ELF file to understand the in memory segment layout including
945 // where the oat header is located within. ImageWriter's
946 // PatchOatCodeAndMethods uses the PatchInformation from the
947 // Compiler to touch up absolute references in the oat file.
948 //
949 // 3. We fixup the ELF program headers so that dlopen will try to
950 // load the .so at the desired location at runtime by offsetting the
951 // Elf32_Phdr.p_vaddr values by the desired base address.
952 //
Brian Carlstrom265091e2013-01-30 14:08:26 -0800953 if (image) {
954 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
955 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
956 image_base,
Brian Carlstrom265091e2013-01-30 14:08:26 -0800957 oat_unstripped,
958 oat_location,
959 *compiler.get());
960 Thread::Current()->TransitionFromSuspendedToRunnable();
961 LOG(INFO) << "Image written successfully: " << image_filename;
962 if (!image_creation_success) {
963 return EXIT_FAILURE;
964 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700965 }
966
Brian Carlstrom265091e2013-01-30 14:08:26 -0800967 if (is_host) {
968 return EXIT_SUCCESS;
969 }
970
971 // If we don't want to strip in place, copy from unstripped location to stripped location.
972 // We need to strip after image creation because FixupElf needs to use .strtab.
973 if (oat_unstripped != oat_stripped) {
974 oat_file.reset();
975 UniquePtr<File> in(OS::OpenFile(oat_unstripped.c_str(), false));
976 UniquePtr<File> out(OS::OpenFile(oat_stripped.c_str(), true));
977 size_t buffer_size = 8192;
978 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
979 while (true) {
980 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
981 if (bytes_read <= 0) {
982 break;
983 }
984 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
985 CHECK(write_ok);
986 }
987 oat_file.reset(out.release());
988 LOG(INFO) << "Oat file copied successfully (stripped): " << oat_stripped;
989 }
990
991 // Strip unneeded sections for target
992 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
993 CHECK_EQ(0, seek_actual);
994 compiler->StripElf(oat_file.get());
995
Brian Carlstromae826982011-11-09 01:33:42 -0800996 // We wrote the oat file successfully, and want to keep it.
Brian Carlstrom54d22c22013-03-13 15:14:57 -0700997 LOG(INFO) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700998 return EXIT_SUCCESS;
999}
1000
1001} // namespace art
1002
1003int main(int argc, char** argv) {
1004 return art::dex2oat(argc, argv);
1005}