blob: 235c0680449b8e450b6a2691c957b7509fed532b [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070016
17#include <stdio.h>
18#include <stdlib.h>
Brian Carlstrom6cd40e52012-05-03 14:15:11 -070019#include <sys/stat.h>
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070020
Brian Carlstromae826982011-11-09 01:33:42 -080021#include <iostream>
22#include <fstream>
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070023#include <string>
24#include <vector>
25
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080027#include "base/stringpiece.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080028#include "base/timing_logger.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070030#include "class_linker.h"
Ian Rogers1212a022013-03-04 10:48:41 -080031#include "compiler/driver/compiler_driver.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "dex_file-inl.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070033#include "image_writer.h"
Ian Rogers6f1dfe42011-12-08 17:28:34 -080034#include "leb128.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/abstract_method-inl.h"
36#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
38#include "mirror/object-inl.h"
39#include "mirror/object_array-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070040#include "oat_writer.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Ian Rogers5e863dd2011-11-02 20:00:10 -070042#include "os.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070043#include "runtime.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070044#include "ScopedLocalRef.h"
45#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070046#include "sirt_ref.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "vector_output_stream.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070048#include "well_known_classes.h"
Brian Carlstroma6cc8932012-01-04 14:44:07 -080049#include "zip_archive.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070050
51namespace art {
52
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080053static void UsageErrorV(const char* fmt, va_list ap) {
54 std::string error;
55 StringAppendV(&error, fmt, ap);
56 LOG(ERROR) << error;
57}
58
59static void UsageError(const char* fmt, ...) {
60 va_list ap;
61 va_start(ap, fmt);
62 UsageErrorV(fmt, ap);
63 va_end(ap);
64}
65
66static void Usage(const char* fmt, ...) {
67 va_list ap;
68 va_start(ap, fmt);
69 UsageErrorV(fmt, ap);
70 va_end(ap);
71
72 UsageError("Usage: dex2oat [options]...");
73 UsageError("");
74 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
75 UsageError(" Example: --dex-file=/system/framework/core.jar");
76 UsageError("");
77 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
78 UsageError(" containing a classes.dex file to compile.");
79 UsageError(" Example: --zip-fd=5");
80 UsageError("");
81 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file corresponding");
82 UsageError(" to the file descriptor specified by --zip-fd.");
83 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
84 UsageError("");
Brian Carlstrom265091e2013-01-30 14:08:26 -080085 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
86 UsageError(" Example: --oat-file=/system/framework/boot.oat");
87 UsageError("");
88 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080089 UsageError(" Example: --oat-file=/system/framework/boot.oat");
90 UsageError("");
91 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
92 UsageError(" to the file descriptor specified by --oat-fd.");
Brian Carlstrom7675e162013-06-10 16:18:04 -070093 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -080094 UsageError("");
Brian Carlstrom265091e2013-01-30 14:08:26 -080095 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
96 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
97 UsageError("");
Logan Chien8b977d32012-02-21 19:14:55 +080098 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
99 UsageError(" Example: --bitcode=/system/framework/boot.bc");
100 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800101 UsageError(" --image=<file.art>: specifies the output image filename.");
102 UsageError(" Example: --image=/system/framework/boot.art");
103 UsageError("");
104 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
105 UsageError(" Example: --image=frameworks/base/preloaded-classes");
106 UsageError("");
107 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
108 UsageError(" Example: --base=0x50000000");
109 UsageError("");
110 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
111 UsageError(" Example: --boot-image=/system/framework/boot.art");
112 UsageError(" Default: <host-prefix>/system/framework/boot.art");
113 UsageError("");
Brian Carlstrom265091e2013-01-30 14:08:26 -0800114 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800115 UsageError(" cross compilation.");
116 UsageError(" Example: --host-prefix=out/target/product/crespo");
117 UsageError(" Default: $ANDROID_PRODUCT_OUT");
118 UsageError("");
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800119 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
120 UsageError(" Example: --android-root=out/host/linux-x86");
121 UsageError(" Default: $ANDROID_ROOT");
122 UsageError("");
jeffhao1f71ae82012-05-24 16:08:24 -0700123 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction");
Ian Rogers49c48942012-03-11 15:15:37 -0700124 UsageError(" set.");
jeffhao1f71ae82012-05-24 16:08:24 -0700125 UsageError(" Example: --instruction-set=x86");
126 UsageError(" Default: arm");
Ian Rogers49c48942012-03-11 15:15:37 -0700127 UsageError("");
buzbeec531cef2012-10-18 07:09:20 -0700128 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend");
129 UsageError(" set.");
130 UsageError(" Example: --instruction-set=Portable");
131 UsageError(" Default: Quick");
Brian Carlstrom265091e2013-01-30 14:08:26 -0800132 UsageError("");
133 UsageError(" --host: used with Portable backend to link against host runtime libraries");
134 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800135 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
136 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
137 UsageError(" Use a separate --runtime-arg switch for each argument.");
138 UsageError(" Example: --runtime-arg -Xms256m");
139 UsageError("");
140 std::cerr << "See log for usage error information\n";
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700141 exit(EXIT_FAILURE);
142}
143
Brian Carlstromae826982011-11-09 01:33:42 -0800144class Dex2Oat {
145 public:
buzbeec531cef2012-10-18 07:09:20 -0700146 static bool Create(Dex2Oat** p_dex2oat, Runtime::Options& options, CompilerBackend compiler_backend,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700147 InstructionSet instruction_set, size_t thread_count, bool support_debugging)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700148 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700149 if (!CreateRuntime(options, instruction_set)) {
150 *p_dex2oat = NULL;
151 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800152 }
buzbeec531cef2012-10-18 07:09:20 -0700153 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700154 support_debugging);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800156 }
157
158 ~Dex2Oat() {
159 delete runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800160 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) << " (threads: " << thread_count_ << ")";
Brian Carlstromae826982011-11-09 01:33:42 -0800161 }
162
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700163
Brian Carlstromae826982011-11-09 01:33:42 -0800164 // Make a list of descriptors for classes to include in the image
Brian Carlstrom4b7b9892013-06-06 21:44:22 -0700165 std::set<std::string>* GetImageClassDescriptors(const char* image_classes_filename)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700166 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800167 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
168 if (image_classes_file.get() == NULL) {
169 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
170 return NULL;
171 }
172
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800173 // Load all the classes specified in the file
Brian Carlstromae826982011-11-09 01:33:42 -0800174 ClassLinker* class_linker = runtime_->GetClassLinker();
Ian Rogers1f539342012-10-03 21:09:42 -0700175 Thread* self = Thread::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800176 while (image_classes_file->good()) {
177 std::string dot;
178 std::getline(*image_classes_file.get(), dot);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800179 if (StartsWith(dot, "#") || dot.empty()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800180 continue;
181 }
Elliott Hughes95572412011-12-13 18:14:20 -0800182 std::string descriptor(DotToDescriptor(dot.c_str()));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800183 SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(descriptor.c_str()));
Brian Carlstromae826982011-11-09 01:33:42 -0800184 if (klass.get() == NULL) {
185 LOG(WARNING) << "Failed to find class " << descriptor;
186 Thread::Current()->ClearException();
187 }
188 }
189 image_classes_file->close();
190
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800191 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
192 // exceptions are resolved by the verifier when there is a catch block in an interested method.
193 // Do this here so that exception classes appear to have been specified image classes.
194 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800195 SirtRef<mirror::Class> java_lang_Throwable(self,
Ian Rogers1f539342012-10-03 21:09:42 -0700196 class_linker->FindSystemClass("Ljava/lang/Throwable;"));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800197 do {
198 unresolved_exception_types.clear();
199 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
200 &unresolved_exception_types);
201 typedef std::set<std::pair<uint16_t, const DexFile*> >::const_iterator It; // TODO: C++0x auto
202 for (It it = unresolved_exception_types.begin(),
203 end = unresolved_exception_types.end();
204 it != end; ++it) {
205 uint16_t exception_type_idx = it->first;
206 const DexFile* dex_file = it->second;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800207 mirror::DexCache* dex_cache = class_linker->FindDexCache(*dex_file);
208 mirror:: ClassLoader* class_loader = NULL;
209 SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
210 dex_cache, class_loader));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800211 if (klass.get() == NULL) {
212 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
213 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
214 LOG(FATAL) << "Failed to resolve class " << descriptor;
215 }
Elliott Hughes35be9b12012-05-29 17:59:26 -0700216 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800217 }
218 // Resolving exceptions may load classes that reference more exceptions, iterate until no
219 // more are found
220 } while (!unresolved_exception_types.empty());
221
Brian Carlstromae826982011-11-09 01:33:42 -0800222 // We walk the roots looking for classes so that we'll pick up the
223 // above classes plus any classes them depend on such super
224 // classes, interfaces, and the required ClassLinker roots.
Brian Carlstrom5f4bd972013-06-06 22:27:40 -0700225 UniquePtr<ImageWriter::DescriptorSet> image_classes(new ImageWriter::DescriptorSet);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800226 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes.get());
Brian Carlstromae826982011-11-09 01:33:42 -0800227 CHECK_NE(image_classes->size(), 0U);
228 return image_classes.release();
229 }
230
Ian Rogers1212a022013-03-04 10:48:41 -0800231 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800232 const std::string* host_prefix,
233 const std::string& android_root,
234 bool is_host,
235 const std::vector<const DexFile*>& dex_files,
236 File* oat_file,
237 const std::string& bitcode_filename,
238 bool image,
Brian Carlstrom5f4bd972013-06-06 22:27:40 -0700239 const ImageWriter::DescriptorSet* image_classes,
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800240 bool dump_stats,
241 bool dump_timings)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800243 // SirtRef and ClassLoader creation needs to come after Runtime::Create
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700244 jobject class_loader = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800245 if (!boot_image_option.empty()) {
246 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromae826982011-11-09 01:33:42 -0800247 std::vector<const DexFile*> class_path_files(dex_files);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800248 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800249 for (size_t i = 0; i < class_path_files.size(); i++) {
250 class_linker->RegisterDexFile(*class_path_files[i]);
251 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700252 ScopedObjectAccessUnchecked soa(Thread::Current());
253 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
254 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
255 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
256 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
257 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800258 }
259
Ian Rogers1212a022013-03-04 10:48:41 -0800260 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
261 instruction_set_,
262 image,
263 thread_count_,
264 support_debugging_,
265 image_classes,
266 dump_stats,
267 dump_timings));
Logan Chien8b977d32012-02-21 19:14:55 +0800268
Ian Rogersc928de92013-02-27 14:30:44 -0800269 if (compiler_backend_ == kPortable) {
Ian Rogers1212a022013-03-04 10:48:41 -0800270 driver->SetBitcodeFileName(bitcode_filename);
buzbeec531cef2012-10-18 07:09:20 -0700271 }
Logan Chien8b977d32012-02-21 19:14:55 +0800272
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700273
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700274 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
275
Ian Rogers1212a022013-03-04 10:48:41 -0800276 driver->CompileAll(class_loader, dex_files);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700277
278 Thread::Current()->TransitionFromSuspendedToRunnable();
Brian Carlstromae826982011-11-09 01:33:42 -0800279
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700280 std::string image_file_location;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700281 uint32_t image_file_location_oat_checksum = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800282 uint32_t image_file_location_oat_data_begin = 0;
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700283 if (!driver->IsImage()) {
284 ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
Brian Carlstrom28db0122012-10-18 16:20:41 -0700285 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
Ian Rogers39ebcb82013-05-30 16:57:23 -0700286 image_file_location_oat_data_begin =
287 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700288 image_file_location = image_space->GetImageFilename();
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700289 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
290 image_file_location = image_file_location.substr(host_prefix->size());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700291 }
292 }
293
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800294 std::vector<uint8_t> oat_contents;
Ian Rogers39ebcb82013-05-30 16:57:23 -0700295 // TODO: change ElfWriterQuick to not require the creation of oat_contents. The old pre-mclinker
296 // OatWriter streamed directly to disk. The new could can be adapted to do it as follows:
297 // 1.) use first pass of OatWriter to calculate size of oat structure,
298 // 2.) call ElfWriterQuick with pointer to OatWriter instead of contents,
299 // 3.) have ElfWriterQuick call back to OatWriter to stream generate the output directly in
300 // place in the elf file.
301 oat_contents.reserve(5 * MB);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800302 VectorOutputStream vector_output_stream(oat_file->GetPath(), oat_contents);
303 if (!OatWriter::Create(vector_output_stream,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700304 dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700305 image_file_location_oat_checksum,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800306 image_file_location_oat_data_begin,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700307 image_file_location,
Ian Rogers1212a022013-03-04 10:48:41 -0800308 *driver.get())) {
Elliott Hughes76160052012-12-12 16:31:20 -0800309 LOG(ERROR) << "Failed to create oat file " << oat_file->GetPath();
Brian Carlstromf5822582012-03-19 22:34:31 -0700310 return NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800311 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800312
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800313 if (!driver->WriteElf(android_root, is_host, dex_files, oat_contents, oat_file)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800314 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
315 return NULL;
316 }
317
Ian Rogers1212a022013-03-04 10:48:41 -0800318 return driver.release();
Brian Carlstromae826982011-11-09 01:33:42 -0800319 }
320
Brian Carlstroma004aa92012-02-08 18:05:09 -0800321 bool CreateImageFile(const std::string& image_filename,
Brian Carlstromae826982011-11-09 01:33:42 -0800322 uintptr_t image_base,
Brian Carlstrom5f4bd972013-06-06 22:27:40 -0700323 ImageWriter::DescriptorSet* image_classes,
Brian Carlstromae826982011-11-09 01:33:42 -0800324 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700325 const std::string& oat_location,
Ian Rogers1212a022013-03-04 10:48:41 -0800326 const CompilerDriver& compiler)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700327 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800328 uintptr_t oat_data_begin;
329 {
330 // ImageWriter is scoped so it can free memory before doing FixupElf
331 ImageWriter image_writer(image_classes);
332 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location, compiler)) {
333 LOG(ERROR) << "Failed to create image file " << image_filename;
334 return false;
335 }
336 oat_data_begin = image_writer.GetOatDataBegin();
337 }
338
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800339 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800340 if (oat_file.get() == NULL) {
341 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800342 return false;
343 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800344 if (!compiler.FixupElf(oat_file.get(), oat_data_begin)) {
345 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
346 return false;
347 }
Brian Carlstromae826982011-11-09 01:33:42 -0800348 return true;
349 }
350
351 private:
buzbeec531cef2012-10-18 07:09:20 -0700352 explicit Dex2Oat(Runtime* runtime, CompilerBackend compiler_backend, InstructionSet instruction_set,
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700353 size_t thread_count, bool support_debugging)
buzbeec531cef2012-10-18 07:09:20 -0700354 : compiler_backend_(compiler_backend),
355 instruction_set_(instruction_set),
Ian Rogers49c48942012-03-11 15:15:37 -0700356 runtime_(runtime),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800357 thread_count_(thread_count),
358 support_debugging_(support_debugging),
359 start_ns_(NanoTime()) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800360 }
Brian Carlstromae826982011-11-09 01:33:42 -0800361
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700362 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700363 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700364 if (!Runtime::Create(options, false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800365 LOG(ERROR) << "Failed to create runtime";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700366 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800367 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700368 Runtime* runtime = Runtime::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800369 // if we loaded an existing image, we will reuse values from the image roots.
Ian Rogers19846512012-02-24 11:42:47 -0800370 if (!runtime->HasResolutionMethod()) {
371 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
372 }
Brian Carlstromae826982011-11-09 01:33:42 -0800373 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
374 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
375 if (!runtime->HasCalleeSaveMethod(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700376 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800377 }
378 }
Ian Rogers19846512012-02-24 11:42:47 -0800379 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700380 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800381 }
382
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800383 static void ResolveExceptionsForMethod(MethodHelper* mh,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700384 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700385 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800386 const DexFile::CodeItem* code_item = mh->GetCodeItem();
387 if (code_item == NULL) {
388 return; // native or abstract method
389 }
390 if (code_item->tries_size_ == 0) {
391 return; // nothing to process
392 }
393 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
394 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
395 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
396 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
397 bool has_catch_all = false;
398 if (encoded_catch_handler_size <= 0) {
399 encoded_catch_handler_size = -encoded_catch_handler_size;
400 has_catch_all = true;
401 }
402 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
403 uint16_t encoded_catch_handler_handlers_type_idx =
404 DecodeUnsignedLeb128(&encoded_catch_handler_list);
405 // Add to set of types to resolve if not already in the dex cache resolved types
406 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
407 exceptions_to_resolve.insert(
408 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
409 &mh->GetDexFile()));
410 }
411 // ignore address associated with catch handler
412 DecodeUnsignedLeb128(&encoded_catch_handler_list);
413 }
414 if (has_catch_all) {
415 // ignore catch all address
416 DecodeUnsignedLeb128(&encoded_catch_handler_list);
417 }
418 }
419 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800421 static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700422 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800423 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
424 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
425 MethodHelper mh;
426 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800427 mirror::AbstractMethod* m = c->GetVirtualMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800428 mh.ChangeMethod(m);
429 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
430 }
431 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800432 mirror::AbstractMethod* m = c->GetDirectMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800433 mh.ChangeMethod(m);
434 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
435 }
436 return true;
437 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700438
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800439 static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom5f4bd972013-06-06 22:27:40 -0700441 ImageWriter::DescriptorSet* image_classes = reinterpret_cast<ImageWriter::DescriptorSet*>(arg);
Brian Carlstromae826982011-11-09 01:33:42 -0800442 if (klass->IsArrayClass() || klass->IsPrimitive()) {
Jesse Wilson254db0f2011-11-16 16:44:11 -0500443 return true;
444 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800445 image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800446 return true;
Jesse Wilson254db0f2011-11-16 16:44:11 -0500447 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500448
Brian Carlstromae826982011-11-09 01:33:42 -0800449 // Appends to dex_files any elements of class_path that it doesn't already
450 // contain. This will open those dex files as necessary.
451 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
452 std::vector<std::string> parsed;
453 Split(class_path, ':', parsed);
Ian Rogers33e95662013-05-20 20:29:14 -0700454 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
455 ScopedObjectAccess soa(Thread::Current());
Brian Carlstromae826982011-11-09 01:33:42 -0800456 for (size_t i = 0; i < parsed.size(); ++i) {
457 if (DexFilesContains(dex_files, parsed[i])) {
458 continue;
459 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800460 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
Brian Carlstromae826982011-11-09 01:33:42 -0800461 if (dex_file == NULL) {
462 LOG(WARNING) << "Failed to open dex file " << parsed[i];
463 } else {
464 dex_files.push_back(dex_file);
465 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500466 }
467 }
Brian Carlstromae826982011-11-09 01:33:42 -0800468
469 // Returns true if dex_files has a dex with the named location.
470 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
471 for (size_t i = 0; i < dex_files.size(); ++i) {
472 if (dex_files[i]->GetLocation() == location) {
473 return true;
474 }
475 }
476 return false;
477 }
478
buzbeec531cef2012-10-18 07:09:20 -0700479 const CompilerBackend compiler_backend_;
480
Ian Rogers49c48942012-03-11 15:15:37 -0700481 const InstructionSet instruction_set_;
Brian Carlstromae826982011-11-09 01:33:42 -0800482
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800483 Runtime* runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800484 size_t thread_count_;
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800485 bool support_debugging_;
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800486 uint64_t start_ns_;
487
Brian Carlstromae826982011-11-09 01:33:42 -0800488 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
489};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500490
Elliott Hughes72395bf2012-04-24 13:45:26 -0700491static bool ParseInt(const char* in, int* out) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800492 char* end;
493 int result = strtol(in, &end, 10);
494 if (in == end || *end != '\0') {
495 return false;
496 }
497 *out = result;
498 return true;
499}
500
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700501static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
502 const std::vector<const char*>& dex_locations,
503 std::vector<const DexFile*>& dex_files) {
504 size_t failure_count = 0;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800505 for (size_t i = 0; i < dex_filenames.size(); i++) {
506 const char* dex_filename = dex_filenames[i];
Brian Carlstroma004aa92012-02-08 18:05:09 -0800507 const char* dex_location = dex_locations[i];
508 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800509 if (dex_file == NULL) {
Ian Rogers33e95662013-05-20 20:29:14 -0700510 LOG(WARNING) << "Could not open .dex from file '" << dex_filename << "'\n";
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700511 ++failure_count;
jeffhao60f83e32012-02-13 17:16:30 -0800512 } else {
513 dex_files.push_back(dex_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800514 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800515 }
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700516 return failure_count;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800517}
518
Brian Carlstrombcc29262012-11-02 11:36:03 -0700519// The primary goal of the watchdog is to prevent stuck build servers
520// during development when fatal aborts lead to a cascade of failures
521// that result in a deadlock.
522class WatchDog {
523
524// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
525#undef CHECK_PTHREAD_CALL
526#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
527 do { \
528 int rc = call args; \
529 if (rc != 0) { \
530 errno = rc; \
531 std::string message(# call); \
532 message += " failed for "; \
533 message += reason; \
Brian Carlstromed115642013-03-15 16:04:40 -0700534 Fatal(message); \
Brian Carlstrombcc29262012-11-02 11:36:03 -0700535 } \
536 } while (false)
537
538 public:
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800539 WatchDog(bool is_watch_dog_enabled) {
540 is_watch_dog_enabled_ = is_watch_dog_enabled;
541 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700542 return;
543 }
544 shutting_down_ = false;
545 const char* reason = "dex2oat watch dog thread startup";
546 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
547 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
548 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
549 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
550 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
551 }
552 ~WatchDog() {
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800553 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700554 return;
555 }
556 const char* reason = "dex2oat watch dog thread shutdown";
557 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
558 shutting_down_ = true;
559 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
560 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
561
562 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
563
564 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
565 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
566 }
567
568 private:
569 static void* CallBack(void* arg) {
570 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
571 self->Wait();
572 return NULL;
573 }
574
Brian Carlstromed115642013-03-15 16:04:40 -0700575 static void Message(char severity, const std::string& message) {
576 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error cases.
577 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
578 kIsDebugBuild ? "d" : "",
579 severity,
580 getpid(),
581 GetTid(),
582 message.c_str());
Ian Rogerseb5cb602013-02-25 15:06:01 -0800583 }
584
Brian Carlstromed115642013-03-15 16:04:40 -0700585 static void Warn(const std::string& message) {
586 Message('W', message);
587 }
588
589 static void Fatal(const std::string& message) {
590 Message('F', message);
Brian Carlstrombcc29262012-11-02 11:36:03 -0700591 exit(1);
592 }
593
594 void Wait() {
Ian Rogerseb5cb602013-02-25 15:06:01 -0800595 bool warning = true;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800596 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
Brian Carlstromed115642013-03-15 16:04:40 -0700597 timespec warning_ts;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800598 InitTimeSpec(true, CLOCK_REALTIME, kWatchDogWarningSeconds * 1000, 0, &warning_ts);
Brian Carlstromed115642013-03-15 16:04:40 -0700599 timespec timeout_ts;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800600 InitTimeSpec(true, CLOCK_REALTIME, kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
Brian Carlstrombcc29262012-11-02 11:36:03 -0700601 const char* reason = "dex2oat watch dog thread waiting";
602 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
603 while (!shutting_down_) {
Ian Rogerseb5cb602013-02-25 15:06:01 -0800604 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
605 warning ? &warning_ts
606 : &timeout_ts));
Brian Carlstrombcc29262012-11-02 11:36:03 -0700607 if (rc == ETIMEDOUT) {
608 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
Ian Rogerseb5cb602013-02-25 15:06:01 -0800609 warning ? kWatchDogWarningSeconds
610 : kWatchDogTimeoutSeconds));
611 if (warning) {
612 Warn(message.c_str());
613 warning = false;
614 } else {
Brian Carlstromed115642013-03-15 16:04:40 -0700615 Fatal(message.c_str());
Ian Rogerseb5cb602013-02-25 15:06:01 -0800616 }
617 } else if (rc != 0) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700618 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
619 strerror(errno)));
Brian Carlstromed115642013-03-15 16:04:40 -0700620 Fatal(message.c_str());
Brian Carlstrombcc29262012-11-02 11:36:03 -0700621 }
622 }
623 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
624 }
625
Brian Carlstromed115642013-03-15 16:04:40 -0700626 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
627#if ART_USE_PORTABLE_COMPILER
628 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
Ian Rogerseb5cb602013-02-25 15:06:01 -0800629 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
Brian Carlstrombcc29262012-11-02 11:36:03 -0700630#else
Brian Carlstromed115642013-03-15 16:04:40 -0700631 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
632 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
Brian Carlstrombcc29262012-11-02 11:36:03 -0700633#endif
634
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800635 bool is_watch_dog_enabled_;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700636 bool shutting_down_;
637 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases
638 pthread_mutex_t mutex_;
639 pthread_cond_t cond_;
640 pthread_attr_t attr_;
641 pthread_t pthread_;
642};
Ian Rogers1c653d52013-06-13 15:04:30 -0700643const unsigned int WatchDog::kWatchDogWarningSeconds;
644const unsigned int WatchDog::kWatchDogTimeoutSeconds;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700645
Elliott Hughes72395bf2012-04-24 13:45:26 -0700646static int dex2oat(int argc, char** argv) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700647 InitLogging(argv);
Elliott Hughes72395bf2012-04-24 13:45:26 -0700648
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700649 // Skip over argv[0].
650 argv++;
651 argc--;
652
653 if (argc == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800654 Usage("no arguments specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700655 }
656
657 std::vector<const char*> dex_filenames;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800658 std::vector<const char*> dex_locations;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800659 int zip_fd = -1;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800660 std::string zip_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700661 std::string oat_filename;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800662 std::string oat_symbols;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800663 std::string oat_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800664 int oat_fd = -1;
Logan Chien8b977d32012-02-21 19:14:55 +0800665 std::string bitcode_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800666 const char* image_classes_filename = NULL;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800667 std::string image_filename;
Brian Carlstromb0011262011-12-09 12:17:24 -0800668 std::string boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700669 uintptr_t image_base = 0;
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700670 UniquePtr<std::string> host_prefix;
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800671 std::string android_root;
jeffhao5d840402011-10-24 17:09:45 -0700672 std::vector<const char*> runtime_args;
Elliott Hughes5c599942012-06-13 16:45:05 -0700673 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800674 bool support_debugging = false;
buzbeec531cef2012-10-18 07:09:20 -0700675#if defined(ART_USE_PORTABLE_COMPILER)
676 CompilerBackend compiler_backend = kPortable;
buzbeec531cef2012-10-18 07:09:20 -0700677#else
678 CompilerBackend compiler_backend = kQuick;
679#endif
jeffhao9ad4f222012-05-30 18:51:19 -0700680#if defined(__arm__)
Ian Rogers49c48942012-03-11 15:15:37 -0700681 InstructionSet instruction_set = kThumb2;
jeffhao9ad4f222012-05-30 18:51:19 -0700682#elif defined(__i386__)
683 InstructionSet instruction_set = kX86;
684#elif defined(__mips__)
685 InstructionSet instruction_set = kMips;
686#else
687#error "Unsupported architecture"
688#endif
Brian Carlstrom265091e2013-01-30 14:08:26 -0800689 bool is_host = false;
Elliott Hughes67d92002012-03-26 15:08:51 -0700690 bool dump_stats = kIsDebugBuild;
691 bool dump_timings = kIsDebugBuild;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800692 bool watch_dog_enabled = !kIsTargetBuild;
Brian Carlstrom16192862011-09-12 17:50:06 -0700693
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700694
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700695 for (int i = 0; i < argc; i++) {
696 const StringPiece option(argv[i]);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800697 bool log_options = false;
698 if (log_options) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700699 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
700 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700701 if (option.starts_with("--dex-file=")) {
702 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstroma004aa92012-02-08 18:05:09 -0800703 } else if (option.starts_with("--dex-location=")) {
704 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800705 } else if (option.starts_with("--zip-fd=")) {
706 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800707 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800708 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800709 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800710 } else if (option.starts_with("--zip-location=")) {
711 zip_location = option.substr(strlen("--zip-location=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800712 } else if (option.starts_with("--oat-file=")) {
713 oat_filename = option.substr(strlen("--oat-file=")).data();
Brian Carlstrom265091e2013-01-30 14:08:26 -0800714 } else if (option.starts_with("--oat-symbols=")) {
715 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800716 } else if (option.starts_with("--oat-fd=")) {
717 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800718 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800719 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800720 }
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800721 } else if (option == "-g") {
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800722 support_debugging = true;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800723 } else if (option == "--watch-dog") {
724 watch_dog_enabled = true;
725 } else if (option == "--no-watch-dog") {
726 watch_dog_enabled = false;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800727 } else if (option.starts_with("-j")) {
Brian Carlstromb12552a2012-02-04 17:17:31 -0800728 const char* thread_count_str = option.substr(strlen("-j")).data();
Elliott Hughes5523ee02012-02-03 18:18:34 -0800729 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800730 Usage("could not parse -j argument '%s' as an integer", thread_count_str);
Elliott Hughes5523ee02012-02-03 18:18:34 -0800731 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800732 } else if (option.starts_with("--oat-location=")) {
733 oat_location = option.substr(strlen("--oat-location=")).data();
Logan Chien8b977d32012-02-21 19:14:55 +0800734 } else if (option.starts_with("--bitcode=")) {
735 bitcode_filename = option.substr(strlen("--bitcode=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700736 } else if (option.starts_with("--image=")) {
737 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800738 } else if (option.starts_with("--image-classes=")) {
739 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700740 } else if (option.starts_with("--base=")) {
741 const char* image_base_str = option.substr(strlen("--base=")).data();
742 char* end;
743 image_base = strtoul(image_base_str, &end, 16);
744 if (end == image_base_str || *end != '\0') {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800745 Usage("Failed to parse hexadecimal value for option %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700746 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700747 } else if (option.starts_with("--boot-image=")) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800748 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700749 } else if (option.starts_with("--host-prefix=")) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700750 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800751 } else if (option.starts_with("--android-root=")) {
752 android_root = option.substr(strlen("--android-root=")).data();
Ian Rogers49c48942012-03-11 15:15:37 -0700753 } else if (option.starts_with("--instruction-set=")) {
754 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
jeffhao1f71ae82012-05-24 16:08:24 -0700755 if (instruction_set_str == "arm") {
Ian Rogers49c48942012-03-11 15:15:37 -0700756 instruction_set = kThumb2;
jeffhao1f71ae82012-05-24 16:08:24 -0700757 } else if (instruction_set_str == "mips") {
Ian Rogers49c48942012-03-11 15:15:37 -0700758 instruction_set = kMips;
jeffhao1f71ae82012-05-24 16:08:24 -0700759 } else if (instruction_set_str == "x86") {
Ian Rogers49c48942012-03-11 15:15:37 -0700760 instruction_set = kX86;
761 }
buzbeec531cef2012-10-18 07:09:20 -0700762 } else if (option.starts_with("--compiler-backend=")) {
763 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
764 if (backend_str == "Quick") {
765 compiler_backend = kQuick;
buzbeec531cef2012-10-18 07:09:20 -0700766 } else if (backend_str == "Portable") {
767 compiler_backend = kPortable;
768 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800769 } else if (option == "--host") {
770 is_host = true;
jeffhao5d840402011-10-24 17:09:45 -0700771 } else if (option == "--runtime-arg") {
772 if (++i >= argc) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800773 Usage("Missing required argument for --runtime-arg");
jeffhao5d840402011-10-24 17:09:45 -0700774 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800775 if (log_options) {
776 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
777 }
jeffhao5d840402011-10-24 17:09:45 -0700778 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700779 } else {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800780 Usage("unknown argument %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700781 }
782 }
783
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800784 if (oat_filename.empty() && oat_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800785 Usage("Output must be supplied with either --oat-file or --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800786 }
787
788 if (!oat_filename.empty() && oat_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800789 Usage("--oat-file should not be used with --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800790 }
791
Brian Carlstrom265091e2013-01-30 14:08:26 -0800792 if (!oat_symbols.empty() && oat_fd != -1) {
793 Usage("--oat-symbols should not be used with --oat-fd");
794 }
795
796 if (!oat_symbols.empty() && is_host) {
797 Usage("--oat-symbols should not be used with --host");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800798 }
799
Brian Carlstroma004aa92012-02-08 18:05:09 -0800800 if (oat_fd != -1 && !image_filename.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800801 Usage("--oat-fd should not be used with --image");
Brian Carlstrome24fa612011-09-29 00:53:55 -0700802 }
803
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700804 if (host_prefix.get() == NULL) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800805 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
806 if (android_product_out != NULL) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700807 host_prefix.reset(new std::string(android_product_out));
Brian Carlstromb0011262011-12-09 12:17:24 -0800808 }
809 }
810
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800811 if (android_root.empty()) {
812 const char* android_root_env_var = getenv("ANDROID_ROOT");
813 if (android_root_env_var == NULL) {
Brian Carlstrom54d22c22013-03-13 15:14:57 -0700814 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800815 }
816 android_root += android_root_env_var;
817 }
818
Brian Carlstroma004aa92012-02-08 18:05:09 -0800819 bool image = (!image_filename.empty());
Brian Carlstromb0011262011-12-09 12:17:24 -0800820 if (!image && boot_image_filename.empty()) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700821 if (host_prefix.get() == NULL) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800822 boot_image_filename += GetAndroidRoot();
823 } else {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700824 boot_image_filename += *host_prefix.get();
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800825 boot_image_filename += "/system";
826 }
827 boot_image_filename += "/framework/boot.art";
Brian Carlstromb0011262011-12-09 12:17:24 -0800828 }
829 std::string boot_image_option;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800830 if (!boot_image_filename.empty()) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800831 boot_image_option += "-Ximage:";
832 boot_image_option += boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700833 }
834
Brian Carlstromae826982011-11-09 01:33:42 -0800835 if (image_classes_filename != NULL && !image) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800836 Usage("--image-classes should only be used with --image");
Brian Carlstromae826982011-11-09 01:33:42 -0800837 }
838
839 if (image_classes_filename != NULL && !boot_image_option.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800840 Usage("--image-classes should not be used with --boot-image");
Brian Carlstrom78128a62011-09-15 17:21:19 -0700841 }
842
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800843 if (dex_filenames.empty() && zip_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800844 Usage("Input must be supplied with either --dex-file or --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800845 }
846
847 if (!dex_filenames.empty() && zip_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800848 Usage("--dex-file should not be used with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800849 }
850
Brian Carlstroma004aa92012-02-08 18:05:09 -0800851 if (!dex_filenames.empty() && !zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800852 Usage("--dex-file should not be used with --zip-location");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800853 }
854
Brian Carlstroma004aa92012-02-08 18:05:09 -0800855 if (dex_locations.empty()) {
856 for (size_t i = 0; i < dex_filenames.size(); i++) {
857 dex_locations.push_back(dex_filenames[i]);
858 }
859 } else if (dex_locations.size() != dex_filenames.size()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800860 Usage("--dex-location arguments do not match --dex-file arguments");
Brian Carlstroma004aa92012-02-08 18:05:09 -0800861 }
862
863 if (zip_fd != -1 && zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800864 Usage("--zip-location should be supplied with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800865 }
866
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700867 if (boot_image_option.empty()) {
868 if (image_base == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800869 Usage("non-zero --base not specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700870 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700871 }
872
Brian Carlstrom265091e2013-01-30 14:08:26 -0800873 std::string oat_stripped(oat_filename);
874 std::string oat_unstripped;
875 if (!oat_symbols.empty()) {
876 oat_unstripped += oat_symbols;
877 } else {
878 oat_unstripped += oat_filename;
879 }
880
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800881 // Done with usage checks, enable watchdog if requested
882 WatchDog watch_dog(watch_dog_enabled);
883
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800884 // Check early that the result of compilation can be written
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800885 UniquePtr<File> oat_file;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800886 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700887 if (create_file) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800888 oat_file.reset(OS::OpenFile(oat_unstripped.c_str(), true));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800889 if (oat_location.empty()) {
890 oat_location = oat_filename;
891 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800892 } else {
Elliott Hughes76160052012-12-12 16:31:20 -0800893 oat_file.reset(new File(oat_fd, oat_location));
894 oat_file->DisableAutoClose();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800895 }
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800896 if (oat_file.get() == NULL) {
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700897 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
898 return EXIT_FAILURE;
899 }
900 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
901 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800902 return EXIT_FAILURE;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700903 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800904
Brian Carlstroma004aa92012-02-08 18:05:09 -0800905 LOG(INFO) << "dex2oat: " << oat_location;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700906
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700907 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700908 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800909 std::vector<const DexFile*> boot_class_path;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700910 if (boot_image_option.empty()) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700911 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
912 if (failure_count > 0) {
913 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
914 return EXIT_FAILURE;
915 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800916 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700917 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700918 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
919 }
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700920 if (host_prefix.get() != NULL) {
921 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700922 }
jeffhao5d840402011-10-24 17:09:45 -0700923 for (size_t i = 0; i < runtime_args.size(); i++) {
924 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
925 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700926
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700927#if ART_SMALL_MODE
928 options.push_back(std::make_pair("-small", reinterpret_cast<void*>(NULL)));
929#endif // ART_SMALL_MODE
930
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700931 Dex2Oat* p_dex2oat;
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700932 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count,
933 support_debugging)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700934 LOG(ERROR) << "Failed to create dex2oat";
935 return EXIT_FAILURE;
936 }
937 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
938 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
939 // give it away now and then switch to a more managable ScopedObjectAccess.
940 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
941 // Whilst we're in native take the opportunity to initialize well known classes.
942 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
943 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700944
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800945 // If --image-classes was specified, calculate the full list of classes to include in the image
Brian Carlstrom5f4bd972013-06-06 22:27:40 -0700946 UniquePtr<ImageWriter::DescriptorSet> image_classes(NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800947 if (image_classes_filename != NULL) {
948 image_classes.reset(dex2oat->GetImageClassDescriptors(image_classes_filename));
949 if (image_classes.get() == NULL) {
950 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
951 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700952 }
953 }
954
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800955 std::vector<const DexFile*> dex_files;
956 if (boot_image_option.empty()) {
957 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
958 } else {
959 if (dex_filenames.empty()) {
960 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
961 if (zip_archive.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800962 LOG(ERROR) << "Failed to zip from file descriptor for " << zip_location;
Brian Carlstrom2e3d1b22012-01-09 18:01:56 -0800963 return EXIT_FAILURE;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800964 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800965 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800966 if (dex_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800967 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800968 return EXIT_FAILURE;
969 }
970 dex_files.push_back(dex_file);
971 } else {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700972 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
973 if (failure_count > 0) {
974 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
975 return EXIT_FAILURE;
976 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800977 }
978 }
979
Anwar Ghuloum8447d842013-04-30 17:27:40 -0700980 // If we're in small mode, but the program is small, turn off small mode.
981 // It doesn't make a difference for the boot image, so let's skip the check
982 // altogether.
983 if (Runtime::Current()->IsSmallMode() && !image) {
984 size_t num_methods = 0;
985 for (size_t i = 0; i != dex_files.size(); ++i) {
986 const DexFile* dex_file = dex_files[i];
987 CHECK(dex_file != NULL);
988 num_methods += dex_file->NumMethodIds();
989 }
990 if (num_methods <= Runtime::Current()->GetSmallModeMethodThreshold()) {
991 Runtime::Current()->SetSmallMode(false);
992 LOG(INFO) << "Below method threshold, compiling anyways";
993 }
994 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700995
Ian Rogers1212a022013-03-04 10:48:41 -0800996 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
997 host_prefix.get(),
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800998 android_root,
Brian Carlstrom265091e2013-01-30 14:08:26 -0800999 is_host,
Ian Rogers1212a022013-03-04 10:48:41 -08001000 dex_files,
1001 oat_file.get(),
1002 bitcode_filename,
1003 image,
1004 image_classes.get(),
1005 dump_stats,
1006 dump_timings));
Brian Carlstromf5822582012-03-19 22:34:31 -07001007
1008 if (compiler.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -08001009 LOG(ERROR) << "Failed to create oat file: " << oat_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001010 return EXIT_FAILURE;
1011 }
1012
Brian Carlstrom265091e2013-01-30 14:08:26 -08001013 LOG(INFO) << "Oat file written successfully (unstripped): " << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001014
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001015 // Notes on the interleaving of creating the image and oat file to
1016 // ensure the references between the two are correct.
1017 //
1018 // Currently we have a memory layout that looks something like this:
1019 //
1020 // +--------------+
1021 // | image |
1022 // +--------------+
1023 // | boot oat |
1024 // +--------------+
1025 // | alloc spaces |
1026 // +--------------+
1027 //
1028 // There are several constraints on the loading of the imag and boot.oat.
1029 //
1030 // 1. The image is expected to be loaded at an absolute address and
1031 // contains Objects with absolute pointers within the image.
1032 //
1033 // 2. There are absolute pointers from Methods in the image to their
1034 // code in the oat.
1035 //
1036 // 3. There are absolute pointers from the code in the oat to Methods
1037 // in the image.
1038 //
1039 // 4. There are absolute pointers from code in the oat to other code
1040 // in the oat.
1041 //
1042 // To get this all correct, we go through several steps.
1043 //
1044 // 1. We have already created that oat file above with
1045 // CreateOatFile. Originally this was just our own proprietary file
1046 // but now it is contained within an ELF dynamic object (aka .so
1047 // file). The Compiler returned by CreateOatFile provides
1048 // PatchInformation for references to oat code and Methods that need
1049 // to be update once we know where the oat file will be located
1050 // after the image.
1051 //
1052 // 2. We create the image file. It needs to know where the oat file
1053 // will be loaded after itself. Originally when oat file was simply
1054 // memory mapped so we could predict where its contents were based
1055 // on the file size. Now that it is an ELF file, we need to inspect
1056 // the ELF file to understand the in memory segment layout including
1057 // where the oat header is located within. ImageWriter's
1058 // PatchOatCodeAndMethods uses the PatchInformation from the
1059 // Compiler to touch up absolute references in the oat file.
1060 //
1061 // 3. We fixup the ELF program headers so that dlopen will try to
1062 // load the .so at the desired location at runtime by offsetting the
1063 // Elf32_Phdr.p_vaddr values by the desired base address.
1064 //
Brian Carlstrom265091e2013-01-30 14:08:26 -08001065 if (image) {
1066 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1067 bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1068 image_base,
1069 image_classes.get(),
1070 oat_unstripped,
1071 oat_location,
1072 *compiler.get());
1073 Thread::Current()->TransitionFromSuspendedToRunnable();
1074 LOG(INFO) << "Image written successfully: " << image_filename;
1075 if (!image_creation_success) {
1076 return EXIT_FAILURE;
1077 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001078 }
1079
Brian Carlstrom265091e2013-01-30 14:08:26 -08001080 if (is_host) {
1081 return EXIT_SUCCESS;
1082 }
1083
1084 // If we don't want to strip in place, copy from unstripped location to stripped location.
1085 // We need to strip after image creation because FixupElf needs to use .strtab.
1086 if (oat_unstripped != oat_stripped) {
1087 oat_file.reset();
1088 UniquePtr<File> in(OS::OpenFile(oat_unstripped.c_str(), false));
1089 UniquePtr<File> out(OS::OpenFile(oat_stripped.c_str(), true));
1090 size_t buffer_size = 8192;
1091 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]);
1092 while (true) {
1093 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1094 if (bytes_read <= 0) {
1095 break;
1096 }
1097 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1098 CHECK(write_ok);
1099 }
1100 oat_file.reset(out.release());
1101 LOG(INFO) << "Oat file copied successfully (stripped): " << oat_stripped;
1102 }
1103
1104 // Strip unneeded sections for target
1105 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1106 CHECK_EQ(0, seek_actual);
1107 compiler->StripElf(oat_file.get());
1108
Brian Carlstromae826982011-11-09 01:33:42 -08001109 // We wrote the oat file successfully, and want to keep it.
Brian Carlstrom54d22c22013-03-13 15:14:57 -07001110 LOG(INFO) << "Oat file written successfully (stripped): " << oat_location;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001111 return EXIT_SUCCESS;
1112}
1113
1114} // namespace art
1115
1116int main(int argc, char** argv) {
1117 return art::dex2oat(argc, argv);
1118}