UnwindLLDB.cpp revision 262528
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/Thread.h"
16#include "lldb/Target/Target.h"
17#include "lldb/Target/Process.h"
18#include "lldb/Target/RegisterContext.h"
19
20#include "UnwindLLDB.h"
21#include "RegisterContextLLDB.h"
22
23using namespace lldb;
24using namespace lldb_private;
25
26UnwindLLDB::UnwindLLDB (Thread &thread) :
27    Unwind (thread),
28    m_frames(),
29    m_unwind_complete(false),
30    m_user_supplied_trap_handler_functions()
31{
32    ProcessSP process_sp(thread.GetProcess());
33    if (process_sp)
34    {
35        Args args;
36        process_sp->GetTarget().GetUserSpecifiedTrapHandlerNames (args);
37        size_t count = args.GetArgumentCount();
38        for (size_t i = 0; i < count; i++)
39        {
40            const char *func_name = args.GetArgumentAtIndex(i);
41            m_user_supplied_trap_handler_functions.push_back (ConstString (func_name));
42        }
43    }
44}
45
46uint32_t
47UnwindLLDB::DoGetFrameCount()
48{
49    if (!m_unwind_complete)
50    {
51//#define DEBUG_FRAME_SPEED 1
52#if DEBUG_FRAME_SPEED
53#define FRAME_COUNT 10000
54        TimeValue time_value (TimeValue::Now());
55#endif
56        if (!AddFirstFrame ())
57            return 0;
58
59        ProcessSP process_sp (m_thread.GetProcess());
60        ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
61
62        while (AddOneMoreFrame (abi))
63        {
64#if DEBUG_FRAME_SPEED
65            if ((m_frames.size() % FRAME_COUNT) == 0)
66            {
67                TimeValue now(TimeValue::Now());
68                uint64_t delta_t = now - time_value;
69                printf ("%u frames in %" PRIu64 ".%09llu ms (%g frames/sec)\n",
70                        FRAME_COUNT,
71                        delta_t / TimeValue::NanoSecPerSec,
72                        delta_t % TimeValue::NanoSecPerSec,
73                        (float)FRAME_COUNT / ((float)delta_t / (float)TimeValue::NanoSecPerSec));
74                time_value = now;
75            }
76#endif
77        }
78    }
79    return m_frames.size ();
80}
81
82bool
83UnwindLLDB::AddFirstFrame ()
84{
85    if (m_frames.size() > 0)
86        return true;
87
88    // First, set up the 0th (initial) frame
89    CursorSP first_cursor_sp(new Cursor ());
90    RegisterContextLLDBSP reg_ctx_sp (new RegisterContextLLDB (m_thread,
91                                                               RegisterContextLLDBSP(),
92                                                               first_cursor_sp->sctx,
93                                                               0, *this));
94    if (reg_ctx_sp.get() == NULL)
95        goto unwind_done;
96
97    if (!reg_ctx_sp->IsValid())
98        goto unwind_done;
99
100    if (!reg_ctx_sp->GetCFA (first_cursor_sp->cfa))
101        goto unwind_done;
102
103    if (!reg_ctx_sp->ReadPC (first_cursor_sp->start_pc))
104        goto unwind_done;
105
106    // Everything checks out, so release the auto pointer value and let the
107    // cursor own it in its shared pointer
108    first_cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
109    m_frames.push_back (first_cursor_sp);
110    return true;
111
112unwind_done:
113    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
114    if (log)
115    {
116        log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
117    }
118    m_unwind_complete = true;
119    return false;
120}
121
122// For adding a non-zero stack frame to m_frames.
123bool
124UnwindLLDB::AddOneMoreFrame (ABI *abi)
125{
126    // If we've already gotten to the end of the stack, don't bother to try again...
127    if (m_unwind_complete)
128        return false;
129
130    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
131    CursorSP cursor_sp(new Cursor ());
132
133    // Frame zero is a little different
134    if (m_frames.size() == 0)
135        return false;
136
137    uint32_t cur_idx = m_frames.size ();
138    RegisterContextLLDBSP reg_ctx_sp(new RegisterContextLLDB (m_thread,
139                                                              m_frames[cur_idx - 1]->reg_ctx_lldb_sp,
140                                                              cursor_sp->sctx,
141                                                              cur_idx,
142                                                              *this));
143
144    // We want to detect an unwind that cycles erronously 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        goto unwind_done;
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 (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
164        {
165            return AddOneMoreFrame (abi);
166        }
167        if (log)
168            log->Printf ("%*sFrame %d did not get a RegisterContext, stopping.",
169                         cur_idx < 100 ? cur_idx : 100, "", cur_idx);
170        goto unwind_done;
171    }
172
173    if (!reg_ctx_sp->IsValid())
174    {
175        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
176        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
177        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
178        {
179            return AddOneMoreFrame (abi);
180        }
181        if (log)
182        {
183            log->Printf("%*sFrame %d invalid RegisterContext for this frame, stopping stack walk",
184                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
185        }
186        goto unwind_done;
187    }
188    if (!reg_ctx_sp->GetCFA (cursor_sp->cfa))
189    {
190        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
191        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
192        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
193        {
194            return AddOneMoreFrame (abi);
195        }
196        if (log)
197        {
198            log->Printf("%*sFrame %d did not get CFA for this frame, stopping stack walk",
199                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
200        }
201        goto unwind_done;
202    }
203    if (abi && !abi->CallFrameAddressIsValid(cursor_sp->cfa))
204    {
205        // On Mac OS X, the _sigtramp asynchronous signal trampoline frame may not have
206        // its (constructed) CFA aligned correctly -- don't do the abi alignment check for
207        // these.
208        if (reg_ctx_sp->IsTrapHandlerFrame() == false)
209        {
210            // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
211            // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
212            if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
213            {
214                return AddOneMoreFrame (abi);
215            }
216            if (log)
217            {
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            }
221            goto unwind_done;
222        }
223    }
224    if (!reg_ctx_sp->ReadPC (cursor_sp->start_pc))
225    {
226        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
227        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
228        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
229        {
230            return AddOneMoreFrame (abi);
231        }
232        if (log)
233        {
234            log->Printf("%*sFrame %d did not get PC for this frame, stopping stack walk",
235                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
236        }
237        goto unwind_done;
238    }
239    if (abi && !abi->CodeAddressIsValid (cursor_sp->start_pc))
240    {
241        // If the RegisterContextLLDB has a fallback UnwindPlan, it will switch to that and return
242        // true.  Subsequent calls to TryFallbackUnwindPlan() will return false.
243        if (m_frames[cur_idx - 1]->reg_ctx_lldb_sp->TryFallbackUnwindPlan())
244        {
245            return AddOneMoreFrame (abi);
246        }
247        if (log)
248        {
249            log->Printf("%*sFrame %d did not get a valid PC, stopping stack walk",
250                        cur_idx < 100 ? cur_idx : 100, "", cur_idx);
251        }
252        goto unwind_done;
253    }
254    if (!m_frames.empty())
255    {
256        // Infinite loop where the current cursor is the same as the previous one...
257        if (m_frames.back()->start_pc == cursor_sp->start_pc && m_frames.back()->cfa == cursor_sp->cfa)
258        {
259            if (log)
260                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());
261            goto unwind_done;
262        }
263    }
264
265    cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
266    m_frames.push_back (cursor_sp);
267    return true;
268
269unwind_done:
270    if (log)
271    {
272        log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
273    }
274    m_unwind_complete = true;
275    return false;
276}
277
278bool
279UnwindLLDB::DoGetFrameInfoAtIndex (uint32_t idx, addr_t& cfa, addr_t& pc)
280{
281    if (m_frames.size() == 0)
282    {
283        if (!AddFirstFrame())
284            return false;
285    }
286
287    ProcessSP process_sp (m_thread.GetProcess());
288    ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
289
290    while (idx >= m_frames.size() && AddOneMoreFrame (abi))
291        ;
292
293    if (idx < m_frames.size ())
294    {
295        cfa = m_frames[idx]->cfa;
296        pc = m_frames[idx]->start_pc;
297        return true;
298    }
299    return false;
300}
301
302lldb::RegisterContextSP
303UnwindLLDB::DoCreateRegisterContextForFrame (StackFrame *frame)
304{
305    lldb::RegisterContextSP reg_ctx_sp;
306    uint32_t idx = frame->GetConcreteFrameIndex ();
307
308    if (idx == 0)
309    {
310        return m_thread.GetRegisterContext();
311    }
312
313    if (m_frames.size() == 0)
314    {
315        if (!AddFirstFrame())
316            return reg_ctx_sp;
317    }
318
319    ProcessSP process_sp (m_thread.GetProcess());
320    ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
321
322    while (idx >= m_frames.size())
323    {
324        if (!AddOneMoreFrame (abi))
325            break;
326    }
327
328    const uint32_t num_frames = m_frames.size();
329    if (idx < num_frames)
330    {
331        Cursor *frame_cursor = m_frames[idx].get();
332        reg_ctx_sp = frame_cursor->reg_ctx_lldb_sp;
333    }
334    return reg_ctx_sp;
335}
336
337UnwindLLDB::RegisterContextLLDBSP
338UnwindLLDB::GetRegisterContextForFrameNum (uint32_t frame_num)
339{
340    RegisterContextLLDBSP reg_ctx_sp;
341    if (frame_num < m_frames.size())
342        reg_ctx_sp = m_frames[frame_num]->reg_ctx_lldb_sp;
343    return reg_ctx_sp;
344}
345
346bool
347UnwindLLDB::SearchForSavedLocationForRegister (uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc, uint32_t starting_frame_num, bool pc_reg)
348{
349    int64_t frame_num = starting_frame_num;
350    if (frame_num >= m_frames.size())
351        return false;
352
353    // Never interrogate more than one level while looking for the saved pc value.  If the value
354    // isn't saved by frame_num, none of the frames lower on the stack will have a useful value.
355    if (pc_reg)
356    {
357        UnwindLLDB::RegisterSearchResult result;
358        result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister (lldb_regnum, regloc);
359        if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
360          return true;
361        else
362          return false;
363    }
364    while (frame_num >= 0)
365    {
366        UnwindLLDB::RegisterSearchResult result;
367        result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister (lldb_regnum, regloc);
368
369        // If we have unwind instructions saying that register N is saved in register M in the middle of
370        // the stack (and N can equal M here, meaning the register was not used in this function), then
371        // change the register number we're looking for to M and keep looking for a concrete  location
372        // down the stack, or an actual value from a live RegisterContext at frame 0.
373        if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound
374            && regloc.type == UnwindLLDB::RegisterLocation::eRegisterInRegister
375            && frame_num > 0)
376        {
377            result = UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
378            lldb_regnum = regloc.location.register_number;
379        }
380
381        if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
382            return true;
383        if (result == UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile)
384            return false;
385        frame_num--;
386    }
387    return false;
388}
389