Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DWARFContext.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/DWARFContext.h"
10
#include "llvm/ADT/STLExtras.h"
11
#include "llvm/ADT/SmallString.h"
12
#include "llvm/ADT/SmallVector.h"
13
#include "llvm/ADT/StringRef.h"
14
#include "llvm/ADT/StringSwitch.h"
15
#include "llvm/BinaryFormat/Dwarf.h"
16
#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
17
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
18
#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
19
#include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
20
#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
21
#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
22
#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
23
#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
24
#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
25
#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
26
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
27
#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
28
#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
29
#include "llvm/DebugInfo/DWARF/DWARFDie.h"
30
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
31
#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
32
#include "llvm/DebugInfo/DWARF/DWARFSection.h"
33
#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
34
#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
35
#include "llvm/MC/MCRegisterInfo.h"
36
#include "llvm/Object/Decompressor.h"
37
#include "llvm/Object/MachO.h"
38
#include "llvm/Object/ObjectFile.h"
39
#include "llvm/Object/RelocationResolver.h"
40
#include "llvm/Support/Casting.h"
41
#include "llvm/Support/DataExtractor.h"
42
#include "llvm/Support/Error.h"
43
#include "llvm/Support/Format.h"
44
#include "llvm/Support/LEB128.h"
45
#include "llvm/Support/MemoryBuffer.h"
46
#include "llvm/Support/Path.h"
47
#include "llvm/Support/TargetRegistry.h"
48
#include "llvm/Support/WithColor.h"
49
#include "llvm/Support/raw_ostream.h"
50
#include <algorithm>
51
#include <cstdint>
52
#include <deque>
53
#include <map>
54
#include <string>
55
#include <utility>
56
#include <vector>
57
58
using namespace llvm;
59
using namespace dwarf;
60
using namespace object;
61
62
#define DEBUG_TYPE "dwarf"
63
64
using DWARFLineTable = DWARFDebugLine::LineTable;
65
using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
66
using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
67
68
DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
69
                           std::string DWPName)
70
1.67k
    : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
71
72
1.67k
DWARFContext::~DWARFContext() = default;
73
74
/// Dump the UUID load command.
75
216
static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
76
216
  auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
77
216
  if (!MachO)
78
121
    return;
79
469
  
for (auto LC : MachO->load_commands())95
{
80
469
    raw_ostream::uuid_t UUID;
81
469
    if (LC.C.cmd == MachO::LC_UUID) {
82
32
      if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
83
0
        OS << "error: UUID load command is too short.\n";
84
0
        return;
85
0
      }
86
32
      OS << "UUID: ";
87
32
      memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
88
32
      OS.write_uuid(UUID);
89
32
      Triple T = MachO->getArchTriple();
90
32
      OS << " (" << T.getArchName() << ')';
91
32
      OS << ' ' << MachO->getFileName() << '\n';
92
32
    }
93
469
  }
94
95
}
95
96
using ContributionCollection =
97
    std::vector<Optional<StrOffsetsContributionDescriptor>>;
98
99
// Collect all the contributions to the string offsets table from all units,
100
// sort them by their starting offsets and remove duplicates.
101
static ContributionCollection
102
29
collectContributionData(DWARFContext::unit_iterator_range Units) {
103
29
  ContributionCollection Contributions;
104
29
  for (const auto &U : Units)
105
64
    if (const auto &C = U->getStringOffsetsTableContribution())
106
56
      Contributions.push_back(C);
107
29
  // Sort the contributions so that any invalid ones are placed at
108
29
  // the start of the contributions vector. This way they are reported
109
29
  // first.
110
29
  llvm::sort(Contributions,
111
29
             [](const Optional<StrOffsetsContributionDescriptor> &L,
112
30
                const Optional<StrOffsetsContributionDescriptor> &R) {
113
30
               if (L && R)
114
30
                 return L->Base < R->Base;
115
0
               return R.hasValue();
116
0
             });
117
29
118
29
  // Uniquify contributions, as it is possible that units (specifically
119
29
  // type units in dwo or dwp files) share contributions. We don't want
120
29
  // to report them more than once.
121
29
  Contributions.erase(
122
29
      std::unique(Contributions.begin(), Contributions.end(),
123
29
                  [](const Optional<StrOffsetsContributionDescriptor> &L,
124
29
                     const Optional<StrOffsetsContributionDescriptor> &R) {
125
27
                    if (L && R)
126
27
                      return L->Base == R->Base && 
L->Size == R->Size19
;
127
0
                    return false;
128
0
                  }),
129
29
      Contributions.end());
130
29
  return Contributions;
131
29
}
132
133
static void dumpDWARFv5StringOffsetsSection(
134
    raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
135
    const DWARFSection &StringOffsetsSection, StringRef StringSection,
136
29
    DWARFContext::unit_iterator_range Units, bool LittleEndian) {
137
29
  auto Contributions = collectContributionData(Units);
138
29
  DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
139
29
  DataExtractor StrData(StringSection, LittleEndian, 0);
140
29
  uint64_t SectionSize = StringOffsetsSection.Data.size();
141
29
  uint32_t Offset = 0;
142
37
  for (auto &Contribution : Contributions) {
143
37
    // Report an ill-formed contribution.
144
37
    if (!Contribution) {
145
0
      OS << "error: invalid contribution to string offsets table in section ."
146
0
         << SectionName << ".\n";
147
0
      return;
148
0
    }
149
37
150
37
    dwarf::DwarfFormat Format = Contribution->getFormat();
151
37
    uint16_t Version = Contribution->getVersion();
152
37
    uint64_t ContributionHeader = Contribution->Base;
153
37
    // In DWARF v5 there is a contribution header that immediately precedes
154
37
    // the string offsets base (the location we have previously retrieved from
155
37
    // the CU DIE's DW_AT_str_offsets attribute). The header is located either
156
37
    // 8 or 16 bytes before the base, depending on the contribution's format.
157
37
    if (Version >= 5)
158
36
      ContributionHeader -= Format == DWARF32 ? 
834
:
162
;
159
37
160
37
    // Detect overlapping contributions.
161
37
    if (Offset > ContributionHeader) {
162
2
      WithColor::error()
163
2
          << "overlapping contributions to string offsets table in section ."
164
2
          << SectionName << ".\n";
165
2
      return;
166
2
    }
167
35
    // Report a gap in the table.
168
35
    if (Offset < ContributionHeader) {
169
5
      OS << format("0x%8.8x: Gap, length = ", Offset);
170
5
      OS << (ContributionHeader - Offset) << "\n";
171
5
    }
172
35
    OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
173
35
    // In DWARF v5 the contribution size in the descriptor does not equal
174
35
    // the originally encoded length (it does not contain the length of the
175
35
    // version field and the padding, a total of 4 bytes). Add them back in
176
35
    // for reporting.
177
35
    OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 
01
:
434
))
178
35
       << ", Format = " << (Format == DWARF32 ? 
"DWARF32"33
:
"DWARF64"2
)
179
35
       << ", Version = " << Version << "\n";
180
35
181
35
    Offset = Contribution->Base;
182
35
    unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
183
526
    while (Offset - Contribution->Base < Contribution->Size) {
184
491
      OS << format("0x%8.8x: ", Offset);
185
491
      // FIXME: We can only extract strings if the offset fits in 32 bits.
186
491
      uint64_t StringOffset =
187
491
          StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
188
491
      // Extract the string if we can and display it. Otherwise just report
189
491
      // the offset.
190
491
      if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
191
491
        uint32_t StringOffset32 = (uint32_t)StringOffset;
192
491
        OS << format("%8.8x ", StringOffset32);
193
491
        const char *S = StrData.getCStr(&StringOffset32);
194
491
        if (S)
195
489
          OS << format("\"%s\"", S);
196
491
      } else
197
0
        OS << format("%16.16" PRIx64 " ", StringOffset);
198
491
      OS << "\n";
199
491
    }
200
35
  }
201
29
  // Report a gap at the end of the table.
202
29
  
if (27
Offset < SectionSize27
) {
203
0
    OS << format("0x%8.8x: Gap, length = ", Offset);
204
0
    OS << (SectionSize - Offset) << "\n";
205
0
  }
206
27
}
207
208
// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
209
// string offsets section, where each compile or type unit contributes a
210
// number of entries (string offsets), with each contribution preceded by
211
// a header containing size and version number. Alternatively, it may be a
212
// monolithic series of string offsets, as generated by the pre-DWARF v5
213
// implementation of split DWARF.
214
static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
215
                                     const DWARFObject &Obj,
216
                                     const DWARFSection &StringOffsetsSection,
217
                                     StringRef StringSection,
218
                                     DWARFContext::unit_iterator_range Units,
219
50
                                     bool LittleEndian, unsigned MaxVersion) {
220
50
  // If we have at least one (compile or type) unit with DWARF v5 or greater,
221
50
  // we assume that the section is formatted like a DWARF v5 string offsets
222
50
  // section.
223
50
  if (MaxVersion >= 5)
224
29
    dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
225
29
                                    StringSection, Units, LittleEndian);
226
21
  else {
227
21
    DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
228
21
    uint32_t offset = 0;
229
21
    uint64_t size = StringOffsetsSection.Data.size();
230
21
    // Ensure that size is a multiple of the size of an entry.
231
21
    if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
232
1
      OS << "error: size of ." << SectionName << " is not a multiple of "
233
1
         << sizeof(uint32_t) << ".\n";
234
1
      size &= -(uint64_t)sizeof(uint32_t);
235
1
    }
236
21
    DataExtractor StrData(StringSection, LittleEndian, 0);
237
274
    while (offset < size) {
238
253
      OS << format("0x%8.8x: ", offset);
239
253
      uint32_t StringOffset = strOffsetExt.getU32(&offset);
240
253
      OS << format("%8.8x  ", StringOffset);
241
253
      const char *S = StrData.getCStr(&StringOffset);
242
253
      if (S)
243
253
        OS << format("\"%s\"", S);
244
253
      OS << "\n";
245
253
    }
246
21
  }
247
50
}
248
249
// Dump the .debug_addr section.
250
static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
251
                            DIDumpOptions DumpOpts, uint16_t Version,
