1 //===-- ThreadPlanCallFunction.cpp ------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project 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/Module.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Target/ABI.h"
21 #include "lldb/Target/LanguageRuntime.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StopInfo.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlanRunToAddress.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/Stream.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 //----------------------------------------------------------------------
35 // ThreadPlanCallFunction: Plan to call a single function
36 //----------------------------------------------------------------------
37 bool ThreadPlanCallFunction::ConstructorSetup(
38     Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr,
39     lldb::addr_t &function_load_addr) {
40   SetIsMasterPlan(true);
41   SetOkayToDiscard(false);
42   SetPrivate(true);
43 
44   ProcessSP process_sp(thread.GetProcess());
45   if (!process_sp)
46     return false;
47 
48   abi = process_sp->GetABI().get();
49 
50   if (!abi)
51     return false;
52 
53   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
54 
55   SetBreakpoints();
56 
57   m_function_sp = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();
58   // If we can't read memory at the point of the process where we are planning
59   // to put our function, we're not going to get any further...
60   Status error;
61   process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error);
62   if (!error.Success()) {
63     m_constructor_errors.Printf(
64         "Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".",
65         m_function_sp);
66     if (log)
67       log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
68                   m_constructor_errors.GetData());
69     return false;
70   }
71 
72   Module *exe_module = GetTarget().GetExecutableModulePointer();
73 
74   if (exe_module == nullptr) {
75     m_constructor_errors.Printf(
76         "Can't execute code without an executable module.");
77     if (log)
78       log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
79                   m_constructor_errors.GetData());
80     return false;
81   } else {
82     ObjectFile *objectFile = exe_module->GetObjectFile();
83     if (!objectFile) {
84       m_constructor_errors.Printf(
85           "Could not find object file for module \"%s\".",
86           exe_module->GetFileSpec().GetFilename().AsCString());
87 
88       if (log)
89         log->Printf("ThreadPlanCallFunction(%p): %s.",
90                     static_cast<void *>(this), m_constructor_errors.GetData());
91       return false;
92     }
93 
94     m_start_addr = objectFile->GetEntryPointAddress();
95     if (!m_start_addr.IsValid()) {
96       m_constructor_errors.Printf(
97           "Could not find entry point address for executable module \"%s\".",
98           exe_module->GetFileSpec().GetFilename().AsCString());
99       if (log)
100         log->Printf("ThreadPlanCallFunction(%p): %s.",
101                     static_cast<void *>(this), m_constructor_errors.GetData());
102       return false;
103     }
104   }
105 
106   start_load_addr = m_start_addr.GetLoadAddress(&GetTarget());
107 
108   // Checkpoint the thread state so we can restore it later.
109   if (log && log->GetVerbose())
110     ReportRegisterState("About to checkpoint thread before function call.  "
111                         "Original register state was:");
112 
113   if (!thread.CheckpointThreadState(m_stored_thread_state)) {
114     m_constructor_errors.Printf("Setting up ThreadPlanCallFunction, failed to "
115                                 "checkpoint thread state.");
116     if (log)
117       log->Printf("ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),
118                   m_constructor_errors.GetData());
119     return false;
120   }
121   function_load_addr = m_function_addr.GetLoadAddress(&GetTarget());
122 
123   return true;
124 }
125 
126 ThreadPlanCallFunction::ThreadPlanCallFunction(
127     Thread &thread, const Address &function, const CompilerType &return_type,
128     llvm::ArrayRef<addr_t> args, const EvaluateExpressionOptions &options)
129     : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
130                  eVoteNoOpinion, eVoteNoOpinion),
131       m_valid(false), m_stop_other_threads(options.GetStopOthers()),
132       m_unwind_on_error(options.DoesUnwindOnError()),
133       m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
134       m_debug_execution(options.GetDebug()),
135       m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
136       m_function_sp(0), m_takedown_done(false),
137       m_should_clear_objc_exception_bp(false),
138       m_should_clear_cxx_exception_bp(false),
139       m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(return_type) {
140   lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;
141   lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;
142   ABI *abi = nullptr;
143 
144   if (!ConstructorSetup(thread, abi, start_load_addr, function_load_addr))
145     return;
146 
147   if (!abi->PrepareTrivialCall(thread, m_function_sp, function_load_addr,
148                                start_load_addr, args))
149     return;
150 
151   ReportRegisterState("Function call was set up.  Register state was:");
152 
153   m_valid = true;
154 }
155 
156 ThreadPlanCallFunction::ThreadPlanCallFunction(
157     Thread &thread, const Address &function,
158     const EvaluateExpressionOptions &options)
159     : ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,
160                  eVoteNoOpinion, eVoteNoOpinion),
161       m_valid(false), m_stop_other_threads(options.GetStopOthers()),
162       m_unwind_on_error(options.DoesUnwindOnError()),
163       m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),
164       m_debug_execution(options.GetDebug()),
165       m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),
166       m_function_sp(0), m_takedown_done(false),
167       m_should_clear_objc_exception_bp(false),
168       m_should_clear_cxx_exception_bp(false),
169       m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(CompilerType()) {}
170 
171 ThreadPlanCallFunction::~ThreadPlanCallFunction() {
172   DoTakedown(PlanSucceeded());
173 }
174 
175 void ThreadPlanCallFunction::ReportRegisterState(const char *message) {
176   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
177   if (log && log->GetVerbose()) {
178     StreamString strm;
179     RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
180 
181     log->PutCString(message);
182 
183     RegisterValue reg_value;
184 
185     for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();
186          reg_idx < num_registers; ++reg_idx) {
187       const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
188       if (reg_ctx->ReadRegister(reg_info, reg_value)) {
189         reg_value.Dump(&strm, reg_info, true, false, eFormatDefault);
190         strm.EOL();
191       }
192     }
193     log->PutString(strm.GetString());
194   }
195 }
196 
197 void ThreadPlanCallFunction::DoTakedown(bool success) {
198   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
199 
200   if (!m_valid) {
201     // Don't call DoTakedown if we were never valid to begin with.
202     if (log)
203       log->Printf("ThreadPlanCallFunction(%p): Log called on "
204                   "ThreadPlanCallFunction that was never valid.",
205                   static_cast<void *>(this));
206     return;
207   }
208 
209   if (!m_takedown_done) {
210     if (success) {
211       SetReturnValue();
212     }
213     if (log)
214       log->Printf("ThreadPlanCallFunction(%p): DoTakedown called for thread "
215                   "0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
216                   static_cast<void *>(this), m_thread.GetID(), m_valid,
217                   IsPlanComplete());
218     m_takedown_done = true;
219     m_stop_address =
220         m_thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();
221     m_real_stop_info_sp = GetPrivateStopInfo();
222     if (!m_thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state)) {
223       if (log)
224         log->Printf("ThreadPlanCallFunction(%p): DoTakedown failed to restore "
225                     "register state",
226                     static_cast<void *>(this));
227     }
228     SetPlanComplete(success);
229     ClearBreakpoints();
230     if (log && log->GetVerbose())
231       ReportRegisterState("Restoring thread state after function call.  "
232                           "Restored register state:");
233   } else {
234     if (log)
235       log->Printf("ThreadPlanCallFunction(%p): DoTakedown called as no-op for "
236                   "thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",
237                   static_cast<void *>(this), m_thread.GetID(), m_valid,
238                   IsPlanComplete());
239   }
240 }
241 
242 void ThreadPlanCallFunction::WillPop() { DoTakedown(PlanSucceeded()); }
243 
244 void ThreadPlanCallFunction::GetDescription(Stream *s, DescriptionLevel level) {
245   if (level == eDescriptionLevelBrief) {
246     s->Printf("Function call thread plan");
247   } else {
248     TargetSP target_sp(m_thread.CalculateTarget());
249     s->Printf("Thread plan to call 0x%" PRIx64,
250               m_function_addr.GetLoadAddress(target_sp.get()));
251   }
252 }
253 
254 bool ThreadPlanCallFunction::ValidatePlan(Stream *error) {
255   if (!m_valid) {
256     if (error) {
257       if (m_constructor_errors.GetSize() > 0)
258         error->PutCString(m_constructor_errors.GetString());
259       else
260         error->PutCString("Unknown error");
261     }
262     return false;
263   }
264 
265   return true;
266 }
267 
268 Vote ThreadPlanCallFunction::ShouldReportStop(Event *event_ptr) {
269   if (m_takedown_done || IsPlanComplete())
270     return eVoteYes;
271   else
272     return ThreadPlan::ShouldReportStop(event_ptr);
273 }
274 
275 bool ThreadPlanCallFunction::DoPlanExplainsStop(Event *event_ptr) {
276   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
277                                                   LIBLLDB_LOG_PROCESS));
278   m_real_stop_info_sp = GetPrivateStopInfo();
279 
280   // If our subplan knows why we stopped, even if it's done (which would
281   // forward the question to us) we answer yes.
282   if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr)) {
283     SetPlanComplete();
284     return true;
285   }
286 
287   // Check if the breakpoint is one of ours.
288 
289   StopReason stop_reason;
290   if (!m_real_stop_info_sp)
291     stop_reason = eStopReasonNone;
292   else
293     stop_reason = m_real_stop_info_sp->GetStopReason();
294   if (log)
295     log->Printf(
296         "ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - %s.",
297         Thread::StopReasonAsCString(stop_reason));
298 
299   if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())
300     return true;
301 
302   // One more quirk here.  If this event was from Halt interrupting the target,
303   // then we should not consider ourselves complete.  Return true to
304   // acknowledge the stop.
305   if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
306     if (log)
307       log->Printf("ThreadPlanCallFunction::PlanExplainsStop: The event is an "
308                   "Interrupt, returning true.");
309     return true;
310   }
311   // We control breakpoints separately from other "stop reasons."  So first,
312   // check the case where we stopped for an internal breakpoint, in that case,
313   // continue on. If it is not an internal breakpoint, consult
314   // m_ignore_breakpoints.
315 
316   if (stop_reason == eStopReasonBreakpoint) {
317     ProcessSP process_sp(m_thread.CalculateProcess());
318     uint64_t break_site_id = m_real_stop_info_sp->GetValue();
319     BreakpointSiteSP bp_site_sp;
320     if (process_sp)
321       bp_site_sp = process_sp->GetBreakpointSiteList().FindByID(break_site_id);
322     if (bp_site_sp) {
323       uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
324       bool is_internal = true;
325       for (uint32_t i = 0; i < num_owners; i++) {
326         Breakpoint &bp = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
327         if (log)
328           log->Printf("ThreadPlanCallFunction::PlanExplainsStop: hit "
329                       "breakpoint %d while calling function",
330                       bp.GetID());
331 
332         if (!bp.IsInternal()) {
333           is_internal = false;
334           break;
335         }
336       }
337       if (is_internal) {
338         if (log)
339           log->Printf("ThreadPlanCallFunction::PlanExplainsStop hit an "
340                       "internal breakpoint, not stopping.");
341         return false;
342       }
343     }
344 
345     if (m_ignore_breakpoints) {
346       if (log)
347         log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are ignoring "
348                     "breakpoints, overriding breakpoint stop info ShouldStop, "
349                     "returning true");
350       m_real_stop_info_sp->OverrideShouldStop(false);
351       return true;
352     } else {
353       if (log)
354         log->Printf("ThreadPlanCallFunction::PlanExplainsStop: we are not "
355                     "ignoring breakpoints, overriding breakpoint stop info "
356                     "ShouldStop, returning true");
357       m_real_stop_info_sp->OverrideShouldStop(true);
358       return false;
359     }
360   } else if (!m_unwind_on_error) {
361     // If we don't want to discard this plan, than any stop we don't understand
362     // should be propagated up the stack.
363     return false;
364   } else {
365     // If the subplan is running, any crashes are attributable to us. If we
366     // want to discard the plan, then we say we explain the stop but if we are
367     // going to be discarded, let whoever is above us explain the stop. But
368     // don't discard the plan if the stop would restart itself (for instance if
369     // it is a signal that is set not to stop.  Check that here first.  We just
370     // say we explain the stop but aren't done and everything will continue on
371     // from there.
372 
373     if (m_real_stop_info_sp &&
374         m_real_stop_info_sp->ShouldStopSynchronous(event_ptr)) {
375       SetPlanComplete(false);
376       return m_subplan_sp ? m_unwind_on_error : false;
377     } else
378       return true;
379   }
380 }
381 
382 bool ThreadPlanCallFunction::ShouldStop(Event *event_ptr) {
383   // We do some computation in DoPlanExplainsStop that may or may not set the
384   // plan as complete. We need to do that here to make sure our state is
385   // correct.
386   DoPlanExplainsStop(event_ptr);
387 
388   if (IsPlanComplete()) {
389     ReportRegisterState("Function completed.  Register state was:");
390     return true;
391   } else {
392     return false;
393   }
394 }
395 
396 bool ThreadPlanCallFunction::StopOthers() { return m_stop_other_threads; }
397 
398 StateType ThreadPlanCallFunction::GetPlanRunState() { return eStateRunning; }
399 
400 void ThreadPlanCallFunction::DidPush() {
401   //#define SINGLE_STEP_EXPRESSIONS
402 
403   // Now set the thread state to "no reason" so we don't run with whatever
404   // signal was outstanding... Wait till the plan is pushed so we aren't
405   // changing the stop info till we're about to run.
406 
407   GetThread().SetStopInfoToNothing();
408 
409 #ifndef SINGLE_STEP_EXPRESSIONS
410   m_subplan_sp.reset(
411       new ThreadPlanRunToAddress(m_thread, m_start_addr, m_stop_other_threads));
412 
413   m_thread.QueueThreadPlan(m_subplan_sp, false);
414   m_subplan_sp->SetPrivate(true);
415 #endif
416 }
417 
418 bool ThreadPlanCallFunction::WillStop() { return true; }
419 
420 bool ThreadPlanCallFunction::MischiefManaged() {
421   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
422 
423   if (IsPlanComplete()) {
424     if (log)
425       log->Printf("ThreadPlanCallFunction(%p): Completed call function plan.",
426                   static_cast<void *>(this));
427 
428     ThreadPlan::MischiefManaged();
429     return true;
430   } else {
431     return false;
432   }
433 }
434 
435 void ThreadPlanCallFunction::SetBreakpoints() {
436   ProcessSP process_sp(m_thread.CalculateProcess());
437   if (m_trap_exceptions && process_sp) {
438     m_cxx_language_runtime =
439         process_sp->GetLanguageRuntime(eLanguageTypeC_plus_plus);
440     m_objc_language_runtime = process_sp->GetLanguageRuntime(eLanguageTypeObjC);
441 
442     if (m_cxx_language_runtime) {
443       m_should_clear_cxx_exception_bp =
444           !m_cxx_language_runtime->ExceptionBreakpointsAreSet();
445       m_cxx_language_runtime->SetExceptionBreakpoints();
446     }
447     if (m_objc_language_runtime) {
448       m_should_clear_objc_exception_bp =
449           !m_objc_language_runtime->ExceptionBreakpointsAreSet();
450       m_objc_language_runtime->SetExceptionBreakpoints();
451     }
452   }
453 }
454 
455 void ThreadPlanCallFunction::ClearBreakpoints() {
456   if (m_trap_exceptions) {
457     if (m_cxx_language_runtime && m_should_clear_cxx_exception_bp)
458       m_cxx_language_runtime->ClearExceptionBreakpoints();
459     if (m_objc_language_runtime && m_should_clear_objc_exception_bp)
460       m_objc_language_runtime->ClearExceptionBreakpoints();
461   }
462 }
463 
464 bool ThreadPlanCallFunction::BreakpointsExplainStop() {
465   StopInfoSP stop_info_sp = GetPrivateStopInfo();
466 
467   if (m_trap_exceptions) {
468     if ((m_cxx_language_runtime &&
469          m_cxx_language_runtime->ExceptionBreakpointsExplainStop(
470              stop_info_sp)) ||
471         (m_objc_language_runtime &&
472          m_objc_language_runtime->ExceptionBreakpointsExplainStop(
473              stop_info_sp))) {
474       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP));
475       if (log)
476         log->Printf("ThreadPlanCallFunction::BreakpointsExplainStop - Hit an "
477                     "exception breakpoint, setting plan complete.");
478 
479       SetPlanComplete(false);
480 
481       // If the user has set the ObjC language breakpoint, it would normally
482       // get priority over our internal catcher breakpoint, but in this case we
483       // can't let that happen, so force the ShouldStop here.
484       stop_info_sp->OverrideShouldStop(true);
485       return true;
486     }
487   }
488 
489   return false;
490 }
491 
492 void ThreadPlanCallFunction::SetStopOthers(bool new_value) {
493   m_subplan_sp->SetStopOthers(new_value);
494 }
495 
496 bool ThreadPlanCallFunction::RestoreThreadState() {
497   return GetThread().RestoreThreadStateFromCheckpoint(m_stored_thread_state);
498 }
499 
500 void ThreadPlanCallFunction::SetReturnValue() {
501   ProcessSP process_sp(m_thread.GetProcess());
502   const ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
503   if (abi && m_return_type.IsValid()) {
504     const bool persistent = false;
505     m_return_valobj_sp =
506         abi->GetReturnValueObject(m_thread, m_return_type, persistent);
507   }
508 }
509