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