1 //===-- ThreadPlanCallFunction.cpp ------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
14 #include "lldb/Target/ThreadPlanCallFunction.h"
15 #include "lldb/Breakpoint/Breakpoint.h"
16 #include "lldb/Breakpoint/BreakpointLocation.h"
17 #include "lldb/Core/Address.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/Stream.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Target/ABI.h"
23 #include "lldb/Target/LanguageRuntime.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/RegisterContext.h"
26 #include "lldb/Target/StopInfo.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/ThreadPlanRunToAddress.h"
32 using namespace lldb_private;
34 //----------------------------------------------------------------------
35 // ThreadPlanCallFunction: Plan to call a single function
36 //----------------------------------------------------------------------
38 ThreadPlanCallFunction::ConstructorSetup (Thread &thread,
40 lldb::addr_t &start_load_addr,
41 lldb::addr_t &function_load_addr)
43 SetIsMasterPlan (true);
44 SetOkayToDiscard (false);
47 ProcessSP process_sp (thread.GetProcess());
51 abi = process_sp->GetABI().get();
56 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP));
60 m_function_sp = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();
61 // If we can't read memory at the point of the process where we are planning to put our function, we're
62 // not going to get any further...
64 process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error);
67 m_constructor_errors.Printf ("Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".", m_function_sp);
69 log->Printf ("ThreadPlanCallFunction(%p): %s.",
70 static_cast<void*>(this),
71 m_constructor_errors.GetData());
75 Module *exe_module = GetTarget().GetExecutableModulePointer();
77 if (exe_module == nullptr)
79 m_constructor_errors.Printf ("Can't execute code without an executable module.");
81 log->Printf ("ThreadPlanCallFunction(%p): %s.",
82 static_cast<void*>(this),
83 m_constructor_errors.GetData());
88 ObjectFile *objectFile = exe_module->GetObjectFile();
91 m_constructor_errors.Printf ("Could not find object file for module \"%s\".",
92 exe_module->GetFileSpec().GetFilename().AsCString());
95 log->Printf ("ThreadPlanCallFunction(%p): %s.",
96 static_cast<void*>(this),
97 m_constructor_errors.GetData());
101 m_start_addr = objectFile->GetEntryPointAddress();
102 if (!m_start_addr.IsValid())
104 m_constructor_errors.Printf ("Could not find entry point address for executable module \"%s\".",
105 exe_module->GetFileSpec().GetFilename().AsCString());
107 log->Printf ("ThreadPlanCallFunction(%p): %s.",
108 static_cast<void*>(this),
109 m_constructor_errors.GetData());
114 start_load_addr = m_start_addr.GetLoadAddress (&GetTarget());
116 // Checkpoint the thread state so we can restore it later.
117 if (log && log->GetVerbose())
118 ReportRegisterState ("About to checkpoint thread before function call. Original register state was:");
120 if (!thread.CheckpointThreadState (m_stored_thread_state))
122 m_constructor_errors.Printf ("Setting up ThreadPlanCallFunction, failed to checkpoint thread state.");
124 log->Printf ("ThreadPlanCallFunction(%p): %s.",
125 static_cast<void*>(this),
126 m_constructor_errors.GetData());
129 function_load_addr = m_function_addr.GetLoadAddress (&GetTarget());
134 ThreadPlanCallFunction::ThreadPlanCallFunction (Thread &thread,
135 const Address &function,
136 const CompilerType &return_type,
137 llvm::ArrayRef<addr_t> args,
138 const EvaluateExpressionOptions &options) :
139 ThreadPlan (ThreadPlan::eKindCallFunction, "Call function plan", thread, eVoteNoOpinion, eVoteNoOpinion),
141 m_stop_other_threads (options.GetStopOthers()),
142 m_unwind_on_error (options.DoesUnwindOnError()),
143 m_ignore_breakpoints (options.DoesIgnoreBreakpoints()),
144 m_debug_execution (options.GetDebug()),
145 m_trap_exceptions (options.GetTrapExceptions()),
146 m_function_addr (function),
148 m_takedown_done (false),
149 m_should_clear_objc_exception_bp(false),
150 m_should_clear_cxx_exception_bp (false),
151 m_stop_address (LLDB_INVALID_ADDRESS),
152 m_return_type (return_type)
154 lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;
155 lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;
158 if (!ConstructorSetup (thread, abi, start_load_addr, function_load_addr))
161 if (!abi->PrepareTrivialCall(thread,
168 ReportRegisterState ("Function call was set up. Register state was:");
173 ThreadPlanCallFunction::ThreadPlanCallFunction(Thread &thread,
174 const Address &function,
175 const EvaluateExpressionOptions &options) :
176 ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread, eVoteNoOpinion, eVoteNoOpinion),
178 m_stop_other_threads(options.GetStopOthers()),
179 m_unwind_on_error(options.DoesUnwindOnError()),
180 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
181 m_debug_execution(options.GetDebug()),
182 m_trap_exceptions(options.GetTrapExceptions()),
183 m_function_addr(function),
185 m_takedown_done(false),
186 m_should_clear_objc_exception_bp(false),
187 m_should_clear_cxx_exception_bp(false),
188 m_stop_address(LLDB_INVALID_ADDRESS),
189 m_return_type(CompilerType())
193 ThreadPlanCallFunction::~ThreadPlanCallFunction ()
195 DoTakedown(PlanSucceeded());
199 ThreadPlanCallFunction::ReportRegisterState (const char *message)
201 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_VERBOSE));
205 RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
207 log->PutCString(message);
209 RegisterValue reg_value;
211 for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();
212 reg_idx < num_registers;
215 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_idx);
216 if (reg_ctx->ReadRegister(reg_info, reg_value))
218 reg_value.Dump(&strm, reg_info, true, false, eFormatDefault);
222 log->PutCString(strm.GetData());
227 ThreadPlanCallFunction::DoTakedown (bool success)
229 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP));
233 //Don't call DoTakedown if we were never valid to begin with.
235 log->Printf ("ThreadPlanCallFunction(%p): Log called on ThreadPlanCallFunction that was never valid.",
236 static_cast<void*>(this));
240 if (!m_takedown_done)
247 log->Printf ("ThreadPlanCallFunction(%p): DoTakedown called for thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
248 static_cast<void*>(this), m_thread.GetID(), m_valid,
250 m_takedown_done = true;
251 m_stop_address = m_thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();
252 m_real_stop_info_sp = GetPrivateStopInfo ();
253 if (!m_thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state))
256 log->Printf("ThreadPlanCallFunction(%p): DoTakedown failed to restore register state",
257 static_cast<void*>(this));
259 SetPlanComplete(success);
261 if (log && log->GetVerbose())
262 ReportRegisterState ("Restoring thread state after function call. Restored register state:");
267 log->Printf ("ThreadPlanCallFunction(%p): DoTakedown called as no-op for thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
268 static_cast<void*>(this), m_thread.GetID(), m_valid,
274 ThreadPlanCallFunction::WillPop ()
276 DoTakedown(PlanSucceeded());
280 ThreadPlanCallFunction::GetDescription (Stream *s, DescriptionLevel level)
282 if (level == eDescriptionLevelBrief)
284 s->Printf("Function call thread plan");
288 TargetSP target_sp (m_thread.CalculateTarget());
289 s->Printf("Thread plan to call 0x%" PRIx64, m_function_addr.GetLoadAddress(target_sp.get()));
294 ThreadPlanCallFunction::ValidatePlan (Stream *error)
300 if (m_constructor_errors.GetSize() > 0)
301 error->PutCString (m_constructor_errors.GetData());
303 error->PutCString ("Unknown error");
312 ThreadPlanCallFunction::ShouldReportStop(Event *event_ptr)
314 if (m_takedown_done || IsPlanComplete())
317 return ThreadPlan::ShouldReportStop(event_ptr);
321 ThreadPlanCallFunction::DoPlanExplainsStop (Event *event_ptr)
323 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP|LIBLLDB_LOG_PROCESS));
324 m_real_stop_info_sp = GetPrivateStopInfo ();
326 // If our subplan knows why we stopped, even if it's done (which would forward the question to us)
328 if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr))
334 // Check if the breakpoint is one of ours.
336 StopReason stop_reason;
337 if (!m_real_stop_info_sp)
338 stop_reason = eStopReasonNone;
340 stop_reason = m_real_stop_info_sp->GetStopReason();
342 log->Printf ("ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - %s.", Thread::StopReasonAsCString(stop_reason));
344 if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())
347 // One more quirk here. If this event was from Halt interrupting the target, then we should not consider
348 // ourselves complete. Return true to acknowledge the stop.
349 if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr))
352 log->Printf ("ThreadPlanCallFunction::PlanExplainsStop: The event is an Interrupt, returning true.");
355 // We control breakpoints separately from other "stop reasons." So first,
356 // check the case where we stopped for an internal breakpoint, in that case, continue on.
357 // If it is not an internal breakpoint, consult m_ignore_breakpoints.
359 if (stop_reason == eStopReasonBreakpoint)
361 ProcessSP process_sp (m_thread.CalculateProcess());
362 uint64_t break_site_id = m_real_stop_info_sp->GetValue();
363 BreakpointSiteSP bp_site_sp;
365 bp_site_sp = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
368 uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
369 bool is_internal = true;
370 for (uint32_t i = 0; i < num_owners; i++)
372 Breakpoint &bp = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
374 log->Printf ("ThreadPlanCallFunction::PlanExplainsStop: hit breakpoint %d while calling function", bp.GetID());
376 if (!bp.IsInternal())
385 log->Printf ("ThreadPlanCallFunction::PlanExplainsStop hit an internal breakpoint, not stopping.");
390 if (m_ignore_breakpoints)
393 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are ignoring breakpoints, overriding breakpoint stop info ShouldStop, returning true");
394 m_real_stop_info_sp->OverrideShouldStop(false);
400 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are not ignoring breakpoints, overriding breakpoint stop info ShouldStop, returning true");
401 m_real_stop_info_sp->OverrideShouldStop(true);
405 else if (!m_unwind_on_error)
407 // If we don't want to discard this plan, than any stop we don't understand should be propagated up the stack.
412 // If the subplan is running, any crashes are attributable to us.
413 // If we want to discard the plan, then we say we explain the stop
414 // but if we are going to be discarded, let whoever is above us
416 // But don't discard the plan if the stop would restart itself (for instance if it is a
417 // signal that is set not to stop. Check that here first. We just say we explain the stop
418 // but aren't done and everything will continue on from there.
420 if (m_real_stop_info_sp && m_real_stop_info_sp->ShouldStopSynchronous(event_ptr))
422 SetPlanComplete(false);
423 return m_subplan_sp ? m_unwind_on_error : false;
431 ThreadPlanCallFunction::ShouldStop (Event *event_ptr)
433 // We do some computation in DoPlanExplainsStop that may or may not set the plan as complete.
434 // We need to do that here to make sure our state is correct.
435 DoPlanExplainsStop(event_ptr);
437 if (IsPlanComplete())
439 ReportRegisterState ("Function completed. Register state was:");
449 ThreadPlanCallFunction::StopOthers ()
451 return m_stop_other_threads;
455 ThreadPlanCallFunction::GetPlanRunState ()
457 return eStateRunning;
461 ThreadPlanCallFunction::DidPush ()
463 //#define SINGLE_STEP_EXPRESSIONS
465 // Now set the thread state to "no reason" so we don't run with whatever signal was outstanding...
466 // Wait till the plan is pushed so we aren't changing the stop info till we're about to run.
468 GetThread().SetStopInfoToNothing();
470 #ifndef SINGLE_STEP_EXPRESSIONS
471 m_subplan_sp.reset(new ThreadPlanRunToAddress(m_thread, m_start_addr, m_stop_other_threads));
473 m_thread.QueueThreadPlan(m_subplan_sp, false);
474 m_subplan_sp->SetPrivate (true);
479 ThreadPlanCallFunction::WillStop ()
485 ThreadPlanCallFunction::MischiefManaged ()
487 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
489 if (IsPlanComplete())
492 log->Printf("ThreadPlanCallFunction(%p): Completed call function plan.",
493 static_cast<void*>(this));
495 ThreadPlan::MischiefManaged ();
505 ThreadPlanCallFunction::SetBreakpoints ()
507 ProcessSP process_sp (m_thread.CalculateProcess());
508 if (m_trap_exceptions && process_sp)
510 m_cxx_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeC_plus_plus);
511 m_objc_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeObjC);
513 if (m_cxx_language_runtime)
515 m_should_clear_cxx_exception_bp = !m_cxx_language_runtime->ExceptionBreakpointsAreSet();
516 m_cxx_language_runtime->SetExceptionBreakpoints();
518 if (m_objc_language_runtime)
520 m_should_clear_objc_exception_bp = !m_objc_language_runtime->ExceptionBreakpointsAreSet();
521 m_objc_language_runtime->SetExceptionBreakpoints();
527 ThreadPlanCallFunction::ClearBreakpoints ()
529 if (m_trap_exceptions)
531 if (m_cxx_language_runtime && m_should_clear_cxx_exception_bp)
532 m_cxx_language_runtime->ClearExceptionBreakpoints();
533 if (m_objc_language_runtime && m_should_clear_objc_exception_bp)
534 m_objc_language_runtime->ClearExceptionBreakpoints();
539 ThreadPlanCallFunction::BreakpointsExplainStop()
541 StopInfoSP stop_info_sp = GetPrivateStopInfo ();
543 if (m_trap_exceptions)
545 if ((m_cxx_language_runtime &&
546 m_cxx_language_runtime->ExceptionBreakpointsExplainStop(stop_info_sp))
547 ||(m_objc_language_runtime &&
548 m_objc_language_runtime->ExceptionBreakpointsExplainStop(stop_info_sp)))
550 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP));
552 log->Printf ("ThreadPlanCallFunction::BreakpointsExplainStop - Hit an exception breakpoint, setting plan complete.");
554 SetPlanComplete(false);
556 // If the user has set the ObjC language breakpoint, it would normally get priority over our internal
557 // catcher breakpoint, but in this case we can't let that happen, so force the ShouldStop here.
558 stop_info_sp->OverrideShouldStop (true);
567 ThreadPlanCallFunction::SetStopOthers (bool new_value)
569 m_subplan_sp->SetStopOthers(new_value);
573 ThreadPlanCallFunction::RestoreThreadState()
575 return GetThread().RestoreThreadStateFromCheckpoint(m_stored_thread_state);
579 ThreadPlanCallFunction::SetReturnValue()
581 ProcessSP process_sp(m_thread.GetProcess());
582 const ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
583 if (abi && m_return_type.IsValid())
585 const bool persistent = false;
586 m_return_valobj_sp = abi->GetReturnValueObject(m_thread, m_return_type, persistent);