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/SourceMgr.h"
27 #include "llvm/Support/SwapByteOrder.h"
28 #include "llvm/Support/YAMLTraits.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstddef>
33 #include <cstdint>
34 #include <memory>
35 #include <string>
36 #include <vector>
37 
38 using namespace llvm;
39 
40 template <typename T>
41 static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian) {
42   if (IsLittleEndian != sys::IsLittleEndianHost)
43     sys::swapByteOrder(Integer);
44   OS.write(reinterpret_cast<char *>(&Integer), sizeof(T));
45 }
46 
47 static Error writeVariableSizedInteger(uint64_t Integer, size_t Size,
48                                        raw_ostream &OS, bool IsLittleEndian) {
49   if (8 == Size)
50     writeInteger((uint64_t)Integer, OS, IsLittleEndian);
51   else if (4 == Size)
52     writeInteger((uint32_t)Integer, OS, IsLittleEndian);
53   else if (2 == Size)
54     writeInteger((uint16_t)Integer, OS, IsLittleEndian);
55   else if (1 == Size)
56     writeInteger((uint8_t)Integer, OS, IsLittleEndian);
57   else
58     return createStringError(errc::not_supported,
59                              "invalid integer write size: %zu", Size);
60 
61   return Error::success();
62 }
63 
64 static void ZeroFillBytes(raw_ostream &OS, size_t Size) {
65   std::vector<uint8_t> FillData;
66   FillData.insert(FillData.begin(), Size, 0);
67   OS.write(reinterpret_cast<char *>(FillData.data()), Size);
68 }
69 
70 static void writeInitialLength(const DWARFYAML::InitialLength &Length,
71                                raw_ostream &OS, bool IsLittleEndian) {
72   writeInteger((uint32_t)Length.TotalLength, OS, IsLittleEndian);
73   if (Length.isDWARF64())
74     writeInteger((uint64_t)Length.TotalLength64, OS, IsLittleEndian);
75 }
76 
77 static void writeInitialLength(const dwarf::DwarfFormat Format,
78                                const uint64_t Length, raw_ostream &OS,
79                                bool IsLittleEndian) {
80   bool IsDWARF64 = Format == dwarf::DWARF64;
81   if (IsDWARF64)
82     cantFail(writeVariableSizedInteger(dwarf::DW_LENGTH_DWARF64, 4, OS,
83                                        IsLittleEndian));
84   cantFail(
85       writeVariableSizedInteger(Length, IsDWARF64 ? 8 : 4, OS, IsLittleEndian));
86 }
87 
88 Error DWARFYAML::emitDebugStr(raw_ostream &OS, const DWARFYAML::Data &DI) {
89   for (auto Str : DI.DebugStrings) {
90     OS.write(Str.data(), Str.size());
91     OS.write('\0');
92   }
93 
94   return Error::success();
95 }
96 
97 Error DWARFYAML::emitDebugAbbrev(raw_ostream &OS, const DWARFYAML::Data &DI) {
98   uint64_t AbbrevCode = 0;
99   for (auto AbbrevDecl : DI.AbbrevDecls) {
100     AbbrevCode = AbbrevDecl.Code ? (uint64_t)*AbbrevDecl.Code : AbbrevCode + 1;
101     encodeULEB128(AbbrevCode, OS);
102     encodeULEB128(AbbrevDecl.Tag, OS);
103     OS.write(AbbrevDecl.Children);
104     for (auto Attr : AbbrevDecl.Attributes) {
105       encodeULEB128(Attr.Attribute, OS);
106       encodeULEB128(Attr.Form, OS);
107       if (Attr.Form == dwarf::DW_FORM_implicit_const)
108         encodeSLEB128(Attr.Value, OS);
109     }
110     encodeULEB128(0, OS);
111     encodeULEB128(0, OS);
112   }
113 
114   // The abbreviations for a given compilation unit end with an entry consisting
115   // of a 0 byte for the abbreviation code.
116   OS.write_zeros(1);
117 
118   return Error::success();
119 }
120 
121 Error DWARFYAML::emitDebugAranges(raw_ostream &OS, const DWARFYAML::Data &DI) {
122   for (auto Range : DI.ARanges) {
123     auto HeaderStart = OS.tell();
124     writeInitialLength(Range.Format, Range.Length, OS, DI.IsLittleEndian);
125     writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian);
126     if (Range.Format == dwarf::DWARF64)
127       writeInteger((uint64_t)Range.CuOffset, OS, DI.IsLittleEndian);
128     else
129       writeInteger((uint32_t)Range.CuOffset, OS, DI.IsLittleEndian);
130     writeInteger((uint8_t)Range.AddrSize, OS, DI.IsLittleEndian);
131     writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
132 
133     auto HeaderSize = OS.tell() - HeaderStart;
134     auto FirstDescriptor = alignTo(HeaderSize, Range.AddrSize * 2);
135     ZeroFillBytes(OS, FirstDescriptor - HeaderSize);
136 
137     for (auto Descriptor : Range.Descriptors) {
138       if (Error Err = writeVariableSizedInteger(
139               Descriptor.Address, Range.AddrSize, OS, DI.IsLittleEndian))
140         return createStringError(errc::not_supported,
141                                  "unable to write debug_aranges address: %s",
142                                  toString(std::move(Err)).c_str());
143       cantFail(writeVariableSizedInteger(Descriptor.Length, Range.AddrSize, OS,
144                                          DI.IsLittleEndian));
145     }
146     ZeroFillBytes(OS, Range.AddrSize * 2);
147   }
148 
149   return Error::success();
150 }
151 
152 Error DWARFYAML::emitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) {
153   const size_t RangesOffset = OS.tell();
154   uint64_t EntryIndex = 0;
155   for (auto DebugRanges : DI.DebugRanges) {
156     const size_t CurrOffset = OS.tell() - RangesOffset;
157     if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset)
158       return createStringError(errc::invalid_argument,
159                                "'Offset' for 'debug_ranges' with index " +
160                                    Twine(EntryIndex) +
161                                    " must be greater than or equal to the "
162                                    "number of bytes written already (0x" +
163                                    Twine::utohexstr(CurrOffset) + ")");
164     if (DebugRanges.Offset)
165       ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset);
166 
167     uint8_t AddrSize;
168     if (DebugRanges.AddrSize)
169       AddrSize = *DebugRanges.AddrSize;
170     else
171       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
172     for (auto Entry : DebugRanges.Entries) {
173       if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS,
174                                                 DI.IsLittleEndian))
175         return createStringError(
176             errc::not_supported,
177             "unable to write debug_ranges address offset: %s",
178             toString(std::move(Err)).c_str());
179       cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS,
180                                          DI.IsLittleEndian));
181     }
182     ZeroFillBytes(OS, AddrSize * 2);
183     ++EntryIndex;
184   }
185 
186   return Error::success();
187 }
188 
189 Error DWARFYAML::emitPubSection(raw_ostream &OS,
190                                 const DWARFYAML::PubSection &Sect,
191                                 bool IsLittleEndian, bool IsGNUPubSec) {
192   writeInitialLength(Sect.Length, OS, IsLittleEndian);
193   writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
194   writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
195   writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
196   for (auto Entry : Sect.Entries) {
197     writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
198     if (IsGNUPubSec)
199       writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian);
200     OS.write(Entry.Name.data(), Entry.Name.size());
201     OS.write('\0');
202   }
203 
204   return Error::success();
205 }
206 
207 namespace {
208 /// An extension of the DWARFYAML::ConstVisitor which writes compile
209 /// units and DIEs to a stream.
210 class DumpVisitor : public DWARFYAML::ConstVisitor {
211   raw_ostream &OS;
212 
213 protected:
214   void onStartCompileUnit(const DWARFYAML::Unit &CU) override {
215     writeInitialLength(CU.Format, CU.Length, OS, DebugInfo.IsLittleEndian);
216     writeInteger((uint16_t)CU.Version, OS, DebugInfo.IsLittleEndian);
217     if (CU.Version >= 5) {
218       writeInteger((uint8_t)CU.Type, OS, DebugInfo.IsLittleEndian);
219       writeInteger((uint8_t)CU.AddrSize, OS, DebugInfo.IsLittleEndian);
220       cantFail(writeVariableSizedInteger(CU.AbbrOffset,
221                                          CU.Format == dwarf::DWARF64 ? 8 : 4,
222                                          OS, DebugInfo.IsLittleEndian));
223     } else {
224       cantFail(writeVariableSizedInteger(CU.AbbrOffset,
225                                          CU.Format == dwarf::DWARF64 ? 8 : 4,
226                                          OS, DebugInfo.IsLittleEndian));
227       writeInteger((uint8_t)CU.AddrSize, OS, DebugInfo.IsLittleEndian);
228     }
229   }
230 
231   void onStartDIE(const DWARFYAML::Unit &CU,
232                   const DWARFYAML::Entry &DIE) override {
233     encodeULEB128(DIE.AbbrCode, OS);
234   }
235 
236   void onValue(const uint8_t U) override {
237     writeInteger(U, OS, DebugInfo.IsLittleEndian);
238   }
239 
240   void onValue(const uint16_t U) override {
241     writeInteger(U, OS, DebugInfo.IsLittleEndian);
242   }
243 
244   void onValue(const uint32_t U) override {
245     writeInteger(U, OS, DebugInfo.IsLittleEndian);
246   }
247 
248   void onValue(const uint64_t U, const bool LEB = false) override {
249     if (LEB)
250       encodeULEB128(U, OS);
251     else
252       writeInteger(U, OS, DebugInfo.IsLittleEndian);
253   }
254 
255   void onValue(const int64_t S, const bool LEB = false) override {
256     if (LEB)
257       encodeSLEB128(S, OS);
258     else
259       writeInteger(S, OS, DebugInfo.IsLittleEndian);
260   }
261 
262   void onValue(const StringRef String) override {
263     OS.write(String.data(), String.size());
264     OS.write('\0');
265   }
266 
267   void onValue(const MemoryBufferRef MBR) override {
268     OS.write(MBR.getBufferStart(), MBR.getBufferSize());
269   }
270 
271 public:
272   DumpVisitor(const DWARFYAML::Data &DI, raw_ostream &Out)
273       : DWARFYAML::ConstVisitor(DI), OS(Out) {}
274 };
275 } // namespace
276 
277 Error DWARFYAML::emitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) {
278   DumpVisitor Visitor(DI, OS);
279   return Visitor.traverseDebugInfo();
280 }
281 
282 static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
283   OS.write(File.Name.data(), File.Name.size());
284   OS.write('\0');
285   encodeULEB128(File.DirIdx, OS);
286   encodeULEB128(File.ModTime, OS);
287   encodeULEB128(File.Length, OS);
288 }
289 
290 Error DWARFYAML::emitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) {
291   for (const auto &LineTable : DI.DebugLines) {
292     writeInitialLength(LineTable.Format, LineTable.Length, OS,
293                        DI.IsLittleEndian);
294     uint64_t SizeOfPrologueLength = LineTable.Format == dwarf::DWARF64 ? 8 : 4;
295     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
296     cantFail(writeVariableSizedInteger(
297         LineTable.PrologueLength, SizeOfPrologueLength, OS, DI.IsLittleEndian));
298     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
299     if (LineTable.Version >= 4)
300       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
301     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
302     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
303     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
304     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
305 
306     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
307       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
308 
309     for (auto IncludeDir : LineTable.IncludeDirs) {
310       OS.write(IncludeDir.data(), IncludeDir.size());
311       OS.write('\0');
312     }
313     OS.write('\0');
314 
315     for (auto File : LineTable.Files)
316       emitFileEntry(OS, File);
317     OS.write('\0');
318 
319     for (auto Op : LineTable.Opcodes) {
320       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
321       if (Op.Opcode == 0) {
322         encodeULEB128(Op.ExtLen, OS);
323         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
324         switch (Op.SubOpcode) {
325         case dwarf::DW_LNE_set_address:
326         case dwarf::DW_LNE_set_discriminator:
327           // TODO: Test this error.
328           if (Error Err = writeVariableSizedInteger(
329                   Op.Data, DI.CompileUnits[0].AddrSize, OS, DI.IsLittleEndian))
330             return Err;
331           break;
332         case dwarf::DW_LNE_define_file:
333           emitFileEntry(OS, Op.FileEntry);
334           break;
335         case dwarf::DW_LNE_end_sequence:
336           break;
337         default:
338           for (auto OpByte : Op.UnknownOpcodeData)
339             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
340         }
341       } else if (Op.Opcode < LineTable.OpcodeBase) {
342         switch (Op.Opcode) {
343         case dwarf::DW_LNS_copy:
344         case dwarf::DW_LNS_negate_stmt:
345         case dwarf::DW_LNS_set_basic_block:
346         case dwarf::DW_LNS_const_add_pc:
347         case dwarf::DW_LNS_set_prologue_end:
348         case dwarf::DW_LNS_set_epilogue_begin:
349           break;
350 
351         case dwarf::DW_LNS_advance_pc:
352         case dwarf::DW_LNS_set_file:
353         case dwarf::DW_LNS_set_column:
354         case dwarf::DW_LNS_set_isa:
355           encodeULEB128(Op.Data, OS);
356           break;
357 
358         case dwarf::DW_LNS_advance_line:
359           encodeSLEB128(Op.SData, OS);
360           break;
361 
362         case dwarf::DW_LNS_fixed_advance_pc:
363           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
364           break;
365 
366         default:
367           for (auto OpData : Op.StandardOpcodeData) {
368             encodeULEB128(OpData, OS);
369           }
370         }
371       }
372     }
373   }
374 
375   return Error::success();
376 }
377 
378 Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) {
379   for (const AddrTableEntry &TableEntry : DI.DebugAddr) {
380     uint8_t AddrSize;
381     if (TableEntry.AddrSize)
382       AddrSize = *TableEntry.AddrSize;
383     else
384       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
385 
386     uint64_t Length;
387     if (TableEntry.Length)
388       Length = (uint64_t)*TableEntry.Length;
389     else
390       // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
391       Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
392                        TableEntry.SegAddrPairs.size();
393 
394     writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian);
395     writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian);
396     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
397     writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
398 
399     for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
400       if (TableEntry.SegSelectorSize != 0)
401         if (Error Err = writeVariableSizedInteger(Pair.Segment,
402                                                   TableEntry.SegSelectorSize,
403                                                   OS, DI.IsLittleEndian))
404           return createStringError(errc::not_supported,
405                                    "unable to write debug_addr segment: %s",
406                                    toString(std::move(Err)).c_str());
407       if (AddrSize != 0)
408         if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
409                                                   DI.IsLittleEndian))
410           return createStringError(errc::not_supported,
411                                    "unable to write debug_addr address: %s",
412                                    toString(std::move(Err)).c_str());
413     }
414   }
415 
416   return Error::success();
417 }
418 
419 Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) {
420   assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
421   for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
422     uint64_t Length;
423     if (Table.Length)
424       Length = *Table.Length;
425     else
426       // sizeof(version) + sizeof(padding) = 4
427       Length =
428           4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
429 
430     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
431     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
432     writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian);
433 
434     for (uint64_t Offset : Table.Offsets) {
435       cantFail(writeVariableSizedInteger(Offset,
436                                          Table.Format == dwarf::DWARF64 ? 8 : 4,
437                                          OS, DI.IsLittleEndian));
438     }
439   }
440 
441   return Error::success();
442 }
443 
444 static Expected<uint64_t>
445 writeRnglistEntry(raw_ostream &OS, const DWARFYAML::RnglistEntry &Entry,
446                   uint8_t AddrSize, bool IsLittleEndian) {
447   uint64_t BeginOffset = OS.tell();
448   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
449 
450   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
451     if (Entry.Values.size() != ExpectedOperands) {
452       return createStringError(
453           errc::invalid_argument,
454           "invalid number (%zu) of operands for the operator: %s, %" PRIu64
455           " expected",
456           Entry.Values.size(),
457           dwarf::RangeListEncodingString(Entry.Operator).str().c_str(),
458           ExpectedOperands);
459     }
460 
461     return Error::success();
462   };
463 
464   auto WriteAddress = [&](uint64_t Addr) -> Error {
465     if (Error Err =
466             writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
467       return createStringError(
468           errc::not_supported,
469           "unable to write address for the operator %s: %s",
470           dwarf::RangeListEncodingString(Entry.Operator).str().c_str(),
471           toString(std::move(Err)).c_str());
472     return Error::success();
473   };
474 
475   switch (Entry.Operator) {
476   case dwarf::DW_RLE_end_of_list:
477     if (Error Err = CheckOperands(0))
478       return std::move(Err);
479     break;
480   case dwarf::DW_RLE_base_addressx:
481     if (Error Err = CheckOperands(1))
482       return std::move(Err);
483     encodeULEB128(Entry.Values[0], OS);
484     break;
485   case dwarf::DW_RLE_startx_endx:
486   case dwarf::DW_RLE_startx_length:
487   case dwarf::DW_RLE_offset_pair:
488     if (Error Err = CheckOperands(2))
489       return std::move(Err);
490     encodeULEB128(Entry.Values[0], OS);
491     encodeULEB128(Entry.Values[1], OS);
492     break;
493   case dwarf::DW_RLE_base_address:
494     if (Error Err = CheckOperands(1))
495       return std::move(Err);
496     if (Error Err = WriteAddress(Entry.Values[0]))
497       return std::move(Err);
498     break;
499   case dwarf::DW_RLE_start_end:
500     if (Error Err = CheckOperands(2))
501       return std::move(Err);
502     if (Error Err = WriteAddress(Entry.Values[0]))
503       return std::move(Err);
504     cantFail(WriteAddress(Entry.Values[1]));
505     break;
506   case dwarf::DW_RLE_start_length:
507     if (Error Err = CheckOperands(2))
508       return std::move(Err);
509     if (Error Err = WriteAddress(Entry.Values[0]))
510       return std::move(Err);
511     encodeULEB128(Entry.Values[1], OS);
512     break;
513   }
514 
515   return OS.tell() - BeginOffset;
516 }
517 
518 Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
519   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
520   for (const DWARFYAML::RnglistTable &Table : *DI.DebugRnglists) {
521     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
522     // sizeof(offset_entry_count) = 8
523     uint64_t Length = 8;
524 
525     uint8_t AddrSize;
526     if (Table.AddrSize)
527       AddrSize = *Table.AddrSize;
528     else
529       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
530 
531     // Since the length of the current range lists entry is undetermined yet, we
532     // firstly write the content of the range lists to a buffer to calculate the
533     // length and then serialize the buffer content to the actual output stream.
534     std::string ListBuffer;
535     raw_string_ostream ListBufferOS(ListBuffer);
536 
537     // Offsets holds offsets for each range list. The i-th element is the offset
538     // from the beginning of the first range list to the location of the i-th
539     // range list.
540     std::vector<uint64_t> Offsets;
541 
542     for (const DWARFYAML::Rnglist &List : Table.Lists) {
543       Offsets.push_back(ListBufferOS.tell());
544       for (const DWARFYAML::RnglistEntry &Entry : List.Entries) {
545         Expected<uint64_t> EntrySize =
546             writeRnglistEntry(ListBufferOS, Entry, AddrSize, DI.IsLittleEndian);
547         if (!EntrySize)
548           return EntrySize.takeError();
549         Length += *EntrySize;
550       }
551     }
552 
553     // If the offset_entry_count field isn't specified, yaml2obj will infer it
554     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
555     // isn't specified either, yaml2obj will infer it from the auto-generated
556     // offsets.
557     uint32_t OffsetEntryCount;
558     if (Table.OffsetEntryCount)
559       OffsetEntryCount = *Table.OffsetEntryCount;
560     else
561       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
562     uint64_t OffsetsSize =
563         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
564     Length += OffsetsSize;
565 
566     // If the length is specified in the YAML description, we use it instead of
567     // the actual length.
568     if (Table.Length)
569       Length = *Table.Length;
570 
571     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
572     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
573     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
574     writeInteger((uint8_t)Table.SegSelectorSize, OS, DI.IsLittleEndian);
575     writeInteger((uint32_t)OffsetEntryCount, OS, DI.IsLittleEndian);
576 
577     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
578       for (uint64_t Offset : Offsets) {
579         cantFail(writeVariableSizedInteger(
580             OffsetsSize + Offset, Table.Format == dwarf::DWARF64 ? 8 : 4, OS,
581             DI.IsLittleEndian));
582       }
583     };
584 
585     if (Table.Offsets)
586       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
587                                      Table.Offsets->size()),
588                   0);
589     else
590       EmitOffsets(Offsets, OffsetsSize);
591 
592     OS.write(ListBuffer.data(), ListBuffer.size());
593   }
594 
595   return Error::success();
596 }
597 
598 using EmitFuncType = Error (*)(raw_ostream &, const DWARFYAML::Data &);
599 
600 static Error
601 emitDebugSectionImpl(const DWARFYAML::Data &DI, EmitFuncType EmitFunc,
602                      StringRef Sec,
603                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
604   std::string Data;
605   raw_string_ostream DebugInfoStream(Data);
606   if (Error Err = EmitFunc(DebugInfoStream, DI))
607     return Err;
608   DebugInfoStream.flush();
609   if (!Data.empty())
610     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
611 
612   return Error::success();
613 }
614 
615 namespace {
616 class DIEFixupVisitor : public DWARFYAML::Visitor {
617   uint64_t Length;
618 
619 public:
620   DIEFixupVisitor(DWARFYAML::Data &DI) : DWARFYAML::Visitor(DI){};
621 
622 protected:
623   void onStartCompileUnit(DWARFYAML::Unit &CU) override {
624     // Size of the unit header, excluding the length field itself.
625     Length = CU.Version >= 5 ? 8 : 7;
626   }
627 
628   void onEndCompileUnit(DWARFYAML::Unit &CU) override { CU.Length = Length; }
629 
630   void onStartDIE(DWARFYAML::Unit &CU, DWARFYAML::Entry &DIE) override {
631     Length += getULEB128Size(DIE.AbbrCode);
632   }
633 
634   void onValue(const uint8_t U) override { Length += 1; }
635   void onValue(const uint16_t U) override { Length += 2; }
636   void onValue(const uint32_t U) override { Length += 4; }
637   void onValue(const uint64_t U, const bool LEB = false) override {
638     if (LEB)
639       Length += getULEB128Size(U);
640     else
641       Length += 8;
642   }
643   void onValue(const int64_t S, const bool LEB = false) override {
644     if (LEB)
645       Length += getSLEB128Size(S);
646     else
647       Length += 8;
648   }
649   void onValue(const StringRef String) override { Length += String.size() + 1; }
650 
651   void onValue(const MemoryBufferRef MBR) override {
652     Length += MBR.getBufferSize();
653   }
654 };
655 } // namespace
656 
657 Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
658 DWARFYAML::emitDebugSections(StringRef YAMLString, bool ApplyFixups,
659                              bool IsLittleEndian) {
660   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
661     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
662   };
663 
664   SMDiagnostic GeneratedDiag;
665   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
666                   &GeneratedDiag);
667 
668   DWARFYAML::Data DI;
669   DI.IsLittleEndian = IsLittleEndian;
670   YIn >> DI;
671   if (YIn.error())
672     return createStringError(YIn.error(), GeneratedDiag.getMessage());
673 
674   if (ApplyFixups) {
675     DIEFixupVisitor DIFixer(DI);
676     if (Error Err = DIFixer.traverseDebugInfo())
677       return std::move(Err);
678   }
679 
680   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
681   Error Err = emitDebugSectionImpl(DI, &DWARFYAML::emitDebugInfo, "debug_info",
682                                    DebugSections);
683   Err = joinErrors(std::move(Err),
684                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugLine,
685                                         "debug_line", DebugSections));
686   Err = joinErrors(std::move(Err),
687                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugStr,
688                                         "debug_str", DebugSections));
689   Err = joinErrors(std::move(Err),
690                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugAbbrev,
691                                         "debug_abbrev", DebugSections));
692   Err = joinErrors(std::move(Err),
693                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugAranges,
694                                         "debug_aranges", DebugSections));
695   Err = joinErrors(std::move(Err),
696                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugRanges,
697                                         "debug_ranges", DebugSections));
698 
699   if (Err)
700     return std::move(Err);
701   return std::move(DebugSections);
702 }
703