1 //===-- ClangExpressionDeclMap.h --------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef liblldb_ClangExpressionDeclMap_h_
11 #define liblldb_ClangExpressionDeclMap_h_
12 
13 // C Includes
14 #include <signal.h>
15 #include <stdint.h>
16 
17 // C++ Includes
18 #include <vector>
19 
20 #include "ClangASTSource.h"
21 #include "ClangExpressionVariable.h"
22 
23 // Other libraries and framework includes
24 // Project includes
25 #include "lldb/Core/ClangForward.h"
26 #include "lldb/Core/Value.h"
27 #include "lldb/Expression/Materializer.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/TaggedASTType.h"
30 #include "lldb/Target/ExecutionContext.h"
31 #include "lldb/lldb-public.h"
32 #include "clang/AST/Decl.h"
33 #include "llvm/ADT/DenseMap.h"
34 
35 namespace lldb_private {
36 
37 //----------------------------------------------------------------------
38 /// @class ClangExpressionDeclMap ClangExpressionDeclMap.h
39 /// "lldb/Expression/ClangExpressionDeclMap.h"
40 /// @brief Manages named entities that are defined in LLDB's debug information.
41 ///
42 /// The Clang parser uses the ClangASTSource as an interface to request named
43 /// entities from outside an expression.  The ClangASTSource reports back,
44 /// listing
45 /// all possible objects corresponding to a particular name.  But it in turn
46 /// relies on ClangExpressionDeclMap, which performs several important
47 /// functions.
48 ///
49 /// First, it records what variables and functions were looked up and what Decls
50 /// were returned for them.
51 ///
52 /// Second, it constructs a struct on behalf of IRForTarget, recording which
53 /// variables should be placed where and relaying this information back so that
54 /// IRForTarget can generate context-independent code.
55 ///
56 /// Third, it "materializes" this struct on behalf of the expression command,
57 /// finding the current values of each variable and placing them into the
58 /// struct so that it can be passed to the JITted version of the IR.
59 ///
60 /// Fourth and finally, it "dematerializes" the struct after the JITted code has
61 /// has executed, placing the new values back where it found the old ones.
62 //----------------------------------------------------------------------
63 class ClangExpressionDeclMap : public ClangASTSource {
64 public:
65   //------------------------------------------------------------------
66   /// Constructor
67   ///
68   /// Initializes class variables.
69   ///
70   /// @param[in] keep_result_in_memory
71   ///     If true, inhibits the normal deallocation of the memory for
72   ///     the result persistent variable, and instead marks the variable
73   ///     as persisting.
74   ///
75   /// @param[in] delegate
76   ///     If non-NULL, use this delegate to report result values.  This
77   ///     allows the client ClangUserExpression to report a result.
78   ///
79   /// @param[in] exe_ctx
80   ///     The execution context to use when parsing.
81   //------------------------------------------------------------------
82   ClangExpressionDeclMap(
83       bool keep_result_in_memory,
84       Materializer::PersistentVariableDelegate *result_delegate,
85       ExecutionContext &exe_ctx);
86 
87   //------------------------------------------------------------------
88   /// Destructor
89   //------------------------------------------------------------------
90   ~ClangExpressionDeclMap() override;
91 
92   //------------------------------------------------------------------
93   /// Enable the state needed for parsing and IR transformation.
94   ///
95   /// @param[in] exe_ctx
96   ///     The execution context to use when finding types for variables.
97   ///     Also used to find a "scratch" AST context to store result types.
98   ///
99   /// @param[in] materializer
100   ///     If non-NULL, the materializer to populate with information about
101   ///     the variables to use
102   ///
103   /// @return
104   ///     True if parsing is possible; false if it is unsafe to continue.
105   //------------------------------------------------------------------
106   bool WillParse(ExecutionContext &exe_ctx, Materializer *materializer);
107 
108   void InstallCodeGenerator(clang::ASTConsumer *code_gen);
109 
110   //------------------------------------------------------------------
111   /// [Used by ClangExpressionParser] For each variable that had an unknown
112   ///     type at the beginning of parsing, determine its final type now.
113   ///
114   /// @return
115   ///     True on success; false otherwise.
116   //------------------------------------------------------------------
117   bool ResolveUnknownTypes();
118 
119   //------------------------------------------------------------------
120   /// Disable the state needed for parsing and IR transformation.
121   //------------------------------------------------------------------
122   void DidParse();
123 
124   //------------------------------------------------------------------
125   /// [Used by IRForTarget] Add a variable to the list of persistent
126   ///     variables for the process.
127   ///
128   /// @param[in] decl
129   ///     The Clang declaration for the persistent variable, used for
130   ///     lookup during parsing.
131   ///
132   /// @param[in] name
133   ///     The name of the persistent variable, usually $something.
134   ///
135   /// @param[in] type
136   ///     The type of the variable, in the Clang parser's context.
137   ///
138   /// @return
139   ///     True on success; false otherwise.
140   //------------------------------------------------------------------
141   bool AddPersistentVariable(const clang::NamedDecl *decl,
142                              const ConstString &name, TypeFromParser type,
143                              bool is_result, bool is_lvalue);
144 
145   //------------------------------------------------------------------
146   /// [Used by IRForTarget] Add a variable to the struct that needs to
147   ///     be materialized each time the expression runs.
148   ///
149   /// @param[in] decl
150   ///     The Clang declaration for the variable.
151   ///
152   /// @param[in] name
153   ///     The name of the variable.
154   ///
155   /// @param[in] value
156   ///     The LLVM IR value for this variable.
157   ///
158   /// @param[in] size
159   ///     The size of the variable in bytes.
160   ///
161   /// @param[in] alignment
162   ///     The required alignment of the variable in bytes.
163   ///
164   /// @return
165   ///     True on success; false otherwise.
166   //------------------------------------------------------------------
167   bool AddValueToStruct(const clang::NamedDecl *decl, const ConstString &name,
168                         llvm::Value *value, size_t size,
169                         lldb::offset_t alignment);
170 
171   //------------------------------------------------------------------
172   /// [Used by IRForTarget] Finalize the struct, laying out the position
173   /// of each object in it.
174   ///
175   /// @return
176   ///     True on success; false otherwise.
177   //------------------------------------------------------------------
178   bool DoStructLayout();
179 
180   //------------------------------------------------------------------
181   /// [Used by IRForTarget] Get general information about the laid-out
182   /// struct after DoStructLayout() has been called.
183   ///
184   /// @param[out] num_elements
185   ///     The number of elements in the struct.
186   ///
187   /// @param[out] size
188   ///     The size of the struct, in bytes.
189   ///
190   /// @param[out] alignment
191   ///     The alignment of the struct, in bytes.
192   ///
193   /// @return
194   ///     True if the information could be retrieved; false otherwise.
195   //------------------------------------------------------------------
196   bool GetStructInfo(uint32_t &num_elements, size_t &size,
197                      lldb::offset_t &alignment);
198 
199   //------------------------------------------------------------------
200   /// [Used by IRForTarget] Get specific information about one field
201   /// of the laid-out struct after DoStructLayout() has been called.
202   ///
203   /// @param[out] decl
204   ///     The parsed Decl for the field, as generated by ClangASTSource
205   ///     on ClangExpressionDeclMap's behalf.  In the case of the result
206   ///     value, this will have the name $__lldb_result even if the
207   ///     result value ends up having the name $1.  This is an
208   ///     implementation detail of IRForTarget.
209   ///
210   /// @param[out] value
211   ///     The IR value for the field (usually a GlobalVariable).  In
212   ///     the case of the result value, this will have the correct
213   ///     name ($1, for instance).  This is an implementation detail
214   ///     of IRForTarget.
215   ///
216   /// @param[out] offset
217   ///     The offset of the field from the beginning of the struct.
218   ///     As long as the struct is aligned according to its required
219   ///     alignment, this offset will align the field correctly.
220   ///
221   /// @param[out] name
222   ///     The name of the field as used in materialization.
223   ///
224   /// @param[in] index
225   ///     The index of the field about which information is requested.
226   ///
227   /// @return
228   ///     True if the information could be retrieved; false otherwise.
229   //------------------------------------------------------------------
230   bool GetStructElement(const clang::NamedDecl *&decl, llvm::Value *&value,
231                         lldb::offset_t &offset, ConstString &name,
232                         uint32_t index);
233 
234   //------------------------------------------------------------------
235   /// [Used by IRForTarget] Get information about a function given its
236   /// Decl.
237   ///
238   /// @param[in] decl
239   ///     The parsed Decl for the Function, as generated by ClangASTSource
240   ///     on ClangExpressionDeclMap's behalf.
241   ///
242   /// @param[out] ptr
243   ///     The absolute address of the function in the target.
244   ///
245   /// @return
246   ///     True if the information could be retrieved; false otherwise.
247   //------------------------------------------------------------------
248   bool GetFunctionInfo(const clang::NamedDecl *decl, uint64_t &ptr);
249 
250   //------------------------------------------------------------------
251   /// [Used by IRForTarget] Get the address of a symbol given nothing
252   /// but its name.
253   ///
254   /// @param[in] target
255   ///     The target to find the symbol in.  If not provided,
256   ///     then the current parsing context's Target.
257   ///
258   /// @param[in] process
259   ///     The process to use.  For Objective-C symbols, the process's
260   ///     Objective-C language runtime may be queried if the process
261   ///     is non-NULL.
262   ///
263   /// @param[in] name
264   ///     The name of the symbol.
265   ///
266   /// @param[in] module
267   ///     The module to limit the search to. This can be NULL
268   ///
269   /// @return
270   ///     Valid load address for the symbol
271   //------------------------------------------------------------------
272   lldb::addr_t GetSymbolAddress(Target &target, Process *process,
273                                 const ConstString &name,
274                                 lldb::SymbolType symbol_type,
275                                 Module *module = NULL);
276 
277   lldb::addr_t GetSymbolAddress(const ConstString &name,
278                                 lldb::SymbolType symbol_type);
279 
280   //------------------------------------------------------------------
281   /// [Used by IRInterpreter] Get basic target information.
282   ///
283   /// @param[out] byte_order
284   ///     The byte order of the target.
285   ///
286   /// @param[out] address_byte_size
287   ///     The size of a pointer in bytes.
288   ///
289   /// @return
290   ///     True if the information could be determined; false
291   ///     otherwise.
292   //------------------------------------------------------------------
293   struct TargetInfo {
294     lldb::ByteOrder byte_order;
295     size_t address_byte_size;
296 
297     TargetInfo() : byte_order(lldb::eByteOrderInvalid), address_byte_size(0) {}
298 
299     bool IsValid() {
300       return (byte_order != lldb::eByteOrderInvalid && address_byte_size != 0);
301     }
302   };
303   TargetInfo GetTargetInfo();
304 
305   //------------------------------------------------------------------
306   /// [Used by ClangASTSource] Find all entities matching a given name,
307   /// using a NameSearchContext to make Decls for them.
308   ///
309   /// @param[in] context
310   ///     The NameSearchContext that can construct Decls for this name.
311   ///
312   /// @return
313   ///     True on success; false otherwise.
314   //------------------------------------------------------------------
315   void FindExternalVisibleDecls(NameSearchContext &context) override;
316 
317   //------------------------------------------------------------------
318   /// Find all entities matching a given name in a given module/namespace,
319   /// using a NameSearchContext to make Decls for them.
320   ///
321   /// @param[in] context
322   ///     The NameSearchContext that can construct Decls for this name.
323   ///
324   /// @param[in] module
325   ///     If non-NULL, the module to query.
326   ///
327   /// @param[in] namespace_decl
328   ///     If valid and module is non-NULL, the parent namespace.
329   ///
330   /// @param[in] name
331   ///     The name as a plain C string.  The NameSearchContext contains
332   ///     a DeclarationName for the name so at first the name may seem
333   ///     redundant, but ClangExpressionDeclMap operates in RTTI land so
334   ///     it can't access DeclarationName.
335   ///
336   /// @param[in] current_id
337   ///     The ID for the current FindExternalVisibleDecls invocation,
338   ///     for logging purposes.
339   ///
340   /// @return
341   ///     True on success; false otherwise.
342   //------------------------------------------------------------------
343   void FindExternalVisibleDecls(NameSearchContext &context,
344                                 lldb::ModuleSP module,
345                                 CompilerDeclContext &namespace_decl,
346                                 unsigned int current_id);
347 
348 private:
349   ExpressionVariableList
350       m_found_entities; ///< All entities that were looked up for the parser.
351   ExpressionVariableList
352       m_struct_members; ///< All entities that need to be placed in the struct.
353   bool m_keep_result_in_memory; ///< True if result persistent variables
354                                 ///generated by this expression should stay in
355                                 ///memory.
356   Materializer::PersistentVariableDelegate
357       *m_result_delegate; ///< If non-NULL, used to report expression results to
358                           ///ClangUserExpression.
359 
360   //----------------------------------------------------------------------
361   /// The following values should not live beyond parsing
362   //----------------------------------------------------------------------
363   class ParserVars {
364   public:
365     ParserVars(ClangExpressionDeclMap &decl_map) : m_decl_map(decl_map) {}
366 
367     Target *GetTarget() {
368       if (m_exe_ctx.GetTargetPtr())
369         return m_exe_ctx.GetTargetPtr();
370       else if (m_sym_ctx.target_sp)
371         m_sym_ctx.target_sp.get();
372       return NULL;
373     }
374 
375     ExecutionContext m_exe_ctx; ///< The execution context to use when parsing.
376     SymbolContext m_sym_ctx; ///< The symbol context to use in finding variables
377                              ///and types.
378     ClangPersistentVariables *m_persistent_vars =
379         nullptr; ///< The persistent variables for the process.
380     bool m_enable_lookups = false; ///< Set to true during parsing if we have
381                                    ///found the first "$__lldb" name.
382     TargetInfo m_target_info;      ///< Basic information about the target.
383     Materializer *m_materializer = nullptr;   ///< If non-NULL, the materializer
384                                               ///to use when reporting used
385                                               ///variables.
386     clang::ASTConsumer *m_code_gen = nullptr; ///< If non-NULL, a code generator
387                                               ///that receives new top-level
388                                               ///functions.
389   private:
390     ClangExpressionDeclMap &m_decl_map;
391     DISALLOW_COPY_AND_ASSIGN(ParserVars);
392   };
393 
394   std::unique_ptr<ParserVars> m_parser_vars;
395 
396   //----------------------------------------------------------------------
397   /// Activate parser-specific variables
398   //----------------------------------------------------------------------
399   void EnableParserVars() {
400     if (!m_parser_vars.get())
401       m_parser_vars.reset(new ParserVars(*this));
402   }
403 
404   //----------------------------------------------------------------------
405   /// Deallocate parser-specific variables
406   //----------------------------------------------------------------------
407   void DisableParserVars() { m_parser_vars.reset(); }
408 
409   //----------------------------------------------------------------------
410   /// The following values contain layout information for the materialized
411   /// struct, but are not specific to a single materialization
412   //----------------------------------------------------------------------
413   struct StructVars {
414     StructVars()
415         : m_struct_alignment(0), m_struct_size(0), m_struct_laid_out(false),
416           m_result_name(), m_object_pointer_type(NULL, NULL) {}
417 
418     lldb::offset_t
419         m_struct_alignment; ///< The alignment of the struct in bytes.
420     size_t m_struct_size;   ///< The size of the struct in bytes.
421     bool m_struct_laid_out; ///< True if the struct has been laid out and the
422                             ///layout is valid (that is, no new fields have been
423                             ///added since).
424     ConstString
425         m_result_name; ///< The name of the result variable ($1, for example)
426     TypeFromUser m_object_pointer_type; ///< The type of the "this" variable, if
427                                         ///one exists
428   };
429 
430   std::unique_ptr<StructVars> m_struct_vars;
431 
432   //----------------------------------------------------------------------
433   /// Activate struct variables
434   //----------------------------------------------------------------------
435   void EnableStructVars() {
436     if (!m_struct_vars.get())
437       m_struct_vars.reset(new struct StructVars);
438   }
439 
440   //----------------------------------------------------------------------
441   /// Deallocate struct variables
442   //----------------------------------------------------------------------
443   void DisableStructVars() { m_struct_vars.reset(); }
444 
445   //----------------------------------------------------------------------
446   /// Get this parser's ID for use in extracting parser- and JIT-specific
447   /// data from persistent variables.
448   //----------------------------------------------------------------------
449   uint64_t GetParserID() { return (uint64_t) this; }
450 
451   //------------------------------------------------------------------
452   /// Given a target, find a data symbol that has the given name.
453   ///
454   /// @param[in] target
455   ///     The target to use as the basis for the search.
456   ///
457   /// @param[in] name
458   ///     The name as a plain C string.
459   ///
460   /// @param[in] module
461   ///     The module to limit the search to. This can be NULL
462   ///
463   /// @return
464   ///     The LLDB Symbol found, or NULL if none was found.
465   //------------------------------------------------------------------
466   const Symbol *FindGlobalDataSymbol(Target &target, const ConstString &name,
467                                      Module *module = NULL);
468 
469   //------------------------------------------------------------------
470   /// Given a target, find a variable that matches the given name and
471   /// type.
472   ///
473   /// @param[in] target
474   ///     The target to use as a basis for finding the variable.
475   ///
476   /// @param[in] module
477   ///     If non-NULL, the module to search.
478   ///
479   /// @param[in] name
480   ///     The name as a plain C string.
481   ///
482   /// @param[in] namespace_decl
483   ///     If non-NULL and module is non-NULL, the parent namespace.
484   ///
485   /// @param[in] type
486   ///     The required type for the variable.  This function may be called
487   ///     during parsing, in which case we don't know its type; hence the
488   ///     default.
489   ///
490   /// @return
491   ///     The LLDB Variable found, or NULL if none was found.
492   //------------------------------------------------------------------
493   lldb::VariableSP FindGlobalVariable(Target &target, lldb::ModuleSP &module,
494                                       const ConstString &name,
495                                       CompilerDeclContext *namespace_decl,
496                                       TypeFromUser *type = NULL);
497 
498   //------------------------------------------------------------------
499   /// Get the value of a variable in a given execution context and return
500   /// the associated Types if needed.
501   ///
502   /// @param[in] var
503   ///     The variable to evaluate.
504   ///
505   /// @param[out] var_location
506   ///     The variable location value to fill in
507   ///
508   /// @param[out] found_type
509   ///     The type of the found value, as it was found in the user process.
510   ///     This is only useful when the variable is being inspected on behalf
511   ///     of the parser, hence the default.
512   ///
513   /// @param[out] parser_type
514   ///     The type of the found value, as it was copied into the parser's
515   ///     AST context.  This is only useful when the variable is being
516   ///     inspected on behalf of the parser, hence the default.
517   ///
518   /// @param[in] decl
519   ///     The Decl to be looked up.
520   ///
521   /// @return
522   ///     Return true if the value was successfully filled in.
523   //------------------------------------------------------------------
524   bool GetVariableValue(lldb::VariableSP &var,
525                         lldb_private::Value &var_location,
526                         TypeFromUser *found_type = NULL,
527                         TypeFromParser *parser_type = NULL);
528 
529   //------------------------------------------------------------------
530   /// Use the NameSearchContext to generate a Decl for the given LLDB
531   /// Variable, and put it in the Tuple list.
532   ///
533   /// @param[in] context
534   ///     The NameSearchContext to use when constructing the Decl.
535   ///
536   /// @param[in] var
537   ///     The LLDB Variable that needs a Decl.
538   ///
539   /// @param[in] valobj
540   ///     The LLDB ValueObject for that variable.
541   //------------------------------------------------------------------
542   void AddOneVariable(NameSearchContext &context, lldb::VariableSP var,
543                       lldb::ValueObjectSP valobj, unsigned int current_id);
544 
545   //------------------------------------------------------------------
546   /// Use the NameSearchContext to generate a Decl for the given
547   /// persistent variable, and put it in the list of found entities.
548   ///
549   /// @param[in] context
550   ///     The NameSearchContext to use when constructing the Decl.
551   ///
552   /// @param[in] pvar
553   ///     The persistent variable that needs a Decl.
554   ///
555   /// @param[in] current_id
556   ///     The ID of the current invocation of FindExternalVisibleDecls
557   ///     for logging purposes.
558   //------------------------------------------------------------------
559   void AddOneVariable(NameSearchContext &context,
560                       lldb::ExpressionVariableSP &pvar_sp,
561                       unsigned int current_id);
562 
563   //------------------------------------------------------------------
564   /// Use the NameSearchContext to generate a Decl for the given LLDB
565   /// symbol (treated as a variable), and put it in the list of found
566   /// entities.
567   ///
568   /// @param[in] context
569   ///     The NameSearchContext to use when constructing the Decl.
570   ///
571   /// @param[in] var
572   ///     The LLDB Variable that needs a Decl.
573   //------------------------------------------------------------------
574   void AddOneGenericVariable(NameSearchContext &context, const Symbol &symbol,
575                              unsigned int current_id);
576 
577   //------------------------------------------------------------------
578   /// Use the NameSearchContext to generate a Decl for the given
579   /// function.  (Functions are not placed in the Tuple list.)  Can
580   /// handle both fully typed functions and generic functions.
581   ///
582   /// @param[in] context
583   ///     The NameSearchContext to use when constructing the Decl.
584   ///
585   /// @param[in] fun
586   ///     The Function that needs to be created.  If non-NULL, this is
587   ///     a fully-typed function.
588   ///
589   /// @param[in] sym
590   ///     The Symbol that corresponds to a function that needs to be
591   ///     created with generic type (unitptr_t foo(...)).
592   //------------------------------------------------------------------
593   void AddOneFunction(NameSearchContext &context, Function *fun, Symbol *sym,
594                       unsigned int current_id);
595 
596   //------------------------------------------------------------------
597   /// Use the NameSearchContext to generate a Decl for the given
598   /// register.
599   ///
600   /// @param[in] context
601   ///     The NameSearchContext to use when constructing the Decl.
602   ///
603   /// @param[in] reg_info
604   ///     The information corresponding to that register.
605   //------------------------------------------------------------------
606   void AddOneRegister(NameSearchContext &context, const RegisterInfo *reg_info,
607                       unsigned int current_id);
608 
609   //------------------------------------------------------------------
610   /// Use the NameSearchContext to generate a Decl for the given
611   /// type.  (Types are not placed in the Tuple list.)
612   ///
613   /// @param[in] context
614   ///     The NameSearchContext to use when constructing the Decl.
615   ///
616   /// @param[in] type
617   ///     The type that needs to be created.
618   //------------------------------------------------------------------
619   void AddOneType(NameSearchContext &context, TypeFromUser &type,
620                   unsigned int current_id);
621 
622   //------------------------------------------------------------------
623   /// Generate a Decl for "*this" and add a member function declaration
624   /// to it for the expression, then report it.
625   ///
626   /// @param[in] context
627   ///     The NameSearchContext to use when constructing the Decl.
628   ///
629   /// @param[in] type
630   ///     The type for *this.
631   //------------------------------------------------------------------
632   void AddThisType(NameSearchContext &context, TypeFromUser &type,
633                    unsigned int current_id);
634 
635   ClangASTContext *GetClangASTContext();
636 };
637 
638 } // namespace lldb_private
639 
640 #endif // liblldb_ClangExpressionDeclMap_h_
641