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 //===----------------------------------------------------------------------===//
10 #include "lldb/Target/ThreadPlanCallFunction.h"
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Breakpoint/BreakpointLocation.h"
13 #include "lldb/Core/Address.h"
14 #include "lldb/Core/DumpRegisterValue.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Symbol/ObjectFile.h"
17 #include "lldb/Target/ABI.h"
18 #include "lldb/Target/LanguageRuntime.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/RegisterContext.h"
21 #include "lldb/Target/StopInfo.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Target/ThreadPlanRunToAddress.h"
25 #include "lldb/Utility/Log.h"
26 #include "lldb/Utility/Stream.h"
29 using namespace lldb_private;
31 //----------------------------------------------------------------------
32 // ThreadPlanCallFunction: Plan to call a single function
33 //----------------------------------------------------------------------
34 bool ThreadPlanCallFunction::ConstructorSetup(
35 Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr,
36 lldb::addr_t &function_load_addr) {
37 SetIsMasterPlan(true);
38 SetOkayToDiscard(false);
41 ProcessSP process_sp(thread.GetProcess());
45 abi = process_sp->GetABI().get();
50 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
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()) {
60 m_constructor_errors.Printf(
61 "Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".",
64 log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
65 m_constructor_errors.GetData());
69 Module *exe_module = GetTarget().GetExecutableModulePointer();
71 if (exe_module == nullptr) {
72 m_constructor_errors.Printf(
73 "Can't execute code without an executable module.");
75 log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
76 m_constructor_errors.GetData());
79 ObjectFile *objectFile = exe_module->GetObjectFile();
81 m_constructor_errors.Printf(
82 "Could not find object file for module \"%s\".",
83 exe_module->GetFileSpec().GetFilename().AsCString());
86 log->Printf("ThreadPlanCallFunction(%p): %s.",
87 static_cast<void *>(this), m_constructor_errors.GetData());
91 m_start_addr = objectFile->GetEntryPointAddress();
92 if (!m_start_addr.IsValid()) {
93 m_constructor_errors.Printf(
94 "Could not find entry point address for executable module \"%s\".",
95 exe_module->GetFileSpec().GetFilename().AsCString());
97 log->Printf("ThreadPlanCallFunction(%p): %s.",
98 static_cast<void *>(this), m_constructor_errors.GetData());
103 start_load_addr = m_start_addr.GetLoadAddress(&GetTarget());
105 // Checkpoint the thread state so we can restore it later.
106 if (log && log->GetVerbose())
107 ReportRegisterState("About to checkpoint thread before function call. "
108 "Original register state was:");
110 if (!thread.CheckpointThreadState(m_stored_thread_state)) {
111 m_constructor_errors.Printf("Setting up ThreadPlanCallFunction, failed to "
112 "checkpoint thread state.");
114 log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
115 m_constructor_errors.GetData());
118 function_load_addr = m_function_addr.GetLoadAddress(&GetTarget());
123 ThreadPlanCallFunction::ThreadPlanCallFunction(
124 Thread &thread, const Address &function, const CompilerType &return_type,
125 llvm::ArrayRef<addr_t> args, const EvaluateExpressionOptions &options)
126 : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
127 eVoteNoOpinion, eVoteNoOpinion),
128 m_valid(false), m_stop_other_threads(options.GetStopOthers()),
129 m_unwind_on_error(options.DoesUnwindOnError()),
130 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
131 m_debug_execution(options.GetDebug()),
132 m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
133 m_function_sp(0), m_takedown_done(false),
134 m_should_clear_objc_exception_bp(false),
135 m_should_clear_cxx_exception_bp(false),
136 m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(return_type) {
137 lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;
138 lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;
141 if (!ConstructorSetup(thread, abi, start_load_addr, function_load_addr))
144 if (!abi->PrepareTrivialCall(thread, m_function_sp, function_load_addr,
145 start_load_addr, args))
148 ReportRegisterState("Function call was set up. Register state was:");
153 ThreadPlanCallFunction::ThreadPlanCallFunction(
154 Thread &thread, const Address &function,
155 const EvaluateExpressionOptions &options)
156 : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
157 eVoteNoOpinion, eVoteNoOpinion),
158 m_valid(false), m_stop_other_threads(options.GetStopOthers()),
159 m_unwind_on_error(options.DoesUnwindOnError()),
160 m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
161 m_debug_execution(options.GetDebug()),
162 m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
163 m_function_sp(0), m_takedown_done(false),
164 m_should_clear_objc_exception_bp(false),
165 m_should_clear_cxx_exception_bp(false),
166 m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(CompilerType()) {}
168 ThreadPlanCallFunction::~ThreadPlanCallFunction() {
169 DoTakedown(PlanSucceeded());
172 void ThreadPlanCallFunction::ReportRegisterState(const char *message) {
173 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
174 if (log && log->GetVerbose()) {
176 RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
178 log->PutCString(message);
180 RegisterValue reg_value;
182 for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();
183 reg_idx < num_registers; ++reg_idx) {
184 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
185 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
186 DumpRegisterValue(reg_value, &strm, reg_info, true, false,
191 log->PutString(strm.GetString());
195 void ThreadPlanCallFunction::DoTakedown(bool success) {
196 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
199 // Don't call DoTakedown if we were never valid to begin with.
201 log->Printf("ThreadPlanCallFunction(%p): Log called on "
202 "ThreadPlanCallFunction that was never valid.",
203 static_cast<void *>(this));
207 if (!m_takedown_done) {
212 log->Printf("ThreadPlanCallFunction(%p): DoTakedown called for thread "
213 "0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
214 static_cast<void *>(this), m_thread.GetID(), m_valid,
216 m_takedown_done = true;
218 m_thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();
219 m_real_stop_info_sp = GetPrivateStopInfo();
220 if (!m_thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state)) {
222 log->Printf("ThreadPlanCallFunction(%p): DoTakedown failed to restore "
224 static_cast<void *>(this));
226 SetPlanComplete(success);
228 if (log && log->GetVerbose())
229 ReportRegisterState("Restoring thread state after function call. "
230 "Restored register state:");
233 log->Printf("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_thread.GetID(), m_valid,
240 void ThreadPlanCallFunction::WillPop() { DoTakedown(PlanSucceeded()); }
242 void ThreadPlanCallFunction::GetDescription(Stream *s, DescriptionLevel level) {
243 if (level == eDescriptionLevelBrief) {
244 s->Printf("Function call thread plan");
246 TargetSP target_sp(m_thread.CalculateTarget());
247 s->Printf("Thread plan to call 0x%" PRIx64,
248 m_function_addr.GetLoadAddress(target_sp.get()));
252 bool ThreadPlanCallFunction::ValidatePlan(Stream *error) {
255 if (m_constructor_errors.GetSize() > 0)
256 error->PutCString(m_constructor_errors.GetString());
258 error->PutCString("Unknown error");
266 Vote ThreadPlanCallFunction::ShouldReportStop(Event *event_ptr) {
267 if (m_takedown_done || IsPlanComplete())
270 return ThreadPlan::ShouldReportStop(event_ptr);
273 bool ThreadPlanCallFunction::DoPlanExplainsStop(Event *event_ptr) {
274 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
275 LIBLLDB_LOG_PROCESS));
276 m_real_stop_info_sp = GetPrivateStopInfo();
278 // If our subplan knows why we stopped, even if it's done (which would
279 // forward the question to us) we answer yes.
280 if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr)) {
285 // Check if the breakpoint is one of ours.
287 StopReason stop_reason;
288 if (!m_real_stop_info_sp)
289 stop_reason = eStopReasonNone;
291 stop_reason = m_real_stop_info_sp->GetStopReason();
294 "ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - %s.",
295 Thread::StopReasonAsCString(stop_reason));
297 if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())
300 // One more quirk here. If this event was from Halt interrupting the target,
301 // then we should not consider ourselves complete. Return true to
302 // acknowledge the stop.
303 if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
305 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: The event is an "
306 "Interrupt, returning true.");
309 // We control breakpoints separately from other "stop reasons." So first,
310 // check the case where we stopped for an internal breakpoint, in that case,
311 // continue on. If it is not an internal breakpoint, consult
312 // m_ignore_breakpoints.
314 if (stop_reason == eStopReasonBreakpoint) {
315 ProcessSP process_sp(m_thread.CalculateProcess());
316 uint64_t break_site_id = m_real_stop_info_sp->GetValue();
317 BreakpointSiteSP bp_site_sp;
319 bp_site_sp = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
321 uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
322 bool is_internal = true;
323 for (uint32_t i = 0; i < num_owners; i++) {
324 Breakpoint &bp = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
326 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: hit "
327 "breakpoint %d while calling function",
330 if (!bp.IsInternal()) {
337 log->Printf("ThreadPlanCallFunction::PlanExplainsStop hit an "
338 "internal breakpoint, not stopping.");
343 if (m_ignore_breakpoints) {
345 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are ignoring "
346 "breakpoints, overriding breakpoint stop info ShouldStop, "
348 m_real_stop_info_sp->OverrideShouldStop(false);
352 log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are not "
353 "ignoring breakpoints, overriding breakpoint stop info "
354 "ShouldStop, returning true");
355 m_real_stop_info_sp->OverrideShouldStop(true);
358 } else if (!m_unwind_on_error) {
359 // If we don't want to discard this plan, than any stop we don't understand
360 // should be propagated up the stack.
363 // If the subplan is running, any crashes are attributable to us. If we
364 // want to discard the plan, then we say we explain the stop but if we are
365 // going to be discarded, let whoever is above us explain the stop. But
366 // don't discard the plan if the stop would restart itself (for instance if
367 // it is a signal that is set not to stop. Check that here first. We just
368 // say we explain the stop but aren't done and everything will continue on
371 if (m_real_stop_info_sp &&
372 m_real_stop_info_sp->ShouldStopSynchronous(event_ptr)) {
373 SetPlanComplete(false);
374 return m_subplan_sp ? m_unwind_on_error : false;
380 bool ThreadPlanCallFunction::ShouldStop(Event *event_ptr) {
381 // We do some computation in DoPlanExplainsStop that may or may not set the
382 // plan as complete. We need to do that here to make sure our state is
384 DoPlanExplainsStop(event_ptr);
386 if (IsPlanComplete()) {
387 ReportRegisterState("Function completed. Register state was:");
394 bool ThreadPlanCallFunction::StopOthers() { return m_stop_other_threads; }
396 StateType ThreadPlanCallFunction::GetPlanRunState() { return eStateRunning; }
398 void ThreadPlanCallFunction::DidPush() {
399 //#define SINGLE_STEP_EXPRESSIONS
401 // Now set the thread state to "no reason" so we don't run with whatever
402 // signal was outstanding... Wait till the plan is pushed so we aren't
403 // changing the stop info till we're about to run.
405 GetThread().SetStopInfoToNothing();
407 #ifndef SINGLE_STEP_EXPRESSIONS
409 new ThreadPlanRunToAddress(m_thread, m_start_addr, m_stop_other_threads));
411 m_thread.QueueThreadPlan(m_subplan_sp, false);
412 m_subplan_sp->SetPrivate(true);
416 bool ThreadPlanCallFunction::WillStop() { return true; }
418 bool ThreadPlanCallFunction::MischiefManaged() {
419 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
421 if (IsPlanComplete()) {
423 log->Printf("ThreadPlanCallFunction(%p): Completed call function plan.",
424 static_cast<void *>(this));
426 ThreadPlan::MischiefManaged();
433 void ThreadPlanCallFunction::SetBreakpoints() {
434 ProcessSP process_sp(m_thread.CalculateProcess());
435 if (m_trap_exceptions && process_sp) {
436 m_cxx_language_runtime =
437 process_sp->GetLanguageRuntime(eLanguageTypeC_plus_plus);
438 m_objc_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeObjC);
440 if (m_cxx_language_runtime) {
441 m_should_clear_cxx_exception_bp =
442 !m_cxx_language_runtime->ExceptionBreakpointsAreSet();
443 m_cxx_language_runtime->SetExceptionBreakpoints();
445 if (m_objc_language_runtime) {
446 m_should_clear_objc_exception_bp =
447 !m_objc_language_runtime->ExceptionBreakpointsAreSet();
448 m_objc_language_runtime->SetExceptionBreakpoints();
453 void ThreadPlanCallFunction::ClearBreakpoints() {
454 if (m_trap_exceptions) {
455 if (m_cxx_language_runtime && m_should_clear_cxx_exception_bp)
456 m_cxx_language_runtime->ClearExceptionBreakpoints();
457 if (m_objc_language_runtime && m_should_clear_objc_exception_bp)
458 m_objc_language_runtime->ClearExceptionBreakpoints();
462 bool ThreadPlanCallFunction::BreakpointsExplainStop() {
463 StopInfoSP stop_info_sp = GetPrivateStopInfo();
465 if (m_trap_exceptions) {
466 if ((m_cxx_language_runtime &&
467 m_cxx_language_runtime->ExceptionBreakpointsExplainStop(
469 (m_objc_language_runtime &&
470 m_objc_language_runtime->ExceptionBreakpointsExplainStop(
472 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
474 log->Printf("ThreadPlanCallFunction::BreakpointsExplainStop - Hit an "
475 "exception breakpoint, setting plan complete.");
477 SetPlanComplete(false);
479 // If the user has set the ObjC language breakpoint, it would normally
480 // get priority over our internal catcher breakpoint, but in this case we
481 // can't let that happen, so force the ShouldStop here.
482 stop_info_sp->OverrideShouldStop(true);
490 void ThreadPlanCallFunction::SetStopOthers(bool new_value) {
491 m_subplan_sp->SetStopOthers(new_value);
494 bool ThreadPlanCallFunction::RestoreThreadState() {
495 return GetThread().RestoreThreadStateFromCheckpoint(m_stored_thread_state);
498 void ThreadPlanCallFunction::SetReturnValue() {
499 ProcessSP process_sp(m_thread.GetProcess());
500 const ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
501 if (abi && m_return_type.IsValid()) {
502 const bool persistent = false;
504 abi->GetReturnValueObject(m_thread, m_return_type, persistent);