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