1 //===-- SymbolFile.h --------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_SYMBOL_SYMBOLFILE_H
10 #define LLDB_SYMBOL_SYMBOLFILE_H
11 
12 #include "lldb/Core/ModuleList.h"
13 #include "lldb/Core/PluginInterface.h"
14 #include "lldb/Core/SourceLocationSpec.h"
15 #include "lldb/Symbol/CompilerDecl.h"
16 #include "lldb/Symbol/CompilerDeclContext.h"
17 #include "lldb/Symbol/CompilerType.h"
18 #include "lldb/Symbol/Function.h"
19 #include "lldb/Symbol/SourceModule.h"
20 #include "lldb/Symbol/Type.h"
21 #include "lldb/Symbol/TypeList.h"
22 #include "lldb/Symbol/TypeSystem.h"
23 #include "lldb/Target/Statistics.h"
24 #include "lldb/Utility/XcodeSDK.h"
25 #include "lldb/lldb-private.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/Support/Errc.h"
28 
29 #include <mutex>
30 
31 #if defined(LLDB_CONFIGURATION_DEBUG)
32 #define ASSERT_MODULE_LOCK(expr) (expr->AssertModuleLock())
33 #else
34 #define ASSERT_MODULE_LOCK(expr) ((void)0)
35 #endif
36 
37 namespace lldb_private {
38 
39 /// Provides public interface for all SymbolFiles. Any protected
40 /// virtual members should go into SymbolFileCommon; most SymbolFile
41 /// implementations should inherit from SymbolFileCommon to override
42 /// the behaviors except SymbolFileOnDemand which inherits
43 /// public interfaces from SymbolFile and forward to underlying concrete
44 /// SymbolFile implementation.
45 class SymbolFile : public PluginInterface {
46   /// LLVM RTTI support.
47   static char ID;
48 
49 public:
50   /// LLVM RTTI support.
51   /// \{
52   virtual bool isA(const void *ClassID) const { return ClassID == &ID; }
53   static bool classof(const SymbolFile *obj) { return obj->isA(&ID); }
54   /// \}
55 
56   // Symbol file ability bits.
57   //
58   // Each symbol file can claim to support one or more symbol file abilities.
59   // These get returned from SymbolFile::GetAbilities(). These help us to
60   // determine which plug-in will be best to load the debug information found
61   // in files.
62   enum Abilities {
63     CompileUnits = (1u << 0),
64     LineTables = (1u << 1),
65     Functions = (1u << 2),
66     Blocks = (1u << 3),
67     GlobalVariables = (1u << 4),
68     LocalVariables = (1u << 5),
69     VariableTypes = (1u << 6),
70     kAllAbilities = ((1u << 7) - 1u)
71   };
72 
73   static SymbolFile *FindPlugin(lldb::ObjectFileSP objfile_sp);
74 
75   // Constructors and Destructors
76   SymbolFile() = default;
77 
78   ~SymbolFile() override = default;
79 
80   /// SymbolFileOnDemand class overrides this to return the underlying
81   /// backing SymbolFile implementation that loads on-demand.
82   virtual SymbolFile *GetBackingSymbolFile() { return this; }
83 
84   /// Get a mask of what this symbol file supports for the object file
85   /// that it was constructed with.
86   ///
87   /// Each symbol file gets to respond with a mask of abilities that
88   /// it supports for each object file. This happens when we are
89   /// trying to figure out which symbol file plug-in will get used
90   /// for a given object file. The plug-in that responds with the
91   /// best mix of "SymbolFile::Abilities" bits set, will get chosen to
92   /// be the symbol file parser. This allows each plug-in to check for
93   /// sections that contain data a symbol file plug-in would need. For
94   /// example the DWARF plug-in requires DWARF sections in a file that
95   /// contain debug information. If the DWARF plug-in doesn't find
96   /// these sections, it won't respond with many ability bits set, and
97   /// we will probably fall back to the symbol table SymbolFile plug-in
98   /// which uses any information in the symbol table. Also, plug-ins
99   /// might check for some specific symbols in a symbol table in the
100   /// case where the symbol table contains debug information (STABS
101   /// and COFF). Not a lot of work should happen in these functions
102   /// as the plug-in might not get selected due to another plug-in
103   /// having more abilities. Any initialization work should be saved
104   /// for "void SymbolFile::InitializeObject()" which will get called
105   /// on the SymbolFile object with the best set of abilities.
106   ///
107   /// \return
108   ///     A uint32_t mask containing bits from the SymbolFile::Abilities
109   ///     enumeration. Any bits that are set represent an ability that
110   ///     this symbol plug-in can parse from the object file.
111   virtual uint32_t GetAbilities() = 0;
112   virtual uint32_t CalculateAbilities() = 0;
113 
114   /// Symbols file subclasses should override this to return the Module that
115   /// owns the TypeSystem that this symbol file modifies type information in.
116   virtual std::recursive_mutex &GetModuleMutex() const;
117 
118   /// Initialize the SymbolFile object.
119   ///
120   /// The SymbolFile object with the best set of abilities (detected
121   /// in "uint32_t SymbolFile::GetAbilities()) will have this function
122   /// called if it is chosen to parse an object file. More complete
123   /// initialization can happen in this function which will get called
124   /// prior to any other functions in the SymbolFile protocol.
125   virtual void InitializeObject() {}
126 
127   /// Whether debug info will be loaded or not.
128   ///
129   /// It will be true for most implementations except SymbolFileOnDemand.
130   virtual bool GetLoadDebugInfoEnabled() { return true; }
131 
132   /// Specify debug info should be loaded.
133   ///
134   /// It will be no-op for most implementations except SymbolFileOnDemand.
135   virtual void SetLoadDebugInfoEnabled() {}
136 
137   // Compile Unit function calls
138   // Approach 1 - iterator
139   virtual uint32_t GetNumCompileUnits() = 0;
140   virtual lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) = 0;
141 
142   virtual Symtab *GetSymtab() = 0;
143 
144   virtual lldb::LanguageType ParseLanguage(CompileUnit &comp_unit) = 0;
145   /// Return the Xcode SDK comp_unit was compiled against.
146   virtual XcodeSDK ParseXcodeSDK(CompileUnit &comp_unit) { return {}; }
147   virtual size_t ParseFunctions(CompileUnit &comp_unit) = 0;
148   virtual bool ParseLineTable(CompileUnit &comp_unit) = 0;
149   virtual bool ParseDebugMacros(CompileUnit &comp_unit) = 0;
150 
151   /// Apply a lambda to each external lldb::Module referenced by this
152   /// \p comp_unit. Recursively also descends into the referenced external
153   /// modules of any encountered compilation unit.
154   ///
155   /// This function can be used to traverse Clang -gmodules debug
156   /// information, which is stored in DWARF files separate from the
157   /// object files.
158   ///
159   /// \param comp_unit
160   ///     When this SymbolFile consists of multiple auxilliary
161   ///     SymbolFiles, for example, a Darwin debug map that references
162   ///     multiple .o files, comp_unit helps choose the auxilliary
163   ///     file. In most other cases comp_unit's symbol file is
164   ///     identical with *this.
165   ///
166   /// \param[in] lambda
167   ///     The lambda that should be applied to every function. The lambda can
168   ///     return true if the iteration should be aborted earlier.
169   ///
170   /// \param visited_symbol_files
171   ///     A set of SymbolFiles that were already visited to avoid
172   ///     visiting one file more than once.
173   ///
174   /// \return
175   ///     If the lambda early-exited, this function returns true to
176   ///     propagate the early exit.
177   virtual bool ForEachExternalModule(
178       lldb_private::CompileUnit &comp_unit,
179       llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
180       llvm::function_ref<bool(Module &)> lambda) {
181     return false;
182   }
183   virtual bool ParseSupportFiles(CompileUnit &comp_unit,
184                                  FileSpecList &support_files) = 0;
185   virtual size_t ParseTypes(CompileUnit &comp_unit) = 0;
186   virtual bool ParseIsOptimized(CompileUnit &comp_unit) { return false; }
187 
188   virtual bool
189   ParseImportedModules(const SymbolContext &sc,
190                        std::vector<SourceModule> &imported_modules) = 0;
191   virtual size_t ParseBlocksRecursive(Function &func) = 0;
192   virtual size_t ParseVariablesForContext(const SymbolContext &sc) = 0;
193   virtual Type *ResolveTypeUID(lldb::user_id_t type_uid) = 0;
194 
195   /// The characteristics of an array type.
196   struct ArrayInfo {
197     int64_t first_index = 0;
198     llvm::SmallVector<uint64_t, 1> element_orders;
199     uint32_t byte_stride = 0;
200     uint32_t bit_stride = 0;
201   };
202   /// If \c type_uid points to an array type, return its characteristics.
203   /// To support variable-length array types, this function takes an
204   /// optional \p ExecutionContext. If \c exe_ctx is non-null, the
205   /// dynamic characteristics for that context are returned.
206   virtual llvm::Optional<ArrayInfo>
207   GetDynamicArrayInfoForUID(lldb::user_id_t type_uid,
208                             const lldb_private::ExecutionContext *exe_ctx) = 0;
209 
210   virtual bool CompleteType(CompilerType &compiler_type) = 0;
211   virtual void ParseDeclsForContext(CompilerDeclContext decl_ctx) {}
212   virtual CompilerDecl GetDeclForUID(lldb::user_id_t uid) {
213     return CompilerDecl();
214   }
215   virtual CompilerDeclContext GetDeclContextForUID(lldb::user_id_t uid) {
216     return CompilerDeclContext();
217   }
218   virtual CompilerDeclContext GetDeclContextContainingUID(lldb::user_id_t uid) {
219     return CompilerDeclContext();
220   }
221   virtual uint32_t ResolveSymbolContext(const Address &so_addr,
222                                         lldb::SymbolContextItem resolve_scope,
223                                         SymbolContext &sc) = 0;
224   virtual uint32_t
225   ResolveSymbolContext(const SourceLocationSpec &src_location_spec,
226                        lldb::SymbolContextItem resolve_scope,
227                        SymbolContextList &sc_list);
228 
229   virtual void DumpClangAST(Stream &s) {}
230   virtual void FindGlobalVariables(ConstString name,
231                                    const CompilerDeclContext &parent_decl_ctx,
232                                    uint32_t max_matches,
233                                    VariableList &variables);
234   virtual void FindGlobalVariables(const RegularExpression &regex,
235                                    uint32_t max_matches,
236                                    VariableList &variables);
237   virtual void FindFunctions(ConstString name,
238                              const CompilerDeclContext &parent_decl_ctx,
239                              lldb::FunctionNameType name_type_mask,
240                              bool include_inlines, SymbolContextList &sc_list);
241   virtual void FindFunctions(const RegularExpression &regex,
242                              bool include_inlines, SymbolContextList &sc_list);
243   virtual void
244   FindTypes(ConstString name, const CompilerDeclContext &parent_decl_ctx,
245             uint32_t max_matches,
246             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
247             TypeMap &types);
248 
249   /// Find types specified by a CompilerContextPattern.
250   /// \param languages
251   ///     Only return results in these languages.
252   /// \param searched_symbol_files
253   ///     Prevents one file from being visited multiple times.
254   virtual void
255   FindTypes(llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
256             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
257             TypeMap &types);
258 
259   virtual void
260   GetMangledNamesForFunction(const std::string &scope_qualified_name,
261                              std::vector<ConstString> &mangled_names);
262 
263   virtual void GetTypes(lldb_private::SymbolContextScope *sc_scope,
264                         lldb::TypeClass type_mask,
265                         lldb_private::TypeList &type_list) = 0;
266 
267   virtual void PreloadSymbols();
268 
269   virtual llvm::Expected<lldb_private::TypeSystem &>
270   GetTypeSystemForLanguage(lldb::LanguageType language) = 0;
271 
272   virtual CompilerDeclContext
273   FindNamespace(ConstString name, const CompilerDeclContext &parent_decl_ctx) {
274     return CompilerDeclContext();
275   }
276 
277   virtual ObjectFile *GetObjectFile() = 0;
278   virtual const ObjectFile *GetObjectFile() const = 0;
279   virtual ObjectFile *GetMainObjectFile() = 0;
280 
281   virtual std::vector<std::unique_ptr<CallEdge>>
282   ParseCallEdgesInFunction(UserID func_id) {
283     return {};
284   }
285 
286   virtual void AddSymbols(Symtab &symtab) {}
287 
288   /// Notify the SymbolFile that the file addresses in the Sections
289   /// for this module have been changed.
290   virtual void SectionFileAddressesChanged() = 0;
291 
292   struct RegisterInfoResolver {
293     virtual ~RegisterInfoResolver(); // anchor
294 
295     virtual const RegisterInfo *ResolveName(llvm::StringRef name) const = 0;
296     virtual const RegisterInfo *ResolveNumber(lldb::RegisterKind kind,
297                                               uint32_t number) const = 0;
298   };
299   virtual lldb::UnwindPlanSP
300   GetUnwindPlan(const Address &address, const RegisterInfoResolver &resolver) {
301     return nullptr;
302   }
303 
304   /// Return the number of stack bytes taken up by the parameters to this
305   /// function.
306   virtual llvm::Expected<lldb::addr_t> GetParameterStackSize(Symbol &symbol) {
307     return llvm::createStringError(make_error_code(llvm::errc::not_supported),
308                                    "Operation not supported.");
309   }
310 
311   virtual void Dump(Stream &s) = 0;
312 
313   /// Metrics gathering functions
314 
315   /// Return the size in bytes of all debug information in the symbol file.
316   ///
317   /// If the debug information is contained in sections of an ObjectFile, then
318   /// this call should add the size of all sections that contain debug
319   /// information. Symbols the symbol tables are not considered debug
320   /// information for this call to make it easy and quick for this number to be
321   /// calculated. If the symbol file is all debug information, the size of the
322   /// entire file should be returned. The default implementation of this
323   /// function will iterate over all sections in a module and add up their
324   /// debug info only section byte sizes.
325   virtual uint64_t GetDebugInfoSize() = 0;
326 
327   /// Return the time taken to parse the debug information.
328   ///
329   /// \returns 0.0 if no information has been parsed or if there is
330   /// no computational cost to parsing the debug information.
331   virtual StatsDuration::Duration GetDebugInfoParseTime() { return {}; }
332 
333   /// Return the time it took to index the debug information in the object
334   /// file.
335   ///
336   /// \returns 0.0 if the file doesn't need to be indexed or if it
337   /// hasn't been indexed yet, or a valid duration if it has.
338   virtual StatsDuration::Duration GetDebugInfoIndexTime() { return {}; }
339 
340   /// Get the additional modules that this symbol file uses to parse debug info.
341   ///
342   /// Some debug info is stored in stand alone object files that are represented
343   /// by unique modules that will show up in the statistics module list. Return
344   /// a list of modules that are not in the target module list that this symbol
345   /// file is currently using so that they can be tracked and assoicated with
346   /// the module in the statistics.
347   virtual ModuleList GetDebugInfoModules() { return ModuleList(); }
348 
349   /// Accessors for the bool that indicates if the debug info index was loaded
350   /// from, or saved to the module index cache.
351   ///
352   /// In statistics it is handy to know if a module's debug info was loaded from
353   /// or saved to the cache. When the debug info index is loaded from the cache
354   /// startup times can be faster. When the cache is enabled and the debug info
355   /// index is saved to the cache, debug sessions can be slower. These accessors
356   /// can be accessed by the statistics and emitted to help track these costs.
357   /// \{
358   virtual bool GetDebugInfoIndexWasLoadedFromCache() const = 0;
359   virtual void SetDebugInfoIndexWasLoadedFromCache() = 0;
360   virtual bool GetDebugInfoIndexWasSavedToCache() const = 0;
361   virtual void SetDebugInfoIndexWasSavedToCache() = 0;
362   /// \}
363 
364 protected:
365   void AssertModuleLock();
366 
367 private:
368   SymbolFile(const SymbolFile &) = delete;
369   const SymbolFile &operator=(const SymbolFile &) = delete;
370 };
371 
372 /// Containing protected virtual methods for child classes to override.
373 /// Most actual SymbolFile implementations should inherit from this class.
374 class SymbolFileCommon : public SymbolFile {
375   /// LLVM RTTI support.
376   static char ID;
377 
378 public:
379   /// LLVM RTTI support.
380   /// \{
381   bool isA(const void *ClassID) const override {
382     return ClassID == &ID || SymbolFile::isA(ClassID);
383   }
384   static bool classof(const SymbolFileCommon *obj) { return obj->isA(&ID); }
385   /// \}
386 
387   // Constructors and Destructors
388   SymbolFileCommon(lldb::ObjectFileSP objfile_sp)
389       : m_objfile_sp(std::move(objfile_sp)) {}
390 
391   ~SymbolFileCommon() override = default;
392 
393   uint32_t GetAbilities() override {
394     if (!m_calculated_abilities) {
395       m_abilities = CalculateAbilities();
396       m_calculated_abilities = true;
397     }
398     return m_abilities;
399   }
400 
401   Symtab *GetSymtab() override;
402 
403   ObjectFile *GetObjectFile() override { return m_objfile_sp.get(); }
404   const ObjectFile *GetObjectFile() const override {
405     return m_objfile_sp.get();
406   }
407   ObjectFile *GetMainObjectFile() override;
408 
409   /// Notify the SymbolFile that the file addresses in the Sections
410   /// for this module have been changed.
411   void SectionFileAddressesChanged() override;
412 
413   // Compile Unit function calls
414   // Approach 1 - iterator
415   uint32_t GetNumCompileUnits() override;
416   lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) override;
417 
418   llvm::Expected<lldb_private::TypeSystem &>
419   GetTypeSystemForLanguage(lldb::LanguageType language) override;
420 
421   void Dump(Stream &s) override;
422 
423   uint64_t GetDebugInfoSize() override;
424 
425   bool GetDebugInfoIndexWasLoadedFromCache() const override {
426     return m_index_was_loaded_from_cache;
427   }
428   void SetDebugInfoIndexWasLoadedFromCache() override {
429     m_index_was_loaded_from_cache = true;
430   }
431   bool GetDebugInfoIndexWasSavedToCache() const override {
432     return m_index_was_saved_to_cache;
433   }
434   void SetDebugInfoIndexWasSavedToCache() override {
435     m_index_was_saved_to_cache = true;
436   }
437 
438 protected:
439   virtual uint32_t CalculateNumCompileUnits() = 0;
440   virtual lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t idx) = 0;
441   virtual TypeList &GetTypeList() { return m_type_list; }
442   void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp);
443 
444   lldb::ObjectFileSP m_objfile_sp; // Keep a reference to the object file in
445                                    // case it isn't the same as the module
446                                    // object file (debug symbols in a separate
447                                    // file)
448   llvm::Optional<std::vector<lldb::CompUnitSP>> m_compile_units;
449   TypeList m_type_list;
450   Symtab *m_symtab = nullptr;
451   uint32_t m_abilities = 0;
452   bool m_calculated_abilities = false;
453   bool m_index_was_loaded_from_cache = false;
454   bool m_index_was_saved_to_cache = false;
455 
456 private:
457   SymbolFileCommon(const SymbolFileCommon &) = delete;
458   const SymbolFileCommon &operator=(const SymbolFileCommon &) = delete;
459 };
460 
461 } // namespace lldb_private
462 
463 #endif // LLDB_SYMBOL_SYMBOLFILE_H
464