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