LLDB  mainline
ClangFunctionCaller.cpp
Go to the documentation of this file.
1 //===-- ClangFunctionCaller.cpp ---------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ClangFunctionCaller.h"
10 
11 #include "ASTStructExtractor.h"
12 #include "ClangExpressionParser.h"
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/RecordLayout.h"
16 #include "clang/CodeGen/CodeGenAction.h"
17 #include "clang/CodeGen/ModuleBuilder.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/ExecutionEngine.h"
22 #include "llvm/IR/Module.h"
23 
24 #include "lldb/Core/Module.h"
25 #include "lldb/Core/ValueObject.h"
30 #include "lldb/Symbol/Function.h"
31 #include "lldb/Symbol/Type.h"
33 #include "lldb/Target/Process.h"
35 #include "lldb/Target/Target.h"
36 #include "lldb/Target/Thread.h"
37 #include "lldb/Target/ThreadPlan.h"
40 #include "lldb/Utility/Log.h"
41 #include "lldb/Utility/State.h"
42 
43 using namespace lldb_private;
44 
45 // ClangFunctionCaller constructor
47  const CompilerType &return_type,
48  const Address &functionAddress,
49  const ValueList &arg_value_list,
50  const char *name)
51  : FunctionCaller(exe_scope, return_type, functionAddress, arg_value_list,
52  name),
53  m_type_system_helper(*this) {
54  m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
55  // Can't make a ClangFunctionCaller without a process.
56  assert(m_jit_process_wp.lock());
57 }
58 
59 // Destructor
61 
62 unsigned
63 
64 ClangFunctionCaller::CompileFunction(lldb::ThreadSP thread_to_use_sp,
65  DiagnosticManager &diagnostic_manager) {
66  if (m_compiled)
67  return 0;
68 
69  // Compilation might call code, make sure to keep on the thread the caller
70  // indicated.
71  ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
72  thread_to_use_sp);
73 
74  // FIXME: How does clang tell us there's no return value? We need to handle
75  // that case.
76  unsigned num_errors = 0;
77 
78  std::string return_type_str(
80 
81  // Cons up the function we're going to wrap our call in, then compile it...
82  // We declare the function "extern "C"" because the compiler might be in C++
83  // mode which would mangle the name and then we couldn't find it again...
85  m_wrapper_function_text.append("extern \"C\" void ");
87  m_wrapper_function_text.append(" (void *input)\n{\n struct ");
89  m_wrapper_function_text.append(" \n {\n");
90  m_wrapper_function_text.append(" ");
91  m_wrapper_function_text.append(return_type_str);
92  m_wrapper_function_text.append(" (*fn_ptr) (");
93 
94  // Get the number of arguments. If we have a function type and it is
95  // prototyped, trust that, otherwise use the values we were given.
96 
97  // FIXME: This will need to be extended to handle Variadic functions. We'll
98  // need
99  // to pull the defined arguments out of the function, then add the types from
100  // the arguments list for the variable arguments.
101 
102  uint32_t num_args = UINT32_MAX;
103  bool trust_function = false;
104  // GetArgumentCount returns -1 for an unprototyped function.
105  CompilerType function_clang_type;
106  if (m_function_ptr) {
107  function_clang_type = m_function_ptr->GetCompilerType();
108  if (function_clang_type) {
109  int num_func_args = function_clang_type.GetFunctionArgumentCount();
110  if (num_func_args >= 0) {
111  trust_function = true;
112  num_args = num_func_args;
113  }
114  }
115  }
116 
117  if (num_args == UINT32_MAX)
118  num_args = m_arg_values.GetSize();
119 
120  std::string args_buffer; // This one stores the definition of all the args in
121  // "struct caller".
122  std::string args_list_buffer; // This one stores the argument list called from
123  // the structure.
124  for (size_t i = 0; i < num_args; i++) {
125  std::string type_name;
126 
127  if (trust_function) {
128  type_name = function_clang_type.GetFunctionArgumentTypeAtIndex(i)
129  .GetTypeName()
130  .AsCString("");
131  } else {
132  CompilerType clang_qual_type =
134  if (clang_qual_type) {
135  type_name = clang_qual_type.GetTypeName().AsCString("");
136  } else {
137  diagnostic_manager.Printf(
139  "Could not determine type of input value %" PRIu64 ".",
140  (uint64_t)i);
141  return 1;
142  }
143  }
144 
145  m_wrapper_function_text.append(type_name);
146  if (i < num_args - 1)
147  m_wrapper_function_text.append(", ");
148 
149  char arg_buf[32];
150  args_buffer.append(" ");
151  args_buffer.append(type_name);
152  snprintf(arg_buf, 31, "arg_%" PRIu64, (uint64_t)i);
153  args_buffer.push_back(' ');
154  args_buffer.append(arg_buf);
155  args_buffer.append(";\n");
156 
157  args_list_buffer.append("__lldb_fn_data->");
158  args_list_buffer.append(arg_buf);
159  if (i < num_args - 1)
160  args_list_buffer.append(", ");
161  }
163  ");\n"); // Close off the function calling prototype.
164 
165  m_wrapper_function_text.append(args_buffer);
166 
167  m_wrapper_function_text.append(" ");
168  m_wrapper_function_text.append(return_type_str);
169  m_wrapper_function_text.append(" return_value;");
170  m_wrapper_function_text.append("\n };\n struct ");
172  m_wrapper_function_text.append("* __lldb_fn_data = (struct ");
174  m_wrapper_function_text.append(" *) input;\n");
175 
177  " __lldb_fn_data->return_value = __lldb_fn_data->fn_ptr (");
178  m_wrapper_function_text.append(args_list_buffer);
179  m_wrapper_function_text.append(");\n}\n");
180 
182  if (log)
183  log->Printf("Expression: \n\n%s\n\n", m_wrapper_function_text.c_str());
184 
185  // Okay, now compile this expression
186 
187  lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
188  if (jit_process_sp) {
189  const bool generate_debug_info = true;
190  m_parser.reset(new ClangExpressionParser(jit_process_sp.get(), *this,
191  generate_debug_info));
192 
193  num_errors = m_parser->Parse(diagnostic_manager);
194  } else {
195  diagnostic_manager.PutString(eDiagnosticSeverityError,
196  "no process - unable to inject function");
197  num_errors = 1;
198  }
199 
200  m_compiled = (num_errors == 0);
201 
202  if (!m_compiled)
203  return num_errors;
204 
205  return num_errors;
206 }
207 
208 clang::ASTConsumer *
209 ClangFunctionCaller::ClangFunctionCallerHelper::ASTTransformer(
210  clang::ASTConsumer *passthrough) {
211  m_struct_extractor.reset(new ASTStructExtractor(
212  passthrough, m_owner.GetWrapperStructName(), m_owner));
213 
214  return m_struct_extractor.get();
215 }
std::string m_wrapper_function_text
The contents of the wrapper function.
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:224
std::unique_ptr< ExpressionParser > m_parser
The parser responsible for compiling the function.
bool m_compiled
True if the wrapper function has already been parsed.
virtual lldb::ProcessSP CalculateProcess()=0
Value * GetValueAtIndex(size_t idx)
Definition: Value.cpp:701
#define UINT32_MAX
Definition: lldb-defines.h:31
CompilerType GetFunctionArgumentTypeAtIndex(size_t idx) const
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
unsigned CompileFunction(lldb::ThreadSP thread_to_use_sp, DiagnosticManager &diagnostic_manager) override
Compile the wrapper function.
Encapsulates a function that can be called.
size_t Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
std::string m_wrapper_function_name
The name of the wrapper function.
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
size_t size_t PutString(DiagnosticSeverity severity, llvm::StringRef str)
lldb::ProcessWP m_jit_process_wp
Expression&#39;s always have to have a target...
Definition: Expression.h:101
const CompilerType & GetCompilerType()
Definition: Value.cpp:239
A section + offset based address class.
Definition: Address.h:80
Function * m_function_ptr
The function we&#39;re going to call.
std::string m_wrapper_struct_name
The name of the struct that contains the target function address, arguments, and result.
CompilerType GetCompilerType()
Definition: Function.cpp:469
int GetFunctionArgumentCount() const
"lldb/Expression/ClangExpressionParser.h" Encapsulates an instance of Clang that can parse expression...
#define LIBLLDB_LOG_EXPRESSIONS
Definition: Logging.h:22
ClangFunctionCaller(ExecutionContextScope &exe_scope, const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, const char *name)
Constructor.
ValueList m_arg_values
The default values of the arguments.
ConstString GetTypeName() const
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
CompilerType m_function_return_type
The opaque clang qual type for the function return type.