• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Module.h ------------------------------------------------*- C++ -*-===//
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 #ifndef LLDB_CORE_MODULE_H
10 #define LLDB_CORE_MODULE_H
11 
12 #include "lldb/Core/Address.h"
13 #include "lldb/Core/ModuleList.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 #include "lldb/Symbol/SymbolContextScope.h"
17 #include "lldb/Symbol/TypeSystem.h"
18 #include "lldb/Target/PathMappingList.h"
19 #include "lldb/Utility/ArchSpec.h"
20 #include "lldb/Utility/ConstString.h"
21 #include "lldb/Utility/FileSpec.h"
22 #include "lldb/Utility/Status.h"
23 #include "lldb/Utility/XcodeSDK.h"
24 #include "lldb/Utility/UUID.h"
25 #include "lldb/lldb-defines.h"
26 #include "lldb/lldb-enumerations.h"
27 #include "lldb/lldb-forward.h"
28 #include "lldb/lldb-types.h"
29 
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Support/Chrono.h"
33 
34 #include <atomic>
35 #include <memory>
36 #include <mutex>
37 #include <stddef.h>
38 #include <stdint.h>
39 #include <string>
40 #include <vector>
41 
42 namespace lldb_private {
43 class CompilerDeclContext;
44 class Function;
45 class Log;
46 class ObjectFile;
47 class RegularExpression;
48 class SectionList;
49 class Stream;
50 class Symbol;
51 class SymbolContext;
52 class SymbolContextList;
53 class SymbolFile;
54 class Symtab;
55 class Target;
56 class TypeList;
57 class TypeMap;
58 class VariableList;
59 
60 /// \class Module Module.h "lldb/Core/Module.h"
61 /// A class that describes an executable image and its associated
62 ///        object and symbol files.
63 ///
64 /// The module is designed to be able to select a single slice of an
65 /// executable image as it would appear on disk and during program execution.
66 ///
67 /// Modules control when and if information is parsed according to which
68 /// accessors are called. For example the object file (ObjectFile)
69 /// representation will only be parsed if the object file is requested using
70 /// the Module::GetObjectFile() is called. The debug symbols will only be
71 /// parsed if the symbol file (SymbolFile) is requested using the
72 /// Module::GetSymbolFile() method.
73 ///
74 /// The module will parse more detailed information as more queries are made.
75 class Module : public std::enable_shared_from_this<Module>,
76                public SymbolContextScope {
77 public:
78   // Static functions that can track the lifetime of module objects. This is
79   // handy because we might have Module objects that are in shared pointers
80   // that aren't in the global module list (from ModuleList). If this is the
81   // case we need to know about it. The modules in the global list maintained
82   // by these functions can be viewed using the "target modules list" command
83   // using the "--global" (-g for short).
84   static size_t GetNumberAllocatedModules();
85 
86   static Module *GetAllocatedModuleAtIndex(size_t idx);
87 
88   static std::recursive_mutex &GetAllocationModuleCollectionMutex();
89 
90   /// Construct with file specification and architecture.
91   ///
92   /// Clients that wish to share modules with other targets should use
93   /// ModuleList::GetSharedModule().
94   ///
95   /// \param[in] file_spec
96   ///     The file specification for the on disk representation of
97   ///     this executable image.
98   ///
99   /// \param[in] arch
100   ///     The architecture to set as the current architecture in
101   ///     this module.
102   ///
103   /// \param[in] object_name
104   ///     The name of an object in a module used to extract a module
105   ///     within a module (.a files and modules that contain multiple
106   ///     architectures).
107   ///
108   /// \param[in] object_offset
109   ///     The offset within an existing module used to extract a
110   ///     module within a module (.a files and modules that contain
111   ///     multiple architectures).
112   Module(
113       const FileSpec &file_spec, const ArchSpec &arch,
114       const ConstString *object_name = nullptr,
115       lldb::offset_t object_offset = 0,
116       const llvm::sys::TimePoint<> &object_mod_time = llvm::sys::TimePoint<>());
117 
118   Module(const ModuleSpec &module_spec);
119 
120   template <typename ObjFilePlugin, typename... Args>
CreateModuleFromObjectFile(Args &&...args)121   static lldb::ModuleSP CreateModuleFromObjectFile(Args &&... args) {
122     // Must create a module and place it into a shared pointer before we can
123     // create an object file since it has a std::weak_ptr back to the module,
124     // so we need to control the creation carefully in this static function
125     lldb::ModuleSP module_sp(new Module());
126     module_sp->m_objfile_sp =
127         std::make_shared<ObjFilePlugin>(module_sp, std::forward<Args>(args)...);
128     module_sp->m_did_load_objfile.store(true, std::memory_order_relaxed);
129 
130     // Once we get the object file, set module ArchSpec to the one we get from
131     // the object file. If the object file does not have an architecture, we
132     // consider the creation a failure.
133     ArchSpec arch = module_sp->m_objfile_sp->GetArchitecture();
134     if (!arch)
135       return nullptr;
136     module_sp->m_arch = arch;
137 
138     // Also copy the object file's FileSpec.
139     module_sp->m_file = module_sp->m_objfile_sp->GetFileSpec();
140     return module_sp;
141   }
142 
143   /// Destructor.
144   ~Module() override;
145 
146   bool MatchesModuleSpec(const ModuleSpec &module_ref);
147 
148   /// Set the load address for all sections in a module to be the file address
149   /// plus \a slide.
150   ///
151   /// Many times a module will be loaded in a target with a constant offset
152   /// applied to all top level sections. This function can set the load
153   /// address for all top level sections to be the section file address +
154   /// offset.
155   ///
156   /// \param[in] target
157   ///     The target in which to apply the section load addresses.
158   ///
159   /// \param[in] value
160   ///     if \a value_is_offset is true, then value is the offset to
161   ///     apply to all file addresses for all top level sections in
162   ///     the object file as each section load address is being set.
163   ///     If \a value_is_offset is false, then "value" is the new
164   ///     absolute base address for the image.
165   ///
166   /// \param[in] value_is_offset
167   ///     If \b true, then \a value is an offset to apply to each
168   ///     file address of each top level section.
169   ///     If \b false, then \a value is the image base address that
170   ///     will be used to rigidly slide all loadable sections.
171   ///
172   /// \param[out] changed
173   ///     If any section load addresses were changed in \a target,
174   ///     then \a changed will be set to \b true. Else \a changed
175   ///     will be set to false. This allows this function to be
176   ///     called multiple times on the same module for the same
177   ///     target. If the module hasn't moved, then \a changed will
178   ///     be false and no module updated notification will need to
179   ///     be sent out.
180   ///
181   /// \return
182   ///     /b True if any sections were successfully loaded in \a target,
183   ///     /b false otherwise.
184   bool SetLoadAddress(Target &target, lldb::addr_t value, bool value_is_offset,
185                       bool &changed);
186 
187   /// \copydoc SymbolContextScope::CalculateSymbolContext(SymbolContext*)
188   ///
189   /// \see SymbolContextScope
190   void CalculateSymbolContext(SymbolContext *sc) override;
191 
192   lldb::ModuleSP CalculateSymbolContextModule() override;
193 
194   void
195   GetDescription(llvm::raw_ostream &s,
196                  lldb::DescriptionLevel level = lldb::eDescriptionLevelFull);
197 
198   /// Get the module path and object name.
199   ///
200   /// Modules can refer to object files. In this case the specification is
201   /// simple and would return the path to the file:
202   ///
203   ///     "/usr/lib/foo.dylib"
204   ///
205   /// Modules can be .o files inside of a BSD archive (.a file). In this case,
206   /// the object specification will look like:
207   ///
208   ///     "/usr/lib/foo.a(bar.o)"
209   ///
210   /// There are many places where logging wants to log this fully qualified
211   /// specification, so we centralize this functionality here.
212   ///
213   /// \return
214   ///     The object path + object name if there is one.
215   std::string GetSpecificationDescription() const;
216 
217   /// Dump a description of this object to a Stream.
218   ///
219   /// Dump a description of the contents of this object to the supplied stream
220   /// \a s. The dumped content will be only what has been loaded or parsed up
221   /// to this point at which this function is called, so this is a good way to
222   /// see what has been parsed in a module.
223   ///
224   /// \param[in] s
225   ///     The stream to which to dump the object description.
226   void Dump(Stream *s);
227 
228   /// \copydoc SymbolContextScope::DumpSymbolContext(Stream*)
229   ///
230   /// \see SymbolContextScope
231   void DumpSymbolContext(Stream *s) override;
232 
233   /// Find a symbol in the object file's symbol table.
234   ///
235   /// \param[in] name
236   ///     The name of the symbol that we are looking for.
237   ///
238   /// \param[in] symbol_type
239   ///     If set to eSymbolTypeAny, find a symbol of any type that
240   ///     has a name that matches \a name. If set to any other valid
241   ///     SymbolType enumeration value, then search only for
242   ///     symbols that match \a symbol_type.
243   ///
244   /// \return
245   ///     Returns a valid symbol pointer if a symbol was found,
246   ///     nullptr otherwise.
247   const Symbol *FindFirstSymbolWithNameAndType(
248       ConstString name,
249       lldb::SymbolType symbol_type = lldb::eSymbolTypeAny);
250 
251   void FindSymbolsWithNameAndType(ConstString name,
252                                   lldb::SymbolType symbol_type,
253                                   SymbolContextList &sc_list);
254 
255   void FindSymbolsMatchingRegExAndType(const RegularExpression &regex,
256                                        lldb::SymbolType symbol_type,
257                                        SymbolContextList &sc_list);
258 
259   /// Find a function symbols in the object file's symbol table.
260   ///
261   /// \param[in] name
262   ///     The name of the symbol that we are looking for.
263   ///
264   /// \param[in] name_type_mask
265   ///     A mask that has one or more bitwise OR'ed values from the
266   ///     lldb::FunctionNameType enumeration type that indicate what
267   ///     kind of names we are looking for.
268   ///
269   /// \param[out] sc_list
270   ///     A list to append any matching symbol contexts to.
271   void FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
272                            SymbolContextList &sc_list);
273 
274   /// Find compile units by partial or full path.
275   ///
276   /// Finds all compile units that match \a path in all of the modules and
277   /// returns the results in \a sc_list.
278   ///
279   /// \param[in] path
280   ///     The name of the function we are looking for.
281   ///
282   /// \param[out] sc_list
283   ///     A symbol context list that gets filled in with all of the
284   ///     matches.
285   void FindCompileUnits(const FileSpec &path, SymbolContextList &sc_list);
286 
287   /// Find functions by name.
288   ///
289   /// If the function is an inlined function, it will have a block,
290   /// representing the inlined function, and the function will be the
291   /// containing function.  If it is not inlined, then the block will be NULL.
292   ///
293   /// \param[in] name
294   ///     The name of the compile unit we are looking for.
295   ///
296   /// \param[in] name_type_mask
297   ///     A bit mask of bits that indicate what kind of names should
298   ///     be used when doing the lookup. Bits include fully qualified
299   ///     names, base names, C++ methods, or ObjC selectors.
300   ///     See FunctionNameType for more details.
301   ///
302   /// \param[out] sc_list
303   ///     A symbol context list that gets filled in with all of the
304   ///     matches.
305   void FindFunctions(ConstString name,
306                      const CompilerDeclContext &parent_decl_ctx,
307                      lldb::FunctionNameType name_type_mask, bool symbols_ok,
308                      bool inlines_ok, SymbolContextList &sc_list);
309 
310   /// Find functions by name.
311   ///
312   /// If the function is an inlined function, it will have a block,
313   /// representing the inlined function, and the function will be the
314   /// containing function.  If it is not inlined, then the block will be NULL.
315   ///
316   /// \param[in] regex
317   ///     A regular expression to use when matching the name.
318   ///
319   /// \param[out] sc_list
320   ///     A symbol context list that gets filled in with all of the
321   ///     matches.
322   void FindFunctions(const RegularExpression &regex, bool symbols_ok,
323                      bool inlines_ok, SymbolContextList &sc_list);
324 
325   /// Find addresses by file/line
326   ///
327   /// \param[in] target_sp
328   ///     The target the addresses are desired for.
329   ///
330   /// \param[in] file
331   ///     Source file to locate.
332   ///
333   /// \param[in] line
334   ///     Source line to locate.
335   ///
336   /// \param[in] function
337   ///	    Optional filter function. Addresses within this function will be
338   ///     added to the 'local' list. All others will be added to the 'extern'
339   ///     list.
340   ///
341   /// \param[out] output_local
342   ///     All matching addresses within 'function'
343   ///
344   /// \param[out] output_extern
345   ///     All matching addresses not within 'function'
346   void FindAddressesForLine(const lldb::TargetSP target_sp,
347                             const FileSpec &file, uint32_t line,
348                             Function *function,
349                             std::vector<Address> &output_local,
350                             std::vector<Address> &output_extern);
351 
352   /// Find global and static variables by name.
353   ///
354   /// \param[in] name
355   ///     The name of the global or static variable we are looking
356   ///     for.
357   ///
358   /// \param[in] parent_decl_ctx
359   ///     If valid, a decl context that results must exist within
360   ///
361   /// \param[in] max_matches
362   ///     Allow the number of matches to be limited to \a
363   ///     max_matches. Specify UINT32_MAX to get all possible matches.
364   ///
365   /// \param[in] variable_list
366   ///     A list of variables that gets the matches appended to.
367   ///
368   void FindGlobalVariables(ConstString name,
369                            const CompilerDeclContext &parent_decl_ctx,
370                            size_t max_matches, VariableList &variable_list);
371 
372   /// Find global and static variables by regular expression.
373   ///
374   /// \param[in] regex
375   ///     A regular expression to use when matching the name.
376   ///
377   /// \param[in] max_matches
378   ///     Allow the number of matches to be limited to \a
379   ///     max_matches. Specify UINT32_MAX to get all possible matches.
380   ///
381   /// \param[in] variable_list
382   ///     A list of variables that gets the matches appended to.
383   ///
384   void FindGlobalVariables(const RegularExpression &regex, size_t max_matches,
385                            VariableList &variable_list);
386 
387   /// Find types by name.
388   ///
389   /// Type lookups in modules go through the SymbolFile. The SymbolFile needs to
390   /// be able to lookup types by basename and not the fully qualified typename.
391   /// This allows the type accelerator tables to stay small, even with heavily
392   /// templatized C++. The type search will then narrow down the search
393   /// results. If "exact_match" is true, then the type search will only match
394   /// exact type name matches. If "exact_match" is false, the type will match
395   /// as long as the base typename matches and as long as any immediate
396   /// containing namespaces/class scopes that are specified match. So to
397   /// search for a type "d" in "b::c", the name "b::c::d" can be specified and
398   /// it will match any class/namespace "b" which contains a class/namespace
399   /// "c" which contains type "d". We do this to allow users to not always
400   /// have to specify complete scoping on all expressions, but it also allows
401   /// for exact matching when required.
402   ///
403   /// \param[in] type_name
404   ///     The name of the type we are looking for that is a fully
405   ///     or partially qualified type name.
406   ///
407   /// \param[in] exact_match
408   ///     If \b true, \a type_name is fully qualified and must match
409   ///     exactly. If \b false, \a type_name is a partially qualified
410   ///     name where the leading namespaces or classes can be
411   ///     omitted to make finding types that a user may type
412   ///     easier.
413   ///
414   /// \param[out] types
415   ///     A type list gets populated with any matches.
416   ///
417   void
418   FindTypes(ConstString type_name, bool exact_match, size_t max_matches,
419             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
420             TypeList &types);
421 
422   /// Find types by name.
423   ///
424   /// This behaves like the other FindTypes method but allows to
425   /// specify a DeclContext and a language for the type being searched
426   /// for.
427   ///
428   /// \param searched_symbol_files
429   ///     Prevents one file from being visited multiple times.
430   void FindTypes(llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
431                  llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
432                  TypeMap &types);
433 
434   lldb::TypeSP FindFirstType(const SymbolContext &sc,
435                              ConstString type_name, bool exact_match);
436 
437   /// Find types by name that are in a namespace. This function is used by the
438   /// expression parser when searches need to happen in an exact namespace
439   /// scope.
440   ///
441   /// \param[in] type_name
442   ///     The name of a type within a namespace that should not include
443   ///     any qualifying namespaces (just a type basename).
444   ///
445   /// \param[out] type_list
446   ///     A type list gets populated with any matches.
447   void FindTypesInNamespace(ConstString type_name,
448                             const CompilerDeclContext &parent_decl_ctx,
449                             size_t max_matches, TypeList &type_list);
450 
451   /// Get const accessor for the module architecture.
452   ///
453   /// \return
454   ///     A const reference to the architecture object.
455   const ArchSpec &GetArchitecture() const;
456 
457   /// Get const accessor for the module file specification.
458   ///
459   /// This function returns the file for the module on the host system that is
460   /// running LLDB. This can differ from the path on the platform since we
461   /// might be doing remote debugging.
462   ///
463   /// \return
464   ///     A const reference to the file specification object.
GetFileSpec()465   const FileSpec &GetFileSpec() const { return m_file; }
466 
467   /// Get accessor for the module platform file specification.
468   ///
469   /// Platform file refers to the path of the module as it is known on the
470   /// remote system on which it is being debugged. For local debugging this is
471   /// always the same as Module::GetFileSpec(). But remote debugging might
472   /// mention a file "/usr/lib/liba.dylib" which might be locally downloaded
473   /// and cached. In this case the platform file could be something like:
474   /// "/tmp/lldb/platform-cache/remote.host.computer/usr/lib/liba.dylib" The
475   /// file could also be cached in a local developer kit directory.
476   ///
477   /// \return
478   ///     A const reference to the file specification object.
GetPlatformFileSpec()479   const FileSpec &GetPlatformFileSpec() const {
480     if (m_platform_file)
481       return m_platform_file;
482     return m_file;
483   }
484 
SetPlatformFileSpec(const FileSpec & file)485   void SetPlatformFileSpec(const FileSpec &file) { m_platform_file = file; }
486 
GetRemoteInstallFileSpec()487   const FileSpec &GetRemoteInstallFileSpec() const {
488     return m_remote_install_file;
489   }
490 
SetRemoteInstallFileSpec(const FileSpec & file)491   void SetRemoteInstallFileSpec(const FileSpec &file) {
492     m_remote_install_file = file;
493   }
494 
GetSymbolFileFileSpec()495   const FileSpec &GetSymbolFileFileSpec() const { return m_symfile_spec; }
496 
497   void PreloadSymbols();
498 
499   void SetSymbolFileFileSpec(const FileSpec &file);
500 
GetModificationTime()501   const llvm::sys::TimePoint<> &GetModificationTime() const {
502     return m_mod_time;
503   }
504 
GetObjectModificationTime()505   const llvm::sys::TimePoint<> &GetObjectModificationTime() const {
506     return m_object_mod_time;
507   }
508 
509   /// This callback will be called by SymbolFile implementations when
510   /// parsing a compile unit that contains SDK information.
511   /// \param sysroot will be added to the path remapping dictionary.
512   void RegisterXcodeSDK(llvm::StringRef sdk, llvm::StringRef sysroot);
513 
514   /// Tells whether this module is capable of being the main executable for a
515   /// process.
516   ///
517   /// \return
518   ///     \b true if it is, \b false otherwise.
519   bool IsExecutable();
520 
521   /// Tells whether this module has been loaded in the target passed in. This
522   /// call doesn't distinguish between whether the module is loaded by the
523   /// dynamic loader, or by a "target module add" type call.
524   ///
525   /// \param[in] target
526   ///    The target to check whether this is loaded in.
527   ///
528   /// \return
529   ///     \b true if it is, \b false otherwise.
530   bool IsLoadedInTarget(Target *target);
531 
532   bool LoadScriptingResourceInTarget(Target *target, Status &error,
533                                      Stream *feedback_stream = nullptr);
534 
535   /// Get the number of compile units for this module.
536   ///
537   /// \return
538   ///     The number of compile units that the symbol vendor plug-in
539   ///     finds.
540   size_t GetNumCompileUnits();
541 
542   lldb::CompUnitSP GetCompileUnitAtIndex(size_t idx);
543 
544   ConstString GetObjectName() const;
545 
GetObjectOffset()546   uint64_t GetObjectOffset() const { return m_object_offset; }
547 
548   /// Get the object file representation for the current architecture.
549   ///
550   /// If the object file has not been located or parsed yet, this function
551   /// will find the best ObjectFile plug-in that can parse Module::m_file.
552   ///
553   /// \return
554   ///     If Module::m_file does not exist, or no plug-in was found
555   ///     that can parse the file, or the object file doesn't contain
556   ///     the current architecture in Module::m_arch, nullptr will be
557   ///     returned, else a valid object file interface will be
558   ///     returned. The returned pointer is owned by this object and
559   ///     remains valid as long as the object is around.
560   virtual ObjectFile *GetObjectFile();
561 
562   /// Get the unified section list for the module. This is the section list
563   /// created by the module's object file and any debug info and symbol files
564   /// created by the symbol vendor.
565   ///
566   /// If the symbol vendor has not been loaded yet, this function will return
567   /// the section list for the object file.
568   ///
569   /// \return
570   ///     Unified module section list.
571   virtual SectionList *GetSectionList();
572 
573   /// Notify the module that the file addresses for the Sections have been
574   /// updated.
575   ///
576   /// If the Section file addresses for a module are updated, this method
577   /// should be called.  Any parts of the module, object file, or symbol file
578   /// that has cached those file addresses must invalidate or update its
579   /// cache.
580   virtual void SectionFileAddressesChanged();
581 
582   /// Returns a reference to the UnwindTable for this Module
583   ///
584   /// The UnwindTable contains FuncUnwinders objects for any function in this
585   /// Module.  If a FuncUnwinders object hasn't been created yet (i.e. the
586   /// function has yet to be unwound in a stack walk), it will be created when
587   /// requested.  Specifically, we do not create FuncUnwinders objects for
588   /// functions until they are needed.
589   ///
590   /// \return
591   ///     Returns the unwind table for this module. If this object has no
592   ///     associated object file, an empty UnwindTable is returned.
593   UnwindTable &GetUnwindTable();
594 
595   llvm::VersionTuple GetVersion();
596 
597   /// Load an object file from memory.
598   ///
599   /// If available, the size of the object file in memory may be passed to
600   /// avoid additional round trips to process memory. If the size is not
601   /// provided, a default value is used. This value should be large enough to
602   /// enable the ObjectFile plugins to read the header of the object file
603   /// without going back to the process.
604   ///
605   /// \return
606   ///     The object file loaded from memory or nullptr, if the operation
607   ///     failed (see the `error` for more information in that case).
608   ObjectFile *GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
609                                   lldb::addr_t header_addr, Status &error,
610                                   size_t size_to_read = 512);
611 
612   /// Get the module's symbol file
613   ///
614   /// If the symbol file has already been loaded, this function returns it. All
615   /// arguments are ignored. If the symbol file has not been located yet, and
616   /// the can_create argument is false, the function returns nullptr. If
617   /// can_create is true, this function will find the best SymbolFile plug-in
618   /// that can use the current object file. feedback_strm, if not null, is used
619   /// to report the details of the search process.
620   virtual SymbolFile *GetSymbolFile(bool can_create = true,
621                                     Stream *feedback_strm = nullptr);
622 
623   Symtab *GetSymtab();
624 
625   /// Get a reference to the UUID value contained in this object.
626   ///
627   /// If the executable image file doesn't not have a UUID value built into
628   /// the file format, an MD5 checksum of the entire file, or slice of the
629   /// file for the current architecture should be used.
630   ///
631   /// \return
632   ///     A const pointer to the internal copy of the UUID value in
633   ///     this module if this module has a valid UUID value, NULL
634   ///     otherwise.
635   const lldb_private::UUID &GetUUID();
636 
637   /// A debugging function that will cause everything in a module to
638   /// be parsed.
639   ///
640   /// All compile units will be parsed, along with all globals and static
641   /// variables and all functions for those compile units. All types, scopes,
642   /// local variables, static variables, global variables, and line tables
643   /// will be parsed. This can be used prior to dumping a module to see a
644   /// complete list of the resulting debug information that gets parsed, or as
645   /// a debug function to ensure that the module can consume all of the debug
646   /// data the symbol vendor provides.
647   void ParseAllDebugSymbols();
648 
649   bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr);
650 
651   /// Resolve the symbol context for the given address.
652   ///
653   /// Tries to resolve the matching symbol context based on a lookup from the
654   /// current symbol vendor.  If the lazy lookup fails, an attempt is made to
655   /// parse the eh_frame section to handle stripped symbols.  If this fails,
656   /// an attempt is made to resolve the symbol to the previous address to
657   /// handle the case of a function with a tail call.
658   ///
659   /// Use properties of the modified SymbolContext to inspect any resolved
660   /// target, module, compilation unit, symbol, function, function block or
661   /// line entry.  Use the return value to determine which of these properties
662   /// have been modified.
663   ///
664   /// \param[in] so_addr
665   ///     A load address to resolve.
666   ///
667   /// \param[in] resolve_scope
668   ///     The scope that should be resolved (see SymbolContext::Scope).
669   ///     A combination of flags from the enumeration SymbolContextItem
670   ///     requesting a resolution depth.  Note that the flags that are
671   ///     actually resolved may be a superset of the requested flags.
672   ///     For instance, eSymbolContextSymbol requires resolution of
673   ///     eSymbolContextModule, and eSymbolContextFunction requires
674   ///     eSymbolContextSymbol.
675   ///
676   /// \param[out] sc
677   ///     The SymbolContext that is modified based on symbol resolution.
678   ///
679   /// \param[in] resolve_tail_call_address
680   ///     Determines if so_addr should resolve to a symbol in the case
681   ///     of a function whose last instruction is a call.  In this case,
682   ///     the PC can be one past the address range of the function.
683   ///
684   /// \return
685   ///     The scope that has been resolved (see SymbolContext::Scope).
686   ///
687   /// \see SymbolContext::Scope
688   uint32_t ResolveSymbolContextForAddress(
689       const Address &so_addr, lldb::SymbolContextItem resolve_scope,
690       SymbolContext &sc, bool resolve_tail_call_address = false);
691 
692   /// Resolve items in the symbol context for a given file and line.
693   ///
694   /// Tries to resolve \a file_path and \a line to a list of matching symbol
695   /// contexts.
696   ///
697   /// The line table entries contains addresses that can be used to further
698   /// resolve the values in each match: the function, block, symbol. Care
699   /// should be taken to minimize the amount of information that is requested
700   /// to only what is needed -- typically the module, compile unit, line table
701   /// and line table entry are sufficient.
702   ///
703   /// \param[in] file_path
704   ///     A path to a source file to match. If \a file_path does not
705   ///     specify a directory, then this query will match all files
706   ///     whose base filename matches. If \a file_path does specify
707   ///     a directory, the fullpath to the file must match.
708   ///
709   /// \param[in] line
710   ///     The source line to match, or zero if just the compile unit
711   ///     should be resolved.
712   ///
713   /// \param[in] check_inlines
714   ///     Check for inline file and line number matches. This option
715   ///     should be used sparingly as it will cause all line tables
716   ///     for every compile unit to be parsed and searched for
717   ///     matching inline file entries.
718   ///
719   /// \param[in] resolve_scope
720   ///     The scope that should be resolved (see
721   ///     SymbolContext::Scope).
722   ///
723   /// \param[out] sc_list
724   ///     A symbol context list that gets matching symbols contexts
725   ///     appended to.
726   ///
727   /// \return
728   ///     The number of matches that were added to \a sc_list.
729   ///
730   /// \see SymbolContext::Scope
731   uint32_t ResolveSymbolContextForFilePath(
732       const char *file_path, uint32_t line, bool check_inlines,
733       lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list);
734 
735   /// Resolve items in the symbol context for a given file and line.
736   ///
737   /// Tries to resolve \a file_spec and \a line to a list of matching symbol
738   /// contexts.
739   ///
740   /// The line table entries contains addresses that can be used to further
741   /// resolve the values in each match: the function, block, symbol. Care
742   /// should be taken to minimize the amount of information that is requested
743   /// to only what is needed -- typically the module, compile unit, line table
744   /// and line table entry are sufficient.
745   ///
746   /// \param[in] file_spec
747   ///     A file spec to a source file to match. If \a file_path does
748   ///     not specify a directory, then this query will match all
749   ///     files whose base filename matches. If \a file_path does
750   ///     specify a directory, the fullpath to the file must match.
751   ///
752   /// \param[in] line
753   ///     The source line to match, or zero if just the compile unit
754   ///     should be resolved.
755   ///
756   /// \param[in] check_inlines
757   ///     Check for inline file and line number matches. This option
758   ///     should be used sparingly as it will cause all line tables
759   ///     for every compile unit to be parsed and searched for
760   ///     matching inline file entries.
761   ///
762   /// \param[in] resolve_scope
763   ///     The scope that should be resolved (see
764   ///     SymbolContext::Scope).
765   ///
766   /// \param[out] sc_list
767   ///     A symbol context list that gets filled in with all of the
768   ///     matches.
769   ///
770   /// \return
771   ///     A integer that contains SymbolContext::Scope bits set for
772   ///     each item that was successfully resolved.
773   ///
774   /// \see SymbolContext::Scope
775   uint32_t ResolveSymbolContextsForFileSpec(
776       const FileSpec &file_spec, uint32_t line, bool check_inlines,
777       lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list);
778 
779   void SetFileSpecAndObjectName(const FileSpec &file,
780                                 ConstString object_name);
781 
782   bool GetIsDynamicLinkEditor();
783 
784   llvm::Expected<TypeSystem &>
785   GetTypeSystemForLanguage(lldb::LanguageType language);
786 
787   // Special error functions that can do printf style formatting that will
788   // prepend the message with something appropriate for this module (like the
789   // architecture, path and object name (if any)). This centralizes code so
790   // that everyone doesn't need to format their error and log messages on their
791   // own and keeps the output a bit more consistent.
792   void LogMessage(Log *log, const char *format, ...)
793       __attribute__((format(printf, 3, 4)));
794 
795   void LogMessageVerboseBacktrace(Log *log, const char *format, ...)
796       __attribute__((format(printf, 3, 4)));
797 
798   void ReportWarning(const char *format, ...)
799       __attribute__((format(printf, 2, 3)));
800 
801   void ReportError(const char *format, ...)
802       __attribute__((format(printf, 2, 3)));
803 
804   // Only report an error once when the module is first detected to be modified
805   // so we don't spam the console with many messages.
806   void ReportErrorIfModifyDetected(const char *format, ...)
807       __attribute__((format(printf, 2, 3)));
808 
809   // Return true if the file backing this module has changed since the module
810   // was originally created  since we saved the initial file modification time
811   // when the module first gets created.
812   bool FileHasChanged() const;
813 
814   // SymbolFile and ObjectFile member objects should lock the
815   // module mutex to avoid deadlocks.
GetMutex()816   std::recursive_mutex &GetMutex() const { return m_mutex; }
817 
GetSourceMappingList()818   PathMappingList &GetSourceMappingList() { return m_source_mappings; }
819 
GetSourceMappingList()820   const PathMappingList &GetSourceMappingList() const {
821     return m_source_mappings;
822   }
823 
824   /// Finds a source file given a file spec using the module source path
825   /// remappings (if any).
826   ///
827   /// Tries to resolve \a orig_spec by checking the module source path
828   /// remappings. It makes sure the file exists, so this call can be expensive
829   /// if the remappings are on a network file system, so use this function
830   /// sparingly (not in a tight debug info parsing loop).
831   ///
832   /// \param[in] orig_spec
833   ///     The original source file path to try and remap.
834   ///
835   /// \param[out] new_spec
836   ///     The newly remapped filespec that is guaranteed to exist.
837   ///
838   /// \return
839   ///     /b true if \a orig_spec was successfully located and
840   ///     \a new_spec is filled in with an existing file spec,
841   ///     \b false otherwise.
842   bool FindSourceFile(const FileSpec &orig_spec, FileSpec &new_spec) const;
843 
844   /// Remaps a source file given \a path into \a new_path.
845   ///
846   /// Remaps \a path if any source remappings match. This function does NOT
847   /// stat the file system so it can be used in tight loops where debug info
848   /// is being parsed.
849   ///
850   /// \param[in] path
851   ///     The original source file path to try and remap.
852   ///
853   /// \param[out] new_path
854   ///     The newly remapped filespec that is may or may not exist.
855   ///
856   /// \return
857   ///     /b true if \a path was successfully located and \a new_path
858   ///     is filled in with a new source path, \b false otherwise.
859   bool RemapSourceFile(llvm::StringRef path, std::string &new_path) const;
860   bool RemapSourceFile(const char *, std::string &) const = delete;
861 
862   /// Update the ArchSpec to a more specific variant.
863   bool MergeArchitecture(const ArchSpec &arch_spec);
864 
865   /// \class LookupInfo Module.h "lldb/Core/Module.h"
866   /// A class that encapsulates name lookup information.
867   ///
868   /// Users can type a wide variety of partial names when setting breakpoints
869   /// by name or when looking for functions by name. The SymbolFile object is
870   /// only required to implement name lookup for function basenames and for
871   /// fully mangled names. This means if the user types in a partial name, we
872   /// must reduce this to a name lookup that will work with all SymbolFile
873   /// objects. So we might reduce a name lookup to look for a basename, and then
874   /// prune out any results that don't match.
875   ///
876   /// The "m_name" member variable represents the name as it was typed by the
877   /// user. "m_lookup_name" will be the name we actually search for through
878   /// the symbol or objects files. Lanaguage is included in case we need to
879   /// filter results by language at a later date. The "m_name_type_mask"
880   /// member variable tells us what kinds of names we are looking for and can
881   /// help us prune out unwanted results.
882   ///
883   /// Function lookups are done in Module.cpp, ModuleList.cpp and in
884   /// BreakpointResolverName.cpp and they all now use this class to do lookups
885   /// correctly.
886   class LookupInfo {
887   public:
LookupInfo()888     LookupInfo()
889         : m_name(), m_lookup_name(), m_language(lldb::eLanguageTypeUnknown),
890           m_name_type_mask(lldb::eFunctionNameTypeNone),
891           m_match_name_after_lookup(false) {}
892 
893     LookupInfo(ConstString name, lldb::FunctionNameType name_type_mask,
894                lldb::LanguageType language);
895 
GetName()896     ConstString GetName() const { return m_name; }
897 
SetName(ConstString name)898     void SetName(ConstString name) { m_name = name; }
899 
GetLookupName()900     ConstString GetLookupName() const { return m_lookup_name; }
901 
SetLookupName(ConstString name)902     void SetLookupName(ConstString name) { m_lookup_name = name; }
903 
GetNameTypeMask()904     lldb::FunctionNameType GetNameTypeMask() const { return m_name_type_mask; }
905 
SetNameTypeMask(lldb::FunctionNameType mask)906     void SetNameTypeMask(lldb::FunctionNameType mask) {
907       m_name_type_mask = mask;
908     }
909 
910     void Prune(SymbolContextList &sc_list, size_t start_idx) const;
911 
912   protected:
913     /// What the user originally typed
914     ConstString m_name;
915 
916     /// The actual name will lookup when calling in the object or symbol file
917     ConstString m_lookup_name;
918 
919     /// Limit matches to only be for this language
920     lldb::LanguageType m_language;
921 
922     /// One or more bits from lldb::FunctionNameType that indicate what kind of
923     /// names we are looking for
924     lldb::FunctionNameType m_name_type_mask;
925 
926     ///< If \b true, then demangled names that match will need to contain
927     ///< "m_name" in order to be considered a match
928     bool m_match_name_after_lookup;
929   };
930 
931 protected:
932   // Member Variables
933   mutable std::recursive_mutex m_mutex; ///< A mutex to keep this object happy
934                                         ///in multi-threaded environments.
935 
936   /// The modification time for this module when it was created.
937   llvm::sys::TimePoint<> m_mod_time;
938 
939   ArchSpec m_arch;      ///< The architecture for this module.
940   UUID m_uuid; ///< Each module is assumed to have a unique identifier to help
941                ///match it up to debug symbols.
942   FileSpec m_file; ///< The file representation on disk for this module (if
943                    ///there is one).
944   FileSpec m_platform_file; ///< The path to the module on the platform on which
945                             ///it is being debugged
946   FileSpec m_remote_install_file; ///< If set when debugging on remote
947                                   ///platforms, this module will be installed at
948                                   ///this location
949   FileSpec m_symfile_spec;   ///< If this path is valid, then this is the file
950                              ///that _will_ be used as the symbol file for this
951                              ///module
952   ConstString m_object_name; ///< The name an object within this module that is
953                              ///selected, or empty of the module is represented
954                              ///by \a m_file.
955   uint64_t m_object_offset;
956   llvm::sys::TimePoint<> m_object_mod_time;
957 
958   /// DataBuffer containing the module image, if it was provided at
959   /// construction time. Otherwise the data will be retrieved by mapping
960   /// one of the FileSpec members above.
961   lldb::DataBufferSP m_data_sp;
962 
963   lldb::ObjectFileSP m_objfile_sp; ///< A shared pointer to the object file
964                                    ///parser for this module as it may or may
965                                    ///not be shared with the SymbolFile
966   llvm::Optional<UnwindTable> m_unwind_table; ///< Table of FuncUnwinders
967                                               /// objects created for this
968                                               /// Module's functions
969   lldb::SymbolVendorUP
970       m_symfile_up; ///< A pointer to the symbol vendor for this module.
971   std::vector<lldb::SymbolVendorUP>
972       m_old_symfiles; ///< If anyone calls Module::SetSymbolFileFileSpec() and
973                       ///changes the symbol file,
974   ///< we need to keep all old symbol files around in case anyone has type
975   ///references to them
976   TypeSystemMap m_type_system_map;   ///< A map of any type systems associated
977                                      ///with this module
978   /// Module specific source remappings for when you have debug info for a
979   /// module that doesn't match where the sources currently are.
980   PathMappingList m_source_mappings =
981       ModuleList::GetGlobalModuleListProperties().GetSymlinkMappings();
982 
983   lldb::SectionListUP m_sections_up; ///< Unified section list for module that
984                                      /// is used by the ObjectFile and and
985                                      /// ObjectFile instances for the debug info
986 
987   std::atomic<bool> m_did_load_objfile{false};
988   std::atomic<bool> m_did_load_symfile{false};
989   std::atomic<bool> m_did_set_uuid{false};
990   mutable bool m_file_has_changed : 1,
991       m_first_file_changed_log : 1; /// See if the module was modified after it
992                                     /// was initially opened.
993 
994   /// Resolve a file or load virtual address.
995   ///
996   /// Tries to resolve \a vm_addr as a file address (if \a
997   /// vm_addr_is_file_addr is true) or as a load address if \a
998   /// vm_addr_is_file_addr is false) in the symbol vendor. \a resolve_scope
999   /// indicates what clients wish to resolve and can be used to limit the
1000   /// scope of what is parsed.
1001   ///
1002   /// \param[in] vm_addr
1003   ///     The load virtual address to resolve.
1004   ///
1005   /// \param[in] vm_addr_is_file_addr
1006   ///     If \b true, \a vm_addr is a file address, else \a vm_addr
1007   ///     if a load address.
1008   ///
1009   /// \param[in] resolve_scope
1010   ///     The scope that should be resolved (see
1011   ///     SymbolContext::Scope).
1012   ///
1013   /// \param[out] so_addr
1014   ///     The section offset based address that got resolved if
1015   ///     any bits are returned.
1016   ///
1017   /// \param[out] sc
1018   //      The symbol context that has objects filled in. Each bit
1019   ///     in the \a resolve_scope pertains to a member in the \a sc.
1020   ///
1021   /// \return
1022   ///     A integer that contains SymbolContext::Scope bits set for
1023   ///     each item that was successfully resolved.
1024   ///
1025   /// \see SymbolContext::Scope
1026   uint32_t ResolveSymbolContextForAddress(lldb::addr_t vm_addr,
1027                                           bool vm_addr_is_file_addr,
1028                                           lldb::SymbolContextItem resolve_scope,
1029                                           Address &so_addr, SymbolContext &sc);
1030 
1031   void SymbolIndicesToSymbolContextList(Symtab *symtab,
1032                                         std::vector<uint32_t> &symbol_indexes,
1033                                         SymbolContextList &sc_list);
1034 
1035   bool SetArchitecture(const ArchSpec &new_arch);
1036 
1037   void SetUUID(const lldb_private::UUID &uuid);
1038 
1039   SectionList *GetUnifiedSectionList();
1040 
1041   friend class ModuleList;
1042   friend class ObjectFile;
1043   friend class SymbolFile;
1044 
1045 private:
1046   Module(); // Only used internally by CreateJITModule ()
1047 
1048   void FindTypes_Impl(
1049       ConstString name, const CompilerDeclContext &parent_decl_ctx,
1050       size_t max_matches,
1051       llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1052       TypeMap &types);
1053 
1054   Module(const Module &) = delete;
1055   const Module &operator=(const Module &) = delete;
1056 };
1057 
1058 } // namespace lldb_private
1059 
1060 #endif // LLDB_CORE_MODULE_H
1061