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                                     continue;
483                             }
484                         }
485 
486                         bool callback_says_stop;
487 
488                         // FIXME: For now the callbacks have to run in async mode - the first time we restart we need
489                         // to get out of there.  So set it here.
490                         // When we figure out how to nest breakpoint hits then this will change.
491 
492                         Debugger &debugger = thread_sp->CalculateTarget()->GetDebugger();
493                         bool old_async = debugger.GetAsyncExecution();
494                         debugger.SetAsyncExecution (true);
495 
496                         callback_says_stop = bp_loc_sp->InvokeCallback (&context);
497 
498                         debugger.SetAsyncExecution (old_async);
499 
500                         if (callback_says_stop)
501                             m_should_stop = true;
502 
503                         // If we are going to stop for this breakpoint, then remove the breakpoint.
504                         if (callback_says_stop && bp_loc_sp && bp_loc_sp->GetBreakpoint().IsOneShot())
505                         {
506                             thread_sp->GetProcess()->GetTarget().RemoveBreakpointByID (bp_loc_sp->GetBreakpoint().GetID());
507                         }
508 
509                         // Also make sure that the callback hasn't continued the target.
510                         // If it did, when we'll set m_should_start to false and get out of here.
511                         if (HasTargetRunSinceMe ())
512                         {
513                             m_should_stop = false;
514                             break;
515                         }
516                     }
517                 }
518                 // We've figured out what this stop wants to do, so mark it as valid so we don't compute it again.
519                 m_should_stop_is_valid = true;
520 
521             }
522             else
523             {
524                 m_should_stop = true;
525                 m_should_stop_is_valid = true;
526                 Log * log_process(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
527 
528                 if (log_process)
529                     log_process->Printf ("Process::%s could not find breakpoint site id: %" PRId64 "...", __FUNCTION__, m_value);
530             }
531             if (log)
532                 log->Printf ("Process::%s returning from action with m_should_stop: %d.", __FUNCTION__, m_should_stop);
533         }
534     }
535 
536 private:
537     std::string m_description;
538     bool m_should_stop;
539     bool m_should_stop_is_valid;
540     bool m_should_perform_action; // Since we are trying to preserve the "state" of the system even if we run functions
541                                   // etc. behind the users backs, we need to make sure we only REALLY perform the action once.
542     lldb::addr_t m_address;       // We use this to capture the breakpoint site address when we create the StopInfo,
543                                   // in case somebody deletes it between the time the StopInfo is made and the
544                                   // description is asked for.
545     lldb::break_id_t m_break_id;
546     bool m_was_one_shot;
547 };
548 
549 
550 //----------------------------------------------------------------------
551 // StopInfoWatchpoint
552 //----------------------------------------------------------------------
553 
554 class StopInfoWatchpoint : public StopInfo
555 {
556 public:
557     // Make sure watchpoint is properly disabled and subsequently enabled while performing watchpoint actions.
558     class WatchpointSentry {
559     public:
560         WatchpointSentry(Process *p, Watchpoint *w):
561             process(p),
562             watchpoint(w)
563         {
564             if (process && watchpoint)
565             {
566                 const bool notify = false;
567                 watchpoint->TurnOnEphemeralMode();
568                 process->DisableWatchpoint(watchpoint, notify);
569             }
570         }
571         ~WatchpointSentry()
572         {
573             if (process && watchpoint)
574             {
575                 if (!watchpoint->IsDisabledDuringEphemeralMode())
576                 {
577                     const bool notify = false;
578                     process->EnableWatchpoint(watchpoint, notify);
579                 }
580                 watchpoint->TurnOffEphemeralMode();
581             }
582         }
583     private:
584         Process *process;
585         Watchpoint *watchpoint;
586     };
587 
588     StopInfoWatchpoint (Thread &thread, break_id_t watch_id) :
589         StopInfo(thread, watch_id),
590         m_description(),
591         m_should_stop(false),
592         m_should_stop_is_valid(false)
593     {
594     }
595 
596     virtual ~StopInfoWatchpoint ()
597     {
598     }
599 
600     virtual StopReason
601     GetStopReason () const
602     {
603         return eStopReasonWatchpoint;
604     }
605 
606     virtual const char *
607     GetDescription ()
608     {
609         if (m_description.empty())
610         {
611             StreamString strm;
612             strm.Printf("watchpoint %" PRIi64, m_value);
613             m_description.swap (strm.GetString());
614         }
615         return m_description.c_str();
616     }
617 
618 protected:
619     virtual bool
620     ShouldStopSynchronous (Event *event_ptr)
621     {
622         // ShouldStop() method is idempotent and should not affect hit count.
623         // See Process::RunPrivateStateThread()->Process()->HandlePrivateEvent()
624         // -->Process()::ShouldBroadcastEvent()->ThreadList::ShouldStop()->
625         // Thread::ShouldStop()->ThreadPlanBase::ShouldStop()->
626         // StopInfoWatchpoint::ShouldStop() and
627         // Event::DoOnRemoval()->Process::ProcessEventData::DoOnRemoval()->
628         // StopInfoWatchpoint::PerformAction().
629         if (m_should_stop_is_valid)
630             return m_should_stop;
631 
632         ThreadSP thread_sp (m_thread_wp.lock());
633         if (thread_sp)
634         {
635             WatchpointSP wp_sp (thread_sp->CalculateTarget()->GetWatchpointList().FindByID(GetValue()));
636             if (wp_sp)
637             {
638                 // Check if we should stop at a watchpoint.
639                 ExecutionContext exe_ctx (thread_sp->GetStackFrameAtIndex(0));
640                 StoppointCallbackContext context (event_ptr, exe_ctx, true);
641                 m_should_stop = wp_sp->ShouldStop (&context);
642             }
643             else
644             {
645                 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
646 
647                 if (log)
648                     log->Printf ("Process::%s could not find watchpoint location id: %" PRId64 "...",
649                                  __FUNCTION__, GetValue());
650 
651                 m_should_stop = true;
652             }
653         }
654         m_should_stop_is_valid = true;
655         return m_should_stop;
656     }
657 
658     bool
659     ShouldStop (Event *event_ptr)
660     {
661         // This just reports the work done by PerformAction or the synchronous stop.  It should
662         // only ever get called after they have had a chance to run.
663         assert (m_should_stop_is_valid);
664         return m_should_stop;
665     }
666 
667     virtual void
668     PerformAction (Event *event_ptr)
669     {
670         Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS);
671         // We're going to calculate if we should stop or not in some way during the course of
672         // this code.  Also by default we're going to stop, so set that here.
673         m_should_stop = true;
674 
675         ThreadSP thread_sp (m_thread_wp.lock());
676         if (thread_sp)
677         {
678 
679             WatchpointSP wp_sp (thread_sp->CalculateTarget()->GetWatchpointList().FindByID(GetValue()));
680             if (wp_sp)
681             {
682                 ExecutionContext exe_ctx (thread_sp->GetStackFrameAtIndex(0));
683                 Process* process = exe_ctx.GetProcessPtr();
684 
685                 // This sentry object makes sure the current watchpoint is disabled while performing watchpoint actions,
686                 // and it is then enabled after we are finished.
687                 WatchpointSentry sentry(process, wp_sp.get());
688 
689                 {
690                     // check if this process is running on an architecture where watchpoints trigger
691                     // before the associated instruction runs. if so, disable the WP, single-step and then
692                     // re-enable the watchpoint
693                     if (process)
694                     {
695                         uint32_t num;
696                         bool wp_triggers_after;
697                         if (process->GetWatchpointSupportInfo(num, wp_triggers_after).Success())
698                         {
699                             if (!wp_triggers_after)
700                             {
701                                 StopInfoSP stored_stop_info_sp = thread_sp->GetStopInfo();
702                                 assert (stored_stop_info_sp.get() == this);
703 
704                                 ThreadPlanSP new_plan_sp(thread_sp->QueueThreadPlanForStepSingleInstruction(false, // step-over
705                                                                                                             false,     // abort_other_plans
706                                                                                                             true));    // stop_other_threads
707                                 new_plan_sp->SetIsMasterPlan (true);
708                                 new_plan_sp->SetOkayToDiscard (false);
709                                 new_plan_sp->SetPrivate (true);
710                                 process->GetThreadList().SetSelectedThreadByID (thread_sp->GetID());
711                                 process->ResumeSynchronous(NULL);
712                                 process->GetThreadList().SetSelectedThreadByID (thread_sp->GetID());
713                                 thread_sp->SetStopInfo(stored_stop_info_sp);
714                             }
715                         }
716                     }
717                 }
718 
719                 if (m_should_stop && wp_sp->GetConditionText() != NULL)
720                 {
721                     // We need to make sure the user sees any parse errors in their condition, so we'll hook the
722                     // constructor errors up to the debugger's Async I/O.
723                     ExpressionResults result_code;
724                     EvaluateExpressionOptions expr_options;
725                     expr_options.SetUnwindOnError(true);
726                     expr_options.SetIgnoreBreakpoints(true);
727                     ValueObjectSP result_value_sp;
728                     Error error;
729                     result_code = ClangUserExpression::Evaluate (exe_ctx,
730                                                                  expr_options,
731                                                                  wp_sp->GetConditionText(),
732                                                                  NULL,
733                                                                  result_value_sp,
734                                                                  error);
735                     if (result_code == eExpressionCompleted)
736                     {
737                         if (result_value_sp)
738                         {
739                             Scalar scalar_value;
740                             if (result_value_sp->ResolveValue (scalar_value))
741                             {
742                                 if (scalar_value.ULongLong(1) == 0)
743                                 {
744                                     // We have been vetoed.  This takes precedence over querying
745                                     // the watchpoint whether it should stop (aka ignore count and
746                                     // friends).  See also StopInfoWatchpoint::ShouldStop() as well
747                                     // as Process::ProcessEventData::DoOnRemoval().
748                                     m_should_stop = false;
749                                 }
750                                 else
751                                     m_should_stop = true;
752                                 if (log)
753                                     log->Printf("Condition successfully evaluated, result is %s.\n",
754                                                 m_should_stop ? "true" : "false");
755                             }
756                             else
757                             {
758                                 m_should_stop = true;
759                                 if (log)
760                                     log->Printf("Failed to get an integer result from the expression.");
761                             }
762                         }
763                     }
764                     else
765                     {
766                         Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
767                         StreamSP error_sp = debugger.GetAsyncErrorStream ();
768                         error_sp->Printf ("Stopped due to an error evaluating condition of watchpoint ");
769                         wp_sp->GetDescription (error_sp.get(), eDescriptionLevelBrief);
770                         error_sp->Printf (": \"%s\"",
771                                           wp_sp->GetConditionText());
772                         error_sp->EOL();
773                         const char *err_str = error.AsCString("<Unknown Error>");
774                         if (log)
775                             log->Printf("Error evaluating condition: \"%s\"\n", err_str);
776 
777                         error_sp->PutCString (err_str);
778                         error_sp->EOL();
779                         error_sp->Flush();
780                         // If the condition fails to be parsed or run, we should stop.
781                         m_should_stop = true;
782                     }
783                 }
784 
785                 // If the condition says to stop, we run the callback to further decide whether to stop.
786                 if (m_should_stop)
787                 {
788                     StoppointCallbackContext context (event_ptr, exe_ctx, false);
789                     bool stop_requested = wp_sp->InvokeCallback (&context);
790                     // Also make sure that the callback hasn't continued the target.
791                     // If it did, when we'll set m_should_stop to false and get out of here.
792                     if (HasTargetRunSinceMe ())
793                         m_should_stop = false;
794 
795                     if (m_should_stop && !stop_requested)
796                     {
797                         // We have been vetoed by the callback mechanism.
798                         m_should_stop = false;
799                     }
800                 }
801                 // Finally, if we are going to stop, print out the new & old values:
802                 if (m_should_stop)
803                 {
804                     wp_sp->CaptureWatchedValue(exe_ctx);
805 
806                     Debugger &debugger = exe_ctx.GetTargetRef().GetDebugger();
807                     StreamSP output_sp = debugger.GetAsyncOutputStream ();
808                     wp_sp->DumpSnapshots(output_sp.get());
809                     output_sp->EOL();
810                     output_sp->Flush();
811                 }
812 
813             }
814             else
815             {
816                 Log * log_process(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
817 
818                 if (log_process)
819                     log_process->Printf ("Process::%s could not find watchpoint id: %" PRId64 "...", __FUNCTION__, m_value);
820             }
821             if (log)
822                 log->Printf ("Process::%s returning from action with m_should_stop: %d.", __FUNCTION__, m_should_stop);
823 
824             m_should_stop_is_valid = true;
825         }
826     }
827 
828 private:
829     std::string m_description;
830     bool m_should_stop;
831     bool m_should_stop_is_valid;
832 };
833 
834 
835 
836 //----------------------------------------------------------------------
837 // StopInfoUnixSignal
838 //----------------------------------------------------------------------
839 
840 class StopInfoUnixSignal : public StopInfo
841 {
842 public:
843 
844     StopInfoUnixSignal (Thread &thread, int signo) :
845         StopInfo (thread, signo)
846     {
847     }
848 
849     virtual ~StopInfoUnixSignal ()
850     {
851     }
852 
853 
854     virtual StopReason
855     GetStopReason () const
856     {
857         return eStopReasonSignal;
858     }
859 
860     virtual bool
861     ShouldStopSynchronous (Event *event_ptr)
862     {
863         ThreadSP thread_sp (m_thread_wp.lock());
864         if (thread_sp)
865             return thread_sp->GetProcess()->GetUnixSignals().GetShouldStop (m_value);
866         return false;
867     }
868 
869     virtual bool
870     ShouldStop (Event *event_ptr)
871     {
872         ThreadSP thread_sp (m_thread_wp.lock());
873         if (thread_sp)
874             return thread_sp->GetProcess()->GetUnixSignals().GetShouldStop (m_value);
875         return false;
876     }
877 
878 
879     // If should stop returns false, check if we should notify of this event
880     virtual bool
881     DoShouldNotify (Event *event_ptr)
882     {
883         ThreadSP thread_sp (m_thread_wp.lock());
884         if (thread_sp)
885         {
886             bool should_notify = thread_sp->GetProcess()->GetUnixSignals().GetShouldNotify (m_value);
887             if (should_notify)
888             {
889                 StreamString strm;
890                 strm.Printf ("thread %d received signal: %s",
891                              thread_sp->GetIndexID(),
892                              thread_sp->GetProcess()->GetUnixSignals().GetSignalAsCString (m_value));
893                 Process::ProcessEventData::AddRestartedReason(event_ptr, strm.GetData());
894             }
895             return should_notify;
896         }
897         return true;
898     }
899 
900 
901     virtual void
902     WillResume (lldb::StateType resume_state)
903     {
904         ThreadSP thread_sp (m_thread_wp.lock());
905         if (thread_sp)
906         {
907             if (thread_sp->GetProcess()->GetUnixSignals().GetShouldSuppress(m_value) == false)
908                 thread_sp->SetResumeSignal(m_value);
909         }
910     }
911 
912     virtual const char *
913     GetDescription ()
914     {
915         if (m_description.empty())
916         {
917             ThreadSP thread_sp (m_thread_wp.lock());
918             if (thread_sp)
919             {
920                 StreamString strm;
921                 const char *signal_name = thread_sp->GetProcess()->GetUnixSignals().GetSignalAsCString (m_value);
922                 if (signal_name)
923                     strm.Printf("signal %s", signal_name);
924                 else
925                     strm.Printf("signal %" PRIi64, m_value);
926                 m_description.swap (strm.GetString());
927             }
928         }
929         return m_description.c_str();
930     }
931 };
932 
933 //----------------------------------------------------------------------
934 // StopInfoTrace
935 //----------------------------------------------------------------------
936 
937 class StopInfoTrace : public StopInfo
938 {
939 public:
940 
941     StopInfoTrace (Thread &thread) :
942         StopInfo (thread, LLDB_INVALID_UID)
943     {
944     }
945 
946     virtual ~StopInfoTrace ()
947     {
948     }
949 
950     virtual StopReason
951     GetStopReason () const
952     {
953         return eStopReasonTrace;
954     }
955 
956     virtual const char *
957     GetDescription ()
958     {
959         if (m_description.empty())
960         return "trace";
961         else
962             return m_description.c_str();
963     }
964 };
965 
966 
967 //----------------------------------------------------------------------
968 // StopInfoException
969 //----------------------------------------------------------------------
970 
971 class StopInfoException : public StopInfo
972 {
973 public:
974 
975     StopInfoException (Thread &thread, const char *description) :
976         StopInfo (thread, LLDB_INVALID_UID)
977     {
978         if (description)
979             SetDescription (description);
980     }
981 
982     virtual
983     ~StopInfoException ()
984     {
985     }
986 
987     virtual StopReason
988     GetStopReason () const
989     {
990         return eStopReasonException;
991     }
992 
993     virtual const char *
994     GetDescription ()
995     {
996         if (m_description.empty())
997             return "exception";
998         else
999             return m_description.c_str();
1000     }
1001 };
1002 
1003 
1004 //----------------------------------------------------------------------
1005 // StopInfoThreadPlan
1006 //----------------------------------------------------------------------
1007 
1008 class StopInfoThreadPlan : public StopInfo
1009 {
1010 public:
1011 
1012     StopInfoThreadPlan (ThreadPlanSP &plan_sp, ValueObjectSP &return_valobj_sp, ClangExpressionVariableSP &expression_variable_sp) :
1013         StopInfo (plan_sp->GetThread(), LLDB_INVALID_UID),
1014         m_plan_sp (plan_sp),
1015         m_return_valobj_sp (return_valobj_sp),
1016         m_expression_variable_sp (expression_variable_sp)
1017     {
1018     }
1019 
1020     virtual ~StopInfoThreadPlan ()
1021     {
1022     }
1023 
1024     virtual StopReason
1025     GetStopReason () const
1026     {
1027         return eStopReasonPlanComplete;
1028     }
1029 
1030     virtual const char *
1031     GetDescription ()
1032     {
1033         if (m_description.empty())
1034         {
1035             StreamString strm;
1036             m_plan_sp->GetDescription (&strm, eDescriptionLevelBrief);
1037             m_description.swap (strm.GetString());
1038         }
1039         return m_description.c_str();
1040     }
1041 
1042     ValueObjectSP
1043     GetReturnValueObject()
1044     {
1045         return m_return_valobj_sp;
1046     }
1047 
1048     ClangExpressionVariableSP
1049     GetExpressionVariable()
1050     {
1051         return m_expression_variable_sp;
1052     }
1053 
1054 protected:
1055     virtual bool
1056     ShouldStop (Event *event_ptr)
1057     {
1058         if (m_plan_sp)
1059             return m_plan_sp->ShouldStop(event_ptr);
1060         else
1061             return StopInfo::ShouldStop(event_ptr);
1062     }
1063 
1064 private:
1065     ThreadPlanSP m_plan_sp;
1066     ValueObjectSP m_return_valobj_sp;
1067     ClangExpressionVariableSP m_expression_variable_sp;
1068 };
1069 
1070 class StopInfoExec : public StopInfo
1071 {
1072 public:
1073 
1074     StopInfoExec (Thread &thread) :
1075         StopInfo (thread, LLDB_INVALID_UID),
1076         m_performed_action (false)
1077     {
1078     }
1079 
1080     virtual
1081     ~StopInfoExec ()
1082     {
1083     }
1084 
1085     virtual StopReason
1086     GetStopReason () const
1087     {
1088         return eStopReasonExec;
1089     }
1090 
1091     virtual const char *
1092     GetDescription ()
1093     {
1094         return "exec";
1095     }
1096 protected:
1097 
1098     virtual void
1099     PerformAction (Event *event_ptr)
1100     {
1101         // Only perform the action once
1102         if (m_performed_action)
1103             return;
1104         m_performed_action = true;
1105         ThreadSP thread_sp (m_thread_wp.lock());
1106         if (thread_sp)
1107             thread_sp->GetProcess()->DidExec();
1108     }
1109 
1110     bool m_performed_action;
1111 };
1112 
1113 } // namespace lldb_private
1114 
1115 StopInfoSP
1116 StopInfo::CreateStopReasonWithBreakpointSiteID (Thread &thread, break_id_t break_id)
1117 {
1118     return StopInfoSP (new StopInfoBreakpoint (thread, break_id));
1119 }
1120 
1121 StopInfoSP
1122 StopInfo::CreateStopReasonWithBreakpointSiteID (Thread &thread, break_id_t break_id, bool should_stop)
1123 {
1124     return StopInfoSP (new StopInfoBreakpoint (thread, break_id, should_stop));
1125 }
1126 
1127 StopInfoSP
1128 StopInfo::CreateStopReasonWithWatchpointID (Thread &thread, break_id_t watch_id)
1129 {
1130     return StopInfoSP (new StopInfoWatchpoint (thread, watch_id));
1131 }
1132 
1133 StopInfoSP
1134 StopInfo::CreateStopReasonWithSignal (Thread &thread, int signo)
1135 {
1136     return StopInfoSP (new StopInfoUnixSignal (thread, signo));
1137 }
1138 
1139 StopInfoSP
1140 StopInfo::CreateStopReasonToTrace (Thread &thread)
1141 {
1142     return StopInfoSP (new StopInfoTrace (thread));
1143 }
1144 
1145 StopInfoSP
1146 StopInfo::CreateStopReasonWithPlan (ThreadPlanSP &plan_sp,
1147                                     ValueObjectSP return_valobj_sp,
1148                                     ClangExpressionVariableSP expression_variable_sp)
1149 {
1150     return StopInfoSP (new StopInfoThreadPlan (plan_sp, return_valobj_sp, expression_variable_sp));
1151 }
1152 
1153 StopInfoSP
1154 StopInfo::CreateStopReasonWithException (Thread &thread, const char *description)
1155 {
1156     return StopInfoSP (new StopInfoException (thread, description));
1157 }
1158 
1159 StopInfoSP
1160 StopInfo::CreateStopReasonWithExec (Thread &thread)
1161 {
1162     return StopInfoSP (new StopInfoExec (thread));
1163 }
1164 
1165 ValueObjectSP
1166 StopInfo::GetReturnValueObject(StopInfoSP &stop_info_sp)
1167 {
1168     if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonPlanComplete)
1169     {
1170         StopInfoThreadPlan *plan_stop_info = static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1171         return plan_stop_info->GetReturnValueObject();
1172     }
1173     else
1174         return ValueObjectSP();
1175 }
1176 
1177 ClangExpressionVariableSP
1178 StopInfo::GetExpressionVariable(StopInfoSP &stop_info_sp)
1179 {
1180     if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonPlanComplete)
1181     {
1182         StopInfoThreadPlan *plan_stop_info = static_cast<StopInfoThreadPlan *>(stop_info_sp.get());
1183         return plan_stop_info->GetExpressionVariable();
1184     }
1185     else
1186         return ClangExpressionVariableSP();
1187 }
1188