Fix crashing on corrupted ELF binaries with invalid offsets in ELF header.
authorAndrii Nakryiko <andriin@fb.com>
Thu, 21 Dec 2017 20:47:30 +0000 (12:47 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 21 Dec 2017 21:06:16 +0000 (13:06 -0800)
Summary:
There are cases where ELF binaries are running fine, but have slightly
corrupted ELF headers, e.g., with section headers offset pointing beyond boundaries
of file. I'm guessing this is due to running strip or objdump with either some
particular combination of flags or some due to buggy version of those tools. This
change prevents from crashing on such files.

Reviewed By: yfeldblum

Differential Revision: D6616027

fbshipit-source-id: 8cb3ac4475a51d1f1045c395977a6a77fbefffb2

folly/experimental/symbolizer/Elf-inl.h

index 51890e40e455420f16509592e9345033fc07f384..0d435b4cf15caa874256e6264f00f0a9df39702a 100644 (file)
@@ -23,25 +23,37 @@ namespace symbolizer {
 
 template <class Fn>
 const ElfPhdr* ElfFile::iterateProgramHeaders(Fn fn) const {
+  // there exist ELF binaries which execute correctly, but have invalid internal
+  // offset(s) to program/section headers; most probably due to invalid
+  // stripping of symbols
+  if (elfHeader().e_phoff + sizeof(ElfPhdr) >= length_) {
+    return nullptr;
+  }
+
   const ElfPhdr* ptr = &at<ElfPhdr>(elfHeader().e_phoff);
   for (size_t i = 0; i < elfHeader().e_phnum; i++, ptr++) {
     if (fn(*ptr)) {
       return ptr;
     }
   }
-
   return nullptr;
 }
 
 template <class Fn>
 const ElfShdr* ElfFile::iterateSections(Fn fn) const {
+  // there exist ELF binaries which execute correctly, but have invalid internal
+  // offset(s) to program/section headers; most probably due to invalid
+  // stripping of symbols
+  if (elfHeader().e_shoff + sizeof(ElfShdr) >= length_) {
+    return nullptr;
+  }
+
   const ElfShdr* ptr = &at<ElfShdr>(elfHeader().e_shoff);
   for (size_t i = 0; i < elfHeader().e_shnum; i++, ptr++) {
     if (fn(*ptr)) {
       return ptr;
     }
   }
-
   return nullptr;
 }