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 struct CallDescriptor { 243 Function *func; 244 CallEdge::AddrType address_type = CallEdge::AddrType::Call; 245 addr_t address = LLDB_INVALID_ADDRESS; 246 }; 247 using CallSequence = std::vector<CallDescriptor>; 248 249 /// Find the unique path through the call graph from \p begin (with return PC 250 /// \p return_pc) to \p end. On success this path is stored into \p path, and 251 /// on failure \p path is unchanged. 252 static void FindInterveningFrames(Function &begin, Function &end, 253 ExecutionContext &exe_ctx, Target &target, 254 addr_t return_pc, CallSequence &path, 255 ModuleList &images, Log *log) { 256 LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}", 257 begin.GetDisplayName(), end.GetDisplayName(), return_pc); 258 259 // Find a non-tail calling edge with the correct return PC. 260 if (log) 261 for (const auto &edge : begin.GetCallEdges()) 262 LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}", 263 edge->GetReturnPCAddress(begin, target)); 264 CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target); 265 if (!first_edge) { 266 LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}", 267 begin.GetDisplayName(), return_pc); 268 return; 269 } 270 271 // The first callee may not be resolved, or there may be nothing to fill in. 272 Function *first_callee = first_edge->GetCallee(images, exe_ctx); 273 if (!first_callee) { 274 LLDB_LOG(log, "Could not resolve callee"); 275 return; 276 } 277 if (first_callee == &end) { 278 LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})", 279 end.GetDisplayName(), return_pc); 280 return; 281 } 282 283 // Run DFS on the tail-calling edges out of the first callee to find \p end. 284 // Fully explore the set of functions reachable from the first edge via tail 285 // calls in order to detect ambiguous executions. 286 struct DFS { 287 CallSequence active_path = {}; 288 CallSequence solution_path = {}; 289 llvm::SmallPtrSet<Function *, 2> visited_nodes = {}; 290 bool ambiguous = false; 291 Function *end; 292 ModuleList &images; 293 Target ⌖ 294 ExecutionContext &context; 295 296 DFS(Function *end, ModuleList &images, Target &target, 297 ExecutionContext &context) 298 : end(end), images(images), target(target), context(context) {} 299 300 void search(CallEdge &first_edge, Function &first_callee, 301 CallSequence &path) { 302 dfs(first_edge, first_callee); 303 if (!ambiguous) 304 path = std::move(solution_path); 305 } 306 307 void dfs(CallEdge ¤t_edge, Function &callee) { 308 // Found a path to the target function. 309 if (&callee == end) { 310 if (solution_path.empty()) 311 solution_path = active_path; 312 else 313 ambiguous = true; 314 return; 315 } 316 317 // Terminate the search if tail recursion is found, or more generally if 318 // there's more than one way to reach a target. This errs on the side of 319 // caution: it conservatively stops searching when some solutions are 320 // still possible to save time in the average case. 321 if (!visited_nodes.insert(&callee).second) { 322 ambiguous = true; 323 return; 324 } 325 326 // Search the calls made from this callee. 327 active_path.push_back(CallDescriptor{&callee}); 328 for (const auto &edge : callee.GetTailCallingEdges()) { 329 Function *next_callee = edge->GetCallee(images, context); 330 if (!next_callee) 331 continue; 332 333 std::tie(active_path.back().address_type, active_path.back().address) = 334 edge->GetCallerAddress(callee, target); 335 336 dfs(*edge, *next_callee); 337 if (ambiguous) 338 return; 339 } 340 active_path.pop_back(); 341 } 342 }; 343 344 DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path); 345 } 346 347 /// Given that \p next_frame will be appended to the frame list, synthesize 348 /// tail call frames between the current end of the list and \p next_frame. 349 /// If any frames are added, adjust the frame index of \p next_frame. 350 /// 351 /// -------------- 352 /// | ... | <- Completed frames. 353 /// -------------- 354 /// | prev_frame | 355 /// -------------- 356 /// | ... | <- Artificial frames inserted here. 357 /// -------------- 358 /// | next_frame | 359 /// -------------- 360 /// | ... | <- Not-yet-visited frames. 361 /// -------------- 362 void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) { 363 // Cannot synthesize tail call frames when the stack is empty (there is no 364 // "previous" frame). 365 if (m_frames.empty()) 366 return; 367 368 TargetSP target_sp = next_frame.CalculateTarget(); 369 if (!target_sp) 370 return; 371 372 lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext(); 373 if (!next_reg_ctx_sp) 374 return; 375 376 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 377 378 StackFrame &prev_frame = *m_frames.back().get(); 379 380 // Find the functions prev_frame and next_frame are stopped in. The function 381 // objects are needed to search the lazy call graph for intervening frames. 382 Function *prev_func = 383 prev_frame.GetSymbolContext(eSymbolContextFunction).function; 384 if (!prev_func) { 385 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function"); 386 return; 387 } 388 Function *next_func = 389 next_frame.GetSymbolContext(eSymbolContextFunction).function; 390 if (!next_func) { 391 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function"); 392 return; 393 } 394 395 // Try to find the unique sequence of (tail) calls which led from next_frame 396 // to prev_frame. 397 CallSequence path; 398 addr_t return_pc = next_reg_ctx_sp->GetPC(); 399 Target &target = *target_sp.get(); 400 ModuleList &images = next_frame.CalculateTarget()->GetImages(); 401 ExecutionContext exe_ctx(target_sp, /*get_process=*/true); 402 exe_ctx.SetFramePtr(&next_frame); 403 FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc, 404 path, images, log); 405 406 // Push synthetic tail call frames. 407 for (auto calleeInfo : llvm::reverse(path)) { 408 Function *callee = calleeInfo.func; 409 uint32_t frame_idx = m_frames.size(); 410 uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex(); 411 addr_t cfa = LLDB_INVALID_ADDRESS; 412 bool cfa_is_valid = false; 413 addr_t pc = calleeInfo.address; 414 // If the callee address refers to the call instruction, we do not want to 415 // subtract 1 from this value. 416 const bool behaves_like_zeroth_frame = 417 calleeInfo.address_type == CallEdge::AddrType::Call; 418 SymbolContext sc; 419 callee->CalculateSymbolContext(&sc); 420 auto synth_frame = std::make_shared<StackFrame>( 421 m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa, 422 cfa_is_valid, pc, StackFrame::Kind::Artificial, 423 behaves_like_zeroth_frame, &sc); 424 m_frames.push_back(synth_frame); 425 LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc); 426 } 427 428 // If any frames were created, adjust next_frame's index. 429 if (!path.empty()) 430 next_frame.SetFrameIndex(m_frames.size()); 431 } 432 433 void StackFrameList::GetFramesUpTo(uint32_t end_idx) { 434 // Do not fetch frames for an invalid thread. 435 if (!m_thread.IsValid()) 436 return; 437 438 // We've already gotten more frames than asked for, or we've already finished 439 // unwinding, return. 440 if (m_frames.size() > end_idx || GetAllFramesFetched()) 441 return; 442 443 Unwind &unwinder = m_thread.GetUnwinder(); 444 445 if (!m_show_inlined_frames) { 446 GetOnlyConcreteFramesUpTo(end_idx, unwinder); 447 return; 448 } 449 450 #if defined(DEBUG_STACK_FRAMES) 451 StreamFile s(stdout, false); 452 #endif 453 // If we are hiding some frames from the outside world, we need to add 454 // those onto the total count of frames to fetch. However, we don't need 455 // to do that if end_idx is 0 since in that case we always get the first 456 // concrete frame and all the inlined frames below it... And of course, if 457 // end_idx is UINT32_MAX that means get all, so just do that... 458 459 uint32_t inlined_depth = 0; 460 if (end_idx > 0 && end_idx != UINT32_MAX) { 461 inlined_depth = GetCurrentInlinedDepth(); 462 if (inlined_depth != UINT32_MAX) { 463 if (end_idx > 0) 464 end_idx += inlined_depth; 465 } 466 } 467 468 StackFrameSP unwind_frame_sp; 469 do { 470 uint32_t idx = m_concrete_frames_fetched++; 471 lldb::addr_t pc = LLDB_INVALID_ADDRESS; 472 lldb::addr_t cfa = LLDB_INVALID_ADDRESS; 473 bool behaves_like_zeroth_frame = (idx == 0); 474 if (idx == 0) { 475 // We might have already created frame zero, only create it if we need 476 // to. 477 if (m_frames.empty()) { 478 RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext()); 479 480 if (reg_ctx_sp) { 481 const bool success = unwinder.GetFrameInfoAtIndex( 482 idx, cfa, pc, behaves_like_zeroth_frame); 483 // There shouldn't be any way not to get the frame info for frame 484 // 0. But if the unwinder can't make one, lets make one by hand 485 // with the SP as the CFA and see if that gets any further. 486 if (!success) { 487 cfa = reg_ctx_sp->GetSP(); 488 pc = reg_ctx_sp->GetPC(); 489 } 490 491 unwind_frame_sp = std::make_shared<StackFrame>( 492 m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp, 493 cfa, pc, behaves_like_zeroth_frame, nullptr); 494 m_frames.push_back(unwind_frame_sp); 495 } 496 } else { 497 unwind_frame_sp = m_frames.front(); 498 cfa = unwind_frame_sp->m_id.GetCallFrameAddress(); 499 } 500 } else { 501 const bool success = 502 unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame); 503 if (!success) { 504 // We've gotten to the end of the stack. 505 SetAllFramesFetched(); 506 break; 507 } 508 const bool cfa_is_valid = true; 509 unwind_frame_sp = std::make_shared<StackFrame>( 510 m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid, 511 pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr); 512 513 // Create synthetic tail call frames between the previous frame and the 514 // newly-found frame. The new frame's index may change after this call, 515 // although its concrete index will stay the same. 516 SynthesizeTailCallFrames(*unwind_frame_sp.get()); 517 518 m_frames.push_back(unwind_frame_sp); 519 } 520 521 assert(unwind_frame_sp); 522 SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext( 523 eSymbolContextBlock | eSymbolContextFunction); 524 Block *unwind_block = unwind_sc.block; 525 if (unwind_block) { 526 Address curr_frame_address(unwind_frame_sp->GetFrameCodeAddress()); 527 TargetSP target_sp = m_thread.CalculateTarget(); 528 // Be sure to adjust the frame address to match the address that was 529 // used to lookup the symbol context above. If we are in the first 530 // concrete frame, then we lookup using the current address, else we 531 // decrement the address by one to get the correct location. 532 if (idx > 0) { 533 if (curr_frame_address.GetOffset() == 0) { 534 // If curr_frame_address points to the first address in a section 535 // then after adjustment it will point to an other section. In that 536 // case resolve the address again to the correct section plus 537 // offset form. 538 addr_t load_addr = curr_frame_address.GetOpcodeLoadAddress( 539 target_sp.get(), AddressClass::eCode); 540 curr_frame_address.SetOpcodeLoadAddress( 541 load_addr - 1, target_sp.get(), AddressClass::eCode); 542 } else { 543 curr_frame_address.Slide(-1); 544 } 545 } 546 547 SymbolContext next_frame_sc; 548 Address next_frame_address; 549 550 while (unwind_sc.GetParentOfInlinedScope( 551 curr_frame_address, next_frame_sc, next_frame_address)) { 552 next_frame_sc.line_entry.ApplyFileMappings(target_sp); 553 behaves_like_zeroth_frame = false; 554 StackFrameSP frame_sp(new StackFrame( 555 m_thread.shared_from_this(), m_frames.size(), idx, 556 unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address, 557 behaves_like_zeroth_frame, &next_frame_sc)); 558 559 m_frames.push_back(frame_sp); 560 unwind_sc = next_frame_sc; 561 curr_frame_address = next_frame_address; 562 } 563 } 564 } while (m_frames.size() - 1 < end_idx); 565 566 // Don't try to merge till you've calculated all the frames in this stack. 567 if (GetAllFramesFetched() && m_prev_frames_sp) { 568 StackFrameList *prev_frames = m_prev_frames_sp.get(); 569 StackFrameList *curr_frames = this; 570 571 #if defined(DEBUG_STACK_FRAMES) 572 s.PutCString("\nprev_frames:\n"); 573 prev_frames->Dump(&s); 574 s.PutCString("\ncurr_frames:\n"); 575 curr_frames->Dump(&s); 576 s.EOL(); 577 #endif 578 size_t curr_frame_num, prev_frame_num; 579 580 for (curr_frame_num = curr_frames->m_frames.size(), 581 prev_frame_num = prev_frames->m_frames.size(); 582 curr_frame_num > 0 && prev_frame_num > 0; 583 --curr_frame_num, --prev_frame_num) { 584 const size_t curr_frame_idx = curr_frame_num - 1; 585 const size_t prev_frame_idx = prev_frame_num - 1; 586 StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]); 587 StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]); 588 589 #if defined(DEBUG_STACK_FRAMES) 590 s.Printf("\n\nCurr frame #%u ", curr_frame_idx); 591 if (curr_frame_sp) 592 curr_frame_sp->Dump(&s, true, false); 593 else 594 s.PutCString("NULL"); 595 s.Printf("\nPrev frame #%u ", prev_frame_idx); 596 if (prev_frame_sp) 597 prev_frame_sp->Dump(&s, true, false); 598 else 599 s.PutCString("NULL"); 600 #endif 601 602 StackFrame *curr_frame = curr_frame_sp.get(); 603 StackFrame *prev_frame = prev_frame_sp.get(); 604 605 if (curr_frame == nullptr || prev_frame == nullptr) 606 break; 607 608 // Check the stack ID to make sure they are equal. 609 if (curr_frame->GetStackID() != prev_frame->GetStackID()) 610 break; 611 612 prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame); 613 // Now copy the fixed up previous frame into the current frames so the 614 // pointer doesn't change. 615 m_frames[curr_frame_idx] = prev_frame_sp; 616 617 #if defined(DEBUG_STACK_FRAMES) 618 s.Printf("\n Copying previous frame to current frame"); 619 #endif 620 } 621 // We are done with the old stack frame list, we can release it now. 622 m_prev_frames_sp.reset(); 623 } 624 625 #if defined(DEBUG_STACK_FRAMES) 626 s.PutCString("\n\nNew frames:\n"); 627 Dump(&s); 628 s.EOL(); 629 #endif 630 } 631 632 uint32_t StackFrameList::GetNumFrames(bool can_create) { 633 std::lock_guard<std::recursive_mutex> guard(m_mutex); 634 635 if (can_create) 636 GetFramesUpTo(UINT32_MAX); 637 638 return GetVisibleStackFrameIndex(m_frames.size()); 639 } 640 641 void StackFrameList::Dump(Stream *s) { 642 if (s == nullptr) 643 return; 644 645 std::lock_guard<std::recursive_mutex> guard(m_mutex); 646 647 const_iterator pos, begin = m_frames.begin(), end = m_frames.end(); 648 for (pos = begin; pos != end; ++pos) { 649 StackFrame *frame = (*pos).get(); 650 s->Printf("%p: ", static_cast<void *>(frame)); 651 if (frame) { 652 frame->GetStackID().Dump(s); 653 frame->DumpUsingSettingsFormat(s); 654 } else 655 s->Printf("frame #%u", (uint32_t)std::distance(begin, pos)); 656 s->EOL(); 657 } 658 s->EOL(); 659 } 660 661 StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) { 662 StackFrameSP frame_sp; 663 std::lock_guard<std::recursive_mutex> guard(m_mutex); 664 uint32_t original_idx = idx; 665 666 uint32_t inlined_depth = GetCurrentInlinedDepth(); 667 if (inlined_depth != UINT32_MAX) 668 idx += inlined_depth; 669 670 if (idx < m_frames.size()) 671 frame_sp = m_frames[idx]; 672 673 if (frame_sp) 674 return frame_sp; 675 676 // GetFramesUpTo will fill m_frames with as many frames as you asked for, if 677 // there are that many. If there weren't then you asked for too many frames. 678 GetFramesUpTo(idx); 679 if (idx < m_frames.size()) { 680 if (m_show_inlined_frames) { 681 // When inline frames are enabled we actually create all the frames in 682 // GetFramesUpTo. 683 frame_sp = m_frames[idx]; 684 } else { 685 addr_t pc, cfa; 686 bool behaves_like_zeroth_frame = (idx == 0); 687 if (m_thread.GetUnwinder().GetFrameInfoAtIndex( 688 idx, cfa, pc, behaves_like_zeroth_frame)) { 689 const bool cfa_is_valid = true; 690 frame_sp = std::make_shared<StackFrame>( 691 m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc, 692 StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr); 693 694 Function *function = 695 frame_sp->GetSymbolContext(eSymbolContextFunction).function; 696 if (function) { 697 // When we aren't showing inline functions we always use the top 698 // most function block as the scope. 699 frame_sp->SetSymbolContextScope(&function->GetBlock(false)); 700 } else { 701 // Set the symbol scope from the symbol regardless if it is nullptr 702 // or valid. 703 frame_sp->SetSymbolContextScope( 704 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol); 705 } 706 SetFrameAtIndex(idx, frame_sp); 707 } 708 } 709 } else if (original_idx == 0) { 710 // There should ALWAYS be a frame at index 0. If something went wrong with 711 // the CurrentInlinedDepth such that there weren't as many frames as we 712 // thought taking that into account, then reset the current inlined depth 713 // and return the real zeroth frame. 714 if (m_frames.empty()) { 715 // Why do we have a thread with zero frames, that should not ever 716 // happen... 717 assert(!m_thread.IsValid() && "A valid thread has no frames."); 718 } else { 719 ResetCurrentInlinedDepth(); 720 frame_sp = m_frames[original_idx]; 721 } 722 } 723 724 return frame_sp; 725 } 726 727 StackFrameSP 728 StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) { 729 // First try assuming the unwind index is the same as the frame index. The 730 // unwind index is always greater than or equal to the frame index, so it is 731 // a good place to start. If we have inlined frames we might have 5 concrete 732 // frames (frame unwind indexes go from 0-4), but we might have 15 frames 733 // after we make all the inlined frames. Most of the time the unwind frame 734 // index (or the concrete frame index) is the same as the frame index. 735 uint32_t frame_idx = unwind_idx; 736 StackFrameSP frame_sp(GetFrameAtIndex(frame_idx)); 737 while (frame_sp) { 738 if (frame_sp->GetFrameIndex() == unwind_idx) 739 break; 740 frame_sp = GetFrameAtIndex(++frame_idx); 741 } 742 return frame_sp; 743 } 744 745 static bool CompareStackID(const StackFrameSP &stack_sp, 746 const StackID &stack_id) { 747 return stack_sp->GetStackID() < stack_id; 748 } 749 750 StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) { 751 StackFrameSP frame_sp; 752 753 if (stack_id.IsValid()) { 754 std::lock_guard<std::recursive_mutex> guard(m_mutex); 755 uint32_t frame_idx = 0; 756 // Do a binary search in case the stack frame is already in our cache 757 collection::const_iterator begin = m_frames.begin(); 758 collection::const_iterator end = m_frames.end(); 759 if (begin != end) { 760 collection::const_iterator pos = 761 std::lower_bound(begin, end, stack_id, CompareStackID); 762 if (pos != end) { 763 if ((*pos)->GetStackID() == stack_id) 764 return *pos; 765 } 766 } 767 do { 768 frame_sp = GetFrameAtIndex(frame_idx); 769 if (frame_sp && frame_sp->GetStackID() == stack_id) 770 break; 771 frame_idx++; 772 } while (frame_sp); 773 } 774 return frame_sp; 775 } 776 777 bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) { 778 if (idx >= m_frames.size()) 779 m_frames.resize(idx + 1); 780 // Make sure allocation succeeded by checking bounds again 781 if (idx < m_frames.size()) { 782 m_frames[idx] = frame_sp; 783 return true; 784 } 785 return false; // resize failed, out of memory? 786 } 787 788 uint32_t StackFrameList::GetSelectedFrameIndex() const { 789 std::lock_guard<std::recursive_mutex> guard(m_mutex); 790 return m_selected_frame_idx; 791 } 792 793 uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) { 794 std::lock_guard<std::recursive_mutex> guard(m_mutex); 795 const_iterator pos; 796 const_iterator begin = m_frames.begin(); 797 const_iterator end = m_frames.end(); 798 m_selected_frame_idx = 0; 799 for (pos = begin; pos != end; ++pos) { 800 if (pos->get() == frame) { 801 m_selected_frame_idx = std::distance(begin, pos); 802 uint32_t inlined_depth = GetCurrentInlinedDepth(); 803 if (inlined_depth != UINT32_MAX) 804 m_selected_frame_idx -= inlined_depth; 805 break; 806 } 807 } 808 SetDefaultFileAndLineToSelectedFrame(); 809 return m_selected_frame_idx; 810 } 811 812 bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) { 813 std::lock_guard<std::recursive_mutex> guard(m_mutex); 814 StackFrameSP frame_sp(GetFrameAtIndex(idx)); 815 if (frame_sp) { 816 SetSelectedFrame(frame_sp.get()); 817 return true; 818 } else 819 return false; 820 } 821 822 void StackFrameList::SetDefaultFileAndLineToSelectedFrame() { 823 if (m_thread.GetID() == 824 m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) { 825 StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex())); 826 if (frame_sp) { 827 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry); 828 if (sc.line_entry.file) 829 m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine( 830 sc.line_entry.file, sc.line_entry.line); 831 } 832 } 833 } 834 835 // The thread has been run, reset the number stack frames to zero so we can 836 // determine how many frames we have lazily. 837 void StackFrameList::Clear() { 838 std::lock_guard<std::recursive_mutex> guard(m_mutex); 839 m_frames.clear(); 840 m_concrete_frames_fetched = 0; 841 } 842 843 void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_up, 844 lldb::StackFrameListSP &prev_sp) { 845 std::unique_lock<std::recursive_mutex> current_lock, previous_lock; 846 if (curr_up) 847 current_lock = std::unique_lock<std::recursive_mutex>(curr_up->m_mutex); 848 if (prev_sp) 849 previous_lock = std::unique_lock<std::recursive_mutex>(prev_sp->m_mutex); 850 851 #if defined(DEBUG_STACK_FRAMES) 852 StreamFile s(stdout, false); 853 s.PutCString("\n\nStackFrameList::Merge():\nPrev:\n"); 854 if (prev_sp) 855 prev_sp->Dump(&s); 856 else 857 s.PutCString("NULL"); 858 s.PutCString("\nCurr:\n"); 859 if (curr_up) 860 curr_up->Dump(&s); 861 else 862 s.PutCString("NULL"); 863 s.EOL(); 864 #endif 865 866 if (!curr_up || curr_up->GetNumFrames(false) == 0) { 867 #if defined(DEBUG_STACK_FRAMES) 868 s.PutCString("No current frames, leave previous frames alone...\n"); 869 #endif 870 curr_up.release(); 871 return; 872 } 873 874 if (!prev_sp || prev_sp->GetNumFrames(false) == 0) { 875 #if defined(DEBUG_STACK_FRAMES) 876 s.PutCString("No previous frames, so use current frames...\n"); 877 #endif 878 // We either don't have any previous frames, or since we have more than one 879 // current frames it means we have all the frames and can safely replace 880 // our previous frames. 881 prev_sp.reset(curr_up.release()); 882 return; 883 } 884 885 const uint32_t num_curr_frames = curr_up->GetNumFrames(false); 886 887 if (num_curr_frames > 1) { 888 #if defined(DEBUG_STACK_FRAMES) 889 s.PutCString( 890 "We have more than one current frame, so use current frames...\n"); 891 #endif 892 // We have more than one current frames it means we have all the frames and 893 // can safely replace our previous frames. 894 prev_sp.reset(curr_up.release()); 895 896 #if defined(DEBUG_STACK_FRAMES) 897 s.PutCString("\nMerged:\n"); 898 prev_sp->Dump(&s); 899 #endif 900 return; 901 } 902 903 StackFrameSP prev_frame_zero_sp(prev_sp->GetFrameAtIndex(0)); 904 StackFrameSP curr_frame_zero_sp(curr_up->GetFrameAtIndex(0)); 905 StackID curr_stack_id(curr_frame_zero_sp->GetStackID()); 906 StackID prev_stack_id(prev_frame_zero_sp->GetStackID()); 907 908 #if defined(DEBUG_STACK_FRAMES) 909 const uint32_t num_prev_frames = prev_sp->GetNumFrames(false); 910 s.Printf("\n%u previous frames with one current frame\n", num_prev_frames); 911 #endif 912 913 // We have only a single current frame 914 // Our previous stack frames only had a single frame as well... 915 if (curr_stack_id == prev_stack_id) { 916 #if defined(DEBUG_STACK_FRAMES) 917 s.Printf("\nPrevious frame #0 is same as current frame #0, merge the " 918 "cached data\n"); 919 #endif 920 921 curr_frame_zero_sp->UpdateCurrentFrameFromPreviousFrame( 922 *prev_frame_zero_sp); 923 // prev_frame_zero_sp->UpdatePreviousFrameFromCurrentFrame 924 // (*curr_frame_zero_sp); 925 // prev_sp->SetFrameAtIndex (0, prev_frame_zero_sp); 926 } else if (curr_stack_id < prev_stack_id) { 927 #if defined(DEBUG_STACK_FRAMES) 928 s.Printf("\nCurrent frame #0 has a stack ID that is less than the previous " 929 "frame #0, insert current frame zero in front of previous\n"); 930 #endif 931 prev_sp->m_frames.insert(prev_sp->m_frames.begin(), curr_frame_zero_sp); 932 } 933 934 curr_up.release(); 935 936 #if defined(DEBUG_STACK_FRAMES) 937 s.PutCString("\nMerged:\n"); 938 prev_sp->Dump(&s); 939 #endif 940 } 941 942 lldb::StackFrameSP 943 StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) { 944 const_iterator pos; 945 const_iterator begin = m_frames.begin(); 946 const_iterator end = m_frames.end(); 947 lldb::StackFrameSP ret_sp; 948 949 for (pos = begin; pos != end; ++pos) { 950 if (pos->get() == stack_frame_ptr) { 951 ret_sp = (*pos); 952 break; 953 } 954 } 955 return ret_sp; 956 } 957 958 size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame, 959 uint32_t num_frames, bool show_frame_info, 960 uint32_t num_frames_with_source, 961 bool show_unique, 962 const char *selected_frame_marker) { 963 size_t num_frames_displayed = 0; 964 965 if (num_frames == 0) 966 return 0; 967 968 StackFrameSP frame_sp; 969 uint32_t frame_idx = 0; 970 uint32_t last_frame; 971 972 // Don't let the last frame wrap around... 973 if (num_frames == UINT32_MAX) 974 last_frame = UINT32_MAX; 975 else 976 last_frame = first_frame + num_frames; 977 978 StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame(); 979 const char *unselected_marker = nullptr; 980 std::string buffer; 981 if (selected_frame_marker) { 982 size_t len = strlen(selected_frame_marker); 983 buffer.insert(buffer.begin(), len, ' '); 984 unselected_marker = buffer.c_str(); 985 } 986 const char *marker = nullptr; 987 988 for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) { 989 frame_sp = GetFrameAtIndex(frame_idx); 990 if (!frame_sp) 991 break; 992 993 if (selected_frame_marker != nullptr) { 994 if (frame_sp == selected_frame_sp) 995 marker = selected_frame_marker; 996 else 997 marker = unselected_marker; 998 } 999 1000 if (!frame_sp->GetStatus(strm, show_frame_info, 1001 num_frames_with_source > (first_frame - frame_idx), 1002 show_unique, marker)) 1003 break; 1004 ++num_frames_displayed; 1005 } 1006 1007 strm.IndentLess(); 1008 return num_frames_displayed; 1009 } 1010