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