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