252
40
                            uint8_t AddrSize) {
253
40
  uint32_t Offset = 0;
254
77
  while (AddrData.isValidOffset(Offset)) {
255
42
    DWARFDebugAddrTable AddrTable;
256
42
    uint32_t TableOffset = Offset;
257
42
    if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
258
10
                                      DWARFContext::dumpWarning)) {
259
10
      WithColor::error() << toString(std::move(Err)) << '\n';
260
10
      // Keep going after an error, if we can, assuming that the length field
261
10
      // could be read. If it couldn't, stop reading the section.
262
10
      if (!AddrTable.hasValidLength())
263
5
        break;
264
5
      uint64_t Length = AddrTable.getLength();
265
5
      Offset = TableOffset + Length;
266
32
    } else {
267
32
      AddrTable.dump(OS, DumpOpts);
268
32
    }
269
42
  }
270
40
}
271
272
// Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
273
static void dumpRnglistsSection(
274
    raw_ostream &OS, DWARFDataExtractor &rnglistData,
275
    llvm::function_ref<Optional<object::SectionedAddress>(uint32_t)>
276
        LookupPooledAddress,
277
12
    DIDumpOptions DumpOpts) {
278
12
  uint32_t Offset = 0;
279
47
  while (rnglistData.isValidOffset(Offset)) {
280
37
    llvm::DWARFDebugRnglistTable Rnglists;
281
37
    uint32_t TableOffset = Offset;
282
37
    if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
283
15
      WithColor::error() << toString(std::move(Err)) << '\n';
284
15
      uint64_t Length = Rnglists.length();
285
15
      // Keep going after an error, if we can, assuming that the length field
286
15
      // could be read. If it couldn't, stop reading the section.
287
15
      if (Length == 0)
288
2
        break;
289
13
      Offset = TableOffset + Length;
290
22
    } else {
291
22
      Rnglists.dump(OS, LookupPooledAddress, DumpOpts);
292
22
    }
293
37
  }
294
12
}
295
296
static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
297
                                DWARFDataExtractor Data,
298
                                const MCRegisterInfo *MRI,
299
4
                                Optional<uint64_t> DumpOffset) {
300
4
  uint32_t Offset = 0;
301
4
  DWARFDebugLoclists Loclists;
302
4
303
4
  DWARFListTableHeader Header(".debug_loclists", "locations");
304
4
  if (Error E = Header.extract(Data, &Offset)) {
305
0
    WithColor::error() << toString(std::move(E)) << '\n';
306
0
    return;
307
0
  }
308
4
309
4
  Header.dump(OS, DumpOpts);
310
4
  DataExtractor LocData(Data.getData().drop_front(Offset),
311
4
                        Data.isLittleEndian(), Header.getAddrSize());
312
4
313
4
  Loclists.parse(LocData, Header.getVersion());
314
4
  Loclists.dump(OS, 0, MRI, DumpOffset);
315
4
}
316
317
void DWARFContext::dump(
318
    raw_ostream &OS, DIDumpOptions DumpOpts,
319
754
    std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
320
754
321
754
  uint64_t DumpType = DumpOpts.DumpType;
322
754
323
754
  StringRef Extension = sys::path::extension(DObj->getFileName());
324
754
  bool IsDWO = (Extension == ".dwo") || 
(Extension == ".dwp")749
;
325
754
326
754
  // Print UUID header.
327
754
  const auto *ObjFile = DObj->getFile();
328
754
  if (DumpType & DIDT_UUID)
329
216
    dumpUUID(OS, *ObjFile);
330
754
331
754
  // Print a header for each explicitly-requested section.
332
754
  // Otherwise just print one for non-empty sections.
333
754
  // Only print empty .dwo section headers when dumping a .dwo file.
334
754
  bool Explicit = DumpType != DIDT_All && 
!IsDWO541
;
335
754
  bool ExplicitDWO = Explicit && 
IsDWO540
;
336
754
  auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
337
23.3k
                        StringRef Section) -> Optional<uint64_t> * {
338
23.3k
    unsigned Mask = 1U << ID;
339
23.3k
    bool Should = (DumpType & Mask) && 
(6.89k
Explicit6.89k
||
!Section.empty()6.68k
);
340
23.3k
    if (!Should)
341
21.6k
      return nullptr;
342
1.66k
    OS << "\n" << Name << " contents:\n";
343
1.66k
    return &DumpOffsets[ID];
344
1.66k
  };
345
754
346
754
  // Dump individual sections.
347
754
  if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
348
754
                 DObj->getAbbrevSection()))
349
188
    getDebugAbbrev()->dump(OS);
350
754
  if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
351
754
                 DObj->getAbbrevDWOSection()))
352
33
    getDebugAbbrevDWO()->dump(OS);
353
754
354
754
  auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
355
600
    OS << '\n' << Name << " contents:\n";
356
600
    if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
357
14
      for (const auto &U : Units)
358
14
        U->getDIEForOffset(DumpOffset.getValue())
359
14
            .dump(OS, 0, DumpOpts.noImplicitRecursion());
360
586
    else
361
586
      for (const auto &U : Units)
362
755
        U->dump(OS, DumpOpts);
363
600
  };
364
754
  if ((DumpType & DIDT_DebugInfo)) {
365
583
    if (Explicit || 
getNumCompileUnits()214
)
366
552
      dumpDebugInfo(".debug_info", info_section_units());
367
583
    if (ExplicitDWO || getNumDWOCompileUnits())
368
48
      dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
369
583
  }
370
754
371
754
  auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
372
28
    OS << '\n' << Name << " contents:\n";
373
28
    for (const auto &U : Units)
374
54
      if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
375
4
        U->getDIEForOffset(*DumpOffset)
376
4
            .dump(OS, 0, DumpOpts.noImplicitRecursion());
377
50
      else
378
50
        U->dump(OS, DumpOpts);
379
28
  };
380
754
  if ((DumpType & DIDT_DebugTypes)) {
381
221
    if (Explicit || 
getNumTypeUnits()213
)
382
18
      dumpDebugType(".debug_types", types_section_units());
383
221
    if (ExplicitDWO || getNumDWOTypeUnits())
384
10
      dumpDebugType(".debug_types.dwo", dwo_types_section_units());
385
221
  }
386
754
387
754
  if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
388
48
                                   DObj->getLocSection().Data)) {
389
48
    getDebugLoc()->dump(OS, getRegisterInfo(), *Off);
390
48
  }
391
754
  if (const auto *Off =
392
4
          shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
393
4
                     DObj->getLoclistsSection().Data)) {
394
4
    DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
395
4
                            0);
396
4
    dumpLoclistsSection(OS, DumpOpts, Data, getRegisterInfo(), *Off);
397
4
  }
398
754
  if (const auto *Off =
399
4
          shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
400
4
                     DObj->getLocDWOSection().Data)) {
401
4
    getDebugLocDWO()->dump(OS, 0, getRegisterInfo(), *Off);
402
4
  }
403
754
404
754
  if (const auto *Off = shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
405
55
                                   DObj->getDebugFrameSection().Data))
406
55
    getDebugFrame()->dump(OS, getRegisterInfo(), *Off);
407
754
408
754
  if (const auto *Off = shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
409
101
                                   DObj->getEHFrameSection().Data))
410
101
    getEHFrame()->dump(OS, getRegisterInfo(), *Off);
411
754
412
754
  if (DumpType & DIDT_DebugMacro) {
413
214
    if (Explicit || 
!getDebugMacro()->empty()213
) {
414
2
      OS << "\n.debug_macinfo contents:\n";
415
2
      getDebugMacro()->dump(OS);
416
2
    }
417
214
  }
418
754
419
754
  if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
420
754
                 DObj->getARangeSection())) {
421
40
    uint32_t offset = 0;
422
40
    DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
423
40
    DWARFDebugArangeSet set;
424
150
    while (set.extract(arangesData, &offset))
425
110
      set.dump(OS);
426
40
  }
427
754
428
754
  auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
429
754
                             DIDumpOptions DumpOpts,
430
754
                             Optional<uint64_t> DumpOffset) {
431
668
    while (!Parser.done()) {
432
417
      if (DumpOffset && 
Parser.getOffset() != *DumpOffset38
) {
433
32
        Parser.skip(dumpWarning);
434
32
        continue;
435
32
      }
436
385
      OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n";
437
385
      if (DumpOpts.Verbose) {
438
224
        Parser.parseNext(dumpWarning, dumpWarning, &OS);
439
224
      } else {
440
161
        DWARFDebugLine::LineTable LineTable =
441
161
            Parser.parseNext(dumpWarning, dumpWarning);
442
161
        LineTable.dump(OS, DumpOpts);
443
161
      }
444
385
    }
445
251
  };
446
754
447
754
  if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
448
233
                                   DObj->getLineSection().Data)) {
449
233
    DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
450
233
                                0);
451
233
    DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
452
233
                                         type_units());
453
233
    DumpLineSection(Parser, DumpOpts, *Off);
454
233
  }
455
754
456
754
  if (const auto *Off =
457
18
          shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
458
18
                     DObj->getLineDWOSection().Data)) {
459
18
    DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
460
18
                                isLittleEndian(), 0);
461
18
    DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
462
18
                                         dwo_type_units());
463
18
    DumpLineSection(Parser, DumpOpts, *Off);
464
18
  }
465
754
466
754
  if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
467
754
                 DObj->getCUIndexSection())) {
468
11
    getCUIndex().dump(OS);
469
11
  }
470
754
471
754
  if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
472
754
                 DObj->getTUIndexSection())) {
473
6
    getTUIndex().dump(OS);
474
6
  }
475
754
476
754
  if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
477
754
                 DObj->getStringSection())) {
478
178
    DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
479
178
    uint32_t offset = 0;
480
178
    uint32_t strOffset = 0;
481
2.43k
    while (const char *s = strData.getCStr(&offset)) {
482
2.25k
      OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
483
2.25k
      strOffset = offset;
484
2.25k
    }
485
178
  }
486
754
  if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
487
754
                 DObj->getStringDWOSection())) {
488
30
    DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
489
30
    uint32_t offset = 0;
490
30
    uint32_t strDWOOffset = 0;
491
333
    while (const char *s = strDWOData.getCStr(&offset)) {
492
303
      OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
493
303
      strDWOOffset = offset;
494
303
    }
495
30
  }
