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