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 // Program headers are sorted by load address, so the first PT_LOAD
267 // header gives us the base address.
268 const ElfPhdr* programHeader =
269 iterateProgramHeaders([](auto& h) { return h.p_type == PT_LOAD; });
271 if (!programHeader) {
273 *msg = "could not find base address";
277 baseAddress_ = programHeader->p_vaddr;
282 const ElfShdr* ElfFile::getSectionByIndex(size_t idx) const {
283 FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
284 return &at<ElfShdr>(elfHeader().e_shoff + idx * sizeof(ElfShdr));
287 folly::StringPiece ElfFile::getSectionBody(const ElfShdr& section) const {
288 return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
291 void ElfFile::validateStringTable(const ElfShdr& stringTable) const {
293 stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
295 const char* start = file_ + stringTable.sh_offset;
296 // First and last bytes must be 0
298 stringTable.sh_size == 0 ||
299 (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
300 "invalid string table");
303 const char* ElfFile::getString(const ElfShdr& stringTable, size_t offset)
305 validateStringTable(stringTable);
307 offset < stringTable.sh_size, "invalid offset in string table");
309 return file_ + stringTable.sh_offset + offset;
312 const char* ElfFile::getSectionName(const ElfShdr& section) const {
313 if (elfHeader().e_shstrndx == SHN_UNDEF) {
314 return nullptr; // no section name string table
317 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
318 return getString(sectionNames, section.sh_name);
321 const ElfShdr* ElfFile::getSectionByName(const char* name) const {
322 if (elfHeader().e_shstrndx == SHN_UNDEF) {
323 return nullptr; // no section name string table
326 // Find offset in the section name string table of the requested name
327 const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
328 const char* foundName = iterateStrings(
329 sectionNames, [&](const char* s) { return !strcmp(name, s); });
330 if (foundName == nullptr) {
334 size_t offset = foundName - (file_ + sectionNames.sh_offset);
336 // Find section with the appropriate sh_name offset
337 const ElfShdr* foundSection = iterateSections([&](const ElfShdr& sh) {
338 if (sh.sh_name == offset) {
346 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
347 Symbol foundSymbol{nullptr, nullptr};
349 auto findSection = [&](const ElfShdr& section) {
350 auto findSymbols = [&](const ElfSym& sym) {
351 if (sym.st_shndx == SHN_UNDEF) {
352 return false; // not a definition
354 if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
355 foundSymbol.first = §ion;
356 foundSymbol.second = &sym;
363 return iterateSymbolsWithTypes(
364 section, {STT_OBJECT, STT_FUNC}, findSymbols);
367 // Try the .dynsym section first if it exists, it's smaller.
368 (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
369 iterateSectionsWithType(SHT_SYMTAB, findSection));
374 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
375 Symbol foundSymbol{nullptr, nullptr};
377 auto findSection = [&](const ElfShdr& section) -> bool {
378 // This section has no string table associated w/ its symbols; hence we
379 // can't get names for them
380 if (section.sh_link == SHN_UNDEF) {
384 auto findSymbols = [&](const ElfSym& sym) -> bool {
385 if (sym.st_shndx == SHN_UNDEF) {
386 return false; // not a definition
388 if (sym.st_name == 0) {
389 return false; // no name for this symbol
391 const char* sym_name =
392 getString(*getSectionByIndex(section.sh_link), sym.st_name);
393 if (strcmp(sym_name, name) == 0) {
394 foundSymbol.first = §ion;
395 foundSymbol.second = &sym;
402 return iterateSymbolsWithTypes(
403 section, {STT_OBJECT, STT_FUNC}, findSymbols);
406 // Try the .dynsym section first if it exists, it's smaller.
407 iterateSectionsWithType(SHT_DYNSYM, findSection) ||
408 iterateSectionsWithType(SHT_SYMTAB, findSection);
413 const ElfShdr* ElfFile::getSectionContainingAddress(ElfAddr addr) const {
414 return iterateSections([&](const ElfShdr& sh) -> bool {
415 return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
419 const char* ElfFile::getSymbolName(Symbol symbol) const {
420 if (!symbol.first || !symbol.second) {
424 if (symbol.second->st_name == 0) {
425 return nullptr; // symbol has no name
428 if (symbol.first->sh_link == SHN_UNDEF) {
429 return nullptr; // symbol table has no strings
433 *getSectionByIndex(symbol.first->sh_link), symbol.second->st_name);
436 } // namespace symbolizer