1 //===-- StopInfo.cpp --------------------------------------------*- C++ -*-===// 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 <string> 10 11 #include "lldb/Breakpoint/Breakpoint.h" 12 #include "lldb/Breakpoint/BreakpointLocation.h" 13 #include "lldb/Breakpoint/StoppointCallbackContext.h" 14 #include "lldb/Breakpoint/Watchpoint.h" 15 #include "lldb/Core/Debugger.h" 16 #include "lldb/Core/ValueObject.h" 17 #include "lldb/Expression/UserExpression.h" 18 #include "lldb/Target/Process.h" 19 #include "lldb/Target/StopInfo.h" 20 #include "lldb/Target/Target.h" 21 #include "lldb/Target/Thread.h" 22 #include "lldb/Target/ThreadPlan.h" 23 #include "lldb/Target/UnixSignals.h" 24 #include "lldb/Utility/Log.h" 25 #include "lldb/Utility/StreamString.h" 26 27 using namespace lldb; 28 using namespace lldb_private; 29 30 StopInfo::StopInfo(Thread &thread, uint64_t value) 31 : m_thread_wp(thread.shared_from_this()), 32 m_stop_id(thread.GetProcess()->GetStopID()), 33 m_resume_id(thread.GetProcess()->GetResumeID()), m_value(value), 34 m_description(), m_override_should_notify(eLazyBoolCalculate), 35 m_override_should_stop(eLazyBoolCalculate), m_extended_info() {} 36 37 bool StopInfo::IsValid() const { 38 ThreadSP thread_sp(m_thread_wp.lock()); 39 if (thread_sp) 40 return thread_sp->GetProcess()->GetStopID() == m_stop_id; 41 return false; 42 } 43 44 void StopInfo::MakeStopInfoValid() { 45 ThreadSP thread_sp(m_thread_wp.lock()); 46 if (thread_sp) { 47 m_stop_id = thread_sp->GetProcess()->GetStopID(); 48 m_resume_id = thread_sp->GetProcess()->GetResumeID(); 49 } 50 } 51 52 bool StopInfo::HasTargetRunSinceMe() { 53 ThreadSP thread_sp(m_thread_wp.lock()); 54 55 if (thread_sp) { 56 lldb::StateType ret_type = thread_sp->GetProcess()->GetPrivateState(); 57 if (ret_type == eStateRunning) { 58 return true; 59 } else if (ret_type == eStateStopped) { 60 // This is a little tricky. We want to count "run and stopped again 61 // before you could ask this question as a "TRUE" answer to 62 // HasTargetRunSinceMe. But we don't want to include any running of the 63 // target done for expressions. So we track both resumes, and resumes 64 // caused by expressions, and check if there are any resumes 65 // NOT caused 66 // by expressions. 67 68 uint32_t curr_resume_id = thread_sp->GetProcess()->GetResumeID(); 69 uint32_t last_user_expression_id = 70 thread_sp->GetProcess()->GetLastUserExpressionResumeID(); 71 if (curr_resume_id == m_resume_id) { 72 return false; 73 } else if (curr_resume_id > last_user_expression_id) { 74 return true; 75 } 76 } 77 } 78 return false; 79 } 80 81 //---------------------------------------------------------------------- 82 // StopInfoBreakpoint 83 //---------------------------------------------------------------------- 84 85 namespace lldb_private { 86 class StopInfoBreakpoint : public StopInfo { 87 public: 88 StopInfoBreakpoint(Thread &thread, break_id_t break_id) 89 : StopInfo(thread, break_id), m_should_stop(false), 90 m_should_stop_is_valid(false), m_should_perform_action(true), 91 m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID), 92 m_was_one_shot(false) { 93 StoreBPInfo(); 94 } 95 96 StopInfoBreakpoint(Thread &thread, break_id_t break_id, bool should_stop) 97 : StopInfo(thread, break_id), m_should_stop(should_stop), 98 m_should_stop_is_valid(true), m_should_perform_action(true), 99 m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID), 100 m_was_one_shot(false) { 101 StoreBPInfo(); 102 } 103 104 ~StopInfoBreakpoint() override = default; 105 106 void StoreBPInfo() { 107 ThreadSP thread_sp(m_thread_wp.lock()); 108 if (thread_sp) { 109 BreakpointSiteSP bp_site_sp( 110 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value)); 111 if (bp_site_sp) { 112 if (bp_site_sp->GetNumberOfOwners() == 1) { 113 BreakpointLocationSP bp_loc_sp = bp_site_sp->GetOwnerAtIndex(0); 114 if (bp_loc_sp) { 115 m_break_id = bp_loc_sp->GetBreakpoint().GetID(); 116 m_was_one_shot = bp_loc_sp->GetBreakpoint().IsOneShot(); 117 } 118 } 119 m_address = bp_site_sp->GetLoadAddress(); 120 } 121 } 122 } 123 124 bool IsValidForOperatingSystemThread(Thread &thread) override { 125 ProcessSP process_sp(thread.GetProcess()); 126 if (process_sp) { 127 BreakpointSiteSP bp_site_sp( 128 process_sp->GetBreakpointSiteList().FindByID(m_value)); 129 if (bp_site_sp) 130 return bp_site_sp->ValidForThisThread(&thread); 131 } 132 return false; 133 } 134 135 StopReason GetStopReason() const override { return eStopReasonBreakpoint; } 136 137 bool ShouldStopSynchronous(Event *event_ptr) override { 138 ThreadSP thread_sp(m_thread_wp.lock()); 139 if (thread_sp) { 140 if (!m_should_stop_is_valid) { 141 // Only check once if we should stop at a breakpoint 142 BreakpointSiteSP bp_site_sp( 143 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value)); 144 if (bp_site_sp) { 145 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0)); 146 StoppointCallbackContext context(event_ptr, exe_ctx, true); 147 bp_site_sp->BumpHitCounts(); 148 m_should_stop = bp_site_sp->ShouldStop(&context); 149 } else { 150 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 151 152 if (log) 153 log->Printf( 154 "Process::%s could not find breakpoint site id: %" PRId64 "...", 155 __FUNCTION__, m_value); 156 157 m_should_stop = true; 158 } 159 m_should_stop_is_valid = true; 160 } 161 return m_should_stop; 162 } 163 return false; 164 } 165 166 bool DoShouldNotify(Event *event_ptr) override { 167 ThreadSP thread_sp(m_thread_wp.lock()); 168 if (thread_sp) { 169 BreakpointSiteSP bp_site_sp( 170 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value)); 171 if (bp_site_sp) { 172 bool all_internal = true; 173 174 for (uint32_t i = 0; i < bp_site_sp->GetNumberOfOwners(); i++) { 175 if (!bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint().IsInternal()) { 176 all_internal = false; 177 break; 178 } 179 } 180 return !all_internal; 181 } 182 } 183 return true; 184 } 185 186 const char *GetDescription() override { 187 if (m_description.empty()) { 188 ThreadSP thread_sp(m_thread_wp.lock()); 189 if (thread_sp) { 190 BreakpointSiteSP bp_site_sp( 191 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value)); 192 if (bp_site_sp) { 193 StreamString strm; 194 // If we have just hit an internal breakpoint, and it has a kind 195 // description, print that instead of the full breakpoint printing: 196 if (bp_site_sp->IsInternal()) { 197 size_t num_owners = bp_site_sp->GetNumberOfOwners(); 198 for (size_t idx = 0; idx < num_owners; idx++) { 199 const char *kind = bp_site_sp->GetOwnerAtIndex(idx) 200 ->GetBreakpoint() 201 .GetBreakpointKind(); 202 if (kind != nullptr) { 203 m_description.assign(kind); 204 return kind; 205 } 206 } 207 } 208 209 strm.Printf("breakpoint "); 210 bp_site_sp->GetDescription(&strm, eDescriptionLevelBrief); 211 m_description = strm.GetString(); 212 } else { 213 StreamString strm; 214 if (m_break_id != LLDB_INVALID_BREAK_ID) { 215 BreakpointSP break_sp = 216 thread_sp->GetProcess()->GetTarget().GetBreakpointByID( 217 m_break_id); 218 if (break_sp) { 219 if (break_sp->IsInternal()) { 220 const char *kind = break_sp->GetBreakpointKind(); 221 if (kind) 222 strm.Printf("internal %s breakpoint(%d).", kind, m_break_id); 223 else 224 strm.Printf("internal breakpoint(%d).", m_break_id); 225 } else { 226 strm.Printf("breakpoint %d.", m_break_id); 227 } 228 } else { 229 if (m_was_one_shot) 230 strm.Printf("one-shot breakpoint %d", m_break_id); 231 else 232 strm.Printf("breakpoint %d which has been deleted.", 233 m_break_id); 234 } 235 } else if (m_address == LLDB_INVALID_ADDRESS) 236 strm.Printf("breakpoint site %" PRIi64 237 " which has been deleted - unknown address", 238 m_value); 239 else 240 strm.Printf("breakpoint site %" PRIi64 241 " which has been deleted - was at 0x%" PRIx64, 242 m_value, m_address); 243 244 m_description = strm.GetString(); 245 } 246 } 247 } 248 return m_description.c_str(); 249 } 250 251 protected: 252 bool ShouldStop(Event *event_ptr) override { 253 // This just reports the work done by PerformAction or the synchronous 254 // stop. It should only ever get called after they have had a chance to 255 // run. 256 assert(m_should_stop_is_valid); 257 return m_should_stop; 258 } 259 260 void PerformAction(Event *event_ptr) override { 261 if (!m_should_perform_action) 262 return; 263 m_should_perform_action = false; 264 bool internal_breakpoint = true; 265 266 ThreadSP thread_sp(m_thread_wp.lock()); 267 268 if (thread_sp) { 269 Log *log = lldb_private::GetLogIfAnyCategoriesSet( 270 LIBLLDB_LOG_BREAKPOINTS | LIBLLDB_LOG_STEP); 271 272 if (!thread_sp->IsValid()) { 273 // This shouldn't ever happen, but just in case, don't do more harm. 274 if (log) { 275 log->Printf("PerformAction got called with an invalid thread."); 276 } 277 m_should_stop = true; 278 m_should_stop_is_valid = true; 279 return; 280 } 281 282 BreakpointSiteSP bp_site_sp( 283 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value)); 284 std::unordered_set<break_id_t> precondition_breakpoints; 285 286 if (bp_site_sp) { 287 // Let's copy the owners list out of the site and store them in a local 288 // list. That way if one of the breakpoint actions changes the site, 289 // then we won't be operating on a bad list. 290 BreakpointLocationCollection site_locations; 291 size_t num_owners = bp_site_sp->CopyOwnersList(site_locations); 292 293 if (num_owners == 0) { 294 m_should_stop = true; 295 } else { 296 // We go through each location, and test first its precondition - 297 // this overrides everything. Note, we only do this once per 298 // breakpoint - not once per location... Then check the condition. 299 // If the condition says to stop, then we run the callback for that 300 // location. If that callback says to stop as well, then we set 301 // m_should_stop to true; we are going to stop. But we still want to 302 // give all the breakpoints whose conditions say we are going to stop 303 // a chance to run their callbacks. Of course if any callback 304 // restarts the target by putting "continue" in the callback, then 305 // we're going to restart, without running the rest of the callbacks. 306 // And in this case we will end up not stopping even if another 307 // location said we should stop. But that's better than not running 308 // all the callbacks. 309 310 m_should_stop = false; 311 312 // We don't select threads as we go through them testing breakpoint 313 // conditions and running commands. So we need to set the thread for 314 // expression evaluation here: 315 ThreadList::ExpressionExecutionThreadPusher thread_pusher(thread_sp); 316 317 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0)); 318 Process *process = exe_ctx.GetProcessPtr(); 319 if (process->GetModIDRef().IsLastResumeForUserExpression()) { 320 // If we are in the middle of evaluating an expression, don't run 321 // asynchronous breakpoint commands or expressions. That could 322 // lead to infinite recursion if the command or condition re-calls 323 // the function with this breakpoint. 324 // TODO: We can keep a list of the breakpoints we've seen while 325 // running expressions in the nested 326 // PerformAction calls that can arise when the action runs a 327 // function that hits another breakpoint, and only stop running 328 // commands when we see the same breakpoint hit a second time. 329 330 m_should_stop_is_valid = true; 331 332 // It is possible that the user has a breakpoint at the same site 333 // as the completed plan had (e.g. user has a breakpoint 334 // on a module entry point, and `ThreadPlanCallFunction` ends 335 // also there). We can't find an internal breakpoint in the loop 336 // later because it was already removed on the plan completion. 337 // So check if the plan was completed, and stop if so. 338 if (thread_sp->CompletedPlanOverridesBreakpoint()) { 339 m_should_stop = true; 340 thread_sp->ResetStopInfo(); 341 return; 342 } 343 344 if (log) 345 log->Printf("StopInfoBreakpoint::PerformAction - Hit a " 346 "breakpoint while running an expression," 347 " not running commands to avoid recursion."); 348 bool ignoring_breakpoints = 349 process->GetIgnoreBreakpointsInExpressions(); 350 if (ignoring_breakpoints) { 351 m_should_stop = false; 352 // Internal breakpoints will always stop. 353 for (size_t j = 0; j < num_owners; j++) { 354 lldb::BreakpointLocationSP bp_loc_sp = 355 bp_site_sp->GetOwnerAtIndex(j); 356 if (bp_loc_sp->GetBreakpoint().IsInternal()) { 357 m_should_stop = true; 358 break; 359 } 360 } 361 } else { 362 m_should_stop = true; 363 } 364 if (log) 365 log->Printf("StopInfoBreakpoint::PerformAction - in expression, " 366 "continuing: %s.", 367 m_should_stop ? "true" : "false"); 368 process->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf( 369 "Warning: hit breakpoint while running function, skipping " 370 "commands and conditions to prevent recursion.\n"); 371 return; 372 } 373 374 StoppointCallbackContext context(event_ptr, exe_ctx, false); 375 376 // For safety's sake let's also grab an extra reference to the 377 // breakpoint owners of the locations we're going to examine, since 378 // the locations are going to have to get back to their breakpoints, 379 // and the locations don't keep their owners alive. I'm just 380 // sticking the BreakpointSP's in a vector since I'm only using it to 381 // locally increment their retain counts. 382 383 std::vector<lldb::BreakpointSP> location_owners; 384 385 for (size_t j = 0; j < num_owners; j++) { 386 BreakpointLocationSP loc(site_locations.GetByIndex(j)); 387 location_owners.push_back(loc->GetBreakpoint().shared_from_this()); 388 } 389 390 for (size_t j = 0; j < num_owners; j++) { 391 lldb::BreakpointLocationSP bp_loc_sp = site_locations.GetByIndex(j); 392 StreamString loc_desc; 393 if (log) { 394 bp_loc_sp->GetDescription(&loc_desc, eDescriptionLevelBrief); 395 } 396 // If another action disabled this breakpoint or its location, then 397 // don't run the actions. 398 if (!bp_loc_sp->IsEnabled() || 399 !bp_loc_sp->GetBreakpoint().IsEnabled()) 400 continue; 401 402 // The breakpoint site may have many locations associated with it, 403 // not all of them valid for this thread. Skip the ones that 404 // aren't: 405 if (!bp_loc_sp->ValidForThisThread(thread_sp.get())) { 406 if (log) { 407 log->Printf("Breakpoint %s hit on thread 0x%llx but it was not " 408 "for this thread, continuing.", 409 loc_desc.GetData(), static_cast<unsigned long long>( 410 thread_sp->GetID())); 411 } 412 continue; 413 } 414 415 internal_breakpoint = bp_loc_sp->GetBreakpoint().IsInternal(); 416 417 // First run the precondition, but since the precondition is per 418 // breakpoint, only run it once per breakpoint. 419 std::pair<std::unordered_set<break_id_t>::iterator, bool> result = 420 precondition_breakpoints.insert( 421 bp_loc_sp->GetBreakpoint().GetID()); 422 if (!result.second) 423 continue; 424 425 bool precondition_result = 426 bp_loc_sp->GetBreakpoint().EvaluatePrecondition(context); 427 if (!precondition_result) 428 continue; 429 430 // Next run the condition for the breakpoint. If that says we 431 // should stop, then we'll run the callback for the breakpoint. If 432 // the callback says we shouldn't stop that will win. 433 434 if (bp_loc_sp->GetConditionText() != nullptr) { 435 Status condition_error; 436 bool condition_says_stop = 437 bp_loc_sp->ConditionSaysStop(exe_ctx, condition_error); 438 439 if (!condition_error.Success()) { 440 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger(); 441 StreamSP error_sp = debugger.GetAsyncErrorStream(); 442 error_sp->Printf("Stopped due to an error evaluating condition " 443 "of breakpoint "); 444 bp_loc_sp->GetDescription(error_sp.get(), 445 eDescriptionLevelBrief); 446 error_sp->Printf(": \"%s\"", bp_loc_sp->GetConditionText()); 447 error_sp->EOL(); 448 const char *err_str = 449 condition_error.AsCString("<Unknown Error>"); 450 if (log) 451 log->Printf("Error evaluating condition: \"%s\"\n", err_str); 452 453 error_sp->PutCString(err_str); 454 error_sp->EOL(); 455 error_sp->Flush(); 456 } else { 457 if (log) { 458 log->Printf("Condition evaluated for breakpoint %s on thread " 459 "0x%llx conditon_says_stop: %i.", 460 loc_desc.GetData(), 461 static_cast<unsigned long long>( 462 thread_sp->GetID()), 463 condition_says_stop); 464 } 465 if (!condition_says_stop) { 466 // We don't want to increment the hit count of breakpoints if 467 // the condition fails. We've already bumped it by the time 468 // we get here, so undo the bump: 469 bp_loc_sp->UndoBumpHitCount(); 470 continue; 471 } 472 } 473 } 474 475 // Check the auto-continue bit on the location, do this before the 476 // callback since it may change this, but that would be for the 477 // NEXT hit. Note, you might think you could check auto-continue 478 // before the condition, and not evaluate the condition if it says 479 // to continue. But failing the condition means the breakpoint was 480 // effectively NOT HIT. So these two states are different. 481 bool auto_continue_says_stop = true; 482 if (bp_loc_sp->IsAutoContinue()) 483 { 484 if (log) 485 log->Printf("Continuing breakpoint %s as AutoContinue was set.", 486 loc_desc.GetData()); 487 // We want this stop reported, so you will know we auto-continued 488 // but only for external breakpoints: 489 if (!internal_breakpoint) 490 thread_sp->SetShouldReportStop(eVoteYes); 491 auto_continue_says_stop = false; 492 } 493 494 bool callback_says_stop = true; 495 496 // FIXME: For now the callbacks have to run in async mode - the 497 // first time we restart we need 498 // to get out of there. So set it here. 499 // When we figure out how to nest breakpoint hits then this will 500 // change. 501 502 Debugger &debugger = thread_sp->CalculateTarget()->GetDebugger(); 503 bool old_async = debugger.GetAsyncExecution(); 504 debugger.SetAsyncExecution(true); 505 506 callback_says_stop = bp_loc_sp->InvokeCallback(&context); 507 508 debugger.SetAsyncExecution(old_async); 509 510 if (callback_says_stop && auto_continue_says_stop) 511 m_should_stop = true; 512 513 // If we are going to stop for this breakpoint, then remove the 514 // breakpoint. 515 if (callback_says_stop && bp_loc_sp && 516 bp_loc_sp->GetBreakpoint().IsOneShot()) { 517 thread_sp->GetProcess()->GetTarget().RemoveBreakpointByID( 518 bp_loc_sp->GetBreakpoint().GetID()); 519 } 520 // Also make sure that the callback hasn't continued the target. If 521 // it did, when we'll set m_should_start to false and get out of 522 // here. 523 if (HasTargetRunSinceMe()) { 524 m_should_stop = false; 525 break; 526 } 527 } 528 } 529 // We've figured out what this stop wants to do, so mark it as valid so 530 // we don't compute it again. 531 m_should_stop_is_valid = true; 532 } else { 533 m_should_stop = true; 534 m_should_stop_is_valid = true; 535 Log *log_process( 536 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 537 538 if (log_process) 539 log_process->Printf( 540 "Process::%s could not find breakpoint site id: %" PRId64 "...", 541 __FUNCTION__, m_value); 542 } 543 544 if ((!m_should_stop || internal_breakpoint) && 545 thread_sp->CompletedPlanOverridesBreakpoint()) { 546 547 // Override should_stop decision when we have completed step plan 548 // additionally to the breakpoint 549 m_should_stop = true; 550 551 // Here we clean the preset stop info so the next GetStopInfo call will 552 // find the appropriate stop info, which should be the stop info 553 // related to the completed plan 554 thread_sp->ResetStopInfo(); 555 } 556 557 if (log) 558 log->Printf("Process::%s returning from action with m_should_stop: %d.", 559 __FUNCTION__, m_should_stop); 560 } 561 } 562 563 private: 564 bool m_should_stop; 565 bool m_should_stop_is_valid; 566 bool m_should_perform_action; // Since we are trying to preserve the "state" 567 // of the system even if we run functions 568 // etc. behind the users backs, we need to make sure we only REALLY perform 569 // the action once. 570 lldb::addr_t m_address; // We use this to capture the breakpoint site address 571 // when we create the StopInfo, 572 // in case somebody deletes it between the time the StopInfo is made and the 573 // description is asked for. 574 lldb::break_id_t m_break_id; 575 bool m_was_one_shot; 576 }; 577 578 //---------------------------------------------------------------------- 579 // StopInfoWatchpoint 580 //---------------------------------------------------------------------- 581 582 class StopInfoWatchpoint : public StopInfo { 583 public: 584 // Make sure watchpoint is properly disabled and subsequently enabled while 585 // performing watchpoint actions. 586 class WatchpointSentry { 587 public: 588 WatchpointSentry(ProcessSP p_sp, WatchpointSP w_sp) : process_sp(p_sp), 589 watchpoint_sp(w_sp) { 590 if (process_sp && watchpoint_sp) { 591 const bool notify = false; 592 watchpoint_sp->TurnOnEphemeralMode(); 593 process_sp->DisableWatchpoint(watchpoint_sp.get(), notify); 594 process_sp->AddPreResumeAction(SentryPreResumeAction, this); 595 } 596 } 597 598 void DoReenable() { 599 if (process_sp && watchpoint_sp) { 600 bool was_disabled = watchpoint_sp->IsDisabledDuringEphemeralMode(); 601 watchpoint_sp->TurnOffEphemeralMode(); 602 const bool notify = false; 603 if (was_disabled) { 604 process_sp->DisableWatchpoint(watchpoint_sp.get(), notify); 605 } else { 606 process_sp->EnableWatchpoint(watchpoint_sp.get(), notify); 607 } 608 } 609 } 610 611 ~WatchpointSentry() { 612 DoReenable(); 613 if (process_sp) 614 process_sp->ClearPreResumeAction(SentryPreResumeAction, this); 615 } 616 617 static bool SentryPreResumeAction(void *sentry_void) { 618 WatchpointSentry *sentry = (WatchpointSentry *) sentry_void; 619 sentry->DoReenable(); 620 return true; 621 } 622 623 private: 624 ProcessSP process_sp; 625 WatchpointSP watchpoint_sp; 626 }; 627 628 StopInfoWatchpoint(Thread &thread, break_id_t watch_id, 629 lldb::addr_t watch_hit_addr) 630 : StopInfo(thread, watch_id), m_should_stop(false), 631 m_should_stop_is_valid(false), m_watch_hit_addr(watch_hit_addr) {} 632 633 ~StopInfoWatchpoint() override = default; 634 635 StopReason GetStopReason() const override { return eStopReasonWatchpoint; } 636 637 const char *GetDescription() override { 638 if (m_description.empty()) { 639 StreamString strm; 640 strm.Printf("watchpoint %" PRIi64, m_value); 641 m_description = strm.GetString(); 642 } 643 return m_description.c_str(); 644 } 645 646 protected: 647 bool ShouldStopSynchronous(Event *event_ptr) override { 648 // ShouldStop() method is idempotent and should not affect hit count. See 649 // Process::RunPrivateStateThread()->Process()->HandlePrivateEvent() 650 // -->Process()::ShouldBroadcastEvent()->ThreadList::ShouldStop()-> 651 // Thread::ShouldStop()->ThreadPlanBase::ShouldStop()-> 652 // StopInfoWatchpoint::ShouldStop() and 653 // Event::DoOnRemoval()->Process::ProcessEventData::DoOnRemoval()-> 654 // StopInfoWatchpoint::PerformAction(). 655 if (m_should_stop_is_valid) 656 return m_should_stop; 657 658 ThreadSP thread_sp(m_thread_wp.lock()); 659 if (thread_sp) { 660 WatchpointSP wp_sp( 661 thread_sp->CalculateTarget()->GetWatchpointList().FindByID( 662 GetValue())); 663 if (wp_sp) { 664 // Check if we should stop at a watchpoint. 665 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0)); 666 StoppointCallbackContext context(event_ptr, exe_ctx, true); 667 m_should_stop = wp_sp->ShouldStop(&context); 668 } else { 669 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 670 671 if (log) 672 log->Printf( 673 "Process::%s could not find watchpoint location id: %" PRId64 674 "...", 675 __FUNCTION__, GetValue()); 676 677 m_should_stop = true; 678 } 679 } 680 m_should_stop_is_valid = true; 681 return m_should_stop; 682 } 683 684 bool ShouldStop(Event *event_ptr) override { 685 // This just reports the work done by PerformAction or the synchronous 686 // stop. It should only ever get called after they have had a chance to 687 // run. 688 assert(m_should_stop_is_valid); 689 return m_should_stop; 690 } 691 692 void PerformAction(Event *event_ptr) override { 693 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS); 694 // We're going to calculate if we should stop or not in some way during the 695 // course of this code. Also by default we're going to stop, so set that 696 // here. 697 m_should_stop = true; 698 699 700 ThreadSP thread_sp(m_thread_wp.lock()); 701 if (thread_sp) { 702 703 WatchpointSP wp_sp( 704 thread_sp->CalculateTarget()->GetWatchpointList().FindByID( 705 GetValue())); 706 if (wp_sp) { 707 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0)); 708 ProcessSP process_sp = exe_ctx.GetProcessSP(); 709 710 { 711 // check if this process is running on an architecture where 712 // watchpoints trigger before the associated instruction runs. if so, 713 // disable the WP, single-step and then re-enable the watchpoint 714 if (process_sp) { 715 uint32_t num; 716 bool wp_triggers_after; 717 718 if (process_sp->GetWatchpointSupportInfo(num, wp_triggers_after) 719 .Success()) { 720 if (!wp_triggers_after) { 721 // We need to preserve the watch_index before watchpoint is 722 // disable. Since Watchpoint::SetEnabled will clear the watch 723 // index. This will fix TestWatchpointIter failure 724 Watchpoint *wp = wp_sp.get(); 725 uint32_t watch_index = wp->GetHardwareIndex(); 726 process_sp->DisableWatchpoint(wp, false); 727 StopInfoSP stored_stop_info_sp = thread_sp->GetStopInfo(); 728 assert(stored_stop_info_sp.get() == this); 729 730 Status new_plan_status; 731 ThreadPlanSP new_plan_sp( 732 thread_sp->QueueThreadPlanForStepSingleInstruction( 733 false, // step-over 734 false, // abort_other_plans 735 true, // stop_other_threads 736 new_plan_status)); 737 if (new_plan_sp && new_plan_status.Success()) { 738 new_plan_sp->SetIsMasterPlan(true); 739 new_plan_sp->SetOkayToDiscard(false); 740 new_plan_sp->SetPrivate(true); 741 } 742 process_sp->GetThreadList().SetSelectedThreadByID( 743 thread_sp->GetID()); 744 process_sp->ResumeSynchronous(nullptr); 745 process_sp->GetThreadList().SetSelectedThreadByID( 746 thread_sp->GetID()); 747 thread_sp->SetStopInfo(stored_stop_info_sp); 748 process_sp->EnableWatchpoint(wp, false); 749 wp->SetHardwareIndex(watch_index); 750 } 751 } 752 } 753 } 754 755 // This sentry object makes sure the current watchpoint is disabled 756 // while performing watchpoint actions, and it is then enabled after we 757 // are finished. 758 WatchpointSentry sentry(process_sp, wp_sp); 759 760 /* 761 * MIPS: Last 3bits of the watchpoint address are masked by the kernel. 762 * For example: 763 * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is 764 * set at 'm', then 765 * watch exception is generated even when 'n' is read/written. To handle 766 * this case, 767 * server emulates the instruction at PC and finds the base address of 768 * the load/store 769 * instruction and appends it in the description of the stop-info 770 * packet. If watchpoint 771 * is not set on this address by user then this do not stop. 772 */ 773 if (m_watch_hit_addr != LLDB_INVALID_ADDRESS) { 774 WatchpointSP wp_hit_sp = 775 thread_sp->CalculateTarget()->GetWatchpointList().FindByAddress( 776 m_watch_hit_addr); 777 if (!wp_hit_sp) { 778 m_should_stop = false; 779 wp_sp->IncrementFalseAlarmsAndReviseHitCount(); 780 } 781 } 782 783 // TODO: This condition should be checked in the synchronous part of the 784 // watchpoint code 785 // (Watchpoint::ShouldStop), so that we avoid pulling an event even if 786 // the watchpoint fails the ignore count condition. It is moved here 787 // temporarily, because for archs with 788 // watchpoint_exceptions_received=before, the code in the previous 789 // lines takes care of moving the inferior to next PC. We have to check 790 // the ignore count condition after this is done, otherwise we will hit 791 // same watchpoint multiple times until we pass ignore condition, but 792 // we won't actually be ignoring them. 793 if (wp_sp->GetHitCount() <= wp_sp->GetIgnoreCount()) 794 m_should_stop = false; 795 796 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger(); 797 798 if (m_should_stop && wp_sp->GetConditionText() != nullptr) { 799 // We need to make sure the user sees any parse errors in their 800 // condition, so we'll hook the constructor errors up to the 801 // debugger's Async I/O. 802 ExpressionResults result_code; 803 EvaluateExpressionOptions expr_options; 804 expr_options.SetUnwindOnError(true); 805 expr_options.SetIgnoreBreakpoints(true); 806 ValueObjectSP result_value_sp; 807 Status error; 808 result_code = UserExpression::Evaluate( 809 exe_ctx, expr_options, wp_sp->GetConditionText(), 810 llvm::StringRef(), result_value_sp, error); 811 812 if (result_code == eExpressionCompleted) { 813 if (result_value_sp) { 814 Scalar scalar_value; 815 if (result_value_sp->ResolveValue(scalar_value)) { 816 if (scalar_value.ULongLong(1) == 0) { 817 // We have been vetoed. This takes precedence over querying 818 // the watchpoint whether it should stop (aka ignore count 819 // and friends). See also StopInfoWatchpoint::ShouldStop() 820 // as well as Process::ProcessEventData::DoOnRemoval(). 821 m_should_stop = false; 822 } else 823 m_should_stop = true; 824 if (log) 825 log->Printf( 826 "Condition successfully evaluated, result is %s.\n", 827 m_should_stop ? "true" : "false"); 828 } else { 829 m_should_stop = true; 830 if (log) 831 log->Printf( 832 "Failed to get an integer result from the expression."); 833 } 834 } 835 } else { 836 StreamSP error_sp = debugger.GetAsyncErrorStream(); 837 error_sp->Printf( 838 "Stopped due to an error evaluating condition of watchpoint "); 839 wp_sp->GetDescription(error_sp.get(), eDescriptionLevelBrief); 840 error_sp->Printf(": \"%s\"", wp_sp->GetConditionText()); 841 error_sp->EOL(); 842 const char *err_str = error.AsCString("<Unknown Error>"); 843 if (log) 844 log->Printf("Error evaluating condition: \"%s\"\n", err_str); 845 846 error_sp->PutCString(err_str); 847 error_sp->EOL(); 848 error_sp->Flush(); 849 // If the condition fails to be parsed or run, we should stop. 850 m_should_stop = true; 851 } 852 } 853 854 // If the condition says to stop, we run the callback to further decide 855 // whether to stop. 856 if (m_should_stop) { 857 // FIXME: For now the callbacks have to run in async mode - the 858 // first time we restart we need 859 // to get out of there. So set it here. 860 // When we figure out how to nest watchpoint hits then this will 861 // change. 862 863 bool old_async = debugger.GetAsyncExecution(); 864 debugger.SetAsyncExecution(true); 865 866 StoppointCallbackContext context(event_ptr, exe_ctx, false); 867 bool stop_requested = wp_sp->InvokeCallback(&context); 868 869 debugger.SetAsyncExecution(old_async); 870 871 // Also make sure that the callback hasn't continued the target. If 872 // it did, when we'll set m_should_stop to false and get out of here. 873 if (HasTargetRunSinceMe()) 874 m_should_stop = false; 875 876 if (m_should_stop && !stop_requested) { 877 // We have been vetoed by the callback mechanism. 878 m_should_stop = false; 879 } 880 } 881 // Finally, if we are going to stop, print out the new & old values: 882 if (m_should_stop) { 883 wp_sp->CaptureWatchedValue(exe_ctx); 884 885 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger(); 886 StreamSP output_sp = debugger.GetAsyncOutputStream(); 887 wp_sp->DumpSnapshots(output_sp.get()); 888 output_sp->EOL(); 889 output_sp->Flush(); 890 } 891 892 } else { 893 Log *log_process( 894 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 895 896 if (log_process) 897 log_process->Printf( 898 "Process::%s could not find watchpoint id: %" PRId64 "...", 899 __FUNCTION__, m_value); 900 } 901 if (log) 902 log->Printf("Process::%s returning from action with m_should_stop: %d.", 903 __FUNCTION__, m_should_stop); 904 905 m_should_stop_is_valid = true; 906 } 907 } 908 909 private: 910 bool m_should_stop; 911 bool m_should_stop_is_valid; 912 lldb::addr_t m_watch_hit_addr; 913 }; 914 915 //---------------------------------------------------------------------- 916 // StopInfoUnixSignal 917 //---------------------------------------------------------------------- 918 919 class StopInfoUnixSignal : public StopInfo { 920 public: 921 StopInfoUnixSignal(Thread &thread, int signo, const char *description) 922 : StopInfo(thread, signo) { 923 SetDescription(description); 924 } 925 926 ~StopInfoUnixSignal() override = default; 927 928 StopReason GetStopReason() const override { return eStopReasonSignal; } 929 930 bool ShouldStopSynchronous(Event *event_ptr) override { 931 ThreadSP thread_sp(m_thread_wp.lock()); 932 if (thread_sp) 933 return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value); 934 return false; 935 } 936 937 bool ShouldStop(Event *event_ptr) override { 938 ThreadSP thread_sp(m_thread_wp.lock()); 939 if (thread_sp) 940 return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value); 941 return false; 942 } 943 944 // If should stop returns false, check if we should notify of this event 945 bool DoShouldNotify(Event *event_ptr) override { 946 ThreadSP thread_sp(m_thread_wp.lock()); 947 if (thread_sp) { 948 bool should_notify = 949 thread_sp->GetProcess()->GetUnixSignals()->GetShouldNotify(m_value); 950 if (should_notify) { 951 StreamString strm; 952 strm.Printf( 953 "thread %d received signal: %s", thread_sp->GetIndexID(), 954 thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString( 955 m_value)); 956 Process::ProcessEventData::AddRestartedReason(event_ptr, 957 strm.GetData()); 958 } 959 return should_notify; 960 } 961 return true; 962 } 963 964 void WillResume(lldb::StateType resume_state) override { 965 ThreadSP thread_sp(m_thread_wp.lock()); 966 if (thread_sp) { 967 if (!thread_sp->GetProcess()->GetUnixSignals()->GetShouldSuppress( 968 m_value)) 969 thread_sp->SetResumeSignal(m_value); 970 } 971 } 972 973 const char *GetDescription() override { 974 if (m_description.empty()) { 975 ThreadSP thread_sp(m_thread_wp.lock()); 976 if (thread_sp) { 977 StreamString strm; 978 const char *signal_name = 979 thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString( 980 m_value); 981 if (signal_name) 982 strm.Printf("signal %s", signal_name); 983 else 984 strm.Printf("signal %" PRIi64, m_value); 985 m_description = strm.GetString(); 986 } 987 } 988 return m_description.c_str(); 989 } 990 }; 991 992 //---------------------------------------------------------------------- 993 // StopInfoTrace 994 //---------------------------------------------------------------------- 995 996 class StopInfoTrace : public StopInfo { 997 public: 998 StopInfoTrace(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {} 999 1000 ~StopInfoTrace() override = default; 1001 1002 StopReason GetStopReason() const override { return eStopReasonTrace; } 1003 1004 const char *GetDescription() override { 1005 if (m_description.empty()) 1006 return "trace"; 1007 else 1008 return m_description.c_str(); 1009 } 1010 }; 1011 1012 //---------------------------------------------------------------------- 1013 // StopInfoException 1014 //---------------------------------------------------------------------- 1015 1016 class StopInfoException : public StopInfo { 1017 public: 1018 StopInfoException(Thread &thread, const char *description) 1019 : StopInfo(thread, LLDB_INVALID_UID) { 1020 if (description) 1021 SetDescription(description); 1022 } 1023 1024 ~StopInfoException() override = default; 1025 1026 StopReason GetStopReason() const override { return eStopReasonException; } 1027 1028 const char *GetDescription() override { 1029 if (m_description.empty()) 1030 return "exception"; 1031 else 1032 return m_description.c_str(); 1033 } 1034 }; 1035 1036 //---------------------------------------------------------------------- 1037 // StopInfoThreadPlan 1038 //---------------------------------------------------------------------- 1039 1040 class StopInfoThreadPlan : public StopInfo { 1041 public: 1042 StopInfoThreadPlan(ThreadPlanSP &plan_sp, ValueObjectSP &return_valobj_sp, 1043 ExpressionVariableSP &expression_variable_sp) 1044 : StopInfo(plan_sp->GetThread(), LLDB_INVALID_UID), m_plan_sp(plan_sp), 1045 m_return_valobj_sp(return_valobj_sp), 1046 m_expression_variable_sp(expression_variable_sp) {} 1047 1048 ~StopInfoThreadPlan() override = default; 1049 1050 StopReason GetStopReason() const override { return eStopReasonPlanComplete; } 1051 1052 const char *GetDescription() override { 1053 if (m_description.empty()) { 1054 StreamString strm; 1055 m_plan_sp->GetDescription(&strm, eDescriptionLevelBrief); 1056 m_description = strm.GetString(); 1057 } 1058 return m_description.c_str(); 1059 } 1060 1061 ValueObjectSP GetReturnValueObject() { return m_return_valobj_sp; } 1062 1063 ExpressionVariableSP GetExpressionVariable() { 1064 return m_expression_variable_sp; 1065 } 1066 1067 protected: 1068 bool ShouldStop(Event *event_ptr) override { 1069 if (m_plan_sp) 1070 return m_plan_sp->ShouldStop(event_ptr); 1071 else 1072 return StopInfo::ShouldStop(event_ptr); 1073 } 1074 1075 private: 1076 ThreadPlanSP m_plan_sp; 1077 ValueObjectSP m_return_valobj_sp; 1078 ExpressionVariableSP m_expression_variable_sp; 1079 }; 1080 1081 //---------------------------------------------------------------------- 1082 // StopInfoExec 1083 //---------------------------------------------------------------------- 1084 1085 class StopInfoExec : public StopInfo { 1086 public: 1087 StopInfoExec(Thread &thread) 1088 : StopInfo(thread, LLDB_INVALID_UID), m_performed_action(false) {} 1089 1090 ~StopInfoExec() override = default; 1091 1092 bool ShouldStop(Event *event_ptr) override { 1093 ThreadSP thread_sp(m_thread_wp.lock()); 1094 if (thread_sp) 1095 return thread_sp->GetProcess()->GetStopOnExec(); 1096 return false; 1097 } 1098 1099 StopReason GetStopReason() const override { return eStopReasonExec; } 1100 1101 const char *GetDescription() override { return "exec"; } 1102 1103 protected: 1104 void PerformAction(Event *event_ptr) override { 1105 // Only perform the action once 1106 if (m_performed_action) 1107 return; 1108 m_performed_action = true; 1109 ThreadSP thread_sp(m_thread_wp.lock()); 1110 if (thread_sp) 1111 thread_sp->GetProcess()->DidExec(); 1112 } 1113 1114 bool m_performed_action; 1115 }; 1116 1117 } // namespace lldb_private 1118 1119 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread, 1120 break_id_t break_id) { 1121 return StopInfoSP(new StopInfoBreakpoint(thread, break_id)); 1122 } 1123 1124 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread, 1125 break_id_t break_id, 1126 bool should_stop) { 1127 return StopInfoSP(new StopInfoBreakpoint(thread, break_id, should_stop)); 1128 } 1129 1130 StopInfoSP 1131 StopInfo::CreateStopReasonWithWatchpointID(Thread &thread, break_id_t watch_id, 1132 lldb::addr_t watch_hit_addr) { 1133 return StopInfoSP(new StopInfoWatchpoint(thread, watch_id, watch_hit_addr)); 1134 } 1135 1136 StopInfoSP StopInfo::CreateStopReasonWithSignal(Thread &thread, int signo, 1137 const char *description) { 1138 return StopInfoSP(new StopInfoUnixSignal(thread, signo, description)); 1139 } 1140 1141 StopInfoSP StopInfo::CreateStopReasonToTrace(Thread &thread) { 1142 return StopInfoSP(new StopInfoTrace(thread)); 1143 } 1144 1145 StopInfoSP StopInfo::CreateStopReasonWithPlan( 1146 ThreadPlanSP &plan_sp, ValueObjectSP return_valobj_sp, 1147 ExpressionVariableSP expression_variable_sp) { 1148 return StopInfoSP(new StopInfoThreadPlan(plan_sp, return_valobj_sp, 1149 expression_variable_sp)); 1150 } 1151 1152 StopInfoSP StopInfo::CreateStopReasonWithException(Thread &thread, 1153 const char *description) { 1154 return StopInfoSP(new StopInfoException(thread, description)); 1155 } 1156 1157 StopInfoSP StopInfo::CreateStopReasonWithExec(Thread &thread) { 1158 return StopInfoSP(new StopInfoExec(thread)); 1159 } 1160 1161 ValueObjectSP StopInfo::GetReturnValueObject(StopInfoSP &stop_info_sp) { 1162 if (stop_info_sp && 1163 stop_info_sp->GetStopReason() == eStopReasonPlanComplete) { 1164 StopInfoThreadPlan *plan_stop_info = 1165 static_cast<StopInfoThreadPlan *>(stop_info_sp.get()); 1166 return plan_stop_info->GetReturnValueObject(); 1167 } else 1168 return ValueObjectSP(); 1169 } 1170 1171 ExpressionVariableSP StopInfo::GetExpressionVariable(StopInfoSP &stop_info_sp) { 1172 if (stop_info_sp && 1173 stop_info_sp->GetStopReason() == eStopReasonPlanComplete) { 1174 StopInfoThreadPlan *plan_stop_info = 1175 static_cast<StopInfoThreadPlan *>(stop_info_sp.get()); 1176 return plan_stop_info->GetExpressionVariable(); 1177 } else 1178 return ExpressionVariableSP(); 1179 } 1180 1181 lldb::ValueObjectSP 1182 StopInfo::GetCrashingDereference(StopInfoSP &stop_info_sp, 1183 lldb::addr_t *crashing_address) { 1184 if (!stop_info_sp) { 1185 return ValueObjectSP(); 1186 } 1187 1188 const char *description = stop_info_sp->GetDescription(); 1189 if (!description) { 1190 return ValueObjectSP(); 1191 } 1192 1193 ThreadSP thread_sp = stop_info_sp->GetThread(); 1194 if (!thread_sp) { 1195 return ValueObjectSP(); 1196 } 1197 1198 StackFrameSP frame_sp = thread_sp->GetSelectedFrame(); 1199 1200 if (!frame_sp) { 1201 return ValueObjectSP(); 1202 } 1203 1204 const char address_string[] = "address="; 1205 1206 const char *address_loc = strstr(description, address_string); 1207 if (!address_loc) { 1208 return ValueObjectSP(); 1209 } 1210 1211 address_loc += (sizeof(address_string) - 1); 1212 1213 uint64_t address = strtoull(address_loc, 0, 0); 1214 if (crashing_address) { 1215 *crashing_address = address; 1216 } 1217 1218 return frame_sp->GuessValueForAddress(address); 1219 } 1220