blob: bc38bdcfc9bbd57a68d53cda19e280416881a0d9 [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"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070030#include "compiler.h"
31#include "image_writer.h"
Ian Rogers6f1dfe42011-12-08 17:28:34 -080032#include "leb128.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "mirror/abstract_method-inl.h"
34#include "mirror/class-inl.h"
35#include "mirror/class_loader.h"
36#include "mirror/object-inl.h"
37#include "mirror/object_array-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070038#include "oat_writer.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080039#include "object_utils.h"
Ian Rogers5e863dd2011-11-02 20:00:10 -070040#include "os.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070041#include "runtime.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070042#include "ScopedLocalRef.h"
43#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070044#include "sirt_ref.h"
Elliott Hughesbb551fa2012-01-25 16:35:29 -080045#include "timing_logger.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080046#include "vector_output_stream.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070047#include "well_known_classes.h"
Brian Carlstroma6cc8932012-01-04 14:44:07 -080048#include "zip_archive.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070049
50namespace art {
51
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080052static void UsageErrorV(const char* fmt, va_list ap) {
53 std::string error;
54 StringAppendV(&error, fmt, ap);
55 LOG(ERROR) << error;
56}
57
58static void UsageError(const char* fmt, ...) {
59 va_list ap;
60 va_start(ap, fmt);
61 UsageErrorV(fmt, ap);
62 va_end(ap);
63}
64
65static void Usage(const char* fmt, ...) {
66 va_list ap;
67 va_start(ap, fmt);
68 UsageErrorV(fmt, ap);
69 va_end(ap);
70
71 UsageError("Usage: dex2oat [options]...");
72 UsageError("");
73 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
74 UsageError(" Example: --dex-file=/system/framework/core.jar");
75 UsageError("");
76 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
77 UsageError(" containing a classes.dex file to compile.");
78 UsageError(" Example: --zip-fd=5");
79 UsageError("");
80 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file corresponding");
81 UsageError(" to the file descriptor specified by --zip-fd.");
82 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
83 UsageError("");
84 UsageError(" --oat-file=<file.oat>: specifies the required oat filename.");
85 UsageError(" Example: --oat-file=/system/framework/boot.oat");
86 UsageError("");
87 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
88 UsageError(" to the file descriptor specified by --oat-fd.");
89 UsageError(" Example: --oat-location=/data/art-cache/system@app@Calculator.apk.oat");
90 UsageError("");
Logan Chien8b977d32012-02-21 19:14:55 +080091 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
92 UsageError(" Example: --bitcode=/system/framework/boot.bc");
93 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080094 UsageError(" --image=<file.art>: specifies the output image filename.");
95 UsageError(" Example: --image=/system/framework/boot.art");
96 UsageError("");
97 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
98 UsageError(" Example: --image=frameworks/base/preloaded-classes");
99 UsageError("");
100 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
101 UsageError(" Example: --base=0x50000000");
102 UsageError("");
103 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
104 UsageError(" Example: --boot-image=/system/framework/boot.art");
105 UsageError(" Default: <host-prefix>/system/framework/boot.art");
106 UsageError("");
107 UsageError(" --host-prefix may be used to translate host paths to target paths during");
108 UsageError(" cross compilation.");
109 UsageError(" Example: --host-prefix=out/target/product/crespo");
110 UsageError(" Default: $ANDROID_PRODUCT_OUT");
111 UsageError("");
jeffhao1f71ae82012-05-24 16:08:24 -0700112 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
Ian Rogers49c48942012-03-11 15:15:37 -0700113 UsageError(" set.");
jeffhao1f71ae82012-05-24 16:08:24 -0700114 UsageError(" Example: --instruction-set=x86");
115 UsageError(" Default: arm");
Ian Rogers49c48942012-03-11 15:15:37 -0700116 UsageError("");
buzbeec531cef2012-10-18 07:09:20 -0700117 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
118 UsageError(" set.");
119 UsageError(" Example: --instruction-set=Portable");
120 UsageError(" Default: Quick");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800121 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
122 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
123 UsageError(" Use a separate --runtime-arg switch for each argument.");
124 UsageError(" Example: --runtime-arg -Xms256m");
125 UsageError("");
126 std::cerr << "See log for usage error information\n";
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700127 exit(EXIT_FAILURE);
128}
129
Brian Carlstromae826982011-11-09 01:33:42 -0800130class Dex2Oat {
131 public:
buzbeec531cef2012-10-18 07:09:20 -0700132 static bool Create(Dex2Oat** p_dex2oat, Runtime::Options& options, CompilerBackend compiler_backend,
133 InstructionSet instruction_set, size_t thread_count, bool support_debugging)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700134 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700135 if (!CreateRuntime(options, instruction_set)) {
136 *p_dex2oat = NULL;
137 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800138 }
buzbeec531cef2012-10-18 07:09:20 -0700139 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count,
140 support_debugging);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800142 }
143
144 ~Dex2Oat() {
145 delete runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800146 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) << " (threads: " << thread_count_ << ")";
Brian Carlstromae826982011-11-09 01:33:42 -0800147 }
148
149 // Make a list of descriptors for classes to include in the image
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700150 const std::set<std::string>* GetImageClassDescriptors(const char* image_classes_filename)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700151 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800152 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
153 if (image_classes_file.get() == NULL) {
154 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
155 return NULL;
156 }
157
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800158 // Load all the classes specified in the file
Brian Carlstromae826982011-11-09 01:33:42 -0800159 ClassLinker* class_linker = runtime_->GetClassLinker();
Ian Rogers1f539342012-10-03 21:09:42 -0700160 Thread* self = Thread::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800161 while (image_classes_file->good()) {
162 std::string dot;
163 std::getline(*image_classes_file.get(), dot);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800164 if (StartsWith(dot, "#") || dot.empty()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800165 continue;
166 }
Elliott Hughes95572412011-12-13 18:14:20 -0800167 std::string descriptor(DotToDescriptor(dot.c_str()));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800168 SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(descriptor.c_str()));
Brian Carlstromae826982011-11-09 01:33:42 -0800169 if (klass.get() == NULL) {
170 LOG(WARNING) << "Failed to find class " << descriptor;
171 Thread::Current()->ClearException();
172 }
173 }
174 image_classes_file->close();
175
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800176 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
177 // exceptions are resolved by the verifier when there is a catch block in an interested method.
178 // Do this here so that exception classes appear to have been specified image classes.
179 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800180 SirtRef<mirror::Class> java_lang_Throwable(self,
Ian Rogers1f539342012-10-03 21:09:42 -0700181 class_linker->FindSystemClass("Ljava/lang/Throwable;"));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800182 do {
183 unresolved_exception_types.clear();
184 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
185 &unresolved_exception_types);
186 typedef std::set<std::pair<uint16_t, const DexFile*> >::const_iterator It; // TODO: C++0x auto
187 for (It it = unresolved_exception_types.begin(),
188 end = unresolved_exception_types.end();
189 it != end; ++it) {
190 uint16_t exception_type_idx = it->first;
191 const DexFile* dex_file = it->second;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800192 mirror::DexCache* dex_cache = class_linker->FindDexCache(*dex_file);
193 mirror:: ClassLoader* class_loader = NULL;
194 SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
195 dex_cache, class_loader));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800196 if (klass.get() == NULL) {
197 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
198 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
199 LOG(FATAL) << "Failed to resolve class " << descriptor;
200 }
Elliott Hughes35be9b12012-05-29 17:59:26 -0700201 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800202 }
203 // Resolving exceptions may load classes that reference more exceptions, iterate until no
204 // more are found
205 } while (!unresolved_exception_types.empty());
206
Brian Carlstromae826982011-11-09 01:33:42 -0800207 // We walk the roots looking for classes so that we'll pick up the
208 // above classes plus any classes them depend on such super
209 // classes, interfaces, and the required ClassLinker roots.
210 UniquePtr<std::set<std::string> > image_classes(new std::set<std::string>());
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800211 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes.get());
Brian Carlstromae826982011-11-09 01:33:42 -0800212 CHECK_NE(image_classes->size(), 0U);
213 return image_classes.release();
214 }
215
Brian Carlstromf5822582012-03-19 22:34:31 -0700216 const Compiler* CreateOatFile(const std::string& boot_image_option,
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700217 const std::string* host_prefix,
Brian Carlstromf5822582012-03-19 22:34:31 -0700218 const std::vector<const DexFile*>& dex_files,
219 File* oat_file,
Logan Chiende08e842012-03-21 00:34:12 +0800220 const std::string& bitcode_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700221 bool image,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700222 const std::set<std::string>* image_classes,
223 bool dump_stats,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 bool dump_timings)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700225 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800226 // SirtRef and ClassLoader creation needs to come after Runtime::Create
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700227 jobject class_loader = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800228 if (!boot_image_option.empty()) {
229 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromae826982011-11-09 01:33:42 -0800230 std::vector<const DexFile*> class_path_files(dex_files);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800231 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800232 for (size_t i = 0; i < class_path_files.size(); i++) {
233 class_linker->RegisterDexFile(*class_path_files[i]);
234 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700235 ScopedObjectAccessUnchecked soa(Thread::Current());
236 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
237 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
238 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
239 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
240 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800241 }
242
buzbeec531cef2012-10-18 07:09:20 -0700243 UniquePtr<Compiler> compiler(new Compiler(compiler_backend_,
244 instruction_set_,
Brian Carlstromf5822582012-03-19 22:34:31 -0700245 image,
246 thread_count_,
247 support_debugging_,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700248 image_classes,
249 dump_stats,
250 dump_timings));
Logan Chien8b977d32012-02-21 19:14:55 +0800251
buzbeec531cef2012-10-18 07:09:20 -0700252 if ((compiler_backend_ == kPortable) || (compiler_backend_ == kIceland)) {
253 compiler->SetBitcodeFileName(bitcode_filename);
254 }
Logan Chien8b977d32012-02-21 19:14:55 +0800255
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
257
258 compiler->CompileAll(class_loader, dex_files);
259
260 Thread::Current()->TransitionFromSuspendedToRunnable();
Brian Carlstromae826982011-11-09 01:33:42 -0800261
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700262 std::string image_file_location;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700263 uint32_t image_file_location_oat_checksum = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800264 uint32_t image_file_location_oat_data_begin = 0;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700265 Heap* heap = Runtime::Current()->GetHeap();
266 if (heap->GetSpaces().size() > 1) {
267 ImageSpace* image_space = heap->GetImageSpace();
Brian Carlstrom28db0122012-10-18 16:20:41 -0700268 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800269 image_file_location_oat_data_begin = reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700270 image_file_location = image_space->GetImageFilename();
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700271 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
272 image_file_location = image_file_location.substr(host_prefix->size());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700273 }
274 }
275
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800276 std::vector<uint8_t> oat_contents;
277 VectorOutputStream vector_output_stream(oat_file->GetPath(), oat_contents);
278 if (!OatWriter::Create(vector_output_stream,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700279 dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700280 image_file_location_oat_checksum,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800281 image_file_location_oat_data_begin,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700282 image_file_location,
Brian Carlstromf5822582012-03-19 22:34:31 -0700283 *compiler.get())) {
Elliott Hughes76160052012-12-12 16:31:20 -0800284 LOG(ERROR) << "Failed to create oat file " << oat_file->GetPath();
Brian Carlstromf5822582012-03-19 22:34:31 -0700285 return NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800286 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800287
288 if (!compiler->WriteElf(oat_contents, oat_file)) {
289 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
290 return NULL;
291 }
292
Brian Carlstromf5822582012-03-19 22:34:31 -0700293 return compiler.release();
Brian Carlstromae826982011-11-09 01:33:42 -0800294 }
295
Brian Carlstroma004aa92012-02-08 18:05:09 -0800296 bool CreateImageFile(const std::string& image_filename,
Brian Carlstromae826982011-11-09 01:33:42 -0800297 uintptr_t image_base,
298 const std::set<std::string>* image_classes,
299 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700300 const std::string& oat_location,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700301 const Compiler& compiler)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700302 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800303 uintptr_t oat_data_begin;
304 {
305 // ImageWriter is scoped so it can free memory before doing FixupElf
306 ImageWriter image_writer(image_classes);
307 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location, compiler)) {
308 LOG(ERROR) << "Failed to create image file " << image_filename;
309 return false;
310 }
311 oat_data_begin = image_writer.GetOatDataBegin();
312 }
313
314 LG << "dex2oat CreateImageFile opening : " << oat_filename;
315 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
316 LG << "dex2oat CreateImageFile opened : " << oat_filename;
317 if (oat_file.get() == NULL) {
318 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800319 return false;
320 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800321 if (!compiler.FixupElf(oat_file.get(), oat_data_begin)) {
322 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
323 return false;
324 }
325 LOG(ERROR) << "ELF file fixed up successfully: " << oat_file->GetPath();
Brian Carlstromae826982011-11-09 01:33:42 -0800326 return true;
327 }
328
329 private:
buzbeec531cef2012-10-18 07:09:20 -0700330 explicit Dex2Oat(Runtime* runtime, CompilerBackend compiler_backend, InstructionSet instruction_set,
331 size_t thread_count, bool support_debugging)
332 : compiler_backend_(compiler_backend),
333 instruction_set_(instruction_set),
Ian Rogers49c48942012-03-11 15:15:37 -0700334 runtime_(runtime),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800335 thread_count_(thread_count),
336 support_debugging_(support_debugging),
337 start_ns_(NanoTime()) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800338 }
Brian Carlstromae826982011-11-09 01:33:42 -0800339
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700340 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700341 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 if (!Runtime::Create(options, false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800343 LOG(ERROR) << "Failed to create runtime";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700344 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800345 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700346 Runtime* runtime = Runtime::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800347 // if we loaded an existing image, we will reuse values from the image roots.
348 if (!runtime->HasJniDlsymLookupStub()) {
Ian Rogers49c48942012-03-11 15:15:37 -0700349 runtime->SetJniDlsymLookupStub(Compiler::CreateJniDlsymLookupStub(instruction_set));
Brian Carlstromae826982011-11-09 01:33:42 -0800350 }
351 if (!runtime->HasAbstractMethodErrorStubArray()) {
Ian Rogers49c48942012-03-11 15:15:37 -0700352 runtime->SetAbstractMethodErrorStubArray(Compiler::CreateAbstractMethodErrorStub(instruction_set));
Brian Carlstromae826982011-11-09 01:33:42 -0800353 }
354 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
355 Runtime::TrampolineType type = Runtime::TrampolineType(i);
356 if (!runtime->HasResolutionStubArray(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700357 runtime->SetResolutionStubArray(Compiler::CreateResolutionStub(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800358 }
359 }
Ian Rogers19846512012-02-24 11:42:47 -0800360 if (!runtime->HasResolutionMethod()) {
361 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
362 }
Brian Carlstromae826982011-11-09 01:33:42 -0800363 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
364 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
365 if (!runtime->HasCalleeSaveMethod(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700366 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800367 }
368 }
Ian Rogers19846512012-02-24 11:42:47 -0800369 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800371 }
372
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800373 static void ResolveExceptionsForMethod(MethodHelper* mh,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700375 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800376 const DexFile::CodeItem* code_item = mh->GetCodeItem();
377 if (code_item == NULL) {
378 return; // native or abstract method
379 }
380 if (code_item->tries_size_ == 0) {
381 return; // nothing to process
382 }
383 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
384 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
385 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
386 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
387 bool has_catch_all = false;
388 if (encoded_catch_handler_size <= 0) {
389 encoded_catch_handler_size = -encoded_catch_handler_size;
390 has_catch_all = true;
391 }
392 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
393 uint16_t encoded_catch_handler_handlers_type_idx =
394 DecodeUnsignedLeb128(&encoded_catch_handler_list);
395 // Add to set of types to resolve if not already in the dex cache resolved types
396 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
397 exceptions_to_resolve.insert(
398 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
399 &mh->GetDexFile()));
400 }
401 // ignore address associated with catch handler
402 DecodeUnsignedLeb128(&encoded_catch_handler_list);
403 }
404 if (has_catch_all) {
405 // ignore catch all address
406 DecodeUnsignedLeb128(&encoded_catch_handler_list);
407 }
408 }
409 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700410
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800411 static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800413 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
414 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
415 MethodHelper mh;
416 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800417 mirror::AbstractMethod* m = c->GetVirtualMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800418 mh.ChangeMethod(m);
419 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
420 }
421 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800422 mirror::AbstractMethod* m = c->GetDirectMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800423 mh.ChangeMethod(m);
424 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
425 }
426 return true;
427 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800429 static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700430 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800431 std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
432 if (klass->IsArrayClass() || klass->IsPrimitive()) {
Jesse Wilson254db0f2011-11-16 16:44:11 -0500433 return true;
434 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800435 image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800436 return true;
Jesse Wilson254db0f2011-11-16 16:44:11 -0500437 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500438
Brian Carlstromae826982011-11-09 01:33:42 -0800439 // Appends to dex_files any elements of class_path that it doesn't already
440 // contain. This will open those dex files as necessary.
441 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
442 std::vector<std::string> parsed;
443 Split(class_path, ':', parsed);
444 for (size_t i = 0; i < parsed.size(); ++i) {
445 if (DexFilesContains(dex_files, parsed[i])) {
446 continue;
447 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800448 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
Brian Carlstromae826982011-11-09 01:33:42 -0800449 if (dex_file == NULL) {
450 LOG(WARNING) << "Failed to open dex file " << parsed[i];
451 } else {
452 dex_files.push_back(dex_file);
453 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500454 }
455 }
Brian Carlstromae826982011-11-09 01:33:42 -0800456
457 // Returns true if dex_files has a dex with the named location.
458 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
459 for (size_t i = 0; i < dex_files.size(); ++i) {
460 if (dex_files[i]->GetLocation() == location) {
461 return true;
462 }
463 }
464 return false;
465 }
466
buzbeec531cef2012-10-18 07:09:20 -0700467 const CompilerBackend compiler_backend_;
468
Ian Rogers49c48942012-03-11 15:15:37 -0700469 const InstructionSet instruction_set_;
Brian Carlstromae826982011-11-09 01:33:42 -0800470
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800471 Runtime* runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800472 size_t thread_count_;
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800473 bool support_debugging_;
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800474 uint64_t start_ns_;
475
Brian Carlstromae826982011-11-09 01:33:42 -0800476 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
477};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500478
Elliott Hughes72395bf2012-04-24 13:45:26 -0700479static bool ParseInt(const char* in, int* out) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800480 char* end;
481 int result = strtol(in, &end, 10);
482 if (in == end || *end != '\0') {
483 return false;
484 }
485 *out = result;
486 return true;
487}
488
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700489static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
490 const std::vector<const char*>& dex_locations,
491 std::vector<const DexFile*>& dex_files) {
492 size_t failure_count = 0;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800493 for (size_t i = 0; i < dex_filenames.size(); i++) {
494 const char* dex_filename = dex_filenames[i];
Brian Carlstroma004aa92012-02-08 18:05:09 -0800495 const char* dex_location = dex_locations[i];
496 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800497 if (dex_file == NULL) {
jeffhao60f83e32012-02-13 17:16:30 -0800498 LOG(WARNING) << "could not open .dex from file " << dex_filename;
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700499 ++failure_count;
jeffhao60f83e32012-02-13 17:16:30 -0800500 } else {
501 dex_files.push_back(dex_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800502 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800503 }
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700504 return failure_count;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800505}
506
Brian Carlstrombcc29262012-11-02 11:36:03 -0700507// The primary goal of the watchdog is to prevent stuck build servers
508// during development when fatal aborts lead to a cascade of failures
509// that result in a deadlock.
510class WatchDog {
511
512// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
513#undef CHECK_PTHREAD_CALL
514#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
515 do { \
516 int rc = call args; \
517 if (rc != 0) { \
518 errno = rc; \
519 std::string message(# call); \
520 message += " failed for "; \
521 message += reason; \
522 Die(message); \
523 } \
524 } while (false)
525
526 public:
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800527 WatchDog(bool is_watch_dog_enabled) {
528 is_watch_dog_enabled_ = is_watch_dog_enabled;
529 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700530 return;
531 }
532 shutting_down_ = false;
533 const char* reason = "dex2oat watch dog thread startup";
534 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
535 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
536 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
537 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
538 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
539 }
540 ~WatchDog() {
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800541 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700542 return;
543 }
544 const char* reason = "dex2oat watch dog thread shutdown";
545 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
546 shutting_down_ = true;
547 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
548 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
549
550 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
551
552 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
553 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
554 }
555
556 private:
557 static void* CallBack(void* arg) {
558 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
559 self->Wait();
560 return NULL;
561 }
562
563 static void Die(const std::string& message) {
564 // TODO: Switch to LOG(FATAL) when we can guarantee it won't prevent shutdown in error cases
565 fprintf(stderr, "%s\n", message.c_str());
566 exit(1);
567 }
568
569 void Wait() {
570 int64_t ms = kWatchDogTimeoutSeconds * 1000;
571 int32_t ns = 0;
572 timespec ts;
573 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
574 const char* reason = "dex2oat watch dog thread waiting";
575 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
576 while (!shutting_down_) {
577 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &ts));
578 if (rc == ETIMEDOUT) {
579 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
580 kWatchDogTimeoutSeconds));
581 Die(message.c_str());
582 }
583 if (rc != 0) {
584 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
585 strerror(errno)));
586 Die(message.c_str());
587 }
588 }
589 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
590 }
591
Brian Carlstrombcc29262012-11-02 11:36:03 -0700592#ifdef ART_USE_LLVM_COMPILER
593 static const unsigned int kWatchDogTimeoutSeconds = 20 * 60; // 15 minutes + buffer
594#else
595 static const unsigned int kWatchDogTimeoutSeconds = 2 * 60; // 1 minute + buffer
596#endif
597
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800598 bool is_watch_dog_enabled_;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700599 bool shutting_down_;
600 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases
601 pthread_mutex_t mutex_;
602 pthread_cond_t cond_;
603 pthread_attr_t attr_;
604 pthread_t pthread_;
605};
606
Elliott Hughes72395bf2012-04-24 13:45:26 -0700607static int dex2oat(int argc, char** argv) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700608 InitLogging(argv);
Elliott Hughes72395bf2012-04-24 13:45:26 -0700609
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700610 // Skip over argv[0].
611 argv++;
612 argc--;
613
614 if (argc == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800615 Usage("no arguments specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700616 }
617
618 std::vector<const char*> dex_filenames;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800619 std::vector<const char*> dex_locations;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800620 int zip_fd = -1;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800621 std::string zip_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700622 std::string oat_filename;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800623 std::string oat_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800624 int oat_fd = -1;
Logan Chien8b977d32012-02-21 19:14:55 +0800625 std::string bitcode_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800626 const char* image_classes_filename = NULL;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800627 std::string image_filename;
Brian Carlstromb0011262011-12-09 12:17:24 -0800628 std::string boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700629 uintptr_t image_base = 0;
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700630 UniquePtr<std::string> host_prefix;
jeffhao5d840402011-10-24 17:09:45 -0700631 std::vector<const char*> runtime_args;
Elliott Hughes5c599942012-06-13 16:45:05 -0700632 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800633 bool support_debugging = false;
buzbeec531cef2012-10-18 07:09:20 -0700634#if defined(ART_USE_PORTABLE_COMPILER)
635 CompilerBackend compiler_backend = kPortable;
636#elif defined(ART_USE_LLVM_COMPILER)
637 CompilerBackend compiler_backend = kIceland;
638#else
639 CompilerBackend compiler_backend = kQuick;
640#endif
jeffhao9ad4f222012-05-30 18:51:19 -0700641#if defined(__arm__)
Ian Rogers49c48942012-03-11 15:15:37 -0700642 InstructionSet instruction_set = kThumb2;
jeffhao9ad4f222012-05-30 18:51:19 -0700643#elif defined(__i386__)
644 InstructionSet instruction_set = kX86;
645#elif defined(__mips__)
646 InstructionSet instruction_set = kMips;
647#else
648#error "Unsupported architecture"
649#endif
Elliott Hughes67d92002012-03-26 15:08:51 -0700650 bool dump_stats = kIsDebugBuild;
651 bool dump_timings = kIsDebugBuild;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800652 bool watch_dog_enabled = !kIsTargetBuild;
Brian Carlstrom16192862011-09-12 17:50:06 -0700653
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700654 for (int i = 0; i < argc; i++) {
655 const StringPiece option(argv[i]);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800656 bool log_options = false;
657 if (log_options) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700658 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
659 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700660 if (option.starts_with("--dex-file=")) {
661 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstroma004aa92012-02-08 18:05:09 -0800662 } else if (option.starts_with("--dex-location=")) {
663 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800664 } else if (option.starts_with("--zip-fd=")) {
665 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800666 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800667 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800668 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800669 } else if (option.starts_with("--zip-location=")) {
670 zip_location = option.substr(strlen("--zip-location=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800671 } else if (option.starts_with("--oat-file=")) {
672 oat_filename = option.substr(strlen("--oat-file=")).data();
673 } else if (option.starts_with("--oat-fd=")) {
674 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800675 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800676 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800677 }
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800678 } else if (option == "-g") {
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800679 support_debugging = true;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800680 } else if (option == "--watch-dog") {
681 watch_dog_enabled = true;
682 } else if (option == "--no-watch-dog") {
683 watch_dog_enabled = false;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800684 } else if (option.starts_with("-j")) {
Brian Carlstromb12552a2012-02-04 17:17:31 -0800685 const char* thread_count_str = option.substr(strlen("-j")).data();
Elliott Hughes5523ee02012-02-03 18:18:34 -0800686 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800687 Usage("could not parse -j argument '%s' as an integer", thread_count_str);
Elliott Hughes5523ee02012-02-03 18:18:34 -0800688 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800689 } else if (option.starts_with("--oat-location=")) {
690 oat_location = option.substr(strlen("--oat-location=")).data();
Logan Chien8b977d32012-02-21 19:14:55 +0800691 } else if (option.starts_with("--bitcode=")) {
692 bitcode_filename = option.substr(strlen("--bitcode=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700693 } else if (option.starts_with("--image=")) {
694 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800695 } else if (option.starts_with("--image-classes=")) {
696 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700697 } else if (option.starts_with("--base=")) {
698 const char* image_base_str = option.substr(strlen("--base=")).data();
699 char* end;
700 image_base = strtoul(image_base_str, &end, 16);
701 if (end == image_base_str || *end != '\0') {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800702 Usage("Failed to parse hexadecimal value for option %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700703 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700704 } else if (option.starts_with("--boot-image=")) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800705 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700706 } else if (option.starts_with("--host-prefix=")) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700707 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
Ian Rogers49c48942012-03-11 15:15:37 -0700708 } else if (option.starts_with("--instruction-set=")) {
709 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
jeffhao1f71ae82012-05-24 16:08:24 -0700710 if (instruction_set_str == "arm") {
Ian Rogers49c48942012-03-11 15:15:37 -0700711 instruction_set = kThumb2;
jeffhao1f71ae82012-05-24 16:08:24 -0700712 } else if (instruction_set_str == "mips") {
Ian Rogers49c48942012-03-11 15:15:37 -0700713 instruction_set = kMips;
jeffhao1f71ae82012-05-24 16:08:24 -0700714 } else if (instruction_set_str == "x86") {
Ian Rogers49c48942012-03-11 15:15:37 -0700715 instruction_set = kX86;
716 }
buzbeec531cef2012-10-18 07:09:20 -0700717 } else if (option.starts_with("--compiler-backend=")) {
718 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
719 if (backend_str == "Quick") {
720 compiler_backend = kQuick;
721 } else if (backend_str == "QuickGBC") {
722 compiler_backend = kQuickGBC;
723 } else if (backend_str == "Iceland") {
724 // TODO: remove this when Portable/Iceland merge complete
725 compiler_backend = kIceland;
726 } else if (backend_str == "Portable") {
727 compiler_backend = kPortable;
728 }
jeffhao5d840402011-10-24 17:09:45 -0700729 } else if (option == "--runtime-arg") {
730 if (++i >= argc) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800731 Usage("Missing required argument for --runtime-arg");
jeffhao5d840402011-10-24 17:09:45 -0700732 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800733 if (log_options) {
734 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
735 }
jeffhao5d840402011-10-24 17:09:45 -0700736 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700737 } else {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800738 Usage("unknown argument %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700739 }
740 }
741
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800742 if (oat_filename.empty() && oat_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800743 Usage("Output must be supplied with either --oat-file or --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
750 if (!oat_filename.empty() && oat_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800751 Usage("--oat-file should not be used with --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800752 }
753
Brian Carlstroma004aa92012-02-08 18:05:09 -0800754 if (oat_fd != -1 && !image_filename.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800755 Usage("--oat-fd should not be used with --image");
Brian Carlstrome24fa612011-09-29 00:53:55 -0700756 }
757
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700758 if (host_prefix.get() == NULL) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800759 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
760 if (android_product_out != NULL) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700761 host_prefix.reset(new std::string(android_product_out));
Brian Carlstromb0011262011-12-09 12:17:24 -0800762 }
763 }
764
Brian Carlstroma004aa92012-02-08 18:05:09 -0800765 bool image = (!image_filename.empty());
Brian Carlstromb0011262011-12-09 12:17:24 -0800766 if (!image && boot_image_filename.empty()) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700767 if (host_prefix.get() == NULL) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800768 boot_image_filename += GetAndroidRoot();
769 } else {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700770 boot_image_filename += *host_prefix.get();
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800771 boot_image_filename += "/system";
772 }
773 boot_image_filename += "/framework/boot.art";
Brian Carlstromb0011262011-12-09 12:17:24 -0800774 }
775 std::string boot_image_option;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800776 if (!boot_image_filename.empty()) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800777 boot_image_option += "-Ximage:";
778 boot_image_option += boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700779 }
780
Brian Carlstromae826982011-11-09 01:33:42 -0800781 if (image_classes_filename != NULL && !image) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800782 Usage("--image-classes should only be used with --image");
Brian Carlstromae826982011-11-09 01:33:42 -0800783 }
784
785 if (image_classes_filename != NULL && !boot_image_option.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800786 Usage("--image-classes should not be used with --boot-image");
Brian Carlstrom78128a62011-09-15 17:21:19 -0700787 }
788
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800789 if (dex_filenames.empty() && zip_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800790 Usage("Input must be supplied with either --dex-file or --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800791 }
792
793 if (!dex_filenames.empty() && zip_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800794 Usage("--dex-file should not be used with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800795 }
796
Brian Carlstroma004aa92012-02-08 18:05:09 -0800797 if (!dex_filenames.empty() && !zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800798 Usage("--dex-file should not be used with --zip-location");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800799 }
800
Brian Carlstroma004aa92012-02-08 18:05:09 -0800801 if (dex_locations.empty()) {
802 for (size_t i = 0; i < dex_filenames.size(); i++) {
803 dex_locations.push_back(dex_filenames[i]);
804 }
805 } else if (dex_locations.size() != dex_filenames.size()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800806 Usage("--dex-location arguments do not match --dex-file arguments");
Brian Carlstroma004aa92012-02-08 18:05:09 -0800807 }
808
809 if (zip_fd != -1 && zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800810 Usage("--zip-location should be supplied with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800811 }
812
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700813 if (boot_image_option.empty()) {
814 if (image_base == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800815 Usage("non-zero --base not specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700816 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700817 }
818
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800819 // Done with usage checks, enable watchdog if requested
820 WatchDog watch_dog(watch_dog_enabled);
821
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800822 // Check early that the result of compilation can be written
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800823 UniquePtr<File> oat_file;
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700824 bool create_file = !oat_filename.empty(); // as opposed to using open file descriptor
825 if (create_file) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800826 oat_file.reset(OS::OpenFile(oat_filename.c_str(), true));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800827 if (oat_location.empty()) {
828 oat_location = oat_filename;
829 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800830 } else {
Elliott Hughes76160052012-12-12 16:31:20 -0800831 oat_file.reset(new File(oat_fd, oat_location));
832 oat_file->DisableAutoClose();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800833 }
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800834 if (oat_file.get() == NULL) {
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700835 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
836 return EXIT_FAILURE;
837 }
838 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
839 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800840 return EXIT_FAILURE;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700841 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800842
Brian Carlstroma004aa92012-02-08 18:05:09 -0800843 LOG(INFO) << "dex2oat: " << oat_location;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700844
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700845 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700846 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800847 std::vector<const DexFile*> boot_class_path;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700848 if (boot_image_option.empty()) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700849 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
850 if (failure_count > 0) {
851 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
852 return EXIT_FAILURE;
853 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800854 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700855 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700856 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
857 }
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700858 if (host_prefix.get() != NULL) {
859 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700860 }
jeffhao5d840402011-10-24 17:09:45 -0700861 for (size_t i = 0; i < runtime_args.size(); i++) {
862 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
863 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700864
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700865 Dex2Oat* p_dex2oat;
buzbeec531cef2012-10-18 07:09:20 -0700866 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count, support_debugging)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700867 LOG(ERROR) << "Failed to create dex2oat";
868 return EXIT_FAILURE;
869 }
870 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
871 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
872 // give it away now and then switch to a more managable ScopedObjectAccess.
873 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
874 // Whilst we're in native take the opportunity to initialize well known classes.
875 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
876 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700877
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800878 // If --image-classes was specified, calculate the full list of classes to include in the image
Brian Carlstromae826982011-11-09 01:33:42 -0800879 UniquePtr<const std::set<std::string> > image_classes(NULL);
880 if (image_classes_filename != NULL) {
881 image_classes.reset(dex2oat->GetImageClassDescriptors(image_classes_filename));
882 if (image_classes.get() == NULL) {
883 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
884 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700885 }
886 }
887
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800888 std::vector<const DexFile*> dex_files;
889 if (boot_image_option.empty()) {
890 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
891 } else {
892 if (dex_filenames.empty()) {
893 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
894 if (zip_archive.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800895 LOG(ERROR) << "Failed to zip from file descriptor for " << zip_location;
Brian Carlstrom2e3d1b22012-01-09 18:01:56 -0800896 return EXIT_FAILURE;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800897 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800898 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800899 if (dex_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800900 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800901 return EXIT_FAILURE;
902 }
903 dex_files.push_back(dex_file);
904 } else {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700905 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
906 if (failure_count > 0) {
907 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
908 return EXIT_FAILURE;
909 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800910 }
911 }
912
Brian Carlstromf5822582012-03-19 22:34:31 -0700913 UniquePtr<const Compiler> compiler(dex2oat->CreateOatFile(boot_image_option,
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700914 host_prefix.get(),
Brian Carlstromf5822582012-03-19 22:34:31 -0700915 dex_files,
916 oat_file.get(),
Brian Carlstromf5822582012-03-19 22:34:31 -0700917 bitcode_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700918 image,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700919 image_classes.get(),
920 dump_stats,
921 dump_timings));
Brian Carlstromf5822582012-03-19 22:34:31 -0700922
923 if (compiler.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800924 LOG(ERROR) << "Failed to create oat file: " << oat_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700925 return EXIT_FAILURE;
926 }
927
Brian Carlstromae826982011-11-09 01:33:42 -0800928 if (!image) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800929 LOG(INFO) << "Oat file written successfully: " << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700930 return EXIT_SUCCESS;
931 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700932
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800933 // Notes on the interleaving of creating the image and oat file to
934 // ensure the references between the two are correct.
935 //
936 // Currently we have a memory layout that looks something like this:
937 //
938 // +--------------+
939 // | image |
940 // +--------------+
941 // | boot oat |
942 // +--------------+
943 // | alloc spaces |
944 // +--------------+
945 //
946 // There are several constraints on the loading of the imag and boot.oat.
947 //
948 // 1. The image is expected to be loaded at an absolute address and
949 // contains Objects with absolute pointers within the image.
950 //
951 // 2. There are absolute pointers from Methods in the image to their
952 // code in the oat.
953 //
954 // 3. There are absolute pointers from the code in the oat to Methods
955 // in the image.
956 //
957 // 4. There are absolute pointers from code in the oat to other code
958 // in the oat.
959 //
960 // To get this all correct, we go through several steps.
961 //
962 // 1. We have already created that oat file above with
963 // CreateOatFile. Originally this was just our own proprietary file
964 // but now it is contained within an ELF dynamic object (aka .so
965 // file). The Compiler returned by CreateOatFile provides
966 // PatchInformation for references to oat code and Methods that need
967 // to be update once we know where the oat file will be located
968 // after the image.
969 //
970 // 2. We create the image file. It needs to know where the oat file
971 // will be loaded after itself. Originally when oat file was simply
972 // memory mapped so we could predict where its contents were based
973 // on the file size. Now that it is an ELF file, we need to inspect
974 // the ELF file to understand the in memory segment layout including
975 // where the oat header is located within. ImageWriter's
976 // PatchOatCodeAndMethods uses the PatchInformation from the
977 // Compiler to touch up absolute references in the oat file.
978 //
979 // 3. We fixup the ELF program headers so that dlopen will try to
980 // load the .so at the desired location at runtime by offsetting the
981 // Elf32_Phdr.p_vaddr values by the desired base address.
982 //
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700983 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
984 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
985 image_base,
986 image_classes.get(),
987 oat_filename,
988 oat_location,
989 *compiler.get());
990 Thread::Current()->TransitionFromSuspendedToRunnable();
991 if (!image_creation_success) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700992 return EXIT_FAILURE;
993 }
994
Brian Carlstromae826982011-11-09 01:33:42 -0800995 // We wrote the oat file successfully, and want to keep it.
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800996 LOG(INFO) << "Oat file written successfully: " << oat_filename;
997 LOG(INFO) << "Image written successfully: " << image_filename;
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}