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