1 //===-- ThreadPlanCallFunction.cpp ------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Target/ThreadPlanCallFunction.h"
10 #include "lldb/Breakpoint/Breakpoint.h"
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/Address.h"
13 #include "lldb/Core/DumpRegisterValue.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 #include "lldb/Target/ABI.h"
17 #include "lldb/Target/LanguageRuntime.h"
18 #include "lldb/Target/Process.h"
19 #include "lldb/Target/RegisterContext.h"
20 #include "lldb/Target/StopInfo.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlanRunToAddress.h"
24 #include "lldb/Utility/Log.h"
25 #include "lldb/Utility/Stream.h"
30 using namespace lldb_private;
32 // ThreadPlanCallFunction: Plan to call a single function
33 bool ThreadPlanCallFunction::ConstructorSetup(
34 Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr,
35 lldb::addr_t &function_load_addr) {
36 SetIsMasterPlan(true);
37 SetOkayToDiscard(false);
40 ProcessSP process_sp(thread.GetProcess());
44 abi = process_sp->GetABI().get();
49 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
53 m_function_sp = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();
54 // If we can't read memory at the point of the process where we are planning
55 // to put our function, we're not going to get any further...
57 process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error);
58 if (!error.Success()) {
59 m_constructor_errors.Printf(
60 "Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".",
63 log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
64 m_constructor_errors.GetData());
68 Module *exe_module = GetTarget().GetExecutableModulePointer();
70 if (exe_module == nullptr) {
71 m_constructor_errors.Printf(
72 "Can't execute code without an executable module.");
74 log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
75 m_constructor_errors.GetData());
78 ObjectFile *objectFile = exe_module->GetObjectFile();
80 m_constructor_errors.Printf(
81 "Could not find object file for module \"%s\".",
82 exe_module->GetFileSpec().GetFilename().AsCString());
85 log->Printf("ThreadPlanCallFunction(%p): %s.",
86 static_cast<void *>(this), m_constructor_errors.GetData());
90 m_start_addr = objectFile->GetEntryPointAddress();
91 if (!m_start_addr.IsValid()) {
92 m_constructor_errors.Printf(
93 "Could not find entry point address for executable module \"%s\".",
94 exe_module->GetFileSpec().GetFilename().AsCString());
96 log->Printf("ThreadPlanCallFunction(%p): %s.",
97 static_cast<void *>(this), m_constructor_errors.GetData());
102 start_load_addr = m_start_addr.GetLoadAddress(&GetTarget());
104 // Checkpoint the thread state so we can restore it later.
105 if (log && log->GetVerbose())
106 ReportRegisterState("About to checkpoint thread before function call. "
107 "Original register state was:");
109 if (!thread.CheckpointThreadState(m_stored_thread_state)) {
110 m_constructor_errors.Printf("Setting up ThreadPlanCallFunction, failed to "
111 "checkpoint thread state.");
113 log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
114 m_constructor_errors.GetData());
117 function_load_addr = m_function_addr.GetLoadAddress(&GetTarget());
122 ThreadPlanCallFunction::ThreadPlanCallFunction(
123 Thread &thread, const Address &function, const CompilerType &return_type,
124 llvm::ArrayRef<addr_t> args, const EvaluateExpressionOptions &options)
125 : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
126 eVoteNoOpinion, eVoteNoOpinion),
127 m_valid(false), m_stop_other_threads(options.GetStopOthers()),
128 m_unwind_on_error(options.DoesUnwindOnError()),
129 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
130 m_debug_execution(options.GetDebug()),
131 m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
132 m_function_sp(0), m_takedown_done(false),
133 m_should_clear_objc_exception_bp(false),
134 m_should_clear_cxx_exception_bp(false),
135 m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(return_type) {
136 lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;
137 lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;
140 if (!ConstructorSetup(thread, abi, start_load_addr, function_load_addr))
143 if (!abi->PrepareTrivialCall(thread, m_function_sp, function_load_addr,
144 start_load_addr, args))
147 ReportRegisterState("Function call was set up. Register state was:");
152 ThreadPlanCallFunction::ThreadPlanCallFunction(
153 Thread &thread, const Address &function,
154 const EvaluateExpressionOptions &options)
155 : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
156 eVoteNoOpinion, eVoteNoOpinion),
157 m_valid(false), m_stop_other_threads(options.GetStopOthers()),
158 m_unwind_on_error(options.DoesUnwindOnError()),
159 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
160 m_debug_execution(options.GetDebug()),
161 m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
162 m_function_sp(0), m_takedown_done(false),
163 m_should_clear_objc_exception_bp(false),
164 m_should_clear_cxx_exception_bp(false),
165 m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(CompilerType()) {}
167 ThreadPlanCallFunction::~ThreadPlanCallFunction() {
168 DoTakedown(PlanSucceeded());
171 void ThreadPlanCallFunction::ReportRegisterState(const char *message) {
172 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
173 if (log && log->GetVerbose()) {
175 RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
177 log->PutCString(message);
179 RegisterValue reg_value;
181 for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();
182 reg_idx < num_registers; ++reg_idx) {
183 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
184 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
185 DumpRegisterValue(reg_value, &strm, reg_info, true, false,
190 log->PutString(strm.GetString());
194 void ThreadPlanCallFunction::DoTakedown(bool success) {
195 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
198 // Don't call DoTakedown if we were never valid to begin with.
200 log->Printf("ThreadPlanCallFunction(%p): Log called on "
201 "ThreadPlanCallFunction that was never valid.",
202 static_cast<void *>(this));
206 if (!m_takedown_done) {
211 log->Printf("ThreadPlanCallFunction(%p): DoTakedown called for thread "
212 "0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
213 static_cast<void *>(this), m_thread.GetID(), m_valid,
215 m_takedown_done = true;
217 m_thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();
218 m_real_stop_info_sp = GetPrivateStopInfo();
219 if (!m_thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state)) {
221 log->Printf("ThreadPlanCallFunction(%p): DoTakedown failed to restore "
223 static_cast<void *>(this));
225 SetPlanComplete(success);
227 if (log && log->GetVerbose())
228 ReportRegisterState("Restoring thread state after function call. "
229 "Restored register state:");
232 log->Printf("ThreadPlanCallFunction(%p): DoTakedown called as no-op for "
233 "thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
234 static_cast<void *>(this), m_thread.GetID(), m_valid,
239 void ThreadPlanCallFunction::WillPop() { DoTakedown(PlanSucceeded()); }
241 void ThreadPlanCallFunction::GetDescription(Stream *s, DescriptionLevel level) {
242 if (level == eDescriptionLevelBrief) {
243 s->Printf("Function call thread plan");
245 TargetSP target_sp(m_thread.CalculateTarget());
246 s->Printf("Thread plan to call 0x%" PRIx64,
247 m_function_addr.GetLoadAddress(target_sp.get()));
251 bool ThreadPlanCallFunction::ValidatePlan(Stream *error) {
254 if (m_constructor_errors.GetSize() > 0)
255 error->PutCString(m_constructor_errors.GetString());
257 error->PutCString("Unknown error");
265 Vote ThreadPlanCallFunction::ShouldReportStop(Event *event_ptr) {
266 if (m_takedown_done || IsPlanComplete())
269 return ThreadPlan::ShouldReportStop(event_ptr);
272 bool ThreadPlanCallFunction::DoPlanExplainsStop(Event *event_ptr) {
273 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
274 LIBLLDB_LOG_PROCESS));
275 m_real_stop_info_sp = GetPrivateStopInfo();
277 // If our subplan knows why we stopped, even if it's done (which would
278 // forward the question to us) we answer yes.
279 if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr)) {
284 // Check if the breakpoint is one of ours.
286 StopReason stop_reason;
287 if (!m_real_stop_info_sp)
288 stop_reason = eStopReasonNone;
290 stop_reason = m_real_stop_info_sp->GetStopReason();
293 "ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - %s.",
294 Thread::StopReasonAsCString(stop_reason));
296 if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())
299 // One more quirk here. If this event was from Halt interrupting the target,
300 // then we should not consider ourselves complete. Return true to
301 // acknowledge the stop.
302 if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
304 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: The event is an "
305 "Interrupt, returning true.");
308 // We control breakpoints separately from other "stop reasons." So first,
309 // check the case where we stopped for an internal breakpoint, in that case,
310 // continue on. If it is not an internal breakpoint, consult
311 // m_ignore_breakpoints.
313 if (stop_reason == eStopReasonBreakpoint) {
314 ProcessSP process_sp(m_thread.CalculateProcess());
315 uint64_t break_site_id = m_real_stop_info_sp->GetValue();
316 BreakpointSiteSP bp_site_sp;
318 bp_site_sp = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
320 uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
321 bool is_internal = true;
322 for (uint32_t i = 0; i < num_owners; i++) {
323 Breakpoint &bp = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
325 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: hit "
326 "breakpoint %d while calling function",
329 if (!bp.IsInternal()) {
336 log->Printf("ThreadPlanCallFunction::PlanExplainsStop hit an "
337 "internal breakpoint, not stopping.");
342 if (m_ignore_breakpoints) {
344 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are ignoring "
345 "breakpoints, overriding breakpoint stop info ShouldStop, "
347 m_real_stop_info_sp->OverrideShouldStop(false);
351 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are not "
352 "ignoring breakpoints, overriding breakpoint stop info "
353 "ShouldStop, returning true");
354 m_real_stop_info_sp->OverrideShouldStop(true);
357 } else if (!m_unwind_on_error) {
358 // If we don't want to discard this plan, than any stop we don't understand
359 // should be propagated up the stack.
362 // If the subplan is running, any crashes are attributable to us. If we
363 // want to discard the plan, then we say we explain the stop but if we are
364 // going to be discarded, let whoever is above us explain the stop. But
365 // don't discard the plan if the stop would restart itself (for instance if
366 // it is a signal that is set not to stop. Check that here first. We just
367 // say we explain the stop but aren't done and everything will continue on
370 if (m_real_stop_info_sp &&
371 m_real_stop_info_sp->ShouldStopSynchronous(event_ptr)) {
372 SetPlanComplete(false);
373 return m_subplan_sp ? m_unwind_on_error : false;
379 bool ThreadPlanCallFunction::ShouldStop(Event *event_ptr) {
380 // We do some computation in DoPlanExplainsStop that may or may not set the
381 // plan as complete. We need to do that here to make sure our state is
383 DoPlanExplainsStop(event_ptr);
385 if (IsPlanComplete()) {
386 ReportRegisterState("Function completed. Register state was:");
393 bool ThreadPlanCallFunction::StopOthers() { return m_stop_other_threads; }
395 StateType ThreadPlanCallFunction::GetPlanRunState() { return eStateRunning; }
397 void ThreadPlanCallFunction::DidPush() {
398 //#define SINGLE_STEP_EXPRESSIONS
400 // Now set the thread state to "no reason" so we don't run with whatever
401 // signal was outstanding... Wait till the plan is pushed so we aren't
402 // changing the stop info till we're about to run.
404 GetThread().SetStopInfoToNothing();
406 #ifndef SINGLE_STEP_EXPRESSIONS
407 m_subplan_sp = std::make_shared<ThreadPlanRunToAddress>(
408 m_thread, m_start_addr, m_stop_other_threads);
410 m_thread.QueueThreadPlan(m_subplan_sp, false);
411 m_subplan_sp->SetPrivate(true);
415 bool ThreadPlanCallFunction::WillStop() { return true; }
417 bool ThreadPlanCallFunction::MischiefManaged() {
418 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
420 if (IsPlanComplete()) {
422 log->Printf("ThreadPlanCallFunction(%p): Completed call function plan.",
423 static_cast<void *>(this));
425 ThreadPlan::MischiefManaged();
432 void ThreadPlanCallFunction::SetBreakpoints() {
433 ProcessSP process_sp(m_thread.CalculateProcess());
434 if (m_trap_exceptions && process_sp) {
435 m_cxx_language_runtime =
436 process_sp->GetLanguageRuntime(eLanguageTypeC_plus_plus);
437 m_objc_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeObjC);
439 if (m_cxx_language_runtime) {
440 m_should_clear_cxx_exception_bp =
441 !m_cxx_language_runtime->ExceptionBreakpointsAreSet();
442 m_cxx_language_runtime->SetExceptionBreakpoints();
444 if (m_objc_language_runtime) {
445 m_should_clear_objc_exception_bp =
446 !m_objc_language_runtime->ExceptionBreakpointsAreSet();
447 m_objc_language_runtime->SetExceptionBreakpoints();
452 void ThreadPlanCallFunction::ClearBreakpoints() {
453 if (m_trap_exceptions) {
454 if (m_cxx_language_runtime && m_should_clear_cxx_exception_bp)
455 m_cxx_language_runtime->ClearExceptionBreakpoints();
456 if (m_objc_language_runtime && m_should_clear_objc_exception_bp)
457 m_objc_language_runtime->ClearExceptionBreakpoints();
461 bool ThreadPlanCallFunction::BreakpointsExplainStop() {
462 StopInfoSP stop_info_sp = GetPrivateStopInfo();
464 if (m_trap_exceptions) {
465 if ((m_cxx_language_runtime &&
466 m_cxx_language_runtime->ExceptionBreakpointsExplainStop(
468 (m_objc_language_runtime &&
469 m_objc_language_runtime->ExceptionBreakpointsExplainStop(
471 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
473 log->Printf("ThreadPlanCallFunction::BreakpointsExplainStop - Hit an "
474 "exception breakpoint, setting plan complete.");
476 SetPlanComplete(false);
478 // If the user has set the ObjC language breakpoint, it would normally
479 // get priority over our internal catcher breakpoint, but in this case we
480 // can't let that happen, so force the ShouldStop here.
481 stop_info_sp->OverrideShouldStop(true);
489 void ThreadPlanCallFunction::SetStopOthers(bool new_value) {
490 m_subplan_sp->SetStopOthers(new_value);
493 bool ThreadPlanCallFunction::RestoreThreadState() {
494 return GetThread().RestoreThreadStateFromCheckpoint(m_stored_thread_state);
497 void ThreadPlanCallFunction::SetReturnValue() {
498 ProcessSP process_sp(m_thread.GetProcess());
499 const ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
500 if (abi && m_return_type.IsValid()) {
501 const bool persistent = false;
503 abi->GetReturnValueObject(m_thread, m_return_type, persistent);