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