blob: eb77c726a3a0c5c07584ca222d7d13f9f48dff0d [file] [log] [blame]
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#include <stdio.h>
4#include <stdlib.h>
Elliott Hughes234da572011-11-03 22:13:06 -07005#include <sys/file.h>
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07006
Brian Carlstromae826982011-11-09 01:33:42 -08007#include <iostream>
8#include <fstream>
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07009#include <string>
10#include <vector>
11
12#include "class_linker.h"
13#include "class_loader.h"
14#include "compiler.h"
Ian Rogers5e863dd2011-11-02 20:00:10 -070015#include "file.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070016#include "image_writer.h"
Ian Rogers6f1dfe42011-12-08 17:28:34 -080017#include "leb128.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070018#include "oat_writer.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080019#include "object_utils.h"
Ian Rogers5e863dd2011-11-02 20:00:10 -070020#include "os.h"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070021#include "runtime.h"
22#include "stringpiece.h"
23
24namespace art {
25
26static void usage() {
27 fprintf(stderr,
28 "Usage: dex2oat [options]...\n"
29 "\n");
30 fprintf(stderr,
Brian Carlstrom78128a62011-09-15 17:21:19 -070031 " --dex-file=<dex-file>: specifies a .dex file to compile. At least one .dex\n"
32 " file must be specified. \n"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070033 " Example: --dex-file=/system/framework/core.jar\n"
34 "\n");
35 fprintf(stderr,
Brian Carlstromae826982011-11-09 01:33:42 -080036 " --oat=<file.oat>: specifies the required oat filename.\n"
37 " Example: --oat=/data/art-cache/boot.oat\n"
38 "\n");
39 fprintf(stderr,
40 " --image=<file.art>: specifies the output image filename.\n"
Brian Carlstrom47a0d5a2011-10-12 21:20:05 -070041 " Example: --image=/data/art-cache/boot.art\n"
Brian Carlstrome24fa612011-09-29 00:53:55 -070042 "\n");
Brian Carlstrome24fa612011-09-29 00:53:55 -070043 fprintf(stderr,
Brian Carlstromae826982011-11-09 01:33:42 -080044 " --image-classes=<classname-file>: specifies classes to include in an image.\n"
45 " Example: --image=frameworks/base/preloaded-classes\n"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070046 "\n");
47 fprintf(stderr,
48 " --base=<hex-address>: specifies the base address when creating a boot image.\n"
49 " Example: --base=0x50000000\n"
50 "\n");
51 fprintf(stderr,
Brian Carlstrome24fa612011-09-29 00:53:55 -070052 " --boot-image=<file.art>: provide the image file for the boot class path.\n"
Brian Carlstrom47a0d5a2011-10-12 21:20:05 -070053 " Example: --boot-image=/data/art-cache/boot.art\n"
Brian Carlstromb0011262011-12-09 12:17:24 -080054 " Default: <host-prefix>/data/art-cache/boot.art\n"
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070055 "\n");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070056 fprintf(stderr,
Brian Carlstrom58ae9412011-10-04 00:56:06 -070057 " --host-prefix may be used to translate host paths to target paths during\n"
58 " cross compilation.\n"
59 " Example: --host-prefix=out/target/product/crespo\n"
Brian Carlstromb0011262011-12-09 12:17:24 -080060 " Default: $ANDROID_PRODUCT_OUT\n"
Brian Carlstrom16192862011-09-12 17:50:06 -070061 "\n");
Brian Carlstrom27ec9612011-09-19 20:20:38 -070062 fprintf(stderr,
jeffhao5d840402011-10-24 17:09:45 -070063 " --runtime-arg <argument>: used to specify various arguments for the runtime,\n"
64 " such as initial heap size, maximum heap size, and verbose output.\n"
65 " Use a separate --runtime-arg switch for each argument.\n"
66 " Example: --runtime-arg -Xms256m\n"
Brian Carlstrom27ec9612011-09-19 20:20:38 -070067 "\n");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070068 exit(EXIT_FAILURE);
69}
70
Elliott Hughes234da572011-11-03 22:13:06 -070071class FileJanitor {
72public:
73 FileJanitor(const std::string& filename, int fd)
74 : filename_(filename), fd_(fd), do_unlink_(true) {
75 }
76
77 void KeepFile() {
78 do_unlink_ = false;
79 }
80
81 ~FileJanitor() {
82 if (fd_ != -1) {
Elliott Hughesb1f9f222011-11-04 18:04:00 -070083 int rc = TEMP_FAILURE_RETRY(flock(fd_, LOCK_UN));
84 if (rc == -1) {
85 PLOG(ERROR) << "Failed to unlock " << filename_;
86 }
Elliott Hughes234da572011-11-03 22:13:06 -070087 }
88 if (do_unlink_) {
Elliott Hughesb1f9f222011-11-04 18:04:00 -070089 int rc = TEMP_FAILURE_RETRY(unlink(filename_.c_str()));
90 if (rc == -1) {
91 PLOG(ERROR) << "Failed to unlink " << filename_;
92 }
Elliott Hughes234da572011-11-03 22:13:06 -070093 }
94 }
95
96private:
97 std::string filename_;
98 int fd_;
99 bool do_unlink_;
100};
101
Brian Carlstromae826982011-11-09 01:33:42 -0800102class Dex2Oat {
103 public:
104
105 static Dex2Oat* Create(Runtime::Options& options) {
106 UniquePtr<Runtime> runtime(CreateRuntime(options));
107 if (runtime.get() == NULL) {
108 return NULL;
109 }
110 return new Dex2Oat(runtime.release());
111 }
112
113 ~Dex2Oat() {
114 delete runtime_;
115 }
116
117 // Make a list of descriptors for classes to include in the image
118 const std::set<std::string>* GetImageClassDescriptors(const char* image_classes_filename) {
119 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
120 if (image_classes_file.get() == NULL) {
121 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
122 return NULL;
123 }
124
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800125 // Load all the classes specified in the file
Brian Carlstromae826982011-11-09 01:33:42 -0800126 ClassLinker* class_linker = runtime_->GetClassLinker();
127 while (image_classes_file->good()) {
128 std::string dot;
129 std::getline(*image_classes_file.get(), dot);
130 if (StringPiece(dot).starts_with("#") || dot.empty()) {
131 continue;
132 }
133 std::string descriptor = DotToDescriptor(dot.c_str());
134 SirtRef<Class> klass(class_linker->FindSystemClass(descriptor));
135 if (klass.get() == NULL) {
136 LOG(WARNING) << "Failed to find class " << descriptor;
137 Thread::Current()->ClearException();
138 }
139 }
140 image_classes_file->close();
141
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800142 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
143 // exceptions are resolved by the verifier when there is a catch block in an interested method.
144 // Do this here so that exception classes appear to have been specified image classes.
145 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
146 do {
147 unresolved_exception_types.clear();
148 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
149 &unresolved_exception_types);
150 typedef std::set<std::pair<uint16_t, const DexFile*> >::const_iterator It; // TODO: C++0x auto
151 for (It it = unresolved_exception_types.begin(),
152 end = unresolved_exception_types.end();
153 it != end; ++it) {
154 uint16_t exception_type_idx = it->first;
155 const DexFile* dex_file = it->second;
156 DexCache* dex_cache = class_linker->FindDexCache(*dex_file);
157 ClassLoader* class_loader = NULL;
158 SirtRef<Class> klass(class_linker->ResolveType(*dex_file, exception_type_idx, dex_cache,
159 class_loader));
160 if (klass.get() == NULL) {
161 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
162 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
163 LOG(FATAL) << "Failed to resolve class " << descriptor;
164 }
165 DCHECK(klass->IsThrowableClass());
166 }
167 // Resolving exceptions may load classes that reference more exceptions, iterate until no
168 // more are found
169 } while (!unresolved_exception_types.empty());
170
Brian Carlstromae826982011-11-09 01:33:42 -0800171 // We walk the roots looking for classes so that we'll pick up the
172 // above classes plus any classes them depend on such super
173 // classes, interfaces, and the required ClassLinker roots.
174 UniquePtr<std::set<std::string> > image_classes(new std::set<std::string>());
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800175 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes.get());
Brian Carlstromae826982011-11-09 01:33:42 -0800176 CHECK_NE(image_classes->size(), 0U);
177 return image_classes.release();
178 }
179
180 bool CreateOatFile(const std::string& boot_image_option,
181 const std::vector<const char*>& dex_filenames,
182 const std::string& host_prefix,
183 File* oat_file,
184 bool image,
185 const std::set<std::string>* image_classes) {
186 // SirtRef and ClassLoader creation needs to come after Runtime::Create
187 UniquePtr<SirtRef<ClassLoader> > class_loader(new SirtRef<ClassLoader>(NULL));
188 if (class_loader.get() == NULL) {
189 LOG(ERROR) << "Failed to create SirtRef for class loader";
190 return false;
191 }
192
193 std::vector<const DexFile*> dex_files;
194 if (!boot_image_option.empty()) {
195 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
196 DexFile::OpenDexFiles(dex_filenames, dex_files, host_prefix);
197 std::vector<const DexFile*> class_path_files(dex_files);
198 OpenClassPathFiles(runtime_->GetClassPath(), class_path_files);
199 for (size_t i = 0; i < class_path_files.size(); i++) {
200 class_linker->RegisterDexFile(*class_path_files[i]);
201 }
202 class_loader.get()->reset(PathClassLoader::AllocCompileTime(class_path_files));
203 } else {
204 dex_files = runtime_->GetClassLinker()->GetBootClassPath();
205 }
206
207 Compiler compiler(instruction_set_, image, image_classes);
208 compiler.CompileAll(class_loader->get(), dex_files);
209
210 if (!OatWriter::Create(oat_file, class_loader->get(), compiler)) {
211 LOG(ERROR) << "Failed to create oat file " << oat_file->name();
212 return false;
213 }
214 return true;
215 }
216
217 bool CreateImageFile(const char* image_filename,
218 uintptr_t image_base,
219 const std::set<std::string>* image_classes,
220 const std::string& oat_filename,
221 const std::string& host_prefix) {
222 // If we have an existing boot image, position new space after its oat file
223 if (Heap::GetSpaces().size() > 1) {
224 Space* last_image_space = Heap::GetSpaces()[Heap::GetSpaces().size()-2];
225 CHECK(last_image_space != NULL);
226 CHECK(last_image_space->IsImageSpace());
227 CHECK(!Heap::GetSpaces()[Heap::GetSpaces().size()-1]->IsImageSpace());
228 byte* oat_limit_addr = last_image_space->GetImageHeader().GetOatLimitAddr();
229 image_base = RoundUp(reinterpret_cast<uintptr_t>(oat_limit_addr), kPageSize);
230 }
231
232 ImageWriter image_writer(image_classes);
233 if (!image_writer.Write(image_filename, image_base, oat_filename, host_prefix)) {
234 LOG(ERROR) << "Failed to create image file " << image_filename;
235 return false;
236 }
237 return true;
238 }
239
240 private:
241
242 Dex2Oat(Runtime* runtime) : runtime_(runtime) {}
243
244 static Runtime* CreateRuntime(Runtime::Options& options) {
245 Runtime* runtime = Runtime::Create(options, false);
246 if (runtime == NULL) {
247 LOG(ERROR) << "Failed to create runtime";
248 return NULL;
249 }
250
251 // if we loaded an existing image, we will reuse values from the image roots.
252 if (!runtime->HasJniDlsymLookupStub()) {
253 runtime->SetJniDlsymLookupStub(Compiler::CreateJniDlysmLookupStub(instruction_set_));
254 }
255 if (!runtime->HasAbstractMethodErrorStubArray()) {
256 runtime->SetAbstractMethodErrorStubArray(Compiler::CreateAbstractMethodErrorStub(instruction_set_));
257 }
258 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
259 Runtime::TrampolineType type = Runtime::TrampolineType(i);
260 if (!runtime->HasResolutionStubArray(type)) {
261 runtime->SetResolutionStubArray(Compiler::CreateResolutionStub(instruction_set_, type), type);
262 }
263 }
264 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
265 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
266 if (!runtime->HasCalleeSaveMethod(type)) {
267 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set_, type), type);
268 }
269 }
270 return runtime;
271 }
272
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800273 static void ResolveExceptionsForMethod(MethodHelper* mh,
274 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve) {
275 const DexFile::CodeItem* code_item = mh->GetCodeItem();
276 if (code_item == NULL) {
277 return; // native or abstract method
278 }
279 if (code_item->tries_size_ == 0) {
280 return; // nothing to process
281 }
282 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
283 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
284 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
285 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
286 bool has_catch_all = false;
287 if (encoded_catch_handler_size <= 0) {
288 encoded_catch_handler_size = -encoded_catch_handler_size;
289 has_catch_all = true;
290 }
291 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
292 uint16_t encoded_catch_handler_handlers_type_idx =
293 DecodeUnsignedLeb128(&encoded_catch_handler_list);
294 // Add to set of types to resolve if not already in the dex cache resolved types
295 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
296 exceptions_to_resolve.insert(
297 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
298 &mh->GetDexFile()));
299 }
300 // ignore address associated with catch handler
301 DecodeUnsignedLeb128(&encoded_catch_handler_list);
302 }
303 if (has_catch_all) {
304 // ignore catch all address
305 DecodeUnsignedLeb128(&encoded_catch_handler_list);
306 }
307 }
308 }
309 static bool ResolveCatchBlockExceptionsClassVisitor(Class* c, void* arg) {
310 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
311 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
312 MethodHelper mh;
313 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
314 Method* m = c->GetVirtualMethod(i);
315 mh.ChangeMethod(m);
316 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
317 }
318 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
319 Method* m = c->GetDirectMethod(i);
320 mh.ChangeMethod(m);
321 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
322 }
323 return true;
324 }
325 static bool RecordImageClassesVisitor(Class* klass, void* arg) {
Brian Carlstromae826982011-11-09 01:33:42 -0800326 std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
327 if (klass->IsArrayClass() || klass->IsPrimitive()) {
Jesse Wilson254db0f2011-11-16 16:44:11 -0500328 return true;
329 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800330 image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800331 return true;
Jesse Wilson254db0f2011-11-16 16:44:11 -0500332 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500333
Brian Carlstromae826982011-11-09 01:33:42 -0800334 // Appends to dex_files any elements of class_path that it doesn't already
335 // contain. This will open those dex files as necessary.
336 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
337 std::vector<std::string> parsed;
338 Split(class_path, ':', parsed);
339 for (size_t i = 0; i < parsed.size(); ++i) {
340 if (DexFilesContains(dex_files, parsed[i])) {
341 continue;
342 }
343 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
344 if (dex_file == NULL) {
345 LOG(WARNING) << "Failed to open dex file " << parsed[i];
346 } else {
347 dex_files.push_back(dex_file);
348 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500349 }
350 }
Brian Carlstromae826982011-11-09 01:33:42 -0800351
352 // Returns true if dex_files has a dex with the named location.
353 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
354 for (size_t i = 0; i < dex_files.size(); ++i) {
355 if (dex_files[i]->GetLocation() == location) {
356 return true;
357 }
358 }
359 return false;
360 }
361
362 Runtime* runtime_;
363 static const InstructionSet instruction_set_ = kThumb2;
364
365 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
366};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500367
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700368int dex2oat(int argc, char** argv) {
369 // Skip over argv[0].
370 argv++;
371 argc--;
372
373 if (argc == 0) {
374 fprintf(stderr, "no arguments specified\n");
375 usage();
376 }
377
378 std::vector<const char*> dex_filenames;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700379 std::string oat_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700380 const char* image_filename = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800381 const char* image_classes_filename = NULL;
Brian Carlstromb0011262011-12-09 12:17:24 -0800382 std::string boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700383 uintptr_t image_base = 0;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700384 std::string host_prefix;
jeffhao5d840402011-10-24 17:09:45 -0700385 std::vector<const char*> runtime_args;
Brian Carlstrom16192862011-09-12 17:50:06 -0700386
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700387 for (int i = 0; i < argc; i++) {
388 const StringPiece option(argv[i]);
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700389 if (false) {
390 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
391 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700392 if (option.starts_with("--dex-file=")) {
393 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700394 } else if (option.starts_with("--oat=")) {
395 oat_filename = option.substr(strlen("--oat=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700396 } else if (option.starts_with("--image=")) {
397 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800398 } else if (option.starts_with("--image-classes=")) {
399 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700400 } else if (option.starts_with("--base=")) {
401 const char* image_base_str = option.substr(strlen("--base=")).data();
402 char* end;
403 image_base = strtoul(image_base_str, &end, 16);
404 if (end == image_base_str || *end != '\0') {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700405 fprintf(stderr, "Failed to parse hexadecimal value for option %s\n", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700406 usage();
407 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700408 } else if (option.starts_with("--boot-image=")) {
Brian Carlstromb0011262011-12-09 12:17:24 -0800409 boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700410 } else if (option.starts_with("--host-prefix=")) {
411 host_prefix = option.substr(strlen("--host-prefix=")).data();
jeffhao5d840402011-10-24 17:09:45 -0700412 } else if (option == "--runtime-arg") {
413 if (++i >= argc) {
414 fprintf(stderr, "Missing required argument for --runtime-arg\n");
415 usage();
416 }
417 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700418 } else {
419 fprintf(stderr, "unknown argument %s\n", option.data());
420 usage();
421 }
422 }
423
Brian Carlstromae826982011-11-09 01:33:42 -0800424 if (oat_filename.empty()) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700425 fprintf(stderr, "--oat file name not specified\n");
426 return EXIT_FAILURE;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700427 }
428
Brian Carlstromb0011262011-12-09 12:17:24 -0800429 if (host_prefix.empty()) {
430 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT");
431 if (android_product_out != NULL) {
432 host_prefix = android_product_out;
433 }
434 }
435
Brian Carlstromae826982011-11-09 01:33:42 -0800436 bool image = (image_filename != NULL);
Brian Carlstromb0011262011-12-09 12:17:24 -0800437 if (!image && boot_image_filename.empty()) {
438 boot_image_filename += host_prefix;
439 boot_image_filename += "/data/art-cache/boot.art";
440 }
441 std::string boot_image_option;
442 if (boot_image_filename != NULL) {
443 boot_image_option += "-Ximage:";
444 boot_image_option += boot_image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700445 }
446
Brian Carlstromae826982011-11-09 01:33:42 -0800447 if (image_classes_filename != NULL && !image) {
448 fprintf(stderr, "--image-classes should only be used with --image\n");
449 return EXIT_FAILURE;
450 }
451
452 if (image_classes_filename != NULL && !boot_image_option.empty()) {
453 fprintf(stderr, "--image-classes should not be used with --boot-image\n");
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700454 return EXIT_FAILURE;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700455 }
456
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700457 if (boot_image_option.empty()) {
458 if (image_base == 0) {
459 fprintf(stderr, "non-zero --base not specified\n");
460 return EXIT_FAILURE;
461 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700462 }
463
Elliott Hughes234da572011-11-03 22:13:06 -0700464 // Create the output file if we can, or open it read-only if we weren't first.
465 bool did_create = true;
466 int fd = open(oat_filename.c_str(), O_EXCL | O_CREAT | O_TRUNC | O_RDWR, 0666);
467 if (fd == -1) {
468 if (errno != EEXIST) {
Ian Rogers5e863dd2011-11-02 20:00:10 -0700469 PLOG(ERROR) << "Unable to create oat file " << oat_filename;
470 return EXIT_FAILURE;
471 }
Elliott Hughes234da572011-11-03 22:13:06 -0700472 did_create = false;
473 fd = open(oat_filename.c_str(), O_RDONLY);
474 if (fd == -1) {
475 PLOG(ERROR) << "Unable to open oat file for reading " << oat_filename;
476 return EXIT_FAILURE;
477 }
Ian Rogers5e863dd2011-11-02 20:00:10 -0700478 }
Elliott Hughes234da572011-11-03 22:13:06 -0700479
480 // Handles removing the file on failure and unlocking on both failure and success.
Brian Carlstromae826982011-11-09 01:33:42 -0800481 FileJanitor oat_file_janitor(oat_filename, fd);
Elliott Hughes234da572011-11-03 22:13:06 -0700482
Elliott Hughes234da572011-11-03 22:13:06 -0700483 // If we won the creation race, block trying to take the lock (since we're going to be doing
484 // the work, we need the lock). If we lost the creation race, spin trying to take the lock
485 // non-blocking until we fail -- at which point we know the other guy has the lock -- and then
486 // block trying to take the now-taken lock.
487 if (did_create) {
488 LOG(INFO) << "This process created " << oat_filename;
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700489 while (TEMP_FAILURE_RETRY(flock(fd, LOCK_EX)) != 0) {
Elliott Hughes234da572011-11-03 22:13:06 -0700490 // Try again.
491 }
492 LOG(INFO) << "This process created and locked " << oat_filename;
493 } else {
494 LOG(INFO) << "Another process has already created " << oat_filename;
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700495 while (TEMP_FAILURE_RETRY(flock(fd, LOCK_EX | LOCK_NB)) == 0) {
Elliott Hughes234da572011-11-03 22:13:06 -0700496 // Give up the lock and hope the creator has taken the lock next time round.
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700497 int rc = TEMP_FAILURE_RETRY(flock(fd, LOCK_UN));
498 if (rc == -1) {
499 PLOG(FATAL) << "Failed to unlock " << oat_filename;
500 }
Elliott Hughes234da572011-11-03 22:13:06 -0700501 }
502 // Now a non-blocking attempt to take the lock has failed, we know the other guy has the
503 // lock, so block waiting to take it.
504 LOG(INFO) << "Another process is already working on " << oat_filename;
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700505 if (TEMP_FAILURE_RETRY(flock(fd, LOCK_EX)) != 0) {
Elliott Hughes234da572011-11-03 22:13:06 -0700506 PLOG(ERROR) << "Waiter unable to wait for creator to finish " << oat_filename;
507 return EXIT_FAILURE;
508 }
509 // We have the lock and the creator has finished.
510 // TODO: check the creator did a good job by checking the header.
511 LOG(INFO) << "Another process finished working on " << oat_filename;
512 // Job done.
Brian Carlstromae826982011-11-09 01:33:42 -0800513 oat_file_janitor.KeepFile();
Elliott Hughes234da572011-11-03 22:13:06 -0700514 return EXIT_SUCCESS;
515 }
516
517 // If we get this far, we won the creation race and have locked the file.
518 UniquePtr<File> oat_file(OS::FileFromFd(oat_filename.c_str(), fd));
519
520 LOG(INFO) << "dex2oat: " << oat_file->name();
Ian Rogers5e863dd2011-11-02 20:00:10 -0700521
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700522 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700523 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700524 std::string boot_class_path_string;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700525 if (boot_image_option.empty()) {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700526 boot_class_path_string += "-Xbootclasspath:";
527 for (size_t i = 0; i < dex_filenames.size()-1; i++) {
528 boot_class_path_string += dex_filenames[i];
529 boot_class_path_string += ":";
530 }
531 boot_class_path_string += dex_filenames[dex_filenames.size()-1];
532 options.push_back(std::make_pair(boot_class_path_string.c_str(), reinterpret_cast<void*>(NULL)));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700533 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700534 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
535 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700536 if (!host_prefix.empty()) {
537 options.push_back(std::make_pair("host-prefix", host_prefix.c_str()));
538 }
jeffhao5d840402011-10-24 17:09:45 -0700539 for (size_t i = 0; i < runtime_args.size(); i++) {
540 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
541 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700542
Brian Carlstromae826982011-11-09 01:33:42 -0800543 UniquePtr<Dex2Oat> dex2oat(Dex2Oat::Create(options));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700544
Brian Carlstromae826982011-11-09 01:33:42 -0800545 // If --image-classes was specified, calculate the full list classes to include in the image
546 UniquePtr<const std::set<std::string> > image_classes(NULL);
547 if (image_classes_filename != NULL) {
548 image_classes.reset(dex2oat->GetImageClassDescriptors(image_classes_filename));
549 if (image_classes.get() == NULL) {
550 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
551 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700552 }
553 }
554
Brian Carlstromae826982011-11-09 01:33:42 -0800555 if (!dex2oat->CreateOatFile(boot_image_option,
556 dex_filenames,
557 host_prefix,
558 oat_file.get(),
559 image,
560 image_classes.get())) {
561 LOG(ERROR) << "Failed to create oat file" << oat_filename;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700562 return EXIT_FAILURE;
563 }
564
Brian Carlstromae826982011-11-09 01:33:42 -0800565 if (!image) {
566 oat_file_janitor.KeepFile();
567 LOG(INFO) << "Oat file written successfully " << oat_filename;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700568 return EXIT_SUCCESS;
569 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700570
Brian Carlstromae826982011-11-09 01:33:42 -0800571 if (!dex2oat->CreateImageFile(image_filename,
572 image_base,
573 image_classes.get(),
574 oat_filename,
575 host_prefix)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700576 return EXIT_FAILURE;
577 }
578
Brian Carlstromae826982011-11-09 01:33:42 -0800579 // We wrote the oat file successfully, and want to keep it.
580 oat_file_janitor.KeepFile();
581 LOG(INFO) << "Oat file written successfully " << oat_filename;
Elliott Hughes234da572011-11-03 22:13:06 -0700582 LOG(INFO) << "Image written successfully " << image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700583 return EXIT_SUCCESS;
584}
585
586} // namespace art
587
588int main(int argc, char** argv) {
589 return art::dex2oat(argc, argv);
590}