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 dwarf::DwarfFormat Format,
72                                const uint64_t Length, raw_ostream &OS,
73                                bool IsLittleEndian) {
74   bool IsDWARF64 = Format == dwarf::DWARF64;
75   if (IsDWARF64)
76     cantFail(writeVariableSizedInteger(dwarf::DW_LENGTH_DWARF64, 4, OS,
77                                        IsLittleEndian));
78   cantFail(
79       writeVariableSizedInteger(Length, IsDWARF64 ? 8 : 4, OS, IsLittleEndian));
80 }
81 
82 static void writeDWARFOffset(uint64_t Offset, dwarf::DwarfFormat Format,
83                              raw_ostream &OS, bool IsLittleEndian) {
84   cantFail(writeVariableSizedInteger(Offset, Format == dwarf::DWARF64 ? 8 : 4,
85                                      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   assert(DI.DebugAranges && "unexpected emitDebugAranges() call");
123   for (auto Range : *DI.DebugAranges) {
124     uint8_t AddrSize;
125     if (Range.AddrSize)
126       AddrSize = *Range.AddrSize;
127     else
128       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
129 
130     uint64_t Length = 4; // sizeof(version) 2 + sizeof(address_size) 1 +
131                          // sizeof(segment_selector_size) 1
132     Length +=
133         Range.Format == dwarf::DWARF64 ? 8 : 4; // sizeof(debug_info_offset)
134 
135     const uint64_t HeaderLength =
136         Length + (Range.Format == dwarf::DWARF64
137                       ? 12
138                       : 4); // sizeof(unit_header) = 12 (DWARF64) or 4 (DWARF32)
139     const uint64_t PaddedHeaderLength = alignTo(HeaderLength, AddrSize * 2);
140 
141     if (Range.Length) {
142       Length = *Range.Length;
143     } else {
144       Length += PaddedHeaderLength - HeaderLength;
145       Length += AddrSize * 2 * (Range.Descriptors.size() + 1);
146     }
147 
148     writeInitialLength(Range.Format, Length, OS, DI.IsLittleEndian);
149     writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian);
150     writeDWARFOffset(Range.CuOffset, Range.Format, OS, DI.IsLittleEndian);
151     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
152     writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
153     ZeroFillBytes(OS, PaddedHeaderLength - HeaderLength);
154 
155     for (auto Descriptor : Range.Descriptors) {
156       if (Error Err = writeVariableSizedInteger(Descriptor.Address, AddrSize,
157                                                 OS, DI.IsLittleEndian))
158         return createStringError(errc::not_supported,
159                                  "unable to write debug_aranges address: %s",
160                                  toString(std::move(Err)).c_str());
161       cantFail(writeVariableSizedInteger(Descriptor.Length, AddrSize, OS,
162                                          DI.IsLittleEndian));
163     }
164     ZeroFillBytes(OS, AddrSize * 2);
165   }
166 
167   return Error::success();
168 }
169 
170 Error DWARFYAML::emitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) {
171   const size_t RangesOffset = OS.tell();
172   uint64_t EntryIndex = 0;
173   for (auto DebugRanges : DI.DebugRanges) {
174     const size_t CurrOffset = OS.tell() - RangesOffset;
175     if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset)
176       return createStringError(errc::invalid_argument,
177                                "'Offset' for 'debug_ranges' with index " +
178                                    Twine(EntryIndex) +
179                                    " must be greater than or equal to the "
180                                    "number of bytes written already (0x" +
181                                    Twine::utohexstr(CurrOffset) + ")");
182     if (DebugRanges.Offset)
183       ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset);
184 
185     uint8_t AddrSize;
186     if (DebugRanges.AddrSize)
187       AddrSize = *DebugRanges.AddrSize;
188     else
189       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
190     for (auto Entry : DebugRanges.Entries) {
191       if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS,
192                                                 DI.IsLittleEndian))
193         return createStringError(
194             errc::not_supported,
195             "unable to write debug_ranges address offset: %s",
196             toString(std::move(Err)).c_str());
197       cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS,
198                                          DI.IsLittleEndian));
199     }
200     ZeroFillBytes(OS, AddrSize * 2);
201     ++EntryIndex;
202   }
203 
204   return Error::success();
205 }
206 
207 static Error emitPubSection(raw_ostream &OS, const DWARFYAML::PubSection &Sect,
208                             bool IsLittleEndian, bool IsGNUPubSec = false) {
209   writeInitialLength(Sect.Format, Sect.Length, OS, IsLittleEndian);
210   writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
211   writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
212   writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
213   for (auto Entry : Sect.Entries) {
214     writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
215     if (IsGNUPubSec)
216       writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian);
217     OS.write(Entry.Name.data(), Entry.Name.size());
218     OS.write('\0');
219   }
220 
221   return Error::success();
222 }
223 
224 Error DWARFYAML::emitDebugPubnames(raw_ostream &OS, const Data &DI) {
225   assert(DI.PubNames && "unexpected emitDebugPubnames() call");
226   return emitPubSection(OS, *DI.PubNames, DI.IsLittleEndian);
227 }
228 
229 Error DWARFYAML::emitDebugPubtypes(raw_ostream &OS, const Data &DI) {
230   assert(DI.PubTypes && "unexpected emitDebugPubtypes() call");
231   return emitPubSection(OS, *DI.PubTypes, DI.IsLittleEndian);
232 }
233 
234 Error DWARFYAML::emitDebugGNUPubnames(raw_ostream &OS, const Data &DI) {
235   assert(DI.GNUPubNames && "unexpected emitDebugGNUPubnames() call");
236   return emitPubSection(OS, *DI.GNUPubNames, DI.IsLittleEndian,
237                         /*IsGNUStyle=*/true);
238 }
239 
240 Error DWARFYAML::emitDebugGNUPubtypes(raw_ostream &OS, const Data &DI) {
241   assert(DI.GNUPubTypes && "unexpected emitDebugGNUPubtypes() call");
242   return emitPubSection(OS, *DI.GNUPubTypes, DI.IsLittleEndian,
243                         /*IsGNUStyle=*/true);
244 }
245 
246 static Expected<uint64_t> writeDIE(ArrayRef<DWARFYAML::Abbrev> AbbrevDecls,
247                                    const dwarf::FormParams &Params,
248                                    const DWARFYAML::Entry &Entry,
249                                    raw_ostream &OS, bool IsLittleEndian) {
250   uint64_t EntryBegin = OS.tell();
251   encodeULEB128(Entry.AbbrCode, OS);
252   uint32_t AbbrCode = Entry.AbbrCode;
253   if (AbbrCode == 0 || Entry.Values.empty())
254     return OS.tell() - EntryBegin;
255 
256   if (AbbrCode > AbbrevDecls.size())
257     return createStringError(
258         errc::invalid_argument,
259         "abbrev code must be less than or equal to the number of "
260         "entries in abbreviation table");
261   const DWARFYAML::Abbrev &Abbrev = AbbrevDecls[AbbrCode - 1];
262   auto FormVal = Entry.Values.begin();
263   auto AbbrForm = Abbrev.Attributes.begin();
264   for (; FormVal != Entry.Values.end() && AbbrForm != Abbrev.Attributes.end();
265        ++FormVal, ++AbbrForm) {
266     dwarf::Form Form = AbbrForm->Form;
267     bool Indirect;
268     do {
269       Indirect = false;
270       switch (Form) {
271       case dwarf::DW_FORM_addr:
272         // TODO: Test this error.
273         if (Error Err = writeVariableSizedInteger(
274                 FormVal->Value, Params.AddrSize, OS, IsLittleEndian))
275           return std::move(Err);
276         break;
277       case dwarf::DW_FORM_ref_addr:
278         // TODO: Test this error.
279         if (Error Err = writeVariableSizedInteger(FormVal->Value,
280                                                   Params.getRefAddrByteSize(),
281                                                   OS, IsLittleEndian))
282           return std::move(Err);
283         break;
284       case dwarf::DW_FORM_exprloc:
285       case dwarf::DW_FORM_block:
286         encodeULEB128(FormVal->BlockData.size(), OS);
287         OS.write((const char *)FormVal->BlockData.data(),
288                  FormVal->BlockData.size());
289         break;
290       case dwarf::DW_FORM_block1: {
291         writeInteger((uint8_t)FormVal->BlockData.size(), OS, IsLittleEndian);
292         OS.write((const char *)FormVal->BlockData.data(),
293                  FormVal->BlockData.size());
294         break;
295       }
296       case dwarf::DW_FORM_block2: {
297         writeInteger((uint16_t)FormVal->BlockData.size(), OS, IsLittleEndian);
298         OS.write((const char *)FormVal->BlockData.data(),
299                  FormVal->BlockData.size());
300         break;
301       }
302       case dwarf::DW_FORM_block4: {
303         writeInteger((uint32_t)FormVal->BlockData.size(), OS, IsLittleEndian);
304         OS.write((const char *)FormVal->BlockData.data(),
305                  FormVal->BlockData.size());
306         break;
307       }
308       case dwarf::DW_FORM_strx:
309       case dwarf::DW_FORM_addrx:
310       case dwarf::DW_FORM_rnglistx:
311       case dwarf::DW_FORM_loclistx:
312       case dwarf::DW_FORM_udata:
313       case dwarf::DW_FORM_ref_udata:
314       case dwarf::DW_FORM_GNU_addr_index:
315       case dwarf::DW_FORM_GNU_str_index:
316         encodeULEB128(FormVal->Value, OS);
317         break;
318       case dwarf::DW_FORM_data1:
319       case dwarf::DW_FORM_ref1:
320       case dwarf::DW_FORM_flag:
321       case dwarf::DW_FORM_strx1:
322       case dwarf::DW_FORM_addrx1:
323         writeInteger((uint8_t)FormVal->Value, OS, IsLittleEndian);
324         break;
325       case dwarf::DW_FORM_data2:
326       case dwarf::DW_FORM_ref2:
327       case dwarf::DW_FORM_strx2:
328       case dwarf::DW_FORM_addrx2:
329         writeInteger((uint16_t)FormVal->Value, OS, IsLittleEndian);
330         break;
331       case dwarf::DW_FORM_data4:
332       case dwarf::DW_FORM_ref4:
333       case dwarf::DW_FORM_ref_sup4:
334       case dwarf::DW_FORM_strx4:
335       case dwarf::DW_FORM_addrx4:
336         writeInteger((uint32_t)FormVal->Value, OS, IsLittleEndian);
337         break;
338       case dwarf::DW_FORM_data8:
339       case dwarf::DW_FORM_ref8:
340       case dwarf::DW_FORM_ref_sup8:
341       case dwarf::DW_FORM_ref_sig8:
342         writeInteger((uint64_t)FormVal->Value, OS, IsLittleEndian);
343         break;
344       case dwarf::DW_FORM_sdata:
345         encodeSLEB128(FormVal->Value, OS);
346         break;
347       case dwarf::DW_FORM_string:
348         OS.write(FormVal->CStr.data(), FormVal->CStr.size());
349         OS.write('\0');
350         break;
351       case dwarf::DW_FORM_indirect:
352         encodeULEB128(FormVal->Value, OS);
353         Indirect = true;
354         Form = static_cast<dwarf::Form>((uint64_t)FormVal->Value);
355         ++FormVal;
356         break;
357       case dwarf::DW_FORM_strp:
358       case dwarf::DW_FORM_sec_offset:
359       case dwarf::DW_FORM_GNU_ref_alt:
360       case dwarf::DW_FORM_GNU_strp_alt:
361       case dwarf::DW_FORM_line_strp:
362       case dwarf::DW_FORM_strp_sup:
363         cantFail(writeVariableSizedInteger(FormVal->Value,
364                                            Params.getDwarfOffsetByteSize(), OS,
365                                            IsLittleEndian));
366         break;
367       default:
368         break;
369       }
370     } while (Indirect);
371   }
372 
373   return OS.tell() - EntryBegin;
374 }
375 
376 Error DWARFYAML::emitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) {
377   for (const DWARFYAML::Unit &Unit : DI.CompileUnits) {
378     uint8_t AddrSize;
379     if (Unit.AddrSize)
380       AddrSize = *Unit.AddrSize;
381     else
382       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
383     dwarf::FormParams Params = {Unit.Version, AddrSize, Unit.Format};
384     uint64_t Length = 3; // sizeof(version) + sizeof(address_size)
385     Length += Unit.Version >= 5 ? 1 : 0;       // sizeof(unit_type)
386     Length += Params.getDwarfOffsetByteSize(); // sizeof(debug_abbrev_offset)
387 
388     // Since the length of the current compilation unit is undetermined yet, we
389     // firstly write the content of the compilation unit to a buffer to
390     // calculate it and then serialize the buffer content to the actual output
391     // stream.
392     std::string EntryBuffer;
393     raw_string_ostream EntryBufferOS(EntryBuffer);
394 
395     for (const DWARFYAML::Entry &Entry : Unit.Entries) {
396       if (Expected<uint64_t> EntryLength = writeDIE(
397               DI.AbbrevDecls, Params, Entry, EntryBufferOS, DI.IsLittleEndian))
398         Length += *EntryLength;
399       else
400         return EntryLength.takeError();
401     }
402 
403     // If the length is specified in the YAML description, we use it instead of
404     // the actual length.
405     if (Unit.Length)
406       Length = *Unit.Length;
407 
408     writeInitialLength(Unit.Format, Length, OS, DI.IsLittleEndian);
409     writeInteger((uint16_t)Unit.Version, OS, DI.IsLittleEndian);
410     if (Unit.Version >= 5) {
411       writeInteger((uint8_t)Unit.Type, OS, DI.IsLittleEndian);
412       writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
413       writeDWARFOffset(Unit.AbbrOffset, Unit.Format, OS, DI.IsLittleEndian);
414     } else {
415       writeDWARFOffset(Unit.AbbrOffset, Unit.Format, OS, DI.IsLittleEndian);
416       writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
417     }
418 
419     OS.write(EntryBuffer.data(), EntryBuffer.size());
420   }
421 
422   return Error::success();
423 }
424 
425 static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
426   OS.write(File.Name.data(), File.Name.size());
427   OS.write('\0');
428   encodeULEB128(File.DirIdx, OS);
429   encodeULEB128(File.ModTime, OS);
430   encodeULEB128(File.Length, OS);
431 }
432 
433 Error DWARFYAML::emitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) {
434   for (const auto &LineTable : DI.DebugLines) {
435     writeInitialLength(LineTable.Format, LineTable.Length, OS,
436                        DI.IsLittleEndian);
437     uint64_t SizeOfPrologueLength = LineTable.Format == dwarf::DWARF64 ? 8 : 4;
438     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
439     cantFail(writeVariableSizedInteger(
440         LineTable.PrologueLength, SizeOfPrologueLength, OS, DI.IsLittleEndian));
441     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
442     if (LineTable.Version >= 4)
443       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
444     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
445     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
446     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
447     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
448 
449     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
450       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
451 
452     for (auto IncludeDir : LineTable.IncludeDirs) {
453       OS.write(IncludeDir.data(), IncludeDir.size());
454       OS.write('\0');
455     }
456     OS.write('\0');
457 
458     for (auto File : LineTable.Files)
459       emitFileEntry(OS, File);
460     OS.write('\0');
461 
462     uint8_t AddrSize = DI.Is64BitAddrSize ? 8 : 4;
463 
464     for (auto Op : LineTable.Opcodes) {
465       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
466       if (Op.Opcode == 0) {
467         encodeULEB128(Op.ExtLen, OS);
468         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
469         switch (Op.SubOpcode) {
470         case dwarf::DW_LNE_set_address:
471           cantFail(writeVariableSizedInteger(Op.Data, AddrSize, OS,
472                                              DI.IsLittleEndian));
473           break;
474         case dwarf::DW_LNE_define_file:
475           emitFileEntry(OS, Op.FileEntry);
476           break;
477         case dwarf::DW_LNE_set_discriminator:
478           encodeULEB128(Op.Data, OS);
479           break;
480         case dwarf::DW_LNE_end_sequence:
481           break;
482         default:
483           for (auto OpByte : Op.UnknownOpcodeData)
484             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
485         }
486       } else if (Op.Opcode < LineTable.OpcodeBase) {
487         switch (Op.Opcode) {
488         case dwarf::DW_LNS_copy:
489         case dwarf::DW_LNS_negate_stmt:
490         case dwarf::DW_LNS_set_basic_block:
491         case dwarf::DW_LNS_const_add_pc:
492         case dwarf::DW_LNS_set_prologue_end:
493         case dwarf::DW_LNS_set_epilogue_begin:
494           break;
495 
496         case dwarf::DW_LNS_advance_pc:
497         case dwarf::DW_LNS_set_file:
498         case dwarf::DW_LNS_set_column:
499         case dwarf::DW_LNS_set_isa:
500           encodeULEB128(Op.Data, OS);
501           break;
502 
503         case dwarf::DW_LNS_advance_line:
504           encodeSLEB128(Op.SData, OS);
505           break;
506 
507         case dwarf::DW_LNS_fixed_advance_pc:
508           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
509           break;
510 
511         default:
512           for (auto OpData : Op.StandardOpcodeData) {
513             encodeULEB128(OpData, OS);
514           }
515         }
516       }
517     }
518   }
519 
520   return Error::success();
521 }
522 
523 Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) {
524   for (const AddrTableEntry &TableEntry : DI.DebugAddr) {
525     uint8_t AddrSize;
526     if (TableEntry.AddrSize)
527       AddrSize = *TableEntry.AddrSize;
528     else
529       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
530 
531     uint64_t Length;
532     if (TableEntry.Length)
533       Length = (uint64_t)*TableEntry.Length;
534     else
535       // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
536       Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
537                        TableEntry.SegAddrPairs.size();
538 
539     writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian);
540     writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian);
541     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
542     writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
543 
544     for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
545       if (TableEntry.SegSelectorSize != 0)
546         if (Error Err = writeVariableSizedInteger(Pair.Segment,
547                                                   TableEntry.SegSelectorSize,
548                                                   OS, DI.IsLittleEndian))
549           return createStringError(errc::not_supported,
550                                    "unable to write debug_addr segment: %s",
551                                    toString(std::move(Err)).c_str());
552       if (AddrSize != 0)
553         if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
554                                                   DI.IsLittleEndian))
555           return createStringError(errc::not_supported,
556                                    "unable to write debug_addr address: %s",
557                                    toString(std::move(Err)).c_str());
558     }
559   }
560 
561   return Error::success();
562 }
563 
564 Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) {
565   assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
566   for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
567     uint64_t Length;
568     if (Table.Length)
569       Length = *Table.Length;
570     else
571       // sizeof(version) + sizeof(padding) = 4
572       Length =
573           4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
574 
575     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
576     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
577     writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian);
578 
579     for (uint64_t Offset : Table.Offsets)
580       writeDWARFOffset(Offset, Table.Format, OS, DI.IsLittleEndian);
581   }
582 
583   return Error::success();
584 }
585 
586 static Error checkOperandCount(StringRef EncodingString,
587                                ArrayRef<yaml::Hex64> Values,
588                                uint64_t ExpectedOperands) {
589   if (Values.size() != ExpectedOperands)
590     return createStringError(
591         errc::invalid_argument,
592         "invalid number (%zu) of operands for the operator: %s, %" PRIu64
593         " expected",
594         Values.size(), EncodingString.str().c_str(), ExpectedOperands);
595 
596   return Error::success();
597 }
598 
599 static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS,
600                                    uint64_t Addr, uint8_t AddrSize,
601                                    bool IsLittleEndian) {
602   if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
603     return createStringError(errc::invalid_argument,
604                              "unable to write address for the operator %s: %s",
605                              EncodingName.str().c_str(),
606                              toString(std::move(Err)).c_str());
607 
608   return Error::success();
609 }
610 
611 static Expected<uint64_t>
612 writeDWARFExpression(raw_ostream &OS,
613                      const DWARFYAML::DWARFOperation &Operation,
614                      uint8_t AddrSize, bool IsLittleEndian) {
615   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
616     return checkOperandCount(dwarf::OperationEncodingString(Operation.Operator),
617                              Operation.Values, ExpectedOperands);
618   };
619 
620   uint64_t ExpressionBegin = OS.tell();
621   writeInteger((uint8_t)Operation.Operator, OS, IsLittleEndian);
622   switch (Operation.Operator) {
623   case dwarf::DW_OP_consts:
624     if (Error Err = CheckOperands(1))
625       return std::move(Err);
626     encodeSLEB128(Operation.Values[0], OS);
627     break;
628   case dwarf::DW_OP_stack_value:
629     if (Error Err = CheckOperands(0))
630       return std::move(Err);
631     break;
632   default:
633     StringRef EncodingStr = dwarf::OperationEncodingString(Operation.Operator);
634     return createStringError(errc::not_supported,
635                              "DWARF expression: " +
636                                  (EncodingStr.empty()
637                                       ? "0x" + utohexstr(Operation.Operator)
638                                       : EncodingStr) +
639                                  " is not supported");
640   }
641   return OS.tell() - ExpressionBegin;
642 }
643 
644 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
645                                          const DWARFYAML::RnglistEntry &Entry,
646                                          uint8_t AddrSize,
647                                          bool IsLittleEndian) {
648   uint64_t BeginOffset = OS.tell();
649   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
650 
651   StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
652 
653   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
654     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
655   };
656 
657   auto WriteAddress = [&](uint64_t Addr) -> Error {
658     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
659                                  IsLittleEndian);
660   };
661 
662   switch (Entry.Operator) {
663   case dwarf::DW_RLE_end_of_list:
664     if (Error Err = CheckOperands(0))
665       return std::move(Err);
666     break;
667   case dwarf::DW_RLE_base_addressx:
668     if (Error Err = CheckOperands(1))
669       return std::move(Err);
670     encodeULEB128(Entry.Values[0], OS);
671     break;
672   case dwarf::DW_RLE_startx_endx:
673   case dwarf::DW_RLE_startx_length:
674   case dwarf::DW_RLE_offset_pair:
675     if (Error Err = CheckOperands(2))
676       return std::move(Err);
677     encodeULEB128(Entry.Values[0], OS);
678     encodeULEB128(Entry.Values[1], OS);
679     break;
680   case dwarf::DW_RLE_base_address:
681     if (Error Err = CheckOperands(1))
682       return std::move(Err);
683     if (Error Err = WriteAddress(Entry.Values[0]))
684       return std::move(Err);
685     break;
686   case dwarf::DW_RLE_start_end:
687     if (Error Err = CheckOperands(2))
688       return std::move(Err);
689     if (Error Err = WriteAddress(Entry.Values[0]))
690       return std::move(Err);
691     cantFail(WriteAddress(Entry.Values[1]));
692     break;
693   case dwarf::DW_RLE_start_length:
694     if (Error Err = CheckOperands(2))
695       return std::move(Err);
696     if (Error Err = WriteAddress(Entry.Values[0]))
697       return std::move(Err);
698     encodeULEB128(Entry.Values[1], OS);
699     break;
700   }
701 
702   return OS.tell() - BeginOffset;
703 }
704 
705 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
706                                          const DWARFYAML::LoclistEntry &Entry,
707                                          uint8_t AddrSize,
708                                          bool IsLittleEndian) {
709   uint64_t BeginOffset = OS.tell();
710   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
711 
712   StringRef EncodingName = dwarf::LocListEncodingString(Entry.Operator);
713 
714   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
715     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
716   };
717 
718   auto WriteAddress = [&](uint64_t Addr) -> Error {
719     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
720                                  IsLittleEndian);
721   };
722 
723   auto WriteDWARFOperations = [&]() -> Error {
724     std::string OpBuffer;
725     raw_string_ostream OpBufferOS(OpBuffer);
726     uint64_t DescriptionsLength = 0;
727 
728     for (const DWARFYAML::DWARFOperation &Op : Entry.Descriptions) {
729       if (Expected<uint64_t> OpSize =
730               writeDWARFExpression(OpBufferOS, Op, AddrSize, IsLittleEndian))
731         DescriptionsLength += *OpSize;
732       else
733         return OpSize.takeError();
734     }
735 
736     if (Entry.DescriptionsLength)
737       DescriptionsLength = *Entry.DescriptionsLength;
738     else
739       DescriptionsLength = OpBuffer.size();
740 
741     encodeULEB128(DescriptionsLength, OS);
742     OS.write(OpBuffer.data(), OpBuffer.size());
743 
744     return Error::success();
745   };
746 
747   switch (Entry.Operator) {
748   case dwarf::DW_LLE_end_of_list:
749     if (Error Err = CheckOperands(0))
750       return std::move(Err);
751     break;
752   case dwarf::DW_LLE_base_addressx:
753     if (Error Err = CheckOperands(1))
754       return std::move(Err);
755     encodeULEB128(Entry.Values[0], OS);
756     break;
757   case dwarf::DW_LLE_startx_endx:
758   case dwarf::DW_LLE_startx_length:
759   case dwarf::DW_LLE_offset_pair:
760     if (Error Err = CheckOperands(2))
761       return std::move(Err);
762     encodeULEB128(Entry.Values[0], OS);
763     encodeULEB128(Entry.Values[1], OS);
764     if (Error Err = WriteDWARFOperations())
765       return std::move(Err);
766     break;
767   case dwarf::DW_LLE_default_location:
768     if (Error Err = CheckOperands(0))
769       return std::move(Err);
770     if (Error Err = WriteDWARFOperations())
771       return std::move(Err);
772     break;
773   case dwarf::DW_LLE_base_address:
774     if (Error Err = CheckOperands(1))
775       return std::move(Err);
776     if (Error Err = WriteAddress(Entry.Values[0]))
777       return std::move(Err);
778     break;
779   case dwarf::DW_LLE_start_end:
780     if (Error Err = CheckOperands(2))
781       return std::move(Err);
782     if (Error Err = WriteAddress(Entry.Values[0]))
783       return std::move(Err);
784     cantFail(WriteAddress(Entry.Values[1]));
785     if (Error Err = WriteDWARFOperations())
786       return std::move(Err);
787     break;
788   case dwarf::DW_LLE_start_length:
789     if (Error Err = CheckOperands(2))
790       return std::move(Err);
791     if (Error Err = WriteAddress(Entry.Values[0]))
792       return std::move(Err);
793     encodeULEB128(Entry.Values[1], OS);
794     if (Error Err = WriteDWARFOperations())
795       return std::move(Err);
796     break;
797   }
798 
799   return OS.tell() - BeginOffset;
800 }
801 
802 template <typename EntryType>
803 Error writeDWARFLists(raw_ostream &OS,
804                       ArrayRef<DWARFYAML::ListTable<EntryType>> Tables,
805                       bool IsLittleEndian, bool Is64BitAddrSize) {
806   for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
807     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
808     // sizeof(offset_entry_count) = 8
809     uint64_t Length = 8;
810 
811     uint8_t AddrSize;
812     if (Table.AddrSize)
813       AddrSize = *Table.AddrSize;
814     else
815       AddrSize = Is64BitAddrSize ? 8 : 4;
816 
817     // Since the length of the current range/location lists entry is
818     // undetermined yet, we firstly write the content of the range/location
819     // lists to a buffer to calculate the length and then serialize the buffer
820     // content to the actual output stream.
821     std::string ListBuffer;
822     raw_string_ostream ListBufferOS(ListBuffer);
823 
824     // Offsets holds offsets for each range/location list. The i-th element is
825     // the offset from the beginning of the first range/location list to the
826     // location of the i-th range list.
827     std::vector<uint64_t> Offsets;
828 
829     for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
830       Offsets.push_back(ListBufferOS.tell());
831       if (List.Content) {
832         List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
833         Length += List.Content->binary_size();
834       } else if (List.Entries) {
835         for (const EntryType &Entry : *List.Entries) {
836           Expected<uint64_t> EntrySize =
837               writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
838           if (!EntrySize)
839             return EntrySize.takeError();
840           Length += *EntrySize;
841         }
842       }
843     }
844 
845     // If the offset_entry_count field isn't specified, yaml2obj will infer it
846     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
847     // isn't specified either, yaml2obj will infer it from the auto-generated
848     // offsets.
849     uint32_t OffsetEntryCount;
850     if (Table.OffsetEntryCount)
851       OffsetEntryCount = *Table.OffsetEntryCount;
852     else
853       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
854     uint64_t OffsetsSize =
855         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
856     Length += OffsetsSize;
857 
858     // If the length is specified in the YAML description, we use it instead of
859     // the actual length.
860     if (Table.Length)
861       Length = *Table.Length;
862 
863     writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
864     writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
865     writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
866     writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
867     writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
868 
869     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
870       for (uint64_t Offset : Offsets)
871         writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
872                          IsLittleEndian);
873     };
874 
875     if (Table.Offsets)
876       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
877                                      Table.Offsets->size()),
878                   0);
879     else if (OffsetEntryCount != 0)
880       EmitOffsets(Offsets, OffsetsSize);
881 
882     OS.write(ListBuffer.data(), ListBuffer.size());
883   }
884 
885   return Error::success();
886 }
887 
888 Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
889   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
890   return writeDWARFLists<DWARFYAML::RnglistEntry>(
891       OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize);
892 }
893 
894 Error DWARFYAML::emitDebugLoclists(raw_ostream &OS, const Data &DI) {
895   assert(DI.DebugLoclists && "unexpected emitDebugRnglists() call");
896   return writeDWARFLists<DWARFYAML::LoclistEntry>(
897       OS, *DI.DebugLoclists, DI.IsLittleEndian, DI.Is64BitAddrSize);
898 }
899 
900 std::function<Error(raw_ostream &, const DWARFYAML::Data &)>
901 DWARFYAML::getDWARFEmitterByName(StringRef SecName) {
902   auto EmitFunc =
903       StringSwitch<
904           std::function<Error(raw_ostream &, const DWARFYAML::Data &)>>(SecName)
905           .Case("debug_abbrev", DWARFYAML::emitDebugAbbrev)
906           .Case("debug_addr", DWARFYAML::emitDebugAddr)
907           .Case("debug_aranges", DWARFYAML::emitDebugAranges)
908           .Case("debug_gnu_pubnames", DWARFYAML::emitDebugGNUPubnames)
909           .Case("debug_gnu_pubtypes", DWARFYAML::emitDebugGNUPubtypes)
910           .Case("debug_info", DWARFYAML::emitDebugInfo)
911           .Case("debug_line", DWARFYAML::emitDebugLine)
912           .Case("debug_loclists", DWARFYAML::emitDebugLoclists)
913           .Case("debug_pubnames", DWARFYAML::emitDebugPubnames)
914           .Case("debug_pubtypes", DWARFYAML::emitDebugPubtypes)
915           .Case("debug_ranges", DWARFYAML::emitDebugRanges)
916           .Case("debug_rnglists", DWARFYAML::emitDebugRnglists)
917           .Case("debug_str", DWARFYAML::emitDebugStr)
918           .Case("debug_str_offsets", DWARFYAML::emitDebugStrOffsets)
919           .Default([&](raw_ostream &, const DWARFYAML::Data &) {
920             return createStringError(errc::not_supported,
921                                      SecName + " is not supported");
922           });
923 
924   return EmitFunc;
925 }
926 
927 static Error
928 emitDebugSectionImpl(const DWARFYAML::Data &DI, StringRef Sec,
929                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
930   std::string Data;
931   raw_string_ostream DebugInfoStream(Data);
932 
933   auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Sec);
934 
935   if (Error Err = EmitFunc(DebugInfoStream, DI))
936     return Err;
937   DebugInfoStream.flush();
938   if (!Data.empty())
939     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
940 
941   return Error::success();
942 }
943 
944 Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
945 DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian,
946                              bool Is64BitAddrSize) {
947   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
948     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
949   };
950 
951   SMDiagnostic GeneratedDiag;
952   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
953                   &GeneratedDiag);
954 
955   DWARFYAML::Data DI;
956   DI.IsLittleEndian = IsLittleEndian;
957   DI.Is64BitAddrSize = Is64BitAddrSize;
958 
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