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