Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/llvm-project/lldb/source/Expression/FunctionCaller.cpp
39587 views
1
//===-- FunctionCaller.cpp ------------------------------------------------===//
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
10
#include "lldb/Expression/FunctionCaller.h"
11
#include "lldb/Core/Module.h"
12
#include "lldb/Core/ValueObject.h"
13
#include "lldb/Core/ValueObjectList.h"
14
#include "lldb/Expression/DiagnosticManager.h"
15
#include "lldb/Expression/IRExecutionUnit.h"
16
#include "lldb/Interpreter/CommandReturnObject.h"
17
#include "lldb/Symbol/Function.h"
18
#include "lldb/Symbol/Type.h"
19
#include "lldb/Target/ExecutionContext.h"
20
#include "lldb/Target/Process.h"
21
#include "lldb/Target/RegisterContext.h"
22
#include "lldb/Target/Target.h"
23
#include "lldb/Target/Thread.h"
24
#include "lldb/Target/ThreadPlan.h"
25
#include "lldb/Target/ThreadPlanCallFunction.h"
26
#include "lldb/Utility/DataExtractor.h"
27
#include "lldb/Utility/LLDBLog.h"
28
#include "lldb/Utility/Log.h"
29
#include "lldb/Utility/State.h"
30
31
using namespace lldb_private;
32
33
char FunctionCaller::ID;
34
35
// FunctionCaller constructor
36
FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope,
37
const CompilerType &return_type,
38
const Address &functionAddress,
39
const ValueList &arg_value_list,
40
const char *name)
41
: Expression(exe_scope), m_execution_unit_sp(), m_parser(),
42
m_jit_module_wp(), m_name(name ? name : "<unknown>"),
43
m_function_ptr(nullptr), m_function_addr(functionAddress),
44
m_function_return_type(return_type),
45
m_wrapper_function_name("__lldb_caller_function"),
46
m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),
47
m_struct_valid(false), m_struct_size(0), m_return_size(0),
48
m_return_offset(0), m_arg_values(arg_value_list), m_compiled(false),
49
m_JITted(false) {
50
m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
51
// Can't make a FunctionCaller without a process.
52
assert(m_jit_process_wp.lock());
53
}
54
55
// Destructor
56
FunctionCaller::~FunctionCaller() {
57
lldb::ProcessSP process_sp(m_jit_process_wp.lock());
58
if (process_sp) {
59
lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
60
if (jit_module_sp)
61
process_sp->GetTarget().GetImages().Remove(jit_module_sp);
62
}
63
}
64
65
bool FunctionCaller::WriteFunctionWrapper(
66
ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {
67
Process *process = exe_ctx.GetProcessPtr();
68
69
if (!process) {
70
diagnostic_manager.Printf(lldb::eSeverityError, "no process.");
71
return false;
72
}
73
74
lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
75
76
if (process != jit_process_sp.get()) {
77
diagnostic_manager.Printf(lldb::eSeverityError,
78
"process does not match the stored process.");
79
return false;
80
}
81
82
if (process->GetState() != lldb::eStateStopped) {
83
diagnostic_manager.Printf(lldb::eSeverityError, "process is not stopped");
84
return false;
85
}
86
87
if (!m_compiled) {
88
diagnostic_manager.Printf(lldb::eSeverityError, "function not compiled");
89
return false;
90
}
91
92
if (m_JITted)
93
return true;
94
95
bool can_interpret = false; // should stay that way
96
97
Status jit_error(m_parser->PrepareForExecution(
98
m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
99
can_interpret, eExecutionPolicyAlways));
100
101
if (!jit_error.Success()) {
102
diagnostic_manager.Printf(lldb::eSeverityError,
103
"Error in PrepareForExecution: %s.",
104
jit_error.AsCString());
105
return false;
106
}
107
108
if (m_parser->GetGenerateDebugInfo()) {
109
lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
110
111
if (jit_module_sp) {
112
ConstString const_func_name(FunctionName());
113
FileSpec jit_file;
114
jit_file.SetFilename(const_func_name);
115
jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
116
m_jit_module_wp = jit_module_sp;
117
process->GetTarget().GetImages().Append(jit_module_sp,
118
true /* notify */);
119
}
120
}
121
if (process && m_jit_start_addr)
122
m_jit_process_wp = process->shared_from_this();
123
124
m_JITted = true;
125
126
return true;
127
}
128
129
bool FunctionCaller::WriteFunctionArguments(
130
ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
131
DiagnosticManager &diagnostic_manager) {
132
return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,
133
diagnostic_manager);
134
}
135
136
// FIXME: Assure that the ValueList we were passed in is consistent with the one
137
// that defined this function.
138
139
bool FunctionCaller::WriteFunctionArguments(
140
ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,
141
ValueList &arg_values, DiagnosticManager &diagnostic_manager) {
142
// All the information to reconstruct the struct is provided by the
143
// StructExtractor.
144
if (!m_struct_valid) {
145
diagnostic_manager.PutString(lldb::eSeverityError,
146
"Argument information was not correctly "
147
"parsed, so the function cannot be called.");
148
return false;
149
}
150
151
Status error;
152
lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
153
154
Process *process = exe_ctx.GetProcessPtr();
155
156
if (process == nullptr)
157
return return_value;
158
159
lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
160
161
if (process != jit_process_sp.get())
162
return false;
163
164
if (args_addr_ref == LLDB_INVALID_ADDRESS) {
165
args_addr_ref = process->AllocateMemory(
166
m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,
167
error);
168
if (args_addr_ref == LLDB_INVALID_ADDRESS)
169
return false;
170
m_wrapper_args_addrs.push_back(args_addr_ref);
171
} else {
172
// Make sure this is an address that we've already handed out.
173
if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
174
args_addr_ref) == m_wrapper_args_addrs.end()) {
175
return false;
176
}
177
}
178
179
// TODO: verify fun_addr needs to be a callable address
180
Scalar fun_addr(
181
m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
182
uint64_t first_offset = m_member_offsets[0];
183
process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,
184
process->GetAddressByteSize(), error);
185
186
// FIXME: We will need to extend this for Variadic functions.
187
188
Status value_error;
189
190
size_t num_args = arg_values.GetSize();
191
if (num_args != m_arg_values.GetSize()) {
192
diagnostic_manager.Printf(
193
lldb::eSeverityError,
194
"Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",
195
(uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
196
return false;
197
}
198
199
for (size_t i = 0; i < num_args; i++) {
200
// FIXME: We should sanity check sizes.
201
202
uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.
203
Value *arg_value = arg_values.GetValueAtIndex(i);
204
205
// FIXME: For now just do scalars:
206
207
// Special case: if it's a pointer, don't do anything (the ABI supports
208
// passing cstrings)
209
210
if (arg_value->GetValueType() == Value::ValueType::HostAddress &&
211
arg_value->GetContextType() == Value::ContextType::Invalid &&
212
arg_value->GetCompilerType().IsPointerType())
213
continue;
214
215
const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
216
217
if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,
218
arg_scalar.GetByteSize(), error))
219
return false;
220
}
221
222
return true;
223
}
224
225
bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx,
226
lldb::addr_t &args_addr_ref,
227
DiagnosticManager &diagnostic_manager) {
228
// Since we might need to call allocate memory and maybe call code to make
229
// the caller, we need to be stopped.
230
Process *process = exe_ctx.GetProcessPtr();
231
if (!process) {
232
diagnostic_manager.PutString(lldb::eSeverityError, "no process");
233
return false;
234
}
235
if (process->GetState() != lldb::eStateStopped) {
236
diagnostic_manager.PutString(lldb::eSeverityError, "process running");
237
return false;
238
}
239
if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
240
return false;
241
if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))
242
return false;
243
if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))
244
return false;
245
246
Log *log = GetLog(LLDBLog::Step);
247
LLDB_LOGF(log, "Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",
248
m_jit_start_addr, args_addr_ref);
249
250
return true;
251
}
252
253
lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction(
254
ExecutionContext &exe_ctx, lldb::addr_t args_addr,
255
const EvaluateExpressionOptions &options,
256
DiagnosticManager &diagnostic_manager) {
257
Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
258
259
LLDB_LOGF(log,
260
"-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "
261
"thread plan to call function \"%s\" --",
262
m_name.c_str());
263
264
// FIXME: Use the errors Stream for better error reporting.
265
Thread *thread = exe_ctx.GetThreadPtr();
266
if (thread == nullptr) {
267
diagnostic_manager.PutString(
268
lldb::eSeverityError, "Can't call a function without a valid thread.");
269
return nullptr;
270
}
271
272
// Okay, now run the function:
273
274
Address wrapper_address(m_jit_start_addr);
275
276
lldb::addr_t args = {args_addr};
277
278
lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction(
279
*thread, wrapper_address, CompilerType(), args, options));
280
new_plan_sp->SetIsControllingPlan(true);
281
new_plan_sp->SetOkayToDiscard(false);
282
return new_plan_sp;
283
}
284
285
bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx,
286
lldb::addr_t args_addr,
287
Value &ret_value) {
288
// Read the return value - it is the last field in the struct:
289
// FIXME: How does clang tell us there's no return value? We need to handle
290
// that case.
291
// FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and
292
// then use GetReturnValueObject
293
// to fetch the value. That way we can fetch any values we need.
294
295
Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
296
297
LLDB_LOGF(log,
298
"-- [FunctionCaller::FetchFunctionResults] Fetching function "
299
"results for \"%s\"--",
300
m_name.c_str());
301
302
Process *process = exe_ctx.GetProcessPtr();
303
304
if (process == nullptr)
305
return false;
306
307
lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
308
309
if (process != jit_process_sp.get())
310
return false;
311
312
Status error;
313
ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(
314
args_addr + m_return_offset, m_return_size, 0, error);
315
316
if (error.Fail())
317
return false;
318
319
ret_value.SetCompilerType(m_function_return_type);
320
ret_value.SetValueType(Value::ValueType::Scalar);
321
return true;
322
}
323
324
void FunctionCaller::DeallocateFunctionResults(ExecutionContext &exe_ctx,
325
lldb::addr_t args_addr) {
326
std::list<lldb::addr_t>::iterator pos;
327
pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),
328
args_addr);
329
if (pos != m_wrapper_args_addrs.end())
330
m_wrapper_args_addrs.erase(pos);
331
332
exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
333
}
334
335
lldb::ExpressionResults FunctionCaller::ExecuteFunction(
336
ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,
337
const EvaluateExpressionOptions &options,
338
DiagnosticManager &diagnostic_manager, Value &results) {
339
lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
340
341
// FunctionCaller::ExecuteFunction execution is always just to get the
342
// result. Unless explicitly asked for, ignore breakpoints and unwind on
343
// error.
344
const bool enable_debugging =
345
exe_ctx.GetTargetPtr() &&
346
exe_ctx.GetTargetPtr()->GetDebugUtilityExpression();
347
EvaluateExpressionOptions real_options = options;
348
real_options.SetDebug(false); // This halts the expression for debugging.
349
real_options.SetGenerateDebugInfo(enable_debugging);
350
real_options.SetUnwindOnError(!enable_debugging);
351
real_options.SetIgnoreBreakpoints(!enable_debugging);
352
353
lldb::addr_t args_addr;
354
355
if (args_addr_ptr != nullptr)
356
args_addr = *args_addr_ptr;
357
else
358
args_addr = LLDB_INVALID_ADDRESS;
359
360
if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)
361
return lldb::eExpressionSetupError;
362
363
if (args_addr == LLDB_INVALID_ADDRESS) {
364
if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))
365
return lldb::eExpressionSetupError;
366
}
367
368
Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));
369
370
LLDB_LOGF(log,
371
"== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",
372
m_name.c_str());
373
374
lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction(
375
exe_ctx, args_addr, real_options, diagnostic_manager);
376
if (!call_plan_sp)
377
return lldb::eExpressionSetupError;
378
379
// We need to make sure we record the fact that we are running an expression
380
// here otherwise this fact will fail to be recorded when fetching an
381
// Objective-C object description
382
if (exe_ctx.GetProcessPtr())
383
exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
384
385
return_value = exe_ctx.GetProcessRef().RunThreadPlan(
386
exe_ctx, call_plan_sp, real_options, diagnostic_manager);
387
388
if (log) {
389
if (return_value != lldb::eExpressionCompleted) {
390
LLDB_LOGF(log,
391
"== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
392
"completed abnormally: %s ==",
393
m_name.c_str(),
394
Process::ExecutionResultAsCString(return_value));
395
} else {
396
LLDB_LOGF(log,
397
"== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
398
"completed normally ==",
399
m_name.c_str());
400
}
401
}
402
403
if (exe_ctx.GetProcessPtr())
404
exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
405
406
if (args_addr_ptr != nullptr)
407
*args_addr_ptr = args_addr;
408
409
if (return_value != lldb::eExpressionCompleted)
410
return return_value;
411
412
FetchFunctionResults(exe_ctx, args_addr, results);
413
414
if (args_addr_ptr == nullptr)
415
DeallocateFunctionResults(exe_ctx, args_addr);
416
417
return lldb::eExpressionCompleted;
418
}
419
420