LLVM 20.0.0git
DWARFEmitter.cpp
Go to the documentation of this file.
1//===- DWARFEmitter - Convert YAML to DWARF binary data -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// The DWARF component of yaml2obj. Provided as library code for tests.
11///
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Errc.h"
22#include "llvm/Support/Error.h"
23#include "llvm/Support/LEB128.h"
31#include <algorithm>
32#include <cassert>
33#include <cstddef>
34#include <cstdint>
35#include <memory>
36#include <optional>
37#include <string>
38#include <vector>
39
40using namespace llvm;
41
42template <typename T>
43static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian) {
44 if (IsLittleEndian != sys::IsLittleEndianHost)
46 OS.write(reinterpret_cast<char *>(&Integer), sizeof(T));
47}
48
50 raw_ostream &OS, bool IsLittleEndian) {
51 if (8 == Size)
52 writeInteger((uint64_t)Integer, OS, IsLittleEndian);
53 else if (4 == Size)
54 writeInteger((uint32_t)Integer, OS, IsLittleEndian);
55 else if (2 == Size)
56 writeInteger((uint16_t)Integer, OS, IsLittleEndian);
57 else if (1 == Size)
58 writeInteger((uint8_t)Integer, OS, IsLittleEndian);
59 else
60 return createStringError(errc::not_supported,
61 "invalid integer write size: %zu", Size);
62
63 return Error::success();
64}
65
66static void ZeroFillBytes(raw_ostream &OS, size_t Size) {
67 std::vector<uint8_t> FillData(Size, 0);
68 OS.write(reinterpret_cast<char *>(FillData.data()), Size);
69}
70
71static void writeInitialLength(const dwarf::DwarfFormat Format,
73 bool IsLittleEndian) {
74 bool IsDWARF64 = Format == dwarf::DWARF64;
75 if (IsDWARF64)
77 IsLittleEndian));
79 writeVariableSizedInteger(Length, IsDWARF64 ? 8 : 4, OS, IsLittleEndian));
80}
81
83 raw_ostream &OS, bool IsLittleEndian) {
85 OS, IsLittleEndian));
86}
87
89 for (StringRef Str : *DI.DebugStrings) {
90 OS.write(Str.data(), Str.size());
91 OS.write('\0');
92 }
93
94 return Error::success();
95}
96
98 assert(Index < DebugAbbrev.size() &&
99 "Index should be less than the size of DebugAbbrev array");
100 auto It = AbbrevTableContents.find(Index);
101 if (It != AbbrevTableContents.cend())
102 return It->second;
103
104 std::string AbbrevTableBuffer;
105 raw_string_ostream OS(AbbrevTableBuffer);
106
107 uint64_t AbbrevCode = 0;
108 for (const DWARFYAML::Abbrev &AbbrevDecl : DebugAbbrev[Index].Table) {
109 AbbrevCode = AbbrevDecl.Code ? (uint64_t)*AbbrevDecl.Code : AbbrevCode + 1;
110 encodeULEB128(AbbrevCode, OS);
111 encodeULEB128(AbbrevDecl.Tag, OS);
112 OS.write(AbbrevDecl.Children);
113 for (const auto &Attr : AbbrevDecl.Attributes) {
114 encodeULEB128(Attr.Attribute, OS);
115 encodeULEB128(Attr.Form, OS);
116 if (Attr.Form == dwarf::DW_FORM_implicit_const)
117 encodeSLEB128(Attr.Value, OS);
118 }
119 encodeULEB128(0, OS);
120 encodeULEB128(0, OS);
121 }
122
123 // The abbreviations for a given compilation unit end with an entry
124 // consisting of a 0 byte for the abbreviation code.
125 OS.write_zeros(1);
126
127 AbbrevTableContents.insert({Index, AbbrevTableBuffer});
128
129 return AbbrevTableContents[Index];
130}
131
133 for (uint64_t I = 0; I < DI.DebugAbbrev.size(); ++I) {
134 StringRef AbbrevTableContent = DI.getAbbrevTableContentByIndex(I);
135 OS.write(AbbrevTableContent.data(), AbbrevTableContent.size());
136 }
137
138 return Error::success();
139}
140
142 assert(DI.DebugAranges && "unexpected emitDebugAranges() call");
143 for (const auto &Range : *DI.DebugAranges) {
144 uint8_t AddrSize;
145 if (Range.AddrSize)
146 AddrSize = *Range.AddrSize;
147 else
148 AddrSize = DI.Is64BitAddrSize ? 8 : 4;
149
150 uint64_t Length = 4; // sizeof(version) 2 + sizeof(address_size) 1 +
151 // sizeof(segment_selector_size) 1
152 Length +=
153 Range.Format == dwarf::DWARF64 ? 8 : 4; // sizeof(debug_info_offset)
154
155 const uint64_t HeaderLength =
156 Length + (Range.Format == dwarf::DWARF64
157 ? 12
158 : 4); // sizeof(unit_header) = 12 (DWARF64) or 4 (DWARF32)
159 const uint64_t PaddedHeaderLength = alignTo(HeaderLength, AddrSize * 2);
160
161 if (Range.Length) {
162 Length = *Range.Length;
163 } else {
164 Length += PaddedHeaderLength - HeaderLength;
165 Length += AddrSize * 2 * (Range.Descriptors.size() + 1);
166 }
167
170 writeDWARFOffset(Range.CuOffset, Range.Format, OS, DI.IsLittleEndian);
171 writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
172 writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian);
173 ZeroFillBytes(OS, PaddedHeaderLength - HeaderLength);
174
175 for (const auto &Descriptor : Range.Descriptors) {
176 if (Error Err = writeVariableSizedInteger(Descriptor.Address, AddrSize,
177 OS, DI.IsLittleEndian))
179 "unable to write debug_aranges address: %s",
180 toString(std::move(Err)).c_str());
181 cantFail(writeVariableSizedInteger(Descriptor.Length, AddrSize, OS,
182 DI.IsLittleEndian));
183 }
184 ZeroFillBytes(OS, AddrSize * 2);
185 }
186
187 return Error::success();
188}
189
191 const size_t RangesOffset = OS.tell();
192 uint64_t EntryIndex = 0;
193 for (const auto &DebugRanges : *DI.DebugRanges) {
194 const size_t CurrOffset = OS.tell() - RangesOffset;
195 if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset)
197 "'Offset' for 'debug_ranges' with index " +
198 Twine(EntryIndex) +
199 " must be greater than or equal to the "
200 "number of bytes written already (0x" +
201 Twine::utohexstr(CurrOffset) + ")");
202 if (DebugRanges.Offset)
203 ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset);
204
205 uint8_t AddrSize;
206 if (DebugRanges.AddrSize)
207 AddrSize = *DebugRanges.AddrSize;
208 else
209 AddrSize = DI.Is64BitAddrSize ? 8 : 4;
210 for (const auto &Entry : DebugRanges.Entries) {
211 if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS,
212 DI.IsLittleEndian))
213 return createStringError(
215 "unable to write debug_ranges address offset: %s",
216 toString(std::move(Err)).c_str());
217 cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS,
218 DI.IsLittleEndian));
219 }
220 ZeroFillBytes(OS, AddrSize * 2);
221 ++EntryIndex;
222 }
223
224 return Error::success();
225}
226
228 bool IsLittleEndian, bool IsGNUPubSec = false) {
229 writeInitialLength(Sect.Format, Sect.Length, OS, IsLittleEndian);
230 writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian);
231 writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian);
232 writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian);
233 for (const auto &Entry : Sect.Entries) {
234 writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian);
235 if (IsGNUPubSec)
236 writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian);
237 OS.write(Entry.Name.data(), Entry.Name.size());
238 OS.write('\0');
239 }
240 return Error::success();
241}
242
244 assert(DI.PubNames && "unexpected emitDebugPubnames() call");
245 return emitPubSection(OS, *DI.PubNames, DI.IsLittleEndian);
246}
247
249 assert(DI.PubTypes && "unexpected emitDebugPubtypes() call");
250 return emitPubSection(OS, *DI.PubTypes, DI.IsLittleEndian);
251}
252
254 assert(DI.GNUPubNames && "unexpected emitDebugGNUPubnames() call");
256 /*IsGNUStyle=*/true);
257}
258
260 assert(DI.GNUPubTypes && "unexpected emitDebugGNUPubtypes() call");
262 /*IsGNUStyle=*/true);
263}
264
266 uint64_t AbbrevTableID,
267 const dwarf::FormParams &Params,
268 const DWARFYAML::Entry &Entry,
269 raw_ostream &OS, bool IsLittleEndian) {
270 uint64_t EntryBegin = OS.tell();
271 encodeULEB128(Entry.AbbrCode, OS);
272 uint32_t AbbrCode = Entry.AbbrCode;
273 if (AbbrCode == 0 || Entry.Values.empty())
274 return OS.tell() - EntryBegin;
275
276 Expected<DWARFYAML::Data::AbbrevTableInfo> AbbrevTableInfoOrErr =
277 DI.getAbbrevTableInfoByID(AbbrevTableID);
278 if (!AbbrevTableInfoOrErr)
280 toString(AbbrevTableInfoOrErr.takeError()) +
281 " for compilation unit with index " +
282 utostr(CUIndex));
283
284 ArrayRef<DWARFYAML::Abbrev> AbbrevDecls(
285 DI.DebugAbbrev[AbbrevTableInfoOrErr->Index].Table);
286
287 if (AbbrCode > AbbrevDecls.size())
288 return createStringError(
290 "abbrev code must be less than or equal to the number of "
291 "entries in abbreviation table");
292 const DWARFYAML::Abbrev &Abbrev = AbbrevDecls[AbbrCode - 1];
293 auto FormVal = Entry.Values.begin();
294 auto AbbrForm = Abbrev.Attributes.begin();
295 for (; FormVal != Entry.Values.end() && AbbrForm != Abbrev.Attributes.end();
296 ++FormVal, ++AbbrForm) {
297 dwarf::Form Form = AbbrForm->Form;
298 bool Indirect;
299 do {
300 Indirect = false;
301 switch (Form) {
302 case dwarf::DW_FORM_addr:
303 // TODO: Test this error.
305 FormVal->Value, Params.AddrSize, OS, IsLittleEndian))
306 return std::move(Err);
307 break;
308 case dwarf::DW_FORM_ref_addr:
309 // TODO: Test this error.
310 if (Error Err = writeVariableSizedInteger(FormVal->Value,
311 Params.getRefAddrByteSize(),
312 OS, IsLittleEndian))
313 return std::move(Err);
314 break;
315 case dwarf::DW_FORM_exprloc:
316 case dwarf::DW_FORM_block:
317 encodeULEB128(FormVal->BlockData.size(), OS);
318 OS.write((const char *)FormVal->BlockData.data(),
319 FormVal->BlockData.size());
320 break;
321 case dwarf::DW_FORM_block1: {
322 writeInteger((uint8_t)FormVal->BlockData.size(), OS, IsLittleEndian);
323 OS.write((const char *)FormVal->BlockData.data(),
324 FormVal->BlockData.size());
325 break;
326 }
327 case dwarf::DW_FORM_block2: {
328 writeInteger((uint16_t)FormVal->BlockData.size(), OS, IsLittleEndian);
329 OS.write((const char *)FormVal->BlockData.data(),
330 FormVal->BlockData.size());
331 break;
332 }
333 case dwarf::DW_FORM_block4: {
334 writeInteger((uint32_t)FormVal->BlockData.size(), OS, IsLittleEndian);
335 OS.write((const char *)FormVal->BlockData.data(),
336 FormVal->BlockData.size());
337 break;
338 }
339 case dwarf::DW_FORM_strx:
340 case dwarf::DW_FORM_addrx:
341 case dwarf::DW_FORM_rnglistx:
342 case dwarf::DW_FORM_loclistx:
343 case dwarf::DW_FORM_udata:
344 case dwarf::DW_FORM_ref_udata:
345 case dwarf::DW_FORM_GNU_addr_index:
346 case dwarf::DW_FORM_GNU_str_index:
347 encodeULEB128(FormVal->Value, OS);
348 break;
349 case dwarf::DW_FORM_data1:
350 case dwarf::DW_FORM_ref1:
351 case dwarf::DW_FORM_flag:
352 case dwarf::DW_FORM_strx1:
353 case dwarf::DW_FORM_addrx1:
354 writeInteger((uint8_t)FormVal->Value, OS, IsLittleEndian);
355 break;
356 case dwarf::DW_FORM_data2:
357 case dwarf::DW_FORM_ref2:
358 case dwarf::DW_FORM_strx2:
359 case dwarf::DW_FORM_addrx2:
360 writeInteger((uint16_t)FormVal->Value, OS, IsLittleEndian);
361 break;
362 case dwarf::DW_FORM_data4:
363 case dwarf::DW_FORM_ref4:
364 case dwarf::DW_FORM_ref_sup4:
365 case dwarf::DW_FORM_strx4:
366 case dwarf::DW_FORM_addrx4:
367 writeInteger((uint32_t)FormVal->Value, OS, IsLittleEndian);
368 break;
369 case dwarf::DW_FORM_data8:
370 case dwarf::DW_FORM_ref8:
371 case dwarf::DW_FORM_ref_sup8:
372 case dwarf::DW_FORM_ref_sig8:
373 writeInteger((uint64_t)FormVal->Value, OS, IsLittleEndian);
374 break;
375 case dwarf::DW_FORM_sdata:
376 encodeSLEB128(FormVal->Value, OS);
377 break;
378 case dwarf::DW_FORM_string:
379 OS.write(FormVal->CStr.data(), FormVal->CStr.size());
380 OS.write('\0');
381 break;
382 case dwarf::DW_FORM_indirect:
383 encodeULEB128(FormVal->Value, OS);
384 Indirect = true;
385 Form = static_cast<dwarf::Form>((uint64_t)FormVal->Value);
386 ++FormVal;
387 break;
388 case dwarf::DW_FORM_strp:
389 case dwarf::DW_FORM_sec_offset:
390 case dwarf::DW_FORM_GNU_ref_alt:
391 case dwarf::DW_FORM_GNU_strp_alt:
392 case dwarf::DW_FORM_line_strp:
393 case dwarf::DW_FORM_strp_sup:
394 cantFail(writeVariableSizedInteger(FormVal->Value,
395 Params.getDwarfOffsetByteSize(), OS,
396 IsLittleEndian));
397 break;
398 default:
399 break;
400 }
401 } while (Indirect);
402 }
403
404 return OS.tell() - EntryBegin;
405}
406
408 for (uint64_t I = 0; I < DI.Units.size(); ++I) {
409 const DWARFYAML::Unit &Unit = DI.Units[I];
410 uint8_t AddrSize;
411 if (Unit.AddrSize)
412 AddrSize = *Unit.AddrSize;
413 else
414 AddrSize = DI.Is64BitAddrSize ? 8 : 4;
415 dwarf::FormParams Params = {Unit.Version, AddrSize, Unit.Format};
416 uint64_t Length = 3; // sizeof(version) + sizeof(address_size)
417 Length += Params.getDwarfOffsetByteSize(); // sizeof(debug_abbrev_offset)
418 if (Unit.Version >= 5) {
419 ++Length; // sizeof(unit_type)
420 switch (Unit.Type) {
421 case dwarf::DW_UT_compile:
422 case dwarf::DW_UT_partial:
423 default:
424 break;
425 case dwarf::DW_UT_type:
426 case dwarf::DW_UT_split_type:
427 // sizeof(type_signature) + sizeof(type_offset)
428 Length += 8 + Params.getDwarfOffsetByteSize();
429 break;
430 case dwarf::DW_UT_skeleton:
431 case dwarf::DW_UT_split_compile:
432 Length += 8; // sizeof(dwo_id)
433 }
434 }
435
436 // Since the length of the current compilation unit is undetermined yet, we
437 // firstly write the content of the compilation unit to a buffer to
438 // calculate it and then serialize the buffer content to the actual output
439 // stream.
440 std::string EntryBuffer;
441 raw_string_ostream EntryBufferOS(EntryBuffer);
442
443 uint64_t AbbrevTableID = Unit.AbbrevTableID.value_or(I);
444 for (const DWARFYAML::Entry &Entry : Unit.Entries) {
445 if (Expected<uint64_t> EntryLength =
446 writeDIE(DI, I, AbbrevTableID, Params, Entry, EntryBufferOS,
447 DI.IsLittleEndian))
448 Length += *EntryLength;
449 else
450 return EntryLength.takeError();
451 }
452
453 // If the length is specified in the YAML description, we use it instead of
454 // the actual length.
455 if (Unit.Length)
456 Length = *Unit.Length;
457
460
461 uint64_t AbbrevTableOffset = 0;
462 if (Unit.AbbrOffset) {
463 AbbrevTableOffset = *Unit.AbbrOffset;
464 } else {
465 if (Expected<DWARFYAML::Data::AbbrevTableInfo> AbbrevTableInfoOrErr =
466 DI.getAbbrevTableInfoByID(AbbrevTableID)) {
467 AbbrevTableOffset = AbbrevTableInfoOrErr->Offset;
468 } else {
469 // The current compilation unit may not have DIEs and it will not be
470 // able to find the associated abbrev table. We consume the error and
471 // assign 0 to the debug_abbrev_offset in such circumstances.
472 consumeError(AbbrevTableInfoOrErr.takeError());
473 }
474 }
475
476 if (Unit.Version >= 5) {
477 writeInteger((uint8_t)Unit.Type, OS, DI.IsLittleEndian);
478 writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
479 writeDWARFOffset(AbbrevTableOffset, Unit.Format, OS, DI.IsLittleEndian);
480 switch (Unit.Type) {
481 case dwarf::DW_UT_compile:
482 case dwarf::DW_UT_partial:
483 default:
484 break;
485 case dwarf::DW_UT_type:
486 case dwarf::DW_UT_split_type:
489 break;
490 case dwarf::DW_UT_skeleton:
491 case dwarf::DW_UT_split_compile:
493 break;
494 }
495 } else {
496 writeDWARFOffset(AbbrevTableOffset, Unit.Format, OS, DI.IsLittleEndian);
497 writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
498 }
499
500 OS.write(EntryBuffer.data(), EntryBuffer.size());
501 }
502
503 return Error::success();
504}
505
506static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) {
507 OS.write(File.Name.data(), File.Name.size());
508 OS.write('\0');
509 encodeULEB128(File.DirIdx, OS);
510 encodeULEB128(File.ModTime, OS);
511 encodeULEB128(File.Length, OS);
512}
513
515 uint8_t AddrSize, bool IsLittleEndian,
516 raw_ostream &OS) {
517 // The first byte of extended opcodes is a zero byte. The next bytes are an
518 // ULEB128 integer giving the number of bytes in the instruction itself (does
519 // not include the first zero byte or the size). We serialize the instruction
520 // itself into the OpBuffer and then write the size of the buffer and the
521 // buffer to the real output stream.
522 std::string OpBuffer;
523 raw_string_ostream OpBufferOS(OpBuffer);
524 writeInteger((uint8_t)Op.SubOpcode, OpBufferOS, IsLittleEndian);
525 switch (Op.SubOpcode) {
526 case dwarf::DW_LNE_set_address:
527 cantFail(writeVariableSizedInteger(Op.Data, AddrSize, OpBufferOS,
528 IsLittleEndian));
529 break;
530 case dwarf::DW_LNE_define_file:
531 emitFileEntry(OpBufferOS, Op.FileEntry);
532 break;
533 case dwarf::DW_LNE_set_discriminator:
534 encodeULEB128(Op.Data, OpBufferOS);
535 break;
536 case dwarf::DW_LNE_end_sequence:
537 break;
538 default:
539 for (auto OpByte : Op.UnknownOpcodeData)
540 writeInteger((uint8_t)OpByte, OpBufferOS, IsLittleEndian);
541 }
542 uint64_t ExtLen = Op.ExtLen.value_or(OpBuffer.size());
543 encodeULEB128(ExtLen, OS);
544 OS.write(OpBuffer.data(), OpBuffer.size());
545}
546
548 uint8_t OpcodeBase, uint8_t AddrSize,
549 raw_ostream &OS, bool IsLittleEndian) {
550 writeInteger((uint8_t)Op.Opcode, OS, IsLittleEndian);
551 if (Op.Opcode == 0) {
552 writeExtendedOpcode(Op, AddrSize, IsLittleEndian, OS);
553 } else if (Op.Opcode < OpcodeBase) {
554 switch (Op.Opcode) {
555 case dwarf::DW_LNS_copy:
556 case dwarf::DW_LNS_negate_stmt:
557 case dwarf::DW_LNS_set_basic_block:
558 case dwarf::DW_LNS_const_add_pc:
559 case dwarf::DW_LNS_set_prologue_end:
560 case dwarf::DW_LNS_set_epilogue_begin:
561 break;
562
563 case dwarf::DW_LNS_advance_pc:
564 case dwarf::DW_LNS_set_file:
565 case dwarf::DW_LNS_set_column:
566 case dwarf::DW_LNS_set_isa:
567 encodeULEB128(Op.Data, OS);
568 break;
569
570 case dwarf::DW_LNS_advance_line:
571 encodeSLEB128(Op.SData, OS);
572 break;
573
574 case dwarf::DW_LNS_fixed_advance_pc:
575 writeInteger((uint16_t)Op.Data, OS, IsLittleEndian);
576 break;
577
578 default:
579 for (auto OpData : Op.StandardOpcodeData) {
580 encodeULEB128(OpData, OS);
581 }
582 }
583 }
584}
585
586static std::vector<uint8_t>
587getStandardOpcodeLengths(uint16_t Version, std::optional<uint8_t> OpcodeBase) {
588 // If the opcode_base field isn't specified, we returns the
589 // standard_opcode_lengths array according to the version by default.
590 std::vector<uint8_t> StandardOpcodeLengths{0, 1, 1, 1, 1, 0,
591 0, 0, 1, 0, 0, 1};
592 if (Version == 2) {
593 // DWARF v2 uses the same first 9 standard opcodes as v3-5.
594 StandardOpcodeLengths.resize(9);
595 } else if (OpcodeBase) {
596 StandardOpcodeLengths.resize(*OpcodeBase > 0 ? *OpcodeBase - 1 : 0, 0);
597 }
598 return StandardOpcodeLengths;
599}
600
602 for (const DWARFYAML::LineTable &LineTable : DI.DebugLines) {
603 // Buffer holds the bytes following the header_length (or prologue_length in
604 // DWARFv2) field to the end of the line number program itself.
605 std::string Buffer;
606 raw_string_ostream BufferOS(Buffer);
607
609 // TODO: Add support for emitting DWARFv5 line table.
610 if (LineTable.Version >= 4)
615
616 std::vector<uint8_t> StandardOpcodeLengths =
619 uint8_t OpcodeBase = LineTable.OpcodeBase
621 : StandardOpcodeLengths.size() + 1;
622 writeInteger(OpcodeBase, BufferOS, DI.IsLittleEndian);
623 for (uint8_t OpcodeLength : StandardOpcodeLengths)
624 writeInteger(OpcodeLength, BufferOS, DI.IsLittleEndian);
625
626 for (StringRef IncludeDir : LineTable.IncludeDirs) {
627 BufferOS.write(IncludeDir.data(), IncludeDir.size());
628 BufferOS.write('\0');
629 }
630 BufferOS.write('\0');
631
632 for (const DWARFYAML::File &File : LineTable.Files)
633 emitFileEntry(BufferOS, File);
634 BufferOS.write('\0');
635
636 uint64_t HeaderLength =
638
640 writeLineTableOpcode(Op, OpcodeBase, DI.Is64BitAddrSize ? 8 : 4, BufferOS,
641 DI.IsLittleEndian);
642
644 if (LineTable.Length) {
646 } else {
647 Length = 2; // sizeof(version)
648 Length +=
649 (LineTable.Format == dwarf::DWARF64 ? 8 : 4); // sizeof(header_length)
650 Length += Buffer.size();
651 }
652
656 OS.write(Buffer.data(), Buffer.size());
657 }
658
659 return Error::success();
660}
661
663 for (const AddrTableEntry &TableEntry : *DI.DebugAddr) {
664 uint8_t AddrSize;
665 if (TableEntry.AddrSize)
666 AddrSize = *TableEntry.AddrSize;
667 else
668 AddrSize = DI.Is64BitAddrSize ? 8 : 4;
669
671 if (TableEntry.Length)
672 Length = (uint64_t)*TableEntry.Length;
673 else
674 // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4
675 Length = 4 + (AddrSize + TableEntry.SegSelectorSize) *
676 TableEntry.SegAddrPairs.size();
677
680 writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian);
681 writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
682
683 for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
684 if (TableEntry.SegSelectorSize != yaml::Hex8{0})
686 TableEntry.SegSelectorSize,
687 OS, DI.IsLittleEndian))
689 "unable to write debug_addr segment: %s",
690 toString(std::move(Err)).c_str());
691 if (AddrSize != 0)
692 if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS,
693 DI.IsLittleEndian))
695 "unable to write debug_addr address: %s",
696 toString(std::move(Err)).c_str());
697 }
698 }
699
700 return Error::success();
701}
702
704 assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call");
705 for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) {
707 if (Table.Length)
708 Length = *Table.Length;
709 else
710 // sizeof(version) + sizeof(padding) = 4
711 Length =
712 4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4);
713
717
718 for (uint64_t Offset : Table.Offsets)
720 }
721
722 return Error::success();
723}
724
725namespace {
726/// Emits the header for a DebugNames section.
727void emitDebugNamesHeader(raw_ostream &OS, bool IsLittleEndian,
728 uint32_t NameCount, uint32_t AbbrevSize,
729 uint32_t CombinedSizeOtherParts) {
730 // Use the same AugmentationString as AsmPrinter.
731 StringRef AugmentationString = "LLVM0700";
732 size_t TotalSize = CombinedSizeOtherParts + 5 * sizeof(uint32_t) +
733 2 * sizeof(uint16_t) + sizeof(NameCount) +
734 sizeof(AbbrevSize) + AugmentationString.size();
735 writeInteger(uint32_t(TotalSize), OS, IsLittleEndian); // Unit length
736
737 // Everything below is included in total size.
738 writeInteger(uint16_t(5), OS, IsLittleEndian); // Version
739 writeInteger(uint16_t(0), OS, IsLittleEndian); // Padding
740 writeInteger(uint32_t(1), OS, IsLittleEndian); // Compilation Unit count
741 writeInteger(uint32_t(0), OS, IsLittleEndian); // Local Type Unit count
742 writeInteger(uint32_t(0), OS, IsLittleEndian); // Foreign Type Unit count
743 writeInteger(uint32_t(0), OS, IsLittleEndian); // Bucket count
744 writeInteger(NameCount, OS, IsLittleEndian);
745 writeInteger(AbbrevSize, OS, IsLittleEndian);
746 writeInteger(uint32_t(AugmentationString.size()), OS, IsLittleEndian);
747 OS.write(AugmentationString.data(), AugmentationString.size());
748 return;
749}
750
751/// Emits the abbreviations for a DebugNames section.
752std::string
753emitDebugNamesAbbrev(ArrayRef<DWARFYAML::DebugNameAbbreviation> Abbrevs) {
754 std::string Data;
756 for (const DWARFYAML::DebugNameAbbreviation &Abbrev : Abbrevs) {
757 encodeULEB128(Abbrev.Code, OS);
758 encodeULEB128(Abbrev.Tag, OS);
759 for (auto [Idx, Form] : Abbrev.Indices) {
762 }
763 encodeULEB128(0, OS);
764 encodeULEB128(0, OS);
765 }
766 encodeULEB128(0, OS);
767 return Data;
768}
769
770/// Emits a simple CU offsets list for a DebugNames section containing a single
771/// CU at offset 0.
772std::string emitDebugNamesCUOffsets(bool IsLittleEndian) {
773 std::string Data;
775 writeInteger(uint32_t(0), OS, IsLittleEndian);
776 return Data;
777}
778
779/// Emits the "NameTable" for a DebugNames section; according to the spec, it
780/// consists of two arrays: an array of string offsets, followed immediately by
781/// an array of entry offsets. The string offsets are emitted in the order
782/// provided in `Entries`.
783std::string emitDebugNamesNameTable(
784 bool IsLittleEndian,
785 const DenseMap<uint32_t, std::vector<DWARFYAML::DebugNameEntry>> &Entries,
786 ArrayRef<uint32_t> EntryPoolOffsets) {
787 assert(Entries.size() == EntryPoolOffsets.size());
788
789 std::string Data;
791
792 for (uint32_t Strp : make_first_range(Entries))
793 writeInteger(Strp, OS, IsLittleEndian);
794 for (uint32_t PoolOffset : EntryPoolOffsets)
795 writeInteger(PoolOffset, OS, IsLittleEndian);
796 return Data;
797}
798
799/// Groups entries based on their name (strp) code and returns a map.
801groupEntries(ArrayRef<DWARFYAML::DebugNameEntry> Entries) {
803 for (const DWARFYAML::DebugNameEntry &Entry : Entries)
804 StrpToEntries[Entry.NameStrp].push_back(Entry);
805 return StrpToEntries;
806}
807
808/// Finds the abbreviation whose code is AbbrevCode and returns a list
809/// containing the expected size of all non-zero-length forms.
811getNonZeroDataSizesFor(uint32_t AbbrevCode,
813 const auto *AbbrevIt = find_if(Abbrevs, [&](const auto &Abbrev) {
814 return Abbrev.Code.value == AbbrevCode;
815 });
816 if (AbbrevIt == Abbrevs.end())
818 "did not find an Abbreviation for this code");
819
820 SmallVector<uint8_t> DataSizes;
821 dwarf::FormParams Params{/*Version=*/5, /*AddrSize=*/4, dwarf::DWARF32};
822 for (auto [Idx, Form] : AbbrevIt->Indices) {
823 std::optional<uint8_t> FormSize = dwarf::getFixedFormByteSize(Form, Params);
824 if (!FormSize)
826 "unsupported Form for YAML debug_names emitter");
827 if (FormSize == 0)
828 continue;
829 DataSizes.push_back(*FormSize);
830 }
831 return DataSizes;
832}
833
834struct PoolOffsetsAndData {
835 std::string PoolData;
836 std::vector<uint32_t> PoolOffsets;
837};
838
839/// Emits the entry pool and returns an array of offsets containing the start
840/// offset for the entries of each unique name.
841/// Verifies that the provided number of data values match those expected by
842/// the abbreviation table.
843Expected<PoolOffsetsAndData> emitDebugNamesEntryPool(
844 bool IsLittleEndian,
845 const DenseMap<uint32_t, std::vector<DWARFYAML::DebugNameEntry>>
846 &StrpToEntries,
848 PoolOffsetsAndData Result;
849 raw_string_ostream OS(Result.PoolData);
850
851 for (ArrayRef<DWARFYAML::DebugNameEntry> EntriesWithSameName :
852 make_second_range(StrpToEntries)) {
853 Result.PoolOffsets.push_back(Result.PoolData.size());
854
855 for (const DWARFYAML::DebugNameEntry &Entry : EntriesWithSameName) {
856 encodeULEB128(Entry.Code, OS);
857
859 getNonZeroDataSizesFor(Entry.Code, Abbrevs);
860 if (!DataSizes)
861 return DataSizes.takeError();
862 if (DataSizes->size() != Entry.Values.size())
863 return createStringError(
865 "mismatch between provided and required number of values");
866
867 for (auto [Value, ValueSize] : zip_equal(Entry.Values, *DataSizes))
868 if (Error E =
869 writeVariableSizedInteger(Value, ValueSize, OS, IsLittleEndian))
870 return std::move(E);
871 }
872 encodeULEB128(0, OS);
873 }
874
875 return Result;
876}
877} // namespace
878
880 assert(DI.DebugNames && "unexpected emitDebugNames() call");
881 const DebugNamesSection DebugNames = DI.DebugNames.value();
882
884 groupEntries(DebugNames.Entries);
885
886 // Emit all sub-sections into individual strings so that we may compute
887 // relative offsets and sizes.
888 Expected<PoolOffsetsAndData> PoolInfo = emitDebugNamesEntryPool(
889 DI.IsLittleEndian, StrpToEntries, DebugNames.Abbrevs);
890 if (!PoolInfo)
891 return PoolInfo.takeError();
892 std::string NamesTableData = emitDebugNamesNameTable(
893 DI.IsLittleEndian, StrpToEntries, PoolInfo->PoolOffsets);
894
895 std::string AbbrevData = emitDebugNamesAbbrev(DebugNames.Abbrevs);
896 std::string CUOffsetsData = emitDebugNamesCUOffsets(DI.IsLittleEndian);
897
898 size_t TotalSize = PoolInfo->PoolData.size() + NamesTableData.size() +
899 AbbrevData.size() + CUOffsetsData.size();
900
901 // Start real emission by combining all individual strings.
902 emitDebugNamesHeader(OS, DI.IsLittleEndian, StrpToEntries.size(),
903 AbbrevData.size(), TotalSize);
904 OS.write(CUOffsetsData.data(), CUOffsetsData.size());
905 // No local TUs, no foreign TUs, no hash lookups table.
906 OS.write(NamesTableData.data(), NamesTableData.size());
907 OS.write(AbbrevData.data(), AbbrevData.size());
908 OS.write(PoolInfo->PoolData.data(), PoolInfo->PoolData.size());
909
910 return Error::success();
911}
912
913static Error checkOperandCount(StringRef EncodingString,
915 uint64_t ExpectedOperands) {
916 if (Values.size() != ExpectedOperands)
917 return createStringError(
919 "invalid number (%zu) of operands for the operator: %s, %" PRIu64
920 " expected",
921 Values.size(), EncodingString.str().c_str(), ExpectedOperands);
922
923 return Error::success();
924}
925
927 uint64_t Addr, uint8_t AddrSize,
928 bool IsLittleEndian) {
929 if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian))
931 "unable to write address for the operator %s: %s",
932 EncodingName.str().c_str(),
933 toString(std::move(Err)).c_str());
934
935 return Error::success();
936}
937
941 uint8_t AddrSize, bool IsLittleEndian) {
942 auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
944 Operation.Values, ExpectedOperands);
945 };
946
947 uint64_t ExpressionBegin = OS.tell();
948 writeInteger((uint8_t)Operation.Operator, OS, IsLittleEndian);
949 switch (Operation.Operator) {
950 case dwarf::DW_OP_consts:
951 if (Error Err = CheckOperands(1))
952 return std::move(Err);
953 encodeSLEB128(Operation.Values[0], OS);
954 break;
955 case dwarf::DW_OP_stack_value:
956 if (Error Err = CheckOperands(0))
957 return std::move(Err);
958 break;
959 default:
960 StringRef EncodingStr = dwarf::OperationEncodingString(Operation.Operator);
962 "DWARF expression: " +
963 (EncodingStr.empty()
964 ? "0x" + utohexstr(Operation.Operator)
965 : EncodingStr) +
966 " is not supported");
967 }
968 return OS.tell() - ExpressionBegin;
969}
970
972 const DWARFYAML::RnglistEntry &Entry,
973 uint8_t AddrSize,
974 bool IsLittleEndian) {
975 uint64_t BeginOffset = OS.tell();
976 writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
977
978 StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator);
979
980 auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
981 return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
982 };
983
984 auto WriteAddress = [&](uint64_t Addr) -> Error {
985 return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
986 IsLittleEndian);
987 };
988
989 switch (Entry.Operator) {
990 case dwarf::DW_RLE_end_of_list:
991 if (Error Err = CheckOperands(0))
992 return std::move(Err);
993 break;
994 case dwarf::DW_RLE_base_addressx:
995 if (Error Err = CheckOperands(1))
996 return std::move(Err);
997 encodeULEB128(Entry.Values[0], OS);
998 break;
999 case dwarf::DW_RLE_startx_endx:
1000 case dwarf::DW_RLE_startx_length:
1001 case dwarf::DW_RLE_offset_pair:
1002 if (Error Err = CheckOperands(2))
1003 return std::move(Err);
1004 encodeULEB128(Entry.Values[0], OS);
1005 encodeULEB128(Entry.Values[1], OS);
1006 break;
1007 case dwarf::DW_RLE_base_address:
1008 if (Error Err = CheckOperands(1))
1009 return std::move(Err);
1010 if (Error Err = WriteAddress(Entry.Values[0]))
1011 return std::move(Err);
1012 break;
1013 case dwarf::DW_RLE_start_end:
1014 if (Error Err = CheckOperands(2))
1015 return std::move(Err);
1016 if (Error Err = WriteAddress(Entry.Values[0]))
1017 return std::move(Err);
1018 cantFail(WriteAddress(Entry.Values[1]));
1019 break;
1020 case dwarf::DW_RLE_start_length:
1021 if (Error Err = CheckOperands(2))
1022 return std::move(Err);
1023 if (Error Err = WriteAddress(Entry.Values[0]))
1024 return std::move(Err);
1025 encodeULEB128(Entry.Values[1], OS);
1026 break;
1027 }
1028
1029 return OS.tell() - BeginOffset;
1030}
1031
1033 const DWARFYAML::LoclistEntry &Entry,
1034 uint8_t AddrSize,
1035 bool IsLittleEndian) {
1036 uint64_t BeginOffset = OS.tell();
1037 writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian);
1038
1039 StringRef EncodingName = dwarf::LocListEncodingString(Entry.Operator);
1040
1041 auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error {
1042 return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands);
1043 };
1044
1045 auto WriteAddress = [&](uint64_t Addr) -> Error {
1046 return writeListEntryAddress(EncodingName, OS, Addr, AddrSize,
1047 IsLittleEndian);
1048 };
1049
1050 auto WriteDWARFOperations = [&]() -> Error {
1051 std::string OpBuffer;
1052 raw_string_ostream OpBufferOS(OpBuffer);
1053 uint64_t DescriptionsLength = 0;
1054
1055 for (const DWARFYAML::DWARFOperation &Op : Entry.Descriptions) {
1056 if (Expected<uint64_t> OpSize =
1057 writeDWARFExpression(OpBufferOS, Op, AddrSize, IsLittleEndian))
1058 DescriptionsLength += *OpSize;
1059 else
1060 return OpSize.takeError();
1061 }
1062
1063 if (Entry.DescriptionsLength)
1064 DescriptionsLength = *Entry.DescriptionsLength;
1065 else
1066 DescriptionsLength = OpBuffer.size();
1067
1068 encodeULEB128(DescriptionsLength, OS);
1069 OS.write(OpBuffer.data(), OpBuffer.size());
1070
1071 return Error::success();
1072 };
1073
1074 switch (Entry.Operator) {
1075 case dwarf::DW_LLE_end_of_list:
1076 if (Error Err = CheckOperands(0))
1077 return std::move(Err);
1078 break;
1079 case dwarf::DW_LLE_base_addressx:
1080 if (Error Err = CheckOperands(1))
1081 return std::move(Err);
1082 encodeULEB128(Entry.Values[0], OS);
1083 break;
1084 case dwarf::DW_LLE_startx_endx:
1085 case dwarf::DW_LLE_startx_length:
1086 case dwarf::DW_LLE_offset_pair:
1087 if (Error Err = CheckOperands(2))
1088 return std::move(Err);
1089 encodeULEB128(Entry.Values[0], OS);
1090 encodeULEB128(Entry.Values[1], OS);
1091 if (Error Err = WriteDWARFOperations())
1092 return std::move(Err);
1093 break;
1094 case dwarf::DW_LLE_default_location:
1095 if (Error Err = CheckOperands(0))
1096 return std::move(Err);
1097 if (Error Err = WriteDWARFOperations())
1098 return std::move(Err);
1099 break;
1100 case dwarf::DW_LLE_base_address:
1101 if (Error Err = CheckOperands(1))
1102 return std::move(Err);
1103 if (Error Err = WriteAddress(Entry.Values[0]))
1104 return std::move(Err);
1105 break;
1106 case dwarf::DW_LLE_start_end:
1107 if (Error Err = CheckOperands(2))
1108 return std::move(Err);
1109 if (Error Err = WriteAddress(Entry.Values[0]))
1110 return std::move(Err);
1111 cantFail(WriteAddress(Entry.Values[1]));
1112 if (Error Err = WriteDWARFOperations())
1113 return std::move(Err);
1114 break;
1115 case dwarf::DW_LLE_start_length:
1116 if (Error Err = CheckOperands(2))
1117 return std::move(Err);
1118 if (Error Err = WriteAddress(Entry.Values[0]))
1119 return std::move(Err);
1120 encodeULEB128(Entry.Values[1], OS);
1121 if (Error Err = WriteDWARFOperations())
1122 return std::move(Err);
1123 break;
1124 }
1125
1126 return OS.tell() - BeginOffset;
1127}
1128
1129template <typename EntryType>
1132 bool IsLittleEndian, bool Is64BitAddrSize) {
1133 for (const DWARFYAML::ListTable<EntryType> &Table : Tables) {
1134 // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) +
1135 // sizeof(offset_entry_count) = 8
1136 uint64_t Length = 8;
1137
1138 uint8_t AddrSize;
1139 if (Table.AddrSize)
1140 AddrSize = *Table.AddrSize;
1141 else
1142 AddrSize = Is64BitAddrSize ? 8 : 4;
1143
1144 // Since the length of the current range/location lists entry is
1145 // undetermined yet, we firstly write the content of the range/location
1146 // lists to a buffer to calculate the length and then serialize the buffer
1147 // content to the actual output stream.
1148 std::string ListBuffer;
1149 raw_string_ostream ListBufferOS(ListBuffer);
1150
1151 // Offsets holds offsets for each range/location list. The i-th element is
1152 // the offset from the beginning of the first range/location list to the
1153 // location of the i-th range list.
1154 std::vector<uint64_t> Offsets;
1155
1156 for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) {
1157 Offsets.push_back(ListBufferOS.tell());
1158 if (List.Content) {
1159 List.Content->writeAsBinary(ListBufferOS, UINT64_MAX);
1160 Length += List.Content->binary_size();
1161 } else if (List.Entries) {
1162 for (const EntryType &Entry : *List.Entries) {
1163 Expected<uint64_t> EntrySize =
1164 writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian);
1165 if (!EntrySize)
1166 return EntrySize.takeError();
1167 Length += *EntrySize;
1168 }
1169 }
1170 }
1171
1172 // If the offset_entry_count field isn't specified, yaml2obj will infer it
1173 // from the 'Offsets' field in the YAML description. If the 'Offsets' field
1174 // isn't specified either, yaml2obj will infer it from the auto-generated
1175 // offsets.
1176 uint32_t OffsetEntryCount;
1177 if (Table.OffsetEntryCount)
1178 OffsetEntryCount = *Table.OffsetEntryCount;
1179 else
1180 OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size();
1181 uint64_t OffsetsSize =
1182 OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4);
1183 Length += OffsetsSize;
1184
1185 // If the length is specified in the YAML description, we use it instead of
1186 // the actual length.
1187 if (Table.Length)
1188 Length = *Table.Length;
1189
1190 writeInitialLength(Table.Format, Length, OS, IsLittleEndian);
1191 writeInteger((uint16_t)Table.Version, OS, IsLittleEndian);
1192 writeInteger((uint8_t)AddrSize, OS, IsLittleEndian);
1193 writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian);
1194 writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian);
1195
1196 auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) {
1197 for (uint64_t Offset : Offsets)
1198 writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS,
1199 IsLittleEndian);
1200 };
1201
1202 if (Table.Offsets)
1203 EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(),
1204 Table.Offsets->size()),
1205 0);
1206 else if (OffsetEntryCount != 0)
1207 EmitOffsets(Offsets, OffsetsSize);
1208
1209 OS.write(ListBuffer.data(), ListBuffer.size());
1210 }
1211
1212 return Error::success();
1213}
1214
1216 assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call");
1217 return writeDWARFLists<DWARFYAML::RnglistEntry>(
1219}
1220
1222 assert(DI.DebugLoclists && "unexpected emitDebugRnglists() call");
1223 return writeDWARFLists<DWARFYAML::LoclistEntry>(
1225}
1226
1227std::function<Error(raw_ostream &, const DWARFYAML::Data &)>
1229 auto EmitFunc =
1231 std::function<Error(raw_ostream &, const DWARFYAML::Data &)>>(SecName)
1232 .Case("debug_abbrev", DWARFYAML::emitDebugAbbrev)
1233 .Case("debug_addr", DWARFYAML::emitDebugAddr)
1234 .Case("debug_aranges", DWARFYAML::emitDebugAranges)
1235 .Case("debug_gnu_pubnames", DWARFYAML::emitDebugGNUPubnames)
1236 .Case("debug_gnu_pubtypes", DWARFYAML::emitDebugGNUPubtypes)
1237 .Case("debug_info", DWARFYAML::emitDebugInfo)
1238 .Case("debug_line", DWARFYAML::emitDebugLine)
1239 .Case("debug_loclists", DWARFYAML::emitDebugLoclists)
1240 .Case("debug_pubnames", DWARFYAML::emitDebugPubnames)
1241 .Case("debug_pubtypes", DWARFYAML::emitDebugPubtypes)
1242 .Case("debug_ranges", DWARFYAML::emitDebugRanges)
1243 .Case("debug_rnglists", DWARFYAML::emitDebugRnglists)
1244 .Case("debug_str", DWARFYAML::emitDebugStr)
1245 .Case("debug_str_offsets", DWARFYAML::emitDebugStrOffsets)
1246 .Case("debug_names", DWARFYAML::emitDebugNames)
1247 .Default([&](raw_ostream &, const DWARFYAML::Data &) {
1249 SecName + " is not supported");
1250 });
1251
1252 return EmitFunc;
1253}
1254
1255static Error
1257 StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) {
1258 std::string Data;
1259 raw_string_ostream DebugInfoStream(Data);
1260
1261 auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Sec);
1262
1263 if (Error Err = EmitFunc(DebugInfoStream, DI))
1264 return Err;
1265 DebugInfoStream.flush();
1266 if (!Data.empty())
1267 OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data);
1268
1269 return Error::success();
1270}
1271
1273DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian,
1274 bool Is64BitAddrSize) {
1275 auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) {
1276 *static_cast<SMDiagnostic *>(DiagContext) = Diag;
1277 };
1278
1279 SMDiagnostic GeneratedDiag;
1280 yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic,
1281 &GeneratedDiag);
1282
1283 DWARFYAML::Data DI;
1284 DI.IsLittleEndian = IsLittleEndian;
1285 DI.Is64BitAddrSize = Is64BitAddrSize;
1286
1287 YIn >> DI;
1288 if (YIn.error())
1289 return createStringError(YIn.error(), GeneratedDiag.getMessage());
1290
1292 Error Err = Error::success();
1293
1294 for (StringRef SecName : DI.getNonEmptySectionNames())
1295 Err = joinErrors(std::move(Err),
1296 emitDebugSectionImpl(DI, SecName, DebugSections));
1297
1298 if (Err)
1299 return std::move(Err);
1300 return std::move(DebugSections);
1301}
This file defines the StringMap class.
static void writeDWARFOffset(uint64_t Offset, dwarf::DwarfFormat Format, raw_ostream &OS, bool IsLittleEndian)
static Error emitDebugSectionImpl(const DWARFYAML::Data &DI, StringRef Sec, StringMap< std::unique_ptr< MemoryBuffer > > &OutputBuffers)
static void ZeroFillBytes(raw_ostream &OS, size_t Size)
static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File)
static Error writeDWARFLists(raw_ostream &OS, ArrayRef< DWARFYAML::ListTable< EntryType > > Tables, bool IsLittleEndian, bool Is64BitAddrSize)
static void writeLineTableOpcode(const DWARFYAML::LineTableOpcode &Op, uint8_t OpcodeBase, uint8_t AddrSize, raw_ostream &OS, bool IsLittleEndian)
static Error writeVariableSizedInteger(uint64_t Integer, size_t Size, raw_ostream &OS, bool IsLittleEndian)
static Expected< uint64_t > writeListEntry(raw_ostream &OS, const DWARFYAML::RnglistEntry &Entry, uint8_t AddrSize, bool IsLittleEndian)
static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian)
static void writeExtendedOpcode(const DWARFYAML::LineTableOpcode &Op, uint8_t AddrSize, bool IsLittleEndian, raw_ostream &OS)
static Error checkOperandCount(StringRef EncodingString, ArrayRef< yaml::Hex64 > Values, uint64_t ExpectedOperands)
static Expected< uint64_t > writeDWARFExpression(raw_ostream &OS, const DWARFYAML::DWARFOperation &Operation, uint8_t AddrSize, bool IsLittleEndian)
static Error emitPubSection(raw_ostream &OS, const DWARFYAML::PubSection &Sect, bool IsLittleEndian, bool IsGNUPubSec=false)
static Expected< uint64_t > writeDIE(const DWARFYAML::Data &DI, uint64_t CUIndex, uint64_t AbbrevTableID, const dwarf::FormParams &Params, const DWARFYAML::Entry &Entry, raw_ostream &OS, bool IsLittleEndian)
static void writeInitialLength(const dwarf::DwarfFormat Format, const uint64_t Length, raw_ostream &OS, bool IsLittleEndian)
static std::vector< uint8_t > getStandardOpcodeLengths(uint16_t Version, std::optional< uint8_t > OpcodeBase)
static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS, uint64_t Addr, uint8_t AddrSize, bool IsLittleEndian)
Common declarations for yaml2obj.
This file declares classes for handling the YAML representation of DWARF Debug Info.
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file contains constants used for implementing Dwarf debug support.
uint64_t Addr
uint64_t Size
#define I(x, y, z)
Definition: MD5.cpp:58
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
This class represents an Operation in the Expression.
unsigned size() const
Definition: DenseMap.h:99
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:281
StringRef getMessage() const
Definition: SourceMgr.h:311
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:215
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:416
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
StringRef RangeListEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:591
StringRef LocListEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:602
StringRef OperationEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:138
#define UINT64_MAX
Definition: DataTypes.h:77
@ Entry
Definition: COFF.h:826
Error emitDebugStrOffsets(raw_ostream &OS, const Data &DI)
Error emitDebugInfo(raw_ostream &OS, const Data &DI)
Error emitDebugRanges(raw_ostream &OS, const Data &DI)
Error emitDebugAranges(raw_ostream &OS, const Data &DI)
Error emitDebugGNUPubnames(raw_ostream &OS, const Data &DI)
Error emitDebugAbbrev(raw_ostream &OS, const Data &DI)
Error emitDebugRnglists(raw_ostream &OS, const Data &DI)
Error emitDebugLoclists(raw_ostream &OS, const Data &DI)
std::function< Error(raw_ostream &, const Data &)> getDWARFEmitterByName(StringRef SecName)
Expected< StringMap< std::unique_ptr< MemoryBuffer > > > emitDebugSections(StringRef YAMLString, bool IsLittleEndian=sys::IsLittleEndianHost, bool Is64BitAddrSize=true)
Error emitDebugGNUPubtypes(raw_ostream &OS, const Data &DI)
Error emitDebugStr(raw_ostream &OS, const Data &DI)
Error emitDebugPubnames(raw_ostream &OS, const Data &DI)
Error emitDebugAddr(raw_ostream &OS, const Data &DI)
Error emitDebugNames(raw_ostream &OS, const Data &DI)
Error emitDebugPubtypes(raw_ostream &OS, const Data &DI)
Error emitDebugLine(raw_ostream &OS, const Data &DI)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
DwarfFormat
Constants that define the DWARF format as 32 or 64 bit.
Definition: Dwarf.h:91
@ DWARF64
Definition: Dwarf.h:91
@ DWARF32
Definition: Dwarf.h:91
std::optional< uint8_t > getFixedFormByteSize(dwarf::Form Form, FormParams Params)
Get the fixed byte size for a given form.
Definition: Dwarf.cpp:771
@ DW_LENGTH_DWARF64
Indicator of 64-bit DWARF format.
Definition: Dwarf.h:55
static const bool IsLittleEndianHost
Definition: SwapByteOrder.h:29
void swapByteOrder(T &Value)
Definition: SwapByteOrder.h:61
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
@ Length
Definition: DWP.cpp:480
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition: STLExtras.h:863
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:438
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition: STLExtras.h:1422
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition: STLExtras.h:1432
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
std::vector< AttributeAbbrev > Attributes
Definition: DWARFYAML.h:41
std::optional< yaml::Hex64 > Length
Definition: DWARFYAML.h:188
std::optional< yaml::Hex8 > AddrSize
Definition: DWARFYAML.h:190
dwarf::DwarfFormat Format
Definition: DWARFYAML.h:187
std::vector< SegAddrPair > SegAddrPairs
Definition: DWARFYAML.h:192
std::vector< Unit > Units
Definition: DWARFYAML.h:251
std::vector< LineTable > DebugLines
Definition: DWARFYAML.h:253
std::optional< std::vector< AddrTableEntry > > DebugAddr
Definition: DWARFYAML.h:244
std::optional< std::vector< Ranges > > DebugRanges
Definition: DWARFYAML.h:243
std::optional< std::vector< ListTable< LoclistEntry > > > DebugLoclists
Definition: DWARFYAML.h:255
std::vector< AbbrevTable > DebugAbbrev
Definition: DWARFYAML.h:239
Expected< AbbrevTableInfo > getAbbrevTableInfoByID(uint64_t ID) const
Definition: DWARFYAML.cpp:61
std::optional< PubSection > GNUPubNames
Definition: DWARFYAML.h:248
std::optional< std::vector< ARange > > DebugAranges
Definition: DWARFYAML.h:242
StringRef getAbbrevTableContentByIndex(uint64_t Index) const
std::optional< PubSection > GNUPubTypes
Definition: DWARFYAML.h:249
SetVector< StringRef > getNonEmptySectionNames() const
Definition: DWARFYAML.cpp:25
std::optional< std::vector< StringOffsetsTable > > DebugStrOffsets
Definition: DWARFYAML.h:241
std::optional< std::vector< StringRef > > DebugStrings
Definition: DWARFYAML.h:240
std::optional< std::vector< ListTable< RnglistEntry > > > DebugRnglists
Definition: DWARFYAML.h:254
std::optional< PubSection > PubNames
Definition: DWARFYAML.h:245
std::optional< DebugNamesSection > DebugNames
Definition: DWARFYAML.h:256
std::optional< PubSection > PubTypes
Definition: DWARFYAML.h:246
std::optional< uint64_t > Length
Definition: DWARFYAML.h:166
std::optional< uint8_t > OpcodeBase
Definition: DWARFYAML.h:174
std::vector< LineTableOpcode > Opcodes
Definition: DWARFYAML.h:178
std::optional< uint64_t > PrologueLength
Definition: DWARFYAML.h:168
dwarf::DwarfFormat Format
Definition: DWARFYAML.h:165
std::vector< File > Files
Definition: DWARFYAML.h:177
std::vector< StringRef > IncludeDirs
Definition: DWARFYAML.h:176
std::optional< std::vector< uint8_t > > StandardOpcodeLengths
Definition: DWARFYAML.h:175
dwarf::DwarfFormat Format
Definition: DWARFYAML.h:85
std::vector< PubEntry > Entries
Definition: DWARFYAML.h:90
std::optional< yaml::Hex64 > Length
Definition: DWARFYAML.h:197
std::vector< yaml::Hex64 > Offsets
Definition: DWARFYAML.h:200
std::optional< uint64_t > AbbrevTableID
Definition: DWARFYAML.h:116
yaml::Hex64 TypeOffset
Definition: DWARFYAML.h:119
dwarf::DwarfFormat Format
Definition: DWARFYAML.h:111
std::optional< yaml::Hex64 > Length
Definition: DWARFYAML.h:112
yaml::Hex64 TypeSignatureOrDwoID
Definition: DWARFYAML.h:118
std::optional< uint8_t > AddrSize
Definition: DWARFYAML.h:114
llvm::dwarf::UnitType Type
Definition: DWARFYAML.h:115
std::vector< Entry > Entries
Definition: DWARFYAML.h:121
std::optional< yaml::Hex64 > AbbrOffset
Definition: DWARFYAML.h:117
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition: Dwarf.h:1077
uint8_t getDwarfOffsetByteSize() const
The size of a reference is determined by the DWARF 32/64-bit format.
Definition: Dwarf.h:1095
uint8_t getRefAddrByteSize() const
The definition of the size of form DW_FORM_ref_addr depends on the version.
Definition: Dwarf.h:1088