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