xref: /llvm-project/lldb/source/Target/StopInfo.cpp (revision 22561cfb443267905d4190f0e2a738e6b412457f)
1 //===-- StopInfo.cpp ------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <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/Breakpoint/WatchpointResource.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Expression/UserExpression.h"
18 #include "lldb/Symbol/Block.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/StopInfo.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlan.h"
24 #include "lldb/Target/ThreadPlanStepInstruction.h"
25 #include "lldb/Target/UnixSignals.h"
26 #include "lldb/Utility/LLDBLog.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/StreamString.h"
29 #include "lldb/ValueObject/ValueObject.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 StopInfo::StopInfo(Thread &thread, uint64_t value)
35     : m_thread_wp(thread.shared_from_this()),
36       m_stop_id(thread.GetProcess()->GetStopID()),
37       m_resume_id(thread.GetProcess()->GetResumeID()), m_value(value),
38       m_description(), m_override_should_notify(eLazyBoolCalculate),
39       m_override_should_stop(eLazyBoolCalculate), m_extended_info() {}
40 
41 bool StopInfo::IsValid() const {
42   ThreadSP thread_sp(m_thread_wp.lock());
43   if (thread_sp)
44     return thread_sp->GetProcess()->GetStopID() == m_stop_id;
45   return false;
46 }
47 
48 void StopInfo::MakeStopInfoValid() {
49   ThreadSP thread_sp(m_thread_wp.lock());
50   if (thread_sp) {
51     m_stop_id = thread_sp->GetProcess()->GetStopID();
52     m_resume_id = thread_sp->GetProcess()->GetResumeID();
53   }
54 }
55 
56 bool StopInfo::HasTargetRunSinceMe() {
57   ThreadSP thread_sp(m_thread_wp.lock());
58 
59   if (thread_sp) {
60     lldb::StateType ret_type = thread_sp->GetProcess()->GetPrivateState();
61     if (ret_type == eStateRunning) {
62       return true;
63     } else if (ret_type == eStateStopped) {
64       // This is a little tricky.  We want to count "run and stopped again
65       // before you could ask this question as a "TRUE" answer to
66       // HasTargetRunSinceMe.  But we don't want to include any running of the
67       // target done for expressions.  So we track both resumes, and resumes
68       // caused by expressions, and check if there are any resumes
69       // NOT caused
70       // by expressions.
71 
72       uint32_t curr_resume_id = thread_sp->GetProcess()->GetResumeID();
73       uint32_t last_user_expression_id =
74           thread_sp->GetProcess()->GetLastUserExpressionResumeID();
75       if (curr_resume_id == m_resume_id) {
76         return false;
77       } else if (curr_resume_id > last_user_expression_id) {
78         return true;
79       }
80     }
81   }
82   return false;
83 }
84 
85 // StopInfoBreakpoint
86 
87 namespace lldb_private {
88 class StopInfoBreakpoint : public StopInfo {
89 public:
90   StopInfoBreakpoint(Thread &thread, break_id_t break_id)
91       : StopInfo(thread, break_id), m_should_stop(false),
92         m_should_stop_is_valid(false), m_should_perform_action(true),
93         m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
94         m_was_all_internal(false), m_was_one_shot(false) {
95     StoreBPInfo();
96   }
97 
98   StopInfoBreakpoint(Thread &thread, break_id_t break_id, bool should_stop)
99       : StopInfo(thread, break_id), m_should_stop(should_stop),
100         m_should_stop_is_valid(true), m_should_perform_action(true),
101         m_address(LLDB_INVALID_ADDRESS), m_break_id(LLDB_INVALID_BREAK_ID),
102         m_was_all_internal(false), m_was_one_shot(false) {
103     StoreBPInfo();
104   }
105 
106   ~StopInfoBreakpoint() override = default;
107 
108   void StoreBPInfo() {
109     ThreadSP thread_sp(m_thread_wp.lock());
110     if (thread_sp) {
111       BreakpointSiteSP bp_site_sp(
112           thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
113       if (bp_site_sp) {
114         uint32_t num_constituents = bp_site_sp->GetNumberOfConstituents();
115         if (num_constituents == 1) {
116           BreakpointLocationSP bp_loc_sp = bp_site_sp->GetConstituentAtIndex(0);
117           if (bp_loc_sp) {
118             Breakpoint & bkpt = bp_loc_sp->GetBreakpoint();
119             m_break_id = bkpt.GetID();
120             m_was_one_shot = bkpt.IsOneShot();
121             m_was_all_internal = bkpt.IsInternal();
122           }
123         } else {
124           m_was_all_internal = true;
125           for (uint32_t i = 0; i < num_constituents; i++) {
126             if (!bp_site_sp->GetConstituentAtIndex(i)
127                      ->GetBreakpoint()
128                      .IsInternal()) {
129               m_was_all_internal = false;
130               break;
131             }
132           }
133         }
134         m_address = bp_site_sp->GetLoadAddress();
135       }
136     }
137   }
138 
139   bool IsValidForOperatingSystemThread(Thread &thread) override {
140     ProcessSP process_sp(thread.GetProcess());
141     if (process_sp) {
142       BreakpointSiteSP bp_site_sp(
143           process_sp->GetBreakpointSiteList().FindByID(m_value));
144       if (bp_site_sp)
145         return bp_site_sp->ValidForThisThread(thread);
146     }
147     return false;
148   }
149 
150   StopReason GetStopReason() const override { return eStopReasonBreakpoint; }
151 
152   bool ShouldStopSynchronous(Event *event_ptr) override {
153     ThreadSP thread_sp(m_thread_wp.lock());
154     if (thread_sp) {
155       if (!m_should_stop_is_valid) {
156         // Only check once if we should stop at a breakpoint
157         BreakpointSiteSP bp_site_sp(
158             thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
159         if (bp_site_sp) {
160           ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
161           StoppointCallbackContext context(event_ptr, exe_ctx, true);
162           bp_site_sp->BumpHitCounts();
163           m_should_stop = bp_site_sp->ShouldStop(&context);
164         } else {
165           Log *log = GetLog(LLDBLog::Process);
166 
167           LLDB_LOGF(log,
168                     "Process::%s could not find breakpoint site id: %" PRId64
169                     "...",
170                     __FUNCTION__, m_value);
171 
172           m_should_stop = true;
173         }
174         m_should_stop_is_valid = true;
175       }
176       return m_should_stop;
177     }
178     return false;
179   }
180 
181   bool DoShouldNotify(Event *event_ptr) override {
182     return !m_was_all_internal;
183   }
184 
185   const char *GetDescription() override {
186     if (m_description.empty()) {
187       ThreadSP thread_sp(m_thread_wp.lock());
188       if (thread_sp) {
189         BreakpointSiteSP bp_site_sp(
190             thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
191         if (bp_site_sp) {
192           StreamString strm;
193           // If we have just hit an internal breakpoint, and it has a kind
194           // description, print that instead of the full breakpoint printing:
195           if (bp_site_sp->IsInternal()) {
196             size_t num_constituents = bp_site_sp->GetNumberOfConstituents();
197             for (size_t idx = 0; idx < num_constituents; idx++) {
198               const char *kind = bp_site_sp->GetConstituentAtIndex(idx)
199                                      ->GetBreakpoint()
200                                      .GetBreakpointKind();
201               if (kind != nullptr) {
202                 m_description.assign(kind);
203                 return kind;
204               }
205             }
206           }
207 
208           strm.Printf("breakpoint ");
209           bp_site_sp->GetDescription(&strm, eDescriptionLevelBrief);
210           m_description = std::string(strm.GetString());
211         } else {
212           StreamString strm;
213           if (m_break_id != LLDB_INVALID_BREAK_ID) {
214             BreakpointSP break_sp =
215                 thread_sp->GetProcess()->GetTarget().GetBreakpointByID(
216                     m_break_id);
217             if (break_sp) {
218               if (break_sp->IsInternal()) {
219                 const char *kind = break_sp->GetBreakpointKind();
220                 if (kind)
221                   strm.Printf("internal %s breakpoint(%d).", kind, m_break_id);
222                 else
223                   strm.Printf("internal breakpoint(%d).", m_break_id);
224               } else {
225                 strm.Printf("breakpoint %d.", m_break_id);
226               }
227             } else {
228               if (m_was_one_shot)
229                 strm.Printf("one-shot breakpoint %d", m_break_id);
230               else
231                 strm.Printf("breakpoint %d which has been deleted.",
232                             m_break_id);
233             }
234           } else if (m_address == LLDB_INVALID_ADDRESS)
235             strm.Printf("breakpoint site %" PRIi64
236                         " which has been deleted - unknown address",
237                         m_value);
238           else
239             strm.Printf("breakpoint site %" PRIi64
240                         " which has been deleted - was at 0x%" PRIx64,
241                         m_value, m_address);
242 
243           m_description = std::string(strm.GetString());
244         }
245       }
246     }
247     return m_description.c_str();
248   }
249 
250   std::optional<uint32_t>
251   GetSuggestedStackFrameIndex(bool inlined_stack) override {
252     if (!inlined_stack)
253       return {};
254 
255     ThreadSP thread_sp(m_thread_wp.lock());
256     if (!thread_sp)
257       return {};
258     BreakpointSiteSP bp_site_sp(
259         thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
260     if (!bp_site_sp)
261       return {};
262 
263     return bp_site_sp->GetSuggestedStackFrameIndex();
264   }
265 
266 protected:
267   bool ShouldStop(Event *event_ptr) override {
268     // This just reports the work done by PerformAction or the synchronous
269     // stop. It should only ever get called after they have had a chance to
270     // run.
271     assert(m_should_stop_is_valid);
272     return m_should_stop;
273   }
274 
275   void PerformAction(Event *event_ptr) override {
276     if (!m_should_perform_action)
277       return;
278     m_should_perform_action = false;
279     bool all_stopping_locs_internal = true;
280 
281     ThreadSP thread_sp(m_thread_wp.lock());
282 
283     if (thread_sp) {
284       Log *log = GetLog(LLDBLog::Breakpoints | LLDBLog::Step);
285 
286       if (!thread_sp->IsValid()) {
287         // This shouldn't ever happen, but just in case, don't do more harm.
288         if (log) {
289           LLDB_LOGF(log, "PerformAction got called with an invalid thread.");
290         }
291         m_should_stop = true;
292         m_should_stop_is_valid = true;
293         return;
294       }
295 
296       BreakpointSiteSP bp_site_sp(
297           thread_sp->GetProcess()->GetBreakpointSiteList().FindByID(m_value));
298       std::unordered_set<break_id_t> precondition_breakpoints;
299       // Breakpoints that fail their condition check are not considered to
300       // have been hit.  If the only locations at this site have failed their
301       // conditions, we should change the stop-info to none.  Otherwise, if we
302       // hit another breakpoint on a different thread which does stop, users
303       // will see a breakpont hit with a failed condition, which is wrong.
304       // Use this variable to tell us if that is true.
305       bool actually_hit_any_locations = false;
306       if (bp_site_sp) {
307         // Let's copy the constituents list out of the site and store them in a
308         // local list.  That way if one of the breakpoint actions changes the
309         // site, then we won't be operating on a bad list.
310         BreakpointLocationCollection site_locations;
311         size_t num_constituents =
312             bp_site_sp->CopyConstituentsList(site_locations);
313 
314         if (num_constituents == 0) {
315           m_should_stop = true;
316           actually_hit_any_locations = true;  // We're going to stop, don't
317                                               // change the stop info.
318         } else {
319           // We go through each location, and test first its precondition -
320           // this overrides everything.  Note, we only do this once per
321           // breakpoint - not once per location... Then check the condition.
322           // If the condition says to stop, then we run the callback for that
323           // location.  If that callback says to stop as well, then we set
324           // m_should_stop to true; we are going to stop. But we still want to
325           // give all the breakpoints whose conditions say we are going to stop
326           // a chance to run their callbacks. Of course if any callback
327           // restarts the target by putting "continue" in the callback, then
328           // we're going to restart, without running the rest of the callbacks.
329           // And in this case we will end up not stopping even if another
330           // location said we should stop. But that's better than not running
331           // all the callbacks.
332 
333           // There's one other complication here.  We may have run an async
334           // breakpoint callback that said we should stop.  We only want to
335           // override that if another breakpoint action says we shouldn't
336           // stop.  If nobody else has an opinion, then we should stop if the
337           // async callback says we should.  An example of this is the async
338           // shared library load notification breakpoint and the setting
339           // stop-on-sharedlibrary-events.
340           // We'll keep the async value in async_should_stop, and track whether
341           // anyone said we should NOT stop in actually_said_continue.
342           bool async_should_stop = false;
343           if (m_should_stop_is_valid)
344             async_should_stop = m_should_stop;
345           bool actually_said_continue = false;
346 
347           m_should_stop = false;
348 
349           // We don't select threads as we go through them testing breakpoint
350           // conditions and running commands. So we need to set the thread for
351           // expression evaluation here:
352           ThreadList::ExpressionExecutionThreadPusher thread_pusher(thread_sp);
353 
354           ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
355           Process *process = exe_ctx.GetProcessPtr();
356           if (process->GetModIDRef().IsRunningExpression()) {
357             // If we are in the middle of evaluating an expression, don't run
358             // asynchronous breakpoint commands or expressions.  That could
359             // lead to infinite recursion if the command or condition re-calls
360             // the function with this breakpoint.
361             // TODO: We can keep a list of the breakpoints we've seen while
362             // running expressions in the nested
363             // PerformAction calls that can arise when the action runs a
364             // function that hits another breakpoint, and only stop running
365             // commands when we see the same breakpoint hit a second time.
366 
367             m_should_stop_is_valid = true;
368 
369             // It is possible that the user has a breakpoint at the same site
370             // as the completed plan had (e.g. user has a breakpoint
371             // on a module entry point, and `ThreadPlanCallFunction` ends
372             // also there). We can't find an internal breakpoint in the loop
373             // later because it was already removed on the plan completion.
374             // So check if the plan was completed, and stop if so.
375             if (thread_sp->CompletedPlanOverridesBreakpoint()) {
376               m_should_stop = true;
377               thread_sp->ResetStopInfo();
378               return;
379             }
380 
381             LLDB_LOGF(log, "StopInfoBreakpoint::PerformAction - Hit a "
382                            "breakpoint while running an expression,"
383                            " not running commands to avoid recursion.");
384             bool ignoring_breakpoints =
385                 process->GetIgnoreBreakpointsInExpressions();
386             // Internal breakpoints should be allowed to do their job, we
387             // can make sure they don't do anything that would cause recursive
388             // command execution:
389             if (!m_was_all_internal) {
390               m_should_stop = !ignoring_breakpoints;
391               LLDB_LOGF(log,
392                         "StopInfoBreakpoint::PerformAction - in expression, "
393                         "continuing: %s.",
394                         m_should_stop ? "true" : "false");
395               Debugger::ReportWarning(
396                   "hit breakpoint while running function, skipping commands "
397                   "and conditions to prevent recursion",
398                     process->GetTarget().GetDebugger().GetID());
399               return;
400             }
401           }
402 
403           StoppointCallbackContext context(event_ptr, exe_ctx, false);
404 
405           // For safety's sake let's also grab an extra reference to the
406           // breakpoint constituents of the locations we're going to examine,
407           // since the locations are going to have to get back to their
408           // breakpoints, and the locations don't keep their constituents alive.
409           // I'm just sticking the BreakpointSP's in a vector since I'm only
410           // using it to locally increment their retain counts.
411 
412           std::vector<lldb::BreakpointSP> location_constituents;
413 
414           for (size_t j = 0; j < num_constituents; j++) {
415             BreakpointLocationSP loc(site_locations.GetByIndex(j));
416             location_constituents.push_back(
417                 loc->GetBreakpoint().shared_from_this());
418           }
419 
420           for (size_t j = 0; j < num_constituents; j++) {
421             lldb::BreakpointLocationSP bp_loc_sp = site_locations.GetByIndex(j);
422             StreamString loc_desc;
423             if (log) {
424               bp_loc_sp->GetDescription(&loc_desc, eDescriptionLevelBrief);
425             }
426             // If another action disabled this breakpoint or its location, then
427             // don't run the actions.
428             if (!bp_loc_sp->IsEnabled() ||
429                 !bp_loc_sp->GetBreakpoint().IsEnabled())
430               continue;
431 
432             // The breakpoint site may have many locations associated with it,
433             // not all of them valid for this thread.  Skip the ones that
434             // aren't:
435             if (!bp_loc_sp->ValidForThisThread(*thread_sp)) {
436               if (log) {
437                 LLDB_LOGF(log,
438                           "Breakpoint %s hit on thread 0x%llx but it was not "
439                           "for this thread, continuing.",
440                           loc_desc.GetData(),
441                           static_cast<unsigned long long>(thread_sp->GetID()));
442               }
443               continue;
444             }
445 
446             // First run the precondition, but since the precondition is per
447             // breakpoint, only run it once per breakpoint.
448             std::pair<std::unordered_set<break_id_t>::iterator, bool> result =
449                 precondition_breakpoints.insert(
450                     bp_loc_sp->GetBreakpoint().GetID());
451             if (!result.second)
452               continue;
453 
454             bool precondition_result =
455                 bp_loc_sp->GetBreakpoint().EvaluatePrecondition(context);
456             if (!precondition_result) {
457               actually_said_continue = true;
458               continue;
459             }
460             // Next run the condition for the breakpoint.  If that says we
461             // should stop, then we'll run the callback for the breakpoint.  If
462             // the callback says we shouldn't stop that will win.
463 
464             if (bp_loc_sp->GetConditionText() == nullptr)
465               actually_hit_any_locations = true;
466             else {
467               Status condition_error;
468               bool condition_says_stop =
469                   bp_loc_sp->ConditionSaysStop(exe_ctx, condition_error);
470 
471               if (!condition_error.Success()) {
472                 // If the condition fails to evaluate, we are going to stop
473                 // at it, so the location was hit.
474                 actually_hit_any_locations = true;
475                 const char *err_str =
476                     condition_error.AsCString("<unknown error>");
477                 LLDB_LOGF(log, "Error evaluating condition: \"%s\"\n", err_str);
478 
479                 StreamString strm;
480                 strm << "stopped due to an error evaluating condition of "
481                         "breakpoint ";
482                 bp_loc_sp->GetDescription(&strm, eDescriptionLevelBrief);
483                 strm << ": \"" << bp_loc_sp->GetConditionText() << "\"\n";
484                 strm << err_str;
485 
486                 Debugger::ReportError(
487                     strm.GetString().str(),
488                     exe_ctx.GetTargetRef().GetDebugger().GetID());
489               } else {
490                 LLDB_LOGF(log,
491                           "Condition evaluated for breakpoint %s on thread "
492                           "0x%llx condition_says_stop: %i.",
493                           loc_desc.GetData(),
494                           static_cast<unsigned long long>(thread_sp->GetID()),
495                           condition_says_stop);
496                 if (condition_says_stop)
497                   actually_hit_any_locations = true;
498                 else {
499                   // We don't want to increment the hit count of breakpoints if
500                   // the condition fails. We've already bumped it by the time
501                   // we get here, so undo the bump:
502                   bp_loc_sp->UndoBumpHitCount();
503                   actually_said_continue = true;
504                   continue;
505                 }
506               }
507             }
508 
509             // We've done all the checks whose failure means "we consider lldb
510             // not to have hit the breakpoint".  Now we're going to check for
511             // conditions that might continue after hitting.  Start with the
512             // ignore count:
513             if (!bp_loc_sp->IgnoreCountShouldStop()) {
514               actually_said_continue = true;
515               continue;
516             }
517 
518             // Check the auto-continue bit on the location, do this before the
519             // callback since it may change this, but that would be for the
520             // NEXT hit.  Note, you might think you could check auto-continue
521             // before the condition, and not evaluate the condition if it says
522             // to continue.  But failing the condition means the breakpoint was
523             // effectively NOT HIT.  So these two states are different.
524             bool auto_continue_says_stop = true;
525             if (bp_loc_sp->IsAutoContinue())
526             {
527               LLDB_LOGF(log,
528                         "Continuing breakpoint %s as AutoContinue was set.",
529                         loc_desc.GetData());
530               // We want this stop reported, so you will know we auto-continued
531               // but only for external breakpoints:
532               if (!bp_loc_sp->GetBreakpoint().IsInternal())
533                 thread_sp->SetShouldReportStop(eVoteYes);
534               auto_continue_says_stop = false;
535             }
536 
537             bool callback_says_stop = true;
538 
539             // FIXME: For now the callbacks have to run in async mode - the
540             // first time we restart we need
541             // to get out of there.  So set it here.
542             // When we figure out how to nest breakpoint hits then this will
543             // change.
544 
545             // Don't run async callbacks in PerformAction.  They have already
546             // been taken into account with async_should_stop.
547             if (!bp_loc_sp->IsCallbackSynchronous()) {
548               Debugger &debugger = thread_sp->CalculateTarget()->GetDebugger();
549               bool old_async = debugger.GetAsyncExecution();
550               debugger.SetAsyncExecution(true);
551 
552               callback_says_stop = bp_loc_sp->InvokeCallback(&context);
553 
554               debugger.SetAsyncExecution(old_async);
555 
556               if (callback_says_stop && auto_continue_says_stop)
557                 m_should_stop = true;
558               else
559                 actually_said_continue = true;
560             }
561 
562             if (m_should_stop && !bp_loc_sp->GetBreakpoint().IsInternal())
563               all_stopping_locs_internal = false;
564 
565             // If we are going to stop for this breakpoint, then remove the
566             // breakpoint.
567             if (callback_says_stop && bp_loc_sp &&
568                 bp_loc_sp->GetBreakpoint().IsOneShot()) {
569               thread_sp->GetProcess()->GetTarget().RemoveBreakpointByID(
570                   bp_loc_sp->GetBreakpoint().GetID());
571             }
572             // Also make sure that the callback hasn't continued the target. If
573             // it did, when we'll set m_should_start to false and get out of
574             // here.
575             if (HasTargetRunSinceMe()) {
576               m_should_stop = false;
577               actually_said_continue = true;
578               break;
579             }
580           }
581           // At this point if nobody actually told us to continue, we should
582           // give the async breakpoint callback a chance to weigh in:
583           if (!actually_said_continue && !m_should_stop) {
584             m_should_stop = async_should_stop;
585           }
586         }
587         // We've figured out what this stop wants to do, so mark it as valid so
588         // we don't compute it again.
589         m_should_stop_is_valid = true;
590       } else {
591         m_should_stop = true;
592         m_should_stop_is_valid = true;
593         actually_hit_any_locations = true;
594         Log *log_process(GetLog(LLDBLog::Process));
595 
596         LLDB_LOGF(log_process,
597                   "Process::%s could not find breakpoint site id: %" PRId64
598                   "...",
599                   __FUNCTION__, m_value);
600       }
601 
602       if ((!m_should_stop || all_stopping_locs_internal) &&
603           thread_sp->CompletedPlanOverridesBreakpoint()) {
604 
605         // Override should_stop decision when we have completed step plan
606         // additionally to the breakpoint
607         m_should_stop = true;
608 
609         // We know we're stopping for a completed plan and we don't want to
610         // show the breakpoint stop, so compute the public stop info immediately
611         // here.
612         thread_sp->CalculatePublicStopInfo();
613       } else if (!actually_hit_any_locations) {
614         // In the end, we didn't actually have any locations that passed their
615         // "was I hit" checks.  So say we aren't stopped.
616         GetThread()->ResetStopInfo();
617         LLDB_LOGF(log, "Process::%s all locations failed condition checks.",
618           __FUNCTION__);
619       }
620 
621       LLDB_LOGF(log,
622                 "Process::%s returning from action with m_should_stop: %d.",
623                 __FUNCTION__, m_should_stop);
624     }
625   }
626 
627 private:
628   bool m_should_stop;
629   bool m_should_stop_is_valid;
630   bool m_should_perform_action; // Since we are trying to preserve the "state"
631                                 // of the system even if we run functions
632   // etc. behind the users backs, we need to make sure we only REALLY perform
633   // the action once.
634   lldb::addr_t m_address; // We use this to capture the breakpoint site address
635                           // when we create the StopInfo,
636   // in case somebody deletes it between the time the StopInfo is made and the
637   // description is asked for.
638   lldb::break_id_t m_break_id;
639   bool m_was_all_internal;
640   bool m_was_one_shot;
641 };
642 
643 // StopInfoWatchpoint
644 
645 class StopInfoWatchpoint : public StopInfo {
646 public:
647   // Make sure watchpoint is properly disabled and subsequently enabled while
648   // performing watchpoint actions.
649   class WatchpointSentry {
650   public:
651     WatchpointSentry(ProcessSP p_sp, WatchpointSP w_sp) : process_sp(p_sp),
652                      watchpoint_sp(w_sp) {
653       if (process_sp && watchpoint_sp) {
654         const bool notify = false;
655         watchpoint_sp->TurnOnEphemeralMode();
656         process_sp->DisableWatchpoint(watchpoint_sp, notify);
657         process_sp->AddPreResumeAction(SentryPreResumeAction, this);
658       }
659     }
660 
661     void DoReenable() {
662       if (process_sp && watchpoint_sp) {
663         bool was_disabled = watchpoint_sp->IsDisabledDuringEphemeralMode();
664         watchpoint_sp->TurnOffEphemeralMode();
665         const bool notify = false;
666         if (was_disabled) {
667           process_sp->DisableWatchpoint(watchpoint_sp, notify);
668         } else {
669           process_sp->EnableWatchpoint(watchpoint_sp, notify);
670         }
671       }
672     }
673 
674     ~WatchpointSentry() {
675         DoReenable();
676         if (process_sp)
677             process_sp->ClearPreResumeAction(SentryPreResumeAction, this);
678     }
679 
680     static bool SentryPreResumeAction(void *sentry_void) {
681         WatchpointSentry *sentry = (WatchpointSentry *) sentry_void;
682         sentry->DoReenable();
683         return true;
684     }
685 
686   private:
687     ProcessSP process_sp;
688     WatchpointSP watchpoint_sp;
689   };
690 
691   StopInfoWatchpoint(Thread &thread, break_id_t watch_id, bool silently_skip_wp)
692       : StopInfo(thread, watch_id), m_silently_skip_wp(silently_skip_wp) {}
693 
694   ~StopInfoWatchpoint() override = default;
695 
696   StopReason GetStopReason() const override { return eStopReasonWatchpoint; }
697 
698   const char *GetDescription() override {
699     if (m_description.empty()) {
700       StreamString strm;
701       strm.Printf("watchpoint %" PRIi64, m_value);
702       m_description = std::string(strm.GetString());
703     }
704     return m_description.c_str();
705   }
706 
707 protected:
708   using StopInfoWatchpointSP = std::shared_ptr<StopInfoWatchpoint>;
709   // This plan is used to orchestrate stepping over the watchpoint for
710   // architectures (e.g. ARM) that report the watch before running the watched
711   // access.  This is the sort of job you have to defer to the thread plans,
712   // if you try to do it directly in the stop info and there are other threads
713   // that needed to process this stop you will have yanked control away from
714   // them and they won't behave correctly.
715   class ThreadPlanStepOverWatchpoint : public ThreadPlanStepInstruction {
716   public:
717     ThreadPlanStepOverWatchpoint(Thread &thread,
718                                  StopInfoWatchpointSP stop_info_sp,
719                                  WatchpointSP watch_sp)
720         : ThreadPlanStepInstruction(thread, false, true, eVoteNoOpinion,
721                                     eVoteNoOpinion),
722           m_stop_info_sp(stop_info_sp), m_watch_sp(watch_sp) {
723       assert(watch_sp);
724     }
725 
726     bool DoWillResume(lldb::StateType resume_state,
727                       bool current_plan) override {
728       if (resume_state == eStateSuspended)
729         return true;
730 
731       if (!m_did_disable_wp) {
732         GetThread().GetProcess()->DisableWatchpoint(m_watch_sp, false);
733         m_did_disable_wp = true;
734       }
735       return true;
736     }
737 
738     bool DoPlanExplainsStop(Event *event_ptr) override {
739       if (ThreadPlanStepInstruction::DoPlanExplainsStop(event_ptr))
740         return true;
741       StopInfoSP stop_info_sp = GetThread().GetPrivateStopInfo();
742       // lldb-server resets the stop info for threads that didn't get to run,
743       // so we might have not gotten to run, but still have a watchpoint stop
744       // reason, in which case this will indeed be for us.
745       if (stop_info_sp
746           && stop_info_sp->GetStopReason() == eStopReasonWatchpoint)
747         return true;
748       return false;
749     }
750 
751     void DidPop() override {
752       // Don't artifically keep the watchpoint alive.
753       m_watch_sp.reset();
754     }
755 
756     bool ShouldStop(Event *event_ptr) override {
757       bool should_stop = ThreadPlanStepInstruction::ShouldStop(event_ptr);
758       bool plan_done = MischiefManaged();
759       if (plan_done) {
760         m_stop_info_sp->SetStepOverPlanComplete();
761         GetThread().SetStopInfo(m_stop_info_sp);
762         ResetWatchpoint();
763       }
764       return should_stop;
765     }
766 
767     bool ShouldRunBeforePublicStop() override {
768         return true;
769     }
770 
771   protected:
772     void ResetWatchpoint() {
773       if (!m_did_disable_wp)
774         return;
775       m_did_disable_wp = true;
776       GetThread().GetProcess()->EnableWatchpoint(m_watch_sp, true);
777     }
778 
779   private:
780     StopInfoWatchpointSP m_stop_info_sp;
781     WatchpointSP m_watch_sp;
782     bool m_did_disable_wp = false;
783   };
784 
785   bool ShouldStopSynchronous(Event *event_ptr) override {
786     // If we are running our step-over the watchpoint plan, stop if it's done
787     // and continue if it's not:
788     if (m_should_stop_is_valid)
789       return m_should_stop;
790 
791     // If we are running our step over plan, then stop here and let the regular
792     // ShouldStop figure out what we should do:  Otherwise, give our plan
793     // more time to get run:
794     if (m_using_step_over_plan)
795       return m_step_over_plan_complete;
796 
797     Log *log = GetLog(LLDBLog::Process);
798     ThreadSP thread_sp(m_thread_wp.lock());
799     assert(thread_sp);
800 
801     if (thread_sp->GetTemporaryResumeState() == eStateSuspended) {
802       // This is the second firing of a watchpoint so don't process it again.
803       LLDB_LOG(log, "We didn't run but stopped with a StopInfoWatchpoint, we "
804                "have already handled this one, don't do it again.");
805       m_should_stop = false;
806       m_should_stop_is_valid = true;
807       return m_should_stop;
808     }
809 
810     WatchpointSP wp_sp(
811         thread_sp->CalculateTarget()->GetWatchpointList().FindByID(GetValue()));
812     // If we can no longer find the watchpoint, we just have to stop:
813     if (!wp_sp) {
814 
815       LLDB_LOGF(log,
816                 "Process::%s could not find watchpoint location id: %" PRId64
817                 "...",
818                 __FUNCTION__, GetValue());
819 
820       m_should_stop = true;
821       m_should_stop_is_valid = true;
822       return true;
823     }
824 
825     ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
826     StoppointCallbackContext context(event_ptr, exe_ctx, true);
827     m_should_stop = wp_sp->ShouldStop(&context);
828     if (!m_should_stop) {
829       // This won't happen at present because we only allow one watchpoint per
830       // watched range.  So we won't stop at a watched address with a disabled
831       // watchpoint.  If we start allowing overlapping watchpoints, then we
832       // will have to make watchpoints be real "WatchpointSite" and delegate to
833       // all the watchpoints sharing the site.  In that case, the code below
834       // would be the right thing to do.
835       m_should_stop_is_valid = true;
836       return m_should_stop;
837     }
838     // If this is a system where we need to execute the watchpoint by hand
839     // after the hit, queue a thread plan to do that, and then say not to stop.
840     // Otherwise, let the async action figure out whether the watchpoint should
841     // stop
842 
843     ProcessSP process_sp = exe_ctx.GetProcessSP();
844     bool wp_triggers_after = process_sp->GetWatchpointReportedAfter();
845 
846     if (!wp_triggers_after) {
847       // We have to step over the watchpoint before we know what to do:
848       StopInfoWatchpointSP me_as_siwp_sp
849           = std::static_pointer_cast<StopInfoWatchpoint>(shared_from_this());
850       ThreadPlanSP step_over_wp_sp(new ThreadPlanStepOverWatchpoint(
851           *(thread_sp.get()), me_as_siwp_sp, wp_sp));
852       // When this plan is done we want to stop, so set this as a Controlling
853       // plan.
854       step_over_wp_sp->SetIsControllingPlan(true);
855       step_over_wp_sp->SetOkayToDiscard(false);
856 
857       Status error;
858       error = thread_sp->QueueThreadPlan(step_over_wp_sp, false);
859       // If we couldn't push the thread plan, just stop here:
860       if (!error.Success()) {
861         LLDB_LOGF(log, "Could not push our step over watchpoint plan: %s",
862             error.AsCString());
863 
864         m_should_stop = true;
865         m_should_stop_is_valid = true;
866         return true;
867       } else {
868       // Otherwise, don't set m_should_stop, we don't know that yet.  Just
869       // say we should continue, and tell the thread we really should do so:
870         thread_sp->SetShouldRunBeforePublicStop(true);
871         m_using_step_over_plan = true;
872         return false;
873       }
874     } else {
875       // We didn't have to do anything special
876       m_should_stop_is_valid = true;
877       return m_should_stop;
878     }
879 
880     return m_should_stop;
881   }
882 
883   bool ShouldStop(Event *event_ptr) override {
884     // This just reports the work done by PerformAction or the synchronous
885     // stop. It should only ever get called after they have had a chance to
886     // run.
887     assert(m_should_stop_is_valid);
888     return m_should_stop;
889   }
890 
891   void PerformAction(Event *event_ptr) override {
892     Log *log = GetLog(LLDBLog::Watchpoints);
893     // We're going to calculate if we should stop or not in some way during the
894     // course of this code.  Also by default we're going to stop, so set that
895     // here.
896     m_should_stop = true;
897 
898 
899     ThreadSP thread_sp(m_thread_wp.lock());
900     if (thread_sp) {
901 
902       WatchpointSP wp_sp(
903           thread_sp->CalculateTarget()->GetWatchpointList().FindByID(
904               GetValue()));
905       if (wp_sp) {
906         // This sentry object makes sure the current watchpoint is disabled
907         // while performing watchpoint actions, and it is then enabled after we
908         // are finished.
909         ExecutionContext exe_ctx(thread_sp->GetStackFrameAtIndex(0));
910         ProcessSP process_sp = exe_ctx.GetProcessSP();
911 
912         WatchpointSentry sentry(process_sp, wp_sp);
913 
914         if (m_silently_skip_wp) {
915           m_should_stop = false;
916           wp_sp->UndoHitCount();
917         }
918 
919         if (wp_sp->GetHitCount() <= wp_sp->GetIgnoreCount()) {
920           m_should_stop = false;
921           m_should_stop_is_valid = true;
922         }
923 
924         Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
925 
926         if (m_should_stop && wp_sp->GetConditionText() != nullptr) {
927           // We need to make sure the user sees any parse errors in their
928           // condition, so we'll hook the constructor errors up to the
929           // debugger's Async I/O.
930           ExpressionResults result_code;
931           EvaluateExpressionOptions expr_options;
932           expr_options.SetUnwindOnError(true);
933           expr_options.SetIgnoreBreakpoints(true);
934           ValueObjectSP result_value_sp;
935           result_code = UserExpression::Evaluate(
936               exe_ctx, expr_options, wp_sp->GetConditionText(),
937               llvm::StringRef(), result_value_sp);
938 
939           if (result_code == eExpressionCompleted) {
940             if (result_value_sp) {
941               Scalar scalar_value;
942               if (result_value_sp->ResolveValue(scalar_value)) {
943                 if (scalar_value.ULongLong(1) == 0) {
944                   // The condition failed, which we consider "not having hit
945                   // the watchpoint" so undo the hit count here.
946                   wp_sp->UndoHitCount();
947                   m_should_stop = false;
948                 } else
949                   m_should_stop = true;
950                 LLDB_LOGF(log,
951                           "Condition successfully evaluated, result is %s.\n",
952                           m_should_stop ? "true" : "false");
953               } else {
954                 m_should_stop = true;
955                 LLDB_LOGF(
956                     log,
957                     "Failed to get an integer result from the expression.");
958               }
959             }
960           } else {
961             const char *err_str = "<unknown error>";
962             if (result_value_sp)
963               err_str = result_value_sp->GetError().AsCString();
964 
965             LLDB_LOGF(log, "Error evaluating condition: \"%s\"\n", err_str);
966 
967             StreamString strm;
968             strm << "stopped due to an error evaluating condition of "
969                     "watchpoint ";
970             wp_sp->GetDescription(&strm, eDescriptionLevelBrief);
971             strm << ": \"" << wp_sp->GetConditionText() << "\"\n";
972             strm << err_str;
973 
974             Debugger::ReportError(strm.GetString().str(),
975                                   exe_ctx.GetTargetRef().GetDebugger().GetID());
976           }
977         }
978 
979         // If the condition says to stop, we run the callback to further decide
980         // whether to stop.
981         if (m_should_stop) {
982             // FIXME: For now the callbacks have to run in async mode - the
983             // first time we restart we need
984             // to get out of there.  So set it here.
985             // When we figure out how to nest watchpoint hits then this will
986             // change.
987 
988           bool old_async = debugger.GetAsyncExecution();
989           debugger.SetAsyncExecution(true);
990 
991           StoppointCallbackContext context(event_ptr, exe_ctx, false);
992           bool stop_requested = wp_sp->InvokeCallback(&context);
993 
994           debugger.SetAsyncExecution(old_async);
995 
996           // Also make sure that the callback hasn't continued the target. If
997           // it did, when we'll set m_should_stop to false and get out of here.
998           if (HasTargetRunSinceMe())
999             m_should_stop = false;
1000 
1001           if (m_should_stop && !stop_requested) {
1002             // We have been vetoed by the callback mechanism.
1003             m_should_stop = false;
1004           }
1005         }
1006 
1007         // Don't stop if the watched region value is unmodified, and
1008         // this is a Modify-type watchpoint.
1009         if (m_should_stop && !wp_sp->WatchedValueReportable(exe_ctx)) {
1010           wp_sp->UndoHitCount();
1011           m_should_stop = false;
1012         }
1013 
1014         // Finally, if we are going to stop, print out the new & old values:
1015         if (m_should_stop) {
1016           wp_sp->CaptureWatchedValue(exe_ctx);
1017 
1018           Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
1019           StreamSP output_sp = debugger.GetAsyncOutputStream();
1020           if (wp_sp->DumpSnapshots(output_sp.get())) {
1021             output_sp->EOL();
1022             output_sp->Flush();
1023           }
1024         }
1025 
1026       } else {
1027         Log *log_process(GetLog(LLDBLog::Process));
1028 
1029         LLDB_LOGF(log_process,
1030                   "Process::%s could not find watchpoint id: %" PRId64 "...",
1031                   __FUNCTION__, m_value);
1032       }
1033       LLDB_LOGF(log,
1034                 "Process::%s returning from action with m_should_stop: %d.",
1035                 __FUNCTION__, m_should_stop);
1036 
1037       m_should_stop_is_valid = true;
1038     }
1039   }
1040 
1041 private:
1042   void SetStepOverPlanComplete() {
1043     assert(m_using_step_over_plan);
1044     m_step_over_plan_complete = true;
1045   }
1046 
1047   bool m_should_stop = false;
1048   bool m_should_stop_is_valid = false;
1049   // A false watchpoint hit has happened -
1050   // the thread stopped with a watchpoint
1051   // hit notification, but the watched region
1052   // was not actually accessed (as determined
1053   // by the gdb stub we're talking to).
1054   // Continue past this watchpoint without
1055   // notifying the user; on some targets this
1056   // may mean disable wp, instruction step,
1057   // re-enable wp, continue.
1058   // On others, just continue.
1059   bool m_silently_skip_wp = false;
1060   bool m_step_over_plan_complete = false;
1061   bool m_using_step_over_plan = false;
1062 };
1063 
1064 // StopInfoUnixSignal
1065 
1066 class StopInfoUnixSignal : public StopInfo {
1067 public:
1068   StopInfoUnixSignal(Thread &thread, int signo, const char *description,
1069                      std::optional<int> code)
1070       : StopInfo(thread, signo), m_code(code) {
1071     SetDescription(description);
1072   }
1073 
1074   ~StopInfoUnixSignal() override = default;
1075 
1076   StopReason GetStopReason() const override { return eStopReasonSignal; }
1077 
1078   bool ShouldStopSynchronous(Event *event_ptr) override {
1079     ThreadSP thread_sp(m_thread_wp.lock());
1080     if (thread_sp)
1081       return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
1082     return false;
1083   }
1084 
1085   bool ShouldStop(Event *event_ptr) override {
1086     ThreadSP thread_sp(m_thread_wp.lock());
1087     if (thread_sp)
1088       return thread_sp->GetProcess()->GetUnixSignals()->GetShouldStop(m_value);
1089     return false;
1090   }
1091 
1092   // If should stop returns false, check if we should notify of this event
1093   bool DoShouldNotify(Event *event_ptr) override {
1094     ThreadSP thread_sp(m_thread_wp.lock());
1095     if (thread_sp) {
1096       bool should_notify =
1097           thread_sp->GetProcess()->GetUnixSignals()->GetShouldNotify(m_value);
1098       if (should_notify) {
1099         StreamString strm;
1100         strm.Format(
1101             "thread {0:d} received signal: {1}", thread_sp->GetIndexID(),
1102             thread_sp->GetProcess()->GetUnixSignals()->GetSignalAsStringRef(
1103                 m_value));
1104         Process::ProcessEventData::AddRestartedReason(event_ptr,
1105                                                       strm.GetData());
1106       }
1107       return should_notify;
1108     }
1109     return true;
1110   }
1111 
1112   void WillResume(lldb::StateType resume_state) override {
1113     ThreadSP thread_sp(m_thread_wp.lock());
1114     if (thread_sp) {
1115       if (!thread_sp->GetProcess()->GetUnixSignals()->GetShouldSuppress(
1116               m_value))
1117         thread_sp->SetResumeSignal(m_value);
1118     }
1119   }
1120 
1121   const char *GetDescription() override {
1122     if (m_description.empty()) {
1123       ThreadSP thread_sp(m_thread_wp.lock());
1124       if (thread_sp) {
1125         UnixSignalsSP unix_signals = thread_sp->GetProcess()->GetUnixSignals();
1126         StreamString strm;
1127         strm << "signal ";
1128 
1129         std::string signal_name =
1130             unix_signals->GetSignalDescription(m_value, m_code);
1131         if (signal_name.size())
1132           strm << signal_name;
1133         else
1134           strm.Printf("%" PRIi64, m_value);
1135 
1136         m_description = std::string(strm.GetString());
1137       }
1138     }
1139     return m_description.c_str();
1140   }
1141 
1142 private:
1143   // In siginfo_t terms, if m_value is si_signo, m_code is si_code.
1144   std::optional<int> m_code;
1145 };
1146 
1147 // StopInfoInterrupt
1148 
1149 class StopInfoInterrupt : public StopInfo {
1150 public:
1151   StopInfoInterrupt(Thread &thread, int signo, const char *description)
1152       : StopInfo(thread, signo) {
1153     SetDescription(description);
1154   }
1155 
1156   ~StopInfoInterrupt() override = default;
1157 
1158   StopReason GetStopReason() const override {
1159     return lldb::eStopReasonInterrupt;
1160   }
1161 
1162   const char *GetDescription() override {
1163     if (m_description.empty()) {
1164       m_description = "async interrupt";
1165     }
1166     return m_description.c_str();
1167   }
1168 };
1169 
1170 // StopInfoTrace
1171 
1172 class StopInfoTrace : public StopInfo {
1173 public:
1174   StopInfoTrace(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {}
1175 
1176   ~StopInfoTrace() override = default;
1177 
1178   StopReason GetStopReason() const override { return eStopReasonTrace; }
1179 
1180   const char *GetDescription() override {
1181     if (m_description.empty())
1182       return "trace";
1183     else
1184       return m_description.c_str();
1185   }
1186 
1187   std::optional<uint32_t>
1188   GetSuggestedStackFrameIndex(bool inlined_stack) override {
1189     // Trace only knows how to adjust inlined stacks:
1190     if (!inlined_stack)
1191       return {};
1192 
1193     ThreadSP thread_sp = GetThread();
1194     StackFrameSP frame_0_sp = thread_sp->GetStackFrameAtIndex(0);
1195     if (!frame_0_sp)
1196       return {};
1197     if (!frame_0_sp->IsInlined())
1198       return {};
1199     Block *block_ptr = frame_0_sp->GetFrameBlock();
1200     if (!block_ptr)
1201       return {};
1202     Address pc_address = frame_0_sp->GetFrameCodeAddress();
1203     AddressRange containing_range;
1204     if (!block_ptr->GetRangeContainingAddress(pc_address, containing_range) ||
1205         pc_address != containing_range.GetBaseAddress())
1206       return {};
1207 
1208     int num_inlined_functions = 0;
1209 
1210     for (Block *container_ptr = block_ptr->GetInlinedParent();
1211          container_ptr != nullptr;
1212          container_ptr = container_ptr->GetInlinedParent()) {
1213       if (!container_ptr->GetRangeContainingAddress(pc_address,
1214                                                     containing_range))
1215         break;
1216       if (pc_address != containing_range.GetBaseAddress())
1217         break;
1218 
1219       num_inlined_functions++;
1220     }
1221     inlined_stack = true;
1222     return num_inlined_functions + 1;
1223   }
1224 };
1225 
1226 // StopInfoException
1227 
1228 class StopInfoException : public StopInfo {
1229 public:
1230   StopInfoException(Thread &thread, const char *description)
1231       : StopInfo(thread, LLDB_INVALID_UID) {
1232     if (description)
1233       SetDescription(description);
1234   }
1235 
1236   ~StopInfoException() override = default;
1237 
1238   StopReason GetStopReason() const override { return eStopReasonException; }
1239 
1240   const char *GetDescription() override {
1241     if (m_description.empty())
1242       return "exception";
1243     else
1244       return m_description.c_str();
1245   }
1246 };
1247 
1248 // StopInfoProcessorTrace
1249 
1250 class StopInfoProcessorTrace : public StopInfo {
1251 public:
1252   StopInfoProcessorTrace(Thread &thread, const char *description)
1253       : StopInfo(thread, LLDB_INVALID_UID) {
1254     if (description)
1255       SetDescription(description);
1256   }
1257 
1258   ~StopInfoProcessorTrace() override = default;
1259 
1260   StopReason GetStopReason() const override {
1261     return eStopReasonProcessorTrace;
1262   }
1263 
1264   const char *GetDescription() override {
1265     if (m_description.empty())
1266       return "processor trace event";
1267     else
1268       return m_description.c_str();
1269   }
1270 };
1271 
1272 // StopInfoThreadPlan
1273 
1274 class StopInfoThreadPlan : public StopInfo {
1275 public:
1276   StopInfoThreadPlan(ThreadPlanSP &plan_sp, ValueObjectSP &return_valobj_sp,
1277                      ExpressionVariableSP &expression_variable_sp)
1278       : StopInfo(plan_sp->GetThread(), LLDB_INVALID_UID), m_plan_sp(plan_sp),
1279         m_return_valobj_sp(return_valobj_sp),
1280         m_expression_variable_sp(expression_variable_sp) {}
1281 
1282   ~StopInfoThreadPlan() override = default;
1283 
1284   StopReason GetStopReason() const override { return eStopReasonPlanComplete; }
1285 
1286   const char *GetDescription() override {
1287     if (m_description.empty()) {
1288       StreamString strm;
1289       m_plan_sp->GetDescription(&strm, eDescriptionLevelBrief);
1290       m_description = std::string(strm.GetString());
1291     }
1292     return m_description.c_str();
1293   }
1294 
1295   ValueObjectSP GetReturnValueObject() { return m_return_valobj_sp; }
1296 
1297   ExpressionVariableSP GetExpressionVariable() {
1298     return m_expression_variable_sp;
1299   }
1300 
1301 protected:
1302   bool ShouldStop(Event *event_ptr) override {
1303     if (m_plan_sp)
1304       return m_plan_sp->ShouldStop(event_ptr);
1305     else
1306       return StopInfo::ShouldStop(event_ptr);
1307   }
1308 
1309 private:
1310   ThreadPlanSP m_plan_sp;
1311   ValueObjectSP m_return_valobj_sp;
1312   ExpressionVariableSP m_expression_variable_sp;
1313 };
1314 
1315 // StopInfoExec
1316 
1317 class StopInfoExec : public StopInfo {
1318 public:
1319   StopInfoExec(Thread &thread) : StopInfo(thread, LLDB_INVALID_UID) {}
1320 
1321   ~StopInfoExec() override = default;
1322 
1323   bool ShouldStop(Event *event_ptr) override {
1324     ThreadSP thread_sp(m_thread_wp.lock());
1325     if (thread_sp)
1326       return thread_sp->GetProcess()->GetStopOnExec();
1327     return false;
1328   }
1329 
1330   StopReason GetStopReason() const override { return eStopReasonExec; }
1331 
1332   const char *GetDescription() override { return "exec"; }
1333 
1334 protected:
1335   void PerformAction(Event *event_ptr) override {
1336     // Only perform the action once
1337     if (m_performed_action)
1338       return;
1339     m_performed_action = true;
1340     ThreadSP thread_sp(m_thread_wp.lock());
1341     if (thread_sp)
1342       thread_sp->GetProcess()->DidExec();
1343   }
1344 
1345   bool m_performed_action = false;
1346 };
1347 
1348 // StopInfoFork
1349 
1350 class StopInfoFork : public StopInfo {
1351 public:
1352   StopInfoFork(Thread &thread, lldb::pid_t child_pid, lldb::tid_t child_tid)
1353       : StopInfo(thread, child_pid), m_child_pid(child_pid),
1354         m_child_tid(child_tid) {}
1355 
1356   ~StopInfoFork() override = default;
1357 
1358   bool ShouldStop(Event *event_ptr) override { return false; }
1359 
1360   StopReason GetStopReason() const override { return eStopReasonFork; }
1361 
1362   const char *GetDescription() override { return "fork"; }
1363 
1364 protected:
1365   void PerformAction(Event *event_ptr) override {
1366     // Only perform the action once
1367     if (m_performed_action)
1368       return;
1369     m_performed_action = true;
1370     ThreadSP thread_sp(m_thread_wp.lock());
1371     if (thread_sp)
1372       thread_sp->GetProcess()->DidFork(m_child_pid, m_child_tid);
1373   }
1374 
1375   bool m_performed_action = false;
1376 
1377 private:
1378   lldb::pid_t m_child_pid;
1379   lldb::tid_t m_child_tid;
1380 };
1381 
1382 // StopInfoVFork
1383 
1384 class StopInfoVFork : public StopInfo {
1385 public:
1386   StopInfoVFork(Thread &thread, lldb::pid_t child_pid, lldb::tid_t child_tid)
1387       : StopInfo(thread, child_pid), m_child_pid(child_pid),
1388         m_child_tid(child_tid) {}
1389 
1390   ~StopInfoVFork() override = default;
1391 
1392   bool ShouldStop(Event *event_ptr) override { return false; }
1393 
1394   StopReason GetStopReason() const override { return eStopReasonVFork; }
1395 
1396   const char *GetDescription() override { return "vfork"; }
1397 
1398 protected:
1399   void PerformAction(Event *event_ptr) override {
1400     // Only perform the action once
1401     if (m_performed_action)
1402       return;
1403     m_performed_action = true;
1404     ThreadSP thread_sp(m_thread_wp.lock());
1405     if (thread_sp)
1406       thread_sp->GetProcess()->DidVFork(m_child_pid, m_child_tid);
1407   }
1408 
1409   bool m_performed_action = false;
1410 
1411 private:
1412   lldb::pid_t m_child_pid;
1413   lldb::tid_t m_child_tid;
1414 };
1415 
1416 // StopInfoVForkDone
1417 
1418 class StopInfoVForkDone : public StopInfo {
1419 public:
1420   StopInfoVForkDone(Thread &thread) : StopInfo(thread, 0) {}
1421 
1422   ~StopInfoVForkDone() override = default;
1423 
1424   bool ShouldStop(Event *event_ptr) override { return false; }
1425 
1426   StopReason GetStopReason() const override { return eStopReasonVForkDone; }
1427 
1428   const char *GetDescription() override { return "vforkdone"; }
1429 
1430 protected:
1431   void PerformAction(Event *event_ptr) override {
1432     // Only perform the action once
1433     if (m_performed_action)
1434       return;
1435     m_performed_action = true;
1436     ThreadSP thread_sp(m_thread_wp.lock());
1437     if (thread_sp)
1438       thread_sp->GetProcess()->DidVForkDone();
1439   }
1440 
1441   bool m_performed_action = false;
1442 };
1443 
1444 } // namespace lldb_private
1445 
1446 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
1447                                                           break_id_t break_id) {
1448   return StopInfoSP(new StopInfoBreakpoint(thread, break_id));
1449 }
1450 
1451 StopInfoSP StopInfo::CreateStopReasonWithBreakpointSiteID(Thread &thread,
1452                                                           break_id_t break_id,
1453                                                           bool should_stop) {
1454   return StopInfoSP(new StopInfoBreakpoint(thread, break_id, should_stop));
1455 }
1456 
1457 // LWP_TODO: We'll need a CreateStopReasonWithWatchpointResourceID akin
1458 // to CreateStopReasonWithBreakpointSiteID
1459 StopInfoSP StopInfo::CreateStopReasonWithWatchpointID(Thread &thread,
1460                                                       break_id_t watch_id,
1461                                                       bool silently_continue) {
1462   return StopInfoSP(
1463       new StopInfoWatchpoint(thread, watch_id, silently_continue));
1464 }
1465 
1466 StopInfoSP StopInfo::CreateStopReasonWithSignal(Thread &thread, int signo,
1467                                                 const char *description,
1468                                                 std::optional<int> code) {
1469   thread.GetProcess()->GetUnixSignals()->IncrementSignalHitCount(signo);
1470   return StopInfoSP(new StopInfoUnixSignal(thread, signo, description, code));
1471 }
1472 
1473 StopInfoSP StopInfo::CreateStopReasonWithInterrupt(Thread &thread, int signo,
1474                                                    const char *description) {
1475   return StopInfoSP(new StopInfoInterrupt(thread, signo, description));
1476 }
1477 
1478 StopInfoSP StopInfo::CreateStopReasonToTrace(Thread &thread) {
1479   return StopInfoSP(new StopInfoTrace(thread));
1480 }
1481 
1482 StopInfoSP StopInfo::CreateStopReasonWithPlan(
1483     ThreadPlanSP &plan_sp, ValueObjectSP return_valobj_sp,
1484     ExpressionVariableSP expression_variable_sp) {
1485   return StopInfoSP(new StopInfoThreadPlan(plan_sp, return_valobj_sp,
1486                                            expression_variable_sp));
1487 }
1488 
1489 StopInfoSP StopInfo::CreateStopReasonWithException(Thread &thread,
1490                                                    const char *description) {
1491   return StopInfoSP(new StopInfoException(thread, description));
1492 }
1493 
1494 StopInfoSP StopInfo::CreateStopReasonProcessorTrace(Thread &thread,
1495                                                     const char *description) {
1496   return StopInfoSP(new StopInfoProcessorTrace(thread, description));
1497 }
1498 
1499 StopInfoSP StopInfo::CreateStopReasonWithExec(Thread &thread) {
1500   return StopInfoSP(new StopInfoExec(thread));
1501 }
1502 
1503 StopInfoSP StopInfo::CreateStopReasonFork(Thread &thread,
1504                                           lldb::pid_t child_pid,
1505                                           lldb::tid_t child_tid) {
1506   return StopInfoSP(new StopInfoFork(thread, child_pid, child_tid));
1507 }
1508 
1509 
1510 StopInfoSP StopInfo::CreateStopReasonVFork(Thread &thread,
1511                                            lldb::pid_t child_pid,
1512                                            lldb::tid_t child_tid) {
1513   return StopInfoSP(new StopInfoVFork(thread, child_pid, child_tid));
1514 }
1515 
1516 StopInfoSP StopInfo::CreateStopReasonVForkDone(Thread &thread) {
1517   return StopInfoSP(new StopInfoVForkDone(thread));
1518 }
1519 
1520 ValueObjectSP StopInfo::GetReturnValueObject(StopInfoSP &stop_info_sp) {
1521   if (stop_info_sp &&
1522       stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
1523     StopInfoThreadPlan *plan_stop_info =
1524         static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1525     return plan_stop_info->GetReturnValueObject();
1526   } else
1527     return ValueObjectSP();
1528 }
1529 
1530 ExpressionVariableSP StopInfo::GetExpressionVariable(StopInfoSP &stop_info_sp) {
1531   if (stop_info_sp &&
1532       stop_info_sp->GetStopReason() == eStopReasonPlanComplete) {
1533     StopInfoThreadPlan *plan_stop_info =
1534         static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1535     return plan_stop_info->GetExpressionVariable();
1536   } else
1537     return ExpressionVariableSP();
1538 }
1539 
1540 lldb::ValueObjectSP
1541 StopInfo::GetCrashingDereference(StopInfoSP &stop_info_sp,
1542                                  lldb::addr_t *crashing_address) {
1543   if (!stop_info_sp) {
1544     return ValueObjectSP();
1545   }
1546 
1547   const char *description = stop_info_sp->GetDescription();
1548   if (!description) {
1549     return ValueObjectSP();
1550   }
1551 
1552   ThreadSP thread_sp = stop_info_sp->GetThread();
1553   if (!thread_sp) {
1554     return ValueObjectSP();
1555   }
1556 
1557   StackFrameSP frame_sp =
1558       thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
1559 
1560   if (!frame_sp) {
1561     return ValueObjectSP();
1562   }
1563 
1564   const char address_string[] = "address=";
1565 
1566   const char *address_loc = strstr(description, address_string);
1567   if (!address_loc) {
1568     return ValueObjectSP();
1569   }
1570 
1571   address_loc += (sizeof(address_string) - 1);
1572 
1573   uint64_t address = strtoull(address_loc, nullptr, 0);
1574   if (crashing_address) {
1575     *crashing_address = address;
1576   }
1577 
1578   return frame_sp->GuessValueForAddress(address);
1579 }
1580