UnwindLLDB.cpp revision 288943
12490Sjkh//===-- UnwindLLDB.cpp -------------------------------------*- C++ -*-===//
22490Sjkh//
32490Sjkh//                     The LLVM Compiler Infrastructure
42490Sjkh//
52490Sjkh// This file is distributed under the University of Illinois Open Source
62490Sjkh// License. See LICENSE.TXT for details.
72490Sjkh//
82490Sjkh//===----------------------------------------------------------------------===//
92490Sjkh
102490Sjkh#include "lldb/Core/Module.h"
112490Sjkh#include "lldb/Core/Log.h"
122490Sjkh#include "lldb/Symbol/FuncUnwinders.h"
132490Sjkh#include "lldb/Symbol/Function.h"
142490Sjkh#include "lldb/Symbol/UnwindPlan.h"
152490Sjkh#include "lldb/Target/ABI.h"
162490Sjkh#include "lldb/Target/Thread.h"
172490Sjkh#include "lldb/Target/Target.h"
182490Sjkh#include "lldb/Target/Process.h"
192490Sjkh#include "lldb/Target/RegisterContext.h"
202490Sjkh
212490Sjkh#include "UnwindLLDB.h"
222490Sjkh#include "RegisterContextLLDB.h"
232490Sjkh
242490Sjkhusing namespace lldb;
252490Sjkhusing namespace lldb_private;
262490Sjkh
272490SjkhUnwindLLDB::UnwindLLDB (Thread &thread) :
282490Sjkh    Unwind (thread),
292490Sjkh    m_frames(),
302490Sjkh    m_unwind_complete(false),
312490Sjkh    m_user_supplied_trap_handler_functions()
322490Sjkh{
332490Sjkh    ProcessSP process_sp(thread.GetProcess());
3410352Sjoerg    if (process_sp)
3510352Sjoerg    {
3610352Sjoerg        Args args;
3710352Sjoerg        process_sp->GetTarget().GetUserSpecifiedTrapHandlerNames (args);
3810352Sjoerg        size_t count = args.GetArgumentCount();
392490Sjkh        for (size_t i = 0; i < count; i++)
402490Sjkh        {
412490Sjkh            const char *func_name = args.GetArgumentAtIndex(i);
422490Sjkh            m_user_supplied_trap_handler_functions.push_back (ConstString (func_name));
432490Sjkh        }
442490Sjkh    }
452490Sjkh}
462490Sjkh
472490Sjkhuint32_t
482490SjkhUnwindLLDB::DoGetFrameCount()
492490Sjkh{
502490Sjkh    if (!m_unwind_complete)
5110352Sjoerg    {
5210352Sjoerg//#define DEBUG_FRAME_SPEED 1
532490Sjkh#if DEBUG_FRAME_SPEED
5410352Sjoerg#define FRAME_COUNT 10000
5510352Sjoerg        TimeValue time_value (TimeValue::Now());
5610352Sjoerg#endif
5710352Sjoerg        if (!AddFirstFrame ())
5810352Sjoerg            return 0;
5910352Sjoerg
6010352Sjoerg        ProcessSP process_sp (m_thread.GetProcess());
6110352Sjoerg        ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
622490Sjkh
632490Sjkh        while (AddOneMoreFrame (abi))
6410352Sjoerg        {
652490Sjkh#if DEBUG_FRAME_SPEED
6610352Sjoerg            if ((m_frames.size() % FRAME_COUNT) == 0)
6710352Sjoerg            {
6810352Sjoerg                TimeValue now(TimeValue::Now());
6910352Sjoerg                uint64_t delta_t = now - time_value;
7010352Sjoerg                printf ("%u frames in %" PRIu64 ".%09llu ms (%g frames/sec)\n",
7110352Sjoerg                        FRAME_COUNT,
7210352Sjoerg                        delta_t / TimeValue::NanoSecPerSec,
7310352Sjoerg                        delta_t % TimeValue::NanoSecPerSec,
7410352Sjoerg                        (float)FRAME_COUNT / ((float)delta_t / (float)TimeValue::NanoSecPerSec));
7510352Sjoerg                time_value = now;
7610352Sjoerg            }
7710352Sjoerg#endif
7810352Sjoerg        }
7910352Sjoerg    }
8010352Sjoerg    return m_frames.size ();
8110352Sjoerg}
8210352Sjoerg
8310352Sjoergbool
8410352SjoergUnwindLLDB::AddFirstFrame ()
8510352Sjoerg{
8610352Sjoerg    if (m_frames.size() > 0)
8710352Sjoerg        return true;
8810352Sjoerg
8910352Sjoerg    // First, set up the 0th (initial) frame
9010352Sjoerg    CursorSP first_cursor_sp(new Cursor ());
9110352Sjoerg    RegisterContextLLDBSP reg_ctx_sp (new RegisterContextLLDB (m_thread,
9210352Sjoerg                                                               RegisterContextLLDBSP(),
9310352Sjoerg                                                               first_cursor_sp->sctx,
9410352Sjoerg                                                               0, *this));
9510352Sjoerg    if (reg_ctx_sp.get() == NULL)
9610352Sjoerg        goto unwind_done;
9710352Sjoerg
9810352Sjoerg    if (!reg_ctx_sp->IsValid())
9910352Sjoerg        goto unwind_done;
10010352Sjoerg
10110352Sjoerg    if (!reg_ctx_sp->GetCFA (first_cursor_sp->cfa))
10210352Sjoerg        goto unwind_done;
10310352Sjoerg
10410352Sjoerg    if (!reg_ctx_sp->ReadPC (first_cursor_sp->start_pc))
10510352Sjoerg        goto unwind_done;
10610352Sjoerg
10710352Sjoerg    // Everything checks out, so release the auto pointer value and let the
10810352Sjoerg    // cursor own it in its shared pointer
10910352Sjoerg    first_cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
11010352Sjoerg    m_frames.push_back (first_cursor_sp);
11110352Sjoerg    return true;
11210352Sjoerg
11310352Sjoergunwind_done:
11410352Sjoerg    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
11510352Sjoerg    if (log)
11610352Sjoerg    {
11710352Sjoerg        log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
11810352Sjoerg    }
11910352Sjoerg    m_unwind_complete = true;
12010352Sjoerg    return false;
12110352Sjoerg}
12210352Sjoerg
12310352SjoergUnwindLLDB::CursorSP
12410352SjoergUnwindLLDB::GetOneMoreFrame (ABI* abi)
12510352Sjoerg{
12610352Sjoerg    assert (m_frames.size() != 0 && "Get one more frame called with empty frame list");
12710352Sjoerg
12810352Sjoerg    // If we've already gotten to the end of the stack, don't bother to try again...
12910352Sjoerg    if (m_unwind_complete)
13010352Sjoerg        return nullptr;
13110352Sjoerg
13210352Sjoerg    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
13310352Sjoerg
13410352Sjoerg    CursorSP prev_frame = m_frames.back();
13510352Sjoerg    uint32_t cur_idx = m_frames.size();
13610352Sjoerg
13710352Sjoerg    CursorSP cursor_sp(new Cursor ());
13810352Sjoerg    RegisterContextLLDBSP reg_ctx_sp(new RegisterContextLLDB (m_thread,
13910352Sjoerg                                                              prev_frame->reg_ctx_lldb_sp,
14010352Sjoerg                                                              cursor_sp->sctx,
14110352Sjoerg                                                              cur_idx,
14210352Sjoerg                                                              *this));
14310352Sjoerg
14410352Sjoerg    // We want to detect an unwind that cycles erroneously and stop backtracing.
14510352Sjoerg    // Don't want this maximum unwind limit to be too low -- if you have a backtrace
14610352Sjoerg    // with an "infinitely recursing" bug, it will crash when the stack blows out
14710352Sjoerg    // and the first 35,000 frames are uninteresting - it's the top most 5 frames that
14810352Sjoerg    // you actually care about.  So you can't just cap the unwind at 10,000 or something.
14910352Sjoerg    // Realistically anything over around 200,000 is going to blow out the stack space.
15010352Sjoerg    // If we're still unwinding at that point, we're probably never going to finish.
15110352Sjoerg    if (cur_idx > 300000)
15210352Sjoerg    {
15310352Sjoerg        if (log)
15410352Sjoerg            log->Printf ("%*sFrame %d unwound too many frames, assuming unwind has gone astray, stopping.",
15510352Sjoerg                         cur_idx < 100 ? cur_idx : 100, "", cur_idx);
15610352Sjoerg        return nullptr;
15710352Sjoerg    }
15810352Sjoerg
15910352Sjoerg    if (reg_ctx_sp.get() == NULL)
16010352Sjoerg    {
16110352Sjoerg        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
16210352Sjoerg        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
16310352Sjoerg        if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
16410352Sjoerg            return GetOneMoreFrame (abi);
16510352Sjoerg
16610352Sjoerg        if (log)
16710352Sjoerg            log->Printf ("%*sFrame %d did not get a RegisterContext, stopping.",
16810352Sjoerg                         cur_idx < 100 ? cur_idx : 100, "", cur_idx);
16910352Sjoerg        return nullptr;
17010352Sjoerg    }
17110352Sjoerg
17210352Sjoerg    if (!reg_ctx_sp->IsValid())
17310352Sjoerg    {
17410352Sjoerg        // We failed to get a valid RegisterContext.
17510352Sjoerg        // See if the regctx below this on the stack has a fallback unwind plan it can use.
17610352Sjoerg        // Subsequent calls to TryFallbackUnwindPlan() will return false.
17710352Sjoerg        if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
17810352Sjoerg            return GetOneMoreFrame (abi);
17910352Sjoerg
18010352Sjoerg        if (log)
18110352Sjoerg            log->Printf("%*sFrame %d invalid RegisterContext for this frame, stopping stack walk",
18210352Sjoerg                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
18310352Sjoerg        return nullptr;
18410352Sjoerg    }
18510352Sjoerg    if (!reg_ctx_sp->GetCFA (cursor_sp->cfa))
18610352Sjoerg    {
18710352Sjoerg        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
18810352Sjoerg        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
18910352Sjoerg        if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
19010352Sjoerg            return GetOneMoreFrame (abi);
19110352Sjoerg
19210352Sjoerg        if (log)
19310352Sjoerg            log->Printf("%*sFrame %d did not get CFA for this frame, stopping stack walk",
19410352Sjoerg                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
19510352Sjoerg        return nullptr;
19610352Sjoerg    }
19710352Sjoerg    if (abi && !abi->CallFrameAddressIsValid(cursor_sp->cfa))
19810352Sjoerg    {
19910352Sjoerg        // On Mac OS X, the _sigtramp asynchronous signal trampoline frame may not have
20010352Sjoerg        // its (constructed) CFA aligned correctly -- don't do the abi alignment check for
20110352Sjoerg        // these.
20210352Sjoerg        if (reg_ctx_sp->IsTrapHandlerFrame() == false)
20310352Sjoerg        {
20410352Sjoerg            // See if we can find a fallback unwind plan for THIS frame.  It may be
20510352Sjoerg            // that the UnwindPlan we're using for THIS frame was bad and gave us a
20610352Sjoerg            // bad CFA.
20710352Sjoerg            // If that's not it, then see if we can change the UnwindPlan for the frame
20810352Sjoerg            // below us ("NEXT") -- see if using that other UnwindPlan gets us a better
2092490Sjkh            // unwind state.
21010352Sjoerg            if (reg_ctx_sp->TryFallbackUnwindPlan() == false
21110352Sjoerg                || reg_ctx_sp->GetCFA (cursor_sp->cfa) == false
21210352Sjoerg                || abi->CallFrameAddressIsValid(cursor_sp->cfa) == false)
21310352Sjoerg            {
2142490Sjkh                if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
21510352Sjoerg                    return GetOneMoreFrame (abi);
21610352Sjoerg
21710352Sjoerg                if (log)
21810352Sjoerg                    log->Printf("%*sFrame %d did not get a valid CFA for this frame, stopping stack walk",
21910352Sjoerg                                cur_idx < 100 ? cur_idx : 100, "", cur_idx);
22010352Sjoerg                return nullptr;
22110352Sjoerg            }
22210352Sjoerg            else
2232490Sjkh            {
2242490Sjkh                if (log)
2252490Sjkh                    log->Printf("%*sFrame %d had a bad CFA value but we switched the UnwindPlan being used and got one that looks more realistic.",
22610352Sjoerg                                cur_idx < 100 ? cur_idx : 100, "", cur_idx);
22710352Sjoerg            }
22810352Sjoerg        }
2292490Sjkh    }
2302490Sjkh    if (!reg_ctx_sp->ReadPC (cursor_sp->start_pc))
23110352Sjoerg    {
2322490Sjkh        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
2332490Sjkh        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
23410352Sjoerg        if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
23510352Sjoerg            return GetOneMoreFrame (abi);
23610352Sjoerg
23710352Sjoerg        if (log)
23810352Sjoerg            log->Printf("%*sFrame %d did not get PC for this frame, stopping stack walk",
23910352Sjoerg                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
24010352Sjoerg        return nullptr;
24110352Sjoerg    }
24210352Sjoerg    if (abi && !abi->CodeAddressIsValid (cursor_sp->start_pc))
24310352Sjoerg    {
24410352Sjoerg        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
24510352Sjoerg        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
24610352Sjoerg        if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
24710352Sjoerg            return GetOneMoreFrame (abi);
24810352Sjoerg
24910352Sjoerg        if (log)
25010352Sjoerg            log->Printf("%*sFrame %d did not get a valid PC, stopping stack walk",
25110352Sjoerg                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
25210352Sjoerg        return nullptr;
25310352Sjoerg    }
25410352Sjoerg    // Infinite loop where the current cursor is the same as the previous one...
25510352Sjoerg    if (prev_frame->start_pc == cursor_sp->start_pc && prev_frame->cfa == cursor_sp->cfa)
25610352Sjoerg    {
25710352Sjoerg        if (log)
25810352Sjoerg            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());
2592490Sjkh        return nullptr;
2602490Sjkh    }
2612490Sjkh
26210352Sjoerg    cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
26310352Sjoerg    return cursor_sp;
26410352Sjoerg}
26510352Sjoerg
26610352Sjoergbool
26710352SjoergUnwindLLDB::AddOneMoreFrame (ABI *abi)
26810352Sjoerg{
26910352Sjoerg    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
27010352Sjoerg
27110352Sjoerg    // Frame zero is a little different
2722490Sjkh    if (m_frames.empty())
27310352Sjoerg        return false;
27410352Sjoerg
27510352Sjoerg    // If we've already gotten to the end of the stack, don't bother to try again...
27610352Sjoerg    if (m_unwind_complete)
2772490Sjkh        return false;
27810352Sjoerg
27910352Sjoerg    CursorSP new_frame = m_candidate_frame;
28010352Sjoerg    if (new_frame == nullptr)
28110352Sjoerg        new_frame = GetOneMoreFrame(abi);
28210352Sjoerg
2832490Sjkh    if (new_frame == nullptr)
2842490Sjkh    {
28510352Sjoerg        if (log)
28610352Sjoerg            log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
2872490Sjkh        m_unwind_complete = true;
28810352Sjoerg        return false;
28910352Sjoerg    }
2902490Sjkh
29110352Sjoerg    m_frames.push_back(new_frame);
29210352Sjoerg
29310352Sjoerg    // If we can get one more frame further then accept that we get back a correct frame.
29410352Sjoerg    m_candidate_frame = GetOneMoreFrame(abi);
29510352Sjoerg    if (m_candidate_frame)
29610352Sjoerg        return true;
29710352Sjoerg
29810352Sjoerg    // We can't go further from the frame returned by GetOneMore frame. Lets try to get a
29910352Sjoerg    // different frame with using the fallback unwind plan.
30010352Sjoerg    if (!m_frames[m_frames.size() - 2]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
30110352Sjoerg    {
30210352Sjoerg        // We don't have a valid fallback unwind plan. Accept the frame as it is. This is a
30310352Sjoerg        // valid situation when we are at the bottom of the stack.
30410352Sjoerg        return true;
30510352Sjoerg    }
30610352Sjoerg
30710352Sjoerg    // Remove the possibly incorrect frame from the frame list and try to add a different one with
30810352Sjoerg    // the newly selected fallback unwind plan.
30910352Sjoerg    m_frames.pop_back();
31010352Sjoerg    CursorSP new_frame_v2 = GetOneMoreFrame(abi);
31110352Sjoerg    if (new_frame_v2 == nullptr)
31210352Sjoerg    {
3132490Sjkh        // We haven't got a new frame from the fallback unwind plan. Accept the frame from the
3142490Sjkh        // original unwind plan. This is a valid situation when we are at the bottom of the stack.
31510352Sjoerg        m_frames.push_back(new_frame);
31610352Sjoerg        return true;
3172490Sjkh    }
3182490Sjkh
3192490Sjkh    // Push the new frame to the list and try to continue from this frame. If we can get a new frame
32010352Sjoerg    // then accept it as the correct one.
32110352Sjoerg    m_frames.push_back(new_frame_v2);
32210352Sjoerg    m_candidate_frame = GetOneMoreFrame(abi);
32310352Sjoerg    if (m_candidate_frame)
3242490Sjkh        return true;
32510352Sjoerg
32610352Sjoerg    // The new frame isn't helped in unwinding. Fall back to the original one as the default unwind
32710352Sjoerg    // plan is usually more reliable then the fallback one.
32810352Sjoerg    m_frames.pop_back();
32910352Sjoerg    m_frames.push_back(new_frame);
33010352Sjoerg    return true;
33110352Sjoerg}
33210352Sjoerg
33310352Sjoergbool
33410352SjoergUnwindLLDB::DoGetFrameInfoAtIndex (uint32_t idx, addr_t& cfa, addr_t& pc)
33510352Sjoerg{
33610352Sjoerg    if (m_frames.size() == 0)
33710352Sjoerg    {
33810352Sjoerg        if (!AddFirstFrame())
33910352Sjoerg            return false;
34010352Sjoerg    }
34110352Sjoerg
34210352Sjoerg    ProcessSP process_sp (m_thread.GetProcess());
34310352Sjoerg    ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
34410352Sjoerg
34510352Sjoerg    while (idx >= m_frames.size() && AddOneMoreFrame (abi))
34610352Sjoerg        ;
34710352Sjoerg
34810352Sjoerg    if (idx < m_frames.size ())
34910352Sjoerg    {
35010352Sjoerg        cfa = m_frames[idx]->cfa;
35110352Sjoerg        pc = m_frames[idx]->start_pc;
35210352Sjoerg        return true;
35310352Sjoerg    }
35410352Sjoerg    return false;
35510352Sjoerg}
35610352Sjoerg
35710352Sjoerglldb::RegisterContextSP
35810352SjoergUnwindLLDB::DoCreateRegisterContextForFrame (StackFrame *frame)
35910352Sjoerg{
36010352Sjoerg    lldb::RegisterContextSP reg_ctx_sp;
36110352Sjoerg    uint32_t idx = frame->GetConcreteFrameIndex ();
36210352Sjoerg
36310352Sjoerg    if (idx == 0)
36410352Sjoerg    {
36510352Sjoerg        return m_thread.GetRegisterContext();
36610352Sjoerg    }
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
392UnwindLLDB::RegisterContextLLDBSP
393UnwindLLDB::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
401bool
402UnwindLLDB::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}
452