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     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
456     writeDWARFOffset(LineTable.PrologueLength, LineTable.Format, OS, DI.IsLittleEndian);
457     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
458     if (LineTable.Version >= 4)
459       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
460     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
461     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
462     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
463     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
464 
465     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
466       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
467 
468     for (auto IncludeDir : LineTable.IncludeDirs) {
469       OS.write(IncludeDir.data(), IncludeDir.size());
470       OS.write('\0');
471     }
472     OS.write('\0');
473 
474     for (auto File : LineTable.Files)
475       emitFileEntry(OS, File);
476     OS.write('\0');
477 
478     uint8_t AddrSize = DI.Is64BitAddrSize ? 8 : 4;
479 
480     for (auto Op : LineTable.Opcodes) {
481       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
482       if (Op.Opcode == 0) {
483         encodeULEB128(Op.ExtLen, OS);
484         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
485         switch (Op.SubOpcode) {
486         case dwarf::DW_LNE_set_address:
487           cantFail(writeVariableSizedInteger(Op.Data, AddrSize, OS,
488                                              DI.IsLittleEndian));
489           break;
490         case dwarf::DW_LNE_define_file:
491           emitFileEntry(OS, Op.FileEntry);
492           break;
493         case dwarf::DW_LNE_set_discriminator:
494           encodeULEB128(Op.Data, OS);
495           break;
496         case dwarf::DW_LNE_end_sequence:
497           break;
498         default:
499           for (auto OpByte : Op.UnknownOpcodeData)
500             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
501         }
502       } else if (Op.Opcode < LineTable.OpcodeBase) {
503         switch (Op.Opcode) {
504         case dwarf::DW_LNS_copy:
505         case dwarf::DW_LNS_negate_stmt:
506         case dwarf::DW_LNS_set_basic_block:
507         case dwarf::DW_LNS_const_add_pc:
508         case dwarf::DW_LNS_set_prologue_end:
509         case dwarf::DW_LNS_set_epilogue_begin:
510           break;
511 
512         case dwarf::DW_LNS_advance_pc:
513         case dwarf::DW_LNS_set_file:
514         case dwarf::DW_LNS_set_column:
515         case dwarf::DW_LNS_set_isa:
516           encodeULEB128(Op.Data, OS);
517           break;
518 
519         case dwarf::DW_LNS_advance_line:
520           encodeSLEB128(Op.SData, OS);
521           break;
522 
523         case dwarf::DW_LNS_fixed_advance_pc:
524           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
525           break;
526 
527         default:
528           for (auto OpData : Op.StandardOpcodeData) {
529             encodeULEB128(OpData, OS);
530           }
531         }
532       }
533     }
534   }
535 
536   return Error::success();
537 }
538 
539 Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) {
540   for (const AddrTableEntry &TableEntry : DI.DebugAddr) {
541     uint8_t AddrSize;
542     if (TableEntry.AddrSize)
543       AddrSize = *TableEntry.AddrSize;
544     else
545       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
546 
547     uint64_t Length;
548     if (TableEntry.Length)
549       Length = (uint64_t)*TableEntry.Length;
550     else
551       // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
552       Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
553                        TableEntry.SegAddrPairs.size();
554 
555     writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian);
556     writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian);
557     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
558     writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
559 
560     for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
561       if (TableEntry.SegSelectorSize != 0)
562         if (Error Err = writeVariableSizedInteger(Pair.Segment,
563                                                   TableEntry.SegSelectorSize,
564                                                   OS, DI.IsLittleEndian))
565           return createStringError(errc::not_supported,
566                                    "unable to write debug_addr segment: %s",
567                                    toString(std::move(Err)).c_str());
568       if (AddrSize != 0)
569         if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
570                                                   DI.IsLittleEndian))
571           return createStringError(errc::not_supported,
572                                    "unable to write debug_addr address: %s",
573                                    toString(std::move(Err)).c_str());
574     }
575   }
576 
577   return Error::success();
578 }
579 
580 Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) {
581   assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
582   for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
583     uint64_t Length;
584     if (Table.Length)
585       Length = *Table.Length;
586     else
587       // sizeof(version) + sizeof(padding) = 4
588       Length =
589           4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
590 
591     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
592     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
593     writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian);
594 
595     for (uint64_t Offset : Table.Offsets)
596       writeDWARFOffset(Offset, Table.Format, OS, DI.IsLittleEndian);
597   }
598 
599   return Error::success();
600 }
601 
602 static Error checkOperandCount(StringRef EncodingString,
603                                ArrayRef<yaml::Hex64> Values,
604                                uint64_t ExpectedOperands) {
605   if (Values.size() != ExpectedOperands)
606     return createStringError(
607         errc::invalid_argument,
608         "invalid number (%zu) of operands for the operator: %s, %" PRIu64
609         " expected",
610         Values.size(), EncodingString.str().c_str(), ExpectedOperands);
611 
612   return Error::success();
613 }
614 
615 static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS,
616                                    uint64_t Addr, uint8_t AddrSize,
617                                    bool IsLittleEndian) {
618   if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
619     return createStringError(errc::invalid_argument,
620                              "unable to write address for the operator %s: %s",
621                              EncodingName.str().c_str(),
622                              toString(std::move(Err)).c_str());
623 
624   return Error::success();
625 }
626 
627 static Expected<uint64_t>
628 writeDWARFExpression(raw_ostream &OS,
629                      const DWARFYAML::DWARFOperation &Operation,
630                      uint8_t AddrSize, bool IsLittleEndian) {
631   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
632     return checkOperandCount(dwarf::OperationEncodingString(Operation.Operator),
633                              Operation.Values, ExpectedOperands);
634   };
635 
636   uint64_t ExpressionBegin = OS.tell();
637   writeInteger((uint8_t)Operation.Operator, OS, IsLittleEndian);
638   switch (Operation.Operator) {
639   case dwarf::DW_OP_consts:
640     if (Error Err = CheckOperands(1))
641       return std::move(Err);
642     encodeSLEB128(Operation.Values[0], OS);
643     break;
644   case dwarf::DW_OP_stack_value:
645     if (Error Err = CheckOperands(0))
646       return std::move(Err);
647     break;
648   default:
649     StringRef EncodingStr = dwarf::OperationEncodingString(Operation.Operator);
650     return createStringError(errc::not_supported,
651                              "DWARF expression: " +
652                                  (EncodingStr.empty()
653                                       ? "0x" + utohexstr(Operation.Operator)
654                                       : EncodingStr) +
655                                  " is not supported");
656   }
657   return OS.tell() - ExpressionBegin;
658 }
659 
660 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
661                                          const DWARFYAML::RnglistEntry &Entry,
662                                          uint8_t AddrSize,
663                                          bool IsLittleEndian) {
664   uint64_t BeginOffset = OS.tell();
665   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
666 
667   StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
668 
669   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
670     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
671   };
672 
673   auto WriteAddress = [&](uint64_t Addr) -> Error {
674     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
675                                  IsLittleEndian);
676   };
677 
678   switch (Entry.Operator) {
679   case dwarf::DW_RLE_end_of_list:
680     if (Error Err = CheckOperands(0))
681       return std::move(Err);
682     break;
683   case dwarf::DW_RLE_base_addressx:
684     if (Error Err = CheckOperands(1))
685       return std::move(Err);
686     encodeULEB128(Entry.Values[0], OS);
687     break;
688   case dwarf::DW_RLE_startx_endx:
689   case dwarf::DW_RLE_startx_length:
690   case dwarf::DW_RLE_offset_pair:
691     if (Error Err = CheckOperands(2))
692       return std::move(Err);
693     encodeULEB128(Entry.Values[0], OS);
694     encodeULEB128(Entry.Values[1], OS);
695     break;
696   case dwarf::DW_RLE_base_address:
697     if (Error Err = CheckOperands(1))
698       return std::move(Err);
699     if (Error Err = WriteAddress(Entry.Values[0]))
700       return std::move(Err);
701     break;
702   case dwarf::DW_RLE_start_end:
703     if (Error Err = CheckOperands(2))
704       return std::move(Err);
705     if (Error Err = WriteAddress(Entry.Values[0]))
706       return std::move(Err);
707     cantFail(WriteAddress(Entry.Values[1]));
708     break;
709   case dwarf::DW_RLE_start_length:
710     if (Error Err = CheckOperands(2))
711       return std::move(Err);
712     if (Error Err = WriteAddress(Entry.Values[0]))
713       return std::move(Err);
714     encodeULEB128(Entry.Values[1], OS);
715     break;
716   }
717 
718   return OS.tell() - BeginOffset;
719 }
720 
721 static Expected<uint64_t> writeListEntry(raw_ostream &OS,
722                                          const DWARFYAML::LoclistEntry &Entry,
723                                          uint8_t AddrSize,
724                                          bool IsLittleEndian) {
725   uint64_t BeginOffset = OS.tell();
726   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
727 
728   StringRef EncodingName = dwarf::LocListEncodingString(Entry.Operator);
729 
730   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
731     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
732   };
733 
734   auto WriteAddress = [&](uint64_t Addr) -> Error {
735     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
736                                  IsLittleEndian);
737   };
738 
739   auto WriteDWARFOperations = [&]() -> Error {
740     std::string OpBuffer;
741     raw_string_ostream OpBufferOS(OpBuffer);
742     uint64_t DescriptionsLength = 0;
743 
744     for (const DWARFYAML::DWARFOperation &Op : Entry.Descriptions) {
745       if (Expected<uint64_t> OpSize =
746               writeDWARFExpression(OpBufferOS, Op, AddrSize, IsLittleEndian))
747         DescriptionsLength += *OpSize;
748       else
749         return OpSize.takeError();
750     }
751 
752     if (Entry.DescriptionsLength)
753       DescriptionsLength = *Entry.DescriptionsLength;
754     else
755       DescriptionsLength = OpBuffer.size();
756 
757     encodeULEB128(DescriptionsLength, OS);
758     OS.write(OpBuffer.data(), OpBuffer.size());
759 
760     return Error::success();
761   };
762 
763   switch (Entry.Operator) {
764   case dwarf::DW_LLE_end_of_list:
765     if (Error Err = CheckOperands(0))
766       return std::move(Err);
767     break;
768   case dwarf::DW_LLE_base_addressx:
769     if (Error Err = CheckOperands(1))
770       return std::move(Err);
771     encodeULEB128(Entry.Values[0], OS);
772     break;
773   case dwarf::DW_LLE_startx_endx:
774   case dwarf::DW_LLE_startx_length:
775   case dwarf::DW_LLE_offset_pair:
776     if (Error Err = CheckOperands(2))
777       return std::move(Err);
778     encodeULEB128(Entry.Values[0], OS);
779     encodeULEB128(Entry.Values[1], OS);
780     if (Error Err = WriteDWARFOperations())
781       return std::move(Err);
782     break;
783   case dwarf::DW_LLE_default_location:
784     if (Error Err = CheckOperands(0))
785       return std::move(Err);
786     if (Error Err = WriteDWARFOperations())
787       return std::move(Err);
788     break;
789   case dwarf::DW_LLE_base_address:
790     if (Error Err = CheckOperands(1))
791       return std::move(Err);
792     if (Error Err = WriteAddress(Entry.Values[0]))
793       return std::move(Err);
794     break;
795   case dwarf::DW_LLE_start_end:
796     if (Error Err = CheckOperands(2))
797       return std::move(Err);
798     if (Error Err = WriteAddress(Entry.Values[0]))
799       return std::move(Err);
800     cantFail(WriteAddress(Entry.Values[1]));
801     if (Error Err = WriteDWARFOperations())
802       return std::move(Err);
803     break;
804   case dwarf::DW_LLE_start_length:
805     if (Error Err = CheckOperands(2))
806       return std::move(Err);
807     if (Error Err = WriteAddress(Entry.Values[0]))
808       return std::move(Err);
809     encodeULEB128(Entry.Values[1], OS);
810     if (Error Err = WriteDWARFOperations())
811       return std::move(Err);
812     break;
813   }
814 
815   return OS.tell() - BeginOffset;
816 }
817 
818 template <typename EntryType>
819 static Error writeDWARFLists(raw_ostream &OS,
820                              ArrayRef<DWARFYAML::ListTable<EntryType>> Tables,
821                              bool IsLittleEndian, bool Is64BitAddrSize) {
822   for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
823     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
824     // sizeof(offset_entry_count) = 8
825     uint64_t Length = 8;
826 
827     uint8_t AddrSize;
828     if (Table.AddrSize)
829       AddrSize = *Table.AddrSize;
830     else
831       AddrSize = Is64BitAddrSize ? 8 : 4;
832 
833     // Since the length of the current range/location lists entry is
834     // undetermined yet, we firstly write the content of the range/location
835     // lists to a buffer to calculate the length and then serialize the buffer
836     // content to the actual output stream.
837     std::string ListBuffer;
838     raw_string_ostream ListBufferOS(ListBuffer);
839 
840     // Offsets holds offsets for each range/location list. The i-th element is
841     // the offset from the beginning of the first range/location list to the
842     // location of the i-th range list.
843     std::vector<uint64_t> Offsets;
844 
845     for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
846       Offsets.push_back(ListBufferOS.tell());
847       if (List.Content) {
848         List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
849         Length += List.Content->binary_size();
850       } else if (List.Entries) {
851         for (const EntryType &Entry : *List.Entries) {
852           Expected<uint64_t> EntrySize =
853               writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
854           if (!EntrySize)
855             return EntrySize.takeError();
856           Length += *EntrySize;
857         }
858       }
859     }
860 
861     // If the offset_entry_count field isn't specified, yaml2obj will infer it
862     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
863     // isn't specified either, yaml2obj will infer it from the auto-generated
864     // offsets.
865     uint32_t OffsetEntryCount;
866     if (Table.OffsetEntryCount)
867       OffsetEntryCount = *Table.OffsetEntryCount;
868     else
869       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
870     uint64_t OffsetsSize =
871         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
872     Length += OffsetsSize;
873 
874     // If the length is specified in the YAML description, we use it instead of
875     // the actual length.
876     if (Table.Length)
877       Length = *Table.Length;
878 
879     writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
880     writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
881     writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
882     writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
883     writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
884 
885     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
886       for (uint64_t Offset : Offsets)
887         writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
888                          IsLittleEndian);
889     };
890 
891     if (Table.Offsets)
892       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
893                                      Table.Offsets->size()),
894                   0);
895     else if (OffsetEntryCount != 0)
896       EmitOffsets(Offsets, OffsetsSize);
897 
898     OS.write(ListBuffer.data(), ListBuffer.size());
899   }
900 
901   return Error::success();
902 }
903 
904 Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
905   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
906   return writeDWARFLists<DWARFYAML::RnglistEntry>(
907       OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize);
908 }
909 
910 Error DWARFYAML::emitDebugLoclists(raw_ostream &OS, const Data &DI) {
911   assert(DI.DebugLoclists && "unexpected emitDebugRnglists() call");
912   return writeDWARFLists<DWARFYAML::LoclistEntry>(
913       OS, *DI.DebugLoclists, DI.IsLittleEndian, DI.Is64BitAddrSize);
914 }
915 
916 std::function<Error(raw_ostream &, const DWARFYAML::Data &)>
917 DWARFYAML::getDWARFEmitterByName(StringRef SecName) {
918   auto EmitFunc =
919       StringSwitch<
920           std::function<Error(raw_ostream &, const DWARFYAML::Data &)>>(SecName)
921           .Case("debug_abbrev", DWARFYAML::emitDebugAbbrev)
922           .Case("debug_addr", DWARFYAML::emitDebugAddr)
923           .Case("debug_aranges", DWARFYAML::emitDebugAranges)
924           .Case("debug_gnu_pubnames", DWARFYAML::emitDebugGNUPubnames)
925           .Case("debug_gnu_pubtypes", DWARFYAML::emitDebugGNUPubtypes)
926           .Case("debug_info", DWARFYAML::emitDebugInfo)
927           .Case("debug_line", DWARFYAML::emitDebugLine)
928           .Case("debug_loclists", DWARFYAML::emitDebugLoclists)
929           .Case("debug_pubnames", DWARFYAML::emitDebugPubnames)
930           .Case("debug_pubtypes", DWARFYAML::emitDebugPubtypes)
931           .Case("debug_ranges", DWARFYAML::emitDebugRanges)
932           .Case("debug_rnglists", DWARFYAML::emitDebugRnglists)
933           .Case("debug_str", DWARFYAML::emitDebugStr)
934           .Case("debug_str_offsets", DWARFYAML::emitDebugStrOffsets)
935           .Default([&](raw_ostream &, const DWARFYAML::Data &) {
936             return createStringError(errc::not_supported,
937                                      SecName + " is not supported");
938           });
939 
940   return EmitFunc;
941 }
942 
943 static Error
944 emitDebugSectionImpl(const DWARFYAML::Data &DI, StringRef Sec,
945                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
946   std::string Data;
947   raw_string_ostream DebugInfoStream(Data);
948 
949   auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Sec);
950 
951   if (Error Err = EmitFunc(DebugInfoStream, DI))
952     return Err;
953   DebugInfoStream.flush();
954   if (!Data.empty())
955     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
956 
957   return Error::success();
958 }
959 
960 Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
961 DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian,
962                              bool Is64BitAddrSize) {
963   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
964     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
965   };
966 
967   SMDiagnostic GeneratedDiag;
968   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
969                   &GeneratedDiag);
970 
971   DWARFYAML::Data DI;
972   DI.IsLittleEndian = IsLittleEndian;
973   DI.Is64BitAddrSize = Is64BitAddrSize;
974 
975   YIn >> DI;
976   if (YIn.error())
977     return createStringError(YIn.error(), GeneratedDiag.getMessage());
978 
979   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
980   Error Err = Error::success();
981   cantFail(std::move(Err));
982 
983   for (StringRef SecName : DI.getNonEmptySectionNames())
984     Err = joinErrors(std::move(Err),
985                      emitDebugSectionImpl(DI, SecName, DebugSections));
986 
987   if (Err)
988     return std::move(Err);
989   return std::move(DebugSections);
990 }
991