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