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