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 "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/ObjectYAML/DWARFYAML.h"
21 #include "llvm/Support/Errc.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/Host.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/SwapByteOrder.h"
29 #include "llvm/Support/YAMLTraits.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cassert>
33 #include <cstddef>
34 #include <cstdint>
35 #include <memory>
36 #include <string>
37 #include <vector>
38 
39 using namespace llvm;
40 
41 template <typename T>
42 static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian) {
43   if (IsLittleEndian != sys::IsLittleEndianHost)
44     sys::swapByteOrder(Integer);
45   OS.write(reinterpret_cast<char *>(&Integer), sizeof(T));
46 }
47 
48 static Error writeVariableSizedInteger(uint64_t Integer, size_t Size,
49                                        raw_ostream &OS, bool IsLittleEndian) {
50   if (8 == Size)
51     writeInteger((uint64_t)Integer, OS, IsLittleEndian);
52   else if (4 == Size)
53     writeInteger((uint32_t)Integer, OS, IsLittleEndian);
54   else if (2 == Size)
55     writeInteger((uint16_t)Integer, OS, IsLittleEndian);
56   else if (1 == Size)
57     writeInteger((uint8_t)Integer, OS, IsLittleEndian);
58   else
59     return createStringError(errc::not_supported,
60                              "invalid integer write size: %zu", Size);
61 
62   return Error::success();
63 }
64 
65 static void ZeroFillBytes(raw_ostream &OS, size_t Size) {
66   std::vector<uint8_t> FillData;
67   FillData.insert(FillData.begin(), Size, 0);
68   OS.write(reinterpret_cast<char *>(FillData.data()), Size);
69 }
70 
71 static void writeInitialLength(const DWARFYAML::InitialLength &Length,
72                                raw_ostream &OS, bool IsLittleEndian) {
73   writeInteger((uint32_t)Length.TotalLength, OS, IsLittleEndian);
74   if (Length.isDWARF64())
75     writeInteger((uint64_t)Length.TotalLength64, OS, IsLittleEndian);
76 }
77 
78 static void writeInitialLength(const dwarf::DwarfFormat Format,
79                                const uint64_t Length, raw_ostream &OS,
80                                bool IsLittleEndian) {
81   bool IsDWARF64 = Format == dwarf::DWARF64;
82   if (IsDWARF64)
83     cantFail(writeVariableSizedInteger(dwarf::DW_LENGTH_DWARF64, 4, OS,
84                                        IsLittleEndian));
85   cantFail(
86       writeVariableSizedInteger(Length, IsDWARF64 ? 8 : 4, OS, IsLittleEndian));
87 }
88 
89 static void writeDWARFOffset(uint64_t Offset, dwarf::DwarfFormat Format,
90                              raw_ostream &OS, bool IsLittleEndian) {
91   cantFail(writeVariableSizedInteger(Offset, Format == dwarf::DWARF64 ? 8 : 4,
92                                      OS, IsLittleEndian));
93 }
94 
95 Error DWARFYAML::emitDebugStr(raw_ostream &OS, const DWARFYAML::Data &DI) {
96   for (auto Str : DI.DebugStrings) {
97     OS.write(Str.data(), Str.size());
98     OS.write('\0');
99   }
100 
101   return Error::success();
102 }
103 
104 Error DWARFYAML::emitDebugAbbrev(raw_ostream &OS, const DWARFYAML::Data &DI) {
105   uint64_t AbbrevCode = 0;
106   for (auto AbbrevDecl : DI.AbbrevDecls) {
107     AbbrevCode = AbbrevDecl.Code ? (uint64_t)*AbbrevDecl.Code : AbbrevCode + 1;
108     encodeULEB128(AbbrevCode, OS);
109     encodeULEB128(AbbrevDecl.Tag, OS);
110     OS.write(AbbrevDecl.Children);
111     for (auto Attr : AbbrevDecl.Attributes) {
112       encodeULEB128(Attr.Attribute, OS);
113       encodeULEB128(Attr.Form, OS);
114       if (Attr.Form == dwarf::DW_FORM_implicit_const)
115         encodeSLEB128(Attr.Value, OS);
116     }
117     encodeULEB128(0, OS);
118     encodeULEB128(0, OS);
119   }
120 
121   // The abbreviations for a given compilation unit end with an entry consisting
122   // of a 0 byte for the abbreviation code.
123   OS.write_zeros(1);
124 
125   return Error::success();
126 }
127 
128 Error DWARFYAML::emitDebugAranges(raw_ostream &OS, const DWARFYAML::Data &DI) {
129   assert(DI.DebugAranges && "unexpected emitDebugAranges() call");
130   for (auto Range : *DI.DebugAranges) {
131     uint8_t AddrSize;
132     if (Range.AddrSize)
133       AddrSize = *Range.AddrSize;
134     else
135       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
136 
137     uint64_t Length = 4; // sizeof(version) 2 + sizeof(address_size) 1 +
138                          // sizeof(segment_selector_size) 1
139     Length +=
140         Range.Format == dwarf::DWARF64 ? 8 : 4; // sizeof(debug_info_offset)
141 
142     const uint64_t HeaderLength =
143         Length + (Range.Format == dwarf::DWARF64
144                       ? 12
145                       : 4); // sizeof(unit_header) = 12 (DWARF64) or 4 (DWARF32)
146     const uint64_t PaddedHeaderLength = alignTo(HeaderLength, AddrSize * 2);
147 
148     if (Range.Length) {
149       Length = *Range.Length;
150     } else {
151       Length += PaddedHeaderLength - HeaderLength;
152       Length += AddrSize * 2 * (Range.Descriptors.size() + 1);
153     }
154 
155     writeInitialLength(Range.Format, Length, OS, DI.IsLittleEndian);
156     writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian);
157     writeDWARFOffset(Range.CuOffset, Range.Format, OS, DI.IsLittleEndian);
158     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
159     writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
160     ZeroFillBytes(OS, PaddedHeaderLength - HeaderLength);
161 
162     for (auto Descriptor : Range.Descriptors) {
163       if (Error Err = writeVariableSizedInteger(Descriptor.Address, AddrSize,
164                                                 OS, DI.IsLittleEndian))
165         return createStringError(errc::not_supported,
166                                  "unable to write debug_aranges address: %s",
167                                  toString(std::move(Err)).c_str());
168       cantFail(writeVariableSizedInteger(Descriptor.Length, AddrSize, OS,
169                                          DI.IsLittleEndian));
170     }
171     ZeroFillBytes(OS, AddrSize * 2);
172   }
173 
174   return Error::success();
175 }
176 
177 Error DWARFYAML::emitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) {
178   const size_t RangesOffset = OS.tell();
179   uint64_t EntryIndex = 0;
180   for (auto DebugRanges : DI.DebugRanges) {
181     const size_t CurrOffset = OS.tell() - RangesOffset;
182     if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset)
183       return createStringError(errc::invalid_argument,
184                                "'Offset' for 'debug_ranges' with index " +
185                                    Twine(EntryIndex) +
186                                    " must be greater than or equal to the "
187                                    "number of bytes written already (0x" +
188                                    Twine::utohexstr(CurrOffset) + ")");
189     if (DebugRanges.Offset)
190       ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset);
191 
192     uint8_t AddrSize;
193     if (DebugRanges.AddrSize)
194       AddrSize = *DebugRanges.AddrSize;
195     else
196       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
197     for (auto Entry : DebugRanges.Entries) {
198       if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS,
199                                                 DI.IsLittleEndian))
200         return createStringError(
201             errc::not_supported,
202             "unable to write debug_ranges address offset: %s",
203             toString(std::move(Err)).c_str());
204       cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS,
205                                          DI.IsLittleEndian));
206     }
207     ZeroFillBytes(OS, AddrSize * 2);
208     ++EntryIndex;
209   }
210 
211   return Error::success();
212 }
213 
214 static Error emitPubSection(raw_ostream &OS, const DWARFYAML::PubSection &Sect,
215                             bool IsLittleEndian, bool IsGNUPubSec = false) {
216   writeInitialLength(Sect.Length, OS, IsLittleEndian);
217   writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
218   writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
219   writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
220   for (auto Entry : Sect.Entries) {
221     writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
222     if (IsGNUPubSec)
223       writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian);
224     OS.write(Entry.Name.data(), Entry.Name.size());
225     OS.write('\0');
226   }
227 
228   return Error::success();
229 }
230 
231 Error DWARFYAML::emitDebugPubnames(raw_ostream &OS, const Data &DI) {
232   assert(DI.PubNames && "unexpected emitDebugPubnames() call");
233   return emitPubSection(OS, *DI.PubNames, DI.IsLittleEndian);
234 }
235 
236 Error DWARFYAML::emitDebugPubtypes(raw_ostream &OS, const Data &DI) {
237   assert(DI.PubTypes && "unexpected emitDebugPubtypes() call");
238   return emitPubSection(OS, *DI.PubTypes, DI.IsLittleEndian);
239 }
240 
241 Error DWARFYAML::emitDebugGNUPubnames(raw_ostream &OS, const Data &DI) {
242   assert(DI.GNUPubNames && "unexpected emitDebugGNUPubnames() call");
243   return emitPubSection(OS, *DI.GNUPubNames, DI.IsLittleEndian,
244                         /*IsGNUStyle=*/true);
245 }
246 
247 Error DWARFYAML::emitDebugGNUPubtypes(raw_ostream &OS, const Data &DI) {
248   assert(DI.GNUPubTypes && "unexpected emitDebugGNUPubtypes() call");
249   return emitPubSection(OS, *DI.GNUPubTypes, DI.IsLittleEndian,
250                         /*IsGNUStyle=*/true);
251 }
252 
253 static Expected<uint64_t> writeDIE(ArrayRef<DWARFYAML::Abbrev> AbbrevDecls,
254                                    const DWARFYAML::Unit &Unit,
255                                    const DWARFYAML::Entry &Entry,
256                                    raw_ostream &OS, bool IsLittleEndian) {
257   uint64_t EntryBegin = OS.tell();
258   encodeULEB128(Entry.AbbrCode, OS);
259   uint32_t AbbrCode = Entry.AbbrCode;
260   if (AbbrCode == 0 || Entry.Values.empty())
261     return OS.tell() - EntryBegin;
262 
263   if (AbbrCode > AbbrevDecls.size())
264     return createStringError(
265         errc::invalid_argument,
266         "abbrev code must be less than or equal to the number of "
267         "entries in abbreviation table");
268   const DWARFYAML::Abbrev &Abbrev = AbbrevDecls[AbbrCode - 1];
269   auto FormVal = Entry.Values.begin();
270   auto AbbrForm = Abbrev.Attributes.begin();
271   for (; FormVal != Entry.Values.end() && AbbrForm != Abbrev.Attributes.end();
272        ++FormVal, ++AbbrForm) {
273     dwarf::Form Form = AbbrForm->Form;
274     bool Indirect;
275     do {
276       Indirect = false;
277       switch (Form) {
278       case dwarf::DW_FORM_addr:
279         // TODO: Test this error.
280         if (Error Err = writeVariableSizedInteger(
281                 FormVal->Value, Unit.FormParams.AddrSize, OS, IsLittleEndian))
282           return std::move(Err);
283         break;
284       case dwarf::DW_FORM_ref_addr:
285         // TODO: Test this error.
286         if (Error Err = writeVariableSizedInteger(
287                 FormVal->Value, Unit.FormParams.getRefAddrByteSize(), OS,
288                 IsLittleEndian))
289           return std::move(Err);
290         break;
291       case dwarf::DW_FORM_exprloc:
292       case dwarf::DW_FORM_block:
293         encodeULEB128(FormVal->BlockData.size(), OS);
294         OS.write((const char *)FormVal->BlockData.data(),
295                  FormVal->BlockData.size());
296         break;
297       case dwarf::DW_FORM_block1: {
298         writeInteger((uint8_t)FormVal->BlockData.size(), OS, IsLittleEndian);
299         OS.write((const char *)FormVal->BlockData.data(),
300                  FormVal->BlockData.size());
301         break;
302       }
303       case dwarf::DW_FORM_block2: {
304         writeInteger((uint16_t)FormVal->BlockData.size(), OS, IsLittleEndian);
305         OS.write((const char *)FormVal->BlockData.data(),
306                  FormVal->BlockData.size());
307         break;
308       }
309       case dwarf::DW_FORM_block4: {
310         writeInteger((uint32_t)FormVal->BlockData.size(), OS, IsLittleEndian);
311         OS.write((const char *)FormVal->BlockData.data(),
312                  FormVal->BlockData.size());
313         break;
314       }
315       case dwarf::DW_FORM_strx:
316       case dwarf::DW_FORM_addrx:
317       case dwarf::DW_FORM_rnglistx:
318       case dwarf::DW_FORM_loclistx:
319       case dwarf::DW_FORM_udata:
320       case dwarf::DW_FORM_ref_udata:
321       case dwarf::DW_FORM_GNU_addr_index:
322       case dwarf::DW_FORM_GNU_str_index:
323         encodeULEB128(FormVal->Value, OS);
324         break;
325       case dwarf::DW_FORM_data1:
326       case dwarf::DW_FORM_ref1:
327       case dwarf::DW_FORM_flag:
328       case dwarf::DW_FORM_strx1:
329       case dwarf::DW_FORM_addrx1:
330         writeInteger((uint8_t)FormVal->Value, OS, IsLittleEndian);
331         break;
332       case dwarf::DW_FORM_data2:
333       case dwarf::DW_FORM_ref2:
334       case dwarf::DW_FORM_strx2:
335       case dwarf::DW_FORM_addrx2:
336         writeInteger((uint16_t)FormVal->Value, OS, IsLittleEndian);
337         break;
338       case dwarf::DW_FORM_data4:
339       case dwarf::DW_FORM_ref4:
340       case dwarf::DW_FORM_ref_sup4:
341       case dwarf::DW_FORM_strx4:
342       case dwarf::DW_FORM_addrx4:
343         writeInteger((uint32_t)FormVal->Value, OS, IsLittleEndian);
344         break;
345       case dwarf::DW_FORM_data8:
346       case dwarf::DW_FORM_ref8:
347       case dwarf::DW_FORM_ref_sup8:
348       case dwarf::DW_FORM_ref_sig8:
349         writeInteger((uint64_t)FormVal->Value, OS, IsLittleEndian);
350         break;
351       case dwarf::DW_FORM_sdata:
352         encodeSLEB128(FormVal->Value, OS);
353         break;
354       case dwarf::DW_FORM_string:
355         OS.write(FormVal->CStr.data(), FormVal->CStr.size());
356         OS.write('\0');
357         break;
358       case dwarf::DW_FORM_indirect:
359         encodeULEB128(FormVal->Value, OS);
360         Indirect = true;
361         Form = static_cast<dwarf::Form>((uint64_t)FormVal->Value);
362         ++FormVal;
363         break;
364       case dwarf::DW_FORM_strp:
365       case dwarf::DW_FORM_sec_offset:
366       case dwarf::DW_FORM_GNU_ref_alt:
367       case dwarf::DW_FORM_GNU_strp_alt:
368       case dwarf::DW_FORM_line_strp:
369       case dwarf::DW_FORM_strp_sup:
370         cantFail(writeVariableSizedInteger(
371             FormVal->Value, Unit.FormParams.getDwarfOffsetByteSize(), OS,
372             IsLittleEndian));
373         break;
374       default:
375         break;
376       }
377     } while (Indirect);
378   }
379 
380   return OS.tell() - EntryBegin;
381 }
382 
383 Error DWARFYAML::emitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) {
384   for (const DWARFYAML::Unit &Unit : DI.CompileUnits) {
385     uint64_t Length = 3; // sizeof(version) + sizeof(address_size)
386     Length += Unit.FormParams.Version >= 5 ? 1 : 0; // sizeof(unit_type)
387     Length +=
388         Unit.FormParams.getDwarfOffsetByteSize(); // sizeof(debug_abbrev_offset)
389 
390     // Since the length of the current compilation unit is undetermined yet, we
391     // firstly write the content of the compilation unit to a buffer to
392     // calculate it and then serialize the buffer content to the actual output
393     // stream.
394     std::string EntryBuffer;
395     raw_string_ostream EntryBufferOS(EntryBuffer);
396 
397     for (const DWARFYAML::Entry &Entry : Unit.Entries) {
398       if (Expected<uint64_t> EntryLength = writeDIE(
399               DI.AbbrevDecls, Unit, Entry, EntryBufferOS, DI.IsLittleEndian))
400         Length += *EntryLength;
401       else
402         return EntryLength.takeError();
403     }
404 
405     // If the length is specified in the YAML description, we use it instead of
406     // the actual length.
407     if (Unit.Length)
408       Length = *Unit.Length;
409 
410     writeInitialLength(Unit.FormParams.Format, Length, OS, DI.IsLittleEndian);
411     writeInteger((uint16_t)Unit.FormParams.Version, OS, DI.IsLittleEndian);
412     if (Unit.FormParams.Version >= 5) {
413       writeInteger((uint8_t)Unit.Type, OS, DI.IsLittleEndian);
414       writeInteger((uint8_t)Unit.FormParams.AddrSize, OS, DI.IsLittleEndian);
415       writeDWARFOffset(Unit.AbbrOffset, Unit.FormParams.Format, OS,
416                        DI.IsLittleEndian);
417     } else {
418       writeDWARFOffset(Unit.AbbrOffset, Unit.FormParams.Format, OS,
419                        DI.IsLittleEndian);
420       writeInteger((uint8_t)Unit.FormParams.AddrSize, OS, DI.IsLittleEndian);
421     }
422 
423     OS.write(EntryBuffer.data(), EntryBuffer.size());
424   }
425 
426   return Error::success();
427 }
428 
429 static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
430   OS.write(File.Name.data(), File.Name.size());
431   OS.write('\0');
432   encodeULEB128(File.DirIdx, OS);
433   encodeULEB128(File.ModTime, OS);
434   encodeULEB128(File.Length, OS);
435 }
436 
437 Error DWARFYAML::emitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) {
438   for (const auto &LineTable : DI.DebugLines) {
439     writeInitialLength(LineTable.Format, LineTable.Length, OS,
440                        DI.IsLittleEndian);
441     uint64_t SizeOfPrologueLength = LineTable.Format == dwarf::DWARF64 ? 8 : 4;
442     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
443     cantFail(writeVariableSizedInteger(
444         LineTable.PrologueLength, SizeOfPrologueLength, OS, DI.IsLittleEndian));
445     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
446     if (LineTable.Version >= 4)
447       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
448     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
449     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
450     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
451     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
452 
453     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
454       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
455 
456     for (auto IncludeDir : LineTable.IncludeDirs) {
457       OS.write(IncludeDir.data(), IncludeDir.size());
458       OS.write('\0');
459     }
460     OS.write('\0');
461 
462     for (auto File : LineTable.Files)
463       emitFileEntry(OS, File);
464     OS.write('\0');
465 
466     for (auto Op : LineTable.Opcodes) {
467       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
468       if (Op.Opcode == 0) {
469         encodeULEB128(Op.ExtLen, OS);
470         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
471         switch (Op.SubOpcode) {
472         case dwarf::DW_LNE_set_address:
473         case dwarf::DW_LNE_set_discriminator:
474           // TODO: Test this error.
475           if (Error Err = writeVariableSizedInteger(
476                   Op.Data, DI.CompileUnits[0].FormParams.AddrSize, OS,
477                   DI.IsLittleEndian))
478             return Err;
479           break;
480         case dwarf::DW_LNE_define_file:
481           emitFileEntry(OS, Op.FileEntry);
482           break;
483         case dwarf::DW_LNE_end_sequence:
484           break;
485         default:
486           for (auto OpByte : Op.UnknownOpcodeData)
487             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
488         }
489       } else if (Op.Opcode < LineTable.OpcodeBase) {
490         switch (Op.Opcode) {
491         case dwarf::DW_LNS_copy:
492         case dwarf::DW_LNS_negate_stmt:
493         case dwarf::DW_LNS_set_basic_block:
494         case dwarf::DW_LNS_const_add_pc:
495         case dwarf::DW_LNS_set_prologue_end:
496         case dwarf::DW_LNS_set_epilogue_begin:
497           break;
498 
499         case dwarf::DW_LNS_advance_pc:
500         case dwarf::DW_LNS_set_file:
501         case dwarf::DW_LNS_set_column:
502         case dwarf::DW_LNS_set_isa:
503           encodeULEB128(Op.Data, OS);
504           break;
505 
506         case dwarf::DW_LNS_advance_line:
507           encodeSLEB128(Op.SData, OS);
508           break;
509 
510         case dwarf::DW_LNS_fixed_advance_pc:
511           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
512           break;
513 
514         default:
515           for (auto OpData : Op.StandardOpcodeData) {
516             encodeULEB128(OpData, OS);
517           }
518         }
519       }
520     }
521   }
522 
523   return Error::success();
524 }
525 
526 Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) {
527   for (const AddrTableEntry &TableEntry : DI.DebugAddr) {
528     uint8_t AddrSize;
529     if (TableEntry.AddrSize)
530       AddrSize = *TableEntry.AddrSize;
531     else
532       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
533 
534     uint64_t Length;
535     if (TableEntry.Length)
536       Length = (uint64_t)*TableEntry.Length;
537     else
538       // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
539       Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
540                        TableEntry.SegAddrPairs.size();
541 
542     writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian);
543     writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian);
544     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
545     writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
546 
547     for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
548       if (TableEntry.SegSelectorSize != 0)
549         if (Error Err = writeVariableSizedInteger(Pair.Segment,
550                                                   TableEntry.SegSelectorSize,
551                                                   OS, DI.IsLittleEndian))
552           return createStringError(errc::not_supported,
553                                    "unable to write debug_addr segment: %s",
554                                    toString(std::move(Err)).c_str());
555       if (AddrSize != 0)
556         if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
557                                                   DI.IsLittleEndian))
558           return createStringError(errc::not_supported,
559                                    "unable to write debug_addr address: %s",
560                                    toString(std::move(Err)).c_str());
561     }
562   }
563 
564   return Error::success();
565 }
566 
567 Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) {
568   assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
569   for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
570     uint64_t Length;
571     if (Table.Length)
572       Length = *Table.Length;
573     else
574       // sizeof(version) + sizeof(padding) = 4
575       Length =
576           4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
577 
578     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
579     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
580     writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian);
581 
582     for (uint64_t Offset : Table.Offsets)
583       writeDWARFOffset(Offset, Table.Format, OS, DI.IsLittleEndian);
584   }
585 
586   return Error::success();
587 }
588 
589 static Error checkOperandCount(StringRef EncodingString,
590                                ArrayRef<yaml::Hex64> Values,
591                                uint64_t ExpectedOperands) {
592   if (Values.size() != ExpectedOperands)
593     return createStringError(
594         errc::invalid_argument,
595         "invalid number (%zu) of operands for the operator: %s, %" PRIu64
596         " expected",
597         Values.size(), EncodingString.str().c_str(), ExpectedOperands);
598 
599   return Error::success();
600 }
601 
602 static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS,
603                                    uint64_t Addr, uint8_t AddrSize,
604                                    bool IsLittleEndian) {
605   if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
606     return createStringError(errc::invalid_argument,
607                              "unable to write address for the operator %s: %s",
608                              EncodingName.str().c_str(),
609                              toString(std::move(Err)).c_str());
610 
611   return Error::success();
612 }
613 
614 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
615                                          const DWARFYAML::RnglistEntry &Entry,
616                                          uint8_t AddrSize,
617                                          bool IsLittleEndian) {
618   uint64_t BeginOffset = OS.tell();
619   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
620 
621   StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
622 
623   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
624     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
625   };
626 
627   auto WriteAddress = [&](uint64_t Addr) -> Error {
628     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
629                                  IsLittleEndian);
630   };
631 
632   switch (Entry.Operator) {
633   case dwarf::DW_RLE_end_of_list:
634     if (Error Err = CheckOperands(0))
635       return std::move(Err);
636     break;
637   case dwarf::DW_RLE_base_addressx:
638     if (Error Err = CheckOperands(1))
639       return std::move(Err);
640     encodeULEB128(Entry.Values[0], OS);
641     break;
642   case dwarf::DW_RLE_startx_endx:
643   case dwarf::DW_RLE_startx_length:
644   case dwarf::DW_RLE_offset_pair:
645     if (Error Err = CheckOperands(2))
646       return std::move(Err);
647     encodeULEB128(Entry.Values[0], OS);
648     encodeULEB128(Entry.Values[1], OS);
649     break;
650   case dwarf::DW_RLE_base_address:
651     if (Error Err = CheckOperands(1))
652       return std::move(Err);
653     if (Error Err = WriteAddress(Entry.Values[0]))
654       return std::move(Err);
655     break;
656   case dwarf::DW_RLE_start_end:
657     if (Error Err = CheckOperands(2))
658       return std::move(Err);
659     if (Error Err = WriteAddress(Entry.Values[0]))
660       return std::move(Err);
661     cantFail(WriteAddress(Entry.Values[1]));
662     break;
663   case dwarf::DW_RLE_start_length:
664     if (Error Err = CheckOperands(2))
665       return std::move(Err);
666     if (Error Err = WriteAddress(Entry.Values[0]))
667       return std::move(Err);
668     encodeULEB128(Entry.Values[1], OS);
669     break;
670   }
671 
672   return OS.tell() - BeginOffset;
673 }
674 
675 template <typename EntryType>
676 Error writeDWARFLists(raw_ostream &OS,
677                       ArrayRef<DWARFYAML::ListTable<EntryType>> Tables,
678                       bool IsLittleEndian, bool Is64BitAddrSize) {
679   for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
680     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
681     // sizeof(offset_entry_count) = 8
682     uint64_t Length = 8;
683 
684     uint8_t AddrSize;
685     if (Table.AddrSize)
686       AddrSize = *Table.AddrSize;
687     else
688       AddrSize = Is64BitAddrSize ? 8 : 4;
689 
690     // Since the length of the current range/location lists entry is
691     // undetermined yet, we firstly write the content of the range/location
692     // lists to a buffer to calculate the length and then serialize the buffer
693     // content to the actual output stream.
694     std::string ListBuffer;
695     raw_string_ostream ListBufferOS(ListBuffer);
696 
697     // Offsets holds offsets for each range/location list. The i-th element is
698     // the offset from the beginning of the first range/location list to the
699     // location of the i-th range list.
700     std::vector<uint64_t> Offsets;
701 
702     for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
703       Offsets.push_back(ListBufferOS.tell());
704       if (List.Content) {
705         List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
706         Length += List.Content->binary_size();
707       } else if (List.Entries) {
708         for (const EntryType &Entry : *List.Entries) {
709           Expected<uint64_t> EntrySize =
710               writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
711           if (!EntrySize)
712             return EntrySize.takeError();
713           Length += *EntrySize;
714         }
715       }
716     }
717 
718     // If the offset_entry_count field isn't specified, yaml2obj will infer it
719     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
720     // isn't specified either, yaml2obj will infer it from the auto-generated
721     // offsets.
722     uint32_t OffsetEntryCount;
723     if (Table.OffsetEntryCount)
724       OffsetEntryCount = *Table.OffsetEntryCount;
725     else
726       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
727     uint64_t OffsetsSize =
728         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
729     Length += OffsetsSize;
730 
731     // If the length is specified in the YAML description, we use it instead of
732     // the actual length.
733     if (Table.Length)
734       Length = *Table.Length;
735 
736     writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
737     writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
738     writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
739     writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
740     writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
741 
742     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
743       for (uint64_t Offset : Offsets)
744         writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
745                          IsLittleEndian);
746     };
747 
748     if (Table.Offsets)
749       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
750                                      Table.Offsets->size()),
751                   0);
752     else
753       EmitOffsets(Offsets, OffsetsSize);
754 
755     OS.write(ListBuffer.data(), ListBuffer.size());
756   }
757 
758   return Error::success();
759 }
760 
761 Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
762   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
763   return writeDWARFLists<DWARFYAML::RnglistEntry>(
764       OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize);
765 }
766 
767 std::function<Error(raw_ostream &, const DWARFYAML::Data &)>
768 DWARFYAML::getDWARFEmitterByName(StringRef SecName) {
769   auto EmitFunc =
770       StringSwitch<
771           std::function<Error(raw_ostream &, const DWARFYAML::Data &)>>(SecName)
772           .Case("debug_abbrev", DWARFYAML::emitDebugAbbrev)
773           .Case("debug_addr", DWARFYAML::emitDebugAddr)
774           .Case("debug_aranges", DWARFYAML::emitDebugAranges)
775           .Case("debug_gnu_pubnames", DWARFYAML::emitDebugGNUPubnames)
776           .Case("debug_gnu_pubtypes", DWARFYAML::emitDebugGNUPubtypes)
777           .Case("debug_info", DWARFYAML::emitDebugInfo)
778           .Case("debug_line", DWARFYAML::emitDebugLine)
779           .Case("debug_pubnames", DWARFYAML::emitDebugPubnames)
780           .Case("debug_pubtypes", DWARFYAML::emitDebugPubtypes)
781           .Case("debug_ranges", DWARFYAML::emitDebugRanges)
782           .Case("debug_rnglists", DWARFYAML::emitDebugRnglists)
783           .Case("debug_str", DWARFYAML::emitDebugStr)
784           .Case("debug_str_offsets", DWARFYAML::emitDebugStrOffsets)
785           .Default([&](raw_ostream &, const DWARFYAML::Data &) {
786             return createStringError(errc::not_supported,
787                                      SecName + " is not supported");
788           });
789 
790   return EmitFunc;
791 }
792 
793 static Error
794 emitDebugSectionImpl(const DWARFYAML::Data &DI, StringRef Sec,
795                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
796   std::string Data;
797   raw_string_ostream DebugInfoStream(Data);
798 
799   auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Sec);
800 
801   if (Error Err = EmitFunc(DebugInfoStream, DI))
802     return Err;
803   DebugInfoStream.flush();
804   if (!Data.empty())
805     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
806 
807   return Error::success();
808 }
809 
810 Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
811 DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian) {
812   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
813     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
814   };
815 
816   SMDiagnostic GeneratedDiag;
817   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
818                   &GeneratedDiag);
819 
820   DWARFYAML::Data DI;
821   DI.IsLittleEndian = IsLittleEndian;
822   YIn >> DI;
823   if (YIn.error())
824     return createStringError(YIn.error(), GeneratedDiag.getMessage());
825 
826   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
827   Error Err = Error::success();
828   cantFail(std::move(Err));
829 
830   for (StringRef SecName : DI.getNonEmptySectionNames())
831     Err = joinErrors(std::move(Err),
832                      emitDebugSectionImpl(DI, SecName, DebugSections));
833 
834   if (Err)
835     return std::move(Err);
836   return std::move(DebugSections);
837 }
838