1 //===-- Watchpoint.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 "lldb/Breakpoint/Watchpoint.h"
10
11 #include "lldb/Breakpoint/StoppointCallbackContext.h"
12 #include "lldb/Breakpoint/WatchpointResource.h"
13 #include "lldb/Core/Value.h"
14 #include "lldb/Core/ValueObject.h"
15 #include "lldb/Core/ValueObjectMemory.h"
16 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
17 #include "lldb/Expression/UserExpression.h"
18 #include "lldb/Symbol/TypeSystem.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/ThreadSpec.h"
22 #include "lldb/Utility/LLDBLog.h"
23 #include "lldb/Utility/Log.h"
24 #include "lldb/Utility/Stream.h"
25
26 using namespace lldb;
27 using namespace lldb_private;
28
Watchpoint(Target & target,lldb::addr_t addr,uint32_t size,const CompilerType * type,bool hardware)29 Watchpoint::Watchpoint(Target &target, lldb::addr_t addr, uint32_t size,
30 const CompilerType *type, bool hardware)
31 : StoppointSite(0, addr, size, hardware), m_target(target),
32 m_enabled(false), m_is_hardware(hardware), m_is_watch_variable(false),
33 m_is_ephemeral(false), m_disabled_count(0), m_watch_read(0),
34 m_watch_write(0), m_watch_modify(0), m_ignore_count(0),
35 m_being_created(true) {
36
37 if (type && type->IsValid())
38 m_type = *type;
39 else {
40 // If we don't have a known type, then we force it to unsigned int of the
41 // right size.
42 auto type_system_or_err =
43 target.GetScratchTypeSystemForLanguage(eLanguageTypeC);
44 if (auto err = type_system_or_err.takeError()) {
45 LLDB_LOG_ERROR(GetLog(LLDBLog::Watchpoints), std::move(err),
46 "Failed to set type: {0}");
47 } else {
48 if (auto ts = *type_system_or_err)
49 m_type =
50 ts->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 8 * size);
51 else
52 LLDB_LOG_ERROR(GetLog(LLDBLog::Watchpoints), std::move(err),
53 "Failed to set type: Typesystem is no longer live: {0}");
54 }
55 }
56
57 // Set the initial value of the watched variable:
58 if (m_target.GetProcessSP()) {
59 ExecutionContext exe_ctx;
60 m_target.GetProcessSP()->CalculateExecutionContext(exe_ctx);
61 CaptureWatchedValue(exe_ctx);
62 }
63 m_being_created = false;
64 }
65
66 Watchpoint::~Watchpoint() = default;
67
68 // This function is used when "baton" doesn't need to be freed
SetCallback(WatchpointHitCallback callback,void * baton,bool is_synchronous)69 void Watchpoint::SetCallback(WatchpointHitCallback callback, void *baton,
70 bool is_synchronous) {
71 // The default "Baton" class will keep a copy of "baton" and won't free or
72 // delete it when it goes out of scope.
73 m_options.SetCallback(callback, std::make_shared<UntypedBaton>(baton),
74 is_synchronous);
75
76 SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged);
77 }
78
79 // This function is used when a baton needs to be freed and therefore is
80 // contained in a "Baton" subclass.
SetCallback(WatchpointHitCallback callback,const BatonSP & callback_baton_sp,bool is_synchronous)81 void Watchpoint::SetCallback(WatchpointHitCallback callback,
82 const BatonSP &callback_baton_sp,
83 bool is_synchronous) {
84 m_options.SetCallback(callback, callback_baton_sp, is_synchronous);
85 SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged);
86 }
87
SetupVariableWatchpointDisabler(StackFrameSP frame_sp) const88 bool Watchpoint::SetupVariableWatchpointDisabler(StackFrameSP frame_sp) const {
89 if (!frame_sp)
90 return false;
91
92 ThreadSP thread_sp = frame_sp->GetThread();
93 if (!thread_sp)
94 return false;
95
96 uint32_t return_frame_index =
97 thread_sp->GetSelectedFrameIndex(DoNoSelectMostRelevantFrame) + 1;
98 if (return_frame_index >= LLDB_INVALID_FRAME_ID)
99 return false;
100
101 StackFrameSP return_frame_sp(
102 thread_sp->GetStackFrameAtIndex(return_frame_index));
103 if (!return_frame_sp)
104 return false;
105
106 ExecutionContext exe_ctx(return_frame_sp);
107 TargetSP target_sp = exe_ctx.GetTargetSP();
108 if (!target_sp)
109 return false;
110
111 Address return_address(return_frame_sp->GetFrameCodeAddress());
112 lldb::addr_t return_addr = return_address.GetLoadAddress(target_sp.get());
113 if (return_addr == LLDB_INVALID_ADDRESS)
114 return false;
115
116 BreakpointSP bp_sp = target_sp->CreateBreakpoint(
117 return_addr, /*internal=*/true, /*request_hardware=*/false);
118 if (!bp_sp || !bp_sp->HasResolvedLocations())
119 return false;
120
121 auto wvc_up = std::make_unique<WatchpointVariableContext>(GetID(), exe_ctx);
122 auto baton_sp = std::make_shared<WatchpointVariableBaton>(std::move(wvc_up));
123 bp_sp->SetCallback(VariableWatchpointDisabler, baton_sp);
124 bp_sp->SetOneShot(true);
125 bp_sp->SetBreakpointKind("variable watchpoint disabler");
126 return true;
127 }
128
VariableWatchpointDisabler(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)129 bool Watchpoint::VariableWatchpointDisabler(void *baton,
130 StoppointCallbackContext *context,
131 user_id_t break_id,
132 user_id_t break_loc_id) {
133 assert(baton && "null baton");
134 if (!baton || !context)
135 return false;
136
137 Log *log = GetLog(LLDBLog::Watchpoints);
138
139 WatchpointVariableContext *wvc =
140 static_cast<WatchpointVariableContext *>(baton);
141
142 LLDB_LOGF(log, "called by breakpoint %" PRIu64 ".%" PRIu64, break_id,
143 break_loc_id);
144
145 if (wvc->watch_id == LLDB_INVALID_WATCH_ID)
146 return false;
147
148 TargetSP target_sp = context->exe_ctx_ref.GetTargetSP();
149 if (!target_sp)
150 return false;
151
152 ProcessSP process_sp = target_sp->GetProcessSP();
153 if (!process_sp)
154 return false;
155
156 WatchpointSP watch_sp =
157 target_sp->GetWatchpointList().FindByID(wvc->watch_id);
158 if (!watch_sp)
159 return false;
160
161 if (wvc->exe_ctx == context->exe_ctx_ref) {
162 LLDB_LOGF(log,
163 "callback for watchpoint %" PRId32
164 " matched internal breakpoint execution context",
165 watch_sp->GetID());
166 process_sp->DisableWatchpoint(watch_sp);
167 return false;
168 }
169 LLDB_LOGF(log,
170 "callback for watchpoint %" PRId32
171 " didn't match internal breakpoint execution context",
172 watch_sp->GetID());
173 return false;
174 }
175
ClearCallback()176 void Watchpoint::ClearCallback() {
177 m_options.ClearCallback();
178 SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged);
179 }
180
SetDeclInfo(const std::string & str)181 void Watchpoint::SetDeclInfo(const std::string &str) { m_decl_str = str; }
182
GetWatchSpec()183 std::string Watchpoint::GetWatchSpec() { return m_watch_spec_str; }
184
SetWatchSpec(const std::string & str)185 void Watchpoint::SetWatchSpec(const std::string &str) {
186 m_watch_spec_str = str;
187 }
188
IsHardware() const189 bool Watchpoint::IsHardware() const {
190 lldbassert(m_is_hardware || !HardwareRequired());
191 return m_is_hardware;
192 }
193
IsWatchVariable() const194 bool Watchpoint::IsWatchVariable() const { return m_is_watch_variable; }
195
SetWatchVariable(bool val)196 void Watchpoint::SetWatchVariable(bool val) { m_is_watch_variable = val; }
197
CaptureWatchedValue(const ExecutionContext & exe_ctx)198 bool Watchpoint::CaptureWatchedValue(const ExecutionContext &exe_ctx) {
199 ConstString g_watch_name("$__lldb__watch_value");
200 m_old_value_sp = m_new_value_sp;
201 Address watch_address(GetLoadAddress());
202 if (!m_type.IsValid()) {
203 // Don't know how to report new & old values, since we couldn't make a
204 // scalar type for this watchpoint. This works around an assert in
205 // ValueObjectMemory::Create.
206 // FIXME: This should not happen, but if it does in some case we care about,
207 // we can go grab the value raw and print it as unsigned.
208 return false;
209 }
210 m_new_value_sp = ValueObjectMemory::Create(
211 exe_ctx.GetBestExecutionContextScope(), g_watch_name.GetStringRef(),
212 watch_address, m_type);
213 m_new_value_sp = m_new_value_sp->CreateConstantValue(g_watch_name);
214 return (m_new_value_sp && m_new_value_sp->GetError().Success());
215 }
216
WatchedValueReportable(const ExecutionContext & exe_ctx)217 bool Watchpoint::WatchedValueReportable(const ExecutionContext &exe_ctx) {
218 if (!m_watch_modify || m_watch_read)
219 return true;
220 if (!m_type.IsValid())
221 return true;
222
223 ConstString g_watch_name("$__lldb__watch_value");
224 Address watch_address(GetLoadAddress());
225 ValueObjectSP newest_valueobj_sp = ValueObjectMemory::Create(
226 exe_ctx.GetBestExecutionContextScope(), g_watch_name.GetStringRef(),
227 watch_address, m_type);
228 newest_valueobj_sp = newest_valueobj_sp->CreateConstantValue(g_watch_name);
229 Status error;
230
231 DataExtractor new_data;
232 DataExtractor old_data;
233
234 newest_valueobj_sp->GetData(new_data, error);
235 if (error.Fail())
236 return true;
237 m_new_value_sp->GetData(old_data, error);
238 if (error.Fail())
239 return true;
240
241 if (new_data.GetByteSize() != old_data.GetByteSize() ||
242 new_data.GetByteSize() == 0)
243 return true;
244
245 if (memcmp(new_data.GetDataStart(), old_data.GetDataStart(),
246 old_data.GetByteSize()) == 0)
247 return false; // Value has not changed, user requested modify watchpoint
248
249 return true;
250 }
251
252 // RETURNS - true if we should stop at this breakpoint, false if we
253 // should continue.
254
ShouldStop(StoppointCallbackContext * context)255 bool Watchpoint::ShouldStop(StoppointCallbackContext *context) {
256 m_hit_counter.Increment();
257
258 return IsEnabled();
259 }
260
GetDescription(Stream * s,lldb::DescriptionLevel level)261 void Watchpoint::GetDescription(Stream *s, lldb::DescriptionLevel level) {
262 DumpWithLevel(s, level);
263 }
264
Dump(Stream * s) const265 void Watchpoint::Dump(Stream *s) const {
266 DumpWithLevel(s, lldb::eDescriptionLevelBrief);
267 }
268
269 // If prefix is nullptr, we display the watch id and ignore the prefix
270 // altogether.
DumpSnapshots(Stream * s,const char * prefix) const271 bool Watchpoint::DumpSnapshots(Stream *s, const char *prefix) const {
272 bool printed_anything = false;
273
274 // For read watchpoints, don't display any before/after value changes.
275 if (m_watch_read && !m_watch_modify && !m_watch_write)
276 return printed_anything;
277
278 s->Printf("\n");
279 s->Printf("Watchpoint %u hit:\n", GetID());
280
281 StreamString values_ss;
282 if (prefix)
283 values_ss.Indent(prefix);
284
285 if (m_old_value_sp) {
286 if (auto *old_value_cstr = m_old_value_sp->GetValueAsCString()) {
287 values_ss.Printf("old value: %s", old_value_cstr);
288 } else {
289 if (auto *old_summary_cstr = m_old_value_sp->GetSummaryAsCString())
290 values_ss.Printf("old value: %s", old_summary_cstr);
291 else {
292 StreamString strm;
293 DumpValueObjectOptions options;
294 options.SetUseDynamicType(eNoDynamicValues)
295 .SetHideRootType(true)
296 .SetHideRootName(true)
297 .SetHideName(true);
298 m_old_value_sp->Dump(strm, options);
299 if (strm.GetData())
300 values_ss.Printf("old value: %s", strm.GetData());
301 }
302 }
303 }
304
305 if (m_new_value_sp) {
306 if (values_ss.GetSize())
307 values_ss.Printf("\n");
308
309 if (auto *new_value_cstr = m_new_value_sp->GetValueAsCString())
310 values_ss.Printf("new value: %s", new_value_cstr);
311 else {
312 if (auto *new_summary_cstr = m_new_value_sp->GetSummaryAsCString())
313 values_ss.Printf("new value: %s", new_summary_cstr);
314 else {
315 StreamString strm;
316 DumpValueObjectOptions options;
317 options.SetUseDynamicType(eNoDynamicValues)
318 .SetHideRootType(true)
319 .SetHideRootName(true)
320 .SetHideName(true);
321 m_new_value_sp->Dump(strm, options);
322 if (strm.GetData())
323 values_ss.Printf("new value: %s", strm.GetData());
324 }
325 }
326 }
327
328 if (values_ss.GetSize()) {
329 s->Printf("%s", values_ss.GetData());
330 printed_anything = true;
331 }
332
333 return printed_anything;
334 }
335
DumpWithLevel(Stream * s,lldb::DescriptionLevel description_level) const336 void Watchpoint::DumpWithLevel(Stream *s,
337 lldb::DescriptionLevel description_level) const {
338 if (s == nullptr)
339 return;
340
341 assert(description_level >= lldb::eDescriptionLevelBrief &&
342 description_level <= lldb::eDescriptionLevelVerbose);
343
344 s->Printf("Watchpoint %u: addr = 0x%8.8" PRIx64
345 " size = %u state = %s type = %s%s%s",
346 GetID(), GetLoadAddress(), m_byte_size,
347 IsEnabled() ? "enabled" : "disabled", m_watch_read ? "r" : "",
348 m_watch_write ? "w" : "", m_watch_modify ? "m" : "");
349
350 if (description_level >= lldb::eDescriptionLevelFull) {
351 if (!m_decl_str.empty())
352 s->Printf("\n declare @ '%s'", m_decl_str.c_str());
353 if (!m_watch_spec_str.empty())
354 s->Printf("\n watchpoint spec = '%s'", m_watch_spec_str.c_str());
355
356 // Dump the snapshots we have taken.
357 DumpSnapshots(s, " ");
358
359 if (GetConditionText())
360 s->Printf("\n condition = '%s'", GetConditionText());
361 m_options.GetCallbackDescription(s, description_level);
362 }
363
364 if (description_level >= lldb::eDescriptionLevelVerbose) {
365 s->Printf("\n hit_count = %-4u ignore_count = %-4u", GetHitCount(),
366 GetIgnoreCount());
367 }
368 }
369
IsEnabled() const370 bool Watchpoint::IsEnabled() const { return m_enabled; }
371
372 // Within StopInfo.cpp, we purposely turn on the ephemeral mode right before
373 // temporarily disable the watchpoint in order to perform possible watchpoint
374 // actions without triggering further watchpoint events. After the temporary
375 // disabled watchpoint is enabled, we then turn off the ephemeral mode.
376
TurnOnEphemeralMode()377 void Watchpoint::TurnOnEphemeralMode() { m_is_ephemeral = true; }
378
TurnOffEphemeralMode()379 void Watchpoint::TurnOffEphemeralMode() {
380 m_is_ephemeral = false;
381 // Leaving ephemeral mode, reset the m_disabled_count!
382 m_disabled_count = 0;
383 }
384
IsDisabledDuringEphemeralMode()385 bool Watchpoint::IsDisabledDuringEphemeralMode() {
386 return m_disabled_count > 1 && m_is_ephemeral;
387 }
388
SetEnabled(bool enabled,bool notify)389 void Watchpoint::SetEnabled(bool enabled, bool notify) {
390 if (!enabled) {
391 if (m_is_ephemeral)
392 ++m_disabled_count;
393
394 // Don't clear the snapshots for now.
395 // Within StopInfo.cpp, we purposely do disable/enable watchpoint while
396 // performing watchpoint actions.
397 }
398 bool changed = enabled != m_enabled;
399 m_enabled = enabled;
400 if (notify && !m_is_ephemeral && changed)
401 SendWatchpointChangedEvent(enabled ? eWatchpointEventTypeEnabled
402 : eWatchpointEventTypeDisabled);
403 }
404
SetWatchpointType(uint32_t type,bool notify)405 void Watchpoint::SetWatchpointType(uint32_t type, bool notify) {
406 int old_watch_read = m_watch_read;
407 int old_watch_write = m_watch_write;
408 int old_watch_modify = m_watch_modify;
409 m_watch_read = (type & LLDB_WATCH_TYPE_READ) != 0;
410 m_watch_write = (type & LLDB_WATCH_TYPE_WRITE) != 0;
411 m_watch_modify = (type & LLDB_WATCH_TYPE_MODIFY) != 0;
412 if (notify &&
413 (old_watch_read != m_watch_read || old_watch_write != m_watch_write ||
414 old_watch_modify != m_watch_modify))
415 SendWatchpointChangedEvent(eWatchpointEventTypeTypeChanged);
416 }
417
WatchpointRead() const418 bool Watchpoint::WatchpointRead() const { return m_watch_read != 0; }
419
WatchpointWrite() const420 bool Watchpoint::WatchpointWrite() const { return m_watch_write != 0; }
421
WatchpointModify() const422 bool Watchpoint::WatchpointModify() const { return m_watch_modify != 0; }
423
GetIgnoreCount() const424 uint32_t Watchpoint::GetIgnoreCount() const { return m_ignore_count; }
425
SetIgnoreCount(uint32_t n)426 void Watchpoint::SetIgnoreCount(uint32_t n) {
427 bool changed = m_ignore_count != n;
428 m_ignore_count = n;
429 if (changed)
430 SendWatchpointChangedEvent(eWatchpointEventTypeIgnoreChanged);
431 }
432
InvokeCallback(StoppointCallbackContext * context)433 bool Watchpoint::InvokeCallback(StoppointCallbackContext *context) {
434 return m_options.InvokeCallback(context, GetID());
435 }
436
SetCondition(const char * condition)437 void Watchpoint::SetCondition(const char *condition) {
438 if (condition == nullptr || condition[0] == '\0') {
439 if (m_condition_up)
440 m_condition_up.reset();
441 } else {
442 // Pass nullptr for expr_prefix (no translation-unit level definitions).
443 Status error;
444 m_condition_up.reset(m_target.GetUserExpressionForLanguage(
445 condition, llvm::StringRef(), lldb::eLanguageTypeUnknown,
446 UserExpression::eResultTypeAny, EvaluateExpressionOptions(), nullptr,
447 error));
448 if (error.Fail()) {
449 // FIXME: Log something...
450 m_condition_up.reset();
451 }
452 }
453 SendWatchpointChangedEvent(eWatchpointEventTypeConditionChanged);
454 }
455
GetConditionText() const456 const char *Watchpoint::GetConditionText() const {
457 if (m_condition_up)
458 return m_condition_up->GetUserText();
459 else
460 return nullptr;
461 }
462
SendWatchpointChangedEvent(lldb::WatchpointEventType eventKind)463 void Watchpoint::SendWatchpointChangedEvent(
464 lldb::WatchpointEventType eventKind) {
465 if (!m_being_created && GetTarget().EventTypeHasListeners(
466 Target::eBroadcastBitWatchpointChanged)) {
467 auto data_sp =
468 std::make_shared<WatchpointEventData>(eventKind, shared_from_this());
469 GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data_sp);
470 }
471 }
472
WatchpointEventData(WatchpointEventType sub_type,const WatchpointSP & new_watchpoint_sp)473 Watchpoint::WatchpointEventData::WatchpointEventData(
474 WatchpointEventType sub_type, const WatchpointSP &new_watchpoint_sp)
475 : m_watchpoint_event(sub_type), m_new_watchpoint_sp(new_watchpoint_sp) {}
476
477 Watchpoint::WatchpointEventData::~WatchpointEventData() = default;
478
GetFlavorString()479 llvm::StringRef Watchpoint::WatchpointEventData::GetFlavorString() {
480 return "Watchpoint::WatchpointEventData";
481 }
482
GetFlavor() const483 llvm::StringRef Watchpoint::WatchpointEventData::GetFlavor() const {
484 return WatchpointEventData::GetFlavorString();
485 }
486
GetWatchpoint()487 WatchpointSP &Watchpoint::WatchpointEventData::GetWatchpoint() {
488 return m_new_watchpoint_sp;
489 }
490
491 WatchpointEventType
GetWatchpointEventType() const492 Watchpoint::WatchpointEventData::GetWatchpointEventType() const {
493 return m_watchpoint_event;
494 }
495
Dump(Stream * s) const496 void Watchpoint::WatchpointEventData::Dump(Stream *s) const {}
497
498 const Watchpoint::WatchpointEventData *
GetEventDataFromEvent(const Event * event)499 Watchpoint::WatchpointEventData::GetEventDataFromEvent(const Event *event) {
500 if (event) {
501 const EventData *event_data = event->GetData();
502 if (event_data &&
503 event_data->GetFlavor() == WatchpointEventData::GetFlavorString())
504 return static_cast<const WatchpointEventData *>(event->GetData());
505 }
506 return nullptr;
507 }
508
509 WatchpointEventType
GetWatchpointEventTypeFromEvent(const EventSP & event_sp)510 Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent(
511 const EventSP &event_sp) {
512 const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get());
513
514 if (data == nullptr)
515 return eWatchpointEventTypeInvalidType;
516 else
517 return data->GetWatchpointEventType();
518 }
519
GetWatchpointFromEvent(const EventSP & event_sp)520 WatchpointSP Watchpoint::WatchpointEventData::GetWatchpointFromEvent(
521 const EventSP &event_sp) {
522 WatchpointSP wp_sp;
523
524 const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get());
525 if (data)
526 wp_sp = data->m_new_watchpoint_sp;
527
528 return wp_sp;
529 }
530