1 //===-- ThreadPlanStepInRange.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/ThreadPlanStepInRange.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 
17 #include "lldb/lldb-private-log.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/Stream.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/RegisterContext.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlanStepOut.h"
28 #include "lldb/Target/ThreadPlanStepThrough.h"
29 #include "lldb/Core/RegularExpression.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 uint32_t ThreadPlanStepInRange::s_default_flag_values = ThreadPlanShouldStopHere::eStepInAvoidNoDebug;
35 
36 //----------------------------------------------------------------------
37 // ThreadPlanStepInRange: Step through a stack range, either stepping over or into
38 // based on the value of \a type.
39 //----------------------------------------------------------------------
40 
41 ThreadPlanStepInRange::ThreadPlanStepInRange
42 (
43     Thread &thread,
44     const AddressRange &range,
45     const SymbolContext &addr_context,
46     lldb::RunMode stop_others,
47     LazyBool step_in_avoids_code_without_debug_info,
48     LazyBool step_out_avoids_code_without_debug_info
49 ) :
50     ThreadPlanStepRange (ThreadPlan::eKindStepInRange, "Step Range stepping in", thread, range, addr_context, stop_others),
51     ThreadPlanShouldStopHere (this),
52     m_step_past_prologue (true),
53     m_virtual_step (false)
54 {
55     SetCallbacks();
56     SetFlagsToDefault ();
57     SetupAvoidNoDebug(step_in_avoids_code_without_debug_info, step_out_avoids_code_without_debug_info);
58 }
59 
60 ThreadPlanStepInRange::ThreadPlanStepInRange
61 (
62     Thread &thread,
63     const AddressRange &range,
64     const SymbolContext &addr_context,
65     const char *step_into_target,
66     lldb::RunMode stop_others,
67     LazyBool step_in_avoids_code_without_debug_info,
68     LazyBool step_out_avoids_code_without_debug_info
69 ) :
70     ThreadPlanStepRange (ThreadPlan::eKindStepInRange, "Step Range stepping in", thread, range, addr_context, stop_others),
71     ThreadPlanShouldStopHere (this),
72     m_step_past_prologue (true),
73     m_virtual_step (false),
74     m_step_into_target (step_into_target)
75 {
76     SetCallbacks();
77     SetFlagsToDefault ();
78     SetupAvoidNoDebug(step_in_avoids_code_without_debug_info, step_out_avoids_code_without_debug_info);
79 }
80 
81 ThreadPlanStepInRange::~ThreadPlanStepInRange ()
82 {
83 }
84 
85 void
86 ThreadPlanStepInRange::SetupAvoidNoDebug(LazyBool step_in_avoids_code_without_debug_info,
87                                          LazyBool step_out_avoids_code_without_debug_info)
88 {
89     bool avoid_nodebug = true;
90 
91     switch (step_in_avoids_code_without_debug_info)
92     {
93         case eLazyBoolYes:
94             avoid_nodebug = true;
95             break;
96         case eLazyBoolNo:
97             avoid_nodebug = false;
98             break;
99         case eLazyBoolCalculate:
100             avoid_nodebug = m_thread.GetStepInAvoidsNoDebug();
101             break;
102     }
103     if (avoid_nodebug)
104         GetFlags().Set (ThreadPlanShouldStopHere::eStepInAvoidNoDebug);
105     else
106         GetFlags().Clear (ThreadPlanShouldStopHere::eStepInAvoidNoDebug);
107 
108     avoid_nodebug = true;
109     switch (step_out_avoids_code_without_debug_info)
110     {
111         case eLazyBoolYes:
112             avoid_nodebug = true;
113             break;
114         case eLazyBoolNo:
115             avoid_nodebug = false;
116             break;
117         case eLazyBoolCalculate:
118             avoid_nodebug = m_thread.GetStepOutAvoidsNoDebug();
119             break;
120     }
121     if (avoid_nodebug)
122         GetFlags().Set (ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
123     else
124         GetFlags().Clear (ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
125 }
126 
127 void
128 ThreadPlanStepInRange::GetDescription (Stream *s, lldb::DescriptionLevel level)
129 {
130     if (level == lldb::eDescriptionLevelBrief)
131         s->Printf("step in");
132     else
133     {
134         s->Printf ("Stepping through range (stepping into functions): ");
135         DumpRanges(s);
136         const char *step_into_target = m_step_into_target.AsCString();
137         if (step_into_target && step_into_target[0] != '\0')
138             s->Printf (" targeting %s.", m_step_into_target.AsCString());
139         else
140             s->PutChar('.');
141     }
142 }
143 
144 bool
145 ThreadPlanStepInRange::ShouldStop (Event *event_ptr)
146 {
147     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
148 
149     if (log)
150     {
151         StreamString s;
152         s.Address (m_thread.GetRegisterContext()->GetPC(),
153                    m_thread.CalculateTarget()->GetArchitecture().GetAddressByteSize());
154         log->Printf("ThreadPlanStepInRange reached %s.", s.GetData());
155     }
156 
157     if (IsPlanComplete())
158         return true;
159 
160     m_no_more_plans = false;
161     if (m_sub_plan_sp && m_sub_plan_sp->IsPlanComplete())
162     {
163         if (!m_sub_plan_sp->PlanSucceeded())
164         {
165             SetPlanComplete();
166             m_no_more_plans = true;
167             return true;
168         }
169         else
170             m_sub_plan_sp.reset();
171     }
172 
173     if (m_virtual_step)
174     {
175         // If we've just completed a virtual step, all we need to do is check for a ShouldStopHere plan, and otherwise
176         // we're done.
177         // FIXME - This can be both a step in and a step out.  Probably should record which in the m_virtual_step.
178         m_sub_plan_sp = CheckShouldStopHereAndQueueStepOut(eFrameCompareYounger);
179     }
180     else
181     {
182         // Stepping through should be done running other threads in general, since we're setting a breakpoint and
183         // continuing.  So only stop others if we are explicitly told to do so.
184 
185         bool stop_others;
186         if (m_stop_others == lldb::eOnlyThisThread)
187             stop_others = true;
188         else
189             stop_others = false;
190 
191         FrameComparison frame_order = CompareCurrentFrameToStartFrame();
192 
193         if (frame_order == eFrameCompareOlder || frame_order == eFrameCompareSameParent)
194         {
195             // If we're in an older frame then we should stop.
196             //
197             // A caveat to this is if we think the frame is older but we're actually in a trampoline.
198             // I'm going to make the assumption that you wouldn't RETURN to a trampoline.  So if we are
199             // in a trampoline we think the frame is older because the trampoline confused the backtracer.
200             m_sub_plan_sp = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);
201             if (!m_sub_plan_sp)
202             {
203                 // Otherwise check the ShouldStopHere for step out:
204                 m_sub_plan_sp = CheckShouldStopHereAndQueueStepOut(frame_order);
205                 if (log)
206                     log->Printf ("ShouldStopHere says we should step out of this frame.");
207             }
208             else if (log)
209             {
210                 log->Printf("Thought I stepped out, but in fact arrived at a trampoline.");
211             }
212 
213         }
214         else if (frame_order == eFrameCompareEqual && InSymbol())
215         {
216             // If we are not in a place we should step through, we're done.
217             // One tricky bit here is that some stubs don't push a frame, so we have to check
218             // both the case of a frame that is younger, or the same as this frame.
219             // However, if the frame is the same, and we are still in the symbol we started
220             // in, the we don't need to do this.  This first check isn't strictly necessary,
221             // but it is more efficient.
222 
223             // If we're still in the range, keep going, either by running to the next branch breakpoint, or by
224             // stepping.
225             if (InRange())
226             {
227                 SetNextBranchBreakpoint();
228                 return false;
229             }
230 
231             SetPlanComplete();
232             m_no_more_plans = true;
233             return true;
234         }
235 
236         // If we get to this point, we're not going to use a previously set "next branch" breakpoint, so delete it:
237         ClearNextBranchBreakpoint();
238 
239         // We may have set the plan up above in the FrameIsOlder section:
240 
241         if (!m_sub_plan_sp)
242             m_sub_plan_sp = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);
243 
244         if (log)
245         {
246             if (m_sub_plan_sp)
247                 log->Printf ("Found a step through plan: %s", m_sub_plan_sp->GetName());
248             else
249                 log->Printf ("No step through plan found.");
250         }
251 
252         // If not, give the "should_stop" callback a chance to push a plan to get us out of here.
253         // But only do that if we actually have stepped in.
254         if (!m_sub_plan_sp && frame_order == eFrameCompareYounger)
255             m_sub_plan_sp = CheckShouldStopHereAndQueueStepOut(frame_order);
256 
257         // If we've stepped in and we are going to stop here, check to see if we were asked to
258         // run past the prologue, and if so do that.
259 
260         if (!m_sub_plan_sp && frame_order == eFrameCompareYounger && m_step_past_prologue)
261         {
262             lldb::StackFrameSP curr_frame = m_thread.GetStackFrameAtIndex(0);
263             if (curr_frame)
264             {
265                 size_t bytes_to_skip = 0;
266                 lldb::addr_t curr_addr = m_thread.GetRegisterContext()->GetPC();
267                 Address func_start_address;
268 
269                 SymbolContext sc = curr_frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextSymbol);
270 
271                 if (sc.function)
272                 {
273                     func_start_address = sc.function->GetAddressRange().GetBaseAddress();
274                     if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))
275                         bytes_to_skip = sc.function->GetPrologueByteSize();
276                 }
277                 else if (sc.symbol)
278                 {
279                     func_start_address = sc.symbol->GetAddress();
280                     if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))
281                         bytes_to_skip = sc.symbol->GetPrologueByteSize();
282                 }
283 
284                 if (bytes_to_skip != 0)
285                 {
286                     func_start_address.Slide (bytes_to_skip);
287                     log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
288                     if (log)
289                         log->Printf ("Pushing past prologue ");
290 
291                     m_sub_plan_sp = m_thread.QueueThreadPlanForRunToAddress(false, func_start_address,true);
292                 }
293             }
294         }
295      }
296 
297      if (!m_sub_plan_sp)
298      {
299         m_no_more_plans = true;
300         SetPlanComplete();
301         return true;
302     }
303     else
304     {
305         m_no_more_plans = false;
306         return false;
307     }
308 }
309 
310 void
311 ThreadPlanStepInRange::SetAvoidRegexp(const char *name)
312 {
313     if (m_avoid_regexp_ap.get() == NULL)
314         m_avoid_regexp_ap.reset (new RegularExpression(name));
315 
316     m_avoid_regexp_ap->Compile (name);
317 }
318 
319 void
320 ThreadPlanStepInRange::SetDefaultFlagValue (uint32_t new_value)
321 {
322     // TODO: Should we test this for sanity?
323     ThreadPlanStepInRange::s_default_flag_values = new_value;
324 }
325 
326 bool
327 ThreadPlanStepInRange::FrameMatchesAvoidCriteria ()
328 {
329     StackFrame *frame = GetThread().GetStackFrameAtIndex(0).get();
330 
331     // Check the library list first, as that's cheapest:
332     bool libraries_say_avoid = false;
333 
334     FileSpecList libraries_to_avoid (GetThread().GetLibrariesToAvoid());
335     size_t num_libraries = libraries_to_avoid.GetSize();
336     if (num_libraries > 0)
337     {
338         SymbolContext sc(frame->GetSymbolContext(eSymbolContextModule));
339         FileSpec frame_library(sc.module_sp->GetFileSpec());
340 
341         if (frame_library)
342         {
343             for (size_t i = 0; i < num_libraries; i++)
344             {
345                 const FileSpec &file_spec(libraries_to_avoid.GetFileSpecAtIndex(i));
346                 if (FileSpec::Equal (file_spec, frame_library, false))
347                 {
348                     libraries_say_avoid = true;
349                     break;
350                 }
351             }
352         }
353     }
354     if (libraries_say_avoid)
355         return true;
356 
357     const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_ap.get();
358     if (avoid_regexp_to_use == NULL)
359         avoid_regexp_to_use = GetThread().GetSymbolsToAvoidRegexp();
360 
361     if (avoid_regexp_to_use != NULL)
362     {
363         SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);
364         if (sc.symbol != NULL)
365         {
366             const char *frame_function_name = sc.GetFunctionName().GetCString();
367             if (frame_function_name)
368             {
369                 size_t num_matches = 0;
370                 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
371                 if (log)
372                     num_matches = 1;
373 
374                 RegularExpression::Match regex_match(num_matches);
375 
376                 bool return_value = avoid_regexp_to_use->Execute(frame_function_name, &regex_match);
377                 if (return_value)
378                 {
379                     if (log)
380                     {
381                         std::string match;
382                         regex_match.GetMatchAtIndex(frame_function_name,0, match);
383                         log->Printf ("Stepping out of function \"%s\" because it matches the avoid regexp \"%s\" - match substring: \"%s\".",
384                                      frame_function_name,
385                                      avoid_regexp_to_use->GetText(),
386                                      match.c_str());
387                     }
388 
389                 }
390                 return return_value;
391             }
392         }
393     }
394     return false;
395 }
396 
397 bool
398 ThreadPlanStepInRange::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, FrameComparison operation, void *baton)
399 {
400     bool should_stop_here = true;
401     StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get();
402     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
403 
404     // First see if the ThreadPlanShouldStopHere default implementation thinks we should get out of here:
405     should_stop_here = ThreadPlanShouldStopHere::DefaultShouldStopHereCallback (current_plan, flags, operation, baton);
406     if (!should_stop_here)
407         return should_stop_here;
408 
409     if (should_stop_here && current_plan->GetKind() == eKindStepInRange && operation == eFrameCompareYounger)
410     {
411         ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);
412         if (step_in_range_plan->m_step_into_target)
413         {
414             SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);
415             if (sc.symbol != NULL)
416             {
417                 // First try an exact match, since that's cheap with ConstStrings.  Then do a strstr compare.
418                 if (step_in_range_plan->m_step_into_target == sc.GetFunctionName())
419                 {
420                     should_stop_here = true;
421                 }
422                 else
423                 {
424                     const char *target_name = step_in_range_plan->m_step_into_target.AsCString();
425                     const char *function_name = sc.GetFunctionName().AsCString();
426 
427                     if (function_name == NULL)
428                         should_stop_here = false;
429                     else if (strstr (function_name, target_name) == NULL)
430                         should_stop_here = false;
431                 }
432                 if (log && !should_stop_here)
433                     log->Printf("Stepping out of frame %s which did not match step into target %s.",
434                                 sc.GetFunctionName().AsCString(),
435                                 step_in_range_plan->m_step_into_target.AsCString());
436             }
437         }
438 
439         if (should_stop_here)
440         {
441             ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);
442             // Don't log the should_step_out here, it's easier to do it in FrameMatchesAvoidCriteria.
443             should_stop_here = !step_in_range_plan->FrameMatchesAvoidCriteria ();
444         }
445     }
446 
447     return should_stop_here;
448 }
449 
450 bool
451 ThreadPlanStepInRange::DoPlanExplainsStop (Event *event_ptr)
452 {
453     // We always explain a stop.  Either we've just done a single step, in which
454     // case we'll do our ordinary processing, or we stopped for some
455     // reason that isn't handled by our sub-plans, in which case we want to just stop right
456     // away.
457     // In general, we don't want to mark the plan as complete for unexplained stops.
458     // For instance, if you step in to some code with no debug info, so you step out
459     // and in the course of that hit a breakpoint, then you want to stop & show the user
460     // the breakpoint, but not unship the step in plan, since you still may want to complete that
461     // plan when you continue.  This is particularly true when doing "step in to target function."
462     // stepping.
463     //
464     // The only variation is that if we are doing "step by running to next branch" in which case
465     // if we hit our branch breakpoint we don't set the plan to complete.
466 
467     bool return_value;
468 
469     if (m_virtual_step)
470     {
471         return_value = true;
472     }
473     else
474     {
475         StopInfoSP stop_info_sp = GetPrivateStopInfo ();
476         if (stop_info_sp)
477         {
478             StopReason reason = stop_info_sp->GetStopReason();
479 
480             switch (reason)
481             {
482             case eStopReasonBreakpoint:
483                 if (NextRangeBreakpointExplainsStop(stop_info_sp))
484                 {
485                     return_value = true;
486                     break;
487                 }
488             case eStopReasonWatchpoint:
489             case eStopReasonSignal:
490             case eStopReasonException:
491             case eStopReasonExec:
492             case eStopReasonThreadExiting:
493                 {
494                     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
495                     if (log)
496                         log->PutCString ("ThreadPlanStepInRange got asked if it explains the stop for some reason other than step.");
497                 }
498                 return_value = false;
499                 break;
500             default:
501                 return_value = true;
502                 break;
503             }
504         }
505         else
506             return_value = true;
507     }
508 
509     return return_value;
510 }
511 
512 bool
513 ThreadPlanStepInRange::DoWillResume (lldb::StateType resume_state, bool current_plan)
514 {
515     if (resume_state == eStateStepping && current_plan)
516     {
517         // See if we are about to step over a virtual inlined call.
518         bool step_without_resume = m_thread.DecrementCurrentInlinedDepth();
519         if (step_without_resume)
520         {
521             Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
522             if (log)
523                 log->Printf ("ThreadPlanStepInRange::DoWillResume: returning false, inline_depth: %d",
524                              m_thread.GetCurrentInlinedDepth());
525             SetStopInfo(StopInfo::CreateStopReasonToTrace(m_thread));
526 
527             // FIXME: Maybe it would be better to create a InlineStep stop reason, but then
528             // the whole rest of the world would have to handle that stop reason.
529             m_virtual_step = true;
530         }
531         return !step_without_resume;
532     }
533     return true;
534 }
535 
536 bool
537 ThreadPlanStepInRange::IsVirtualStep()
538 {
539   return m_virtual_step;
540 }
541