blob: 97212ce57d9d2d11722c1a966329731ba3e72a9d [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.");
93 UsageError(" Example: --oat-location=/data/art-cache/system@app@Calculator.apk.oat");
94 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("");
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700140 UsageError(" --light-mode: compile only if generating image file");
141 UsageError("");
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800142 std::cerr << "See log for usage error information\n";
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700143 exit(EXIT_FAILURE);
144}
145
Brian Carlstromae826982011-11-09 01:33:42 -0800146class Dex2Oat {
147 public:
buzbeec531cef2012-10-18 07:09:20 -0700148 static bool Create(Dex2Oat** p_dex2oat, Runtime::Options& options, CompilerBackend compiler_backend,
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700149 InstructionSet instruction_set, size_t thread_count, bool support_debugging,
150 bool light_mode)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700151 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152 if (!CreateRuntime(options, instruction_set)) {
153 *p_dex2oat = NULL;
154 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800155 }
buzbeec531cef2012-10-18 07:09:20 -0700156 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count,
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700157 support_debugging, light_mode);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700158 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800159 }
160
161 ~Dex2Oat() {
162 delete runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800163 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) << " (threads: " << thread_count_ << ")";
Brian Carlstromae826982011-11-09 01:33:42 -0800164 }
165
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700166
Brian Carlstromae826982011-11-09 01:33:42 -0800167 // Make a list of descriptors for classes to include in the image
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700168 const std::set<std::string>* GetImageClassDescriptors(const char* image_classes_filename)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700169 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800170 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
171 if (image_classes_file.get() == NULL) {
172 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
173 return NULL;
174 }
175
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800176 // Load all the classes specified in the file
Brian Carlstromae826982011-11-09 01:33:42 -0800177 ClassLinker* class_linker = runtime_->GetClassLinker();
Ian Rogers1f539342012-10-03 21:09:42 -0700178 Thread* self = Thread::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800179 while (image_classes_file->good()) {
180 std::string dot;
181 std::getline(*image_classes_file.get(), dot);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800182 if (StartsWith(dot, "#") || dot.empty()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800183 continue;
184 }
Elliott Hughes95572412011-12-13 18:14:20 -0800185 std::string descriptor(DotToDescriptor(dot.c_str()));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800186 SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(descriptor.c_str()));
Brian Carlstromae826982011-11-09 01:33:42 -0800187 if (klass.get() == NULL) {
188 LOG(WARNING) << "Failed to find class " << descriptor;
189 Thread::Current()->ClearException();
190 }
191 }
192 image_classes_file->close();
193
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800194 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
195 // exceptions are resolved by the verifier when there is a catch block in an interested method.
196 // Do this here so that exception classes appear to have been specified image classes.
197 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800198 SirtRef<mirror::Class> java_lang_Throwable(self,
Ian Rogers1f539342012-10-03 21:09:42 -0700199 class_linker->FindSystemClass("Ljava/lang/Throwable;"));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800200 do {
201 unresolved_exception_types.clear();
202 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
203 &unresolved_exception_types);
204 typedef std::set<std::pair<uint16_t, const DexFile*> >::const_iterator It; // TODO: C++0x auto
205 for (It it = unresolved_exception_types.begin(),
206 end = unresolved_exception_types.end();
207 it != end; ++it) {
208 uint16_t exception_type_idx = it->first;
209 const DexFile* dex_file = it->second;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800210 mirror::DexCache* dex_cache = class_linker->FindDexCache(*dex_file);
211 mirror:: ClassLoader* class_loader = NULL;
212 SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
213 dex_cache, class_loader));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800214 if (klass.get() == NULL) {
215 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
216 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
217 LOG(FATAL) << "Failed to resolve class " << descriptor;
218 }
Elliott Hughes35be9b12012-05-29 17:59:26 -0700219 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800220 }
221 // Resolving exceptions may load classes that reference more exceptions, iterate until no
222 // more are found
223 } while (!unresolved_exception_types.empty());
224
Brian Carlstromae826982011-11-09 01:33:42 -0800225 // We walk the roots looking for classes so that we'll pick up the
226 // above classes plus any classes them depend on such super
227 // classes, interfaces, and the required ClassLinker roots.
228 UniquePtr<std::set<std::string> > image_classes(new std::set<std::string>());
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800229 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes.get());
Brian Carlstromae826982011-11-09 01:33:42 -0800230 CHECK_NE(image_classes->size(), 0U);
231 return image_classes.release();
232 }
233
Ian Rogers1212a022013-03-04 10:48:41 -0800234 const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800235 const std::string* host_prefix,
236 const std::string& android_root,
237 bool is_host,
238 const std::vector<const DexFile*>& dex_files,
239 File* oat_file,
240 const std::string& bitcode_filename,
241 bool image,
242 const std::set<std::string>* image_classes,
243 bool dump_stats,
244 bool dump_timings)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700245 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800246 // SirtRef and ClassLoader creation needs to come after Runtime::Create
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700247 jobject class_loader = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800248 if (!boot_image_option.empty()) {
249 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromae826982011-11-09 01:33:42 -0800250 std::vector<const DexFile*> class_path_files(dex_files);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800251 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800252 for (size_t i = 0; i < class_path_files.size(); i++) {
253 class_linker->RegisterDexFile(*class_path_files[i]);
254 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700255 ScopedObjectAccessUnchecked soa(Thread::Current());
256 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
257 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
258 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
259 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
260 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800261 }
262
Ian Rogers1212a022013-03-04 10:48:41 -0800263 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_,
264 instruction_set_,
265 image,
266 thread_count_,
267 support_debugging_,
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700268 light_mode_,
Ian Rogers1212a022013-03-04 10:48:41 -0800269 image_classes,
270 dump_stats,
271 dump_timings));
Logan Chien8b977d32012-02-21 19:14:55 +0800272
Ian Rogersc928de92013-02-27 14:30:44 -0800273 if (compiler_backend_ == kPortable) {
Ian Rogers1212a022013-03-04 10:48:41 -0800274 driver->SetBitcodeFileName(bitcode_filename);
buzbeec531cef2012-10-18 07:09:20 -0700275 }
Logan Chien8b977d32012-02-21 19:14:55 +0800276
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700277 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
278
Ian Rogers1212a022013-03-04 10:48:41 -0800279 driver->CompileAll(class_loader, dex_files);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700280
281 Thread::Current()->TransitionFromSuspendedToRunnable();
Brian Carlstromae826982011-11-09 01:33:42 -0800282
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700283 std::string image_file_location;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700284 uint32_t image_file_location_oat_checksum = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800285 uint32_t image_file_location_oat_data_begin = 0;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700286 Heap* heap = Runtime::Current()->GetHeap();
287 if (heap->GetSpaces().size() > 1) {
288 ImageSpace* image_space = heap->GetImageSpace();
Brian Carlstrom28db0122012-10-18 16:20:41 -0700289 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800290 image_file_location_oat_data_begin = reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700291 image_file_location = image_space->GetImageFilename();
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700292 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) {
293 image_file_location = image_file_location.substr(host_prefix->size());
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700294 }
295 }
296
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800297 std::vector<uint8_t> oat_contents;
298 VectorOutputStream vector_output_stream(oat_file->GetPath(), oat_contents);
299 if (!OatWriter::Create(vector_output_stream,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700300 dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700301 image_file_location_oat_checksum,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800302 image_file_location_oat_data_begin,
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700303 image_file_location,
Ian Rogers1212a022013-03-04 10:48:41 -0800304 *driver.get())) {
Elliott Hughes76160052012-12-12 16:31:20 -0800305 LOG(ERROR) << "Failed to create oat file " << oat_file->GetPath();
Brian Carlstromf5822582012-03-19 22:34:31 -0700306 return NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800307 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800308
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800309 if (!driver->WriteElf(android_root, is_host, dex_files, oat_contents, oat_file)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800310 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
311 return NULL;
312 }
313
Ian Rogers1212a022013-03-04 10:48:41 -0800314 return driver.release();
Brian Carlstromae826982011-11-09 01:33:42 -0800315 }
316
Brian Carlstroma004aa92012-02-08 18:05:09 -0800317 bool CreateImageFile(const std::string& image_filename,
Brian Carlstromae826982011-11-09 01:33:42 -0800318 uintptr_t image_base,
319 const std::set<std::string>* image_classes,
320 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -0700321 const std::string& oat_location,
Ian Rogers1212a022013-03-04 10:48:41 -0800322 const CompilerDriver& compiler)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700323 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800324 uintptr_t oat_data_begin;
325 {
326 // ImageWriter is scoped so it can free memory before doing FixupElf
327 ImageWriter image_writer(image_classes);
328 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location, compiler)) {
329 LOG(ERROR) << "Failed to create image file " << image_filename;
330 return false;
331 }
332 oat_data_begin = image_writer.GetOatDataBegin();
333 }
334
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800335 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false));
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800336 if (oat_file.get() == NULL) {
337 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800338 return false;
339 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800340 if (!compiler.FixupElf(oat_file.get(), oat_data_begin)) {
341 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
342 return false;
343 }
Brian Carlstromae826982011-11-09 01:33:42 -0800344 return true;
345 }
346
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700347 void SetLightMode(bool light_mode) {
348 light_mode_ = light_mode;
349 }
350
351 bool GetLightMode() {
352 return light_mode_;
353 }
354
Brian Carlstromae826982011-11-09 01:33:42 -0800355 private:
buzbeec531cef2012-10-18 07:09:20 -0700356 explicit Dex2Oat(Runtime* runtime, CompilerBackend compiler_backend, InstructionSet instruction_set,
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700357 size_t thread_count, bool support_debugging, bool light_mode)
buzbeec531cef2012-10-18 07:09:20 -0700358 : compiler_backend_(compiler_backend),
359 instruction_set_(instruction_set),
Ian Rogers49c48942012-03-11 15:15:37 -0700360 runtime_(runtime),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800361 thread_count_(thread_count),
362 support_debugging_(support_debugging),
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700363 light_mode_(light_mode),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800364 start_ns_(NanoTime()) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800365 }
Brian Carlstromae826982011-11-09 01:33:42 -0800366
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700367 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700368 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700369 if (!Runtime::Create(options, false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800370 LOG(ERROR) << "Failed to create runtime";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700371 return false;
Brian Carlstromae826982011-11-09 01:33:42 -0800372 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700373 Runtime* runtime = Runtime::Current();
Brian Carlstromae826982011-11-09 01:33:42 -0800374 // if we loaded an existing image, we will reuse values from the image roots.
375 if (!runtime->HasJniDlsymLookupStub()) {
Ian Rogers1212a022013-03-04 10:48:41 -0800376 runtime->SetJniDlsymLookupStub(CompilerDriver::CreateJniDlsymLookupStub(instruction_set));
Brian Carlstromae826982011-11-09 01:33:42 -0800377 }
378 if (!runtime->HasAbstractMethodErrorStubArray()) {
Ian Rogers1212a022013-03-04 10:48:41 -0800379 runtime->SetAbstractMethodErrorStubArray(CompilerDriver::CreateAbstractMethodErrorStub(instruction_set));
Brian Carlstromae826982011-11-09 01:33:42 -0800380 }
381 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
382 Runtime::TrampolineType type = Runtime::TrampolineType(i);
383 if (!runtime->HasResolutionStubArray(type)) {
Ian Rogers1212a022013-03-04 10:48:41 -0800384 runtime->SetResolutionStubArray(CompilerDriver::CreateResolutionStub(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800385 }
386 }
Ian Rogers19846512012-02-24 11:42:47 -0800387 if (!runtime->HasResolutionMethod()) {
388 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
389 }
Brian Carlstromae826982011-11-09 01:33:42 -0800390 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
391 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
392 if (!runtime->HasCalleeSaveMethod(type)) {
Ian Rogers49c48942012-03-11 15:15:37 -0700393 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type);
Brian Carlstromae826982011-11-09 01:33:42 -0800394 }
395 }
Ian Rogers19846512012-02-24 11:42:47 -0800396 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700397 return true;
Brian Carlstromae826982011-11-09 01:33:42 -0800398 }
399
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800400 static void ResolveExceptionsForMethod(MethodHelper* mh,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700401 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700402 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800403 const DexFile::CodeItem* code_item = mh->GetCodeItem();
404 if (code_item == NULL) {
405 return; // native or abstract method
406 }
407 if (code_item->tries_size_ == 0) {
408 return; // nothing to process
409 }
410 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
411 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
412 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
413 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
414 bool has_catch_all = false;
415 if (encoded_catch_handler_size <= 0) {
416 encoded_catch_handler_size = -encoded_catch_handler_size;
417 has_catch_all = true;
418 }
419 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
420 uint16_t encoded_catch_handler_handlers_type_idx =
421 DecodeUnsignedLeb128(&encoded_catch_handler_list);
422 // Add to set of types to resolve if not already in the dex cache resolved types
423 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
424 exceptions_to_resolve.insert(
425 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
426 &mh->GetDexFile()));
427 }
428 // ignore address associated with catch handler
429 DecodeUnsignedLeb128(&encoded_catch_handler_list);
430 }
431 if (has_catch_all) {
432 // ignore catch all address
433 DecodeUnsignedLeb128(&encoded_catch_handler_list);
434 }
435 }
436 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700437
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800438 static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700439 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800440 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
441 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
442 MethodHelper mh;
443 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800444 mirror::AbstractMethod* m = c->GetVirtualMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800445 mh.ChangeMethod(m);
446 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
447 }
448 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800449 mirror::AbstractMethod* m = c->GetDirectMethod(i);
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800450 mh.ChangeMethod(m);
451 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
452 }
453 return true;
454 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800456 static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700457 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromae826982011-11-09 01:33:42 -0800458 std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
459 if (klass->IsArrayClass() || klass->IsPrimitive()) {
Jesse Wilson254db0f2011-11-16 16:44:11 -0500460 return true;
461 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800462 image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800463 return true;
Jesse Wilson254db0f2011-11-16 16:44:11 -0500464 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500465
Brian Carlstromae826982011-11-09 01:33:42 -0800466 // Appends to dex_files any elements of class_path that it doesn't already
467 // contain. This will open those dex files as necessary.
468 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
469 std::vector<std::string> parsed;
470 Split(class_path, ':', parsed);
471 for (size_t i = 0; i < parsed.size(); ++i) {
472 if (DexFilesContains(dex_files, parsed[i])) {
473 continue;
474 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800475 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]);
Brian Carlstromae826982011-11-09 01:33:42 -0800476 if (dex_file == NULL) {
477 LOG(WARNING) << "Failed to open dex file " << parsed[i];
478 } else {
479 dex_files.push_back(dex_file);
480 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500481 }
482 }
Brian Carlstromae826982011-11-09 01:33:42 -0800483
484 // Returns true if dex_files has a dex with the named location.
485 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
486 for (size_t i = 0; i < dex_files.size(); ++i) {
487 if (dex_files[i]->GetLocation() == location) {
488 return true;
489 }
490 }
491 return false;
492 }
493
buzbeec531cef2012-10-18 07:09:20 -0700494 const CompilerBackend compiler_backend_;
495
Ian Rogers49c48942012-03-11 15:15:37 -0700496 const InstructionSet instruction_set_;
Brian Carlstromae826982011-11-09 01:33:42 -0800497
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800498 Runtime* runtime_;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800499 size_t thread_count_;
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800500 bool support_debugging_;
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700501 bool light_mode_;
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800502 uint64_t start_ns_;
503
Brian Carlstromae826982011-11-09 01:33:42 -0800504 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
505};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500506
Elliott Hughes72395bf2012-04-24 13:45:26 -0700507static bool ParseInt(const char* in, int* out) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800508 char* end;
509 int result = strtol(in, &end, 10);
510 if (in == end || *end != '\0') {
511 return false;
512 }
513 *out = result;
514 return true;
515}
516
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700517static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
518 const std::vector<const char*>& dex_locations,
519 std::vector<const DexFile*>& dex_files) {
520 size_t failure_count = 0;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800521 for (size_t i = 0; i < dex_filenames.size(); i++) {
522 const char* dex_filename = dex_filenames[i];
Brian Carlstroma004aa92012-02-08 18:05:09 -0800523 const char* dex_location = dex_locations[i];
524 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800525 if (dex_file == NULL) {
jeffhao60f83e32012-02-13 17:16:30 -0800526 LOG(WARNING) << "could not open .dex from file " << dex_filename;
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700527 ++failure_count;
jeffhao60f83e32012-02-13 17:16:30 -0800528 } else {
529 dex_files.push_back(dex_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800530 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800531 }
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700532 return failure_count;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800533}
534
Brian Carlstrombcc29262012-11-02 11:36:03 -0700535// The primary goal of the watchdog is to prevent stuck build servers
536// during development when fatal aborts lead to a cascade of failures
537// that result in a deadlock.
538class WatchDog {
539
540// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
541#undef CHECK_PTHREAD_CALL
542#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
543 do { \
544 int rc = call args; \
545 if (rc != 0) { \
546 errno = rc; \
547 std::string message(# call); \
548 message += " failed for "; \
549 message += reason; \
Brian Carlstromed115642013-03-15 16:04:40 -0700550 Fatal(message); \
Brian Carlstrombcc29262012-11-02 11:36:03 -0700551 } \
552 } while (false)
553
554 public:
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800555 WatchDog(bool is_watch_dog_enabled) {
556 is_watch_dog_enabled_ = is_watch_dog_enabled;
557 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700558 return;
559 }
560 shutting_down_ = false;
561 const char* reason = "dex2oat watch dog thread startup";
562 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason);
563 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason);
564 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
565 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
566 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
567 }
568 ~WatchDog() {
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800569 if (!is_watch_dog_enabled_) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700570 return;
571 }
572 const char* reason = "dex2oat watch dog thread shutdown";
573 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
574 shutting_down_ = true;
575 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
576 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
577
578 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason);
579
580 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
581 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
582 }
583
584 private:
585 static void* CallBack(void* arg) {
586 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
587 self->Wait();
588 return NULL;
589 }
590
Brian Carlstromed115642013-03-15 16:04:40 -0700591 static void Message(char severity, const std::string& message) {
592 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error cases.
593 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
594 kIsDebugBuild ? "d" : "",
595 severity,
596 getpid(),
597 GetTid(),
598 message.c_str());
Ian Rogerseb5cb602013-02-25 15:06:01 -0800599 }
600
Brian Carlstromed115642013-03-15 16:04:40 -0700601 static void Warn(const std::string& message) {
602 Message('W', message);
603 }
604
605 static void Fatal(const std::string& message) {
606 Message('F', message);
Brian Carlstrombcc29262012-11-02 11:36:03 -0700607 exit(1);
608 }
609
610 void Wait() {
Ian Rogerseb5cb602013-02-25 15:06:01 -0800611 bool warning = true;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800612 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
Brian Carlstromed115642013-03-15 16:04:40 -0700613 timespec warning_ts;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800614 InitTimeSpec(true, CLOCK_REALTIME, kWatchDogWarningSeconds * 1000, 0, &warning_ts);
Brian Carlstromed115642013-03-15 16:04:40 -0700615 timespec timeout_ts;
Ian Rogerseb5cb602013-02-25 15:06:01 -0800616 InitTimeSpec(true, CLOCK_REALTIME, kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
Brian Carlstrombcc29262012-11-02 11:36:03 -0700617 const char* reason = "dex2oat watch dog thread waiting";
618 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
619 while (!shutting_down_) {
Ian Rogerseb5cb602013-02-25 15:06:01 -0800620 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
621 warning ? &warning_ts
622 : &timeout_ts));
Brian Carlstrombcc29262012-11-02 11:36:03 -0700623 if (rc == ETIMEDOUT) {
624 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
Ian Rogerseb5cb602013-02-25 15:06:01 -0800625 warning ? kWatchDogWarningSeconds
626 : kWatchDogTimeoutSeconds));
627 if (warning) {
628 Warn(message.c_str());
629 warning = false;
630 } else {
Brian Carlstromed115642013-03-15 16:04:40 -0700631 Fatal(message.c_str());
Ian Rogerseb5cb602013-02-25 15:06:01 -0800632 }
633 } else if (rc != 0) {
Brian Carlstrombcc29262012-11-02 11:36:03 -0700634 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
635 strerror(errno)));
Brian Carlstromed115642013-03-15 16:04:40 -0700636 Fatal(message.c_str());
Brian Carlstrombcc29262012-11-02 11:36:03 -0700637 }
638 }
639 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
640 }
641
Brian Carlstromed115642013-03-15 16:04:40 -0700642 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
643#if ART_USE_PORTABLE_COMPILER
644 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes.
Ian Rogerseb5cb602013-02-25 15:06:01 -0800645 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer.
Brian Carlstrombcc29262012-11-02 11:36:03 -0700646#else
Brian Carlstromed115642013-03-15 16:04:40 -0700647 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute.
648 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer.
Brian Carlstrombcc29262012-11-02 11:36:03 -0700649#endif
650
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800651 bool is_watch_dog_enabled_;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700652 bool shutting_down_;
653 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases
654 pthread_mutex_t mutex_;
655 pthread_cond_t cond_;
656 pthread_attr_t attr_;
657 pthread_t pthread_;
658};
659
Elliott Hughes72395bf2012-04-24 13:45:26 -0700660static int dex2oat(int argc, char** argv) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700661 InitLogging(argv);
Elliott Hughes72395bf2012-04-24 13:45:26 -0700662
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700663 // Skip over argv[0].
664 argv++;
665 argc--;
666
667 if (argc == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800668 Usage("no arguments specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700669 }
670
671 std::vector<const char*> dex_filenames;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800672 std::vector<const char*> dex_locations;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800673 int zip_fd = -1;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800674 std::string zip_location;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700675 std::string oat_filename;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800676 std::string oat_symbols;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800677 std::string oat_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800678 int oat_fd = -1;
Logan Chien8b977d32012-02-21 19:14:55 +0800679 std::string bitcode_filename;
Brian Carlstromae826982011-11-09 01:33:42 -0800680 const char* image_classes_filename = NULL;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800681 std::string image_filename;
Brian Carlstromb0011262011-12-09 12:17:24 -0800682 std::string boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700683 uintptr_t image_base = 0;
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700684 UniquePtr<std::string> host_prefix;
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800685 std::string android_root;
jeffhao5d840402011-10-24 17:09:45 -0700686 std::vector<const char*> runtime_args;
Elliott Hughes5c599942012-06-13 16:45:05 -0700687 int thread_count = sysconf(_SC_NPROCESSORS_CONF);
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800688 bool support_debugging = false;
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700689 bool light_mode = false;
buzbeec531cef2012-10-18 07:09:20 -0700690#if defined(ART_USE_PORTABLE_COMPILER)
691 CompilerBackend compiler_backend = kPortable;
buzbeec531cef2012-10-18 07:09:20 -0700692#else
693 CompilerBackend compiler_backend = kQuick;
694#endif
jeffhao9ad4f222012-05-30 18:51:19 -0700695#if defined(__arm__)
Ian Rogers49c48942012-03-11 15:15:37 -0700696 InstructionSet instruction_set = kThumb2;
jeffhao9ad4f222012-05-30 18:51:19 -0700697#elif defined(__i386__)
698 InstructionSet instruction_set = kX86;
699#elif defined(__mips__)
700 InstructionSet instruction_set = kMips;
701#else
702#error "Unsupported architecture"
703#endif
Brian Carlstrom265091e2013-01-30 14:08:26 -0800704 bool is_host = false;
Elliott Hughes67d92002012-03-26 15:08:51 -0700705 bool dump_stats = kIsDebugBuild;
706 bool dump_timings = kIsDebugBuild;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800707 bool watch_dog_enabled = !kIsTargetBuild;
Brian Carlstrom16192862011-09-12 17:50:06 -0700708
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700709#if ART_LIGHT_MODE
710 light_mode = true;
711#endif // ART_LIGHT_MODE
712
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700713 for (int i = 0; i < argc; i++) {
714 const StringPiece option(argv[i]);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800715 bool log_options = false;
716 if (log_options) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700717 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
718 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700719 if (option.starts_with("--dex-file=")) {
720 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstroma004aa92012-02-08 18:05:09 -0800721 } else if (option.starts_with("--dex-location=")) {
722 dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800723 } else if (option.starts_with("--zip-fd=")) {
724 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800725 if (!ParseInt(zip_fd_str, &zip_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800726 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800727 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800728 } else if (option.starts_with("--zip-location=")) {
729 zip_location = option.substr(strlen("--zip-location=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800730 } else if (option.starts_with("--oat-file=")) {
731 oat_filename = option.substr(strlen("--oat-file=")).data();
Brian Carlstrom265091e2013-01-30 14:08:26 -0800732 } else if (option.starts_with("--oat-symbols=")) {
733 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800734 } else if (option.starts_with("--oat-fd=")) {
735 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800736 if (!ParseInt(oat_fd_str, &oat_fd)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800737 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800738 }
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800739 } else if (option == "-g") {
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800740 support_debugging = true;
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700741 } else if (option == "--light-mode") {
742 light_mode = true;
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800743 } else if (option == "--watch-dog") {
744 watch_dog_enabled = true;
745 } else if (option == "--no-watch-dog") {
746 watch_dog_enabled = false;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800747 } else if (option.starts_with("-j")) {
Brian Carlstromb12552a2012-02-04 17:17:31 -0800748 const char* thread_count_str = option.substr(strlen("-j")).data();
Elliott Hughes5523ee02012-02-03 18:18:34 -0800749 if (!ParseInt(thread_count_str, &thread_count)) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800750 Usage("could not parse -j argument '%s' as an integer", thread_count_str);
Elliott Hughes5523ee02012-02-03 18:18:34 -0800751 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800752 } else if (option.starts_with("--oat-location=")) {
753 oat_location = option.substr(strlen("--oat-location=")).data();
Logan Chien8b977d32012-02-21 19:14:55 +0800754 } else if (option.starts_with("--bitcode=")) {
755 bitcode_filename = option.substr(strlen("--bitcode=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700756 } else if (option.starts_with("--image=")) {
757 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800758 } else if (option.starts_with("--image-classes=")) {
759 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700760 } else if (option.starts_with("--base=")) {
761 const char* image_base_str = option.substr(strlen("--base=")).data();
762 char* end;
763 image_base = strtoul(image_base_str, &end, 16);
764 if (end == image_base_str || *end != '\0') {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800765 Usage("Failed to parse hexadecimal value for option %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700766 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700767 } else if (option.starts_with("--boot-image=")) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800768 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700769 } else if (option.starts_with("--host-prefix=")) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700770 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data()));
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800771 } else if (option.starts_with("--android-root=")) {
772 android_root = option.substr(strlen("--android-root=")).data();
Ian Rogers49c48942012-03-11 15:15:37 -0700773 } else if (option.starts_with("--instruction-set=")) {
774 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
jeffhao1f71ae82012-05-24 16:08:24 -0700775 if (instruction_set_str == "arm") {
Ian Rogers49c48942012-03-11 15:15:37 -0700776 instruction_set = kThumb2;
jeffhao1f71ae82012-05-24 16:08:24 -0700777 } else if (instruction_set_str == "mips") {
Ian Rogers49c48942012-03-11 15:15:37 -0700778 instruction_set = kMips;
jeffhao1f71ae82012-05-24 16:08:24 -0700779 } else if (instruction_set_str == "x86") {
Ian Rogers49c48942012-03-11 15:15:37 -0700780 instruction_set = kX86;
781 }
buzbeec531cef2012-10-18 07:09:20 -0700782 } else if (option.starts_with("--compiler-backend=")) {
783 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
784 if (backend_str == "Quick") {
785 compiler_backend = kQuick;
buzbeec531cef2012-10-18 07:09:20 -0700786 } else if (backend_str == "Portable") {
787 compiler_backend = kPortable;
788 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800789 } else if (option == "--host") {
790 is_host = true;
jeffhao5d840402011-10-24 17:09:45 -0700791 } else if (option == "--runtime-arg") {
792 if (++i >= argc) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800793 Usage("Missing required argument for --runtime-arg");
jeffhao5d840402011-10-24 17:09:45 -0700794 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800795 if (log_options) {
796 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
797 }
jeffhao5d840402011-10-24 17:09:45 -0700798 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700799 } else {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800800 Usage("unknown argument %s", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700801 }
802 }
803
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800804 if (oat_filename.empty() && oat_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800805 Usage("Output must be supplied with either --oat-file or --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800806 }
807
808 if (!oat_filename.empty() && oat_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800809 Usage("--oat-file should not be used with --oat-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800810 }
811
Brian Carlstrom265091e2013-01-30 14:08:26 -0800812 if (!oat_symbols.empty() && oat_fd != -1) {
813 Usage("--oat-symbols should not be used with --oat-fd");
814 }
815
816 if (!oat_symbols.empty() && is_host) {
817 Usage("--oat-symbols should not be used with --host");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800818 }
819
Brian Carlstroma004aa92012-02-08 18:05:09 -0800820 if (oat_fd != -1 && !image_filename.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800821 Usage("--oat-fd should not be used with --image");
Brian Carlstrome24fa612011-09-29 00:53:55 -0700822 }
823
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700824 if (host_prefix.get() == NULL) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800825 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
826 if (android_product_out != NULL) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700827 host_prefix.reset(new std::string(android_product_out));
Brian Carlstromb0011262011-12-09 12:17:24 -0800828 }
829 }
830
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800831 if (android_root.empty()) {
832 const char* android_root_env_var = getenv("ANDROID_ROOT");
833 if (android_root_env_var == NULL) {
Brian Carlstrom54d22c22013-03-13 15:14:57 -0700834 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom3f47c122013-03-07 00:02:40 -0800835 }
836 android_root += android_root_env_var;
837 }
838
Brian Carlstroma004aa92012-02-08 18:05:09 -0800839 bool image = (!image_filename.empty());
Brian Carlstromb0011262011-12-09 12:17:24 -0800840 if (!image && boot_image_filename.empty()) {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700841 if (host_prefix.get() == NULL) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800842 boot_image_filename += GetAndroidRoot();
843 } else {
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700844 boot_image_filename += *host_prefix.get();
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800845 boot_image_filename += "/system";
846 }
847 boot_image_filename += "/framework/boot.art";
Brian Carlstromb0011262011-12-09 12:17:24 -0800848 }
849 std::string boot_image_option;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800850 if (!boot_image_filename.empty()) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800851 boot_image_option += "-Ximage:";
852 boot_image_option += boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700853 }
854
Brian Carlstromae826982011-11-09 01:33:42 -0800855 if (image_classes_filename != NULL && !image) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800856 Usage("--image-classes should only be used with --image");
Brian Carlstromae826982011-11-09 01:33:42 -0800857 }
858
859 if (image_classes_filename != NULL && !boot_image_option.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800860 Usage("--image-classes should not be used with --boot-image");
Brian Carlstrom78128a62011-09-15 17:21:19 -0700861 }
862
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800863 if (dex_filenames.empty() && zip_fd == -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800864 Usage("Input must be supplied with either --dex-file or --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800865 }
866
867 if (!dex_filenames.empty() && zip_fd != -1) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800868 Usage("--dex-file should not be used with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800869 }
870
Brian Carlstroma004aa92012-02-08 18:05:09 -0800871 if (!dex_filenames.empty() && !zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800872 Usage("--dex-file should not be used with --zip-location");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800873 }
874
Brian Carlstroma004aa92012-02-08 18:05:09 -0800875 if (dex_locations.empty()) {
876 for (size_t i = 0; i < dex_filenames.size(); i++) {
877 dex_locations.push_back(dex_filenames[i]);
878 }
879 } else if (dex_locations.size() != dex_filenames.size()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800880 Usage("--dex-location arguments do not match --dex-file arguments");
Brian Carlstroma004aa92012-02-08 18:05:09 -0800881 }
882
883 if (zip_fd != -1 && zip_location.empty()) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800884 Usage("--zip-location should be supplied with --zip-fd");
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800885 }
886
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700887 if (boot_image_option.empty()) {
888 if (image_base == 0) {
Brian Carlstromcbfe6fe2012-02-17 11:13:36 -0800889 Usage("non-zero --base not specified");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700890 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700891 }
892
Brian Carlstrom265091e2013-01-30 14:08:26 -0800893 std::string oat_stripped(oat_filename);
894 std::string oat_unstripped;
895 if (!oat_symbols.empty()) {
896 oat_unstripped += oat_symbols;
897 } else {
898 oat_unstripped += oat_filename;
899 }
900
Brian Carlstrom994d62a2012-11-05 20:43:45 -0800901 // Done with usage checks, enable watchdog if requested
902 WatchDog watch_dog(watch_dog_enabled);
903
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800904 // Check early that the result of compilation can be written
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800905 UniquePtr<File> oat_file;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800906 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700907 if (create_file) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800908 oat_file.reset(OS::OpenFile(oat_unstripped.c_str(), true));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800909 if (oat_location.empty()) {
910 oat_location = oat_filename;
911 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800912 } else {
Elliott Hughes76160052012-12-12 16:31:20 -0800913 oat_file.reset(new File(oat_fd, oat_location));
914 oat_file->DisableAutoClose();
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800915 }
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800916 if (oat_file.get() == NULL) {
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700917 PLOG(ERROR) << "Failed to create oat file: " << oat_location;
918 return EXIT_FAILURE;
919 }
920 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
921 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
Brian Carlstrom6ef827a2011-12-11 14:57:47 -0800922 return EXIT_FAILURE;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700923 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800924
Brian Carlstroma004aa92012-02-08 18:05:09 -0800925 LOG(INFO) << "dex2oat: " << oat_location;
Ian Rogers5e863dd2011-11-02 20:00:10 -0700926
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700927 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700928 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800929 std::vector<const DexFile*> boot_class_path;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700930 if (boot_image_option.empty()) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700931 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
932 if (failure_count > 0) {
933 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
934 return EXIT_FAILURE;
935 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800936 options.push_back(std::make_pair("bootclasspath", &boot_class_path));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700937 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700938 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
939 }
Brian Carlstrom34f1fa42012-04-05 18:28:12 -0700940 if (host_prefix.get() != NULL) {
941 options.push_back(std::make_pair("host-prefix", host_prefix->c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700942 }
jeffhao5d840402011-10-24 17:09:45 -0700943 for (size_t i = 0; i < runtime_args.size(); i++) {
944 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
945 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700946
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700947 Dex2Oat* p_dex2oat;
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700948 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count, support_debugging, light_mode)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700949 LOG(ERROR) << "Failed to create dex2oat";
950 return EXIT_FAILURE;
951 }
952 UniquePtr<Dex2Oat> dex2oat(p_dex2oat);
953 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
954 // give it away now and then switch to a more managable ScopedObjectAccess.
955 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
956 // Whilst we're in native take the opportunity to initialize well known classes.
957 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv());
958 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700959
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800960 // If --image-classes was specified, calculate the full list of classes to include in the image
Brian Carlstromae826982011-11-09 01:33:42 -0800961 UniquePtr<const std::set<std::string> > image_classes(NULL);
962 if (image_classes_filename != NULL) {
963 image_classes.reset(dex2oat->GetImageClassDescriptors(image_classes_filename));
964 if (image_classes.get() == NULL) {
965 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
966 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700967 }
968 }
969
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800970 std::vector<const DexFile*> dex_files;
971 if (boot_image_option.empty()) {
972 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
973 } else {
974 if (dex_filenames.empty()) {
975 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd));
976 if (zip_archive.get() == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800977 LOG(ERROR) << "Failed to zip from file descriptor for " << zip_location;
Brian Carlstrom2e3d1b22012-01-09 18:01:56 -0800978 return EXIT_FAILURE;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800979 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800980 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800981 if (dex_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800982 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location;
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800983 return EXIT_FAILURE;
984 }
985 dex_files.push_back(dex_file);
986 } else {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700987 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
988 if (failure_count > 0) {
989 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
990 return EXIT_FAILURE;
991 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800992 }
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}