Add missing uint32 type to folly::ProgramOptions::gFlagAdders
[folly.git] / folly / experimental / symbolizer / Elf.cpp
index d9160018b49670fa4fb5365c11c21c97b2c31a73..cc643866d432a78528ad48ee757cc1029100dd2a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2017-present Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+#include <folly/experimental/symbolizer/Elf.h>
 
-
-#include "folly/experimental/symbolizer/Elf.h"
-
-#include <sys/mman.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <endian.h>
 #include <fcntl.h>
+#include <folly/portability/SysMman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 
 #include <string>
 
 #include <glog/logging.h>
 
-#include "folly/Conv.h"
-#include "folly/Exception.h"
+#include <folly/Conv.h>
+#include <folly/Exception.h>
+#include <folly/ScopeGuard.h>
 
 namespace folly {
 namespace symbolizer {
 
-ElfFile::ElfFile()
+ElfFile::ElfFile() noexcept
   : fd_(-1),
     file_(static_cast<char*>(MAP_FAILED)),
     length_(0),
     baseAddress_(0) {
 }
 
-ElfFile::ElfFile(const char* name)
-  : fd_(open(name, O_RDONLY)),
+ElfFile::ElfFile(const char* name, bool readOnly)
+  : fd_(-1),
     file_(static_cast<char*>(MAP_FAILED)),
     length_(0),
     baseAddress_(0) {
-  if (fd_ == -1) {
-    folly::throwSystemError("open ", name);
+  open(name, readOnly);
+}
+
+void ElfFile::open(const char* name, bool readOnly) {
+  const char* msg = "";
+  int r = openNoThrow(name, readOnly, &msg);
+  if (r == kSystemError) {
+    throwSystemError(msg);
+  } else {
+    CHECK_EQ(r, kSuccess) << msg;
   }
+}
 
+int ElfFile::openNoThrow(const char* name,
+                         bool readOnly,
+                         const char** msg) noexcept {
+  FOLLY_SAFE_CHECK(fd_ == -1, "File already open");
+  fd_ = ::open(name, readOnly ? O_RDONLY : O_RDWR);
+  if (fd_ == -1) {
+    if (msg) *msg = "open";
+    return kSystemError;
+  }
+  // Always close fd and unmap in case of failure along the way to avoid
+  // check failure above if we leave fd != -1 and the object is recycled
+  // like it is inside SignalSafeElfCache
+  ScopeGuard guard = makeGuard([&]{ reset(); });
   struct stat st;
   int r = fstat(fd_, &st);
   if (r == -1) {
-    folly::throwSystemError("fstat");
+    if (msg) *msg = "fstat";
+    return kSystemError;
   }
 
   length_ = st.st_size;
-  file_ = static_cast<char*>(
-      mmap(nullptr, length_, PROT_READ, MAP_SHARED, fd_, 0));
+  int prot = PROT_READ;
+  if (!readOnly) {
+    prot |= PROT_WRITE;
+  }
+  file_ = static_cast<char*>(mmap(nullptr, length_, prot, MAP_SHARED, fd_, 0));
   if (file_ == MAP_FAILED) {
-    folly::throwSystemError("mmap");
+    if (msg) *msg = "mmap";
+    return kSystemError;
+  }
+  if (!init(msg)) {
+    errno = EINVAL;
+    return kInvalidElfFile;
+  }
+  guard.dismiss();
+  return kSuccess;
+}
+
+int ElfFile::openAndFollow(const char* name,
+                           bool readOnly,
+                           const char** msg) noexcept {
+  auto result = openNoThrow(name, readOnly, msg);
+  if (!readOnly || result != kSuccess) return result;
+
+  /* NOTE .gnu_debuglink specifies only the name of the debugging info file
+   * (with no directory components). GDB checks 3 different directories, but
+   * ElfFile only supports the first version:
+   *     - dirname(name)
+   *     - dirname(name) + /.debug/
+   *     - X/dirname(name)/ - where X is set in gdb's `debug-file-directory`.
+   */
+  auto dirend = strrchr(name, '/');
+  // include ending '/' if any.
+  auto dirlen = dirend != nullptr ? dirend + 1 - name : 0;
+
+  auto debuginfo = getSectionByName(".gnu_debuglink");
+  if (!debuginfo) return result;
+
+  // The section starts with the filename, with any leading directory
+  // components removed, followed by a zero byte.
+  auto debugFileName = getSectionBody(*debuginfo);
+  auto debugFileLen = strlen(debugFileName.begin());
+  if (dirlen + debugFileLen >= PATH_MAX) {
+    return result;
   }
-  init();
+
+  char linkname[PATH_MAX];
+  memcpy(linkname, name, dirlen);
+  memcpy(linkname + dirlen, debugFileName.begin(), debugFileLen + 1);
+  reset();
+  result = openNoThrow(linkname, readOnly, msg);
+  if (result == kSuccess) return result;
+  return openNoThrow(name, readOnly, msg);
 }
 
 ElfFile::~ElfFile() {
-  destroy();
+  reset();
 }
 
-ElfFile::ElfFile(ElfFile&& other)
+ElfFile::ElfFile(ElfFile&& other) noexcept
   : fd_(other.fd_),
     file_(other.file_),
     length_(other.length_),
@@ -81,7 +148,7 @@ ElfFile::ElfFile(ElfFile&& other)
 
 ElfFile& ElfFile::operator=(ElfFile&& other) {
   assert(this != &other);
-  destroy();
+  reset();
 
   fd_ = other.fd_;
   file_ = other.file_;
@@ -96,62 +163,76 @@ ElfFile& ElfFile::operator=(ElfFile&& other) {
   return *this;
 }
 
-void ElfFile::destroy() {
+void ElfFile::reset() {
   if (file_ != MAP_FAILED) {
     munmap(file_, length_);
+    file_ = static_cast<char*>(MAP_FAILED);
   }
 
   if (fd_ != -1) {
     close(fd_);
+    fd_ = -1;
   }
 }
 
-void ElfFile::init() {
+bool ElfFile::init(const char** msg) {
   auto& elfHeader = this->elfHeader();
 
   // Validate ELF magic numbers
-  enforce(elfHeader.e_ident[EI_MAG0] == ELFMAG0 &&
-          elfHeader.e_ident[EI_MAG1] == ELFMAG1 &&
-          elfHeader.e_ident[EI_MAG2] == ELFMAG2 &&
-          elfHeader.e_ident[EI_MAG3] == ELFMAG3,
-          "invalid ELF magic");
+  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 (msg) *msg = "invalid ELF magic";
+    return false;
+  }
 
   // Validate ELF class (32/64 bits)
 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
 #define P1(a, b) P2(a, b)
 #define P2(a, b) a ## b
-  enforce(elfHeader.e_ident[EI_CLASS] == EXPECTED_CLASS,
-          "invalid ELF class");
+  if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
+    if (msg) *msg = "invalid ELF class";
+    return false;
+  }
 #undef P1
 #undef P2
 #undef EXPECTED_CLASS
 
   // Validate ELF data encoding (LSB/MSB)
-#if __BYTE_ORDER == __LITTLE_ENDIAN
-# define EXPECTED_ENCODING ELFDATA2LSB
-#elif __BYTE_ORDER == __BIG_ENDIAN
-# define EXPECTED_ENCODING ELFDATA2MSB
-#else
-# error Unsupported byte order
-#endif
-  enforce(elfHeader.e_ident[EI_DATA] == EXPECTED_ENCODING,
-          "invalid ELF encoding");
-#undef EXPECTED_ENCODING
+  static constexpr auto kExpectedEncoding =
+      kIsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
+  if (elfHeader.e_ident[EI_DATA] != kExpectedEncoding) {
+    if (msg) *msg = "invalid ELF encoding";
+    return false;
+  }
 
   // Validate ELF version (1)
-  enforce(elfHeader.e_ident[EI_VERSION] == EV_CURRENT &&
-          elfHeader.e_version == EV_CURRENT,
-          "invalid ELF version");
+  if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
+      elfHeader.e_version != EV_CURRENT) {
+    if (msg) *msg = "invalid ELF version";
+    return false;
+  }
 
   // We only support executable and shared object files
-  enforce(elfHeader.e_type == ET_EXEC || elfHeader.e_type == ET_DYN,
-          "invalid ELF file type");
+  if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
+    if (msg) *msg = "invalid ELF file type";
+    return false;
+  }
+
+  if (elfHeader.e_phnum == 0) {
+    if (msg) *msg = "no program header!";
+    return false;
+  }
 
-  enforce(elfHeader.e_phnum != 0, "no program header!");
-  enforce(elfHeader.e_phentsize == sizeof(ElfW(Phdr)),
-          "invalid program header entry size");
-  enforce(elfHeader.e_shentsize == sizeof(ElfW(Shdr)),
-          "invalid section header entry size");
+  if (elfHeader.e_phentsize != sizeof(ElfW(Phdr))) {
+    if (msg) *msg = "invalid program header entry size";
+    return false;
+  }
+
+  if (elfHeader.e_shentsize != sizeof(ElfW(Shdr))) {
+    if (msg) *msg = "invalid section header entry size";
+  }
 
   const ElfW(Phdr)* programHeader = &at<ElfW(Phdr)>(elfHeader.e_phoff);
   bool foundBase = false;
@@ -165,11 +246,16 @@ void ElfFile::init() {
     }
   }
 
-  enforce(foundBase, "could not find base address");
+  if (!foundBase) {
+    if (msg) *msg =  "could not find base address";
+    return false;
+  }
+
+  return true;
 }
 
 const ElfW(Shdr)* ElfFile::getSectionByIndex(size_t idx) const {
-  enforce(idx < elfHeader().e_shnum, "invalid section index");
+  FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
   return &at<ElfW(Shdr)>(elfHeader().e_shoff + idx * sizeof(ElfW(Shdr)));
 }
 
@@ -178,19 +264,21 @@ folly::StringPiece ElfFile::getSectionBody(const ElfW(Shdr)& section) const {
 }
 
 void ElfFile::validateStringTable(const ElfW(Shdr)& stringTable) const {
-  enforce(stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
+  FOLLY_SAFE_CHECK(stringTable.sh_type == SHT_STRTAB,
+                   "invalid type for string table");
 
   const char* start = file_ + stringTable.sh_offset;
   // First and last bytes must be 0
-  enforce(stringTable.sh_size == 0 ||
-          (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
-          "invalid string table");
+  FOLLY_SAFE_CHECK(stringTable.sh_size == 0 ||
+                   (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
+                   "invalid string table");
 }
 
 const char* ElfFile::getString(const ElfW(Shdr)& stringTable, size_t offset)
   const {
   validateStringTable(stringTable);
-  enforce(offset < stringTable.sh_size, "invalid offset in string table");
+  FOLLY_SAFE_CHECK(offset < stringTable.sh_size,
+                   "invalid offset in string table");
 
   return file_ + stringTable.sh_offset + offset;
 }
@@ -234,42 +322,76 @@ const ElfW(Shdr)* ElfFile::getSectionByName(const char* name) const {
 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
   Symbol foundSymbol {nullptr, nullptr};
 
-  auto find = [&] (const ElfW(Shdr)& section) {
-    enforce(section.sh_entsize == sizeof(ElfW(Sym)),
-            "invalid entry size in symbol table");
-
-    const ElfW(Sym)* sym = &at<ElfW(Sym)>(section.sh_offset);
-    const ElfW(Sym)* end = &at<ElfW(Sym)>(section.sh_offset + section.sh_size);
-    for (; sym != end; ++sym) {
-      // st_info has the same representation on 32- and 64-bit platforms
-      auto type = ELF32_ST_TYPE(sym->st_info);
-
-      // TODO(tudorb): Handle STT_TLS, but then we'd have to understand
-      // thread-local relocations.  If all we're looking up is functions
-      // (instruction pointers), it doesn't matter, though.
-      if (type != STT_OBJECT && type != STT_FUNC) {
-        continue;
-      }
-      if (sym->st_shndx == SHN_UNDEF) {
-        continue;  // not a definition
+  auto findSection = [&](const ElfW(Shdr)& section) {
+    auto findSymbols = [&](const ElfW(Sym)& sym) {
+      if (sym.st_shndx == SHN_UNDEF) {
+        return false;  // not a definition
       }
-      if (address >= sym->st_value && address < sym->st_value + sym->st_size) {
+      if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
         foundSymbol.first = &section;
-        foundSymbol.second = sym;
+        foundSymbol.second = &sym;
         return true;
       }
+
+      return false;
+    };
+
+    return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
+      iterateSymbolsWithType(section, STT_FUNC, findSymbols);
+  };
+
+  // Try the .dynsym section first if it exists, it's smaller.
+  (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
+   iterateSectionsWithType(SHT_SYMTAB, findSection));
+
+  return foundSymbol;
+}
+
+ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
+  Symbol foundSymbol{nullptr, nullptr};
+
+  auto findSection = [&](const ElfW(Shdr)& section) -> bool {
+    // This section has no string table associated w/ its symbols; hence we
+    // can't get names for them
+    if (section.sh_link == SHN_UNDEF) {
+      return false;
     }
 
-    return false;
+    auto findSymbols = [&](const ElfW(Sym)& sym) -> bool {
+      if (sym.st_shndx == SHN_UNDEF) {
+        return false;  // not a definition
+      }
+      if (sym.st_name == 0) {
+        return false;  // no name for this symbol
+      }
+      const char* sym_name = getString(
+        *getSectionByIndex(section.sh_link), sym.st_name);
+      if (strcmp(sym_name, name) == 0) {
+        foundSymbol.first = &section;
+        foundSymbol.second = &sym;
+        return true;
+      }
+
+      return false;
+    };
+
+    return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
+      iterateSymbolsWithType(section, STT_FUNC, findSymbols);
   };
 
   // Try the .dynsym section first if it exists, it's smaller.
-  (iterateSectionsWithType(SHT_DYNSYM, find) ||
-   iterateSectionsWithType(SHT_SYMTAB, find));
+  iterateSectionsWithType(SHT_DYNSYM, findSection) ||
+    iterateSectionsWithType(SHT_SYMTAB, findSection);
 
   return foundSymbol;
 }
 
+const ElfW(Shdr)* ElfFile::getSectionContainingAddress(ElfW(Addr) addr) const {
+  return iterateSections([&](const ElfW(Shdr)& sh) -> bool {
+    return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
+  });
+}
+
 const char* ElfFile::getSymbolName(Symbol symbol) const {
   if (!symbol.first || !symbol.second) {
     return nullptr;
@@ -289,4 +411,3 @@ const char* ElfFile::getSymbolName(Symbol symbol) const {
 
 }  // namespace symbolizer
 }  // namespace folly
-