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