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