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