496
754
  if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
497
754
                 DObj->getLineStringSection())) {
498
22
    DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0);
499
22
    uint32_t offset = 0;
500
22
    uint32_t strOffset = 0;
501
87
    while (const char *s = strData.getCStr(&offset)) {
502
65
      OS << format("0x%8.8x: \"", strOffset);
503
65
      OS.write_escaped(s);
504
65
      OS << "\"\n";
505
65
      strOffset = offset;
506
65
    }
507
22
  }
508
754
509
754
  if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
510
754
                 DObj->getAddrSection().Data)) {
511
40
    DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
512
40
                                   isLittleEndian(), 0);
513
40
    dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
514
40
  }
515
754
516
754
  if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
517
754
                 DObj->getRangeSection().Data)) {
518
33
    uint8_t savedAddressByteSize = getCUAddrSize();
519
33
    DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
520
33
                                  isLittleEndian(), savedAddressByteSize);
521
33
    uint32_t offset = 0;
522
33
    DWARFDebugRangeList rangeList;
523
67
    while (rangesData.isValidOffset(offset)) {
524
35
      if (Error E = rangeList.extract(rangesData, &offset)) {
525
1
        WithColor::error() << toString(std::move(E)) << '\n';
526
1
        break;
527
1
      }
528
34
      rangeList.dump(OS);
529
34
    }
530
33
  }
531
754
532
754
  auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
533
14
    const auto &CUs = compile_units();
534
14
    auto I = CUs.begin();
535
14
    if (I == CUs.end())
536
6
      return None;
537
8
    return (*I)->getAddrOffsetSectionItem(Index);
538
8
  };
539
754
540
754
  if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
541
754
                 DObj->getRnglistsSection().Data)) {
542
10
    DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
543
10
                                   isLittleEndian(), 0);
544
10
    dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
545
10
  }
546
754
547
754
  if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
548
754
                 DObj->getRnglistsDWOSection().Data)) {
549
2
    DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
550
2
                                   isLittleEndian(), 0);
551
2
    dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
552
2
  }
553
754
554
754
  if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
555
754
                 DObj->getPubNamesSection().Data))
556
77
    DWARFDebugPubTable(*DObj, DObj->getPubNamesSection(), isLittleEndian(), false)
557
77
        .dump(OS);
558
754
559
754
  if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
560
754
                 DObj->getPubTypesSection().Data))
561
69
    DWARFDebugPubTable(*DObj, DObj->getPubTypesSection(), isLittleEndian(), false)
562
69
        .dump(OS);
563
754
564
754
  if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
565
754
                 DObj->getGnuPubNamesSection().Data))
566
5
    DWARFDebugPubTable(*DObj, DObj->getGnuPubNamesSection(), isLittleEndian(),
567
5
                       true /* GnuStyle */)
568
5
        .dump(OS);
569
754
570
754
  if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
571
754
                 DObj->getGnuPubTypesSection().Data))
572
4
    DWARFDebugPubTable(*DObj, DObj->getGnuPubTypesSection(), isLittleEndian(),
573
4
                       true /* GnuStyle */)
574
4
        .dump(OS);
575
754
576
754
  if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
577
754
                 DObj->getStringOffsetSection().Data))
578
22
    dumpStringOffsetsSection(OS, "debug_str_offsets", *DObj,
579
22
                             DObj->getStringOffsetSection(),
580
22
                             DObj->getStringSection(), normal_units(),
581
22
                             isLittleEndian(), getMaxVersion());
582
754
  if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
583
754
                 DObj->getStringOffsetDWOSection().Data))
584
28
    dumpStringOffsetsSection(OS, "debug_str_offsets.dwo", *DObj,
585
28
                             DObj->getStringOffsetDWOSection(),
586
28
                             DObj->getStringDWOSection(), dwo_units(),
587
28
                             isLittleEndian(), getMaxDWOVersion());
588
754
589
754
  if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
590
754
                 DObj->getGdbIndexSection())) {
591
12
    getGdbIndex().dump(OS);
592
12
  }
593
754
594
754
  if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
595
754
                 DObj->getAppleNamesSection().Data))
596
91
    getAppleNames().dump(OS);
597
754
598
754
  if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
599
754
                 DObj->getAppleTypesSection().Data))
600
91
    getAppleTypes().dump(OS);
601
754
602
754
  if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
603
754
                 DObj->getAppleNamespacesSection().Data))
604
89
    getAppleNamespaces().dump(OS);
605
754
606
754
  if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
607
754
                 DObj->getAppleObjCSection().Data))
608
89
    getAppleObjC().dump(OS);
609
754
  if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
610
754
                 DObj->getDebugNamesSection().Data))
611
31
    getDebugNames().dump(OS);
612
754
}
613
614
7
DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
615
7
  parseDWOUnits(LazyParse);
616
7
617
7
  if (const auto &CUI = getCUIndex()) {
618
1
    if (const auto *R = CUI.getFromHash(Hash))
619
1
      return dyn_cast_or_null<DWARFCompileUnit>(
620
1
          DWOUnits.getUnitForIndexEntry(*R));
621
0
    return nullptr;
622
0
  }
623
6
624
6
  // If there's no index, just search through the CUs in the DWO - there's
625
6
  // probably only one unless this is something like LTO - though an in-process
626
6
  // built/cached lookup table could be used in that case to improve repeated
627
6
  // lookups of different CUs in the DWO.
628
7
  
for (const auto &DWOCU : dwo_compile_units())6
{
629
7
    // Might not have parsed DWO ID yet.
630
7
    if (!DWOCU->getDWOId()) {
631
0
      if (Optional<uint64_t> DWOId =
632
0
          toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
633
0
        DWOCU->setDWOId(*DWOId);
634
0
      else
635
0
        // No DWO ID?
636
0
        continue;
637
7
    }
638
7
    if (DWOCU->getDWOId() == Hash)
639
6
      return dyn_cast<DWARFCompileUnit>(DWOCU.get());
640
7
  }
641
6
  
return nullptr0
;
642
6
}
643
644
744
DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
645
744
  parseNormalUnits();
646
744
  if (auto *CU = NormalUnits.getUnitForOffset(Offset))
647
742
    return CU->getDIEForOffset(Offset);
648
2
  return DWARFDie();
649
2
}
650
651
83
bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
652
83
  bool Success = true;
653
83
  DWARFVerifier verifier(OS, *this, DumpOpts);
654
83
655
83
  Success &= verifier.handleDebugAbbrev();
656
83
  if (DumpOpts.DumpType & DIDT_DebugInfo)
657
72
    Success &= verifier.handleDebugInfo();
658
83
  if (DumpOpts.DumpType & DIDT_DebugLine)
659
35
    Success &= verifier.handleDebugLine();
660
83
  Success &= verifier.handleAccelTables();
661
83
  return Success;
662
83
}
663
664
101
const DWARFUnitIndex &DWARFContext::getCUIndex() {
665
101
  if (CUIndex)
666
46
    return *CUIndex;
667
55
668
55
  DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
669
55
670
55
  CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
671
55
  CUIndex->parse(CUIndexData);
672
55
  return *CUIndex;
673
55
}
674
675
29
const DWARFUnitIndex &DWARFContext::getTUIndex() {
676
29
  if (TUIndex)
677
18
    return *TUIndex;
678
11
679
11
  DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
680
11
681
11
  TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
682
11
  TUIndex->parse(TUIndexData);
683
11
  return *TUIndex;
684
11
}
685
686
12
DWARFGdbIndex &DWARFContext::getGdbIndex() {
687
12
  if (GdbIndex)
688
0
    return *GdbIndex;
689
12
690
12
  DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
691
12
  GdbIndex = llvm::make_unique<DWARFGdbIndex>();
692
12
  GdbIndex->parse(GdbIndexData);
693
12
  return *GdbIndex;
694
12
}
695
696
1.96k
const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
697
1.96k
  if (Abbrev)
698
526
    return Abbrev.get();
699
1.44k
700
1.44k
  DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
701
1.44k
702
1.44k
  Abbrev.reset(new DWARFDebugAbbrev());
703
1.44k
  Abbrev->extract(abbrData);
704
1.44k
  return Abbrev.get();
705
1.44k
}
706
707
109
const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
708
109
  if (AbbrevDWO)
709
48
    return AbbrevDWO.get();
710
61
711
61
  DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
712
61
  AbbrevDWO.reset(new DWARFDebugAbbrev());
713
61
  AbbrevDWO->extract(abbrData);
714
61
  return AbbrevDWO.get();
715
61
}
716
717
90
const DWARFDebugLoc *DWARFContext::getDebugLoc() {
718
90
  if (Loc)
719
32
    return Loc.get();
720
58
721
58
  Loc.reset(new DWARFDebugLoc);
722
58
  // Assume all units have the same address byte size.
723
58
  if (getNumCompileUnits()) {
724
56
    DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
725
56
                               getUnitAtIndex(0)->getAddressByteSize());
726
56
    Loc->parse(LocData);
727
56
  }
728
58
  return Loc.get();
729
58
}
730
731
4
const DWARFDebugLoclists *DWARFContext::getDebugLocDWO() {
732
4
  if (LocDWO)
733
0
    return LocDWO.get();
734
4
735
4
  LocDWO.reset(new DWARFDebugLoclists());
736
4
  // Assume all compile units have the same address byte size.
737
4
  // FIXME: We don't need AddressSize for split DWARF since relocatable
738
4
  // addresses cannot appear there. At the moment DWARFExpression requires it.
739
4
  DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 4);
740
4
  // Use version 4. DWO does not support the DWARF v5 .debug_loclists yet and
741
4
  // that means we are parsing the new style .debug_loc (pre-standatized version
742
4
  // of the .debug_loclists).
743
4
  LocDWO->parse(LocData, 4 /* Version */);
744
4
  return LocDWO.get();
