1 //===-- ThreadPlanStepRange.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Target/ThreadPlanStepRange.h"
10 #include "lldb/Breakpoint/BreakpointLocation.h"
11 #include "lldb/Breakpoint/BreakpointSite.h"
12 #include "lldb/Core/Disassembler.h"
13 #include "lldb/Symbol/Function.h"
14 #include "lldb/Symbol/Symbol.h"
15 #include "lldb/Target/ExecutionContext.h"
16 #include "lldb/Target/Process.h"
17 #include "lldb/Target/RegisterContext.h"
18 #include "lldb/Target/StopInfo.h"
19 #include "lldb/Target/Target.h"
20 #include "lldb/Target/Thread.h"
21 #include "lldb/Target/ThreadPlanRunToAddress.h"
22 #include "lldb/Utility/Log.h"
23 #include "lldb/Utility/Stream.h"
24 
25 using namespace lldb;
26 using namespace lldb_private;
27 
28 // ThreadPlanStepRange: Step through a stack range, either stepping over or
29 // into based on the value of \a type.
30 
31 ThreadPlanStepRange::ThreadPlanStepRange(ThreadPlanKind kind, const char *name,
32                                          Thread &thread,
33                                          const AddressRange &range,
34                                          const SymbolContext &addr_context,
35                                          lldb::RunMode stop_others,
36                                          bool given_ranges_only)
37     : ThreadPlan(kind, name, thread, eVoteNoOpinion, eVoteNoOpinion),
38       m_addr_context(addr_context), m_address_ranges(),
39       m_stop_others(stop_others), m_stack_id(), m_parent_stack_id(),
40       m_no_more_plans(false), m_first_run_event(true), m_use_fast_step(false),
41       m_given_ranges_only(given_ranges_only) {
42   m_use_fast_step = GetTarget().GetUseFastStepping();
43   AddRange(range);
44   m_stack_id = thread.GetStackFrameAtIndex(0)->GetStackID();
45   StackFrameSP parent_stack = thread.GetStackFrameAtIndex(1);
46   if (parent_stack)
47     m_parent_stack_id = parent_stack->GetStackID();
48 }
49 
50 ThreadPlanStepRange::~ThreadPlanStepRange() { ClearNextBranchBreakpoint(); }
51 
52 void ThreadPlanStepRange::DidPush() {
53   // See if we can find a "next range" breakpoint:
54   SetNextBranchBreakpoint();
55 }
56 
57 bool ThreadPlanStepRange::ValidatePlan(Stream *error) {
58   if (m_could_not_resolve_hw_bp) {
59     if (error)
60       error->PutCString(
61           "Could not create hardware breakpoint for thread plan.");
62     return false;
63   }
64   return true;
65 }
66 
67 Vote ThreadPlanStepRange::ShouldReportStop(Event *event_ptr) {
68   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
69 
70   const Vote vote = IsPlanComplete() ? eVoteYes : eVoteNo;
71   LLDB_LOGF(log, "ThreadPlanStepRange::ShouldReportStop() returning vote %i\n",
72             vote);
73   return vote;
74 }
75 
76 void ThreadPlanStepRange::AddRange(const AddressRange &new_range) {
77   // For now I'm just adding the ranges.  At some point we may want to condense
78   // the ranges if they overlap, though I don't think it is likely to be very
79   // important.
80   m_address_ranges.push_back(new_range);
81 
82   // Fill the slot for this address range with an empty DisassemblerSP in the
83   // instruction ranges. I want the indices to match, but I don't want to do
84   // the work to disassemble this range if I don't step into it.
85   m_instruction_ranges.push_back(DisassemblerSP());
86 }
87 
88 void ThreadPlanStepRange::DumpRanges(Stream *s) {
89   Thread &thread = GetThread();
90   size_t num_ranges = m_address_ranges.size();
91   if (num_ranges == 1) {
92     m_address_ranges[0].Dump(s, &GetTarget(), Address::DumpStyleLoadAddress);
93   } else {
94     for (size_t i = 0; i < num_ranges; i++) {
95       s->Printf(" %" PRIu64 ": ", uint64_t(i));
96       m_address_ranges[i].Dump(s, &GetTarget(), Address::DumpStyleLoadAddress);
97     }
98   }
99 }
100 
101 bool ThreadPlanStepRange::InRange() {
102   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
103   bool ret_value = false;
104   Thread &thread = GetThread();
105   lldb::addr_t pc_load_addr = thread.GetRegisterContext()->GetPC();
106 
107   size_t num_ranges = m_address_ranges.size();
108   for (size_t i = 0; i < num_ranges; i++) {
109     ret_value =
110         m_address_ranges[i].ContainsLoadAddress(pc_load_addr, &GetTarget());
111     if (ret_value)
112       break;
113   }
114 
115   if (!ret_value && !m_given_ranges_only) {
116     // See if we've just stepped to another part of the same line number...
117     StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
118 
119     SymbolContext new_context(
120         frame->GetSymbolContext(eSymbolContextEverything));
121     if (m_addr_context.line_entry.IsValid() &&
122         new_context.line_entry.IsValid()) {
123       if (m_addr_context.line_entry.original_file ==
124           new_context.line_entry.original_file) {
125         if (m_addr_context.line_entry.line == new_context.line_entry.line) {
126           m_addr_context = new_context;
127           const bool include_inlined_functions =
128               GetKind() == eKindStepOverRange;
129           AddRange(m_addr_context.line_entry.GetSameLineContiguousAddressRange(
130               include_inlined_functions));
131           ret_value = true;
132           if (log) {
133             StreamString s;
134             m_addr_context.line_entry.Dump(&s, &GetTarget(), true,
135                                            Address::DumpStyleLoadAddress,
136                                            Address::DumpStyleLoadAddress, true);
137 
138             LLDB_LOGF(
139                 log,
140                 "Step range plan stepped to another range of same line: %s",
141                 s.GetData());
142           }
143         } else if (new_context.line_entry.line == 0) {
144           new_context.line_entry.line = m_addr_context.line_entry.line;
145           m_addr_context = new_context;
146           const bool include_inlined_functions =
147               GetKind() == eKindStepOverRange;
148           AddRange(m_addr_context.line_entry.GetSameLineContiguousAddressRange(
149               include_inlined_functions));
150           ret_value = true;
151           if (log) {
152             StreamString s;
153             m_addr_context.line_entry.Dump(&s, &GetTarget(), true,
154                                            Address::DumpStyleLoadAddress,
155                                            Address::DumpStyleLoadAddress, true);
156 
157             LLDB_LOGF(log,
158                       "Step range plan stepped to a range at linenumber 0 "
159                       "stepping through that range: %s",
160                       s.GetData());
161           }
162         } else if (new_context.line_entry.range.GetBaseAddress().GetLoadAddress(
163                        &GetTarget()) != pc_load_addr) {
164           // Another thing that sometimes happens here is that we step out of
165           // one line into the MIDDLE of another line.  So far I mostly see
166           // this due to bugs in the debug information. But we probably don't
167           // want to be in the middle of a line range, so in that case reset
168           // the stepping range to the line we've stepped into the middle of
169           // and continue.
170           m_addr_context = new_context;
171           m_address_ranges.clear();
172           AddRange(m_addr_context.line_entry.range);
173           ret_value = true;
174           if (log) {
175             StreamString s;
176             m_addr_context.line_entry.Dump(&s, &GetTarget(), true,
177                                            Address::DumpStyleLoadAddress,
178                                            Address::DumpStyleLoadAddress, true);
179 
180             LLDB_LOGF(log,
181                       "Step range plan stepped to the middle of new "
182                       "line(%d): %s, continuing to clear this line.",
183                       new_context.line_entry.line, s.GetData());
184           }
185         }
186       }
187     }
188   }
189 
190   if (!ret_value && log)
191     LLDB_LOGF(log, "Step range plan out of range to 0x%" PRIx64, pc_load_addr);
192 
193   return ret_value;
194 }
195 
196 bool ThreadPlanStepRange::InSymbol() {
197   lldb::addr_t cur_pc = GetThread().GetRegisterContext()->GetPC();
198   if (m_addr_context.function != nullptr) {
199     return m_addr_context.function->GetAddressRange().ContainsLoadAddress(
200         cur_pc, &GetTarget());
201   } else if (m_addr_context.symbol && m_addr_context.symbol->ValueIsAddress()) {
202     AddressRange range(m_addr_context.symbol->GetAddressRef(),
203                        m_addr_context.symbol->GetByteSize());
204     return range.ContainsLoadAddress(cur_pc, &GetTarget());
205   }
206   return false;
207 }
208 
209 // FIXME: This should also handle inlining if we aren't going to do inlining in
210 // the
211 // main stack.
212 //
213 // Ideally we should remember the whole stack frame list, and then compare that
214 // to the current list.
215 
216 lldb::FrameComparison ThreadPlanStepRange::CompareCurrentFrameToStartFrame() {
217   FrameComparison frame_order;
218   Thread &thread = GetThread();
219   StackID cur_frame_id = thread.GetStackFrameAtIndex(0)->GetStackID();
220 
221   if (cur_frame_id == m_stack_id) {
222     frame_order = eFrameCompareEqual;
223   } else if (cur_frame_id < m_stack_id) {
224     frame_order = eFrameCompareYounger;
225   } else {
226     StackFrameSP cur_parent_frame = thread.GetStackFrameAtIndex(1);
227     StackID cur_parent_id;
228     if (cur_parent_frame)
229       cur_parent_id = cur_parent_frame->GetStackID();
230     if (m_parent_stack_id.IsValid() && cur_parent_id.IsValid() &&
231         m_parent_stack_id == cur_parent_id)
232       frame_order = eFrameCompareSameParent;
233     else
234       frame_order = eFrameCompareOlder;
235   }
236   return frame_order;
237 }
238 
239 bool ThreadPlanStepRange::StopOthers() {
240   switch (m_stop_others) {
241   case lldb::eOnlyThisThread:
242     return true;
243   case lldb::eOnlyDuringStepping:
244     // If there is a call in the range of the next branch breakpoint,
245     // then we should always run all threads, since a call can execute
246     // arbitrary code which might for instance take a lock that's held
247     // by another thread.
248     return !m_found_calls;
249   case lldb::eAllThreads:
250     return false;
251   }
252   llvm_unreachable("Unhandled run mode!");
253 }
254 
255 InstructionList *ThreadPlanStepRange::GetInstructionsForAddress(
256     lldb::addr_t addr, size_t &range_index, size_t &insn_offset) {
257   size_t num_ranges = m_address_ranges.size();
258   for (size_t i = 0; i < num_ranges; i++) {
259     if (m_address_ranges[i].ContainsLoadAddress(addr, &GetTarget())) {
260       // Some joker added a zero size range to the stepping range...
261       if (m_address_ranges[i].GetByteSize() == 0)
262         return nullptr;
263 
264       if (!m_instruction_ranges[i]) {
265         // Disassemble the address range given:
266         const char *plugin_name = nullptr;
267         const char *flavor = nullptr;
268         const bool prefer_file_cache = true;
269         m_instruction_ranges[i] = Disassembler::DisassembleRange(
270             GetTarget().GetArchitecture(), plugin_name, flavor, GetTarget(),
271             m_address_ranges[i], prefer_file_cache);
272       }
273       if (!m_instruction_ranges[i])
274         return nullptr;
275       else {
276         // Find where we are in the instruction list as well.  If we aren't at
277         // an instruction, return nullptr. In this case, we're probably lost,
278         // and shouldn't try to do anything fancy.
279 
280         insn_offset =
281             m_instruction_ranges[i]
282                 ->GetInstructionList()
283                 .GetIndexOfInstructionAtLoadAddress(addr, GetTarget());
284         if (insn_offset == UINT32_MAX)
285           return nullptr;
286         else {
287           range_index = i;
288           return &m_instruction_ranges[i]->GetInstructionList();
289         }
290       }
291     }
292   }
293   return nullptr;
294 }
295 
296 void ThreadPlanStepRange::ClearNextBranchBreakpoint() {
297   if (m_next_branch_bp_sp) {
298     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
299     LLDB_LOGF(log, "Removing next branch breakpoint: %d.",
300               m_next_branch_bp_sp->GetID());
301     GetTarget().RemoveBreakpointByID(m_next_branch_bp_sp->GetID());
302     m_next_branch_bp_sp.reset();
303     m_could_not_resolve_hw_bp = false;
304     m_found_calls = false;
305   }
306 }
307 
308 bool ThreadPlanStepRange::SetNextBranchBreakpoint() {
309   if (m_next_branch_bp_sp)
310     return true;
311 
312   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
313   // Stepping through ranges using breakpoints doesn't work yet, but with this
314   // off we fall back to instruction single stepping.
315   if (!m_use_fast_step)
316     return false;
317 
318   // clear the m_found_calls, we'll rediscover it for this range.
319   m_found_calls = false;
320 
321   lldb::addr_t cur_addr = GetThread().GetRegisterContext()->GetPC();
322   // Find the current address in our address ranges, and fetch the disassembly
323   // if we haven't already:
324   size_t pc_index;
325   size_t range_index;
326   InstructionList *instructions =
327       GetInstructionsForAddress(cur_addr, range_index, pc_index);
328   if (instructions == nullptr)
329     return false;
330   else {
331     Target &target = GetThread().GetProcess()->GetTarget();
332     const bool ignore_calls = GetKind() == eKindStepOverRange;
333     uint32_t branch_index =
334         instructions->GetIndexOfNextBranchInstruction(pc_index, target,
335                                                       ignore_calls,
336                                                       &m_found_calls);
337 
338     Address run_to_address;
339 
340     // If we didn't find a branch, run to the end of the range.
341     if (branch_index == UINT32_MAX) {
342       uint32_t last_index = instructions->GetSize() - 1;
343       if (last_index - pc_index > 1) {
344         InstructionSP last_inst =
345             instructions->GetInstructionAtIndex(last_index);
346         size_t last_inst_size = last_inst->GetOpcode().GetByteSize();
347         run_to_address = last_inst->GetAddress();
348         run_to_address.Slide(last_inst_size);
349       }
350     } else if (branch_index - pc_index > 1) {
351       run_to_address =
352           instructions->GetInstructionAtIndex(branch_index)->GetAddress();
353     }
354 
355     if (run_to_address.IsValid()) {
356       const bool is_internal = true;
357       m_next_branch_bp_sp =
358           GetTarget().CreateBreakpoint(run_to_address, is_internal, false);
359       if (m_next_branch_bp_sp) {
360 
361         if (m_next_branch_bp_sp->IsHardware() &&
362             !m_next_branch_bp_sp->HasResolvedLocations())
363           m_could_not_resolve_hw_bp = true;
364 
365         if (log) {
366           lldb::break_id_t bp_site_id = LLDB_INVALID_BREAK_ID;
367           BreakpointLocationSP bp_loc =
368               m_next_branch_bp_sp->GetLocationAtIndex(0);
369           if (bp_loc) {
370             BreakpointSiteSP bp_site = bp_loc->GetBreakpointSite();
371             if (bp_site) {
372               bp_site_id = bp_site->GetID();
373             }
374           }
375           LLDB_LOGF(log,
376                     "ThreadPlanStepRange::SetNextBranchBreakpoint - Setting "
377                     "breakpoint %d (site %d) to run to address 0x%" PRIx64,
378                     m_next_branch_bp_sp->GetID(), bp_site_id,
379                     run_to_address.GetLoadAddress(&m_process.GetTarget()));
380         }
381 
382         m_next_branch_bp_sp->SetThreadID(m_tid);
383         m_next_branch_bp_sp->SetBreakpointKind("next-branch-location");
384 
385         return true;
386       } else
387         return false;
388     }
389   }
390   return false;
391 }
392 
393 bool ThreadPlanStepRange::NextRangeBreakpointExplainsStop(
394     lldb::StopInfoSP stop_info_sp) {
395   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
396   if (!m_next_branch_bp_sp)
397     return false;
398 
399   break_id_t bp_site_id = stop_info_sp->GetValue();
400   BreakpointSiteSP bp_site_sp =
401       m_process.GetBreakpointSiteList().FindByID(bp_site_id);
402   if (!bp_site_sp)
403     return false;
404   else if (!bp_site_sp->IsBreakpointAtThisSite(m_next_branch_bp_sp->GetID()))
405     return false;
406   else {
407     // If we've hit the next branch breakpoint, then clear it.
408     size_t num_owners = bp_site_sp->GetNumberOfOwners();
409     bool explains_stop = true;
410     // If all the owners are internal, then we are probably just stepping over
411     // this range from multiple threads, or multiple frames, so we want to
412     // continue.  If one is not internal, then we should not explain the stop,
413     // and let the user breakpoint handle the stop.
414     for (size_t i = 0; i < num_owners; i++) {
415       if (!bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint().IsInternal()) {
416         explains_stop = false;
417         break;
418       }
419     }
420     LLDB_LOGF(log,
421               "ThreadPlanStepRange::NextRangeBreakpointExplainsStop - Hit "
422               "next range breakpoint which has %" PRIu64
423               " owners - explains stop: %u.",
424               (uint64_t)num_owners, explains_stop);
425     ClearNextBranchBreakpoint();
426     return explains_stop;
427   }
428 }
429 
430 bool ThreadPlanStepRange::WillStop() { return true; }
431 
432 StateType ThreadPlanStepRange::GetPlanRunState() {
433   if (m_next_branch_bp_sp)
434     return eStateRunning;
435   else
436     return eStateStepping;
437 }
438 
439 bool ThreadPlanStepRange::MischiefManaged() {
440   // If we have pushed some plans between ShouldStop & MischiefManaged, then
441   // we're not done...
442   // I do this check first because we might have stepped somewhere that will
443   // fool InRange into
444   // thinking it needs to step past the end of that line.  This happens, for
445   // instance, when stepping over inlined code that is in the middle of the
446   // current line.
447 
448   if (!m_no_more_plans)
449     return false;
450 
451   bool done = true;
452   if (!IsPlanComplete()) {
453     if (InRange()) {
454       done = false;
455     } else {
456       FrameComparison frame_order = CompareCurrentFrameToStartFrame();
457       done = (frame_order != eFrameCompareOlder) ? m_no_more_plans : true;
458     }
459   }
460 
461   if (done) {
462     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
463     LLDB_LOGF(log, "Completed step through range plan.");
464     ClearNextBranchBreakpoint();
465     ThreadPlan::MischiefManaged();
466     return true;
467   } else {
468     return false;
469   }
470 }
471 
472 bool ThreadPlanStepRange::IsPlanStale() {
473   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
474   FrameComparison frame_order = CompareCurrentFrameToStartFrame();
475 
476   if (frame_order == eFrameCompareOlder) {
477     if (log) {
478       LLDB_LOGF(log, "ThreadPlanStepRange::IsPlanStale returning true, we've "
479                      "stepped out.");
480     }
481     return true;
482   } else if (frame_order == eFrameCompareEqual && InSymbol()) {
483     // If we are not in a place we should step through, we've gotten stale. One
484     // tricky bit here is that some stubs don't push a frame, so we should.
485     // check that we are in the same symbol.
486     if (!InRange()) {
487       // Set plan Complete when we reach next instruction just after the range
488       lldb::addr_t addr = GetThread().GetRegisterContext()->GetPC() - 1;
489       size_t num_ranges = m_address_ranges.size();
490       for (size_t i = 0; i < num_ranges; i++) {
491         bool in_range =
492             m_address_ranges[i].ContainsLoadAddress(addr, &GetTarget());
493         if (in_range) {
494           SetPlanComplete();
495         }
496       }
497       return true;
498     }
499   }
500   return false;
501 }
502