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 #define STT_GNU_IFUNC 10
36 namespace symbolizer {
38 ElfFile::ElfFile() noexcept
40 file_(static_cast<char*>(MAP_FAILED)),
44 ElfFile::ElfFile(const char* name, bool readOnly)
46 file_(static_cast<char*>(MAP_FAILED)),
52 void ElfFile::open(const char* name, bool readOnly) {
54 int r = openNoThrow(name, readOnly, &msg);
55 if (r == kSystemError) {
56 throwSystemError(msg);
58 CHECK_EQ(r, kSuccess) << msg;
62 int ElfFile::openNoThrow(
65 const char** msg) noexcept {
66 FOLLY_SAFE_CHECK(fd_ == -1, "File already open");
67 fd_ = ::open(name, readOnly ? O_RDONLY : O_RDWR);
74 // Always close fd and unmap in case of failure along the way to avoid
75 // check failure above if we leave fd != -1 and the object is recycled
76 // like it is inside SignalSafeElfCache
77 ScopeGuard guard = makeGuard([&] { reset(); });
79 int r = fstat(fd_, &st);
92 file_ = static_cast<char*>(mmap(nullptr, length_, prot, MAP_SHARED, fd_, 0));
93 if (file_ == MAP_FAILED) {
101 return kInvalidElfFile;
107 int ElfFile::openAndFollow(
110 const char** msg) noexcept {
111 auto result = openNoThrow(name, readOnly, msg);
112 if (!readOnly || result != kSuccess) {
116 /* NOTE .gnu_debuglink specifies only the name of the debugging info file
117 * (with no directory components). GDB checks 3 different directories, but
118 * ElfFile only supports the first version:
120 * - dirname(name) + /.debug/
121 * - X/dirname(name)/ - where X is set in gdb's `debug-file-directory`.
123 auto dirend = strrchr(name, '/');
124 // include ending '/' if any.
125 auto dirlen = dirend != nullptr ? dirend + 1 - name : 0;
127 auto debuginfo = getSectionByName(".gnu_debuglink");
132 // The section starts with the filename, with any leading directory
133 // components removed, followed by a zero byte.
134 auto debugFileName = getSectionBody(*debuginfo);
135 auto debugFileLen = strlen(debugFileName.begin());
136 if (dirlen + debugFileLen >= PATH_MAX) {
140 char linkname[PATH_MAX];
141 memcpy(linkname, name, dirlen);
142 memcpy(linkname + dirlen, debugFileName.begin(), debugFileLen + 1);
144 result = openNoThrow(linkname, readOnly, msg);
145 if (result == kSuccess) {
148 return openNoThrow(name, readOnly, msg);
151 ElfFile::~ElfFile() {
155 ElfFile::ElfFile(ElfFile&& other) noexcept
158 length_(other.length_),
159 baseAddress_(other.baseAddress_) {
161 other.file_ = static_cast<char*>(MAP_FAILED);
163 other.baseAddress_ = 0;
166 ElfFile& ElfFile::operator=(ElfFile&& other) {
167 assert(this != &other);
172 length_ = other.length_;
173 baseAddress_ = other.baseAddress_;
176 other.file_ = static_cast<char*>(MAP_FAILED);
178 other.baseAddress_ = 0;
183 void ElfFile::reset() {
184 if (file_ != MAP_FAILED) {
185 munmap(file_, length_);
186 file_ = static_cast<char*>(MAP_FAILED);
195 bool ElfFile::init(const char** msg) {
198 *msg = "not an ELF file (too short)";
203 // Validate ELF magic numbers
204 if (file_[EI_MAG0] != ELFMAG0 || file_[EI_MAG1] != ELFMAG1 ||
205 file_[EI_MAG2] != ELFMAG2 || file_[EI_MAG3] != ELFMAG3) {
207 *msg = "invalid ELF magic";
212 auto& elfHeader = this->elfHeader();
214 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
215 #define P1(a, b) P2(a, b)
216 #define P2(a, b) a##b
217 // Validate ELF class (32/64 bits)
218 if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
220 *msg = "invalid ELF class";
226 #undef EXPECTED_CLASS
228 // Validate ELF data encoding (LSB/MSB)
229 static constexpr auto kExpectedEncoding =
230 kIsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
231 if (elfHeader.e_ident[EI_DATA] != kExpectedEncoding) {
233 *msg = "invalid ELF encoding";
238 // Validate ELF version (1)
239 if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
240 elfHeader.e_version != EV_CURRENT) {
242 *msg = "invalid ELF version";
247 // We only support executable and shared object files
248 if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
250 *msg = "invalid ELF file type";
255 if (elfHeader.e_phnum == 0) {
257 *msg = "no program header!";
262 if (elfHeader.e_phentsize != sizeof(ElfPhdr)) {
264 *msg = "invalid program header entry size";
269 if (elfHeader.e_shentsize != sizeof(ElfShdr)) {
271 *msg = "invalid section header entry size";
275 // Program headers are sorted by load address, so the first PT_LOAD
276 // header gives us the base address.
277 const ElfPhdr* programHeader =
278 iterateProgramHeaders([](auto& h) { return h.p_type == PT_LOAD; });
280 if (!programHeader) {
282 *msg = "could not find base address";
286 baseAddress_ = programHeader->p_vaddr;
291 const ElfShdr* ElfFile::getSectionByIndex(size_t idx) const {
292 FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
293 return &at<ElfShdr>(elfHeader().e_shoff + idx * sizeof(ElfShdr));
296 folly::StringPiece ElfFile::getSectionBody(const ElfShdr& section) const {
297 return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
300 void ElfFile::validateStringTable(const ElfShdr& stringTable) const {
302 stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
304 const char* start = file_ + stringTable.sh_offset;
305 // First and last bytes must be 0
307 stringTable.sh_size == 0 ||
308 (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
309 "invalid string table");
312 const char* ElfFile::getString(const ElfShdr& stringTable, size_t offset)
314 validateStringTable(stringTable);
316 offset < stringTable.sh_size, "invalid offset in string table");
318 return file_ + stringTable.sh_offset + offset;
321 const char* ElfFile::getSectionName(const ElfShdr& section) const {
322 if (elfHeader().e_shstrndx == SHN_UNDEF) {
323 return nullptr; // no section name string table
326 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
327 return getString(sectionNames, section.sh_name);
330 const ElfShdr* ElfFile::getSectionByName(const char* name) const {
331 if (elfHeader().e_shstrndx == SHN_UNDEF) {
332 return nullptr; // no section name string table
335 // Find offset in the section name string table of the requested name
336 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
337 const char* foundName = iterateStrings(
338 sectionNames, [&](const char* s) { return !strcmp(name, s); });
339 if (foundName == nullptr) {
343 size_t offset = foundName - (file_ + sectionNames.sh_offset);
345 // Find section with the appropriate sh_name offset
346 const ElfShdr* foundSection = iterateSections([&](const ElfShdr& sh) {
347 if (sh.sh_name == offset) {
355 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
356 Symbol foundSymbol{nullptr, nullptr};
358 auto findSection = [&](const ElfShdr& section) {
359 auto findSymbols = [&](const ElfSym& sym) {
360 if (sym.st_shndx == SHN_UNDEF) {
361 return false; // not a definition
363 if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
364 foundSymbol.first = §ion;
365 foundSymbol.second = &sym;
372 return iterateSymbolsWithTypes(
373 section, {STT_OBJECT, STT_FUNC, STT_GNU_IFUNC}, findSymbols);
376 // Try the .dynsym section first if it exists, it's smaller.
377 (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
378 iterateSectionsWithType(SHT_SYMTAB, findSection));
383 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
384 Symbol foundSymbol{nullptr, nullptr};
386 auto findSection = [&](const ElfShdr& section) -> bool {
387 // This section has no string table associated w/ its symbols; hence we
388 // can't get names for them
389 if (section.sh_link == SHN_UNDEF) {
393 auto findSymbols = [&](const ElfSym& sym) -> bool {
394 if (sym.st_shndx == SHN_UNDEF) {
395 return false; // not a definition
397 if (sym.st_name == 0) {
398 return false; // no name for this symbol
400 const char* sym_name =
401 getString(*getSectionByIndex(section.sh_link), sym.st_name);
402 if (strcmp(sym_name, name) == 0) {
403 foundSymbol.first = §ion;
404 foundSymbol.second = &sym;
411 return iterateSymbolsWithTypes(
412 section, {STT_OBJECT, STT_FUNC, STT_GNU_IFUNC}, findSymbols);
415 // Try the .dynsym section first if it exists, it's smaller.
416 iterateSectionsWithType(SHT_DYNSYM, findSection) ||
417 iterateSectionsWithType(SHT_SYMTAB, findSection);
422 const ElfShdr* ElfFile::getSectionContainingAddress(ElfAddr addr) const {
423 return iterateSections([&](const ElfShdr& sh) -> bool {
424 return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
428 const char* ElfFile::getSymbolName(Symbol symbol) const {
429 if (!symbol.first || !symbol.second) {
433 if (symbol.second->st_name == 0) {
434 return nullptr; // symbol has no name
437 if (symbol.first->sh_link == SHN_UNDEF) {
438 return nullptr; // symbol table has no strings
442 *getSectionByIndex(symbol.first->sh_link), symbol.second->st_name);
445 } // namespace symbolizer