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