Make dex2oat fail early if it can't write oat file

Change-Id: I4097110a76b5b5b3729c236d6cc6e47e2519ebe0
diff --git a/src/dex2oat.cc b/src/dex2oat.cc
index 1b7d9a3..9b6c74e 100644
--- a/src/dex2oat.cc
+++ b/src/dex2oat.cc
@@ -9,8 +9,10 @@
 #include "class_linker.h"
 #include "class_loader.h"
 #include "compiler.h"
+#include "file.h"
 #include "image_writer.h"
 #include "oat_writer.h"
+#include "os.h"
 #include "runtime.h"
 #include "stringpiece.h"
 
@@ -141,6 +143,17 @@
     }
   }
 
+  // Check early that the result of compilation can be written
+  if (OS::FileExists(oat_filename.c_str())) {
+    // File exists, check we can write to it
+    UniquePtr<File> file(OS::OpenFile(oat_filename.c_str(), true));
+    if (file.get() == NULL) {
+      PLOG(ERROR) << "Unable to create oat file " << oat_filename;
+      return EXIT_FAILURE;
+    }
+  }
+  LOG(INFO) << "dex2oat: " << oat_filename;
+
   Runtime::Options options;
   options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL)));
   std::string boot_class_path_string;