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) {
12907088c10SChris Bieneman     auto HeaderStart = OS.tell();
130613c4a87SXing GUO     writeInitialLength(Range.Format, Range.Length, OS, DI.IsLittleEndian);
13107088c10SChris Bieneman     writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian);
132367d0d4cSXing GUO     writeDWARFOffset(Range.CuOffset, Range.Format, OS, DI.IsLittleEndian);
13307088c10SChris Bieneman     writeInteger((uint8_t)Range.AddrSize, OS, DI.IsLittleEndian);
13407088c10SChris Bieneman     writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
13507088c10SChris Bieneman 
13607088c10SChris Bieneman     auto HeaderSize = OS.tell() - HeaderStart;
13707088c10SChris Bieneman     auto FirstDescriptor = alignTo(HeaderSize, Range.AddrSize * 2);
13807088c10SChris Bieneman     ZeroFillBytes(OS, FirstDescriptor - HeaderSize);
13907088c10SChris Bieneman 
14007088c10SChris Bieneman     for (auto Descriptor : Range.Descriptors) {
1419aaa32cfSXing GUO       if (Error Err = writeVariableSizedInteger(
1429aaa32cfSXing GUO               Descriptor.Address, Range.AddrSize, OS, DI.IsLittleEndian))
1439aaa32cfSXing GUO         return createStringError(errc::not_supported,
1449aaa32cfSXing GUO                                  "unable to write debug_aranges address: %s",
1459aaa32cfSXing GUO                                  toString(std::move(Err)).c_str());
1469aaa32cfSXing GUO       cantFail(writeVariableSizedInteger(Descriptor.Length, Range.AddrSize, OS,
1479aaa32cfSXing GUO                                          DI.IsLittleEndian));
14807088c10SChris Bieneman     }
14907088c10SChris Bieneman     ZeroFillBytes(OS, Range.AddrSize * 2);
15007088c10SChris Bieneman   }
1519939f231SXing GUO 
1529939f231SXing GUO   return Error::success();
15307088c10SChris Bieneman }
15407088c10SChris Bieneman 
1559939f231SXing GUO Error DWARFYAML::emitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) {
1566025fc22SGreg Clayton   const size_t RangesOffset = OS.tell();
157e4344e14SXing GUO   uint64_t EntryIndex = 0;
1586e73f12aSGreg Clayton   for (auto DebugRanges : DI.DebugRanges) {
1596025fc22SGreg Clayton     const size_t CurrOffset = OS.tell() - RangesOffset;
16099c23354SXing GUO     if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset)
161e4344e14SXing GUO       return createStringError(errc::invalid_argument,
162e4344e14SXing GUO                                "'Offset' for 'debug_ranges' with index " +
163e4344e14SXing GUO                                    Twine(EntryIndex) +
164e4344e14SXing GUO                                    " must be greater than or equal to the "
165e4344e14SXing GUO                                    "number of bytes written already (0x" +
166e4344e14SXing GUO                                    Twine::utohexstr(CurrOffset) + ")");
16799c23354SXing GUO     if (DebugRanges.Offset)
16899c23354SXing GUO       ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset);
169ff9c1ae2SXing GUO 
170ff9c1ae2SXing GUO     uint8_t AddrSize;
171ff9c1ae2SXing GUO     if (DebugRanges.AddrSize)
172ff9c1ae2SXing GUO       AddrSize = *DebugRanges.AddrSize;
173ff9c1ae2SXing GUO     else
174830a7c2aSXing GUO       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
1756e73f12aSGreg Clayton     for (auto Entry : DebugRanges.Entries) {
1769aaa32cfSXing GUO       if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS,
1779aaa32cfSXing GUO                                                 DI.IsLittleEndian))
1789aaa32cfSXing GUO         return createStringError(
1799aaa32cfSXing GUO             errc::not_supported,
1809aaa32cfSXing GUO             "unable to write debug_ranges address offset: %s",
1819aaa32cfSXing GUO             toString(std::move(Err)).c_str());
1829aaa32cfSXing GUO       cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS,
1839aaa32cfSXing GUO                                          DI.IsLittleEndian));
1846025fc22SGreg Clayton     }
185ff9c1ae2SXing GUO     ZeroFillBytes(OS, AddrSize * 2);
186e4344e14SXing GUO     ++EntryIndex;
1876025fc22SGreg Clayton   }
1889939f231SXing GUO 
1899939f231SXing GUO   return Error::success();
1906025fc22SGreg Clayton }
1916025fc22SGreg Clayton 
1929939f231SXing GUO Error DWARFYAML::emitPubSection(raw_ostream &OS,
19307088c10SChris Bieneman                                 const DWARFYAML::PubSection &Sect,
194b6f08b7cSXing GUO                                 bool IsLittleEndian, bool IsGNUPubSec) {
195faf1feb5SChris Bieneman   writeInitialLength(Sect.Length, OS, IsLittleEndian);
19607088c10SChris Bieneman   writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
19707088c10SChris Bieneman   writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
19807088c10SChris Bieneman   writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
19907088c10SChris Bieneman   for (auto Entry : Sect.Entries) {
20007088c10SChris Bieneman     writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
201b6f08b7cSXing GUO     if (IsGNUPubSec)
20293bc571dSXing GUO       writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian);
20307088c10SChris Bieneman     OS.write(Entry.Name.data(), Entry.Name.size());
20407088c10SChris Bieneman     OS.write('\0');
20507088c10SChris Bieneman   }
2069939f231SXing GUO 
2079939f231SXing GUO   return Error::success();
20807088c10SChris Bieneman }
20907088c10SChris Bieneman 
21092874d28SXing GUO static Expected<uint64_t> writeDIE(ArrayRef<DWARFYAML::Abbrev> AbbrevDecls,
21192874d28SXing GUO                                    const DWARFYAML::Unit &Unit,
21292874d28SXing GUO                                    const DWARFYAML::Entry &Entry,
21392874d28SXing GUO                                    raw_ostream &OS, bool IsLittleEndian) {
21492874d28SXing GUO   uint64_t EntryBegin = OS.tell();
21592874d28SXing GUO   encodeULEB128(Entry.AbbrCode, OS);
21692874d28SXing GUO   uint32_t AbbrCode = Entry.AbbrCode;
21792874d28SXing GUO   if (AbbrCode == 0 || Entry.Values.empty())
21892874d28SXing GUO     return OS.tell() - EntryBegin;
21907088c10SChris Bieneman 
22092874d28SXing GUO   if (AbbrCode > AbbrevDecls.size())
22192874d28SXing GUO     return createStringError(
22292874d28SXing GUO         errc::invalid_argument,
22392874d28SXing GUO         "abbrev code must be less than or equal to the number of "
22492874d28SXing GUO         "entries in abbreviation table");
22592874d28SXing GUO   const DWARFYAML::Abbrev &Abbrev = AbbrevDecls[AbbrCode - 1];
22692874d28SXing GUO   auto FormVal = Entry.Values.begin();
22792874d28SXing GUO   auto AbbrForm = Abbrev.Attributes.begin();
22892874d28SXing GUO   for (; FormVal != Entry.Values.end() && AbbrForm != Abbrev.Attributes.end();
22992874d28SXing GUO        ++FormVal, ++AbbrForm) {
23092874d28SXing GUO     dwarf::Form Form = AbbrForm->Form;
23192874d28SXing GUO     bool Indirect;
23292874d28SXing GUO     do {
23392874d28SXing GUO       Indirect = false;
23492874d28SXing GUO       switch (Form) {
23592874d28SXing GUO       case dwarf::DW_FORM_addr:
23692874d28SXing GUO         // TODO: Test this error.
237bbb057c4SXing GUO         if (Error Err = writeVariableSizedInteger(
238bbb057c4SXing GUO                 FormVal->Value, Unit.FormParams.AddrSize, OS, IsLittleEndian))
23992874d28SXing GUO           return std::move(Err);
24092874d28SXing GUO         break;
24192874d28SXing GUO       case dwarf::DW_FORM_ref_addr:
24292874d28SXing GUO         // TODO: Test this error.
24392874d28SXing GUO         if (Error Err = writeVariableSizedInteger(
244bbb057c4SXing GUO                 FormVal->Value, Unit.FormParams.getRefAddrByteSize(), OS,
245bbb057c4SXing GUO                 IsLittleEndian))
24692874d28SXing GUO           return std::move(Err);
24792874d28SXing GUO         break;
24892874d28SXing GUO       case dwarf::DW_FORM_exprloc:
24992874d28SXing GUO       case dwarf::DW_FORM_block:
25092874d28SXing GUO         encodeULEB128(FormVal->BlockData.size(), OS);
25192874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
25292874d28SXing GUO                  FormVal->BlockData.size());
25392874d28SXing GUO         break;
25492874d28SXing GUO       case dwarf::DW_FORM_block1: {
25592874d28SXing GUO         writeInteger((uint8_t)FormVal->BlockData.size(), OS, IsLittleEndian);
25692874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
25792874d28SXing GUO                  FormVal->BlockData.size());
25892874d28SXing GUO         break;
25907088c10SChris Bieneman       }
26092874d28SXing GUO       case dwarf::DW_FORM_block2: {
26192874d28SXing GUO         writeInteger((uint16_t)FormVal->BlockData.size(), OS, IsLittleEndian);
26292874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
26392874d28SXing GUO                  FormVal->BlockData.size());
26492874d28SXing GUO         break;
26507088c10SChris Bieneman       }
26692874d28SXing GUO       case dwarf::DW_FORM_block4: {
26792874d28SXing GUO         writeInteger((uint32_t)FormVal->BlockData.size(), OS, IsLittleEndian);
26892874d28SXing GUO         OS.write((const char *)FormVal->BlockData.data(),
26992874d28SXing GUO                  FormVal->BlockData.size());
27092874d28SXing GUO         break;
27107088c10SChris Bieneman       }
27292874d28SXing GUO       case dwarf::DW_FORM_strx:
27392874d28SXing GUO       case dwarf::DW_FORM_addrx:
27492874d28SXing GUO       case dwarf::DW_FORM_rnglistx:
27592874d28SXing GUO       case dwarf::DW_FORM_loclistx:
27692874d28SXing GUO       case dwarf::DW_FORM_udata:
27792874d28SXing GUO       case dwarf::DW_FORM_ref_udata:
27892874d28SXing GUO       case dwarf::DW_FORM_GNU_addr_index:
27992874d28SXing GUO       case dwarf::DW_FORM_GNU_str_index:
28092874d28SXing GUO         encodeULEB128(FormVal->Value, OS);
28192874d28SXing GUO         break;
28292874d28SXing GUO       case dwarf::DW_FORM_data1:
28392874d28SXing GUO       case dwarf::DW_FORM_ref1:
28492874d28SXing GUO       case dwarf::DW_FORM_flag:
28592874d28SXing GUO       case dwarf::DW_FORM_strx1:
28692874d28SXing GUO       case dwarf::DW_FORM_addrx1:
28792874d28SXing GUO         writeInteger((uint8_t)FormVal->Value, OS, IsLittleEndian);
28892874d28SXing GUO         break;
28992874d28SXing GUO       case dwarf::DW_FORM_data2:
29092874d28SXing GUO       case dwarf::DW_FORM_ref2:
29192874d28SXing GUO       case dwarf::DW_FORM_strx2:
29292874d28SXing GUO       case dwarf::DW_FORM_addrx2:
29392874d28SXing GUO         writeInteger((uint16_t)FormVal->Value, OS, IsLittleEndian);
29492874d28SXing GUO         break;
29592874d28SXing GUO       case dwarf::DW_FORM_data4:
29692874d28SXing GUO       case dwarf::DW_FORM_ref4:
29792874d28SXing GUO       case dwarf::DW_FORM_ref_sup4:
29892874d28SXing GUO       case dwarf::DW_FORM_strx4:
29992874d28SXing GUO       case dwarf::DW_FORM_addrx4:
30092874d28SXing GUO         writeInteger((uint32_t)FormVal->Value, OS, IsLittleEndian);
30192874d28SXing GUO         break;
30292874d28SXing GUO       case dwarf::DW_FORM_data8:
30392874d28SXing GUO       case dwarf::DW_FORM_ref8:
30492874d28SXing GUO       case dwarf::DW_FORM_ref_sup8:
30592874d28SXing GUO       case dwarf::DW_FORM_ref_sig8:
30692874d28SXing GUO         writeInteger((uint64_t)FormVal->Value, OS, IsLittleEndian);
30792874d28SXing GUO         break;
30892874d28SXing GUO       case dwarf::DW_FORM_sdata:
30992874d28SXing GUO         encodeSLEB128(FormVal->Value, OS);
31092874d28SXing GUO         break;
31192874d28SXing GUO       case dwarf::DW_FORM_string:
31292874d28SXing GUO         OS.write(FormVal->CStr.data(), FormVal->CStr.size());
31307088c10SChris Bieneman         OS.write('\0');
31492874d28SXing GUO         break;
31592874d28SXing GUO       case dwarf::DW_FORM_indirect:
31692874d28SXing GUO         encodeULEB128(FormVal->Value, OS);
31792874d28SXing GUO         Indirect = true;
31892874d28SXing GUO         Form = static_cast<dwarf::Form>((uint64_t)FormVal->Value);
31992874d28SXing GUO         ++FormVal;
32092874d28SXing GUO         break;
32192874d28SXing GUO       case dwarf::DW_FORM_strp:
32292874d28SXing GUO       case dwarf::DW_FORM_sec_offset:
32392874d28SXing GUO       case dwarf::DW_FORM_GNU_ref_alt:
32492874d28SXing GUO       case dwarf::DW_FORM_GNU_strp_alt:
32592874d28SXing GUO       case dwarf::DW_FORM_line_strp:
32692874d28SXing GUO       case dwarf::DW_FORM_strp_sup:
327bbb057c4SXing GUO         cantFail(writeVariableSizedInteger(
328bbb057c4SXing GUO             FormVal->Value, Unit.FormParams.getDwarfOffsetByteSize(), OS,
329bbb057c4SXing GUO             IsLittleEndian));
33092874d28SXing GUO         break;
33192874d28SXing GUO       default:
33292874d28SXing GUO         break;
33392874d28SXing GUO       }
33492874d28SXing GUO     } while (Indirect);
33507088c10SChris Bieneman   }
3368f471f72SChris Bieneman 
33792874d28SXing GUO   return OS.tell() - EntryBegin;
33807088c10SChris Bieneman }
3398f471f72SChris Bieneman 
3409939f231SXing GUO Error DWARFYAML::emitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) {
34192874d28SXing GUO   for (const DWARFYAML::Unit &Unit : DI.CompileUnits) {
34292874d28SXing GUO     uint64_t Length = 3; // sizeof(version) + sizeof(address_size)
343bbb057c4SXing GUO     Length += Unit.FormParams.Version >= 5 ? 1 : 0; // sizeof(unit_type)
34492874d28SXing GUO     Length +=
345bbb057c4SXing GUO         Unit.FormParams.getDwarfOffsetByteSize(); // sizeof(debug_abbrev_offset)
34692874d28SXing GUO 
34792874d28SXing GUO     // Since the length of the current compilation unit is undetermined yet, we
34892874d28SXing GUO     // firstly write the content of the compilation unit to a buffer to
34992874d28SXing GUO     // calculate it and then serialize the buffer content to the actual output
35092874d28SXing GUO     // stream.
35192874d28SXing GUO     std::string EntryBuffer;
35292874d28SXing GUO     raw_string_ostream EntryBufferOS(EntryBuffer);
35392874d28SXing GUO 
35492874d28SXing GUO     for (const DWARFYAML::Entry &Entry : Unit.Entries) {
35592874d28SXing GUO       if (Expected<uint64_t> EntryLength = writeDIE(
35692874d28SXing GUO               DI.AbbrevDecls, Unit, Entry, EntryBufferOS, DI.IsLittleEndian))
35792874d28SXing GUO         Length += *EntryLength;
35892874d28SXing GUO       else
35992874d28SXing GUO         return EntryLength.takeError();
36092874d28SXing GUO     }
36192874d28SXing GUO 
36292874d28SXing GUO     // If the length is specified in the YAML description, we use it instead of
36392874d28SXing GUO     // the actual length.
36492874d28SXing GUO     if (Unit.Length)
36592874d28SXing GUO       Length = *Unit.Length;
36692874d28SXing GUO 
367bbb057c4SXing GUO     writeInitialLength(Unit.FormParams.Format, Length, OS, DI.IsLittleEndian);
368bbb057c4SXing GUO     writeInteger((uint16_t)Unit.FormParams.Version, OS, DI.IsLittleEndian);
369bbb057c4SXing GUO     if (Unit.FormParams.Version >= 5) {
37092874d28SXing GUO       writeInteger((uint8_t)Unit.Type, OS, DI.IsLittleEndian);
371bbb057c4SXing GUO       writeInteger((uint8_t)Unit.FormParams.AddrSize, OS, DI.IsLittleEndian);
372bbb057c4SXing GUO       writeDWARFOffset(Unit.AbbrOffset, Unit.FormParams.Format, OS,
373bbb057c4SXing GUO                        DI.IsLittleEndian);
37492874d28SXing GUO     } else {
375bbb057c4SXing GUO       writeDWARFOffset(Unit.AbbrOffset, Unit.FormParams.Format, OS,
376bbb057c4SXing GUO                        DI.IsLittleEndian);
377bbb057c4SXing GUO       writeInteger((uint8_t)Unit.FormParams.AddrSize, OS, DI.IsLittleEndian);
37892874d28SXing GUO     }
37992874d28SXing GUO 
38092874d28SXing GUO     OS.write(EntryBuffer.data(), EntryBuffer.size());
38192874d28SXing GUO   }
38292874d28SXing GUO 
38392874d28SXing GUO   return Error::success();
38407088c10SChris Bieneman }
38507088c10SChris Bieneman 
38667b4afc4SXing GUO static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
38707088c10SChris Bieneman   OS.write(File.Name.data(), File.Name.size());
38807088c10SChris Bieneman   OS.write('\0');
38907088c10SChris Bieneman   encodeULEB128(File.DirIdx, OS);
39007088c10SChris Bieneman   encodeULEB128(File.ModTime, OS);
39107088c10SChris Bieneman   encodeULEB128(File.Length, OS);
39207088c10SChris Bieneman }
39307088c10SChris Bieneman 
3949939f231SXing GUO Error DWARFYAML::emitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) {
395efcf06f5SBenjamin Kramer   for (const auto &LineTable : DI.DebugLines) {
3960431e4bcSXing GUO     writeInitialLength(LineTable.Format, LineTable.Length, OS,
3970431e4bcSXing GUO                        DI.IsLittleEndian);
3980431e4bcSXing GUO     uint64_t SizeOfPrologueLength = LineTable.Format == dwarf::DWARF64 ? 8 : 4;
39907088c10SChris Bieneman     writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian);
4009aaa32cfSXing GUO     cantFail(writeVariableSizedInteger(
4019aaa32cfSXing GUO         LineTable.PrologueLength, SizeOfPrologueLength, OS, DI.IsLittleEndian));
40207088c10SChris Bieneman     writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian);
40307088c10SChris Bieneman     if (LineTable.Version >= 4)
40407088c10SChris Bieneman       writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian);
40507088c10SChris Bieneman     writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian);
40607088c10SChris Bieneman     writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian);
40707088c10SChris Bieneman     writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian);
40807088c10SChris Bieneman     writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian);
40907088c10SChris Bieneman 
41007088c10SChris Bieneman     for (auto OpcodeLength : LineTable.StandardOpcodeLengths)
41107088c10SChris Bieneman       writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian);
41207088c10SChris Bieneman 
41307088c10SChris Bieneman     for (auto IncludeDir : LineTable.IncludeDirs) {
41407088c10SChris Bieneman       OS.write(IncludeDir.data(), IncludeDir.size());
41507088c10SChris Bieneman       OS.write('\0');
41607088c10SChris Bieneman     }
41707088c10SChris Bieneman     OS.write('\0');
41807088c10SChris Bieneman 
41907088c10SChris Bieneman     for (auto File : LineTable.Files)
42067b4afc4SXing GUO       emitFileEntry(OS, File);
42107088c10SChris Bieneman     OS.write('\0');
42207088c10SChris Bieneman 
42307088c10SChris Bieneman     for (auto Op : LineTable.Opcodes) {
42407088c10SChris Bieneman       writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian);
42507088c10SChris Bieneman       if (Op.Opcode == 0) {
42607088c10SChris Bieneman         encodeULEB128(Op.ExtLen, OS);
42707088c10SChris Bieneman         writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian);
42807088c10SChris Bieneman         switch (Op.SubOpcode) {
42907088c10SChris Bieneman         case dwarf::DW_LNE_set_address:
43007088c10SChris Bieneman         case dwarf::DW_LNE_set_discriminator:
4319aaa32cfSXing GUO           // TODO: Test this error.
4329aaa32cfSXing GUO           if (Error Err = writeVariableSizedInteger(
433bbb057c4SXing GUO                   Op.Data, DI.CompileUnits[0].FormParams.AddrSize, OS,
434bbb057c4SXing GUO                   DI.IsLittleEndian))
4359aaa32cfSXing GUO             return Err;
43607088c10SChris Bieneman           break;
43707088c10SChris Bieneman         case dwarf::DW_LNE_define_file:
43867b4afc4SXing GUO           emitFileEntry(OS, Op.FileEntry);
43907088c10SChris Bieneman           break;
44007088c10SChris Bieneman         case dwarf::DW_LNE_end_sequence:
44107088c10SChris Bieneman           break;
44207088c10SChris Bieneman         default:
44307088c10SChris Bieneman           for (auto OpByte : Op.UnknownOpcodeData)
44407088c10SChris Bieneman             writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian);
44507088c10SChris Bieneman         }
44607088c10SChris Bieneman       } else if (Op.Opcode < LineTable.OpcodeBase) {
44707088c10SChris Bieneman         switch (Op.Opcode) {
44807088c10SChris Bieneman         case dwarf::DW_LNS_copy:
44907088c10SChris Bieneman         case dwarf::DW_LNS_negate_stmt:
45007088c10SChris Bieneman         case dwarf::DW_LNS_set_basic_block:
45107088c10SChris Bieneman         case dwarf::DW_LNS_const_add_pc:
45207088c10SChris Bieneman         case dwarf::DW_LNS_set_prologue_end:
45307088c10SChris Bieneman         case dwarf::DW_LNS_set_epilogue_begin:
45407088c10SChris Bieneman           break;
45507088c10SChris Bieneman 
45607088c10SChris Bieneman         case dwarf::DW_LNS_advance_pc:
45707088c10SChris Bieneman         case dwarf::DW_LNS_set_file:
45807088c10SChris Bieneman         case dwarf::DW_LNS_set_column:
45907088c10SChris Bieneman         case dwarf::DW_LNS_set_isa:
46007088c10SChris Bieneman           encodeULEB128(Op.Data, OS);
46107088c10SChris Bieneman           break;
46207088c10SChris Bieneman 
46307088c10SChris Bieneman         case dwarf::DW_LNS_advance_line:
46407088c10SChris Bieneman           encodeSLEB128(Op.SData, OS);
46507088c10SChris Bieneman           break;
46607088c10SChris Bieneman 
46707088c10SChris Bieneman         case dwarf::DW_LNS_fixed_advance_pc:
46807088c10SChris Bieneman           writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian);
46907088c10SChris Bieneman           break;
47007088c10SChris Bieneman 
47107088c10SChris Bieneman         default:
47207088c10SChris Bieneman           for (auto OpData : Op.StandardOpcodeData) {
47307088c10SChris Bieneman             encodeULEB128(OpData, OS);
47407088c10SChris Bieneman           }
47507088c10SChris Bieneman         }
47607088c10SChris Bieneman       }
47707088c10SChris Bieneman     }
47807088c10SChris Bieneman   }
4799939f231SXing GUO 
4809939f231SXing GUO   return Error::success();
48107088c10SChris Bieneman }
4822e752db4SChris Bieneman 
4838aaeaddeSXing GUO Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) {
4848aaeaddeSXing GUO   for (const AddrTableEntry &TableEntry : DI.DebugAddr) {
4858aaeaddeSXing GUO     uint8_t AddrSize;
4868aaeaddeSXing GUO     if (TableEntry.AddrSize)
4878aaeaddeSXing GUO       AddrSize = *TableEntry.AddrSize;
4888aaeaddeSXing GUO     else
489830a7c2aSXing GUO       AddrSize = DI.Is64BitAddrSize ? 8 : 4;
4908aaeaddeSXing GUO 
4918aaeaddeSXing GUO     uint64_t Length;
4928aaeaddeSXing GUO     if (TableEntry.Length)
4938aaeaddeSXing GUO       Length = (uint64_t)*TableEntry.Length;
4948aaeaddeSXing GUO     else
4958aaeaddeSXing GUO       // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
4968aaeaddeSXing GUO       Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
4978aaeaddeSXing GUO                        TableEntry.SegAddrPairs.size();
4988aaeaddeSXing GUO 
4998aaeaddeSXing GUO     writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian);
5008aaeaddeSXing GUO     writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian);
5018aaeaddeSXing GUO     writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
5028aaeaddeSXing GUO     writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
5038aaeaddeSXing GUO 
5048aaeaddeSXing GUO     for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
5058aaeaddeSXing GUO       if (TableEntry.SegSelectorSize != 0)
5069aaa32cfSXing GUO         if (Error Err = writeVariableSizedInteger(Pair.Segment,
5079aaa32cfSXing GUO                                                   TableEntry.SegSelectorSize,
5089aaa32cfSXing GUO                                                   OS, DI.IsLittleEndian))
5099aaa32cfSXing GUO           return createStringError(errc::not_supported,
5109aaa32cfSXing GUO                                    "unable to write debug_addr segment: %s",
5119aaa32cfSXing GUO                                    toString(std::move(Err)).c_str());
5128aaeaddeSXing GUO       if (AddrSize != 0)
5139aaa32cfSXing GUO         if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
5149aaa32cfSXing GUO                                                   DI.IsLittleEndian))
5159aaa32cfSXing GUO           return createStringError(errc::not_supported,
5169aaa32cfSXing GUO                                    "unable to write debug_addr address: %s",
5179aaa32cfSXing GUO                                    toString(std::move(Err)).c_str());
5188aaeaddeSXing GUO     }
5198aaeaddeSXing GUO   }
5208aaeaddeSXing GUO 
5218aaeaddeSXing GUO   return Error::success();
5228aaeaddeSXing GUO }
5238aaeaddeSXing GUO 
52410478c9cSXing GUO Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) {
52510478c9cSXing GUO   assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
52610478c9cSXing GUO   for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
52710478c9cSXing GUO     uint64_t Length;
52810478c9cSXing GUO     if (Table.Length)
52910478c9cSXing GUO       Length = *Table.Length;
53010478c9cSXing GUO     else
53110478c9cSXing GUO       // sizeof(version) + sizeof(padding) = 4
53210478c9cSXing GUO       Length =
53310478c9cSXing GUO           4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
53410478c9cSXing GUO 
53510478c9cSXing GUO     writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian);
53610478c9cSXing GUO     writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian);
53710478c9cSXing GUO     writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian);
53810478c9cSXing GUO 
539367d0d4cSXing GUO     for (uint64_t Offset : Table.Offsets)
540367d0d4cSXing GUO       writeDWARFOffset(Offset, Table.Format, OS, DI.IsLittleEndian);
54110478c9cSXing GUO   }
54210478c9cSXing GUO 
54310478c9cSXing GUO   return Error::success();
54410478c9cSXing GUO }
54510478c9cSXing GUO 
546a997e6edSXing GUO static Error checkListEntryOperands(StringRef EncodingString,
547a997e6edSXing GUO                                     ArrayRef<yaml::Hex64> Values,
548a997e6edSXing GUO                                     uint64_t ExpectedOperands) {
549a997e6edSXing GUO   if (Values.size() != ExpectedOperands)
550a997e6edSXing GUO     return createStringError(
551a997e6edSXing GUO         errc::invalid_argument,
552a997e6edSXing GUO         "invalid number (%zu) of operands for the operator: %s, %" PRIu64
553a997e6edSXing GUO         " expected",
554a997e6edSXing GUO         Values.size(), EncodingString.str().c_str(), ExpectedOperands);
555a997e6edSXing GUO 
556a997e6edSXing GUO   return Error::success();
557a997e6edSXing GUO }
558a997e6edSXing GUO 
559a997e6edSXing GUO static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS,
560a997e6edSXing GUO                                    uint64_t Addr, uint8_t AddrSize,
561a997e6edSXing GUO                                    bool IsLittleEndian) {
562a997e6edSXing GUO   if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
563a997e6edSXing GUO     return createStringError(errc::invalid_argument,
564a997e6edSXing GUO                              "unable to write address for the operator %s: %s",
565a997e6edSXing GUO                              EncodingName.str().c_str(),
566a997e6edSXing GUO                              toString(std::move(Err)).c_str());
567a997e6edSXing GUO 
568a997e6edSXing GUO   return Error::success();
569a997e6edSXing GUO }
570a997e6edSXing GUO 
571c4cf250cSXing GUO static Expected<uint64_t> writeListEntry(raw_ostream &OS,
572c4cf250cSXing GUO                                          const DWARFYAML::RnglistEntry &Entry,
573c4cf250cSXing GUO                                          uint8_t AddrSize,
574c4cf250cSXing GUO                                          bool IsLittleEndian) {
5751ab3d6c8SXing GUO   uint64_t BeginOffset = OS.tell();
5761ab3d6c8SXing GUO   writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
5771ab3d6c8SXing GUO 
578a997e6edSXing GUO   StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
5791ab3d6c8SXing GUO 
580a997e6edSXing GUO   auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
581a997e6edSXing GUO     return checkListEntryOperands(EncodingName, Entry.Values, ExpectedOperands);
5821ab3d6c8SXing GUO   };
5831ab3d6c8SXing GUO 
5841ab3d6c8SXing GUO   auto WriteAddress = [&](uint64_t Addr) -> Error {
585a997e6edSXing GUO     return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
586a997e6edSXing GUO                                  IsLittleEndian);
5871ab3d6c8SXing GUO   };
5881ab3d6c8SXing GUO 
5891ab3d6c8SXing GUO   switch (Entry.Operator) {
5901ab3d6c8SXing GUO   case dwarf::DW_RLE_end_of_list:
5911ab3d6c8SXing GUO     if (Error Err = CheckOperands(0))
5921ab3d6c8SXing GUO       return std::move(Err);
5931ab3d6c8SXing GUO     break;
5941ab3d6c8SXing GUO   case dwarf::DW_RLE_base_addressx:
5951ab3d6c8SXing GUO     if (Error Err = CheckOperands(1))
5961ab3d6c8SXing GUO       return std::move(Err);
5971ab3d6c8SXing GUO     encodeULEB128(Entry.Values[0], OS);
5981ab3d6c8SXing GUO     break;
5991ab3d6c8SXing GUO   case dwarf::DW_RLE_startx_endx:
6001ab3d6c8SXing GUO   case dwarf::DW_RLE_startx_length:
6011ab3d6c8SXing GUO   case dwarf::DW_RLE_offset_pair:
6021ab3d6c8SXing GUO     if (Error Err = CheckOperands(2))
6031ab3d6c8SXing GUO       return std::move(Err);
6041ab3d6c8SXing GUO     encodeULEB128(Entry.Values[0], OS);
6051ab3d6c8SXing GUO     encodeULEB128(Entry.Values[1], OS);
6061ab3d6c8SXing GUO     break;
6071ab3d6c8SXing GUO   case dwarf::DW_RLE_base_address:
6081ab3d6c8SXing GUO     if (Error Err = CheckOperands(1))
6091ab3d6c8SXing GUO       return std::move(Err);
6101ab3d6c8SXing GUO     if (Error Err = WriteAddress(Entry.Values[0]))
6111ab3d6c8SXing GUO       return std::move(Err);
6121ab3d6c8SXing GUO     break;
6131ab3d6c8SXing GUO   case dwarf::DW_RLE_start_end:
6141ab3d6c8SXing GUO     if (Error Err = CheckOperands(2))
6151ab3d6c8SXing GUO       return std::move(Err);
6161ab3d6c8SXing GUO     if (Error Err = WriteAddress(Entry.Values[0]))
6171ab3d6c8SXing GUO       return std::move(Err);
6181ab3d6c8SXing GUO     cantFail(WriteAddress(Entry.Values[1]));
6191ab3d6c8SXing GUO     break;
6201ab3d6c8SXing GUO   case dwarf::DW_RLE_start_length:
6211ab3d6c8SXing GUO     if (Error Err = CheckOperands(2))
6221ab3d6c8SXing GUO       return std::move(Err);
6231ab3d6c8SXing GUO     if (Error Err = WriteAddress(Entry.Values[0]))
6241ab3d6c8SXing GUO       return std::move(Err);
6251ab3d6c8SXing GUO     encodeULEB128(Entry.Values[1], OS);
6261ab3d6c8SXing GUO     break;
6271ab3d6c8SXing GUO   }
6281ab3d6c8SXing GUO 
6291ab3d6c8SXing GUO   return OS.tell() - BeginOffset;
6301ab3d6c8SXing GUO }
6311ab3d6c8SXing GUO 
632c4cf250cSXing GUO template <typename EntryType>
633c4cf250cSXing GUO Error writeDWARFLists(raw_ostream &OS,
634c4cf250cSXing GUO                       ArrayRef<DWARFYAML::ListTable<EntryType>> Tables,
635c4cf250cSXing GUO                       bool IsLittleEndian, bool Is64BitAddrSize) {
636c4cf250cSXing GUO   for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
6371ab3d6c8SXing GUO     // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
6381ab3d6c8SXing GUO     // sizeof(offset_entry_count) = 8
6391ab3d6c8SXing GUO     uint64_t Length = 8;
6401ab3d6c8SXing GUO 
6411ab3d6c8SXing GUO     uint8_t AddrSize;
6421ab3d6c8SXing GUO     if (Table.AddrSize)
6431ab3d6c8SXing GUO       AddrSize = *Table.AddrSize;
6441ab3d6c8SXing GUO     else
645c4cf250cSXing GUO       AddrSize = Is64BitAddrSize ? 8 : 4;
6461ab3d6c8SXing GUO 
647c4cf250cSXing GUO     // Since the length of the current range/location lists entry is
648c4cf250cSXing GUO     // undetermined yet, we firstly write the content of the range/location
649c4cf250cSXing GUO     // lists to a buffer to calculate the length and then serialize the buffer
650c4cf250cSXing GUO     // content to the actual output stream.
6511ab3d6c8SXing GUO     std::string ListBuffer;
6521ab3d6c8SXing GUO     raw_string_ostream ListBufferOS(ListBuffer);
6531ab3d6c8SXing GUO 
654c4cf250cSXing GUO     // Offsets holds offsets for each range/location list. The i-th element is
655c4cf250cSXing GUO     // the offset from the beginning of the first range/location list to the
656c4cf250cSXing GUO     // location of the i-th range list.
6571ab3d6c8SXing GUO     std::vector<uint64_t> Offsets;
6581ab3d6c8SXing GUO 
659c4cf250cSXing GUO     for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
6601ab3d6c8SXing GUO       Offsets.push_back(ListBufferOS.tell());
661*22ec861dSXing GUO       if (List.Content) {
662*22ec861dSXing GUO         List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
663*22ec861dSXing GUO         Length += List.Content->binary_size();
664*22ec861dSXing GUO       } else if (List.Entries) {
665*22ec861dSXing GUO         for (const EntryType &Entry : *List.Entries) {
6661ab3d6c8SXing GUO           Expected<uint64_t> EntrySize =
667c4cf250cSXing GUO               writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
6681ab3d6c8SXing GUO           if (!EntrySize)
6691ab3d6c8SXing GUO             return EntrySize.takeError();
6701ab3d6c8SXing GUO           Length += *EntrySize;
6711ab3d6c8SXing GUO         }
6721ab3d6c8SXing GUO       }
673*22ec861dSXing GUO     }
6741ab3d6c8SXing GUO 
6751ab3d6c8SXing GUO     // If the offset_entry_count field isn't specified, yaml2obj will infer it
6761ab3d6c8SXing GUO     // from the 'Offsets' field in the YAML description. If the 'Offsets' field
6771ab3d6c8SXing GUO     // isn't specified either, yaml2obj will infer it from the auto-generated
6781ab3d6c8SXing GUO     // offsets.
6791ab3d6c8SXing GUO     uint32_t OffsetEntryCount;
6801ab3d6c8SXing GUO     if (Table.OffsetEntryCount)
6811ab3d6c8SXing GUO       OffsetEntryCount = *Table.OffsetEntryCount;
6821ab3d6c8SXing GUO     else
6831ab3d6c8SXing GUO       OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
6841ab3d6c8SXing GUO     uint64_t OffsetsSize =
6851ab3d6c8SXing GUO         OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
6861ab3d6c8SXing GUO     Length += OffsetsSize;
6871ab3d6c8SXing GUO 
6881ab3d6c8SXing GUO     // If the length is specified in the YAML description, we use it instead of
6891ab3d6c8SXing GUO     // the actual length.
6901ab3d6c8SXing GUO     if (Table.Length)
6911ab3d6c8SXing GUO       Length = *Table.Length;
6921ab3d6c8SXing GUO 
693c4cf250cSXing GUO     writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
694c4cf250cSXing GUO     writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
695c4cf250cSXing GUO     writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
696c4cf250cSXing GUO     writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
697c4cf250cSXing GUO     writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
6981ab3d6c8SXing GUO 
6991ab3d6c8SXing GUO     auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
700367d0d4cSXing GUO       for (uint64_t Offset : Offsets)
701367d0d4cSXing GUO         writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
702367d0d4cSXing GUO                          IsLittleEndian);
7031ab3d6c8SXing GUO     };
7041ab3d6c8SXing GUO 
7051ab3d6c8SXing GUO     if (Table.Offsets)
7061ab3d6c8SXing GUO       EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
7071ab3d6c8SXing GUO                                      Table.Offsets->size()),
7081ab3d6c8SXing GUO                   0);
7091ab3d6c8SXing GUO     else
7101ab3d6c8SXing GUO       EmitOffsets(Offsets, OffsetsSize);
7111ab3d6c8SXing GUO 
7121ab3d6c8SXing GUO     OS.write(ListBuffer.data(), ListBuffer.size());
7131ab3d6c8SXing GUO   }
7141ab3d6c8SXing GUO 
7151ab3d6c8SXing GUO   return Error::success();
7161ab3d6c8SXing GUO }
7171ab3d6c8SXing GUO 
718c4cf250cSXing GUO Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) {
719c4cf250cSXing GUO   assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
720c4cf250cSXing GUO   return writeDWARFLists<DWARFYAML::RnglistEntry>(
721c4cf250cSXing GUO       OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize);
722c4cf250cSXing GUO }
723c4cf250cSXing GUO 
7249939f231SXing GUO using EmitFuncType = Error (*)(raw_ostream &, const DWARFYAML::Data &);
7252e752db4SChris Bieneman 
7269939f231SXing GUO static Error
72767b4afc4SXing GUO emitDebugSectionImpl(const DWARFYAML::Data &DI, EmitFuncType EmitFunc,
728efcf06f5SBenjamin Kramer                      StringRef Sec,
7292e752db4SChris Bieneman                      StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
7302e752db4SChris Bieneman   std::string Data;
7312e752db4SChris Bieneman   raw_string_ostream DebugInfoStream(Data);
7329939f231SXing GUO   if (Error Err = EmitFunc(DebugInfoStream, DI))
7339939f231SXing GUO     return Err;
7342e752db4SChris Bieneman   DebugInfoStream.flush();
7352e752db4SChris Bieneman   if (!Data.empty())
7362e752db4SChris Bieneman     OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
7379939f231SXing GUO 
7389939f231SXing GUO   return Error::success();
7392e752db4SChris Bieneman }
7402e752db4SChris Bieneman 
7415c709edaSJonas Devlieghere Expected<StringMap<std::unique_ptr<MemoryBuffer>>>
74292874d28SXing GUO DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian) {
7438f9ca561SXing GUO   auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
7448f9ca561SXing GUO     *static_cast<SMDiagnostic *>(DiagContext) = Diag;
7458f9ca561SXing GUO   };
7468f9ca561SXing GUO 
7478f9ca561SXing GUO   SMDiagnostic GeneratedDiag;
7488f9ca561SXing GUO   yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
7498f9ca561SXing GUO                   &GeneratedDiag);
7502e752db4SChris Bieneman 
7512e752db4SChris Bieneman   DWARFYAML::Data DI;
7522e752db4SChris Bieneman   DI.IsLittleEndian = IsLittleEndian;
7532e752db4SChris Bieneman   YIn >> DI;
7542e752db4SChris Bieneman   if (YIn.error())
7558f9ca561SXing GUO     return createStringError(YIn.error(), GeneratedDiag.getMessage());
7562e752db4SChris Bieneman 
7575c709edaSJonas Devlieghere   StringMap<std::unique_ptr<MemoryBuffer>> DebugSections;
7589939f231SXing GUO   Error Err = emitDebugSectionImpl(DI, &DWARFYAML::emitDebugInfo, "debug_info",
7592e752db4SChris Bieneman                                    DebugSections);
7609939f231SXing GUO   Err = joinErrors(std::move(Err),
7619939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugLine,
7629939f231SXing GUO                                         "debug_line", DebugSections));
7639939f231SXing GUO   Err = joinErrors(std::move(Err),
7649939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugStr,
7659939f231SXing GUO                                         "debug_str", DebugSections));
7669939f231SXing GUO   Err = joinErrors(std::move(Err),
7679939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugAbbrev,
7689939f231SXing GUO                                         "debug_abbrev", DebugSections));
7699939f231SXing GUO   Err = joinErrors(std::move(Err),
7709939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugAranges,
7719939f231SXing GUO                                         "debug_aranges", DebugSections));
7729939f231SXing GUO   Err = joinErrors(std::move(Err),
7739939f231SXing GUO                    emitDebugSectionImpl(DI, &DWARFYAML::emitDebugRanges,
7749939f231SXing GUO                                         "debug_ranges", DebugSections));
7759939f231SXing GUO 
7769939f231SXing GUO   if (Err)
7779939f231SXing GUO     return std::move(Err);
778c55cf4afSBill Wendling   return std::move(DebugSections);
7792e752db4SChris Bieneman }
780