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 #include "lldb/Target/ThreadPlanCallFunction.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 #include "llvm/Support/MachO.h"
16 // Project includes
17 #include "lldb/lldb-private-log.h"
18 #include "lldb/Breakpoint/Breakpoint.h"
19 #include "lldb/Breakpoint/BreakpointLocation.h"
20 #include "lldb/Core/Address.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/Stream.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"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 //----------------------------------------------------------------------
35 // ThreadPlanCallFunction: Plan to call a single function
36 //----------------------------------------------------------------------
37 
38 ThreadPlanCallFunction::ThreadPlanCallFunction (Thread &thread,
39                                                 Address &function,
40                                                 lldb::addr_t arg,
41                                                 bool stop_other_threads,
42                                                 bool discard_on_error,
43                                                 lldb::addr_t *this_arg,
44                                                 lldb::addr_t *cmd_arg) :
45     ThreadPlan (ThreadPlan::eKindCallFunction, "Call function plan", thread, eVoteNoOpinion, eVoteNoOpinion),
46     m_valid (false),
47     m_stop_other_threads (stop_other_threads),
48     m_arg_addr (arg),
49     m_args (NULL),
50     m_process (thread.GetProcess()),
51     m_thread (thread),
52     m_takedown_done (false)
53 {
54     SetOkayToDiscard (discard_on_error);
55 
56     Process& process = thread.GetProcess();
57     Target& target = process.GetTarget();
58     const ABI *abi = process.GetABI();
59 
60     if (!abi)
61         return;
62 
63     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
64 
65     SetBreakpoints();
66 
67     lldb::addr_t spBelowRedZone = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();
68 
69     SymbolContextList contexts;
70     SymbolContext context;
71     ModuleSP executableModuleSP (target.GetExecutableModule());
72 
73     if (!executableModuleSP ||
74         !executableModuleSP->FindSymbolsWithNameAndType(ConstString ("start"), eSymbolTypeCode, contexts))
75         return;
76 
77     contexts.GetContextAtIndex(0, context);
78 
79     m_start_addr = context.symbol->GetValue();
80     lldb::addr_t StartLoadAddr = m_start_addr.GetLoadAddress(&target);
81 
82     // Checkpoint the thread state so we can restore it later.
83     if (log && log->GetVerbose())
84         ReportRegisterState ("About to checkpoint thread before function call.  Original register state was:");
85 
86     if (!thread.CheckpointThreadState (m_stored_thread_state))
87     {
88         if (log)
89             log->Printf ("Setting up ThreadPlanCallFunction, failed to checkpoint thread state.");
90         return;
91     }
92     // Now set the thread state to "no reason" so we don't run with whatever signal was outstanding...
93     thread.SetStopInfoToNothing();
94 
95     m_function_addr = function;
96     lldb::addr_t FunctionLoadAddr = m_function_addr.GetLoadAddress(&target);
97 
98     if (!abi->PrepareTrivialCall(thread,
99                                  spBelowRedZone,
100                                  FunctionLoadAddr,
101                                  StartLoadAddr,
102                                  m_arg_addr,
103                                  this_arg,
104                                  cmd_arg))
105         return;
106 
107     ReportRegisterState ("Function call was set up.  Register state was:");
108 
109     m_valid = true;
110 }
111 
112 ThreadPlanCallFunction::~ThreadPlanCallFunction ()
113 {
114 }
115 
116 void
117 ThreadPlanCallFunction::ReportRegisterState (const char *message)
118 {
119     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
120     if (log)
121     {
122         RegisterContext *reg_ctx = m_thread.GetRegisterContext().get();
123 
124         log->PutCString(message);
125 
126         for (uint32_t register_index = 0, num_registers = reg_ctx->GetRegisterCount();
127              register_index < num_registers;
128              ++register_index)
129         {
130             const char *register_name = reg_ctx->GetRegisterName(register_index);
131             uint64_t register_value = reg_ctx->ReadRegisterAsUnsigned(register_index, LLDB_INVALID_ADDRESS);
132 
133             log->Printf("  %s = 0x%llx", register_name, register_value);
134         }
135     }
136 }
137 
138 void
139 ThreadPlanCallFunction::DoTakedown ()
140 {
141     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
142     if (!m_takedown_done)
143     {
144         if (log)
145             log->Printf ("DoTakedown called for thread 0x%4.4x, m_valid: %d complete: %d.\n", m_thread.GetID(), m_valid, IsPlanComplete());
146         m_takedown_done = true;
147         m_thread.RestoreThreadStateFromCheckpoint(m_stored_thread_state);
148         SetPlanComplete();
149         ClearBreakpoints();
150         if (log && log->GetVerbose())
151             ReportRegisterState ("Restoring thread state after function call.  Restored register state:");
152     }
153     else
154     {
155         if (log)
156             log->Printf ("DoTakedown called as no-op for thread 0x%4.4x, m_valid: %d complete: %d.\n", m_thread.GetID(), m_valid, IsPlanComplete());
157     }
158 }
159 
160 void
161 ThreadPlanCallFunction::WillPop ()
162 {
163     DoTakedown();
164 }
165 
166 void
167 ThreadPlanCallFunction::GetDescription (Stream *s, lldb::DescriptionLevel level)
168 {
169     if (level == lldb::eDescriptionLevelBrief)
170     {
171         s->Printf("Function call thread plan");
172     }
173     else
174     {
175         if (m_args)
176             s->Printf("Thread plan to call 0x%llx with parsed arguments", m_function_addr.GetLoadAddress(&m_process.GetTarget()), m_arg_addr);
177         else
178             s->Printf("Thread plan to call 0x%llx void * argument at: 0x%llx", m_function_addr.GetLoadAddress(&m_process.GetTarget()), m_arg_addr);
179     }
180 }
181 
182 bool
183 ThreadPlanCallFunction::ValidatePlan (Stream *error)
184 {
185     if (!m_valid)
186         return false;
187 
188     return true;
189 }
190 
191 bool
192 ThreadPlanCallFunction::PlanExplainsStop ()
193 {
194     // If our subplan knows why we stopped, even if it's done (which would forward the question to us)
195     // we answer yes.
196     if(m_subplan_sp.get() != NULL && m_subplan_sp->PlanExplainsStop())
197         return true;
198 
199     // Check if the breakpoint is one of ours.
200 
201     if (BreakpointsExplainStop())
202         return true;
203 
204     // If we don't want to discard this plan, than any stop we don't understand should be propagated up the stack.
205     if (!OkayToDiscard())
206         return false;
207 
208     // Otherwise, check the case where we stopped for an internal breakpoint, in that case, continue on.
209     // If it is not an internal breakpoint, consult OkayToDiscard.
210     lldb::StopInfoSP stop_info_sp = GetPrivateStopReason();
211 
212     if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint)
213     {
214         uint64_t break_site_id = stop_info_sp->GetValue();
215         lldb::BreakpointSiteSP bp_site_sp = m_thread.GetProcess().GetBreakpointSiteList().FindByID(break_site_id);
216         if (bp_site_sp)
217         {
218             uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
219             bool is_internal = true;
220             for (uint32_t i = 0; i < num_owners; i++)
221             {
222                 Breakpoint &bp = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
223 
224                 if (!bp.IsInternal())
225                 {
226                     is_internal = false;
227                     break;
228                 }
229             }
230             if (is_internal)
231                 return false;
232         }
233 
234         return OkayToDiscard();
235     }
236     else
237     {
238         // If the subplan is running, any crashes are attributable to us.
239         return (m_subplan_sp.get() != NULL);
240     }
241 }
242 
243 bool
244 ThreadPlanCallFunction::ShouldStop (Event *event_ptr)
245 {
246     if (PlanExplainsStop())
247     {
248         ReportRegisterState ("Function completed.  Register state was:");
249 
250         DoTakedown();
251 
252         return true;
253     }
254     else
255     {
256         return false;
257     }
258 }
259 
260 bool
261 ThreadPlanCallFunction::StopOthers ()
262 {
263     return m_stop_other_threads;
264 }
265 
266 void
267 ThreadPlanCallFunction::SetStopOthers (bool new_value)
268 {
269     if (m_subplan_sp)
270     {
271         ThreadPlanRunToAddress *address_plan = static_cast<ThreadPlanRunToAddress *>(m_subplan_sp.get());
272         address_plan->SetStopOthers(new_value);
273     }
274     m_stop_other_threads = new_value;
275 }
276 
277 StateType
278 ThreadPlanCallFunction::GetPlanRunState ()
279 {
280     return eStateRunning;
281 }
282 
283 void
284 ThreadPlanCallFunction::DidPush ()
285 {
286 //#define SINGLE_STEP_EXPRESSIONS
287 
288 #ifndef SINGLE_STEP_EXPRESSIONS
289     m_subplan_sp.reset(new ThreadPlanRunToAddress(m_thread, m_start_addr, m_stop_other_threads));
290 
291     m_thread.QueueThreadPlan(m_subplan_sp, false);
292     m_subplan_sp->SetPrivate (true);
293 #endif
294 }
295 
296 bool
297 ThreadPlanCallFunction::WillStop ()
298 {
299     return true;
300 }
301 
302 bool
303 ThreadPlanCallFunction::MischiefManaged ()
304 {
305     if (IsPlanComplete())
306     {
307         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
308 
309         if (log)
310             log->Printf("Completed call function plan.");
311 
312         ThreadPlan::MischiefManaged ();
313         return true;
314     }
315     else
316     {
317         return false;
318     }
319 }
320 
321 void
322 ThreadPlanCallFunction::SetBreakpoints ()
323 {
324     m_cxx_language_runtime = m_process.GetLanguageRuntime(eLanguageTypeC_plus_plus);
325     m_objc_language_runtime = m_process.GetLanguageRuntime(eLanguageTypeObjC);
326 
327     if (m_cxx_language_runtime)
328         m_cxx_language_runtime->SetExceptionBreakpoints();
329     if (m_objc_language_runtime)
330         m_objc_language_runtime->SetExceptionBreakpoints();
331 }
332 
333 void
334 ThreadPlanCallFunction::ClearBreakpoints ()
335 {
336     if (m_cxx_language_runtime)
337         m_cxx_language_runtime->ClearExceptionBreakpoints();
338     if (m_objc_language_runtime)
339         m_objc_language_runtime->ClearExceptionBreakpoints();
340 }
341 
342 bool
343 ThreadPlanCallFunction::BreakpointsExplainStop()
344 {
345     lldb::StopInfoSP stop_info_sp = GetPrivateStopReason();
346 
347     if (m_cxx_language_runtime &&
348         m_cxx_language_runtime->ExceptionBreakpointsExplainStop(stop_info_sp))
349         return true;
350 
351     if (m_objc_language_runtime &&
352         m_objc_language_runtime->ExceptionBreakpointsExplainStop(stop_info_sp))
353         return true;
354 
355     return false;
356 }
357