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