1//===-- Module.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 "lldb/Core/Module.h"
10
11#include "lldb/Core/AddressRange.h"
12#include "lldb/Core/AddressResolverFileLine.h"
13#include "lldb/Core/DataFileCache.h"
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/FileSpecList.h"
16#include "lldb/Core/Mangled.h"
17#include "lldb/Core/ModuleSpec.h"
18#include "lldb/Core/SearchFilter.h"
19#include "lldb/Core/Section.h"
20#include "lldb/Host/FileSystem.h"
21#include "lldb/Host/Host.h"
22#include "lldb/Host/HostInfo.h"
23#include "lldb/Interpreter/CommandInterpreter.h"
24#include "lldb/Interpreter/ScriptInterpreter.h"
25#include "lldb/Symbol/CompileUnit.h"
26#include "lldb/Symbol/Function.h"
27#include "lldb/Symbol/LocateSymbolFile.h"
28#include "lldb/Symbol/ObjectFile.h"
29#include "lldb/Symbol/Symbol.h"
30#include "lldb/Symbol/SymbolContext.h"
31#include "lldb/Symbol/SymbolFile.h"
32#include "lldb/Symbol/SymbolVendor.h"
33#include "lldb/Symbol/Symtab.h"
34#include "lldb/Symbol/Type.h"
35#include "lldb/Symbol/TypeList.h"
36#include "lldb/Symbol/TypeMap.h"
37#include "lldb/Symbol/TypeSystem.h"
38#include "lldb/Target/Language.h"
39#include "lldb/Target/Process.h"
40#include "lldb/Target/Target.h"
41#include "lldb/Utility/DataBufferHeap.h"
42#include "lldb/Utility/LLDBAssert.h"
43#include "lldb/Utility/LLDBLog.h"
44#include "lldb/Utility/Log.h"
45#include "lldb/Utility/RegularExpression.h"
46#include "lldb/Utility/Status.h"
47#include "lldb/Utility/Stream.h"
48#include "lldb/Utility/StreamString.h"
49#include "lldb/Utility/Timer.h"
50
51#if defined(_WIN32)
52#include "lldb/Host/windows/PosixApi.h"
53#endif
54
55#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
56#include "Plugins/Language/ObjC/ObjCLanguage.h"
57
58#include "llvm/ADT/STLExtras.h"
59#include "llvm/Support/Compiler.h"
60#include "llvm/Support/DJB.h"
61#include "llvm/Support/FileSystem.h"
62#include "llvm/Support/FormatVariadic.h"
63#include "llvm/Support/JSON.h"
64#include "llvm/Support/Signals.h"
65#include "llvm/Support/raw_ostream.h"
66
67#include <cassert>
68#include <cinttypes>
69#include <cstdarg>
70#include <cstdint>
71#include <cstring>
72#include <map>
73#include <type_traits>
74#include <utility>
75
76namespace lldb_private {
77class CompilerDeclContext;
78}
79namespace lldb_private {
80class VariableList;
81}
82
83using namespace lldb;
84using namespace lldb_private;
85
86// Shared pointers to modules track module lifetimes in targets and in the
87// global module, but this collection will track all module objects that are
88// still alive
89typedef std::vector<Module *> ModuleCollection;
90
91static ModuleCollection &GetModuleCollection() {
92 // This module collection needs to live past any module, so we could either
93 // make it a shared pointer in each module or just leak is. Since it is only
94 // an empty vector by the time all the modules have gone away, we just leak
95 // it for now. If we decide this is a big problem we can introduce a
96 // Finalize method that will tear everything down in a predictable order.
97
98 static ModuleCollection *g_module_collection = nullptr;
99 if (g_module_collection == nullptr)
100 g_module_collection = new ModuleCollection();
101
102 return *g_module_collection;
103}
104
105std::recursive_mutex &Module::GetAllocationModuleCollectionMutex() {
106 // NOTE: The mutex below must be leaked since the global module list in
107 // the ModuleList class will get torn at some point, and we can't know if it
108 // will tear itself down before the "g_module_collection_mutex" below will.
109 // So we leak a Mutex object below to safeguard against that
110
111 static std::recursive_mutex *g_module_collection_mutex = nullptr;
112 if (g_module_collection_mutex == nullptr)
113 g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak
114 return *g_module_collection_mutex;
115}
116
117size_t Module::GetNumberAllocatedModules() {
118 std::lock_guard<std::recursive_mutex> guard(
119 GetAllocationModuleCollectionMutex());
120 return GetModuleCollection().size();
121}
122
123Module *Module::GetAllocatedModuleAtIndex(size_t idx) {
124 std::lock_guard<std::recursive_mutex> guard(
125 GetAllocationModuleCollectionMutex());
126 ModuleCollection &modules = GetModuleCollection();
127 if (idx < modules.size())
128 return modules[idx];
129 return nullptr;
130}
131
132Module::Module(const ModuleSpec &module_spec)
133 : m_file_has_changed(false), m_first_file_changed_log(false) {
134 // Scope for locker below...
135 {
136 std::lock_guard<std::recursive_mutex> guard(
137 GetAllocationModuleCollectionMutex());
138 GetModuleCollection().push_back(this);
139 }
140
141 Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
142 if (log != nullptr)
143 LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
144 static_cast<void *>(this),
145 module_spec.GetArchitecture().GetArchitectureName(),
146 module_spec.GetFileSpec().GetPath().c_str(),
147 module_spec.GetObjectName().IsEmpty() ? "" : "(",
148 module_spec.GetObjectName().AsCString(""),
149 module_spec.GetObjectName().IsEmpty() ? "" : ")");
150
151 auto data_sp = module_spec.GetData();
152 lldb::offset_t file_size = 0;
153 if (data_sp)
154 file_size = data_sp->GetByteSize();
155
156 // First extract all module specifications from the file using the local file
157 // path. If there are no specifications, then don't fill anything in
158 ModuleSpecList modules_specs;
159 if (ObjectFile::GetModuleSpecifications(
160 module_spec.GetFileSpec(), 0, file_size, modules_specs, data_sp) == 0)
161 return;
162
163 // Now make sure that one of the module specifications matches what we just
164 // extract. We might have a module specification that specifies a file
165 // "/usr/lib/dyld" with UUID XXX, but we might have a local version of
166 // "/usr/lib/dyld" that has
167 // UUID YYY and we don't want those to match. If they don't match, just don't
168 // fill any ivars in so we don't accidentally grab the wrong file later since
169 // they don't match...
170 ModuleSpec matching_module_spec;
171 if (!modules_specs.FindMatchingModuleSpec(module_spec,
172 matching_module_spec)) {
173 if (log) {
174 LLDB_LOGF(log, "Found local object file but the specs didn't match");
175 }
176 return;
177 }
178
179 // Set m_data_sp if it was initially provided in the ModuleSpec. Note that
180 // we cannot use the data_sp variable here, because it will have been
181 // modified by GetModuleSpecifications().
182 if (auto module_spec_data_sp = module_spec.GetData()) {
183 m_data_sp = module_spec_data_sp;
184 m_mod_time = {};
185 } else {
186 if (module_spec.GetFileSpec())
187 m_mod_time =
188 FileSystem::Instance().GetModificationTime(module_spec.GetFileSpec());
189 else if (matching_module_spec.GetFileSpec())
190 m_mod_time = FileSystem::Instance().GetModificationTime(
191 matching_module_spec.GetFileSpec());
192 }
193
194 // Copy the architecture from the actual spec if we got one back, else use
195 // the one that was specified
196 if (matching_module_spec.GetArchitecture().IsValid())
197 m_arch = matching_module_spec.GetArchitecture();
198 else if (module_spec.GetArchitecture().IsValid())
199 m_arch = module_spec.GetArchitecture();
200
201 // Copy the file spec over and use the specified one (if there was one) so we
202 // don't use a path that might have gotten resolved a path in
203 // 'matching_module_spec'
204 if (module_spec.GetFileSpec())
205 m_file = module_spec.GetFileSpec();
206 else if (matching_module_spec.GetFileSpec())
207 m_file = matching_module_spec.GetFileSpec();
208
209 // Copy the platform file spec over
210 if (module_spec.GetPlatformFileSpec())
211 m_platform_file = module_spec.GetPlatformFileSpec();
212 else if (matching_module_spec.GetPlatformFileSpec())
213 m_platform_file = matching_module_spec.GetPlatformFileSpec();
214
215 // Copy the symbol file spec over
216 if (module_spec.GetSymbolFileSpec())
217 m_symfile_spec = module_spec.GetSymbolFileSpec();
218 else if (matching_module_spec.GetSymbolFileSpec())
219 m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
220
221 // Copy the object name over
222 if (matching_module_spec.GetObjectName())
223 m_object_name = matching_module_spec.GetObjectName();
224 else
225 m_object_name = module_spec.GetObjectName();
226
227 // Always trust the object offset (file offset) and object modification time
228 // (for mod time in a BSD static archive) of from the matching module
229 // specification
230 m_object_offset = matching_module_spec.GetObjectOffset();
231 m_object_mod_time = matching_module_spec.GetObjectModificationTime();
232}
233
234Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
235 const ConstString *object_name, lldb::offset_t object_offset,
236 const llvm::sys::TimePoint<> &object_mod_time)
237 : m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
238 m_arch(arch), m_file(file_spec), m_object_offset(object_offset),
239 m_object_mod_time(object_mod_time), m_file_has_changed(false),
240 m_first_file_changed_log(false) {
241 // Scope for locker below...
242 {
243 std::lock_guard<std::recursive_mutex> guard(
244 GetAllocationModuleCollectionMutex());
245 GetModuleCollection().push_back(this);
246 }
247
248 if (object_name)
249 m_object_name = *object_name;
250
251 Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
252 if (log != nullptr)
253 LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
254 static_cast<void *>(this), m_arch.GetArchitectureName(),
255 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
256 m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
257}
258
259Module::Module() : m_file_has_changed(false), m_first_file_changed_log(false) {
260 std::lock_guard<std::recursive_mutex> guard(
261 GetAllocationModuleCollectionMutex());
262 GetModuleCollection().push_back(this);
263}
264
265Module::~Module() {
266 // Lock our module down while we tear everything down to make sure we don't
267 // get any access to the module while it is being destroyed
268 std::lock_guard<std::recursive_mutex> guard(m_mutex);
269 // Scope for locker below...
270 {
271 std::lock_guard<std::recursive_mutex> guard(
272 GetAllocationModuleCollectionMutex());
273 ModuleCollection &modules = GetModuleCollection();
274 ModuleCollection::iterator end = modules.end();
275 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
276 assert(pos != end);
277 modules.erase(pos);
278 }
279 Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
280 if (log != nullptr)
281 LLDB_LOGF(log, "%p Module::~Module((%s) '%s%s%s%s')",
282 static_cast<void *>(this), m_arch.GetArchitectureName(),
283 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
284 m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
285 // Release any auto pointers before we start tearing down our member
286 // variables since the object file and symbol files might need to make
287 // function calls back into this module object. The ordering is important
288 // here because symbol files can require the module object file. So we tear
289 // down the symbol file first, then the object file.
290 m_sections_up.reset();
291 m_symfile_up.reset();
292 m_objfile_sp.reset();
293}
294
295ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
296 lldb::addr_t header_addr, Status &error,
297 size_t size_to_read) {
298 if (m_objfile_sp) {
299 error.SetErrorString("object file already exists");
300 } else {
301 std::lock_guard<std::recursive_mutex> guard(m_mutex);
302 if (process_sp) {
303 m_did_load_objfile = true;
304 std::shared_ptr<DataBufferHeap> data_sp =
305 std::make_shared<DataBufferHeap>(size_to_read, 0);
306 Status readmem_error;
307 const size_t bytes_read =
308 process_sp->ReadMemory(header_addr, data_sp->GetBytes(),
309 data_sp->GetByteSize(), readmem_error);
310 if (bytes_read < size_to_read)
311 data_sp->SetByteSize(bytes_read);
312 if (data_sp->GetByteSize() > 0) {
313 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
314 header_addr, data_sp);
315 if (m_objfile_sp) {
316 StreamString s;
317 s.Printf("0x%16.16" PRIx64, header_addr);
318 m_object_name.SetString(s.GetString());
319
320 // Once we get the object file, update our module with the object
321 // file's architecture since it might differ in vendor/os if some
322 // parts were unknown.
323 m_arch = m_objfile_sp->GetArchitecture();
324
325 // Augment the arch with the target's information in case
326 // we are unable to extract the os/environment from memory.
327 m_arch.MergeFrom(process_sp->GetTarget().GetArchitecture());
328 } else {
329 error.SetErrorString("unable to find suitable object file plug-in");
330 }
331 } else {
332 error.SetErrorStringWithFormat("unable to read header from memory: %s",
333 readmem_error.AsCString());
334 }
335 } else {
336 error.SetErrorString("invalid process");
337 }
338 }
339 return m_objfile_sp.get();
340}
341
342const lldb_private::UUID &Module::GetUUID() {
343 if (!m_did_set_uuid.load()) {
344 std::lock_guard<std::recursive_mutex> guard(m_mutex);
345 if (!m_did_set_uuid.load()) {
346 ObjectFile *obj_file = GetObjectFile();
347
348 if (obj_file != nullptr) {
349 m_uuid = obj_file->GetUUID();
350 m_did_set_uuid = true;
351 }
352 }
353 }
354 return m_uuid;
355}
356
357void Module::SetUUID(const lldb_private::UUID &uuid) {
358 std::lock_guard<std::recursive_mutex> guard(m_mutex);
359 if (!m_did_set_uuid) {
360 m_uuid = uuid;
361 m_did_set_uuid = true;
362 } else {
363 lldbassert(0 && "Attempting to overwrite the existing module UUID");
364 }
365}
366
367llvm::Expected<TypeSystem &>
368Module::GetTypeSystemForLanguage(LanguageType language) {
369 return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
370}
371
372void Module::ParseAllDebugSymbols() {
373 std::lock_guard<std::recursive_mutex> guard(m_mutex);
374 size_t num_comp_units = GetNumCompileUnits();
375 if (num_comp_units == 0)
376 return;
377
378 SymbolFile *symbols = GetSymbolFile();
379
380 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) {
381 SymbolContext sc;
382 sc.module_sp = shared_from_this();
383 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
384 if (!sc.comp_unit)
385 continue;
386
387 symbols->ParseVariablesForContext(sc);
388
389 symbols->ParseFunctions(*sc.comp_unit);
390
391 sc.comp_unit->ForeachFunction([&sc, &symbols](const FunctionSP &f) {
392 symbols->ParseBlocksRecursive(*f);
393
394 // Parse the variables for this function and all its blocks
395 sc.function = f.get();
396 symbols->ParseVariablesForContext(sc);
397 return false;
398 });
399
400 // Parse all types for this compile unit
401 symbols->ParseTypes(*sc.comp_unit);
402 }
403}
404
405void Module::CalculateSymbolContext(SymbolContext *sc) {
406 sc->module_sp = shared_from_this();
407}
408
409ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
410
411void Module::DumpSymbolContext(Stream *s) {
412 s->Printf(", Module{%p}", static_cast<void *>(this));
413}
414
415size_t Module::GetNumCompileUnits() {
416 std::lock_guard<std::recursive_mutex> guard(m_mutex);
417 LLDB_SCOPED_TIMERF("Module::GetNumCompileUnits (module = %p)",
418 static_cast<void *>(this));
419 if (SymbolFile *symbols = GetSymbolFile())
420 return symbols->GetNumCompileUnits();
421 return 0;
422}
423
424CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
425 std::lock_guard<std::recursive_mutex> guard(m_mutex);
426 size_t num_comp_units = GetNumCompileUnits();
427 CompUnitSP cu_sp;
428
429 if (index < num_comp_units) {
430 if (SymbolFile *symbols = GetSymbolFile())
431 cu_sp = symbols->GetCompileUnitAtIndex(index);
432 }
433 return cu_sp;
434}
435
436bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
437 std::lock_guard<std::recursive_mutex> guard(m_mutex);
438 SectionList *section_list = GetSectionList();
439 if (section_list)
440 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
441 return false;
442}
443
444uint32_t Module::ResolveSymbolContextForAddress(
445 const Address &so_addr, lldb::SymbolContextItem resolve_scope,
446 SymbolContext &sc, bool resolve_tail_call_address) {
447 std::lock_guard<std::recursive_mutex> guard(m_mutex);
448 uint32_t resolved_flags = 0;
449
450 // Clear the result symbol context in case we don't find anything, but don't
451 // clear the target
452 sc.Clear(false);
453
454 // Get the section from the section/offset address.
455 SectionSP section_sp(so_addr.GetSection());
456
457 // Make sure the section matches this module before we try and match anything
458 if (section_sp && section_sp->GetModule().get() == this) {
459 // If the section offset based address resolved itself, then this is the
460 // right module.
461 sc.module_sp = shared_from_this();
462 resolved_flags |= eSymbolContextModule;
463
464 SymbolFile *symfile = GetSymbolFile();
465 if (!symfile)
466 return resolved_flags;
467
468 // Resolve the compile unit, function, block, line table or line entry if
469 // requested.
470 if (resolve_scope & eSymbolContextCompUnit ||
471 resolve_scope & eSymbolContextFunction ||
472 resolve_scope & eSymbolContextBlock ||
473 resolve_scope & eSymbolContextLineEntry ||
474 resolve_scope & eSymbolContextVariable) {
475 symfile->SetLoadDebugInfoEnabled();
476 resolved_flags |=
477 symfile->ResolveSymbolContext(so_addr, resolve_scope, sc);
478 }
479
480 // Resolve the symbol if requested, but don't re-look it up if we've
481 // already found it.
482 if (resolve_scope & eSymbolContextSymbol &&
483 !(resolved_flags & eSymbolContextSymbol)) {
484 Symtab *symtab = symfile->GetSymtab();
485 if (symtab && so_addr.IsSectionOffset()) {
486 Symbol *matching_symbol = nullptr;
487
488 symtab->ForEachSymbolContainingFileAddress(
489 so_addr.GetFileAddress(),
490 [&matching_symbol](Symbol *symbol) -> bool {
491 if (symbol->GetType() != eSymbolTypeInvalid) {
492 matching_symbol = symbol;
493 return false; // Stop iterating
494 }
495 return true; // Keep iterating
496 });
497 sc.symbol = matching_symbol;
498 if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
499 !(resolved_flags & eSymbolContextFunction)) {
500 bool verify_unique = false; // No need to check again since
501 // ResolveSymbolContext failed to find a
502 // symbol at this address.
503 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
504 sc.symbol =
505 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
506 }
507
508 if (sc.symbol) {
509 if (sc.symbol->IsSynthetic()) {
510 // We have a synthetic symbol so lets check if the object file from
511 // the symbol file in the symbol vendor is different than the
512 // object file for the module, and if so search its symbol table to
513 // see if we can come up with a better symbol. For example dSYM
514 // files on MacOSX have an unstripped symbol table inside of them.
515 ObjectFile *symtab_objfile = symtab->GetObjectFile();
516 if (symtab_objfile && symtab_objfile->IsStripped()) {
517 ObjectFile *symfile_objfile = symfile->GetObjectFile();
518 if (symfile_objfile != symtab_objfile) {
519 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
520 if (symfile_symtab) {
521 Symbol *symbol =
522 symfile_symtab->FindSymbolContainingFileAddress(
523 so_addr.GetFileAddress());
524 if (symbol && !symbol->IsSynthetic()) {
525 sc.symbol = symbol;
526 }
527 }
528 }
529 }
530 }
531 resolved_flags |= eSymbolContextSymbol;
532 }
533 }
534 }
535
536 // For function symbols, so_addr may be off by one. This is a convention
537 // consistent with FDE row indices in eh_frame sections, but requires extra
538 // logic here to permit symbol lookup for disassembly and unwind.
539 if (resolve_scope & eSymbolContextSymbol &&
540 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
541 so_addr.IsSectionOffset()) {
542 Address previous_addr = so_addr;
543 previous_addr.Slide(-1);
544
545 bool do_resolve_tail_call_address = false; // prevent recursion
546 const uint32_t flags = ResolveSymbolContextForAddress(
547 previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
548 if (flags & eSymbolContextSymbol) {
549 AddressRange addr_range;
550 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
551 false, addr_range)) {
552 if (addr_range.GetBaseAddress().GetSection() ==
553 so_addr.GetSection()) {
554 // If the requested address is one past the address range of a
555 // function (i.e. a tail call), or the decremented address is the
556 // start of a function (i.e. some forms of trampoline), indicate
557 // that the symbol has been resolved.
558 if (so_addr.GetOffset() ==
559 addr_range.GetBaseAddress().GetOffset() ||
560 so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() +
561 addr_range.GetByteSize()) {
562 resolved_flags |= flags;
563 }
564 } else {
565 sc.symbol =
566 nullptr; // Don't trust the symbol if the sections didn't match.
567 }
568 }
569 }
570 }
571 }
572 return resolved_flags;
573}
574
575uint32_t Module::ResolveSymbolContextForFilePath(
576 const char *file_path, uint32_t line, bool check_inlines,
577 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
578 FileSpec file_spec(file_path);
579 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
580 resolve_scope, sc_list);
581}
582
583uint32_t Module::ResolveSymbolContextsForFileSpec(
584 const FileSpec &file_spec, uint32_t line, bool check_inlines,
585 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
586 std::lock_guard<std::recursive_mutex> guard(m_mutex);
587 LLDB_SCOPED_TIMERF("Module::ResolveSymbolContextForFilePath (%s:%u, "
588 "check_inlines = %s, resolve_scope = 0x%8.8x)",
589 file_spec.GetPath().c_str(), line,
590 check_inlines ? "yes" : "no", resolve_scope);
591
592 const uint32_t initial_count = sc_list.GetSize();
593
594 if (SymbolFile *symbols = GetSymbolFile()) {
595 // TODO: Handle SourceLocationSpec column information
596 SourceLocationSpec location_spec(file_spec, line, /*column=*/llvm::None,
597 check_inlines, /*exact_match=*/false);
598
599 symbols->ResolveSymbolContext(location_spec, resolve_scope, sc_list);
600 }
601
602 return sc_list.GetSize() - initial_count;
603}
604
605void Module::FindGlobalVariables(ConstString name,
606 const CompilerDeclContext &parent_decl_ctx,
607 size_t max_matches, VariableList &variables) {
608 if (SymbolFile *symbols = GetSymbolFile())
609 symbols->FindGlobalVariables(name, parent_decl_ctx, max_matches, variables);
610}
611
612void Module::FindGlobalVariables(const RegularExpression &regex,
613 size_t max_matches, VariableList &variables) {
614 SymbolFile *symbols = GetSymbolFile();
615 if (symbols)
616 symbols->FindGlobalVariables(regex, max_matches, variables);
617}
618
619void Module::FindCompileUnits(const FileSpec &path,
620 SymbolContextList &sc_list) {
621 const size_t num_compile_units = GetNumCompileUnits();
622 SymbolContext sc;
623 sc.module_sp = shared_from_this();
624 for (size_t i = 0; i < num_compile_units; ++i) {
625 sc.comp_unit = GetCompileUnitAtIndex(i).get();
626 if (sc.comp_unit) {
627 if (FileSpec::Match(path, sc.comp_unit->GetPrimaryFile()))
628 sc_list.Append(sc);
629 }
630 }
631}
632
633Module::LookupInfo::LookupInfo(ConstString name,
634 FunctionNameType name_type_mask,
635 LanguageType language)
636 : m_name(name), m_lookup_name(), m_language(language) {
637 const char *name_cstr = name.GetCString();
638 llvm::StringRef basename;
639 llvm::StringRef context;
640
641 if (name_type_mask & eFunctionNameTypeAuto) {
642 if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
643 m_name_type_mask = eFunctionNameTypeFull;
644 else if ((language == eLanguageTypeUnknown ||
645 Language::LanguageIsObjC(language)) &&
646 ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
647 m_name_type_mask = eFunctionNameTypeFull;
648 else if (Language::LanguageIsC(language)) {
649 m_name_type_mask = eFunctionNameTypeFull;
650 } else {
651 if ((language == eLanguageTypeUnknown ||
652 Language::LanguageIsObjC(language)) &&
653 ObjCLanguage::IsPossibleObjCSelector(name_cstr))
654 m_name_type_mask |= eFunctionNameTypeSelector;
655
656 CPlusPlusLanguage::MethodName cpp_method(name);
657 basename = cpp_method.GetBasename();
658 if (basename.empty()) {
659 if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
660 basename))
661 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
662 else
663 m_name_type_mask |= eFunctionNameTypeFull;
664 } else {
665 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
666 }
667 }
668 } else {
669 m_name_type_mask = name_type_mask;
670 if (name_type_mask & eFunctionNameTypeMethod ||
671 name_type_mask & eFunctionNameTypeBase) {
672 // If they've asked for a CPP method or function name and it can't be
673 // that, we don't even need to search for CPP methods or names.
674 CPlusPlusLanguage::MethodName cpp_method(name);
675 if (cpp_method.IsValid()) {
676 basename = cpp_method.GetBasename();
677
678 if (!cpp_method.GetQualifiers().empty()) {
679 // There is a "const" or other qualifier following the end of the
680 // function parens, this can't be a eFunctionNameTypeBase
681 m_name_type_mask &= ~(eFunctionNameTypeBase);
682 if (m_name_type_mask == eFunctionNameTypeNone)
683 return;
684 }
685 } else {
686 // If the CPP method parser didn't manage to chop this up, try to fill
687 // in the base name if we can. If a::b::c is passed in, we need to just
688 // look up "c", and then we'll filter the result later.
689 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
690 basename);
691 }
692 }
693
694 if (name_type_mask & eFunctionNameTypeSelector) {
695 if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
696 m_name_type_mask &= ~(eFunctionNameTypeSelector);
697 if (m_name_type_mask == eFunctionNameTypeNone)
698 return;
699 }
700 }
701
702 // Still try and get a basename in case someone specifies a name type mask
703 // of eFunctionNameTypeFull and a name like "A::func"
704 if (basename.empty()) {
705 if (name_type_mask & eFunctionNameTypeFull &&
706 !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
707 CPlusPlusLanguage::MethodName cpp_method(name);
708 basename = cpp_method.GetBasename();
709 if (basename.empty())
710 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
711 basename);
712 }
713 }
714 }
715
716 if (!basename.empty()) {
717 // The name supplied was a partial C++ path like "a::count". In this case
718 // we want to do a lookup on the basename "count" and then make sure any
719 // matching results contain "a::count" so that it would match "b::a::count"
720 // and "a::count". This is why we set "match_name_after_lookup" to true
721 m_lookup_name.SetString(basename);
722 m_match_name_after_lookup = true;
723 } else {
724 // The name is already correct, just use the exact name as supplied, and we
725 // won't need to check if any matches contain "name"
726 m_lookup_name = name;
727 m_match_name_after_lookup = false;
728 }
729}
730
731bool Module::LookupInfo::NameMatchesLookupInfo(
732 ConstString function_name, LanguageType language_type) const {
733 // We always keep unnamed symbols
734 if (!function_name)
735 return true;
736
737 // If we match exactly, we can return early
738 if (m_name == function_name)
739 return true;
740
741 // If function_name is mangled, we'll need to demangle it.
742 // In the pathologial case where the function name "looks" mangled but is
743 // actually demangled (e.g. a method named _Zonk), this operation should be
744 // relatively inexpensive since no demangling is actually occuring. See
745 // Mangled::SetValue for more context.
746 const bool function_name_may_be_mangled =
747 Mangled::GetManglingScheme(function_name.GetStringRef()) !=
748 Mangled::eManglingSchemeNone;
749 ConstString demangled_function_name = function_name;
750 if (function_name_may_be_mangled) {
751 Mangled mangled_function_name(function_name);
752 demangled_function_name = mangled_function_name.GetDemangledName();
753 }
754
755 // If the symbol has a language, then let the language make the match.
756 // Otherwise just check that the demangled function name contains the
757 // demangled user-provided name.
758 if (Language *language = Language::FindPlugin(language_type))
759 return language->DemangledNameContainsPath(m_name.GetStringRef(),
760 demangled_function_name);
761
762 llvm::StringRef function_name_ref = demangled_function_name.GetStringRef();
763 return function_name_ref.contains(m_name.GetStringRef());
764}
765
766void Module::LookupInfo::Prune(SymbolContextList &sc_list,
767 size_t start_idx) const {
768 if (m_match_name_after_lookup && m_name) {
769 SymbolContext sc;
770 size_t i = start_idx;
771 while (i < sc_list.GetSize()) {
772 if (!sc_list.GetContextAtIndex(i, sc))
773 break;
774
775 bool keep_it =
776 NameMatchesLookupInfo(sc.GetFunctionName(), sc.GetLanguage());
777 if (keep_it)
778 ++i;
779 else
780 sc_list.RemoveContextAtIndex(i);
781 }
782 }
783
784 // If we have only full name matches we might have tried to set breakpoint on
785 // "func" and specified eFunctionNameTypeFull, but we might have found
786 // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
787 // "func()" and "func" should end up matching.
788 if (m_name_type_mask == eFunctionNameTypeFull) {
789 SymbolContext sc;
790 size_t i = start_idx;
791 while (i < sc_list.GetSize()) {
792 if (!sc_list.GetContextAtIndex(i, sc))
793 break;
794 // Make sure the mangled and demangled names don't match before we try to
795 // pull anything out
796 ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
797 ConstString full_name(sc.GetFunctionName());
798 if (mangled_name != m_name && full_name != m_name) {
799 CPlusPlusLanguage::MethodName cpp_method(full_name);
800 if (cpp_method.IsValid()) {
801 if (cpp_method.GetContext().empty()) {
802 if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
803 sc_list.RemoveContextAtIndex(i);
804 continue;
805 }
806 } else {
807 std::string qualified_name;
808 llvm::StringRef anon_prefix("(anonymous namespace)");
809 if (cpp_method.GetContext() == anon_prefix)
810 qualified_name = cpp_method.GetBasename().str();
811 else
812 qualified_name = cpp_method.GetScopeQualifiedName();
813 if (qualified_name != m_name.GetCString()) {
814 sc_list.RemoveContextAtIndex(i);
815 continue;
816 }
817 }
818 }
819 }
820 ++i;
821 }
822 }
823}
824
825void Module::FindFunctions(const Module::LookupInfo &lookup_info,
826 const CompilerDeclContext &parent_decl_ctx,
827 const ModuleFunctionSearchOptions &options,
828 SymbolContextList &sc_list) {
829 // Find all the functions (not symbols, but debug information functions...
830 if (SymbolFile *symbols = GetSymbolFile()) {
831 symbols->FindFunctions(lookup_info, parent_decl_ctx,
832 options.include_inlines, sc_list);
833 // Now check our symbol table for symbols that are code symbols if
834 // requested
835 if (options.include_symbols) {
836 if (Symtab *symtab = symbols->GetSymtab()) {
837 symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
838 lookup_info.GetNameTypeMask(), sc_list);
839 }
840 }
841 }
842}
843
844void Module::FindFunctions(ConstString name,
845 const CompilerDeclContext &parent_decl_ctx,
846 FunctionNameType name_type_mask,
847 const ModuleFunctionSearchOptions &options,
848 SymbolContextList &sc_list) {
849 const size_t old_size = sc_list.GetSize();
850 LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
851 FindFunctions(lookup_info, parent_decl_ctx, options, sc_list);
852 if (name_type_mask & eFunctionNameTypeAuto) {
853 const size_t new_size = sc_list.GetSize();
854 if (old_size < new_size)
855 lookup_info.Prune(sc_list, old_size);
856 }
857}
858
859void Module::FindFunctions(const RegularExpression &regex,
860 const ModuleFunctionSearchOptions &options,
861 SymbolContextList &sc_list) {
862 const size_t start_size = sc_list.GetSize();
863
864 if (SymbolFile *symbols = GetSymbolFile()) {
865 symbols->FindFunctions(regex, options.include_inlines, sc_list);
866
867 // Now check our symbol table for symbols that are code symbols if
868 // requested
869 if (options.include_symbols) {
870 Symtab *symtab = symbols->GetSymtab();
871 if (symtab) {
872 std::vector<uint32_t> symbol_indexes;
873 symtab->AppendSymbolIndexesMatchingRegExAndType(
874 regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
875 symbol_indexes);
876 const size_t num_matches = symbol_indexes.size();
877 if (num_matches) {
878 SymbolContext sc(this);
879 const size_t end_functions_added_index = sc_list.GetSize();
880 size_t num_functions_added_to_sc_list =
881 end_functions_added_index - start_size;
882 if (num_functions_added_to_sc_list == 0) {
883 // No functions were added, just symbols, so we can just append
884 // them
885 for (size_t i = 0; i < num_matches; ++i) {
886 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
887 SymbolType sym_type = sc.symbol->GetType();
888 if (sc.symbol && (sym_type == eSymbolTypeCode ||
889 sym_type == eSymbolTypeResolver))
890 sc_list.Append(sc);
891 }
892 } else {
893 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
894 FileAddrToIndexMap file_addr_to_index;
895 for (size_t i = start_size; i < end_functions_added_index; ++i) {
896 const SymbolContext &sc = sc_list[i];
897 if (sc.block)
898 continue;
899 file_addr_to_index[sc.function->GetAddressRange()
900 .GetBaseAddress()
901 .GetFileAddress()] = i;
902 }
903
904 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
905 // Functions were added so we need to merge symbols into any
906 // existing function symbol contexts
907 for (size_t i = start_size; i < num_matches; ++i) {
908 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
909 SymbolType sym_type = sc.symbol->GetType();
910 if (sc.symbol && sc.symbol->ValueIsAddress() &&
911 (sym_type == eSymbolTypeCode ||
912 sym_type == eSymbolTypeResolver)) {
913 FileAddrToIndexMap::const_iterator pos =
914 file_addr_to_index.find(
915 sc.symbol->GetAddressRef().GetFileAddress());
916 if (pos == end)
917 sc_list.Append(sc);
918 else
919 sc_list[pos->second].symbol = sc.symbol;
920 }
921 }
922 }
923 }
924 }
925 }
926 }
927}
928
929void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
930 const FileSpec &file, uint32_t line,
931 Function *function,
932 std::vector<Address> &output_local,
933 std::vector<Address> &output_extern) {
934 SearchFilterByModule filter(target_sp, m_file);
935
936 // TODO: Handle SourceLocationSpec column information
937 SourceLocationSpec location_spec(file, line, /*column=*/llvm::None,
938 /*check_inlines=*/true,
939 /*exact_match=*/false);
940 AddressResolverFileLine resolver(location_spec);
941 resolver.ResolveAddress(filter);
942
943 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
944 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
945 Function *f = addr.CalculateSymbolContextFunction();
946 if (f && f == function)
947 output_local.push_back(addr);
948 else
949 output_extern.push_back(addr);
950 }
951}
952
953void Module::FindTypes_Impl(
954 ConstString name, const CompilerDeclContext &parent_decl_ctx,
955 size_t max_matches,
956 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
957 TypeMap &types) {
958 if (SymbolFile *symbols = GetSymbolFile())
959 symbols->FindTypes(name, parent_decl_ctx, max_matches,
960 searched_symbol_files, types);
961}
962
963void Module::FindTypesInNamespace(ConstString type_name,
964 const CompilerDeclContext &parent_decl_ctx,
965 size_t max_matches, TypeList &type_list) {
966 TypeMap types_map;
967 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
968 FindTypes_Impl(type_name, parent_decl_ctx, max_matches, searched_symbol_files,
969 types_map);
970 if (types_map.GetSize()) {
971 SymbolContext sc;
972 sc.module_sp = shared_from_this();
973 sc.SortTypeList(types_map, type_list);
974 }
975}
976
977lldb::TypeSP Module::FindFirstType(const SymbolContext &sc, ConstString name,
978 bool exact_match) {
979 TypeList type_list;
980 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
981 FindTypes(name, exact_match, 1, searched_symbol_files, type_list);
982 if (type_list.GetSize())
983 return type_list.GetTypeAtIndex(0);
984 return TypeSP();
985}
986
987void Module::FindTypes(
988 ConstString name, bool exact_match, size_t max_matches,
989 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
990 TypeList &types) {
991 const char *type_name_cstr = name.GetCString();
992 llvm::StringRef type_scope;
993 llvm::StringRef type_basename;
994 TypeClass type_class = eTypeClassAny;
995 TypeMap typesmap;
996
997 if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
998 type_class)) {
999 // Check if "name" starts with "::" which means the qualified type starts
1000 // from the root namespace and implies and exact match. The typenames we
1001 // get back from clang do not start with "::" so we need to strip this off
1002 // in order to get the qualified names to match
1003 exact_match = type_scope.consume_front("::");
1004
1005 ConstString type_basename_const_str(type_basename);
1006 FindTypes_Impl(type_basename_const_str, CompilerDeclContext(), max_matches,
1007 searched_symbol_files, typesmap);
1008 if (typesmap.GetSize())
1009 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1010 exact_match);
1011 } else {
1012 // The type is not in a namespace/class scope, just search for it by
1013 // basename
1014 if (type_class != eTypeClassAny && !type_basename.empty()) {
1015 // The "type_name_cstr" will have been modified if we have a valid type
1016 // class prefix (like "struct", "class", "union", "typedef" etc).
1017 FindTypes_Impl(ConstString(type_basename), CompilerDeclContext(),
1018 UINT_MAX, searched_symbol_files, typesmap);
1019 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1020 exact_match);
1021 } else {
1022 FindTypes_Impl(name, CompilerDeclContext(), UINT_MAX,
1023 searched_symbol_files, typesmap);
1024 if (exact_match) {
1025 typesmap.RemoveMismatchedTypes(type_scope, name.GetStringRef(),
1026 type_class, exact_match);
1027 }
1028 }
1029 }
1030 if (typesmap.GetSize()) {
1031 SymbolContext sc;
1032 sc.module_sp = shared_from_this();
1033 sc.SortTypeList(typesmap, types);
1034 }
1035}
1036
1037void Module::FindTypes(
1038 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1039 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1040 TypeMap &types) {
1041 // If a scoped timer is needed, place it in a SymbolFile::FindTypes override.
1042 // A timer here is too high volume for some cases, for example when calling
1043 // FindTypes on each object file.
1044 if (SymbolFile *symbols = GetSymbolFile())
1045 symbols->FindTypes(pattern, languages, searched_symbol_files, types);
1046}
1047
1048SymbolFile *Module::GetSymbolFile(bool can_create, Stream *feedback_strm) {
1049 if (!m_did_load_symfile.load()) {
1050 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1051 if (!m_did_load_symfile.load() && can_create) {
1052 ObjectFile *obj_file = GetObjectFile();
1053 if (obj_file != nullptr) {
1054 LLDB_SCOPED_TIMER();
1055 m_symfile_up.reset(
1056 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1057 m_did_load_symfile = true;
1058 }
1059 }
1060 }
1061 return m_symfile_up ? m_symfile_up->GetSymbolFile() : nullptr;
1062}
1063
1064Symtab *Module::GetSymtab() {
1065 if (SymbolFile *symbols = GetSymbolFile())
1066 return symbols->GetSymtab();
1067 return nullptr;
1068}
1069
1070void Module::SetFileSpecAndObjectName(const FileSpec &file,
1071 ConstString object_name) {
1072 // Container objects whose paths do not specify a file directly can call this
1073 // function to correct the file and object names.
1074 m_file = file;
1075 m_mod_time = FileSystem::Instance().GetModificationTime(file);
1076 m_object_name = object_name;
1077}
1078
1079const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1080
1081std::string Module::GetSpecificationDescription() const {
1082 std::string spec(GetFileSpec().GetPath());
1083 if (m_object_name) {
1084 spec += '(';
1085 spec += m_object_name.GetCString();
1086 spec += ')';
1087 }
1088 return spec;
1089}
1090
1091void Module::GetDescription(llvm::raw_ostream &s,
1092 lldb::DescriptionLevel level) {
1093 if (level >= eDescriptionLevelFull) {
1094 if (m_arch.IsValid())
1095 s << llvm::formatv("({0}) ", m_arch.GetArchitectureName());
1096 }
1097
1098 if (level == eDescriptionLevelBrief) {
1099 const char *filename = m_file.GetFilename().GetCString();
1100 if (filename)
1101 s << filename;
1102 } else {
1103 char path[PATH_MAX];
1104 if (m_file.GetPath(path, sizeof(path)))
1105 s << path;
1106 }
1107
1108 const char *object_name = m_object_name.GetCString();
1109 if (object_name)
1110 s << llvm::formatv("({0})", object_name);
1111}
1112
1113bool Module::FileHasChanged() const {
1114 // We have provided the DataBuffer for this module to avoid accessing the
1115 // filesystem. We never want to reload those files.
1116 if (m_data_sp)
1117 return false;
1118 if (!m_file_has_changed)
1119 m_file_has_changed =
1120 (FileSystem::Instance().GetModificationTime(m_file) != m_mod_time);
1121 return m_file_has_changed;
1122}
1123
1124void Module::ReportWarningOptimization(
1125 llvm::Optional<lldb::user_id_t> debugger_id) {
1126 ConstString file_name = GetFileSpec().GetFilename();
1127 if (file_name.IsEmpty())
1128 return;
1129
1130 StreamString ss;
1131 ss << file_name.GetStringRef()
1132 << " was compiled with optimization - stepping may behave "
1133 "oddly; variables may not be available.";
1134 Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1135 &m_optimization_warning);
1136}
1137
1138void Module::ReportWarningUnsupportedLanguage(
1139 LanguageType language, llvm::Optional<lldb::user_id_t> debugger_id) {
1140 StreamString ss;
1141 ss << "This version of LLDB has no plugin for the language \""
1142 << Language::GetNameForLanguageType(language)
1143 << "\". "
1144 "Inspection of frame variables will be limited.";
1145 Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1146 &m_language_warning);
1147}
1148
1149void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1150 if (!m_first_file_changed_log) {
1151 if (FileHasChanged()) {
1152 m_first_file_changed_log = true;
1153 if (format) {
1154 StreamString strm;
1155 strm.PutCString("the object file ");
1156 GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1157 strm.PutCString(" has been modified\n");
1158
1159 va_list args;
1160 va_start(args, format);
1161 strm.PrintfVarArg(format, args);
1162 va_end(args);
1163
1164 const int format_len = strlen(format);
1165 if (format_len > 0) {
1166 const char last_char = format[format_len - 1];
1167 if (last_char != '\n' && last_char != '\r')
1168 strm.EOL();
1169 }
1170 strm.PutCString("The debug session should be aborted as the original "
1171 "debug information has been overwritten.");
1172 Debugger::ReportError(std::string(strm.GetString()));
1173 }
1174 }
1175 }
1176}
1177
1178void Module::ReportError(const char *format, ...) {
1179 if (format && format[0]) {
1180 StreamString strm;
1181 GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelBrief);
1182 strm.PutChar(' ');
1183
1184 va_list args;
1185 va_start(args, format);
1186 strm.PrintfVarArg(format, args);
1187 va_end(args);
1188
1189 Debugger::ReportError(std::string(strm.GetString()));
1190 }
1191}
1192
1193void Module::ReportWarning(const char *format, ...) {
1194 if (format && format[0]) {
1195 StreamString strm;
1196 GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1197 strm.PutChar(' ');
1198
1199 va_list args;
1200 va_start(args, format);
1201 strm.PrintfVarArg(format, args);
1202 va_end(args);
1203
1204 Debugger::ReportWarning(std::string(strm.GetString()));
1205 }
1206}
1207
1208void Module::LogMessage(Log *log, const char *format, ...) {
1209 if (log != nullptr) {
1210 StreamString log_message;
1211 GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1212 log_message.PutCString(": ");
1213 va_list args;
1214 va_start(args, format);
1215 log_message.PrintfVarArg(format, args);
1216 va_end(args);
1217 log->PutCString(log_message.GetData());
1218 }
1219}
1220
1221void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1222 if (log != nullptr) {
1223 StreamString log_message;
1224 GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1225 log_message.PutCString(": ");
1226 va_list args;
1227 va_start(args, format);
1228 log_message.PrintfVarArg(format, args);
1229 va_end(args);
1230 if (log->GetVerbose()) {
1231 std::string back_trace;
1232 llvm::raw_string_ostream stream(back_trace);
1233 llvm::sys::PrintStackTrace(stream);
1234 log_message.PutCString(back_trace);
1235 }
1236 log->PutCString(log_message.GetData());
1237 }
1238}
1239
1240void Module::Dump(Stream *s) {
1241 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1242 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1243 s->Indent();
1244 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1245 m_object_name ? "(" : "",
1246 m_object_name ? m_object_name.GetCString() : "",
1247 m_object_name ? ")" : "");
1248
1249 s->IndentMore();
1250
1251 ObjectFile *objfile = GetObjectFile();
1252 if (objfile)
1253 objfile->Dump(s);
1254
1255 if (SymbolFile *symbols = GetSymbolFile())
1256 symbols->Dump(*s);
1257
1258 s->IndentLess();
1259}
1260
1261ConstString Module::GetObjectName() const { return m_object_name; }
1262
1263ObjectFile *Module::GetObjectFile() {
1264 if (!m_did_load_objfile.load()) {
1265 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1266 if (!m_did_load_objfile.load()) {
1267 LLDB_SCOPED_TIMERF("Module::GetObjectFile () module = %s",
1268 GetFileSpec().GetFilename().AsCString(""));
1269 lldb::offset_t data_offset = 0;
1270 lldb::offset_t file_size = 0;
1271
1272 if (m_data_sp)
1273 file_size = m_data_sp->GetByteSize();
1274 else if (m_file)
1275 file_size = FileSystem::Instance().GetByteSize(m_file);
1276
1277 if (file_size > m_object_offset) {
1278 m_did_load_objfile = true;
1279 // FindPlugin will modify its data_sp argument. Do not let it
1280 // modify our m_data_sp member.
1281 auto data_sp = m_data_sp;
1282 m_objfile_sp = ObjectFile::FindPlugin(
1283 shared_from_this(), &m_file, m_object_offset,
1284 file_size - m_object_offset, data_sp, data_offset);
1285 if (m_objfile_sp) {
1286 // Once we get the object file, update our module with the object
1287 // file's architecture since it might differ in vendor/os if some
1288 // parts were unknown. But since the matching arch might already be
1289 // more specific than the generic COFF architecture, only merge in
1290 // those values that overwrite unspecified unknown values.
1291 m_arch.MergeFrom(m_objfile_sp->GetArchitecture());
1292 } else {
1293 ReportError("failed to load objfile for %s",
1294 GetFileSpec().GetPath().c_str());
1295 }
1296 }
1297 }
1298 }
1299 return m_objfile_sp.get();
1300}
1301
1302SectionList *Module::GetSectionList() {
1303 // Populate m_sections_up with sections from objfile.
1304 if (!m_sections_up) {
1305 ObjectFile *obj_file = GetObjectFile();
1306 if (obj_file != nullptr)
1307 obj_file->CreateSections(*GetUnifiedSectionList());
1308 }
1309 return m_sections_up.get();
1310}
1311
1312void Module::SectionFileAddressesChanged() {
1313 ObjectFile *obj_file = GetObjectFile();
1314 if (obj_file)
1315 obj_file->SectionFileAddressesChanged();
1316 if (SymbolFile *symbols = GetSymbolFile())
1317 symbols->SectionFileAddressesChanged();
1318}
1319
1320UnwindTable &Module::GetUnwindTable() {
1321 if (!m_unwind_table) {
1322 m_unwind_table.emplace(*this);
1323 if (!m_symfile_spec)
1324 Symbols::DownloadSymbolFileAsync(GetUUID());
1325 }
1326 return *m_unwind_table;
1327}
1328
1329SectionList *Module::GetUnifiedSectionList() {
1330 if (!m_sections_up)
1331 m_sections_up = std::make_unique<SectionList>();
1332 return m_sections_up.get();
1333}
1334
1335const Symbol *Module::FindFirstSymbolWithNameAndType(ConstString name,
1336 SymbolType symbol_type) {
1337 LLDB_SCOPED_TIMERF(
1338 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1339 name.AsCString(), symbol_type);
1340 if (Symtab *symtab = GetSymtab())
1341 return symtab->FindFirstSymbolWithNameAndType(
1342 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1343 return nullptr;
1344}
1345void Module::SymbolIndicesToSymbolContextList(
1346 Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1347 SymbolContextList &sc_list) {
1348 // No need to protect this call using m_mutex all other method calls are
1349 // already thread safe.
1350
1351 size_t num_indices = symbol_indexes.size();
1352 if (num_indices > 0) {
1353 SymbolContext sc;
1354 CalculateSymbolContext(&sc);
1355 for (size_t i = 0; i < num_indices; i++) {
1356 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1357 if (sc.symbol)
1358 sc_list.Append(sc);
1359 }
1360 }
1361}
1362
1363void Module::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
1364 SymbolContextList &sc_list) {
1365 LLDB_SCOPED_TIMERF("Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1366 name.AsCString(), name_type_mask);
1367 if (Symtab *symtab = GetSymtab())
1368 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1369}
1370
1371void Module::FindSymbolsWithNameAndType(ConstString name,
1372 SymbolType symbol_type,
1373 SymbolContextList &sc_list) {
1374 // No need to protect this call using m_mutex all other method calls are
1375 // already thread safe.
1376 if (Symtab *symtab = GetSymtab()) {
1377 std::vector<uint32_t> symbol_indexes;
1378 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1379 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1380 }
1381}
1382
1383void Module::FindSymbolsMatchingRegExAndType(
1384 const RegularExpression &regex, SymbolType symbol_type,
1385 SymbolContextList &sc_list, Mangled::NamePreference mangling_preference) {
1386 // No need to protect this call using m_mutex all other method calls are
1387 // already thread safe.
1388 LLDB_SCOPED_TIMERF(
1389 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1390 regex.GetText().str().c_str(), symbol_type);
1391 if (Symtab *symtab = GetSymtab()) {
1392 std::vector<uint32_t> symbol_indexes;
1393 symtab->FindAllSymbolsMatchingRexExAndType(
1394 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1395 symbol_indexes, mangling_preference);
1396 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1397 }
1398}
1399
1400void Module::PreloadSymbols() {
1401 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1402 SymbolFile *sym_file = GetSymbolFile();
1403 if (!sym_file)
1404 return;
1405
1406 // Load the object file symbol table and any symbols from the SymbolFile that
1407 // get appended using SymbolFile::AddSymbols(...).
1408 if (Symtab *symtab = sym_file->GetSymtab())
1409 symtab->PreloadSymbols();
1410
1411 // Now let the symbol file preload its data and the symbol table will be
1412 // available without needing to take the module lock.
1413 sym_file->PreloadSymbols();
1414}
1415
1416void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1417 if (!FileSystem::Instance().Exists(file))
1418 return;
1419 if (m_symfile_up) {
1420 // Remove any sections in the unified section list that come from the
1421 // current symbol vendor.
1422 SectionList *section_list = GetSectionList();
1423 SymbolFile *symbol_file = GetSymbolFile();
1424 if (section_list && symbol_file) {
1425 ObjectFile *obj_file = symbol_file->GetObjectFile();
1426 // Make sure we have an object file and that the symbol vendor's objfile
1427 // isn't the same as the module's objfile before we remove any sections
1428 // for it...
1429 if (obj_file) {
1430 // Check to make sure we aren't trying to specify the file we already
1431 // have
1432 if (obj_file->GetFileSpec() == file) {
1433 // We are being told to add the exact same file that we already have
1434 // we don't have to do anything.
1435 return;
1436 }
1437
1438 // Cleare the current symtab as we are going to replace it with a new
1439 // one
1440 obj_file->ClearSymtab();
1441
1442 // Clear the unwind table too, as that may also be affected by the
1443 // symbol file information.
1444 m_unwind_table.reset();
1445
1446 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1447 // instead of a full path to the symbol file within the bundle
1448 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1449 // check this
1450
1451 if (FileSystem::Instance().IsDirectory(file)) {
1452 std::string new_path(file.GetPath());
1453 std::string old_path(obj_file->GetFileSpec().GetPath());
1454 if (llvm::StringRef(old_path).startswith(new_path)) {
1455 // We specified the same bundle as the symbol file that we already
1456 // have
1457 return;
1458 }
1459 }
1460
1461 if (obj_file != m_objfile_sp.get()) {
1462 size_t num_sections = section_list->GetNumSections(0);
1463 for (size_t idx = num_sections; idx > 0; --idx) {
1464 lldb::SectionSP section_sp(
1465 section_list->GetSectionAtIndex(idx - 1));
1466 if (section_sp->GetObjectFile() == obj_file) {
1467 section_list->DeleteSection(idx - 1);
1468 }
1469 }
1470 }
1471 }
1472 }
1473 // Keep all old symbol files around in case there are any lingering type
1474 // references in any SBValue objects that might have been handed out.
1475 m_old_symfiles.push_back(std::move(m_symfile_up));
1476 }
1477 m_symfile_spec = file;
1478 m_symfile_up.reset();
1479 m_did_load_symfile = false;
1480}
1481
1482bool Module::IsExecutable() {
1483 if (GetObjectFile() == nullptr)
1484 return false;
1485 else
1486 return GetObjectFile()->IsExecutable();
1487}
1488
1489bool Module::IsLoadedInTarget(Target *target) {
1490 ObjectFile *obj_file = GetObjectFile();
1491 if (obj_file) {
1492 SectionList *sections = GetSectionList();
1493 if (sections != nullptr) {
1494 size_t num_sections = sections->GetSize();
1495 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1496 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1497 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1498 return true;
1499 }
1500 }
1501 }
1502 }
1503 return false;
1504}
1505
1506bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1507 Stream *feedback_stream) {
1508 if (!target) {
1509 error.SetErrorString("invalid destination Target");
1510 return false;
1511 }
1512
1513 LoadScriptFromSymFile should_load =
1514 target->TargetProperties::GetLoadScriptFromSymbolFile();
1515
1516 if (should_load == eLoadScriptFromSymFileFalse)
1517 return false;
1518
1519 Debugger &debugger = target->GetDebugger();
1520 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1521 if (script_language != eScriptLanguageNone) {
1522
1523 PlatformSP platform_sp(target->GetPlatform());
1524
1525 if (!platform_sp) {
1526 error.SetErrorString("invalid Platform");
1527 return false;
1528 }
1529
1530 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1531 target, *this, feedback_stream);
1532
1533 const uint32_t num_specs = file_specs.GetSize();
1534 if (num_specs) {
1535 ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1536 if (script_interpreter) {
1537 for (uint32_t i = 0; i < num_specs; ++i) {
1538 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1539 if (scripting_fspec &&
1540 FileSystem::Instance().Exists(scripting_fspec)) {
1541 if (should_load == eLoadScriptFromSymFileWarn) {
1542 if (feedback_stream)
1543 feedback_stream->Printf(
1544 "warning: '%s' contains a debug script. To run this script "
1545 "in "
1546 "this debug session:\n\n command script import "
1547 "\"%s\"\n\n"
1548 "To run all discovered debug scripts in this session:\n\n"
1549 " settings set target.load-script-from-symbol-file "
1550 "true\n",
1551 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1552 scripting_fspec.GetPath().c_str());
1553 return false;
1554 }
1555 StreamString scripting_stream;
1556 scripting_fspec.Dump(scripting_stream.AsRawOstream());
1557 LoadScriptOptions options;
1558 bool did_load = script_interpreter->LoadScriptingModule(
1559 scripting_stream.GetData(), options, error);
1560 if (!did_load)
1561 return false;
1562 }
1563 }
1564 } else {
1565 error.SetErrorString("invalid ScriptInterpreter");
1566 return false;
1567 }
1568 }
1569 }
1570 return true;
1571}
1572
1573bool Module::SetArchitecture(const ArchSpec &new_arch) {
1574 if (!m_arch.IsValid()) {
1575 m_arch = new_arch;
1576 return true;
1577 }
1578 return m_arch.IsCompatibleMatch(new_arch);
1579}
1580
1581bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1582 bool value_is_offset, bool &changed) {
1583 ObjectFile *object_file = GetObjectFile();
1584 if (object_file != nullptr) {
1585 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1586 return true;
1587 } else {
1588 changed = false;
1589 }
1590 return false;
1591}
1592
1593bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1594 const UUID &uuid = module_ref.GetUUID();
1595
1596 if (uuid.IsValid()) {
1597 // If the UUID matches, then nothing more needs to match...
1598 return (uuid == GetUUID());
1599 }
1600
1601 const FileSpec &file_spec = module_ref.GetFileSpec();
1602 if (!FileSpec::Match(file_spec, m_file) &&
1603 !FileSpec::Match(file_spec, m_platform_file))
1604 return false;
1605
1606 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1607 if (!FileSpec::Match(platform_file_spec, GetPlatformFileSpec()))
1608 return false;
1609
1610 const ArchSpec &arch = module_ref.GetArchitecture();
1611 if (arch.IsValid()) {
1612 if (!m_arch.IsCompatibleMatch(arch))
1613 return false;
1614 }
1615
1616 ConstString object_name = module_ref.GetObjectName();
1617 if (object_name) {
1618 if (object_name != GetObjectName())
1619 return false;
1620 }
1621 return true;
1622}
1623
1624bool Module::FindSourceFile(const FileSpec &orig_spec,
1625 FileSpec &new_spec) const {
1626 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1627 if (auto remapped = m_source_mappings.FindFile(orig_spec)) {
1628 new_spec = *remapped;
1629 return true;
1630 }
1631 return false;
1632}
1633
1634llvm::Optional<std::string>
1635Module::RemapSourceFile(llvm::StringRef path) const {
1636 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1637 if (auto remapped = m_source_mappings.RemapPath(path))
1638 return remapped->GetPath();
1639 return {};
1640}
1641
1642void Module::RegisterXcodeSDK(llvm::StringRef sdk_name,
1643 llvm::StringRef sysroot) {
1644 XcodeSDK sdk(sdk_name.str());
1645 llvm::StringRef sdk_path(HostInfo::GetXcodeSDKPath(sdk));
1646 if (sdk_path.empty())
1647 return;
1648 // If the SDK changed for a previously registered source path, update it.
1649 // This could happend with -fdebug-prefix-map, otherwise it's unlikely.
1650 if (!m_source_mappings.Replace(sysroot, sdk_path, true))
1651 // In the general case, however, append it to the list.
1652 m_source_mappings.Append(sysroot, sdk_path, false);
1653}
1654
1655bool Module::MergeArchitecture(const ArchSpec &arch_spec) {
1656 if (!arch_spec.IsValid())
1657 return false;
1658 LLDB_LOGF(GetLog(LLDBLog::Object | LLDBLog::Modules),
1659 "module has arch %s, merging/replacing with arch %s",
1660 m_arch.GetTriple().getTriple().c_str(),
1661 arch_spec.GetTriple().getTriple().c_str());
1662 if (!m_arch.IsCompatibleMatch(arch_spec)) {
1663 // The new architecture is different, we just need to replace it.
1664 return SetArchitecture(arch_spec);
1665 }
1666
1667 // Merge bits from arch_spec into "merged_arch" and set our architecture.
1668 ArchSpec merged_arch(m_arch);
1669 merged_arch.MergeFrom(arch_spec);
1670 // SetArchitecture() is a no-op if m_arch is already valid.
1671 m_arch = ArchSpec();
1672 return SetArchitecture(merged_arch);
1673}
1674
1675llvm::VersionTuple Module::GetVersion() {
1676 if (ObjectFile *obj_file = GetObjectFile())
1677 return obj_file->GetVersion();
1678 return llvm::VersionTuple();
1679}
1680
1681bool Module::GetIsDynamicLinkEditor() {
1682 ObjectFile *obj_file = GetObjectFile();
1683
1684 if (obj_file)
1685 return obj_file->GetIsDynamicLinkEditor();
1686
1687 return false;
1688}
1689
1690uint32_t Module::Hash() {
1691 std::string identifier;
1692 llvm::raw_string_ostream id_strm(identifier);
1693 id_strm << m_arch.GetTriple().str() << '-' << m_file.GetPath();
1694 if (m_object_name)
1695 id_strm << '(' << m_object_name.GetStringRef() << ')';
1696 if (m_object_offset > 0)
1697 id_strm << m_object_offset;
1698 const auto mtime = llvm::sys::toTimeT(m_object_mod_time);
1699 if (mtime > 0)
1700 id_strm << mtime;
1701 return llvm::djbHash(id_strm.str());
1702}
1703
1704std::string Module::GetCacheKey() {
1705 std::string key;
1706 llvm::raw_string_ostream strm(key);
1707 strm << m_arch.GetTriple().str() << '-' << m_file.GetFilename();
1708 if (m_object_name)
1709 strm << '(' << m_object_name.GetStringRef() << ')';
1710 strm << '-' << llvm::format_hex(Hash(), 10);
1711 return strm.str();
1712}
1713
1714DataFileCache *Module::GetIndexCache() {
1715 if (!ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
1716 return nullptr;
1717 // NOTE: intentional leak so we don't crash if global destructor chain gets
1718 // called as other threads still use the result of this function
1719 static DataFileCache *g_data_file_cache =
1720 new DataFileCache(ModuleList::GetGlobalModuleListProperties()
1721 .GetLLDBIndexCachePath()
1722 .GetPath());
1723 return g_data_file_cache;
1724}
1725

source code of lldb/source/Core/Module.cpp