From f1b3030832bb33efb9161d851b2915d7d94bedf7 Mon Sep 17 00:00:00 2001
From: Brian Carlstrom <bdc@google.com>
Date: Thu, 28 Mar 2013 10:35:32 -0700
Subject: Gracefully valdiate oat magic on OatFile::Open

Change-Id: If234c2bfae2a7211caed0b7471d7661f2e69e2f0
---
 src/oat_file.cc | 16 +++++++++-------
 src/oat_file.h  |  2 +-
 2 files changed, 10 insertions(+), 8 deletions(-)

diff --git a/src/oat_file.cc b/src/oat_file.cc
index 7c4085e..92ebae3 100644
--- a/src/oat_file.cc
+++ b/src/oat_file.cc
@@ -52,8 +52,7 @@ OatFile* OatFile::OpenMemory(std::vector<uint8_t>& oat_contents,
   UniquePtr<OatFile> oat_file(new OatFile(location));
   oat_file->begin_ = &oat_contents[0];
   oat_file->end_ = &oat_contents[oat_contents.size()];
-  oat_file->Setup();
-  return oat_file.release();
+  return oat_file->Setup() ? oat_file.release() : NULL;
 }
 
 OatFile* OatFile::Open(const std::string& filename,
@@ -160,8 +159,7 @@ bool OatFile::Dlopen(const std::string& elf_filename, byte* requested_base) {
   }
   // Readjust to be non-inclusive upper bound.
   end_ += sizeof(uint32_t);
-  Setup();
-  return true;
+  return Setup();
 }
 
 bool OatFile::ElfFileOpen(File* file, byte* requested_base, bool writable) {
@@ -196,11 +194,14 @@ bool OatFile::ElfFileOpen(File* file, byte* requested_base, bool writable) {
   }
   // Readjust to be non-inclusive upper bound.
   end_ += sizeof(uint32_t);
-  Setup();
-  return true;
+  return Setup();
 }
 
-void OatFile::Setup() {
+bool OatFile::Setup() {
+  if (!GetOatHeader().IsValid()) {
+    LOG(WARNING) << "Invalid oat magic for " << GetLocation();
+    return false;
+  }
   const byte* oat = Begin();
   oat += sizeof(OatHeader);
   oat += GetOatHeader().GetImageFileLocationSize();
@@ -250,6 +251,7 @@ void OatFile::Setup() {
                                                          dex_file_pointer,
                                                          methods_offsets_pointer));
   }
+  return true;
 }
 
 const OatHeader& OatFile::GetOatHeader() const {
diff --git a/src/oat_file.h b/src/oat_file.h
index e71db47..1814f19 100644
--- a/src/oat_file.h
+++ b/src/oat_file.h
@@ -230,7 +230,7 @@ class OatFile {
   explicit OatFile(const std::string& filename);
   bool Dlopen(const std::string& elf_filename, byte* requested_base);
   bool ElfFileOpen(File* file, byte* requested_base, bool writable);
-  void Setup();
+  bool Setup();
 
   const byte* Begin() const;
   const byte* End() const;
-- 
cgit v1.1