1 //===-- DWARFUnit.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 "DWARFUnit.h"
10
11 #include "lldb/Core/Module.h"
12 #include "lldb/Host/StringConvert.h"
13 #include "lldb/Symbol/ObjectFile.h"
14 #include "lldb/Utility/LLDBAssert.h"
15 #include "lldb/Utility/StreamString.h"
16 #include "lldb/Utility/Timer.h"
17 #include "llvm/Object/Error.h"
18
19 #include "DWARFCompileUnit.h"
20 #include "DWARFDebugAranges.h"
21 #include "DWARFDebugInfo.h"
22 #include "DWARFTypeUnit.h"
23 #include "LogChannelDWARF.h"
24 #include "SymbolFileDWARFDwo.h"
25
26 using namespace lldb;
27 using namespace lldb_private;
28 using namespace std;
29
30 extern int g_verbose;
31
DWARFUnit(SymbolFileDWARF & dwarf,lldb::user_id_t uid,const DWARFUnitHeader & header,const DWARFAbbreviationDeclarationSet & abbrevs,DIERef::Section section,bool is_dwo)32 DWARFUnit::DWARFUnit(SymbolFileDWARF &dwarf, lldb::user_id_t uid,
33 const DWARFUnitHeader &header,
34 const DWARFAbbreviationDeclarationSet &abbrevs,
35 DIERef::Section section, bool is_dwo)
36 : UserID(uid), m_dwarf(dwarf), m_header(header), m_abbrevs(&abbrevs),
37 m_cancel_scopes(false), m_section(section), m_is_dwo(is_dwo),
38 m_dwo_id(header.GetDWOId()) {}
39
40 DWARFUnit::~DWARFUnit() = default;
41
42 // Parses first DIE of a compile unit.
ExtractUnitDIEIfNeeded()43 void DWARFUnit::ExtractUnitDIEIfNeeded() {
44 {
45 llvm::sys::ScopedReader lock(m_first_die_mutex);
46 if (m_first_die)
47 return; // Already parsed
48 }
49 llvm::sys::ScopedWriter lock(m_first_die_mutex);
50 if (m_first_die)
51 return; // Already parsed
52
53 LLDB_SCOPED_TIMERF("%8.8x: DWARFUnit::ExtractUnitDIEIfNeeded()", GetOffset());
54
55 // Set the offset to that of the first DIE and calculate the start of the
56 // next compilation unit header.
57 lldb::offset_t offset = GetFirstDIEOffset();
58
59 // We are in our compile unit, parse starting at the offset we were told to
60 // parse
61 const DWARFDataExtractor &data = GetData();
62 if (offset < GetNextUnitOffset() &&
63 m_first_die.Extract(data, this, &offset)) {
64 AddUnitDIE(m_first_die);
65 return;
66 }
67 }
68
69 // Parses a compile unit and indexes its DIEs if it hasn't already been done.
70 // It will leave this compile unit extracted forever.
ExtractDIEsIfNeeded()71 void DWARFUnit::ExtractDIEsIfNeeded() {
72 m_cancel_scopes = true;
73
74 {
75 llvm::sys::ScopedReader lock(m_die_array_mutex);
76 if (!m_die_array.empty())
77 return; // Already parsed
78 }
79 llvm::sys::ScopedWriter lock(m_die_array_mutex);
80 if (!m_die_array.empty())
81 return; // Already parsed
82
83 ExtractDIEsRWLocked();
84 }
85
86 // Parses a compile unit and indexes its DIEs if it hasn't already been done.
87 // It will clear this compile unit after returned instance gets out of scope,
88 // no other ScopedExtractDIEs instance is running for this compile unit
89 // and no ExtractDIEsIfNeeded() has been executed during this ScopedExtractDIEs
90 // lifetime.
ExtractDIEsScoped()91 DWARFUnit::ScopedExtractDIEs DWARFUnit::ExtractDIEsScoped() {
92 ScopedExtractDIEs scoped(*this);
93
94 {
95 llvm::sys::ScopedReader lock(m_die_array_mutex);
96 if (!m_die_array.empty())
97 return scoped; // Already parsed
98 }
99 llvm::sys::ScopedWriter lock(m_die_array_mutex);
100 if (!m_die_array.empty())
101 return scoped; // Already parsed
102
103 // Otherwise m_die_array would be already populated.
104 lldbassert(!m_cancel_scopes);
105
106 ExtractDIEsRWLocked();
107 scoped.m_clear_dies = true;
108 return scoped;
109 }
110
ScopedExtractDIEs(DWARFUnit & cu)111 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(DWARFUnit &cu) : m_cu(&cu) {
112 m_cu->m_die_array_scoped_mutex.lock_shared();
113 }
114
~ScopedExtractDIEs()115 DWARFUnit::ScopedExtractDIEs::~ScopedExtractDIEs() {
116 if (!m_cu)
117 return;
118 m_cu->m_die_array_scoped_mutex.unlock_shared();
119 if (!m_clear_dies || m_cu->m_cancel_scopes)
120 return;
121 // Be sure no other ScopedExtractDIEs is running anymore.
122 llvm::sys::ScopedWriter lock_scoped(m_cu->m_die_array_scoped_mutex);
123 llvm::sys::ScopedWriter lock(m_cu->m_die_array_mutex);
124 if (m_cu->m_cancel_scopes)
125 return;
126 m_cu->ClearDIEsRWLocked();
127 }
128
ScopedExtractDIEs(ScopedExtractDIEs && rhs)129 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(ScopedExtractDIEs &&rhs)
130 : m_cu(rhs.m_cu), m_clear_dies(rhs.m_clear_dies) {
131 rhs.m_cu = nullptr;
132 }
133
operator =(DWARFUnit::ScopedExtractDIEs && rhs)134 DWARFUnit::ScopedExtractDIEs &DWARFUnit::ScopedExtractDIEs::operator=(
135 DWARFUnit::ScopedExtractDIEs &&rhs) {
136 m_cu = rhs.m_cu;
137 rhs.m_cu = nullptr;
138 m_clear_dies = rhs.m_clear_dies;
139 return *this;
140 }
141
142 // Parses a compile unit and indexes its DIEs, m_die_array_mutex must be
143 // held R/W and m_die_array must be empty.
ExtractDIEsRWLocked()144 void DWARFUnit::ExtractDIEsRWLocked() {
145 llvm::sys::ScopedWriter first_die_lock(m_first_die_mutex);
146
147 LLDB_SCOPED_TIMERF("%8.8x: DWARFUnit::ExtractDIEsIfNeeded()", GetOffset());
148
149 // Set the offset to that of the first DIE and calculate the start of the
150 // next compilation unit header.
151 lldb::offset_t offset = GetFirstDIEOffset();
152 lldb::offset_t next_cu_offset = GetNextUnitOffset();
153
154 DWARFDebugInfoEntry die;
155
156 uint32_t depth = 0;
157 // We are in our compile unit, parse starting at the offset we were told to
158 // parse
159 const DWARFDataExtractor &data = GetData();
160 std::vector<uint32_t> die_index_stack;
161 die_index_stack.reserve(32);
162 die_index_stack.push_back(0);
163 bool prev_die_had_children = false;
164 while (offset < next_cu_offset && die.Extract(data, this, &offset)) {
165 const bool null_die = die.IsNULL();
166 if (depth == 0) {
167 assert(m_die_array.empty() && "Compile unit DIE already added");
168
169 // The average bytes per DIE entry has been seen to be around 14-20 so
170 // lets pre-reserve half of that since we are now stripping the NULL
171 // tags.
172
173 // Only reserve the memory if we are adding children of the main
174 // compile unit DIE. The compile unit DIE is always the first entry, so
175 // if our size is 1, then we are adding the first compile unit child
176 // DIE and should reserve the memory.
177 m_die_array.reserve(GetDebugInfoSize() / 24);
178 m_die_array.push_back(die);
179
180 if (!m_first_die)
181 AddUnitDIE(m_die_array.front());
182
183 // With -fsplit-dwarf-inlining, clang will emit non-empty skeleton compile
184 // units. We are not able to access these DIE *and* the dwo file
185 // simultaneously. We also don't need to do that as the dwo file will
186 // contain a superset of information. So, we don't even attempt to parse
187 // any remaining DIEs.
188 if (m_dwo) {
189 m_die_array.front().SetHasChildren(false);
190 break;
191 }
192
193 } else {
194 if (null_die) {
195 if (prev_die_had_children) {
196 // This will only happen if a DIE says is has children but all it
197 // contains is a NULL tag. Since we are removing the NULL DIEs from
198 // the list (saves up to 25% in C++ code), we need a way to let the
199 // DIE know that it actually doesn't have children.
200 if (!m_die_array.empty())
201 m_die_array.back().SetHasChildren(false);
202 }
203 } else {
204 die.SetParentIndex(m_die_array.size() - die_index_stack[depth - 1]);
205
206 if (die_index_stack.back())
207 m_die_array[die_index_stack.back()].SetSiblingIndex(
208 m_die_array.size() - die_index_stack.back());
209
210 // Only push the DIE if it isn't a NULL DIE
211 m_die_array.push_back(die);
212 }
213 }
214
215 if (null_die) {
216 // NULL DIE.
217 if (!die_index_stack.empty())
218 die_index_stack.pop_back();
219
220 if (depth > 0)
221 --depth;
222 prev_die_had_children = false;
223 } else {
224 die_index_stack.back() = m_die_array.size() - 1;
225 // Normal DIE
226 const bool die_has_children = die.HasChildren();
227 if (die_has_children) {
228 die_index_stack.push_back(0);
229 ++depth;
230 }
231 prev_die_had_children = die_has_children;
232 }
233
234 if (depth == 0)
235 break; // We are done with this compile unit!
236 }
237
238 if (!m_die_array.empty()) {
239 if (m_first_die) {
240 // Only needed for the assertion.
241 m_first_die.SetHasChildren(m_die_array.front().HasChildren());
242 lldbassert(m_first_die == m_die_array.front());
243 }
244 m_first_die = m_die_array.front();
245 }
246
247 m_die_array.shrink_to_fit();
248
249 if (m_dwo)
250 m_dwo->ExtractDIEsIfNeeded();
251 }
252
253 // This is used when a split dwarf is enabled.
254 // A skeleton compilation unit may contain the DW_AT_str_offsets_base attribute
255 // that points to the first string offset of the CU contribution to the
256 // .debug_str_offsets. At the same time, the corresponding split debug unit also
257 // may use DW_FORM_strx* forms pointing to its own .debug_str_offsets.dwo and
258 // for that case, we should find the offset (skip the section header).
SetDwoStrOffsetsBase()259 void DWARFUnit::SetDwoStrOffsetsBase() {
260 lldb::offset_t baseOffset = 0;
261
262 if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
263 if (const auto *contribution =
264 entry->getContribution(llvm::DW_SECT_STR_OFFSETS))
265 baseOffset = contribution->Offset;
266 else
267 return;
268 }
269
270 if (GetVersion() >= 5) {
271 const DWARFDataExtractor &strOffsets =
272 GetSymbolFileDWARF().GetDWARFContext().getOrLoadStrOffsetsData();
273 uint64_t length = strOffsets.GetU32(&baseOffset);
274 if (length == 0xffffffff)
275 length = strOffsets.GetU64(&baseOffset);
276
277 // Check version.
278 if (strOffsets.GetU16(&baseOffset) < 5)
279 return;
280
281 // Skip padding.
282 baseOffset += 2;
283 }
284
285 SetStrOffsetsBase(baseOffset);
286 }
287
GetDWOId()288 uint64_t DWARFUnit::GetDWOId() {
289 ExtractUnitDIEIfNeeded();
290 return m_dwo_id;
291 }
292
293 // m_die_array_mutex must be already held as read/write.
AddUnitDIE(const DWARFDebugInfoEntry & cu_die)294 void DWARFUnit::AddUnitDIE(const DWARFDebugInfoEntry &cu_die) {
295 llvm::Optional<uint64_t> addr_base, gnu_addr_base, ranges_base,
296 gnu_ranges_base;
297
298 DWARFAttributes attributes;
299 size_t num_attributes = cu_die.GetAttributes(this, attributes);
300
301 // Extract DW_AT_addr_base first, as other attributes may need it.
302 for (size_t i = 0; i < num_attributes; ++i) {
303 if (attributes.AttributeAtIndex(i) != DW_AT_addr_base)
304 continue;
305 DWARFFormValue form_value;
306 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
307 addr_base = form_value.Unsigned();
308 SetAddrBase(*addr_base);
309 break;
310 }
311 }
312
313 for (size_t i = 0; i < num_attributes; ++i) {
314 dw_attr_t attr = attributes.AttributeAtIndex(i);
315 DWARFFormValue form_value;
316 if (!attributes.ExtractFormValueAtIndex(i, form_value))
317 continue;
318 switch (attr) {
319 case DW_AT_loclists_base:
320 SetLoclistsBase(form_value.Unsigned());
321 break;
322 case DW_AT_rnglists_base:
323 ranges_base = form_value.Unsigned();
324 SetRangesBase(*ranges_base);
325 break;
326 case DW_AT_str_offsets_base:
327 SetStrOffsetsBase(form_value.Unsigned());
328 break;
329 case DW_AT_low_pc:
330 SetBaseAddress(form_value.Address());
331 break;
332 case DW_AT_entry_pc:
333 // If the value was already set by DW_AT_low_pc, don't update it.
334 if (m_base_addr == LLDB_INVALID_ADDRESS)
335 SetBaseAddress(form_value.Address());
336 break;
337 case DW_AT_stmt_list:
338 m_line_table_offset = form_value.Unsigned();
339 break;
340 case DW_AT_GNU_addr_base:
341 gnu_addr_base = form_value.Unsigned();
342 break;
343 case DW_AT_GNU_ranges_base:
344 gnu_ranges_base = form_value.Unsigned();
345 break;
346 case DW_AT_GNU_dwo_id:
347 m_dwo_id = form_value.Unsigned();
348 break;
349 }
350 }
351
352 if (m_is_dwo) {
353 SetDwoStrOffsetsBase();
354 return;
355 }
356
357 std::shared_ptr<SymbolFileDWARFDwo> dwo_symbol_file =
358 m_dwarf.GetDwoSymbolFileForCompileUnit(*this, cu_die);
359 if (!dwo_symbol_file)
360 return;
361
362 DWARFUnit *dwo_cu = dwo_symbol_file->GetDWOCompileUnitForHash(m_dwo_id);
363
364 if (!dwo_cu)
365 return; // Can't fetch the compile unit from the dwo file.
366 dwo_cu->SetUserData(this);
367
368 DWARFBaseDIE dwo_cu_die = dwo_cu->GetUnitDIEOnly();
369 if (!dwo_cu_die.IsValid())
370 return; // Can't fetch the compile unit DIE from the dwo file.
371
372 // Here for DWO CU we want to use the address base set in the skeleton unit
373 // (DW_AT_addr_base) if it is available and use the DW_AT_GNU_addr_base
374 // otherwise. We do that because pre-DWARF v5 could use the DW_AT_GNU_*
375 // attributes which were applicable to the DWO units. The corresponding
376 // DW_AT_* attributes standardized in DWARF v5 are also applicable to the main
377 // unit in contrast.
378 if (addr_base)
379 dwo_cu->SetAddrBase(*addr_base);
380 else if (gnu_addr_base)
381 dwo_cu->SetAddrBase(*gnu_addr_base);
382
383 if (GetVersion() <= 4 && gnu_ranges_base)
384 dwo_cu->SetRangesBase(*gnu_ranges_base);
385 else if (dwo_symbol_file->GetDWARFContext()
386 .getOrLoadRngListsData()
387 .GetByteSize() > 0)
388 dwo_cu->SetRangesBase(llvm::DWARFListTableHeader::getHeaderSize(DWARF32));
389
390 if (GetVersion() >= 5 &&
391 dwo_symbol_file->GetDWARFContext().getOrLoadLocListsData().GetByteSize() >
392 0)
393 dwo_cu->SetLoclistsBase(llvm::DWARFListTableHeader::getHeaderSize(DWARF32));
394 dwo_cu->SetBaseAddress(GetBaseAddress());
395
396 m_dwo = std::shared_ptr<DWARFUnit>(std::move(dwo_symbol_file), dwo_cu);
397 }
398
GetDebugInfoSize() const399 size_t DWARFUnit::GetDebugInfoSize() const {
400 return GetLengthByteSize() + GetLength() - GetHeaderByteSize();
401 }
402
GetAbbreviations() const403 const DWARFAbbreviationDeclarationSet *DWARFUnit::GetAbbreviations() const {
404 return m_abbrevs;
405 }
406
GetAbbrevOffset() const407 dw_offset_t DWARFUnit::GetAbbrevOffset() const {
408 return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET;
409 }
410
GetLineTableOffset()411 dw_offset_t DWARFUnit::GetLineTableOffset() {
412 ExtractUnitDIEIfNeeded();
413 return m_line_table_offset;
414 }
415
SetAddrBase(dw_addr_t addr_base)416 void DWARFUnit::SetAddrBase(dw_addr_t addr_base) { m_addr_base = addr_base; }
417
418 // Parse the rangelist table header, including the optional array of offsets
419 // following it (DWARF v5 and later).
420 template <typename ListTableType>
421 static llvm::Expected<ListTableType>
ParseListTableHeader(const llvm::DWARFDataExtractor & data,uint64_t offset,DwarfFormat format)422 ParseListTableHeader(const llvm::DWARFDataExtractor &data, uint64_t offset,
423 DwarfFormat format) {
424 // We are expected to be called with Offset 0 or pointing just past the table
425 // header. Correct Offset in the latter case so that it points to the start
426 // of the header.
427 if (offset > 0) {
428 uint64_t HeaderSize = llvm::DWARFListTableHeader::getHeaderSize(format);
429 if (offset < HeaderSize)
430 return llvm::createStringError(errc::invalid_argument,
431 "did not detect a valid"
432 " list table with base = 0x%" PRIx64 "\n",
433 offset);
434 offset -= HeaderSize;
435 }
436 ListTableType Table;
437 if (llvm::Error E = Table.extractHeaderAndOffsets(data, &offset))
438 return std::move(E);
439 return Table;
440 }
441
SetLoclistsBase(dw_addr_t loclists_base)442 void DWARFUnit::SetLoclistsBase(dw_addr_t loclists_base) {
443 m_loclists_base = loclists_base;
444
445 uint64_t header_size = llvm::DWARFListTableHeader::getHeaderSize(DWARF32);
446 if (loclists_base < header_size)
447 return;
448
449 m_loclist_table_header.emplace(".debug_loclists", "locations");
450 uint64_t offset = loclists_base - header_size;
451 if (llvm::Error E = m_loclist_table_header->extract(
452 m_dwarf.GetDWARFContext().getOrLoadLocListsData().GetAsLLVM(),
453 &offset)) {
454 GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
455 "Failed to extract location list table at offset 0x%" PRIx64 ": %s",
456 loclists_base, toString(std::move(E)).c_str());
457 }
458 }
459
460 std::unique_ptr<llvm::DWARFLocationTable>
GetLocationTable(const DataExtractor & data) const461 DWARFUnit::GetLocationTable(const DataExtractor &data) const {
462 llvm::DWARFDataExtractor llvm_data(
463 data.GetData(), data.GetByteOrder() == lldb::eByteOrderLittle,
464 data.GetAddressByteSize());
465
466 if (m_is_dwo || GetVersion() >= 5)
467 return std::make_unique<llvm::DWARFDebugLoclists>(llvm_data, GetVersion());
468 return std::make_unique<llvm::DWARFDebugLoc>(llvm_data);
469 }
470
GetLocationData() const471 DWARFDataExtractor DWARFUnit::GetLocationData() const {
472 DWARFContext &Ctx = GetSymbolFileDWARF().GetDWARFContext();
473 const DWARFDataExtractor &data =
474 GetVersion() >= 5 ? Ctx.getOrLoadLocListsData() : Ctx.getOrLoadLocData();
475 if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
476 if (const auto *contribution = entry->getContribution(llvm::DW_SECT_EXT_LOC))
477 return DWARFDataExtractor(data, contribution->Offset,
478 contribution->Length);
479 return DWARFDataExtractor();
480 }
481 return data;
482 }
483
SetRangesBase(dw_addr_t ranges_base)484 void DWARFUnit::SetRangesBase(dw_addr_t ranges_base) {
485 m_ranges_base = ranges_base;
486
487 if (GetVersion() < 5)
488 return;
489
490 if (auto table_or_error = ParseListTableHeader<llvm::DWARFDebugRnglistTable>(
491 m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(),
492 ranges_base, DWARF32))
493 m_rnglist_table = std::move(table_or_error.get());
494 else
495 GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
496 "Failed to extract range list table at offset 0x%" PRIx64 ": %s",
497 ranges_base, toString(table_or_error.takeError()).c_str());
498 }
499
SetStrOffsetsBase(dw_offset_t str_offsets_base)500 void DWARFUnit::SetStrOffsetsBase(dw_offset_t str_offsets_base) {
501 m_str_offsets_base = str_offsets_base;
502 }
503
504 // It may be called only with m_die_array_mutex held R/W.
ClearDIEsRWLocked()505 void DWARFUnit::ClearDIEsRWLocked() {
506 m_die_array.clear();
507 m_die_array.shrink_to_fit();
508
509 if (m_dwo)
510 m_dwo->ClearDIEsRWLocked();
511 }
512
GetByteOrder() const513 lldb::ByteOrder DWARFUnit::GetByteOrder() const {
514 return m_dwarf.GetObjectFile()->GetByteOrder();
515 }
516
SetBaseAddress(dw_addr_t base_addr)517 void DWARFUnit::SetBaseAddress(dw_addr_t base_addr) { m_base_addr = base_addr; }
518
519 // Compare function DWARFDebugAranges::Range structures
CompareDIEOffset(const DWARFDebugInfoEntry & die,const dw_offset_t die_offset)520 static bool CompareDIEOffset(const DWARFDebugInfoEntry &die,
521 const dw_offset_t die_offset) {
522 return die.GetOffset() < die_offset;
523 }
524
525 // GetDIE()
526 //
527 // Get the DIE (Debug Information Entry) with the specified offset by first
528 // checking if the DIE is contained within this compile unit and grabbing the
529 // DIE from this compile unit. Otherwise we grab the DIE from the DWARF file.
530 DWARFDIE
GetDIE(dw_offset_t die_offset)531 DWARFUnit::GetDIE(dw_offset_t die_offset) {
532 if (die_offset == DW_INVALID_OFFSET)
533 return DWARFDIE(); // Not found
534
535 if (!ContainsDIEOffset(die_offset)) {
536 GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
537 "GetDIE for DIE 0x%" PRIx32 " is outside of its CU 0x%" PRIx32,
538 die_offset, GetOffset());
539 return DWARFDIE(); // Not found
540 }
541
542 ExtractDIEsIfNeeded();
543 DWARFDebugInfoEntry::const_iterator end = m_die_array.cend();
544 DWARFDebugInfoEntry::const_iterator pos =
545 lower_bound(m_die_array.cbegin(), end, die_offset, CompareDIEOffset);
546
547 if (pos != end && die_offset == (*pos).GetOffset())
548 return DWARFDIE(this, &(*pos));
549 return DWARFDIE(); // Not found
550 }
551
GetNonSkeletonUnit()552 DWARFUnit &DWARFUnit::GetNonSkeletonUnit() {
553 ExtractUnitDIEIfNeeded();
554 if (m_dwo)
555 return *m_dwo;
556 return *this;
557 }
558
GetAddressByteSize(const DWARFUnit * cu)559 uint8_t DWARFUnit::GetAddressByteSize(const DWARFUnit *cu) {
560 if (cu)
561 return cu->GetAddressByteSize();
562 return DWARFUnit::GetDefaultAddressSize();
563 }
564
GetDefaultAddressSize()565 uint8_t DWARFUnit::GetDefaultAddressSize() { return 4; }
566
GetUserData() const567 void *DWARFUnit::GetUserData() const { return m_user_data; }
568
SetUserData(void * d)569 void DWARFUnit::SetUserData(void *d) { m_user_data = d; }
570
Supports_DW_AT_APPLE_objc_complete_type()571 bool DWARFUnit::Supports_DW_AT_APPLE_objc_complete_type() {
572 return GetProducer() != eProducerLLVMGCC;
573 }
574
DW_AT_decl_file_attributes_are_invalid()575 bool DWARFUnit::DW_AT_decl_file_attributes_are_invalid() {
576 // llvm-gcc makes completely invalid decl file attributes and won't ever be
577 // fixed, so we need to know to ignore these.
578 return GetProducer() == eProducerLLVMGCC;
579 }
580
Supports_unnamed_objc_bitfields()581 bool DWARFUnit::Supports_unnamed_objc_bitfields() {
582 if (GetProducer() == eProducerClang) {
583 const uint32_t major_version = GetProducerVersionMajor();
584 return major_version > 425 ||
585 (major_version == 425 && GetProducerVersionUpdate() >= 13);
586 }
587 return true; // Assume all other compilers didn't have incorrect ObjC bitfield
588 // info
589 }
590
ParseProducerInfo()591 void DWARFUnit::ParseProducerInfo() {
592 m_producer_version_major = UINT32_MAX;
593 m_producer_version_minor = UINT32_MAX;
594 m_producer_version_update = UINT32_MAX;
595
596 const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
597 if (die) {
598
599 const char *producer_cstr =
600 die->GetAttributeValueAsString(this, DW_AT_producer, nullptr);
601 if (producer_cstr) {
602 RegularExpression llvm_gcc_regex(
603 llvm::StringRef("^4\\.[012]\\.[01] \\(Based on Apple "
604 "Inc\\. build [0-9]+\\) \\(LLVM build "
605 "[\\.0-9]+\\)$"));
606 if (llvm_gcc_regex.Execute(llvm::StringRef(producer_cstr))) {
607 m_producer = eProducerLLVMGCC;
608 } else if (strstr(producer_cstr, "clang")) {
609 static RegularExpression g_clang_version_regex(
610 llvm::StringRef("clang-([0-9]+)\\.([0-9]+)\\.([0-9]+)"));
611 llvm::SmallVector<llvm::StringRef, 4> matches;
612 if (g_clang_version_regex.Execute(llvm::StringRef(producer_cstr),
613 &matches)) {
614 m_producer_version_major =
615 StringConvert::ToUInt32(matches[1].str().c_str(), UINT32_MAX, 10);
616 m_producer_version_minor =
617 StringConvert::ToUInt32(matches[2].str().c_str(), UINT32_MAX, 10);
618 m_producer_version_update =
619 StringConvert::ToUInt32(matches[3].str().c_str(), UINT32_MAX, 10);
620 }
621 m_producer = eProducerClang;
622 } else if (strstr(producer_cstr, "GNU"))
623 m_producer = eProducerGCC;
624 }
625 }
626 if (m_producer == eProducerInvalid)
627 m_producer = eProcucerOther;
628 }
629
GetProducer()630 DWARFProducer DWARFUnit::GetProducer() {
631 if (m_producer == eProducerInvalid)
632 ParseProducerInfo();
633 return m_producer;
634 }
635
GetProducerVersionMajor()636 uint32_t DWARFUnit::GetProducerVersionMajor() {
637 if (m_producer_version_major == 0)
638 ParseProducerInfo();
639 return m_producer_version_major;
640 }
641
GetProducerVersionMinor()642 uint32_t DWARFUnit::GetProducerVersionMinor() {
643 if (m_producer_version_minor == 0)
644 ParseProducerInfo();
645 return m_producer_version_minor;
646 }
647
GetProducerVersionUpdate()648 uint32_t DWARFUnit::GetProducerVersionUpdate() {
649 if (m_producer_version_update == 0)
650 ParseProducerInfo();
651 return m_producer_version_update;
652 }
653
GetDWARFLanguageType()654 uint64_t DWARFUnit::GetDWARFLanguageType() {
655 if (m_language_type)
656 return *m_language_type;
657
658 const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
659 if (!die)
660 m_language_type = 0;
661 else
662 m_language_type = die->GetAttributeValueAsUnsigned(this, DW_AT_language, 0);
663 return *m_language_type;
664 }
665
GetIsOptimized()666 bool DWARFUnit::GetIsOptimized() {
667 if (m_is_optimized == eLazyBoolCalculate) {
668 const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
669 if (die) {
670 m_is_optimized = eLazyBoolNo;
671 if (die->GetAttributeValueAsUnsigned(this, DW_AT_APPLE_optimized, 0) ==
672 1) {
673 m_is_optimized = eLazyBoolYes;
674 }
675 }
676 }
677 return m_is_optimized == eLazyBoolYes;
678 }
679
GetPathStyle()680 FileSpec::Style DWARFUnit::GetPathStyle() {
681 if (!m_comp_dir)
682 ComputeCompDirAndGuessPathStyle();
683 return m_comp_dir->GetPathStyle();
684 }
685
GetCompilationDirectory()686 const FileSpec &DWARFUnit::GetCompilationDirectory() {
687 if (!m_comp_dir)
688 ComputeCompDirAndGuessPathStyle();
689 return *m_comp_dir;
690 }
691
GetAbsolutePath()692 const FileSpec &DWARFUnit::GetAbsolutePath() {
693 if (!m_file_spec)
694 ComputeAbsolutePath();
695 return *m_file_spec;
696 }
697
GetFile(size_t file_idx)698 FileSpec DWARFUnit::GetFile(size_t file_idx) {
699 return m_dwarf.GetFile(*this, file_idx);
700 }
701
702 // DWARF2/3 suggests the form hostname:pathname for compilation directory.
703 // Remove the host part if present.
704 static llvm::StringRef
removeHostnameFromPathname(llvm::StringRef path_from_dwarf)705 removeHostnameFromPathname(llvm::StringRef path_from_dwarf) {
706 if (!path_from_dwarf.contains(':'))
707 return path_from_dwarf;
708 llvm::StringRef host, path;
709 std::tie(host, path) = path_from_dwarf.split(':');
710
711 if (host.contains('/'))
712 return path_from_dwarf;
713
714 // check whether we have a windows path, and so the first character is a
715 // drive-letter not a hostname.
716 if (host.size() == 1 && llvm::isAlpha(host[0]) && path.startswith("\\"))
717 return path_from_dwarf;
718
719 return path;
720 }
721
ComputeCompDirAndGuessPathStyle()722 void DWARFUnit::ComputeCompDirAndGuessPathStyle() {
723 m_comp_dir = FileSpec();
724 const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
725 if (!die)
726 return;
727
728 llvm::StringRef comp_dir = removeHostnameFromPathname(
729 die->GetAttributeValueAsString(this, DW_AT_comp_dir, nullptr));
730 if (!comp_dir.empty()) {
731 FileSpec::Style comp_dir_style =
732 FileSpec::GuessPathStyle(comp_dir).getValueOr(FileSpec::Style::native);
733 m_comp_dir = FileSpec(comp_dir, comp_dir_style);
734 } else {
735 // Try to detect the style based on the DW_AT_name attribute, but just store
736 // the detected style in the m_comp_dir field.
737 const char *name =
738 die->GetAttributeValueAsString(this, DW_AT_name, nullptr);
739 m_comp_dir = FileSpec(
740 "", FileSpec::GuessPathStyle(name).getValueOr(FileSpec::Style::native));
741 }
742 }
743
ComputeAbsolutePath()744 void DWARFUnit::ComputeAbsolutePath() {
745 m_file_spec = FileSpec();
746 const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
747 if (!die)
748 return;
749
750 m_file_spec =
751 FileSpec(die->GetAttributeValueAsString(this, DW_AT_name, nullptr),
752 GetPathStyle());
753
754 if (m_file_spec->IsRelative())
755 m_file_spec->MakeAbsolute(GetCompilationDirectory());
756 }
757
GetDwoSymbolFile()758 SymbolFileDWARFDwo *DWARFUnit::GetDwoSymbolFile() {
759 ExtractUnitDIEIfNeeded();
760 if (m_dwo)
761 return &llvm::cast<SymbolFileDWARFDwo>(m_dwo->GetSymbolFileDWARF());
762 return nullptr;
763 }
764
GetFunctionAranges()765 const DWARFDebugAranges &DWARFUnit::GetFunctionAranges() {
766 if (m_func_aranges_up == nullptr) {
767 m_func_aranges_up = std::make_unique<DWARFDebugAranges>();
768 const DWARFDebugInfoEntry *die = DIEPtr();
769 if (die)
770 die->BuildFunctionAddressRangeTable(this, m_func_aranges_up.get());
771
772 if (m_dwo) {
773 const DWARFDebugInfoEntry *dwo_die = m_dwo->DIEPtr();
774 if (dwo_die)
775 dwo_die->BuildFunctionAddressRangeTable(m_dwo.get(),
776 m_func_aranges_up.get());
777 }
778
779 const bool minimize = false;
780 m_func_aranges_up->Sort(minimize);
781 }
782 return *m_func_aranges_up;
783 }
784
785 llvm::Expected<DWARFUnitHeader>
extract(const DWARFDataExtractor & data,DIERef::Section section,lldb::offset_t * offset_ptr,const llvm::DWARFUnitIndex * index)786 DWARFUnitHeader::extract(const DWARFDataExtractor &data,
787 DIERef::Section section, lldb::offset_t *offset_ptr,
788 const llvm::DWARFUnitIndex *index) {
789 DWARFUnitHeader header;
790 header.m_offset = *offset_ptr;
791 if (index)
792 header.m_index_entry = index->getFromOffset(*offset_ptr);
793 header.m_length = data.GetDWARFInitialLength(offset_ptr);
794 header.m_version = data.GetU16(offset_ptr);
795 if (header.m_version == 5) {
796 header.m_unit_type = data.GetU8(offset_ptr);
797 header.m_addr_size = data.GetU8(offset_ptr);
798 header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
799 if (header.m_unit_type == llvm::dwarf::DW_UT_skeleton ||
800 header.m_unit_type == llvm::dwarf::DW_UT_split_compile)
801 header.m_dwo_id = data.GetU64(offset_ptr);
802 } else {
803 header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
804 header.m_addr_size = data.GetU8(offset_ptr);
805 header.m_unit_type =
806 section == DIERef::Section::DebugTypes ? DW_UT_type : DW_UT_compile;
807 }
808
809 if (header.m_index_entry) {
810 if (header.m_abbr_offset) {
811 return llvm::createStringError(
812 llvm::inconvertibleErrorCode(),
813 "Package unit with a non-zero abbreviation offset");
814 }
815 auto *unit_contrib = header.m_index_entry->getContribution();
816 if (!unit_contrib || unit_contrib->Length != header.m_length + 4) {
817 return llvm::createStringError(llvm::inconvertibleErrorCode(),
818 "Inconsistent DWARF package unit index");
819 }
820 auto *abbr_entry =
821 header.m_index_entry->getContribution(llvm::DW_SECT_ABBREV);
822 if (!abbr_entry) {
823 return llvm::createStringError(
824 llvm::inconvertibleErrorCode(),
825 "DWARF package index missing abbreviation column");
826 }
827 header.m_abbr_offset = abbr_entry->Offset;
828 }
829 if (header.IsTypeUnit()) {
830 header.m_type_hash = data.GetU64(offset_ptr);
831 header.m_type_offset = data.GetDWARFOffset(offset_ptr);
832 }
833
834 bool length_OK = data.ValidOffset(header.GetNextUnitOffset() - 1);
835 bool version_OK = SymbolFileDWARF::SupportedVersion(header.m_version);
836 bool addr_size_OK = (header.m_addr_size == 4) || (header.m_addr_size == 8);
837 bool type_offset_OK =
838 !header.IsTypeUnit() || (header.m_type_offset <= header.GetLength());
839
840 if (!length_OK)
841 return llvm::make_error<llvm::object::GenericBinaryError>(
842 "Invalid unit length");
843 if (!version_OK)
844 return llvm::make_error<llvm::object::GenericBinaryError>(
845 "Unsupported unit version");
846 if (!addr_size_OK)
847 return llvm::make_error<llvm::object::GenericBinaryError>(
848 "Invalid unit address size");
849 if (!type_offset_OK)
850 return llvm::make_error<llvm::object::GenericBinaryError>(
851 "Type offset out of range");
852
853 return header;
854 }
855
856 llvm::Expected<DWARFUnitSP>
extract(SymbolFileDWARF & dwarf,user_id_t uid,const DWARFDataExtractor & debug_info,DIERef::Section section,lldb::offset_t * offset_ptr,const llvm::DWARFUnitIndex * index)857 DWARFUnit::extract(SymbolFileDWARF &dwarf, user_id_t uid,
858 const DWARFDataExtractor &debug_info,
859 DIERef::Section section, lldb::offset_t *offset_ptr,
860 const llvm::DWARFUnitIndex *index) {
861 assert(debug_info.ValidOffset(*offset_ptr));
862
863 auto expected_header =
864 DWARFUnitHeader::extract(debug_info, section, offset_ptr, index);
865 if (!expected_header)
866 return expected_header.takeError();
867
868 const DWARFDebugAbbrev *abbr = dwarf.DebugAbbrev();
869 if (!abbr)
870 return llvm::make_error<llvm::object::GenericBinaryError>(
871 "No debug_abbrev data");
872
873 bool abbr_offset_OK =
874 dwarf.GetDWARFContext().getOrLoadAbbrevData().ValidOffset(
875 expected_header->GetAbbrOffset());
876 if (!abbr_offset_OK)
877 return llvm::make_error<llvm::object::GenericBinaryError>(
878 "Abbreviation offset for unit is not valid");
879
880 const DWARFAbbreviationDeclarationSet *abbrevs =
881 abbr->GetAbbreviationDeclarationSet(expected_header->GetAbbrOffset());
882 if (!abbrevs)
883 return llvm::make_error<llvm::object::GenericBinaryError>(
884 "No abbrev exists at the specified offset.");
885
886 bool is_dwo = dwarf.GetDWARFContext().isDwo();
887 if (expected_header->IsTypeUnit())
888 return DWARFUnitSP(new DWARFTypeUnit(dwarf, uid, *expected_header, *abbrevs,
889 section, is_dwo));
890 return DWARFUnitSP(new DWARFCompileUnit(dwarf, uid, *expected_header,
891 *abbrevs, section, is_dwo));
892 }
893
GetData() const894 const lldb_private::DWARFDataExtractor &DWARFUnit::GetData() const {
895 return m_section == DIERef::Section::DebugTypes
896 ? m_dwarf.GetDWARFContext().getOrLoadDebugTypesData()
897 : m_dwarf.GetDWARFContext().getOrLoadDebugInfoData();
898 }
899
GetHeaderByteSize() const900 uint32_t DWARFUnit::GetHeaderByteSize() const {
901 switch (m_header.GetUnitType()) {
902 case llvm::dwarf::DW_UT_compile:
903 case llvm::dwarf::DW_UT_partial:
904 return GetVersion() < 5 ? 11 : 12;
905 case llvm::dwarf::DW_UT_skeleton:
906 case llvm::dwarf::DW_UT_split_compile:
907 return 20;
908 case llvm::dwarf::DW_UT_type:
909 case llvm::dwarf::DW_UT_split_type:
910 return GetVersion() < 5 ? 23 : 24;
911 }
912 llvm_unreachable("invalid UnitType.");
913 }
914
915 llvm::Optional<uint64_t>
GetStringOffsetSectionItem(uint32_t index) const916 DWARFUnit::GetStringOffsetSectionItem(uint32_t index) const {
917 offset_t offset = GetStrOffsetsBase() + index * 4;
918 return m_dwarf.GetDWARFContext().getOrLoadStrOffsetsData().GetU32(&offset);
919 }
920
921 llvm::Expected<DWARFRangeList>
FindRnglistFromOffset(dw_offset_t offset)922 DWARFUnit::FindRnglistFromOffset(dw_offset_t offset) {
923 if (GetVersion() <= 4) {
924 const DWARFDebugRanges *debug_ranges = m_dwarf.GetDebugRanges();
925 if (!debug_ranges)
926 return llvm::make_error<llvm::object::GenericBinaryError>(
927 "No debug_ranges section");
928 DWARFRangeList ranges;
929 debug_ranges->FindRanges(this, offset, ranges);
930 return ranges;
931 }
932
933 if (!m_rnglist_table)
934 return llvm::createStringError(errc::invalid_argument,
935 "missing or invalid range list table");
936
937 auto range_list_or_error = m_rnglist_table->findList(
938 m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(), offset);
939 if (!range_list_or_error)
940 return range_list_or_error.takeError();
941
942 llvm::Expected<llvm::DWARFAddressRangesVector> llvm_ranges =
943 range_list_or_error->getAbsoluteRanges(
944 llvm::object::SectionedAddress{GetBaseAddress()},
945 GetAddressByteSize(), [&](uint32_t index) {
946 uint32_t index_size = GetAddressByteSize();
947 dw_offset_t addr_base = GetAddrBase();
948 lldb::offset_t offset = addr_base + index * index_size;
949 return llvm::object::SectionedAddress{
950 m_dwarf.GetDWARFContext().getOrLoadAddrData().GetMaxU64(
951 &offset, index_size)};
952 });
953 if (!llvm_ranges)
954 return llvm_ranges.takeError();
955
956 DWARFRangeList ranges;
957 for (const llvm::DWARFAddressRange &llvm_range : *llvm_ranges) {
958 ranges.Append(DWARFRangeList::Entry(llvm_range.LowPC,
959 llvm_range.HighPC - llvm_range.LowPC));
960 }
961 return ranges;
962 }
963
964 llvm::Expected<DWARFRangeList>
FindRnglistFromIndex(uint32_t index)965 DWARFUnit::FindRnglistFromIndex(uint32_t index) {
966 if (llvm::Optional<uint64_t> offset = GetRnglistOffset(index))
967 return FindRnglistFromOffset(*offset);
968 if (m_rnglist_table)
969 return llvm::createStringError(errc::invalid_argument,
970 "invalid range list table index %d", index);
971
972 return llvm::createStringError(errc::invalid_argument,
973 "missing or invalid range list table");
974 }
975