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
9#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
10#include "llvm/ADT/SmallString.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/ADT/StringExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/BinaryFormat/Dwarf.h"
15#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
16#include "llvm/DebugInfo/DWARF/DWARFDie.h"
17#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
18#include "llvm/Support/Errc.h"
19#include "llvm/Support/Format.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/raw_ostream.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 {
37 dwarf::LineNumberEntryFormat Type;
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
49void DWARFDebugLine::ContentTypeTracker::trackContentType(
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
71DWARFDebugLine::Prologue::Prologue() { clear(); }
72
73bool DWARFDebugLine::Prologue::hasFileAtIndex(uint64_t FileIndex) const {
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>
83DWARFDebugLine::Prologue::getLastValidFileIndex() const {
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
95const llvm::DWARFDebugLine::FileNameEntry &
96DWARFDebugLine::Prologue::getFileNameEntry(uint64_t Index) const {
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
106void DWARFDebugLine::Prologue::clear() {
107 TotalLength = PrologueLength = 0;
108 SegSelectorSize = 0;
109 MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
110 OpcodeBase = 0;
111 FormParams = dwarf::FormParams({.Version: 0, .AddrSize: 0, .Format: DWARF32});
112 ContentTypes = ContentTypeTracker();
113 StandardOpcodeLengths.clear();
114 IncludeDirectories.clear();
115 FileNames.clear();
116}
117
118void DWARFDebugLine::Prologue::dump(raw_ostream &OS,
119 DIDumpOptions DumpOptions) const {
120 if (!totalLengthIsValid())
121 return;
122 int OffsetDumpWidth = 2 * dwarf::getDwarfOffsetByteSize(Format: FormParams.Format);
123 OS << "Line table prologue:\n"
124 << format(Fmt: " total_length: 0x%0*" PRIx64 "\n", Vals: OffsetDumpWidth,
125 Vals: TotalLength)
126 << " format: " << dwarf::FormatString(Format: FormParams.Format) << "\n"
127 << format(Fmt: " version: %u\n", Vals: getVersion());
128 if (!versionIsSupported(Version: getVersion()))
129 return;
130 if (getVersion() >= 5)
131 OS << format(Fmt: " address_size: %u\n", Vals: getAddressSize())
132 << format(Fmt: " seg_select_size: %u\n", Vals: SegSelectorSize);
133 OS << format(Fmt: " prologue_length: 0x%0*" PRIx64 "\n", Vals: OffsetDumpWidth,
134 Vals: PrologueLength)
135 << format(Fmt: " min_inst_length: %u\n", Vals: MinInstLength)
136 << format(Fmt: getVersion() >= 4 ? "max_ops_per_inst: %u\n" : "", Vals: MaxOpsPerInst)
137 << format(Fmt: " default_is_stmt: %u\n", Vals: DefaultIsStmt)
138 << format(Fmt: " line_base: %i\n", Vals: LineBase)
139 << format(Fmt: " line_range: %u\n", Vals: LineRange)
140 << format(Fmt: " opcode_base: %u\n", Vals: OpcodeBase);
141
142 for (uint32_t I = 0; I != StandardOpcodeLengths.size(); ++I)
143 OS << formatv(Fmt: "standard_opcode_lengths[{0}] = {1}\n",
144 Vals: static_cast<dwarf::LineNumberOps>(I + 1),
145 Vals: StandardOpcodeLengths[I]);
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(Fmt: "include_directories[%3u] = ", Vals: I + DirBase);
152 IncludeDirectories[I].dump(OS, DumpOpts: 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(Fmt: "file_names[%3u]:\n", Vals: I + FileBase);
163 OS << " name: ";
164 FileEntry.Name.dump(OS, DumpOpts: DumpOptions);
165 OS << '\n' << format(Fmt: " dir_index: %" PRIu64 "\n", Vals: FileEntry.DirIdx);
166 if (ContentTypes.HasMD5)
167 OS << " md5_checksum: " << FileEntry.Checksum.digest() << '\n';
168 if (ContentTypes.HasModTime)
169 OS << format(Fmt: " mod_time: 0x%8.8" PRIx64 "\n", Vals: FileEntry.ModTime);
170 if (ContentTypes.HasLength)
171 OS << format(Fmt: " length: 0x%8.8" PRIx64 "\n", Vals: FileEntry.Length);
172 if (ContentTypes.HasSource) {
173 auto Source = FileEntry.Source.getAsCString();
174 if (!Source)
175 consumeError(Err: Source.takeError());
176 else if ((*Source)[0]) {
177 OS << " source: ";
178 FileEntry.Source.dump(OS, DumpOpts: DumpOptions);
179 OS << '\n';
180 }
181 }
182 }
183 }
184}
185
186// Parse v2-v4 directory and file tables.
187static Error
188parseV2DirFileTables(const DWARFDataExtractor &DebugLineData,
189 uint64_t *OffsetPtr,
190 DWARFDebugLine::ContentTypeTracker &ContentTypes,
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: &Err);
196 if (Err) {
197 consumeError(Err: std::move(Err));
198 return createStringError(EC: errc::invalid_argument,
199 S: "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(F: dwarf::DW_FORM_string, V: S.data());
206 IncludeDirectories.push_back(x: 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: &Err);
215 if (!Err && Name.empty())
216 break;
217
218 DWARFDebugLine::FileNameEntry FileEntry;
219 FileEntry.Name =
220 DWARFFormValue::createFromPValue(F: dwarf::DW_FORM_string, V: Name.data());
221 FileEntry.DirIdx = DebugLineData.getULEB128(offset_ptr: OffsetPtr, Err: &Err);
222 FileEntry.ModTime = DebugLineData.getULEB128(offset_ptr: OffsetPtr, Err: &Err);
223 FileEntry.Length = DebugLineData.getULEB128(offset_ptr: OffsetPtr, Err: &Err);
224
225 if (Err) {
226 consumeError(Err: std::move(Err));
227 return createStringError(
228 EC: errc::invalid_argument,
229 S: "file names table was not null terminated before "
230 "the end of the prologue");
231 }
232 FileNames.push_back(x: 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,
243 DWARFDebugLine::ContentTypeTracker *ContentTypes) {
244 Error Err = Error::success();
245 ContentDescriptors Descriptors;
246 int FormatCount = DebugLineData.getU8(offset_ptr: OffsetPtr, Err: &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(offset_ptr: OffsetPtr, Err: &Err));
252 Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(offset_ptr: OffsetPtr, Err: &Err));
253 if (Descriptor.Type == dwarf::DW_LNCT_path)
254 HasPath = true;
255 if (ContentTypes)
256 ContentTypes->trackContentType(ContentType: Descriptor.Type);
257 Descriptors.push_back(Elt: Descriptor);
258 }
259
260 if (Err)
261 return createStringError(EC: errc::invalid_argument,
262 Fmt: "failed to parse entry content descriptors: %s",
263 Vals: toString(E: std::move(Err)).c_str());
264
265 if (!HasPath)
266 return createStringError(EC: errc::invalid_argument,
267 S: "failed to parse entry content descriptions"
268 " because no path was found");
269 return Descriptors;
270}
271
272static Error
273parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
274 uint64_t *OffsetPtr, const dwarf::FormParams &FormParams,
275 const DWARFContext &Ctx, const DWARFUnit *U,
276 DWARFDebugLine::ContentTypeTracker &ContentTypes,
277 std::vector<DWARFFormValue> &IncludeDirectories,
278 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
279 // Get the directory entry description.
280 llvm::Expected<ContentDescriptors> DirDescriptors =
281 parseV5EntryFormat(DebugLineData, OffsetPtr, ContentTypes: 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(offset_ptr: 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(Data: DebugLineData, OffsetPtr, FormParams, Context: &Ctx, Unit: U))
293 return createStringError(EC: errc::invalid_argument,
294 S: "failed to parse directory entry because "
295 "extracting the form value failed");
296 IncludeDirectories.push_back(x: Value);
297 break;
298 default:
299 if (!Value.skipValue(DebugInfoData: DebugLineData, OffsetPtr, Params: FormParams))
300 return createStringError(EC: errc::invalid_argument,
301 S: "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: &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(offset_ptr: OffsetPtr);
315 for (uint64_t I = 0; I != FileEntryCount; ++I) {
316 DWARFDebugLine::FileNameEntry FileEntry;
317 for (auto Descriptor : *FileDescriptors) {
318 DWARFFormValue Value(Descriptor.Form);
319 if (!Value.extractValue(Data: DebugLineData, OffsetPtr, FormParams, Context: &Ctx, Unit: U))
320 return createStringError(EC: errc::invalid_argument,
321 S: "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(
342 EC: errc::invalid_argument,
343 S: "failed to parse file entry because the MD5 hash is invalid");
344 llvm::uninitialized_copy(Src: *Value.getAsBlock(),
345 Dst: FileEntry.Checksum.begin());
346 break;
347 default:
348 break;
349 }
350 }
351 FileNames.push_back(x: FileEntry);
352 }
353 return Error::success();
354}
355
356uint64_t DWARFDebugLine::Prologue::getLength() const {
357 uint64_t Length = PrologueLength + sizeofTotalLength() +
358 sizeof(getVersion()) + sizeofPrologueLength();
359 if (getVersion() >= 5)
360 Length += 2; // Address + Segment selector sizes.
361 return Length;
362}
363
364Error DWARFDebugLine::Prologue::parse(
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(args&: TotalLength, args&: FormParams.Format) =
373 DebugLineData.getInitialLength(C&: Cursor);
374
375 DebugLineData =
376 DWARFDataExtractor(DebugLineData, Cursor.tell() + TotalLength);
377 FormParams.Version = DebugLineData.getU16(C&: Cursor);
378 if (Cursor && !versionIsSupported(Version: 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(
384 EC: errc::not_supported,
385 Fmt: "parsing line table prologue at offset 0x%8.8" PRIx64
386 ": unsupported version %" PRIu16,
387 Vals: PrologueOffset, Vals: getVersion());
388 }
389
390 if (getVersion() >= 5) {
391 FormParams.AddrSize = DebugLineData.getU8(C&: 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(
398 EC: errc::not_supported,
399 Fmt: "parsing line table prologue at offset 0x%8.8" PRIx64
400 ": invalid address size %" PRIu8,
401 Vals: PrologueOffset, Vals: PrologueAddrSize));
402 }
403 } else if (DataAddrSize != PrologueAddrSize) {
404 RecoverableErrorHandler(createStringError(
405 EC: errc::not_supported,
406 Fmt: "parsing line table prologue at offset 0x%8.8" PRIx64 ": address "
407 "size %" PRIu8 " doesn't match architecture address size %" PRIu8,
408 Vals: PrologueOffset, Vals: PrologueAddrSize, Vals: DataAddrSize));
409 }
410 }
411 SegSelectorSize = DebugLineData.getU8(C&: Cursor);
412 }
413
414 PrologueLength =
415 DebugLineData.getRelocatedValue(C&: Cursor, Size: sizeofPrologueLength());
416 const uint64_t EndPrologueOffset = PrologueLength + Cursor.tell();
417 DebugLineData = DWARFDataExtractor(DebugLineData, EndPrologueOffset);
418 MinInstLength = DebugLineData.getU8(C&: Cursor);
419 if (getVersion() >= 4)
420 MaxOpsPerInst = DebugLineData.getU8(C&: Cursor);
421 DefaultIsStmt = DebugLineData.getU8(C&: Cursor);
422 LineBase = DebugLineData.getU8(C&: Cursor);
423 LineRange = DebugLineData.getU8(C&: Cursor);
424 OpcodeBase = DebugLineData.getU8(C&: 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(
431 EC: errc::invalid_argument,
432 Fmt: "parsing line table prologue at offset 0x%8.8" PRIx64
433 " found opcode base of 0. Assuming no standard opcodes",
434 Vals: PrologueOffset));
435 } else if (Cursor) {
436 StandardOpcodeLengths.reserve(n: OpcodeBase - 1);
437 for (uint32_t I = 1; I < OpcodeBase; ++I) {
438 uint8_t OpLen = DebugLineData.getU8(C&: Cursor);
439 StandardOpcodeLengths.push_back(x: 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(
449 EC: errc::invalid_argument,
450 Fmt: "parsing line table prologue at offset 0x%8.8" PRIx64 ": %s",
451 Vals: PrologueOffset, Vals: toString(E: Cursor.takeError()).c_str());
452
453 Error E =
454 getVersion() >= 5
455 ? parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U,
456 ContentTypes, IncludeDirectories, FileNames)
457 : parseV2DirFileTables(DebugLineData, OffsetPtr, ContentTypes,
458 IncludeDirectories, FileNames);
459 if (E) {
460 RecoverableErrorHandler(joinErrors(
461 E1: createStringError(
462 EC: errc::invalid_argument,
463 Fmt: "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 Vals: PrologueOffset, Vals: *OffsetPtr),
467 E2: std::move(E)));
468 return Error::success();
469 }
470
471 assert(*OffsetPtr <= EndPrologueOffset);
472 if (*OffsetPtr != EndPrologueOffset) {
473 RecoverableErrorHandler(createStringError(
474 EC: errc::invalid_argument,
475 Fmt: "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 Vals: PrologueOffset, Vals: *OffsetPtr, Vals: EndPrologueOffset));
479 }
480 return Error::success();
481}
482
483DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); }
484
485void DWARFDebugLine::Row::postAppend() {
486 Discriminator = 0;
487 BasicBlock = false;
488 PrologueEnd = false;
489 EpilogueBegin = false;
490}
491
492void DWARFDebugLine::Row::reset(bool DefaultIsStmt) {
493 Address.Address = 0;
494 Address.SectionIndex = object::SectionedAddress::UndefSection;
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
508void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS, unsigned Indent) {
509 OS.indent(NumSpaces: Indent)
510 << "Address Line Column File ISA Discriminator OpIndex "
511 "Flags\n";
512 OS.indent(NumSpaces: Indent)
513 << "------------------ ------ ------ ------ --- ------------- ------- "
514 "-------------\n";
515}
516
517void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
518 OS << format(Fmt: "0x%16.16" PRIx64 " %6u %6u", Vals: Address.Address, Vals: Line, Vals: Column)
519 << format(Fmt: " %6u %3u %13u %7u ", Vals: File, Vals: Isa, Vals: Discriminator, Vals: OpIndex)
520 << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "")
521 << (PrologueEnd ? " prologue_end" : "")
522 << (EpilogueBegin ? " epilogue_begin" : "")
523 << (EndSequence ? " end_sequence" : "") << '\n';
524}
525
526DWARFDebugLine::Sequence::Sequence() { reset(); }
527
528void DWARFDebugLine::Sequence::reset() {
529 LowPC = 0;
530 HighPC = 0;
531 SectionIndex = object::SectionedAddress::UndefSection;
532 FirstRowIndex = 0;
533 LastRowIndex = 0;
534 Empty = true;
535 StmtSeqOffset = UINT64_MAX;
536}
537
538DWARFDebugLine::LineTable::LineTable() { clear(); }
539
540void DWARFDebugLine::LineTable::dump(raw_ostream &OS,
541 DIDumpOptions DumpOptions) const {
542 Prologue.dump(OS, DumpOptions);
543
544 if (!Rows.empty()) {
545 OS << '\n';
546 Row::dumpTableHeader(OS, Indent: 0);
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
557void DWARFDebugLine::LineTable::clear() {
558 Prologue.clear();
559 Rows.clear();
560 Sequences.clear();
561}
562
563DWARFDebugLine::ParsingState::ParsingState(
564 struct LineTable *LT, uint64_t TableOffset,
565 function_ref<void(Error)> ErrorHandler)
566 : LineTable(LT), LineTableOffset(TableOffset), ErrorHandler(ErrorHandler) {}
567
568void DWARFDebugLine::ParsingState::resetRowAndSequence(uint64_t Offset) {
569 Row.reset(DefaultIsStmt: 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 }
582 LineTable->appendRow(R: Row);
583 if (Row.EndSequence) {
584 // Record the end of instruction sequence.
585 Sequence.HighPC = Row.Address.Address;
586 Sequence.LastRowIndex = RowNumber + 1;
587 Sequence.SectionIndex = Row.Address.SectionIndex;
588 if (Sequence.isValid())
589 LineTable->appendSequence(S: Sequence);
590 Sequence.reset();
591 }
592 Row.postAppend();
593}
594
595const DWARFDebugLine::LineTable *
596DWARFDebugLine::getLineTable(uint64_t Offset) const {
597 LineTableConstIter Pos = LineTableMap.find(x: Offset);
598 if (Pos != LineTableMap.end())
599 return &Pos->second;
600 return nullptr;
601}
602
603Expected<const DWARFDebugLine::LineTable *> DWARFDebugLine::getOrParseLineTable(
604 DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx,
605 const DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
606 if (!DebugLineData.isValidOffset(offset: Offset))
607 return createStringError(EC: errc::invalid_argument,
608 Fmt: "offset 0x%8.8" PRIx64
609 " is not a valid debug line section offset",
610 Vals: Offset);
611
612 std::pair<LineTableIter, bool> Pos =
613 LineTableMap.insert(x: LineTableMapTy::value_type(Offset, LineTable()));
614 LineTable *LT = &Pos.first->second;
615 if (Pos.second) {
616 if (Error Err =
617 LT->parse(DebugLineData, OffsetPtr: &Offset, Ctx, U, RecoverableErrorHandler))
618 return std::move(Err);
619 return LT;
620 }
621 return LT;
622}
623
624void DWARFDebugLine::clearLineTable(uint64_t Offset) {
625 LineTableMap.erase(x: Offset);
626}
627
628static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase) {
629 assert(Opcode != 0);
630 if (Opcode < OpcodeBase)
631 return LNStandardString(Standard: 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, OpcodeBase: 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 &&
644 LineTable->Prologue.MaxOpsPerInst == 0)
645 ErrorHandler(createStringError(
646 EC: errc::invalid_argument,
647 Fmt: "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 Vals: LineTableOffset, Vals: OpcodeName.data(), Vals: 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)
658 ErrorHandler(createStringError(
659 EC: errc::not_supported,
660 Fmt: "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 Vals: LineTableOffset, Vals: OpcodeName.data(), Vals: OpcodeOffset,
666 Vals: LineTable->Prologue.MaxOpsPerInst));
667 if (ReportAdvanceAddrProblem && LineTable->Prologue.MinInstLength == 0)
668 ErrorHandler(
669 createStringError(EC: errc::invalid_argument,
670 Fmt: "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 Vals: LineTableOffset, Vals: OpcodeName.data(), Vals: 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(a: LineTable->Prologue.MaxOpsPerInst, b: uint8_t{1});
690
691 uint64_t AddrOffset = ((Row.OpIndex + OperationAdvance) / MaxOpsPerInst) *
692 LineTable->Prologue.MinInstLength;
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: AddrOffset, .OpIndexDelta: 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 =
709 getOpcodeName(Opcode, OpcodeBase: LineTable->Prologue.OpcodeBase);
710 ErrorHandler(
711 createStringError(EC: errc::not_supported,
712 Fmt: "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 Vals: LineTableOffset, Vals: OpcodeName.data(), Vals: 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 =
725 LineTable->Prologue.LineRange != 0
726 ? AdjustedOpcode / LineTable->Prologue.LineRange
727 : 0;
728 AddrOpIndexDelta Advance =
729 advanceAddrOpIndex(OperationAdvance, Opcode, OpcodeOffset);
730 return {.AddrDelta: Advance.AddrOffset, .OpIndexDelta: Advance.OpIndexDelta, .AdjustedOpcode: 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 =
772 LineTable->Prologue.LineBase +
773 (AddrAdvanceResult.AdjustedOpcode % LineTable->Prologue.LineRange);
774 Row.Line += LineOffset;
775 return {.Address: AddrAdvanceResult.AddrDelta, .Line: LineOffset,
776 .OpIndex: 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(C&: Cursor);
785 if (Cursor)
786 return Value;
787 return std::nullopt;
788}
789
790Error DWARFDebugLine::LineTable::parse(
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&: *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(offset: DebugLineOffset,
819 length: ProgramLength)) {
820 assert(DebugLineData.size() > DebugLineOffset &&
821 "prologue parsing should handle invalid offset");
822 uint64_t BytesRemaining = DebugLineData.size() - DebugLineOffset;
823 RecoverableErrorHandler(
824 createStringError(EC: errc::invalid_argument,
825 Fmt: "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 Vals: DebugLineOffset, Vals: ProgramLength, Vals: 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&: *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(Offset: *OffsetPtr);
855
856 bool TombstonedAddress = false;
857 auto EmitRow = [&] {
858 if (!TombstonedAddress) {
859 if (Verbose) {
860 *OS << "\n";
861 OS->indent(NumSpaces: 12);
862 }
863 if (OS)
864 State.Row.dump(OS&: *OS);
865 State.appendRowToMatrix();
866 }
867 };
868 while (*OffsetPtr < EndOffset) {
869 DataExtractor::Cursor Cursor(*OffsetPtr);
870
871 if (Verbose)
872 *OS << format(Fmt: "0x%08.08" PRIx64 ": ", Vals: *OffsetPtr);
873
874 uint64_t OpcodeOffset = *OffsetPtr;
875 uint8_t Opcode = TableData.getU8(C&: Cursor);
876 size_t RowCount = Rows.size();
877
878 if (Cursor && Verbose)
879 *OS << format(Fmt: "%02.02" PRIx8 " ", Vals: 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(C&: 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(C&: 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(Encoding: 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(Offset: 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(
942 EC: errc::invalid_argument,
943 Fmt: "mismatching address size at offset 0x%8.8" PRIx64
944 " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
945 Vals: ExtOffset, Vals: ExtractorAddressSize, Vals: 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(
953 EC: errc::invalid_argument,
954 Fmt: "address size 0x%2.2" PRIx64
955 " of DW_LNE_set_address opcode at offset 0x%8.8" PRIx64
956 " is unsupported",
957 Vals: OpcodeAddressSize, Vals: ExtOffset));
958 TableData.skip(C&: Cursor, Length: OpcodeAddressSize);
959 } else {
960 TableData.setAddressSize(OpcodeAddressSize);
961 State.Row.Address.Address = TableData.getRelocatedAddress(
962 C&: Cursor, SecIx: &State.Row.Address.SectionIndex);
963 State.Row.OpIndex = 0;
964
965 uint64_t Tombstone =
966 dwarf::computeTombstoneAddress(AddressByteSize: 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&: *OS, AddressSize: OpcodeAddressSize,
977 Address: 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(C&: Cursor);
1007 FileEntry.Name =
1008 DWARFFormValue::createFromPValue(F: dwarf::DW_FORM_string, V: Name);
1009 FileEntry.DirIdx = TableData.getULEB128(C&: Cursor);
1010 FileEntry.ModTime = TableData.getULEB128(C&: Cursor);
1011 FileEntry.Length = TableData.getULEB128(C&: Cursor);
1012 Prologue.FileNames.push_back(x: FileEntry);
1013 if (Cursor && Verbose)
1014 *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time="
1015 << format(Fmt: "(0x%16.16" PRIx64 ")", Vals: FileEntry.ModTime)
1016 << ", length=" << FileEntry.Length << ")";
1017 }
1018 break;
1019
1020 case DW_LNE_set_discriminator:
1021 State.Row.Discriminator = TableData.getULEB128(C&: Cursor);
1022 if (Cursor && Verbose)
1023 *OS << " (" << State.Row.Discriminator << ")";
1024 break;
1025
1026 default:
1027 if (Cursor && Verbose)
1028 *OS << format(Fmt: "Unrecognized extended op 0x%02.02" PRIx8, Vals: SubOpcode)
1029 << format(Fmt: " length %" PRIx64, Vals: 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(C&: Cursor, Length: 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(
1042 EC: errc::illegal_byte_sequence,
1043 Fmt: "unexpected line op length at offset 0x%8.8" PRIx64
1044 " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64,
1045 Vals: ExtOffset, Vals: Len, Vals: Cursor.tell() - ExtOffset));
1046 if (!Cursor && Verbose) {
1047 DWARFDataExtractor::Cursor ByteCursor(OperandOffset);
1048 uint8_t Byte = TableData.getU8(C&: ByteCursor);
1049 if (ByteCursor) {
1050 *OS << " (<parsing error>";
1051 do {
1052 *OS << format(Fmt: " %2.2" PRIx8, Vals: Byte);
1053 Byte = TableData.getU8(C&: 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(Err: ByteCursor.takeError());
1062 }
1063 *OffsetPtr = End;
1064 } else if (Opcode < Prologue.OpcodeBase) {
1065 if (Verbose)
1066 *OS << LNStandardString(Standard: 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>(Data&: TableData, Cursor)) {
1081 ParsingState::AddrOpIndexDelta Advance =
1082 State.advanceAddrOpIndex(OperationAdvance: *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(C&: 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>(Data&: 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>(Data&: 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 {
1149 ParsingState::OpcodeAdvanceResults Advance =
1150 State.advanceForOpcode(Opcode, OpcodeOffset);
1151 if (Verbose)
1152 *OS << format(Fmt: " (addr += 0x%16.16" PRIx64 ", op-index += %" PRIu8
1153 ")",
1154 Vals: Advance.AddrDelta, Vals: 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(C&: Cursor, Size: 2);
1171 if (Cursor) {
1172 State.Row.Address.Address += PCOffset;
1173 State.Row.OpIndex = 0;
1174 if (Verbose)
1175 *OS << format(Fmt: " (addr += 0x%4.4" PRIx16 ", op-index = 0)",
1176 Vals: 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>(Data&: 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>(Data&: TableData, Cursor))
1217 Operands.push_back(x: *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(Fmt: "0x%16.16" PRIx64, Vals: Value);
1226 *OS << ')';
1227 }
1228 }
1229 break;
1230 }
1231
1232 *OffsetPtr = Cursor.tell();
1233 } else {
1234 // Special Opcodes.
1235 ParsingState::SpecialOpcodeDelta Delta =
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(
1266 EC: errc::illegal_byte_sequence,
1267 Fmt: "last sequence in debug line table at offset 0x%8.8" PRIx64
1268 " is not terminated",
1269 Vals: DebugLineOffset));
1270
1271 // Sort all sequences so that address lookup will work faster.
1272 if (!Sequences.empty()) {
1273 llvm::stable_sort(Range&: Sequences, C: Sequence::orderByHighPC);
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,
1293 object::SectionedAddress Address) const {
1294 if (!Seq.containsPC(PC: 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.
1305 DWARFDebugLine::Row Row;
1306 Row.Address = Address;
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(first: FirstRow + 1, last: LastRow - 1, val: Row,
1312 comp: DWARFDebugLine::Row::orderByAddress) -
1313 1;
1314 assert(Seq.SectionIndex == RowPos->Address.SectionIndex);
1315 return RowPos - Rows.begin();
1316}
1317
1318uint32_t
1319DWARFDebugLine::LineTable::lookupAddress(object::SectionedAddress Address,
1320 bool *IsApproximateLine) const {
1321
1322 // Search for relocatable addresses
1323 uint32_t Result = lookupAddressImpl(Address, IsApproximateLine);
1324
1325 if (Result != UnknownRowIndex ||
1326 Address.SectionIndex == object::SectionedAddress::UndefSection)
1327 return Result;
1328
1329 // Search for absolute addresses
1330 Address.SectionIndex = object::SectionedAddress::UndefSection;
1331 return lookupAddressImpl(Address, IsApproximateLine);
1332}
1333
1334uint32_t
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.
1341 DWARFDebugLine::Sequence Sequence;
1342 Sequence.SectionIndex = Address.SectionIndex;
1343 Sequence.HighPC = Address.Address;
1344 SequenceIter It = llvm::upper_bound(Range: Sequences, Value&: Sequence,
1345 C: DWARFDebugLine::Sequence::orderByHighPC);
1346 if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex)
1347 return UnknownRowIndex;
1348
1349 uint32_t RowIndex = findRowInSeq(Seq: *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
1368bool DWARFDebugLine::LineTable::lookupAddressRange(
1369 object::SectionedAddress Address, uint64_t Size,
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
1377 if (Address.SectionIndex == object::SectionedAddress::UndefSection)
1378 return false;
1379
1380 // Search for absolute addresses
1381 Address.SectionIndex = object::SectionedAddress::UndefSection;
1382 return lookupAddressRangeImpl(Address, Size, Result, StmtSequenceOffset);
1383}
1384
1385bool DWARFDebugLine::LineTable::lookupAddressRangeImpl(
1386 object::SectionedAddress Address, uint64_t Size,
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.
1393 DWARFDebugLine::Sequence Sequence;
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(first: Sequences.begin(), last: LastSeq,
1403 pred: [&](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(first: Sequences.begin(), last: LastSeq, val: Sequence,
1417 comp: DWARFDebugLine::Sequence::orderByHighPC);
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(PC: 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(Seq: CurSeq, Address);
1436
1437 // Figure out the last row in the range.
1438 uint32_t LastRowIndex =
1439 findRowInSeq(Seq: CurSeq, Address: {.Address: EndAddr - 1, .SectionIndex: 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(x: 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(Index: FileIndex);
1462 if (auto E = dwarf::toString(V: 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.
1471 return sys::path::is_absolute(path: Path, style: sys::path::Style::posix) ||
1472 sys::path::is_absolute(path: Path, style: sys::path::Style::windows);
1473}
1474
1475bool DWARFDebugLine::Prologue::getFileNameByIndex(
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(Index: FileIndex);
1481 auto E = dwarf::toString(V: Entry.Name);
1482 if (!E)
1483 return false;
1484 StringRef FileName = *E;
1485 if (Kind == FileLineInfoKind::RawValue ||
1486 isPathAbsoluteOnWindowsOrPosix(Path: FileName)) {
1487 Result = std::string(FileName);
1488 return true;
1489 }
1490 if (Kind == FileLineInfoKind::BaseNameOnly) {
1491 Result = std::string(llvm::sys::path::filename(path: 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(V: IncludeDirectories[Entry.DirIdx]);
1504 } else {
1505 if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size())
1506 IncludeDir = dwarf::toStringRef(V: 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(Path: IncludeDir))
1516 sys::path::append(path&: FilePath, style: Style, a: 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(path&: FilePath, style: Style, a: IncludeDir, b: FileName);
1524 Result = std::string(FilePath);
1525 return true;
1526}
1527
1528bool DWARFDebugLine::LineTable::getFileLineInfoForAddress(
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, IsApproximateLine: 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(FileIndex: Row.File, CompDir, Kind, Result&: Result.FileName))
1539 return false;
1540 Result.Line = Row.Line;
1541 Result.Column = Row.Column;
1542 Result.Discriminator = Row.Discriminator;
1543 Result.Source = getSourceByIndex(FileIndex: Row.File, Kind);
1544 return true;
1545}
1546
1547bool DWARFDebugLine::LineTable::getDirectoryForEntry(
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(V: Prologue.IncludeDirectories[Entry.DirIdx], Default: "");
1553 return true;
1554 }
1555 return false;
1556 }
1557 if (0 < Entry.DirIdx && Entry.DirIdx <= Prologue.IncludeDirectories.size()) {
1558 Directory =
1559 dwarf::toString(V: Prologue.IncludeDirectories[Entry.DirIdx - 1], Default: "");
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.
1569static DWARFDebugLine::SectionParser::LineToUnitMap
1570buildLineToUnitMap(DWARFUnitVector::iterator_range Units) {
1571 DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit;
1572 for (const auto &U : Units)
1573 if (auto CUDIE = U->getUnitDIE())
1574 if (auto StmtOffset = toSectionOffset(V: CUDIE.find(Attr: DW_AT_stmt_list)))
1575 LineToUnit.insert(x: std::make_pair(x&: *StmtOffset, y: &*U));
1576 return LineToUnit;
1577}
1578
1579DWARFDebugLine::SectionParser::SectionParser(
1580 DWARFDataExtractor &Data, const DWARFContext &C,
1581 DWARFUnitVector::iterator_range Units)
1582 : DebugLineData(Data), Context(C) {
1583 LineToUnit = buildLineToUnitMap(Units);
1584 if (!DebugLineData.isValidOffset(offset: Offset))
1585 Done = true;
1586}
1587
1588bool DWARFDebugLine::Prologue::totalLengthIsValid() const {
1589 return TotalLength != 0u;
1590}
1591
1592DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext(
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, OffsetPtr: &Offset, Ctx: Context, U,
1602 RecoverableErrorHandler, OS, Verbose))
1603 UnrecoverableErrorHandler(std::move(Err));
1604 moveToNextTable(OldOffset, P: LT.Prologue);
1605 return LT;
1606}
1607
1608void DWARFDebugLine::SectionParser::skip(
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, OffsetPtr: &Offset,
1617 RecoverableErrorHandler, Ctx: Context, U))
1618 UnrecoverableErrorHandler(std::move(Err));
1619 moveToNextTable(OldOffset, P: LT.Prologue);
1620}
1621
1622DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) {
1623 DWARFUnit *U = nullptr;
1624 auto It = LineToUnit.find(x: 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) {
1632 DataExtractor::Cursor Cursor(Offset);
1633 auto [TotalLength, _] = DebugLineData.getInitialLength(C&: Cursor);
1634 DWARFDataExtractor HeaderData(DebugLineData, Cursor.tell() + TotalLength);
1635 uint16_t Version = HeaderData.getU16(C&: 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(Err: 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: 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(Value: Offset, Align);
1672 if (!DebugLineData.isValidOffset(offset: 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(Offset: AlignedOffset)) {
1680 Offset = AlignedOffset;
1681 break;
1682 }
1683 }
1684}
1685