2 * Copyright 2014 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/Dwarf.h"
20 #include <type_traits>
25 namespace symbolizer {
27 Dwarf::Dwarf(const ElfFile* elf) : elf_(elf) {
31 Dwarf::Section::Section(folly::StringPiece d) : is64Bit_(false), data_(d) {
36 // All following read* functions read from a StringPiece, advancing the
37 // StringPiece, and aborting if there's not enough room.
39 // Read (bitwise) one object of type T
41 typename std::enable_if<std::is_pod<T>::value, T>::type
42 read(folly::StringPiece& sp) {
43 FOLLY_SAFE_CHECK(sp.size() >= sizeof(T), "underflow");
45 memcpy(&x, sp.data(), sizeof(T));
46 sp.advance(sizeof(T));
50 // Read ULEB (unsigned) varint value; algorithm from the DWARF spec
51 uint64_t readULEB(folly::StringPiece& sp, uint8_t& shift, uint8_t& val) {
55 val = read<uint8_t>(sp);
56 r |= ((uint64_t)(val & 0x7f) << shift);
62 uint64_t readULEB(folly::StringPiece& sp) {
65 return readULEB(sp, shift, val);
68 // Read SLEB (signed) varint value; algorithm from the DWARF spec
69 int64_t readSLEB(folly::StringPiece& sp) {
72 uint64_t r = readULEB(sp, shift, val);
74 if (shift < 64 && (val & 0x40)) {
75 r |= -(1ULL << shift); // sign extend
81 // Read a value of "section offset" type, which may be 4 or 8 bytes
82 uint64_t readOffset(folly::StringPiece& sp, bool is64Bit) {
83 return is64Bit ? read<uint64_t>(sp) : read<uint32_t>(sp);
87 folly::StringPiece readBytes(folly::StringPiece& sp, uint64_t len) {
88 FOLLY_SAFE_CHECK(len >= sp.size(), "invalid string length");
89 folly::StringPiece ret(sp.data(), len);
94 // Read a null-terminated string
95 folly::StringPiece readNullTerminated(folly::StringPiece& sp) {
96 const char* p = static_cast<const char*>(
97 memchr(sp.data(), 0, sp.size()));
98 FOLLY_SAFE_CHECK(p, "invalid null-terminated string");
99 folly::StringPiece ret(sp.data(), p);
100 sp.assign(p + 1, sp.end());
104 // Skip over padding until sp.data() - start is a multiple of alignment
105 void skipPadding(folly::StringPiece& sp, const char* start, size_t alignment) {
106 size_t remainder = (sp.data() - start) % alignment;
108 FOLLY_SAFE_CHECK(alignment - remainder <= sp.size(), "invalid padding");
109 sp.advance(alignment - remainder);
113 // Simplify a path -- as much as we can while not moving data around...
114 void simplifyPath(folly::StringPiece& sp) {
115 // Strip leading slashes and useless patterns (./), leaving one initial
122 // Strip leading slashes, leaving one.
123 while (sp.startsWith("//")) {
127 if (sp.startsWith("/./")) {
128 // Note 2, not 3, to keep it absolute
133 if (sp.removePrefix("./")) {
140 // Strip trailing slashes and useless patterns (/.).
146 // Strip trailing slashes
147 while (sp.removeSuffix('/')) { }
149 if (sp.removeSuffix("/.")) {
159 Dwarf::Path::Path(folly::StringPiece baseDir, folly::StringPiece subDir,
160 folly::StringPiece file)
173 if (file_[0] == '/') {
179 if (!subDir_.empty() && subDir_[0] == '/') {
180 baseDir_.clear(); // subDir_ is absolute
183 // Make sure that baseDir_ isn't empty; subDir_ may be
184 if (baseDir_.empty()) {
185 swap(baseDir_, subDir_);
188 simplifyPath(baseDir_);
189 simplifyPath(subDir_);
193 size_t Dwarf::Path::size() const {
194 if (baseDir_.empty()) {
195 assert(subDir_.empty());
200 baseDir_.size() + !subDir_.empty() + subDir_.size() + !file_.empty() +
204 size_t Dwarf::Path::toBuffer(char* buf, size_t bufSize) const {
205 size_t totalSize = 0;
207 auto append = [&] (folly::StringPiece sp) {
209 size_t toCopy = std::min(sp.size(), bufSize - 1);
210 memcpy(buf, sp.data(), toCopy);
214 totalSize += sp.size();
217 if (!baseDir_.empty()) {
220 if (!subDir_.empty()) {
221 assert(!baseDir_.empty());
225 if (!file_.empty()) {
226 if (!baseDir_.empty()) {
234 assert(totalSize == size());
238 void Dwarf::Path::toString(std::string& dest) const {
239 size_t initialSize = dest.size();
240 dest.reserve(initialSize + size());
241 if (!baseDir_.empty()) {
242 dest.append(baseDir_.begin(), baseDir_.end());
244 if (!subDir_.empty()) {
245 assert(!baseDir_.empty());
247 dest.append(subDir_.begin(), subDir_.end());
249 if (!file_.empty()) {
251 dest.append(file_.begin(), file_.end());
253 assert(dest.size() == initialSize + size());
256 // Next chunk in section
257 bool Dwarf::Section::next(folly::StringPiece& chunk) {
263 // Initial length is a uint32_t value for a 32-bit section, and
264 // a 96-bit value (0xffffffff followed by the 64-bit length) for a 64-bit
266 auto initialLength = read<uint32_t>(chunk);
267 is64Bit_ = (initialLength == (uint32_t)-1);
268 auto length = is64Bit_ ? read<uint64_t>(chunk) : initialLength;
269 FOLLY_SAFE_CHECK(length <= chunk.size(), "invalid DWARF section");
270 chunk.reset(chunk.data(), length);
271 data_.assign(chunk.end(), data_.end());
275 bool Dwarf::getSection(const char* name, folly::StringPiece* section) const {
276 const ElfW(Shdr)* elfSection = elf_->getSectionByName(name);
281 *section = elf_->getSectionBody(*elfSection);
286 // Make sure that all .debug_* sections exist
287 if (!getSection(".debug_info", &info_) ||
288 !getSection(".debug_abbrev", &abbrev_) ||
289 !getSection(".debug_aranges", &aranges_) ||
290 !getSection(".debug_line", &line_) ||
291 !getSection(".debug_str", &strings_)) {
295 getSection(".debug_str", &strings_);
298 bool Dwarf::readAbbreviation(folly::StringPiece& section,
299 DIEAbbreviation& abbr) {
301 abbr.code = readULEB(section);
302 if (abbr.code == 0) {
307 abbr.tag = readULEB(section);
309 // does this entry have children?
310 abbr.hasChildren = (read<uint8_t>(section) != DW_CHILDREN_no);
313 const char* attributeBegin = section.data();
315 FOLLY_SAFE_CHECK(!section.empty(), "invalid attribute section");
316 auto attr = readAttribute(section);
317 if (attr.name == 0 && attr.form == 0) {
322 abbr.attributes.assign(attributeBegin, section.data());
326 Dwarf::DIEAbbreviation::Attribute Dwarf::readAttribute(
327 folly::StringPiece& sp) {
328 return { readULEB(sp), readULEB(sp) };
331 Dwarf::DIEAbbreviation Dwarf::getAbbreviation(uint64_t code, uint64_t offset)
333 // Linear search in the .debug_abbrev section, starting at offset
334 folly::StringPiece section = abbrev_;
335 section.advance(offset);
337 Dwarf::DIEAbbreviation abbr;
338 while (readAbbreviation(section, abbr)) {
339 if (abbr.code == code) {
344 FOLLY_SAFE_CHECK(false, "could not find abbreviation code");
347 Dwarf::AttributeValue Dwarf::readAttributeValue(
348 folly::StringPiece& sp, uint64_t form, bool is64Bit) const {
351 return read<uintptr_t>(sp);
353 return readBytes(sp, read<uint8_t>(sp));
355 return readBytes(sp, read<uint16_t>(sp));
357 return readBytes(sp, read<uint32_t>(sp));
358 case DW_FORM_block: // fallthrough
359 case DW_FORM_exprloc:
360 return readBytes(sp, readULEB(sp));
361 case DW_FORM_data1: // fallthrough
363 return read<uint8_t>(sp);
364 case DW_FORM_data2: // fallthrough
366 return read<uint16_t>(sp);
367 case DW_FORM_data4: // fallthrough
369 return read<uint32_t>(sp);
370 case DW_FORM_data8: // fallthrough
372 return read<uint64_t>(sp);
375 case DW_FORM_udata: // fallthrough
376 case DW_FORM_ref_udata:
379 return read<uint8_t>(sp);
380 case DW_FORM_flag_present:
382 case DW_FORM_sec_offset: // fallthrough
383 case DW_FORM_ref_addr:
384 return readOffset(sp, is64Bit);
386 return readNullTerminated(sp);
388 return getStringFromStringSection(readOffset(sp, is64Bit));
389 case DW_FORM_indirect: // form is explicitly specified
390 return readAttributeValue(sp, readULEB(sp), is64Bit);
392 FOLLY_SAFE_CHECK(false, "invalid attribute form");
396 folly::StringPiece Dwarf::getStringFromStringSection(uint64_t offset) const {
397 FOLLY_SAFE_CHECK(offset < strings_.size(), "invalid strp offset");
398 folly::StringPiece sp(strings_);
400 return readNullTerminated(sp);
403 bool Dwarf::findAddress(uintptr_t address, LocationInfo& locationInfo) const {
404 locationInfo = LocationInfo();
406 if (!elf_) { // no file
410 // Find address range in .debug_aranges, map to compilation unit
411 Section arangesSection(aranges_);
412 folly::StringPiece chunk;
413 uint64_t debugInfoOffset;
415 while (!found && arangesSection.next(chunk)) {
416 auto version = read<uint16_t>(chunk);
417 FOLLY_SAFE_CHECK(version == 2, "invalid aranges version");
419 debugInfoOffset = readOffset(chunk, arangesSection.is64Bit());
420 auto addressSize = read<uint8_t>(chunk);
421 FOLLY_SAFE_CHECK(addressSize == sizeof(uintptr_t), "invalid address size");
422 auto segmentSize = read<uint8_t>(chunk);
423 FOLLY_SAFE_CHECK(segmentSize == 0, "segmented architecture not supported");
425 // Padded to a multiple of 2 addresses.
426 // Strangely enough, this is the only place in the DWARF spec that requires
428 skipPadding(chunk, aranges_.data(), 2 * sizeof(uintptr_t));
430 auto start = read<uintptr_t>(chunk);
431 auto length = read<uintptr_t>(chunk);
437 // Is our address in this range?
438 if (address >= start && address < start + length) {
449 // Read compilation unit header from .debug_info
450 folly::StringPiece sp(info_);
451 sp.advance(debugInfoOffset);
452 Section debugInfoSection(sp);
453 FOLLY_SAFE_CHECK(debugInfoSection.next(chunk), "invalid debug info");
455 auto version = read<uint16_t>(chunk);
456 FOLLY_SAFE_CHECK(version >= 2 && version <= 4, "invalid info version");
457 uint64_t abbrevOffset = readOffset(chunk, debugInfoSection.is64Bit());
458 auto addressSize = read<uint8_t>(chunk);
459 FOLLY_SAFE_CHECK(addressSize == sizeof(uintptr_t), "invalid address size");
461 // We survived so far. The first (and only) DIE should be
462 // DW_TAG_compile_unit
463 // TODO(tudorb): Handle DW_TAG_partial_unit?
464 auto code = readULEB(chunk);
465 FOLLY_SAFE_CHECK(code != 0, "invalid code");
466 auto abbr = getAbbreviation(code, abbrevOffset);
467 FOLLY_SAFE_CHECK(abbr.tag == DW_TAG_compile_unit,
468 "expecting compile unit entry");
470 // Read attributes, extracting the few we care about
471 bool foundLineOffset = false;
472 uint64_t lineOffset = 0;
473 folly::StringPiece compilationDirectory;
474 folly::StringPiece mainFileName;
476 DIEAbbreviation::Attribute attr;
477 folly::StringPiece attributes = abbr.attributes;
479 attr = readAttribute(attributes);
480 if (attr.name == 0 && attr.form == 0) {
483 auto val = readAttributeValue(chunk, attr.form,
484 debugInfoSection.is64Bit());
486 case DW_AT_stmt_list:
487 // Offset in .debug_line for the line number VM program for this
489 lineOffset = boost::get<uint64_t>(val);
490 foundLineOffset = true;
493 // Compilation directory
494 compilationDirectory = boost::get<folly::StringPiece>(val);
497 // File name of main file being compiled
498 mainFileName = boost::get<folly::StringPiece>(val);
503 if (!mainFileName.empty()) {
504 locationInfo.hasMainFile = true;
505 locationInfo.mainFile = Path(compilationDirectory, "", mainFileName);
508 if (foundLineOffset) {
509 folly::StringPiece lineSection(line_);
510 lineSection.advance(lineOffset);
511 LineNumberVM lineVM(lineSection, compilationDirectory);
513 // Execute line number VM program to find file and line
514 locationInfo.hasFileAndLine =
515 lineVM.findAddress(address, locationInfo.file, locationInfo.line);
521 Dwarf::LineNumberVM::LineNumberVM(folly::StringPiece data,
522 folly::StringPiece compilationDirectory)
523 : compilationDirectory_(compilationDirectory) {
524 Section section(data);
525 FOLLY_SAFE_CHECK(section.next(data_), "invalid line number VM");
526 is64Bit_ = section.is64Bit();
531 void Dwarf::LineNumberVM::reset() {
536 isStmt_ = defaultIsStmt_;
538 endSequence_ = false;
539 prologueEnd_ = false;
540 epilogueBegin_ = false;
545 void Dwarf::LineNumberVM::init() {
546 version_ = read<uint16_t>(data_);
547 FOLLY_SAFE_CHECK(version_ >= 2 && version_ <= 4,
548 "invalid version in line number VM");
549 uint64_t headerLength = readOffset(data_, is64Bit_);
550 FOLLY_SAFE_CHECK(headerLength <= data_.size(),
551 "invalid line number VM header length");
552 folly::StringPiece header(data_.data(), headerLength);
553 data_.assign(header.end(), data_.end());
555 minLength_ = read<uint8_t>(header);
556 if (version_ == 4) { // Version 2 and 3 records don't have this
557 uint8_t maxOpsPerInstruction = read<uint8_t>(header);
558 FOLLY_SAFE_CHECK(maxOpsPerInstruction == 1, "VLIW not supported");
560 defaultIsStmt_ = read<uint8_t>(header);
561 lineBase_ = read<int8_t>(header); // yes, signed
562 lineRange_ = read<uint8_t>(header);
563 opcodeBase_ = read<uint8_t>(header);
564 FOLLY_SAFE_CHECK(opcodeBase_ != 0, "invalid opcode base");
565 standardOpcodeLengths_ = reinterpret_cast<const uint8_t*>(header.data());
566 header.advance(opcodeBase_ - 1);
568 // We don't want to use heap, so we don't keep an unbounded amount of state.
569 // We'll just skip over include directories and file names here, and
570 // we'll loop again when we actually need to retrieve one.
571 folly::StringPiece sp;
572 const char* tmp = header.data();
573 includeDirectoryCount_ = 0;
574 while (!(sp = readNullTerminated(header)).empty()) {
575 ++includeDirectoryCount_;
577 includeDirectories_.assign(tmp, header.data());
582 while (readFileName(header, fn)) {
585 fileNames_.assign(tmp, header.data());
588 bool Dwarf::LineNumberVM::next(folly::StringPiece& program) {
589 Dwarf::LineNumberVM::StepResult ret;
592 } while (ret == CONTINUE);
594 return (ret == COMMIT);
597 Dwarf::LineNumberVM::FileName Dwarf::LineNumberVM::getFileName(uint64_t index)
599 FOLLY_SAFE_CHECK(index != 0, "invalid file index 0");
602 if (index <= fileNameCount_) {
603 folly::StringPiece fileNames = fileNames_;
604 for (; index; --index) {
605 if (!readFileName(fileNames, fn)) {
612 index -= fileNameCount_;
614 folly::StringPiece program = data_;
615 for (; index; --index) {
616 FOLLY_SAFE_CHECK(nextDefineFile(program, fn), "invalid file index");
622 folly::StringPiece Dwarf::LineNumberVM::getIncludeDirectory(uint64_t index)
625 return folly::StringPiece();
628 FOLLY_SAFE_CHECK(index <= includeDirectoryCount_,
629 "invalid include directory");
631 folly::StringPiece includeDirectories = includeDirectories_;
632 folly::StringPiece dir;
633 for (; index; --index) {
634 dir = readNullTerminated(includeDirectories);
643 bool Dwarf::LineNumberVM::readFileName(folly::StringPiece& program,
645 fn.relativeName = readNullTerminated(program);
646 if (fn.relativeName.empty()) {
649 fn.directoryIndex = readULEB(program);
650 // Skip over file size and last modified time
656 bool Dwarf::LineNumberVM::nextDefineFile(folly::StringPiece& program,
657 FileName& fn) const {
658 while (!program.empty()) {
659 auto opcode = read<uint8_t>(program);
661 if (opcode >= opcodeBase_) { // special opcode
665 if (opcode != 0) { // standard opcode
666 // Skip, slurp the appropriate number of LEB arguments
667 uint8_t argCount = standardOpcodeLengths_[opcode - 1];
675 auto length = readULEB(program);
676 // the opcode itself should be included in the length, so length >= 1
677 FOLLY_SAFE_CHECK(length != 0, "invalid extended opcode length");
678 read<uint8_t>(program); // extended opcode
681 if (opcode == DW_LNE_define_file) {
682 FOLLY_SAFE_CHECK(readFileName(program, fn),
683 "invalid empty file in DW_LNE_define_file");
687 program.advance(length);
694 Dwarf::LineNumberVM::StepResult Dwarf::LineNumberVM::step(
695 folly::StringPiece& program) {
696 auto opcode = read<uint8_t>(program);
698 if (opcode >= opcodeBase_) { // special opcode
699 uint8_t adjustedOpcode = opcode - opcodeBase_;
700 uint8_t opAdvance = adjustedOpcode / lineRange_;
702 address_ += minLength_ * opAdvance;
703 line_ += lineBase_ + adjustedOpcode % lineRange_;
706 prologueEnd_ = false;
707 epilogueBegin_ = false;
712 if (opcode != 0) { // standard opcode
713 // Only interpret opcodes that are recognized by the version we're parsing;
714 // the others are vendor extensions and we should ignore them.
718 prologueEnd_ = false;
719 epilogueBegin_ = false;
722 case DW_LNS_advance_pc:
723 address_ += minLength_ * readULEB(program);
725 case DW_LNS_advance_line:
726 line_ += readSLEB(program);
728 case DW_LNS_set_file:
729 file_ = readULEB(program);
731 case DW_LNS_set_column:
732 column_ = readULEB(program);
734 case DW_LNS_negate_stmt:
737 case DW_LNS_set_basic_block:
740 case DW_LNS_const_add_pc:
741 address_ += minLength_ * ((255 - opcodeBase_) / lineRange_);
743 case DW_LNS_fixed_advance_pc:
744 address_ += read<uint16_t>(program);
746 case DW_LNS_set_prologue_end:
747 if (version_ == 2) break; // not supported in version 2
750 case DW_LNS_set_epilogue_begin:
751 if (version_ == 2) break; // not supported in version 2
752 epilogueBegin_ = true;
755 if (version_ == 2) break; // not supported in version 2
756 isa_ = readULEB(program);
760 // Unrecognized standard opcode, slurp the appropriate number of LEB
762 uint8_t argCount = standardOpcodeLengths_[opcode - 1];
770 auto length = readULEB(program);
771 // the opcode itself should be included in the length, so length >= 1
772 FOLLY_SAFE_CHECK(length != 0, "invalid extended opcode length");
773 auto extendedOpcode = read<uint8_t>(program);
776 switch (extendedOpcode) {
777 case DW_LNE_end_sequence:
779 case DW_LNE_set_address:
780 address_ = read<uintptr_t>(program);
782 case DW_LNE_define_file:
783 // We can't process DW_LNE_define_file here, as it would require us to
784 // use unbounded amounts of state (ie. use the heap). We'll do a second
785 // pass (using nextDefineFile()) if necessary.
787 case DW_LNE_set_discriminator:
788 discriminator_ = readULEB(program);
792 // Unrecognized extended opcode
793 program.advance(length);
797 bool Dwarf::LineNumberVM::findAddress(uintptr_t target, Path& file,
799 folly::StringPiece program = data_;
801 // Within each sequence of instructions, the address may only increase.
802 // Unfortunately, within the same compilation unit, sequences may appear
803 // in any order. So any sequence is a candidate if it starts at an address
804 // <= the target address, and we know we've found the target address if
805 // a candidate crosses the target address.
808 LOW_SEQ, // candidate
814 uint64_t prevFile = 0;
815 uint64_t prevLine = 0;
816 while (!program.empty()) {
817 bool seqEnd = !next(program);
819 if (state == START) {
821 state = address_ <= target ? LOW_SEQ : HIGH_SEQ;
825 if (state == LOW_SEQ) {
826 if (address_ > target) {
827 // Found it! Note that ">" is indeed correct (not ">="), as each
828 // sequence is guaranteed to have one entry past-the-end (emitted by
829 // DW_LNE_end_sequence)
833 auto fn = getFileName(prevFile);
834 file = Path(compilationDirectory_,
835 getIncludeDirectory(fn.directoryIndex),
853 } // namespace symbolizer