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