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