1//===- DWARFDebugFrame.h - Parsing of .debug_frame ------------------------===//
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#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
10#include "llvm/ADT/DenseMap.h"
11#include "llvm/ADT/StringExtras.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/BinaryFormat/Dwarf.h"
14#include "llvm/DebugInfo/DIContext.h"
15#include "llvm/DebugInfo/DWARF/DWARFCFIPrinter.h"
16#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
17#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
18#include "llvm/DebugInfo/DWARF/DWARFUnwindTablePrinter.h"
19#include "llvm/DebugInfo/DWARF/LowLevel/DWARFCFIProgram.h"
20#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/DataExtractor.h"
23#include "llvm/Support/Errc.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/FormatAdapters.h"
27#include "llvm/Support/FormatVariadic.h"
28#include "llvm/Support/raw_ostream.h"
29#include <cassert>
30#include <cinttypes>
31#include <cstdint>
32#include <optional>
33
34using namespace llvm;
35using namespace dwarf;
36
37Expected<UnwindTable> llvm::dwarf::createUnwindTable(const FDE *Fde) {
38 const CIE *Cie = Fde->getLinkedCIE();
39 if (Cie == nullptr)
40 return createStringError(EC: errc::invalid_argument,
41 Fmt: "unable to get CIE for FDE at offset 0x%" PRIx64,
42 Vals: Fde->getOffset());
43
44 // Rows will be empty if there are no CFI instructions.
45 if (Cie->cfis().empty() && Fde->cfis().empty())
46 return UnwindTable({});
47
48 UnwindTable::RowContainer CieRows;
49 UnwindRow Row;
50 Row.setAddress(Fde->getInitialLocation());
51 if (Error CieError = parseRows(CFIP: Cie->cfis(), CurrRow&: Row, InitialLocs: nullptr).moveInto(Value&: CieRows))
52 return std::move(CieError);
53 // We need to save the initial locations of registers from the CIE parsing
54 // in case we run into DW_CFA_restore or DW_CFA_restore_extended opcodes.
55 UnwindTable::RowContainer FdeRows;
56 const RegisterLocations InitialLocs = Row.getRegisterLocations();
57 if (Error FdeError =
58 parseRows(CFIP: Fde->cfis(), CurrRow&: Row, InitialLocs: &InitialLocs).moveInto(Value&: FdeRows))
59 return std::move(FdeError);
60
61 UnwindTable::RowContainer AllRows;
62 AllRows.insert(position: AllRows.end(), first: CieRows.begin(), last: CieRows.end());
63 AllRows.insert(position: AllRows.end(), first: FdeRows.begin(), last: FdeRows.end());
64
65 // May be all the CFI instructions were DW_CFA_nop amd Row becomes empty.
66 // Do not add that to the unwind table.
67 if (Row.getRegisterLocations().hasLocations() ||
68 Row.getCFAValue().getLocation() != UnwindLocation::Unspecified)
69 AllRows.push_back(x: Row);
70 return UnwindTable(std::move(AllRows));
71}
72
73Expected<UnwindTable> llvm::dwarf::createUnwindTable(const CIE *Cie) {
74 // Rows will be empty if there are no CFI instructions.
75 if (Cie->cfis().empty())
76 return UnwindTable({});
77
78 UnwindTable::RowContainer Rows;
79 UnwindRow Row;
80 if (Error CieError = parseRows(CFIP: Cie->cfis(), CurrRow&: Row, InitialLocs: nullptr).moveInto(Value&: Rows))
81 return std::move(CieError);
82 // May be all the CFI instructions were DW_CFA_nop amd Row becomes empty.
83 // Do not add that to the unwind table.
84 if (Row.getRegisterLocations().hasLocations() ||
85 Row.getCFAValue().getLocation() != UnwindLocation::Unspecified)
86 Rows.push_back(x: Row);
87 return UnwindTable(std::move(Rows));
88}
89
90// Returns the CIE identifier to be used by the requested format.
91// CIE ids for .debug_frame sections are defined in Section 7.24 of DWARFv5.
92// For CIE ID in .eh_frame sections see
93// https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
94constexpr uint64_t getCIEId(bool IsDWARF64, bool IsEH) {
95 if (IsEH)
96 return 0;
97 if (IsDWARF64)
98 return DW64_CIE_ID;
99 return DW_CIE_ID;
100}
101
102void CIE::dump(raw_ostream &OS, DIDumpOptions DumpOpts) const {
103 // A CIE with a zero length is a terminator entry in the .eh_frame section.
104 if (DumpOpts.IsEH && Length == 0) {
105 OS << formatv(Fmt: "{0:x-8}", Vals: Offset) << " ZERO terminator\n";
106 return;
107 }
108
109 OS << formatv(Fmt: "{0:x-8}", Vals: Offset)
110 << formatv(Fmt: " {0:x-}",
111 Vals: fmt_align(Item: Length, Where: AlignStyle::Right, Amount: IsDWARF64 ? 16 : 8, Fill: '0'))
112 << formatv(Fmt: " {0:x-}",
113 Vals: fmt_align(Item: getCIEId(IsDWARF64, IsEH: DumpOpts.IsEH), Where: AlignStyle::Right,
114 Amount: IsDWARF64 && !DumpOpts.IsEH ? 16 : 8, Fill: '0'))
115 << " CIE\n"
116 << " Format: " << FormatString(IsDWARF64) << "\n";
117 if (DumpOpts.IsEH && Version != 1)
118 OS << "WARNING: unsupported CIE version\n";
119 OS << formatv(Fmt: " Version: {0}\n", Vals: Version)
120 << " Augmentation: \"" << Augmentation << "\"\n";
121 if (Version >= 4) {
122 OS << formatv(Fmt: " Address size: {0}\n", Vals: (uint32_t)AddressSize);
123 OS << formatv(Fmt: " Segment desc size: {0}\n",
124 Vals: (uint32_t)SegmentDescriptorSize);
125 }
126 OS << formatv(Fmt: " Code alignment factor: {0}\n",
127 Vals: (uint32_t)CodeAlignmentFactor);
128 OS << formatv(Fmt: " Data alignment factor: {0}\n", Vals: (int32_t)DataAlignmentFactor);
129 OS << formatv(Fmt: " Return address column: {0}\n",
130 Vals: (int32_t)ReturnAddressRegister);
131 if (Personality)
132 OS << formatv(Fmt: " Personality Address: {0:x-16}\n", Vals: *Personality);
133 if (!AugmentationData.empty()) {
134 OS << " Augmentation data: ";
135 for (uint8_t Byte : AugmentationData)
136 OS << ' ' << hexdigit(X: Byte >> 4) << hexdigit(X: Byte & 0xf);
137 OS << "\n";
138 }
139 OS << "\n";
140 printCFIProgram(P: CFIs, OS, DumpOpts, /*IndentLevel=*/1,
141 /*InitialLocation=*/Address: {});
142 OS << "\n";
143
144 if (Expected<UnwindTable> RowsOrErr = createUnwindTable(Cie: this))
145 printUnwindTable(Rows: *RowsOrErr, OS, DumpOpts, IndentLevel: 1);
146 else {
147 DumpOpts.RecoverableErrorHandler(joinErrors(
148 E1: createStringError(EC: errc::invalid_argument,
149 S: "decoding the CIE opcodes into rows failed"),
150 E2: RowsOrErr.takeError()));
151 }
152 OS << "\n";
153}
154
155void FDE::dump(raw_ostream &OS, DIDumpOptions DumpOpts) const {
156 OS << formatv(Fmt: "{0:x-8}", Vals: Offset)
157 << formatv(Fmt: " {0:x-}",
158 Vals: fmt_align(Item: Length, Where: AlignStyle::Right, Amount: IsDWARF64 ? 16 : 8, Fill: '0'))
159 << formatv(Fmt: " {0:x-}", Vals: fmt_align(Item: CIEPointer, Where: AlignStyle::Right,
160 Amount: IsDWARF64 && !DumpOpts.IsEH ? 16 : 8, Fill: '0'))
161 << " FDE cie=";
162 if (LinkedCIE)
163 OS << formatv(Fmt: "{0:x-8}", Vals: LinkedCIE->getOffset());
164 else
165 OS << "<invalid offset>";
166 OS << formatv(Fmt: " pc={0:x-8}...{1:x-8}\n", Vals: InitialLocation,
167 Vals: InitialLocation + AddressRange);
168 OS << " Format: " << FormatString(IsDWARF64) << "\n";
169 if (LSDAAddress)
170 OS << formatv(Fmt: " LSDA Address: {0:x-16}\n", Vals: *LSDAAddress);
171 printCFIProgram(P: CFIs, OS, DumpOpts, /*IndentLevel=*/1, Address: InitialLocation);
172 OS << "\n";
173
174 if (Expected<UnwindTable> RowsOrErr = createUnwindTable(Fde: this))
175 printUnwindTable(Rows: *RowsOrErr, OS, DumpOpts, IndentLevel: 1);
176 else {
177 DumpOpts.RecoverableErrorHandler(joinErrors(
178 E1: createStringError(EC: errc::invalid_argument,
179 S: "decoding the FDE opcodes into rows failed"),
180 E2: RowsOrErr.takeError()));
181 }
182 OS << "\n";
183}
184
185DWARFDebugFrame::DWARFDebugFrame(Triple::ArchType Arch,
186 bool IsEH, uint64_t EHFrameAddress)
187 : Arch(Arch), IsEH(IsEH), EHFrameAddress(EHFrameAddress) {}
188
189DWARFDebugFrame::~DWARFDebugFrame() = default;
190
191[[maybe_unused]] static void dumpDataAux(DataExtractor Data, uint64_t Offset,
192 int Length) {
193 errs() << "DUMP: ";
194 for (int i = 0; i < Length; ++i) {
195 uint8_t c = Data.getU8(offset_ptr: &Offset);
196 errs().write_hex(N: c); errs() << " ";
197 }
198 errs() << "\n";
199}
200
201Error DWARFDebugFrame::parse(DWARFDataExtractor Data, bool ParseCFIProgram) {
202 uint64_t Offset = 0;
203 DenseMap<uint64_t, CIE *> CIEs;
204
205 // Retain the section contents so that the programs left undecoded below can
206 // be parsed on demand later.
207 if (!ParseCFIProgram)
208 this->Data = Data;
209
210 while (Data.isValidOffset(offset: Offset)) {
211 uint64_t StartOffset = Offset;
212
213 uint64_t Length;
214 DwarfFormat Format;
215 std::tie(args&: Length, args&: Format) = Data.getInitialLength(Off: &Offset);
216 bool IsDWARF64 = Format == DWARF64;
217
218 // If the Length is 0, then this CIE is a terminator. We add it because some
219 // dumper tools might need it to print something special for such entries
220 // (e.g. llvm-objdump --dwarf=frames prints "ZERO terminator").
221 if (Length == 0) {
222 auto Cie = std::make_unique<CIE>(
223 args&: IsDWARF64, args&: StartOffset, args: 0, args: 0, args: SmallString<8>(), args: 0, args: 0, args: 0, args: 0, args: 0,
224 args: SmallString<8>(), args: 0, args: 0, args: std::nullopt, args: std::nullopt, args: Arch);
225 CIEs[StartOffset] = Cie.get();
226 Entries.push_back(x: std::move(Cie));
227 break;
228 }
229
230 // At this point, Offset points to the next field after Length.
231 // Length is the structure size excluding itself. Compute an offset one
232 // past the end of the structure (needed to know how many instructions to
233 // read).
234 uint64_t StartStructureOffset = Offset;
235 uint64_t EndStructureOffset = Offset + Length;
236
237 // The Id field's size depends on the DWARF format
238 Error Err = Error::success();
239 uint64_t Id = Data.getRelocatedValue(Size: (IsDWARF64 && !IsEH) ? 8 : 4, Off: &Offset,
240 /*SectionIndex=*/nullptr, Err: &Err);
241 if (Err)
242 return Err;
243
244 if (Id == getCIEId(IsDWARF64, IsEH)) {
245 uint8_t Version = Data.getU8(offset_ptr: &Offset);
246 const char *Augmentation = Data.getCStr(OffsetPtr: &Offset);
247 StringRef AugmentationString(Augmentation ? Augmentation : "");
248 uint8_t AddressSize = Version < 4 ? Data.getAddressSize() :
249 Data.getU8(offset_ptr: &Offset);
250 Data.setAddressSize(AddressSize);
251 uint8_t SegmentDescriptorSize = Version < 4 ? 0 : Data.getU8(offset_ptr: &Offset);
252 uint64_t CodeAlignmentFactor = Data.getULEB128(offset_ptr: &Offset);
253 int64_t DataAlignmentFactor = Data.getSLEB128(OffsetPtr: &Offset);
254 uint64_t ReturnAddressRegister =
255 Version == 1 ? Data.getU8(offset_ptr: &Offset) : Data.getULEB128(offset_ptr: &Offset);
256
257 // Parse the augmentation data for EH CIEs
258 StringRef AugmentationData("");
259 uint32_t FDEPointerEncoding = DW_EH_PE_absptr;
260 uint32_t LSDAPointerEncoding = DW_EH_PE_omit;
261 std::optional<uint64_t> Personality;
262 std::optional<uint32_t> PersonalityEncoding;
263 if (IsEH) {
264 std::optional<uint64_t> AugmentationLength;
265 uint64_t StartAugmentationOffset;
266 uint64_t EndAugmentationOffset;
267
268 // Walk the augmentation string to get all the augmentation data.
269 for (unsigned i = 0, e = AugmentationString.size(); i != e; ++i) {
270 switch (AugmentationString[i]) {
271 default:
272 return createStringError(
273 EC: errc::invalid_argument,
274 Fmt: "unknown augmentation character %c in entry at 0x%" PRIx64,
275 Vals: AugmentationString[i], Vals: StartOffset);
276 case 'L':
277 LSDAPointerEncoding = Data.getU8(offset_ptr: &Offset);
278 break;
279 case 'P': {
280 if (Personality)
281 return createStringError(
282 EC: errc::invalid_argument,
283 Fmt: "duplicate personality in entry at 0x%" PRIx64, Vals: StartOffset);
284 PersonalityEncoding = Data.getU8(offset_ptr: &Offset);
285 Personality = Data.getEncodedPointer(
286 Offset: &Offset, Encoding: *PersonalityEncoding,
287 PCRelOffset: EHFrameAddress ? EHFrameAddress + Offset : 0);
288 break;
289 }
290 case 'R':
291 FDEPointerEncoding = Data.getU8(offset_ptr: &Offset);
292 break;
293 case 'S':
294 // Current frame is a signal trampoline.
295 break;
296 case 'z':
297 if (i)
298 return createStringError(
299 EC: errc::invalid_argument,
300 Fmt: "'z' must be the first character at 0x%" PRIx64, Vals: StartOffset);
301 // Parse the augmentation length first. We only parse it if
302 // the string contains a 'z'.
303 AugmentationLength = Data.getULEB128(offset_ptr: &Offset);
304 StartAugmentationOffset = Offset;
305 EndAugmentationOffset = Offset + *AugmentationLength;
306 break;
307 case 'B':
308 // B-Key is used for signing functions associated with this
309 // augmentation string
310 break;
311 // This stack frame contains MTE tagged data, so needs to be
312 // untagged on unwind.
313 case 'G':
314 break;
315 }
316 }
317
318 if (AugmentationLength) {
319 if (Offset != EndAugmentationOffset)
320 return createStringError(EC: errc::invalid_argument,
321 Fmt: "parsing augmentation data at 0x%" PRIx64
322 " failed",
323 Vals: StartOffset);
324 AugmentationData = Data.getData().slice(Start: StartAugmentationOffset,
325 End: EndAugmentationOffset);
326 }
327 }
328
329 auto Cie = std::make_unique<CIE>(
330 args&: IsDWARF64, args&: StartOffset, args&: Length, args&: Version, args&: AugmentationString,
331 args&: AddressSize, args&: SegmentDescriptorSize, args&: CodeAlignmentFactor,
332 args&: DataAlignmentFactor, args&: ReturnAddressRegister, args&: AugmentationData,
333 args&: FDEPointerEncoding, args&: LSDAPointerEncoding, args&: Personality,
334 args&: PersonalityEncoding, args: Arch);
335 CIEs[StartOffset] = Cie.get();
336 Entries.emplace_back(args: std::move(Cie));
337 } else {
338 // FDE
339 uint64_t CIEPointer = Id;
340 uint64_t InitialLocation = 0;
341 uint64_t AddressRange = 0;
342 std::optional<uint64_t> LSDAAddress;
343 CIE *Cie = CIEs[IsEH ? (StartStructureOffset - CIEPointer) : CIEPointer];
344
345 if (IsEH) {
346 // The address size is encoded in the CIE we reference.
347 if (!Cie)
348 return createStringError(EC: errc::invalid_argument,
349 Fmt: "parsing FDE data at 0x%" PRIx64
350 " failed due to missing CIE",
351 Vals: StartOffset);
352 if (auto Val =
353 Data.getEncodedPointer(Offset: &Offset, Encoding: Cie->getFDEPointerEncoding(),
354 PCRelOffset: EHFrameAddress + Offset)) {
355 InitialLocation = *Val;
356 }
357 if (auto Val = Data.getEncodedPointer(
358 Offset: &Offset, Encoding: Cie->getFDEPointerEncoding(), PCRelOffset: 0)) {
359 AddressRange = *Val;
360 }
361
362 StringRef AugmentationString = Cie->getAugmentationString();
363 if (!AugmentationString.empty()) {
364 // Parse the augmentation length and data for this FDE.
365 uint64_t AugmentationLength = Data.getULEB128(offset_ptr: &Offset);
366
367 uint64_t EndAugmentationOffset = Offset + AugmentationLength;
368
369 // Decode the LSDA if the CIE augmentation string said we should.
370 if (Cie->getLSDAPointerEncoding() != DW_EH_PE_omit) {
371 LSDAAddress = Data.getEncodedPointer(
372 Offset: &Offset, Encoding: Cie->getLSDAPointerEncoding(),
373 PCRelOffset: EHFrameAddress ? Offset + EHFrameAddress : 0);
374 }
375
376 if (Offset != EndAugmentationOffset)
377 return createStringError(EC: errc::invalid_argument,
378 Fmt: "parsing augmentation data at 0x%" PRIx64
379 " failed",
380 Vals: StartOffset);
381 }
382 } else {
383 InitialLocation = Data.getRelocatedAddress(Off: &Offset);
384 AddressRange = Data.getRelocatedAddress(Off: &Offset);
385 }
386
387 Entries.emplace_back(args: new FDE(IsDWARF64, StartOffset, Length, CIEPointer,
388 InitialLocation, AddressRange, Cie,
389 LSDAAddress, Arch));
390 }
391
392 if (!ParseCFIProgram) {
393 // Record where this entry's CFI instructions begin, so that the program
394 // left undecoded here can be parsed on demand later.
395 Entries.back()->markCFIProgramUnparsed(StartOffset: Offset);
396 Offset = EndStructureOffset;
397 continue;
398 }
399
400 if (Error E =
401 Entries.back()->cfis().parse(Data, Offset: &Offset, EndOffset: EndStructureOffset))
402 return E;
403
404 if (Offset != EndStructureOffset)
405 return createStringError(
406 EC: errc::invalid_argument,
407 Fmt: "parsing entry instructions at 0x%" PRIx64 " failed", Vals: StartOffset);
408 }
409
410 return Error::success();
411}
412
413FrameEntry *DWARFDebugFrame::getEntryAtOffset(uint64_t Offset) const {
414 auto It = partition_point(Range: Entries, P: [=](const std::unique_ptr<FrameEntry> &E) {
415 return E->getOffset() < Offset;
416 });
417 if (It != Entries.end() && (*It)->getOffset() == Offset)
418 return It->get();
419 return nullptr;
420}
421
422Error DWARFDebugFrame::parseCFIProgram(FrameEntry &Entry) const {
423 std::optional<uint64_t> StartOffset = Entry.getUnparsedCFIStartOffset();
424 if (!StartOffset)
425 return Error::success();
426
427 if (!Data)
428 return createStringError(
429 EC: errc::invalid_argument,
430 Fmt: "cannot parse the instructions of the entry at 0x%" PRIx64
431 " on demand: the section contents were not retained",
432 Vals: Entry.getOffset());
433
434 uint64_t Offset = *StartOffset;
435 uint64_t EndOffset = Entry.getEndOffset();
436 assert(Offset >= Entry.getOffset() && Offset <= EndOffset &&
437 "entry does not know where its instructions begin");
438 DWARFDataExtractor EntryData = *Data;
439 // Clear previous unsuccessful parsing attempts, if any.
440 Entry.cfis().clear();
441 if (Error E = Entry.cfis().parse(Data&: EntryData, Offset: &Offset, EndOffset))
442 return E;
443
444 if (Offset != EndOffset)
445 return createStringError(EC: errc::invalid_argument,
446 Fmt: "parsing entry instructions at 0x%" PRIx64
447 " failed",
448 Vals: Entry.getOffset());
449
450 // Signal we have a valid fully parsed CFI program.
451 Entry.markCFIProgramParsed();
452 return Error::success();
453}
454
455Error DWARFDebugFrame::parseAllCFIPrograms() const {
456 for (const auto &Entry : Entries)
457 if (Error E = parseCFIProgram(Entry&: *Entry))
458 return E;
459 return Error::success();
460}
461
462void DWARFDebugFrame::dumpEntry(FrameEntry &Entry, raw_ostream &OS,
463 DIDumpOptions DumpOpts) const {
464 if (const auto *Fde = dyn_cast<FDE>(Val: &Entry))
465 if (const CIE *Cie = Fde->getLinkedCIE())
466 if (FrameEntry *CieEntry = getEntryAtOffset(Offset: Cie->getOffset()))
467 if (Error E = parseCFIProgram(Entry&: *CieEntry))
468 DumpOpts.RecoverableErrorHandler(std::move(E));
469
470 if (Error E = parseCFIProgram(Entry))
471 DumpOpts.RecoverableErrorHandler(std::move(E));
472
473 Entry.dump(OS, DumpOpts);
474}
475
476void DWARFDebugFrame::dump(raw_ostream &OS, DIDumpOptions DumpOpts,
477 std::optional<uint64_t> Offset) const {
478 DumpOpts.IsEH = IsEH;
479 if (Offset) {
480 if (auto *Entry = getEntryAtOffset(Offset: *Offset))
481 dumpEntry(Entry&: *Entry, OS, DumpOpts);
482 return;
483 }
484
485 OS << "\n";
486 for (const auto &Entry : Entries)
487 dumpEntry(Entry&: *Entry, OS, DumpOpts);
488}
489