1 //===-- StopInfo.cpp --------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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"
28 using namespace lldb_private;
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() {}
37 bool StopInfo::IsValid() const {
38 ThreadSP thread_sp(m_thread_wp.lock());
40 return thread_sp->GetProcess()->GetStopID() == m_stop_id;
44 void StopInfo::MakeStopInfoValid() {
45 ThreadSP thread_sp(m_thread_wp.lock());
47 m_stop_id = thread_sp->GetProcess()->GetStopID();
48 m_resume_id = thread_sp->GetProcess()->GetResumeID();
52 bool StopInfo::HasTargetRunSinceMe() {
53 ThreadSP thread_sp(m_thread_wp.lock());
56 lldb::StateType ret_type = thread_sp->GetProcess()->GetPrivateState();
57 if (ret_type == eStateRunning) {
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
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) {
73 } else if (curr_resume_id > last_user_expression_id) {
83 namespace lldb_private {
84 class StopInfoBreakpoint : public StopInfo {
86 StopInfoBreakpoint(Thread &thread, break_id_t break_id)
87 : StopInfo(thread, break_id), m_should_stop(false),
88 m_should_stop_is_valid(false), m_should_perform_action(true),
89 m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
90 m_was_one_shot(false) {
94 StopInfoBreakpoint(Thread &thread, break_id_t break_id, bool should_stop)
95 : StopInfo(thread, break_id), m_should_stop(should_stop),
96 m_should_stop_is_valid(true), m_should_perform_action(true),
97 m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
98 m_was_one_shot(false) {
102 ~StopInfoBreakpoint() override = default;
105 ThreadSP thread_sp(m_thread_wp.lock());
107 BreakpointSiteSP bp_site_sp(
108 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
110 if (bp_site_sp->GetNumberOfOwners() == 1) {
111 BreakpointLocationSP bp_loc_sp = bp_site_sp->GetOwnerAtIndex(0);
113 m_break_id = bp_loc_sp->GetBreakpoint().GetID();
114 m_was_one_shot = bp_loc_sp->GetBreakpoint().IsOneShot();
117 m_address = bp_site_sp->GetLoadAddress();
122 bool IsValidForOperatingSystemThread(Thread &thread) override {
123 ProcessSP process_sp(thread.GetProcess());
125 BreakpointSiteSP bp_site_sp(
126 process_sp->GetBreakpointSiteList().FindByID(m_value));
128 return bp_site_sp->ValidForThisThread(&thread);
133 StopReason GetStopReason() const override { return eStopReasonBreakpoint; }
135 bool ShouldStopSynchronous(Event *event_ptr) override {
136 ThreadSP thread_sp(m_thread_wp.lock());
138 if (!m_should_stop_is_valid) {
139 // Only check once if we should stop at a breakpoint
140 BreakpointSiteSP bp_site_sp(
141 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
143 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
144 StoppointCallbackContext context(event_ptr, exe_ctx, true);
145 bp_site_sp->BumpHitCounts();
146 m_should_stop = bp_site_sp->ShouldStop(&context);
148 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
152 "Process::%s could not find breakpoint site id: %" PRId64 "...",
153 __FUNCTION__, m_value);
155 m_should_stop = true;
157 m_should_stop_is_valid = true;
159 return m_should_stop;
164 bool DoShouldNotify(Event *event_ptr) override {
165 ThreadSP thread_sp(m_thread_wp.lock());
167 BreakpointSiteSP bp_site_sp(
168 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
170 bool all_internal = true;
172 for (uint32_t i = 0; i < bp_site_sp->GetNumberOfOwners(); i++) {
173 if (!bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint().IsInternal()) {
174 all_internal = false;
178 return !all_internal;
184 const char *GetDescription() override {
185 if (m_description.empty()) {
186 ThreadSP thread_sp(m_thread_wp.lock());
188 BreakpointSiteSP bp_site_sp(
189 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
192 // If we have just hit an internal breakpoint, and it has a kind
193 // description, print that instead of the full breakpoint printing:
194 if (bp_site_sp->IsInternal()) {
195 size_t num_owners = bp_site_sp->GetNumberOfOwners();
196 for (size_t idx = 0; idx < num_owners; idx++) {
197 const char *kind = bp_site_sp->GetOwnerAtIndex(idx)
199 .GetBreakpointKind();
200 if (kind != nullptr) {
201 m_description.assign(kind);
207 strm.Printf("breakpoint ");
208 bp_site_sp->GetDescription(&strm, eDescriptionLevelBrief);
209 m_description = strm.GetString();
212 if (m_break_id != LLDB_INVALID_BREAK_ID) {
213 BreakpointSP break_sp =
214 thread_sp->GetProcess()->GetTarget().GetBreakpointByID(
217 if (break_sp->IsInternal()) {
218 const char *kind = break_sp->GetBreakpointKind();
220 strm.Printf("internal %s breakpoint(%d).", kind, m_break_id);
222 strm.Printf("internal breakpoint(%d).", m_break_id);
224 strm.Printf("breakpoint %d.", m_break_id);
228 strm.Printf("one-shot breakpoint %d", m_break_id);
230 strm.Printf("breakpoint %d which has been deleted.",
233 } else if (m_address == LLDB_INVALID_ADDRESS)
234 strm.Printf("breakpoint site %" PRIi64
235 " which has been deleted - unknown address",
238 strm.Printf("breakpoint site %" PRIi64
239 " which has been deleted - was at 0x%" PRIx64,
242 m_description = strm.GetString();
246 return m_description.c_str();
250 bool ShouldStop(Event *event_ptr) override {
251 // This just reports the work done by PerformAction or the synchronous
252 // stop. It should only ever get called after they have had a chance to
254 assert(m_should_stop_is_valid);
255 return m_should_stop;
258 void PerformAction(Event *event_ptr) override {
259 if (!m_should_perform_action)
261 m_should_perform_action = false;
262 bool internal_breakpoint = true;
264 ThreadSP thread_sp(m_thread_wp.lock());
267 Log *log = lldb_private::GetLogIfAnyCategoriesSet(
268 LIBLLDB_LOG_BREAKPOINTS | LIBLLDB_LOG_STEP);
270 if (!thread_sp->IsValid()) {
271 // This shouldn't ever happen, but just in case, don't do more harm.
273 log->Printf("PerformAction got called with an invalid thread.");
275 m_should_stop = true;
276 m_should_stop_is_valid = true;
280 BreakpointSiteSP bp_site_sp(
281 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
282 std::unordered_set<break_id_t> precondition_breakpoints;
285 // Let's copy the owners list out of the site and store them in a local
286 // list. That way if one of the breakpoint actions changes the site,
287 // then we won't be operating on a bad list.
288 BreakpointLocationCollection site_locations;
289 size_t num_owners = bp_site_sp->CopyOwnersList(site_locations);
291 if (num_owners == 0) {
292 m_should_stop = true;
294 // We go through each location, and test first its precondition -
295 // this overrides everything. Note, we only do this once per
296 // breakpoint - not once per location... Then check the condition.
297 // If the condition says to stop, then we run the callback for that
298 // location. If that callback says to stop as well, then we set
299 // m_should_stop to true; we are going to stop. But we still want to
300 // give all the breakpoints whose conditions say we are going to stop
301 // a chance to run their callbacks. Of course if any callback
302 // restarts the target by putting "continue" in the callback, then
303 // we're going to restart, without running the rest of the callbacks.
304 // And in this case we will end up not stopping even if another
305 // location said we should stop. But that's better than not running
306 // all the callbacks.
308 m_should_stop = false;
310 // We don't select threads as we go through them testing breakpoint
311 // conditions and running commands. So we need to set the thread for
312 // expression evaluation here:
313 ThreadList::ExpressionExecutionThreadPusher thread_pusher(thread_sp);
315 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
316 Process *process = exe_ctx.GetProcessPtr();
317 if (process->GetModIDRef().IsLastResumeForUserExpression()) {
318 // If we are in the middle of evaluating an expression, don't run
319 // asynchronous breakpoint commands or expressions. That could
320 // lead to infinite recursion if the command or condition re-calls
321 // the function with this breakpoint.
322 // TODO: We can keep a list of the breakpoints we've seen while
323 // running expressions in the nested
324 // PerformAction calls that can arise when the action runs a
325 // function that hits another breakpoint, and only stop running
326 // commands when we see the same breakpoint hit a second time.
328 m_should_stop_is_valid = true;
330 // It is possible that the user has a breakpoint at the same site
331 // as the completed plan had (e.g. user has a breakpoint
332 // on a module entry point, and `ThreadPlanCallFunction` ends
333 // also there). We can't find an internal breakpoint in the loop
334 // later because it was already removed on the plan completion.
335 // So check if the plan was completed, and stop if so.
336 if (thread_sp->CompletedPlanOverridesBreakpoint()) {
337 m_should_stop = true;
338 thread_sp->ResetStopInfo();
343 log->Printf("StopInfoBreakpoint::PerformAction - Hit a "
344 "breakpoint while running an expression,"
345 " not running commands to avoid recursion.");
346 bool ignoring_breakpoints =
347 process->GetIgnoreBreakpointsInExpressions();
348 if (ignoring_breakpoints) {
349 m_should_stop = false;
350 // Internal breakpoints will always stop.
351 for (size_t j = 0; j < num_owners; j++) {
352 lldb::BreakpointLocationSP bp_loc_sp =
353 bp_site_sp->GetOwnerAtIndex(j);
354 if (bp_loc_sp->GetBreakpoint().IsInternal()) {
355 m_should_stop = true;
360 m_should_stop = true;
363 log->Printf("StopInfoBreakpoint::PerformAction - in expression, "
365 m_should_stop ? "true" : "false");
366 process->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
367 "Warning: hit breakpoint while running function, skipping "
368 "commands and conditions to prevent recursion.\n");
372 StoppointCallbackContext context(event_ptr, exe_ctx, false);
374 // For safety's sake let's also grab an extra reference to the
375 // breakpoint owners of the locations we're going to examine, since
376 // the locations are going to have to get back to their breakpoints,
377 // and the locations don't keep their owners alive. I'm just
378 // sticking the BreakpointSP's in a vector since I'm only using it to
379 // locally increment their retain counts.
381 std::vector<lldb::BreakpointSP> location_owners;
383 for (size_t j = 0; j < num_owners; j++) {
384 BreakpointLocationSP loc(site_locations.GetByIndex(j));
385 location_owners.push_back(loc->GetBreakpoint().shared_from_this());
388 for (size_t j = 0; j < num_owners; j++) {
389 lldb::BreakpointLocationSP bp_loc_sp = site_locations.GetByIndex(j);
390 StreamString loc_desc;
392 bp_loc_sp->GetDescription(&loc_desc, eDescriptionLevelBrief);
394 // If another action disabled this breakpoint or its location, then
395 // don't run the actions.
396 if (!bp_loc_sp->IsEnabled() ||
397 !bp_loc_sp->GetBreakpoint().IsEnabled())
400 // The breakpoint site may have many locations associated with it,
401 // not all of them valid for this thread. Skip the ones that
403 if (!bp_loc_sp->ValidForThisThread(thread_sp.get())) {
405 log->Printf("Breakpoint %s hit on thread 0x%llx but it was not "
406 "for this thread, continuing.",
407 loc_desc.GetData(), static_cast<unsigned long long>(
408 thread_sp->GetID()));
413 internal_breakpoint = bp_loc_sp->GetBreakpoint().IsInternal();
415 // First run the precondition, but since the precondition is per
416 // breakpoint, only run it once per breakpoint.
417 std::pair<std::unordered_set<break_id_t>::iterator, bool> result =
418 precondition_breakpoints.insert(
419 bp_loc_sp->GetBreakpoint().GetID());
423 bool precondition_result =
424 bp_loc_sp->GetBreakpoint().EvaluatePrecondition(context);
425 if (!precondition_result)
428 // Next run the condition for the breakpoint. If that says we
429 // should stop, then we'll run the callback for the breakpoint. If
430 // the callback says we shouldn't stop that will win.
432 if (bp_loc_sp->GetConditionText() != nullptr) {
433 Status condition_error;
434 bool condition_says_stop =
435 bp_loc_sp->ConditionSaysStop(exe_ctx, condition_error);
437 if (!condition_error.Success()) {
438 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
439 StreamSP error_sp = debugger.GetAsyncErrorStream();
440 error_sp->Printf("Stopped due to an error evaluating condition "
442 bp_loc_sp->GetDescription(error_sp.get(),
443 eDescriptionLevelBrief);
444 error_sp->Printf(": \"%s\"", bp_loc_sp->GetConditionText());
446 const char *err_str =
447 condition_error.AsCString("<Unknown Error>");
449 log->Printf("Error evaluating condition: \"%s\"\n", err_str);
451 error_sp->PutCString(err_str);
456 log->Printf("Condition evaluated for breakpoint %s on thread "
457 "0x%llx conditon_says_stop: %i.",
459 static_cast<unsigned long long>(
461 condition_says_stop);
463 if (!condition_says_stop) {
464 // We don't want to increment the hit count of breakpoints if
465 // the condition fails. We've already bumped it by the time
466 // we get here, so undo the bump:
467 bp_loc_sp->UndoBumpHitCount();
473 // Check the auto-continue bit on the location, do this before the
474 // callback since it may change this, but that would be for the
475 // NEXT hit. Note, you might think you could check auto-continue
476 // before the condition, and not evaluate the condition if it says
477 // to continue. But failing the condition means the breakpoint was
478 // effectively NOT HIT. So these two states are different.
479 bool auto_continue_says_stop = true;
480 if (bp_loc_sp->IsAutoContinue())
483 log->Printf("Continuing breakpoint %s as AutoContinue was set.",
485 // We want this stop reported, so you will know we auto-continued
486 // but only for external breakpoints:
487 if (!internal_breakpoint)
488 thread_sp->SetShouldReportStop(eVoteYes);
489 auto_continue_says_stop = false;
492 bool callback_says_stop = true;
494 // FIXME: For now the callbacks have to run in async mode - the
495 // first time we restart we need
496 // to get out of there. So set it here.
497 // When we figure out how to nest breakpoint hits then this will
500 Debugger &debugger = thread_sp->CalculateTarget()->GetDebugger();
501 bool old_async = debugger.GetAsyncExecution();
502 debugger.SetAsyncExecution(true);
504 callback_says_stop = bp_loc_sp->InvokeCallback(&context);
506 debugger.SetAsyncExecution(old_async);
508 if (callback_says_stop && auto_continue_says_stop)
509 m_should_stop = true;
511 // If we are going to stop for this breakpoint, then remove the
513 if (callback_says_stop && bp_loc_sp &&
514 bp_loc_sp->GetBreakpoint().IsOneShot()) {
515 thread_sp->GetProcess()->GetTarget().RemoveBreakpointByID(
516 bp_loc_sp->GetBreakpoint().GetID());
518 // Also make sure that the callback hasn't continued the target. If
519 // it did, when we'll set m_should_start to false and get out of
521 if (HasTargetRunSinceMe()) {
522 m_should_stop = false;
527 // We've figured out what this stop wants to do, so mark it as valid so
528 // we don't compute it again.
529 m_should_stop_is_valid = true;
531 m_should_stop = true;
532 m_should_stop_is_valid = true;
534 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
538 "Process::%s could not find breakpoint site id: %" PRId64 "...",
539 __FUNCTION__, m_value);
542 if ((!m_should_stop || internal_breakpoint) &&
543 thread_sp->CompletedPlanOverridesBreakpoint()) {
545 // Override should_stop decision when we have completed step plan
546 // additionally to the breakpoint
547 m_should_stop = true;
549 // Here we clean the preset stop info so the next GetStopInfo call will
550 // find the appropriate stop info, which should be the stop info
551 // related to the completed plan
552 thread_sp->ResetStopInfo();
556 log->Printf("Process::%s returning from action with m_should_stop: %d.",
557 __FUNCTION__, m_should_stop);
563 bool m_should_stop_is_valid;
564 bool m_should_perform_action; // Since we are trying to preserve the "state"
565 // of the system even if we run functions
566 // etc. behind the users backs, we need to make sure we only REALLY perform
568 lldb::addr_t m_address; // We use this to capture the breakpoint site address
569 // when we create the StopInfo,
570 // in case somebody deletes it between the time the StopInfo is made and the
571 // description is asked for.
572 lldb::break_id_t m_break_id;
576 // StopInfoWatchpoint
578 class StopInfoWatchpoint : public StopInfo {
580 // Make sure watchpoint is properly disabled and subsequently enabled while
581 // performing watchpoint actions.
582 class WatchpointSentry {
584 WatchpointSentry(ProcessSP p_sp, WatchpointSP w_sp) : process_sp(p_sp),
585 watchpoint_sp(w_sp) {
586 if (process_sp && watchpoint_sp) {
587 const bool notify = false;
588 watchpoint_sp->TurnOnEphemeralMode();
589 process_sp->DisableWatchpoint(watchpoint_sp.get(), notify);
590 process_sp->AddPreResumeAction(SentryPreResumeAction, this);
595 if (process_sp && watchpoint_sp) {
596 bool was_disabled = watchpoint_sp->IsDisabledDuringEphemeralMode();
597 watchpoint_sp->TurnOffEphemeralMode();
598 const bool notify = false;
600 process_sp->DisableWatchpoint(watchpoint_sp.get(), notify);
602 process_sp->EnableWatchpoint(watchpoint_sp.get(), notify);
607 ~WatchpointSentry() {
610 process_sp->ClearPreResumeAction(SentryPreResumeAction, this);
613 static bool SentryPreResumeAction(void *sentry_void) {
614 WatchpointSentry *sentry = (WatchpointSentry *) sentry_void;
615 sentry->DoReenable();
620 ProcessSP process_sp;
621 WatchpointSP watchpoint_sp;
624 StopInfoWatchpoint(Thread &thread, break_id_t watch_id,
625 lldb::addr_t watch_hit_addr)
626 : StopInfo(thread, watch_id), m_should_stop(false),
627 m_should_stop_is_valid(false), m_watch_hit_addr(watch_hit_addr) {}
629 ~StopInfoWatchpoint() override = default;
631 StopReason GetStopReason() const override { return eStopReasonWatchpoint; }
633 const char *GetDescription() override {
634 if (m_description.empty()) {
636 strm.Printf("watchpoint %" PRIi64, m_value);
637 m_description = strm.GetString();
639 return m_description.c_str();
643 bool ShouldStopSynchronous(Event *event_ptr) override {
644 // ShouldStop() method is idempotent and should not affect hit count. See
645 // Process::RunPrivateStateThread()->Process()->HandlePrivateEvent()
646 // -->Process()::ShouldBroadcastEvent()->ThreadList::ShouldStop()->
647 // Thread::ShouldStop()->ThreadPlanBase::ShouldStop()->
648 // StopInfoWatchpoint::ShouldStop() and
649 // Event::DoOnRemoval()->Process::ProcessEventData::DoOnRemoval()->
650 // StopInfoWatchpoint::PerformAction().
651 if (m_should_stop_is_valid)
652 return m_should_stop;
654 ThreadSP thread_sp(m_thread_wp.lock());
657 thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
660 // Check if we should stop at a watchpoint.
661 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
662 StoppointCallbackContext context(event_ptr, exe_ctx, true);
663 m_should_stop = wp_sp->ShouldStop(&context);
665 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
669 "Process::%s could not find watchpoint location id: %" PRId64
671 __FUNCTION__, GetValue());
673 m_should_stop = true;
676 m_should_stop_is_valid = true;
677 return m_should_stop;
680 bool ShouldStop(Event *event_ptr) override {
681 // This just reports the work done by PerformAction or the synchronous
682 // stop. It should only ever get called after they have had a chance to
684 assert(m_should_stop_is_valid);
685 return m_should_stop;
688 void PerformAction(Event *event_ptr) override {
689 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS);
690 // We're going to calculate if we should stop or not in some way during the
691 // course of this code. Also by default we're going to stop, so set that
693 m_should_stop = true;
696 ThreadSP thread_sp(m_thread_wp.lock());
700 thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
703 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
704 ProcessSP process_sp = exe_ctx.GetProcessSP();
707 // check if this process is running on an architecture where
708 // watchpoints trigger before the associated instruction runs. if so,
709 // disable the WP, single-step and then re-enable the watchpoint
712 bool wp_triggers_after;
714 if (process_sp->GetWatchpointSupportInfo(num, wp_triggers_after)
716 if (!wp_triggers_after) {
717 // We need to preserve the watch_index before watchpoint is
718 // disable. Since Watchpoint::SetEnabled will clear the watch
719 // index. This will fix TestWatchpointIter failure
720 Watchpoint *wp = wp_sp.get();
721 uint32_t watch_index = wp->GetHardwareIndex();
722 process_sp->DisableWatchpoint(wp, false);
723 StopInfoSP stored_stop_info_sp = thread_sp->GetStopInfo();
724 assert(stored_stop_info_sp.get() == this);
726 Status new_plan_status;
727 ThreadPlanSP new_plan_sp(
728 thread_sp->QueueThreadPlanForStepSingleInstruction(
730 false, // abort_other_plans
731 true, // stop_other_threads
733 if (new_plan_sp && new_plan_status.Success()) {
734 new_plan_sp->SetIsMasterPlan(true);
735 new_plan_sp->SetOkayToDiscard(false);
736 new_plan_sp->SetPrivate(true);
738 process_sp->GetThreadList().SetSelectedThreadByID(
740 process_sp->ResumeSynchronous(nullptr);
741 process_sp->GetThreadList().SetSelectedThreadByID(
743 thread_sp->SetStopInfo(stored_stop_info_sp);
744 process_sp->EnableWatchpoint(wp, false);
745 wp->SetHardwareIndex(watch_index);
751 // This sentry object makes sure the current watchpoint is disabled
752 // while performing watchpoint actions, and it is then enabled after we
754 WatchpointSentry sentry(process_sp, wp_sp);
757 * MIPS: Last 3bits of the watchpoint address are masked by the kernel.
759 * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is
761 * watch exception is generated even when 'n' is read/written. To handle
763 * server emulates the instruction at PC and finds the base address of
765 * instruction and appends it in the description of the stop-info
766 * packet. If watchpoint
767 * is not set on this address by user then this do not stop.
769 if (m_watch_hit_addr != LLDB_INVALID_ADDRESS) {
770 WatchpointSP wp_hit_sp =
771 thread_sp->CalculateTarget()->GetWatchpointList().FindByAddress(
774 m_should_stop = false;
775 wp_sp->IncrementFalseAlarmsAndReviseHitCount();
779 // TODO: This condition should be checked in the synchronous part of the
781 // (Watchpoint::ShouldStop), so that we avoid pulling an event even if
782 // the watchpoint fails the ignore count condition. It is moved here
783 // temporarily, because for archs with
784 // watchpoint_exceptions_received=before, the code in the previous
785 // lines takes care of moving the inferior to next PC. We have to check
786 // the ignore count condition after this is done, otherwise we will hit
787 // same watchpoint multiple times until we pass ignore condition, but
788 // we won't actually be ignoring them.
789 if (wp_sp->GetHitCount() <= wp_sp->GetIgnoreCount())
790 m_should_stop = false;
792 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
794 if (m_should_stop && wp_sp->GetConditionText() != nullptr) {
795 // We need to make sure the user sees any parse errors in their
796 // condition, so we'll hook the constructor errors up to the
797 // debugger's Async I/O.
798 ExpressionResults result_code;
799 EvaluateExpressionOptions expr_options;
800 expr_options.SetUnwindOnError(true);
801 expr_options.SetIgnoreBreakpoints(true);
802 ValueObjectSP result_value_sp;
804 result_code = UserExpression::Evaluate(
805 exe_ctx, expr_options, wp_sp->GetConditionText(),
806 llvm::StringRef(), result_value_sp, error);
808 if (result_code == eExpressionCompleted) {
809 if (result_value_sp) {
811 if (result_value_sp->ResolveValue(scalar_value)) {
812 if (scalar_value.ULongLong(1) == 0) {
813 // We have been vetoed. This takes precedence over querying
814 // the watchpoint whether it should stop (aka ignore count
815 // and friends). See also StopInfoWatchpoint::ShouldStop()
816 // as well as Process::ProcessEventData::DoOnRemoval().
817 m_should_stop = false;
819 m_should_stop = true;
822 "Condition successfully evaluated, result is %s.\n",
823 m_should_stop ? "true" : "false");
825 m_should_stop = true;
828 "Failed to get an integer result from the expression.");
832 StreamSP error_sp = debugger.GetAsyncErrorStream();
834 "Stopped due to an error evaluating condition of watchpoint ");
835 wp_sp->GetDescription(error_sp.get(), eDescriptionLevelBrief);
836 error_sp->Printf(": \"%s\"", wp_sp->GetConditionText());
838 const char *err_str = error.AsCString("<Unknown Error>");
840 log->Printf("Error evaluating condition: \"%s\"\n", err_str);
842 error_sp->PutCString(err_str);
845 // If the condition fails to be parsed or run, we should stop.
846 m_should_stop = true;
850 // If the condition says to stop, we run the callback to further decide
853 // FIXME: For now the callbacks have to run in async mode - the
854 // first time we restart we need
855 // to get out of there. So set it here.
856 // When we figure out how to nest watchpoint hits then this will
859 bool old_async = debugger.GetAsyncExecution();
860 debugger.SetAsyncExecution(true);
862 StoppointCallbackContext context(event_ptr, exe_ctx, false);
863 bool stop_requested = wp_sp->InvokeCallback(&context);
865 debugger.SetAsyncExecution(old_async);
867 // Also make sure that the callback hasn't continued the target. If
868 // it did, when we'll set m_should_stop to false and get out of here.
869 if (HasTargetRunSinceMe())
870 m_should_stop = false;
872 if (m_should_stop && !stop_requested) {
873 // We have been vetoed by the callback mechanism.
874 m_should_stop = false;
877 // Finally, if we are going to stop, print out the new & old values:
879 wp_sp->CaptureWatchedValue(exe_ctx);
881 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
882 StreamSP output_sp = debugger.GetAsyncOutputStream();
883 wp_sp->DumpSnapshots(output_sp.get());
890 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
894 "Process::%s could not find watchpoint id: %" PRId64 "...",
895 __FUNCTION__, m_value);
898 log->Printf("Process::%s returning from action with m_should_stop: %d.",
899 __FUNCTION__, m_should_stop);
901 m_should_stop_is_valid = true;
907 bool m_should_stop_is_valid;
908 lldb::addr_t m_watch_hit_addr;
911 // StopInfoUnixSignal
913 class StopInfoUnixSignal : public StopInfo {
915 StopInfoUnixSignal(Thread &thread, int signo, const char *description)
916 : StopInfo(thread, signo) {
917 SetDescription(description);
920 ~StopInfoUnixSignal() override = default;
922 StopReason GetStopReason() const override { return eStopReasonSignal; }
924 bool ShouldStopSynchronous(Event *event_ptr) override {
925 ThreadSP thread_sp(m_thread_wp.lock());
927 return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
931 bool ShouldStop(Event *event_ptr) override {
932 ThreadSP thread_sp(m_thread_wp.lock());
934 return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
938 // If should stop returns false, check if we should notify of this event
939 bool DoShouldNotify(Event *event_ptr) override {
940 ThreadSP thread_sp(m_thread_wp.lock());
943 thread_sp->GetProcess()->GetUnixSignals()->GetShouldNotify(m_value);
947 "thread %d received signal: %s", thread_sp->GetIndexID(),
948 thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString(
950 Process::ProcessEventData::AddRestartedReason(event_ptr,
953 return should_notify;
958 void WillResume(lldb::StateType resume_state) override {
959 ThreadSP thread_sp(m_thread_wp.lock());
961 if (!thread_sp->GetProcess()->GetUnixSignals()->GetShouldSuppress(
963 thread_sp->SetResumeSignal(m_value);
967 const char *GetDescription() override {
968 if (m_description.empty()) {
969 ThreadSP thread_sp(m_thread_wp.lock());
972 const char *signal_name =
973 thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString(
976 strm.Printf("signal %s", signal_name);
978 strm.Printf("signal %" PRIi64, m_value);
979 m_description = strm.GetString();
982 return m_description.c_str();
988 class StopInfoTrace : public StopInfo {
990 StopInfoTrace(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {}
992 ~StopInfoTrace() override = default;
994 StopReason GetStopReason() const override { return eStopReasonTrace; }
996 const char *GetDescription() override {
997 if (m_description.empty())
1000 return m_description.c_str();
1004 // StopInfoException
1006 class StopInfoException : public StopInfo {
1008 StopInfoException(Thread &thread, const char *description)
1009 : StopInfo(thread, LLDB_INVALID_UID) {
1011 SetDescription(description);
1014 ~StopInfoException() override = default;
1016 StopReason GetStopReason() const override { return eStopReasonException; }
1018 const char *GetDescription() override {
1019 if (m_description.empty())
1022 return m_description.c_str();
1026 // StopInfoThreadPlan
1028 class StopInfoThreadPlan : public StopInfo {
1030 StopInfoThreadPlan(ThreadPlanSP &plan_sp, ValueObjectSP &return_valobj_sp,
1031 ExpressionVariableSP &expression_variable_sp)
1032 : StopInfo(plan_sp->GetThread(), LLDB_INVALID_UID), m_plan_sp(plan_sp),
1033 m_return_valobj_sp(return_valobj_sp),
1034 m_expression_variable_sp(expression_variable_sp) {}
1036 ~StopInfoThreadPlan() override = default;
1038 StopReason GetStopReason() const override { return eStopReasonPlanComplete; }
1040 const char *GetDescription() override {
1041 if (m_description.empty()) {
1043 m_plan_sp->GetDescription(&strm, eDescriptionLevelBrief);
1044 m_description = strm.GetString();
1046 return m_description.c_str();
1049 ValueObjectSP GetReturnValueObject() { return m_return_valobj_sp; }
1051 ExpressionVariableSP GetExpressionVariable() {
1052 return m_expression_variable_sp;
1056 bool ShouldStop(Event *event_ptr) override {
1058 return m_plan_sp->ShouldStop(event_ptr);
1060 return StopInfo::ShouldStop(event_ptr);
1064 ThreadPlanSP m_plan_sp;
1065 ValueObjectSP m_return_valobj_sp;
1066 ExpressionVariableSP m_expression_variable_sp;
1071 class StopInfoExec : public StopInfo {
1073 StopInfoExec(Thread &thread)
1074 : StopInfo(thread, LLDB_INVALID_UID), m_performed_action(false) {}
1076 ~StopInfoExec() override = default;
1078 bool ShouldStop(Event *event_ptr) override {
1079 ThreadSP thread_sp(m_thread_wp.lock());
1081 return thread_sp->GetProcess()->GetStopOnExec();
1085 StopReason GetStopReason() const override { return eStopReasonExec; }
1087 const char *GetDescription() override { return "exec"; }
1090 void PerformAction(Event *event_ptr) override {
1091 // Only perform the action once
1092 if (m_performed_action)
1094 m_performed_action = true;
1095 ThreadSP thread_sp(m_thread_wp.lock());
1097 thread_sp->GetProcess()->DidExec();
1100 bool m_performed_action;
1103 } // namespace lldb_private
1105 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
1106 break_id_t break_id) {
1107 return StopInfoSP(new StopInfoBreakpoint(thread, break_id));
1110 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
1111 break_id_t break_id,
1113 return StopInfoSP(new StopInfoBreakpoint(thread, break_id, should_stop));
1117 StopInfo::CreateStopReasonWithWatchpointID(Thread &thread, break_id_t watch_id,
1118 lldb::addr_t watch_hit_addr) {
1119 return StopInfoSP(new StopInfoWatchpoint(thread, watch_id, watch_hit_addr));
1122 StopInfoSP StopInfo::CreateStopReasonWithSignal(Thread &thread, int signo,
1123 const char *description) {
1124 return StopInfoSP(new StopInfoUnixSignal(thread, signo, description));
1127 StopInfoSP StopInfo::CreateStopReasonToTrace(Thread &thread) {
1128 return StopInfoSP(new StopInfoTrace(thread));
1131 StopInfoSP StopInfo::CreateStopReasonWithPlan(
1132 ThreadPlanSP &plan_sp, ValueObjectSP return_valobj_sp,
1133 ExpressionVariableSP expression_variable_sp) {
1134 return StopInfoSP(new StopInfoThreadPlan(plan_sp, return_valobj_sp,
1135 expression_variable_sp));
1138 StopInfoSP StopInfo::CreateStopReasonWithException(Thread &thread,
1139 const char *description) {
1140 return StopInfoSP(new StopInfoException(thread, description));
1143 StopInfoSP StopInfo::CreateStopReasonWithExec(Thread &thread) {
1144 return StopInfoSP(new StopInfoExec(thread));
1147 ValueObjectSP StopInfo::GetReturnValueObject(StopInfoSP &stop_info_sp) {
1149 stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
1150 StopInfoThreadPlan *plan_stop_info =
1151 static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1152 return plan_stop_info->GetReturnValueObject();
1154 return ValueObjectSP();
1157 ExpressionVariableSP StopInfo::GetExpressionVariable(StopInfoSP &stop_info_sp) {
1159 stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
1160 StopInfoThreadPlan *plan_stop_info =
1161 static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1162 return plan_stop_info->GetExpressionVariable();
1164 return ExpressionVariableSP();
1168 StopInfo::GetCrashingDereference(StopInfoSP &stop_info_sp,
1169 lldb::addr_t *crashing_address) {
1170 if (!stop_info_sp) {
1171 return ValueObjectSP();
1174 const char *description = stop_info_sp->GetDescription();
1176 return ValueObjectSP();
1179 ThreadSP thread_sp = stop_info_sp->GetThread();
1181 return ValueObjectSP();
1184 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
1187 return ValueObjectSP();
1190 const char address_string[] = "address=";
1192 const char *address_loc = strstr(description, address_string);
1194 return ValueObjectSP();
1197 address_loc += (sizeof(address_string) - 1);
1199 uint64_t address = strtoull(address_loc, nullptr, 0);
1200 if (crashing_address) {
1201 *crashing_address = address;
1204 return frame_sp->GuessValueForAddress(address);