blob: a2d35e48ade43543e703c4567a4dae3fe94c415f [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"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070029#include "class_linker.h"
30#include "class_loader.h"
31#include "compiler.h"
32#include "image_writer.h"
Ian Rogers6f1dfe42011-12-08 17:28:34 -080033#include "leb128.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070034#include "oat_writer.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
Ian Rogers5e863dd2011-11-02 20:00:10 -070036#include "os.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070037#include "runtime.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "ScopedLocalRef.h"
39#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070040#include "sirt_ref.h"
Elliott Hughesbb551fa2012-01-25 16:35:29 -080041#include "timing_logger.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080042#include "vector_output_stream.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070043#include "well_known_classes.h"
Brian Carlstroma6cc8932012-01-04 14:44:07 -080044#include "zip_archive.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070045
46namespace art {
47
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080048static void UsageErrorV(const char* fmt, va_list ap) {
49 std::string error;
50 StringAppendV(&error, fmt, ap);
51 LOG(ERROR) << error;
52}
53
54static void UsageError(const char* fmt, ...) {
55 va_list ap;
56 va_start(ap, fmt);
57 UsageErrorV(fmt, ap);
58 va_end(ap);
59}
60
61static void Usage(const char* fmt, ...) {
62 va_list ap;
63 va_start(ap, fmt);
64 UsageErrorV(fmt, ap);
65 va_end(ap);
66
67 UsageError("Usage: dex2oat [options]...");
68 UsageError("");
69 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
70 UsageError(" Example: --dex-file=/system/framework/core.jar");
71 UsageError("");
72 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
73 UsageError(" containing a classes.dex file to compile.");
74 UsageError(" Example: --zip-fd=5");
75 UsageError("");
76 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file corresponding");
77 UsageError(" to the file descriptor specified by --zip-fd.");
78 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
79 UsageError("");
80 UsageError(" --oat-file=<file.oat>: specifies the required oat filename.");
81 UsageError(" Example: --oat-file=/system/framework/boot.oat");
82 UsageError("");
83 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
84 UsageError(" to the file descriptor specified by --oat-fd.");
85 UsageError(" Example: --oat-location=/data/art-cache/system@app@Calculator.apk.oat");
86 UsageError("");
Logan Chien8b977d32012-02-21 19:14:55 +080087 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
88 UsageError(" Example: --bitcode=/system/framework/boot.bc");
89 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080090 UsageError(" --image=<file.art>: specifies the output image filename.");
91 UsageError(" Example: --image=/system/framework/boot.art");
92 UsageError("");
93 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
94 UsageError(" Example: --image=frameworks/base/preloaded-classes");
95 UsageError("");
96 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
97 UsageError(" Example: --base=0x50000000");
98 UsageError("");
99 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
100 UsageError(" Example: --boot-image=/system/framework/boot.art");
101 UsageError(" Default: <host-prefix>/system/framework/boot.art");
102 UsageError("");
103 UsageError(" --host-prefix may be used to translate host paths to target paths during");
104 UsageError(" cross compilation.");
105 UsageError(" Example: --host-prefix=out/target/product/crespo");
106 UsageError(" Default: $ANDROID_PRODUCT_OUT");
107 UsageError("");
jeffhao1f71ae82012-05-24 16:08:24 -0700108 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
Ian Rogers49c48942012-03-11 15:15:37 -0700109 UsageError(" set.");
jeffhao1f71ae82012-05-24 16:08:24 -0700110 UsageError(" Example: --instruction-set=x86");
111 UsageError(" Default: arm");
Ian Rogers49c48942012-03-11 15:15:37 -0700112 UsageError("");
buzbeec531cef2012-10-18 07:09:20 -0700113 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
114 UsageError(" set.");
115 UsageError(" Example: --instruction-set=Portable");
116 UsageError(" Default: Quick");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800117 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
118 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
119 UsageError(" Use a separate --runtime-arg switch for each argument.");
120 UsageError(" Example: --runtime-arg -Xms256m");
121 UsageError("");
122 std::cerr << "See log for usage error information\n";
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700123 exit(EXIT_FAILURE);
124}
125
Brian Carlstromae826982011-11-09 01:33:42 -0800126class Dex2Oat {
127 public:
buzbeec531cef2012-10-18 07:09:20 -0700128 static bool Create(Dex2Oat** p_dex2oat, Runtime::Options& options, CompilerBackend compiler_backend,
129 InstructionSet instruction_set, size_t thread_count, bool support_debugging)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700130 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700131 if (!CreateRuntime(options, instruction_set)) {
132 *p_dex2oat = NULL;
133 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800134 }
buzbeec531cef2012-10-18 07:09:20 -0700135 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count,
136 support_debugging);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800138 }
139
140 ~Dex2Oat() {
141 delete runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800142 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) << " (threads: " << thread_count_ << ")";
Brian Carlstromae826982011-11-09 01:33:42 -0800143 }
144
145 // Make a list of descriptors for classes to include in the image
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700146 const std::set<std::string>* GetImageClassDescriptors(const char* image_classes_filename)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700147 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800148 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
149 if (image_classes_file.get() == NULL) {
150 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
151 return NULL;
152 }
153
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800154 // Load all the classes specified in the file
Brian Carlstromae826982011-11-09 01:33:42 -0800155 ClassLinker* class_linker = runtime_->GetClassLinker();
Ian Rogers1f539342012-10-03 21:09:42 -0700156 Thread* self = Thread::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800157 while (image_classes_file->good()) {
158 std::string dot;
159 std::getline(*image_classes_file.get(), dot);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800160 if (StartsWith(dot, "#") || dot.empty()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800161 continue;
162 }
Elliott Hughes95572412011-12-13 18:14:20 -0800163 std::string descriptor(DotToDescriptor(dot.c_str()));
Ian Rogers1f539342012-10-03 21:09:42 -0700164 SirtRef<Class> klass(self, class_linker->FindSystemClass(descriptor.c_str()));
Brian Carlstromae826982011-11-09 01:33:42 -0800165 if (klass.get() == NULL) {
166 LOG(WARNING) << "Failed to find class " << descriptor;
167 Thread::Current()->ClearException();
168 }
169 }
170 image_classes_file->close();
171
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800172 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
173 // exceptions are resolved by the verifier when there is a catch block in an interested method.
174 // Do this here so that exception classes appear to have been specified image classes.
175 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
Ian Rogers1f539342012-10-03 21:09:42 -0700176 SirtRef<Class> java_lang_Throwable(self,
177 class_linker->FindSystemClass("Ljava/lang/Throwable;"));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800178 do {
179 unresolved_exception_types.clear();
180 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
181 &unresolved_exception_types);
182 typedef std::set<std::pair<uint16_t, const DexFile*> >::const_iterator It; // TODO: C++0x auto
183 for (It it = unresolved_exception_types.begin(),
184 end = unresolved_exception_types.end();
185 it != end; ++it) {
186 uint16_t exception_type_idx = it->first;
187 const DexFile* dex_file = it->second;
188 DexCache* dex_cache = class_linker->FindDexCache(*dex_file);
189 ClassLoader* class_loader = NULL;
Ian Rogers1f539342012-10-03 21:09:42 -0700190 SirtRef<Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
191 dex_cache, class_loader));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800192 if (klass.get() == NULL) {
193 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
194 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
195 LOG(FATAL) << "Failed to resolve class " << descriptor;
196 }
Elliott Hughes35be9b12012-05-29 17:59:26 -0700197 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800198 }
199 // Resolving exceptions may load classes that reference more exceptions, iterate until no
200 // more are found
201 } while (!unresolved_exception_types.empty());
202
Brian Carlstromae826982011-11-09 01:33:42 -0800203 // We walk the roots looking for classes so that we'll pick up the
204 // above classes plus any classes them depend on such super
205 // classes, interfaces, and the required ClassLinker roots.
206 UniquePtr<std::set<std::string> > image_classes(new std::set<std::string>());
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800207 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes.get());
Brian Carlstromae826982011-11-09 01:33:42 -0800208 CHECK_NE(image_classes->size(), 0U);
209 return image_classes.release();
210 }
211
Brian Carlstromf5822582012-03-19 22:34:31 -0700212 const Compiler* CreateOatFile(const std::string& boot_image_option,
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700213 const std::string* host_prefix,
Brian Carlstromf5822582012-03-19 22:34:31 -0700214 const std::vector<const DexFile*>& dex_files,
215 File* oat_file,
Logan Chiende08e842012-03-21 00:34:12 +0800216 const std::string& bitcode_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700217 bool image,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700218 const std::set<std::string>* image_classes,
219 bool dump_stats,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700220 bool dump_timings)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800222 // SirtRef and ClassLoader creation needs to come after Runtime::Create
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700223 jobject class_loader = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800224 if (!boot_image_option.empty()) {
225 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromae826982011-11-09 01:33:42 -0800226 std::vector<const DexFile*> class_path_files(dex_files);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800227 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800228 for (size_t i = 0; i < class_path_files.size(); i++) {
229 class_linker->RegisterDexFile(*class_path_files[i]);
230 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700231 ScopedObjectAccessUnchecked soa(Thread::Current());
232 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
233 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
234 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
235 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
236 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800237 }
238
buzbeec531cef2012-10-18 07:09:20 -0700239 UniquePtr<Compiler> compiler(new Compiler(compiler_backend_,
240 instruction_set_,
Brian Carlstromf5822582012-03-19 22:34:31 -0700241 image,
242 thread_count_,
243 support_debugging_,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700244 image_classes,
245 dump_stats,
246 dump_timings));
Logan Chien8b977d32012-02-21 19:14:55 +0800247
buzbeec531cef2012-10-18 07:09:20 -0700248 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)) {
249 compiler->SetBitcodeFileName(bitcode_filename);
250 }
Logan Chien8b977d32012-02-21 19:14:55 +0800251
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700252 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
253
254 compiler->CompileAll(class_loader, dex_files);
255
256 Thread::Current()->TransitionFromSuspendedToRunnable();
Brian Carlstromae826982011-11-09 01:33:42 -0800257
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700258 std::string image_file_location;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700259 uint32_t image_file_location_oat_checksum = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800260 uint32_t image_file_location_oat_data_begin = 0;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700261 Heap* heap = Runtime::Current()->GetHeap();
262 if (heap->GetSpaces().size() > 1) {
263 ImageSpace* image_space = heap->GetImageSpace();
Brian Carlstrom28db0122012-10-18 16:20:41 -0700264 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800265 image_file_location_oat_data_begin = reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700266 image_file_location = image_space->GetImageFilename();
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700267 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
268 image_file_location = image_file_location.substr(host_prefix->size());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700269 }
270 }
271
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800272 std::vector<uint8_t> oat_contents;
273 VectorOutputStream vector_output_stream(oat_file->GetPath(), oat_contents);
274 if (!OatWriter::Create(vector_output_stream,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700275 dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700276 image_file_location_oat_checksum,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800277 image_file_location_oat_data_begin,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700278 image_file_location,
Brian Carlstromf5822582012-03-19 22:34:31 -0700279 *compiler.get())) {
Elliott Hughes76160052012-12-12 16:31:20 -0800280 LOG(ERROR) << "Failed to create oat file " << oat_file->GetPath();
Brian Carlstromf5822582012-03-19 22:34:31 -0700281 return NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800282 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800283
284 if (!compiler->WriteElf(oat_contents, oat_file)) {
285 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
286 return NULL;
287 }
288
Brian Carlstromf5822582012-03-19 22:34:31 -0700289 return compiler.release();
Brian Carlstromae826982011-11-09 01:33:42 -0800290 }
291
Brian Carlstroma004aa92012-02-08 18:05:09 -0800292 bool CreateImageFile(const std::string& image_filename,
Brian Carlstromae826982011-11-09 01:33:42 -0800293 uintptr_t image_base,
294 const std::set<std::string>* image_classes,
295 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700296 const std::string& oat_location,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700297 const Compiler& compiler)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700298 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800299 uintptr_t oat_data_begin;
300 {
301 // ImageWriter is scoped so it can free memory before doing FixupElf
302 ImageWriter image_writer(image_classes);
303 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location, compiler)) {
304 LOG(ERROR) << "Failed to create image file " << image_filename;
305 return false;
306 }
307 oat_data_begin = image_writer.GetOatDataBegin();
308 }
309
310 LG << "dex2oat CreateImageFile opening : " << oat_filename;
311 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
312 LG << "dex2oat CreateImageFile opened : " << oat_filename;
313 if (oat_file.get() == NULL) {
314 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800315 return false;
316 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800317 if (!compiler.FixupElf(oat_file.get(), oat_data_begin)) {
318 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
319 return false;
320 }
321 LOG(ERROR) << "ELF file fixed up successfully: " << oat_file->GetPath();
Brian Carlstromae826982011-11-09 01:33:42 -0800322 return true;
323 }
324
325 private:
buzbeec531cef2012-10-18 07:09:20 -0700326 explicit Dex2Oat(Runtime* runtime, CompilerBackend compiler_backend, InstructionSet instruction_set,
327 size_t thread_count, bool support_debugging)
328 : compiler_backend_(compiler_backend),
329 instruction_set_(instruction_set),
Ian Rogers49c48942012-03-11 15:15:37 -0700330 runtime_(runtime),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800331 thread_count_(thread_count),
332 support_debugging_(support_debugging),
333 start_ns_(NanoTime()) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800334 }
Brian Carlstromae826982011-11-09 01:33:42 -0800335
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700336 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700337 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700338 if (!Runtime::Create(options, false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800339 LOG(ERROR) << "Failed to create runtime";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700340 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800341 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 Runtime* runtime = Runtime::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800343 // if we loaded an existing image, we will reuse values from the image roots.
344 if (!runtime->HasJniDlsymLookupStub()) {
Ian Rogers49c48942012-03-11 15:15:37 -0700345 runtime->SetJniDlsymLookupStub(Compiler::CreateJniDlsymLookupStub(instruction_set));
Brian Carlstromae826982011-11-09 01:33:42 -0800346 }
347 if (!runtime->HasAbstractMethodErrorStubArray()) {
Ian Rogers49c48942012-03-11 15:15:37 -0700348 runtime->SetAbstractMethodErrorStubArray(Compiler::CreateAbstractMethodErrorStub(instruction_set));
Brian Carlstromae826982011-11-09 01:33:42 -0800349 }
350 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
351 Runtime::TrampolineType type = Runtime::TrampolineType(i);
352 if (!runtime->HasResolutionStubArray(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700353 runtime->SetResolutionStubArray(Compiler::CreateResolutionStub(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800354 }
355 }
Ian Rogers19846512012-02-24 11:42:47 -0800356 if (!runtime->HasResolutionMethod()) {
357 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
358 }
Brian Carlstromae826982011-11-09 01:33:42 -0800359 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
360 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
361 if (!runtime->HasCalleeSaveMethod(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700362 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800363 }
364 }
Ian Rogers19846512012-02-24 11:42:47 -0800365 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700366 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800367 }
368
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800369 static void ResolveExceptionsForMethod(MethodHelper* mh,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700371 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800372 const DexFile::CodeItem* code_item = mh->GetCodeItem();
373 if (code_item == NULL) {
374 return; // native or abstract method
375 }
376 if (code_item->tries_size_ == 0) {
377 return; // nothing to process
378 }
379 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
380 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
381 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
382 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
383 bool has_catch_all = false;
384 if (encoded_catch_handler_size <= 0) {
385 encoded_catch_handler_size = -encoded_catch_handler_size;
386 has_catch_all = true;
387 }
388 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
389 uint16_t encoded_catch_handler_handlers_type_idx =
390 DecodeUnsignedLeb128(&encoded_catch_handler_list);
391 // Add to set of types to resolve if not already in the dex cache resolved types
392 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
393 exceptions_to_resolve.insert(
394 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
395 &mh->GetDexFile()));
396 }
397 // ignore address associated with catch handler
398 DecodeUnsignedLeb128(&encoded_catch_handler_list);
399 }
400 if (has_catch_all) {
401 // ignore catch all address
402 DecodeUnsignedLeb128(&encoded_catch_handler_list);
403 }
404 }
405 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406
407 static bool ResolveCatchBlockExceptionsClassVisitor(Class* c, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700408 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800409 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
410 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
411 MethodHelper mh;
412 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700413 AbstractMethod* m = c->GetVirtualMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800414 mh.ChangeMethod(m);
415 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
416 }
417 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700418 AbstractMethod* m = c->GetDirectMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800419 mh.ChangeMethod(m);
420 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
421 }
422 return true;
423 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424
425 static bool RecordImageClassesVisitor(Class* klass, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700426 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800427 std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
428 if (klass->IsArrayClass() || klass->IsPrimitive()) {
Jesse Wilson254db0f2011-11-16 16:44:11 -0500429 return true;
430 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800431 image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800432 return true;
Jesse Wilson254db0f2011-11-16 16:44:11 -0500433 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500434
Brian Carlstromae826982011-11-09 01:33:42 -0800435 // Appends to dex_files any elements of class_path that it doesn't already
436 // contain. This will open those dex files as necessary.
437 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
438 std::vector<std::string> parsed;
439 Split(class_path, ':', parsed);
440 for (size_t i = 0; i < parsed.size(); ++i) {
441 if (DexFilesContains(dex_files, parsed[i])) {
442 continue;
443 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800444 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
Brian Carlstromae826982011-11-09 01:33:42 -0800445 if (dex_file == NULL) {
446 LOG(WARNING) << "Failed to open dex file " << parsed[i];
447 } else {
448 dex_files.push_back(dex_file);
449 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500450 }
451 }
Brian Carlstromae826982011-11-09 01:33:42 -0800452
453 // Returns true if dex_files has a dex with the named location.
454 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
455 for (size_t i = 0; i < dex_files.size(); ++i) {
456 if (dex_files[i]->GetLocation() == location) {
457 return true;
458 }
459 }
460 return false;
461 }
462
buzbeec531cef2012-10-18 07:09:20 -0700463 const CompilerBackend compiler_backend_;
464
Ian Rogers49c48942012-03-11 15:15:37 -0700465 const InstructionSet instruction_set_;
Brian Carlstromae826982011-11-09 01:33:42 -0800466
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800467 Runtime* runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800468 size_t thread_count_;
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800469 bool support_debugging_;
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800470 uint64_t start_ns_;
471
Brian Carlstromae826982011-11-09 01:33:42 -0800472 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
473};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500474
Elliott Hughes72395bf2012-04-24 13:45:26 -0700475static bool ParseInt(const char* in, int* out) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800476 char* end;
477 int result = strtol(in, &end, 10);
478 if (in == end || *end != '\0') {
479 return false;
480 }
481 *out = result;
482 return true;
483}
484
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700485static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
486 const std::vector<const char*>& dex_locations,
487 std::vector<const DexFile*>& dex_files) {
488 size_t failure_count = 0;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800489 for (size_t i = 0; i < dex_filenames.size(); i++) {
490 const char* dex_filename = dex_filenames[i];
Brian Carlstroma004aa92012-02-08 18:05:09 -0800491 const char* dex_location = dex_locations[i];
492 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800493 if (dex_file == NULL) {
jeffhao60f83e32012-02-13 17:16:30 -0800494 LOG(WARNING) << "could not open .dex from file " << dex_filename;
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700495 ++failure_count;
jeffhao60f83e32012-02-13 17:16:30 -0800496 } else {
497 dex_files.push_back(dex_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800498 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800499 }
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700500 return failure_count;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800501}
502
Brian Carlstrombcc29262012-11-02 11:36:03 -0700503// The primary goal of the watchdog is to prevent stuck build servers
504// during development when fatal aborts lead to a cascade of failures
505// that result in a deadlock.
506class WatchDog {
507
508// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
509#undef CHECK_PTHREAD_CALL
510#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
511 do { \
512 int rc = call args; \
513 if (rc != 0) { \
514 errno = rc; \
515 std::string message(# call); \
516 message += " failed for "; \
517 message += reason; \
518 Die(message); \
519 } \
520 } while (false)
521
522 public:
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800523 WatchDog(bool is_watch_dog_enabled) {
524 is_watch_dog_enabled_ = is_watch_dog_enabled;
525 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700526 return;
527 }
528 shutting_down_ = false;
529 const char* reason = "dex2oat watch dog thread startup";
530 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
531 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
532 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
533 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
534 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
535 }
536 ~WatchDog() {
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800537 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700538 return;
539 }
540 const char* reason = "dex2oat watch dog thread shutdown";
541 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
542 shutting_down_ = true;
543 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
544 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
545
546 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
547
548 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
549 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
550 }
551
552 private:
553 static void* CallBack(void* arg) {
554 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
555 self->Wait();
556 return NULL;
557 }
558
559 static void Die(const std::string& message) {
560 // TODO: Switch to LOG(FATAL) when we can guarantee it won't prevent shutdown in error cases
561 fprintf(stderr, "%s\n", message.c_str());
562 exit(1);
563 }
564
565 void Wait() {
566 int64_t ms = kWatchDogTimeoutSeconds * 1000;
567 int32_t ns = 0;
568 timespec ts;
569 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
570 const char* reason = "dex2oat watch dog thread waiting";
571 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
572 while (!shutting_down_) {
573 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &ts));
574 if (rc == ETIMEDOUT) {
575 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
576 kWatchDogTimeoutSeconds));
577 Die(message.c_str());
578 }
579 if (rc != 0) {
580 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
581 strerror(errno)));
582 Die(message.c_str());
583 }
584 }
585 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
586 }
587
Brian Carlstrombcc29262012-11-02 11:36:03 -0700588#ifdef ART_USE_LLVM_COMPILER
589 static const unsigned int kWatchDogTimeoutSeconds = 20 * 60; // 15 minutes + buffer
590#else
591 static const unsigned int kWatchDogTimeoutSeconds = 2 * 60; // 1 minute + buffer
592#endif
593
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800594 bool is_watch_dog_enabled_;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700595 bool shutting_down_;
596 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases
597 pthread_mutex_t mutex_;
598 pthread_cond_t cond_;
599 pthread_attr_t attr_;
600 pthread_t pthread_;
601};
602
Elliott Hughes72395bf2012-04-24 13:45:26 -0700603static int dex2oat(int argc, char** argv) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700604 InitLogging(argv);
Elliott Hughes72395bf2012-04-24 13:45:26 -0700605
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700606 // Skip over argv[0].
607 argv++;
608 argc--;
609
610 if (argc == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800611 Usage("no arguments specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700612 }
613
614 std::vector<const char*> dex_filenames;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800615 std::vector<const char*> dex_locations;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800616 int zip_fd = -1;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800617 std::string zip_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700618 std::string oat_filename;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800619 std::string oat_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800620 int oat_fd = -1;
Logan Chien8b977d32012-02-21 19:14:55 +0800621 std::string bitcode_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800622 const char* image_classes_filename = NULL;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800623 std::string image_filename;
Brian Carlstromb0011262011-12-09 12:17:24 -0800624 std::string boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700625 uintptr_t image_base = 0;
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700626 UniquePtr<std::string> host_prefix;
jeffhao5d840402011-10-24 17:09:45 -0700627 std::vector<const char*> runtime_args;
Elliott Hughes5c599942012-06-13 16:45:05 -0700628 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800629 bool support_debugging = false;
buzbeec531cef2012-10-18 07:09:20 -0700630#if defined(ART_USE_PORTABLE_COMPILER)
631 CompilerBackend compiler_backend = kPortable;
632#elif defined(ART_USE_LLVM_COMPILER)
633 CompilerBackend compiler_backend = kIceland;
634#else
635 CompilerBackend compiler_backend = kQuick;
636#endif
jeffhao9ad4f222012-05-30 18:51:19 -0700637#if defined(__arm__)
Ian Rogers49c48942012-03-11 15:15:37 -0700638 InstructionSet instruction_set = kThumb2;
jeffhao9ad4f222012-05-30 18:51:19 -0700639#elif defined(__i386__)
640 InstructionSet instruction_set = kX86;
641#elif defined(__mips__)
642 InstructionSet instruction_set = kMips;
643#else
644#error "Unsupported architecture"
645#endif
Elliott Hughes67d92002012-03-26 15:08:51 -0700646 bool dump_stats = kIsDebugBuild;
647 bool dump_timings = kIsDebugBuild;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800648 bool watch_dog_enabled = !kIsTargetBuild;
Brian Carlstrom16192862011-09-12 17:50:06 -0700649
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700650 for (int i = 0; i < argc; i++) {
651 const StringPiece option(argv[i]);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800652 bool log_options = false;
653 if (log_options) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700654 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
655 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700656 if (option.starts_with("--dex-file=")) {
657 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstroma004aa92012-02-08 18:05:09 -0800658 } else if (option.starts_with("--dex-location=")) {
659 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800660 } else if (option.starts_with("--zip-fd=")) {
661 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800662 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800663 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800664 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800665 } else if (option.starts_with("--zip-location=")) {
666 zip_location = option.substr(strlen("--zip-location=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800667 } else if (option.starts_with("--oat-file=")) {
668 oat_filename = option.substr(strlen("--oat-file=")).data();
669 } else if (option.starts_with("--oat-fd=")) {
670 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800671 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800672 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800673 }
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800674 } else if (option == "-g") {
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800675 support_debugging = true;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800676 } else if (option == "--watch-dog") {
677 watch_dog_enabled = true;
678 } else if (option == "--no-watch-dog") {
679 watch_dog_enabled = false;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800680 } else if (option.starts_with("-j")) {
Brian Carlstromb12552a2012-02-04 17:17:31 -0800681 const char* thread_count_str = option.substr(strlen("-j")).data();
Elliott Hughes5523ee02012-02-03 18:18:34 -0800682 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800683 Usage("could not parse -j argument '%s' as an integer", thread_count_str);
Elliott Hughes5523ee02012-02-03 18:18:34 -0800684 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800685 } else if (option.starts_with("--oat-location=")) {
686 oat_location = option.substr(strlen("--oat-location=")).data();
Logan Chien8b977d32012-02-21 19:14:55 +0800687 } else if (option.starts_with("--bitcode=")) {
688 bitcode_filename = option.substr(strlen("--bitcode=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700689 } else if (option.starts_with("--image=")) {
690 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800691 } else if (option.starts_with("--image-classes=")) {
692 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700693 } else if (option.starts_with("--base=")) {
694 const char* image_base_str = option.substr(strlen("--base=")).data();
695 char* end;
696 image_base = strtoul(image_base_str, &end, 16);
697 if (end == image_base_str || *end != '\0') {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800698 Usage("Failed to parse hexadecimal value for option %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700699 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700700 } else if (option.starts_with("--boot-image=")) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800701 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700702 } else if (option.starts_with("--host-prefix=")) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700703 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
Ian Rogers49c48942012-03-11 15:15:37 -0700704 } else if (option.starts_with("--instruction-set=")) {
705 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
jeffhao1f71ae82012-05-24 16:08:24 -0700706 if (instruction_set_str == "arm") {
Ian Rogers49c48942012-03-11 15:15:37 -0700707 instruction_set = kThumb2;
jeffhao1f71ae82012-05-24 16:08:24 -0700708 } else if (instruction_set_str == "mips") {
Ian Rogers49c48942012-03-11 15:15:37 -0700709 instruction_set = kMips;
jeffhao1f71ae82012-05-24 16:08:24 -0700710 } else if (instruction_set_str == "x86") {
Ian Rogers49c48942012-03-11 15:15:37 -0700711 instruction_set = kX86;
712 }
buzbeec531cef2012-10-18 07:09:20 -0700713 } else if (option.starts_with("--compiler-backend=")) {
714 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
715 if (backend_str == "Quick") {
716 compiler_backend = kQuick;
717 } else if (backend_str == "QuickGBC") {
718 compiler_backend = kQuickGBC;
719 } else if (backend_str == "Iceland") {
720 // TODO: remove this when Portable/Iceland merge complete
721 compiler_backend = kIceland;
722 } else if (backend_str == "Portable") {
723 compiler_backend = kPortable;
724 }
jeffhao5d840402011-10-24 17:09:45 -0700725 } else if (option == "--runtime-arg") {
726 if (++i >= argc) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800727 Usage("Missing required argument for --runtime-arg");
jeffhao5d840402011-10-24 17:09:45 -0700728 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800729 if (log_options) {
730 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
731 }
jeffhao5d840402011-10-24 17:09:45 -0700732 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700733 } else {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800734 Usage("unknown argument %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700735 }
736 }
737
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800738 if (oat_filename.empty() && oat_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800739 Usage("Output must be supplied with either --oat-file or --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800740 }
741
742 if (!oat_filename.empty() && oat_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800743 Usage("--oat-file should not be used with --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800744 }
745
746 if (!oat_filename.empty() && oat_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800747 Usage("--oat-file should not be used with --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800748 }
749
Brian Carlstroma004aa92012-02-08 18:05:09 -0800750 if (oat_fd != -1 && !image_filename.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800751 Usage("--oat-fd should not be used with --image");
Brian Carlstrome24fa612011-09-29 00:53:55 -0700752 }
753
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700754 if (host_prefix.get() == NULL) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800755 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
756 if (android_product_out != NULL) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700757 host_prefix.reset(new std::string(android_product_out));
Brian Carlstromb0011262011-12-09 12:17:24 -0800758 }
759 }
760
Brian Carlstroma004aa92012-02-08 18:05:09 -0800761 bool image = (!image_filename.empty());
Brian Carlstromb0011262011-12-09 12:17:24 -0800762 if (!image && boot_image_filename.empty()) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700763 if (host_prefix.get() == NULL) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800764 boot_image_filename += GetAndroidRoot();
765 } else {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700766 boot_image_filename += *host_prefix.get();
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800767 boot_image_filename += "/system";
768 }
769 boot_image_filename += "/framework/boot.art";
Brian Carlstromb0011262011-12-09 12:17:24 -0800770 }
771 std::string boot_image_option;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800772 if (!boot_image_filename.empty()) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800773 boot_image_option += "-Ximage:";
774 boot_image_option += boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700775 }
776
Brian Carlstromae826982011-11-09 01:33:42 -0800777 if (image_classes_filename != NULL && !image) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800778 Usage("--image-classes should only be used with --image");
Brian Carlstromae826982011-11-09 01:33:42 -0800779 }
780
781 if (image_classes_filename != NULL && !boot_image_option.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800782 Usage("--image-classes should not be used with --boot-image");
Brian Carlstrom78128a62011-09-15 17:21:19 -0700783 }
784
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800785 if (dex_filenames.empty() && zip_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800786 Usage("Input must be supplied with either --dex-file or --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800787 }
788
789 if (!dex_filenames.empty() && zip_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800790 Usage("--dex-file should not be used with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800791 }
792
Brian Carlstroma004aa92012-02-08 18:05:09 -0800793 if (!dex_filenames.empty() && !zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800794 Usage("--dex-file should not be used with --zip-location");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800795 }
796
Brian Carlstroma004aa92012-02-08 18:05:09 -0800797 if (dex_locations.empty()) {
798 for (size_t i = 0; i < dex_filenames.size(); i++) {
799 dex_locations.push_back(dex_filenames[i]);
800 }
801 } else if (dex_locations.size() != dex_filenames.size()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800802 Usage("--dex-location arguments do not match --dex-file arguments");
Brian Carlstroma004aa92012-02-08 18:05:09 -0800803 }
804
805 if (zip_fd != -1 && zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800806 Usage("--zip-location should be supplied with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800807 }
808
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700809 if (boot_image_option.empty()) {
810 if (image_base == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800811 Usage("non-zero --base not specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700812 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700813 }
814
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800815 // Done with usage checks, enable watchdog if requested
816 WatchDog watch_dog(watch_dog_enabled);
817
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800818 // Check early that the result of compilation can be written
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800819 UniquePtr<File> oat_file;
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700820 bool create_file = !oat_filename.empty(); // as opposed to using open file descriptor
821 if (create_file) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800822 oat_file.reset(OS::OpenFile(oat_filename.c_str(), true));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800823 if (oat_location.empty()) {
824 oat_location = oat_filename;
825 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800826 } else {
Elliott Hughes76160052012-12-12 16:31:20 -0800827 oat_file.reset(new File(oat_fd, oat_location));
828 oat_file->DisableAutoClose();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800829 }
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800830 if (oat_file.get() == NULL) {
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700831 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
832 return EXIT_FAILURE;
833 }
834 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
835 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800836 return EXIT_FAILURE;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700837 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800838
Brian Carlstroma004aa92012-02-08 18:05:09 -0800839 LOG(INFO) << "dex2oat: " << oat_location;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700840
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700841 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700842 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800843 std::vector<const DexFile*> boot_class_path;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700844 if (boot_image_option.empty()) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700845 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
846 if (failure_count > 0) {
847 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
848 return EXIT_FAILURE;
849 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800850 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700851 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700852 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
853 }
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700854 if (host_prefix.get() != NULL) {
855 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700856 }
jeffhao5d840402011-10-24 17:09:45 -0700857 for (size_t i = 0; i < runtime_args.size(); i++) {
858 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
859 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700860
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700861 Dex2Oat* p_dex2oat;
buzbeec531cef2012-10-18 07:09:20 -0700862 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count, support_debugging)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700863 LOG(ERROR) << "Failed to create dex2oat";
864 return EXIT_FAILURE;
865 }
866 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
867 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
868 // give it away now and then switch to a more managable ScopedObjectAccess.
869 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
870 // Whilst we're in native take the opportunity to initialize well known classes.
871 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
872 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700873
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800874 // If --image-classes was specified, calculate the full list of classes to include in the image
Brian Carlstromae826982011-11-09 01:33:42 -0800875 UniquePtr<const std::set<std::string> > image_classes(NULL);
876 if (image_classes_filename != NULL) {
877 image_classes.reset(dex2oat->GetImageClassDescriptors(image_classes_filename));
878 if (image_classes.get() == NULL) {
879 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
880 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700881 }
882 }
883
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800884 std::vector<const DexFile*> dex_files;
885 if (boot_image_option.empty()) {
886 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
887 } else {
888 if (dex_filenames.empty()) {
889 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
890 if (zip_archive.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800891 LOG(ERROR) << "Failed to zip from file descriptor for " << zip_location;
Brian Carlstrom2e3d1b22012-01-09 18:01:56 -0800892 return EXIT_FAILURE;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800893 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800894 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800895 if (dex_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800896 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800897 return EXIT_FAILURE;
898 }
899 dex_files.push_back(dex_file);
900 } else {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700901 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
902 if (failure_count > 0) {
903 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
904 return EXIT_FAILURE;
905 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800906 }
907 }
908
Brian Carlstromf5822582012-03-19 22:34:31 -0700909 UniquePtr<const Compiler> compiler(dex2oat->CreateOatFile(boot_image_option,
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700910 host_prefix.get(),
Brian Carlstromf5822582012-03-19 22:34:31 -0700911 dex_files,
912 oat_file.get(),
Brian Carlstromf5822582012-03-19 22:34:31 -0700913 bitcode_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700914 image,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700915 image_classes.get(),
916 dump_stats,
917 dump_timings));
Brian Carlstromf5822582012-03-19 22:34:31 -0700918
919 if (compiler.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800920 LOG(ERROR) << "Failed to create oat file: " << oat_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700921 return EXIT_FAILURE;
922 }
923
Brian Carlstromae826982011-11-09 01:33:42 -0800924 if (!image) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800925 LOG(INFO) << "Oat file written successfully: " << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700926 return EXIT_SUCCESS;
927 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700928
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800929 // Notes on the interleaving of creating the image and oat file to
930 // ensure the references between the two are correct.
931 //
932 // Currently we have a memory layout that looks something like this:
933 //
934 // +--------------+
935 // | image |
936 // +--------------+
937 // | boot oat |
938 // +--------------+
939 // | alloc spaces |
940 // +--------------+
941 //
942 // There are several constraints on the loading of the imag and boot.oat.
943 //
944 // 1. The image is expected to be loaded at an absolute address and
945 // contains Objects with absolute pointers within the image.
946 //
947 // 2. There are absolute pointers from Methods in the image to their
948 // code in the oat.
949 //
950 // 3. There are absolute pointers from the code in the oat to Methods
951 // in the image.
952 //
953 // 4. There are absolute pointers from code in the oat to other code
954 // in the oat.
955 //
956 // To get this all correct, we go through several steps.
957 //
958 // 1. We have already created that oat file above with
959 // CreateOatFile. Originally this was just our own proprietary file
960 // but now it is contained within an ELF dynamic object (aka .so
961 // file). The Compiler returned by CreateOatFile provides
962 // PatchInformation for references to oat code and Methods that need
963 // to be update once we know where the oat file will be located
964 // after the image.
965 //
966 // 2. We create the image file. It needs to know where the oat file
967 // will be loaded after itself. Originally when oat file was simply
968 // memory mapped so we could predict where its contents were based
969 // on the file size. Now that it is an ELF file, we need to inspect
970 // the ELF file to understand the in memory segment layout including
971 // where the oat header is located within. ImageWriter's
972 // PatchOatCodeAndMethods uses the PatchInformation from the
973 // Compiler to touch up absolute references in the oat file.
974 //
975 // 3. We fixup the ELF program headers so that dlopen will try to
976 // load the .so at the desired location at runtime by offsetting the
977 // Elf32_Phdr.p_vaddr values by the desired base address.
978 //
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700979 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
980 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
981 image_base,
982 image_classes.get(),
983 oat_filename,
984 oat_location,
985 *compiler.get());
986 Thread::Current()->TransitionFromSuspendedToRunnable();
987 if (!image_creation_success) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700988 return EXIT_FAILURE;
989 }
990
Brian Carlstromae826982011-11-09 01:33:42 -0800991 // We wrote the oat file successfully, and want to keep it.
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800992 LOG(INFO) << "Oat file written successfully: " << oat_filename;
993 LOG(INFO) << "Image written successfully: " << image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700994 return EXIT_SUCCESS;
995}
996
997} // namespace art
998
999int main(int argc, char** argv) {
1000 return art::dex2oat(argc, argv);
1001}