745
4
}
746
747
1.15k
const DWARFDebugAranges *DWARFContext::getDebugAranges() {
748
1.15k
  if (Aranges)
749
943
    return Aranges.get();
750
208
751
208
  Aranges.reset(new DWARFDebugAranges());
752
208
  Aranges->generate(this);
753
208
  return Aranges.get();
754
208
}
755
756
55
const DWARFDebugFrame *DWARFContext::getDebugFrame() {
757
55
  if (DebugFrame)
758
0
    return DebugFrame.get();
759
55
760
55
  // There's a "bug" in the DWARFv3 standard with respect to the target address
761
55
  // size within debug frame sections. While DWARF is supposed to be independent
762
55
  // of its container, FDEs have fields with size being "target address size",
763
55
  // which isn't specified in DWARF in general. It's only specified for CUs, but
764
55
  // .eh_frame can appear without a .debug_info section. Follow the example of
765
55
  // other tools (libdwarf) and extract this from the container (ObjectFile
766
55
  // provides this information). This problem is fixed in DWARFv4
767
55
  // See this dwarf-discuss discussion for more details:
768
55
  // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
769
55
  DWARFDataExtractor debugFrameData(*DObj, DObj->getDebugFrameSection(),
770
55
                                    isLittleEndian(), DObj->getAddressSize());
771
55
  DebugFrame.reset(new DWARFDebugFrame(getArch(), false /* IsEH */));
772
55
  DebugFrame->parse(debugFrameData);
773
55
  return DebugFrame.get();
774
55
}
775
776
101
const DWARFDebugFrame *DWARFContext::getEHFrame() {
777
101
  if (EHFrame)
778
0
    return EHFrame.get();
779
101
780
101
  DWARFDataExtractor debugFrameData(*DObj, DObj->getEHFrameSection(),
781
101
                                    isLittleEndian(), DObj->getAddressSize());
782
101
  DebugFrame.reset(new DWARFDebugFrame(getArch(), true /* IsEH */));
783
101
  DebugFrame->parse(debugFrameData);
784
101
  return DebugFrame.get();
785
101
}
786
787
215
const DWARFDebugMacro *DWARFContext::getDebugMacro() {
788
215
  if (Macro)
789
1
    return Macro.get();
790
214
791
214
  DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
792
214
  Macro.reset(new DWARFDebugMacro());
793
214
  Macro->parse(MacinfoData);
794
214
  return Macro.get();
795
214
}
796
797
template <typename T>
798
static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
799
                        const DWARFSection &Section, StringRef StringSection,
800
463
                        bool IsLittleEndian) {
801
463
  if (Cache)
802
12
    return *Cache;
803
451
  DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
804
451
  DataExtractor StrData(StringSection, IsLittleEndian, 0);
805
451
  Cache.reset(new T(AccelSection, StrData));
806
451
  if (Error E = Cache->extract())
807
24
    llvm::consumeError(std::move(E));
808
451
  return *Cache;
809
451
}
DWARFContext.cpp:llvm::DWARFDebugNames& getAccelTable<llvm::DWARFDebugNames>(std::__1::unique_ptr<llvm::DWARFDebugNames, std::__1::default_delete<llvm::DWARFDebugNames> >&, llvm::DWARFObject const&, llvm::DWARFSection const&, llvm::StringRef, bool)
Line
Count
Source
800
49
                        bool IsLittleEndian) {
801
49
  if (Cache)
802
3
    return *Cache;
803
46
  DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
804
46
  DataExtractor StrData(StringSection, IsLittleEndian, 0);
805
46
  Cache.reset(new T(AccelSection, StrData));
806
46
  if (Error E = Cache->extract())
807
0
    llvm::consumeError(std::move(E));
808
46
  return *Cache;
809
46
}
DWARFContext.cpp:llvm::AppleAcceleratorTable& getAccelTable<llvm::AppleAcceleratorTable>(std::__1::unique_ptr<llvm::AppleAcceleratorTable, std::__1::default_delete<llvm::AppleAcceleratorTable> >&, llvm::DWARFObject const&, llvm::DWARFSection const&, llvm::StringRef, bool)
Line
Count
Source
800
414
                        bool IsLittleEndian) {
801
414
  if (Cache)
802
9
    return *Cache;
803
405
  DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
804
405
  DataExtractor StrData(StringSection, IsLittleEndian, 0);
805
405
  Cache.reset(new T(AccelSection, StrData));
806
405
  if (Error E = Cache->extract())
807
24
    llvm::consumeError(std::move(E));
808
405
  return *Cache;
809
405
}
810
811
49
const DWARFDebugNames &DWARFContext::getDebugNames() {
812
49
  return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(),
813
49
                       DObj->getStringSection(), isLittleEndian());
814
49
}
815
816
109
const AppleAcceleratorTable &DWARFContext::getAppleNames() {
817
109
  return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
818
109
                       DObj->getStringSection(), isLittleEndian());
819
109
}
820
821
109
const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
822
109
  return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
823
109
                       DObj->getStringSection(), isLittleEndian());
824
109
}
825
826
107
const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
827
107
  return getAccelTable(AppleNamespaces, *DObj,
828
107
                       DObj->getAppleNamespacesSection(),
829
107
                       DObj->getStringSection(), isLittleEndian());
830
107
}
831
832
89
const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
833
89
  return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
834
89
                       DObj->getStringSection(), isLittleEndian());
835
89
}
836
837
const DWARFDebugLine::LineTable *
838
4.07k
DWARFContext::getLineTableForUnit(DWARFUnit *U) {
839
4.07k
  Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
840
4.07k
      getLineTableForUnit(U, dumpWarning);
841
4.07k
  if (!ExpectedLineTable) {
842
0
    dumpWarning(ExpectedLineTable.takeError());
843
0
    return nullptr;
844
0
  }
845
4.07k
  return *ExpectedLineTable;
846
4.07k
}
847
848
Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
849
4.11k
    DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
850
4.11k
  if (!Line)
851
821
    Line.reset(new DWARFDebugLine);
852
4.11k
853
4.11k
  auto UnitDIE = U->getUnitDIE();
854
4.11k
  if (!UnitDIE)
855
0
    return nullptr;
856
4.11k
857
4.11k
  auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
858
4.11k
  if (!Offset)
859
214
    return nullptr; // No line table for this compile unit.
860
3.89k
861
3.89k
  uint32_t stmtOffset = *Offset + U->getLineTableOffset();
862
3.89k
  // See if the line table is cached.
863
3.89k
  if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
864
2.95k
    return lt;
865
941
866
941
  // Make sure the offset is good before we try to parse.
867
941
  if (stmtOffset >= U->getLineSection().Data.size())
868
24
    return nullptr;
869
917
870
917
  // We have to parse it first.
871
917
  DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
872
917
                              U->getAddressByteSize());
873
917
  return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
874
917
                                   RecoverableErrorCallback);
875
917
}
876
877
5.17k
void DWARFContext::parseNormalUnits() {
878
5.17k
  if (!NormalUnits.empty())
879
3.45k
    return;
880
1.72k
  DObj->forEachInfoSections([&](const DWARFSection &S) {
881
1.41k
    NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
882
1.41k
  });
883
1.72k
  NormalUnits.finishedInfoUnits();
884
1.72k
  DObj->forEachTypesSections([&](const DWARFSection &S) {
885
36
    NormalUnits.addUnitsForSection(*this, S, DW_SECT_TYPES);
886
36
  });
887
1.72k
}
888
889
997
void DWARFContext::parseDWOUnits(bool Lazy) {
890
997
  if (!DWOUnits.empty())
891
175
    return;
892
822
  DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
893
62
    DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
894
62
  });
895
822
  DWOUnits.finishedInfoUnits();
896
822
  DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
897
11
    DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_TYPES, Lazy);
898
11
  });
899
822
}
900
901
1.15k
DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
902
1.15k
  parseNormalUnits();
903
1.15k
  return dyn_cast_or_null<DWARFCompileUnit>(
904
1.15k
      NormalUnits.getUnitForOffset(Offset));
905
1.15k
}
906
907
1.15k
DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
908
1.15k
  // First, get the offset of the compile unit.
909
1.15k
  uint32_t CUOffset = getDebugAranges()->findAddress(Address);
910
1.15k
  // Retrieve the compile unit.
911
1.15k
  return getCompileUnitForOffset(CUOffset);
912
1.15k
}
913
914
7
DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
915
7
  DIEsForAddress Result;
916
7
917
7
  DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
918
7
  if (!CU)
919
3
    return Result;
920
4
921
4
  Result.CompileUnit = CU;
922
4
  Result.FunctionDIE = CU->getSubroutineForAddress(Address);
923
4
924
4
  std::vector<DWARFDie> Worklist;
925
4
  Worklist.push_back(Result.FunctionDIE);
926
10
  while (!Worklist.empty()) {
927
8
    DWARFDie DIE = Worklist.back();
928
8
    Worklist.pop_back();
929
8
930
8
    if (!DIE.isValid())
931
1
      continue;
932
7
933
7
    if (DIE.getTag() == DW_TAG_lexical_block &&
934
7
        
DIE.addressRangeContainsAddress(Address)3
) {
935
2
      Result.BlockDIE = DIE;
936
2
      break;
937
2
    }
938
5
939
5
    for (auto Child : DIE)
940
4
      Worklist.push_back(Child);
941
5
  }
942
4
943
4
  return Result;
944
4
}
945
946
/// TODO: change input parameter from "uint64_t Address"
947
///       into "SectionedAddress Address"
948
static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
949
                                                  uint64_t Address,
950
                                                  FunctionNameKind Kind,
951
                                                  std::string &FunctionName,
952
727
                                                  uint32_t &StartLine) {
953
727
  // The address may correspond to instruction in some inlined function,
954
727
  // so we have to build the chain of inlined functions and take the
955
727
  // name of the topmost function in it.
956
727
  SmallVector<DWARFDie, 4> InlinedChain;
957
727
  CU->getInlinedChainForAddress(Address, InlinedChain);
958
727
  if (InlinedChain.empty())
959
111
    return false;
960
616
961
616
  const DWARFDie &DIE = InlinedChain[0];
962
616
  bool FoundResult = false;
963
616
  const char *Name = nullptr;
964
616
  if (Kind != FunctionNameKind::None && 
(Name = DIE.getSubroutineName(Kind))31
) {
965
31
    FunctionName = Name;
966
31
    FoundResult = true;
967
31
  }
968
616
  if (auto DeclLineResult = DIE.getDeclLine()) {
969
616
    StartLine = DeclLineResult;
970
616
    FoundResult = true;
971
616
  }
972
616
973
616
  return FoundResult;
974
616
}
975
976
35
static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
977
35
  if (auto SizeAttr = Type.find(DW_AT_byte_size))
