107088c10SChris Bieneman //===- DWARFEmitter - Convert YAML to DWARF binary data -------------------===//
207088c10SChris Bieneman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
607088c10SChris Bieneman //
707088c10SChris Bieneman //===----------------------------------------------------------------------===//
807088c10SChris Bieneman ///
907088c10SChris Bieneman /// \file
105f8f34e4SAdrian Prantl /// The DWARF component of yaml2obj. Provided as library code for tests.
1107088c10SChris Bieneman ///
1207088c10SChris Bieneman //===----------------------------------------------------------------------===//
1307088c10SChris Bieneman 
1407088c10SChris Bieneman #include "llvm/ObjectYAML/DWARFEmitter.h"
15c4cf250cSXing GUO #include "llvm/ADT/ArrayRef.h"
1628082ab0SEugene Zelenko #include "llvm/ADT/StringMap.h"
1728082ab0SEugene Zelenko #include "llvm/ADT/StringRef.h"
18929edd8bSXing GUO #include "llvm/BinaryFormat/Dwarf.h"
1907088c10SChris Bieneman #include "llvm/ObjectYAML/DWARFYAML.h"
20e4344e14SXing GUO #include "llvm/Support/Errc.h"
2107088c10SChris Bieneman #include "llvm/Support/Error.h"
2228082ab0SEugene Zelenko #include "llvm/Support/Host.h"
2307088c10SChris Bieneman #include "llvm/Support/LEB128.h"
2428082ab0SEugene Zelenko #include "llvm/Support/MathExtras.h"
2528082ab0SEugene Zelenko #include "llvm/Support/MemoryBuffer.h"
268f9ca561SXing GUO #include "llvm/Support/SourceMgr.h"
2707088c10SChris Bieneman #include "llvm/Support/SwapByteOrder.h"
2828082ab0SEugene Zelenko #include "llvm/Support/YAMLTraits.h"
296bda14b3SChandler Carruth #include "llvm/Support/raw_ostream.h"
3007088c10SChris Bieneman #include <algorithm>
3128082ab0SEugene Zelenko #include <cassert>
3228082ab0SEugene Zelenko #include <cstddef>
3328082ab0SEugene Zelenko #include <cstdint>
3428082ab0SEugene Zelenko #include <memory>
3528082ab0SEugene Zelenko #include <string>
3628082ab0SEugene Zelenko #include <vector>
3707088c10SChris Bieneman 
3807088c10SChris Bieneman using namespace llvm;
3907088c10SChris Bieneman 
4007088c10SChris Bieneman template <typename T>
41efcf06f5SBenjamin Kramer static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian) {
4207088c10SChris Bieneman   if (IsLittleEndian != sys::IsLittleEndianHost)
4307088c10SChris Bieneman     sys::swapByteOrder(Integer);
4407088c10SChris Bieneman   OS.write(reinterpret_cast<char *>(&Integer), sizeof(T));
4507088c10SChris Bieneman }
4607088c10SChris Bieneman 
479aaa32cfSXing GUO static Error writeVariableSizedInteger(uint64_t Integer, size_t Size,
48efcf06f5SBenjamin Kramer                                        raw_ostream &OS, bool IsLittleEndian) {
4907088c10SChris Bieneman   if (8 == Size)
5007088c10SChris Bieneman     writeInteger((uint64_t)Integer, OS, IsLittleEndian);
5107088c10SChris Bieneman   else if (4 == Size)
5207088c10SChris Bieneman     writeInteger((uint32_t)Integer, OS, IsLittleEndian);
5307088c10SChris Bieneman   else if (2 == Size)
5407088c10SChris Bieneman     writeInteger((uint16_t)Integer, OS, IsLittleEndian);
5507088c10SChris Bieneman   else if (1 == Size)
5607088c10SChris Bieneman     writeInteger((uint8_t)Integer, OS, IsLittleEndian);
5707088c10SChris Bieneman   else
589aaa32cfSXing GUO     return createStringError(errc::not_supported,
599aaa32cfSXing GUO                              "invalid integer write size: %zu", Size);
609aaa32cfSXing GUO 
619aaa32cfSXing GUO   return Error::success();
6207088c10SChris Bieneman }
6307088c10SChris Bieneman 
64efcf06f5SBenjamin Kramer static void ZeroFillBytes(raw_ostream &OS, size_t Size) {
6507088c10SChris Bieneman   std::vector<uint8_t> FillData;
6607088c10SChris Bieneman   FillData.insert(FillData.begin(), Size, 0);
6707088c10SChris Bieneman   OS.write(reinterpret_cast<char *>(FillData.data()), Size);
6807088c10SChris Bieneman }
6907088c10SChris Bieneman 
7049a49fe8SBenjamin Kramer static void writeInitialLength(const DWARFYAML::InitialLength &Length,
7149a49fe8SBenjamin Kramer                                raw_ostream &OS, bool IsLittleEndian) {
72faf1feb5SChris Bieneman   writeInteger((uint32_t)Length.TotalLength, OS, IsLittleEndian);
73faf1feb5SChris Bieneman   if (Length.isDWARF64())
74faf1feb5SChris Bieneman     writeInteger((uint64_t)Length.TotalLength64, OS, IsLittleEndian);
75faf1feb5SChris Bieneman }
76faf1feb5SChris Bieneman 
77613c4a87SXing GUO static void writeInitialLength(const dwarf::DwarfFormat Format,
78613c4a87SXing GUO                                const uint64_t Length, raw_ostream &OS,
79613c4a87SXing GUO                                bool IsLittleEndian) {
80613c4a87SXing GUO   bool IsDWARF64 = Format == dwarf::DWARF64;
81613c4a87SXing GUO   if (IsDWARF64)
829aaa32cfSXing GUO     cantFail(writeVariableSizedInteger(dwarf::DW_LENGTH_DWARF64, 4, OS,
839aaa32cfSXing GUO                                        IsLittleEndian));
849aaa32cfSXing GUO   cantFail(
859aaa32cfSXing GUO       writeVariableSizedInteger(Length, IsDWARF64 ? 8 : 4, OS, IsLittleEndian));
86613c4a87SXing GUO }
87613c4a87SXing GUO 
88367d0d4cSXing GUO static void writeDWARFOffset(uint64_t Offset, dwarf::DwarfFormat Format,
89367d0d4cSXing GUO                              raw_ostream &OS, bool IsLittleEndian) {
90367d0d4cSXing GUO   cantFail(writeVariableSizedInteger(Offset, Format == dwarf::DWARF64 ? 8 : 4,
91367d0d4cSXing GUO                                      OS, IsLittleEndian));
92367d0d4cSXing GUO }
93367d0d4cSXing GUO 
949939f231SXing GUO Error DWARFYAML::emitDebugStr(raw_ostream &OS, const DWARFYAML::Data &DI) {
9507088c10SChris Bieneman   for (auto Str : DI.DebugStrings) {
9607088c10SChris Bieneman     OS.write(Str.data(), Str.size());
9707088c10SChris Bieneman     OS.write('\0');
9807088c10SChris Bieneman   }
999939f231SXing GUO 
1009939f231SXing GUO   return Error::success();
10107088c10SChris Bieneman }
10207088c10SChris Bieneman 
1039939f231SXing GUO Error DWARFYAML::emitDebugAbbrev(raw_ostream &OS, const DWARFYAML::Data &DI) {
104d261a1c0SXing GUO   uint64_t AbbrevCode = 0;
10507088c10SChris Bieneman   for (auto AbbrevDecl : DI.AbbrevDecls) {
106d261a1c0SXing GUO     AbbrevCode = AbbrevDecl.Code ? (uint64_t)*AbbrevDecl.Code : AbbrevCode + 1;
107d261a1c0SXing GUO     encodeULEB128(AbbrevCode, OS);
10807088c10SChris Bieneman     encodeULEB128(AbbrevDecl.Tag, OS);
10907088c10SChris Bieneman     OS.write(AbbrevDecl.Children);
11007088c10SChris Bieneman     for (auto Attr : AbbrevDecl.Attributes) {
11107088c10SChris Bieneman       encodeULEB128(Attr.Attribute, OS);
11207088c10SChris Bieneman       encodeULEB128(Attr.Form, OS);
113bcf513f2SChris Bieneman       if (Attr.Form == dwarf::DW_FORM_implicit_const)
114bcf513f2SChris Bieneman         encodeSLEB128(Attr.Value, OS);
11507088c10SChris Bieneman     }
11607088c10SChris Bieneman     encodeULEB128(0, OS);
11707088c10SChris Bieneman     encodeULEB128(0, OS);
11807088c10SChris Bieneman   }
1199939f231SXing GUO 
12038907b69SXing GUO   // The abbreviations for a given compilation unit end with an entry consisting
12138907b69SXing GUO   // of a 0 byte for the abbreviation code.
12238907b69SXing GUO   OS.write_zeros(1);
12338907b69SXing GUO 
1249939f231SXing GUO   return Error::success();
12507088c10SChris Bieneman }
12607088c10SChris Bieneman 
1279939f231SXing GUO Error DWARFYAML::emitDebugAranges(raw_ostream &OS, const DWARFYAML::Data &DI) {
12807088c10SChris Bieneman   for (auto Range : DI.ARanges) {
129006f6f8aSXing GUO     uint8_t AddrSize;
130006f6f8aSXing GUO     if (Range.AddrSize)
131006f6f8aSXing GUO       AddrSize = *Range.AddrSize;
132006f6f8aSXing GUO     else
133006f6f8aSXing GUO       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
134006f6f8aSXing GUO 
1353da6a974SXing GUO     uint64_t Length = 4; // sizeof(version) 2 + sizeof(address_size) 1 +
1363da6a974SXing GUO                          // sizeof(segment_selector_size) 1
1373da6a974SXing GUO     Length +=
1383da6a974SXing GUO         Range.Format == dwarf::DWARF64 ? 8 : 4; // sizeof(debug_info_offset)
1393da6a974SXing GUO 
1403da6a974SXing GUO     const uint64_t HeaderLength =
1413da6a974SXing GUO         Length + (Range.Format == dwarf::DWARF64
1423da6a974SXing GUO                       ? 12
1433da6a974SXing GUO                       : 4); // sizeof(unit_header) = 12 (DWARF64) or 4 (DWARF32)
1443da6a974SXing GUO     const uint64_t PaddedHeaderLength = alignTo(HeaderLength, AddrSize * 2);
1453da6a974SXing GUO 
1463da6a974SXing GUO     if (Range.Length) {
1473da6a974SXing GUO       Length = *Range.Length;
1483da6a974SXing GUO     } else {
1493da6a974SXing GUO       Length += PaddedHeaderLength - HeaderLength;
1503da6a974SXing GUO       Length += AddrSize * 2 * (Range.Descriptors.size() + 1);
1513da6a974SXing GUO     }
1523da6a974SXing GUO 
1533da6a974SXing GUO     writeInitialLength(Range.Format, Length, OS, DI.IsLittleEndian);
15407088c10SChris Bieneman     writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian);
155367d0d4cSXing GUO     writeDWARFOffset(Range.CuOffset, Range.Format, OS, DI.IsLittleEndian);
156006f6f8aSXing GUO     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
15707088c10SChris Bieneman     writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
1583da6a974SXing GUO     ZeroFillBytes(OS, PaddedHeaderLength - HeaderLength);
15907088c10SChris Bieneman 
16007088c10SChris Bieneman     for (auto Descriptor : Range.Descriptors) {
161006f6f8aSXing GUO       if (Error Err = writeVariableSizedInteger(Descriptor.Address, AddrSize,
162006f6f8aSXing GUO                                                 OS, DI.IsLittleEndian))
1639aaa32cfSXing GUO         return createStringError(errc::not_supported,
1649aaa32cfSXing GUO                                  "unable to write debug_aranges address: %s",
1659aaa32cfSXing GUO                                  toString(std::move(Err)).c_str());
166006f6f8aSXing GUO       cantFail(writeVariableSizedInteger(Descriptor.Length, AddrSize, OS,
1679aaa32cfSXing GUO                                          DI.IsLittleEndian));
16807088c10SChris Bieneman     }
169006f6f8aSXing GUO     ZeroFillBytes(OS, AddrSize * 2);
17007088c10SChris Bieneman   }
1719939f231SXing GUO 
1729939f231SXing GUO   return Error::success();
17307088c10SChris Bieneman }
17407088c10SChris Bieneman 
1759939f231SXing GUO Error DWARFYAML::emitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) {
1766025fc22SGreg Clayton   const size_t RangesOffset = OS.tell();
177e4344e14SXing GUO   uint64_t EntryIndex = 0;
1786e73f12aSGreg Clayton   for (auto DebugRanges : DI.DebugRanges) {
1796025fc22SGreg Clayton     const size_t CurrOffset = OS.tell() - RangesOffset;
18099c23354SXing GUO     if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset)
181e4344e14SXing GUO       return createStringError(errc::invalid_argument,
182e4344e14SXing GUO                                "'Offset' for 'debug_ranges' with index " +
183e4344e14SXing GUO                                    Twine(EntryIndex) +
184e4344e14SXing GUO                                    " must be greater than or equal to the "
185e4344e14SXing GUO                                    "number of bytes written already (0x" +
186e4344e14SXing GUO                                    Twine::utohexstr(CurrOffset) + ")");
18799c23354SXing GUO     if (DebugRanges.Offset)
18899c23354SXing GUO       ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset);
189ff9c1ae2SXing GUO 
190ff9c1ae2SXing GUO     uint8_t AddrSize;
191ff9c1ae2SXing GUO     if (DebugRanges.AddrSize)
192ff9c1ae2SXing GUO       AddrSize = *DebugRanges.AddrSize;
193ff9c1ae2SXing GUO     else
194830a7c2aSXing GUO       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
1956e73f12aSGreg Clayton     for (auto Entry : DebugRanges.Entries) {
1969aaa32cfSXing GUO       if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS,
1979aaa32cfSXing GUO                                                 DI.IsLittleEndian))
1989aaa32cfSXing GUO         return createStringError(
1999aaa32cfSXing GUO             errc::not_supported,
2009aaa32cfSXing GUO             "unable to write debug_ranges address offset: %s",
2019aaa32cfSXing GUO             toString(std::move(Err)).c_str());
2029aaa32cfSXing GUO       cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS,
2039aaa32cfSXing GUO                                          DI.IsLittleEndian));
2046025fc22SGreg Clayton     }
205ff9c1ae2SXing GUO     ZeroFillBytes(OS, AddrSize * 2);
206e4344e14SXing GUO     ++EntryIndex;
2076025fc22SGreg Clayton   }
2089939f231SXing GUO 
2099939f231SXing GUO   return Error::success();
2106025fc22SGreg Clayton }
2116025fc22SGreg Clayton 
212*cbf5bf51SXing GUO static Error emitPubSection(raw_ostream &OS, const DWARFYAML::PubSection &Sect,
213*cbf5bf51SXing GUO                             bool IsLittleEndian, bool IsGNUPubSec = false) {
214faf1feb5SChris Bieneman   writeInitialLength(Sect.Length, OS, IsLittleEndian);
21507088c10SChris Bieneman   writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
21607088c10SChris Bieneman   writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
21707088c10SChris Bieneman   writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
21807088c10SChris Bieneman   for (auto Entry : Sect.Entries) {
21907088c10SChris Bieneman     writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
220b6f08b7cSXing GUO     if (IsGNUPubSec)
22193bc571dSXing GUO       writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian);
22207088c10SChris Bieneman     OS.write(Entry.Name.data(), Entry.Name.size());
22307088c10SChris Bieneman     OS.write('\0');
22407088c10SChris Bieneman   }
2259939f231SXing GUO 
2269939f231SXing GUO   return Error::success();
22707088c10SChris Bieneman }
22807088c10SChris Bieneman 
229*cbf5bf51SXing GUO Error DWARFYAML::emitDebugPubnames(raw_ostream &OS, const Data &DI) {
230*cbf5bf51SXing GUO   assert(DI.PubNames && "unexpected emitDebugPubnames() call");
231*cbf5bf51SXing GUO   return emitPubSection(OS, *DI.PubNames, DI.IsLittleEndian);
232*cbf5bf51SXing GUO }
233*cbf5bf51SXing GUO 
234*cbf5bf51SXing GUO Error DWARFYAML::emitDebugPubtypes(raw_ostream &OS, const Data &DI) {
235*cbf5bf51SXing GUO   assert(DI.PubTypes && "unexpected emitDebugPubtypes() call");
236*cbf5bf51SXing GUO   return emitPubSection(OS, *DI.PubTypes, DI.IsLittleEndian);
237*cbf5bf51SXing GUO }
238*cbf5bf51SXing GUO 
239*cbf5bf51SXing GUO Error DWARFYAML::emitDebugGNUPubnames(raw_ostream &OS, const Data &DI) {
240*cbf5bf51SXing GUO   assert(DI.GNUPubNames && "unexpected emitDebugGNUPubnames() call");
241*cbf5bf51SXing GUO   return emitPubSection(OS, *DI.GNUPubNames, DI.IsLittleEndian,
242*cbf5bf51SXing GUO                         /*IsGNUStyle=*/true);
243*cbf5bf51SXing GUO }
244*cbf5bf51SXing GUO 
245*cbf5bf51SXing GUO Error DWARFYAML::emitDebugGNUPubtypes(raw_ostream &OS, const Data &DI) {
246*cbf5bf51SXing GUO   assert(DI.GNUPubTypes && "unexpected emitDebugGNUPubtypes() call");
247*cbf5bf51SXing GUO   return emitPubSection(OS, *DI.GNUPubTypes, DI.IsLittleEndian,
248*cbf5bf51SXing GUO                         /*IsGNUStyle=*/true);
249*cbf5bf51SXing GUO }
250*cbf5bf51SXing GUO 
25192874d28SXing GUO static Expected<uint64_t> writeDIE(ArrayRef<DWARFYAML::Abbrev> AbbrevDecls,
25292874d28SXing GUO                                    const DWARFYAML::Unit &Unit,
25392874d28SXing GUO                                    const DWARFYAML::Entry &Entry,
25492874d28SXing GUO                                    raw_ostream &OS, bool IsLittleEndian) {
25592874d28SXing GUO   uint64_t EntryBegin = OS.tell();
25692874d28SXing GUO   encodeULEB128(Entry.AbbrCode, OS);
25792874d28SXing GUO   uint32_t AbbrCode = Entry.AbbrCode;
25892874d28SXing GUO   if (AbbrCode == 0 || Entry.Values.empty())
25992874d28SXing GUO     return OS.tell() - EntryBegin;
26007088c10SChris Bieneman 
26192874d28SXing GUO   if (AbbrCode > AbbrevDecls.size())
26292874d28SXing GUO     return createStringError(
26392874d28SXing GUO         errc::invalid_argument,
26492874d28SXing GUO         "abbrev code must be less than or equal to the number of "
26592874d28SXing GUO         "entries in abbreviation table");
26692874d28SXing GUO   const DWARFYAML::Abbrev &Abbrev = AbbrevDecls[AbbrCode - 1];
26792874d28SXing GUO   auto FormVal = Entry.Values.begin();
26892874d28SXing GUO   auto AbbrForm = Abbrev.Attributes.begin();
26992874d28SXing GUO   for (; FormVal != Entry.Values.end() && AbbrForm != Abbrev.Attributes.end();
27092874d28SXing GUO        ++FormVal, ++AbbrForm) {
27192874d28SXing GUO     dwarf::Form Form = AbbrForm->Form;
27292874d28SXing GUO     bool Indirect;
27392874d28SXing GUO     do {
27492874d28SXing GUO       Indirect = false;
27592874d28SXing GUO       switch (Form) {
27692874d28SXing GUO       case dwarf::DW_FORM_addr:
27792874d28SXing GUO         // TODO: Test this error.
278bbb057c4SXing GUO         if (Error Err = writeVariableSizedInteger(
279bbb057c4SXing GUO                 FormVal->Value, Unit.FormParams.AddrSize, OS, IsLittleEndian))
28092874d28SXing GUO           return std::move(Err);
28192874d28SXing GUO         break;
28292874d28SXing GUO       case dwarf::DW_FORM_ref_addr:
28392874d28SXing GUO         // TODO: Test this error.
28492874d28SXing GUO         if (Error Err = writeVariableSizedInteger(
285bbb057c4SXing GUO                 FormVal->Value, Unit.FormParams.getRefAddrByteSize(), OS,
286bbb057c4SXing GUO                 IsLittleEndian))
28792874d28SXing GUO           return std::move(Err);
28892874d28SXing GUO         break;
28992874d28SXing GUO       case dwarf::DW_FORM_exprloc:
29092874d28SXing GUO       case dwarf::DW_FORM_block:
29192874d28SXing GUO         encodeULEB128(FormVal->BlockData.size(), OS);
29292874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
29392874d28SXing GUO                  FormVal->BlockData.size());
29492874d28SXing GUO         break;
29592874d28SXing GUO       case dwarf::DW_FORM_block1: {
29692874d28SXing GUO         writeInteger((uint8_t)FormVal->BlockData.size(), OS, IsLittleEndian);
29792874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
29892874d28SXing GUO                  FormVal->BlockData.size());
29992874d28SXing GUO         break;
30007088c10SChris Bieneman       }
30192874d28SXing GUO       case dwarf::DW_FORM_block2: {
30292874d28SXing GUO         writeInteger((uint16_t)FormVal->BlockData.size(), OS, IsLittleEndian);
30392874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
30492874d28SXing GUO                  FormVal->BlockData.size());
30592874d28SXing GUO         break;
30607088c10SChris Bieneman       }
30792874d28SXing GUO       case dwarf::DW_FORM_block4: {
30892874d28SXing GUO         writeInteger((uint32_t)FormVal->BlockData.size(), OS, IsLittleEndian);
30992874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
31092874d28SXing GUO                  FormVal->BlockData.size());
31192874d28SXing GUO         break;
31207088c10SChris Bieneman       }
31392874d28SXing GUO       case dwarf::DW_FORM_strx:
31492874d28SXing GUO       case dwarf::DW_FORM_addrx:
31592874d28SXing GUO       case dwarf::DW_FORM_rnglistx:
31692874d28SXing GUO       case dwarf::DW_FORM_loclistx:
31792874d28SXing GUO       case dwarf::DW_FORM_udata:
31892874d28SXing GUO       case dwarf::DW_FORM_ref_udata:
31992874d28SXing GUO       case dwarf::DW_FORM_GNU_addr_index:
32092874d28SXing GUO       case dwarf::DW_FORM_GNU_str_index:
32192874d28SXing GUO         encodeULEB128(FormVal->Value, OS);
32292874d28SXing GUO         break;
32392874d28SXing GUO       case dwarf::DW_FORM_data1:
32492874d28SXing GUO       case dwarf::DW_FORM_ref1:
32592874d28SXing GUO       case dwarf::DW_FORM_flag:
32692874d28SXing GUO       case dwarf::DW_FORM_strx1:
32792874d28SXing GUO       case dwarf::DW_FORM_addrx1:
32892874d28SXing GUO         writeInteger((uint8_t)FormVal->Value, OS, IsLittleEndian);
32992874d28SXing GUO         break;
33092874d28SXing GUO       case dwarf::DW_FORM_data2:
33192874d28SXing GUO       case dwarf::DW_FORM_ref2:
33292874d28SXing GUO       case dwarf::DW_FORM_strx2:
33392874d28SXing GUO       case dwarf::DW_FORM_addrx2:
33492874d28SXing GUO         writeInteger((uint16_t)FormVal->Value, OS, IsLittleEndian);
33592874d28SXing GUO         break;
33692874d28SXing GUO       case dwarf::DW_FORM_data4:
33792874d28SXing GUO       case dwarf::DW_FORM_ref4:
33892874d28SXing GUO       case dwarf::DW_FORM_ref_sup4:
33992874d28SXing GUO       case dwarf::DW_FORM_strx4:
34092874d28SXing GUO       case dwarf::DW_FORM_addrx4:
34192874d28SXing GUO         writeInteger((uint32_t)FormVal->Value, OS, IsLittleEndian);
34292874d28SXing GUO         break;
34392874d28SXing GUO       case dwarf::DW_FORM_data8:
34492874d28SXing GUO       case dwarf::DW_FORM_ref8:
34592874d28SXing GUO       case dwarf::DW_FORM_ref_sup8:
34692874d28SXing GUO       case dwarf::DW_FORM_ref_sig8:
34792874d28SXing GUO         writeInteger((uint64_t)FormVal->Value, OS, IsLittleEndian);
34892874d28SXing GUO         break;
34992874d28SXing GUO       case dwarf::DW_FORM_sdata:
35092874d28SXing GUO         encodeSLEB128(FormVal->Value, OS);
35192874d28SXing GUO         break;
35292874d28SXing GUO       case dwarf::DW_FORM_string:
35392874d28SXing GUO         OS.write(FormVal->CStr.data(), FormVal->CStr.size());
35407088c10SChris Bieneman         OS.write('\0');
35592874d28SXing GUO         break;
35692874d28SXing GUO       case dwarf::DW_FORM_indirect:
35792874d28SXing GUO         encodeULEB128(FormVal->Value, OS);
35892874d28SXing GUO         Indirect = true;
35992874d28SXing GUO         Form = static_cast<dwarf::Form>((uint64_t)FormVal->Value);
36092874d28SXing GUO         ++FormVal;
36192874d28SXing GUO         break;
36292874d28SXing GUO       case dwarf::DW_FORM_strp:
36392874d28SXing GUO       case dwarf::DW_FORM_sec_offset:
36492874d28SXing GUO       case dwarf::DW_FORM_GNU_ref_alt:
36592874d28SXing GUO       case dwarf::DW_FORM_GNU_strp_alt:
36692874d28SXing GUO       case dwarf::DW_FORM_line_strp:
36792874d28SXing GUO       case dwarf::DW_FORM_strp_sup:
368bbb057c4SXing GUO         cantFail(writeVariableSizedInteger(
369bbb057c4SXing GUO             FormVal->Value, Unit.FormParams.getDwarfOffsetByteSize(), OS,
370bbb057c4SXing GUO             IsLittleEndian));
37192874d28SXing GUO         break;
37292874d28SXing GUO       default:
37392874d28SXing GUO         break;
37492874d28SXing GUO       }
37592874d28SXing GUO     } while (Indirect);
37607088c10SChris Bieneman   }
3778f471f72SChris Bieneman 
37892874d28SXing GUO   return OS.tell() - EntryBegin;
37907088c10SChris Bieneman }
3808f471f72SChris Bieneman 
3819939f231SXing GUO Error DWARFYAML::emitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) {
38292874d28SXing GUO   for (const DWARFYAML::Unit &Unit : DI.CompileUnits) {
38392874d28SXing GUO     uint64_t Length = 3; // sizeof(version) + sizeof(address_size)
384bbb057c4SXing GUO     Length += Unit.FormParams.Version >= 5 ? 1 : 0; // sizeof(unit_type)
38592874d28SXing GUO     Length +=
386bbb057c4SXing GUO         Unit.FormParams.getDwarfOffsetByteSize(); // sizeof(debug_abbrev_offset)
38792874d28SXing GUO 
38892874d28SXing GUO     // Since the length of the current compilation unit is undetermined yet, we
38992874d28SXing GUO     // firstly write the content of the compilation unit to a buffer to
39092874d28SXing GUO     // calculate it and then serialize the buffer content to the actual output
39192874d28SXing GUO     // stream.
39292874d28SXing GUO     std::string EntryBuffer;
39392874d28SXing GUO     raw_string_ostream EntryBufferOS(EntryBuffer);
39492874d28SXing GUO 
39592874d28SXing GUO     for (const DWARFYAML::Entry &Entry : Unit.Entries) {
39692874d28SXing GUO       if (Expected<uint64_t> EntryLength = writeDIE(
39792874d28SXing GUO               DI.AbbrevDecls, Unit, Entry, EntryBufferOS, DI.IsLittleEndian))
39892874d28SXing GUO         Length += *EntryLength;
39992874d28SXing GUO       else
40092874d28SXing GUO         return EntryLength.takeError();
40192874d28SXing GUO     }
40292874d28SXing GUO 
40392874d28SXing GUO     // If the length is specified in the YAML description, we use it instead of
40492874d28SXing GUO     // the actual length.
40592874d28SXing GUO     if (Unit.Length)
40692874d28SXing GUO       Length = *Unit.Length;
40792874d28SXing GUO 
408bbb057c4SXing GUO     writeInitialLength(Unit.FormParams.Format, Length, OS, DI.IsLittleEndian);
409bbb057c4SXing GUO     writeInteger((uint16_t)Unit.FormParams.Version, OS, DI.IsLittleEndian);
410bbb057c4SXing GUO     if (Unit.FormParams.Version >= 5) {
41192874d28SXing GUO       writeInteger((uint8_t)Unit.Type, OS, DI.IsLittleEndian);
412bbb057c4SXing GUO       writeInteger((uint8_t)Unit.FormParams.AddrSize, OS, DI.IsLittleEndian);
413bbb057c4SXing GUO       writeDWARFOffset(Unit.AbbrOffset, Unit.FormParams.Format, OS,
414bbb057c4SXing GUO                        DI.IsLittleEndian);
41592874d28SXing GUO     } else {
416bbb057c4SXing GUO       writeDWARFOffset(Unit.AbbrOffset, Unit.FormParams.Format, OS,
417bbb057c4SXing GUO                        DI.IsLittleEndian);
418bbb057c4SXing GUO       writeInteger((uint8_t)Unit.FormParams.AddrSize, OS, DI.IsLittleEndian);
41992874d28SXing GUO     }
42092874d28SXing GUO 
42192874d28SXing GUO     OS.write(EntryBuffer.data(), EntryBuffer.size());
42292874d28SXing GUO   }
42392874d28SXing GUO 
42492874d28SXing GUO   return Error::success();
42507088c10SChris Bieneman }
42607088c10SChris Bieneman 
42767b4afc4SXing GUO static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
42807088c10SChris Bieneman   OS.write(File.Name.data(), File.Name.size());
42907088c10SChris Bieneman   OS.write('\0');
43007088c10SChris Bieneman   encodeULEB128(File.DirIdx, OS);
43107088c10SChris Bieneman   encodeULEB128(File.ModTime, OS);
43207088c10SChris Bieneman   encodeULEB128(File.Length, OS);
43307088c10SChris Bieneman }
43407088c10SChris Bieneman 
4359939f231SXing GUO Error DWARFYAML::emitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) {
436efcf06f5SBenjamin Kramer   for (const auto &LineTable : DI.DebugLines) {
4370431e4bcSXing GUO     writeInitialLength(LineTable.Format, LineTable.Length, OS,
4380431e4bcSXing GUO                        DI.IsLittleEndian);
4390431e4bcSXing GUO     uint64_t SizeOfPrologueLength = LineTable.Format == dwarf::DWARF64 ? 8 : 4;
44007088c10SChris Bieneman     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
4419aaa32cfSXing GUO     cantFail(writeVariableSizedInteger(
4429aaa32cfSXing GUO         LineTable.PrologueLength, SizeOfPrologueLength, OS, DI.IsLittleEndian));
44307088c10SChris Bieneman     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
44407088c10SChris Bieneman     if (LineTable.Version >= 4)
44507088c10SChris Bieneman       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
44607088c10SChris Bieneman     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
44707088c10SChris Bieneman     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
44807088c10SChris Bieneman     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
44907088c10SChris Bieneman     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
45007088c10SChris Bieneman 
45107088c10SChris Bieneman     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
45207088c10SChris Bieneman       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
45307088c10SChris Bieneman 
45407088c10SChris Bieneman     for (auto IncludeDir : LineTable.IncludeDirs) {
45507088c10SChris Bieneman       OS.write(IncludeDir.data(), IncludeDir.size());
45607088c10SChris Bieneman       OS.write('\0');
45707088c10SChris Bieneman     }
45807088c10SChris Bieneman     OS.write('\0');
45907088c10SChris Bieneman 
46007088c10SChris Bieneman     for (auto File : LineTable.Files)
46167b4afc4SXing GUO       emitFileEntry(OS, File);
46207088c10SChris Bieneman     OS.write('\0');
46307088c10SChris Bieneman 
46407088c10SChris Bieneman     for (auto Op : LineTable.Opcodes) {
46507088c10SChris Bieneman       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
46607088c10SChris Bieneman       if (Op.Opcode == 0) {
46707088c10SChris Bieneman         encodeULEB128(Op.ExtLen, OS);
46807088c10SChris Bieneman         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
46907088c10SChris Bieneman         switch (Op.SubOpcode) {
47007088c10SChris Bieneman         case dwarf::DW_LNE_set_address:
47107088c10SChris Bieneman         case dwarf::DW_LNE_set_discriminator:
4729aaa32cfSXing GUO           // TODO: Test this error.
4739aaa32cfSXing GUO           if (Error Err = writeVariableSizedInteger(
474bbb057c4SXing GUO                   Op.Data, DI.CompileUnits[0].FormParams.AddrSize, OS,
475bbb057c4SXing GUO                   DI.IsLittleEndian))
4769aaa32cfSXing GUO             return Err;
47707088c10SChris Bieneman           break;
47807088c10SChris Bieneman         case dwarf::DW_LNE_define_file:
47967b4afc4SXing GUO           emitFileEntry(OS, Op.FileEntry);
48007088c10SChris Bieneman           break;
48107088c10SChris Bieneman         case dwarf::DW_LNE_end_sequence:
48207088c10SChris Bieneman           break;
48307088c10SChris Bieneman         default:
48407088c10SChris Bieneman           for (auto OpByte : Op.UnknownOpcodeData)
48507088c10SChris Bieneman             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
48607088c10SChris Bieneman         }
48707088c10SChris Bieneman       } else if (Op.Opcode < LineTable.OpcodeBase) {
48807088c10SChris Bieneman         switch (Op.Opcode) {
48907088c10SChris Bieneman         case dwarf::DW_LNS_copy:
49007088c10SChris Bieneman         case dwarf::DW_LNS_negate_stmt:
49107088c10SChris Bieneman         case dwarf::DW_LNS_set_basic_block:
49207088c10SChris Bieneman         case dwarf::DW_LNS_const_add_pc:
49307088c10SChris Bieneman         case dwarf::DW_LNS_set_prologue_end:
49407088c10SChris Bieneman         case dwarf::DW_LNS_set_epilogue_begin:
49507088c10SChris Bieneman           break;
49607088c10SChris Bieneman 
49707088c10SChris Bieneman         case dwarf::DW_LNS_advance_pc:
49807088c10SChris Bieneman         case dwarf::DW_LNS_set_file:
49907088c10SChris Bieneman         case dwarf::DW_LNS_set_column:
50007088c10SChris Bieneman         case dwarf::DW_LNS_set_isa:
50107088c10SChris Bieneman           encodeULEB128(Op.Data, OS);
50207088c10SChris Bieneman           break;
50307088c10SChris Bieneman 
50407088c10SChris Bieneman         case dwarf::DW_LNS_advance_line:
50507088c10SChris Bieneman           encodeSLEB128(Op.SData, OS);
50607088c10SChris Bieneman           break;
50707088c10SChris Bieneman 
50807088c10SChris Bieneman         case dwarf::DW_LNS_fixed_advance_pc:
50907088c10SChris Bieneman           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
51007088c10SChris Bieneman           break;
51107088c10SChris Bieneman 
51207088c10SChris Bieneman         default:
51307088c10SChris Bieneman           for (auto OpData : Op.StandardOpcodeData) {
51407088c10SChris Bieneman             encodeULEB128(OpData, OS);
51507088c10SChris Bieneman           }
51607088c10SChris Bieneman         }
51707088c10SChris Bieneman       }
51807088c10SChris Bieneman     }
51907088c10SChris Bieneman   }
5209939f231SXing GUO 
5219939f231SXing GUO   return Error::success();
52207088c10SChris Bieneman }
5232e752db4SChris Bieneman 
5248aaeaddeSXing GUO Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) {
5258aaeaddeSXing GUO   for (const AddrTableEntry &TableEntry : DI.DebugAddr) {
5268aaeaddeSXing GUO     uint8_t AddrSize;
5278aaeaddeSXing GUO     if (TableEntry.AddrSize)
5288aaeaddeSXing GUO       AddrSize = *TableEntry.AddrSize;
5298aaeaddeSXing GUO     else
530830a7c2aSXing GUO       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
5318aaeaddeSXing GUO 
5328aaeaddeSXing GUO     uint64_t Length;
5338aaeaddeSXing GUO     if (TableEntry.Length)
5348aaeaddeSXing GUO       Length = (uint64_t)*TableEntry.Length;
5358aaeaddeSXing GUO     else
5368aaeaddeSXing GUO       // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
5378aaeaddeSXing GUO       Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
5388aaeaddeSXing GUO                        TableEntry.SegAddrPairs.size();
5398aaeaddeSXing GUO 
5408aaeaddeSXing GUO     writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian);
5418aaeaddeSXing GUO     writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian);
5428aaeaddeSXing GUO     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
5438aaeaddeSXing GUO     writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
5448aaeaddeSXing GUO 
5458aaeaddeSXing GUO     for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
5468aaeaddeSXing GUO       if (TableEntry.SegSelectorSize != 0)
5479aaa32cfSXing GUO         if (Error Err = writeVariableSizedInteger(Pair.Segment,
5489aaa32cfSXing GUO                                                   TableEntry.SegSelectorSize,
5499aaa32cfSXing GUO                                                   OS, DI.IsLittleEndian))
5509aaa32cfSXing GUO           return createStringError(errc::not_supported,
5519aaa32cfSXing GUO                                    "unable to write debug_addr segment: %s",
5529aaa32cfSXing GUO                                    toString(std::move(Err)).c_str());
5538aaeaddeSXing GUO       if (AddrSize != 0)
5549aaa32cfSXing GUO         if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
5559aaa32cfSXing GUO                                                   DI.IsLittleEndian))
5569aaa32cfSXing GUO           return createStringError(errc::not_supported,
5579aaa32cfSXing GUO                                    "unable to write debug_addr address: %s",
5589aaa32cfSXing GUO                                    toString(std::move(Err)).c_str());
5598aaeaddeSXing GUO     }
5608aaeaddeSXing GUO   }
5618aaeaddeSXing GUO 
5628aaeaddeSXing GUO   return Error::success();
5638aaeaddeSXing GUO }
5648aaeaddeSXing GUO 
56510478c9cSXing GUO Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) {
56610478c9cSXing GUO   assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
56710478c9cSXing GUO   for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
56810478c9cSXing GUO     uint64_t Length;
56910478c9cSXing GUO     if (Table.Length)
57010478c9cSXing GUO       Length = *Table.Length;
57110478c9cSXing GUO     else
57210478c9cSXing GUO       // sizeof(version) + sizeof(padding) = 4
57310478c9cSXing GUO       Length =
57410478c9cSXing GUO           4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
57510478c9cSXing GUO 
57610478c9cSXing GUO     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
57710478c9cSXing GUO     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
57810478c9cSXing GUO     writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian);
57910478c9cSXing GUO 
580367d0d4cSXing GUO     for (uint64_t Offset : Table.Offsets)
581367d0d4cSXing GUO       writeDWARFOffset(Offset, Table.Format, OS, DI.IsLittleEndian);
58210478c9cSXing GUO   }
58310478c9cSXing GUO 
58410478c9cSXing GUO   return Error::success();
58510478c9cSXing GUO }
58610478c9cSXing GUO 
5876784d82dSXing GUO static Error checkOperandCount(StringRef EncodingString,
588a997e6edSXing GUO                                ArrayRef<yaml::Hex64> Values,
589a997e6edSXing GUO                                uint64_t ExpectedOperands) {
590a997e6edSXing GUO   if (Values.size() != ExpectedOperands)
591a997e6edSXing GUO     return createStringError(
592a997e6edSXing GUO         errc::invalid_argument,
593a997e6edSXing GUO         "invalid number (%zu) of operands for the operator: %s, %" PRIu64
594a997e6edSXing GUO         " expected",
595a997e6edSXing GUO         Values.size(), EncodingString.str().c_str(), ExpectedOperands);
596a997e6edSXing GUO 
597a997e6edSXing GUO   return Error::success();
598a997e6edSXing GUO }
599a997e6edSXing GUO 
600a997e6edSXing GUO static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS,
601a997e6edSXing GUO                                    uint64_t Addr, uint8_t AddrSize,
602a997e6edSXing GUO                                    bool IsLittleEndian) {
603a997e6edSXing GUO   if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
604a997e6edSXing GUO     return createStringError(errc::invalid_argument,
605a997e6edSXing GUO                              "unable to write address for the operator %s: %s",
606a997e6edSXing GUO                              EncodingName.str().c_str(),
607a997e6edSXing GUO                              toString(std::move(Err)).c_str());
608a997e6edSXing GUO 
609a997e6edSXing GUO   return Error::success();
610a997e6edSXing GUO }
611a997e6edSXing GUO 
612c4cf250cSXing GUO static Expected<uint64_t> writeListEntry(raw_ostream &OS,
613c4cf250cSXing GUO                                          const DWARFYAML::RnglistEntry &Entry,
614c4cf250cSXing GUO                                          uint8_t AddrSize,
615c4cf250cSXing GUO                                          bool IsLittleEndian) {
6161ab3d6c8SXing GUO   uint64_t BeginOffset = OS.tell();
6171ab3d6c8SXing GUO   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
6181ab3d6c8SXing GUO 
619a997e6edSXing GUO   StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
6201ab3d6c8SXing GUO 
621a997e6edSXing GUO   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
6226784d82dSXing GUO     return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
6231ab3d6c8SXing GUO   };
6241ab3d6c8SXing GUO 
6251ab3d6c8SXing GUO   auto WriteAddress = [&](uint64_t Addr) -> Error {
626a997e6edSXing GUO     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
627a997e6edSXing GUO                                  IsLittleEndian);
6281ab3d6c8SXing GUO   };
6291ab3d6c8SXing GUO 
6301ab3d6c8SXing GUO   switch (Entry.Operator) {
6311ab3d6c8SXing GUO   case dwarf::DW_RLE_end_of_list:
6321ab3d6c8SXing GUO     if (Error Err = CheckOperands(0))
6331ab3d6c8SXing GUO       return std::move(Err);
6341ab3d6c8SXing GUO     break;
6351ab3d6c8SXing GUO   case dwarf::DW_RLE_base_addressx:
6361ab3d6c8SXing GUO     if (Error Err = CheckOperands(1))
6371ab3d6c8SXing GUO       return std::move(Err);
6381ab3d6c8SXing GUO     encodeULEB128(Entry.Values[0], OS);
6391ab3d6c8SXing GUO     break;
6401ab3d6c8SXing GUO   case dwarf::DW_RLE_startx_endx:
6411ab3d6c8SXing GUO   case dwarf::DW_RLE_startx_length:
6421ab3d6c8SXing GUO   case dwarf::DW_RLE_offset_pair:
6431ab3d6c8SXing GUO     if (Error Err = CheckOperands(2))
6441ab3d6c8SXing GUO       return std::move(Err);
6451ab3d6c8SXing GUO     encodeULEB128(Entry.Values[0], OS);
6461ab3d6c8SXing GUO     encodeULEB128(Entry.Values[1], OS);
6471ab3d6c8SXing GUO     break;
6481ab3d6c8SXing GUO   case dwarf::DW_RLE_base_address:
6491ab3d6c8SXing GUO     if (Error Err = CheckOperands(1))
6501ab3d6c8SXing GUO       return std::move(Err);
6511ab3d6c8SXing GUO     if (Error Err = WriteAddress(Entry.Values[0]))
6521ab3d6c8SXing GUO       return std::move(Err);
6531ab3d6c8SXing GUO     break;
6541ab3d6c8SXing GUO   case dwarf::DW_RLE_start_end:
6551ab3d6c8SXing GUO     if (Error Err = CheckOperands(2))
6561ab3d6c8SXing GUO       return std::move(Err);
6571ab3d6c8SXing GUO     if (Error Err = WriteAddress(Entry.Values[0]))
6581ab3d6c8SXing GUO       return std::move(Err);
6591ab3d6c8SXing GUO     cantFail(WriteAddress(Entry.Values[1]));
6601ab3d6c8SXing GUO     break;
6611ab3d6c8SXing GUO   case dwarf::DW_RLE_start_length:
6621ab3d6c8SXing GUO     if (Error Err = CheckOperands(2))
6631ab3d6c8SXing GUO       return std::move(Err);
6641ab3d6c8SXing GUO     if (Error Err = WriteAddress(Entry.Values[0]))
6651ab3d6c8SXing GUO       return std::move(Err);
6661ab3d6c8SXing GUO     encodeULEB128(Entry.Values[1], OS);
6671ab3d6c8SXing GUO     break;
6681ab3d6c8SXing GUO   }
6691ab3d6c8SXing GUO 
6701ab3d6c8SXing GUO   return OS.tell() - BeginOffset;
6711ab3d6c8SXing GUO }
6721ab3d6c8SXing GUO 
673c4cf250cSXing GUO template <typename EntryType>
674c4cf250cSXing GUO Error writeDWARFLists(raw_ostream &OS,
675c4cf250cSXing GUO                       ArrayRef<DWARFYAML::ListTable<EntryType>> Tables,
676c4cf250cSXing GUO                       bool IsLittleEndian, bool Is64BitAddrSize) {
677c4cf250cSXing GUO   for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
6781ab3d6c8SXing GUO     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
6791ab3d6c8SXing GUO     // sizeof(offset_entry_count) = 8
6801ab3d6c8SXing GUO     uint64_t Length = 8;
6811ab3d6c8SXing GUO 
6821ab3d6c8SXing GUO     uint8_t AddrSize;
6831ab3d6c8SXing GUO     if (Table.AddrSize)
6841ab3d6c8SXing GUO       AddrSize = *Table.AddrSize;
6851ab3d6c8SXing GUO     else
686c4cf250cSXing GUO       AddrSize = Is64BitAddrSize ? 8 : 4;
6871ab3d6c8SXing GUO 
688c4cf250cSXing GUO     // Since the length of the current range/location lists entry is
689c4cf250cSXing GUO     // undetermined yet, we firstly write the content of the range/location
690c4cf250cSXing GUO     // lists to a buffer to calculate the length and then serialize the buffer
691c4cf250cSXing GUO     // content to the actual output stream.
6921ab3d6c8SXing GUO     std::string ListBuffer;
6931ab3d6c8SXing GUO     raw_string_ostream ListBufferOS(ListBuffer);
6941ab3d6c8SXing GUO 
695c4cf250cSXing GUO     // Offsets holds offsets for each range/location list. The i-th element is
696c4cf250cSXing GUO     // the offset from the beginning of the first range/location list to the
697c4cf250cSXing GUO     // location of the i-th range list.
6981ab3d6c8SXing GUO     std::vector<uint64_t> Offsets;
6991ab3d6c8SXing GUO 
700c4cf250cSXing GUO     for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
7011ab3d6c8SXing GUO       Offsets.push_back(ListBufferOS.tell());
70222ec861dSXing GUO       if (List.Content) {
70322ec861dSXing GUO         List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
70422ec861dSXing GUO         Length += List.Content->binary_size();
70522ec861dSXing GUO       } else if (List.Entries) {
70622ec861dSXing GUO         for (const EntryType &Entry : *List.Entries) {
7071ab3d6c8SXing GUO           Expected<uint64_t> EntrySize =
708c4cf250cSXing GUO               writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
7091ab3d6c8SXing GUO           if (!EntrySize)
7101ab3d6c8SXing GUO             return EntrySize.takeError();
7111ab3d6c8SXing GUO           Length += *EntrySize;
7121ab3d6c8SXing GUO         }
7131ab3d6c8SXing GUO       }
71422ec861dSXing GUO     }
7151ab3d6c8SXing GUO 
7161ab3d6c8SXing GUO     // If the offset_entry_count field isn't specified, yaml2obj will infer it
7171ab3d6c8SXing GUO     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
7181ab3d6c8SXing GUO     // isn't specified either, yaml2obj will infer it from the auto-generated
7191ab3d6c8SXing GUO     // offsets.
7201ab3d6c8SXing GUO     uint32_t OffsetEntryCount;
7211ab3d6c8SXing GUO     if (Table.OffsetEntryCount)
7221ab3d6c8SXing GUO       OffsetEntryCount = *Table.OffsetEntryCount;
7231ab3d6c8SXing GUO     else
7241ab3d6c8SXing GUO       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
7251ab3d6c8SXing GUO     uint64_t OffsetsSize =
7261ab3d6c8SXing GUO         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
7271ab3d6c8SXing GUO     Length += OffsetsSize;
7281ab3d6c8SXing GUO 
7291ab3d6c8SXing GUO     // If the length is specified in the YAML description, we use it instead of
7301ab3d6c8SXing GUO     // the actual length.
7311ab3d6c8SXing GUO     if (Table.Length)
7321ab3d6c8SXing GUO       Length = *Table.Length;
7331ab3d6c8SXing GUO 
734c4cf250cSXing GUO     writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
735c4cf250cSXing GUO     writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
736c4cf250cSXing GUO     writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
737c4cf250cSXing GUO     writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
738c4cf250cSXing GUO     writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
7391ab3d6c8SXing GUO 
7401ab3d6c8SXing GUO     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
741367d0d4cSXing GUO       for (uint64_t Offset : Offsets)
742367d0d4cSXing GUO         writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
743367d0d4cSXing GUO                          IsLittleEndian);
7441ab3d6c8SXing GUO     };
7451ab3d6c8SXing GUO 
7461ab3d6c8SXing GUO     if (Table.Offsets)
7471ab3d6c8SXing GUO       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
7481ab3d6c8SXing GUO                                      Table.Offsets->size()),
7491ab3d6c8SXing GUO                   0);
7501ab3d6c8SXing GUO     else
7511ab3d6c8SXing GUO       EmitOffsets(Offsets, OffsetsSize);
7521ab3d6c8SXing GUO 
7531ab3d6c8SXing GUO     OS.write(ListBuffer.data(), ListBuffer.size());
7541ab3d6c8SXing GUO   }
7551ab3d6c8SXing GUO 
7561ab3d6c8SXing GUO   return Error::success();
7571ab3d6c8SXing GUO }
7581ab3d6c8SXing GUO 
759c4cf250cSXing GUO Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
760c4cf250cSXing GUO   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
761c4cf250cSXing GUO   return writeDWARFLists<DWARFYAML::RnglistEntry>(
762c4cf250cSXing GUO       OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize);
763c4cf250cSXing GUO }
764c4cf250cSXing GUO 
7659939f231SXing GUO using EmitFuncType = Error (*)(raw_ostream &, const DWARFYAML::Data &);
7662e752db4SChris Bieneman 
7679939f231SXing GUO static Error
76867b4afc4SXing GUO emitDebugSectionImpl(const DWARFYAML::Data &DI, EmitFuncType EmitFunc,
769efcf06f5SBenjamin Kramer                      StringRef Sec,
7702e752db4SChris Bieneman                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
7712e752db4SChris Bieneman   std::string Data;
7722e752db4SChris Bieneman   raw_string_ostream DebugInfoStream(Data);
7739939f231SXing GUO   if (Error Err = EmitFunc(DebugInfoStream, DI))
7749939f231SXing GUO     return Err;
7752e752db4SChris Bieneman   DebugInfoStream.flush();
7762e752db4SChris Bieneman   if (!Data.empty())
7772e752db4SChris Bieneman     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
7789939f231SXing GUO 
7799939f231SXing GUO   return Error::success();
7802e752db4SChris Bieneman }
7812e752db4SChris Bieneman 
7825c709edaSJonas Devlieghere Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
78392874d28SXing GUO DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian) {
7848f9ca561SXing GUO   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
7858f9ca561SXing GUO     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
7868f9ca561SXing GUO   };
7878f9ca561SXing GUO 
7888f9ca561SXing GUO   SMDiagnostic GeneratedDiag;
7898f9ca561SXing GUO   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
7908f9ca561SXing GUO                   &GeneratedDiag);
7912e752db4SChris Bieneman 
7922e752db4SChris Bieneman   DWARFYAML::Data DI;
7932e752db4SChris Bieneman   DI.IsLittleEndian = IsLittleEndian;
7942e752db4SChris Bieneman   YIn >> DI;
7952e752db4SChris Bieneman   if (YIn.error())
7968f9ca561SXing GUO     return createStringError(YIn.error(), GeneratedDiag.getMessage());
7972e752db4SChris Bieneman 
7985c709edaSJonas Devlieghere   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
7999939f231SXing GUO   Error Err = emitDebugSectionImpl(DI, &DWARFYAML::emitDebugInfo, "debug_info",
8002e752db4SChris Bieneman                                    DebugSections);
8019939f231SXing GUO   Err = joinErrors(std::move(Err),
8029939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugLine,
8039939f231SXing GUO                                         "debug_line", DebugSections));
8049939f231SXing GUO   Err = joinErrors(std::move(Err),
8059939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugStr,
8069939f231SXing GUO                                         "debug_str", DebugSections));
8079939f231SXing GUO   Err = joinErrors(std::move(Err),
8089939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugAbbrev,
8099939f231SXing GUO                                         "debug_abbrev", DebugSections));
8109939f231SXing GUO   Err = joinErrors(std::move(Err),
8119939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugAranges,
8129939f231SXing GUO                                         "debug_aranges", DebugSections));
8139939f231SXing GUO   Err = joinErrors(std::move(Err),
8149939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugRanges,
8159939f231SXing GUO                                         "debug_ranges", DebugSections));
8169939f231SXing GUO 
8179939f231SXing GUO   if (Err)
8189939f231SXing GUO     return std::move(Err);
819c55cf4afSBill Wendling   return std::move(DebugSections);
8202e752db4SChris Bieneman }
821