1 //===- DWARFEmitter - Convert YAML to DWARF binary data -------------------===//
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 /// \file
10 /// The DWARF component of yaml2obj. Provided as library code for tests.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ObjectYAML/DWARFEmitter.h"
15 #include "DWARFVisitor.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ObjectYAML/DWARFYAML.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/LEB128.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/SwapByteOrder.h"
25 #include "llvm/Support/YAMLTraits.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <cstddef>
30 #include <cstdint>
31 #include <memory>
32 #include <string>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 template <typename T>
38 static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian) {
39   if (IsLittleEndian != sys::IsLittleEndianHost)
40     sys::swapByteOrder(Integer);
41   OS.write(reinterpret_cast<char *>(&Integer), sizeof(T));
42 }
43 
44 static void writeVariableSizedInteger(uint64_t Integer, size_t Size,
45                                       raw_ostream &OS, bool IsLittleEndian) {
46   if (8 == Size)
47     writeInteger((uint64_t)Integer, OS, IsLittleEndian);
48   else if (4 == Size)
49     writeInteger((uint32_t)Integer, OS, IsLittleEndian);
50   else if (2 == Size)
51     writeInteger((uint16_t)Integer, OS, IsLittleEndian);
52   else if (1 == Size)
53     writeInteger((uint8_t)Integer, OS, IsLittleEndian);
54   else
55     assert(false && "Invalid integer write size.");
56 }
57 
58 static void ZeroFillBytes(raw_ostream &OS, size_t Size) {
59   std::vector<uint8_t> FillData;
60   FillData.insert(FillData.begin(), Size, 0);
61   OS.write(reinterpret_cast<char *>(FillData.data()), Size);
62 }
63 
64 static void writeInitialLength(const DWARFYAML::InitialLength &Length,
65                                raw_ostream &OS, bool IsLittleEndian) {
66   writeInteger((uint32_t)Length.TotalLength, OS, IsLittleEndian);
67   if (Length.isDWARF64())
68     writeInteger((uint64_t)Length.TotalLength64, OS, IsLittleEndian);
69 }
70 
71 void DWARFYAML::EmitDebugStr(raw_ostream &OS, const DWARFYAML::Data &DI) {
72   for (auto Str : DI.DebugStrings) {
73     OS.write(Str.data(), Str.size());
74     OS.write('\0');
75   }
76 }
77 
78 void DWARFYAML::EmitDebugAbbrev(raw_ostream &OS, const DWARFYAML::Data &DI) {
79   for (auto AbbrevDecl : DI.AbbrevDecls) {
80     encodeULEB128(AbbrevDecl.Code, OS);
81     encodeULEB128(AbbrevDecl.Tag, OS);
82     OS.write(AbbrevDecl.Children);
83     for (auto Attr : AbbrevDecl.Attributes) {
84       encodeULEB128(Attr.Attribute, OS);
85       encodeULEB128(Attr.Form, OS);
86       if (Attr.Form == dwarf::DW_FORM_implicit_const)
87         encodeSLEB128(Attr.Value, OS);
88     }
89     encodeULEB128(0, OS);
90     encodeULEB128(0, OS);
91   }
92 }
93 
94 void DWARFYAML::EmitDebugAranges(raw_ostream &OS, const DWARFYAML::Data &DI) {
95   for (auto Range : DI.ARanges) {
96     auto HeaderStart = OS.tell();
97     writeInitialLength(Range.Length, OS, DI.IsLittleEndian);
98     writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian);
99     writeInteger((uint32_t)Range.CuOffset, OS, DI.IsLittleEndian);
100     writeInteger((uint8_t)Range.AddrSize, OS, DI.IsLittleEndian);
101     writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
102 
103     auto HeaderSize = OS.tell() - HeaderStart;
104     auto FirstDescriptor = alignTo(HeaderSize, Range.AddrSize * 2);
105     ZeroFillBytes(OS, FirstDescriptor - HeaderSize);
106 
107     for (auto Descriptor : Range.Descriptors) {
108       writeVariableSizedInteger(Descriptor.Address, Range.AddrSize, OS,
109                                 DI.IsLittleEndian);
110       writeVariableSizedInteger(Descriptor.Length, Range.AddrSize, OS,
111                                 DI.IsLittleEndian);
112     }
113     ZeroFillBytes(OS, Range.AddrSize * 2);
114   }
115 }
116 
117 void DWARFYAML::EmitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) {
118   const size_t RangesOffset = OS.tell();
119   for (auto DebugRanges : DI.DebugRanges) {
120     const size_t CurrOffset = OS.tell() - RangesOffset;
121     assert(DebugRanges.Offset <= CurrOffset);
122     if (DebugRanges.Offset > CurrOffset)
123       ZeroFillBytes(OS, DebugRanges.Offset - CurrOffset);
124     for (auto Entry : DebugRanges.Entries) {
125       writeVariableSizedInteger(Entry.LowOffset, DebugRanges.AddrSize, OS,
126                                 DI.IsLittleEndian);
127       writeVariableSizedInteger(Entry.HighOffset, DebugRanges.AddrSize, OS,
128                                 DI.IsLittleEndian);
129     }
130     ZeroFillBytes(OS, DebugRanges.AddrSize * 2);
131   }
132 }
133 
134 void DWARFYAML::EmitPubSection(raw_ostream &OS,
135                                const DWARFYAML::PubSection &Sect,
136                                bool IsLittleEndian) {
137   writeInitialLength(Sect.Length, OS, IsLittleEndian);
138   writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
139   writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
140   writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
141   for (auto Entry : Sect.Entries) {
142     writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
143     if (Sect.IsGNUStyle)
144       writeInteger((uint32_t)Entry.Descriptor, OS, IsLittleEndian);
145     OS.write(Entry.Name.data(), Entry.Name.size());
146     OS.write('\0');
147   }
148 }
149 
150 namespace {
151 /// An extension of the DWARFYAML::ConstVisitor which writes compile
152 /// units and DIEs to a stream.
153 class DumpVisitor : public DWARFYAML::ConstVisitor {
154   raw_ostream &OS;
155 
156 protected:
157   void onStartCompileUnit(const DWARFYAML::Unit &CU) override {
158     writeInitialLength(CU.Length, OS, DebugInfo.IsLittleEndian);
159     writeInteger((uint16_t)CU.Version, OS, DebugInfo.IsLittleEndian);
160     if(CU.Version >= 5) {
161       writeInteger((uint8_t)CU.Type, OS, DebugInfo.IsLittleEndian);
162       writeInteger((uint8_t)CU.AddrSize, OS, DebugInfo.IsLittleEndian);
163       writeInteger((uint32_t)CU.AbbrOffset, OS, DebugInfo.IsLittleEndian);
164     }else {
165       writeInteger((uint32_t)CU.AbbrOffset, OS, DebugInfo.IsLittleEndian);
166       writeInteger((uint8_t)CU.AddrSize, OS, DebugInfo.IsLittleEndian);
167     }
168   }
169 
170   void onStartDIE(const DWARFYAML::Unit &CU,
171                   const DWARFYAML::Entry &DIE) override {
172     encodeULEB128(DIE.AbbrCode, OS);
173   }
174 
175   void onValue(const uint8_t U) override {
176     writeInteger(U, OS, DebugInfo.IsLittleEndian);
177   }
178 
179   void onValue(const uint16_t U) override {
180     writeInteger(U, OS, DebugInfo.IsLittleEndian);
181   }
182 
183   void onValue(const uint32_t U) override {
184     writeInteger(U, OS, DebugInfo.IsLittleEndian);
185   }
186 
187   void onValue(const uint64_t U, const bool LEB = false) override {
188     if (LEB)
189       encodeULEB128(U, OS);
190     else
191       writeInteger(U, OS, DebugInfo.IsLittleEndian);
192   }
193 
194   void onValue(const int64_t S, const bool LEB = false) override {
195     if (LEB)
196       encodeSLEB128(S, OS);
197     else
198       writeInteger(S, OS, DebugInfo.IsLittleEndian);
199   }
200 
201   void onValue(const StringRef String) override {
202     OS.write(String.data(), String.size());
203     OS.write('\0');
204   }
205 
206   void onValue(const MemoryBufferRef MBR) override {
207     OS.write(MBR.getBufferStart(), MBR.getBufferSize());
208   }
209 
210 public:
211   DumpVisitor(const DWARFYAML::Data &DI, raw_ostream &Out)
212       : DWARFYAML::ConstVisitor(DI), OS(Out) {}
213 };
214 } // namespace
215 
216 void DWARFYAML::EmitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) {
217   DumpVisitor Visitor(DI, OS);
218   Visitor.traverseDebugInfo();
219 }
220 
221 static void EmitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
222   OS.write(File.Name.data(), File.Name.size());
223   OS.write('\0');
224   encodeULEB128(File.DirIdx, OS);
225   encodeULEB128(File.ModTime, OS);
226   encodeULEB128(File.Length, OS);
227 }
228 
229 void DWARFYAML::EmitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) {
230   for (const auto &LineTable : DI.DebugLines) {
231     writeInitialLength(LineTable.Length, OS, DI.IsLittleEndian);
232     uint64_t SizeOfPrologueLength = LineTable.Length.isDWARF64() ? 8 : 4;
233     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
234     writeVariableSizedInteger(LineTable.PrologueLength, SizeOfPrologueLength,
235                               OS, DI.IsLittleEndian);
236     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
237     if (LineTable.Version >= 4)
238       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
239     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
240     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
241     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
242     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
243 
244     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
245       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
246 
247     for (auto IncludeDir : LineTable.IncludeDirs) {
248       OS.write(IncludeDir.data(), IncludeDir.size());
249       OS.write('\0');
250     }
251     OS.write('\0');
252 
253     for (auto File : LineTable.Files)
254       EmitFileEntry(OS, File);
255     OS.write('\0');
256 
257     for (auto Op : LineTable.Opcodes) {
258       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
259       if (Op.Opcode == 0) {
260         encodeULEB128(Op.ExtLen, OS);
261         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
262         switch (Op.SubOpcode) {
263         case dwarf::DW_LNE_set_address:
264         case dwarf::DW_LNE_set_discriminator:
265           writeVariableSizedInteger(Op.Data, DI.CompileUnits[0].AddrSize, OS,
266                                     DI.IsLittleEndian);
267           break;
268         case dwarf::DW_LNE_define_file:
269           EmitFileEntry(OS, Op.FileEntry);
270           break;
271         case dwarf::DW_LNE_end_sequence:
272           break;
273         default:
274           for (auto OpByte : Op.UnknownOpcodeData)
275             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
276         }
277       } else if (Op.Opcode < LineTable.OpcodeBase) {
278         switch (Op.Opcode) {
279         case dwarf::DW_LNS_copy:
280         case dwarf::DW_LNS_negate_stmt:
281         case dwarf::DW_LNS_set_basic_block:
282         case dwarf::DW_LNS_const_add_pc:
283         case dwarf::DW_LNS_set_prologue_end:
284         case dwarf::DW_LNS_set_epilogue_begin:
285           break;
286 
287         case dwarf::DW_LNS_advance_pc:
288         case dwarf::DW_LNS_set_file:
289         case dwarf::DW_LNS_set_column:
290         case dwarf::DW_LNS_set_isa:
291           encodeULEB128(Op.Data, OS);
292           break;
293 
294         case dwarf::DW_LNS_advance_line:
295           encodeSLEB128(Op.SData, OS);
296           break;
297 
298         case dwarf::DW_LNS_fixed_advance_pc:
299           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
300           break;
301 
302         default:
303           for (auto OpData : Op.StandardOpcodeData) {
304             encodeULEB128(OpData, OS);
305           }
306         }
307       }
308     }
309   }
310 }
311 
312 using EmitFuncType = void (*)(raw_ostream &, const DWARFYAML::Data &);
313 
314 static void
315 EmitDebugSectionImpl(const DWARFYAML::Data &DI, EmitFuncType EmitFunc,
316                      StringRef Sec,
317                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
318   std::string Data;
319   raw_string_ostream DebugInfoStream(Data);
320   EmitFunc(DebugInfoStream, DI);
321   DebugInfoStream.flush();
322   if (!Data.empty())
323     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
324 }
325 
326 namespace {
327 class DIEFixupVisitor : public DWARFYAML::Visitor {
328   uint64_t Length;
329 
330 public:
331   DIEFixupVisitor(DWARFYAML::Data &DI) : DWARFYAML::Visitor(DI){};
332 
333 private:
334   virtual void onStartCompileUnit(DWARFYAML::Unit &CU) {
335     // Size of the unit header, excluding the length field itself.
336     Length = CU.Version >= 5 ? 8 : 7;
337   }
338 
339   virtual void onEndCompileUnit(DWARFYAML::Unit &CU) {
340     CU.Length.setLength(Length);
341   }
342 
343   virtual void onStartDIE(DWARFYAML::Unit &CU, DWARFYAML::Entry &DIE) {
344     Length += getULEB128Size(DIE.AbbrCode);
345   }
346 
347   virtual void onValue(const uint8_t U) { Length += 1; }
348   virtual void onValue(const uint16_t U) { Length += 2; }
349   virtual void onValue(const uint32_t U) { Length += 4; }
350   virtual void onValue(const uint64_t U, const bool LEB = false) {
351     if (LEB)
352       Length += getULEB128Size(U);
353     else
354       Length += 8;
355   }
356   virtual void onValue(const int64_t S, const bool LEB = false) {
357     if (LEB)
358       Length += getSLEB128Size(S);
359     else
360       Length += 8;
361   }
362   virtual void onValue(const StringRef String) { Length += String.size() + 1; }
363 
364   virtual void onValue(const MemoryBufferRef MBR) {
365     Length += MBR.getBufferSize();
366   }
367 };
368 } // namespace
369 
370 Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
371 DWARFYAML::EmitDebugSections(StringRef YAMLString, bool ApplyFixups,
372                              bool IsLittleEndian) {
373   yaml::Input YIn(YAMLString);
374 
375   DWARFYAML::Data DI;
376   DI.IsLittleEndian = IsLittleEndian;
377   YIn >> DI;
378   if (YIn.error())
379     return errorCodeToError(YIn.error());
380 
381   if (ApplyFixups) {
382     DIEFixupVisitor DIFixer(DI);
383     DIFixer.traverseDebugInfo();
384   }
385 
386   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
387   EmitDebugSectionImpl(DI, &DWARFYAML::EmitDebugInfo, "debug_info",
388                        DebugSections);
389   EmitDebugSectionImpl(DI, &DWARFYAML::EmitDebugLine, "debug_line",
390                        DebugSections);
391   EmitDebugSectionImpl(DI, &DWARFYAML::EmitDebugStr, "debug_str",
392                        DebugSections);
393   EmitDebugSectionImpl(DI, &DWARFYAML::EmitDebugAbbrev, "debug_abbrev",
394                        DebugSections);
395   EmitDebugSectionImpl(DI, &DWARFYAML::EmitDebugAranges, "debug_aranges",
396                        DebugSections);
397   EmitDebugSectionImpl(DI, &DWARFYAML::EmitDebugRanges, "debug_ranges",
398                        DebugSections);
399   return std::move(DebugSections);
400 }
401