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) {
196 auto& elfHeader = this->elfHeader();
198 // Validate ELF magic numbers
199 if (!(elfHeader.e_ident[EI_MAG0] == ELFMAG0 &&
200 elfHeader.e_ident[EI_MAG1] == ELFMAG1 &&
201 elfHeader.e_ident[EI_MAG2] == ELFMAG2 &&
202 elfHeader.e_ident[EI_MAG3] == ELFMAG3)) {
204 *msg = "invalid ELF magic";
209 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
210 #define P1(a, b) P2(a, b)
211 #define P2(a, b) a##b
212 // Validate ELF class (32/64 bits)
213 if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
215 *msg = "invalid ELF class";
221 #undef EXPECTED_CLASS
223 // Validate ELF data encoding (LSB/MSB)
224 static constexpr auto kExpectedEncoding =
225 kIsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
226 if (elfHeader.e_ident[EI_DATA] != kExpectedEncoding) {
228 *msg = "invalid ELF encoding";
233 // Validate ELF version (1)
234 if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
235 elfHeader.e_version != EV_CURRENT) {
237 *msg = "invalid ELF version";
242 // We only support executable and shared object files
243 if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
245 *msg = "invalid ELF file type";
250 if (elfHeader.e_phnum == 0) {
252 *msg = "no program header!";
257 if (elfHeader.e_phentsize != sizeof(ElfPhdr)) {
259 *msg = "invalid program header entry size";
264 if (elfHeader.e_shentsize != sizeof(ElfShdr)) {
266 *msg = "invalid section header entry size";
270 // Program headers are sorted by load address, so the first PT_LOAD
271 // header gives us the base address.
272 const ElfPhdr* programHeader =
273 iterateProgramHeaders([](auto& h) { return h.p_type == PT_LOAD; });
275 if (!programHeader) {
277 *msg = "could not find base address";
281 baseAddress_ = programHeader->p_vaddr;
286 const ElfShdr* ElfFile::getSectionByIndex(size_t idx) const {
287 FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
288 return &at<ElfShdr>(elfHeader().e_shoff + idx * sizeof(ElfShdr));
291 folly::StringPiece ElfFile::getSectionBody(const ElfShdr& section) const {
292 return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
295 void ElfFile::validateStringTable(const ElfShdr& stringTable) const {
297 stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
299 const char* start = file_ + stringTable.sh_offset;
300 // First and last bytes must be 0
302 stringTable.sh_size == 0 ||
303 (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
304 "invalid string table");
307 const char* ElfFile::getString(const ElfShdr& stringTable, size_t offset)
309 validateStringTable(stringTable);
311 offset < stringTable.sh_size, "invalid offset in string table");
313 return file_ + stringTable.sh_offset + offset;
316 const char* ElfFile::getSectionName(const ElfShdr& section) const {
317 if (elfHeader().e_shstrndx == SHN_UNDEF) {
318 return nullptr; // no section name string table
321 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
322 return getString(sectionNames, section.sh_name);
325 const ElfShdr* ElfFile::getSectionByName(const char* name) const {
326 if (elfHeader().e_shstrndx == SHN_UNDEF) {
327 return nullptr; // no section name string table
330 // Find offset in the section name string table of the requested name
331 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
332 const char* foundName = iterateStrings(
333 sectionNames, [&](const char* s) { return !strcmp(name, s); });
334 if (foundName == nullptr) {
338 size_t offset = foundName - (file_ + sectionNames.sh_offset);
340 // Find section with the appropriate sh_name offset
341 const ElfShdr* foundSection = iterateSections([&](const ElfShdr& sh) {
342 if (sh.sh_name == offset) {
350 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
351 Symbol foundSymbol{nullptr, nullptr};
353 auto findSection = [&](const ElfShdr& section) {
354 auto findSymbols = [&](const ElfSym& sym) {
355 if (sym.st_shndx == SHN_UNDEF) {
356 return false; // not a definition
358 if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
359 foundSymbol.first = §ion;
360 foundSymbol.second = &sym;
367 return iterateSymbolsWithTypes(
368 section, {STT_OBJECT, STT_FUNC, STT_GNU_IFUNC}, findSymbols);
371 // Try the .dynsym section first if it exists, it's smaller.
372 (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
373 iterateSectionsWithType(SHT_SYMTAB, findSection));
378 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
379 Symbol foundSymbol{nullptr, nullptr};
381 auto findSection = [&](const ElfShdr& section) -> bool {
382 // This section has no string table associated w/ its symbols; hence we
383 // can't get names for them
384 if (section.sh_link == SHN_UNDEF) {
388 auto findSymbols = [&](const ElfSym& sym) -> bool {
389 if (sym.st_shndx == SHN_UNDEF) {
390 return false; // not a definition
392 if (sym.st_name == 0) {
393 return false; // no name for this symbol
395 const char* sym_name =
396 getString(*getSectionByIndex(section.sh_link), sym.st_name);
397 if (strcmp(sym_name, name) == 0) {
398 foundSymbol.first = §ion;
399 foundSymbol.second = &sym;
406 return iterateSymbolsWithTypes(
407 section, {STT_OBJECT, STT_FUNC, STT_GNU_IFUNC}, findSymbols);
410 // Try the .dynsym section first if it exists, it's smaller.
411 iterateSectionsWithType(SHT_DYNSYM, findSection) ||
412 iterateSectionsWithType(SHT_SYMTAB, findSection);
417 const ElfShdr* ElfFile::getSectionContainingAddress(ElfAddr addr) const {
418 return iterateSections([&](const ElfShdr& sh) -> bool {
419 return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
423 const char* ElfFile::getSymbolName(Symbol symbol) const {
424 if (!symbol.first || !symbol.second) {
428 if (symbol.second->st_name == 0) {
429 return nullptr; // symbol has no name
432 if (symbol.first->sh_link == SHN_UNDEF) {
433 return nullptr; // symbol table has no strings
437 *getSectionByIndex(symbol.first->sh_link), symbol.second->st_name);
440 } // namespace symbolizer