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