LLVM 20.0.0git
DWARFDebugLine.cpp
Go to the documentation of this file.
1//===- DWARFDebugLine.cpp -------------------------------------------------===//
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
12#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/Errc.h"
18#include "llvm/Support/Format.h"
21#include <algorithm>
22#include <cassert>
23#include <cinttypes>
24#include <cstdint>
25#include <cstdio>
26#include <utility>
27
28using namespace llvm;
29using namespace dwarf;
30
32
33namespace {
34
35struct ContentDescriptor {
38};
39
40using ContentDescriptors = SmallVector<ContentDescriptor, 4>;
41
42} // end anonymous namespace
43
44static bool versionIsSupported(uint16_t Version) {
45 return Version >= 2 && Version <= 5;
46}
47
49 dwarf::LineNumberEntryFormat ContentType) {
50 switch (ContentType) {
51 case dwarf::DW_LNCT_timestamp:
52 HasModTime = true;
53 break;
54 case dwarf::DW_LNCT_size:
55 HasLength = true;
56 break;
57 case dwarf::DW_LNCT_MD5:
58 HasMD5 = true;
59 break;
60 case dwarf::DW_LNCT_LLVM_source:
61 HasSource = true;
62 break;
63 default:
64 // We only care about values we consider optional, and new values may be
65 // added in the vendor extension range, so we do not match exhaustively.
66 break;
67 }
68}
69
71
73 uint16_t DwarfVersion = getVersion();
74 assert(DwarfVersion != 0 &&
75 "line table prologue has no dwarf version information");
76 if (DwarfVersion >= 5)
77 return FileIndex < FileNames.size();
78 return FileIndex != 0 && FileIndex <= FileNames.size();
79}
80
81std::optional<uint64_t>
83 if (FileNames.empty())
84 return std::nullopt;
85 uint16_t DwarfVersion = getVersion();
86 assert(DwarfVersion != 0 &&
87 "line table prologue has no dwarf version information");
88 // In DWARF v5 the file names are 0-indexed.
89 if (DwarfVersion >= 5)
90 return FileNames.size() - 1;
91 return FileNames.size();
92}
93
96 uint16_t DwarfVersion = getVersion();
97 assert(DwarfVersion != 0 &&
98 "line table prologue has no dwarf version information");
99 // In DWARF v5 the file names are 0-indexed.
100 if (DwarfVersion >= 5)
101 return FileNames[Index];
102 return FileNames[Index - 1];
103}
104
106 TotalLength = PrologueLength = 0;
107 SegSelectorSize = 0;
108 MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
109 OpcodeBase = 0;
111 ContentTypes = ContentTypeTracker();
112 StandardOpcodeLengths.clear();
113 IncludeDirectories.clear();
114 FileNames.clear();
115}
116
118 DIDumpOptions DumpOptions) const {
119 if (!totalLengthIsValid())
120 return;
121 int OffsetDumpWidth = 2 * dwarf::getDwarfOffsetByteSize(FormParams.Format);
122 OS << "Line table prologue:\n"
123 << format(" total_length: 0x%0*" PRIx64 "\n", OffsetDumpWidth,
124 TotalLength)
125 << " format: " << dwarf::FormatString(FormParams.Format) << "\n"
126 << format(" version: %u\n", getVersion());
127 if (!versionIsSupported(getVersion()))
128 return;
129 if (getVersion() >= 5)
130 OS << format(" address_size: %u\n", getAddressSize())
131 << format(" seg_select_size: %u\n", SegSelectorSize);
132 OS << format(" prologue_length: 0x%0*" PRIx64 "\n", OffsetDumpWidth,
133 PrologueLength)
134 << format(" min_inst_length: %u\n", MinInstLength)
135 << format(getVersion() >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
136 << format(" default_is_stmt: %u\n", DefaultIsStmt)
137 << format(" line_base: %i\n", LineBase)
138 << format(" line_range: %u\n", LineRange)
139 << format(" opcode_base: %u\n", OpcodeBase);
140
141 for (uint32_t I = 0; I != StandardOpcodeLengths.size(); ++I)
142 OS << formatv("standard_opcode_lengths[{0}] = {1}\n",
143 static_cast<dwarf::LineNumberOps>(I + 1),
144 StandardOpcodeLengths[I]);
145
146 if (!IncludeDirectories.empty()) {
147 // DWARF v5 starts directory indexes at 0.
148 uint32_t DirBase = getVersion() >= 5 ? 0 : 1;
149 for (uint32_t I = 0; I != IncludeDirectories.size(); ++I) {
150 OS << format("include_directories[%3u] = ", I + DirBase);
151 IncludeDirectories[I].dump(OS, DumpOptions);
152 OS << '\n';
153 }
154 }
155
156 if (!FileNames.empty()) {
157 // DWARF v5 starts file indexes at 0.
158 uint32_t FileBase = getVersion() >= 5 ? 0 : 1;
159 for (uint32_t I = 0; I != FileNames.size(); ++I) {
160 const FileNameEntry &FileEntry = FileNames[I];
161 OS << format("file_names[%3u]:\n", I + FileBase);
162 OS << " name: ";
163 FileEntry.Name.dump(OS, DumpOptions);
164 OS << '\n' << format(" dir_index: %" PRIu64 "\n", FileEntry.DirIdx);
165 if (ContentTypes.HasMD5)
166 OS << " md5_checksum: " << FileEntry.Checksum.digest() << '\n';
167 if (ContentTypes.HasModTime)
168 OS << format(" mod_time: 0x%8.8" PRIx64 "\n", FileEntry.ModTime);
169 if (ContentTypes.HasLength)
170 OS << format(" length: 0x%8.8" PRIx64 "\n", FileEntry.Length);
171 if (ContentTypes.HasSource) {
172 auto Source = FileEntry.Source.getAsCString();
173 if (!Source)
174 consumeError(Source.takeError());
175 else if ((*Source)[0]) {
176 OS << " source: ";
177 FileEntry.Source.dump(OS, DumpOptions);
178 OS << '\n';
179 }
180 }
181 }
182 }
183}
184
185// Parse v2-v4 directory and file tables.
186static Error
188 uint64_t *OffsetPtr,
190 std::vector<DWARFFormValue> &IncludeDirectories,
191 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
192 while (true) {
193 Error Err = Error::success();
194 StringRef S = DebugLineData.getCStrRef(OffsetPtr, &Err);
195 if (Err) {
196 consumeError(std::move(Err));
198 "include directories table was not null "
199 "terminated before the end of the prologue");
200 }
201 if (S.empty())
202 break;
203 DWARFFormValue Dir =
204 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, S.data());
205 IncludeDirectories.push_back(Dir);
206 }
207
208 ContentTypes.HasModTime = true;
209 ContentTypes.HasLength = true;
210
211 while (true) {
212 Error Err = Error::success();
213 StringRef Name = DebugLineData.getCStrRef(OffsetPtr, &Err);
214 if (!Err && Name.empty())
215 break;
216
218 FileEntry.Name =
219 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name.data());
220 FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr, &Err);
221 FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr, &Err);
222 FileEntry.Length = DebugLineData.getULEB128(OffsetPtr, &Err);
223
224 if (Err) {
225 consumeError(std::move(Err));
226 return createStringError(
228 "file names table was not null terminated before "
229 "the end of the prologue");
230 }
231 FileNames.push_back(FileEntry);
232 }
233
234 return Error::success();
235}
236
237// Parse v5 directory/file entry content descriptions.
238// Returns the descriptors, or an error if we did not find a path or ran off
239// the end of the prologue.
241parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
243 Error Err = Error::success();
244 ContentDescriptors Descriptors;
245 int FormatCount = DebugLineData.getU8(OffsetPtr, &Err);
246 bool HasPath = false;
247 for (int I = 0; I != FormatCount && !Err; ++I) {
248 ContentDescriptor Descriptor;
249 Descriptor.Type =
250 dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr, &Err));
251 Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr, &Err));
252 if (Descriptor.Type == dwarf::DW_LNCT_path)
253 HasPath = true;
254 if (ContentTypes)
255 ContentTypes->trackContentType(Descriptor.Type);
256 Descriptors.push_back(Descriptor);
257 }
258
259 if (Err)
261 "failed to parse entry content descriptors: %s",
262 toString(std::move(Err)).c_str());
263
264 if (!HasPath)
266 "failed to parse entry content descriptions"
267 " because no path was found");
268 return Descriptors;
269}
270
271static Error
273 uint64_t *OffsetPtr, const dwarf::FormParams &FormParams,
274 const DWARFContext &Ctx, const DWARFUnit *U,
276 std::vector<DWARFFormValue> &IncludeDirectories,
277 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
278 // Get the directory entry description.
280 parseV5EntryFormat(DebugLineData, OffsetPtr, nullptr);
281 if (!DirDescriptors)
282 return DirDescriptors.takeError();
283
284 // Get the directory entries, according to the format described above.
285 uint64_t DirEntryCount = DebugLineData.getULEB128(OffsetPtr);
286 for (uint64_t I = 0; I != DirEntryCount; ++I) {
287 for (auto Descriptor : *DirDescriptors) {
288 DWARFFormValue Value(Descriptor.Form);
289 switch (Descriptor.Type) {
290 case DW_LNCT_path:
291 if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
293 "failed to parse directory entry because "
294 "extracting the form value failed");
295 IncludeDirectories.push_back(Value);
296 break;
297 default:
298 if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams))
300 "failed to parse directory entry because "
301 "skipping the form value failed");
302 }
303 }
304 }
305
306 // Get the file entry description.
307 llvm::Expected<ContentDescriptors> FileDescriptors =
308 parseV5EntryFormat(DebugLineData, OffsetPtr, &ContentTypes);
309 if (!FileDescriptors)
310 return FileDescriptors.takeError();
311
312 // Get the file entries, according to the format described above.
313 uint64_t FileEntryCount = DebugLineData.getULEB128(OffsetPtr);
314 for (uint64_t I = 0; I != FileEntryCount; ++I) {
316 for (auto Descriptor : *FileDescriptors) {
317 DWARFFormValue Value(Descriptor.Form);
318 if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
320 "failed to parse file entry because "
321 "extracting the form value failed");
322 switch (Descriptor.Type) {
323 case DW_LNCT_path:
324 FileEntry.Name = Value;
325 break;
326 case DW_LNCT_LLVM_source:
327 FileEntry.Source = Value;
328 break;
329 case DW_LNCT_directory_index:
330 FileEntry.DirIdx = *Value.getAsUnsignedConstant();
331 break;
332 case DW_LNCT_timestamp:
333 FileEntry.ModTime = *Value.getAsUnsignedConstant();
334 break;
335 case DW_LNCT_size:
336 FileEntry.Length = *Value.getAsUnsignedConstant();
337 break;
338 case DW_LNCT_MD5:
339 if (!Value.getAsBlock() || Value.getAsBlock()->size() != 16)
340 return createStringError(
342 "failed to parse file entry because the MD5 hash is invalid");
343 std::uninitialized_copy_n(Value.getAsBlock()->begin(), 16,
344 FileEntry.Checksum.begin());
345 break;
346 default:
347 break;
348 }
349 }
350 FileNames.push_back(FileEntry);
351 }
352 return Error::success();
353}
354
356 uint64_t Length = PrologueLength + sizeofTotalLength() +
357 sizeof(getVersion()) + sizeofPrologueLength();
358 if (getVersion() >= 5)
359 Length += 2; // Address + Segment selector sizes.
360 return Length;
361}
362
364 DWARFDataExtractor DebugLineData, uint64_t *OffsetPtr,
365 function_ref<void(Error)> RecoverableErrorHandler, const DWARFContext &Ctx,
366 const DWARFUnit *U) {
367 const uint64_t PrologueOffset = *OffsetPtr;
368
369 clear();
370 DataExtractor::Cursor Cursor(*OffsetPtr);
371 std::tie(TotalLength, FormParams.Format) =
372 DebugLineData.getInitialLength(Cursor);
373
374 DebugLineData =
375 DWARFDataExtractor(DebugLineData, Cursor.tell() + TotalLength);
376 FormParams.Version = DebugLineData.getU16(Cursor);
377 if (Cursor && !versionIsSupported(getVersion())) {
378 // Treat this error as unrecoverable - we cannot be sure what any of
379 // the data represents including the length field, so cannot skip it or make
380 // any reasonable assumptions.
381 *OffsetPtr = Cursor.tell();
382 return createStringError(
384 "parsing line table prologue at offset 0x%8.8" PRIx64
385 ": unsupported version %" PRIu16,
386 PrologueOffset, getVersion());
387 }
388
389 if (getVersion() >= 5) {
390 FormParams.AddrSize = DebugLineData.getU8(Cursor);
391 const uint8_t DataAddrSize = DebugLineData.getAddressSize();
392 const uint8_t PrologueAddrSize = getAddressSize();
393 if (Cursor) {
394 if (DataAddrSize == 0) {
395 if (PrologueAddrSize != 4 && PrologueAddrSize != 8) {
396 RecoverableErrorHandler(createStringError(
398 "parsing line table prologue at offset 0x%8.8" PRIx64
399 ": invalid address size %" PRIu8,
400 PrologueOffset, PrologueAddrSize));
401 }
402 } else if (DataAddrSize != PrologueAddrSize) {
403 RecoverableErrorHandler(createStringError(
405 "parsing line table prologue at offset 0x%8.8" PRIx64 ": address "
406 "size %" PRIu8 " doesn't match architecture address size %" PRIu8,
407 PrologueOffset, PrologueAddrSize, DataAddrSize));
408 }
409 }
410 SegSelectorSize = DebugLineData.getU8(Cursor);
411 }
412
413 PrologueLength =
414 DebugLineData.getRelocatedValue(Cursor, sizeofPrologueLength());
415 const uint64_t EndPrologueOffset = PrologueLength + Cursor.tell();
416 DebugLineData = DWARFDataExtractor(DebugLineData, EndPrologueOffset);
417 MinInstLength = DebugLineData.getU8(Cursor);
418 if (getVersion() >= 4)
419 MaxOpsPerInst = DebugLineData.getU8(Cursor);
420 DefaultIsStmt = DebugLineData.getU8(Cursor);
421 LineBase = DebugLineData.getU8(Cursor);
422 LineRange = DebugLineData.getU8(Cursor);
423 OpcodeBase = DebugLineData.getU8(Cursor);
424
425 if (Cursor && OpcodeBase == 0) {
426 // If the opcode base is 0, we cannot read the standard opcode lengths (of
427 // which there are supposed to be one fewer than the opcode base). Assume
428 // there are no standard opcodes and continue parsing.
429 RecoverableErrorHandler(createStringError(
431 "parsing line table prologue at offset 0x%8.8" PRIx64
432 " found opcode base of 0. Assuming no standard opcodes",
433 PrologueOffset));
434 } else if (Cursor) {
435 StandardOpcodeLengths.reserve(OpcodeBase - 1);
436 for (uint32_t I = 1; I < OpcodeBase; ++I) {
437 uint8_t OpLen = DebugLineData.getU8(Cursor);
438 StandardOpcodeLengths.push_back(OpLen);
439 }
440 }
441
442 *OffsetPtr = Cursor.tell();
443 // A corrupt file name or directory table does not prevent interpretation of
444 // the main line program, so check the cursor state now so that its errors can
445 // be handled separately.
446 if (!Cursor)
447 return createStringError(
449 "parsing line table prologue at offset 0x%8.8" PRIx64 ": %s",
450 PrologueOffset, toString(Cursor.takeError()).c_str());
451
452 Error E =
453 getVersion() >= 5
454 ? parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U,
455 ContentTypes, IncludeDirectories, FileNames)
456 : parseV2DirFileTables(DebugLineData, OffsetPtr, ContentTypes,
457 IncludeDirectories, FileNames);
458 if (E) {
459 RecoverableErrorHandler(joinErrors(
462 "parsing line table prologue at 0x%8.8" PRIx64
463 " found an invalid directory or file table description at"
464 " 0x%8.8" PRIx64,
465 PrologueOffset, *OffsetPtr),
466 std::move(E)));
467 return Error::success();
468 }
469
470 assert(*OffsetPtr <= EndPrologueOffset);
471 if (*OffsetPtr != EndPrologueOffset) {
472 RecoverableErrorHandler(createStringError(
474 "unknown data in line table prologue at offset 0x%8.8" PRIx64
475 ": parsing ended (at offset 0x%8.8" PRIx64
476 ") before reaching the prologue end at offset 0x%8.8" PRIx64,
477 PrologueOffset, *OffsetPtr, EndPrologueOffset));
478 }
479 return Error::success();
480}
481
482DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); }
483
485 Discriminator = 0;
486 BasicBlock = false;
487 PrologueEnd = false;
488 EpilogueBegin = false;
489}
490
491void DWARFDebugLine::Row::reset(bool DefaultIsStmt) {
492 Address.Address = 0;
494 Line = 1;
495 Column = 0;
496 File = 1;
497 Isa = 0;
498 Discriminator = 0;
499 IsStmt = DefaultIsStmt;
500 OpIndex = 0;
501 BasicBlock = false;
502 EndSequence = false;
503 PrologueEnd = false;
504 EpilogueBegin = false;
505}
506
508 OS.indent(Indent)
509 << "Address Line Column File ISA Discriminator OpIndex "
510 "Flags\n";
511 OS.indent(Indent)
512 << "------------------ ------ ------ ------ --- ------------- ------- "
513 "-------------\n";
514}
515
517 OS << format("0x%16.16" PRIx64 " %6u %6u", Address.Address, Line, Column)
518 << format(" %6u %3u %13u %7u ", File, Isa, Discriminator, OpIndex)
519 << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "")
520 << (PrologueEnd ? " prologue_end" : "")
521 << (EpilogueBegin ? " epilogue_begin" : "")
522 << (EndSequence ? " end_sequence" : "") << '\n';
523}
524
526
528 LowPC = 0;
529 HighPC = 0;
531 FirstRowIndex = 0;
532 LastRowIndex = 0;
533 Empty = true;
534}
535
537
539 DIDumpOptions DumpOptions) const {
540 Prologue.dump(OS, DumpOptions);
541
542 if (!Rows.empty()) {
543 OS << '\n';
545 for (const Row &R : Rows) {
546 R.dump(OS);
547 }
548 }
549
550 // Terminate the table with a final blank line to clearly delineate it from
551 // later dumps.
552 OS << '\n';
553}
554
556 Prologue.clear();
557 Rows.clear();
558 Sequences.clear();
559}
560
561DWARFDebugLine::ParsingState::ParsingState(
562 struct LineTable *LT, uint64_t TableOffset,
564 : LineTable(LT), LineTableOffset(TableOffset), ErrorHandler(ErrorHandler) {
565 resetRowAndSequence();
566}
567
568void DWARFDebugLine::ParsingState::resetRowAndSequence() {
569 Row.reset(LineTable->Prologue.DefaultIsStmt);
570 Sequence.reset();
571}
572
573void DWARFDebugLine::ParsingState::appendRowToMatrix() {
574 unsigned RowNumber = LineTable->Rows.size();
575 if (Sequence.Empty) {
576 // Record the beginning of instruction sequence.
577 Sequence.Empty = false;
578 Sequence.LowPC = Row.Address.Address;
579 Sequence.FirstRowIndex = RowNumber;
580 }
581 LineTable->appendRow(Row);
582 if (Row.EndSequence) {
583 // Record the end of instruction sequence.
584 Sequence.HighPC = Row.Address.Address;
585 Sequence.LastRowIndex = RowNumber + 1;
586 Sequence.SectionIndex = Row.Address.SectionIndex;
587 if (Sequence.isValid())
588 LineTable->appendSequence(Sequence);
589 Sequence.reset();
590 }
591 Row.postAppend();
592}
593
596 LineTableConstIter Pos = LineTableMap.find(Offset);
597 if (Pos != LineTableMap.end())
598 return &Pos->second;
599 return nullptr;
600}
601
603 DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx,
604 const DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
605 if (!DebugLineData.isValidOffset(Offset))
607 "offset 0x%8.8" PRIx64
608 " is not a valid debug line section offset",
609 Offset);
610
611 std::pair<LineTableIter, bool> Pos =
612 LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable()));
613 LineTable *LT = &Pos.first->second;
614 if (Pos.second) {
615 if (Error Err =
616 LT->parse(DebugLineData, &Offset, Ctx, U, RecoverableErrorHandler))
617 return std::move(Err);
618 return LT;
619 }
620 return LT;
621}
622
624 LineTableMap.erase(Offset);
625}
626
627static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase) {
628 assert(Opcode != 0);
629 if (Opcode < OpcodeBase)
630 return LNStandardString(Opcode);
631 return "special";
632}
633
635DWARFDebugLine::ParsingState::advanceAddrOpIndex(uint64_t OperationAdvance,
636 uint8_t Opcode,
637 uint64_t OpcodeOffset) {
638 StringRef OpcodeName = getOpcodeName(Opcode, LineTable->Prologue.OpcodeBase);
639 // For versions less than 4, the MaxOpsPerInst member is set to 0, as the
640 // maximum_operations_per_instruction field wasn't introduced until DWARFv4.
641 // Don't warn about bad values in this situation.
642 if (ReportAdvanceAddrProblem && LineTable->Prologue.getVersion() >= 4 &&
643 LineTable->Prologue.MaxOpsPerInst == 0)
646 "line table program at offset 0x%8.8" PRIx64
647 " contains a %s opcode at offset 0x%8.8" PRIx64
648 ", but the prologue maximum_operations_per_instruction value is 0"
649 ", which is invalid. Assuming a value of 1 instead",
650 LineTableOffset, OpcodeName.data(), OpcodeOffset));
651 // Although we are able to correctly parse line number programs with
652 // MaxOpsPerInst > 1, the rest of DWARFDebugLine and its
653 // users have not been updated to handle line information for all operations
654 // in a multi-operation instruction, so warn about potentially incorrect
655 // results.
656 if (ReportAdvanceAddrProblem && LineTable->Prologue.MaxOpsPerInst > 1)
659 "line table program at offset 0x%8.8" PRIx64
660 " contains a %s opcode at offset 0x%8.8" PRIx64
661 ", but the prologue maximum_operations_per_instruction value is %" PRId8
662 ", which is experimentally supported, so line number information "
663 "may be incorrect",
664 LineTableOffset, OpcodeName.data(), OpcodeOffset,
665 LineTable->Prologue.MaxOpsPerInst));
666 if (ReportAdvanceAddrProblem && LineTable->Prologue.MinInstLength == 0)
669 "line table program at offset 0x%8.8" PRIx64
670 " contains a %s opcode at offset 0x%8.8" PRIx64
671 ", but the prologue minimum_instruction_length value "
672 "is 0, which prevents any address advancing",
673 LineTableOffset, OpcodeName.data(), OpcodeOffset));
674 ReportAdvanceAddrProblem = false;
675
676 // Advances the address and op_index according to DWARFv5, section 6.2.5.1:
677 //
678 // new address = address +
679 // minimum_instruction_length *
680 // ((op_index + operation advance) / maximum_operations_per_instruction)
681 //
682 // new op_index =
683 // (op_index + operation advance) % maximum_operations_per_instruction
684
685 // For versions less than 4, the MaxOpsPerInst member is set to 0, as the
686 // maximum_operations_per_instruction field wasn't introduced until DWARFv4.
687 uint8_t MaxOpsPerInst =
688 std::max(LineTable->Prologue.MaxOpsPerInst, uint8_t{1});
689
690 uint64_t AddrOffset = ((Row.OpIndex + OperationAdvance) / MaxOpsPerInst) *
691 LineTable->Prologue.MinInstLength;
692 Row.Address.Address += AddrOffset;
693
694 uint8_t PrevOpIndex = Row.OpIndex;
695 Row.OpIndex = (Row.OpIndex + OperationAdvance) % MaxOpsPerInst;
696 int16_t OpIndexDelta = static_cast<int16_t>(Row.OpIndex) - PrevOpIndex;
697
698 return {AddrOffset, OpIndexDelta};
699}
700
702DWARFDebugLine::ParsingState::advanceForOpcode(uint8_t Opcode,
703 uint64_t OpcodeOffset) {
704 assert(Opcode == DW_LNS_const_add_pc ||
705 Opcode >= LineTable->Prologue.OpcodeBase);
706 if (ReportBadLineRange && LineTable->Prologue.LineRange == 0) {
707 StringRef OpcodeName =
708 getOpcodeName(Opcode, LineTable->Prologue.OpcodeBase);
711 "line table program at offset 0x%8.8" PRIx64
712 " contains a %s opcode at offset 0x%8.8" PRIx64
713 ", but the prologue line_range value is 0. The "
714 "address and line will not be adjusted",
715 LineTableOffset, OpcodeName.data(), OpcodeOffset));
716 ReportBadLineRange = false;
717 }
718
719 uint8_t OpcodeValue = Opcode;
720 if (Opcode == DW_LNS_const_add_pc)
721 OpcodeValue = 255;
722 uint8_t AdjustedOpcode = OpcodeValue - LineTable->Prologue.OpcodeBase;
723 uint64_t OperationAdvance =
724 LineTable->Prologue.LineRange != 0
725 ? AdjustedOpcode / LineTable->Prologue.LineRange
726 : 0;
727 AddrOpIndexDelta Advance =
728 advanceAddrOpIndex(OperationAdvance, Opcode, OpcodeOffset);
729 return {Advance.AddrOffset, Advance.OpIndexDelta, AdjustedOpcode};
730}
731
733DWARFDebugLine::ParsingState::handleSpecialOpcode(uint8_t Opcode,
734 uint64_t OpcodeOffset) {
735 // A special opcode value is chosen based on the amount that needs
736 // to be added to the line and address registers. The maximum line
737 // increment for a special opcode is the value of the line_base
738 // field in the header, plus the value of the line_range field,
739 // minus 1 (line base + line range - 1). If the desired line
740 // increment is greater than the maximum line increment, a standard
741 // opcode must be used instead of a special opcode. The "address
742 // advance" is calculated by dividing the desired address increment
743 // by the minimum_instruction_length field from the header. The
744 // special opcode is then calculated using the following formula:
745 //
746 // opcode = (desired line increment - line_base) +
747 // (line_range * address advance) + opcode_base
748 //
749 // If the resulting opcode is greater than 255, a standard opcode
750 // must be used instead.
751 //
752 // To decode a special opcode, subtract the opcode_base from the
753 // opcode itself to give the adjusted opcode. The amount to
754 // increment the address register is the result of the adjusted
755 // opcode divided by the line_range multiplied by the
756 // minimum_instruction_length field from the header. That is:
757 //
758 // address increment = (adjusted opcode / line_range) *
759 // minimum_instruction_length
760 //
761 // The amount to increment the line register is the line_base plus
762 // the result of the adjusted opcode modulo the line_range. That is:
763 //
764 // line increment = line_base + (adjusted opcode % line_range)
765
767 advanceForOpcode(Opcode, OpcodeOffset);
768 int32_t LineOffset = 0;
769 if (LineTable->Prologue.LineRange != 0)
770 LineOffset =
771 LineTable->Prologue.LineBase +
772 (AddrAdvanceResult.AdjustedOpcode % LineTable->Prologue.LineRange);
773 Row.Line += LineOffset;
774 return {AddrAdvanceResult.AddrDelta, LineOffset,
775 AddrAdvanceResult.OpIndexDelta};
776}
777
778/// Parse a ULEB128 using the specified \p Cursor. \returns the parsed value on
779/// success, or std::nullopt if \p Cursor is in a failing state.
780template <typename T>
781static std::optional<T> parseULEB128(DWARFDataExtractor &Data,
782 DataExtractor::Cursor &Cursor) {
783 T Value = Data.getULEB128(Cursor);
784 if (Cursor)
785 return Value;
786 return std::nullopt;
787}
788
790 DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
791 const DWARFContext &Ctx, const DWARFUnit *U,
792 function_ref<void(Error)> RecoverableErrorHandler, raw_ostream *OS,
793 bool Verbose) {
794 assert((OS || !Verbose) && "cannot have verbose output without stream");
795 const uint64_t DebugLineOffset = *OffsetPtr;
796
797 clear();
798
799 Error PrologueErr =
800 Prologue.parse(DebugLineData, OffsetPtr, RecoverableErrorHandler, Ctx, U);
801
802 if (OS) {
803 DIDumpOptions DumpOptions;
804 DumpOptions.Verbose = Verbose;
805 Prologue.dump(*OS, DumpOptions);
806 }
807
808 if (PrologueErr) {
809 // Ensure there is a blank line after the prologue to clearly delineate it
810 // from later dumps.
811 if (OS)
812 *OS << "\n";
813 return PrologueErr;
814 }
815
817 if (!DebugLineData.isValidOffsetForDataOfSize(DebugLineOffset,
818 ProgramLength)) {
819 assert(DebugLineData.size() > DebugLineOffset &&
820 "prologue parsing should handle invalid offset");
821 uint64_t BytesRemaining = DebugLineData.size() - DebugLineOffset;
822 RecoverableErrorHandler(
824 "line table program with offset 0x%8.8" PRIx64
825 " has length 0x%8.8" PRIx64 " but only 0x%8.8" PRIx64
826 " bytes are available",
827 DebugLineOffset, ProgramLength, BytesRemaining));
828 // Continue by capping the length at the number of remaining bytes.
829 ProgramLength = BytesRemaining;
830 }
831
832 // Create a DataExtractor which can only see the data up to the end of the
833 // table, to prevent reading past the end.
834 const uint64_t EndOffset = DebugLineOffset + ProgramLength;
835 DWARFDataExtractor TableData(DebugLineData, EndOffset);
836
837 // See if we should tell the data extractor the address size.
838 if (TableData.getAddressSize() == 0)
840 else
842 Prologue.getAddressSize() == TableData.getAddressSize());
843
844 ParsingState State(this, DebugLineOffset, RecoverableErrorHandler);
845
846 *OffsetPtr = DebugLineOffset + Prologue.getLength();
847 if (OS && *OffsetPtr < EndOffset) {
848 *OS << '\n';
849 Row::dumpTableHeader(*OS, /*Indent=*/Verbose ? 12 : 0);
850 }
851 bool TombstonedAddress = false;
852 auto EmitRow = [&] {
853 if (!TombstonedAddress) {
854 if (Verbose) {
855 *OS << "\n";
856 OS->indent(12);
857 }
858 if (OS)
859 State.Row.dump(*OS);
860 State.appendRowToMatrix();
861 }
862 };
863 while (*OffsetPtr < EndOffset) {
864 DataExtractor::Cursor Cursor(*OffsetPtr);
865
866 if (Verbose)
867 *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr);
868
869 uint64_t OpcodeOffset = *OffsetPtr;
870 uint8_t Opcode = TableData.getU8(Cursor);
871 size_t RowCount = Rows.size();
872
873 if (Cursor && Verbose)
874 *OS << format("%02.02" PRIx8 " ", Opcode);
875
876 if (Opcode == 0) {
877 // Extended Opcodes always start with a zero opcode followed by
878 // a uleb128 length so you can skip ones you don't know about
879 uint64_t Len = TableData.getULEB128(Cursor);
880 uint64_t ExtOffset = Cursor.tell();
881
882 // Tolerate zero-length; assume length is correct and soldier on.
883 if (Len == 0) {
884 if (Cursor && Verbose)
885 *OS << "Badly formed extended line op (length 0)\n";
886 if (!Cursor) {
887 if (Verbose)
888 *OS << "\n";
889 RecoverableErrorHandler(Cursor.takeError());
890 }
891 *OffsetPtr = Cursor.tell();
892 continue;
893 }
894
895 uint8_t SubOpcode = TableData.getU8(Cursor);
896 // OperandOffset will be the same as ExtOffset, if it was not possible to
897 // read the SubOpcode.
898 uint64_t OperandOffset = Cursor.tell();
899 if (Verbose)
900 *OS << LNExtendedString(SubOpcode);
901 switch (SubOpcode) {
902 case DW_LNE_end_sequence:
903 // Set the end_sequence register of the state machine to true and
904 // append a row to the matrix using the current values of the
905 // state-machine registers. Then reset the registers to the initial
906 // values specified above. Every statement program sequence must end
907 // with a DW_LNE_end_sequence instruction which creates a row whose
908 // address is that of the byte after the last target machine instruction
909 // of the sequence.
910 State.Row.EndSequence = true;
911 // No need to test the Cursor is valid here, since it must be to get
912 // into this code path - if it were invalid, the default case would be
913 // followed.
914 EmitRow();
915 State.resetRowAndSequence();
916 break;
917
918 case DW_LNE_set_address:
919 // Takes a single relocatable address as an operand. The size of the
920 // operand is the size appropriate to hold an address on the target
921 // machine. Set the address register to the value given by the
922 // relocatable address and set the op_index register to 0. All of the
923 // other statement program opcodes that affect the address register
924 // add a delta to it. This instruction stores a relocatable value into
925 // it instead.
926 //
927 // Make sure the extractor knows the address size. If not, infer it
928 // from the size of the operand.
929 {
930 uint8_t ExtractorAddressSize = TableData.getAddressSize();
931 uint64_t OpcodeAddressSize = Len - 1;
932 if (ExtractorAddressSize != OpcodeAddressSize &&
933 ExtractorAddressSize != 0)
934 RecoverableErrorHandler(createStringError(
936 "mismatching address size at offset 0x%8.8" PRIx64
937 " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
938 ExtOffset, ExtractorAddressSize, Len - 1));
939
940 // Assume that the line table is correct and temporarily override the
941 // address size. If the size is unsupported, give up trying to read
942 // the address and continue to the next opcode.
943 if (OpcodeAddressSize != 1 && OpcodeAddressSize != 2 &&
944 OpcodeAddressSize != 4 && OpcodeAddressSize != 8) {
945 RecoverableErrorHandler(createStringError(
947 "address size 0x%2.2" PRIx64
948 " of DW_LNE_set_address opcode at offset 0x%8.8" PRIx64
949 " is unsupported",
950 OpcodeAddressSize, ExtOffset));
951 TableData.skip(Cursor, OpcodeAddressSize);
952 } else {
953 TableData.setAddressSize(OpcodeAddressSize);
954 State.Row.Address.Address = TableData.getRelocatedAddress(
955 Cursor, &State.Row.Address.SectionIndex);
956 State.Row.OpIndex = 0;
957
958 uint64_t Tombstone =
959 dwarf::computeTombstoneAddress(OpcodeAddressSize);
960 TombstonedAddress = State.Row.Address.Address == Tombstone;
961
962 // Restore the address size if the extractor already had it.
963 if (ExtractorAddressSize != 0)
964 TableData.setAddressSize(ExtractorAddressSize);
965 }
966
967 if (Cursor && Verbose) {
968 *OS << " (";
969 DWARFFormValue::dumpAddress(*OS, OpcodeAddressSize,
970 State.Row.Address.Address);
971 *OS << ')';
972 }
973 }
974 break;
975
976 case DW_LNE_define_file:
977 // Takes 4 arguments. The first is a null terminated string containing
978 // a source file name. The second is an unsigned LEB128 number
979 // representing the directory index of the directory in which the file
980 // was found. The third is an unsigned LEB128 number representing the
981 // time of last modification of the file. The fourth is an unsigned
982 // LEB128 number representing the length in bytes of the file. The time
983 // and length fields may contain LEB128(0) if the information is not
984 // available.
985 //
986 // The directory index represents an entry in the include_directories
987 // section of the statement program prologue. The index is LEB128(0)
988 // if the file was found in the current directory of the compilation,
989 // LEB128(1) if it was found in the first directory in the
990 // include_directories section, and so on. The directory index is
991 // ignored for file names that represent full path names.
992 //
993 // The files are numbered, starting at 1, in the order in which they
994 // appear; the names in the prologue come before names defined by
995 // the DW_LNE_define_file instruction. These numbers are used in the
996 // the file register of the state machine.
997 {
998 FileNameEntry FileEntry;
999 const char *Name = TableData.getCStr(Cursor);
1000 FileEntry.Name =
1001 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name);
1002 FileEntry.DirIdx = TableData.getULEB128(Cursor);
1003 FileEntry.ModTime = TableData.getULEB128(Cursor);
1004 FileEntry.Length = TableData.getULEB128(Cursor);
1005 Prologue.FileNames.push_back(FileEntry);
1006 if (Cursor && Verbose)
1007 *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time="
1008 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime)
1009 << ", length=" << FileEntry.Length << ")";
1010 }
1011 break;
1012
1013 case DW_LNE_set_discriminator:
1014 State.Row.Discriminator = TableData.getULEB128(Cursor);
1015 if (Cursor && Verbose)
1016 *OS << " (" << State.Row.Discriminator << ")";
1017 break;
1018
1019 default:
1020 if (Cursor && Verbose)
1021 *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode)
1022 << format(" length %" PRIx64, Len);
1023 // Len doesn't include the zero opcode byte or the length itself, but
1024 // it does include the sub_opcode, so we have to adjust for that.
1025 TableData.skip(Cursor, Len - 1);
1026 break;
1027 }
1028 // Make sure the length as recorded in the table and the standard length
1029 // for the opcode match. If they don't, continue from the end as claimed
1030 // by the table. Similarly, continue from the claimed end in the event of
1031 // a parsing error.
1032 uint64_t End = ExtOffset + Len;
1033 if (Cursor && Cursor.tell() != End)
1034 RecoverableErrorHandler(createStringError(
1036 "unexpected line op length at offset 0x%8.8" PRIx64
1037 " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64,
1038 ExtOffset, Len, Cursor.tell() - ExtOffset));
1039 if (!Cursor && Verbose) {
1040 DWARFDataExtractor::Cursor ByteCursor(OperandOffset);
1041 uint8_t Byte = TableData.getU8(ByteCursor);
1042 if (ByteCursor) {
1043 *OS << " (<parsing error>";
1044 do {
1045 *OS << format(" %2.2" PRIx8, Byte);
1046 Byte = TableData.getU8(ByteCursor);
1047 } while (ByteCursor);
1048 *OS << ")";
1049 }
1050
1051 // The only parse failure in this case should be if the end was reached.
1052 // In that case, throw away the error, as the main Cursor's error will
1053 // be sufficient.
1054 consumeError(ByteCursor.takeError());
1055 }
1056 *OffsetPtr = End;
1057 } else if (Opcode < Prologue.OpcodeBase) {
1058 if (Verbose)
1059 *OS << LNStandardString(Opcode);
1060 switch (Opcode) {
1061 // Standard Opcodes
1062 case DW_LNS_copy:
1063 // Takes no arguments. Append a row to the matrix using the
1064 // current values of the state-machine registers.
1065 EmitRow();
1066 break;
1067
1068 case DW_LNS_advance_pc:
1069 // Takes a single unsigned LEB128 operand as the operation advance
1070 // and modifies the address and op_index registers of the state machine
1071 // according to that.
1072 if (std::optional<uint64_t> Operand =
1073 parseULEB128<uint64_t>(TableData, Cursor)) {
1075 State.advanceAddrOpIndex(*Operand, Opcode, OpcodeOffset);
1076 if (Verbose)
1077 *OS << " (addr += " << Advance.AddrOffset
1078 << ", op-index += " << Advance.OpIndexDelta << ")";
1079 }
1080 break;
1081
1082 case DW_LNS_advance_line:
1083 // Takes a single signed LEB128 operand and adds that value to
1084 // the line register of the state machine.
1085 {
1086 int64_t LineDelta = TableData.getSLEB128(Cursor);
1087 if (Cursor) {
1088 State.Row.Line += LineDelta;
1089 if (Verbose)
1090 *OS << " (" << State.Row.Line << ")";
1091 }
1092 }
1093 break;
1094
1095 case DW_LNS_set_file:
1096 // Takes a single unsigned LEB128 operand and stores it in the file
1097 // register of the state machine.
1098 if (std::optional<uint16_t> File =
1099 parseULEB128<uint16_t>(TableData, Cursor)) {
1100 State.Row.File = *File;
1101 if (Verbose)
1102 *OS << " (" << State.Row.File << ")";
1103 }
1104 break;
1105
1106 case DW_LNS_set_column:
1107 // Takes a single unsigned LEB128 operand and stores it in the
1108 // column register of the state machine.
1109 if (std::optional<uint16_t> Column =
1110 parseULEB128<uint16_t>(TableData, Cursor)) {
1111 State.Row.Column = *Column;
1112 if (Verbose)
1113 *OS << " (" << State.Row.Column << ")";
1114 }
1115 break;
1116
1117 case DW_LNS_negate_stmt:
1118 // Takes no arguments. Set the is_stmt register of the state
1119 // machine to the logical negation of its current value.
1120 State.Row.IsStmt = !State.Row.IsStmt;
1121 break;
1122
1123 case DW_LNS_set_basic_block:
1124 // Takes no arguments. Set the basic_block register of the
1125 // state machine to true
1126 State.Row.BasicBlock = true;
1127 break;
1128
1129 case DW_LNS_const_add_pc:
1130 // Takes no arguments. Advance the address and op_index registers of
1131 // the state machine by the increments corresponding to special
1132 // opcode 255. The motivation for DW_LNS_const_add_pc is this:
1133 // when the statement program needs to advance the address by a
1134 // small amount, it can use a single special opcode, which occupies
1135 // a single byte. When it needs to advance the address by up to
1136 // twice the range of the last special opcode, it can use
1137 // DW_LNS_const_add_pc followed by a special opcode, for a total
1138 // of two bytes. Only if it needs to advance the address by more
1139 // than twice that range will it need to use both DW_LNS_advance_pc
1140 // and a special opcode, requiring three or more bytes.
1141 {
1143 State.advanceForOpcode(Opcode, OpcodeOffset);
1144 if (Verbose)
1145 *OS << format(" (addr += 0x%16.16" PRIx64 ", op-index += %" PRIu8
1146 ")",
1147 Advance.AddrDelta, Advance.OpIndexDelta);
1148 }
1149 break;
1150
1151 case DW_LNS_fixed_advance_pc:
1152 // Takes a single uhalf operand. Add to the address register of
1153 // the state machine the value of the (unencoded) operand and set
1154 // the op_index register to 0. This is the only extended opcode that
1155 // takes an argument that is not a variable length number.
1156 // The motivation for DW_LNS_fixed_advance_pc is this: existing
1157 // assemblers cannot emit DW_LNS_advance_pc or special opcodes because
1158 // they cannot encode LEB128 numbers or judge when the computation
1159 // of a special opcode overflows and requires the use of
1160 // DW_LNS_advance_pc. Such assemblers, however, can use
1161 // DW_LNS_fixed_advance_pc instead, sacrificing compression.
1162 {
1163 uint16_t PCOffset = TableData.getRelocatedValue(Cursor, 2);
1164 if (Cursor) {
1165 State.Row.Address.Address += PCOffset;
1166 State.Row.OpIndex = 0;
1167 if (Verbose)
1168 *OS << format(" (addr += 0x%4.4" PRIx16 ", op-index = 0)",
1169 PCOffset);
1170 }
1171 }
1172 break;
1173
1174 case DW_LNS_set_prologue_end:
1175 // Takes no arguments. Set the prologue_end register of the
1176 // state machine to true
1177 State.Row.PrologueEnd = true;
1178 break;
1179
1180 case DW_LNS_set_epilogue_begin:
1181 // Takes no arguments. Set the basic_block register of the
1182 // state machine to true
1183 State.Row.EpilogueBegin = true;
1184 break;
1185
1186 case DW_LNS_set_isa:
1187 // Takes a single unsigned LEB128 operand and stores it in the
1188 // ISA register of the state machine.
1189 if (std::optional<uint8_t> Isa =
1190 parseULEB128<uint8_t>(TableData, Cursor)) {
1191 State.Row.Isa = *Isa;
1192 if (Verbose)
1193 *OS << " (" << (uint64_t)State.Row.Isa << ")";
1194 }
1195 break;
1196
1197 default:
1198 // Handle any unknown standard opcodes here. We know the lengths
1199 // of such opcodes because they are specified in the prologue
1200 // as a multiple of LEB128 operands for each opcode.
1201 {
1202 assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size());
1203 if (Verbose)
1204 *OS << "Unrecognized standard opcode";
1205 uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1];
1206 std::vector<uint64_t> Operands;
1207 for (uint8_t I = 0; I < OpcodeLength; ++I) {
1208 if (std::optional<uint64_t> Value =
1209 parseULEB128<uint64_t>(TableData, Cursor))
1210 Operands.push_back(*Value);
1211 else
1212 break;
1213 }
1214 if (Verbose && !Operands.empty()) {
1215 *OS << " (operands: ";
1216 bool First = true;
1217 for (uint64_t Value : Operands) {
1218 if (!First)
1219 *OS << ", ";
1220 First = false;
1221 *OS << format("0x%16.16" PRIx64, Value);
1222 }
1223 if (Verbose)
1224 *OS << ')';
1225 }
1226 }
1227 break;
1228 }
1229
1230 *OffsetPtr = Cursor.tell();
1231 } else {
1232 // Special Opcodes.
1234 State.handleSpecialOpcode(Opcode, OpcodeOffset);
1235
1236 if (Verbose)
1237 *OS << "address += " << Delta.Address << ", line += " << Delta.Line
1238 << ", op-index += " << Delta.OpIndex;
1239 EmitRow();
1240 *OffsetPtr = Cursor.tell();
1241 }
1242
1243 // When a row is added to the matrix, it is also dumped, which includes a
1244 // new line already, so don't add an extra one.
1245 if (Verbose && Rows.size() == RowCount)
1246 *OS << "\n";
1247
1248 // Most parse failures other than when parsing extended opcodes are due to
1249 // failures to read ULEBs. Bail out of parsing, since we don't know where to
1250 // continue reading from as there is no stated length for such byte
1251 // sequences. Print the final trailing new line if needed before doing so.
1252 if (!Cursor && Opcode != 0) {
1253 if (Verbose)
1254 *OS << "\n";
1255 return Cursor.takeError();
1256 }
1257
1258 if (!Cursor)
1259 RecoverableErrorHandler(Cursor.takeError());
1260 }
1261
1262 if (!State.Sequence.Empty)
1263 RecoverableErrorHandler(createStringError(
1265 "last sequence in debug line table at offset 0x%8.8" PRIx64
1266 " is not terminated",
1267 DebugLineOffset));
1268
1269 // Sort all sequences so that address lookup will work faster.
1270 if (!Sequences.empty()) {
1272 // Note: actually, instruction address ranges of sequences should not
1273 // overlap (in shared objects and executables). If they do, the address
1274 // lookup would still work, though, but result would be ambiguous.
1275 // We don't report warning in this case. For example,
1276 // sometimes .so compiled from multiple object files contains a few
1277 // rudimentary sequences for address ranges [0x0, 0xsomething).
1278 }
1279
1280 // Terminate the table with a final blank line to clearly delineate it from
1281 // later dumps.
1282 if (OS)
1283 *OS << "\n";
1284
1285 return Error::success();
1286}
1287
1288uint32_t DWARFDebugLine::LineTable::findRowInSeq(
1289 const DWARFDebugLine::Sequence &Seq,
1291 if (!Seq.containsPC(Address))
1292 return UnknownRowIndex;
1293 assert(Seq.SectionIndex == Address.SectionIndex);
1294 // In some cases, e.g. first instruction in a function, the compiler generates
1295 // two entries, both with the same address. We want the last one.
1296 //
1297 // In general we want a non-empty range: the last row whose address is less
1298 // than or equal to Address. This can be computed as upper_bound - 1.
1299 //
1300 // TODO: This function, and its users, needs to be update to return multiple
1301 // rows for bundles with multiple op-indexes.
1304 RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex;
1305 RowIter LastRow = Rows.begin() + Seq.LastRowIndex;
1306 assert(FirstRow->Address.Address <= Row.Address.Address &&
1307 Row.Address.Address < LastRow[-1].Address.Address);
1308 RowIter RowPos = std::upper_bound(FirstRow + 1, LastRow - 1, Row,
1310 1;
1311 assert(Seq.SectionIndex == RowPos->Address.SectionIndex);
1312 return RowPos - Rows.begin();
1313}
1314
1317 bool *IsApproximateLine) const {
1318
1319 // Search for relocatable addresses
1320 uint32_t Result = lookupAddressImpl(Address, IsApproximateLine);
1321
1322 if (Result != UnknownRowIndex ||
1324 return Result;
1325
1326 // Search for absolute addresses
1328 return lookupAddressImpl(Address, IsApproximateLine);
1329}
1330
1332DWARFDebugLine::LineTable::lookupAddressImpl(object::SectionedAddress Address,
1333 bool *IsApproximateLine) const {
1334 assert((!IsApproximateLine || !*IsApproximateLine) &&
1335 "Make sure IsApproximateLine is appropriately "
1336 "initialized, if provided");
1337 // First, find an instruction sequence containing the given address.
1339 Sequence.SectionIndex = Address.SectionIndex;
1340 Sequence.HighPC = Address.Address;
1341 SequenceIter It = llvm::upper_bound(Sequences, Sequence,
1343 if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex)
1344 return UnknownRowIndex;
1345
1346 uint32_t RowIndex = findRowInSeq(*It, Address);
1347 if (RowIndex == UnknownRowIndex || !IsApproximateLine)
1348 return RowIndex;
1349
1350 // Approximation will only be attempted if a valid RowIndex exists.
1351 uint32_t ApproxRowIndex = RowIndex;
1352 // Approximation Loop
1353 for (; ApproxRowIndex >= It->FirstRowIndex; --ApproxRowIndex) {
1354 if (Rows[ApproxRowIndex].Line)
1355 return ApproxRowIndex;
1356 *IsApproximateLine = true;
1357 }
1358 // Approximation Loop fails to find the valid ApproxRowIndex
1359 if (ApproxRowIndex < It->FirstRowIndex)
1360 *IsApproximateLine = false;
1361
1362 return RowIndex;
1363}
1364
1367 std::vector<uint32_t> &Result) const {
1368
1369 // Search for relocatable addresses
1370 if (lookupAddressRangeImpl(Address, Size, Result))
1371 return true;
1372
1374 return false;
1375
1376 // Search for absolute addresses
1378 return lookupAddressRangeImpl(Address, Size, Result);
1379}
1380
1381bool DWARFDebugLine::LineTable::lookupAddressRangeImpl(
1383 std::vector<uint32_t> &Result) const {
1384 if (Sequences.empty())
1385 return false;
1386 uint64_t EndAddr = Address.Address + Size;
1387 // First, find an instruction sequence containing the given address.
1389 Sequence.SectionIndex = Address.SectionIndex;
1390 Sequence.HighPC = Address.Address;
1391 SequenceIter LastSeq = Sequences.end();
1392 SequenceIter SeqPos = llvm::upper_bound(
1394 if (SeqPos == LastSeq || !SeqPos->containsPC(Address))
1395 return false;
1396
1397 SequenceIter StartPos = SeqPos;
1398
1399 // Add the rows from the first sequence to the vector, starting with the
1400 // index we just calculated
1401
1402 while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) {
1403 const DWARFDebugLine::Sequence &CurSeq = *SeqPos;
1404 // For the first sequence, we need to find which row in the sequence is the
1405 // first in our range.
1406 uint32_t FirstRowIndex = CurSeq.FirstRowIndex;
1407 if (SeqPos == StartPos)
1408 FirstRowIndex = findRowInSeq(CurSeq, Address);
1409
1410 // Figure out the last row in the range.
1411 uint32_t LastRowIndex =
1412 findRowInSeq(CurSeq, {EndAddr - 1, Address.SectionIndex});
1413 if (LastRowIndex == UnknownRowIndex)
1414 LastRowIndex = CurSeq.LastRowIndex - 1;
1415
1416 assert(FirstRowIndex != UnknownRowIndex);
1417 assert(LastRowIndex != UnknownRowIndex);
1418
1419 for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) {
1420 Result.push_back(I);
1421 }
1422
1423 ++SeqPos;
1424 }
1425
1426 return true;
1427}
1428
1429std::optional<StringRef>
1430DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex,
1431 FileLineInfoKind Kind) const {
1432 if (Kind == FileLineInfoKind::None || !Prologue.hasFileAtIndex(FileIndex))
1433 return std::nullopt;
1434 const FileNameEntry &Entry = Prologue.getFileNameEntry(FileIndex);
1435 if (auto E = dwarf::toString(Entry.Source))
1436 return StringRef(*E);
1437 return std::nullopt;
1438}
1439
1440static bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path) {
1441 // Debug info can contain paths from any OS, not necessarily
1442 // an OS we're currently running on. Moreover different compilation units can
1443 // be compiled on different operating systems and linked together later.
1446}
1447
1449 uint64_t FileIndex, StringRef CompDir, FileLineInfoKind Kind,
1450 std::string &Result, sys::path::Style Style) const {
1451 if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex))
1452 return false;
1453 const FileNameEntry &Entry = getFileNameEntry(FileIndex);
1454 auto E = dwarf::toString(Entry.Name);
1455 if (!E)
1456 return false;
1457 StringRef FileName = *E;
1458 if (Kind == FileLineInfoKind::RawValue ||
1460 Result = std::string(FileName);
1461 return true;
1462 }
1463 if (Kind == FileLineInfoKind::BaseNameOnly) {
1464 Result = std::string(llvm::sys::path::filename(FileName));
1465 return true;
1466 }
1467
1468 SmallString<16> FilePath;
1469 StringRef IncludeDir;
1470 // Be defensive about the contents of Entry.
1471 if (getVersion() >= 5) {
1472 // DirIdx 0 is the compilation directory, so don't include it for
1473 // relative names.
1474 if ((Entry.DirIdx != 0 || Kind != FileLineInfoKind::RelativeFilePath) &&
1475 Entry.DirIdx < IncludeDirectories.size())
1476 IncludeDir = dwarf::toStringRef(IncludeDirectories[Entry.DirIdx]);
1477 } else {
1478 if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size())
1479 IncludeDir = dwarf::toStringRef(IncludeDirectories[Entry.DirIdx - 1]);
1480 }
1481
1482 // For absolute paths only, include the compilation directory of compile unit,
1483 // unless v5 DirIdx == 0 (IncludeDir indicates the compilation directory). We
1484 // know that FileName is not absolute, the only way to have an absolute path
1485 // at this point would be if IncludeDir is absolute.
1486 if (Kind == FileLineInfoKind::AbsoluteFilePath &&
1487 (getVersion() < 5 || Entry.DirIdx != 0) && !CompDir.empty() &&
1488 !isPathAbsoluteOnWindowsOrPosix(IncludeDir))
1489 sys::path::append(FilePath, Style, CompDir);
1490
1491 assert((Kind == FileLineInfoKind::AbsoluteFilePath ||
1492 Kind == FileLineInfoKind::RelativeFilePath) &&
1493 "invalid FileLineInfo Kind");
1494
1495 // sys::path::append skips empty strings.
1496 sys::path::append(FilePath, Style, IncludeDir, FileName);
1497 Result = std::string(FilePath);
1498 return true;
1499}
1500
1502 object::SectionedAddress Address, bool Approximate, const char *CompDir,
1503 FileLineInfoKind Kind, DILineInfo &Result) const {
1504 // Get the index of row we're looking for in the line table.
1505 uint32_t RowIndex =
1506 lookupAddress(Address, Approximate ? &Result.IsApproximateLine : nullptr);
1507 if (RowIndex == -1U)
1508 return false;
1509 // Take file number and line/column from the row.
1510 const auto &Row = Rows[RowIndex];
1511 if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
1512 return false;
1513 Result.Line = Row.Line;
1514 Result.Column = Row.Column;
1515 Result.Discriminator = Row.Discriminator;
1516 Result.Source = getSourceByIndex(Row.File, Kind);
1517 return true;
1518}
1519
1521 const FileNameEntry &Entry, std::string &Directory) const {
1522 if (Prologue.getVersion() >= 5) {
1523 if (Entry.DirIdx < Prologue.IncludeDirectories.size()) {
1524 Directory =
1525 dwarf::toString(Prologue.IncludeDirectories[Entry.DirIdx], "");
1526 return true;
1527 }
1528 return false;
1529 }
1530 if (0 < Entry.DirIdx && Entry.DirIdx <= Prologue.IncludeDirectories.size()) {
1531 Directory =
1532 dwarf::toString(Prologue.IncludeDirectories[Entry.DirIdx - 1], "");
1533 return true;
1534 }
1535 return false;
1536}
1537
1538// We want to supply the Unit associated with a .debug_line[.dwo] table when
1539// we dump it, if possible, but still dump the table even if there isn't a Unit.
1540// Therefore, collect up handles on all the Units that point into the
1541// line-table section.
1545 for (const auto &U : Units)
1546 if (auto CUDIE = U->getUnitDIE())
1547 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
1548 LineToUnit.insert(std::make_pair(*StmtOffset, &*U));
1549 return LineToUnit;
1550}
1551
1555 : DebugLineData(Data), Context(C) {
1556 LineToUnit = buildLineToUnitMap(Units);
1557 if (!DebugLineData.isValidOffset(Offset))
1558 Done = true;
1559}
1560
1562 return TotalLength != 0u;
1563}
1564
1566 function_ref<void(Error)> RecoverableErrorHandler,
1567 function_ref<void(Error)> UnrecoverableErrorHandler, raw_ostream *OS,
1568 bool Verbose) {
1569 assert(DebugLineData.isValidOffset(Offset) &&
1570 "parsing should have terminated");
1571 DWARFUnit *U = prepareToParse(Offset);
1572 uint64_t OldOffset = Offset;
1573 LineTable LT;
1574 if (Error Err = LT.parse(DebugLineData, &Offset, Context, U,
1575 RecoverableErrorHandler, OS, Verbose))
1576 UnrecoverableErrorHandler(std::move(Err));
1577 moveToNextTable(OldOffset, LT.Prologue);
1578 return LT;
1579}
1580
1582 function_ref<void(Error)> RecoverableErrorHandler,
1583 function_ref<void(Error)> UnrecoverableErrorHandler) {
1584 assert(DebugLineData.isValidOffset(Offset) &&
1585 "parsing should have terminated");
1586 DWARFUnit *U = prepareToParse(Offset);
1587 uint64_t OldOffset = Offset;
1588 LineTable LT;
1589 if (Error Err = LT.Prologue.parse(DebugLineData, &Offset,
1590 RecoverableErrorHandler, Context, U))
1591 UnrecoverableErrorHandler(std::move(Err));
1592 moveToNextTable(OldOffset, LT.Prologue);
1593}
1594
1595DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) {
1596 DWARFUnit *U = nullptr;
1597 auto It = LineToUnit.find(Offset);
1598 if (It != LineToUnit.end())
1599 U = It->second;
1600 DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0);
1601 return U;
1602}
1603
1604bool DWARFDebugLine::SectionParser::hasValidVersion(uint64_t Offset) {
1606 auto [TotalLength, _] = DebugLineData.getInitialLength(Cursor);
1607 DWARFDataExtractor HeaderData(DebugLineData, Cursor.tell() + TotalLength);
1608 uint16_t Version = HeaderData.getU16(Cursor);
1609 if (!Cursor) {
1610 // Ignore any error here.
1611 // If this is not the end of the section parseNext() will still be
1612 // attempted, where this error will occur again (and can be handled).
1613 consumeError(Cursor.takeError());
1614 return false;
1615 }
1617}
1618
1619void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset,
1620 const Prologue &P) {
1621 // If the length field is not valid, we don't know where the next table is, so
1622 // cannot continue to parse. Mark the parser as done, and leave the Offset
1623 // value as it currently is. This will be the end of the bad length field.
1624 if (!P.totalLengthIsValid()) {
1625 Done = true;
1626 return;
1627 }
1628
1629 Offset = OldOffset + P.TotalLength + P.sizeofTotalLength();
1630 if (!DebugLineData.isValidOffset(Offset)) {
1631 Done = true;
1632 return;
1633 }
1634
1635 // Heuristic: If the version is valid, then this is probably a line table.
1636 // Otherwise, the offset might need alignment (to a 4 or 8 byte boundary).
1637 if (hasValidVersion(Offset))
1638 return;
1639
1640 // ARM C/C++ Compiler aligns each line table to word boundaries and pads out
1641 // the .debug_line section to a word multiple. Note that in the specification
1642 // this does not seem forbidden since each unit has a DW_AT_stmt_list.
1643 for (unsigned Align : {4, 8}) {
1644 uint64_t AlignedOffset = alignTo(Offset, Align);
1645 if (!DebugLineData.isValidOffset(AlignedOffset)) {
1646 // This is almost certainly not another line table but some alignment
1647 // padding. This assumes the alignments tested are ordered, and are
1648 // smaller than the header size (which is true for 4 and 8).
1649 Done = true;
1650 return;
1651 }
1652 if (hasValidVersion(AlignedOffset)) {
1653 Offset = AlignedOffset;
1654 break;
1655 }
1656 }
1657}
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:148
static Error parseV5DirFileTables(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, const dwarf::FormParams &FormParams, const DWARFContext &Ctx, const DWARFUnit *U, DWARFDebugLine::ContentTypeTracker &ContentTypes, std::vector< DWARFFormValue > &IncludeDirectories, std::vector< DWARFDebugLine::FileNameEntry > &FileNames)
static Error parseV2DirFileTables(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, DWARFDebugLine::ContentTypeTracker &ContentTypes, std::vector< DWARFFormValue > &IncludeDirectories, std::vector< DWARFDebugLine::FileNameEntry > &FileNames)
static llvm::Expected< ContentDescriptors > parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, DWARFDebugLine::ContentTypeTracker *ContentTypes)
static DWARFDebugLine::SectionParser::LineToUnitMap buildLineToUnitMap(DWARFUnitVector::iterator_range Units)
static bool versionIsSupported(uint16_t Version)
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
static std::optional< T > parseULEB128(DWARFDataExtractor &Data, DataExtractor::Cursor &Cursor)
Parse a ULEB128 using the specified Cursor.
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
static fatal_error_handler_t ErrorHandler
#define _
@ EndSequence
End of the line table.
Definition: LineTable.cpp:17
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned OpIndex
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Definition: DWARFContext.h:48
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
uint64_t getRelocatedAddress(uint64_t *Off, uint64_t *SecIx=nullptr) const
Extracts an address-sized value and applies a relocation to the result if one exists for the given of...
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...
uint64_t getRelocatedValue(uint32_t Size, uint64_t *Off, uint64_t *SectionIndex=nullptr, Error *Err=nullptr) const
Extracts a value and applies a relocation to the result if one exists for the given offset.
void skip(function_ref< void(Error)> RecoverableErrorHandler, function_ref< void(Error)> UnrecoverableErrorHandler)
Skip the current line table and go to the following line table (if present) immediately.
std::map< uint64_t, DWARFUnit * > LineToUnitMap
LineTable parseNext(function_ref< void(Error)> RecoverableErrorHandler, function_ref< void(Error)> UnrecoverableErrorHandler, raw_ostream *OS=nullptr, bool Verbose=false)
Get the next line table from the section.
SectionParser(DWARFDataExtractor &Data, const DWARFContext &C, DWARFUnitVector::iterator_range Units)
void clearLineTable(uint64_t Offset)
Expected< const LineTable * > getOrParseLineTable(DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx, const DWARFUnit *U, function_ref< void(Error)> RecoverableErrorHandler)
const LineTable * getLineTable(uint64_t Offset) const
void dumpAddress(raw_ostream &OS, uint64_t Address) const
static DWARFFormValue createFromPValue(dwarf::Form F, const char *V)
void dump(raw_ostream &OS, DIDumpOptions DumpOpts=DIDumpOptions()) const
Expected< const char * > getAsCString() const
A class representing a position in a DataExtractor, as well as any error encountered during extractio...
Definition: DataExtractor.h:54
uint64_t tell() const
Return the current position of this Cursor.
Definition: DataExtractor.h:71
Error takeError()
Return error contained inside this Cursor, if any.
Definition: DataExtractor.h:78
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.
StringRef getCStrRef(uint64_t *OffsetPtr, Error *Err=nullptr) const
Extract a C string from *offset_ptr.
uint8_t getU8(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint8_t value from *offset_ptr.
uint64_t getULEB128(uint64_t *offset_ptr, llvm::Error *Err=nullptr) const
Extract a unsigned LEB128 value from *offset_ptr.
uint8_t getAddressSize() const
Get the address size for this extractor.
Definition: DataExtractor.h:99
int64_t getSLEB128(uint64_t *OffsetPtr, Error *Err=nullptr) const
Extract a signed LEB128 value from *offset_ptr.
uint16_t getU16(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint16_t value from *offset_ptr.
void skip(Cursor &C, uint64_t Length) const
Advance the Cursor position by the given number of bytes.
void setAddressSize(uint8_t Size)
Set the address size for this extractor.
bool isValidOffset(uint64_t offset) const
Test the validity of offset.
bool isValidOffsetForDataOfSize(uint64_t offset, uint64_t length) const
Test the availability of length bytes of data from offset.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
StringRef LNExtendedString(unsigned Encoding)
Definition: Dwarf.cpp:523
StringRef FormatString(DwarfFormat Format)
Definition: Dwarf.cpp:868
StringRef LNStandardString(unsigned Standard)
Definition: Dwarf.cpp:512
@ Entry
Definition: COFF.h:826
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path)
Definition: Utils.h:98
LineNumberEntryFormat
Definition: Dwarf.h:780
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
LineNumberOps
Line Number Standard Opcode Encodings.
Definition: Dwarf.h:767
@ DWARF32
Definition: Dwarf.h:91
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
uint8_t getDwarfOffsetByteSize(DwarfFormat Format)
The size of a reference determined by the DWARF 32/64-bit format.
Definition: Dwarf.h:1064
uint64_t computeTombstoneAddress(uint8_t AddressByteSize)
Definition: Dwarf.h:1205
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
Definition: PtrState.h:41
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition: Path.cpp:672
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
@ Length
Definition: DWP.cpp:480
@ Done
Definition: Threading.h:61
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1974
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
@ illegal_byte_sequence
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:438
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Container for dump options that control which debug information will be dumped.
Definition: DIContext.h:196
A format-neutral container for source line information.
Definition: DIContext.h:32
Tracks which optional content types are present in a DWARF file name entry format.
bool HasLength
Whether filename entries provide a file size.
bool HasSource
For v5, whether filename entries provide source text.
bool HasModTime
Whether filename entries provide a modification timestamp.
bool HasMD5
For v5, whether filename entries provide an MD5 checksum.
void trackContentType(dwarf::LineNumberEntryFormat ContentType)
Update tracked content types with ContentType.
uint32_t lookupAddress(object::SectionedAddress Address, bool *IsApproximateLine=nullptr) const
Returns the index of the row with file/line info for a given address, or UnknownRowIndex if there is ...
bool getDirectoryForEntry(const FileNameEntry &Entry, std::string &Directory) const
Extracts directory name by its Entry in include directories table in prologue.
bool getFileLineInfoForAddress(object::SectionedAddress Address, bool Approximate, const char *CompDir, DILineInfoSpecifier::FileLineInfoKind Kind, DILineInfo &Result) const
Fills the Result argument with the file and line information corresponding to Address.
Error parse(DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, const DWARFContext &Ctx, const DWARFUnit *U, function_ref< void(Error)> RecoverableErrorHandler, raw_ostream *OS=nullptr, bool Verbose=false)
Parse prologue and all rows.
bool lookupAddressRange(object::SectionedAddress Address, uint64_t Size, std::vector< uint32_t > &Result) const
void dump(raw_ostream &OS, DIDumpOptions DumpOptions) const
bool hasFileAtIndex(uint64_t FileIndex) const
void dump(raw_ostream &OS, DIDumpOptions DumpOptions) const
uint32_t sizeofTotalLength() const
std::optional< uint64_t > getLastValidFileIndex() const
Error parse(DWARFDataExtractor Data, uint64_t *OffsetPtr, function_ref< void(Error)> RecoverableErrorHandler, const DWARFContext &Ctx, const DWARFUnit *U=nullptr)
std::vector< DWARFFormValue > IncludeDirectories
uint8_t OpcodeBase
The number assigned to the first special opcode.
std::vector< uint8_t > StandardOpcodeLengths
const llvm::DWARFDebugLine::FileNameEntry & getFileNameEntry(uint64_t Index) const
Get DWARF-version aware access to the file name entry at the provided index.
bool getFileNameByIndex(uint64_t FileIndex, StringRef CompDir, DILineInfoSpecifier::FileLineInfoKind Kind, std::string &Result, sys::path::Style Style=sys::path::Style::native) const
uint64_t TotalLength
The size in bytes of the statement information for this compilation unit (not including the total_len...
uint64_t getLength() const
Length of the prologue in bytes.
std::vector< FileNameEntry > FileNames
Standard .debug_line state machine structure.
static bool orderByAddress(const Row &LHS, const Row &RHS)
uint32_t Line
An unsigned integer indicating a source line number.
uint16_t File
An unsigned integer indicating the identity of the source file corresponding to a machine instruction...
uint32_t Discriminator
An unsigned integer representing the DWARF path discriminator value for this location.
object::SectionedAddress Address
The program-counter value corresponding to a machine instruction generated by the compiler and sectio...
void postAppend()
Called after a row is appended to the matrix.
uint16_t Column
An unsigned integer indicating a column number within a source line.
static void dumpTableHeader(raw_ostream &OS, unsigned Indent)
void reset(bool DefaultIsStmt)
Row(bool DefaultIsStmt=false)
void dump(raw_ostream &OS) const
Represents a series of contiguous machine instructions.
static bool orderByHighPC(const Sequence &LHS, const Sequence &RHS)
bool containsPC(object::SectionedAddress PC) const
uint64_t SectionIndex
If relocation information is present then this is the index of the section which contains above addre...
SmallString< 32 > digest() const
Definition: MD5.cpp:281
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition: Dwarf.h:1077
DwarfFormat Format
Definition: Dwarf.h:1080
static const uint64_t UndefSection
Definition: ObjectFile.h:146