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