Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:42:45

0001 //===-- Module.h ------------------------------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLDB_CORE_MODULE_H
0010 #define LLDB_CORE_MODULE_H
0011 
0012 #include "lldb/Core/Address.h"
0013 #include "lldb/Core/ModuleList.h"
0014 #include "lldb/Core/ModuleSpec.h"
0015 #include "lldb/Symbol/ObjectFile.h"
0016 #include "lldb/Symbol/SymbolContextScope.h"
0017 #include "lldb/Symbol/TypeSystem.h"
0018 #include "lldb/Target/PathMappingList.h"
0019 #include "lldb/Target/Statistics.h"
0020 #include "lldb/Utility/ArchSpec.h"
0021 #include "lldb/Utility/ConstString.h"
0022 #include "lldb/Utility/FileSpec.h"
0023 #include "lldb/Utility/Status.h"
0024 #include "lldb/Utility/UUID.h"
0025 #include "lldb/Utility/XcodeSDK.h"
0026 #include "lldb/lldb-defines.h"
0027 #include "lldb/lldb-enumerations.h"
0028 #include "lldb/lldb-forward.h"
0029 #include "lldb/lldb-types.h"
0030 
0031 #include "llvm/ADT/DenseSet.h"
0032 #include "llvm/ADT/STLFunctionalExtras.h"
0033 #include "llvm/ADT/StableHashing.h"
0034 #include "llvm/ADT/StringRef.h"
0035 #include "llvm/Support/Chrono.h"
0036 
0037 #include <atomic>
0038 #include <cstddef>
0039 #include <cstdint>
0040 #include <memory>
0041 #include <mutex>
0042 #include <optional>
0043 #include <string>
0044 #include <vector>
0045 
0046 namespace lldb_private {
0047 class CompilerDeclContext;
0048 class Function;
0049 class Log;
0050 class ObjectFile;
0051 class RegularExpression;
0052 class SectionList;
0053 class Stream;
0054 class Symbol;
0055 class SymbolContext;
0056 class SymbolContextList;
0057 class SymbolFile;
0058 class Symtab;
0059 class Target;
0060 class TypeList;
0061 class TypeMap;
0062 class VariableList;
0063 
0064 /// Options used by Module::FindFunctions. This cannot be a nested class
0065 /// because it must be forward-declared in ModuleList.h.
0066 struct ModuleFunctionSearchOptions {
0067   /// Include the symbol table.
0068   bool include_symbols = false;
0069   /// Include inlined functions.
0070   bool include_inlines = false;
0071 };
0072 
0073 /// \class Module Module.h "lldb/Core/Module.h"
0074 /// A class that describes an executable image and its associated
0075 ///        object and symbol files.
0076 ///
0077 /// The module is designed to be able to select a single slice of an
0078 /// executable image as it would appear on disk and during program execution.
0079 ///
0080 /// Modules control when and if information is parsed according to which
0081 /// accessors are called. For example the object file (ObjectFile)
0082 /// representation will only be parsed if the object file is requested using
0083 /// the Module::GetObjectFile() is called. The debug symbols will only be
0084 /// parsed if the symbol file (SymbolFile) is requested using the
0085 /// Module::GetSymbolFile() method.
0086 ///
0087 /// The module will parse more detailed information as more queries are made.
0088 class Module : public std::enable_shared_from_this<Module>,
0089                public SymbolContextScope {
0090 public:
0091   class LookupInfo;
0092   // Static functions that can track the lifetime of module objects. This is
0093   // handy because we might have Module objects that are in shared pointers
0094   // that aren't in the global module list (from ModuleList). If this is the
0095   // case we need to know about it. The modules in the global list maintained
0096   // by these functions can be viewed using the "target modules list" command
0097   // using the "--global" (-g for short).
0098   static size_t GetNumberAllocatedModules();
0099 
0100   static Module *GetAllocatedModuleAtIndex(size_t idx);
0101 
0102   static std::recursive_mutex &GetAllocationModuleCollectionMutex();
0103 
0104   /// Construct with file specification and architecture.
0105   ///
0106   /// Clients that wish to share modules with other targets should use
0107   /// ModuleList::GetSharedModule().
0108   ///
0109   /// \param[in] file_spec
0110   ///     The file specification for the on disk representation of
0111   ///     this executable image.
0112   ///
0113   /// \param[in] arch
0114   ///     The architecture to set as the current architecture in
0115   ///     this module.
0116   ///
0117   /// \param[in] object_name
0118   ///     The name of an object in a module used to extract a module
0119   ///     within a module (.a files and modules that contain multiple
0120   ///     architectures).
0121   ///
0122   /// \param[in] object_offset
0123   ///     The offset within an existing module used to extract a
0124   ///     module within a module (.a files and modules that contain
0125   ///     multiple architectures).
0126   Module(
0127       const FileSpec &file_spec, const ArchSpec &arch,
0128       ConstString object_name = ConstString(), lldb::offset_t object_offset = 0,
0129       const llvm::sys::TimePoint<> &object_mod_time = llvm::sys::TimePoint<>());
0130 
0131   Module(const ModuleSpec &module_spec);
0132 
0133   template <typename ObjFilePlugin, typename... Args>
0134   static lldb::ModuleSP CreateModuleFromObjectFile(Args &&...args) {
0135     // Must create a module and place it into a shared pointer before we can
0136     // create an object file since it has a std::weak_ptr back to the module,
0137     // so we need to control the creation carefully in this static function
0138     lldb::ModuleSP module_sp(new Module());
0139     module_sp->m_objfile_sp =
0140         std::make_shared<ObjFilePlugin>(module_sp, std::forward<Args>(args)...);
0141     module_sp->m_did_load_objfile.store(true, std::memory_order_relaxed);
0142 
0143     // Once we get the object file, set module ArchSpec to the one we get from
0144     // the object file. If the object file does not have an architecture, we
0145     // consider the creation a failure.
0146     ArchSpec arch = module_sp->m_objfile_sp->GetArchitecture();
0147     if (!arch)
0148       return nullptr;
0149     module_sp->m_arch = arch;
0150 
0151     // Also copy the object file's FileSpec.
0152     module_sp->m_file = module_sp->m_objfile_sp->GetFileSpec();
0153     return module_sp;
0154   }
0155 
0156   /// Destructor.
0157   ~Module() override;
0158 
0159   bool MatchesModuleSpec(const ModuleSpec &module_ref);
0160 
0161   /// Set the load address for all sections in a module to be the file address
0162   /// plus \a slide.
0163   ///
0164   /// Many times a module will be loaded in a target with a constant offset
0165   /// applied to all top level sections. This function can set the load
0166   /// address for all top level sections to be the section file address +
0167   /// offset.
0168   ///
0169   /// \param[in] target
0170   ///     The target in which to apply the section load addresses.
0171   ///
0172   /// \param[in] value
0173   ///     if \a value_is_offset is true, then value is the offset to
0174   ///     apply to all file addresses for all top level sections in
0175   ///     the object file as each section load address is being set.
0176   ///     If \a value_is_offset is false, then "value" is the new
0177   ///     absolute base address for the image.
0178   ///
0179   /// \param[in] value_is_offset
0180   ///     If \b true, then \a value is an offset to apply to each
0181   ///     file address of each top level section.
0182   ///     If \b false, then \a value is the image base address that
0183   ///     will be used to rigidly slide all loadable sections.
0184   ///
0185   /// \param[out] changed
0186   ///     If any section load addresses were changed in \a target,
0187   ///     then \a changed will be set to \b true. Else \a changed
0188   ///     will be set to false. This allows this function to be
0189   ///     called multiple times on the same module for the same
0190   ///     target. If the module hasn't moved, then \a changed will
0191   ///     be false and no module updated notification will need to
0192   ///     be sent out.
0193   ///
0194   /// \return
0195   ///     /b True if any sections were successfully loaded in \a target,
0196   ///     /b false otherwise.
0197   bool SetLoadAddress(Target &target, lldb::addr_t value, bool value_is_offset,
0198                       bool &changed);
0199 
0200   /// \copydoc SymbolContextScope::CalculateSymbolContext(SymbolContext*)
0201   ///
0202   /// \see SymbolContextScope
0203   void CalculateSymbolContext(SymbolContext *sc) override;
0204 
0205   lldb::ModuleSP CalculateSymbolContextModule() override;
0206 
0207   void
0208   GetDescription(llvm::raw_ostream &s,
0209                  lldb::DescriptionLevel level = lldb::eDescriptionLevelFull);
0210 
0211   /// Get the module path and object name.
0212   ///
0213   /// Modules can refer to object files. In this case the specification is
0214   /// simple and would return the path to the file:
0215   ///
0216   ///     "/usr/lib/foo.dylib"
0217   ///
0218   /// Modules can be .o files inside of a BSD archive (.a file). In this case,
0219   /// the object specification will look like:
0220   ///
0221   ///     "/usr/lib/foo.a(bar.o)"
0222   ///
0223   /// There are many places where logging wants to log this fully qualified
0224   /// specification, so we centralize this functionality here.
0225   ///
0226   /// \return
0227   ///     The object path + object name if there is one.
0228   std::string GetSpecificationDescription() const;
0229 
0230   /// Dump a description of this object to a Stream.
0231   ///
0232   /// Dump a description of the contents of this object to the supplied stream
0233   /// \a s. The dumped content will be only what has been loaded or parsed up
0234   /// to this point at which this function is called, so this is a good way to
0235   /// see what has been parsed in a module.
0236   ///
0237   /// \param[in] s
0238   ///     The stream to which to dump the object description.
0239   void Dump(Stream *s);
0240 
0241   /// \copydoc SymbolContextScope::DumpSymbolContext(Stream*)
0242   ///
0243   /// \see SymbolContextScope
0244   void DumpSymbolContext(Stream *s) override;
0245 
0246   /// Find a symbol in the object file's symbol table.
0247   ///
0248   /// \param[in] name
0249   ///     The name of the symbol that we are looking for.
0250   ///
0251   /// \param[in] symbol_type
0252   ///     If set to eSymbolTypeAny, find a symbol of any type that
0253   ///     has a name that matches \a name. If set to any other valid
0254   ///     SymbolType enumeration value, then search only for
0255   ///     symbols that match \a symbol_type.
0256   ///
0257   /// \return
0258   ///     Returns a valid symbol pointer if a symbol was found,
0259   ///     nullptr otherwise.
0260   const Symbol *FindFirstSymbolWithNameAndType(
0261       ConstString name, lldb::SymbolType symbol_type = lldb::eSymbolTypeAny);
0262 
0263   void FindSymbolsWithNameAndType(ConstString name,
0264                                   lldb::SymbolType symbol_type,
0265                                   SymbolContextList &sc_list);
0266 
0267   void FindSymbolsMatchingRegExAndType(
0268       const RegularExpression &regex, lldb::SymbolType symbol_type,
0269       SymbolContextList &sc_list,
0270       Mangled::NamePreference mangling_preference = Mangled::ePreferDemangled);
0271 
0272   /// Find a function symbols in the object file's symbol table.
0273   ///
0274   /// \param[in] name
0275   ///     The name of the symbol that we are looking for.
0276   ///
0277   /// \param[in] name_type_mask
0278   ///     A mask that has one or more bitwise OR'ed values from the
0279   ///     lldb::FunctionNameType enumeration type that indicate what
0280   ///     kind of names we are looking for.
0281   ///
0282   /// \param[out] sc_list
0283   ///     A list to append any matching symbol contexts to.
0284   void FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
0285                            SymbolContextList &sc_list);
0286 
0287   /// Find compile units by partial or full path.
0288   ///
0289   /// Finds all compile units that match \a path in all of the modules and
0290   /// returns the results in \a sc_list.
0291   ///
0292   /// \param[in] path
0293   ///     The name of the function we are looking for.
0294   ///
0295   /// \param[out] sc_list
0296   ///     A symbol context list that gets filled in with all of the
0297   ///     matches.
0298   void FindCompileUnits(const FileSpec &path, SymbolContextList &sc_list);
0299 
0300   /// Find functions by lookup info.
0301   ///
0302   /// If the function is an inlined function, it will have a block,
0303   /// representing the inlined function, and the function will be the
0304   /// containing function.  If it is not inlined, then the block will be NULL.
0305   ///
0306   /// \param[in] lookup_info
0307   ///     The lookup info of the function we are looking for.
0308   ///
0309   /// \param[out] sc_list
0310   ///     A symbol context list that gets filled in with all of the
0311   ///     matches.
0312   void FindFunctions(const LookupInfo &lookup_info,
0313                      const CompilerDeclContext &parent_decl_ctx,
0314                      const ModuleFunctionSearchOptions &options,
0315                      SymbolContextList &sc_list);
0316 
0317   /// Find functions by name.
0318   ///
0319   /// If the function is an inlined function, it will have a block,
0320   /// representing the inlined function, and the function will be the
0321   /// containing function.  If it is not inlined, then the block will be NULL.
0322   ///
0323   /// \param[in] name
0324   ///     The name of the function we are looking for.
0325   ///
0326   /// \param[in] name_type_mask
0327   ///     A bit mask of bits that indicate what kind of names should
0328   ///     be used when doing the lookup. Bits include fully qualified
0329   ///     names, base names, C++ methods, or ObjC selectors.
0330   ///     See FunctionNameType for more details.
0331   ///
0332   /// \param[out] sc_list
0333   ///     A symbol context list that gets filled in with all of the
0334   ///     matches.
0335   void FindFunctions(ConstString name,
0336                      const CompilerDeclContext &parent_decl_ctx,
0337                      lldb::FunctionNameType name_type_mask,
0338                      const ModuleFunctionSearchOptions &options,
0339                      SymbolContextList &sc_list);
0340 
0341   /// Find functions by compiler context.
0342   void FindFunctions(llvm::ArrayRef<CompilerContext> compiler_ctx,
0343                      lldb::FunctionNameType name_type_mask,
0344                      const ModuleFunctionSearchOptions &options,
0345                      SymbolContextList &sc_list);
0346 
0347   /// Find functions by name.
0348   ///
0349   /// If the function is an inlined function, it will have a block,
0350   /// representing the inlined function, and the function will be the
0351   /// containing function.  If it is not inlined, then the block will be NULL.
0352   ///
0353   /// \param[in] regex
0354   ///     A regular expression to use when matching the name.
0355   ///
0356   /// \param[out] sc_list
0357   ///     A symbol context list that gets filled in with all of the
0358   ///     matches.
0359   void FindFunctions(const RegularExpression &regex,
0360                      const ModuleFunctionSearchOptions &options,
0361                      SymbolContextList &sc_list);
0362 
0363   /// Find addresses by file/line
0364   ///
0365   /// \param[in] target_sp
0366   ///     The target the addresses are desired for.
0367   ///
0368   /// \param[in] file
0369   ///     Source file to locate.
0370   ///
0371   /// \param[in] line
0372   ///     Source line to locate.
0373   ///
0374   /// \param[in] function
0375   ///       Optional filter function. Addresses within this function will be
0376   ///     added to the 'local' list. All others will be added to the 'extern'
0377   ///     list.
0378   ///
0379   /// \param[out] output_local
0380   ///     All matching addresses within 'function'
0381   ///
0382   /// \param[out] output_extern
0383   ///     All matching addresses not within 'function'
0384   void FindAddressesForLine(const lldb::TargetSP target_sp,
0385                             const FileSpec &file, uint32_t line,
0386                             Function *function,
0387                             std::vector<Address> &output_local,
0388                             std::vector<Address> &output_extern);
0389 
0390   /// Find global and static variables by name.
0391   ///
0392   /// \param[in] name
0393   ///     The name of the global or static variable we are looking
0394   ///     for.
0395   ///
0396   /// \param[in] parent_decl_ctx
0397   ///     If valid, a decl context that results must exist within
0398   ///
0399   /// \param[in] max_matches
0400   ///     Allow the number of matches to be limited to \a
0401   ///     max_matches. Specify UINT32_MAX to get all possible matches.
0402   ///
0403   /// \param[in] variable_list
0404   ///     A list of variables that gets the matches appended to.
0405   ///
0406   void FindGlobalVariables(ConstString name,
0407                            const CompilerDeclContext &parent_decl_ctx,
0408                            size_t max_matches, VariableList &variable_list);
0409 
0410   /// Find global and static variables by regular expression.
0411   ///
0412   /// \param[in] regex
0413   ///     A regular expression to use when matching the name.
0414   ///
0415   /// \param[in] max_matches
0416   ///     Allow the number of matches to be limited to \a
0417   ///     max_matches. Specify UINT32_MAX to get all possible matches.
0418   ///
0419   /// \param[in] variable_list
0420   ///     A list of variables that gets the matches appended to.
0421   ///
0422   void FindGlobalVariables(const RegularExpression &regex, size_t max_matches,
0423                            VariableList &variable_list);
0424 
0425   /// Find types using a type-matching object that contains all search
0426   /// parameters.
0427   ///
0428   /// \see lldb_private::TypeQuery
0429   ///
0430   /// \param[in] query
0431   ///     A type matching object that contains all of the details of the type
0432   ///     search.
0433   ///
0434   /// \param[in] results
0435   ///     Any matching types will be populated into the \a results object using
0436   ///     TypeMap::InsertUnique(...).
0437   void FindTypes(const TypeQuery &query, TypeResults &results);
0438 
0439   /// Get const accessor for the module architecture.
0440   ///
0441   /// \return
0442   ///     A const reference to the architecture object.
0443   const ArchSpec &GetArchitecture() const;
0444 
0445   /// Get const accessor for the module file specification.
0446   ///
0447   /// This function returns the file for the module on the host system that is
0448   /// running LLDB. This can differ from the path on the platform since we
0449   /// might be doing remote debugging.
0450   ///
0451   /// \return
0452   ///     A const reference to the file specification object.
0453   const FileSpec &GetFileSpec() const { return m_file; }
0454 
0455   /// Get accessor for the module platform file specification.
0456   ///
0457   /// Platform file refers to the path of the module as it is known on the
0458   /// remote system on which it is being debugged. For local debugging this is
0459   /// always the same as Module::GetFileSpec(). But remote debugging might
0460   /// mention a file "/usr/lib/liba.dylib" which might be locally downloaded
0461   /// and cached. In this case the platform file could be something like:
0462   /// "/tmp/lldb/platform-cache/remote.host.computer/usr/lib/liba.dylib" The
0463   /// file could also be cached in a local developer kit directory.
0464   ///
0465   /// \return
0466   ///     A const reference to the file specification object.
0467   const FileSpec &GetPlatformFileSpec() const {
0468     if (m_platform_file)
0469       return m_platform_file;
0470     return m_file;
0471   }
0472 
0473   void SetPlatformFileSpec(const FileSpec &file) { m_platform_file = file; }
0474 
0475   const FileSpec &GetRemoteInstallFileSpec() const {
0476     return m_remote_install_file;
0477   }
0478 
0479   void SetRemoteInstallFileSpec(const FileSpec &file) {
0480     m_remote_install_file = file;
0481   }
0482 
0483   const FileSpec &GetSymbolFileFileSpec() const { return m_symfile_spec; }
0484 
0485   void PreloadSymbols();
0486 
0487   void SetSymbolFileFileSpec(const FileSpec &file);
0488 
0489   const llvm::sys::TimePoint<> &GetModificationTime() const {
0490     return m_mod_time;
0491   }
0492 
0493   const llvm::sys::TimePoint<> &GetObjectModificationTime() const {
0494     return m_object_mod_time;
0495   }
0496 
0497   /// This callback will be called by SymbolFile implementations when
0498   /// parsing a compile unit that contains SDK information.
0499   /// \param sysroot will be added to the path remapping dictionary.
0500   void RegisterXcodeSDK(llvm::StringRef sdk, llvm::StringRef sysroot);
0501 
0502   /// Tells whether this module is capable of being the main executable for a
0503   /// process.
0504   ///
0505   /// \return
0506   ///     \b true if it is, \b false otherwise.
0507   bool IsExecutable();
0508 
0509   /// Tells whether this module has been loaded in the target passed in. This
0510   /// call doesn't distinguish between whether the module is loaded by the
0511   /// dynamic loader, or by a "target module add" type call.
0512   ///
0513   /// \param[in] target
0514   ///    The target to check whether this is loaded in.
0515   ///
0516   /// \return
0517   ///     \b true if it is, \b false otherwise.
0518   bool IsLoadedInTarget(Target *target);
0519 
0520   bool LoadScriptingResourceInTarget(Target *target, Status &error,
0521                                      Stream &feedback_stream);
0522 
0523   /// Get the number of compile units for this module.
0524   ///
0525   /// \return
0526   ///     The number of compile units that the symbol vendor plug-in
0527   ///     finds.
0528   size_t GetNumCompileUnits();
0529 
0530   lldb::CompUnitSP GetCompileUnitAtIndex(size_t idx);
0531 
0532   ConstString GetObjectName() const;
0533 
0534   uint64_t GetObjectOffset() const { return m_object_offset; }
0535 
0536   /// Get the object file representation for the current architecture.
0537   ///
0538   /// If the object file has not been located or parsed yet, this function
0539   /// will find the best ObjectFile plug-in that can parse Module::m_file.
0540   ///
0541   /// \return
0542   ///     If Module::m_file does not exist, or no plug-in was found
0543   ///     that can parse the file, or the object file doesn't contain
0544   ///     the current architecture in Module::m_arch, nullptr will be
0545   ///     returned, else a valid object file interface will be
0546   ///     returned. The returned pointer is owned by this object and
0547   ///     remains valid as long as the object is around.
0548   virtual ObjectFile *GetObjectFile();
0549 
0550   /// Get the unified section list for the module. This is the section list
0551   /// created by the module's object file and any debug info and symbol files
0552   /// created by the symbol vendor.
0553   ///
0554   /// If the symbol vendor has not been loaded yet, this function will return
0555   /// the section list for the object file.
0556   ///
0557   /// \return
0558   ///     Unified module section list.
0559   virtual SectionList *GetSectionList();
0560 
0561   /// Notify the module that the file addresses for the Sections have been
0562   /// updated.
0563   ///
0564   /// If the Section file addresses for a module are updated, this method
0565   /// should be called.  Any parts of the module, object file, or symbol file
0566   /// that has cached those file addresses must invalidate or update its
0567   /// cache.
0568   virtual void SectionFileAddressesChanged();
0569 
0570   /// Returns a reference to the UnwindTable for this Module
0571   ///
0572   /// The UnwindTable contains FuncUnwinders objects for any function in this
0573   /// Module.  If a FuncUnwinders object hasn't been created yet (i.e. the
0574   /// function has yet to be unwound in a stack walk), it will be created when
0575   /// requested.  Specifically, we do not create FuncUnwinders objects for
0576   /// functions until they are needed.
0577   ///
0578   /// \return
0579   ///     Returns the unwind table for this module. If this object has no
0580   ///     associated object file, an empty UnwindTable is returned.
0581   UnwindTable &GetUnwindTable();
0582 
0583   llvm::VersionTuple GetVersion();
0584 
0585   /// Load an object file from memory.
0586   ///
0587   /// If available, the size of the object file in memory may be passed to
0588   /// avoid additional round trips to process memory. If the size is not
0589   /// provided, a default value is used. This value should be large enough to
0590   /// enable the ObjectFile plugins to read the header of the object file
0591   /// without going back to the process.
0592   ///
0593   /// \return
0594   ///     The object file loaded from memory or nullptr, if the operation
0595   ///     failed (see the `error` for more information in that case).
0596   ObjectFile *GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
0597                                   lldb::addr_t header_addr, Status &error,
0598                                   size_t size_to_read = 512);
0599 
0600   /// Get the module's symbol file
0601   ///
0602   /// If the symbol file has already been loaded, this function returns it. All
0603   /// arguments are ignored. If the symbol file has not been located yet, and
0604   /// the can_create argument is false, the function returns nullptr. If
0605   /// can_create is true, this function will find the best SymbolFile plug-in
0606   /// that can use the current object file. feedback_strm, if not null, is used
0607   /// to report the details of the search process.
0608   virtual SymbolFile *GetSymbolFile(bool can_create = true,
0609                                     Stream *feedback_strm = nullptr);
0610 
0611   Symtab *GetSymtab();
0612 
0613   /// Get a reference to the UUID value contained in this object.
0614   ///
0615   /// If the executable image file doesn't not have a UUID value built into
0616   /// the file format, an MD5 checksum of the entire file, or slice of the
0617   /// file for the current architecture should be used.
0618   ///
0619   /// \return
0620   ///     A const pointer to the internal copy of the UUID value in
0621   ///     this module if this module has a valid UUID value, NULL
0622   ///     otherwise.
0623   const lldb_private::UUID &GetUUID();
0624 
0625   /// A debugging function that will cause everything in a module to
0626   /// be parsed.
0627   ///
0628   /// All compile units will be parsed, along with all globals and static
0629   /// variables and all functions for those compile units. All types, scopes,
0630   /// local variables, static variables, global variables, and line tables
0631   /// will be parsed. This can be used prior to dumping a module to see a
0632   /// complete list of the resulting debug information that gets parsed, or as
0633   /// a debug function to ensure that the module can consume all of the debug
0634   /// data the symbol vendor provides.
0635   void ParseAllDebugSymbols();
0636 
0637   bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr);
0638 
0639   /// Resolve the symbol context for the given address.
0640   ///
0641   /// Tries to resolve the matching symbol context based on a lookup from the
0642   /// current symbol vendor.  If the lazy lookup fails, an attempt is made to
0643   /// parse the eh_frame section to handle stripped symbols.  If this fails,
0644   /// an attempt is made to resolve the symbol to the previous address to
0645   /// handle the case of a function with a tail call.
0646   ///
0647   /// Use properties of the modified SymbolContext to inspect any resolved
0648   /// target, module, compilation unit, symbol, function, function block or
0649   /// line entry.  Use the return value to determine which of these properties
0650   /// have been modified.
0651   ///
0652   /// \param[in] so_addr
0653   ///     A load address to resolve.
0654   ///
0655   /// \param[in] resolve_scope
0656   ///     The scope that should be resolved (see SymbolContext::Scope).
0657   ///     A combination of flags from the enumeration SymbolContextItem
0658   ///     requesting a resolution depth.  Note that the flags that are
0659   ///     actually resolved may be a superset of the requested flags.
0660   ///     For instance, eSymbolContextSymbol requires resolution of
0661   ///     eSymbolContextModule, and eSymbolContextFunction requires
0662   ///     eSymbolContextSymbol.
0663   ///
0664   /// \param[out] sc
0665   ///     The SymbolContext that is modified based on symbol resolution.
0666   ///
0667   /// \param[in] resolve_tail_call_address
0668   ///     Determines if so_addr should resolve to a symbol in the case
0669   ///     of a function whose last instruction is a call.  In this case,
0670   ///     the PC can be one past the address range of the function.
0671   ///
0672   /// \return
0673   ///     The scope that has been resolved (see SymbolContext::Scope).
0674   ///
0675   /// \see SymbolContext::Scope
0676   uint32_t ResolveSymbolContextForAddress(
0677       const Address &so_addr, lldb::SymbolContextItem resolve_scope,
0678       SymbolContext &sc, bool resolve_tail_call_address = false);
0679 
0680   /// Resolve items in the symbol context for a given file and line.
0681   ///
0682   /// Tries to resolve \a file_path and \a line to a list of matching symbol
0683   /// contexts.
0684   ///
0685   /// The line table entries contains addresses that can be used to further
0686   /// resolve the values in each match: the function, block, symbol. Care
0687   /// should be taken to minimize the amount of information that is requested
0688   /// to only what is needed -- typically the module, compile unit, line table
0689   /// and line table entry are sufficient.
0690   ///
0691   /// \param[in] file_path
0692   ///     A path to a source file to match. If \a file_path does not
0693   ///     specify a directory, then this query will match all files
0694   ///     whose base filename matches. If \a file_path does specify
0695   ///     a directory, the fullpath to the file must match.
0696   ///
0697   /// \param[in] line
0698   ///     The source line to match, or zero if just the compile unit
0699   ///     should be resolved.
0700   ///
0701   /// \param[in] check_inlines
0702   ///     Check for inline file and line number matches. This option
0703   ///     should be used sparingly as it will cause all line tables
0704   ///     for every compile unit to be parsed and searched for
0705   ///     matching inline file entries.
0706   ///
0707   /// \param[in] resolve_scope
0708   ///     The scope that should be resolved (see
0709   ///     SymbolContext::Scope).
0710   ///
0711   /// \param[out] sc_list
0712   ///     A symbol context list that gets matching symbols contexts
0713   ///     appended to.
0714   ///
0715   /// \return
0716   ///     The number of matches that were added to \a sc_list.
0717   ///
0718   /// \see SymbolContext::Scope
0719   uint32_t ResolveSymbolContextForFilePath(
0720       const char *file_path, uint32_t line, bool check_inlines,
0721       lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list);
0722 
0723   /// Resolve items in the symbol context for a given file and line.
0724   ///
0725   /// Tries to resolve \a file_spec and \a line to a list of matching symbol
0726   /// contexts.
0727   ///
0728   /// The line table entries contains addresses that can be used to further
0729   /// resolve the values in each match: the function, block, symbol. Care
0730   /// should be taken to minimize the amount of information that is requested
0731   /// to only what is needed -- typically the module, compile unit, line table
0732   /// and line table entry are sufficient.
0733   ///
0734   /// \param[in] file_spec
0735   ///     A file spec to a source file to match. If \a file_path does
0736   ///     not specify a directory, then this query will match all
0737   ///     files whose base filename matches. If \a file_path does
0738   ///     specify a directory, the fullpath to the file must match.
0739   ///
0740   /// \param[in] line
0741   ///     The source line to match, or zero if just the compile unit
0742   ///     should be resolved.
0743   ///
0744   /// \param[in] check_inlines
0745   ///     Check for inline file and line number matches. This option
0746   ///     should be used sparingly as it will cause all line tables
0747   ///     for every compile unit to be parsed and searched for
0748   ///     matching inline file entries.
0749   ///
0750   /// \param[in] resolve_scope
0751   ///     The scope that should be resolved (see
0752   ///     SymbolContext::Scope).
0753   ///
0754   /// \param[out] sc_list
0755   ///     A symbol context list that gets filled in with all of the
0756   ///     matches.
0757   ///
0758   /// \return
0759   ///     A integer that contains SymbolContext::Scope bits set for
0760   ///     each item that was successfully resolved.
0761   ///
0762   /// \see SymbolContext::Scope
0763   uint32_t ResolveSymbolContextsForFileSpec(
0764       const FileSpec &file_spec, uint32_t line, bool check_inlines,
0765       lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list);
0766 
0767   void SetFileSpecAndObjectName(const FileSpec &file, ConstString object_name);
0768 
0769   bool GetIsDynamicLinkEditor();
0770 
0771   llvm::Expected<lldb::TypeSystemSP>
0772   GetTypeSystemForLanguage(lldb::LanguageType language);
0773 
0774   /// Call \p callback for each \p TypeSystem in this \p Module.
0775   /// Return true from callback to keep iterating, false to stop iterating.
0776   void ForEachTypeSystem(llvm::function_ref<bool(lldb::TypeSystemSP)> callback);
0777 
0778   // Special error functions that can do printf style formatting that will
0779   // prepend the message with something appropriate for this module (like the
0780   // architecture, path and object name (if any)). This centralizes code so
0781   // that everyone doesn't need to format their error and log messages on their
0782   // own and keeps the output a bit more consistent.
0783   template <typename... Args>
0784   void LogMessage(Log *log, const char *format, Args &&...args) {
0785     LogMessage(log, llvm::formatv(format, std::forward<Args>(args)...));
0786   }
0787 
0788   template <typename... Args>
0789   void LogMessageVerboseBacktrace(Log *log, const char *format,
0790                                   Args &&...args) {
0791     LogMessageVerboseBacktrace(
0792         log, llvm::formatv(format, std::forward<Args>(args)...));
0793   }
0794 
0795   template <typename... Args>
0796   void ReportWarning(const char *format, Args &&...args) {
0797     ReportWarning(llvm::formatv(format, std::forward<Args>(args)...));
0798   }
0799 
0800   template <typename... Args>
0801   void ReportError(const char *format, Args &&...args) {
0802     ReportError(llvm::formatv(format, std::forward<Args>(args)...));
0803   }
0804 
0805   // Only report an error once when the module is first detected to be modified
0806   // so we don't spam the console with many messages.
0807   template <typename... Args>
0808   void ReportErrorIfModifyDetected(const char *format, Args &&...args) {
0809     ReportErrorIfModifyDetected(
0810         llvm::formatv(format, std::forward<Args>(args)...));
0811   }
0812 
0813   void ReportWarningOptimization(std::optional<lldb::user_id_t> debugger_id);
0814 
0815   void
0816   ReportWarningUnsupportedLanguage(lldb::LanguageType language,
0817                                    std::optional<lldb::user_id_t> debugger_id);
0818 
0819   // Return true if the file backing this module has changed since the module
0820   // was originally created  since we saved the initial file modification time
0821   // when the module first gets created.
0822   bool FileHasChanged() const;
0823 
0824   // SymbolFile and ObjectFile member objects should lock the
0825   // module mutex to avoid deadlocks.
0826   std::recursive_mutex &GetMutex() const { return m_mutex; }
0827 
0828   PathMappingList &GetSourceMappingList() { return m_source_mappings; }
0829 
0830   const PathMappingList &GetSourceMappingList() const {
0831     return m_source_mappings;
0832   }
0833 
0834   /// Finds a source file given a file spec using the module source path
0835   /// remappings (if any).
0836   ///
0837   /// Tries to resolve \a orig_spec by checking the module source path
0838   /// remappings. It makes sure the file exists, so this call can be expensive
0839   /// if the remappings are on a network file system, so use this function
0840   /// sparingly (not in a tight debug info parsing loop).
0841   ///
0842   /// \param[in] orig_spec
0843   ///     The original source file path to try and remap.
0844   ///
0845   /// \param[out] new_spec
0846   ///     The newly remapped filespec that is guaranteed to exist.
0847   ///
0848   /// \return
0849   ///     /b true if \a orig_spec was successfully located and
0850   ///     \a new_spec is filled in with an existing file spec,
0851   ///     \b false otherwise.
0852   bool FindSourceFile(const FileSpec &orig_spec, FileSpec &new_spec) const;
0853 
0854   /// Remaps a source file given \a path into \a new_path.
0855   ///
0856   /// Remaps \a path if any source remappings match. This function does NOT
0857   /// stat the file system so it can be used in tight loops where debug info
0858   /// is being parsed.
0859   ///
0860   /// \param[in] path
0861   ///     The original source file path to try and remap.
0862   ///
0863   /// \return
0864   ///     The newly remapped filespec that is may or may not exist if
0865   ///     \a path was successfully located.
0866   std::optional<std::string> RemapSourceFile(llvm::StringRef path) const;
0867   bool RemapSourceFile(const char *, std::string &) const = delete;
0868 
0869   /// Update the ArchSpec to a more specific variant.
0870   bool MergeArchitecture(const ArchSpec &arch_spec);
0871 
0872   /// Accessor for the symbol table parse time metric.
0873   ///
0874   /// The value is returned as a reference to allow it to be updated by the
0875   /// ElapsedTime RAII object.
0876   StatsDuration &GetSymtabParseTime() { return m_symtab_parse_time; }
0877 
0878   /// Accessor for the symbol table index time metric.
0879   ///
0880   /// The value is returned as a reference to allow it to be updated by the
0881   /// ElapsedTime RAII object.
0882   StatsDuration &GetSymtabIndexTime() { return m_symtab_index_time; }
0883 
0884   void ResetStatistics();
0885 
0886   /// \class LookupInfo Module.h "lldb/Core/Module.h"
0887   /// A class that encapsulates name lookup information.
0888   ///
0889   /// Users can type a wide variety of partial names when setting breakpoints
0890   /// by name or when looking for functions by name. The SymbolFile object is
0891   /// only required to implement name lookup for function basenames and for
0892   /// fully mangled names. This means if the user types in a partial name, we
0893   /// must reduce this to a name lookup that will work with all SymbolFile
0894   /// objects. So we might reduce a name lookup to look for a basename, and then
0895   /// prune out any results that don't match.
0896   ///
0897   /// The "m_name" member variable represents the name as it was typed by the
0898   /// user. "m_lookup_name" will be the name we actually search for through
0899   /// the symbol or objects files. Lanaguage is included in case we need to
0900   /// filter results by language at a later date. The "m_name_type_mask"
0901   /// member variable tells us what kinds of names we are looking for and can
0902   /// help us prune out unwanted results.
0903   ///
0904   /// Function lookups are done in Module.cpp, ModuleList.cpp and in
0905   /// BreakpointResolverName.cpp and they all now use this class to do lookups
0906   /// correctly.
0907   class LookupInfo {
0908   public:
0909     LookupInfo() = default;
0910 
0911     LookupInfo(ConstString name, lldb::FunctionNameType name_type_mask,
0912                lldb::LanguageType language);
0913 
0914     ConstString GetName() const { return m_name; }
0915 
0916     void SetName(ConstString name) { m_name = name; }
0917 
0918     ConstString GetLookupName() const { return m_lookup_name; }
0919 
0920     void SetLookupName(ConstString name) { m_lookup_name = name; }
0921 
0922     lldb::FunctionNameType GetNameTypeMask() const { return m_name_type_mask; }
0923 
0924     void SetNameTypeMask(lldb::FunctionNameType mask) {
0925       m_name_type_mask = mask;
0926     }
0927 
0928     lldb::LanguageType GetLanguageType() const { return m_language; }
0929 
0930     bool NameMatchesLookupInfo(
0931         ConstString function_name,
0932         lldb::LanguageType language_type = lldb::eLanguageTypeUnknown) const;
0933 
0934     void Prune(SymbolContextList &sc_list, size_t start_idx) const;
0935 
0936   protected:
0937     /// What the user originally typed
0938     ConstString m_name;
0939 
0940     /// The actual name will lookup when calling in the object or symbol file
0941     ConstString m_lookup_name;
0942 
0943     /// Limit matches to only be for this language
0944     lldb::LanguageType m_language = lldb::eLanguageTypeUnknown;
0945 
0946     /// One or more bits from lldb::FunctionNameType that indicate what kind of
0947     /// names we are looking for
0948     lldb::FunctionNameType m_name_type_mask = lldb::eFunctionNameTypeNone;
0949 
0950     ///< If \b true, then demangled names that match will need to contain
0951     ///< "m_name" in order to be considered a match
0952     bool m_match_name_after_lookup = false;
0953   };
0954 
0955   /// Get a unique hash for this module.
0956   ///
0957   /// The hash should be enough to identify the file on disk and the
0958   /// architecture of the file. If the module represents an object inside of a
0959   /// file, then the hash should include the object name and object offset to
0960   /// ensure a unique hash. Some examples:
0961   /// - just a regular object file (mach-o, elf, coff, etc) should create a hash
0962   /// - a universal mach-o file that contains to multiple architectures,
0963   ///   each architecture slice should have a unique hash even though they come
0964   ///   from the same file
0965   /// - a .o file inside of a BSD archive. Each .o file will have an object name
0966   ///   and object offset that should produce a unique hash. The object offset
0967   ///   is needed as BSD archive files can contain multiple .o files that have
0968   ///   the same name.
0969   uint32_t Hash();
0970 
0971   /// Get a unique cache key for the current module.
0972   ///
0973   /// The cache key must be unique for a file on disk and not change if the file
0974   /// is updated. This allows cache data to use this key as a prefix and as
0975   /// files are modified in disk, we will overwrite the cache files. If one file
0976   /// can contain multiple files, like a universal mach-o file or like a BSD
0977   /// archive, the cache key must contain enough information to differentiate
0978   /// these different files.
0979   std::string GetCacheKey();
0980 
0981   /// Get the global index file cache.
0982   ///
0983   /// LLDB can cache data for a module between runs. This cache directory can be
0984   /// used to stored data that previously was manually created each time you debug.
0985   /// Examples include debug information indexes, symbol tables, symbol table
0986   /// indexes, and more.
0987   ///
0988   /// \returns
0989   ///   If caching is enabled in the lldb settings, return a pointer to the data
0990   ///   file cache. If caching is not enabled, return NULL.
0991   static DataFileCache *GetIndexCache();
0992 protected:
0993   // Member Variables
0994   mutable std::recursive_mutex m_mutex; ///< A mutex to keep this object happy
0995                                         /// in multi-threaded environments.
0996 
0997   /// The modification time for this module when it was created.
0998   llvm::sys::TimePoint<> m_mod_time;
0999 
1000   ArchSpec m_arch; ///< The architecture for this module.
1001   UUID m_uuid; ///< Each module is assumed to have a unique identifier to help
1002                /// match it up to debug symbols.
1003   FileSpec m_file; ///< The file representation on disk for this module (if
1004                    /// there is one).
1005   FileSpec m_platform_file; ///< The path to the module on the platform on which
1006                             /// it is being debugged
1007   FileSpec m_remote_install_file; ///< If set when debugging on remote
1008                                   /// platforms, this module will be installed
1009                                   /// at this location
1010   FileSpec m_symfile_spec;   ///< If this path is valid, then this is the file
1011                              /// that _will_ be used as the symbol file for this
1012                              /// module
1013   ConstString m_object_name; ///< The name an object within this module that is
1014                              /// selected, or empty of the module is represented
1015                              /// by \a m_file.
1016   uint64_t m_object_offset = 0;
1017   llvm::sys::TimePoint<> m_object_mod_time;
1018 
1019   /// DataBuffer containing the module image, if it was provided at
1020   /// construction time. Otherwise the data will be retrieved by mapping
1021   /// one of the FileSpec members above.
1022   lldb::DataBufferSP m_data_sp;
1023 
1024   lldb::ObjectFileSP m_objfile_sp; ///< A shared pointer to the object file
1025                                    /// parser for this module as it may or may
1026                                    /// not be shared with the SymbolFile
1027   UnwindTable m_unwind_table;      ///< Table of FuncUnwinders
1028                                    /// objects created for this
1029                                    /// Module's functions
1030   lldb::SymbolVendorUP
1031       m_symfile_up; ///< A pointer to the symbol vendor for this module.
1032   std::vector<lldb::SymbolVendorUP>
1033       m_old_symfiles; ///< If anyone calls Module::SetSymbolFileFileSpec() and
1034                       /// changes the symbol file,
1035   ///< we need to keep all old symbol files around in case anyone has type
1036   /// references to them
1037   TypeSystemMap m_type_system_map; ///< A map of any type systems associated
1038                                    /// with this module
1039   /// Module specific source remappings for when you have debug info for a
1040   /// module that doesn't match where the sources currently are.
1041   PathMappingList m_source_mappings =
1042       ModuleList::GetGlobalModuleListProperties().GetSymlinkMappings();
1043 
1044   lldb::SectionListUP m_sections_up; ///< Unified section list for module that
1045                                      /// is used by the ObjectFile and
1046                                      /// ObjectFile instances for the debug info
1047 
1048   std::atomic<bool> m_did_load_objfile{false};
1049   std::atomic<bool> m_did_load_symfile{false};
1050   std::atomic<bool> m_did_set_uuid{false};
1051   mutable bool m_file_has_changed : 1,
1052       m_first_file_changed_log : 1; /// See if the module was modified after it
1053                                     /// was initially opened.
1054   /// We store a symbol table parse time duration here because we might have
1055   /// an object file and a symbol file which both have symbol tables. The parse
1056   /// time for the symbol tables can be aggregated here.
1057   StatsDuration m_symtab_parse_time;
1058   /// We store a symbol named index time duration here because we might have
1059   /// an object file and a symbol file which both have symbol tables. The parse
1060   /// time for the symbol tables can be aggregated here.
1061   StatsDuration m_symtab_index_time;
1062 
1063   /// A set of hashes of all warnings and errors, to avoid reporting them
1064   /// multiple times to the same Debugger.
1065   llvm::DenseMap<llvm::stable_hash, std::unique_ptr<std::once_flag>>
1066       m_shown_diagnostics;
1067   std::recursive_mutex m_diagnostic_mutex;
1068 
1069   void SymbolIndicesToSymbolContextList(Symtab *symtab,
1070                                         std::vector<uint32_t> &symbol_indexes,
1071                                         SymbolContextList &sc_list);
1072 
1073   bool SetArchitecture(const ArchSpec &new_arch);
1074 
1075   void SetUUID(const lldb_private::UUID &uuid);
1076 
1077   SectionList *GetUnifiedSectionList();
1078 
1079   friend class ModuleList;
1080   friend class ObjectFile;
1081   friend class SymbolFile;
1082 
1083 private:
1084   Module(); // Only used internally by CreateJITModule ()
1085 
1086   Module(const Module &) = delete;
1087   const Module &operator=(const Module &) = delete;
1088 
1089   void LogMessage(Log *log, const llvm::formatv_object_base &payload);
1090   void LogMessageVerboseBacktrace(Log *log,
1091                                   const llvm::formatv_object_base &payload);
1092   void ReportWarning(const llvm::formatv_object_base &payload);
1093   void ReportError(const llvm::formatv_object_base &payload);
1094   void ReportErrorIfModifyDetected(const llvm::formatv_object_base &payload);
1095   std::once_flag *GetDiagnosticOnceFlag(llvm::StringRef msg);
1096 };
1097 
1098 } // namespace lldb_private
1099 
1100 #endif // LLDB_CORE_MODULE_H