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>
615 writeDWARFExpression(raw_ostream &OS,
616                      const DWARFYAML::DWARFOperation &Operation,
617                      uint8_t AddrSize, bool IsLittleEndian) {
618   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
619     return checkOperandCount(dwarf::OperationEncodingString(Operation.Operator),
620                              Operation.Values, ExpectedOperands);
621   };
622 
623   uint64_t ExpressionBegin = OS.tell();
624   writeInteger((uint8_t)Operation.Operator, OS, IsLittleEndian);
625   switch (Operation.Operator) {
626   case dwarf::DW_OP_consts:
627     if (Error Err = CheckOperands(1))
628       return std::move(Err);
629     encodeSLEB128(Operation.Values[0], OS);
630     break;
631   case dwarf::DW_OP_stack_value:
632     if (Error Err = CheckOperands(0))
633       return std::move(Err);
634     break;
635   default:
636     StringRef EncodingStr = dwarf::OperationEncodingString(Operation.Operator);
637     return createStringError(errc::not_supported,
638                              "DWARF expression: " +
639                                  (EncodingStr.empty()
640                                       ? "0x" + utohexstr(Operation.Operator)
641                                       : EncodingStr) +
642                                  " is not supported");
643   }
644   return OS.tell() - ExpressionBegin;
645 }
646 
647 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
648                                          const DWARFYAML::RnglistEntry &Entry,
649                                          uint8_t AddrSize,
650                                          bool IsLittleEndian) {
651   uint64_t BeginOffset = OS.tell();
652   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
653 
654   StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
655 
656   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
657     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
658   };
659 
660   auto WriteAddress = [&](uint64_t Addr) -> Error {
661     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
662                                  IsLittleEndian);
663   };
664 
665   switch (Entry.Operator) {
666   case dwarf::DW_RLE_end_of_list:
667     if (Error Err = CheckOperands(0))
668       return std::move(Err);
669     break;
670   case dwarf::DW_RLE_base_addressx:
671     if (Error Err = CheckOperands(1))
672       return std::move(Err);
673     encodeULEB128(Entry.Values[0], OS);
674     break;
675   case dwarf::DW_RLE_startx_endx:
676   case dwarf::DW_RLE_startx_length:
677   case dwarf::DW_RLE_offset_pair:
678     if (Error Err = CheckOperands(2))
679       return std::move(Err);
680     encodeULEB128(Entry.Values[0], OS);
681     encodeULEB128(Entry.Values[1], OS);
682     break;
683   case dwarf::DW_RLE_base_address:
684     if (Error Err = CheckOperands(1))
685       return std::move(Err);
686     if (Error Err = WriteAddress(Entry.Values[0]))
687       return std::move(Err);
688     break;
689   case dwarf::DW_RLE_start_end:
690     if (Error Err = CheckOperands(2))
691       return std::move(Err);
692     if (Error Err = WriteAddress(Entry.Values[0]))
693       return std::move(Err);
694     cantFail(WriteAddress(Entry.Values[1]));
695     break;
696   case dwarf::DW_RLE_start_length:
697     if (Error Err = CheckOperands(2))
698       return std::move(Err);
699     if (Error Err = WriteAddress(Entry.Values[0]))
700       return std::move(Err);
701     encodeULEB128(Entry.Values[1], OS);
702     break;
703   }
704 
705   return OS.tell() - BeginOffset;
706 }
707 
708 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
709                                          const DWARFYAML::LoclistEntry &Entry,
710                                          uint8_t AddrSize,
711                                          bool IsLittleEndian) {
712   uint64_t BeginOffset = OS.tell();
713   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
714 
715   StringRef EncodingName = dwarf::LocListEncodingString(Entry.Operator);
716 
717   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
718     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
719   };
720 
721   auto WriteAddress = [&](uint64_t Addr) -> Error {
722     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
723                                  IsLittleEndian);
724   };
725 
726   auto WriteDWARFOperations = [&]() -> Error {
727     std::string OpBuffer;
728     raw_string_ostream OpBufferOS(OpBuffer);
729     uint64_t DescriptionsLength = 0;
730 
731     for (const DWARFYAML::DWARFOperation &Op : Entry.Descriptions) {
732       if (Expected<uint64_t> OpSize =
733               writeDWARFExpression(OpBufferOS, Op, AddrSize, IsLittleEndian))
734         DescriptionsLength += *OpSize;
735       else
736         return OpSize.takeError();
737     }
738 
739     if (Entry.DescriptionsLength)
740       DescriptionsLength = *Entry.DescriptionsLength;
741     else
742       DescriptionsLength = OpBuffer.size();
743 
744     encodeULEB128(DescriptionsLength, OS);
745     OS.write(OpBuffer.data(), OpBuffer.size());
746 
747     return Error::success();
748   };
749 
750   switch (Entry.Operator) {
751   case dwarf::DW_LLE_end_of_list:
752     if (Error Err = CheckOperands(0))
753       return std::move(Err);
754     break;
755   case dwarf::DW_LLE_base_addressx:
756     if (Error Err = CheckOperands(1))
757       return std::move(Err);
758     encodeULEB128(Entry.Values[0], OS);
759     break;
760   case dwarf::DW_LLE_startx_endx:
761   case dwarf::DW_LLE_startx_length:
762   case dwarf::DW_LLE_offset_pair:
763     if (Error Err = CheckOperands(2))
764       return std::move(Err);
765     encodeULEB128(Entry.Values[0], OS);
766     encodeULEB128(Entry.Values[1], OS);
767     if (Error Err = WriteDWARFOperations())
768       return std::move(Err);
769     break;
770   case dwarf::DW_LLE_default_location:
771     if (Error Err = CheckOperands(0))
772       return std::move(Err);
773     if (Error Err = WriteDWARFOperations())
774       return std::move(Err);
775     break;
776   case dwarf::DW_LLE_base_address:
777     if (Error Err = CheckOperands(1))
778       return std::move(Err);
779     if (Error Err = WriteAddress(Entry.Values[0]))
780       return std::move(Err);
781     break;
782   case dwarf::DW_LLE_start_end:
783     if (Error Err = CheckOperands(2))
784       return std::move(Err);
785     if (Error Err = WriteAddress(Entry.Values[0]))
786       return std::move(Err);
787     cantFail(WriteAddress(Entry.Values[1]));
788     if (Error Err = WriteDWARFOperations())
789       return std::move(Err);
790     break;
791   case dwarf::DW_LLE_start_length:
792     if (Error Err = CheckOperands(2))
793       return std::move(Err);
794     if (Error Err = WriteAddress(Entry.Values[0]))
795       return std::move(Err);
796     encodeULEB128(Entry.Values[1], OS);
797     if (Error Err = WriteDWARFOperations())
798       return std::move(Err);
799     break;
800   }
801 
802   return OS.tell() - BeginOffset;
803 }
804 
805 template <typename EntryType>
806 Error writeDWARFLists(raw_ostream &OS,
807                       ArrayRef<DWARFYAML::ListTable<EntryType>> Tables,
808                       bool IsLittleEndian, bool Is64BitAddrSize) {
809   for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
810     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
811     // sizeof(offset_entry_count) = 8
812     uint64_t Length = 8;
813 
814     uint8_t AddrSize;
815     if (Table.AddrSize)
816       AddrSize = *Table.AddrSize;
817     else
818       AddrSize = Is64BitAddrSize ? 8 : 4;
819 
820     // Since the length of the current range/location lists entry is
821     // undetermined yet, we firstly write the content of the range/location
822     // lists to a buffer to calculate the length and then serialize the buffer
823     // content to the actual output stream.
824     std::string ListBuffer;
825     raw_string_ostream ListBufferOS(ListBuffer);
826 
827     // Offsets holds offsets for each range/location list. The i-th element is
828     // the offset from the beginning of the first range/location list to the
829     // location of the i-th range list.
830     std::vector<uint64_t> Offsets;
831 
832     for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
833       Offsets.push_back(ListBufferOS.tell());
834       if (List.Content) {
835         List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
836         Length += List.Content->binary_size();
837       } else if (List.Entries) {
838         for (const EntryType &Entry : *List.Entries) {
839           Expected<uint64_t> EntrySize =
840               writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
841           if (!EntrySize)
842             return EntrySize.takeError();
843           Length += *EntrySize;
844         }
845       }
846     }
847 
848     // If the offset_entry_count field isn't specified, yaml2obj will infer it
849     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
850     // isn't specified either, yaml2obj will infer it from the auto-generated
851     // offsets.
852     uint32_t OffsetEntryCount;
853     if (Table.OffsetEntryCount)
854       OffsetEntryCount = *Table.OffsetEntryCount;
855     else
856       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
857     uint64_t OffsetsSize =
858         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
859     Length += OffsetsSize;
860 
861     // If the length is specified in the YAML description, we use it instead of
862     // the actual length.
863     if (Table.Length)
864       Length = *Table.Length;
865 
866     writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
867     writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
868     writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
869     writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
870     writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
871 
872     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
873       for (uint64_t Offset : Offsets)
874         writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
875                          IsLittleEndian);
876     };
877 
878     if (Table.Offsets)
879       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
880                                      Table.Offsets->size()),
881                   0);
882     else if (OffsetEntryCount != 0)
883       EmitOffsets(Offsets, OffsetsSize);
884 
885     OS.write(ListBuffer.data(), ListBuffer.size());
886   }
887 
888   return Error::success();
889 }
890 
891 Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
892   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
893   return writeDWARFLists<DWARFYAML::RnglistEntry>(
894       OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize);
895 }
896 
897 Error DWARFYAML::emitDebugLoclists(raw_ostream &OS, const Data &DI) {
898   assert(DI.DebugLoclists && "unexpected emitDebugRnglists() call");
899   return writeDWARFLists<DWARFYAML::LoclistEntry>(
900       OS, *DI.DebugLoclists, DI.IsLittleEndian, DI.Is64BitAddrSize);
901 }
902 
903 std::function<Error(raw_ostream &, const DWARFYAML::Data &)>
904 DWARFYAML::getDWARFEmitterByName(StringRef SecName) {
905   auto EmitFunc =
906       StringSwitch<
907           std::function<Error(raw_ostream &, const DWARFYAML::Data &)>>(SecName)
908           .Case("debug_abbrev", DWARFYAML::emitDebugAbbrev)
909           .Case("debug_addr", DWARFYAML::emitDebugAddr)
910           .Case("debug_aranges", DWARFYAML::emitDebugAranges)
911           .Case("debug_gnu_pubnames", DWARFYAML::emitDebugGNUPubnames)
912           .Case("debug_gnu_pubtypes", DWARFYAML::emitDebugGNUPubtypes)
913           .Case("debug_info", DWARFYAML::emitDebugInfo)
914           .Case("debug_line", DWARFYAML::emitDebugLine)
915           .Case("debug_loclists", DWARFYAML::emitDebugLoclists)
916           .Case("debug_pubnames", DWARFYAML::emitDebugPubnames)
917           .Case("debug_pubtypes", DWARFYAML::emitDebugPubtypes)
918           .Case("debug_ranges", DWARFYAML::emitDebugRanges)
919           .Case("debug_rnglists", DWARFYAML::emitDebugRnglists)
920           .Case("debug_str", DWARFYAML::emitDebugStr)
921           .Case("debug_str_offsets", DWARFYAML::emitDebugStrOffsets)
922           .Default([&](raw_ostream &, const DWARFYAML::Data &) {
923             return createStringError(errc::not_supported,
924                                      SecName + " is not supported");
925           });
926 
927   return EmitFunc;
928 }
929 
930 static Error
931 emitDebugSectionImpl(const DWARFYAML::Data &DI, StringRef Sec,
932                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
933   std::string Data;
934   raw_string_ostream DebugInfoStream(Data);
935 
936   auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Sec);
937 
938   if (Error Err = EmitFunc(DebugInfoStream, DI))
939     return Err;
940   DebugInfoStream.flush();
941   if (!Data.empty())
942     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
943 
944   return Error::success();
945 }
946 
947 Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
948 DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian) {
949   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
950     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
951   };
952 
953   SMDiagnostic GeneratedDiag;
954   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
955                   &GeneratedDiag);
956 
957   DWARFYAML::Data DI;
958   DI.IsLittleEndian = IsLittleEndian;
959   YIn >> DI;
960   if (YIn.error())
961     return createStringError(YIn.error(), GeneratedDiag.getMessage());
962 
963   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
964   Error Err = Error::success();
965   cantFail(std::move(Err));
966 
967   for (StringRef SecName : DI.getNonEmptySectionNames())
968     Err = joinErrors(std::move(Err),
969                      emitDebugSectionImpl(DI, SecName, DebugSections));
970 
971   if (Err)
972     return std::move(Err);
973   return std::move(DebugSections);
974 }
975