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