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