blob: 61d445e4e762deb1b838b4e85489b64245ab2c6c [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 Carlstrom69b15fb2011-09-03 12:25:21 -070054 "\n");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070055 fprintf(stderr,
Brian Carlstrom58ae9412011-10-04 00:56:06 -070056 " --host-prefix may be used to translate host paths to target paths during\n"
57 " cross compilation.\n"
58 " Example: --host-prefix=out/target/product/crespo\n"
Brian Carlstrom16192862011-09-12 17:50:06 -070059 "\n");
Brian Carlstrom27ec9612011-09-19 20:20:38 -070060 fprintf(stderr,
jeffhao5d840402011-10-24 17:09:45 -070061 " --runtime-arg <argument>: used to specify various arguments for the runtime,\n"
62 " such as initial heap size, maximum heap size, and verbose output.\n"
63 " Use a separate --runtime-arg switch for each argument.\n"
64 " Example: --runtime-arg -Xms256m\n"
Brian Carlstrom27ec9612011-09-19 20:20:38 -070065 "\n");
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070066 exit(EXIT_FAILURE);
67}
68
Elliott Hughes234da572011-11-03 22:13:06 -070069class FileJanitor {
70public:
71 FileJanitor(const std::string& filename, int fd)
72 : filename_(filename), fd_(fd), do_unlink_(true) {
73 }
74
75 void KeepFile() {
76 do_unlink_ = false;
77 }
78
79 ~FileJanitor() {
80 if (fd_ != -1) {
Elliott Hughesb1f9f222011-11-04 18:04:00 -070081 int rc = TEMP_FAILURE_RETRY(flock(fd_, LOCK_UN));
82 if (rc == -1) {
83 PLOG(ERROR) << "Failed to unlock " << filename_;
84 }
Elliott Hughes234da572011-11-03 22:13:06 -070085 }
86 if (do_unlink_) {
Elliott Hughesb1f9f222011-11-04 18:04:00 -070087 int rc = TEMP_FAILURE_RETRY(unlink(filename_.c_str()));
88 if (rc == -1) {
89 PLOG(ERROR) << "Failed to unlink " << filename_;
90 }
Elliott Hughes234da572011-11-03 22:13:06 -070091 }
92 }
93
94private:
95 std::string filename_;
96 int fd_;
97 bool do_unlink_;
98};
99
Brian Carlstromae826982011-11-09 01:33:42 -0800100class Dex2Oat {
101 public:
102
103 static Dex2Oat* Create(Runtime::Options& options) {
104 UniquePtr<Runtime> runtime(CreateRuntime(options));
105 if (runtime.get() == NULL) {
106 return NULL;
107 }
108 return new Dex2Oat(runtime.release());
109 }
110
111 ~Dex2Oat() {
112 delete runtime_;
113 }
114
115 // Make a list of descriptors for classes to include in the image
116 const std::set<std::string>* GetImageClassDescriptors(const char* image_classes_filename) {
117 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, std::ifstream::in));
118 if (image_classes_file.get() == NULL) {
119 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
120 return NULL;
121 }
122
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800123 // Load all the classes specified in the file
Brian Carlstromae826982011-11-09 01:33:42 -0800124 ClassLinker* class_linker = runtime_->GetClassLinker();
125 while (image_classes_file->good()) {
126 std::string dot;
127 std::getline(*image_classes_file.get(), dot);
128 if (StringPiece(dot).starts_with("#") || dot.empty()) {
129 continue;
130 }
131 std::string descriptor = DotToDescriptor(dot.c_str());
132 SirtRef<Class> klass(class_linker->FindSystemClass(descriptor));
133 if (klass.get() == NULL) {
134 LOG(WARNING) << "Failed to find class " << descriptor;
135 Thread::Current()->ClearException();
136 }
137 }
138 image_classes_file->close();
139
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800140 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
141 // exceptions are resolved by the verifier when there is a catch block in an interested method.
142 // Do this here so that exception classes appear to have been specified image classes.
143 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
144 do {
145 unresolved_exception_types.clear();
146 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
147 &unresolved_exception_types);
148 typedef std::set<std::pair<uint16_t, const DexFile*> >::const_iterator It; // TODO: C++0x auto
149 for (It it = unresolved_exception_types.begin(),
150 end = unresolved_exception_types.end();
151 it != end; ++it) {
152 uint16_t exception_type_idx = it->first;
153 const DexFile* dex_file = it->second;
154 DexCache* dex_cache = class_linker->FindDexCache(*dex_file);
155 ClassLoader* class_loader = NULL;
156 SirtRef<Class> klass(class_linker->ResolveType(*dex_file, exception_type_idx, dex_cache,
157 class_loader));
158 if (klass.get() == NULL) {
159 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
160 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
161 LOG(FATAL) << "Failed to resolve class " << descriptor;
162 }
163 DCHECK(klass->IsThrowableClass());
164 }
165 // Resolving exceptions may load classes that reference more exceptions, iterate until no
166 // more are found
167 } while (!unresolved_exception_types.empty());
168
Brian Carlstromae826982011-11-09 01:33:42 -0800169 // We walk the roots looking for classes so that we'll pick up the
170 // above classes plus any classes them depend on such super
171 // classes, interfaces, and the required ClassLinker roots.
172 UniquePtr<std::set<std::string> > image_classes(new std::set<std::string>());
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800173 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes.get());
Brian Carlstromae826982011-11-09 01:33:42 -0800174 CHECK_NE(image_classes->size(), 0U);
175 return image_classes.release();
176 }
177
178 bool CreateOatFile(const std::string& boot_image_option,
179 const std::vector<const char*>& dex_filenames,
180 const std::string& host_prefix,
181 File* oat_file,
182 bool image,
183 const std::set<std::string>* image_classes) {
184 // SirtRef and ClassLoader creation needs to come after Runtime::Create
185 UniquePtr<SirtRef<ClassLoader> > class_loader(new SirtRef<ClassLoader>(NULL));
186 if (class_loader.get() == NULL) {
187 LOG(ERROR) << "Failed to create SirtRef for class loader";
188 return false;
189 }
190
191 std::vector<const DexFile*> dex_files;
192 if (!boot_image_option.empty()) {
193 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
194 DexFile::OpenDexFiles(dex_filenames, dex_files, host_prefix);
195 std::vector<const DexFile*> class_path_files(dex_files);
196 OpenClassPathFiles(runtime_->GetClassPath(), class_path_files);
197 for (size_t i = 0; i < class_path_files.size(); i++) {
198 class_linker->RegisterDexFile(*class_path_files[i]);
199 }
200 class_loader.get()->reset(PathClassLoader::AllocCompileTime(class_path_files));
201 } else {
202 dex_files = runtime_->GetClassLinker()->GetBootClassPath();
203 }
204
205 Compiler compiler(instruction_set_, image, image_classes);
206 compiler.CompileAll(class_loader->get(), dex_files);
207
208 if (!OatWriter::Create(oat_file, class_loader->get(), compiler)) {
209 LOG(ERROR) << "Failed to create oat file " << oat_file->name();
210 return false;
211 }
212 return true;
213 }
214
215 bool CreateImageFile(const char* image_filename,
216 uintptr_t image_base,
217 const std::set<std::string>* image_classes,
218 const std::string& oat_filename,
219 const std::string& host_prefix) {
220 // If we have an existing boot image, position new space after its oat file
221 if (Heap::GetSpaces().size() > 1) {
222 Space* last_image_space = Heap::GetSpaces()[Heap::GetSpaces().size()-2];
223 CHECK(last_image_space != NULL);
224 CHECK(last_image_space->IsImageSpace());
225 CHECK(!Heap::GetSpaces()[Heap::GetSpaces().size()-1]->IsImageSpace());
226 byte* oat_limit_addr = last_image_space->GetImageHeader().GetOatLimitAddr();
227 image_base = RoundUp(reinterpret_cast<uintptr_t>(oat_limit_addr), kPageSize);
228 }
229
230 ImageWriter image_writer(image_classes);
231 if (!image_writer.Write(image_filename, image_base, oat_filename, host_prefix)) {
232 LOG(ERROR) << "Failed to create image file " << image_filename;
233 return false;
234 }
235 return true;
236 }
237
238 private:
239
240 Dex2Oat(Runtime* runtime) : runtime_(runtime) {}
241
242 static Runtime* CreateRuntime(Runtime::Options& options) {
243 Runtime* runtime = Runtime::Create(options, false);
244 if (runtime == NULL) {
245 LOG(ERROR) << "Failed to create runtime";
246 return NULL;
247 }
248
249 // if we loaded an existing image, we will reuse values from the image roots.
250 if (!runtime->HasJniDlsymLookupStub()) {
251 runtime->SetJniDlsymLookupStub(Compiler::CreateJniDlysmLookupStub(instruction_set_));
252 }
253 if (!runtime->HasAbstractMethodErrorStubArray()) {
254 runtime->SetAbstractMethodErrorStubArray(Compiler::CreateAbstractMethodErrorStub(instruction_set_));
255 }
256 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
257 Runtime::TrampolineType type = Runtime::TrampolineType(i);
258 if (!runtime->HasResolutionStubArray(type)) {
259 runtime->SetResolutionStubArray(Compiler::CreateResolutionStub(instruction_set_, type), type);
260 }
261 }
262 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
263 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
264 if (!runtime->HasCalleeSaveMethod(type)) {
265 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set_, type), type);
266 }
267 }
268 return runtime;
269 }
270
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800271 static void ResolveExceptionsForMethod(MethodHelper* mh,
272 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve) {
273 const DexFile::CodeItem* code_item = mh->GetCodeItem();
274 if (code_item == NULL) {
275 return; // native or abstract method
276 }
277 if (code_item->tries_size_ == 0) {
278 return; // nothing to process
279 }
280 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
281 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
282 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
283 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
284 bool has_catch_all = false;
285 if (encoded_catch_handler_size <= 0) {
286 encoded_catch_handler_size = -encoded_catch_handler_size;
287 has_catch_all = true;
288 }
289 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
290 uint16_t encoded_catch_handler_handlers_type_idx =
291 DecodeUnsignedLeb128(&encoded_catch_handler_list);
292 // Add to set of types to resolve if not already in the dex cache resolved types
293 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
294 exceptions_to_resolve.insert(
295 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
296 &mh->GetDexFile()));
297 }
298 // ignore address associated with catch handler
299 DecodeUnsignedLeb128(&encoded_catch_handler_list);
300 }
301 if (has_catch_all) {
302 // ignore catch all address
303 DecodeUnsignedLeb128(&encoded_catch_handler_list);
304 }
305 }
306 }
307 static bool ResolveCatchBlockExceptionsClassVisitor(Class* c, void* arg) {
308 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
309 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
310 MethodHelper mh;
311 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
312 Method* m = c->GetVirtualMethod(i);
313 mh.ChangeMethod(m);
314 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
315 }
316 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
317 Method* m = c->GetDirectMethod(i);
318 mh.ChangeMethod(m);
319 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
320 }
321 return true;
322 }
323 static bool RecordImageClassesVisitor(Class* klass, void* arg) {
Brian Carlstromae826982011-11-09 01:33:42 -0800324 std::set<std::string>* image_classes = reinterpret_cast<std::set<std::string>*>(arg);
325 if (klass->IsArrayClass() || klass->IsPrimitive()) {
Jesse Wilson254db0f2011-11-16 16:44:11 -0500326 return true;
327 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800328 image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800329 return true;
Jesse Wilson254db0f2011-11-16 16:44:11 -0500330 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500331
Brian Carlstromae826982011-11-09 01:33:42 -0800332 // Appends to dex_files any elements of class_path that it doesn't already
333 // contain. This will open those dex files as necessary.
334 static void OpenClassPathFiles(const std::string& class_path, std::vector<const DexFile*>& dex_files) {
335 std::vector<std::string> parsed;
336 Split(class_path, ':', parsed);
337 for (size_t i = 0; i < parsed.size(); ++i) {
338 if (DexFilesContains(dex_files, parsed[i])) {
339 continue;
340 }
341 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
342 if (dex_file == NULL) {
343 LOG(WARNING) << "Failed to open dex file " << parsed[i];
344 } else {
345 dex_files.push_back(dex_file);
346 }
Jesse Wilson254db0f2011-11-16 16:44:11 -0500347 }
348 }
Brian Carlstromae826982011-11-09 01:33:42 -0800349
350 // Returns true if dex_files has a dex with the named location.
351 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, const std::string& location) {
352 for (size_t i = 0; i < dex_files.size(); ++i) {
353 if (dex_files[i]->GetLocation() == location) {
354 return true;
355 }
356 }
357 return false;
358 }
359
360 Runtime* runtime_;
361 static const InstructionSet instruction_set_ = kThumb2;
362
363 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
364};
Jesse Wilson254db0f2011-11-16 16:44:11 -0500365
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700366int dex2oat(int argc, char** argv) {
367 // Skip over argv[0].
368 argv++;
369 argc--;
370
371 if (argc == 0) {
372 fprintf(stderr, "no arguments specified\n");
373 usage();
374 }
375
376 std::vector<const char*> dex_filenames;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700377 std::string oat_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700378 const char* image_filename = NULL;
Brian Carlstromae826982011-11-09 01:33:42 -0800379 const char* image_classes_filename = NULL;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700380 std::string boot_image_option;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700381 uintptr_t image_base = 0;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700382 std::string host_prefix;
jeffhao5d840402011-10-24 17:09:45 -0700383 std::vector<const char*> runtime_args;
Brian Carlstrom16192862011-09-12 17:50:06 -0700384
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700385 for (int i = 0; i < argc; i++) {
386 const StringPiece option(argv[i]);
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700387 if (false) {
388 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
389 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700390 if (option.starts_with("--dex-file=")) {
391 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700392 } else if (option.starts_with("--oat=")) {
393 oat_filename = option.substr(strlen("--oat=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700394 } else if (option.starts_with("--image=")) {
395 image_filename = option.substr(strlen("--image=")).data();
Brian Carlstromae826982011-11-09 01:33:42 -0800396 } else if (option.starts_with("--image-classes=")) {
397 image_classes_filename = option.substr(strlen("--image-classes=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700398 } else if (option.starts_with("--base=")) {
399 const char* image_base_str = option.substr(strlen("--base=")).data();
400 char* end;
401 image_base = strtoul(image_base_str, &end, 16);
402 if (end == image_base_str || *end != '\0') {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700403 fprintf(stderr, "Failed to parse hexadecimal value for option %s\n", option.data());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700404 usage();
405 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700406 } else if (option.starts_with("--boot-image=")) {
407 const char* boot_image_filename = option.substr(strlen("--boot-image=")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700408 boot_image_option.clear();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700409 boot_image_option += "-Ximage:";
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700410 boot_image_option += boot_image_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700411 } else if (option.starts_with("--host-prefix=")) {
412 host_prefix = option.substr(strlen("--host-prefix=")).data();
jeffhao5d840402011-10-24 17:09:45 -0700413 } else if (option == "--runtime-arg") {
414 if (++i >= argc) {
415 fprintf(stderr, "Missing required argument for --runtime-arg\n");
416 usage();
417 }
418 runtime_args.push_back(argv[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700419 } else {
420 fprintf(stderr, "unknown argument %s\n", option.data());
421 usage();
422 }
423 }
424
Brian Carlstromae826982011-11-09 01:33:42 -0800425 if (oat_filename.empty()) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700426 fprintf(stderr, "--oat file name not specified\n");
427 return EXIT_FAILURE;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700428 }
429
Brian Carlstromae826982011-11-09 01:33:42 -0800430 bool image = (image_filename != NULL);
431 if (!image && boot_image_option.empty()) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700432 fprintf(stderr, "Either --image or --boot-image must be specified\n");
433 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700434 }
435
Brian Carlstromae826982011-11-09 01:33:42 -0800436 if (image_classes_filename != NULL && !image) {
437 fprintf(stderr, "--image-classes should only be used with --image\n");
438 return EXIT_FAILURE;
439 }
440
441 if (image_classes_filename != NULL && !boot_image_option.empty()) {
442 fprintf(stderr, "--image-classes should not be used with --boot-image\n");
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700443 return EXIT_FAILURE;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700444 }
445
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700446 if (boot_image_option.empty()) {
447 if (image_base == 0) {
448 fprintf(stderr, "non-zero --base not specified\n");
449 return EXIT_FAILURE;
450 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700451 }
452
Elliott Hughes234da572011-11-03 22:13:06 -0700453 // Create the output file if we can, or open it read-only if we weren't first.
454 bool did_create = true;
455 int fd = open(oat_filename.c_str(), O_EXCL | O_CREAT | O_TRUNC | O_RDWR, 0666);
456 if (fd == -1) {
457 if (errno != EEXIST) {
Ian Rogers5e863dd2011-11-02 20:00:10 -0700458 PLOG(ERROR) << "Unable to create oat file " << oat_filename;
459 return EXIT_FAILURE;
460 }
Elliott Hughes234da572011-11-03 22:13:06 -0700461 did_create = false;
462 fd = open(oat_filename.c_str(), O_RDONLY);
463 if (fd == -1) {
464 PLOG(ERROR) << "Unable to open oat file for reading " << oat_filename;
465 return EXIT_FAILURE;
466 }
Ian Rogers5e863dd2011-11-02 20:00:10 -0700467 }
Elliott Hughes234da572011-11-03 22:13:06 -0700468
469 // Handles removing the file on failure and unlocking on both failure and success.
Brian Carlstromae826982011-11-09 01:33:42 -0800470 FileJanitor oat_file_janitor(oat_filename, fd);
Elliott Hughes234da572011-11-03 22:13:06 -0700471
Elliott Hughes234da572011-11-03 22:13:06 -0700472 // If we won the creation race, block trying to take the lock (since we're going to be doing
473 // the work, we need the lock). If we lost the creation race, spin trying to take the lock
474 // non-blocking until we fail -- at which point we know the other guy has the lock -- and then
475 // block trying to take the now-taken lock.
476 if (did_create) {
477 LOG(INFO) << "This process created " << oat_filename;
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700478 while (TEMP_FAILURE_RETRY(flock(fd, LOCK_EX)) != 0) {
Elliott Hughes234da572011-11-03 22:13:06 -0700479 // Try again.
480 }
481 LOG(INFO) << "This process created and locked " << oat_filename;
482 } else {
483 LOG(INFO) << "Another process has already created " << oat_filename;
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700484 while (TEMP_FAILURE_RETRY(flock(fd, LOCK_EX | LOCK_NB)) == 0) {
Elliott Hughes234da572011-11-03 22:13:06 -0700485 // Give up the lock and hope the creator has taken the lock next time round.
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700486 int rc = TEMP_FAILURE_RETRY(flock(fd, LOCK_UN));
487 if (rc == -1) {
488 PLOG(FATAL) << "Failed to unlock " << oat_filename;
489 }
Elliott Hughes234da572011-11-03 22:13:06 -0700490 }
491 // Now a non-blocking attempt to take the lock has failed, we know the other guy has the
492 // lock, so block waiting to take it.
493 LOG(INFO) << "Another process is already working on " << oat_filename;
Elliott Hughesb1f9f222011-11-04 18:04:00 -0700494 if (TEMP_FAILURE_RETRY(flock(fd, LOCK_EX)) != 0) {
Elliott Hughes234da572011-11-03 22:13:06 -0700495 PLOG(ERROR) << "Waiter unable to wait for creator to finish " << oat_filename;
496 return EXIT_FAILURE;
497 }
498 // We have the lock and the creator has finished.
499 // TODO: check the creator did a good job by checking the header.
500 LOG(INFO) << "Another process finished working on " << oat_filename;
501 // Job done.
Brian Carlstromae826982011-11-09 01:33:42 -0800502 oat_file_janitor.KeepFile();
Elliott Hughes234da572011-11-03 22:13:06 -0700503 return EXIT_SUCCESS;
504 }
505
506 // If we get this far, we won the creation race and have locked the file.
507 UniquePtr<File> oat_file(OS::FileFromFd(oat_filename.c_str(), fd));
508
509 LOG(INFO) << "dex2oat: " << oat_file->name();
Ian Rogers5e863dd2011-11-02 20:00:10 -0700510
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700511 Runtime::Options options;
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700512 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700513 std::string boot_class_path_string;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700514 if (boot_image_option.empty()) {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700515 boot_class_path_string += "-Xbootclasspath:";
516 for (size_t i = 0; i < dex_filenames.size()-1; i++) {
517 boot_class_path_string += dex_filenames[i];
518 boot_class_path_string += ":";
519 }
520 boot_class_path_string += dex_filenames[dex_filenames.size()-1];
521 options.push_back(std::make_pair(boot_class_path_string.c_str(), reinterpret_cast<void*>(NULL)));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700522 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700523 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL)));
524 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700525 if (!host_prefix.empty()) {
526 options.push_back(std::make_pair("host-prefix", host_prefix.c_str()));
527 }
jeffhao5d840402011-10-24 17:09:45 -0700528 for (size_t i = 0; i < runtime_args.size(); i++) {
529 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL)));
530 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700531
Brian Carlstromae826982011-11-09 01:33:42 -0800532 UniquePtr<Dex2Oat> dex2oat(Dex2Oat::Create(options));
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700533
Brian Carlstromae826982011-11-09 01:33:42 -0800534 // If --image-classes was specified, calculate the full list classes to include in the image
535 UniquePtr<const std::set<std::string> > image_classes(NULL);
536 if (image_classes_filename != NULL) {
537 image_classes.reset(dex2oat->GetImageClassDescriptors(image_classes_filename));
538 if (image_classes.get() == NULL) {
539 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename;
540 return EXIT_FAILURE;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700541 }
542 }
543
Brian Carlstromae826982011-11-09 01:33:42 -0800544 if (!dex2oat->CreateOatFile(boot_image_option,
545 dex_filenames,
546 host_prefix,
547 oat_file.get(),
548 image,
549 image_classes.get())) {
550 LOG(ERROR) << "Failed to create oat file" << oat_filename;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700551 return EXIT_FAILURE;
552 }
553
Brian Carlstromae826982011-11-09 01:33:42 -0800554 if (!image) {
555 oat_file_janitor.KeepFile();
556 LOG(INFO) << "Oat file written successfully " << oat_filename;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700557 return EXIT_SUCCESS;
558 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700559
Brian Carlstromae826982011-11-09 01:33:42 -0800560 if (!dex2oat->CreateImageFile(image_filename,
561 image_base,
562 image_classes.get(),
563 oat_filename,
564 host_prefix)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700565 return EXIT_FAILURE;
566 }
567
Brian Carlstromae826982011-11-09 01:33:42 -0800568 // We wrote the oat file successfully, and want to keep it.
569 oat_file_janitor.KeepFile();
570 LOG(INFO) << "Oat file written successfully " << oat_filename;
Elliott Hughes234da572011-11-03 22:13:06 -0700571 LOG(INFO) << "Image written successfully " << image_filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700572 return EXIT_SUCCESS;
573}
574
575} // namespace art
576
577int main(int argc, char** argv) {
578 return art::dex2oat(argc, argv);
579}