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