LLDB mainline
UnwindLLDB.cpp
Go to the documentation of this file.
1//===-- UnwindLLDB.cpp ----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "lldb/Core/Module.h"
14#include "lldb/Target/ABI.h"
15#include "lldb/Target/Process.h"
18#include "lldb/Target/Target.h"
19#include "lldb/Target/Thread.h"
21#include "lldb/Utility/Log.h"
22
23using namespace lldb;
24using namespace lldb_private;
25
27 : Unwind(thread), m_frames(), m_unwind_complete(false),
29 ProcessSP process_sp(thread.GetProcess());
30 if (process_sp) {
31 Args args;
32 process_sp->GetTarget().GetUserSpecifiedTrapHandlerNames(args);
33 size_t count = args.GetArgumentCount();
34 for (size_t i = 0; i < count; i++) {
35 const char *func_name = args.GetArgumentAtIndex(i);
37 }
38 }
39}
40
42 if (!m_unwind_complete) {
43//#define DEBUG_FRAME_SPEED 1
44#if DEBUG_FRAME_SPEED
45#define FRAME_COUNT 10000
46 using namespace std::chrono;
47 auto time_value = steady_clock::now();
48#endif
49 if (!AddFirstFrame())
50 return 0;
51
52 ProcessSP process_sp(m_thread.GetProcess());
53 ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
54
55 while (AddOneMoreFrame(abi)) {
56#if DEBUG_FRAME_SPEED
57 if ((m_frames.size() % FRAME_COUNT) == 0) {
58 const auto now = steady_clock::now();
59 const auto delta_t = now - time_value;
60 printf("%u frames in %.9f ms (%g frames/sec)\n", FRAME_COUNT,
61 duration<double, std::milli>(delta_t).count(),
62 (float)FRAME_COUNT / duration<double>(delta_t).count());
63 time_value = now;
64 }
65#endif
66 }
67 }
68 return m_frames.size();
69}
70
72 if (m_frames.size() > 0)
73 return true;
74
75 ProcessSP process_sp(m_thread.GetProcess());
76 ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
77
78 // First, set up the 0th (initial) frame
79 CursorSP first_cursor_sp(new Cursor());
81 m_thread, RegisterContextLLDBSP(), first_cursor_sp->sctx, 0, *this));
82 if (reg_ctx_sp.get() == nullptr)
83 goto unwind_done;
84
85 if (!reg_ctx_sp->IsValid())
86 goto unwind_done;
87
88 if (!reg_ctx_sp->GetCFA(first_cursor_sp->cfa))
89 goto unwind_done;
90
91 if (!reg_ctx_sp->ReadPC(first_cursor_sp->start_pc))
92 goto unwind_done;
93
94 // Everything checks out, so release the auto pointer value and let the
95 // cursor own it in its shared pointer
96 first_cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
97 m_frames.push_back(first_cursor_sp);
98
99 // Update the Full Unwind Plan for this frame if not valid
101
102 return true;
103
104unwind_done:
105 Log *log = GetLog(LLDBLog::Unwind);
106 LLDB_LOGF(log, "th%d Unwind of this thread is complete.",
107 m_thread.GetIndexID());
108 m_unwind_complete = true;
109 return false;
110}
111
113 assert(m_frames.size() != 0 &&
114 "Get one more frame called with empty frame list");
115
116 // If we've already gotten to the end of the stack, don't bother to try
117 // again...
119 return nullptr;
120
121 Log *log = GetLog(LLDBLog::Unwind);
122
123 CursorSP prev_frame = m_frames.back();
124 uint32_t cur_idx = m_frames.size();
125
126 CursorSP cursor_sp(new Cursor());
128 m_thread, prev_frame->reg_ctx_lldb_sp, cursor_sp->sctx, cur_idx, *this));
129
130 uint64_t max_stack_depth = m_thread.GetMaxBacktraceDepth();
131
132 // We want to detect an unwind that cycles erroneously and stop backtracing.
133 // Don't want this maximum unwind limit to be too low -- if you have a
134 // backtrace with an "infinitely recursing" bug, it will crash when the stack
135 // blows out and the first 35,000 frames are uninteresting - it's the top
136 // most 5 frames that you actually care about. So you can't just cap the
137 // unwind at 10,000 or something. Realistically anything over around 200,000
138 // is going to blow out the stack space. If we're still unwinding at that
139 // point, we're probably never going to finish.
140 if (cur_idx >= max_stack_depth) {
141 LLDB_LOGF(log,
142 "%*sFrame %d unwound too many frames, assuming unwind has "
143 "gone astray, stopping.",
144 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
145 return nullptr;
146 }
147
148 if (reg_ctx_sp.get() == nullptr) {
149 // If the RegisterContextUnwind has a fallback UnwindPlan, it will switch to
150 // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
151 // return false.
152 if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
153 // TryFallbackUnwindPlan for prev_frame succeeded and updated
154 // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
155 // still needs to be updated. Hence updating it.
156 if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
157 return nullptr;
158
159 return GetOneMoreFrame(abi);
160 }
161
162 LLDB_LOGF(log, "%*sFrame %d did not get a RegisterContext, stopping.",
163 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
164 return nullptr;
165 }
166
167 if (!reg_ctx_sp->IsValid()) {
168 // We failed to get a valid RegisterContext. See if the regctx below this
169 // on the stack has a fallback unwind plan it can use. Subsequent calls to
170 // TryFallbackUnwindPlan() will return false.
171 if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
172 // TryFallbackUnwindPlan for prev_frame succeeded and updated
173 // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
174 // still needs to be updated. Hence updating it.
175 if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
176 return nullptr;
177
178 return GetOneMoreFrame(abi);
179 }
180
181 LLDB_LOGF(log,
182 "%*sFrame %d invalid RegisterContext for this frame, "
183 "stopping stack walk",
184 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
185 return nullptr;
186 }
187 if (!reg_ctx_sp->GetCFA(cursor_sp->cfa)) {
188 // If the RegisterContextUnwind has a fallback UnwindPlan, it will switch to
189 // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
190 // return false.
191 if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
192 // TryFallbackUnwindPlan for prev_frame succeeded and updated
193 // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
194 // 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 LLDB_LOGF(log,
202 "%*sFrame %d did not get CFA for this frame, stopping stack walk",
203 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
204 return nullptr;
205 }
206 if (abi && !abi->CallFrameAddressIsValid(cursor_sp->cfa)) {
207 // On Mac OS X, the _sigtramp asynchronous signal trampoline frame may not
208 // have its (constructed) CFA aligned correctly -- don't do the abi
209 // alignment check for these.
210 if (!reg_ctx_sp->IsTrapHandlerFrame()) {
211 // See if we can find a fallback unwind plan for THIS frame. It may be
212 // that the UnwindPlan we're using for THIS frame was bad and gave us a
213 // bad CFA. If that's not it, then see if we can change the UnwindPlan
214 // for the frame below us ("NEXT") -- see if using that other UnwindPlan
215 // gets us a better unwind state.
216 if (!reg_ctx_sp->TryFallbackUnwindPlan() ||
217 !reg_ctx_sp->GetCFA(cursor_sp->cfa) ||
218 !abi->CallFrameAddressIsValid(cursor_sp->cfa)) {
219 if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
220 // TryFallbackUnwindPlan for prev_frame succeeded and updated
221 // reg_ctx_lldb_sp field of prev_frame. However, cfa field of
222 // prev_frame still needs to be updated. Hence updating it.
223 if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
224 return nullptr;
225
226 return GetOneMoreFrame(abi);
227 }
228
229 LLDB_LOGF(log,
230 "%*sFrame %d did not get a valid CFA for this frame, "
231 "stopping stack walk",
232 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
233 return nullptr;
234 } else {
235 LLDB_LOGF(log,
236 "%*sFrame %d had a bad CFA value but we switched the "
237 "UnwindPlan being used and got one that looks more "
238 "realistic.",
239 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
240 }
241 }
242 }
243 if (!reg_ctx_sp->ReadPC(cursor_sp->start_pc)) {
244 // If the RegisterContextUnwind has a fallback UnwindPlan, it will switch to
245 // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
246 // return false.
247 if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
248 // TryFallbackUnwindPlan for prev_frame succeeded and updated
249 // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
250 // still needs to be updated. Hence updating it.
251 if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
252 return nullptr;
253
254 return GetOneMoreFrame(abi);
255 }
256
257 LLDB_LOGF(log,
258 "%*sFrame %d did not get PC for this frame, stopping stack walk",
259 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
260 return nullptr;
261 }
262
263 // Invalid code addresses should not appear on the stack *unless* we're
264 // directly below a trap handler frame (in this case, the invalid address is
265 // likely the cause of the trap).
266 if (abi && !abi->CodeAddressIsValid(cursor_sp->start_pc) &&
267 !prev_frame->reg_ctx_lldb_sp->IsTrapHandlerFrame()) {
268 // If the RegisterContextUnwind has a fallback UnwindPlan, it will switch to
269 // that and return true. Subsequent calls to TryFallbackUnwindPlan() will
270 // return false.
271 if (prev_frame->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
272 // TryFallbackUnwindPlan for prev_frame succeeded and updated
273 // reg_ctx_lldb_sp field of prev_frame. However, cfa field of prev_frame
274 // still needs to be updated. Hence updating it.
275 if (!(prev_frame->reg_ctx_lldb_sp->GetCFA(prev_frame->cfa)))
276 return nullptr;
277
278 return GetOneMoreFrame(abi);
279 }
280
281 LLDB_LOGF(log, "%*sFrame %d did not get a valid PC, stopping stack walk",
282 cur_idx < 100 ? cur_idx : 100, "", cur_idx);
283 return nullptr;
284 }
285 // Infinite loop where the current cursor is the same as the previous one...
286 if (prev_frame->start_pc == cursor_sp->start_pc &&
287 prev_frame->cfa == cursor_sp->cfa) {
288 LLDB_LOGF(log,
289 "th%d pc of this frame is the same as the previous frame and "
290 "CFAs for both frames are identical -- stopping unwind",
291 m_thread.GetIndexID());
292 return nullptr;
293 }
294
295 cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
296 return cursor_sp;
297}
298
300 // This function is called for First Frame only.
301 assert(m_frames.size() == 1 && "No. of cursor frames are not 1");
302
303 bool old_m_unwind_complete = m_unwind_complete;
304 CursorSP old_m_candidate_frame = m_candidate_frame;
305
306 // Try to unwind 2 more frames using the Unwinder. It uses Full UnwindPlan
307 // and if Full UnwindPlan fails, then uses FallBack UnwindPlan. Also update
308 // the cfa of Frame 0 (if required).
309 AddOneMoreFrame(abi);
310
311 // Remove all the frames added by above function as the purpose of using
312 // above function was just to check whether Unwinder of Frame 0 works or not.
313 for (uint32_t i = 1; i < m_frames.size(); i++)
314 m_frames.pop_back();
315
316 // Restore status after calling AddOneMoreFrame
317 m_unwind_complete = old_m_unwind_complete;
318 m_candidate_frame = old_m_candidate_frame;
319}
320
322 Log *log = GetLog(LLDBLog::Unwind);
323
324 // Frame zero is a little different
325 if (m_frames.empty())
326 return false;
327
328 // If we've already gotten to the end of the stack, don't bother to try
329 // again...
331 return false;
332
333 CursorSP new_frame = m_candidate_frame;
334 if (new_frame == nullptr)
335 new_frame = GetOneMoreFrame(abi);
336
337 if (new_frame == nullptr) {
338 LLDB_LOGF(log, "th%d Unwind of this thread is complete.",
339 m_thread.GetIndexID());
340 m_unwind_complete = true;
341 return false;
342 }
343
344 m_frames.push_back(new_frame);
345
346 // If we can get one more frame further then accept that we get back a
347 // correct frame.
350 return true;
351
352 // We can't go further from the frame returned by GetOneMore frame. Lets try
353 // to get a different frame with using the fallback unwind plan.
354 if (!m_frames[m_frames.size() - 2]
355 ->reg_ctx_lldb_sp->TryFallbackUnwindPlan()) {
356 // We don't have a valid fallback unwind plan. Accept the frame as it is.
357 // This is a valid situation when we are at the bottom of the stack.
358 return true;
359 }
360
361 // Remove the possibly incorrect frame from the frame list and try to add a
362 // different one with the newly selected fallback unwind plan.
363 m_frames.pop_back();
364 CursorSP new_frame_v2 = GetOneMoreFrame(abi);
365 if (new_frame_v2 == nullptr) {
366 // We haven't got a new frame from the fallback unwind plan. Accept the
367 // frame from the original unwind plan. This is a valid situation when we
368 // are at the bottom of the stack.
369 m_frames.push_back(new_frame);
370 return true;
371 }
372
373 // Push the new frame to the list and try to continue from this frame. If we
374 // can get a new frame then accept it as the correct one.
375 m_frames.push_back(new_frame_v2);
377 if (m_candidate_frame) {
378 // If control reached here then TryFallbackUnwindPlan had succeeded for
379 // Cursor::m_frames[m_frames.size() - 2]. It also succeeded to Unwind next
380 // 2 frames i.e. m_frames[m_frames.size() - 1] and a frame after that. For
381 // Cursor::m_frames[m_frames.size() - 2], reg_ctx_lldb_sp field was already
382 // updated during TryFallbackUnwindPlan call above. However, cfa field
383 // still needs to be updated. Hence updating it here and then returning.
384 return m_frames[m_frames.size() - 2]->reg_ctx_lldb_sp->GetCFA(
385 m_frames[m_frames.size() - 2]->cfa);
386 }
387
388 // The new frame hasn't helped in unwinding. Fall back to the original one as
389 // the default unwind plan is usually more reliable then the fallback one.
390 m_frames.pop_back();
391 m_frames.push_back(new_frame);
392 return true;
393}
394
396 bool &behaves_like_zeroth_frame) {
397 if (m_frames.size() == 0) {
398 if (!AddFirstFrame())
399 return false;
400 }
401
402 ProcessSP process_sp(m_thread.GetProcess());
403 ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
404
405 while (idx >= m_frames.size() && AddOneMoreFrame(abi))
406 ;
407
408 if (idx < m_frames.size()) {
409 cfa = m_frames[idx]->cfa;
410 pc = m_frames[idx]->start_pc;
411 if (idx == 0) {
412 // Frame zero always behaves like it.
413 behaves_like_zeroth_frame = true;
414 } else if (m_frames[idx - 1]->reg_ctx_lldb_sp->IsTrapHandlerFrame()) {
415 // This could be an asynchronous signal, thus the
416 // pc might point to the interrupted instruction rather
417 // than a post-call instruction
418 behaves_like_zeroth_frame = true;
419 } else if (m_frames[idx]->reg_ctx_lldb_sp->IsTrapHandlerFrame()) {
420 // This frame may result from signal processing installing
421 // a pointer to the first byte of a signal-return trampoline
422 // in the return address slot of the frame below, so this
423 // too behaves like the zeroth frame (i.e. the pc might not
424 // be pointing just past a call in it)
425 behaves_like_zeroth_frame = true;
426 } else if (m_frames[idx]->reg_ctx_lldb_sp->BehavesLikeZerothFrame()) {
427 behaves_like_zeroth_frame = true;
428 } else {
429 behaves_like_zeroth_frame = false;
430 }
431 return true;
432 }
433 return false;
434}
435
438 lldb::RegisterContextSP reg_ctx_sp;
439 uint32_t idx = frame->GetConcreteFrameIndex();
440
441 if (idx == 0) {
442 return m_thread.GetRegisterContext();
443 }
444
445 if (m_frames.size() == 0) {
446 if (!AddFirstFrame())
447 return reg_ctx_sp;
448 }
449
450 ProcessSP process_sp(m_thread.GetProcess());
451 ABI *abi = process_sp ? process_sp->GetABI().get() : nullptr;
452
453 while (idx >= m_frames.size()) {
454 if (!AddOneMoreFrame(abi))
455 break;
456 }
457
458 const uint32_t num_frames = m_frames.size();
459 if (idx < num_frames) {
460 Cursor *frame_cursor = m_frames[idx].get();
461 reg_ctx_sp = frame_cursor->reg_ctx_lldb_sp;
462 }
463 return reg_ctx_sp;
464}
465
468 RegisterContextLLDBSP reg_ctx_sp;
469 if (frame_num < m_frames.size())
470 reg_ctx_sp = m_frames[frame_num]->reg_ctx_lldb_sp;
471 return reg_ctx_sp;
472}
473
475 uint32_t lldb_regnum,
477 uint32_t starting_frame_num, bool pc_reg) {
478 int64_t frame_num = starting_frame_num;
479 if (static_cast<size_t>(frame_num) >= m_frames.size())
480 return false;
481
482 // Never interrogate more than one level while looking for the saved pc
483 // value. If the value isn't saved by frame_num, none of the frames lower on
484 // the stack will have a useful value.
485 if (pc_reg) {
487 result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister(
488 lldb_regnum, regloc);
490 }
491 while (frame_num >= 0) {
493 result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister(
494 lldb_regnum, regloc);
495
496 // We descended down to the live register context aka stack frame 0 and are
497 // reading the value out of a live register.
500 eRegisterInLiveRegisterContext) {
501 return true;
502 }
503
504 // If we have unwind instructions saying that register N is saved in
505 // register M in the middle of the stack (and N can equal M here, meaning
506 // the register was not used in this function), then change the register
507 // number we're looking for to M and keep looking for a concrete location
508 // down the stack, or an actual value from a live RegisterContext at frame
509 // 0.
511 regloc.type ==
513 frame_num > 0) {
515 lldb_regnum = regloc.location.register_number;
516 }
517
519 return true;
521 return false;
522 frame_num--;
523 }
524 return false;
525}
#define LLDB_LOGF(log,...)
Definition Log.h:383
virtual bool CodeAddressIsValid(lldb::addr_t pc)=0
virtual bool CallFrameAddressIsValid(lldb::addr_t cfa)=0
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
A uniqued constant string class.
Definition ConstString.h:40
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual uint32_t GetConcreteFrameIndex()
Query this frame to find what frame it is in this Thread's StackFrameList, not counting inlined frame...
Definition StackFrame.h:471
void UpdateUnwindPlanForFirstFrameIfInvalid(ABI *abi)
std::vector< ConstString > m_user_supplied_trap_handler_functions
Definition UnwindLLDB.h:152
std::vector< CursorSP > m_frames
Definition UnwindLLDB.h:144
RegisterContextLLDBSP GetRegisterContextForFrameNum(uint32_t frame_num)
lldb::RegisterContextSP DoCreateRegisterContextForFrame(lldb_private::StackFrame *frame) override
UnwindLLDB(lldb_private::Thread &thread)
friend class lldb_private::RegisterContextUnwind
Definition UnwindLLDB.h:40
std::shared_ptr< Cursor > CursorSP
Definition UnwindLLDB.h:143
bool AddOneMoreFrame(ABI *abi)
CursorSP GetOneMoreFrame(ABI *abi)
std::shared_ptr< RegisterContextUnwind > RegisterContextLLDBSP
Definition UnwindLLDB.h:95
bool DoGetFrameInfoAtIndex(uint32_t frame_idx, lldb::addr_t &cfa, lldb::addr_t &start_pc, bool &behaves_like_zeroth_frame) override
bool SearchForSavedLocationForRegister(uint32_t lldb_regnum, lldb_private::UnwindLLDB::ConcreteRegisterLocation &regloc, uint32_t starting_frame_num, bool pc_register)
uint32_t DoGetFrameCount() override
Thread & m_thread
Definition Unwind.h:76
Unwind(Thread &thread)
Definition Unwind.h:21
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
An UnwindPlan::Row::AbstractRegisterLocation, combined with the register context and memory for a spe...
Definition UnwindLLDB.h:46
union lldb_private::UnwindLLDB::ConcreteRegisterLocation::@112231307016025255352221255122100277032134020214 location
RegisterContextLLDBSP reg_ctx_lldb_sp
Definition UnwindLLDB.h:134