1 //===-- SymbolFileDWARFDebugMap.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_SOURCE_PLUGINS_SYMBOLFILE_DWARF_SYMBOLFILEDWARFDEBUGMAP_H
10 #define LLDB_SOURCE_PLUGINS_SYMBOLFILE_DWARF_SYMBOLFILEDWARFDEBUGMAP_H
11 
12 #include "DIERef.h"
13 #include "lldb/Symbol/SymbolFile.h"
14 #include "lldb/Utility/RangeMap.h"
15 #include "llvm/Support/Chrono.h"
16 #include <bitset>
17 #include <map>
18 #include <optional>
19 #include <vector>
20 
21 #include "UniqueDWARFASTType.h"
22 
23 class SymbolFileDWARF;
24 class DWARFCompileUnit;
25 class DWARFDebugAranges;
26 class DWARFDeclContext;
27 
28 class SymbolFileDWARFDebugMap : public lldb_private::SymbolFileCommon {
29   /// LLVM RTTI support.
30   static char ID;
31 
32 public:
33   /// LLVM RTTI support.
34   /// \{
35   bool isA(const void *ClassID) const override {
36     return ClassID == &ID || SymbolFileCommon::isA(ClassID);
37   }
38   static bool classof(const SymbolFile *obj) { return obj->isA(&ID); }
39   /// \}
40 
41   // Static Functions
42   static void Initialize();
43 
44   static void Terminate();
45 
46   static llvm::StringRef GetPluginNameStatic() { return "dwarf-debugmap"; }
47 
48   static llvm::StringRef GetPluginDescriptionStatic();
49 
50   static lldb_private::SymbolFile *
51   CreateInstance(lldb::ObjectFileSP objfile_sp);
52 
53   // Constructors and Destructors
54   SymbolFileDWARFDebugMap(lldb::ObjectFileSP objfile_sp);
55   ~SymbolFileDWARFDebugMap() override;
56 
57   uint32_t CalculateAbilities() override;
58   void InitializeObject() override;
59 
60   // Compile Unit function calls
61   lldb::LanguageType
62   ParseLanguage(lldb_private::CompileUnit &comp_unit) override;
63   lldb_private::XcodeSDK
64   ParseXcodeSDK(lldb_private::CompileUnit &comp_unit) override;
65   llvm::SmallSet<lldb::LanguageType, 4>
66   ParseAllLanguages(lldb_private::CompileUnit &comp_unit) override;
67   size_t ParseFunctions(lldb_private::CompileUnit &comp_unit) override;
68   bool ParseLineTable(lldb_private::CompileUnit &comp_unit) override;
69   bool ParseDebugMacros(lldb_private::CompileUnit &comp_unit) override;
70 
71   bool ForEachExternalModule(
72       lldb_private::CompileUnit &, llvm::DenseSet<lldb_private::SymbolFile *> &,
73       llvm::function_ref<bool(lldb_private::Module &)>) override;
74 
75   bool ParseSupportFiles(lldb_private::CompileUnit &comp_unit,
76                          lldb_private::FileSpecList &support_files) override;
77 
78   bool ParseIsOptimized(lldb_private::CompileUnit &comp_unit) override;
79 
80   size_t ParseTypes(lldb_private::CompileUnit &comp_unit) override;
81 
82   bool ParseImportedModules(
83       const lldb_private::SymbolContext &sc,
84       std::vector<lldb_private::SourceModule> &imported_modules) override;
85   size_t ParseBlocksRecursive(lldb_private::Function &func) override;
86   size_t
87   ParseVariablesForContext(const lldb_private::SymbolContext &sc) override;
88 
89   lldb_private::Type *ResolveTypeUID(lldb::user_id_t type_uid) override;
90   std::optional<ArrayInfo> GetDynamicArrayInfoForUID(
91       lldb::user_id_t type_uid,
92       const lldb_private::ExecutionContext *exe_ctx) override;
93 
94   lldb_private::CompilerDeclContext
95   GetDeclContextForUID(lldb::user_id_t uid) override;
96   lldb_private::CompilerDeclContext
97   GetDeclContextContainingUID(lldb::user_id_t uid) override;
98   void
99   ParseDeclsForContext(lldb_private::CompilerDeclContext decl_ctx) override;
100 
101   bool CompleteType(lldb_private::CompilerType &compiler_type) override;
102   uint32_t ResolveSymbolContext(const lldb_private::Address &so_addr,
103                                 lldb::SymbolContextItem resolve_scope,
104                                 lldb_private::SymbolContext &sc) override;
105   uint32_t ResolveSymbolContext(
106       const lldb_private::SourceLocationSpec &src_location_spec,
107       lldb::SymbolContextItem resolve_scope,
108       lldb_private::SymbolContextList &sc_list) override;
109 
110   lldb_private::Status
111   CalculateFrameVariableError(lldb_private::StackFrame &frame) override;
112 
113   void
114   FindGlobalVariables(lldb_private::ConstString name,
115                       const lldb_private::CompilerDeclContext &parent_decl_ctx,
116                       uint32_t max_matches,
117                       lldb_private::VariableList &variables) override;
118   void FindGlobalVariables(const lldb_private::RegularExpression &regex,
119                            uint32_t max_matches,
120                            lldb_private::VariableList &variables) override;
121   void FindFunctions(const lldb_private::Module::LookupInfo &lookup_info,
122                      const lldb_private::CompilerDeclContext &parent_decl_ctx,
123                      bool include_inlines,
124                      lldb_private::SymbolContextList &sc_list) override;
125   void FindFunctions(const lldb_private::RegularExpression &regex,
126                      bool include_inlines,
127                      lldb_private::SymbolContextList &sc_list) override;
128   void
129   FindTypes(lldb_private::ConstString name,
130             const lldb_private::CompilerDeclContext &parent_decl_ctx,
131             uint32_t max_matches,
132             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
133             lldb_private::TypeMap &types) override;
134   void
135   FindTypes(llvm::ArrayRef<lldb_private::CompilerContext> context,
136             lldb_private::LanguageSet languages,
137             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
138             lldb_private::TypeMap &types) override;
139   lldb_private::CompilerDeclContext
140   FindNamespace(lldb_private::ConstString name,
141                 const lldb_private::CompilerDeclContext &parent_decl_ctx,
142                 bool only_root_namespaces) override;
143   void GetTypes(lldb_private::SymbolContextScope *sc_scope,
144                 lldb::TypeClass type_mask,
145                 lldb_private::TypeList &type_list) override;
146   std::vector<std::unique_ptr<lldb_private::CallEdge>>
147   ParseCallEdgesInFunction(lldb_private::UserID func_id) override;
148 
149   void DumpClangAST(lldb_private::Stream &s) override;
150 
151   // PluginInterface protocol
152   llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); }
153 
154   // Statistics overrides.
155   lldb_private::ModuleList GetDebugInfoModules() override;
156 
157   void GetCompileOptions(
158       std::unordered_map<lldb::CompUnitSP, lldb_private::Args> &args) override;
159 
160 protected:
161   enum { kHaveInitializedOSOs = (1 << 0), kNumFlags };
162 
163   friend class DebugMapModule;
164   friend class DWARFASTParserClang;
165   friend class DWARFCompileUnit;
166   friend class SymbolFileDWARF;
167   struct OSOInfo {
168     lldb::ModuleSP module_sp;
169 
170     OSOInfo() : module_sp() {}
171   };
172 
173   typedef std::shared_ptr<OSOInfo> OSOInfoSP;
174 
175   typedef lldb_private::RangeDataVector<lldb::addr_t, lldb::addr_t,
176                                         lldb::addr_t>
177       FileRangeMap;
178 
179   // Class specific types
180   struct CompileUnitInfo {
181     lldb_private::FileSpec so_file;
182     lldb_private::ConstString oso_path;
183     llvm::sys::TimePoint<> oso_mod_time;
184     lldb_private::Status oso_load_error;
185     OSOInfoSP oso_sp;
186     /// The compile units that an object file contains.
187     llvm::SmallVector<lldb::CompUnitSP, 2> compile_units_sps;
188     /// A map from the compile unit ID to its index in the vector.
189     llvm::SmallDenseMap<uint64_t, uint64_t, 2> id_to_index_map;
190     uint32_t first_symbol_index = UINT32_MAX;
191     uint32_t last_symbol_index = UINT32_MAX;
192     uint32_t first_symbol_id = UINT32_MAX;
193     uint32_t last_symbol_id = UINT32_MAX;
194     FileRangeMap file_range_map;
195     bool file_range_map_valid = false;
196 
197     CompileUnitInfo() = default;
198 
199     const FileRangeMap &GetFileRangeMap(SymbolFileDWARFDebugMap *exe_symfile);
200   };
201 
202   // Protected Member Functions
203   void InitOSO();
204 
205   /// This function actually returns the number of object files, which may be
206   /// less than the actual number of compile units, since an object file may
207   /// contain more than one compile unit. SymbolFileDWARFDebugMap looks up the
208   /// number of compile units by reading the nlist symbol table, which
209   /// currently, on macOS, only reports one compile unit per object file, and
210   /// there's no efficient way to calculate the actual number of compile units
211   /// upfront.
212   uint32_t CalculateNumCompileUnits() override;
213 
214   /// This function actually returns the first compile unit the object file at
215   /// the given index contains.
216   lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override;
217 
218   static uint32_t GetOSOIndexFromUserID(lldb::user_id_t uid) {
219     std::optional<uint32_t> OsoNum = DIERef(uid).file_index();
220     lldbassert(OsoNum && "Invalid OSO Index");
221     return *OsoNum;
222   }
223 
224   static SymbolFileDWARF *GetSymbolFileAsSymbolFileDWARF(SymbolFile *sym_file);
225 
226   bool GetFileSpecForSO(uint32_t oso_idx, lldb_private::FileSpec &file_spec);
227 
228   CompileUnitInfo *GetCompUnitInfo(const lldb_private::SymbolContext &sc);
229   CompileUnitInfo *GetCompUnitInfo(const lldb_private::CompileUnit &comp_unit);
230 
231   size_t GetCompUnitInfosForModule(const lldb_private::Module *oso_module,
232                                    std::vector<CompileUnitInfo *> &cu_infos);
233 
234   lldb_private::Module *
235   GetModuleByCompUnitInfo(CompileUnitInfo *comp_unit_info);
236 
237   lldb_private::Module *GetModuleByOSOIndex(uint32_t oso_idx);
238 
239   lldb_private::ObjectFile *
240   GetObjectFileByCompUnitInfo(CompileUnitInfo *comp_unit_info);
241 
242   lldb_private::ObjectFile *GetObjectFileByOSOIndex(uint32_t oso_idx);
243 
244   uint32_t GetCompUnitInfoIndex(const CompileUnitInfo *comp_unit_info);
245 
246   SymbolFileDWARF *GetSymbolFile(const lldb_private::SymbolContext &sc);
247   SymbolFileDWARF *GetSymbolFile(const lldb_private::CompileUnit &comp_unit);
248 
249   SymbolFileDWARF *GetSymbolFileByCompUnitInfo(CompileUnitInfo *comp_unit_info);
250 
251   SymbolFileDWARF *GetSymbolFileByOSOIndex(uint32_t oso_idx);
252 
253   // If closure returns "false", iteration continues.  If it returns
254   // "true", iteration terminates.
255   void ForEachSymbolFile(std::function<bool(SymbolFileDWARF *)> closure) {
256     for (uint32_t oso_idx = 0, num_oso_idxs = m_compile_unit_infos.size();
257          oso_idx < num_oso_idxs; ++oso_idx) {
258       if (SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex(oso_idx)) {
259         if (closure(oso_dwarf))
260           return;
261       }
262     }
263   }
264 
265   CompileUnitInfo *GetCompileUnitInfoForSymbolWithIndex(uint32_t symbol_idx,
266                                                         uint32_t *oso_idx_ptr);
267 
268   CompileUnitInfo *GetCompileUnitInfoForSymbolWithID(lldb::user_id_t symbol_id,
269                                                      uint32_t *oso_idx_ptr);
270 
271   static int
272   SymbolContainsSymbolWithIndex(uint32_t *symbol_idx_ptr,
273                                 const CompileUnitInfo *comp_unit_info);
274 
275   static int SymbolContainsSymbolWithID(lldb::user_id_t *symbol_idx_ptr,
276                                         const CompileUnitInfo *comp_unit_info);
277 
278   void PrivateFindGlobalVariables(
279       lldb_private::ConstString name,
280       const lldb_private::CompilerDeclContext &parent_decl_ctx,
281       const std::vector<uint32_t> &name_symbol_indexes, uint32_t max_matches,
282       lldb_private::VariableList &variables);
283 
284   void SetCompileUnit(SymbolFileDWARF *oso_dwarf,
285                       const lldb::CompUnitSP &cu_sp);
286 
287   /// Returns the compile unit associated with the dwarf compile unit. This may
288   /// be one of the extra compile units an object file contains which isn't
289   /// reachable by ParseCompileUnitAtIndex(uint32_t).
290   lldb::CompUnitSP GetCompileUnit(SymbolFileDWARF *oso_dwarf,
291                                   DWARFCompileUnit &dwarf_cu);
292 
293   CompileUnitInfo *GetCompileUnitInfo(SymbolFileDWARF *oso_dwarf);
294 
295   lldb::TypeSP FindDefinitionTypeForDWARFDeclContext(const DWARFDIE &die);
296 
297   bool Supports_DW_AT_APPLE_objc_complete_type(SymbolFileDWARF *skip_dwarf_oso);
298 
299   lldb::TypeSP FindCompleteObjCDefinitionTypeForDIE(
300       const DWARFDIE &die, lldb_private::ConstString type_name,
301       bool must_be_implementation);
302 
303   UniqueDWARFASTTypeMap &GetUniqueDWARFASTTypeMap() {
304     return m_unique_ast_type_map;
305   }
306 
307   // OSOEntry
308   class OSOEntry {
309   public:
310     OSOEntry() = default;
311 
312     OSOEntry(uint32_t exe_sym_idx, lldb::addr_t oso_file_addr)
313         : m_exe_sym_idx(exe_sym_idx), m_oso_file_addr(oso_file_addr) {}
314 
315     uint32_t GetExeSymbolIndex() const { return m_exe_sym_idx; }
316 
317     bool operator<(const OSOEntry &rhs) const {
318       return m_exe_sym_idx < rhs.m_exe_sym_idx;
319     }
320 
321     lldb::addr_t GetOSOFileAddress() const { return m_oso_file_addr; }
322 
323     void SetOSOFileAddress(lldb::addr_t oso_file_addr) {
324       m_oso_file_addr = oso_file_addr;
325     }
326 
327   protected:
328     uint32_t m_exe_sym_idx = UINT32_MAX;
329     lldb::addr_t m_oso_file_addr = LLDB_INVALID_ADDRESS;
330   };
331 
332   typedef lldb_private::RangeDataVector<lldb::addr_t, lldb::addr_t, OSOEntry>
333       DebugMap;
334 
335   // Member Variables
336   std::bitset<kNumFlags> m_flags;
337   std::vector<CompileUnitInfo> m_compile_unit_infos;
338   std::vector<uint32_t> m_func_indexes; // Sorted by address
339   std::vector<uint32_t> m_glob_indexes;
340   std::map<std::pair<lldb_private::ConstString, llvm::sys::TimePoint<>>,
341            OSOInfoSP>
342       m_oso_map;
343   UniqueDWARFASTTypeMap m_unique_ast_type_map;
344   lldb_private::LazyBool m_supports_DW_AT_APPLE_objc_complete_type;
345   DebugMap m_debug_map;
346 
347   // When an object file from the debug map gets parsed in
348   // SymbolFileDWARF, it needs to tell the debug map about the object
349   // files addresses by calling this function once for each N_FUN,
350   // N_GSYM and N_STSYM and after all entries in the debug map have
351   // been matched up, FinalizeOSOFileRanges() should be called.
352   bool AddOSOFileRange(CompileUnitInfo *cu_info, lldb::addr_t exe_file_addr,
353                        lldb::addr_t exe_byte_size, lldb::addr_t oso_file_addr,
354                        lldb::addr_t oso_byte_size);
355 
356   // Called after calling AddOSOFileRange() for each object file debug
357   // map entry to finalize the info for the unlinked compile unit.
358   void FinalizeOSOFileRanges(CompileUnitInfo *cu_info);
359 
360   /// Convert \a addr from a .o file address, to an executable address.
361   ///
362   /// \param[in] addr
363   ///     A section offset address from a .o file
364   ///
365   /// \return
366   ///     Returns true if \a addr was converted to be an executable
367   ///     section/offset address, false otherwise.
368   bool LinkOSOAddress(lldb_private::Address &addr);
369 
370   /// Convert a .o file "file address" to an executable "file address".
371   ///
372   /// \param[in] oso_symfile
373   ///     The DWARF symbol file that contains \a oso_file_addr
374   ///
375   /// \param[in] oso_file_addr
376   ///     A .o file "file address" to convert.
377   ///
378   /// \return
379   ///     LLDB_INVALID_ADDRESS if \a oso_file_addr is not in the
380   ///     linked executable, otherwise a valid "file address" from the
381   ///     linked executable that contains the debug map.
382   lldb::addr_t LinkOSOFileAddress(SymbolFileDWARF *oso_symfile,
383                                   lldb::addr_t oso_file_addr);
384 
385   /// Given a line table full of lines with "file addresses" that are
386   /// for a .o file represented by \a oso_symfile, link a new line table
387   /// and return it.
388   ///
389   /// \param[in] oso_symfile
390   ///     The DWARF symbol file that produced the \a line_table
391   ///
392   /// \param[in] line_table
393   ///     A pointer to the line table.
394   ///
395   /// \return
396   ///     Returns a valid line table full of linked addresses, or NULL
397   ///     if none of the line table addresses exist in the main
398   ///     executable.
399   lldb_private::LineTable *
400   LinkOSOLineTable(SymbolFileDWARF *oso_symfile,
401                    lldb_private::LineTable *line_table);
402 
403   size_t AddOSOARanges(SymbolFileDWARF *dwarf2Data,
404                        DWARFDebugAranges *debug_aranges);
405 };
406 
407 #endif // LLDB_SOURCE_PLUGINS_SYMBOLFILE_DWARF_SYMBOLFILEDWARFDEBUGMAP_H
408