978
12
    if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
979
12
      return Size;
980
23
981
23
  switch (Type.getTag()) {
982
23
  case DW_TAG_pointer_type:
983
9
  case DW_TAG_reference_type:
984
9
  case DW_TAG_rvalue_reference_type:
985
9
    return PointerSize;
986
9
  case DW_TAG_ptr_to_member_type: {
987
2
    if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
988
2
      if (BaseType.getTag() == DW_TAG_subroutine_type)
989
1
        return 2 * PointerSize;
990
1
    return PointerSize;
991
1
  }
992
4
  case DW_TAG_const_type:
993
4
  case DW_TAG_volatile_type:
994
4
  case DW_TAG_restrict_type:
995
4
  case DW_TAG_typedef: {
996
4
    if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
997
4
      return getTypeSize(BaseType, PointerSize);
998
0
    break;
999
0
  }
1000
8
  case DW_TAG_array_type: {
1001
8
    DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type);
1002
8
    if (!BaseType)
1003
0
      return Optional<uint64_t>();
1004
8
    Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
1005
8
    if (!BaseSize)
1006
0
      return Optional<uint64_t>();
1007
8
    uint64_t Size = *BaseSize;
1008
9
    for (DWARFDie Child : Type) {
1009
9
      if (Child.getTag() != DW_TAG_subrange_type)
1010
0
        continue;
1011
9
1012
9
      if (auto ElemCountAttr = Child.find(DW_AT_count))
1013
8
        if (Optional<uint64_t> ElemCount =
1014
8
                ElemCountAttr->getAsUnsignedConstant())
1015
8
          Size *= *ElemCount;
1016
9
      if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
1017
1
        if (Optional<int64_t> UpperBound =
1018
1
                UpperBoundAttr->getAsSignedConstant()) {
1019
1
          int64_t LowerBound = 0;
1020
1
          if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
1021
1
            LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
1022
1
          Size *= *UpperBound - LowerBound + 1;
1023
1
        }
1024
9
    }
1025
8
    return Size;
1026
8
  }
1027
8
  default:
1028
0
    break;
1029
0
  }
1030
0
  return Optional<uint64_t>();
1031
0
}
1032
1033
void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1034
32
                                   DWARFDie Die, std::vector<DILocal> &Result) {
1035
32
  if (Die.getTag() == DW_TAG_variable ||
1036
32
      
Die.getTag() == DW_TAG_formal_parameter15
) {
1037
23
    DILocal Local;
1038
23
    if (auto NameAttr = Subprogram.find(DW_AT_name))
1039
23
      if (Optional<const char *> Name = NameAttr->getAsCString())
1040
23
        Local.FunctionName = *Name;
1041
23
    if (auto LocationAttr = Die.find(DW_AT_location))
1042
23
      if (Optional<ArrayRef<uint8_t>> Location = LocationAttr->getAsBlock())
1043
18
        if (!Location->empty() && (*Location)[0] == DW_OP_fbreg)
1044
18
          Local.FrameOffset =
1045
18
              decodeSLEB128(Location->data() + 1, nullptr, Location->end());
1046
23
    if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
1047
5
      Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1048
23
1049
23
    if (auto Origin =
1050
9
            Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1051
9
      Die = Origin;
1052
23
    if (auto NameAttr = Die.find(DW_AT_name))
1053
23
      if (Optional<const char *> Name = NameAttr->getAsCString())
1054
23
        Local.Name = *Name;
1055
23
    if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
1056
23
      Local.Size = getTypeSize(Type, getCUAddrSize());
1057
23
    if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
1058
23
      if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
1059
23
        LT->getFileNameByIndex(
1060
23
            DeclFileAttr->getAsUnsignedConstant().getValue(),
1061
23
            CU->getCompilationDir(),
1062
23
            DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1063
23
            Local.DeclFile);
1064
23
    }
1065
23
    if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
1066
23
      Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
1067
23
1068
23
    Result.push_back(Local);
1069
23
    return;
1070
23
  }
1071
9
1072
9
  if (Die.getTag() == DW_TAG_inlined_subroutine)
1073
3
    if (auto Origin =
1074
3
            Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1075
3
      Subprogram = Origin;
1076
9
1077
9
  for (auto Child : Die)
1078
29
    addLocalsForDie(CU, Subprogram, Child, Result);
1079
9
}
1080
1081
std::vector<DILocal>
1082
3
DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
1083
3
  std::vector<DILocal> Result;
1084
3
  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1085
3
  if (!CU)
1086
0
    return Result;
1087
3
1088
3
  DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
1089
3
  if (Subprogram.isValid())
1090
3
    addLocalsForDie(CU, Subprogram, Subprogram, Result);
1091
3
  return Result;
1092
3
}
1093
1094
DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
1095
947
                                               DILineInfoSpecifier Spec) {
1096
947
  DILineInfo Result;
1097
947
1098
947
  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1099
947
  if (!CU)
1100
242
    return Result;
1101
705
1102
705
  getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1103
705
                                        Result.FunctionName, Result.StartLine);
1104
705
  if (Spec.FLIKind != FileLineInfoKind::None) {
1105
705
    if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
1106
705
      LineTable->getFileLineInfoForAddress(
1107
705
          {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1108
705
          Spec.FLIKind, Result);
1109
705
    }
1110
705
  }
1111
705
  return Result;
1112
705
}
1113
1114
DILineInfoTable DWARFContext::getLineInfoForAddressRange(
1115
22
    object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
1116
22
  DILineInfoTable  Lines;
1117
22
  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1118
22
  if (!CU)
1119
0
    return Lines;
1120
22
1121
22
  std::string FunctionName = "<invalid>";
1122
22
  uint32_t StartLine = 0;
1123
22
  getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1124
22
                                        FunctionName, StartLine);
1125
22
1126
22
  // If the Specifier says we don't need FileLineInfo, just
1127
22
  // return the top-most function at the starting address.
1128
22
  if (Spec.FLIKind == FileLineInfoKind::None) {
1129
0
    DILineInfo Result;
1130
0
    Result.FunctionName = FunctionName;
1131
0
    Result.StartLine = StartLine;
1132
0
    Lines.push_back(std::make_pair(Address.Address, Result));
1133
0
    return Lines;
1134
0
  }
1135
22
1136
22
  const DWARFLineTable *LineTable = getLineTableForUnit(CU);
1137
22
1138
22
  // Get the index of row we're looking for in the line table.
1139
22
  std::vector<uint32_t> RowVector;
1140
22
  if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
1141
22
                                     Size, RowVector)) {
1142
0
    return Lines;
1143
0
  }
1144
22
1145
86
  
for (uint32_t RowIndex : RowVector)22
{
1146
86
    // Take file number and line/column from the row.
1147
86
    const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
1148
86
    DILineInfo Result;
1149
86
    LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1150
86
                                  Spec.FLIKind, Result.FileName);
1151
86
    Result.FunctionName = FunctionName;
1152
86
    Result.Line = Row.Line;
1153
86
    Result.Column = Row.Column;
1154
86
    Result.StartLine = StartLine;
1155
86
    Lines.push_back(std::make_pair(Row.Address.Address, Result));
1156
86
  }
1157
22
1158
22
  return Lines;
1159
22
}
1160
1161
DIInliningInfo
1162
DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
1163
172
                                        DILineInfoSpecifier Spec) {
1164
172
  DIInliningInfo InliningInfo;
1165
172
1166
172
  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1167
172
  if (!CU)
1168
21
    return InliningInfo;
1169
151
1170
151
  const DWARFLineTable *LineTable = nullptr;
1171
151
  SmallVector<DWARFDie, 4> InlinedChain;
1172
151
  CU->getInlinedChainForAddress(Address.Address, InlinedChain);
1173
151
  if (InlinedChain.size() == 0) {
1174
53
    // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1175
53
    // try to at least get file/line info from symbol table.
1176
53
    if (Spec.FLIKind != FileLineInfoKind::None) {
1177
53
      DILineInfo Frame;
1178
53
      LineTable = getLineTableForUnit(CU);
1179
53
      if (LineTable && LineTable->getFileLineInfoForAddress(
1180
53
                           {Address.Address, Address.SectionIndex},
1181
53
                           CU->getCompilationDir(), Spec.FLIKind, Frame))
1182
53
        InliningInfo.addFrame(Frame);
1183
53
    }
1184
53
    return InliningInfo;
1185
53
  }
1186
98
1187
98
  uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
1188
296
  for (uint32_t i = 0, n = InlinedChain.size(); i != n; 
i++198
) {
1189
198
    DWARFDie &FunctionDIE = InlinedChain[i];
1190
198
    DILineInfo Frame;
1191
198
    // Get function name if necessary.
1192
198
    if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
1193
163
      Frame.FunctionName = Name;
1194
198
    if (auto DeclLineResult = FunctionDIE.getDeclLine())
1195
185
      Frame.StartLine = DeclLineResult;
1196
198
    if (Spec.FLIKind != FileLineInfoKind::None) {
1197
198
      if (i == 0) {
1198
98
        // For the topmost frame, initialize the line table of this
1199
98
        // compile unit and fetch file/line info from it.
1200
98
        LineTable = getLineTableForUnit(CU);
1201
98
        // For the topmost routine, get file/line info from line table.
1202
98
        if (LineTable)
1203
98
          LineTable->getFileLineInfoForAddress(
1204
98
              {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1205
98
              Spec.FLIKind, Frame);
1206
100
      } else {
1207
100
        // Otherwise, use call file, call line and call column from
1208
100
        // previous DIE in inlined chain.
1209
100
        if (LineTable)
1210
100
          LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1211
100
                                        Spec.FLIKind, Frame.FileName);
1212
100
        Frame.Line = CallLine;
1213
100
        Frame.Column = CallColumn;
1214
100
        Frame.Discriminator = CallDiscriminator;
1215
100
      }
1216
198
      // Get call file/line/column of a current DIE.
1217
198
      if (i + 1 < n) {
1218
100
        FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1219
100
                                   CallDiscriminator);
1220
100
      }
1221
198
    }
1222
198
    InliningInfo.addFrame(Frame);
1223
198
  }
