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