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;
480 while (const char *S = Data.getCStr(&LocalOffset)) {
481 uint64_t NewOffset = Strings.getOffset(S, LocalOffset - PrevOffset);
482 OffsetRemapping[PrevOffset] = NewOffset;
483 // Only promote the .debug_str_offsets to DWARF64 if our setting allows it.
484 if (StrOffsetsOptValue != Dwarf64StrOffsetsPromotion::Disabled &&
485 NewOffset > UINT32_MAX) {
486 NewOffsetSize = 8;
487 }
488 PrevOffset = LocalOffset;
489 }
490
491 Data = DataExtractor(CurStrOffsetSection, true, 0);
492
494
495 uint64_t Offset = 0;
496 uint64_t Size = CurStrOffsetSection.size();
497 if (Version > 4) {
498 while (Offset < Size) {
499 const uint64_t HeaderSize = debugStrOffsetsHeaderSize(Data, Version);
500 assert(HeaderSize <= Size - Offset &&
501 "StrOffsetSection size is less than its header");
502
503 uint64_t ContributionEnd = 0;
504 uint64_t ContributionSize = 0;
505 uint64_t HeaderLengthOffset = Offset;
506 if (HeaderSize == 8) {
507 ContributionSize = Data.getU32(&HeaderLengthOffset);
508 } else if (HeaderSize == 16) {
509 OldOffsetSize = 8;
510 HeaderLengthOffset += 4; // skip the dwarf64 marker
511 ContributionSize = Data.getU64(&HeaderLengthOffset);
512 }
513 ContributionEnd = ContributionSize + HeaderLengthOffset;
514
515 StringRef HeaderBytes = Data.getBytes(&Offset, HeaderSize);
516 if (OldOffsetSize == 4 && NewOffsetSize == 8) {
517 // We had a DWARF32 .debug_str_offsets header, but we need to emit
518 // some string offsets that require 64 bit offsets on the .debug_str
519 // section. Emit the .debug_str_offsets header in DWARF64 format so we
520 // can emit string offsets that exceed UINT32_MAX without truncating
521 // the string offset.
522
523 // 2 bytes for DWARF version, 2 bytes pad.
524 const uint64_t VersionPadSize = 4;
525 const uint64_t NewLength =
526 (ContributionSize - VersionPadSize) * 2 + VersionPadSize;
527 // Emit the DWARF64 length that starts with a 4 byte DW_LENGTH_DWARF64
528 // value followed by the 8 byte updated length.
530 Out.emitIntValue(NewLength, 8);
531 // Emit DWARF version as a 2 byte integer.
532 Out.emitIntValue(Version, 2);
533 // Emit 2 bytes of padding.
534 Out.emitIntValue(0, 2);
535 // Update the .debug_str_offsets section length contribution for the
536 // this .dwo file.
537 for (auto &Pair : SectionLength) {
538 if (Pair.first == DW_SECT_STR_OFFSETS) {
539 Pair.second = NewLength + 12;
540 break;
541 }
542 }
543 } else {
544 // Just emit the same .debug_str_offsets header.
545 Out.emitBytes(HeaderBytes);
546 }
547 writeNewOffsetsTo(Out, Data, OffsetRemapping, Offset, ContributionEnd,
548 OldOffsetSize, NewOffsetSize);
549 }
550
551 } else {
552 assert(OldOffsetSize == NewOffsetSize);
553 writeNewOffsetsTo(Out, Data, OffsetRemapping, Offset, Size, OldOffsetSize,
554 NewOffsetSize);
555 }
556}
557
559
560static void
562 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
563 const AccessField &Field) {
564 for (const auto &E : IndexEntries)
565 for (size_t I = 0; I != std::size(E.second.Contributions); ++I)
566 if (ContributionOffsets[I])
568 ? E.second.Contributions[I].getOffset32()
569 : E.second.Contributions[I].getLength32()),
570 4);
571}
572
573static void writeIndex(DWPWriter &Out, DWPSectionId Section,
574 ArrayRef<unsigned> ContributionOffsets,
575 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
576 uint32_t IndexVersion) {
577 if (IndexEntries.empty())
578 return;
579
580 unsigned Columns = 0;
581 for (auto &C : ContributionOffsets)
582 if (C)
583 ++Columns;
584
585 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
586 uint64_t Mask = Buckets.size() - 1;
587 size_t I = 0;
588 for (const auto &P : IndexEntries) {
589 auto S = P.first;
590 auto H = S & Mask;
591 auto HP = ((S >> 32) & Mask) | 1;
592 while (Buckets[H]) {
593 assert(S != IndexEntries.begin()[Buckets[H] - 1].first &&
594 "Duplicate unit");
595 H = (H + HP) & Mask;
596 }
597 Buckets[H] = I + 1;
598 ++I;
599 }
600
601 Out.switchSection(Section);
602 Out.emitIntValue(IndexVersion, 4); // Version
603 Out.emitIntValue(Columns, 4); // Columns
604 Out.emitIntValue(IndexEntries.size(), 4); // Num Units
605 Out.emitIntValue(Buckets.size(), 4); // Num Buckets
606
607 // Write the signatures.
608 for (const auto &I : Buckets)
609 Out.emitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8);
610
611 // Write the indexes.
612 for (const auto &I : Buckets)
613 Out.emitIntValue(I, 4);
614
615 // Write the column headers (which sections will appear in the table)
616 for (size_t I = 0; I != ContributionOffsets.size(); ++I)
617 if (ContributionOffsets[I])
619
620 // Write the offsets.
621 writeIndexTable(Out, ContributionOffsets, IndexEntries, AccessField::Offset);
622
623 // Write the lengths.
624 writeIndexTable(Out, ContributionOffsets, IndexEntries, AccessField::Length);
625}
626
627/// Map input ELF section names to DWP section IDs and DWARF section kinds.
631 {"debug_info.dwo", {DS_Info, DW_SECT_INFO}},
632 {"debug_types.dwo", {DS_Types, DW_SECT_EXT_TYPES}},
633 {"debug_str_offsets.dwo", {DS_StrOffsets, DW_SECT_STR_OFFSETS}},
634 {"debug_str.dwo", {DS_Str, static_cast<DWARFSectionKind>(0)}},
635 {"debug_loc.dwo", {DS_Loc, DW_SECT_EXT_LOC}},
636 {"debug_line.dwo", {DS_Line, DW_SECT_LINE}},
637 {"debug_macro.dwo", {DS_Macro, DW_SECT_MACRO}},
638 {"debug_abbrev.dwo", {DS_Abbrev, DW_SECT_ABBREV}},
639 {"debug_loclists.dwo", {DS_Loclists, DW_SECT_LOCLISTS}},
640 {"debug_rnglists.dwo", {DS_Rnglists, DW_SECT_RNGLISTS}},
641 {"debug_cu_index", {DS_CUIndex, static_cast<DWARFSectionKind>(0)}},
642 {"debug_tu_index", {DS_TUIndex, static_cast<DWARFSectionKind>(0)}},
643 };
644 return Map;
645}
646
648 const StringMap<std::pair<DWPSectionId, DWARFSectionKind>> &KnownSections,
649 const SectionRef &Section, DWPWriter &Out,
650 std::deque<SmallString<32>> &UncompressedSections,
651 uint32_t (&ContributionOffsets)[8], UnitIndexEntry &CurEntry,
652 StringRef &CurStrSection, StringRef &CurStrOffsetSection,
653 std::vector<StringRef> &CurTypesSection,
654 std::vector<StringRef> &CurInfoSection, StringRef &AbbrevSection,
655 StringRef &CurCUIndexSection, StringRef &CurTUIndexSection,
656 SectionLengths &SectionLength) {
657 if (Section.isBSS())
658 return Error::success();
659
660 if (Section.isVirtual())
661 return Error::success();
662
663 Expected<StringRef> NameOrErr = Section.getName();
664 if (!NameOrErr)
665 return NameOrErr.takeError();
666 StringRef Name = *NameOrErr;
667
668 Expected<StringRef> ContentsOrErr = Section.getContents();
669 if (!ContentsOrErr)
670 return ContentsOrErr.takeError();
671 StringRef Contents = *ContentsOrErr;
672
673 if (auto Err = handleCompressedSection(UncompressedSections, Section, Name,
674 Contents))
675 return Err;
676
677 Name = Name.substr(Name.find_first_not_of("._"));
678
679 auto SectionPair = KnownSections.find(Name);
680 if (SectionPair == KnownSections.end())
681 return Error::success();
682
683 DWPSectionId SectionId = SectionPair->second.first;
684 DWARFSectionKind Kind = SectionPair->second.second;
685
686 if (Kind) {
687 if (Kind != DW_SECT_EXT_TYPES && Kind != DW_SECT_INFO)
688 SectionLength.push_back(std::make_pair(Kind, Contents.size()));
689 if (Kind == DW_SECT_ABBREV)
690 AbbrevSection = Contents;
691 }
692
693 switch (SectionId) {
694 case DS_StrOffsets:
695 CurStrOffsetSection = Contents;
696 break;
697 case DS_Str:
698 CurStrSection = Contents;
699 break;
700 case DS_Types:
701 CurTypesSection.push_back(Contents);
702 break;
703 case DS_CUIndex:
704 CurCUIndexSection = Contents;
705 break;
706 case DS_TUIndex:
707 CurTUIndexSection = Contents;
708 break;
709 case DS_Info:
710 CurInfoSection.push_back(Contents);
711 break;
712 default:
713 // Pass-through: emit directly to output (zero-copy).
714 Out.switchSection(SectionId);
715 Out.emitBytes(Contents);
716 break;
717 }
718 return Error::success();
719}
720
722 OnCuIndexOverflow OverflowOptValue,
723 Dwarf64StrOffsetsPromotion StrOffsetsOptValue,
724 raw_pwrite_stream *OutputOS) {
725 const auto &KnownSections = getKnownSections();
726
729
730 uint32_t ContributionOffsets[8] = {};
731 uint16_t Version = 0;
732 uint32_t IndexVersion = 0;
733 StringRef FirstInput;
734 bool AnySectionOverflow = false;
735
736 DWPStringPool Strings(Out);
737
739 Objects.reserve(Inputs.size());
740
741 std::deque<SmallString<32>> UncompressedSections;
742
743 bool MachineSet = false;
744
745 for (const auto &Input : Inputs) {
747 if (!ErrOrObj) {
748 return handleErrors(ErrOrObj.takeError(),
749 [&](std::unique_ptr<ECError> EC) -> Error {
750 return createFileError(Input, Error(std::move(EC)));
751 });
752 }
753
754 auto &Obj = *ErrOrObj->getBinary();
755 Objects.push_back(std::move(*ErrOrObj));
756
757 // Set output format metadata from the first input file.
758 if (!MachineSet) {
759 if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) {
760 Out.setMachine(ELFObj->getEMachine());
761 Out.setOSABI(ELFObj->getEIdentOSABI());
762 } else if (Obj.isWasm()) {
763 Out.setIsWASM(true);
764 }
765 MachineSet = true;
766 }
767
768 UnitIndexEntry CurEntry = {};
769
770 StringRef CurStrSection;
771 StringRef CurStrOffsetSection;
772 std::vector<StringRef> CurTypesSection;
773 std::vector<StringRef> CurInfoSection;
774 StringRef AbbrevSection;
775 StringRef CurCUIndexSection;
776 StringRef CurTUIndexSection;
777
778 // This maps each section contained in this file to its length.
779 // This information is later on used to calculate the contributions,
780 // i.e. offset and length, of each compile/type unit to a section.
781 SectionLengths SectionLength;
782
783 for (const auto &Section : Obj.sections())
784 if (auto Err = handleSection(
785 KnownSections, Section, Out, UncompressedSections,
786 ContributionOffsets, CurEntry, CurStrSection, CurStrOffsetSection,
787 CurTypesSection, CurInfoSection, AbbrevSection, CurCUIndexSection,
788 CurTUIndexSection, SectionLength))
789 return Err;
790
791 if (CurInfoSection.empty())
792 continue;
793
795 parseInfoSectionUnitHeader(CurInfoSection.front());
796 if (!HeaderOrErr)
797 return HeaderOrErr.takeError();
798 InfoSectionUnitHeader &Header = *HeaderOrErr;
799
800 if (Version == 0) {
801 Version = Header.Version;
802 IndexVersion = Version < 5 ? 2 : 5;
803 FirstInput = Input;
804 } else if (Version != Header.Version) {
806 "incompatible DWARF compile unit version: " + Input + " (version " +
807 utostr(Header.Version) + ") and " + FirstInput.str() + " (version " +
808 utostr(Version) + ")");
809 }
810
811 writeStringsAndOffsets(Out, Strings, CurStrSection, CurStrOffsetSection,
812 Header.Version, SectionLength, StrOffsetsOptValue,
813 Inputs.size() == 1);
814
815 for (auto Pair : SectionLength) {
816 auto Index = getContributionIndex(Pair.first, IndexVersion);
817 CurEntry.Contributions[Index].setOffset(ContributionOffsets[Index]);
818 CurEntry.Contributions[Index].setLength(Pair.second);
819 uint32_t OldOffset = ContributionOffsets[Index];
820 ContributionOffsets[Index] += CurEntry.Contributions[Index].getLength32();
821 if (OldOffset > ContributionOffsets[Index]) {
822 uint32_t SectionIndex = 0;
823 for (auto &Section : Obj.sections()) {
824 if (SectionIndex == Index) {
826 OldOffset, ContributionOffsets[Index], *Section.getName(),
827 OverflowOptValue, AnySectionOverflow))
828 return Err;
829 }
830 ++SectionIndex;
831 }
832 if (AnySectionOverflow)
833 break;
834 }
835 }
836
837 uint32_t &InfoSectionOffset =
838 ContributionOffsets[getContributionIndex(DW_SECT_INFO, IndexVersion)];
839 if (CurCUIndexSection.empty()) {
840 bool FoundCUUnit = false;
842 for (StringRef Info : CurInfoSection) {
843 uint64_t UnitOffset = 0;
844 while (Info.size() > UnitOffset) {
845 Expected<InfoSectionUnitHeader> HeaderOrError =
846 parseInfoSectionUnitHeader(Info.substr(UnitOffset, Info.size()));
847 if (!HeaderOrError)
848 return HeaderOrError.takeError();
849 InfoSectionUnitHeader &Header = *HeaderOrError;
850
851 UnitIndexEntry Entry = CurEntry;
852 auto &C = Entry.Contributions[getContributionIndex(DW_SECT_INFO,
853 IndexVersion)];
854 C.setOffset(InfoSectionOffset);
855 C.setLength(Header.Length + 4);
856
857 if (std::numeric_limits<uint32_t>::max() - InfoSectionOffset <
858 C.getLength32()) {
860 InfoSectionOffset, InfoSectionOffset + C.getLength32(),
861 "debug_info", OverflowOptValue, AnySectionOverflow))
862 return Err;
863 if (AnySectionOverflow) {
864 FoundCUUnit = true;
865 break;
866 }
867 }
868
869 UnitOffset += C.getLength32();
870 if (Header.Version < 5 ||
871 Header.UnitType == dwarf::DW_UT_split_compile) {
873 Header, AbbrevSection,
874 Info.substr(UnitOffset - C.getLength32(), C.getLength32()),
875 CurStrOffsetSection, CurStrSection);
876
877 if (!EID)
878 return createFileError(Input, EID.takeError());
879 const auto &ID = *EID;
880 auto P = IndexEntries.insert(std::make_pair(ID.Signature, Entry));
881 if (!P.second)
882 return buildDuplicateError(*P.first, ID, "");
883 P.first->second.Name = ID.Name;
884 P.first->second.DWOName = ID.DWOName;
885
886 FoundCUUnit = true;
887 } else if (Header.UnitType == dwarf::DW_UT_split_type) {
888 auto P = TypeIndexEntries.insert(
889 std::make_pair(*Header.Signature, Entry));
890 if (!P.second)
891 continue;
892 }
893 Out.emitBytes(
894 Info.substr(UnitOffset - C.getLength32(), C.getLength32()));
895 InfoSectionOffset += C.getLength32();
896 }
897 if (AnySectionOverflow)
898 break;
899 }
900
901 if (!FoundCUUnit)
902 return make_error<DWPError>("no compile unit found in file: " + Input);
903
904 if (IndexVersion == 2) {
905 // Add types from the .debug_types section from DWARF < 5.
907 Out, TypeIndexEntries, DS_Types, CurTypesSection, CurEntry,
908 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES, 2)],
909 OverflowOptValue, AnySectionOverflow))
910 return Err;
911 }
912 if (AnySectionOverflow)
913 break;
914 continue;
915 }
916
917 if (CurInfoSection.size() != 1)
918 return make_error<DWPError>("expected exactly one occurrence of a debug "
919 "info section in a .dwp file");
920 StringRef DwpSingleInfoSection = CurInfoSection.front();
921
922 DWARFUnitIndex CUIndex(DW_SECT_INFO);
923 DataExtractor CUIndexData(CurCUIndexSection, Obj.isLittleEndian(), 0);
924 if (!CUIndex.parse(CUIndexData))
925 return make_error<DWPError>("failed to parse cu_index");
926 if (CUIndex.getVersion() != IndexVersion)
927 return make_error<DWPError>("incompatible cu_index versions, found " +
928 utostr(CUIndex.getVersion()) +
929 " and expecting " + utostr(IndexVersion));
930
932 for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
933 auto *I = E.getContributions();
934 if (!I)
935 continue;
936 auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
937 StringRef CUInfoSection =
938 getSubsection(DwpSingleInfoSection, E, DW_SECT_INFO);
939 Expected<InfoSectionUnitHeader> HeaderOrError =
940 parseInfoSectionUnitHeader(CUInfoSection);
941 if (!HeaderOrError)
942 return HeaderOrError.takeError();
943 InfoSectionUnitHeader &Header = *HeaderOrError;
944
946 Header, getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
947 CUInfoSection,
948 getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
949 CurStrSection);
950 if (!EID)
951 return createFileError(Input, EID.takeError());
952 const auto &ID = *EID;
953 if (!P.second)
954 return buildDuplicateError(*P.first, ID, Input);
955 auto &NewEntry = P.first->second;
956 NewEntry.Name = ID.Name;
957 NewEntry.DWOName = ID.DWOName;
958 NewEntry.DWPName = Input;
959 for (auto Kind : CUIndex.getColumnKinds()) {
961 continue;
962 auto &C =
963 NewEntry.Contributions[getContributionIndex(Kind, IndexVersion)];
964 C.setOffset(C.getOffset() + I->getOffset());
965 C.setLength(I->getLength());
966 ++I;
967 }
968 unsigned Index = getContributionIndex(DW_SECT_INFO, IndexVersion);
969 auto &C = NewEntry.Contributions[Index];
970 Out.emitBytes(CUInfoSection);
971 C.setOffset(InfoSectionOffset);
972 InfoSectionOffset += C.getLength32();
973 }
974
975 if (!CurTUIndexSection.empty()) {
976 llvm::DWARFSectionKind TUSectionKind;
977 DWPSectionId OutSection;
978 StringRef TypeInputSection;
979 // Write type units into debug info section for DWARFv5.
980 if (Version >= 5) {
981 TUSectionKind = DW_SECT_INFO;
982 OutSection = DS_Info;
983 TypeInputSection = DwpSingleInfoSection;
984 } else {
985 // Write type units into debug types section for DWARF < 5.
986 if (CurTypesSection.size() != 1)
988 "multiple type unit sections in .dwp file");
989
990 TUSectionKind = DW_SECT_EXT_TYPES;
991 OutSection = DS_Types;
992 TypeInputSection = CurTypesSection.front();
993 }
994
995 DWARFUnitIndex TUIndex(TUSectionKind);
996 DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0);
997 if (!TUIndex.parse(TUIndexData))
998 return make_error<DWPError>("failed to parse tu_index");
999 if (TUIndex.getVersion() != IndexVersion)
1000 return make_error<DWPError>("incompatible tu_index versions, found " +
1001 utostr(TUIndex.getVersion()) +
1002 " and expecting " + utostr(IndexVersion));
1003
1004 unsigned TypesContributionIndex =
1005 getContributionIndex(TUSectionKind, IndexVersion);
1006 if (Error Err = addAllTypesFromDWP(
1007 Out, TypeIndexEntries, TUIndex, OutSection, TypeInputSection,
1008 CurEntry, ContributionOffsets[TypesContributionIndex],
1009 TypesContributionIndex, OverflowOptValue, AnySectionOverflow))
1010 return Err;
1011 }
1012 if (AnySectionOverflow)
1013 break;
1014 }
1015
1016 if (Version < 5) {
1017 // Lie about there being no info contributions so the TU index only includes
1018 // the type unit contribution for DWARF < 5. In DWARFv5 the TU index has a
1019 // contribution to the info section, so we do not want to lie about it.
1020 ContributionOffsets[0] = 0;
1021 }
1022 writeIndex(Out, DS_TUIndex, ContributionOffsets, TypeIndexEntries,
1023 IndexVersion);
1024
1025 if (Version < 5) {
1026 // Lie about the type contribution for DWARF < 5. In DWARFv5 the type
1027 // section does not exist, so no need to do anything about this.
1028 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES, 2)] = 0;
1029 // Unlie about the info contribution
1030 ContributionOffsets[0] = 1;
1031 }
1032
1033 writeIndex(Out, DS_CUIndex, ContributionOffsets, IndexEntries, IndexVersion);
1034
1035 // Write ELF output while input data is still alive (zero-copy chunks
1036 // reference mmap'd input data held by the Objects vector above).
1037 if (OutputOS)
1038 return Out.write(*OutputOS);
1039
1040 return Error::success();
1041}
1042
1043//===----------------------------------------------------------------------===//
1044// DWPWriter::writeELF — produce a minimal ELF64 relocatable object.
1045//===----------------------------------------------------------------------===//
1046
1049
1050 // Section metadata table.
1051 struct SectionMeta {
1052 DWPSectionId Id;
1053 const char *Name;
1054 uint64_t Flags;
1055 uint64_t EntSize;
1056 };
1057 static constexpr SectionMeta Meta[] = {
1058 {DS_Loclists, ".debug_loclists.dwo", ELF::SHF_EXCLUDE, 0},
1059 {DS_Loc, ".debug_loc.dwo", ELF::SHF_EXCLUDE, 0},
1060 {DS_Abbrev, ".debug_abbrev.dwo", ELF::SHF_EXCLUDE, 0},
1061 {DS_Line, ".debug_line.dwo", ELF::SHF_EXCLUDE, 0},
1062 {DS_Rnglists, ".debug_rnglists.dwo", ELF::SHF_EXCLUDE, 0},
1063 {DS_Macro, ".debug_macro.dwo", ELF::SHF_EXCLUDE, 0},
1064 {DS_Str, ".debug_str.dwo",
1066 {DS_StrOffsets, ".debug_str_offsets.dwo", ELF::SHF_EXCLUDE, 0},
1067 {DS_Info, ".debug_info.dwo", ELF::SHF_EXCLUDE, 0},
1068 {DS_Types, ".debug_types.dwo", ELF::SHF_EXCLUDE, 0},
1069 {DS_TUIndex, ".debug_tu_index", 0, 0},
1070 {DS_CUIndex, ".debug_cu_index", 0, 0},
1071 };
1072
1073 // Collect non-empty sections and build the section name string table.
1074 struct OutputEntry {
1075 const SectionData *Data;
1076 const char *Name;
1077 uint64_t Flags;
1078 uint64_t EntSize;
1079 uint32_t NameOffset;
1080 uint64_t FileOffset; // filled in during layout
1081 };
1083
1084 SmallString<256> Strtab;
1085 Strtab.push_back('\0'); // null string at offset 0
1086
1087 for (const auto &M : Meta) {
1088 if (Sections[M.Id].empty())
1089 continue;
1090 uint32_t NameOff = Strtab.size();
1091 Strtab.append(M.Name);
1092 Strtab.push_back('\0');
1093 Entries.push_back(
1094 {&Sections[M.Id], M.Name, M.Flags, M.EntSize, NameOff, 0});
1095 }
1096
1097 // Add .strtab and .symtab name entries.
1098 uint32_t StrtabNameOff = Strtab.size();
1099 Strtab.append(".strtab");
1100 Strtab.push_back('\0');
1101 uint32_t SymtabNameOff = Strtab.size();
1102 Strtab.append(".symtab");
1103 Strtab.push_back('\0');
1104
1105 // Layout:
1106 // [ELF Header] 64 bytes
1107 // [section data...] variable
1108 // [.strtab data] variable
1109 // [padding to 8-byte align]
1110 // [.symtab data] 24 bytes (one null entry)
1111 // [padding to 8-byte align]
1112 // [Section Header Table] 64 * NumSections bytes
1113
1114 constexpr uint64_t EhdrSize = sizeof(ELF::Elf64_Ehdr);
1115 constexpr uint64_t SymEntSize = 24;
1116
1117 uint64_t Offset = EhdrSize;
1118 for (auto &E : Entries) {
1119 E.FileOffset = Offset;
1120 Offset += E.Data->totalSize();
1121 }
1122
1123 uint64_t StrtabOffset = Offset;
1124 Offset += Strtab.size();
1125
1126 uint64_t SymtabOffset = alignTo(Offset, 8);
1127 Offset = SymtabOffset + SymEntSize;
1128
1129 uint64_t SHTOffset = alignTo(Offset, 8);
1130
1131 // Section indices: [0]=null, [1..N]=data, [N+1]=strtab, [N+2]=symtab
1132 uint32_t StrtabIdx = 1 + Entries.size();
1133 uint32_t SymtabIdx = StrtabIdx + 1;
1134 uint32_t NumSections = SymtabIdx + 1;
1135
1136 // --- Write ELF header ---
1137 ELF::writeHeader(Wr, /*Is64Bit=*/true, ELFOSABI, /*ABIVersion=*/0, ELFMachine,
1138 /*EFlags=*/0, SHTOffset, NumSections, StrtabIdx);
1139
1140 // --- Write section data ---
1141 for (const auto &E : Entries)
1142 E.Data->writeTo(OS);
1143
1144 // --- Write .strtab ---
1145 OS.write(Strtab.data(), Strtab.size());
1146
1147 // --- Pad + write .symtab (one null symbol entry) ---
1148 OS.write_zeros(SymtabOffset - (StrtabOffset + Strtab.size()));
1149 OS.write_zeros(SymEntSize);
1150
1151 // --- Pad for section header table ---
1152 uint64_t CurPos = SymtabOffset + SymEntSize;
1153 OS.write_zeros(SHTOffset - CurPos);
1154
1155 // [0] ELF::SHT_NULL
1156 ELF::writeSectionHeader(Wr, true, 0, ELF::SHT_NULL, 0, 0, 0, 0, 0, 0, 0, 0);
1157
1158 // [1..N] data sections
1159 for (const auto &E : Entries)
1160 ELF::writeSectionHeader(Wr, true, E.NameOffset, ELF::SHT_PROGBITS, E.Flags,
1161 0, E.FileOffset, E.Data->totalSize(), 0, 0, 1,
1162 E.EntSize);
1163
1164 // [N+1] .strtab
1165 ELF::writeSectionHeader(Wr, true, StrtabNameOff, ELF::SHT_STRTAB, 0, 0,
1166 StrtabOffset, Strtab.size(), 0, 0, 1, 0);
1167
1168 // [N+2] .symtab
1169 ELF::writeSectionHeader(Wr, true, SymtabNameOff, ELF::SHT_SYMTAB, 0, 0,
1170 SymtabOffset, SymEntSize, StrtabIdx, 1, 8,
1171 SymEntSize);
1172
1173 return Error::success();
1174}
1175
1176//===----------------------------------------------------------------------===//
1177// DWPWriter::writeWASM — produce a minimal WASM object with custom sections.
1178//===----------------------------------------------------------------------===//
1179
1181 // Section name table (same names as ELF but without SHF_EXCLUDE flags).
1182 static constexpr struct {
1183 DWPSectionId Id;
1184 const char *Name;
1185 } Meta[] = {
1186 {DS_Loclists, ".debug_loclists.dwo"},
1187 {DS_Loc, ".debug_loc.dwo"},
1188 {DS_Abbrev, ".debug_abbrev.dwo"},
1189 {DS_Line, ".debug_line.dwo"},
1190 {DS_Rnglists, ".debug_rnglists.dwo"},
1191 {DS_Macro, ".debug_macro.dwo"},
1192 {DS_Str, ".debug_str.dwo"},
1193 {DS_StrOffsets, ".debug_str_offsets.dwo"},
1194 {DS_Info, ".debug_info.dwo"},
1195 {DS_Types, ".debug_types.dwo"},
1196 {DS_TUIndex, ".debug_tu_index"},
1197 {DS_CUIndex, ".debug_cu_index"},
1198 };
1199
1200 // WASM magic and version.
1201 OS.write("\0asm", 4);
1202 const uint8_t Version[] = {0x01, 0x00, 0x00, 0x00};
1203 OS.write(reinterpret_cast<const char *>(Version), 4);
1204
1205 // Emit each non-empty section as a WASM custom section (id=0).
1206 for (const auto &M : Meta) {
1207 const SectionData &SD = Sections[M.Id];
1208 if (SD.empty())
1209 continue;
1210
1211 size_t NameLen = strlen(M.Name);
1212 uint64_t PayloadSize = SD.totalSize();
1213
1214 // Custom section payload = ULEB128(name_len) + name + data.
1215 uint8_t NameLenEncoded[10];
1216 unsigned NameLenSize = encodeULEB128(NameLen, NameLenEncoded);
1217 uint64_t SectionPayloadSize = NameLenSize + NameLen + PayloadSize;
1218
1219 // Section header: id byte + ULEB128(section_payload_size).
1220 OS.write(0x00); // Custom section id
1221 uint8_t SizeEncoded[10];
1222 unsigned SizeLen = encodeULEB128(SectionPayloadSize, SizeEncoded);
1223 OS.write(reinterpret_cast<const char *>(SizeEncoded), SizeLen);
1224
1225 // Name
1226 OS.write(reinterpret_cast<const char *>(NameLenEncoded), NameLenSize);
1227 OS.write(M.Name, NameLen);
1228
1229 // Data
1230 SD.writeTo(OS);
1231 }
1232
1233 return Error::success();
1234}
1235
1236} // 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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
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)
Definition DWP.h:152
Direct ELF writer for DWP output.
Definition DWP.h:59
void switchSection(DWPSectionId Id)
Definition DWP.h:117
Error write(raw_pwrite_stream &OS)
Definition DWP.h:139
Error writeWASM(raw_pwrite_stream &OS)
Definition DWP.cpp:1180
void setIsWASM(bool V)
Definition DWP.h:111
void setMachine(uint16_t Machine)
Definition DWP.h:109
Error writeELF(raw_pwrite_stream &OS)
Definition DWP.cpp:1047
void setOSABI(uint8_t OSABI)
Definition DWP.h:110
void emitBytes(StringRef Data)
Zero-copy: stores a reference to the input data without copying.
Definition DWP.h:121
void emitIntValue(uint64_t Value, unsigned Size)
Definition DWP.h:129
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:38
iterator begin()
Definition MapVector.h:67
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
size_type size() const
Definition MapVector.h:58
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:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
char back() const
Get the last character in the string.
Definition StringRef.h:153
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
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:1257
@ SHF_STRINGS
Definition ELF.h:1260
@ SHF_EXCLUDE
Definition ELF.h:1285
@ SHF_COMPRESSED
Definition ELF.h:1279
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:1152
@ SHT_PROGBITS
Definition ELF.h:1150
@ SHT_NULL
Definition ELF.h:1149
@ SHT_SYMTAB
Definition ELF.h:1151
@ 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:558
@ Offset
Definition DWP.cpp:558
@ Length
Definition DWP.cpp:558
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:216
static void writeIndexTable(DWPWriter &Out, ArrayRef< unsigned > ContributionOffsets, const MapVector< uint64_t, UnitIndexEntry > &IndexEntries, const AccessField &Field)
Definition DWP.cpp:561
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:647
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:573
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:36
@ DS_Abbrev
Definition DWP.h:39
@ DS_Str
Definition DWP.h:45
@ DS_Rnglists
Definition DWP.h:43
@ DS_Loc
Definition DWP.h:41
@ DS_Types
Definition DWP.h:38
@ DS_Loclists
Definition DWP.h:42
@ DS_TUIndex
Definition DWP.h:48
@ DS_CUIndex
Definition DWP.h:47
@ DS_Info
Definition DWP.h:37
@ DS_Line
Definition DWP.h:40
@ DS_Macro
Definition DWP.h:44
@ DS_StrOffsets
Definition DWP.h:46
static const StringMap< std::pair< DWPSectionId, DWARFSectionKind > > & getKnownSections()
Map input ELF section names to DWP section IDs and DWARF section kinds.
Definition DWP.cpp:629
OnCuIndexOverflow
Definition DWP.h:23
@ SoftStop
Definition DWP.h:25
@ Continue
Definition DWP.h:26
Dwarf64StrOffsetsPromotion
Definition DWP.h:29
@ Always
Always emit .debug_str_offsets talbes as DWARF64 for testing.
Definition DWP.h:32
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:30
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:721
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:167
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.