1224
98
  return InliningInfo;
1225
98
}
1226
1227
std::shared_ptr<DWARFContext>
1228
10
DWARFContext::getDWOContext(StringRef AbsolutePath) {
1229
10
  if (auto S = DWP.lock()) {
1230
0
    DWARFContext *Ctxt = S->Context.get();
1231
0
    return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1232
0
  }
1233
10
1234
10
  std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1235
10
1236
10
  if (auto S = Entry->lock()) {
1237
0
    DWARFContext *Ctxt = S->Context.get();
1238
0
    return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1239
0
  }
1240
10
1241
10
  Expected<OwningBinary<ObjectFile>> Obj = [&] {
1242
10
    if (!CheckedForDWP) {
1243
9
      SmallString<128> DWPName;
1244
9
      auto Obj = object::ObjectFile::createObjectFile(
1245
9
          this->DWPName.empty()
1246
9
              ? 
(DObj->getFileName() + ".dwp").toStringRef(DWPName)8
1247
9
              : 
StringRef(this->DWPName)1
);
1248
9
      if (Obj) {
1249
1
        Entry = &DWP;
1250
1
        return Obj;
1251
8
      } else {
1252
8
        CheckedForDWP = true;
1253
8
        // TODO: Should this error be handled (maybe in a high verbosity mode)
1254
8
        // before falling back to .dwo files?
1255
8
        consumeError(Obj.takeError());
1256
8
      }
1257
9
    }
1258
10
1259
10
    
return object::ObjectFile::createObjectFile(AbsolutePath)9
;
1260
10
  }();
1261
10
1262
10
  if (!Obj) {
1263
4
    // TODO: Actually report errors helpfully.
1264
4
    consumeError(Obj.takeError());
1265
4
    return nullptr;
1266
4
  }
1267
6
1268
6
  auto S = std::make_shared<DWOFile>();
1269
6
  S->File = std::move(Obj.get());
1270
6
  S->Context = DWARFContext::create(*S->File.getBinary());
1271
6
  *Entry = S;
1272
6
  auto *Ctxt = S->Context.get();
1273
6
  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1274
6
}
1275
1276
44
static Error createError(const Twine &Reason, llvm::Error E) {
1277
44
  return make_error<StringError>(Reason + toString(std::move(E)),
1278
44
                                 inconvertibleErrorCode());
1279
44
}
1280
1281
/// SymInfo contains information about symbol: it's address
1282
/// and section index which is -1LL for absolute symbols.
1283
struct SymInfo {
1284
  uint64_t Address;
1285
  uint64_t SectionIndex;
1286
};
1287
1288
/// Returns the address of symbol relocation used against and a section index.
1289
/// Used for futher relocations computation. Symbol's section load address is
1290
static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1291
                                       const RelocationRef &Reloc,
1292
                                       const LoadedObjectInfo *L,
1293
6.46k
                                       std::map<SymbolRef, SymInfo> &Cache) {
1294
6.46k
  SymInfo Ret = {0, (uint64_t)-1LL};
1295
6.46k
  object::section_iterator RSec = Obj.section_end();
1296
6.46k
  object::symbol_iterator Sym = Reloc.getSymbol();
1297
6.46k
1298
6.46k
  std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1299
6.46k
  // First calculate the address of the symbol or section as it appears
1300
6.46k
  // in the object file
1301
6.46k
  if (Sym != Obj.symbol_end()) {
1302
6.36k
    bool New;
1303
6.36k
    std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
1304
6.36k
    if (!New)
1305
3.21k
      return CacheIt->second;
1306
3.15k
1307
3.15k
    Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1308
3.15k
    if (!SymAddrOrErr)
1309
0
      return createError("failed to compute symbol address: ",
1310
0
                         SymAddrOrErr.takeError());
1311
3.15k
1312
3.15k
    // Also remember what section this symbol is in for later
1313
3.15k
    auto SectOrErr = Sym->getSection();
1314
3.15k
    if (!SectOrErr)
1315
0
      return createError("failed to get symbol section: ",
1316
0
                         SectOrErr.takeError());
1317
3.15k
1318
3.15k
    RSec = *SectOrErr;
1319
3.15k
    Ret.Address = *SymAddrOrErr;
1320
3.15k
  } else 
if (auto *101
MObj101
= dyn_cast<MachOObjectFile>(&Obj)) {
1321
13
    RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
1322
13
    Ret.Address = RSec->getAddress();
1323
13
  }
1324
6.46k
1325
6.46k
  
if (3.25k
RSec != Obj.section_end()3.25k
)
1326
3.13k
    Ret.SectionIndex = RSec->getIndex();
1327
3.25k
1328
3.25k
  // If we are given load addresses for the sections, we need to adjust:
1329
3.25k
  // SymAddr = (Address of Symbol Or Section in File) -
1330
3.25k
  //           (Address of Section in File) +
1331
3.25k
  //           (Load Address of Section)
1332
3.25k
  // RSec is now either the section being targeted or the section
1333
3.25k
  // containing the symbol being targeted. In either case,
1334
3.25k
  // we need to perform the same computation.
1335
3.25k
  if (L && 
RSec != Obj.section_end()31
)
1336
31
    if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
1337
24
      Ret.Address += SectionLoadAddress - RSec->getAddress();
1338
3.25k
1339
3.25k
  if (CacheIt != Cache.end())
1340
3.15k
    CacheIt->second = Ret;
1341
3.25k
1342
3.25k
  return Ret;
1343
6.46k
}
1344
1345
static bool isRelocScattered(const object::ObjectFile &Obj,
1346
6.46k
                             const RelocationRef &Reloc) {
1347
6.46k
  const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1348
6.46k
  if (!MachObj)
1349
6.45k
    return false;
1350
13
  // MachO also has relocations that point to sections and
1351
13
  // scattered relocations.
1352
13
  auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1353
13
  return MachObj->isRelocationScattered(RelocInfo);
1354
13
}
1355
1356
41
ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
1357
41
  WithColor::error() << toString(std::move(E)) << '\n';
1358
41
  return ErrorPolicy::Continue;
1359
41
}
1360
1361
namespace {
1362
struct DWARFSectionMap final : public DWARFSection {
1363
  RelocAddrMap Relocs;
1364
};
1365
1366
class DWARFObjInMemory final : public DWARFObject {
1367
  bool IsLittleEndian;
1368
  uint8_t AddressSize;
1369
  StringRef FileName;
1370
  const object::ObjectFile *Obj = nullptr;
1371
  std::vector<SectionName> SectionNames;
1372
1373
  using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1374
                                   std::map<object::SectionRef, unsigned>>;
1375
1376
  InfoSectionMap InfoSections;
1377
  InfoSectionMap TypesSections;
1378
  InfoSectionMap InfoDWOSections;
1379
  InfoSectionMap TypesDWOSections;
1380
1381
  DWARFSectionMap LocSection;
1382
  DWARFSectionMap LocListsSection;
1383
  DWARFSectionMap LineSection;
1384
  DWARFSectionMap RangeSection;
1385
  DWARFSectionMap RnglistsSection;
1386
  DWARFSectionMap StringOffsetSection;
1387
  DWARFSectionMap LineDWOSection;
1388
  DWARFSectionMap DebugFrameSection;
1389
  DWARFSectionMap EHFrameSection;
1390
  DWARFSectionMap LocDWOSection;
1391
  DWARFSectionMap StringOffsetDWOSection;
1392
  DWARFSectionMap RangeDWOSection;
1393
  DWARFSectionMap RnglistsDWOSection;
1394
  DWARFSectionMap AddrSection;
1395
  DWARFSectionMap AppleNamesSection;
1396
  DWARFSectionMap AppleTypesSection;
1397
  DWARFSectionMap AppleNamespacesSection;
1398
  DWARFSectionMap AppleObjCSection;
1399
  DWARFSectionMap DebugNamesSection;
1400
  DWARFSectionMap PubNamesSection;
1401
  DWARFSectionMap PubTypesSection;
1402
  DWARFSectionMap GnuPubNamesSection;
1403
  DWARFSectionMap GnuPubTypesSection;
1404
1405
21.1k
  DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1406
21.1k
    return StringSwitch<DWARFSectionMap *>(Name)
1407
21.1k
        .Case("debug_loc", &LocSection)
1408
21.1k
        .Case("debug_loclists", &LocListsSection)
1409
21.1k
        .Case("debug_line", &LineSection)
1410
21.1k
        .Case("debug_frame", &DebugFrameSection)
1411
21.1k
        .Case("eh_frame", &EHFrameSection)
1412
21.1k
        .Case("debug_str_offsets", &StringOffsetSection)
1413
21.1k
        .Case("debug_ranges", &RangeSection)
1414
21.1k
        .Case("debug_rnglists", &RnglistsSection)
1415
21.1k
        .Case("debug_loc.dwo", &LocDWOSection)
1416
21.1k
        .Case("debug_line.dwo", &LineDWOSection)
1417
21.1k
        .Case("debug_names", &DebugNamesSection)
1418
21.1k
        .Case("debug_rnglists.dwo", &RnglistsDWOSection)
1419
21.1k
        .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1420
21.1k
        .Case("debug_addr", &AddrSection)
1421
21.1k
        .Case("apple_names", &AppleNamesSection)
1422
21.1k
        .Case("debug_pubnames", &PubNamesSection)
1423
21.1k
        .Case("debug_pubtypes", &PubTypesSection)
1424
21.1k
        .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1425
21.1k
        .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1426
21.1k
        .Case("apple_types", &AppleTypesSection)
1427
21.1k
        .Case("apple_namespaces", &AppleNamespacesSection)
1428
21.1k
        .Case("apple_namespac", &AppleNamespacesSection)
1429
21.1k
        .Case("apple_objc", &AppleObjCSection)
1430
21.1k
        .Default(nullptr);
1431
21.1k
  }
1432
1433
  StringRef AbbrevSection;
1434
  StringRef ARangeSection;
1435
  StringRef StringSection;
1436
  StringRef MacinfoSection;
1437
  StringRef AbbrevDWOSection;
1438
  StringRef StringDWOSection;
1439
  StringRef CUIndexSection;
1440
  StringRef GdbIndexSection;
1441
  StringRef TUIndexSection;
1442
  StringRef LineStringSection;
1443
1444
  // A deque holding section data whose iterators are not invalidated when
1445
  // new decompressed sections are inserted at the end.
1446
  std::deque<SmallString<0>> UncompressedSections;
1447
1448
19.2k
  StringRef *mapSectionToMember(StringRef Name) {
1449
19.2k
    if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1450
6.18k
      return &Sec->Data;
1451
13.0k
    return StringSwitch<StringRef *>(Name)
1452
13.0k
        .Case("debug_abbrev", &AbbrevSection)
1453
13.0k
        .Case("debug_aranges", &ARangeSection)
1454
13.0k
        .Case("debug_str", &StringSection)
1455
13.0k
        .Case("debug_macinfo", &MacinfoSection)
1456
13.0k
        .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1457
13.0k
        .Case("debug_str.dwo", &StringDWOSection)
1458
13.0k
        .Case("debug_cu_index", &CUIndexSection)
1459
13.0k
        .Case("debug_tu_index", &TUIndexSection)
1460
13.0k
        .Case("gdb_index", &GdbIndexSection)
1461
13.0k
        .Case("debug_line_str", &LineStringSection)
1462
13.0k
        // Any more debug info sections go here.
1463
13.0k
        .Default(nullptr);
1464
13.0k
  }
1465
1466
  /// If Sec is compressed section, decompresses and updates its contents
1467
  /// provided by Data. Otherwise leaves it unchanged.
1468
  Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1469
19.1k
                        StringRef &Data) {
1470
19.1k
    if (!Decompressor::isCompressed(Sec))
1471
19.1k
      return Error::success();
1472
42
1473
42
    Expected<Decompressor> Decompressor =
1474
42
        Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1475
42
    if (!Decompressor)
1476
4
      return Decompressor.takeError();
1477
38
1478
38
    SmallString<0> Out;
1479
38
    if (auto Err = Decompressor->resizeAndDecompress(Out))
1480
1
      return Err;
1481
37
1482
37
    UncompressedSections.push_back(std::move(Out));
1483
37
    Data = UncompressedSections.back();
1484
37
1485
37
    return Error::success();
1486
37
  }
