LLDB  mainline
UnwindLLDB.cpp
Go to the documentation of this file.
1 //===-- UnwindLLDB.cpp -------------------------------------*- C++ -*-===//
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/Core/Module.h"
11 #include "lldb/Symbol/Function.h"
12 #include "lldb/Symbol/UnwindPlan.h"
13 #include "lldb/Target/ABI.h"
14 #include "lldb/Target/Process.h"
16 #include "lldb/Target/Target.h"
17 #include "lldb/Target/Thread.h"
18 #include "lldb/Utility/Log.h"
19 
20 #include "RegisterContextLLDB.h"
21 #include "UnwindLLDB.h"
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 UnwindLLDB::UnwindLLDB(Thread &thread)
27  : Unwind(thread), m_frames(), m_unwind_complete(false),
28  m_user_supplied_trap_handler_functions() {
29  ProcessSP process_sp(thread.GetProcess());
30  if (process_sp) {
31  Args args;
32  process_sp->GetTarget().GetUserSpecifiedTrapHandlerNames(args);
33  size_t count = args.GetArgumentCount();
34  for (size_t i = 0; i < count; i++) {
35  const char *func_name = args.GetArgumentAtIndex(i);
36  m_user_supplied_trap_handler_functions.push_back(ConstString(func_name));
37  }
38  }
39 }
40 
42  if (!m_unwind_complete) {
43 //#define DEBUG_FRAME_SPEED 1
44 #if DEBUG_FRAME_SPEED
45 #define FRAME_COUNT 10000
46  using namespace std::chrono;
47  auto time_value = steady_clock::now();
48 #endif
49  if (!AddFirstFrame())
50  return 0;
51 
52  ProcessSP process_sp(m_thread.GetProcess());
53  ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
54 
55  while (AddOneMoreFrame(abi)) {
56 #if DEBUG_FRAME_SPEED
57  if ((m_frames.size() % FRAME_COUNT) == 0) {
58  const auto now = steady_clock::now();
59  const auto delta_t = now - time_value;
60  printf("%u frames in %.9f ms (%g frames/sec)\n", FRAME_COUNT,
61  duration<double, std::milli>(delta_t).count(),
62  (float)FRAME_COUNT / duration<double>(delta_t).count());
63  time_value = now;
64  }
65 #endif
66  }
67  }
68  return m_frames.size();
69 }
70 
71 bool UnwindLLDB::AddFirstFrame() {
72  if (m_frames.size() > 0)
73  return true;
74 
75  ProcessSP process_sp(m_thread.GetProcess());
76  ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
77 
78  // First, set up the 0th (initial) frame
79  CursorSP first_cursor_sp(new Cursor());
81  m_thread, RegisterContextLLDBSP(), first_cursor_sp->sctx, 0, *this));
82  if (reg_ctx_sp.get() == NULL)
83  goto unwind_done;
84 
85  if (!reg_ctx_sp->IsValid())
86  goto unwind_done;
87 
88  if (!reg_ctx_sp->GetCFA(first_cursor_sp->cfa))
89  goto unwind_done;
90 
91  if (!reg_ctx_sp->ReadPC(first_cursor_sp->start_pc))
92  goto unwind_done;
93 
94  // Everything checks out, so release the auto pointer value and let the
95  // cursor own it in its shared pointer
96  first_cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
97  m_frames.push_back(first_cursor_sp);
98 
99  // Update the Full Unwind Plan for this frame if not valid
100  UpdateUnwindPlanForFirstFrameIfInvalid(abi);
101 
102  return true;
103 
104 unwind_done:
106  if (log) {
107  log->Printf("th%d Unwind of this thread is complete.",
108  m_thread.GetIndexID());
109  }
110  m_unwind_complete = true;
111  return false;
112 }
113 
114 UnwindLLDB::CursorSP UnwindLLDB::GetOneMoreFrame(ABI *abi) {
115  assert(m_frames.size() != 0 &&
116  "Get one more frame called with empty frame list");
117 
118  // If we've already gotten to the end of the stack, don't bother to try
119  // again...
120  if (m_unwind_complete)
121  return nullptr;
122 
124 
125  CursorSP prev_frame = m_frames.back();
126  uint32_t cur_idx = m_frames.size();
127 
128  CursorSP cursor_sp(new Cursor());
130  m_thread, prev_frame->reg_ctx_lldb_sp, cursor_sp->sctx, cur_idx, *this));
131 
132  uint64_t max_stack_depth = m_thread.GetMaxBacktraceDepth();
133 
134  // We want to detect an unwind that cycles erroneously and stop backtracing.
135  // Don't want this maximum unwind limit to be too low -- if you have a
136  // backtrace with an "infinitely recursing" bug, it will crash when the stack
137  // blows out and the first 35,000 frames are uninteresting - it's the top
138  // most 5 frames that you actually care about. So you can't just cap the
139  // unwind at 10,000 or something. Realistically anything over around 200,000
140  // is going to blow out the stack space. If we're still unwinding at that
141  // point, we're probably never going to finish.
142  if (cur_idx >= max_stack_depth) {
143  if (log)
144  log->Printf("%*sFrame %d unwound too many frames, assuming unwind has "
145  "gone astray, stopping.",
146  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
147  return nullptr;
148  }
149 
150  if (reg_ctx_sp.get() == NULL) {
151  // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to
152  // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
153  // return false.
154  if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
155  // TryFallbackUnwindPlan for prev_frame succeeded and updated
156  // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
157  // still needs to be updated. Hence updating it.
158  if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
159  return nullptr;
160 
161  return GetOneMoreFrame(abi);
162  }
163 
164  if (log)
165  log->Printf("%*sFrame %d did not get a RegisterContext, stopping.",
166  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
167  return nullptr;
168  }
169 
170  if (!reg_ctx_sp->IsValid()) {
171  // We failed to get a valid RegisterContext. See if the regctx below this
172  // on the stack has a fallback unwind plan it can use. Subsequent calls to
173  // TryFallbackUnwindPlan() will return false.
174  if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
175  // TryFallbackUnwindPlan for prev_frame succeeded and updated
176  // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
177  // still needs to be updated. Hence updating it.
178  if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
179  return nullptr;
180 
181  return GetOneMoreFrame(abi);
182  }
183 
184  if (log)
185  log->Printf("%*sFrame %d invalid RegisterContext for this frame, "
186  "stopping stack walk",
187  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
188  return nullptr;
189  }
190  if (!reg_ctx_sp->GetCFA(cursor_sp->cfa)) {
191  // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to
192  // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
193  // return false.
194  if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
195  // TryFallbackUnwindPlan for prev_frame succeeded and updated
196  // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
197  // still needs to be updated. Hence updating it.
198  if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
199  return nullptr;
200 
201  return GetOneMoreFrame(abi);
202  }
203 
204  if (log)
205  log->Printf(
206  "%*sFrame %d did not get CFA for this frame, stopping stack walk",
207  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
208  return nullptr;
209  }
210  if (abi && !abi->CallFrameAddressIsValid(cursor_sp->cfa)) {
211  // On Mac OS X, the _sigtramp asynchronous signal trampoline frame may not
212  // have its (constructed) CFA aligned correctly -- don't do the abi
213  // alignment check for these.
214  if (!reg_ctx_sp->IsTrapHandlerFrame()) {
215  // See if we can find a fallback unwind plan for THIS frame. It may be
216  // that the UnwindPlan we're using for THIS frame was bad and gave us a
217  // bad CFA. If that's not it, then see if we can change the UnwindPlan
218  // for the frame below us ("NEXT") -- see if using that other UnwindPlan
219  // gets us a better unwind state.
220  if (!reg_ctx_sp->TryFallbackUnwindPlan() ||
221  !reg_ctx_sp->GetCFA(cursor_sp->cfa) ||
222  !abi->CallFrameAddressIsValid(cursor_sp->cfa)) {
223  if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
224  // TryFallbackUnwindPlan for prev_frame succeeded and updated
225  // reg_ctx_lldb_sp field of prev_frame. However, cfa field of
226  // prev_frame still needs to be updated. Hence updating it.
227  if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
228  return nullptr;
229 
230  return GetOneMoreFrame(abi);
231  }
232 
233  if (log)
234  log->Printf("%*sFrame %d did not get a valid CFA for this frame, "
235  "stopping stack walk",
236  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
237  return nullptr;
238  } else {
239  if (log)
240  log->Printf("%*sFrame %d had a bad CFA value but we switched the "
241  "UnwindPlan being used and got one that looks more "
242  "realistic.",
243  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
244  }
245  }
246  }
247  if (!reg_ctx_sp->ReadPC(cursor_sp->start_pc)) {
248  // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to
249  // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
250  // return false.
251  if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
252  // TryFallbackUnwindPlan for prev_frame succeeded and updated
253  // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
254  // still needs to be updated. Hence updating it.
255  if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
256  return nullptr;
257 
258  return GetOneMoreFrame(abi);
259  }
260 
261  if (log)
262  log->Printf(
263  "%*sFrame %d did not get PC for this frame, stopping stack walk",
264  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
265  return nullptr;
266  }
267  if (abi && !abi->CodeAddressIsValid(cursor_sp->start_pc)) {
268  // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to
269  // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
270  // return false.
271  if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
272  // TryFallbackUnwindPlan for prev_frame succeeded and updated
273  // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
274  // still needs to be updated. Hence updating it.
275  if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
276  return nullptr;
277 
278  return GetOneMoreFrame(abi);
279  }
280 
281  if (log)
282  log->Printf("%*sFrame %d did not get a valid PC, stopping stack walk",
283  cur_idx < 100 ? cur_idx : 100, "", cur_idx);
284  return nullptr;
285  }
286  // Infinite loop where the current cursor is the same as the previous one...
287  if (prev_frame->start_pc == cursor_sp->start_pc &&
288  prev_frame->cfa == cursor_sp->cfa) {
289  if (log)
290  log->Printf("th%d pc of this frame is the same as the previous frame and "
291  "CFAs for both frames are identical -- stopping unwind",
292  m_thread.GetIndexID());
293  return nullptr;
294  }
295 
296  cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
297  return cursor_sp;
298 }
299 
300 void UnwindLLDB::UpdateUnwindPlanForFirstFrameIfInvalid(ABI *abi) {
301  // This function is called for First Frame only.
302  assert(m_frames.size() == 1 && "No. of cursor frames are not 1");
303 
304  bool old_m_unwind_complete = m_unwind_complete;
305  CursorSP old_m_candidate_frame = m_candidate_frame;
306 
307  // Try to unwind 2 more frames using the Unwinder. It uses Full UnwindPlan
308  // and if Full UnwindPlan fails, then uses FallBack UnwindPlan. Also update
309  // the cfa of Frame 0 (if required).
310  AddOneMoreFrame(abi);
311 
312  // Remove all the frames added by above function as the purpose of using
313  // above function was just to check whether Unwinder of Frame 0 works or not.
314  for (uint32_t i = 1; i < m_frames.size(); i++)
315  m_frames.pop_back();
316 
317  // Restore status after calling AddOneMoreFrame
318  m_unwind_complete = old_m_unwind_complete;
319  m_candidate_frame = old_m_candidate_frame;
320  return;
321 }
322 
323 bool UnwindLLDB::AddOneMoreFrame(ABI *abi) {
325 
326  // Frame zero is a little different
327  if (m_frames.empty())
328  return false;
329 
330  // If we've already gotten to the end of the stack, don't bother to try
331  // again...
332  if (m_unwind_complete)
333  return false;
334 
335  CursorSP new_frame = m_candidate_frame;
336  if (new_frame == nullptr)
337  new_frame = GetOneMoreFrame(abi);
338 
339  if (new_frame == nullptr) {
340  if (log)
341  log->Printf("th%d Unwind of this thread is complete.",
342  m_thread.GetIndexID());
343  m_unwind_complete = true;
344  return false;
345  }
346 
347  m_frames.push_back(new_frame);
348 
349  // If we can get one more frame further then accept that we get back a
350  // correct frame.
351  m_candidate_frame = GetOneMoreFrame(abi);
352  if (m_candidate_frame)
353  return true;
354 
355  // We can't go further from the frame returned by GetOneMore frame. Lets try
356  // to get a different frame with using the fallback unwind plan.
357  if (!m_frames[m_frames.size() - 2]
358  ->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
359  // We don't have a valid fallback unwind plan. Accept the frame as it is.
360  // This is a valid situation when we are at the bottom of the stack.
361  return true;
362  }
363 
364  // Remove the possibly incorrect frame from the frame list and try to add a
365  // different one with the newly selected fallback unwind plan.
366  m_frames.pop_back();
367  CursorSP new_frame_v2 = GetOneMoreFrame(abi);
368  if (new_frame_v2 == nullptr) {
369  // We haven't got a new frame from the fallback unwind plan. Accept the
370  // frame from the original unwind plan. This is a valid situation when we
371  // are at the bottom of the stack.
372  m_frames.push_back(new_frame);
373  return true;
374  }
375 
376  // Push the new frame to the list and try to continue from this frame. If we
377  // can get a new frame then accept it as the correct one.
378  m_frames.push_back(new_frame_v2);
379  m_candidate_frame = GetOneMoreFrame(abi);
380  if (m_candidate_frame) {
381  // If control reached here then TryFallbackUnwindPlan had succeeded for
382  // Cursor::m_frames[m_frames.size() - 2]. It also succeeded to Unwind next
383  // 2 frames i.e. m_frames[m_frames.size() - 1] and a frame after that. For
384  // Cursor::m_frames[m_frames.size() - 2], reg_ctx_lldb_sp field was already
385  // updated during TryFallbackUnwindPlan call above. However, cfa field
386  // still needs to be updated. Hence updating it here and then returning.
387  return m_frames[m_frames.size() - 2]->reg_ctx_lldb_sp->GetCFA(
388  m_frames[m_frames.size() - 2]->cfa);
389  }
390 
391  // The new frame hasn't helped in unwinding. Fall back to the original one as
392  // the default unwind plan is usually more reliable then the fallback one.
393  m_frames.pop_back();
394  m_frames.push_back(new_frame);
395  return true;
396 }
397 
399  if (m_frames.size() == 0) {
400  if (!AddFirstFrame())
401  return false;
402  }
403 
404  ProcessSP process_sp(m_thread.GetProcess());
405  ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
406 
407  while (idx >= m_frames.size() && AddOneMoreFrame(abi))
408  ;
409 
410  if (idx < m_frames.size()) {
411  cfa = m_frames[idx]->cfa;
412  pc = m_frames[idx]->start_pc;
413  return true;
414  }
415  return false;
416 }
417 
418 lldb::RegisterContextSP
420  lldb::RegisterContextSP reg_ctx_sp;
421  uint32_t idx = frame->GetConcreteFrameIndex();
422 
423  if (idx == 0) {
424  return m_thread.GetRegisterContext();
425  }
426 
427  if (m_frames.size() == 0) {
428  if (!AddFirstFrame())
429  return reg_ctx_sp;
430  }
431 
432  ProcessSP process_sp(m_thread.GetProcess());
433  ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
434 
435  while (idx >= m_frames.size()) {
436  if (!AddOneMoreFrame(abi))
437  break;
438  }
439 
440  const uint32_t num_frames = m_frames.size();
441  if (idx < num_frames) {
442  Cursor *frame_cursor = m_frames[idx].get();
443  reg_ctx_sp = frame_cursor->reg_ctx_lldb_sp;
444  }
445  return reg_ctx_sp;
446 }
447 
450  RegisterContextLLDBSP reg_ctx_sp;
451  if (frame_num < m_frames.size())
452  reg_ctx_sp = m_frames[frame_num]->reg_ctx_lldb_sp;
453  return reg_ctx_sp;
454 }
455 
458  uint32_t starting_frame_num, bool pc_reg) {
459  int64_t frame_num = starting_frame_num;
460  if (static_cast<size_t>(frame_num) >= m_frames.size())
461  return false;
462 
463  // Never interrogate more than one level while looking for the saved pc
464  // value. If the value isn't saved by frame_num, none of the frames lower on
465  // the stack will have a useful value.
466  if (pc_reg) {
468  result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister(
469  lldb_regnum, regloc);
470  return result == UnwindLLDB::RegisterSearchResult::eRegisterFound;
471  }
472  while (frame_num >= 0) {
474  result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister(
475  lldb_regnum, regloc);
476 
477  // We descended down to the live register context aka stack frame 0 and are
478  // reading the value out of a live register.
479  if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound &&
480  regloc.type ==
482  return true;
483  }
484 
485  // If we have unwind instructions saying that register N is saved in
486  // register M in the middle of the stack (and N can equal M here, meaning
487  // the register was not used in this function), then change the register
488  // number we're looking for to M and keep looking for a concrete location
489  // down the stack, or an actual value from a live RegisterContext at frame
490  // 0.
491  if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound &&
493  frame_num > 0) {
494  result = UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
495  lldb_regnum = regloc.location.register_number;
496  }
497 
498  if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
499  return true;
500  if (result == UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile)
501  return false;
502  frame_num--;
503  }
504  return false;
505 }
A command line argument class.
Definition: Args.h:32
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
virtual bool CodeAddressIsValid(lldb::addr_t pc)=0
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.cpp:254
union lldb_private::UnwindLLDB::RegisterLocation::@144 location
bool DoGetFrameInfoAtIndex(uint32_t frame_idx, lldb::addr_t &cfa, lldb::addr_t &start_pc) override
Definition: UnwindLLDB.cpp:398
#define LIBLLDB_LOG_UNWIND
Definition: Logging.h:29
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx. ...
Definition: Args.cpp:256
std::shared_ptr< RegisterContextLLDB > RegisterContextLLDBSP
Definition: UnwindLLDB.h:81
lldb::RegisterContextSP DoCreateRegisterContextForFrame(lldb_private::StackFrame *frame) override
Definition: UnwindLLDB.cpp:419
virtual bool CallFrameAddressIsValid(lldb::addr_t cfa)=0
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
Thread & m_thread
Definition: Unwind.h:74
virtual lldb::RegisterContextSP GetRegisterContext()=0
bool SearchForSavedLocationForRegister(uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc, uint32_t starting_frame_num, bool pc_register)
Definition: UnwindLLDB.cpp:456
lldb::ProcessSP GetProcess() const
Definition: Thread.h:154
uint64_t addr_t
Definition: lldb-types.h:83
A uniqued constant string class.
Definition: ConstString.h:38
RegisterContextLLDBSP GetRegisterContextForFrameNum(uint32_t frame_num)
Definition: UnwindLLDB.cpp:449
Definition: SBAddress.h:15
uint32_t GetIndexID() const
Definition: Thread.cpp:1515
uint32_t GetConcreteFrameIndex() const
Query this frame to find what frame it is in this Thread&#39;s StackFrameList, not counting inlined frame...
Definition: StackFrame.h:389
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
uint64_t GetMaxBacktraceDepth() const
Definition: Thread.cpp:168
This base class provides an interface to stack frames.
Definition: StackFrame.h:40
uint32_t DoGetFrameCount() override
Definition: UnwindLLDB.cpp:41