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