ed7d1ae82cab9e4d662459ba29591dc0912bc1f1
[folly.git] / folly / experimental / symbolizer / Dwarf.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 // DWARF record parser
18
19 #pragma once
20
21 #include <boost/variant.hpp>
22
23 #include <folly/experimental/symbolizer/Elf.h>
24 #include <folly/Range.h>
25
26 namespace folly {
27 namespace symbolizer {
28
29 /**
30  * DWARF record parser.
31  *
32  * We only implement enough DWARF functionality to convert from PC address
33  * to file and line number information.
34  *
35  * This means (although they're not part of the public API of this class), we
36  * can parse Debug Information Entries (DIEs), abbreviations, attributes (of
37  * all forms), and we can interpret bytecode for the line number VM.
38  *
39  * We can interpret DWARF records of version 2, 3, or 4, although we don't
40  * actually support many of the version 4 features (such as VLIW, multiple
41  * operations per instruction)
42  *
43  * Note that the DWARF record parser does not allocate heap memory at all.
44  * This is on purpose: you can use the parser from
45  * memory-constrained situations (such as an exception handler for
46  * std::out_of_memory)  If it weren't for this requirement, some things would
47  * be much simpler: the Path class would be unnecessary and would be replaced
48  * with a std::string; the list of file names in the line number VM would be
49  * kept as a vector of strings instead of re-executing the program to look for
50  * DW_LNE_define_file instructions, etc.
51  */
52 class Dwarf {
53   // Note that Dwarf uses (and returns) StringPiece a lot.
54   // The StringPieces point within sections in the ELF file, and so will
55   // be live for as long as the passed-in ElfFile is live.
56  public:
57   /** Create a DWARF parser around an ELF file. */
58   explicit Dwarf(const ElfFile* elf);
59
60   /**
61    * Represent a file path a s collection of three parts (base directory,
62    * subdirectory, and file).
63    */
64   class Path {
65    public:
66     Path() { }
67
68     Path(folly::StringPiece baseDir, folly::StringPiece subDir,
69          folly::StringPiece file);
70
71     folly::StringPiece baseDir() const { return baseDir_; };
72     folly::StringPiece subDir() const { return subDir_; }
73     folly::StringPiece file() const { return file_; }
74
75     size_t size() const;
76
77     /**
78      * Copy the Path to a buffer of size bufSize.
79      *
80      * toBuffer behaves like snprintf: It will always null-terminate the
81      * buffer (so it will copy at most bufSize-1 bytes), and it will return
82      * the number of bytes that would have been written if there had been
83      * enough room, so, if toBuffer returns a value >= bufSize, the output
84      * was truncated.
85      */
86     size_t toBuffer(char* buf, size_t bufSize) const;
87
88     void toString(std::string& dest) const;
89     std::string toString() const {
90       std::string s;
91       toString(s);
92       return s;
93     }
94
95     // TODO(tudorb): Implement operator==, operator!=; not as easy as it
96     // seems as the same path can be represented in multiple ways
97    private:
98     folly::StringPiece baseDir_;
99     folly::StringPiece subDir_;
100     folly::StringPiece file_;
101   };
102
103   struct LocationInfo {
104     LocationInfo() : hasMainFile(false), hasFileAndLine(false), line(0) { }
105
106     bool hasMainFile;
107     Path mainFile;
108
109     bool hasFileAndLine;
110     Path file;
111     uint64_t line;
112   };
113
114   /** Find the file and line number information corresponding to address */
115   bool findAddress(uintptr_t address, LocationInfo& info) const;
116
117  private:
118   void init();
119   static bool findDebugInfoOffset(uintptr_t address,
120                                   StringPiece aranges,
121                                   uint64_t& offset);
122   bool findLocation(uintptr_t address,
123                     StringPiece& infoEntry,
124                     LocationInfo& info) const;
125
126   const ElfFile* elf_;
127
128   // DWARF section made up of chunks, each prefixed with a length header.
129   // The length indicates whether the chunk is DWARF-32 or DWARF-64, which
130   // guides interpretation of "section offset" records.
131   // (yes, DWARF-32 and DWARF-64 sections may coexist in the same file)
132   class Section {
133    public:
134     Section() : is64Bit_(false) { }
135
136     explicit Section(folly::StringPiece d);
137
138     // Return next chunk, if any; the 4- or 12-byte length was already
139     // parsed and isn't part of the chunk.
140     bool next(folly::StringPiece& chunk);
141
142     // Is the current chunk 64 bit?
143     bool is64Bit() const { return is64Bit_; }
144
145    private:
146     // Yes, 32- and 64- bit sections may coexist.  Yikes!
147     bool is64Bit_;
148     folly::StringPiece data_;
149   };
150
151   // Abbreviation for a Debugging Information Entry.
152   struct DIEAbbreviation {
153     uint64_t code;
154     uint64_t tag;
155     bool hasChildren;
156
157     struct Attribute {
158       uint64_t name;
159       uint64_t form;
160     };
161
162     folly::StringPiece attributes;
163   };
164
165   // Interpreter for the line number bytecode VM
166   class LineNumberVM {
167    public:
168     LineNumberVM(folly::StringPiece data,
169                  folly::StringPiece compilationDirectory);
170
171     bool findAddress(uintptr_t address, Path& file, uint64_t& line);
172
173    private:
174     void init();
175     void reset();
176
177     // Execute until we commit one new row to the line number matrix
178     bool next(folly::StringPiece& program);
179     enum StepResult {
180       CONTINUE,  // Continue feeding opcodes
181       COMMIT,    // Commit new <address, file, line> tuple
182       END,       // End of sequence
183     };
184     // Execute one opcode
185     StepResult step(folly::StringPiece& program);
186
187     struct FileName {
188       folly::StringPiece relativeName;
189       // 0 = current compilation directory
190       // otherwise, 1-based index in the list of include directories
191       uint64_t directoryIndex;
192     };
193     // Read one FileName object, advance sp
194     static bool readFileName(folly::StringPiece& sp, FileName& fn);
195
196     // Get file name at given index; may be in the initial table
197     // (fileNames_) or defined using DW_LNE_define_file (and we reexecute
198     // enough of the program to find it, if so)
199     FileName getFileName(uint64_t index) const;
200
201     // Get include directory at given index
202     folly::StringPiece getIncludeDirectory(uint64_t index) const;
203
204     // Execute opcodes until finding a DW_LNE_define_file and return true;
205     // return file at the end.
206     bool nextDefineFile(folly::StringPiece& program, FileName& fn) const;
207
208     // Initialization
209     bool is64Bit_;
210     folly::StringPiece data_;
211     folly::StringPiece compilationDirectory_;
212
213     // Header
214     uint16_t version_;
215     uint8_t minLength_;
216     bool defaultIsStmt_;
217     int8_t lineBase_;
218     uint8_t lineRange_;
219     uint8_t opcodeBase_;
220     const uint8_t* standardOpcodeLengths_;
221
222     folly::StringPiece includeDirectories_;
223     size_t includeDirectoryCount_;
224
225     folly::StringPiece fileNames_;
226     size_t fileNameCount_;
227
228     // State machine registers
229     uint64_t address_;
230     uint64_t file_;
231     uint64_t line_;
232     uint64_t column_;
233     bool isStmt_;
234     bool basicBlock_;
235     bool endSequence_;
236     bool prologueEnd_;
237     bool epilogueBegin_;
238     uint64_t isa_;
239     uint64_t discriminator_;
240   };
241
242   // Read an abbreviation from a StringPiece, return true if at end; advance sp
243   static bool readAbbreviation(folly::StringPiece& sp, DIEAbbreviation& abbr);
244
245   // Get abbreviation corresponding to a code, in the chunk starting at
246   // offset in the .debug_abbrev section
247   DIEAbbreviation getAbbreviation(uint64_t code, uint64_t offset) const;
248
249   // Read one attribute <name, form> pair, advance sp; returns <0, 0> at end.
250   static DIEAbbreviation::Attribute readAttribute(folly::StringPiece& sp);
251
252   // Read one attribute value, advance sp
253   typedef boost::variant<uint64_t, folly::StringPiece> AttributeValue;
254   AttributeValue readAttributeValue(
255       folly::StringPiece& sp,
256       uint64_t form,
257       bool is64Bit) const;
258
259   // Get an ELF section by name, return true if found
260   bool getSection(const char* name, folly::StringPiece* section) const;
261
262   // Get a string from the .debug_str section
263   folly::StringPiece getStringFromStringSection(uint64_t offset) const;
264
265   folly::StringPiece info_;       // .debug_info
266   folly::StringPiece abbrev_;     // .debug_abbrev
267   folly::StringPiece aranges_;    // .debug_aranges
268   folly::StringPiece line_;       // .debug_line
269   folly::StringPiece strings_;    // .debug_str
270 };
271
272 inline std::ostream& operator<<(std::ostream& out, const Dwarf::Path& path) {
273   return out << path.toString();
274 }
275
276 }  // namespace symbolizer
277 }  // namespace folly