LLDB mainline
ThreadPlanCallFunction.cpp
Go to the documentation of this file.
1//===-- ThreadPlanCallFunction.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
12#include "lldb/Core/Address.h"
14#include "lldb/Core/Module.h"
16#include "lldb/Target/ABI.h"
18#include "lldb/Target/Process.h"
21#include "lldb/Target/Target.h"
22#include "lldb/Target/Thread.h"
25#include "lldb/Utility/Log.h"
26#include "lldb/Utility/Stream.h"
27
28#include <memory>
29
30using namespace lldb;
31using namespace lldb_private;
32
33// ThreadPlanCallFunction: Plan to call a single function
35 Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr,
36 lldb::addr_t &function_load_addr) {
38 SetOkayToDiscard(false);
39 SetPrivate(true);
40
41 ProcessSP process_sp(thread.GetProcess());
42 if (!process_sp)
43 return false;
44
45 abi = process_sp->GetABI().get();
46
47 if (!abi)
48 return false;
49
50 Log *log = GetLog(LLDBLog::Step);
51
53
54 m_function_sp = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();
55 // If we can't read memory at the point of the process where we are planning
56 // to put our function, we're not going to get any further...
58 process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error);
59 if (!error.Success()) {
61 "Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".",
63 LLDB_LOGF(log, "ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
64 m_constructor_errors.GetData());
65 return false;
66 }
67
68 llvm::Expected<Address> start_address = GetTarget().GetEntryPointAddress();
69 if (!start_address) {
71 "%s", llvm::toString(start_address.takeError()).c_str());
72 LLDB_LOGF(log, "ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
73 m_constructor_errors.GetData());
74 return false;
75 }
76
77 m_start_addr = *start_address;
78 start_load_addr = m_start_addr.GetLoadAddress(&GetTarget());
79
80 // Checkpoint the thread state so we can restore it later.
81 if (log && log->GetVerbose())
82 ReportRegisterState("About to checkpoint thread before function call. "
83 "Original register state was:");
84
85 if (!thread.CheckpointThreadState(m_stored_thread_state)) {
86 m_constructor_errors.Printf("Setting up ThreadPlanCallFunction, failed to "
87 "checkpoint thread state.");
88 LLDB_LOGF(log, "ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
89 m_constructor_errors.GetData());
90 return false;
91 }
92 function_load_addr = m_function_addr.GetLoadAddress(&GetTarget());
93
94 return true;
95}
96
98 Thread &thread, const Address &function, const CompilerType &return_type,
99 llvm::ArrayRef<addr_t> args, const EvaluateExpressionOptions &options)
100 : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
102 m_valid(false), m_stop_other_threads(options.GetStopOthers()),
103 m_unwind_on_error(options.DoesUnwindOnError()),
104 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
105 m_debug_execution(options.GetDebug()),
106 m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
107 m_start_addr(), m_function_sp(0), m_subplan_sp(),
108 m_cxx_language_runtime(nullptr), m_objc_language_runtime(nullptr),
109 m_stored_thread_state(), m_real_stop_info_sp(), m_constructor_errors(),
110 m_return_valobj_sp(), m_takedown_done(false),
111 m_should_clear_objc_exception_bp(false),
112 m_should_clear_cxx_exception_bp(false),
113 m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(return_type) {
114 bool runs_as_top_level_code = options.GetREPLEnabled();
115 if (runs_as_top_level_code)
118
119 lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;
120 lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;
121 ABI *abi = nullptr;
122
123 if (!ConstructorSetup(thread, abi, start_load_addr, function_load_addr))
124 return;
125
126 if (!abi->PrepareTrivialCall(thread, m_function_sp, function_load_addr,
127 start_load_addr, args))
128 return;
129
130 ReportRegisterState("Function call was set up. Register state was:");
131
132 m_valid = true;
133}
134
136 Thread &thread, const Address &function,
137 const EvaluateExpressionOptions &options)
138 : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
140 m_valid(false), m_stop_other_threads(options.GetStopOthers()),
141 m_unwind_on_error(options.DoesUnwindOnError()),
142 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
143 m_debug_execution(options.GetDebug()),
144 m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
152
156
158 Log *log = GetLog(LLDBLog::Step);
159 if (log && log->GetVerbose()) {
160 StreamString strm;
161 RegisterContext *reg_ctx = GetThread().GetRegisterContext().get();
162
163 log->PutCString(message);
164
165 RegisterValue reg_value;
166
167 for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();
168 reg_idx < num_registers; ++reg_idx) {
169 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
170 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
171 DumpRegisterValue(reg_value, strm, *reg_info, true, false,
173 strm.EOL();
174 }
175 }
176 log->PutString(strm.GetString());
177 }
178}
179
181 Log *log = GetLog(LLDBLog::Step);
182 Thread &thread = GetThread();
183
184 if (!m_valid) {
185 // If ConstructorSetup was succesfull but PrepareTrivialCall was not,
186 // we will have a saved register state and potentially modified registers.
187 // Restore those.
188 if (m_stored_thread_state.register_backup_sp)
189 if (!thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state))
190 LLDB_LOGF(
191 log,
192 "ThreadPlanCallFunction(%p): Failed to restore register state from "
193 "invalid plan that contained a saved register state.",
194 static_cast<void *>(this));
195
196 // Don't call DoTakedown if we were never valid to begin with.
197 LLDB_LOGF(log,
198 "ThreadPlanCallFunction(%p): Log called on "
199 "ThreadPlanCallFunction that was never valid.",
200 static_cast<void *>(this));
201 return;
202 }
203
204 if (!m_takedown_done) {
205 if (success) {
207 }
208 LLDB_LOGF(log,
209 "ThreadPlanCallFunction(%p): DoTakedown called for thread "
210 "0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
211 static_cast<void *>(this), m_tid, m_valid, IsPlanComplete());
212 m_takedown_done = true;
213 RegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
214 if (reg_ctx_sp)
215 m_stop_address = reg_ctx_sp->GetPC();
216 else
218
220 if (!thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state)) {
221 LLDB_LOGF(log,
222 "ThreadPlanCallFunction(%p): DoTakedown failed to restore "
223 "register state",
224 static_cast<void *>(this));
225 }
226 SetPlanComplete(success);
228 if (log && log->GetVerbose())
229 ReportRegisterState("Restoring thread state after function call. "
230 "Restored register state:");
231 } else {
232 LLDB_LOGF(log,
233 "ThreadPlanCallFunction(%p): DoTakedown called as no-op for "
234 "thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
235 static_cast<void *>(this), m_tid, m_valid, IsPlanComplete());
236 }
237}
238
240
242 if (level == eDescriptionLevelBrief) {
243 s->PutCString("Function call thread plan");
244 } else {
245 s->Printf("Thread plan to call 0x%" PRIx64,
246 m_function_addr.GetLoadAddress(&GetTarget()));
247 }
248}
249
251 if (!m_valid) {
252 if (error) {
253 if (m_constructor_errors.GetSize() > 0)
254 error->PutCString(m_constructor_errors.GetString());
255 else
256 error->PutCString("Unknown error");
257 }
258 return false;
259 }
260
261 return true;
262}
263
266 return eVoteYes;
267 else
268 return ThreadPlan::ShouldReportStop(event_ptr);
269}
270
274
275 // If our subplan knows why we stopped, even if it's done (which would
276 // forward the question to us) we answer yes.
277 if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr)) {
279 return true;
280 }
281
282 // Check if the breakpoint is one of ours.
283
284 StopReason stop_reason;
286 stop_reason = eStopReasonNone;
287 else
288 stop_reason = m_real_stop_info_sp->GetStopReason();
289 LLDB_LOG(log,
290 "ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - {0}.",
291 Thread::StopReasonAsString(stop_reason));
292
293 if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())
294 return true;
295
296 // One more quirk here. If this event was from Halt interrupting the target,
297 // then we should not consider ourselves complete. Return true to
298 // acknowledge the stop.
300 LLDB_LOGF(log, "ThreadPlanCallFunction::PlanExplainsStop: The event is an "
301 "Interrupt, returning true.");
302 return true;
303 }
304 // We control breakpoints separately from other "stop reasons." So first,
305 // check the case where we stopped for an internal breakpoint, in that case,
306 // continue on. If it is not an internal breakpoint, consult
307 // m_ignore_breakpoints.
308
309 if (stop_reason == eStopReasonBreakpoint) {
310 uint64_t break_site_id = m_real_stop_info_sp->GetValue();
311 BreakpointSiteSP bp_site_sp;
312 bp_site_sp = m_process.GetBreakpointSiteList().FindByID(break_site_id);
313 if (bp_site_sp) {
314 uint32_t num_owners = bp_site_sp->GetNumberOfConstituents();
315 bool is_internal = true;
316 for (uint32_t i = 0; i < num_owners; i++) {
317 Breakpoint &bp = bp_site_sp->GetConstituentAtIndex(i)->GetBreakpoint();
318 LLDB_LOGF(log,
319 "ThreadPlanCallFunction::PlanExplainsStop: hit "
320 "breakpoint %d while calling function",
321 bp.GetID());
322
323 if (!bp.IsInternal()) {
324 is_internal = false;
325 break;
326 }
327 }
328 if (is_internal) {
329 LLDB_LOGF(log, "ThreadPlanCallFunction::PlanExplainsStop hit an "
330 "internal breakpoint, not stopping.");
331 return false;
332 }
333 }
334
336 LLDB_LOGF(log,
337 "ThreadPlanCallFunction::PlanExplainsStop: we are ignoring "
338 "breakpoints, overriding breakpoint stop info ShouldStop, "
339 "returning true");
340 m_real_stop_info_sp->OverrideShouldStop(false);
341 return true;
342 } else {
343 LLDB_LOGF(log, "ThreadPlanCallFunction::PlanExplainsStop: we are not "
344 "ignoring breakpoints, overriding breakpoint stop info "
345 "ShouldStop, returning true");
346 m_real_stop_info_sp->OverrideShouldStop(true);
347 return false;
348 }
349 } else if (!m_unwind_on_error) {
350 // If we don't want to discard this plan, than any stop we don't understand
351 // should be propagated up the stack.
352 return false;
353 } else {
354 // If the subplan is running, any crashes are attributable to us. If we
355 // want to discard the plan, then we say we explain the stop but if we are
356 // going to be discarded, let whoever is above us explain the stop. But
357 // don't discard the plan if the stop would restart itself (for instance if
358 // it is a signal that is set not to stop. Check that here first. We just
359 // say we explain the stop but aren't done and everything will continue on
360 // from there.
361
362 // Fork events are not handled by this plan — let them fall through
363 // to ThreadPlanBase. DidFork is called via PerformAction when the
364 // event is delivered.
366 StopReason reason = m_real_stop_info_sp->GetStopReason();
367 if (reason == eStopReasonFork || reason == eStopReasonVFork ||
368 reason == eStopReasonVForkDone)
369 return false;
370 }
371
373 m_real_stop_info_sp->ShouldStopSynchronous(event_ptr)) {
374 SetPlanComplete(false);
375 return m_subplan_sp ? m_unwind_on_error : false;
376 } else
377 return true;
378 }
379}
380
382 // We do some computation in DoPlanExplainsStop that may or may not set the
383 // plan as complete. We need to do that here to make sure our state is
384 // correct.
385 DoPlanExplainsStop(event_ptr);
386
387 if (IsPlanComplete()) {
388 ReportRegisterState("Function completed. Register state was:");
389 return true;
390 } else {
391 return false;
392 }
393}
394
396
398
400 //#define SINGLE_STEP_EXPRESSIONS
401
402 // Now set the thread state to "no reason" so we don't run with whatever
403 // signal was outstanding... Wait till the plan is pushed so we aren't
404 // changing the stop info till we're about to run.
405
407
408#ifndef SINGLE_STEP_EXPRESSIONS
409 Thread &thread = GetThread();
410 m_subplan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, m_start_addr,
412
413 thread.QueueThreadPlan(m_subplan_sp, false);
414 m_subplan_sp->SetPrivate(true);
415#endif
416}
417
418bool ThreadPlanCallFunction::WillStop() { return true; }
419
421 Log *log = GetLog(LLDBLog::Step);
422
423 if (IsPlanComplete()) {
424 LLDB_LOGF(log, "ThreadPlanCallFunction(%p): Completed call function plan.",
425 static_cast<void *>(this));
426
428 return true;
429 } else {
430 return false;
431 }
432}
433
435 if (m_trap_exceptions) {
437 m_process.GetLanguageRuntime(eLanguageTypeC_plus_plus);
439
442 !m_cxx_language_runtime->ExceptionBreakpointsAreSet();
443 m_cxx_language_runtime->SetExceptionBreakpoints();
444 }
447 !m_objc_language_runtime->ExceptionBreakpointsAreSet();
448 m_objc_language_runtime->SetExceptionBreakpoints();
449 }
450 }
453 m_error_backstop_runtime->CreateErrorBackstopBreakpoint();
454}
455
466
468 StopInfoSP stop_info_sp = GetPrivateStopInfo();
469
470 if (m_trap_exceptions) {
472 m_cxx_language_runtime->ExceptionBreakpointsExplainStop(
473 stop_info_sp)) ||
475 m_objc_language_runtime->ExceptionBreakpointsExplainStop(
476 stop_info_sp))) {
477 Log *log = GetLog(LLDBLog::Step);
478 LLDB_LOGF(log, "ThreadPlanCallFunction::BreakpointsExplainStop - Hit an "
479 "exception breakpoint, setting plan complete.");
480
481 SetPlanComplete(false);
482
483 // If the user has set the ObjC language breakpoint, it would normally
484 // get priority over our internal catcher breakpoint, but in this case we
485 // can't let that happen, so force the ShouldStop here.
486 stop_info_sp->OverrideShouldStop(true);
487 return true;
488 }
489 }
490 if (m_error_backstop_bp_sp && stop_info_sp &&
491 stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
492 m_process.GetBreakpointSiteList().StopPointSiteContainsBreakpoint(
493 stop_info_sp->GetValue(), m_error_backstop_bp_sp->GetID())) {
494 // This was top-level code that threw an error.
495 SetPlanComplete(true);
496 if (StackFrameSP frame_sp = GetThread().GetStackFrameAtIndex(0)) {
498 m_error_backstop_runtime->GetErrorValueAtBackstop(*frame_sp);
499 if (m_return_valobj_sp) {
501 return true;
502 }
503 }
504 }
505
506 return false;
507}
508
510 m_subplan_sp->SetStopOthers(new_value);
511}
512
516
518 const ABI *abi = m_process.GetABI().get();
519 if (abi && m_return_type.IsValid()) {
520 const bool persistent = false;
522 abi->GetReturnValueObject(GetThread(), m_return_type, persistent);
523 }
524}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
lldb::ValueObjectSP GetReturnValueObject(Thread &thread, CompilerType &type, bool persistent=true) const
Definition ABI.cpp:61
virtual size_t GetRedZoneSize() const =0
A section + offset based address class.
Definition Address.h:62
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition Breakpoint.h:83
bool IsInternal() const
Tell whether this breakpoint is an "internal" breakpoint.
Generic representation of a type in a programming language.
SourceLanguage GetLanguage() const
Definition Target.h:372
void PutCString(const char *cstr)
Definition Log.cpp:162
bool GetVerbose() const
Definition Log.cpp:329
void PutString(llvm::StringRef str)
Definition Log.cpp:164
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition Process.cpp:4864
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
Definition Process.cpp:1555
virtual const RegisterInfo * GetRegisterInfoAtIndex(size_t reg)=0
virtual size_t GetRegisterCount()=0
virtual bool ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
An error handling class.
Definition Status.h:118
lldb::break_id_t GetID() const
Definition Stoppoint.cpp:22
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
llvm::Expected< lldb_private::Address > GetEntryPointAddress()
This method will return the address of the starting function for this binary, e.g.
Definition Target.cpp:3103
bool RemoveBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1230
void SetStopOthers(bool new_value) override
bool ValidatePlan(Stream *error) override
Returns whether this plan could be successfully created.
bool ConstructorSetup(Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr, lldb::addr_t &function_load_addr)
Vote ShouldReportStop(Event *event_ptr) override
ThreadPlanCallFunction(Thread &thread, const Address &function, const CompilerType &return_type, llvm::ArrayRef< lldb::addr_t > args, const EvaluateExpressionOptions &options)
bool DoPlanExplainsStop(Event *event_ptr) override
bool ShouldStop(Event *event_ptr) override
void GetDescription(Stream *s, lldb::DescriptionLevel level) override
Print a description of this thread to the stream s.
Thread::ThreadStateCheckpoint m_stored_thread_state
LanguageRuntime * m_error_backstop_runtime
The runtime that catches errors the expression doesn't handle, if it runs as top-level code.
virtual Vote ShouldReportStop(Event *event_ptr)
void SetPrivate(bool input)
Definition ThreadPlan.h:444
ThreadPlan(ThreadPlanKind kind, const char *name, Thread &thread, Vote report_stop_vote, Vote report_run_vote)
void SetPlanComplete(bool success=true)
Thread & GetThread()
Returns the Thread that is using this thread plan.
void SetOkayToDiscard(bool value)
Definition ThreadPlan.h:431
virtual bool MischiefManaged()
bool SetIsControllingPlan(bool value)
Definition ThreadPlan.h:423
lldb::StopInfoSP GetPrivateStopInfo()
Definition ThreadPlan.h:548
void RestoreThreadStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:572
virtual lldb::RegisterContextSP GetRegisterContext()=0
void SetStopInfoToNothing()
Definition Thread.cpp:513
static std::string StopReasonAsString(lldb::StopReason reason)
Definition Thread.cpp:2047
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
void DumpRegisterValue(const RegisterValue &reg_val, Stream &s, const RegisterInfo &reg_info, bool prefix_with_name, bool prefix_with_alt_name, lldb::Format format, uint32_t reg_name_right_align_at=0, ExecutionContextScope *exe_scope=nullptr, bool print_type=false, lldb::TargetSP target_sp=nullptr)
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
StateType
Process and Thread States.
@ eStateRunning
Process or thread is running and can't be examined.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
StopReason
Thread stop reasons.
@ eStopReasonBreakpoint
@ eStopReasonVForkDone
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Every register is described in detail including its name, alternate name (optional),...
lldb::LanguageType AsLanguageType() const
Definition Language.cpp:671