FunctionCaller.h revision 296417
1//===-- FunctionCaller.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_FunctionCaller_h_
11#define liblldb_FunctionCaller_h_
12
13// C Includes
14// C++ Includes
15#include <list>
16#include <memory>
17#include <string>
18#include <vector>
19
20// Other libraries and framework includes
21// Project includes
22#include "lldb/Core/Address.h"
23#include "lldb/Core/Value.h"
24#include "lldb/Expression/Expression.h"
25#include "lldb/Expression/ExpressionParser.h"
26#include "lldb/Symbol/CompilerType.h"
27
28namespace lldb_private
29{
30
31//----------------------------------------------------------------------
32/// @class FunctionCaller FunctionCaller.h "lldb/Expression/FunctionCaller.h"
33/// @brief Encapsulates a function that can be called.
34///
35/// A given FunctionCaller object can handle a single function signature.
36/// Once constructed, it can set up any number of concurrent calls to
37/// functions with that signature.
38///
39/// It performs the call by synthesizing a structure that contains the pointer
40/// to the function and the arguments that should be passed to that function,
41/// and producing a special-purpose JIT-compiled function that accepts a void*
42/// pointing to this struct as its only argument and calls the function in the
43/// struct with the written arguments.  This method lets Clang handle the
44/// vagaries of function calling conventions.
45///
46/// The simplest use of the FunctionCaller is to construct it with a
47/// function representative of the signature you want to use, then call
48/// ExecuteFunction(ExecutionContext &, Stream &, Value &).
49///
50/// If you need to reuse the arguments for several calls, you can call
51/// InsertFunction() followed by WriteFunctionArguments(), which will return
52/// the location of the args struct for the wrapper function in args_addr_ref.
53///
54/// If you need to call the function on the thread plan stack, you can also
55/// call InsertFunction() followed by GetThreadPlanToCallFunction().
56///
57/// Any of the methods that take arg_addr_ptr or arg_addr_ref can be passed
58/// a pointer set to LLDB_INVALID_ADDRESS and new structure will be allocated
59/// and its address returned in that variable.
60///
61/// Any of the methods that take arg_addr_ptr can be passed nullptr, and the
62/// argument space will be managed for you.
63//----------------------------------------------------------------------
64class FunctionCaller : public Expression
65{
66public:
67    //------------------------------------------------------------------
68    /// Constructor
69    ///
70    /// @param[in] exe_scope
71    ///     An execution context scope that gets us at least a target and
72    ///     process.
73    ///
74    /// @param[in] ast_context
75    ///     The AST context to evaluate argument types in.
76    ///
77    /// @param[in] return_qualtype
78    ///     An opaque Clang QualType for the function result.  Should be
79    ///     defined in ast_context.
80    ///
81    /// @param[in] function_address
82    ///     The address of the function to call.
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    FunctionCaller (ExecutionContextScope &exe_scope,
89                   const CompilerType &return_type,
90                   const Address& function_address,
91                   const ValueList &arg_value_list,
92                   const char *name);
93
94    //------------------------------------------------------------------
95    /// Destructor
96    //------------------------------------------------------------------
97    ~FunctionCaller() override;
98
99    //------------------------------------------------------------------
100    /// Compile the wrapper function
101    ///
102    /// @param[in] errors
103    ///     The stream to print parser errors to.
104    ///
105    /// @return
106    ///     The number of errors.
107    //------------------------------------------------------------------
108    virtual unsigned
109    CompileFunction (Stream &errors) = 0;
110
111    //------------------------------------------------------------------
112    /// Insert the default function wrapper and its default argument struct
113    ///
114    /// @param[in] exe_ctx
115    ///     The execution context to insert the function and its arguments
116    ///     into.
117    ///
118    /// @param[in,out] args_addr_ref
119    ///     The address of the structure to write the arguments into.  May
120    ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
121    ///     and args_addr_ref is pointed to it.
122    ///
123    /// @param[in] errors
124    ///     The stream to write errors to.
125    ///
126    /// @return
127    ///     True on success; false otherwise.
128    //------------------------------------------------------------------
129    bool
130    InsertFunction (ExecutionContext &exe_ctx,
131                    lldb::addr_t &args_addr_ref,
132                    Stream &errors);
133
134    //------------------------------------------------------------------
135    /// Insert the default function wrapper (using the JIT)
136    ///
137    /// @param[in] exe_ctx
138    ///     The execution context to insert the function and its arguments
139    ///     into.
140    ///
141    /// @param[in] errors
142    ///     The stream to write errors to.
143    ///
144    /// @return
145    ///     True on success; false otherwise.
146    //------------------------------------------------------------------
147    bool WriteFunctionWrapper (ExecutionContext &exe_ctx,
148                               Stream &errors);
149
150    //------------------------------------------------------------------
151    /// Insert the default function argument struct
152    ///
153    /// @param[in] exe_ctx
154    ///     The execution context to insert the function and its arguments
155    ///     into.
156    ///
157    /// @param[in,out] args_addr_ref
158    ///     The address of the structure to write the arguments into.  May
159    ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
160    ///     and args_addr_ref is pointed to it.
161    ///
162    /// @param[in] errors
163    ///     The stream to write errors to.
164    ///
165    /// @return
166    ///     True on success; false otherwise.
167    //------------------------------------------------------------------
168    bool WriteFunctionArguments (ExecutionContext &exe_ctx,
169                                 lldb::addr_t &args_addr_ref,
170                                 Stream &errors);
171
172    //------------------------------------------------------------------
173    /// Insert an argument struct with a non-default function address and
174    /// non-default argument values
175    ///
176    /// @param[in] exe_ctx
177    ///     The execution context to insert the function and its arguments
178    ///     into.
179    ///
180    /// @param[in,out] args_addr_ref
181    ///     The address of the structure to write the arguments into.  May
182    ///     be LLDB_INVALID_ADDRESS; if it is, a new structure is allocated
183    ///     and args_addr_ref is pointed at it.
184    ///
185    /// @param[in] arg_values
186    ///     The values of the function's arguments.
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                                 ValueList &arg_values,
197                                 Stream &errors);
198
199    //------------------------------------------------------------------
200    /// Run the function this FunctionCaller was created with.
201    ///
202    /// This is the full version.
203    ///
204    /// @param[in] exe_ctx
205    ///     The thread & process in which this function will run.
206    ///
207    /// @param[in] args_addr_ptr
208    ///     If nullptr, the function will take care of allocating & deallocating the wrapper
209    ///     args structure.  Otherwise, if set to LLDB_INVALID_ADDRESS, a new structure
210    ///     will be allocated, filled and the address returned to you.  You are responsible
211    ///     for deallocating it.  And if passed in with a value other than LLDB_INVALID_ADDRESS,
212    ///     this should point to an already allocated structure with the values already written.
213    ///
214    /// @param[in] errors
215    ///     Errors will be written here if there are any.
216    ///
217    /// @param[in] options
218    ///     The options for this expression execution.
219    ///
220    /// @param[out] results
221    ///     The result value will be put here after running the function.
222    ///
223    /// @return
224    ///     Returns one of the ExpressionResults enum indicating function call status.
225    //------------------------------------------------------------------
226    lldb::ExpressionResults
227    ExecuteFunction(ExecutionContext &exe_ctx,
228                    lldb::addr_t *args_addr_ptr,
229                    const EvaluateExpressionOptions &options,
230                    Stream &errors,
231                    Value &results);
232
233    //------------------------------------------------------------------
234    /// Get a thread plan to run the function this FunctionCaller was created with.
235    ///
236    /// @param[in] exe_ctx
237    ///     The execution context to insert the function and its arguments
238    ///     into.
239    ///
240    /// @param[in] func_addr
241    ///     The address of the function in the target process.
242    ///
243    /// @param[in] args_addr
244    ///     The address of the argument struct.
245    ///
246    /// @param[in] errors
247    ///     The stream to write errors to.
248    ///
249    /// @param[in] stop_others
250    ///     True if other threads should pause during execution.
251    ///
252    /// @param[in] unwind_on_error
253    ///     True if the thread plan may simply be discarded if an error occurs.
254    ///
255    /// @return
256    ///     A ThreadPlan shared pointer for executing the function.
257    //------------------------------------------------------------------
258    lldb::ThreadPlanSP
259    GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
260                                 lldb::addr_t args_addr,
261                                 const EvaluateExpressionOptions &options,
262                                 Stream &errors);
263
264    //------------------------------------------------------------------
265    /// Get the result of the function from its struct
266    ///
267    /// @param[in] exe_ctx
268    ///     The execution context to retrieve the result from.
269    ///
270    /// @param[in] args_addr
271    ///     The address of the argument struct.
272    ///
273    /// @param[out] ret_value
274    ///     The value returned by the function.
275    ///
276    /// @return
277    ///     True on success; false otherwise.
278    //------------------------------------------------------------------
279    bool FetchFunctionResults (ExecutionContext &exe_ctx,
280                               lldb::addr_t args_addr,
281                               Value &ret_value);
282
283    //------------------------------------------------------------------
284    /// Deallocate the arguments structure
285    ///
286    /// @param[in] exe_ctx
287    ///     The execution context to insert the function and its arguments
288    ///     into.
289    ///
290    /// @param[in] args_addr
291    ///     The address of the argument struct.
292    //------------------------------------------------------------------
293    void DeallocateFunctionResults (ExecutionContext &exe_ctx,
294                                    lldb::addr_t args_addr);
295
296    //------------------------------------------------------------------
297    /// Interface for ClangExpression
298    //------------------------------------------------------------------
299
300    //------------------------------------------------------------------
301    /// Return the string that the parser should parse.  Must be a full
302    /// translation unit.
303    //------------------------------------------------------------------
304    const char *
305    Text() override
306    {
307        return m_wrapper_function_text.c_str();
308    }
309
310    //------------------------------------------------------------------
311    /// Return the function name that should be used for executing the
312    /// expression.  Text() should contain the definition of this
313    /// function.
314    //------------------------------------------------------------------
315    const char *
316    FunctionName() override
317    {
318        return m_wrapper_function_name.c_str();
319    }
320
321    //------------------------------------------------------------------
322    /// Return the object that the parser should use when registering
323    /// local variables. May be nullptr if the Expression doesn't care.
324    //------------------------------------------------------------------
325    ExpressionVariableList *
326    LocalVariables ()
327    {
328        return nullptr;
329    }
330
331    //------------------------------------------------------------------
332    /// Return true if validation code should be inserted into the
333    /// expression.
334    //------------------------------------------------------------------
335    bool
336    NeedsValidation() override
337    {
338        return false;
339    }
340
341    //------------------------------------------------------------------
342    /// Return true if external variables in the expression should be
343    /// resolved.
344    //------------------------------------------------------------------
345    bool
346    NeedsVariableResolution() override
347    {
348        return false;
349    }
350
351    ValueList
352    GetArgumentValues () const
353    {
354        return m_arg_values;
355    }
356
357protected:
358    // Note: the parser needs to be destructed before the execution unit, so
359    // declare the execution unit first.
360    std::shared_ptr<IRExecutionUnit> m_execution_unit_sp;
361    std::unique_ptr<ExpressionParser> m_parser;                     ///< The parser responsible for compiling the function.
362                                                                    ///< This will get made in CompileFunction, so it is
363                                                                    ///< safe to access it after that.
364
365    lldb::ModuleWP                  m_jit_module_wp;
366    std::string                     m_name;                         ///< The name of this clang function - for debugging purposes.
367
368    Function                       *m_function_ptr;                 ///< The function we're going to call. May be nullptr if we don't have debug info for the function.
369    Address                         m_function_addr;                ///< If we don't have the FunctionSP, we at least need the address & return type.
370    CompilerType                    m_function_return_type;         ///< The opaque clang qual type for the function return type.
371
372    std::string                     m_wrapper_function_name;        ///< The name of the wrapper function.
373    std::string                     m_wrapper_function_text;        ///< The contents of the wrapper function.
374    std::string                     m_wrapper_struct_name;          ///< The name of the struct that contains the target function address, arguments, and result.
375    std::list<lldb::addr_t>         m_wrapper_args_addrs;           ///< The addresses of the arguments to the wrapper function.
376
377    bool                            m_struct_valid;                 ///< True if the ASTStructExtractor has populated the variables below.
378
379    //------------------------------------------------------------------
380    /// These values are populated by the ASTStructExtractor
381    size_t                          m_struct_size;                  ///< The size of the argument struct, in bytes.
382    std::vector<uint64_t>           m_member_offsets;               ///< The offset of each member in the struct, in bytes.
383    uint64_t                        m_return_size;                  ///< The size of the result variable, in bytes.
384    uint64_t                        m_return_offset;                ///< The offset of the result variable in the struct, in bytes.
385    //------------------------------------------------------------------
386
387    ValueList                       m_arg_values;                   ///< The default values of the arguments.
388
389    bool                            m_compiled;                     ///< True if the wrapper function has already been parsed.
390    bool                            m_JITted;                       ///< True if the wrapper function has already been JIT-compiled.
391};
392
393} // namespace lldb_private
394
395#endif // liblldb_FunctionCaller_h_
396