1 //===-- ManualDWARFIndex.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 "Plugins/SymbolFile/DWARF/ManualDWARFIndex.h"
10 #include "Plugins/Language/ObjC/ObjCLanguage.h"
11 #include "Plugins/SymbolFile/DWARF/DWARFDebugInfo.h"
12 #include "Plugins/SymbolFile/DWARF/DWARFDeclContext.h"
13 #include "Plugins/SymbolFile/DWARF/LogChannelDWARF.h"
14 #include "Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h"
15 #include "lldb/Core/DataFileCache.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/Progress.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Utility/DataEncoder.h"
21 #include "lldb/Utility/DataExtractor.h"
22 #include "lldb/Utility/Stream.h"
23 #include "lldb/Utility/Timer.h"
24 #include "llvm/Support/FormatVariadic.h"
25 #include "llvm/Support/ThreadPool.h"
26
27 using namespace lldb_private;
28 using namespace lldb;
29 using namespace lldb_private::dwarf;
30
Index()31 void ManualDWARFIndex::Index() {
32 if (m_indexed)
33 return;
34 m_indexed = true;
35
36 ElapsedTime elapsed(m_index_time);
37 LLDB_SCOPED_TIMERF("%p", static_cast<void *>(m_dwarf));
38 if (LoadFromCache()) {
39 m_dwarf->SetDebugInfoIndexWasLoadedFromCache();
40 return;
41 }
42
43 DWARFDebugInfo &main_info = m_dwarf->DebugInfo();
44 SymbolFileDWARFDwo *dwp_dwarf = m_dwarf->GetDwpSymbolFile().get();
45 DWARFDebugInfo *dwp_info = dwp_dwarf ? &dwp_dwarf->DebugInfo() : nullptr;
46
47 std::vector<DWARFUnit *> units_to_index;
48 units_to_index.reserve(main_info.GetNumUnits() +
49 (dwp_info ? dwp_info->GetNumUnits() : 0));
50
51 // Process all units in the main file, as well as any type units in the dwp
52 // file. Type units in dwo files are handled when we reach the dwo file in
53 // IndexUnit.
54 for (size_t U = 0; U < main_info.GetNumUnits(); ++U) {
55 DWARFUnit *unit = main_info.GetUnitAtIndex(U);
56 if (unit && m_units_to_avoid.count(unit->GetOffset()) == 0)
57 units_to_index.push_back(unit);
58 }
59 if (dwp_info && dwp_info->ContainsTypeUnits()) {
60 for (size_t U = 0; U < dwp_info->GetNumUnits(); ++U) {
61 if (auto *tu = llvm::dyn_cast<DWARFTypeUnit>(dwp_info->GetUnitAtIndex(U)))
62 units_to_index.push_back(tu);
63 }
64 }
65
66 if (units_to_index.empty())
67 return;
68
69 StreamString module_desc;
70 m_module.GetDescription(module_desc.AsRawOstream(),
71 lldb::eDescriptionLevelBrief);
72
73 // Include 2 passes per unit to index for extracting DIEs from the unit and
74 // indexing the unit, and then 8 extra entries for finalizing each index set.
75 const uint64_t total_progress = units_to_index.size() * 2 + 8;
76 Progress progress(
77 llvm::formatv("Manually indexing DWARF for {0}", module_desc.GetData()),
78 total_progress);
79
80 std::vector<IndexSet> sets(units_to_index.size());
81
82 // Keep memory down by clearing DIEs for any units if indexing
83 // caused us to load the unit's DIEs.
84 std::vector<llvm::Optional<DWARFUnit::ScopedExtractDIEs>> clear_cu_dies(
85 units_to_index.size());
86 auto parser_fn = [&](size_t cu_idx) {
87 IndexUnit(*units_to_index[cu_idx], dwp_dwarf, sets[cu_idx]);
88 progress.Increment();
89 };
90
91 auto extract_fn = [&](size_t cu_idx) {
92 clear_cu_dies[cu_idx] = units_to_index[cu_idx]->ExtractDIEsScoped();
93 progress.Increment();
94 };
95
96 // Share one thread pool across operations to avoid the overhead of
97 // recreating the threads.
98 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
99
100 // Create a task runner that extracts dies for each DWARF unit in a
101 // separate thread.
102 // First figure out which units didn't have their DIEs already
103 // parsed and remember this. If no DIEs were parsed prior to this index
104 // function call, we are going to want to clear the CU dies after we are
105 // done indexing to make sure we don't pull in all DWARF dies, but we need
106 // to wait until all units have been indexed in case a DIE in one
107 // unit refers to another and the indexes accesses those DIEs.
108 for (size_t i = 0; i < units_to_index.size(); ++i)
109 task_group.async(extract_fn, i);
110 task_group.wait();
111
112 // Now create a task runner that can index each DWARF unit in a
113 // separate thread so we can index quickly.
114 for (size_t i = 0; i < units_to_index.size(); ++i)
115 task_group.async(parser_fn, i);
116 task_group.wait();
117
118 auto finalize_fn = [this, &sets, &progress](NameToDIE(IndexSet::*index)) {
119 NameToDIE &result = m_set.*index;
120 for (auto &set : sets)
121 result.Append(set.*index);
122 result.Finalize();
123 progress.Increment();
124 };
125
126 task_group.async(finalize_fn, &IndexSet::function_basenames);
127 task_group.async(finalize_fn, &IndexSet::function_fullnames);
128 task_group.async(finalize_fn, &IndexSet::function_methods);
129 task_group.async(finalize_fn, &IndexSet::function_selectors);
130 task_group.async(finalize_fn, &IndexSet::objc_class_selectors);
131 task_group.async(finalize_fn, &IndexSet::globals);
132 task_group.async(finalize_fn, &IndexSet::types);
133 task_group.async(finalize_fn, &IndexSet::namespaces);
134 task_group.wait();
135
136 SaveToCache();
137 }
138
IndexUnit(DWARFUnit & unit,SymbolFileDWARFDwo * dwp,IndexSet & set)139 void ManualDWARFIndex::IndexUnit(DWARFUnit &unit, SymbolFileDWARFDwo *dwp,
140 IndexSet &set) {
141 Log *log = GetLog(DWARFLog::Lookups);
142
143 if (log) {
144 m_module.LogMessage(
145 log, "ManualDWARFIndex::IndexUnit for unit at .debug_info[0x%8.8x]",
146 unit.GetOffset());
147 }
148
149 const LanguageType cu_language = SymbolFileDWARF::GetLanguage(unit);
150
151 IndexUnitImpl(unit, cu_language, set);
152
153 if (SymbolFileDWARFDwo *dwo_symbol_file = unit.GetDwoSymbolFile()) {
154 // Type units in a dwp file are indexed separately, so we just need to
155 // process the split unit here. However, if the split unit is in a dwo file,
156 // then we need to process type units here.
157 if (dwo_symbol_file == dwp) {
158 IndexUnitImpl(unit.GetNonSkeletonUnit(), cu_language, set);
159 } else {
160 DWARFDebugInfo &dwo_info = dwo_symbol_file->DebugInfo();
161 for (size_t i = 0; i < dwo_info.GetNumUnits(); ++i)
162 IndexUnitImpl(*dwo_info.GetUnitAtIndex(i), cu_language, set);
163 }
164 }
165 }
166
IndexUnitImpl(DWARFUnit & unit,const LanguageType cu_language,IndexSet & set)167 void ManualDWARFIndex::IndexUnitImpl(DWARFUnit &unit,
168 const LanguageType cu_language,
169 IndexSet &set) {
170 for (const DWARFDebugInfoEntry &die : unit.dies()) {
171 const dw_tag_t tag = die.Tag();
172
173 switch (tag) {
174 case DW_TAG_array_type:
175 case DW_TAG_base_type:
176 case DW_TAG_class_type:
177 case DW_TAG_constant:
178 case DW_TAG_enumeration_type:
179 case DW_TAG_inlined_subroutine:
180 case DW_TAG_namespace:
181 case DW_TAG_string_type:
182 case DW_TAG_structure_type:
183 case DW_TAG_subprogram:
184 case DW_TAG_subroutine_type:
185 case DW_TAG_typedef:
186 case DW_TAG_union_type:
187 case DW_TAG_unspecified_type:
188 case DW_TAG_variable:
189 break;
190
191 default:
192 continue;
193 }
194
195 DWARFAttributes attributes;
196 const char *name = nullptr;
197 const char *mangled_cstr = nullptr;
198 bool is_declaration = false;
199 // bool is_artificial = false;
200 bool has_address = false;
201 bool has_location_or_const_value = false;
202 bool is_global_or_static_variable = false;
203
204 DWARFFormValue specification_die_form;
205 const size_t num_attributes = die.GetAttributes(&unit, attributes);
206 if (num_attributes > 0) {
207 for (uint32_t i = 0; i < num_attributes; ++i) {
208 dw_attr_t attr = attributes.AttributeAtIndex(i);
209 DWARFFormValue form_value;
210 switch (attr) {
211 case DW_AT_name:
212 if (attributes.ExtractFormValueAtIndex(i, form_value))
213 name = form_value.AsCString();
214 break;
215
216 case DW_AT_declaration:
217 if (attributes.ExtractFormValueAtIndex(i, form_value))
218 is_declaration = form_value.Unsigned() != 0;
219 break;
220
221 case DW_AT_MIPS_linkage_name:
222 case DW_AT_linkage_name:
223 if (attributes.ExtractFormValueAtIndex(i, form_value))
224 mangled_cstr = form_value.AsCString();
225 break;
226
227 case DW_AT_low_pc:
228 case DW_AT_high_pc:
229 case DW_AT_ranges:
230 has_address = true;
231 break;
232
233 case DW_AT_entry_pc:
234 has_address = true;
235 break;
236
237 case DW_AT_location:
238 case DW_AT_const_value:
239 has_location_or_const_value = true;
240 is_global_or_static_variable = die.IsGlobalOrStaticScopeVariable();
241
242 break;
243
244 case DW_AT_specification:
245 if (attributes.ExtractFormValueAtIndex(i, form_value))
246 specification_die_form = form_value;
247 break;
248 }
249 }
250 }
251
252 DIERef ref = *DWARFDIE(&unit, &die).GetDIERef();
253 switch (tag) {
254 case DW_TAG_inlined_subroutine:
255 case DW_TAG_subprogram:
256 if (has_address) {
257 if (name) {
258 bool is_objc_method = false;
259 if (cu_language == eLanguageTypeObjC ||
260 cu_language == eLanguageTypeObjC_plus_plus) {
261 ObjCLanguage::MethodName objc_method(name, true);
262 if (objc_method.IsValid(true)) {
263 is_objc_method = true;
264 ConstString class_name_with_category(
265 objc_method.GetClassNameWithCategory());
266 ConstString objc_selector_name(objc_method.GetSelector());
267 ConstString objc_fullname_no_category_name(
268 objc_method.GetFullNameWithoutCategory(true));
269 ConstString class_name_no_category(objc_method.GetClassName());
270 set.function_fullnames.Insert(ConstString(name), ref);
271 if (class_name_with_category)
272 set.objc_class_selectors.Insert(class_name_with_category, ref);
273 if (class_name_no_category &&
274 class_name_no_category != class_name_with_category)
275 set.objc_class_selectors.Insert(class_name_no_category, ref);
276 if (objc_selector_name)
277 set.function_selectors.Insert(objc_selector_name, ref);
278 if (objc_fullname_no_category_name)
279 set.function_fullnames.Insert(objc_fullname_no_category_name,
280 ref);
281 }
282 }
283 // If we have a mangled name, then the DW_AT_name attribute is
284 // usually the method name without the class or any parameters
285 bool is_method = DWARFDIE(&unit, &die).IsMethod();
286
287 if (is_method)
288 set.function_methods.Insert(ConstString(name), ref);
289 else
290 set.function_basenames.Insert(ConstString(name), ref);
291
292 if (!is_method && !mangled_cstr && !is_objc_method)
293 set.function_fullnames.Insert(ConstString(name), ref);
294 }
295 if (mangled_cstr) {
296 // Make sure our mangled name isn't the same string table entry as
297 // our name. If it starts with '_', then it is ok, else compare the
298 // string to make sure it isn't the same and we don't end up with
299 // duplicate entries
300 if (name && name != mangled_cstr &&
301 ((mangled_cstr[0] == '_') ||
302 (::strcmp(name, mangled_cstr) != 0))) {
303 set.function_fullnames.Insert(ConstString(mangled_cstr), ref);
304 }
305 }
306 }
307 break;
308
309 case DW_TAG_array_type:
310 case DW_TAG_base_type:
311 case DW_TAG_class_type:
312 case DW_TAG_constant:
313 case DW_TAG_enumeration_type:
314 case DW_TAG_string_type:
315 case DW_TAG_structure_type:
316 case DW_TAG_subroutine_type:
317 case DW_TAG_typedef:
318 case DW_TAG_union_type:
319 case DW_TAG_unspecified_type:
320 if (name && !is_declaration)
321 set.types.Insert(ConstString(name), ref);
322 if (mangled_cstr && !is_declaration)
323 set.types.Insert(ConstString(mangled_cstr), ref);
324 break;
325
326 case DW_TAG_namespace:
327 if (name)
328 set.namespaces.Insert(ConstString(name), ref);
329 break;
330
331 case DW_TAG_variable:
332 if (name && has_location_or_const_value && is_global_or_static_variable) {
333 set.globals.Insert(ConstString(name), ref);
334 // Be sure to include variables by their mangled and demangled names if
335 // they have any since a variable can have a basename "i", a mangled
336 // named "_ZN12_GLOBAL__N_11iE" and a demangled mangled name
337 // "(anonymous namespace)::i"...
338
339 // Make sure our mangled name isn't the same string table entry as our
340 // name. If it starts with '_', then it is ok, else compare the string
341 // to make sure it isn't the same and we don't end up with duplicate
342 // entries
343 if (mangled_cstr && name != mangled_cstr &&
344 ((mangled_cstr[0] == '_') || (::strcmp(name, mangled_cstr) != 0))) {
345 set.globals.Insert(ConstString(mangled_cstr), ref);
346 }
347 }
348 break;
349
350 default:
351 continue;
352 }
353 }
354 }
355
GetGlobalVariables(ConstString basename,llvm::function_ref<bool (DWARFDIE die)> callback)356 void ManualDWARFIndex::GetGlobalVariables(
357 ConstString basename, llvm::function_ref<bool(DWARFDIE die)> callback) {
358 Index();
359 m_set.globals.Find(basename,
360 DIERefCallback(callback, basename.GetStringRef()));
361 }
362
GetGlobalVariables(const RegularExpression & regex,llvm::function_ref<bool (DWARFDIE die)> callback)363 void ManualDWARFIndex::GetGlobalVariables(
364 const RegularExpression ®ex,
365 llvm::function_ref<bool(DWARFDIE die)> callback) {
366 Index();
367 m_set.globals.Find(regex, DIERefCallback(callback, regex.GetText()));
368 }
369
GetGlobalVariables(DWARFUnit & unit,llvm::function_ref<bool (DWARFDIE die)> callback)370 void ManualDWARFIndex::GetGlobalVariables(
371 DWARFUnit &unit, llvm::function_ref<bool(DWARFDIE die)> callback) {
372 lldbassert(!unit.GetSymbolFileDWARF().GetDwoNum());
373 Index();
374 m_set.globals.FindAllEntriesForUnit(unit, DIERefCallback(callback));
375 }
376
GetObjCMethods(ConstString class_name,llvm::function_ref<bool (DWARFDIE die)> callback)377 void ManualDWARFIndex::GetObjCMethods(
378 ConstString class_name, llvm::function_ref<bool(DWARFDIE die)> callback) {
379 Index();
380 m_set.objc_class_selectors.Find(
381 class_name, DIERefCallback(callback, class_name.GetStringRef()));
382 }
383
GetCompleteObjCClass(ConstString class_name,bool must_be_implementation,llvm::function_ref<bool (DWARFDIE die)> callback)384 void ManualDWARFIndex::GetCompleteObjCClass(
385 ConstString class_name, bool must_be_implementation,
386 llvm::function_ref<bool(DWARFDIE die)> callback) {
387 Index();
388 m_set.types.Find(class_name,
389 DIERefCallback(callback, class_name.GetStringRef()));
390 }
391
GetTypes(ConstString name,llvm::function_ref<bool (DWARFDIE die)> callback)392 void ManualDWARFIndex::GetTypes(
393 ConstString name, llvm::function_ref<bool(DWARFDIE die)> callback) {
394 Index();
395 m_set.types.Find(name, DIERefCallback(callback, name.GetStringRef()));
396 }
397
GetTypes(const DWARFDeclContext & context,llvm::function_ref<bool (DWARFDIE die)> callback)398 void ManualDWARFIndex::GetTypes(
399 const DWARFDeclContext &context,
400 llvm::function_ref<bool(DWARFDIE die)> callback) {
401 Index();
402 auto name = context[0].name;
403 m_set.types.Find(ConstString(name),
404 DIERefCallback(callback, llvm::StringRef(name)));
405 }
406
GetNamespaces(ConstString name,llvm::function_ref<bool (DWARFDIE die)> callback)407 void ManualDWARFIndex::GetNamespaces(
408 ConstString name, llvm::function_ref<bool(DWARFDIE die)> callback) {
409 Index();
410 m_set.namespaces.Find(name, DIERefCallback(callback, name.GetStringRef()));
411 }
412
GetFunctions(ConstString name,SymbolFileDWARF & dwarf,const CompilerDeclContext & parent_decl_ctx,uint32_t name_type_mask,llvm::function_ref<bool (DWARFDIE die)> callback)413 void ManualDWARFIndex::GetFunctions(
414 ConstString name, SymbolFileDWARF &dwarf,
415 const CompilerDeclContext &parent_decl_ctx, uint32_t name_type_mask,
416 llvm::function_ref<bool(DWARFDIE die)> callback) {
417 Index();
418
419 if (name_type_mask & eFunctionNameTypeFull) {
420 if (!m_set.function_fullnames.Find(
421 name, DIERefCallback(
422 [&](DWARFDIE die) {
423 if (!SymbolFileDWARF::DIEInDeclContext(parent_decl_ctx,
424 die))
425 return true;
426 return callback(die);
427 },
428 name.GetStringRef())))
429 return;
430 }
431 if (name_type_mask & eFunctionNameTypeBase) {
432 if (!m_set.function_basenames.Find(
433 name, DIERefCallback(
434 [&](DWARFDIE die) {
435 if (!SymbolFileDWARF::DIEInDeclContext(parent_decl_ctx,
436 die))
437 return true;
438 return callback(die);
439 },
440 name.GetStringRef())))
441 return;
442 }
443
444 if (name_type_mask & eFunctionNameTypeMethod && !parent_decl_ctx.IsValid()) {
445 if (!m_set.function_methods.Find(
446 name, DIERefCallback(callback, name.GetStringRef())))
447 return;
448 }
449
450 if (name_type_mask & eFunctionNameTypeSelector &&
451 !parent_decl_ctx.IsValid()) {
452 if (!m_set.function_selectors.Find(
453 name, DIERefCallback(callback, name.GetStringRef())))
454 return;
455 }
456 }
457
GetFunctions(const RegularExpression & regex,llvm::function_ref<bool (DWARFDIE die)> callback)458 void ManualDWARFIndex::GetFunctions(
459 const RegularExpression ®ex,
460 llvm::function_ref<bool(DWARFDIE die)> callback) {
461 Index();
462
463 if (!m_set.function_basenames.Find(regex,
464 DIERefCallback(callback, regex.GetText())))
465 return;
466 if (!m_set.function_fullnames.Find(regex,
467 DIERefCallback(callback, regex.GetText())))
468 return;
469 }
470
Dump(Stream & s)471 void ManualDWARFIndex::Dump(Stream &s) {
472 s.Format("Manual DWARF index for ({0}) '{1:F}':",
473 m_module.GetArchitecture().GetArchitectureName(),
474 m_module.GetObjectFile()->GetFileSpec());
475 s.Printf("\nFunction basenames:\n");
476 m_set.function_basenames.Dump(&s);
477 s.Printf("\nFunction fullnames:\n");
478 m_set.function_fullnames.Dump(&s);
479 s.Printf("\nFunction methods:\n");
480 m_set.function_methods.Dump(&s);
481 s.Printf("\nFunction selectors:\n");
482 m_set.function_selectors.Dump(&s);
483 s.Printf("\nObjective-C class selectors:\n");
484 m_set.objc_class_selectors.Dump(&s);
485 s.Printf("\nGlobals and statics:\n");
486 m_set.globals.Dump(&s);
487 s.Printf("\nTypes:\n");
488 m_set.types.Dump(&s);
489 s.Printf("\nNamespaces:\n");
490 m_set.namespaces.Dump(&s);
491 }
492
493 constexpr llvm::StringLiteral kIdentifierManualDWARFIndex("DIDX");
494 // Define IDs for the different tables when encoding and decoding the
495 // ManualDWARFIndex NameToDIE objects so we can avoid saving any empty maps.
496 enum DataID {
497 kDataIDFunctionBasenames = 1u,
498 kDataIDFunctionFullnames,
499 kDataIDFunctionMethods,
500 kDataIDFunctionSelectors,
501 kDataIDFunctionObjcClassSelectors,
502 kDataIDGlobals,
503 kDataIDTypes,
504 kDataIDNamespaces,
505 kDataIDEnd = 255u,
506
507 };
508 constexpr uint32_t CURRENT_CACHE_VERSION = 1;
509
Decode(const DataExtractor & data,lldb::offset_t * offset_ptr)510 bool ManualDWARFIndex::IndexSet::Decode(const DataExtractor &data,
511 lldb::offset_t *offset_ptr) {
512 StringTableReader strtab;
513 // We now decode the string table for all strings in the data cache file.
514 if (!strtab.Decode(data, offset_ptr))
515 return false;
516
517 llvm::StringRef identifier((const char *)data.GetData(offset_ptr, 4), 4);
518 if (identifier != kIdentifierManualDWARFIndex)
519 return false;
520 const uint32_t version = data.GetU32(offset_ptr);
521 if (version != CURRENT_CACHE_VERSION)
522 return false;
523
524 bool done = false;
525 while (!done) {
526 switch (data.GetU8(offset_ptr)) {
527 default:
528 // If we got here, this is not expected, we expect the data IDs to match
529 // one of the values from the DataID enumeration.
530 return false;
531 case kDataIDFunctionBasenames:
532 if (!function_basenames.Decode(data, offset_ptr, strtab))
533 return false;
534 break;
535 case kDataIDFunctionFullnames:
536 if (!function_fullnames.Decode(data, offset_ptr, strtab))
537 return false;
538 break;
539 case kDataIDFunctionMethods:
540 if (!function_methods.Decode(data, offset_ptr, strtab))
541 return false;
542 break;
543 case kDataIDFunctionSelectors:
544 if (!function_selectors.Decode(data, offset_ptr, strtab))
545 return false;
546 break;
547 case kDataIDFunctionObjcClassSelectors:
548 if (!objc_class_selectors.Decode(data, offset_ptr, strtab))
549 return false;
550 break;
551 case kDataIDGlobals:
552 if (!globals.Decode(data, offset_ptr, strtab))
553 return false;
554 break;
555 case kDataIDTypes:
556 if (!types.Decode(data, offset_ptr, strtab))
557 return false;
558 break;
559 case kDataIDNamespaces:
560 if (!namespaces.Decode(data, offset_ptr, strtab))
561 return false;
562 break;
563 case kDataIDEnd:
564 // We got to the end of our NameToDIE encodings.
565 done = true;
566 break;
567 }
568 }
569 // Success!
570 return true;
571 }
572
Encode(DataEncoder & encoder) const573 void ManualDWARFIndex::IndexSet::Encode(DataEncoder &encoder) const {
574 ConstStringTable strtab;
575
576 // Encoder the DWARF index into a separate encoder first. This allows us
577 // gather all of the strings we willl need in "strtab" as we will need to
578 // write the string table out before the symbol table.
579 DataEncoder index_encoder(encoder.GetByteOrder(),
580 encoder.GetAddressByteSize());
581
582 index_encoder.AppendData(kIdentifierManualDWARFIndex);
583 // Encode the data version.
584 index_encoder.AppendU32(CURRENT_CACHE_VERSION);
585
586 if (!function_basenames.IsEmpty()) {
587 index_encoder.AppendU8(kDataIDFunctionBasenames);
588 function_basenames.Encode(index_encoder, strtab);
589 }
590 if (!function_fullnames.IsEmpty()) {
591 index_encoder.AppendU8(kDataIDFunctionFullnames);
592 function_fullnames.Encode(index_encoder, strtab);
593 }
594 if (!function_methods.IsEmpty()) {
595 index_encoder.AppendU8(kDataIDFunctionMethods);
596 function_methods.Encode(index_encoder, strtab);
597 }
598 if (!function_selectors.IsEmpty()) {
599 index_encoder.AppendU8(kDataIDFunctionSelectors);
600 function_selectors.Encode(index_encoder, strtab);
601 }
602 if (!objc_class_selectors.IsEmpty()) {
603 index_encoder.AppendU8(kDataIDFunctionObjcClassSelectors);
604 objc_class_selectors.Encode(index_encoder, strtab);
605 }
606 if (!globals.IsEmpty()) {
607 index_encoder.AppendU8(kDataIDGlobals);
608 globals.Encode(index_encoder, strtab);
609 }
610 if (!types.IsEmpty()) {
611 index_encoder.AppendU8(kDataIDTypes);
612 types.Encode(index_encoder, strtab);
613 }
614 if (!namespaces.IsEmpty()) {
615 index_encoder.AppendU8(kDataIDNamespaces);
616 namespaces.Encode(index_encoder, strtab);
617 }
618 index_encoder.AppendU8(kDataIDEnd);
619
620 // Now that all strings have been gathered, we will emit the string table.
621 strtab.Encode(encoder);
622 // Followed the the symbol table data.
623 encoder.AppendData(index_encoder.GetData());
624 }
625
Decode(const DataExtractor & data,lldb::offset_t * offset_ptr,bool & signature_mismatch)626 bool ManualDWARFIndex::Decode(const DataExtractor &data,
627 lldb::offset_t *offset_ptr,
628 bool &signature_mismatch) {
629 signature_mismatch = false;
630 CacheSignature signature;
631 if (!signature.Decode(data, offset_ptr))
632 return false;
633 if (CacheSignature(m_dwarf->GetObjectFile()) != signature) {
634 signature_mismatch = true;
635 return false;
636 }
637 IndexSet set;
638 if (!set.Decode(data, offset_ptr))
639 return false;
640 m_set = std::move(set);
641 return true;
642 }
643
Encode(DataEncoder & encoder) const644 bool ManualDWARFIndex::Encode(DataEncoder &encoder) const {
645 CacheSignature signature(m_dwarf->GetObjectFile());
646 if (!signature.Encode(encoder))
647 return false;
648 m_set.Encode(encoder);
649 return true;
650 }
651
GetCacheKey()652 std::string ManualDWARFIndex::GetCacheKey() {
653 std::string key;
654 llvm::raw_string_ostream strm(key);
655 // DWARF Index can come from different object files for the same module. A
656 // module can have one object file as the main executable and might have
657 // another object file in a separate symbol file, or we might have a .dwo file
658 // that claims its module is the main executable.
659 ObjectFile *objfile = m_dwarf->GetObjectFile();
660 strm << objfile->GetModule()->GetCacheKey() << "-dwarf-index-"
661 << llvm::format_hex(objfile->GetCacheHash(), 10);
662 return strm.str();
663 }
664
LoadFromCache()665 bool ManualDWARFIndex::LoadFromCache() {
666 DataFileCache *cache = Module::GetIndexCache();
667 if (!cache)
668 return false;
669 ObjectFile *objfile = m_dwarf->GetObjectFile();
670 if (!objfile)
671 return false;
672 std::unique_ptr<llvm::MemoryBuffer> mem_buffer_up =
673 cache->GetCachedData(GetCacheKey());
674 if (!mem_buffer_up)
675 return false;
676 DataExtractor data(mem_buffer_up->getBufferStart(),
677 mem_buffer_up->getBufferSize(),
678 endian::InlHostByteOrder(),
679 objfile->GetAddressByteSize());
680 bool signature_mismatch = false;
681 lldb::offset_t offset = 0;
682 const bool result = Decode(data, &offset, signature_mismatch);
683 if (signature_mismatch)
684 cache->RemoveCacheFile(GetCacheKey());
685 return result;
686 }
687
SaveToCache()688 void ManualDWARFIndex::SaveToCache() {
689 DataFileCache *cache = Module::GetIndexCache();
690 if (!cache)
691 return; // Caching is not enabled.
692 ObjectFile *objfile = m_dwarf->GetObjectFile();
693 if (!objfile)
694 return;
695 DataEncoder file(endian::InlHostByteOrder(), objfile->GetAddressByteSize());
696 // Encode will return false if the object file doesn't have anything to make
697 // a signature from.
698 if (Encode(file)) {
699 if (cache->SetCachedData(GetCacheKey(), file.GetData()))
700 m_dwarf->SetDebugInfoIndexWasSavedToCache();
701 }
702 }
703