1487
1488
public:
1489
  DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1490
                   uint8_t AddrSize, bool IsLittleEndian)
1491
19
      : IsLittleEndian(IsLittleEndian) {
1492
61
    for (const auto &SecIt : Sections) {
1493
61
      if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1494
42
        *SectionData = SecIt.second->getBuffer();
1495
19
      else if (SecIt.first() == "debug_info")
1496
19
        // Find debug_info and debug_types data by section rather than name as
1497
19
        // there are multiple, comdat grouped, of these sections.
1498
19
        InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1499
0
      else if (SecIt.first() == "debug_info.dwo")
1500
0
        InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1501
0
      else if (SecIt.first() == "debug_types")
1502
0
        TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1503
0
      else if (SecIt.first() == "debug_types.dwo")
1504
0
        TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1505
61
    }
1506
19
  }
1507
  DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1508
                   function_ref<ErrorPolicy(Error)> HandleError)
1509
      : IsLittleEndian(Obj.isLittleEndian()),
1510
        AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1511
1.40k
        Obj(&Obj) {
1512
1.40k
1513
1.40k
    StringMap<unsigned> SectionAmountMap;
1514
19.9k
    for (const SectionRef &Section : Obj.sections()) {
1515
19.9k
      StringRef Name;
1516
19.9k
      Section.getName(Name);
1517
19.9k
      ++SectionAmountMap[Name];
1518
19.9k
      SectionNames.push_back({ Name, true });
1519
19.9k
1520
19.9k
      // Skip BSS and Virtual sections, they aren't interesting.
1521
19.9k
      if (Section.isBSS() || 
Section.isVirtual()19.6k
)
1522
360
        continue;
1523
19.6k
1524
19.6k
      // Skip sections stripped by dsymutil.
1525
19.6k
      if (Section.isStripped())
1526
427
        continue;
1527
19.1k
1528
19.1k
      StringRef Data;
1529
19.1k
      section_iterator RelocatedSection = Section.getRelocatedSection();
1530
19.1k
      // Try to obtain an already relocated version of this section.
1531
19.1k
      // Else use the unrelocated section from the object file. We'll have to
1532
19.1k
      // apply relocations ourselves later.
1533
19.1k
      if (!L || 
!L->getLoadedSectionContents(*RelocatedSection, Data)76
) {
1534
19.1k
        Expected<StringRef> E = Section.getContents();
1535
19.1k
        if (E)
1536
19.1k
          Data = *E;
1537
16
        else
1538
16
          // maybeDecompress below will error.
1539
16
          consumeError(E.takeError());
1540
19.1k
      }
1541
19.1k
1542
19.1k
      if (auto Err = maybeDecompress(Section, Name, Data)) {
1543
5
        ErrorPolicy EP = HandleError(createError(
1544
5
            "failed to decompress '" + Name + "', ", std::move(Err)));
1545
5
        if (EP == ErrorPolicy::Halt)
1546
1
          return;
1547
4
        continue;
1548
4
      }
1549
19.1k
1550
19.1k
      // Compressed sections names in GNU style starts from ".z",
1551
19.1k
      // at this point section is decompressed and we drop compression prefix.
1552
19.1k
      Name = Name.substr(
1553
19.1k
          Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1554
19.1k
1555
19.1k
      // Map platform specific debug section names to DWARF standard section
1556
19.1k
      // names.
1557
19.1k
      Name = Obj.mapDebugSectionName(Name);
1558
19.1k
1559
19.1k
      if (StringRef *SectionData = mapSectionToMember(Name)) {
1560
9.71k
        *SectionData = Data;
1561
9.71k
        if (Name == "debug_ranges") {
1562
389
          // FIXME: Use the other dwo range section when we emit it.
1563
389
          RangeDWOSection.Data = Data;
1564
389
        }
1565
9.71k
      } else 
if (9.45k
Name == "debug_info"9.45k
) {
1566
1.23k
        // Find debug_info and debug_types data by section rather than name as
1567
1.23k
        // there are multiple, comdat grouped, of these sections.
1568
1.23k
        InfoSections[Section].Data = Data;
1569
8.22k
      } else if (Name == "debug_info.dwo") {
1570
63
        InfoDWOSections[Section].Data = Data;
1571
8.15k
      } else if (Name == "debug_types") {
1572
37
        TypesSections[Section].Data = Data;
1573
8.12k
      } else if (Name == "debug_types.dwo") {
1574
12
        TypesDWOSections[Section].Data = Data;
1575
12
      }
1576
19.1k
1577
19.1k
      if (RelocatedSection == Obj.section_end())
1578
8.97k
        continue;
1579
10.1k
1580
10.1k
      StringRef RelSecName;
1581
10.1k
      StringRef RelSecData;
1582
10.1k
      RelocatedSection->getName(RelSecName);
1583
10.1k
1584
10.1k
      // If the section we're relocating was relocated already by the JIT,
1585
10.1k
      // then we used the relocated version above, so we do not need to process
1586
10.1k
      // relocations for it now.
1587
10.1k
      if (L && 
L->getLoadedSectionContents(*RelocatedSection, RelSecData)47
)
1588
0
        continue;
1589
10.1k
1590
10.1k
      // In Mach-o files, the relocations do not need to be applied if
1591
10.1k
      // there is no load offset to apply. The value read at the
1592
10.1k
      // relocation point already factors in the section address
1593
10.1k
      // (actually applying the relocations will produce wrong results
1594
10.1k
      // as the section address will be added twice).
1595
10.1k
      if (!L && 
isa<MachOObjectFile>(&Obj)10.1k
)
1596
8.29k
        continue;
1597
1.90k
1598
1.90k
      RelSecName = RelSecName.substr(
1599
1.90k
          RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1600
1.90k
1601
1.90k
      // TODO: Add support for relocations in other sections as needed.
1602
1.90k
      // Record relocations for the debug_info and debug_line sections.
1603
1.90k
      DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1604
1.90k
      RelocAddrMap *Map = Sec ? 
&Sec->Relocs1.09k
:
nullptr815
;
1605
1.90k
      if (!Map) {
1606
815
        // Find debug_info and debug_types relocs by section rather than name
1607
815
        // as there are multiple, comdat grouped, of these sections.
1608
815
        if (RelSecName == "debug_info")
1609
400
          Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1610
400
                     .Relocs;
1611
415
        else if (RelSecName == "debug_info.dwo")
1612
8
          Map = &static_cast<DWARFSectionMap &>(
1613
8
                     InfoDWOSections[*RelocatedSection])
1614
8
                     .Relocs;
1615
407
        else if (RelSecName == "debug_types")
1616
36
          Map =
1617
36
              &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1618
36
                   .Relocs;
1619
371
        else if (RelSecName == "debug_types.dwo")
1620
4
          Map = &static_cast<DWARFSectionMap &>(
1621
4
                     TypesDWOSections[*RelocatedSection])
1622
4
                     .Relocs;
1623
367
        else
1624
367
          continue;
1625
1.54k
      }
1626
1.54k
1627
1.54k
      if (Section.relocation_begin() == Section.relocation_end())
1628
42
        continue;
1629
1.49k
1630
1.49k
      // Symbol to [address, section index] cache mapping.
1631
1.49k
      std::map<SymbolRef, SymInfo> AddrCache;
1632
1.49k
      bool (*Supports)(uint64_t);
1633
1.49k
      RelocationResolver Resolver;
1634
1.49k
      std::tie(Supports, Resolver) = getRelocationResolver(Obj);
1635
6.46k
      for (const RelocationRef &Reloc : Section.relocations()) {
1636
6.46k
        // FIXME: it's not clear how to correctly handle scattered
1637
6.46k
        // relocations.
1638
6.46k
        if (isRelocScattered(Obj, Reloc))
1639
0
          continue;
1640
6.46k
1641
6.46k
        Expected<SymInfo> SymInfoOrErr =
1642
6.46k
            getSymbolInfo(Obj, Reloc, L, AddrCache);
1643
6.46k
        if (!SymInfoOrErr) {
1644
0
          if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1645
0
            return;
1646
0
          continue;
1647
0
        }
1648
6.46k
1649
6.46k
        // Check if Resolver can handle this relocation type early so as not to
1650
6.46k
        // handle invalid cases in DWARFDataExtractor.
1651
6.46k
        //
1652
6.46k
        // TODO Don't store Resolver in every RelocAddrEntry.
1653
6.46k
        if (Supports && 
Supports(Reloc.getType())6.45k
) {
1654
6.42k
          auto I = Map->try_emplace(
1655
6.42k
              Reloc.getOffset(),
1656
6.42k
              RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
1657
6.42k
                             SymInfoOrErr->Address,
1658
6.42k
                             Optional<object::RelocationRef>(), 0, Resolver});
1659
6.42k
          // If we didn't successfully insert that's because we already had a
1660
6.42k
          // relocation for that offset. Store it as a second relocation in the
1661
6.42k
          // same RelocAddrEntry instead.
1662
6.42k
          if (!I.second) {
1663
35
            RelocAddrEntry &entry = I.first->getSecond();
1664
35
            if (entry.Reloc2) {
1665
0
              ErrorPolicy EP = HandleError(createError(
1666
0
                  "At most two relocations per offset are supported"));
1667
0
              if (EP == ErrorPolicy::Halt)
1668
0
                return;
1669
35
            }
1670
35
            entry.Reloc2 = Reloc;
1671
35
            entry.SymbolValue2 = SymInfoOrErr->Address;
1672
35
          }
1673
6.42k
        } else {
1674
39
          SmallString<32> Type;
1675
39
          Reloc.getTypeName(Type);
1676
39
          ErrorPolicy EP = HandleError(
1677
39
              createError("failed to compute relocation: " + Type + ", ",
1678
39
                          errorCodeToError(object_error::parse_failed)));
1679
39
          if (EP == ErrorPolicy::Halt)
1680
0
            return;
1681
39
        }
1682
6.46k
      }
1683
1.49k
    }
1684
1.40k
1685
1.40k
    
for (SectionName &S : SectionNames)1.39k
1686
19.9k
      if (SectionAmountMap[S.Name] > 1)
1687
193
        S.IsNameUnique = false;
1688
1.39k
  }
1689
1690
  Optional<RelocAddrEntry> find(const DWARFSection &S,
1691
62.4k
                                uint64_t Pos) const override {
1692
62.4k
    auto &Sec = static_cast<const DWARFSectionMap &>(S);
1693
62.4k
    RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1694
62.4k
    if (AI == Sec.Relocs.end())
1695
53.8k
      return None;
1696
8.60k
    return AI->second;
1697
8.60k
  }
1698
1699
993
  const object::ObjectFile *getFile() const override { return Obj; }
1700
1701
369
  ArrayRef<SectionName> getSectionNames() const override {
1702
369
    return SectionNames;
1703
369
  }
1704
1705
9.57k
  bool isLittleEndian() const override { return IsLittleEndian; }
1706
898
  StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1707
844
  const DWARFSection &getLineDWOSection() const override {
1708
844
    return LineDWOSection;
1709
844
  }
1710
831
  const DWARFSection &getLocDWOSection() const override {
1711
831
    return LocDWOSection;
1712
831
  }
1713
884
  StringRef getStringDWOSection() const override { return StringDWOSection; }
1714
854
  const DWARFSection &getStringOffsetDWOSection() const override {
1715
854
    return StringOffsetDWOSection;
1716
854
  }
1717
73
  const DWARFSection &getRangeDWOSection() const override {
1718
73
    return RangeDWOSection;
1719
73
  }
1720
779
  const DWARFSection &getRnglistsDWOSection() const override {
1721
779
    return RnglistsDWOSection;
1722
779
  }
1723
2.05k
  const DWARFSection &getAddrSection() const override { return AddrSection; }
1724
808
  StringRef getCUIndexSection() const override { return CUIndexSection; }
1725
765
  StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1726
764
  StringRef getTUIndexSection() const override { return TUIndexSection; }
1727
1728
  // DWARF v5
1729
2.11k
  const DWARFSection &getStringOffsetSection() const override {
1730
2.11k
    return StringOffsetSection;
1731
2.11k
  }
1732
1.16k
  StringRef getLineStringSection() const override { return LineStringSection; }
1733
1734
  // Sections for DWARF5 split dwarf proposal.
1735
  void forEachInfoDWOSections(
1736
822
      function_ref<void(const DWARFSection &)> F) const override {
1737
822
    for (auto &P : InfoDWOSections)
1738
62
      F(P.second);
1739
822
  }
1740
  void forEachTypesDWOSections(
1741
822
      function_ref<void(const DWARFSection &)> F) const override {
1742
822
    for (auto &P : TypesDWOSections)
1743
11
      F(P.second);
1744
822
  }
1745
1746
2.02k
  StringRef getAbbrevSection() const override { return AbbrevSection; }
1747
2.13k
  const DWARFSection &getLocSection() const override { return LocSection; }
1748
764
  const DWARFSection &getLoclistsSection() const override { return LocListsSection; }
1749
1.03k
  StringRef getARangeSection() const override { return ARangeSection; }
1750
965
  const DWARFSection &getDebugFrameSection() const override {
1751
965
    return DebugFrameSection;
1752
965
  }
1753
855
  const DWARFSection &getEHFrameSection() const override {
1754
855
    return EHFrameSection;
1755
855
  }
1756
2.82k
  const DWARFSection &getLineSection() const override { return LineSection; }
1757
3.46k
  StringRef getStringSection() const override { return StringSection; }
1758
2.28k
  const DWARFSection &getRangeSection() const override { return RangeSection; }
1759
878
  const DWARFSection &getRnglistsSection() const override {
1760
878
    return RnglistsSection;
1761
878
  }
1762
214
  StringRef getMacinfoSection() const override { return MacinfoSection; }
1763
864
  const DWARFSection &getPubNamesSection() const override { return PubNamesSection; }
1764
856
  const DWARFSection &getPubTypesSection() const override { return PubTypesSection; }
1765
792
  const DWARFSection &getGnuPubNamesSection() const override {
1766
792
    return GnuPubNamesSection;
1767
792
  }
1768
791
  const DWARFSection &getGnuPubTypesSection() const override {
1769
791
    return GnuPubTypesSection;
1770
791
  }
1771
1.14k
  const DWARFSection &getAppleNamesSection() const override {
1772
1.14k
    return AppleNamesSection;
1773
1.14k
  }
1774
969
  const DWARFSection &getAppleTypesSection() const override {
1775
969
    return AppleTypesSection;
1776
969
  }
1777
966
  const DWARFSection &getAppleNamespacesSection() const override {
1778
966
    return AppleNamespacesSection;
1779
966
  }
1780
1.05k
  const DWARFSection &getAppleObjCSection() const override {
1781
1.05k
    return AppleObjCSection;
1782
1.05k
  }
1783
1.09k
  const DWARFSection &getDebugNamesSection() const override {
1784
1.09k
    return DebugNamesSection;
1785
1.09k
  }
1786
1787
762
  StringRef getFileName() const override { return FileName; }
1788
562
  uint8_t getAddressSize() const override { return AddressSize; }
1789
  void forEachInfoSections(
1790
1.54k
      function_ref<void(const DWARFSection &)> F) const override {
1791
1.54k
    for (auto &P : InfoSections)
1792
1.22k
      F(P.second);
1793
1.54k
  }
1794
  void forEachTypesSections(
1795
1.54k
      function_ref<void(const DWARFSection &)> F) const override {
1796
1.54k
    for (auto &P : TypesSections)
1797
38
      F(P.second);
1798
1.54k
  }
1799
};
1800
} // namespace
1801
1802
std::unique_ptr<DWARFContext>
1803
DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1804
                     function_ref<ErrorPolicy(Error)> HandleError,
