Fix ElfFile crashing when opening short (<64 bytes) files.
authorAndrii Nakryiko <andriin@fb.com>
Mon, 27 Nov 2017 19:31:18 +0000 (11:31 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Mon, 27 Nov 2017 19:40:20 +0000 (11:40 -0800)
Summary:
ElfFile in init() assumes file is long enough to contain complete
ElfHeader, which is 64 bytes long. This is not true for valid non-ELF files like
short scripts. They shouldn't cause crash.

Reviewed By: myreg

Differential Revision: D6410210

fbshipit-source-id: 28fd017d8de17c431d7d006a1655ade8a95994bd

folly/experimental/symbolizer/Elf.cpp

index 071f1b43ea83ceb3f2adfef2f269b55beb52f219..9cf3d13748d13a6f66fdfcb15c6f7b82c33ef43b 100644 (file)
@@ -193,19 +193,24 @@ void ElfFile::reset() {
 }
 
 bool ElfFile::init(const char** msg) {
-  auto& elfHeader = this->elfHeader();
+  if (length_ < 4) {
+    if (msg) {
+      *msg = "not an ELF file (too short)";
+    }
+    return false;
+  }
 
   // Validate ELF magic numbers
-  if (!(elfHeader.e_ident[EI_MAG0] == ELFMAG0 &&
-        elfHeader.e_ident[EI_MAG1] == ELFMAG1 &&
-        elfHeader.e_ident[EI_MAG2] == ELFMAG2 &&
-        elfHeader.e_ident[EI_MAG3] == ELFMAG3)) {
+  if (file_[EI_MAG0] != ELFMAG0 || file_[EI_MAG1] != ELFMAG1 ||
+      file_[EI_MAG2] != ELFMAG2 || file_[EI_MAG3] != ELFMAG3) {
     if (msg) {
       *msg = "invalid ELF magic";
     }
     return false;
   }
 
+  auto& elfHeader = this->elfHeader();
+
 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
 #define P1(a, b) P2(a, b)
 #define P2(a, b) a##b