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