2 * Copyright 2016 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.
18 #include <folly/experimental/symbolizer/Elf.h>
21 #include <sys/types.h>
27 #include <glog/logging.h>
29 #include <folly/Conv.h>
30 #include <folly/Exception.h>
31 #include <folly/ScopeGuard.h>
34 namespace symbolizer {
36 ElfFile::ElfFile() noexcept
38 file_(static_cast<char*>(MAP_FAILED)),
43 ElfFile::ElfFile(const char* name, bool readOnly)
45 file_(static_cast<char*>(MAP_FAILED)),
51 void ElfFile::open(const char* name, bool readOnly) {
53 int r = openNoThrow(name, readOnly, &msg);
54 if (r == kSystemError) {
55 throwSystemError(msg);
57 CHECK_EQ(r, kSuccess) << msg;
61 int ElfFile::openNoThrow(const char* name,
63 const char** msg) noexcept {
64 FOLLY_SAFE_CHECK(fd_ == -1, "File already open");
65 fd_ = ::open(name, readOnly ? O_RDONLY : O_RDWR);
67 if (msg) *msg = "open";
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);
77 if (msg) *msg = "fstat";
86 file_ = static_cast<char*>(mmap(nullptr, length_, prot, MAP_SHARED, fd_, 0));
87 if (file_ == MAP_FAILED) {
88 if (msg) *msg = "mmap";
93 return kInvalidElfFile;
99 int ElfFile::openAndFollow(const char* name,
101 const char** msg) noexcept {
102 auto result = openNoThrow(name, readOnly, msg);
103 if (!readOnly || result != kSuccess) return result;
105 /* NOTE .gnu_debuglink specifies only the name of the debugging info file
106 * (with no directory components). GDB checks 3 different directories, but
107 * ElfFile only supports the first version:
109 * - dirname(name) + /.debug/
110 * - X/dirname(name)/ - where X is set in gdb's `debug-file-directory`.
112 auto dirend = strrchr(name, '/');
113 // include ending '/' if any.
114 auto dirlen = dirend != nullptr ? dirend + 1 - name : 0;
116 auto debuginfo = getSectionByName(".gnu_debuglink");
117 if (!debuginfo) return result;
119 // The section starts with the filename, with any leading directory
120 // components removed, followed by a zero byte.
121 auto debugFileName = getSectionBody(*debuginfo);
122 auto debugFileLen = strlen(debugFileName.begin());
123 if (dirlen + debugFileLen >= PATH_MAX) {
127 char linkname[PATH_MAX];
128 memcpy(linkname, name, dirlen);
129 memcpy(linkname + dirlen, debugFileName.begin(), debugFileLen + 1);
131 result = openNoThrow(linkname, readOnly, msg);
132 if (result == kSuccess) return result;
133 return openNoThrow(name, readOnly, msg);
136 ElfFile::~ElfFile() {
140 ElfFile::ElfFile(ElfFile&& other) noexcept
143 length_(other.length_),
144 baseAddress_(other.baseAddress_) {
146 other.file_ = static_cast<char*>(MAP_FAILED);
148 other.baseAddress_ = 0;
151 ElfFile& ElfFile::operator=(ElfFile&& other) {
152 assert(this != &other);
157 length_ = other.length_;
158 baseAddress_ = other.baseAddress_;
161 other.file_ = static_cast<char*>(MAP_FAILED);
163 other.baseAddress_ = 0;
168 void ElfFile::reset() {
169 if (file_ != MAP_FAILED) {
170 munmap(file_, length_);
171 file_ = static_cast<char*>(MAP_FAILED);
180 bool ElfFile::init(const char** msg) {
181 auto& elfHeader = this->elfHeader();
183 // Validate ELF magic numbers
184 if (!(elfHeader.e_ident[EI_MAG0] == ELFMAG0 &&
185 elfHeader.e_ident[EI_MAG1] == ELFMAG1 &&
186 elfHeader.e_ident[EI_MAG2] == ELFMAG2 &&
187 elfHeader.e_ident[EI_MAG3] == ELFMAG3)) {
188 if (msg) *msg = "invalid ELF magic";
192 // Validate ELF class (32/64 bits)
193 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
194 #define P1(a, b) P2(a, b)
195 #define P2(a, b) a ## b
196 if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
197 if (msg) *msg = "invalid ELF class";
202 #undef EXPECTED_CLASS
204 // Validate ELF data encoding (LSB/MSB)
205 static constexpr auto kExpectedEncoding =
206 kIsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
207 if (elfHeader.e_ident[EI_DATA] != kExpectedEncoding) {
208 if (msg) *msg = "invalid ELF encoding";
212 // Validate ELF version (1)
213 if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
214 elfHeader.e_version != EV_CURRENT) {
215 if (msg) *msg = "invalid ELF version";
219 // We only support executable and shared object files
220 if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
221 if (msg) *msg = "invalid ELF file type";
225 if (elfHeader.e_phnum == 0) {
226 if (msg) *msg = "no program header!";
230 if (elfHeader.e_phentsize != sizeof(ElfW(Phdr))) {
231 if (msg) *msg = "invalid program header entry size";
235 if (elfHeader.e_shentsize != sizeof(ElfW(Shdr))) {
236 if (msg) *msg = "invalid section header entry size";
239 const ElfW(Phdr)* programHeader = &at<ElfW(Phdr)>(elfHeader.e_phoff);
240 bool foundBase = false;
241 for (size_t i = 0; i < elfHeader.e_phnum; programHeader++, i++) {
242 // Program headers are sorted by load address, so the first PT_LOAD
243 // header gives us the base address.
244 if (programHeader->p_type == PT_LOAD) {
245 baseAddress_ = programHeader->p_vaddr;
252 if (msg) *msg = "could not find base address";
259 const ElfW(Shdr)* ElfFile::getSectionByIndex(size_t idx) const {
260 FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
261 return &at<ElfW(Shdr)>(elfHeader().e_shoff + idx * sizeof(ElfW(Shdr)));
264 folly::StringPiece ElfFile::getSectionBody(const ElfW(Shdr)& section) const {
265 return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
268 void ElfFile::validateStringTable(const ElfW(Shdr)& stringTable) const {
269 FOLLY_SAFE_CHECK(stringTable.sh_type == SHT_STRTAB,
270 "invalid type for string table");
272 const char* start = file_ + stringTable.sh_offset;
273 // First and last bytes must be 0
274 FOLLY_SAFE_CHECK(stringTable.sh_size == 0 ||
275 (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
276 "invalid string table");
279 const char* ElfFile::getString(const ElfW(Shdr)& stringTable, size_t offset)
281 validateStringTable(stringTable);
282 FOLLY_SAFE_CHECK(offset < stringTable.sh_size,
283 "invalid offset in string table");
285 return file_ + stringTable.sh_offset + offset;
288 const char* ElfFile::getSectionName(const ElfW(Shdr)& section) const {
289 if (elfHeader().e_shstrndx == SHN_UNDEF) {
290 return nullptr; // no section name string table
293 const ElfW(Shdr)& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
294 return getString(sectionNames, section.sh_name);
297 const ElfW(Shdr)* ElfFile::getSectionByName(const char* name) const {
298 if (elfHeader().e_shstrndx == SHN_UNDEF) {
299 return nullptr; // no section name string table
302 // Find offset in the section name string table of the requested name
303 const ElfW(Shdr)& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
304 const char* foundName = iterateStrings(
306 [&] (const char* s) { return !strcmp(name, s); });
307 if (foundName == nullptr) {
311 size_t offset = foundName - (file_ + sectionNames.sh_offset);
313 // Find section with the appropriate sh_name offset
314 const ElfW(Shdr)* foundSection = iterateSections(
315 [&](const ElfW(Shdr)& sh) {
316 if (sh.sh_name == offset) {
324 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
325 Symbol foundSymbol {nullptr, nullptr};
327 auto findSection = [&](const ElfW(Shdr)& section) {
328 auto findSymbols = [&](const ElfW(Sym)& sym) {
329 if (sym.st_shndx == SHN_UNDEF) {
330 return false; // not a definition
332 if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
333 foundSymbol.first = §ion;
334 foundSymbol.second = &sym;
341 return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
342 iterateSymbolsWithType(section, STT_FUNC, findSymbols);
345 // Try the .dynsym section first if it exists, it's smaller.
346 (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
347 iterateSectionsWithType(SHT_SYMTAB, findSection));
352 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
353 Symbol foundSymbol{nullptr, nullptr};
355 auto findSection = [&](const ElfW(Shdr)& section) -> bool {
356 // This section has no string table associated w/ its symbols; hence we
357 // can't get names for them
358 if (section.sh_link == SHN_UNDEF) {
362 auto findSymbols = [&](const ElfW(Sym)& sym) -> bool {
363 if (sym.st_shndx == SHN_UNDEF) {
364 return false; // not a definition
366 if (sym.st_name == 0) {
367 return false; // no name for this symbol
369 const char* sym_name = getString(
370 *getSectionByIndex(section.sh_link), sym.st_name);
371 if (strcmp(sym_name, name) == 0) {
372 foundSymbol.first = §ion;
373 foundSymbol.second = &sym;
380 return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
381 iterateSymbolsWithType(section, STT_FUNC, findSymbols);
384 // Try the .dynsym section first if it exists, it's smaller.
385 iterateSectionsWithType(SHT_DYNSYM, findSection) ||
386 iterateSectionsWithType(SHT_SYMTAB, findSection);
391 const ElfW(Shdr)* ElfFile::getSectionContainingAddress(ElfW(Addr) addr) const {
392 return iterateSections([&](const ElfW(Shdr)& sh) -> bool {
393 return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
397 const char* ElfFile::getSymbolName(Symbol symbol) const {
398 if (!symbol.first || !symbol.second) {
402 if (symbol.second->st_name == 0) {
403 return nullptr; // symbol has no name
406 if (symbol.first->sh_link == SHN_UNDEF) {
407 return nullptr; // symbol table has no strings
410 return getString(*getSectionByIndex(symbol.first->sh_link),
411 symbol.second->st_name);
414 } // namespace symbolizer