1254721Semaste//===-- UnwindLLDB.cpp -------------------------------------*- C++ -*-===//
2254721Semaste//
3254721Semaste//                     The LLVM Compiler Infrastructure
4254721Semaste//
5254721Semaste// This file is distributed under the University of Illinois Open Source
6254721Semaste// License. See LICENSE.TXT for details.
7254721Semaste//
8254721Semaste//===----------------------------------------------------------------------===//
9254721Semaste
10254721Semaste#include "lldb/Core/Module.h"
11254721Semaste#include "lldb/Core/Log.h"
12254721Semaste#include "lldb/Symbol/FuncUnwinders.h"
13254721Semaste#include "lldb/Symbol/Function.h"
14254721Semaste#include "lldb/Symbol/UnwindPlan.h"
15254721Semaste#include "lldb/Target/Thread.h"
16254721Semaste#include "lldb/Target/Target.h"
17254721Semaste#include "lldb/Target/Process.h"
18254721Semaste#include "lldb/Target/RegisterContext.h"
19254721Semaste
20254721Semaste#include "UnwindLLDB.h"
21254721Semaste#include "RegisterContextLLDB.h"
22254721Semaste
23254721Semasteusing namespace lldb;
24254721Semasteusing namespace lldb_private;
25254721Semaste
26254721SemasteUnwindLLDB::UnwindLLDB (Thread &thread) :
27254721Semaste    Unwind (thread),
28254721Semaste    m_frames(),
29269024Semaste    m_unwind_complete(false),
30269024Semaste    m_user_supplied_trap_handler_functions()
31254721Semaste{
32269024Semaste    ProcessSP process_sp(thread.GetProcess());
33269024Semaste    if (process_sp)
34269024Semaste    {
35269024Semaste        Args args;
36269024Semaste        process_sp->GetTarget().GetUserSpecifiedTrapHandlerNames (args);
37269024Semaste        size_t count = args.GetArgumentCount();
38269024Semaste        for (size_t i = 0; i < count; i++)
39269024Semaste        {
40269024Semaste            const char *func_name = args.GetArgumentAtIndex(i);
41269024Semaste            m_user_supplied_trap_handler_functions.push_back (ConstString (func_name));
42269024Semaste        }
43269024Semaste    }
44254721Semaste}
45254721Semaste
46254721Semasteuint32_t
47254721SemasteUnwindLLDB::DoGetFrameCount()
48254721Semaste{
49254721Semaste    if (!m_unwind_complete)
50254721Semaste    {
51254721Semaste//#define DEBUG_FRAME_SPEED 1
52254721Semaste#if DEBUG_FRAME_SPEED
53254721Semaste#define FRAME_COUNT 10000
54254721Semaste        TimeValue time_value (TimeValue::Now());
55254721Semaste#endif
56254721Semaste        if (!AddFirstFrame ())
57254721Semaste            return 0;
58254721Semaste
59254721Semaste        ProcessSP process_sp (m_thread.GetProcess());
60254721Semaste        ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
61254721Semaste
62254721Semaste        while (AddOneMoreFrame (abi))
63254721Semaste        {
64254721Semaste#if DEBUG_FRAME_SPEED
65254721Semaste            if ((m_frames.size() % FRAME_COUNT) == 0)
66254721Semaste            {
67254721Semaste                TimeValue now(TimeValue::Now());
68254721Semaste                uint64_t delta_t = now - time_value;
69254721Semaste                printf ("%u frames in %" PRIu64 ".%09llu ms (%g frames/sec)\n",
70254721Semaste                        FRAME_COUNT,
71254721Semaste                        delta_t / TimeValue::NanoSecPerSec,
72254721Semaste                        delta_t % TimeValue::NanoSecPerSec,
73254721Semaste                        (float)FRAME_COUNT / ((float)delta_t / (float)TimeValue::NanoSecPerSec));
74254721Semaste                time_value = now;
75254721Semaste            }
76254721Semaste#endif
77254721Semaste        }
78254721Semaste    }
79254721Semaste    return m_frames.size ();
80254721Semaste}
81254721Semaste
82254721Semastebool
83254721SemasteUnwindLLDB::AddFirstFrame ()
84254721Semaste{
85254721Semaste    if (m_frames.size() > 0)
86254721Semaste        return true;
87254721Semaste
88254721Semaste    // First, set up the 0th (initial) frame
89254721Semaste    CursorSP first_cursor_sp(new Cursor ());
90254721Semaste    RegisterContextLLDBSP reg_ctx_sp (new RegisterContextLLDB (m_thread,
91254721Semaste                                                               RegisterContextLLDBSP(),
92254721Semaste                                                               first_cursor_sp->sctx,
93254721Semaste                                                               0, *this));
94254721Semaste    if (reg_ctx_sp.get() == NULL)
95254721Semaste        goto unwind_done;
96254721Semaste
97254721Semaste    if (!reg_ctx_sp->IsValid())
98254721Semaste        goto unwind_done;
99254721Semaste
100254721Semaste    if (!reg_ctx_sp->GetCFA (first_cursor_sp->cfa))
101254721Semaste        goto unwind_done;
102254721Semaste
103254721Semaste    if (!reg_ctx_sp->ReadPC (first_cursor_sp->start_pc))
104254721Semaste        goto unwind_done;
105254721Semaste
106254721Semaste    // Everything checks out, so release the auto pointer value and let the
107254721Semaste    // cursor own it in its shared pointer
108254721Semaste    first_cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
109254721Semaste    m_frames.push_back (first_cursor_sp);
110254721Semaste    return true;
111269024Semaste
112254721Semasteunwind_done:
113269024Semaste    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
114269024Semaste    if (log)
115269024Semaste    {
116269024Semaste        log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
117269024Semaste    }
118254721Semaste    m_unwind_complete = true;
119254721Semaste    return false;
120254721Semaste}
121254721Semaste
122254721Semaste// For adding a non-zero stack frame to m_frames.
123254721Semastebool
124254721SemasteUnwindLLDB::AddOneMoreFrame (ABI *abi)
125254721Semaste{
126254721Semaste    // If we've already gotten to the end of the stack, don't bother to try again...
127254721Semaste    if (m_unwind_complete)
128254721Semaste        return false;
129254721Semaste
130254721Semaste    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
131254721Semaste    CursorSP cursor_sp(new Cursor ());
132254721Semaste
133254721Semaste    // Frame zero is a little different
134254721Semaste    if (m_frames.size() == 0)
135254721Semaste        return false;
136254721Semaste
137254721Semaste    uint32_t cur_idx = m_frames.size ();
138254721Semaste    RegisterContextLLDBSP reg_ctx_sp(new RegisterContextLLDB (m_thread,
139254721Semaste                                                              m_frames[cur_idx - 1]->reg_ctx_lldb_sp,
140254721Semaste                                                              cursor_sp->sctx,
141254721Semaste                                                              cur_idx,
142254721Semaste                                                              *this));
143254721Semaste
144254721Semaste    // We want to detect an unwind that cycles erronously and stop backtracing.
145254721Semaste    // Don't want this maximum unwind limit to be too low -- if you have a backtrace
146254721Semaste    // with an "infinitely recursing" bug, it will crash when the stack blows out
147254721Semaste    // and the first 35,000 frames are uninteresting - it's the top most 5 frames that
148254721Semaste    // you actually care about.  So you can't just cap the unwind at 10,000 or something.
149254721Semaste    // Realistically anything over around 200,000 is going to blow out the stack space.
150254721Semaste    // If we're still unwinding at that point, we're probably never going to finish.
151254721Semaste    if (cur_idx > 300000)
152254721Semaste    {
153254721Semaste        if (log)
154254721Semaste            log->Printf ("%*sFrame %d unwound too many frames, assuming unwind has gone astray, stopping.",
155254721Semaste                         cur_idx < 100 ? cur_idx : 100, "", cur_idx);
156254721Semaste        goto unwind_done;
157254721Semaste    }
158254721Semaste
159254721Semaste    if (reg_ctx_sp.get() == NULL)
160269024Semaste    {
161269024Semaste        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
162269024Semaste        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
163269024Semaste        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
164269024Semaste        {
165269024Semaste            return AddOneMoreFrame (abi);
166269024Semaste        }
167269024Semaste        if (log)
168269024Semaste            log->Printf ("%*sFrame %d did not get a RegisterContext, stopping.",
169269024Semaste                         cur_idx < 100 ? cur_idx : 100, "", cur_idx);
170254721Semaste        goto unwind_done;
171269024Semaste    }
172254721Semaste
173254721Semaste    if (!reg_ctx_sp->IsValid())
174254721Semaste    {
175269024Semaste        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
176269024Semaste        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
177269024Semaste        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
178269024Semaste        {
179269024Semaste            return AddOneMoreFrame (abi);
180269024Semaste        }
181254721Semaste        if (log)
182254721Semaste        {
183254721Semaste            log->Printf("%*sFrame %d invalid RegisterContext for this frame, stopping stack walk",
184254721Semaste                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
185254721Semaste        }
186254721Semaste        goto unwind_done;
187254721Semaste    }
188254721Semaste    if (!reg_ctx_sp->GetCFA (cursor_sp->cfa))
189254721Semaste    {
190269024Semaste        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
191269024Semaste        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
192269024Semaste        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
193269024Semaste        {
194269024Semaste            return AddOneMoreFrame (abi);
195269024Semaste        }
196254721Semaste        if (log)
197254721Semaste        {
198254721Semaste            log->Printf("%*sFrame %d did not get CFA for this frame, stopping stack walk",
199254721Semaste                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
200254721Semaste        }
201254721Semaste        goto unwind_done;
202254721Semaste    }
203254721Semaste    if (abi && !abi->CallFrameAddressIsValid(cursor_sp->cfa))
204254721Semaste    {
205269024Semaste        // On Mac OS X, the _sigtramp asynchronous signal trampoline frame may not have
206269024Semaste        // its (constructed) CFA aligned correctly -- don't do the abi alignment check for
207269024Semaste        // these.
208269024Semaste        if (reg_ctx_sp->IsTrapHandlerFrame() == false)
209254721Semaste        {
210269024Semaste            // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
211269024Semaste            // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
212269024Semaste            if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
213269024Semaste            {
214269024Semaste                return AddOneMoreFrame (abi);
215269024Semaste            }
216269024Semaste            if (log)
217269024Semaste            {
218269024Semaste                log->Printf("%*sFrame %d did not get a valid CFA for this frame, stopping stack walk",
219269024Semaste                            cur_idx < 100 ? cur_idx : 100, "", cur_idx);
220269024Semaste            }
221269024Semaste            goto unwind_done;
222254721Semaste        }
223254721Semaste    }
224254721Semaste    if (!reg_ctx_sp->ReadPC (cursor_sp->start_pc))
225254721Semaste    {
226269024Semaste        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
227269024Semaste        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
228269024Semaste        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
229269024Semaste        {
230269024Semaste            return AddOneMoreFrame (abi);
231269024Semaste        }
232254721Semaste        if (log)
233254721Semaste        {
234254721Semaste            log->Printf("%*sFrame %d did not get PC for this frame, stopping stack walk",
235254721Semaste                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
236254721Semaste        }
237254721Semaste        goto unwind_done;
238254721Semaste    }
239254721Semaste    if (abi && !abi->CodeAddressIsValid (cursor_sp->start_pc))
240254721Semaste    {
241269024Semaste        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
242269024Semaste        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
243269024Semaste        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
244269024Semaste        {
245269024Semaste            return AddOneMoreFrame (abi);
246269024Semaste        }
247254721Semaste        if (log)
248254721Semaste        {
249254721Semaste            log->Printf("%*sFrame %d did not get a valid PC, stopping stack walk",
250254721Semaste                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
251254721Semaste        }
252254721Semaste        goto unwind_done;
253254721Semaste    }
254269024Semaste    if (!m_frames.empty())
255269024Semaste    {
256269024Semaste        // Infinite loop where the current cursor is the same as the previous one...
257269024Semaste        if (m_frames.back()->start_pc == cursor_sp->start_pc && m_frames.back()->cfa == cursor_sp->cfa)
258269024Semaste        {
259269024Semaste            if (log)
260269024Semaste                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());
261269024Semaste            goto unwind_done;
262269024Semaste        }
263269024Semaste    }
264263363Semaste
265254721Semaste    cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
266254721Semaste    m_frames.push_back (cursor_sp);
267254721Semaste    return true;
268254721Semaste
269254721Semasteunwind_done:
270269024Semaste    if (log)
271269024Semaste    {
272269024Semaste        log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
273269024Semaste    }
274254721Semaste    m_unwind_complete = true;
275254721Semaste    return false;
276254721Semaste}
277254721Semaste
278254721Semastebool
279254721SemasteUnwindLLDB::DoGetFrameInfoAtIndex (uint32_t idx, addr_t& cfa, addr_t& pc)
280254721Semaste{
281254721Semaste    if (m_frames.size() == 0)
282254721Semaste    {
283254721Semaste        if (!AddFirstFrame())
284254721Semaste            return false;
285254721Semaste    }
286254721Semaste
287254721Semaste    ProcessSP process_sp (m_thread.GetProcess());
288254721Semaste    ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
289254721Semaste
290254721Semaste    while (idx >= m_frames.size() && AddOneMoreFrame (abi))
291254721Semaste        ;
292254721Semaste
293254721Semaste    if (idx < m_frames.size ())
294254721Semaste    {
295254721Semaste        cfa = m_frames[idx]->cfa;
296254721Semaste        pc = m_frames[idx]->start_pc;
297254721Semaste        return true;
298254721Semaste    }
299254721Semaste    return false;
300254721Semaste}
301254721Semaste
302254721Semastelldb::RegisterContextSP
303254721SemasteUnwindLLDB::DoCreateRegisterContextForFrame (StackFrame *frame)
304254721Semaste{
305254721Semaste    lldb::RegisterContextSP reg_ctx_sp;
306254721Semaste    uint32_t idx = frame->GetConcreteFrameIndex ();
307254721Semaste
308254721Semaste    if (idx == 0)
309254721Semaste    {
310254721Semaste        return m_thread.GetRegisterContext();
311254721Semaste    }
312254721Semaste
313254721Semaste    if (m_frames.size() == 0)
314254721Semaste    {
315254721Semaste        if (!AddFirstFrame())
316254721Semaste            return reg_ctx_sp;
317254721Semaste    }
318254721Semaste
319254721Semaste    ProcessSP process_sp (m_thread.GetProcess());
320254721Semaste    ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
321254721Semaste
322254721Semaste    while (idx >= m_frames.size())
323254721Semaste    {
324254721Semaste        if (!AddOneMoreFrame (abi))
325254721Semaste            break;
326254721Semaste    }
327254721Semaste
328254721Semaste    const uint32_t num_frames = m_frames.size();
329254721Semaste    if (idx < num_frames)
330254721Semaste    {
331254721Semaste        Cursor *frame_cursor = m_frames[idx].get();
332254721Semaste        reg_ctx_sp = frame_cursor->reg_ctx_lldb_sp;
333254721Semaste    }
334254721Semaste    return reg_ctx_sp;
335254721Semaste}
336254721Semaste
337254721SemasteUnwindLLDB::RegisterContextLLDBSP
338254721SemasteUnwindLLDB::GetRegisterContextForFrameNum (uint32_t frame_num)
339254721Semaste{
340254721Semaste    RegisterContextLLDBSP reg_ctx_sp;
341254721Semaste    if (frame_num < m_frames.size())
342254721Semaste        reg_ctx_sp = m_frames[frame_num]->reg_ctx_lldb_sp;
343254721Semaste    return reg_ctx_sp;
344254721Semaste}
345254721Semaste
346254721Semastebool
347254721SemasteUnwindLLDB::SearchForSavedLocationForRegister (uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc, uint32_t starting_frame_num, bool pc_reg)
348254721Semaste{
349254721Semaste    int64_t frame_num = starting_frame_num;
350254721Semaste    if (frame_num >= m_frames.size())
351254721Semaste        return false;
352254721Semaste
353254721Semaste    // Never interrogate more than one level while looking for the saved pc value.  If the value
354254721Semaste    // isn't saved by frame_num, none of the frames lower on the stack will have a useful value.
355254721Semaste    if (pc_reg)
356254721Semaste    {
357254721Semaste        UnwindLLDB::RegisterSearchResult result;
358254721Semaste        result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister (lldb_regnum, regloc);
359254721Semaste        if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
360254721Semaste          return true;
361254721Semaste        else
362254721Semaste          return false;
363254721Semaste    }
364254721Semaste    while (frame_num >= 0)
365254721Semaste    {
366254721Semaste        UnwindLLDB::RegisterSearchResult result;
367254721Semaste        result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister (lldb_regnum, regloc);
368254721Semaste
369254721Semaste        // If we have unwind instructions saying that register N is saved in register M in the middle of
370254721Semaste        // the stack (and N can equal M here, meaning the register was not used in this function), then
371254721Semaste        // change the register number we're looking for to M and keep looking for a concrete  location
372254721Semaste        // down the stack, or an actual value from a live RegisterContext at frame 0.
373254721Semaste        if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound
374254721Semaste            && regloc.type == UnwindLLDB::RegisterLocation::eRegisterInRegister
375254721Semaste            && frame_num > 0)
376254721Semaste        {
377254721Semaste            result = UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
378254721Semaste            lldb_regnum = regloc.location.register_number;
379254721Semaste        }
380254721Semaste
381254721Semaste        if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
382254721Semaste            return true;
383254721Semaste        if (result == UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile)
384254721Semaste            return false;
385254721Semaste        frame_num--;
386254721Semaste    }
387254721Semaste    return false;
388254721Semaste}
389