LLVM 23.0.0git
DWP.cpp
Go to the documentation of this file.
1//===-- llvm-dwp.cpp - Split DWARF merging tool for llvm ------------------===//
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// A utility for merging DWARF 5 Split DWARF .dwo files into .dwp (DWARF
10// package files).
11//
12//===----------------------------------------------------------------------===//
13#include "llvm/DWP/DWP.h"
14#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/Twine.h"
18#include "llvm/DWP/DWPError.h"
19#include "llvm/DWP/ELFWriter.h"
23#include "llvm/Support/LEB128.h"
25#include <limits>
26
27using namespace llvm;
28using namespace llvm::object;
29
30// Returns the size of debug_str_offsets section headers in bytes.
32 uint16_t DwarfVersion) {
33 if (DwarfVersion <= 4)
34 return 0; // There is no header before dwarf 5.
35 uint64_t Offset = 0;
36 uint64_t Length = StrOffsetsData.getU32(&Offset);
38 return 16; // unit length: 12 bytes, version: 2 bytes, padding: 2 bytes.
39 return 8; // unit length: 4 bytes, version: 2 bytes, padding: 2 bytes.
40}
41
42static uint64_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
43 uint64_t Offset = 0;
44 DataExtractor AbbrevData(Abbrev, true, 0);
45 while (AbbrevData.getULEB128(&Offset) != AbbrCode) {
46 // Tag
47 AbbrevData.getULEB128(&Offset);
48 // DW_CHILDREN
49 AbbrevData.getU8(&Offset);
50 // Attributes
51 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
52 ;
53 }
54 return Offset;
55}
56
59 StringRef StrOffsets, StringRef Str, uint16_t Version) {
60 if (Form == dwarf::DW_FORM_string)
61 return InfoData.getCStr(&InfoOffset);
62 uint64_t StrIndex;
63 switch (Form) {
64 case dwarf::DW_FORM_strx1:
65 StrIndex = InfoData.getU8(&InfoOffset);
66 break;
67 case dwarf::DW_FORM_strx2:
68 StrIndex = InfoData.getU16(&InfoOffset);
69 break;
70 case dwarf::DW_FORM_strx3:
71 StrIndex = InfoData.getU24(&InfoOffset);
72 break;
73 case dwarf::DW_FORM_strx4:
74 StrIndex = InfoData.getU32(&InfoOffset);
75 break;
76 case dwarf::DW_FORM_strx:
77 case dwarf::DW_FORM_GNU_str_index:
78 StrIndex = InfoData.getULEB128(&InfoOffset);
79 break;
80 default:
82 "string field must be encoded with one of the following: "
83 "DW_FORM_string, DW_FORM_strx, DW_FORM_strx1, DW_FORM_strx2, "
84 "DW_FORM_strx3, DW_FORM_strx4, or DW_FORM_GNU_str_index.");
85 }
86 DataExtractor StrOffsetsData(StrOffsets, true, 0);
87 uint64_t StrOffsetsOffset = 4 * StrIndex;
88 StrOffsetsOffset += debugStrOffsetsHeaderSize(StrOffsetsData, Version);
89
90 uint64_t StrOffset = StrOffsetsData.getU32(&StrOffsetsOffset);
91 DataExtractor StrData(Str, true, 0);
92 return StrData.getCStr(&StrOffset);
93}
94
97 StringRef Info, StringRef StrOffsets, StringRef Str) {
98 DataExtractor InfoData(Info, true, 0);
99 uint64_t Offset = Header.HeaderSize;
100 if (Header.Version >= 5 && Header.UnitType != dwarf::DW_UT_split_compile)
102 std::string("unit type DW_UT_split_compile type not found in "
103 "debug_info header. Unexpected unit type 0x" +
104 utostr(Header.UnitType) + " found"));
105
107
108 uint32_t AbbrCode = InfoData.getULEB128(&Offset);
109 DataExtractor AbbrevData(Abbrev, true, 0);
110 uint64_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
111 auto Tag = static_cast<dwarf::Tag>(AbbrevData.getULEB128(&AbbrevOffset));
112 if (Tag != dwarf::DW_TAG_compile_unit)
113 return make_error<DWPError>("top level DIE is not a compile unit");
114 // DW_CHILDREN
115 AbbrevData.getU8(&AbbrevOffset);
116 uint32_t Name;
117 dwarf::Form Form;
118 while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
119 (Form = static_cast<dwarf::Form>(
120 AbbrevData.getULEB128(&AbbrevOffset))) &&
121 (Name != 0 || Form != 0)) {
122 switch (Name) {
123 case dwarf::DW_AT_name: {
125 Form, InfoData, Offset, StrOffsets, Str, Header.Version);
126 if (!EName)
127 return EName.takeError();
128 ID.Name = *EName;
129 break;
130 }
131 case dwarf::DW_AT_GNU_dwo_name:
132 case dwarf::DW_AT_dwo_name: {
134 Form, InfoData, Offset, StrOffsets, Str, Header.Version);
135 if (!EName)
136 return EName.takeError();
137 ID.DWOName = *EName;
138 break;
139 }
140 case dwarf::DW_AT_GNU_dwo_id:
141 Header.Signature = InfoData.getU64(&Offset);
142 break;
143 default:
145 Form, InfoData, &Offset,
146 dwarf::FormParams({Header.Version, Header.AddrSize, Header.Format}));
147 }
148 }
149 if (!Header.Signature)
150 return make_error<DWPError>("compile unit missing dwo_id");
151 ID.Signature = *Header.Signature;
152 return ID;
153}
154
158
159// Convert an internal section identifier into the index to use with
160// UnitIndexEntry::Contributions.
162 uint32_t IndexVersion) {
163 assert(serializeSectionKind(Kind, IndexVersion) >= DW_SECT_INFO);
164 return serializeSectionKind(Kind, IndexVersion) - DW_SECT_INFO;
165}
166
167// Convert a UnitIndexEntry::Contributions index to the corresponding on-disk
168// value of the section identifier.
169static unsigned getOnDiskSectionId(unsigned Index) {
170 return Index + DW_SECT_INFO;
171}
172
174 const DWARFUnitIndex::Entry &Entry,
176 const auto *Off = Entry.getContribution(Kind);
177 if (!Off)
178 return StringRef();
179 return Section.substr(Off->getOffset(), Off->getLength());
180}
181
183 uint32_t OverflowedOffset,
185 OnCuIndexOverflow OverflowOptValue,
186 bool &AnySectionOverflow) {
187 std::string Msg =
188 (SectionName +
189 Twine(" Section Contribution Offset overflow 4G. Previous Offset ") +
190 Twine(PrevOffset) + Twine(", After overflow offset ") +
191 Twine(OverflowedOffset) + Twine("."))
192 .str();
193 if (OverflowOptValue == OnCuIndexOverflow::Continue) {
195 return Error::success();
196 } else if (OverflowOptValue == OnCuIndexOverflow::SoftStop) {
197 AnySectionOverflow = true;
199 return Error::success();
200 }
201 return make_error<DWPError>(Msg);
202}
203
205 DWPWriter &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
206 const DWARFUnitIndex &TUIndex, DWPSectionId OutputSection, StringRef Types,
207 const UnitIndexEntry &TUEntry, uint32_t &TypesOffset,
208 unsigned TypesContributionIndex, OnCuIndexOverflow OverflowOptValue,
209 bool &AnySectionOverflow) {
210 Out.switchSection(OutputSection);
211 for (const DWARFUnitIndex::Entry &E : TUIndex.getRows()) {
212 auto *I = E.getContributions();
213 if (!I)
214 continue;
215 auto P = TypeIndexEntries.insert(std::make_pair(E.getSignature(), TUEntry));
216 if (!P.second)
217 continue;
218 auto &Entry = P.first->second;
219 // Zero out the debug_info contribution
220 Entry.Contributions[0] = {};
221 for (auto Kind : TUIndex.getColumnKinds()) {
223 continue;
224 auto &C =
225 Entry.Contributions[getContributionIndex(Kind, TUIndex.getVersion())];
226 C.setOffset(C.getOffset() + I->getOffset());
227 C.setLength(I->getLength());
228 ++I;
229 }
230 auto &C = Entry.Contributions[TypesContributionIndex];
231 Out.emitBytes(Types.substr(
232 C.getOffset() -
233 TUEntry.Contributions[TypesContributionIndex].getOffset(),
234 C.getLength()));
235 C.setOffset(TypesOffset);
236 uint32_t OldOffset = TypesOffset;
237 static_assert(sizeof(OldOffset) == sizeof(TypesOffset));
238 TypesOffset += C.getLength();
239 if (OldOffset > TypesOffset) {
240 if (Error Err = sectionOverflowErrorOrWarning(OldOffset, TypesOffset,
241 "Types", OverflowOptValue,
242 AnySectionOverflow))
243 return Err;
244 if (AnySectionOverflow) {
245 TypesOffset = OldOffset;
246 return Error::success();
247 }
248 }
249 }
250 return Error::success();
251}
252
254 DWPWriter &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
255 DWPSectionId OutputSection, const std::vector<StringRef> &TypesSections,
256 const UnitIndexEntry &CUEntry, uint32_t &TypesOffset,
257 OnCuIndexOverflow OverflowOptValue, bool &AnySectionOverflow) {
258 for (StringRef Types : TypesSections) {
259 Out.switchSection(OutputSection);
260 uint64_t Offset = 0;
261 DataExtractor Data(Types, true, 0);
262 while (Data.isValidOffset(Offset)) {
263 UnitIndexEntry Entry = CUEntry;
264 // Zero out the debug_info contribution
265 Entry.Contributions[0] = {};
266 auto &C = Entry.Contributions[getContributionIndex(DW_SECT_EXT_TYPES, 2)];
267 C.setOffset(TypesOffset);
268 auto PrevOffset = Offset;
269 // Length of the unit, including the 4 byte length field.
270 C.setLength(Data.getU32(&Offset) + 4);
271
272 Data.getU16(&Offset); // Version
273 Data.getU32(&Offset); // Abbrev offset
274 Data.getU8(&Offset); // Address size
275 auto Signature = Data.getU64(&Offset);
276 Offset = PrevOffset + C.getLength32();
277
278 auto P = TypeIndexEntries.insert(std::make_pair(Signature, Entry));
279 if (!P.second)
280 continue;
281
282 Out.emitBytes(Types.substr(PrevOffset, C.getLength32()));
283 uint32_t OldOffset = TypesOffset;
284 TypesOffset += C.getLength32();
285 if (OldOffset > TypesOffset) {
286 if (Error Err = sectionOverflowErrorOrWarning(OldOffset, TypesOffset,
287 "Types", OverflowOptValue,
288 AnySectionOverflow))
289 return Err;
290 if (AnySectionOverflow) {
291 TypesOffset = OldOffset;
292 return Error::success();
293 }
294 }
295 }
296 }
297 return Error::success();
298}
299
300static std::string buildDWODescription(StringRef Name, StringRef DWPName,
301 StringRef DWOName) {
302 std::string Text = "\'";
303 Text += Name;
304 Text += '\'';
305 bool HasDWO = !DWOName.empty();
306 bool HasDWP = !DWPName.empty();
307 if (HasDWO || HasDWP) {
308 Text += " (from ";
309 if (HasDWO) {
310 Text += '\'';
311 Text += DWOName;
312 Text += '\'';
313 }
314 if (HasDWO && HasDWP)
315 Text += " in ";
316 if (!DWPName.empty()) {
317 Text += '\'';
318 Text += DWPName;
319 Text += '\'';
320 }
321 Text += ")";
322 }
323 return Text;
324}
325
328 ("failure while decompressing compressed section: '" + Name + "', " +
329 llvm::toString(std::move(E)))
330 .str());
331}
332
333static Error
334handleCompressedSection(std::deque<SmallString<32>> &UncompressedSections,
335 SectionRef Sec, StringRef Name, StringRef &Contents) {
336 auto *Obj = dyn_cast<ELFObjectFileBase>(Sec.getObject());
337 if (!Obj ||
338 !(static_cast<ELFSectionRef>(Sec).getFlags() & ELF::SHF_COMPRESSED))
339 return Error::success();
340 bool IsLE = isa<object::ELF32LEObjectFile>(Obj) ||
342 bool Is64 = isa<object::ELF64LEObjectFile>(Obj) ||
344 Expected<Decompressor> Dec = Decompressor::create(Name, Contents, IsLE, Is64);
345 if (!Dec)
346 return createError(Name, Dec.takeError());
347
348 UncompressedSections.emplace_back();
349 if (Error E = Dec->resizeAndDecompress(UncompressedSections.back()))
350 return createError(Name, std::move(E));
351
352 Contents = UncompressedSections.back();
353 return Error::success();
354}
355
356static Error
357buildDuplicateError(const std::pair<uint64_t, UnitIndexEntry> &PrevE,
358 const CompileUnitIdentifiers &ID, StringRef DWPName) {
360 std::string("duplicate DWO ID (") + utohexstr(PrevE.first) + ") in " +
361 buildDWODescription(PrevE.second.Name, PrevE.second.DWPName,
362 PrevE.second.DWOName) +
363 " and " + buildDWODescription(ID.Name, DWPName, ID.DWOName));
364}
365
366// Create a mask so we don't trigger a emitIntValue() assert below if the
367// NewOffset is over 4GB.
369 DenseMap<uint64_t, uint64_t> &OffsetRemapping,
371 uint32_t OldOffsetSize, uint32_t NewOffsetSize) {
372 const uint64_t NewOffsetMask = NewOffsetSize == 8 ? UINT64_MAX : UINT32_MAX;
373 while (Offset < Size) {
374 const uint64_t OldOffset = Data.getUnsigned(&Offset, OldOffsetSize);
375 const uint64_t NewOffset = OffsetRemapping[OldOffset];
376 // Truncate the string offset like the old llvm-dwp would have if we aren't
377 // promoting the .debug_str_offsets to DWARF64.
378 Out.emitIntValue(NewOffset & NewOffsetMask, NewOffsetSize);
379 }
380}
381
382namespace llvm {
383// Parse and return the header of an info section compile/type unit.
386 Error Err = Error::success();
387 uint64_t Offset = 0;
388 DWARFDataExtractor InfoData(Info, true, 0);
389 std::tie(Header.Length, Header.Format) =
390 InfoData.getInitialLength(&Offset, &Err);
391 if (Err)
392 return make_error<DWPError>("cannot parse compile unit length: " +
393 llvm::toString(std::move(Err)));
394
395 if (!InfoData.isValidOffset(Offset + (Header.Length - 1))) {
397 "compile unit exceeds .debug_info section range: " +
398 utostr(Offset + Header.Length) + " >= " + utostr(InfoData.size()));
399 }
400
401 Header.Version = InfoData.getU16(&Offset, &Err);
402 if (Err)
403 return make_error<DWPError>("cannot parse compile unit version: " +
404 llvm::toString(std::move(Err)));
405
406 uint64_t MinHeaderLength;
407 if (Header.Version >= 5) {
408 // Size: Version (2), UnitType (1), AddrSize (1), DebugAbbrevOffset (4),
409 // Signature (8)
410 MinHeaderLength = 16;
411 } else {
412 // Size: Version (2), DebugAbbrevOffset (4), AddrSize (1)
413 MinHeaderLength = 7;
414 }
415 if (Header.Length < MinHeaderLength) {
416 return make_error<DWPError>("unit length is too small: expected at least " +
417 utostr(MinHeaderLength) + " got " +
418 utostr(Header.Length) + ".");
419 }
420 if (Header.Version >= 5) {
421 Header.UnitType = InfoData.getU8(&Offset);
422 Header.AddrSize = InfoData.getU8(&Offset);
423 Header.DebugAbbrevOffset = InfoData.getU32(&Offset);
424 Header.Signature = InfoData.getU64(&Offset);
425 if (Header.UnitType == dwarf::DW_UT_split_type) {
426 // Type offset.
427 MinHeaderLength += 4;
428 if (Header.Length < MinHeaderLength)
429 return make_error<DWPError>("type unit is missing type offset");
430 InfoData.getU32(&Offset);
431 }
432 } else {
433 // Note that, address_size and debug_abbrev_offset fields have switched
434 // places between dwarf version 4 and 5.
435 Header.DebugAbbrevOffset = InfoData.getU32(&Offset);
436 Header.AddrSize = InfoData.getU8(&Offset);
437 }
438
439 Header.HeaderSize = Offset;
440 return Header;
441}
442
443static void
445 StringRef CurStrSection, StringRef CurStrOffsetSection,
446 uint16_t Version, SectionLengths &SectionLength,
447 const Dwarf64StrOffsetsPromotion StrOffsetsOptValue,
448 bool SingleInput) {
449 // Could possibly produce an error or warning if one of these was non-null but
450 // the other was null.
451 if (CurStrSection.empty() || CurStrOffsetSection.empty())
452 return;
453
454 // Fast path: when there is only one input, all strings are unique and offsets
455 // don't need remapping. Copy both sections directly without any hashing.
456 if (SingleInput && StrOffsetsOptValue != Dwarf64StrOffsetsPromotion::Always) {
458 Out.emitBytes(CurStrSection);
460 Out.emitBytes(CurStrOffsetSection);
461 return;
462 }
463
464 DenseMap<uint64_t, uint64_t> OffsetRemapping;
465 // Pre-reserve based on estimated string count to avoid rehashing.
466 OffsetRemapping.reserve(CurStrSection.size() / 20);
467
468 DataExtractor Data(CurStrSection, true, 0);
469 uint64_t LocalOffset = 0;
470 uint64_t PrevOffset = 0;
471
472 // Keep track if any new string offsets exceed UINT32_MAX. If any do, we can
473 // emit a DWARF64 .debug_str_offsets table for this compile unit. If the
474 // \a StrOffsetsOptValue argument is Dwarf64StrOffsetsPromotion::Always, then
475 // force the emission of DWARF64 .debug_str_offsets for testing.
476 uint32_t OldOffsetSize = 4;
477 uint32_t NewOffsetSize =
478 StrOffsetsOptValue == Dwarf64StrOffsetsPromotion::Always ? 8 : 4;
479 while (const char *S = Data.getCStr(&LocalOffset)) {
480 uint64_t NewOffset = Strings.getOffset(S, LocalOffset - PrevOffset);
481 OffsetRemapping[PrevOffset] = NewOffset;
482 // Only promote the .debug_str_offsets to DWARF64 if our setting allows it.
483 if (StrOffsetsOptValue != Dwarf64StrOffsetsPromotion::Disabled &&
484 NewOffset > UINT32_MAX) {
485 NewOffsetSize = 8;
486 }
487 PrevOffset = LocalOffset;
488 }
489
490 Data = DataExtractor(CurStrOffsetSection, true, 0);
491
493
494 uint64_t Offset = 0;
495 uint64_t Size = CurStrOffsetSection.size();
496 if (Version > 4) {
497 while (Offset < Size) {
498 const uint64_t HeaderSize = debugStrOffsetsHeaderSize(Data, Version);
499 assert(HeaderSize <= Size - Offset &&
500 "StrOffsetSection size is less than its header");
501
502 uint64_t ContributionEnd = 0;
503 uint64_t ContributionSize = 0;
504 uint64_t HeaderLengthOffset = Offset;
505 if (HeaderSize == 8) {
506 ContributionSize = Data.getU32(&HeaderLengthOffset);
507 } else if (HeaderSize == 16) {
508 OldOffsetSize = 8;
509 HeaderLengthOffset += 4; // skip the dwarf64 marker
510 ContributionSize = Data.getU64(&HeaderLengthOffset);
511 }
512 ContributionEnd = ContributionSize + HeaderLengthOffset;
513
514 StringRef HeaderBytes = Data.getBytes(&Offset, HeaderSize);
515 if (OldOffsetSize == 4 && NewOffsetSize == 8) {
516 // We had a DWARF32 .debug_str_offsets header, but we need to emit
517 // some string offsets that require 64 bit offsets on the .debug_str
518 // section. Emit the .debug_str_offsets header in DWARF64 format so we
519 // can emit string offsets that exceed UINT32_MAX without truncating
520 // the string offset.
521
522 // 2 bytes for DWARF version, 2 bytes pad.
523 const uint64_t VersionPadSize = 4;
524 const uint64_t NewLength =
525 (ContributionSize - VersionPadSize) * 2 + VersionPadSize;
526 // Emit the DWARF64 length that starts with a 4 byte DW_LENGTH_DWARF64
527 // value followed by the 8 byte updated length.
529 Out.emitIntValue(NewLength, 8);
530 // Emit DWARF version as a 2 byte integer.
531 Out.emitIntValue(Version, 2);
532 // Emit 2 bytes of padding.
533 Out.emitIntValue(0, 2);
534 // Update the .debug_str_offsets section length contribution for the
535 // this .dwo file.
536 for (auto &Pair : SectionLength) {
537 if (Pair.first == DW_SECT_STR_OFFSETS) {
538 Pair.second = NewLength + 12;
539 break;
540 }
541 }
542 } else {
543 // Just emit the same .debug_str_offsets header.
544 Out.emitBytes(HeaderBytes);
545 }
546 writeNewOffsetsTo(Out, Data, OffsetRemapping, Offset, ContributionEnd,
547 OldOffsetSize, NewOffsetSize);
548 }
549
550 } else {
551 assert(OldOffsetSize == NewOffsetSize);
552 writeNewOffsetsTo(Out, Data, OffsetRemapping, Offset, Size, OldOffsetSize,
553 NewOffsetSize);
554 }
555}
556
558
559static void
561 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
562 const AccessField &Field) {
563 for (const auto &E : IndexEntries)
564 for (size_t I = 0; I != std::size(E.second.Contributions); ++I)
565 if (ContributionOffsets[I])
567 ? E.second.Contributions[I].getOffset32()
568 : E.second.Contributions[I].getLength32()),
569 4);
570}
571
572static void writeIndex(DWPWriter &Out, DWPSectionId Section,
573 ArrayRef<unsigned> ContributionOffsets,
574 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
575 uint32_t IndexVersion) {
576 if (IndexEntries.empty())
577 return;
578
579 unsigned Columns = 0;
580 for (auto &C : ContributionOffsets)
581 if (C)
582 ++Columns;
583
584 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
585 uint64_t Mask = Buckets.size() - 1;
586 size_t I = 0;
587 for (const auto &P : IndexEntries) {
588 auto S = P.first;
589 auto H = S & Mask;
590 auto HP = ((S >> 32) & Mask) | 1;
591 while (Buckets[H]) {
592 assert(S != IndexEntries.begin()[Buckets[H] - 1].first &&
593 "Duplicate unit");
594 H = (H + HP) & Mask;
595 }
596 Buckets[H] = I + 1;
597 ++I;
598 }
599
600 Out.switchSection(Section);
601 Out.emitIntValue(IndexVersion, 4); // Version
602 Out.emitIntValue(Columns, 4); // Columns
603 Out.emitIntValue(IndexEntries.size(), 4); // Num Units
604 Out.emitIntValue(Buckets.size(), 4); // Num Buckets
605
606 // Write the signatures.
607 for (const auto &I : Buckets)
608 Out.emitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8);
609
610 // Write the indexes.
611 for (const auto &I : Buckets)
612 Out.emitIntValue(I, 4);
613
614 // Write the column headers (which sections will appear in the table)
615 for (size_t I = 0; I != ContributionOffsets.size(); ++I)
616 if (ContributionOffsets[I])
618
619 // Write the offsets.
620 writeIndexTable(Out, ContributionOffsets, IndexEntries, AccessField::Offset);
621
622 // Write the lengths.
623 writeIndexTable(Out, ContributionOffsets, IndexEntries, AccessField::Length);
624}
625
626/// Map input ELF section names to DWP section IDs and DWARF section kinds.
630 {"debug_info.dwo", {DS_Info, DW_SECT_INFO}},
631 {"debug_types.dwo", {DS_Types, DW_SECT_EXT_TYPES}},
632 {"debug_str_offsets.dwo", {DS_StrOffsets, DW_SECT_STR_OFFSETS}},
633 {"debug_str.dwo", {DS_Str, static_cast<DWARFSectionKind>(0)}},
634 {"debug_loc.dwo", {DS_Loc, DW_SECT_EXT_LOC}},
635 {"debug_line.dwo", {DS_Line, DW_SECT_LINE}},
636 {"debug_macro.dwo", {DS_Macro, DW_SECT_MACRO}},
637 {"debug_abbrev.dwo", {DS_Abbrev, DW_SECT_ABBREV}},
638 {"debug_loclists.dwo", {DS_Loclists, DW_SECT_LOCLISTS}},
639 {"debug_rnglists.dwo", {DS_Rnglists, DW_SECT_RNGLISTS}},
640 {"debug_cu_index", {DS_CUIndex, static_cast<DWARFSectionKind>(0)}},
641 {"debug_tu_index", {DS_TUIndex, static_cast<DWARFSectionKind>(0)}},
642 };
643 return Map;
644}
645
647 const StringMap<std::pair<DWPSectionId, DWARFSectionKind>> &KnownSections,
648 const SectionRef &Section, DWPWriter &Out,
649 std::deque<SmallString<32>> &UncompressedSections,
650 uint32_t (&ContributionOffsets)[8], UnitIndexEntry &CurEntry,
651 StringRef &CurStrSection, StringRef &CurStrOffsetSection,
652 std::vector<StringRef> &CurTypesSection,
653 std::vector<StringRef> &CurInfoSection, StringRef &AbbrevSection,
654 StringRef &CurCUIndexSection, StringRef &CurTUIndexSection,
655 SectionLengths &SectionLength) {
656 if (Section.isBSS())
657 return Error::success();
658
659 if (Section.isVirtual())
660 return Error::success();
661
662 Expected<StringRef> NameOrErr = Section.getName();
663 if (!NameOrErr)
664 return NameOrErr.takeError();
665 StringRef Name = *NameOrErr;
666
667 Expected<StringRef> ContentsOrErr = Section.getContents();
668 if (!ContentsOrErr)
669 return ContentsOrErr.takeError();
670 StringRef Contents = *ContentsOrErr;
671
672 if (auto Err = handleCompressedSection(UncompressedSections, Section, Name,
673 Contents))
674 return Err;
675
676 Name = Name.substr(Name.find_first_not_of("._"));
677
678 auto SectionPair = KnownSections.find(Name);
679 if (SectionPair == KnownSections.end())
680 return Error::success();
681
682 DWPSectionId SectionId = SectionPair->second.first;
683 DWARFSectionKind Kind = SectionPair->second.second;
684
685 if (Kind) {
686 if (Kind != DW_SECT_EXT_TYPES && Kind != DW_SECT_INFO)
687 SectionLength.push_back(std::make_pair(Kind, Contents.size()));
688 if (Kind == DW_SECT_ABBREV)
689 AbbrevSection = Contents;
690 }
691
692 switch (SectionId) {
693 case DS_StrOffsets:
694 CurStrOffsetSection = Contents;
695 break;
696 case DS_Str:
697 CurStrSection = Contents;
698 break;
699 case DS_Types:
700 CurTypesSection.push_back(Contents);
701 break;
702 case DS_CUIndex:
703 CurCUIndexSection = Contents;
704 break;
705 case DS_TUIndex:
706 CurTUIndexSection = Contents;
707 break;
708 case DS_Info:
709 CurInfoSection.push_back(Contents);
710 break;
711 default:
712 // Pass-through: emit directly to output (zero-copy).
713 Out.switchSection(SectionId);
714 Out.emitBytes(Contents);
715 break;
716 }
717 return Error::success();
718}
719
721 OnCuIndexOverflow OverflowOptValue,
722 Dwarf64StrOffsetsPromotion StrOffsetsOptValue,
723 raw_pwrite_stream *OutputOS) {
724 const auto &KnownSections = getKnownSections();
725
728
729 uint32_t ContributionOffsets[8] = {};
730 uint16_t Version = 0;
731 uint32_t IndexVersion = 0;
732 StringRef FirstInput;
733 bool AnySectionOverflow = false;
734
736
738 Objects.reserve(Inputs.size());
739
740 std::deque<SmallString<32>> UncompressedSections;
741
742 bool MachineSet = false;
743
744 for (const auto &Input : Inputs) {
746 if (!ErrOrObj) {
747 return handleErrors(ErrOrObj.takeError(),
748 [&](std::unique_ptr<ECError> EC) -> Error {
749 return createFileError(Input, Error(std::move(EC)));
750 });
751 }
752
753 auto &Obj = *ErrOrObj->getBinary();
754 Objects.push_back(std::move(*ErrOrObj));
755
756 // Set output format metadata from the first input file.
757 if (!MachineSet) {
758 if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) {
759 Out.setMachine(ELFObj->getEMachine());
760 Out.setOSABI(ELFObj->getOS());
761 } else if (Obj.isWasm()) {
762 Out.setIsWASM(true);
763 }
764 MachineSet = true;
765 }
766
767 UnitIndexEntry CurEntry = {};
768
769 StringRef CurStrSection;
770 StringRef CurStrOffsetSection;
771 std::vector<StringRef> CurTypesSection;
772 std::vector<StringRef> CurInfoSection;
773 StringRef AbbrevSection;
774 StringRef CurCUIndexSection;
775 StringRef CurTUIndexSection;
776
777 // This maps each section contained in this file to its length.
778 // This information is later on used to calculate the contributions,
779 // i.e. offset and length, of each compile/type unit to a section.
780 SectionLengths SectionLength;
781
782 for (const auto &Section : Obj.sections())
783 if (auto Err = handleSection(
784 KnownSections, Section, Out, UncompressedSections,
785 ContributionOffsets, CurEntry, CurStrSection, CurStrOffsetSection,
786 CurTypesSection, CurInfoSection, AbbrevSection, CurCUIndexSection,
787 CurTUIndexSection, SectionLength))
788 return Err;
789
790 if (CurInfoSection.empty())
791 continue;
792
794 parseInfoSectionUnitHeader(CurInfoSection.front());
795 if (!HeaderOrErr)
796 return HeaderOrErr.takeError();
797 InfoSectionUnitHeader &Header = *HeaderOrErr;
798
799 if (Version == 0) {
800 Version = Header.Version;
801 IndexVersion = Version < 5 ? 2 : 5;
802 FirstInput = Input;
803 } else if (Version != Header.Version) {
805 "incompatible DWARF compile unit version: " + Input + " (version " +
806 utostr(Header.Version) + ") and " + FirstInput.str() + " (version " +
807 utostr(Version) + ")");
808 }
809
810 writeStringsAndOffsets(Out, Strings, CurStrSection, CurStrOffsetSection,
811 Header.Version, SectionLength, StrOffsetsOptValue,
812 Inputs.size() == 1);
813
814 for (auto Pair : SectionLength) {
815 auto Index = getContributionIndex(Pair.first, IndexVersion);
816 CurEntry.Contributions[Index].setOffset(ContributionOffsets[Index]);
817 CurEntry.Contributions[Index].setLength(Pair.second);
818 uint32_t OldOffset = ContributionOffsets[Index];
819 ContributionOffsets[Index] += CurEntry.Contributions[Index].getLength32();
820 if (OldOffset > ContributionOffsets[Index]) {
821 uint32_t SectionIndex = 0;
822 for (auto &Section : Obj.sections()) {
823 if (SectionIndex == Index) {
825 OldOffset, ContributionOffsets[Index], *Section.getName(),
826 OverflowOptValue, AnySectionOverflow))
827 return Err;
828 }
829 ++SectionIndex;
830 }
831 if (AnySectionOverflow)
832 break;
833 }
834 }
835
836 uint32_t &InfoSectionOffset =
837 ContributionOffsets[getContributionIndex(DW_SECT_INFO, IndexVersion)];
838 if (CurCUIndexSection.empty()) {
839 bool FoundCUUnit = false;
841 for (StringRef Info : CurInfoSection) {
842 uint64_t UnitOffset = 0;
843 while (Info.size() > UnitOffset) {
844 Expected<InfoSectionUnitHeader> HeaderOrError =
845 parseInfoSectionUnitHeader(Info.substr(UnitOffset, Info.size()));
846 if (!HeaderOrError)
847 return HeaderOrError.takeError();
848 InfoSectionUnitHeader &Header = *HeaderOrError;
849
850 UnitIndexEntry Entry = CurEntry;
851 auto &C = Entry.Contributions[getContributionIndex(DW_SECT_INFO,
852 IndexVersion)];
853 C.setOffset(InfoSectionOffset);
854 C.setLength(Header.Length + 4);
855
856 if (std::numeric_limits<uint32_t>::max() - InfoSectionOffset <
857 C.getLength32()) {
859 InfoSectionOffset, InfoSectionOffset + C.getLength32(),
860 "debug_info", OverflowOptValue, AnySectionOverflow))
861 return Err;
862 if (AnySectionOverflow) {
863 FoundCUUnit = true;
864 break;
865 }
866 }
867
868 UnitOffset += C.getLength32();
869 if (Header.Version < 5 ||
870 Header.UnitType == dwarf::DW_UT_split_compile) {
872 Header, AbbrevSection,
873 Info.substr(UnitOffset - C.getLength32(), C.getLength32()),
874 CurStrOffsetSection, CurStrSection);
875
876 if (!EID)
877 return createFileError(Input, EID.takeError());
878 const auto &ID = *EID;
879 auto P = IndexEntries.insert(std::make_pair(ID.Signature, Entry));
880 if (!P.second)
881 return buildDuplicateError(*P.first, ID, "");
882 P.first->second.Name = ID.Name;
883 P.first->second.DWOName = ID.DWOName;
884
885 FoundCUUnit = true;
886 } else if (Header.UnitType == dwarf::DW_UT_split_type) {
887 auto P = TypeIndexEntries.insert(
888 std::make_pair(*Header.Signature, Entry));
889 if (!P.second)
890 continue;
891 }
892 Out.emitBytes(
893 Info.substr(UnitOffset - C.getLength32(), C.getLength32()));
894 InfoSectionOffset += C.getLength32();
895 }
896 if (AnySectionOverflow)
897 break;
898 }
899
900 if (!FoundCUUnit)
901 return make_error<DWPError>("no compile unit found in file: " + Input);
902
903 if (IndexVersion == 2) {
904 // Add types from the .debug_types section from DWARF < 5.
906 Out, TypeIndexEntries, DS_Types, CurTypesSection, CurEntry,
907 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES, 2)],
908 OverflowOptValue, AnySectionOverflow))
909 return Err;
910 }
911 if (AnySectionOverflow)
912 break;
913 continue;
914 }
915
916 if (CurInfoSection.size() != 1)
917 return make_error<DWPError>("expected exactly one occurrence of a debug "
918 "info section in a .dwp file");
919 StringRef DwpSingleInfoSection = CurInfoSection.front();
920
921 DWARFUnitIndex CUIndex(DW_SECT_INFO);
922 DataExtractor CUIndexData(CurCUIndexSection, Obj.isLittleEndian(), 0);
923 if (!CUIndex.parse(CUIndexData))
924 return make_error<DWPError>("failed to parse cu_index");
925 if (CUIndex.getVersion() != IndexVersion)
926 return make_error<DWPError>("incompatible cu_index versions, found " +
927 utostr(CUIndex.getVersion()) +
928 " and expecting " + utostr(IndexVersion));
929
931 for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
932 auto *I = E.getContributions();
933 if (!I)
934 continue;
935 auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
936 StringRef CUInfoSection =
937 getSubsection(DwpSingleInfoSection, E, DW_SECT_INFO);
938 Expected<InfoSectionUnitHeader> HeaderOrError =
939 parseInfoSectionUnitHeader(CUInfoSection);
940 if (!HeaderOrError)
941 return HeaderOrError.takeError();
942 InfoSectionUnitHeader &Header = *HeaderOrError;
943
945 Header, getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
946 CUInfoSection,
947 getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
948 CurStrSection);
949 if (!EID)
950 return createFileError(Input, EID.takeError());
951 const auto &ID = *EID;
952 if (!P.second)
953 return buildDuplicateError(*P.first, ID, Input);
954 auto &NewEntry = P.first->second;
955 NewEntry.Name = ID.Name;
956 NewEntry.DWOName = ID.DWOName;
957 NewEntry.DWPName = Input;
958 for (auto Kind : CUIndex.getColumnKinds()) {
960 continue;
961 auto &C =
962 NewEntry.Contributions[getContributionIndex(Kind, IndexVersion)];
963 C.setOffset(C.getOffset() + I->getOffset());
964 C.setLength(I->getLength());
965 ++I;
966 }
967 unsigned Index = getContributionIndex(DW_SECT_INFO, IndexVersion);
968 auto &C = NewEntry.Contributions[Index];
969 Out.emitBytes(CUInfoSection);
970 C.setOffset(InfoSectionOffset);
971 InfoSectionOffset += C.getLength32();
972 }
973
974 if (!CurTUIndexSection.empty()) {
975 llvm::DWARFSectionKind TUSectionKind;
976 DWPSectionId OutSection;
977 StringRef TypeInputSection;
978 // Write type units into debug info section for DWARFv5.
979 if (Version >= 5) {
980 TUSectionKind = DW_SECT_INFO;
981 OutSection = DS_Info;
982 TypeInputSection = DwpSingleInfoSection;
983 } else {
984 // Write type units into debug types section for DWARF < 5.
985 if (CurTypesSection.size() != 1)
987 "multiple type unit sections in .dwp file");
988
989 TUSectionKind = DW_SECT_EXT_TYPES;
990 OutSection = DS_Types;
991 TypeInputSection = CurTypesSection.front();
992 }
993
994 DWARFUnitIndex TUIndex(TUSectionKind);
995 DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0);
996 if (!TUIndex.parse(TUIndexData))
997 return make_error<DWPError>("failed to parse tu_index");
998 if (TUIndex.getVersion() != IndexVersion)
999 return make_error<DWPError>("incompatible tu_index versions, found " +
1000 utostr(TUIndex.getVersion()) +
1001 " and expecting " + utostr(IndexVersion));
1002
1003 unsigned TypesContributionIndex =
1004 getContributionIndex(TUSectionKind, IndexVersion);
1005 if (Error Err = addAllTypesFromDWP(
1006 Out, TypeIndexEntries, TUIndex, OutSection, TypeInputSection,
1007 CurEntry, ContributionOffsets[TypesContributionIndex],
1008 TypesContributionIndex, OverflowOptValue, AnySectionOverflow))
1009 return Err;
1010 }
1011 if (AnySectionOverflow)
1012 break;
1013 }
1014
1015 if (Version < 5) {
1016 // Lie about there being no info contributions so the TU index only includes
1017 // the type unit contribution for DWARF < 5. In DWARFv5 the TU index has a
1018 // contribution to the info section, so we do not want to lie about it.
1019 ContributionOffsets[0] = 0;
1020 }
1021 writeIndex(Out, DS_TUIndex, ContributionOffsets, TypeIndexEntries,
1022 IndexVersion);
1023
1024 if (Version < 5) {
1025 // Lie about the type contribution for DWARF < 5. In DWARFv5 the type
1026 // section does not exist, so no need to do anything about this.
1027 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES, 2)] = 0;
1028 // Unlie about the info contribution
1029 ContributionOffsets[0] = 1;
1030 }
1031
1032 writeIndex(Out, DS_CUIndex, ContributionOffsets, IndexEntries, IndexVersion);
1033
1034 // Write ELF output while input data is still alive (zero-copy chunks
1035 // reference mmap'd input data held by the Objects vector above).
1036 if (OutputOS)
1037 return Out.write(*OutputOS);
1038
1039 return Error::success();
1040}
1041
1042//===----------------------------------------------------------------------===//
1043// DWPWriter::writeELF — produce a minimal ELF64 relocatable object.
1044//===----------------------------------------------------------------------===//
1045
1048
1049 // Section metadata table.
1050 struct SectionMeta {
1051 DWPSectionId Id;
1052 const char *Name;
1053 uint64_t Flags;
1054 uint64_t EntSize;
1055 };
1056 static constexpr SectionMeta Meta[] = {
1057 {DS_Loclists, ".debug_loclists.dwo", ELF::SHF_EXCLUDE, 0},
1058 {DS_Loc, ".debug_loc.dwo", ELF::SHF_EXCLUDE, 0},
1059 {DS_Abbrev, ".debug_abbrev.dwo", ELF::SHF_EXCLUDE, 0},
1060 {DS_Line, ".debug_line.dwo", ELF::SHF_EXCLUDE, 0},
1061 {DS_Rnglists, ".debug_rnglists.dwo", ELF::SHF_EXCLUDE, 0},
1062 {DS_Macro, ".debug_macro.dwo", ELF::SHF_EXCLUDE, 0},
1063 {DS_Str, ".debug_str.dwo",
1065 {DS_StrOffsets, ".debug_str_offsets.dwo", ELF::SHF_EXCLUDE, 0},
1066 {DS_Info, ".debug_info.dwo", ELF::SHF_EXCLUDE, 0},
1067 {DS_Types, ".debug_types.dwo", ELF::SHF_EXCLUDE, 0},
1068 {DS_TUIndex, ".debug_tu_index", 0, 0},
1069 {DS_CUIndex, ".debug_cu_index", 0, 0},
1070 };
1071
1072 // Collect non-empty sections and build the section name string table.
1073 struct OutputEntry {
1074 const SectionData *Data;
1075 const char *Name;
1076 uint64_t Flags;
1077 uint64_t EntSize;
1078 uint32_t NameOffset;
1079 uint64_t FileOffset; // filled in during layout
1080 };
1082
1083 SmallString<256> Strtab;
1084 Strtab.push_back('\0'); // null string at offset 0
1085
1086 for (const auto &M : Meta) {
1087 if (Sections[M.Id].empty())
1088 continue;
1089 uint32_t NameOff = Strtab.size();
1090 Strtab.append(M.Name);
1091 Strtab.push_back('\0');
1092 Entries.push_back(
1093 {&Sections[M.Id], M.Name, M.Flags, M.EntSize, NameOff, 0});
1094 }
1095
1096 // Add .strtab and .symtab name entries.
1097 uint32_t StrtabNameOff = Strtab.size();
1098 Strtab.append(".strtab");
1099 Strtab.push_back('\0');
1100 uint32_t SymtabNameOff = Strtab.size();
1101 Strtab.append(".symtab");
1102 Strtab.push_back('\0');
1103
1104 // Layout:
1105 // [ELF Header] 64 bytes
1106 // [section data...] variable
1107 // [.strtab data] variable
1108 // [padding to 8-byte align]
1109 // [.symtab data] 24 bytes (one null entry)
1110 // [padding to 8-byte align]
1111 // [Section Header Table] 64 * NumSections bytes
1112
1113 constexpr uint64_t EhdrSize = sizeof(ELF::Elf64_Ehdr);
1114 constexpr uint64_t SymEntSize = 24;
1115
1116 uint64_t Offset = EhdrSize;
1117 for (auto &E : Entries) {
1118 E.FileOffset = Offset;
1119 Offset += E.Data->totalSize();
1120 }
1121
1122 uint64_t StrtabOffset = Offset;
1123 Offset += Strtab.size();
1124
1125 uint64_t SymtabOffset = alignTo(Offset, 8);
1126 Offset = SymtabOffset + SymEntSize;
1127
1128 uint64_t SHTOffset = alignTo(Offset, 8);
1129
1130 // Section indices: [0]=null, [1..N]=data, [N+1]=strtab, [N+2]=symtab
1131 uint32_t StrtabIdx = 1 + Entries.size();
1132 uint32_t SymtabIdx = StrtabIdx + 1;
1133 uint32_t NumSections = SymtabIdx + 1;
1134
1135 // --- Write ELF header ---
1136 ELF::writeHeader(Wr, /*Is64Bit=*/true, ELFOSABI, /*ABIVersion=*/0, ELFMachine,
1137 /*EFlags=*/0, SHTOffset, NumSections, StrtabIdx);
1138
1139 // --- Write section data ---
1140 for (const auto &E : Entries)
1141 E.Data->writeTo(OS);
1142
1143 // --- Write .strtab ---
1144 OS.write(Strtab.data(), Strtab.size());
1145
1146 // --- Pad + write .symtab (one null symbol entry) ---
1147 OS.write_zeros(SymtabOffset - (StrtabOffset + Strtab.size()));
1148 OS.write_zeros(SymEntSize);
1149
1150 // --- Pad for section header table ---
1151 uint64_t CurPos = SymtabOffset + SymEntSize;
1152 OS.write_zeros(SHTOffset - CurPos);
1153
1154 // [0] ELF::SHT_NULL
1155 ELF::writeSectionHeader(Wr, true, 0, ELF::SHT_NULL, 0, 0, 0, 0, 0, 0, 0, 0);
1156
1157 // [1..N] data sections
1158 for (const auto &E : Entries)
1159 ELF::writeSectionHeader(Wr, true, E.NameOffset, ELF::SHT_PROGBITS, E.Flags,
1160 0, E.FileOffset, E.Data->totalSize(), 0, 0, 1,
1161 E.EntSize);
1162
1163 // [N+1] .strtab
1164 ELF::writeSectionHeader(Wr, true, StrtabNameOff, ELF::SHT_STRTAB, 0, 0,
1165 StrtabOffset, Strtab.size(), 0, 0, 1, 0);
1166
1167 // [N+2] .symtab
1168 ELF::writeSectionHeader(Wr, true, SymtabNameOff, ELF::SHT_SYMTAB, 0, 0,
1169 SymtabOffset, SymEntSize, StrtabIdx, 1, 8,
1170 SymEntSize);
1171
1172 return Error::success();
1173}
1174
1175//===----------------------------------------------------------------------===//
1176// DWPWriter::writeWASM — produce a minimal WASM object with custom sections.
1177//===----------------------------------------------------------------------===//
1178
1180 // Section name table (same names as ELF but without SHF_EXCLUDE flags).
1181 static constexpr struct {
1182 DWPSectionId Id;
1183 const char *Name;
1184 } Meta[] = {
1185 {DS_Loclists, ".debug_loclists.dwo"},
1186 {DS_Loc, ".debug_loc.dwo"},
1187 {DS_Abbrev, ".debug_abbrev.dwo"},
1188 {DS_Line, ".debug_line.dwo"},
1189 {DS_Rnglists, ".debug_rnglists.dwo"},
1190 {DS_Macro, ".debug_macro.dwo"},
1191 {DS_Str, ".debug_str.dwo"},
1192 {DS_StrOffsets, ".debug_str_offsets.dwo"},
1193 {DS_Info, ".debug_info.dwo"},
1194 {DS_Types, ".debug_types.dwo"},
1195 {DS_TUIndex, ".debug_tu_index"},
1196 {DS_CUIndex, ".debug_cu_index"},
1197 };
1198
1199 // WASM magic and version.
1200 OS.write("\0asm", 4);
1201 const uint8_t Version[] = {0x01, 0x00, 0x00, 0x00};
1202 OS.write(reinterpret_cast<const char *>(Version), 4);
1203
1204 // Emit each non-empty section as a WASM custom section (id=0).
1205 for (const auto &M : Meta) {
1206 const SectionData &SD = Sections[M.Id];
1207 if (SD.empty())
1208 continue;
1209
1210 size_t NameLen = strlen(M.Name);
1211 uint64_t PayloadSize = SD.totalSize();
1212
1213 // Custom section payload = ULEB128(name_len) + name + data.
1214 uint8_t NameLenEncoded[10];
1215 unsigned NameLenSize = encodeULEB128(NameLen, NameLenEncoded);
1216 uint64_t SectionPayloadSize = NameLenSize + NameLen + PayloadSize;
1217
1218 // Section header: id byte + ULEB128(section_payload_size).
1219 OS.write(0x00); // Custom section id
1220 uint8_t SizeEncoded[10];
1221 unsigned SizeLen = encodeULEB128(SectionPayloadSize, SizeEncoded);
1222 OS.write(reinterpret_cast<const char *>(SizeEncoded), SizeLen);
1223
1224 // Name
1225 OS.write(reinterpret_cast<const char *>(NameLenEncoded), NameLenSize);
1226 OS.write(M.Name, NameLen);
1227
1228 // Data
1229 SD.writeTo(OS);
1230 }
1231
1232 return Error::success();
1233}
1234
1235} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static unsigned getContributionIndex(DWARFSectionKind Kind, uint32_t IndexVersion)
Definition DWP.cpp:161
static uint64_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode)
Definition DWP.cpp:42
static Error handleCompressedSection(std::deque< SmallString< 32 > > &UncompressedSections, SectionRef Sec, StringRef Name, StringRef &Contents)
Definition DWP.cpp:334
static std::string buildDWODescription(StringRef Name, StringRef DWPName, StringRef DWOName)
Definition DWP.cpp:300
static void writeNewOffsetsTo(DWPWriter &Out, DataExtractor &Data, DenseMap< uint64_t, uint64_t > &OffsetRemapping, uint64_t &Offset, const uint64_t Size, uint32_t OldOffsetSize, uint32_t NewOffsetSize)
Definition DWP.cpp:368
static uint64_t debugStrOffsetsHeaderSize(DataExtractor StrOffsetsData, uint16_t DwarfVersion)
Definition DWP.cpp:31
static Error addAllTypesFromTypesSection(DWPWriter &Out, MapVector< uint64_t, UnitIndexEntry > &TypeIndexEntries, DWPSectionId OutputSection, const std::vector< StringRef > &TypesSections, const UnitIndexEntry &CUEntry, uint32_t &TypesOffset, OnCuIndexOverflow OverflowOptValue, bool &AnySectionOverflow)
Definition DWP.cpp:253
static Expected< const char * > getIndexedString(dwarf::Form Form, DataExtractor InfoData, uint64_t &InfoOffset, StringRef StrOffsets, StringRef Str, uint16_t Version)
Definition DWP.cpp:58
static unsigned getOnDiskSectionId(unsigned Index)
Definition DWP.cpp:169
static Expected< CompileUnitIdentifiers > getCUIdentifiers(InfoSectionUnitHeader &Header, StringRef Abbrev, StringRef Info, StringRef StrOffsets, StringRef Str)
Definition DWP.cpp:96
static Error sectionOverflowErrorOrWarning(uint32_t PrevOffset, uint32_t OverflowedOffset, StringRef SectionName, OnCuIndexOverflow OverflowOptValue, bool &AnySectionOverflow)
Definition DWP.cpp:182
static Error addAllTypesFromDWP(DWPWriter &Out, MapVector< uint64_t, UnitIndexEntry > &TypeIndexEntries, const DWARFUnitIndex &TUIndex, DWPSectionId OutputSection, StringRef Types, const UnitIndexEntry &TUEntry, uint32_t &TypesOffset, unsigned TypesContributionIndex, OnCuIndexOverflow OverflowOptValue, bool &AnySectionOverflow)
Definition DWP.cpp:204
static StringRef getSubsection(StringRef Section, const DWARFUnitIndex::Entry &Entry, DWARFSectionKind Kind)
Definition DWP.cpp:173
static bool isSupportedSectionKind(DWARFSectionKind Kind)
Definition DWP.cpp:155
static Error buildDuplicateError(const std::pair< uint64_t, UnitIndexEntry > &PrevE, const CompileUnitIdentifiers &ID, StringRef DWPName)
Definition DWP.cpp:357
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
OptimizedStructLayoutField Field
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static uint32_t getFlags(const Symbol *Sym)
Definition TapiFile.cpp:26
The Input class is used to parse a yaml document into in-memory structs and vectors.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
std::pair< uint64_t, dwarf::DwarfFormat > getInitialLength(uint64_t *Off, Error *Err=nullptr) const
Extracts the DWARF "initial length" field, which can either be a 32-bit value smaller than 0xfffffff0...
A DWARFDataExtractor (typically for an in-memory copy of an object-file section) plus a relocation ma...
bool skipValue(DataExtractor DebugInfoData, uint64_t *OffsetPtr, const dwarf::FormParams Params) const
Skip a form's value in DebugInfoData at the offset specified by OffsetPtr.
uint32_t getVersion() const
LLVM_ABI bool parse(DataExtractor IndexData)
ArrayRef< DWARFSectionKind > getColumnKinds() const
ArrayRef< Entry > getRows() const
uint64_t getOffset(const char *Str, unsigned Length)
Direct ELF writer for DWP output, bypassing MCStreamer.
Definition DWP.h:60
void switchSection(DWPSectionId Id)
Definition DWP.h:118
Error write(raw_pwrite_stream &OS)
Definition DWP.h:140
Error writeWASM(raw_pwrite_stream &OS)
Definition DWP.cpp:1179
void setIsWASM(bool V)
Definition DWP.h:112
void setMachine(uint16_t Machine)
Definition DWP.h:110
Error writeELF(raw_pwrite_stream &OS)
Definition DWP.cpp:1046
void setOSABI(uint8_t OSABI)
Definition DWP.h:111
void emitBytes(StringRef Data)
Zero-copy: stores a reference to the input data without copying.
Definition DWP.h:122
void emitIntValue(uint64_t Value, unsigned Size)
Definition DWP.h:130
SmallVectorImpl< char > & getSectionBuffer(DWPSectionId Id)
Definition DWP.h:114
LLVM_ABI uint32_t getU32(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint32_t value from *offset_ptr.
size_t size() const
Return the number of bytes in the underlying buffer.
const char * getCStr(uint64_t *OffsetPtr, Error *Err=nullptr) const
Extract a C string from *offset_ptr.
LLVM_ABI uint8_t getU8(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint8_t value from *offset_ptr.
LLVM_ABI uint64_t getULEB128(uint64_t *offset_ptr, llvm::Error *Err=nullptr) const
Extract a unsigned LEB128 value from *offset_ptr.
LLVM_ABI uint16_t getU16(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint16_t value from *offset_ptr.
LLVM_ABI uint64_t getU64(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint64_t value from *offset_ptr.
bool isValidOffset(uint64_t offset) const
Test the validity of offset.
LLVM_ABI uint32_t getU24(uint64_t *OffsetPtr, Error *Err=nullptr) const
Extract a 24-bit unsigned value from *offset_ptr and return it in a uint32_t.
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:114
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
bool empty() const
Definition MapVector.h:77
iterator begin()
Definition MapVector.h:65
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:124
size_type size() const
Definition MapVector.h:56
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:221
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:590
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:140
char back() const
Get the last character in the string.
Definition StringRef.h:152
constexpr size_t size() const
Get the string size.
Definition StringRef.h:143
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI void defaultWarningHandler(Error Warning)
Implement default handling for Warning.
static LLVM_ABI Expected< Decompressor > create(StringRef Name, StringRef Data, bool IsLE, bool Is64Bit)
Create decompressor object.
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
const ObjectFile * getObject() const
Definition ObjectFile.h:607
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
raw_ostream & write(unsigned char C)
An abstract base class for streams implementations that also support a pwrite operation.
#define UINT64_MAX
Definition DataTypes.h:77
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ SHF_MERGE
Definition ELF.h:1255
@ SHF_STRINGS
Definition ELF.h:1258
@ SHF_EXCLUDE
Definition ELF.h:1283
@ SHF_COMPRESSED
Definition ELF.h:1277
void writeHeader(support::endian::Writer &W, bool Is64Bit, uint8_t OSABI, uint8_t ABIVersion, uint16_t EMachine, uint32_t EFlags, uint64_t SHOff, uint16_t SHNum, uint16_t SHStrNdx)
Write an ELF file header (Elf32_Ehdr or Elf64_Ehdr) for an ET_REL object.
Definition ELFWriter.cpp:21
void writeSectionHeader(support::endian::Writer &W, bool Is64Bit, uint32_t Name, uint32_t Type, uint64_t Flags, uint64_t Address, uint64_t Offset, uint64_t Size, uint32_t Link, uint32_t Info, uint64_t Alignment, uint64_t EntrySize)
Write a single ELF section header entry (Elf32_Shdr or Elf64_Shdr).
Definition ELFWriter.cpp:48
@ SHT_STRTAB
Definition ELF.h:1150
@ SHT_PROGBITS
Definition ELF.h:1148
@ SHT_NULL
Definition ELF.h:1147
@ SHT_SYMTAB
Definition ELF.h:1149
@ DW_LENGTH_DWARF64
Indicator of 64-bit DWARF format.
Definition Dwarf.h:57
Error createError(const Twine &Err)
Definition Error.h:86
This is an optimization pass for GlobalISel generic memory operations.
AccessField
Definition DWP.cpp:557
@ Offset
Definition DWP.cpp:557
@ Length
Definition DWP.cpp:557
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
std::string utostr(uint64_t X, bool isNeg=false)
std::vector< std::pair< DWARFSectionKind, uint32_t > > SectionLengths
Definition DWP.h:195
static void writeIndexTable(DWPWriter &Out, ArrayRef< unsigned > ContributionOffsets, const MapVector< uint64_t, UnitIndexEntry > &IndexEntries, const AccessField &Field)
Definition DWP.cpp:560
DWARFSectionKind
The enum of section identifiers to be used in internal interfaces.
@ DW_SECT_EXT_LOC
@ DW_SECT_EXT_unknown
Denotes a value read from an index section that does not correspond to any of the supported standards...
@ DW_SECT_EXT_TYPES
static void writeStringsAndOffsets(DWPWriter &Out, DWPStringPool &Strings, StringRef CurStrSection, StringRef CurStrOffsetSection, uint16_t Version, SectionLengths &SectionLength, const Dwarf64StrOffsetsPromotion StrOffsetsOptValue, bool SingleInput)
Definition DWP.cpp:444
static Error handleSection(const StringMap< std::pair< DWPSectionId, DWARFSectionKind > > &KnownSections, const SectionRef &Section, DWPWriter &Out, std::deque< SmallString< 32 > > &UncompressedSections, uint32_t(&ContributionOffsets)[8], UnitIndexEntry &CurEntry, StringRef &CurStrSection, StringRef &CurStrOffsetSection, std::vector< StringRef > &CurTypesSection, std::vector< StringRef > &CurInfoSection, StringRef &AbbrevSection, StringRef &CurCUIndexSection, StringRef &CurTUIndexSection, SectionLengths &SectionLength)
Definition DWP.cpp:646
LLVM_ABI uint32_t serializeSectionKind(DWARFSectionKind Kind, unsigned IndexVersion)
Convert the internal value for a section kind to an on-disk value.
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:334
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static void writeIndex(DWPWriter &Out, DWPSectionId Section, ArrayRef< unsigned > ContributionOffsets, const MapVector< uint64_t, UnitIndexEntry > &IndexEntries, uint32_t IndexVersion)
Definition DWP.cpp:572
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI Expected< InfoSectionUnitHeader > parseInfoSectionUnitHeader(StringRef Info)
Definition DWP.cpp:384
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:79
DWPSectionId
Section identifiers for DWP output.
Definition DWP.h:37
@ DS_Abbrev
Definition DWP.h:40
@ DS_Str
Definition DWP.h:46
@ DS_Rnglists
Definition DWP.h:44
@ DS_Loc
Definition DWP.h:42
@ DS_Types
Definition DWP.h:39
@ DS_Loclists
Definition DWP.h:43
@ DS_TUIndex
Definition DWP.h:49
@ DS_CUIndex
Definition DWP.h:48
@ DS_Info
Definition DWP.h:38
@ DS_Line
Definition DWP.h:41
@ DS_Macro
Definition DWP.h:45
@ DS_StrOffsets
Definition DWP.h:47
static const StringMap< std::pair< DWPSectionId, DWARFSectionKind > > & getKnownSections()
Map input ELF section names to DWP section IDs and DWARF section kinds.
Definition DWP.cpp:628
OnCuIndexOverflow
Definition DWP.h:24
@ SoftStop
Definition DWP.h:26
@ Continue
Definition DWP.h:27
Dwarf64StrOffsetsPromotion
Definition DWP.h:30
@ Always
Always emit .debug_str_offsets talbes as DWARF64 for testing.
Definition DWP.h:33
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:31
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:720
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:373
DWARFUnitIndex::Entry::SectionContribution Contributions[8]
Definition DWP.h:146
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition Dwarf.h:1114
Adapter to write values to a stream in a particular byte order.