1805
1.40k
                     std::string DWPName) {
1806
1.40k
  auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
1807
1.40k
  return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
1808
1.40k
}
1809
1810
std::unique_ptr<DWARFContext>
1811
DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1812
19
                     uint8_t AddrSize, bool isLittleEndian) {
1813
19
  auto DObj =
1814
19
      llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1815
19
  return llvm::make_unique<DWARFContext>(std::move(DObj), "");
1816
19
}
1817
1818
796
Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1819
796
  // Detect the architecture from the object file. We usually don't need OS
1820
796
  // info to lookup a target and create register info.
1821
796
  Triple TT;
1822
796
  TT.setArch(Triple::ArchType(Obj.getArch()));
1823
796
  TT.setVendor(Triple::UnknownVendor);
1824
796
  TT.setOS(Triple::UnknownOS);
1825
796
  std::string TargetLookupError;
1826
796
  const Target *TheTarget =
1827
796
      TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1828
796
  if (!TargetLookupError.empty())
1829
2
    return createStringError(errc::invalid_argument,
1830
2
                             TargetLookupError.c_str());
1831
794
  RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1832
794
  return Error::success();
1833
794
}
1834
1835
96
uint8_t DWARFContext::getCUAddrSize() {
1836
96
  // In theory, different compile units may have different address byte
1837
96
  // sizes, but for simplicity we just use the address byte size of the
1838
96
  // last compile unit. In practice the address size field is repeated across
1839
96
  // various DWARF headers (at least in version 5) to make it easier to dump
1840
96
  // them independently, not to enable varying the address size.
1841
96
  uint8_t Addr = 0;
1842
96
  for (const auto &CU : compile_units()) {
1843
87
    Addr = CU->getAddressByteSize();
1844
87
    break;
1845
87
  }
1846
96
  return Addr;
1847
96
}
1848
1849
243
void DWARFContext::dumpWarning(Error Warning) {
1850
243
  handleAllErrors(std::move(Warning), [](ErrorInfoBase &Info) {
1851
76
      WithColor::warning() << Info.message() << '\n';
1852
76
  });
1853
243
}