1 //===-- ClangFunction.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 lldb_ClangFunction_h_
11 #define lldb_ClangFunction_h_
12 
13 // C Includes
14 // C++ Includes
15 #include <vector>
16 #include <list>
17 // Other libraries and framework includes
18 // Project includes
19 #include "lldb/Core/ClangForward.h"
20 #include "lldb/Core/Address.h"
21 #include "lldb/Core/ArchSpec.h"
22 #include "lldb/Core/Value.h"
23 #include "lldb/Core/ValueObjectList.h"
24 #include "lldb/Expression/ClangExpression.h"
25 #include "lldb/Target/Process.h"
26 
27 namespace lldb_private
28 {
29 
30 class ASTStructExtractor;
31 class ClangExpressionParser;
32 
33 //----------------------------------------------------------------------
34 /// @class ClangFunction ClangFunction.h "lldb/Expression/ClangFunction.h"
35 /// @brief Encapsulates a function that can be called.
36 ///
37 /// A given ClangFunction object can handle a single function signature.
38 /// Once constructed, it can set up any number of concurrent calls to
39 /// functions with that signature.
40 ///
41 /// It performs the call by synthesizing a structure that contains the pointer
42 /// to the function and the arguments that should be passed to that function,
43 /// and producing a special-purpose JIT-compiled function that accepts a void*
44 /// pointing to this struct as its only argument and calls the function in the
45 /// struct with the written arguments.  This method lets Clang handle the
46 /// vagaries of function calling conventions.
47 ///
48 /// The simplest use of the ClangFunction is to construct it with a
49 /// function representative of the signature you want to use, then call
50 /// ExecuteFunction(ExecutionContext &, Stream &, Value &).
51 ///
52 /// If you need to reuse the arguments for several calls, you can call
53 /// InsertFunction() followed by WriteFunctionArguments(), which will return
54 /// the location of the args struct for the wrapper function in args_addr_ref.
55 ///
56 /// If you need to call the function on the thread plan stack, you can also
57 /// call InsertFunction() followed by GetThreadPlanToCallFunction().
58 ///
59 /// Any of the methods that take arg_addr_ptr or arg_addr_ref can be passed
60 /// a pointer set to LLDB_INVALID_ADDRESS and new structure will be allocated
61 /// and its address returned in that variable.
62 ///
63 /// Any of the methods that take arg_addr_ptr can be passed NULL, and the
64 /// argument space will be managed for you.
65 //----------------------------------------------------------------------
66 class ClangFunction : public ClangExpression
67 {
68     friend class ASTStructExtractor;
69 public:
70 	//------------------------------------------------------------------
71 	/// Constructor
72     ///
73     /// @param[in] exe_scope
74     ///     An execution context scope that gets us at least a target and
75     ///     process.
76     ///
77     /// @param[in] function_ptr
78     ///     The default function to be called.  Can be overridden using
79     ///     WriteFunctionArguments().
80     ///
81     /// @param[in] ast_context
82     ///     The AST context to evaluate argument types in.
83     ///
84     /// @param[in] arg_value_list
85     ///     The default values to use when calling this function.  Can
86     ///     be overridden using WriteFunctionArguments().
87 	//------------------------------------------------------------------
88 	ClangFunction (ExecutionContextScope &exe_scope,
89                    Function &function_ptr,
90                    ClangASTContext *ast_context,
91                    const ValueList &arg_value_list);
92 
93     //------------------------------------------------------------------
94 	/// Constructor
95     ///
96     /// @param[in] exe_scope
97     ///     An execution context scope that gets us at least a target and
98     ///     process.
99     ///
100     /// @param[in] ast_context
101     ///     The AST context to evaluate argument types in.
102     ///
103     /// @param[in] return_qualtype
104     ///     An opaque Clang QualType for the function result.  Should be
105     ///     defined in ast_context.
106     ///
107     /// @param[in] function_address
108     ///     The address of the function to call.
109     ///
110     /// @param[in] arg_value_list
111     ///     The default values to use when calling this function.  Can
112     ///     be overridden using WriteFunctionArguments().
113 	//------------------------------------------------------------------
114 	ClangFunction (ExecutionContextScope &exe_scope,
115                    const ClangASTType &return_type,
116                    const Address& function_address,
117                    const ValueList &arg_value_list);
118 
119     //------------------------------------------------------------------
120 	/// Destructor
121 	//------------------------------------------------------------------
122 	virtual
123     ~ClangFunction();
124 
125     //------------------------------------------------------------------
126 	/// Compile the wrapper function
127     ///
128     /// @param[in] errors
129     ///     The stream to print parser errors to.
130     ///
131     /// @return
132     ///     The number of errors.
133 	//------------------------------------------------------------------
134     unsigned
135     CompileFunction (Stream &errors);
136 
137     //------------------------------------------------------------------
138 	/// Insert the default function wrapper and its default argument struct
139     ///
140     /// @param[in] exe_ctx
141     ///     The execution context to insert the function and its arguments
142     ///     into.
143     ///
144     /// @param[in,out] args_addr_ref
145     ///     The address of the structure to write the arguments into.  May
146     ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
147     ///     and args_addr_ref is pointed to it.
148     ///
149     /// @param[in] errors
150     ///     The stream to write errors to.
151     ///
152     /// @return
153     ///     True on success; false otherwise.
154 	//------------------------------------------------------------------
155     bool
156     InsertFunction (ExecutionContext &exe_ctx,
157                     lldb::addr_t &args_addr_ref,
158                     Stream &errors);
159 
160     //------------------------------------------------------------------
161 	/// Insert the default function wrapper (using the JIT)
162     ///
163     /// @param[in] exe_ctx
164     ///     The execution context to insert the function and its arguments
165     ///     into.
166     ///
167     /// @param[in] errors
168     ///     The stream to write errors to.
169     ///
170     /// @return
171     ///     True on success; false otherwise.
172 	//------------------------------------------------------------------
173     bool WriteFunctionWrapper (ExecutionContext &exe_ctx,
174                                Stream &errors);
175 
176     //------------------------------------------------------------------
177 	/// Insert the default function argument struct
178     ///
179     /// @param[in] exe_ctx
180     ///     The execution context to insert the function and its arguments
181     ///     into.
182     ///
183     /// @param[in,out] args_addr_ref
184     ///     The address of the structure to write the arguments into.  May
185     ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
186     ///     and args_addr_ref is pointed to it.
187     ///
188     /// @param[in] errors
189     ///     The stream to write errors to.
190     ///
191     /// @return
192     ///     True on success; false otherwise.
193 	//------------------------------------------------------------------
194     bool WriteFunctionArguments (ExecutionContext &exe_ctx,
195                                  lldb::addr_t &args_addr_ref,
196                                  Stream &errors);
197 
198     //------------------------------------------------------------------
199 	/// Insert an argument struct with a non-default function address and
200     /// non-default argument values
201     ///
202     /// @param[in] exe_ctx
203     ///     The execution context to insert the function and its arguments
204     ///     into.
205     ///
206     /// @param[in,out] args_addr_ref
207     ///     The address of the structure to write the arguments into.  May
208     ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
209     ///     and args_addr_ref is pointed to it.
210     ///
211     /// @param[in] function_address
212     ///     The address of the function to call.
213     ///
214     /// @param[in] arg_values
215     ///     The values of the function's arguments.
216     ///
217     /// @param[in] errors
218     ///     The stream to write errors to.
219     ///
220     /// @return
221     ///     True on success; false otherwise.
222 	//------------------------------------------------------------------
223     bool WriteFunctionArguments (ExecutionContext &exe_ctx,
224                                  lldb::addr_t &args_addr_ref,
225                                  Address function_address,
226                                  ValueList &arg_values,
227                                  Stream &errors);
228 
229     //------------------------------------------------------------------
230 	/// [Static] Execute a function, passing it a single void* parameter.
231     /// ClangFunction uses this to call the wrapper function.
232     ///
233     /// @param[in] exe_ctx
234     ///     The execution context to insert the function and its arguments
235     ///     into.
236     ///
237     /// @param[in] function_address
238     ///     The address of the function in the target process.
239     ///
240     /// @param[in] void_arg
241     ///     The value of the void* parameter.
242     ///
243     /// @param[in] stop_others
244     ///     True if other threads should pause during execution.
245     ///
246     /// @param[in] try_all_threads
247     ///     If the timeout expires, true if other threads should run.  If
248     ///     the function may try to take locks, this is useful.
249     ///
250     /// @param[in] unwind_on_error
251     ///     If true, and the execution stops before completion, we unwind the
252     ///     function call, and return the program state to what it was before the
253     ///     execution.  If false, we leave the program in the stopped state.
254     ///
255     /// @param[in] timeout_usec
256     ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
257     ///     will try on one thread for the lesser of .25 sec and half the total timeout.
258     ///     then switch to running all threads, otherwise this will be the total timeout.
259     ///
260     /// @param[in] errors
261     ///     The stream to write errors to.
262     ///
263     /// @param[in] this_arg
264     ///     If non-NULL, the function is invoked like a C++ method, with the
265     ///     value pointed to by the pointer as its 'this' argument.
266     ///
267     /// @return
268     ///     Returns one of the ExecutionResults enum indicating function call status.
269 	//------------------------------------------------------------------
270     static ExecutionResults
271     ExecuteFunction (ExecutionContext &exe_ctx,
272                      lldb::addr_t function_address,
273                      lldb::addr_t &void_arg,
274                      bool stop_others,
275                      bool try_all_threads,
276                      bool unwind_on_error,
277                      bool ignore_breakpoints,
278                      uint32_t timeout_usec,
279                      Stream &errors,
280                      lldb::addr_t* this_arg = 0);
281 
282     //------------------------------------------------------------------
283     /// Run the function this ClangFunction was created with.
284     ///
285     /// This simple version will run the function stopping other threads
286     /// for a fixed timeout period (1000 usec) and if it does not complete,
287     /// we halt the process and try with all threads running.
288     ///
289     /// @param[in] exe_ctx
290     ///     The thread & process in which this function will run.
291     ///
292     /// @param[in] errors
293     ///     Errors will be written here if there are any.
294     ///
295     /// @param[out] results
296     ///     The result value will be put here after running the function.
297     ///
298     /// @return
299     ///     Returns one of the ExecutionResults enum indicating function call status.
300     //------------------------------------------------------------------
301     ExecutionResults
302     ExecuteFunction(ExecutionContext &exe_ctx,
303                      Stream &errors,
304                      Value &results);
305 
306     //------------------------------------------------------------------
307     /// Run the function this ClangFunction was created with.
308     ///
309     /// This simple version will run the function obeying the stop_others
310     /// argument.  There is no timeout.
311     ///
312     /// @param[in] exe_ctx
313     ///     The thread & process in which this function will run.
314     ///
315     /// @param[in] errors
316     ///     Errors will be written here if there are any.
317     ///
318     /// @param[in] stop_others
319     ///     If \b true, run only this thread, if \b false let all threads run.
320     ///
321     /// @param[out] results
322     ///     The result value will be put here after running the function.
323     ///
324     /// @return
325     ///     Returns one of the ExecutionResults enum indicating function call status.
326     //------------------------------------------------------------------
327     ExecutionResults
328     ExecuteFunction(ExecutionContext &exe_ctx,
329                      Stream &errors, bool stop_others,
330                      Value &results);
331 
332     //------------------------------------------------------------------
333     /// Run the function this ClangFunction was created with.
334     ///
335     /// This simple version will run the function on one thread.  If \a timeout_usec
336     /// is not zero, we time out after that timeout.  If \a try_all_threads is true, then we will
337     /// resume with all threads on, otherwise we halt the process, and eExecutionInterrupted will be returned.
338     ///
339     /// @param[in] exe_ctx
340     ///     The thread & process in which this function will run.
341     ///
342     /// @param[in] errors
343     ///     Errors will be written here if there are any.
344     ///
345     /// @param[in] timeout_usec
346     ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
347     ///     will try on one thread for the lesser of .25 sec and half the total timeout.
348     ///     then switch to running all threads, otherwise this will be the total timeout.
349     ///
350     /// @param[in] try_all_threads
351     ///     If \b true, run only this thread, if \b false let all threads run.
352     ///
353     /// @param[out] results
354     ///     The result value will be put here after running the function.
355     ///
356     /// @return
357     ///     Returns one of the ExecutionResults enum indicating function call status.
358     //------------------------------------------------------------------
359     ExecutionResults
360     ExecuteFunction(ExecutionContext &exe_ctx,
361                     Stream &errors,
362                     uint32_t single_thread_timeout_usec,
363                     bool try_all_threads,
364                     Value &results);
365 
366     //------------------------------------------------------------------
367     /// Run the function this ClangFunction was created with.
368     ///
369     /// This is the full version.
370     ///
371     /// @param[in] exe_ctx
372     ///     The thread & process in which this function will run.
373     ///
374     /// @param[in] args_addr_ptr
375     ///     If NULL, the function will take care of allocating & deallocating the wrapper
376     ///     args structure.  Otherwise, if set to LLDB_INVALID_ADDRESS, a new structure
377     ///     will be allocated, filled and the address returned to you.  You are responsible
378     ///     for deallocating it.  And if passed in with a value other than LLDB_INVALID_ADDRESS,
379     ///     this should point to an already allocated structure with the values already written.
380     ///
381     /// @param[in] errors
382     ///     Errors will be written here if there are any.
383     ///
384     /// @param[in] stop_others
385     ///     If \b true, run only this thread, if \b false let all threads run.
386     ///
387     /// @param[in] timeout_usec
388     ///     Timeout value (0 for no timeout). If try_all_threads is true, then we
389     ///     will try on one thread for the lesser of .25 sec and half the total timeout.
390     ///     then switch to running all threads, otherwise this will be the total timeout.
391     ///
392     ///
393     /// @param[in] try_all_threads
394     ///     If \b true, run only this thread, if \b false let all threads run.
395     ///
396     /// @param[out] results
397     ///     The result value will be put here after running the function.
398     ///
399     /// @return
400     ///     Returns one of the ExecutionResults enum indicating function call status.
401     //------------------------------------------------------------------
402     ExecutionResults
403     ExecuteFunction(ExecutionContext &exe_ctx,
404                     lldb::addr_t *args_addr_ptr,
405                     Stream &errors,
406                     bool stop_others,
407                     uint32_t timeout_usec,
408                     bool try_all_threads,
409                     bool unwind_on_error,
410                     bool ignore_breakpoints,
411                     Value &results);
412 
413     //------------------------------------------------------------------
414     /// [static] Get a thread plan to run a function.
415     ///
416     /// @param[in] exe_ctx
417     ///     The execution context to insert the function and its arguments
418     ///     into.
419     ///
420     /// @param[in] func_addr
421     ///     The address of the function in the target process.
422     ///
423     /// @param[in] args_addr_ref
424     ///     The value of the void* parameter.
425     ///
426     /// @param[in] errors
427     ///     The stream to write errors to.
428     ///
429     /// @param[in] stop_others
430     ///     True if other threads should pause during execution.
431     ///
432     /// @param[in] unwind_on_error
433     ///     True if the thread plan may simply be discarded if an error occurs.
434     ///
435     /// @param[in] ignore_breakpoints
436     ///     True if the expression execution will ignore breakpoint hits and continue executing.
437     ///
438     /// @param[in] this_arg
439     ///     If non-NULL (and cmd_arg is NULL), the function is invoked like a C++
440     ///     method, with the value pointed to by the pointer as its 'this'
441     ///     argument.
442     ///
443     /// @param[in] cmd_arg
444     ///     If non-NULL, the function is invoked like an Objective-C method, with
445     ///     this_arg in the 'self' slot and cmd_arg in the '_cmd' slot
446     ///
447     /// @return
448     ///     A ThreadPlan for executing the function.
449 	//------------------------------------------------------------------
450     static ThreadPlan *
451     GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
452                                  lldb::addr_t func_addr,
453                                  lldb::addr_t &args_addr_ref,
454                                  Stream &errors,
455                                  bool stop_others,
456                                  bool unwind_on_error,
457                                  bool ignore_breakpoints,
458                                  lldb::addr_t *this_arg = 0,
459                                  lldb::addr_t *cmd_arg = 0);
460 
461     //------------------------------------------------------------------
462     /// Get a thread plan to run the function this ClangFunction was created with.
463     ///
464     /// @param[in] exe_ctx
465     ///     The execution context to insert the function and its arguments
466     ///     into.
467     ///
468     /// @param[in] func_addr
469     ///     The address of the function in the target process.
470     ///
471     /// @param[in] args_addr_ref
472     ///     The value of the void* parameter.
473     ///
474     /// @param[in] errors
475     ///     The stream to write errors to.
476     ///
477     /// @param[in] stop_others
478     ///     True if other threads should pause during execution.
479     ///
480     /// @param[in] unwind_on_error
481     ///     True if the thread plan may simply be discarded if an error occurs.
482     ///
483     /// @return
484     ///     A ThreadPlan for executing the function.
485 	//------------------------------------------------------------------
486     ThreadPlan *
487     GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
488                                  lldb::addr_t &args_addr_ref,
489                                  Stream &errors,
490                                  bool stop_others,
491                                  bool unwind_on_error = true,
492                                  bool ignore_breakpoints = true)
493     {
494         return ClangFunction::GetThreadPlanToCallFunction (exe_ctx,
495                                                            m_jit_start_addr,
496                                                            args_addr_ref,
497                                                            errors,
498                                                            stop_others,
499                                                            unwind_on_error,
500                                                            ignore_breakpoints);
501     }
502 
503     //------------------------------------------------------------------
504     /// Get the result of the function from its struct
505     ///
506     /// @param[in] exe_ctx
507     ///     The execution context to retrieve the result from.
508     ///
509     /// @param[in] args_addr
510     ///     The address of the argument struct.
511     ///
512     /// @param[in] ret_value
513     ///     The value returned by the function.
514     ///
515     /// @return
516     ///     True on success; false otherwise.
517 	//------------------------------------------------------------------
518     bool FetchFunctionResults (ExecutionContext &exe_ctx,
519                                lldb::addr_t args_addr,
520                                Value &ret_value);
521 
522     //------------------------------------------------------------------
523     /// Deallocate the arguments structure
524     ///
525     /// @param[in] exe_ctx
526     ///     The execution context to insert the function and its arguments
527     ///     into.
528     ///
529     /// @param[in] args_addr
530     ///     The address of the argument struct.
531 	//------------------------------------------------------------------
532     void DeallocateFunctionResults (ExecutionContext &exe_ctx,
533                                     lldb::addr_t args_addr);
534 
535     //------------------------------------------------------------------
536     /// Interface for ClangExpression
537     //------------------------------------------------------------------
538 
539     //------------------------------------------------------------------
540     /// Return the string that the parser should parse.  Must be a full
541     /// translation unit.
542     //------------------------------------------------------------------
543     const char *
Text()544     Text ()
545     {
546         return m_wrapper_function_text.c_str();
547     }
548 
549     //------------------------------------------------------------------
550     /// Return the function name that should be used for executing the
551     /// expression.  Text() should contain the definition of this
552     /// function.
553     //------------------------------------------------------------------
554     const char *
FunctionName()555     FunctionName ()
556     {
557         return m_wrapper_function_name.c_str();
558     }
559 
560     //------------------------------------------------------------------
561     /// Return the object that the parser should use when resolving external
562     /// values.  May be NULL if everything should be self-contained.
563     //------------------------------------------------------------------
564     ClangExpressionDeclMap *
DeclMap()565     DeclMap ()
566     {
567         return NULL;
568     }
569 
570     //------------------------------------------------------------------
571     /// Return the object that the parser should use when registering
572     /// local variables.  May be NULL if the Expression doesn't care.
573     //------------------------------------------------------------------
574     ClangExpressionVariableList *
LocalVariables()575     LocalVariables ()
576     {
577         return NULL;
578     }
579 
580     //------------------------------------------------------------------
581     /// Return the object that the parser should allow to access ASTs.
582     /// May be NULL if the ASTs do not need to be transformed.
583     ///
584     /// @param[in] passthrough
585     ///     The ASTConsumer that the returned transformer should send
586     ///     the ASTs to after transformation.
587     //------------------------------------------------------------------
588     clang::ASTConsumer *
589     ASTTransformer (clang::ASTConsumer *passthrough);
590 
591     //------------------------------------------------------------------
592     /// Return true if validation code should be inserted into the
593     /// expression.
594     //------------------------------------------------------------------
595     bool
NeedsValidation()596     NeedsValidation ()
597     {
598         return false;
599     }
600 
601     //------------------------------------------------------------------
602     /// Return true if external variables in the expression should be
603     /// resolved.
604     //------------------------------------------------------------------
605     bool
NeedsVariableResolution()606     NeedsVariableResolution ()
607     {
608         return false;
609     }
610 
611     ValueList
GetArgumentValues()612     GetArgumentValues () const
613     {
614         return m_arg_values;
615     }
616 private:
617 	//------------------------------------------------------------------
618 	// For ClangFunction only
619 	//------------------------------------------------------------------
620 
621     std::unique_ptr<ClangExpressionParser> m_parser;                 ///< The parser responsible for compiling the function.
622     std::unique_ptr<IRExecutionUnit> m_execution_unit_ap;
623 
624     Function                       *m_function_ptr;                 ///< The function we're going to call.  May be NULL if we don't have debug info for the function.
625     Address                         m_function_addr;                ///< If we don't have the FunctionSP, we at least need the address & return type.
626     ClangASTType                    m_function_return_type;         ///< The opaque clang qual type for the function return type.
627     ClangASTContext                *m_clang_ast_context;            ///< This is the clang_ast_context that we're getting types from the and value, and the function return the function pointer is NULL.
628 
629     std::string                     m_wrapper_function_name;        ///< The name of the wrapper function.
630     std::string                     m_wrapper_function_text;        ///< The contents of the wrapper function.
631     std::string                     m_wrapper_struct_name;          ///< The name of the struct that contains the target function address, arguments, and result.
632     std::list<lldb::addr_t>         m_wrapper_args_addrs;           ///< The addresses of the arguments to the wrapper function.
633 
634     bool                            m_struct_valid;                 ///< True if the ASTStructExtractor has populated the variables below.
635 
636 	//------------------------------------------------------------------
637 	/// These values are populated by the ASTStructExtractor
638     size_t                          m_struct_size;                  ///< The size of the argument struct, in bytes.
639     std::vector<uint64_t>           m_member_offsets;               ///< The offset of each member in the struct, in bytes.
640     uint64_t                        m_return_size;                  ///< The size of the result variable, in bytes.
641     uint64_t                        m_return_offset;                ///< The offset of the result variable in the struct, in bytes.
642     //------------------------------------------------------------------
643 
644     ValueList                       m_arg_values;                   ///< The default values of the arguments.
645 
646     bool                            m_compiled;                     ///< True if the wrapper function has already been parsed.
647     bool                            m_JITted;                       ///< True if the wrapper function has already been JIT-compiled.
648 };
649 
650 } // Namespace lldb_private
651 
652 #endif  // lldb_ClangFunction_h_
653