1 //===-- StopInfo.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 // Other libraries and framework includes
16 #include "lldb/Breakpoint/Breakpoint.h"
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 #include "lldb/Breakpoint/StoppointCallbackContext.h"
19 #include "lldb/Breakpoint/Watchpoint.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/ValueObject.h"
22 #include "lldb/Expression/UserExpression.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/StopInfo.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlan.h"
28 #include "lldb/Target/UnixSignals.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/StreamString.h"
33 using namespace lldb_private;
35 StopInfo::StopInfo(Thread &thread, uint64_t value)
36 : m_thread_wp(thread.shared_from_this()),
37 m_stop_id(thread.GetProcess()->GetStopID()),
38 m_resume_id(thread.GetProcess()->GetResumeID()), m_value(value),
39 m_description(), m_override_should_notify(eLazyBoolCalculate),
40 m_override_should_stop(eLazyBoolCalculate), m_extended_info() {}
42 bool StopInfo::IsValid() const {
43 ThreadSP thread_sp(m_thread_wp.lock());
45 return thread_sp->GetProcess()->GetStopID() == m_stop_id;
49 void StopInfo::MakeStopInfoValid() {
50 ThreadSP thread_sp(m_thread_wp.lock());
52 m_stop_id = thread_sp->GetProcess()->GetStopID();
53 m_resume_id = thread_sp->GetProcess()->GetResumeID();
57 bool StopInfo::HasTargetRunSinceMe() {
58 ThreadSP thread_sp(m_thread_wp.lock());
61 lldb::StateType ret_type = thread_sp->GetProcess()->GetPrivateState();
62 if (ret_type == eStateRunning) {
64 } else if (ret_type == eStateStopped) {
65 // This is a little tricky. We want to count "run and stopped again
66 // before you could ask this question as a "TRUE" answer to
67 // HasTargetRunSinceMe. But we don't want to include any running of the
68 // target done for expressions. So we track both resumes, and resumes
69 // caused by expressions, and check if there are any resumes
73 uint32_t curr_resume_id = thread_sp->GetProcess()->GetResumeID();
74 uint32_t last_user_expression_id =
75 thread_sp->GetProcess()->GetLastUserExpressionResumeID();
76 if (curr_resume_id == m_resume_id) {
78 } else if (curr_resume_id > last_user_expression_id) {
86 //----------------------------------------------------------------------
88 //----------------------------------------------------------------------
90 namespace lldb_private {
91 class StopInfoBreakpoint : public StopInfo {
93 StopInfoBreakpoint(Thread &thread, break_id_t break_id)
94 : StopInfo(thread, break_id), m_should_stop(false),
95 m_should_stop_is_valid(false), m_should_perform_action(true),
96 m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
97 m_was_one_shot(false) {
101 StopInfoBreakpoint(Thread &thread, break_id_t break_id, bool should_stop)
102 : StopInfo(thread, break_id), m_should_stop(should_stop),
103 m_should_stop_is_valid(true), m_should_perform_action(true),
104 m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
105 m_was_one_shot(false) {
109 ~StopInfoBreakpoint() override = default;
112 ThreadSP thread_sp(m_thread_wp.lock());
114 BreakpointSiteSP bp_site_sp(
115 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
117 if (bp_site_sp->GetNumberOfOwners() == 1) {
118 BreakpointLocationSP bp_loc_sp = bp_site_sp->GetOwnerAtIndex(0);
120 m_break_id = bp_loc_sp->GetBreakpoint().GetID();
121 m_was_one_shot = bp_loc_sp->GetBreakpoint().IsOneShot();
124 m_address = bp_site_sp->GetLoadAddress();
129 bool IsValidForOperatingSystemThread(Thread &thread) override {
130 ProcessSP process_sp(thread.GetProcess());
132 BreakpointSiteSP bp_site_sp(
133 process_sp->GetBreakpointSiteList().FindByID(m_value));
135 return bp_site_sp->ValidForThisThread(&thread);
140 StopReason GetStopReason() const override { return eStopReasonBreakpoint; }
142 bool ShouldStopSynchronous(Event *event_ptr) override {
143 ThreadSP thread_sp(m_thread_wp.lock());
145 if (!m_should_stop_is_valid) {
146 // Only check once if we should stop at a breakpoint
147 BreakpointSiteSP bp_site_sp(
148 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
150 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
151 StoppointCallbackContext context(event_ptr, exe_ctx, true);
152 bp_site_sp->BumpHitCounts();
153 m_should_stop = bp_site_sp->ShouldStop(&context);
155 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
159 "Process::%s could not find breakpoint site id: %" PRId64 "...",
160 __FUNCTION__, m_value);
162 m_should_stop = true;
164 m_should_stop_is_valid = true;
166 return m_should_stop;
171 bool DoShouldNotify(Event *event_ptr) override {
172 ThreadSP thread_sp(m_thread_wp.lock());
174 BreakpointSiteSP bp_site_sp(
175 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
177 bool all_internal = true;
179 for (uint32_t i = 0; i < bp_site_sp->GetNumberOfOwners(); i++) {
180 if (!bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint().IsInternal()) {
181 all_internal = false;
185 return !all_internal;
191 const char *GetDescription() override {
192 if (m_description.empty()) {
193 ThreadSP thread_sp(m_thread_wp.lock());
195 BreakpointSiteSP bp_site_sp(
196 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
199 // If we have just hit an internal breakpoint, and it has a kind
200 // description, print that instead of the full breakpoint printing:
201 if (bp_site_sp->IsInternal()) {
202 size_t num_owners = bp_site_sp->GetNumberOfOwners();
203 for (size_t idx = 0; idx < num_owners; idx++) {
204 const char *kind = bp_site_sp->GetOwnerAtIndex(idx)
206 .GetBreakpointKind();
207 if (kind != nullptr) {
208 m_description.assign(kind);
214 strm.Printf("breakpoint ");
215 bp_site_sp->GetDescription(&strm, eDescriptionLevelBrief);
216 m_description = strm.GetString();
219 if (m_break_id != LLDB_INVALID_BREAK_ID) {
220 BreakpointSP break_sp =
221 thread_sp->GetProcess()->GetTarget().GetBreakpointByID(
224 if (break_sp->IsInternal()) {
225 const char *kind = break_sp->GetBreakpointKind();
227 strm.Printf("internal %s breakpoint(%d).", kind, m_break_id);
229 strm.Printf("internal breakpoint(%d).", m_break_id);
231 strm.Printf("breakpoint %d.", m_break_id);
235 strm.Printf("one-shot breakpoint %d", m_break_id);
237 strm.Printf("breakpoint %d which has been deleted.",
240 } else if (m_address == LLDB_INVALID_ADDRESS)
241 strm.Printf("breakpoint site %" PRIi64
242 " which has been deleted - unknown address",
245 strm.Printf("breakpoint site %" PRIi64
246 " which has been deleted - was at 0x%" PRIx64,
249 m_description = strm.GetString();
253 return m_description.c_str();
257 bool ShouldStop(Event *event_ptr) override {
258 // This just reports the work done by PerformAction or the synchronous
259 // stop. It should only ever get called after they have had a chance to
261 assert(m_should_stop_is_valid);
262 return m_should_stop;
265 void PerformAction(Event *event_ptr) override {
266 if (!m_should_perform_action)
268 m_should_perform_action = false;
269 bool internal_breakpoint = true;
271 ThreadSP thread_sp(m_thread_wp.lock());
274 Log *log = lldb_private::GetLogIfAnyCategoriesSet(
275 LIBLLDB_LOG_BREAKPOINTS | LIBLLDB_LOG_STEP);
277 if (!thread_sp->IsValid()) {
278 // This shouldn't ever happen, but just in case, don't do more harm.
280 log->Printf("PerformAction got called with an invalid thread.");
282 m_should_stop = true;
283 m_should_stop_is_valid = true;
287 BreakpointSiteSP bp_site_sp(
288 thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
289 std::unordered_set<break_id_t> precondition_breakpoints;
292 // Let's copy the owners list out of the site and store them in a local
293 // list. That way if one of the breakpoint actions changes the site,
294 // then we won't be operating on a bad list.
295 BreakpointLocationCollection site_locations;
296 size_t num_owners = bp_site_sp->CopyOwnersList(site_locations);
298 if (num_owners == 0) {
299 m_should_stop = true;
301 // We go through each location, and test first its precondition -
302 // this overrides everything. Note, we only do this once per
303 // breakpoint - not once per location... Then check the condition.
304 // If the condition says to stop, then we run the callback for that
305 // location. If that callback says to stop as well, then we set
306 // m_should_stop to true; we are going to stop. But we still want to
307 // give all the breakpoints whose conditions say we are going to stop
308 // a chance to run their callbacks. Of course if any callback
309 // restarts the target by putting "continue" in the callback, then
310 // we're going to restart, without running the rest of the callbacks.
311 // And in this case we will end up not stopping even if another
312 // location said we should stop. But that's better than not running
313 // all the callbacks.
315 m_should_stop = false;
317 // We don't select threads as we go through them testing breakpoint
318 // conditions and running commands. So we need to set the thread for
319 // expression evaluation here:
320 ThreadList::ExpressionExecutionThreadPusher thread_pusher(thread_sp);
322 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
323 Process *process = exe_ctx.GetProcessPtr();
324 if (process->GetModIDRef().IsLastResumeForUserExpression()) {
325 // If we are in the middle of evaluating an expression, don't run
326 // asynchronous breakpoint commands or expressions. That could
327 // lead to infinite recursion if the command or condition re-calls
328 // the function with this breakpoint.
329 // TODO: We can keep a list of the breakpoints we've seen while
330 // running expressions in the nested
331 // PerformAction calls that can arise when the action runs a
332 // function that hits another breakpoint, and only stop running
333 // commands when we see the same breakpoint hit a second time.
335 m_should_stop_is_valid = true;
337 log->Printf("StopInfoBreakpoint::PerformAction - Hit a "
338 "breakpoint while running an expression,"
339 " not running commands to avoid recursion.");
340 bool ignoring_breakpoints =
341 process->GetIgnoreBreakpointsInExpressions();
342 if (ignoring_breakpoints) {
343 m_should_stop = false;
344 // Internal breakpoints will always stop.
345 for (size_t j = 0; j < num_owners; j++) {
346 lldb::BreakpointLocationSP bp_loc_sp =
347 bp_site_sp->GetOwnerAtIndex(j);
348 if (bp_loc_sp->GetBreakpoint().IsInternal()) {
349 m_should_stop = true;
354 m_should_stop = true;
357 log->Printf("StopInfoBreakpoint::PerformAction - in expression, "
359 m_should_stop ? "true" : "false");
360 process->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
361 "Warning: hit breakpoint while "
362 "running function, skipping commands and conditions to prevent "
367 StoppointCallbackContext context(event_ptr, exe_ctx, false);
369 // For safety's sake let's also grab an extra reference to the
370 // breakpoint owners of the locations we're going to examine, since
371 // the locations are going to have to get back to their breakpoints,
372 // and the locations don't keep their owners alive. I'm just
373 // sticking the BreakpointSP's in a vector since I'm only using it to
374 // locally increment their retain counts.
376 std::vector<lldb::BreakpointSP> location_owners;
378 for (size_t j = 0; j < num_owners; j++) {
379 BreakpointLocationSP loc(site_locations.GetByIndex(j));
380 location_owners.push_back(loc->GetBreakpoint().shared_from_this());
383 for (size_t j = 0; j < num_owners; j++) {
384 lldb::BreakpointLocationSP bp_loc_sp = site_locations.GetByIndex(j);
385 StreamString loc_desc;
387 bp_loc_sp->GetDescription(&loc_desc, eDescriptionLevelBrief);
389 // If another action disabled this breakpoint or its location, then
390 // don't run the actions.
391 if (!bp_loc_sp->IsEnabled() ||
392 !bp_loc_sp->GetBreakpoint().IsEnabled())
395 // The breakpoint site may have many locations associated with it,
396 // not all of them valid for this thread. Skip the ones that
398 if (!bp_loc_sp->ValidForThisThread(thread_sp.get())) {
400 log->Printf("Breakpoint %s hit on thread 0x%llx but it was not "
401 "for this thread, continuing.",
402 loc_desc.GetData(), static_cast<unsigned long long>(
403 thread_sp->GetID()));
408 internal_breakpoint = bp_loc_sp->GetBreakpoint().IsInternal();
410 // First run the precondition, but since the precondition is per
411 // breakpoint, only run it once per breakpoint.
412 std::pair<std::unordered_set<break_id_t>::iterator, bool> result =
413 precondition_breakpoints.insert(
414 bp_loc_sp->GetBreakpoint().GetID());
418 bool precondition_result =
419 bp_loc_sp->GetBreakpoint().EvaluatePrecondition(context);
420 if (!precondition_result)
423 // Next run the condition for the breakpoint. If that says we
424 // should stop, then we'll run the callback for the breakpoint. If
425 // the callback says we shouldn't stop that will win.
427 if (bp_loc_sp->GetConditionText() != nullptr) {
428 Status condition_error;
429 bool condition_says_stop =
430 bp_loc_sp->ConditionSaysStop(exe_ctx, condition_error);
432 if (!condition_error.Success()) {
433 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
434 StreamSP error_sp = debugger.GetAsyncErrorStream();
435 error_sp->Printf("Stopped due to an error evaluating condition "
437 bp_loc_sp->GetDescription(error_sp.get(),
438 eDescriptionLevelBrief);
439 error_sp->Printf(": \"%s\"", bp_loc_sp->GetConditionText());
441 const char *err_str =
442 condition_error.AsCString("<Unknown Error>");
444 log->Printf("Error evaluating condition: \"%s\"\n", err_str);
446 error_sp->PutCString(err_str);
451 log->Printf("Condition evaluated for breakpoint %s on thread "
452 "0x%llx conditon_says_stop: %i.",
454 static_cast<unsigned long long>(
456 condition_says_stop);
458 if (!condition_says_stop) {
459 // We don't want to increment the hit count of breakpoints if
460 // the condition fails. We've already bumped it by the time
461 // we get here, so undo the bump:
462 bp_loc_sp->UndoBumpHitCount();
468 // Check the auto-continue bit on the location, do this before the
469 // callback since it may change this, but that would be for the
470 // NEXT hit. Note, you might think you could check auto-continue
471 // before the condition, and not evaluate the condition if it says
472 // to continue. But failing the condition means the breakpoint was
473 // effectively NOT HIT. So these two states are different.
474 bool auto_continue_says_stop = true;
475 if (bp_loc_sp->IsAutoContinue())
478 log->Printf("Continuing breakpoint %s as AutoContinue was set.",
480 // We want this stop reported, so you will know we auto-continued
481 // but only for external breakpoints:
482 if (!internal_breakpoint)
483 thread_sp->SetShouldReportStop(eVoteYes);
484 auto_continue_says_stop = false;
487 bool callback_says_stop = true;
489 // FIXME: For now the callbacks have to run in async mode - the
490 // first time we restart we need
491 // to get out of there. So set it here.
492 // When we figure out how to nest breakpoint hits then this will
495 Debugger &debugger = thread_sp->CalculateTarget()->GetDebugger();
496 bool old_async = debugger.GetAsyncExecution();
497 debugger.SetAsyncExecution(true);
499 callback_says_stop = bp_loc_sp->InvokeCallback(&context);
501 debugger.SetAsyncExecution(old_async);
503 if (callback_says_stop && auto_continue_says_stop)
504 m_should_stop = true;
506 // If we are going to stop for this breakpoint, then remove the
508 if (callback_says_stop && bp_loc_sp &&
509 bp_loc_sp->GetBreakpoint().IsOneShot()) {
510 thread_sp->GetProcess()->GetTarget().RemoveBreakpointByID(
511 bp_loc_sp->GetBreakpoint().GetID());
513 // Also make sure that the callback hasn't continued the target. If
514 // it did, when we'll set m_should_start to false and get out of
516 if (HasTargetRunSinceMe()) {
517 m_should_stop = false;
522 // We've figured out what this stop wants to do, so mark it as valid so
523 // we don't compute it again.
524 m_should_stop_is_valid = true;
526 m_should_stop = true;
527 m_should_stop_is_valid = true;
529 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
533 "Process::%s could not find breakpoint site id: %" PRId64 "...",
534 __FUNCTION__, m_value);
537 if ((m_should_stop == false || internal_breakpoint)
538 && thread_sp->CompletedPlanOverridesBreakpoint()) {
540 // Override should_stop decision when we have completed step plan
541 // additionally to the breakpoint
542 m_should_stop = true;
544 // Here we clean the preset stop info so the next GetStopInfo call will
545 // find the appropriate stop info, which should be the stop info
546 // related to the completed plan
547 thread_sp->ResetStopInfo();
551 log->Printf("Process::%s returning from action with m_should_stop: %d.",
552 __FUNCTION__, m_should_stop);
558 bool m_should_stop_is_valid;
559 bool m_should_perform_action; // Since we are trying to preserve the "state"
560 // of the system even if we run functions
561 // etc. behind the users backs, we need to make sure we only REALLY perform
563 lldb::addr_t m_address; // We use this to capture the breakpoint site address
564 // when we create the StopInfo,
565 // in case somebody deletes it between the time the StopInfo is made and the
566 // description is asked for.
567 lldb::break_id_t m_break_id;
571 //----------------------------------------------------------------------
572 // StopInfoWatchpoint
573 //----------------------------------------------------------------------
575 class StopInfoWatchpoint : public StopInfo {
577 // Make sure watchpoint is properly disabled and subsequently enabled while
578 // performing watchpoint actions.
579 class WatchpointSentry {
581 WatchpointSentry(ProcessSP p_sp, WatchpointSP w_sp) : process_sp(p_sp),
582 watchpoint_sp(w_sp) {
583 if (process_sp && watchpoint_sp) {
584 const bool notify = false;
585 watchpoint_sp->TurnOnEphemeralMode();
586 process_sp->DisableWatchpoint(watchpoint_sp.get(), notify);
587 process_sp->AddPreResumeAction(SentryPreResumeAction, this);
592 if (process_sp && watchpoint_sp) {
593 bool was_disabled = watchpoint_sp->IsDisabledDuringEphemeralMode();
594 watchpoint_sp->TurnOffEphemeralMode();
595 const bool notify = false;
597 process_sp->DisableWatchpoint(watchpoint_sp.get(), notify);
599 process_sp->EnableWatchpoint(watchpoint_sp.get(), notify);
604 ~WatchpointSentry() {
607 process_sp->ClearPreResumeAction(SentryPreResumeAction, this);
610 static bool SentryPreResumeAction(void *sentry_void) {
611 WatchpointSentry *sentry = (WatchpointSentry *) sentry_void;
612 sentry->DoReenable();
617 ProcessSP process_sp;
618 WatchpointSP watchpoint_sp;
621 StopInfoWatchpoint(Thread &thread, break_id_t watch_id,
622 lldb::addr_t watch_hit_addr)
623 : StopInfo(thread, watch_id), m_should_stop(false),
624 m_should_stop_is_valid(false), m_watch_hit_addr(watch_hit_addr) {}
626 ~StopInfoWatchpoint() override = default;
628 StopReason GetStopReason() const override { return eStopReasonWatchpoint; }
630 const char *GetDescription() override {
631 if (m_description.empty()) {
633 strm.Printf("watchpoint %" PRIi64, m_value);
634 m_description = strm.GetString();
636 return m_description.c_str();
640 bool ShouldStopSynchronous(Event *event_ptr) override {
641 // ShouldStop() method is idempotent and should not affect hit count. See
642 // Process::RunPrivateStateThread()->Process()->HandlePrivateEvent()
643 // -->Process()::ShouldBroadcastEvent()->ThreadList::ShouldStop()->
644 // Thread::ShouldStop()->ThreadPlanBase::ShouldStop()->
645 // StopInfoWatchpoint::ShouldStop() and
646 // Event::DoOnRemoval()->Process::ProcessEventData::DoOnRemoval()->
647 // StopInfoWatchpoint::PerformAction().
648 if (m_should_stop_is_valid)
649 return m_should_stop;
651 ThreadSP thread_sp(m_thread_wp.lock());
654 thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
657 // Check if we should stop at a watchpoint.
658 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
659 StoppointCallbackContext context(event_ptr, exe_ctx, true);
660 m_should_stop = wp_sp->ShouldStop(&context);
662 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
666 "Process::%s could not find watchpoint location id: %" PRId64
668 __FUNCTION__, GetValue());
670 m_should_stop = true;
673 m_should_stop_is_valid = true;
674 return m_should_stop;
677 bool ShouldStop(Event *event_ptr) override {
678 // This just reports the work done by PerformAction or the synchronous
679 // stop. It should only ever get called after they have had a chance to
681 assert(m_should_stop_is_valid);
682 return m_should_stop;
685 void PerformAction(Event *event_ptr) override {
686 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS);
687 // We're going to calculate if we should stop or not in some way during the
688 // course of this code. Also by default we're going to stop, so set that
690 m_should_stop = true;
693 ThreadSP thread_sp(m_thread_wp.lock());
697 thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
700 ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
701 ProcessSP process_sp = exe_ctx.GetProcessSP();
704 // check if this process is running on an architecture where
705 // watchpoints trigger before the associated instruction runs. if so,
706 // disable the WP, single-step and then re-enable the watchpoint
709 bool wp_triggers_after;
711 if (process_sp->GetWatchpointSupportInfo(num, wp_triggers_after)
713 if (!wp_triggers_after) {
714 // We need to preserve the watch_index before watchpoint is
715 // disable. Since Watchpoint::SetEnabled will clear the watch
716 // index. This will fix TestWatchpointIter failure
717 Watchpoint *wp = wp_sp.get();
718 uint32_t watch_index = wp->GetHardwareIndex();
719 process_sp->DisableWatchpoint(wp, false);
720 StopInfoSP stored_stop_info_sp = thread_sp->GetStopInfo();
721 assert(stored_stop_info_sp.get() == this);
723 ThreadPlanSP new_plan_sp(
724 thread_sp->QueueThreadPlanForStepSingleInstruction(
726 false, // abort_other_plans
727 true)); // stop_other_threads
728 new_plan_sp->SetIsMasterPlan(true);
729 new_plan_sp->SetOkayToDiscard(false);
730 new_plan_sp->SetPrivate(true);
731 process_sp->GetThreadList().SetSelectedThreadByID(
733 process_sp->ResumeSynchronous(nullptr);
734 process_sp->GetThreadList().SetSelectedThreadByID(
736 thread_sp->SetStopInfo(stored_stop_info_sp);
737 process_sp->EnableWatchpoint(wp, false);
738 wp->SetHardwareIndex(watch_index);
744 // This sentry object makes sure the current watchpoint is disabled
745 // while performing watchpoint actions, and it is then enabled after we
747 WatchpointSentry sentry(process_sp, wp_sp);
750 * MIPS: Last 3bits of the watchpoint address are masked by the kernel.
752 * 'n' is at 0x120010d00 and 'm' is 0x120010d04. When a watchpoint is
754 * watch exception is generated even when 'n' is read/written. To handle
756 * server emulates the instruction at PC and finds the base address of
758 * instruction and appends it in the description of the stop-info
759 * packet. If watchpoint
760 * is not set on this address by user then this do not stop.
762 if (m_watch_hit_addr != LLDB_INVALID_ADDRESS) {
763 WatchpointSP wp_hit_sp =
764 thread_sp->CalculateTarget()->GetWatchpointList().FindByAddress(
767 m_should_stop = false;
768 wp_sp->IncrementFalseAlarmsAndReviseHitCount();
772 // TODO: This condition should be checked in the synchronous part of the
774 // (Watchpoint::ShouldStop), so that we avoid pulling an event even if
775 // the watchpoint fails the ignore count condition. It is moved here
776 // temporarily, because for archs with
777 // watchpoint_exceptions_received=before, the code in the previous
778 // lines takes care of moving the inferior to next PC. We have to check
779 // the ignore count condition after this is done, otherwise we will hit
780 // same watchpoint multiple times until we pass ignore condition, but
781 // we won't actually be ignoring them.
782 if (wp_sp->GetHitCount() <= wp_sp->GetIgnoreCount())
783 m_should_stop = false;
785 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
787 if (m_should_stop && wp_sp->GetConditionText() != nullptr) {
788 // We need to make sure the user sees any parse errors in their
789 // condition, so we'll hook the constructor errors up to the
790 // debugger's Async I/O.
791 ExpressionResults result_code;
792 EvaluateExpressionOptions expr_options;
793 expr_options.SetUnwindOnError(true);
794 expr_options.SetIgnoreBreakpoints(true);
795 ValueObjectSP result_value_sp;
797 result_code = UserExpression::Evaluate(
798 exe_ctx, expr_options, wp_sp->GetConditionText(),
799 llvm::StringRef(), result_value_sp, error);
801 if (result_code == eExpressionCompleted) {
802 if (result_value_sp) {
804 if (result_value_sp->ResolveValue(scalar_value)) {
805 if (scalar_value.ULongLong(1) == 0) {
806 // We have been vetoed. This takes precedence over querying
807 // the watchpoint whether it should stop (aka ignore count
808 // and friends). See also StopInfoWatchpoint::ShouldStop()
809 // as well as Process::ProcessEventData::DoOnRemoval().
810 m_should_stop = false;
812 m_should_stop = true;
815 "Condition successfully evaluated, result is %s.\n",
816 m_should_stop ? "true" : "false");
818 m_should_stop = true;
821 "Failed to get an integer result from the expression.");
825 StreamSP error_sp = debugger.GetAsyncErrorStream();
827 "Stopped due to an error evaluating condition of watchpoint ");
828 wp_sp->GetDescription(error_sp.get(), eDescriptionLevelBrief);
829 error_sp->Printf(": \"%s\"", wp_sp->GetConditionText());
831 const char *err_str = error.AsCString("<Unknown Error>");
833 log->Printf("Error evaluating condition: \"%s\"\n", err_str);
835 error_sp->PutCString(err_str);
838 // If the condition fails to be parsed or run, we should stop.
839 m_should_stop = true;
843 // If the condition says to stop, we run the callback to further decide
846 // FIXME: For now the callbacks have to run in async mode - the
847 // first time we restart we need
848 // to get out of there. So set it here.
849 // When we figure out how to nest watchpoint hits then this will
852 bool old_async = debugger.GetAsyncExecution();
853 debugger.SetAsyncExecution(true);
855 StoppointCallbackContext context(event_ptr, exe_ctx, false);
856 bool stop_requested = wp_sp->InvokeCallback(&context);
858 debugger.SetAsyncExecution(old_async);
860 // Also make sure that the callback hasn't continued the target. If
861 // it did, when we'll set m_should_stop to false and get out of here.
862 if (HasTargetRunSinceMe())
863 m_should_stop = false;
865 if (m_should_stop && !stop_requested) {
866 // We have been vetoed by the callback mechanism.
867 m_should_stop = false;
870 // Finally, if we are going to stop, print out the new & old values:
872 wp_sp->CaptureWatchedValue(exe_ctx);
874 Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
875 StreamSP output_sp = debugger.GetAsyncOutputStream();
876 wp_sp->DumpSnapshots(output_sp.get());
883 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
887 "Process::%s could not find watchpoint id: %" PRId64 "...",
888 __FUNCTION__, m_value);
891 log->Printf("Process::%s returning from action with m_should_stop: %d.",
892 __FUNCTION__, m_should_stop);
894 m_should_stop_is_valid = true;
900 bool m_should_stop_is_valid;
901 lldb::addr_t m_watch_hit_addr;
904 //----------------------------------------------------------------------
905 // StopInfoUnixSignal
906 //----------------------------------------------------------------------
908 class StopInfoUnixSignal : public StopInfo {
910 StopInfoUnixSignal(Thread &thread, int signo, const char *description)
911 : StopInfo(thread, signo) {
912 SetDescription(description);
915 ~StopInfoUnixSignal() override = default;
917 StopReason GetStopReason() const override { return eStopReasonSignal; }
919 bool ShouldStopSynchronous(Event *event_ptr) override {
920 ThreadSP thread_sp(m_thread_wp.lock());
922 return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
926 bool ShouldStop(Event *event_ptr) override {
927 ThreadSP thread_sp(m_thread_wp.lock());
929 return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
933 // If should stop returns false, check if we should notify of this event
934 bool DoShouldNotify(Event *event_ptr) override {
935 ThreadSP thread_sp(m_thread_wp.lock());
938 thread_sp->GetProcess()->GetUnixSignals()->GetShouldNotify(m_value);
942 "thread %d received signal: %s", thread_sp->GetIndexID(),
943 thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString(
945 Process::ProcessEventData::AddRestartedReason(event_ptr,
948 return should_notify;
953 void WillResume(lldb::StateType resume_state) override {
954 ThreadSP thread_sp(m_thread_wp.lock());
956 if (!thread_sp->GetProcess()->GetUnixSignals()->GetShouldSuppress(
958 thread_sp->SetResumeSignal(m_value);
962 const char *GetDescription() override {
963 if (m_description.empty()) {
964 ThreadSP thread_sp(m_thread_wp.lock());
967 const char *signal_name =
968 thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsCString(
971 strm.Printf("signal %s", signal_name);
973 strm.Printf("signal %" PRIi64, m_value);
974 m_description = strm.GetString();
977 return m_description.c_str();
981 //----------------------------------------------------------------------
983 //----------------------------------------------------------------------
985 class StopInfoTrace : public StopInfo {
987 StopInfoTrace(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {}
989 ~StopInfoTrace() override = default;
991 StopReason GetStopReason() const override { return eStopReasonTrace; }
993 const char *GetDescription() override {
994 if (m_description.empty())
997 return m_description.c_str();
1001 //----------------------------------------------------------------------
1002 // StopInfoException
1003 //----------------------------------------------------------------------
1005 class StopInfoException : public StopInfo {
1007 StopInfoException(Thread &thread, const char *description)
1008 : StopInfo(thread, LLDB_INVALID_UID) {
1010 SetDescription(description);
1013 ~StopInfoException() override = default;
1015 StopReason GetStopReason() const override { return eStopReasonException; }
1017 const char *GetDescription() override {
1018 if (m_description.empty())
1021 return m_description.c_str();
1025 //----------------------------------------------------------------------
1026 // StopInfoThreadPlan
1027 //----------------------------------------------------------------------
1029 class StopInfoThreadPlan : public StopInfo {
1031 StopInfoThreadPlan(ThreadPlanSP &plan_sp, ValueObjectSP &return_valobj_sp,
1032 ExpressionVariableSP &expression_variable_sp)
1033 : StopInfo(plan_sp->GetThread(), LLDB_INVALID_UID), m_plan_sp(plan_sp),
1034 m_return_valobj_sp(return_valobj_sp),
1035 m_expression_variable_sp(expression_variable_sp) {}
1037 ~StopInfoThreadPlan() override = default;
1039 StopReason GetStopReason() const override { return eStopReasonPlanComplete; }
1041 const char *GetDescription() override {
1042 if (m_description.empty()) {
1044 m_plan_sp->GetDescription(&strm, eDescriptionLevelBrief);
1045 m_description = strm.GetString();
1047 return m_description.c_str();
1050 ValueObjectSP GetReturnValueObject() { return m_return_valobj_sp; }
1052 ExpressionVariableSP GetExpressionVariable() {
1053 return m_expression_variable_sp;
1057 bool ShouldStop(Event *event_ptr) override {
1059 return m_plan_sp->ShouldStop(event_ptr);
1061 return StopInfo::ShouldStop(event_ptr);
1065 ThreadPlanSP m_plan_sp;
1066 ValueObjectSP m_return_valobj_sp;
1067 ExpressionVariableSP m_expression_variable_sp;
1070 //----------------------------------------------------------------------
1072 //----------------------------------------------------------------------
1074 class StopInfoExec : public StopInfo {
1076 StopInfoExec(Thread &thread)
1077 : StopInfo(thread, LLDB_INVALID_UID), m_performed_action(false) {}
1079 ~StopInfoExec() override = default;
1081 bool ShouldStop(Event *event_ptr) override {
1082 ThreadSP thread_sp(m_thread_wp.lock());
1084 return thread_sp->GetProcess()->GetStopOnExec();
1088 StopReason GetStopReason() const override { return eStopReasonExec; }
1090 const char *GetDescription() override { return "exec"; }
1093 void PerformAction(Event *event_ptr) override {
1094 // Only perform the action once
1095 if (m_performed_action)
1097 m_performed_action = true;
1098 ThreadSP thread_sp(m_thread_wp.lock());
1100 thread_sp->GetProcess()->DidExec();
1103 bool m_performed_action;
1106 } // namespace lldb_private
1108 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
1109 break_id_t break_id) {
1110 return StopInfoSP(new StopInfoBreakpoint(thread, break_id));
1113 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
1114 break_id_t break_id,
1116 return StopInfoSP(new StopInfoBreakpoint(thread, break_id, should_stop));
1120 StopInfo::CreateStopReasonWithWatchpointID(Thread &thread, break_id_t watch_id,
1121 lldb::addr_t watch_hit_addr) {
1122 return StopInfoSP(new StopInfoWatchpoint(thread, watch_id, watch_hit_addr));
1125 StopInfoSP StopInfo::CreateStopReasonWithSignal(Thread &thread, int signo,
1126 const char *description) {
1127 return StopInfoSP(new StopInfoUnixSignal(thread, signo, description));
1130 StopInfoSP StopInfo::CreateStopReasonToTrace(Thread &thread) {
1131 return StopInfoSP(new StopInfoTrace(thread));
1134 StopInfoSP StopInfo::CreateStopReasonWithPlan(
1135 ThreadPlanSP &plan_sp, ValueObjectSP return_valobj_sp,
1136 ExpressionVariableSP expression_variable_sp) {
1137 return StopInfoSP(new StopInfoThreadPlan(plan_sp, return_valobj_sp,
1138 expression_variable_sp));
1141 StopInfoSP StopInfo::CreateStopReasonWithException(Thread &thread,
1142 const char *description) {
1143 return StopInfoSP(new StopInfoException(thread, description));
1146 StopInfoSP StopInfo::CreateStopReasonWithExec(Thread &thread) {
1147 return StopInfoSP(new StopInfoExec(thread));
1150 ValueObjectSP StopInfo::GetReturnValueObject(StopInfoSP &stop_info_sp) {
1152 stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
1153 StopInfoThreadPlan *plan_stop_info =
1154 static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1155 return plan_stop_info->GetReturnValueObject();
1157 return ValueObjectSP();
1160 ExpressionVariableSP StopInfo::GetExpressionVariable(StopInfoSP &stop_info_sp) {
1162 stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
1163 StopInfoThreadPlan *plan_stop_info =
1164 static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1165 return plan_stop_info->GetExpressionVariable();
1167 return ExpressionVariableSP();
1171 StopInfo::GetCrashingDereference(StopInfoSP &stop_info_sp,
1172 lldb::addr_t *crashing_address) {
1173 if (!stop_info_sp) {
1174 return ValueObjectSP();
1177 const char *description = stop_info_sp->GetDescription();
1179 return ValueObjectSP();
1182 ThreadSP thread_sp = stop_info_sp->GetThread();
1184 return ValueObjectSP();
1187 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
1190 return ValueObjectSP();
1193 const char address_string[] = "address=";
1195 const char *address_loc = strstr(description, address_string);
1197 return ValueObjectSP();
1200 address_loc += (sizeof(address_string) - 1);
1202 uint64_t address = strtoull(address_loc, 0, 0);
1203 if (crashing_address) {
1204 *crashing_address = address;
1207 return frame_sp->GuessValueForAddress(address);