2 * Copyright 2017-present Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #include <folly/experimental/symbolizer/Elf.h>
19 #include <folly/portability/SysMman.h>
21 #include <sys/types.h>
25 #include <glog/logging.h>
27 #include <folly/Conv.h>
28 #include <folly/Exception.h>
29 #include <folly/ScopeGuard.h>
32 namespace symbolizer {
34 ElfFile::ElfFile() noexcept
36 file_(static_cast<char*>(MAP_FAILED)),
40 ElfFile::ElfFile(const char* name, bool readOnly)
42 file_(static_cast<char*>(MAP_FAILED)),
48 void ElfFile::open(const char* name, bool readOnly) {
50 int r = openNoThrow(name, readOnly, &msg);
51 if (r == kSystemError) {
52 throwSystemError(msg);
54 CHECK_EQ(r, kSuccess) << msg;
58 int ElfFile::openNoThrow(
61 const char** msg) noexcept {
62 FOLLY_SAFE_CHECK(fd_ == -1, "File already open");
63 fd_ = ::open(name, readOnly ? O_RDONLY : O_RDWR);
70 // Always close fd and unmap in case of failure along the way to avoid
71 // check failure above if we leave fd != -1 and the object is recycled
72 // like it is inside SignalSafeElfCache
73 ScopeGuard guard = makeGuard([&] { reset(); });
75 int r = fstat(fd_, &st);
88 file_ = static_cast<char*>(mmap(nullptr, length_, prot, MAP_SHARED, fd_, 0));
89 if (file_ == MAP_FAILED) {
97 return kInvalidElfFile;
103 int ElfFile::openAndFollow(
106 const char** msg) noexcept {
107 auto result = openNoThrow(name, readOnly, msg);
108 if (!readOnly || result != kSuccess) {
112 /* NOTE .gnu_debuglink specifies only the name of the debugging info file
113 * (with no directory components). GDB checks 3 different directories, but
114 * ElfFile only supports the first version:
116 * - dirname(name) + /.debug/
117 * - X/dirname(name)/ - where X is set in gdb's `debug-file-directory`.
119 auto dirend = strrchr(name, '/');
120 // include ending '/' if any.
121 auto dirlen = dirend != nullptr ? dirend + 1 - name : 0;
123 auto debuginfo = getSectionByName(".gnu_debuglink");
128 // The section starts with the filename, with any leading directory
129 // components removed, followed by a zero byte.
130 auto debugFileName = getSectionBody(*debuginfo);
131 auto debugFileLen = strlen(debugFileName.begin());
132 if (dirlen + debugFileLen >= PATH_MAX) {
136 char linkname[PATH_MAX];
137 memcpy(linkname, name, dirlen);
138 memcpy(linkname + dirlen, debugFileName.begin(), debugFileLen + 1);
140 result = openNoThrow(linkname, readOnly, msg);
141 if (result == kSuccess) {
144 return openNoThrow(name, readOnly, msg);
147 ElfFile::~ElfFile() {
151 ElfFile::ElfFile(ElfFile&& other) noexcept
154 length_(other.length_),
155 baseAddress_(other.baseAddress_) {
157 other.file_ = static_cast<char*>(MAP_FAILED);
159 other.baseAddress_ = 0;
162 ElfFile& ElfFile::operator=(ElfFile&& other) {
163 assert(this != &other);
168 length_ = other.length_;
169 baseAddress_ = other.baseAddress_;
172 other.file_ = static_cast<char*>(MAP_FAILED);
174 other.baseAddress_ = 0;
179 void ElfFile::reset() {
180 if (file_ != MAP_FAILED) {
181 munmap(file_, length_);
182 file_ = static_cast<char*>(MAP_FAILED);
191 bool ElfFile::init(const char** msg) {
192 auto& elfHeader = this->elfHeader();
194 // Validate ELF magic numbers
195 if (!(elfHeader.e_ident[EI_MAG0] == ELFMAG0 &&
196 elfHeader.e_ident[EI_MAG1] == ELFMAG1 &&
197 elfHeader.e_ident[EI_MAG2] == ELFMAG2 &&
198 elfHeader.e_ident[EI_MAG3] == ELFMAG3)) {
200 *msg = "invalid ELF magic";
205 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
206 #define P1(a, b) P2(a, b)
207 #define P2(a, b) a##b
208 // Validate ELF class (32/64 bits)
209 if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
211 *msg = "invalid ELF class";
217 #undef EXPECTED_CLASS
219 // Validate ELF data encoding (LSB/MSB)
220 static constexpr auto kExpectedEncoding =
221 kIsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
222 if (elfHeader.e_ident[EI_DATA] != kExpectedEncoding) {
224 *msg = "invalid ELF encoding";
229 // Validate ELF version (1)
230 if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
231 elfHeader.e_version != EV_CURRENT) {
233 *msg = "invalid ELF version";
238 // We only support executable and shared object files
239 if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
241 *msg = "invalid ELF file type";
246 if (elfHeader.e_phnum == 0) {
248 *msg = "no program header!";
253 if (elfHeader.e_phentsize != sizeof(ElfPhdr)) {
255 *msg = "invalid program header entry size";
260 if (elfHeader.e_shentsize != sizeof(ElfShdr)) {
262 *msg = "invalid section header entry size";
266 const ElfPhdr* programHeader = &at<ElfPhdr>(elfHeader.e_phoff);
267 bool foundBase = false;
268 for (size_t i = 0; i < elfHeader.e_phnum; programHeader++, i++) {
269 // Program headers are sorted by load address, so the first PT_LOAD
270 // header gives us the base address.
271 if (programHeader->p_type == PT_LOAD) {
272 baseAddress_ = programHeader->p_vaddr;
280 *msg = "could not find base address";
288 const ElfShdr* ElfFile::getSectionByIndex(size_t idx) const {
289 FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
290 return &at<ElfShdr>(elfHeader().e_shoff + idx * sizeof(ElfShdr));
293 folly::StringPiece ElfFile::getSectionBody(const ElfShdr& section) const {
294 return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
297 void ElfFile::validateStringTable(const ElfShdr& stringTable) const {
299 stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
301 const char* start = file_ + stringTable.sh_offset;
302 // First and last bytes must be 0
304 stringTable.sh_size == 0 ||
305 (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
306 "invalid string table");
309 const char* ElfFile::getString(const ElfShdr& stringTable, size_t offset)
311 validateStringTable(stringTable);
313 offset < stringTable.sh_size, "invalid offset in string table");
315 return file_ + stringTable.sh_offset + offset;
318 const char* ElfFile::getSectionName(const ElfShdr& section) const {
319 if (elfHeader().e_shstrndx == SHN_UNDEF) {
320 return nullptr; // no section name string table
323 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
324 return getString(sectionNames, section.sh_name);
327 const ElfShdr* ElfFile::getSectionByName(const char* name) const {
328 if (elfHeader().e_shstrndx == SHN_UNDEF) {
329 return nullptr; // no section name string table
332 // Find offset in the section name string table of the requested name
333 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
334 const char* foundName = iterateStrings(
335 sectionNames, [&](const char* s) { return !strcmp(name, s); });
336 if (foundName == nullptr) {
340 size_t offset = foundName - (file_ + sectionNames.sh_offset);
342 // Find section with the appropriate sh_name offset
343 const ElfShdr* foundSection = iterateSections([&](const ElfShdr& sh) {
344 if (sh.sh_name == offset) {
352 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
353 Symbol foundSymbol{nullptr, nullptr};
355 auto findSection = [&](const ElfShdr& section) {
356 auto findSymbols = [&](const ElfSym& sym) {
357 if (sym.st_shndx == SHN_UNDEF) {
358 return false; // not a definition
360 if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
361 foundSymbol.first = §ion;
362 foundSymbol.second = &sym;
369 return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
370 iterateSymbolsWithType(section, STT_FUNC, findSymbols);
373 // Try the .dynsym section first if it exists, it's smaller.
374 (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
375 iterateSectionsWithType(SHT_SYMTAB, findSection));
380 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
381 Symbol foundSymbol{nullptr, nullptr};
383 auto findSection = [&](const ElfShdr& section) -> bool {
384 // This section has no string table associated w/ its symbols; hence we
385 // can't get names for them
386 if (section.sh_link == SHN_UNDEF) {
390 auto findSymbols = [&](const ElfSym& sym) -> bool {
391 if (sym.st_shndx == SHN_UNDEF) {
392 return false; // not a definition
394 if (sym.st_name == 0) {
395 return false; // no name for this symbol
397 const char* sym_name =
398 getString(*getSectionByIndex(section.sh_link), sym.st_name);
399 if (strcmp(sym_name, name) == 0) {
400 foundSymbol.first = §ion;
401 foundSymbol.second = &sym;
408 return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
409 iterateSymbolsWithType(section, STT_FUNC, findSymbols);
412 // Try the .dynsym section first if it exists, it's smaller.
413 iterateSectionsWithType(SHT_DYNSYM, findSection) ||
414 iterateSectionsWithType(SHT_SYMTAB, findSection);
419 const ElfShdr* ElfFile::getSectionContainingAddress(ElfAddr addr) const {
420 return iterateSections([&](const ElfShdr& sh) -> bool {
421 return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
425 const char* ElfFile::getSymbolName(Symbol symbol) const {
426 if (!symbol.first || !symbol.second) {
430 if (symbol.second->st_name == 0) {
431 return nullptr; // symbol has no name
434 if (symbol.first->sh_link == SHN_UNDEF) {
435 return nullptr; // symbol table has no strings
439 *getSectionByIndex(symbol.first->sh_link), symbol.second->st_name);
442 } // namespace symbolizer