1 //===-- StackFrameList.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 9 #include "lldb/Target/StackFrameList.h" 10 #include "lldb/Breakpoint/Breakpoint.h" 11 #include "lldb/Breakpoint/BreakpointLocation.h" 12 #include "lldb/Core/SourceManager.h" 13 #include "lldb/Core/StreamFile.h" 14 #include "lldb/Symbol/Block.h" 15 #include "lldb/Symbol/Function.h" 16 #include "lldb/Symbol/Symbol.h" 17 #include "lldb/Target/Process.h" 18 #include "lldb/Target/RegisterContext.h" 19 #include "lldb/Target/StackFrame.h" 20 #include "lldb/Target/StopInfo.h" 21 #include "lldb/Target/Target.h" 22 #include "lldb/Target/Thread.h" 23 #include "lldb/Target/Unwind.h" 24 #include "lldb/Utility/Log.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 27 #include <memory> 28 29 //#define DEBUG_STACK_FRAMES 1 30 31 using namespace lldb; 32 using namespace lldb_private; 33 34 // StackFrameList constructor 35 StackFrameList::StackFrameList(Thread &thread, 36 const lldb::StackFrameListSP &prev_frames_sp, 37 bool show_inline_frames) 38 : m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_mutex(), m_frames(), 39 m_selected_frame_idx(0), m_concrete_frames_fetched(0), 40 m_current_inlined_depth(UINT32_MAX), 41 m_current_inlined_pc(LLDB_INVALID_ADDRESS), 42 m_show_inlined_frames(show_inline_frames) { 43 if (prev_frames_sp) { 44 m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth; 45 m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc; 46 } 47 } 48 49 StackFrameList::~StackFrameList() { 50 // Call clear since this takes a lock and clears the stack frame list in case 51 // another thread is currently using this stack frame list 52 Clear(); 53 } 54 55 void StackFrameList::CalculateCurrentInlinedDepth() { 56 uint32_t cur_inlined_depth = GetCurrentInlinedDepth(); 57 if (cur_inlined_depth == UINT32_MAX) { 58 ResetCurrentInlinedDepth(); 59 } 60 } 61 62 uint32_t StackFrameList::GetCurrentInlinedDepth() { 63 if (m_show_inlined_frames && m_current_inlined_pc != LLDB_INVALID_ADDRESS) { 64 lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC(); 65 if (cur_pc != m_current_inlined_pc) { 66 m_current_inlined_pc = LLDB_INVALID_ADDRESS; 67 m_current_inlined_depth = UINT32_MAX; 68 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 69 if (log && log->GetVerbose()) 70 LLDB_LOGF( 71 log, 72 "GetCurrentInlinedDepth: invalidating current inlined depth.\n"); 73 } 74 return m_current_inlined_depth; 75 } else { 76 return UINT32_MAX; 77 } 78 } 79 80 void StackFrameList::ResetCurrentInlinedDepth() { 81 if (!m_show_inlined_frames) 82 return; 83 84 std::lock_guard<std::recursive_mutex> guard(m_mutex); 85 86 GetFramesUpTo(0); 87 if (m_frames.empty()) 88 return; 89 if (!m_frames[0]->IsInlined()) { 90 m_current_inlined_depth = UINT32_MAX; 91 m_current_inlined_pc = LLDB_INVALID_ADDRESS; 92 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 93 if (log && log->GetVerbose()) 94 LLDB_LOGF( 95 log, 96 "ResetCurrentInlinedDepth: Invalidating current inlined depth.\n"); 97 return; 98 } 99 100 // We only need to do something special about inlined blocks when we are 101 // at the beginning of an inlined function: 102 // FIXME: We probably also have to do something special if the PC is at 103 // the END of an inlined function, which coincides with the end of either 104 // its containing function or another inlined function. 105 106 Block *block_ptr = m_frames[0]->GetFrameBlock(); 107 if (!block_ptr) 108 return; 109 110 Address pc_as_address; 111 lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC(); 112 pc_as_address.SetLoadAddress(curr_pc, &(m_thread.GetProcess()->GetTarget())); 113 AddressRange containing_range; 114 if (!block_ptr->GetRangeContainingAddress(pc_as_address, containing_range) || 115 pc_as_address != containing_range.GetBaseAddress()) 116 return; 117 118 // If we got here because of a breakpoint hit, then set the inlined depth 119 // depending on where the breakpoint was set. If we got here because of a 120 // crash, then set the inlined depth to the deepest most block. Otherwise, 121 // we stopped here naturally as the result of a step, so set ourselves in the 122 // containing frame of the whole set of nested inlines, so the user can then 123 // "virtually" step into the frames one by one, or next over the whole mess. 124 // Note: We don't have to handle being somewhere in the middle of the stack 125 // here, since ResetCurrentInlinedDepth doesn't get called if there is a 126 // valid inlined depth set. 127 StopInfoSP stop_info_sp = m_thread.GetStopInfo(); 128 if (!stop_info_sp) 129 return; 130 switch (stop_info_sp->GetStopReason()) { 131 case eStopReasonWatchpoint: 132 case eStopReasonException: 133 case eStopReasonExec: 134 case eStopReasonSignal: 135 // In all these cases we want to stop in the deepest frame. 136 m_current_inlined_pc = curr_pc; 137 m_current_inlined_depth = 0; 138 break; 139 case eStopReasonBreakpoint: { 140 // FIXME: Figure out what this break point is doing, and set the inline 141 // depth appropriately. Be careful to take into account breakpoints that 142 // implement step over prologue, since that should do the default 143 // calculation. For now, if the breakpoints corresponding to this hit are 144 // all internal, I set the stop location to the top of the inlined stack, 145 // since that will make things like stepping over prologues work right. 146 // But if there are any non-internal breakpoints I do to the bottom of the 147 // stack, since that was the old behavior. 148 uint32_t bp_site_id = stop_info_sp->GetValue(); 149 BreakpointSiteSP bp_site_sp( 150 m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id)); 151 bool all_internal = true; 152 if (bp_site_sp) { 153 uint32_t num_owners = bp_site_sp->GetNumberOfOwners(); 154 for (uint32_t i = 0; i < num_owners; i++) { 155 Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint(); 156 if (!bp_ref.IsInternal()) { 157 all_internal = false; 158 } 159 } 160 } 161 if (!all_internal) { 162 m_current_inlined_pc = curr_pc; 163 m_current_inlined_depth = 0; 164 break; 165 } 166 } 167 LLVM_FALLTHROUGH; 168 default: { 169 // Otherwise, we should set ourselves at the container of the inlining, so 170 // that the user can descend into them. So first we check whether we have 171 // more than one inlined block sharing this PC: 172 int num_inlined_functions = 0; 173 174 for (Block *container_ptr = block_ptr->GetInlinedParent(); 175 container_ptr != nullptr; 176 container_ptr = container_ptr->GetInlinedParent()) { 177 if (!container_ptr->GetRangeContainingAddress(pc_as_address, 178 containing_range)) 179 break; 180 if (pc_as_address != containing_range.GetBaseAddress()) 181 break; 182 183 num_inlined_functions++; 184 } 185 m_current_inlined_pc = curr_pc; 186 m_current_inlined_depth = num_inlined_functions + 1; 187 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 188 if (log && log->GetVerbose()) 189 LLDB_LOGF(log, 190 "ResetCurrentInlinedDepth: setting inlined " 191 "depth: %d 0x%" PRIx64 ".\n", 192 m_current_inlined_depth, curr_pc); 193 194 break; 195 } 196 } 197 } 198 199 bool StackFrameList::DecrementCurrentInlinedDepth() { 200 if (m_show_inlined_frames) { 201 uint32_t current_inlined_depth = GetCurrentInlinedDepth(); 202 if (current_inlined_depth != UINT32_MAX) { 203 if (current_inlined_depth > 0) { 204 m_current_inlined_depth--; 205 return true; 206 } 207 } 208 } 209 return false; 210 } 211 212 void StackFrameList::SetCurrentInlinedDepth(uint32_t new_depth) { 213 m_current_inlined_depth = new_depth; 214 if (new_depth == UINT32_MAX) 215 m_current_inlined_pc = LLDB_INVALID_ADDRESS; 216 else 217 m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC(); 218 } 219 220 void StackFrameList::GetOnlyConcreteFramesUpTo(uint32_t end_idx, 221 Unwind &unwinder) { 222 assert(m_thread.IsValid() && "Expected valid thread"); 223 assert(m_frames.size() <= end_idx && "Expected there to be frames to fill"); 224 225 if (end_idx < m_concrete_frames_fetched) 226 return; 227 228 uint32_t num_frames = unwinder.GetFramesUpTo(end_idx); 229 if (num_frames <= end_idx + 1) { 230 // Done unwinding. 231 m_concrete_frames_fetched = UINT32_MAX; 232 } 233 234 // Don't create the frames eagerly. Defer this work to GetFrameAtIndex, 235 // which can lazily query the unwinder to create frames. 236 m_frames.resize(num_frames); 237 } 238 239 /// A sequence of calls that comprise some portion of a backtrace. Each frame 240 /// is represented as a pair of a callee (Function *) and an address within the 241 /// callee. 242 using CallSequence = std::vector<std::pair<Function *, addr_t>>; 243 244 /// Find the unique path through the call graph from \p begin (with return PC 245 /// \p return_pc) to \p end. On success this path is stored into \p path, and 246 /// on failure \p path is unchanged. 247 static void FindInterveningFrames(Function &begin, Function &end, 248 ExecutionContext &exe_ctx, Target &target, 249 addr_t return_pc, CallSequence &path, 250 ModuleList &images, Log *log) { 251 LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}", 252 begin.GetDisplayName(), end.GetDisplayName(), return_pc); 253 254 // Find a non-tail calling edge with the correct return PC. 255 if (log) 256 for (const auto &edge : begin.GetCallEdges()) 257 LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}", 258 edge->GetReturnPCAddress(begin, target)); 259 CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target); 260 if (!first_edge) { 261 LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}", 262 begin.GetDisplayName(), return_pc); 263 return; 264 } 265 266 // The first callee may not be resolved, or there may be nothing to fill in. 267 Function *first_callee = first_edge->GetCallee(images, exe_ctx); 268 if (!first_callee) { 269 LLDB_LOG(log, "Could not resolve callee"); 270 return; 271 } 272 if (first_callee == &end) { 273 LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})", 274 end.GetDisplayName(), return_pc); 275 return; 276 } 277 278 // Run DFS on the tail-calling edges out of the first callee to find \p end. 279 // Fully explore the set of functions reachable from the first edge via tail 280 // calls in order to detect ambiguous executions. 281 struct DFS { 282 CallSequence active_path = {}; 283 CallSequence solution_path = {}; 284 llvm::SmallPtrSet<Function *, 2> visited_nodes = {}; 285 bool ambiguous = false; 286 Function *end; 287 ModuleList &images; 288 Target ⌖ 289 ExecutionContext &context; 290 291 DFS(Function *end, ModuleList &images, Target &target, 292 ExecutionContext &context) 293 : end(end), images(images), target(target), context(context) {} 294 295 void search(CallEdge &first_edge, Function &first_callee, 296 CallSequence &path) { 297 dfs(first_edge, first_callee); 298 if (!ambiguous) 299 path = std::move(solution_path); 300 } 301 302 void dfs(CallEdge ¤t_edge, Function &callee) { 303 // Found a path to the target function. 304 if (&callee == end) { 305 if (solution_path.empty()) 306 solution_path = active_path; 307 else 308 ambiguous = true; 309 return; 310 } 311 312 // Terminate the search if tail recursion is found, or more generally if 313 // there's more than one way to reach a target. This errs on the side of 314 // caution: it conservatively stops searching when some solutions are 315 // still possible to save time in the average case. 316 if (!visited_nodes.insert(&callee).second) { 317 ambiguous = true; 318 return; 319 } 320 321 // Search the calls made from this callee. 322 active_path.emplace_back(&callee, LLDB_INVALID_ADDRESS); 323 for (const auto &edge : callee.GetTailCallingEdges()) { 324 Function *next_callee = edge->GetCallee(images, context); 325 if (!next_callee) 326 continue; 327 328 addr_t tail_call_pc = edge->GetCallInstPC(callee, target); 329 active_path.back().second = tail_call_pc; 330 331 dfs(*edge, *next_callee); 332 if (ambiguous) 333 return; 334 } 335 active_path.pop_back(); 336 } 337 }; 338 339 DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path); 340 } 341 342 /// Given that \p next_frame will be appended to the frame list, synthesize 343 /// tail call frames between the current end of the list and \p next_frame. 344 /// If any frames are added, adjust the frame index of \p next_frame. 345 /// 346 /// -------------- 347 /// | ... | <- Completed frames. 348 /// -------------- 349 /// | prev_frame | 350 /// -------------- 351 /// | ... | <- Artificial frames inserted here. 352 /// -------------- 353 /// | next_frame | 354 /// -------------- 355 /// | ... | <- Not-yet-visited frames. 356 /// -------------- 357 void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) { 358 // Cannot synthesize tail call frames when the stack is empty (there is no 359 // "previous" frame). 360 if (m_frames.empty()) 361 return; 362 363 TargetSP target_sp = next_frame.CalculateTarget(); 364 if (!target_sp) 365 return; 366 367 lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext(); 368 if (!next_reg_ctx_sp) 369 return; 370 371 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 372 373 StackFrame &prev_frame = *m_frames.back().get(); 374 375 // Find the functions prev_frame and next_frame are stopped in. The function 376 // objects are needed to search the lazy call graph for intervening frames. 377 Function *prev_func = 378 prev_frame.GetSymbolContext(eSymbolContextFunction).function; 379 if (!prev_func) { 380 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function"); 381 return; 382 } 383 Function *next_func = 384 next_frame.GetSymbolContext(eSymbolContextFunction).function; 385 if (!next_func) { 386 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function"); 387 return; 388 } 389 390 // Try to find the unique sequence of (tail) calls which led from next_frame 391 // to prev_frame. 392 CallSequence path; 393 addr_t return_pc = next_reg_ctx_sp->GetPC(); 394 Target &target = *target_sp.get(); 395 ModuleList &images = next_frame.CalculateTarget()->GetImages(); 396 ExecutionContext exe_ctx(target_sp, /*get_process=*/true); 397 exe_ctx.SetFramePtr(&next_frame); 398 FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc, 399 path, images, log); 400 401 // Push synthetic tail call frames. 402 for (auto calleeInfo : llvm::reverse(path)) { 403 Function *callee = calleeInfo.first; 404 uint32_t frame_idx = m_frames.size(); 405 uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex(); 406 addr_t cfa = LLDB_INVALID_ADDRESS; 407 bool cfa_is_valid = false; 408 addr_t pc = calleeInfo.second; 409 constexpr bool behaves_like_zeroth_frame = false; 410 SymbolContext sc; 411 callee->CalculateSymbolContext(&sc); 412 auto synth_frame = std::make_shared<StackFrame>( 413 m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa, 414 cfa_is_valid, pc, StackFrame::Kind::Artificial, 415 behaves_like_zeroth_frame, &sc); 416 m_frames.push_back(synth_frame); 417 LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc); 418 } 419 420 // If any frames were created, adjust next_frame's index. 421 if (!path.empty()) 422 next_frame.SetFrameIndex(m_frames.size()); 423 } 424 425 void StackFrameList::GetFramesUpTo(uint32_t end_idx) { 426 // Do not fetch frames for an invalid thread. 427 if (!m_thread.IsValid()) 428 return; 429 430 // We've already gotten more frames than asked for, or we've already finished 431 // unwinding, return. 432 if (m_frames.size() > end_idx || GetAllFramesFetched()) 433 return; 434 435 Unwind &unwinder = m_thread.GetUnwinder(); 436 437 if (!m_show_inlined_frames) { 438 GetOnlyConcreteFramesUpTo(end_idx, unwinder); 439 return; 440 } 441 442 #if defined(DEBUG_STACK_FRAMES) 443 StreamFile s(stdout, false); 444 #endif 445 // If we are hiding some frames from the outside world, we need to add 446 // those onto the total count of frames to fetch. However, we don't need 447 // to do that if end_idx is 0 since in that case we always get the first 448 // concrete frame and all the inlined frames below it... And of course, if 449 // end_idx is UINT32_MAX that means get all, so just do that... 450 451 uint32_t inlined_depth = 0; 452 if (end_idx > 0 && end_idx != UINT32_MAX) { 453 inlined_depth = GetCurrentInlinedDepth(); 454 if (inlined_depth != UINT32_MAX) { 455 if (end_idx > 0) 456 end_idx += inlined_depth; 457 } 458 } 459 460 StackFrameSP unwind_frame_sp; 461 do { 462 uint32_t idx = m_concrete_frames_fetched++; 463 lldb::addr_t pc = LLDB_INVALID_ADDRESS; 464 lldb::addr_t cfa = LLDB_INVALID_ADDRESS; 465 bool behaves_like_zeroth_frame = (idx == 0); 466 if (idx == 0) { 467 // We might have already created frame zero, only create it if we need 468 // to. 469 if (m_frames.empty()) { 470 RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext()); 471 472 if (reg_ctx_sp) { 473 const bool success = unwinder.GetFrameInfoAtIndex( 474 idx, cfa, pc, behaves_like_zeroth_frame); 475 // There shouldn't be any way not to get the frame info for frame 476 // 0. But if the unwinder can't make one, lets make one by hand 477 // with the SP as the CFA and see if that gets any further. 478 if (!success) { 479 cfa = reg_ctx_sp->GetSP(); 480 pc = reg_ctx_sp->GetPC(); 481 } 482 483 unwind_frame_sp = std::make_shared<StackFrame>( 484 m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp, 485 cfa, pc, behaves_like_zeroth_frame, nullptr); 486 m_frames.push_back(unwind_frame_sp); 487 } 488 } else { 489 unwind_frame_sp = m_frames.front(); 490 cfa = unwind_frame_sp->m_id.GetCallFrameAddress(); 491 } 492 } else { 493 const bool success = 494 unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame); 495 if (!success) { 496 // We've gotten to the end of the stack. 497 SetAllFramesFetched(); 498 break; 499 } 500 const bool cfa_is_valid = true; 501 unwind_frame_sp = std::make_shared<StackFrame>( 502 m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid, 503 pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr); 504 505 // Create synthetic tail call frames between the previous frame and the 506 // newly-found frame. The new frame's index may change after this call, 507 // although its concrete index will stay the same. 508 SynthesizeTailCallFrames(*unwind_frame_sp.get()); 509 510 m_frames.push_back(unwind_frame_sp); 511 } 512 513 assert(unwind_frame_sp); 514 SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext( 515 eSymbolContextBlock | eSymbolContextFunction); 516 Block *unwind_block = unwind_sc.block; 517 if (unwind_block) { 518 Address curr_frame_address(unwind_frame_sp->GetFrameCodeAddress()); 519 TargetSP target_sp = m_thread.CalculateTarget(); 520 // Be sure to adjust the frame address to match the address that was 521 // used to lookup the symbol context above. If we are in the first 522 // concrete frame, then we lookup using the current address, else we 523 // decrement the address by one to get the correct location. 524 if (idx > 0) { 525 if (curr_frame_address.GetOffset() == 0) { 526 // If curr_frame_address points to the first address in a section 527 // then after adjustment it will point to an other section. In that 528 // case resolve the address again to the correct section plus 529 // offset form. 530 addr_t load_addr = curr_frame_address.GetOpcodeLoadAddress( 531 target_sp.get(), AddressClass::eCode); 532 curr_frame_address.SetOpcodeLoadAddress( 533 load_addr - 1, target_sp.get(), AddressClass::eCode); 534 } else { 535 curr_frame_address.Slide(-1); 536 } 537 } 538 539 SymbolContext next_frame_sc; 540 Address next_frame_address; 541 542 while (unwind_sc.GetParentOfInlinedScope( 543 curr_frame_address, next_frame_sc, next_frame_address)) { 544 next_frame_sc.line_entry.ApplyFileMappings(target_sp); 545 behaves_like_zeroth_frame = false; 546 StackFrameSP frame_sp(new StackFrame( 547 m_thread.shared_from_this(), m_frames.size(), idx, 548 unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address, 549 behaves_like_zeroth_frame, &next_frame_sc)); 550 551 m_frames.push_back(frame_sp); 552 unwind_sc = next_frame_sc; 553 curr_frame_address = next_frame_address; 554 } 555 } 556 } while (m_frames.size() - 1 < end_idx); 557 558 // Don't try to merge till you've calculated all the frames in this stack. 559 if (GetAllFramesFetched() && m_prev_frames_sp) { 560 StackFrameList *prev_frames = m_prev_frames_sp.get(); 561 StackFrameList *curr_frames = this; 562 563 #if defined(DEBUG_STACK_FRAMES) 564 s.PutCString("\nprev_frames:\n"); 565 prev_frames->Dump(&s); 566 s.PutCString("\ncurr_frames:\n"); 567 curr_frames->Dump(&s); 568 s.EOL(); 569 #endif 570 size_t curr_frame_num, prev_frame_num; 571 572 for (curr_frame_num = curr_frames->m_frames.size(), 573 prev_frame_num = prev_frames->m_frames.size(); 574 curr_frame_num > 0 && prev_frame_num > 0; 575 --curr_frame_num, --prev_frame_num) { 576 const size_t curr_frame_idx = curr_frame_num - 1; 577 const size_t prev_frame_idx = prev_frame_num - 1; 578 StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]); 579 StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]); 580 581 #if defined(DEBUG_STACK_FRAMES) 582 s.Printf("\n\nCurr frame #%u ", curr_frame_idx); 583 if (curr_frame_sp) 584 curr_frame_sp->Dump(&s, true, false); 585 else 586 s.PutCString("NULL"); 587 s.Printf("\nPrev frame #%u ", prev_frame_idx); 588 if (prev_frame_sp) 589 prev_frame_sp->Dump(&s, true, false); 590 else 591 s.PutCString("NULL"); 592 #endif 593 594 StackFrame *curr_frame = curr_frame_sp.get(); 595 StackFrame *prev_frame = prev_frame_sp.get(); 596 597 if (curr_frame == nullptr || prev_frame == nullptr) 598 break; 599 600 // Check the stack ID to make sure they are equal. 601 if (curr_frame->GetStackID() != prev_frame->GetStackID()) 602 break; 603 604 prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame); 605 // Now copy the fixed up previous frame into the current frames so the 606 // pointer doesn't change. 607 m_frames[curr_frame_idx] = prev_frame_sp; 608 609 #if defined(DEBUG_STACK_FRAMES) 610 s.Printf("\n Copying previous frame to current frame"); 611 #endif 612 } 613 // We are done with the old stack frame list, we can release it now. 614 m_prev_frames_sp.reset(); 615 } 616 617 #if defined(DEBUG_STACK_FRAMES) 618 s.PutCString("\n\nNew frames:\n"); 619 Dump(&s); 620 s.EOL(); 621 #endif 622 } 623 624 uint32_t StackFrameList::GetNumFrames(bool can_create) { 625 std::lock_guard<std::recursive_mutex> guard(m_mutex); 626 627 if (can_create) 628 GetFramesUpTo(UINT32_MAX); 629 630 return GetVisibleStackFrameIndex(m_frames.size()); 631 } 632 633 void StackFrameList::Dump(Stream *s) { 634 if (s == nullptr) 635 return; 636 637 std::lock_guard<std::recursive_mutex> guard(m_mutex); 638 639 const_iterator pos, begin = m_frames.begin(), end = m_frames.end(); 640 for (pos = begin; pos != end; ++pos) { 641 StackFrame *frame = (*pos).get(); 642 s->Printf("%p: ", static_cast<void *>(frame)); 643 if (frame) { 644 frame->GetStackID().Dump(s); 645 frame->DumpUsingSettingsFormat(s); 646 } else 647 s->Printf("frame #%u", (uint32_t)std::distance(begin, pos)); 648 s->EOL(); 649 } 650 s->EOL(); 651 } 652 653 StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) { 654 StackFrameSP frame_sp; 655 std::lock_guard<std::recursive_mutex> guard(m_mutex); 656 uint32_t original_idx = idx; 657 658 uint32_t inlined_depth = GetCurrentInlinedDepth(); 659 if (inlined_depth != UINT32_MAX) 660 idx += inlined_depth; 661 662 if (idx < m_frames.size()) 663 frame_sp = m_frames[idx]; 664 665 if (frame_sp) 666 return frame_sp; 667 668 // GetFramesUpTo will fill m_frames with as many frames as you asked for, if 669 // there are that many. If there weren't then you asked for too many frames. 670 GetFramesUpTo(idx); 671 if (idx < m_frames.size()) { 672 if (m_show_inlined_frames) { 673 // When inline frames are enabled we actually create all the frames in 674 // GetFramesUpTo. 675 frame_sp = m_frames[idx]; 676 } else { 677 addr_t pc, cfa; 678 bool behaves_like_zeroth_frame = (idx == 0); 679 if (m_thread.GetUnwinder().GetFrameInfoAtIndex( 680 idx, cfa, pc, behaves_like_zeroth_frame)) { 681 const bool cfa_is_valid = true; 682 frame_sp = std::make_shared<StackFrame>( 683 m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc, 684 StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr); 685 686 Function *function = 687 frame_sp->GetSymbolContext(eSymbolContextFunction).function; 688 if (function) { 689 // When we aren't showing inline functions we always use the top 690 // most function block as the scope. 691 frame_sp->SetSymbolContextScope(&function->GetBlock(false)); 692 } else { 693 // Set the symbol scope from the symbol regardless if it is nullptr 694 // or valid. 695 frame_sp->SetSymbolContextScope( 696 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol); 697 } 698 SetFrameAtIndex(idx, frame_sp); 699 } 700 } 701 } else if (original_idx == 0) { 702 // There should ALWAYS be a frame at index 0. If something went wrong with 703 // the CurrentInlinedDepth such that there weren't as many frames as we 704 // thought taking that into account, then reset the current inlined depth 705 // and return the real zeroth frame. 706 if (m_frames.empty()) { 707 // Why do we have a thread with zero frames, that should not ever 708 // happen... 709 assert(!m_thread.IsValid() && "A valid thread has no frames."); 710 } else { 711 ResetCurrentInlinedDepth(); 712 frame_sp = m_frames[original_idx]; 713 } 714 } 715 716 return frame_sp; 717 } 718 719 StackFrameSP 720 StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) { 721 // First try assuming the unwind index is the same as the frame index. The 722 // unwind index is always greater than or equal to the frame index, so it is 723 // a good place to start. If we have inlined frames we might have 5 concrete 724 // frames (frame unwind indexes go from 0-4), but we might have 15 frames 725 // after we make all the inlined frames. Most of the time the unwind frame 726 // index (or the concrete frame index) is the same as the frame index. 727 uint32_t frame_idx = unwind_idx; 728 StackFrameSP frame_sp(GetFrameAtIndex(frame_idx)); 729 while (frame_sp) { 730 if (frame_sp->GetFrameIndex() == unwind_idx) 731 break; 732 frame_sp = GetFrameAtIndex(++frame_idx); 733 } 734 return frame_sp; 735 } 736 737 static bool CompareStackID(const StackFrameSP &stack_sp, 738 const StackID &stack_id) { 739 return stack_sp->GetStackID() < stack_id; 740 } 741 742 StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) { 743 StackFrameSP frame_sp; 744 745 if (stack_id.IsValid()) { 746 std::lock_guard<std::recursive_mutex> guard(m_mutex); 747 uint32_t frame_idx = 0; 748 // Do a binary search in case the stack frame is already in our cache 749 collection::const_iterator begin = m_frames.begin(); 750 collection::const_iterator end = m_frames.end(); 751 if (begin != end) { 752 collection::const_iterator pos = 753 std::lower_bound(begin, end, stack_id, CompareStackID); 754 if (pos != end) { 755 if ((*pos)->GetStackID() == stack_id) 756 return *pos; 757 } 758 } 759 do { 760 frame_sp = GetFrameAtIndex(frame_idx); 761 if (frame_sp && frame_sp->GetStackID() == stack_id) 762 break; 763 frame_idx++; 764 } while (frame_sp); 765 } 766 return frame_sp; 767 } 768 769 bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) { 770 if (idx >= m_frames.size()) 771 m_frames.resize(idx + 1); 772 // Make sure allocation succeeded by checking bounds again 773 if (idx < m_frames.size()) { 774 m_frames[idx] = frame_sp; 775 return true; 776 } 777 return false; // resize failed, out of memory? 778 } 779 780 uint32_t StackFrameList::GetSelectedFrameIndex() const { 781 std::lock_guard<std::recursive_mutex> guard(m_mutex); 782 return m_selected_frame_idx; 783 } 784 785 uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) { 786 std::lock_guard<std::recursive_mutex> guard(m_mutex); 787 const_iterator pos; 788 const_iterator begin = m_frames.begin(); 789 const_iterator end = m_frames.end(); 790 m_selected_frame_idx = 0; 791 for (pos = begin; pos != end; ++pos) { 792 if (pos->get() == frame) { 793 m_selected_frame_idx = std::distance(begin, pos); 794 uint32_t inlined_depth = GetCurrentInlinedDepth(); 795 if (inlined_depth != UINT32_MAX) 796 m_selected_frame_idx -= inlined_depth; 797 break; 798 } 799 } 800 SetDefaultFileAndLineToSelectedFrame(); 801 return m_selected_frame_idx; 802 } 803 804 bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) { 805 std::lock_guard<std::recursive_mutex> guard(m_mutex); 806 StackFrameSP frame_sp(GetFrameAtIndex(idx)); 807 if (frame_sp) { 808 SetSelectedFrame(frame_sp.get()); 809 return true; 810 } else 811 return false; 812 } 813 814 void StackFrameList::SetDefaultFileAndLineToSelectedFrame() { 815 if (m_thread.GetID() == 816 m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) { 817 StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex())); 818 if (frame_sp) { 819 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry); 820 if (sc.line_entry.file) 821 m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine( 822 sc.line_entry.file, sc.line_entry.line); 823 } 824 } 825 } 826 827 // The thread has been run, reset the number stack frames to zero so we can 828 // determine how many frames we have lazily. 829 void StackFrameList::Clear() { 830 std::lock_guard<std::recursive_mutex> guard(m_mutex); 831 m_frames.clear(); 832 m_concrete_frames_fetched = 0; 833 } 834 835 void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_up, 836 lldb::StackFrameListSP &prev_sp) { 837 std::unique_lock<std::recursive_mutex> current_lock, previous_lock; 838 if (curr_up) 839 current_lock = std::unique_lock<std::recursive_mutex>(curr_up->m_mutex); 840 if (prev_sp) 841 previous_lock = std::unique_lock<std::recursive_mutex>(prev_sp->m_mutex); 842 843 #if defined(DEBUG_STACK_FRAMES) 844 StreamFile s(stdout, false); 845 s.PutCString("\n\nStackFrameList::Merge():\nPrev:\n"); 846 if (prev_sp) 847 prev_sp->Dump(&s); 848 else 849 s.PutCString("NULL"); 850 s.PutCString("\nCurr:\n"); 851 if (curr_up) 852 curr_up->Dump(&s); 853 else 854 s.PutCString("NULL"); 855 s.EOL(); 856 #endif 857 858 if (!curr_up || curr_up->GetNumFrames(false) == 0) { 859 #if defined(DEBUG_STACK_FRAMES) 860 s.PutCString("No current frames, leave previous frames alone...\n"); 861 #endif 862 curr_up.release(); 863 return; 864 } 865 866 if (!prev_sp || prev_sp->GetNumFrames(false) == 0) { 867 #if defined(DEBUG_STACK_FRAMES) 868 s.PutCString("No previous frames, so use current frames...\n"); 869 #endif 870 // We either don't have any previous frames, or since we have more than one 871 // current frames it means we have all the frames and can safely replace 872 // our previous frames. 873 prev_sp.reset(curr_up.release()); 874 return; 875 } 876 877 const uint32_t num_curr_frames = curr_up->GetNumFrames(false); 878 879 if (num_curr_frames > 1) { 880 #if defined(DEBUG_STACK_FRAMES) 881 s.PutCString( 882 "We have more than one current frame, so use current frames...\n"); 883 #endif 884 // We have more than one current frames it means we have all the frames and 885 // can safely replace our previous frames. 886 prev_sp.reset(curr_up.release()); 887 888 #if defined(DEBUG_STACK_FRAMES) 889 s.PutCString("\nMerged:\n"); 890 prev_sp->Dump(&s); 891 #endif 892 return; 893 } 894 895 StackFrameSP prev_frame_zero_sp(prev_sp->GetFrameAtIndex(0)); 896 StackFrameSP curr_frame_zero_sp(curr_up->GetFrameAtIndex(0)); 897 StackID curr_stack_id(curr_frame_zero_sp->GetStackID()); 898 StackID prev_stack_id(prev_frame_zero_sp->GetStackID()); 899 900 #if defined(DEBUG_STACK_FRAMES) 901 const uint32_t num_prev_frames = prev_sp->GetNumFrames(false); 902 s.Printf("\n%u previous frames with one current frame\n", num_prev_frames); 903 #endif 904 905 // We have only a single current frame 906 // Our previous stack frames only had a single frame as well... 907 if (curr_stack_id == prev_stack_id) { 908 #if defined(DEBUG_STACK_FRAMES) 909 s.Printf("\nPrevious frame #0 is same as current frame #0, merge the " 910 "cached data\n"); 911 #endif 912 913 curr_frame_zero_sp->UpdateCurrentFrameFromPreviousFrame( 914 *prev_frame_zero_sp); 915 // prev_frame_zero_sp->UpdatePreviousFrameFromCurrentFrame 916 // (*curr_frame_zero_sp); 917 // prev_sp->SetFrameAtIndex (0, prev_frame_zero_sp); 918 } else if (curr_stack_id < prev_stack_id) { 919 #if defined(DEBUG_STACK_FRAMES) 920 s.Printf("\nCurrent frame #0 has a stack ID that is less than the previous " 921 "frame #0, insert current frame zero in front of previous\n"); 922 #endif 923 prev_sp->m_frames.insert(prev_sp->m_frames.begin(), curr_frame_zero_sp); 924 } 925 926 curr_up.release(); 927 928 #if defined(DEBUG_STACK_FRAMES) 929 s.PutCString("\nMerged:\n"); 930 prev_sp->Dump(&s); 931 #endif 932 } 933 934 lldb::StackFrameSP 935 StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) { 936 const_iterator pos; 937 const_iterator begin = m_frames.begin(); 938 const_iterator end = m_frames.end(); 939 lldb::StackFrameSP ret_sp; 940 941 for (pos = begin; pos != end; ++pos) { 942 if (pos->get() == stack_frame_ptr) { 943 ret_sp = (*pos); 944 break; 945 } 946 } 947 return ret_sp; 948 } 949 950 size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame, 951 uint32_t num_frames, bool show_frame_info, 952 uint32_t num_frames_with_source, 953 bool show_unique, 954 const char *selected_frame_marker) { 955 size_t num_frames_displayed = 0; 956 957 if (num_frames == 0) 958 return 0; 959 960 StackFrameSP frame_sp; 961 uint32_t frame_idx = 0; 962 uint32_t last_frame; 963 964 // Don't let the last frame wrap around... 965 if (num_frames == UINT32_MAX) 966 last_frame = UINT32_MAX; 967 else 968 last_frame = first_frame + num_frames; 969 970 StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame(); 971 const char *unselected_marker = nullptr; 972 std::string buffer; 973 if (selected_frame_marker) { 974 size_t len = strlen(selected_frame_marker); 975 buffer.insert(buffer.begin(), len, ' '); 976 unselected_marker = buffer.c_str(); 977 } 978 const char *marker = nullptr; 979 980 for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) { 981 frame_sp = GetFrameAtIndex(frame_idx); 982 if (!frame_sp) 983 break; 984 985 if (selected_frame_marker != nullptr) { 986 if (frame_sp == selected_frame_sp) 987 marker = selected_frame_marker; 988 else 989 marker = unselected_marker; 990 } 991 992 if (!frame_sp->GetStatus(strm, show_frame_info, 993 num_frames_with_source > (first_frame - frame_idx), 994 show_unique, marker)) 995 break; 996 ++num_frames_displayed; 997 } 998 999 strm.IndentLess(); 1000 return num_frames_displayed; 1001 } 1002