• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- unittests/DebugInfo/DWARF/DwarfGenerator.h -------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // A file that can generate DWARF debug info for unit tests.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_UNITTESTS_DEBUG_INFO_DWARF_DWARFGENERATOR_H
14 #define LLVM_UNITTESTS_DEBUG_INFO_DWARF_DWARFGENERATOR_H
15 
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
19 #include "llvm/Support/Error.h"
20 
21 #include <memory>
22 #include <string>
23 #include <tuple>
24 #include <vector>
25 
26 namespace llvm {
27 
28 class AsmPrinter;
29 class DIE;
30 class DIEAbbrev;
31 class DwarfStringPool;
32 class MCAsmBackend;
33 class MCAsmInfo;
34 class MCCodeEmitter;
35 class MCContext;
36 struct MCDwarfLineTableParams;
37 class MCInstrInfo;
38 class MCRegisterInfo;
39 class MCStreamer;
40 class MCSubtargetInfo;
41 class raw_fd_ostream;
42 class TargetLoweringObjectFile;
43 class TargetMachine;
44 class Triple;
45 
46 namespace dwarfgen {
47 
48 class Generator;
49 class CompileUnit;
50 
51 /// A DWARF debug information entry class used to generate DWARF DIEs.
52 ///
53 /// This class is used to quickly generate DWARF debug information by creating
54 /// child DIEs or adding attributes to the current DIE. Instances of this class
55 /// are created from the compile unit (dwarfgen::CompileUnit::getUnitDIE()) or
56 /// by calling dwarfgen::DIE::addChild(...) and using the returned DIE object.
57 class DIE {
58   dwarfgen::CompileUnit *CU;
59   llvm::DIE *Die;
60 
61 protected:
62   friend class Generator;
63   friend class CompileUnit;
64 
CU(U)65   DIE(CompileUnit *U = nullptr, llvm::DIE *D = nullptr) : CU(U), Die(D) {}
66 
67   /// Called with a compile/type unit relative offset prior to generating the
68   /// DWARF debug info.
69   ///
70   /// \param CUOffset the compile/type unit relative offset where the
71   /// abbreviation code for this DIE will be encoded.
72   unsigned computeSizeAndOffsets(unsigned CUOffset);
73 
74 public:
75   /// Add an attribute value that has no value.
76   ///
77   /// \param Attr a dwarf::Attribute enumeration value or any uint16_t that
78   /// represents a user defined DWARF attribute.
79   /// \param Form the dwarf::Form to use when encoding the attribute. This is
80   /// only used with the DW_FORM_flag_present form encoding.
81   void addAttribute(uint16_t Attr, dwarf::Form Form);
82 
83   /// Add an attribute value to be encoded as a DIEInteger
84   ///
85   /// \param Attr a dwarf::Attribute enumeration value or any uint16_t that
86   /// represents a user defined DWARF attribute.
87   /// \param Form the dwarf::Form to use when encoding the attribute.
88   /// \param U the unsigned integer to encode.
89   void addAttribute(uint16_t Attr, dwarf::Form Form, uint64_t U);
90 
91   /// Add an attribute value to be encoded as a DIEExpr
92   ///
93   /// \param Attr a dwarf::Attribute enumeration value or any uint16_t that
94   /// represents a user defined DWARF attribute.
95   /// \param Form the dwarf::Form to use when encoding the attribute.
96   /// \param Expr the MC expression used to compute the value.
97   void addAttribute(uint16_t Attr, dwarf::Form Form, const MCExpr &Expr);
98 
99   /// Add an attribute value to be encoded as a DIEString or DIEInlinedString.
100   ///
101   /// \param Attr a dwarf::Attribute enumeration value or any uint16_t that
102   /// represents a user defined DWARF attribute.
103   /// \param Form the dwarf::Form to use when encoding the attribute. The form
104   /// must be one of DW_FORM_strp or DW_FORM_string.
105   /// \param String the string to encode.
106   void addAttribute(uint16_t Attr, dwarf::Form Form, StringRef String);
107 
108   /// Add an attribute value to be encoded as a DIEEntry.
109   ///
110   /// DIEEntry attributes refer to other llvm::DIE objects that have been
111   /// created.
112   ///
113   /// \param Attr a dwarf::Attribute enumeration value or any uint16_t that
114   /// represents a user defined DWARF attribute.
115   /// \param Form the dwarf::Form to use when encoding the attribute. The form
116   /// must be one of DW_FORM_strp or DW_FORM_string.
117   /// \param RefDie the DIE that this attriute refers to.
118   void addAttribute(uint16_t Attr, dwarf::Form Form, dwarfgen::DIE &RefDie);
119 
120   /// Add an attribute value to be encoded as a DIEBlock.
121   ///
122   /// DIEBlock attributes refers to binary data that is stored as the
123   /// attribute's value.
124   ///
125   /// \param Attr a dwarf::Attribute enumeration value or any uint16_t that
126   /// represents a user defined DWARF attribute.
127   /// \param Form the dwarf::Form to use when encoding the attribute. The form
128   /// must be one of DW_FORM_strp or DW_FORM_string.
129   /// \param P a pointer to the data to store as the attribute value.
130   /// \param S the size in bytes of the data pointed to by P .
131   void addAttribute(uint16_t Attr, dwarf::Form Form, const void *P, size_t S);
132 
133   /// Add a DW_AT_str_offsets_base attribute to this DIE.
134   void addStrOffsetsBaseAttribute();
135 
136   /// Add a new child to this DIE object.
137   ///
138   /// \param Tag the dwarf::Tag to assing to the llvm::DIE object.
139   /// \returns the newly created DIE object that is now a child owned by this
140   /// object.
141   dwarfgen::DIE addChild(dwarf::Tag Tag);
142 };
143 
144 /// A DWARF compile unit used to generate DWARF compile/type units.
145 ///
146 /// Instances of these classes are created by instances of the Generator
147 /// class. All information required to generate a DWARF compile unit is
148 /// contained inside this class.
149 class CompileUnit {
150   Generator &DG;
151   BasicDIEUnit DU;
152   uint64_t Length; /// The length in bytes of all of the DIEs in this unit.
153   const uint16_t Version; /// The Dwarf version number for this unit.
154   const uint8_t AddrSize; /// The size in bytes of an address for this unit.
155 
156 public:
CompileUnit(Generator & D,uint16_t V,uint8_t A)157   CompileUnit(Generator &D, uint16_t V, uint8_t A)
158       : DG(D), DU(dwarf::DW_TAG_compile_unit), Version(V), AddrSize(A) {}
159   DIE getUnitDIE();
getGenerator()160   Generator &getGenerator() { return DG; }
getOffset()161   uint64_t getOffset() const { return DU.getDebugSectionOffset(); }
getLength()162   uint64_t getLength() const { return Length; }
getVersion()163   uint16_t getVersion() const { return Version; }
getAddressSize()164   uint16_t getAddressSize() const { return AddrSize; }
setOffset(uint64_t Offset)165   void setOffset(uint64_t Offset) { DU.setDebugSectionOffset(Offset); }
setLength(uint64_t L)166   void setLength(uint64_t L) { Length = L; }
167 };
168 
169 /// A DWARF line unit-like class used to generate DWARF line units.
170 ///
171 /// Instances of this class are created by instances of the Generator class.
172 class LineTable {
173 public:
174   enum ValueLength { Byte = 1, Half = 2, Long = 4, Quad = 8, ULEB, SLEB };
175 
176   struct ValueAndLength {
177     uint64_t Value = 0;
178     ValueLength Length = Byte;
179   };
180 
181   LineTable(uint16_t Version, dwarf::DwarfFormat Format, uint8_t AddrSize,
182             uint8_t SegSize = 0)
Version(Version)183       : Version(Version), Format(Format), AddrSize(AddrSize), SegSize(SegSize) {
184     assert(Version >= 2 && Version <= 5 && "unsupported version");
185   }
186 
187   // Create a Prologue suitable to pass to setPrologue, with a single file and
188   // include directory entry.
189   DWARFDebugLine::Prologue createBasicPrologue() const;
190 
191   // Set or replace the current prologue with the specified prologue. If no
192   // prologue is set, a default one will be used when generating.
193   void setPrologue(DWARFDebugLine::Prologue NewPrologue);
194   // Used to write an arbitrary payload instead of the standard prologue. This
195   // is useful if you wish to test handling of corrupt .debug_line sections.
196   void setCustomPrologue(ArrayRef<ValueAndLength> NewPrologue);
197 
198   // Add a byte to the program, with the given value. This can be used to
199   // specify a special opcode, or to add arbitrary contents to the section.
200   void addByte(uint8_t Value);
201   // Add a standard opcode to the program. The opcode and operands do not have
202   // to be valid.
203   void addStandardOpcode(uint8_t Opcode, ArrayRef<ValueAndLength> Operands);
204   // Add an extended opcode to the program with the specified length, opcode,
205   // and operands. These values do not have to be valid.
206   void addExtendedOpcode(uint64_t Length, uint8_t Opcode,
207                          ArrayRef<ValueAndLength> Operands);
208 
209   // Write the contents of the LineUnit to the current section in the generator.
210   void generate(MCContext &MC, AsmPrinter &Asm) const;
211 
212 private:
213   void writeData(ArrayRef<ValueAndLength> Data, AsmPrinter &Asm) const;
214   MCSymbol *writeDefaultPrologue(AsmPrinter &Asm) const;
215   void writePrologue(AsmPrinter &Asm) const;
216 
217   void writeProloguePayload(const DWARFDebugLine::Prologue &Prologue,
218                             AsmPrinter &Asm) const;
219 
220   // Calculate the number of bytes the Contents will take up.
221   size_t getContentsSize() const;
222 
223   llvm::Optional<DWARFDebugLine::Prologue> Prologue;
224   std::vector<ValueAndLength> CustomPrologue;
225   std::vector<ValueAndLength> Contents;
226 
227   // The Version field is used for determining how to write the Prologue, if a
228   // non-custom prologue is used. The version value actually written, will be
229   // that specified in the Prologue, if a custom prologue has been passed in.
230   // Otherwise, it will be this value.
231   uint16_t Version;
232 
233   dwarf::DwarfFormat Format;
234   uint8_t AddrSize;
235   uint8_t SegSize;
236 };
237 
238 /// A DWARF generator.
239 ///
240 /// Generate DWARF for unit tests by creating any instance of this class and
241 /// calling Generator::addCompileUnit(), and then getting the dwarfgen::DIE from
242 /// the returned compile unit and adding attributes and children to each DIE.
243 class Generator {
244   std::unique_ptr<MCRegisterInfo> MRI;
245   std::unique_ptr<MCAsmInfo> MAI;
246   std::unique_ptr<MCContext> MC;
247   MCAsmBackend *MAB; // Owned by MCStreamer
248   std::unique_ptr<MCInstrInfo> MII;
249   std::unique_ptr<MCSubtargetInfo> MSTI;
250   MCCodeEmitter *MCE; // Owned by MCStreamer
251   MCStreamer *MS;     // Owned by AsmPrinter
252   std::unique_ptr<TargetMachine> TM;
253   TargetLoweringObjectFile *TLOF; // Owned by TargetMachine;
254   std::unique_ptr<AsmPrinter> Asm;
255   BumpPtrAllocator Allocator;
256   std::unique_ptr<DwarfStringPool> StringPool; // Entries owned by Allocator.
257   std::vector<std::unique_ptr<CompileUnit>> CompileUnits;
258   std::vector<std::unique_ptr<LineTable>> LineTables;
259   DIEAbbrevSet Abbreviations;
260 
261   MCSymbol *StringOffsetsStartSym;
262 
263   SmallString<4096> FileBytes;
264   /// The stream we use to generate the DWARF into as an ELF file.
265   std::unique_ptr<raw_svector_ostream> Stream;
266   /// The DWARF version to generate.
267   uint16_t Version;
268 
269   /// Private constructor, call Generator::Create(...) to get a DWARF generator
270   /// expected.
271   Generator();
272 
273   /// Create the streamer and setup the output buffer.
274   llvm::Error init(Triple TheTriple, uint16_t DwarfVersion);
275 
276 public:
277   /// Create a DWARF generator or get an appropriate error.
278   ///
279   /// \param TheTriple the triple to use when creating any required support
280   /// classes needed to emit the DWARF.
281   /// \param DwarfVersion the version of DWARF to emit.
282   ///
283   /// \returns a llvm::Expected that either contains a unique_ptr to a Generator
284   /// or a llvm::Error.
285   static llvm::Expected<std::unique_ptr<Generator>>
286   create(Triple TheTriple, uint16_t DwarfVersion);
287 
288   ~Generator();
289 
290   /// Generate all DWARF sections and return a memory buffer that
291   /// contains an ELF file that contains the DWARF.
292   StringRef generate();
293 
294   /// Add a compile unit to be generated.
295   ///
296   /// \returns a dwarfgen::CompileUnit that can be used to retrieve the compile
297   /// unit dwarfgen::DIE that can be used to add attributes and add child DIE
298   /// objects to.
299   dwarfgen::CompileUnit &addCompileUnit();
300 
301   /// Add a line table unit to be generated.
302   /// \param DwarfFormat the DWARF format to use (DWARF32 or DWARF64).
303   ///
304   /// \returns a dwarfgen::LineTable that can be used to customise the contents
305   /// of the line table.
306   LineTable &
307   addLineTable(dwarf::DwarfFormat DwarfFormat = dwarf::DwarfFormat::DWARF32);
308 
getAllocator()309   BumpPtrAllocator &getAllocator() { return Allocator; }
getAsmPrinter()310   AsmPrinter *getAsmPrinter() const { return Asm.get(); }
getMCContext()311   MCContext *getMCContext() const { return MC.get(); }
getAbbrevSet()312   DIEAbbrevSet &getAbbrevSet() { return Abbreviations; }
getStringPool()313   DwarfStringPool &getStringPool() { return *StringPool; }
getStringOffsetsStartSym()314   MCSymbol *getStringOffsetsStartSym() const { return StringOffsetsStartSym; }
315 
316   /// Save the generated DWARF file to disk.
317   ///
318   /// \param Path the path to save the ELF file to.
319   bool saveFile(StringRef Path);
320 };
321 
322 } // end namespace dwarfgen
323 
324 } // end namespace llvm
325 
326 #endif // LLVM_UNITTESTS_DEBUG_INFO_DWARF_DWARFGENERATOR_H
327