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/Core/Value.h"
13 #include "lldb/Core/ValueObject.h"
14 #include "lldb/Core/ValueObjectMemory.h"
15 #include "lldb/Expression/UserExpression.h"
16 #include "lldb/Symbol/TypeSystem.h"
17 #include "lldb/Target/Process.h"
18 #include "lldb/Target/Target.h"
19 #include "lldb/Target/ThreadSpec.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/Stream.h"
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 Watchpoint::Watchpoint(Target &target, lldb::addr_t addr, uint32_t size,
27                        const CompilerType *type, bool hardware)
28     : StoppointLocation(0, addr, size, hardware), m_target(target),
29       m_enabled(false), m_is_hardware(hardware), m_is_watch_variable(false),
30       m_is_ephemeral(false), m_disabled_count(0), m_watch_read(0),
31       m_watch_write(0), m_watch_was_read(0), m_watch_was_written(0),
32       m_ignore_count(0), m_false_alarms(0), m_decl_str(), m_watch_spec_str(),
33       m_type(), m_error(), m_options(), m_being_created(true) {
34 
35   if (type && type->IsValid())
36     m_type = *type;
37   else {
38     // If we don't have a known type, then we force it to unsigned int of the
39     // right size.
40     auto type_system_or_err =
41         target.GetScratchTypeSystemForLanguage(eLanguageTypeC);
42     if (auto err = type_system_or_err.takeError()) {
43       LLDB_LOG_ERROR(
44           lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS),
45           std::move(err), "Failed to set type.");
46     } else {
47       m_type = type_system_or_err->GetBuiltinTypeForEncodingAndBitSize(
48           eEncodingUint, 8 * size);
49     }
50   }
51 
52   // Set the initial value of the watched variable:
53   if (m_target.GetProcessSP()) {
54     ExecutionContext exe_ctx;
55     m_target.GetProcessSP()->CalculateExecutionContext(exe_ctx);
56     CaptureWatchedValue(exe_ctx);
57   }
58   m_being_created = false;
59 }
60 
61 Watchpoint::~Watchpoint() = default;
62 
63 // This function is used when "baton" doesn't need to be freed
64 void Watchpoint::SetCallback(WatchpointHitCallback callback, void *baton,
65                              bool is_synchronous) {
66   // The default "Baton" class will keep a copy of "baton" and won't free or
67   // delete it when it goes goes out of scope.
68   m_options.SetCallback(callback, std::make_shared<UntypedBaton>(baton),
69                         is_synchronous);
70 
71   SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged);
72 }
73 
74 // This function is used when a baton needs to be freed and therefore is
75 // contained in a "Baton" subclass.
76 void Watchpoint::SetCallback(WatchpointHitCallback callback,
77                              const BatonSP &callback_baton_sp,
78                              bool is_synchronous) {
79   m_options.SetCallback(callback, callback_baton_sp, is_synchronous);
80   SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged);
81 }
82 
83 void Watchpoint::ClearCallback() {
84   m_options.ClearCallback();
85   SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged);
86 }
87 
88 void Watchpoint::SetDeclInfo(const std::string &str) { m_decl_str = str; }
89 
90 std::string Watchpoint::GetWatchSpec() { return m_watch_spec_str; }
91 
92 void Watchpoint::SetWatchSpec(const std::string &str) {
93   m_watch_spec_str = str;
94 }
95 
96 // Override default impl of StoppointLocation::IsHardware() since m_is_hardware
97 // member field is more accurate.
98 bool Watchpoint::IsHardware() const {
99   lldbassert(m_is_hardware || !HardwareRequired());
100   return m_is_hardware;
101 }
102 
103 bool Watchpoint::IsWatchVariable() const { return m_is_watch_variable; }
104 
105 void Watchpoint::SetWatchVariable(bool val) { m_is_watch_variable = val; }
106 
107 bool Watchpoint::CaptureWatchedValue(const ExecutionContext &exe_ctx) {
108   ConstString watch_name("$__lldb__watch_value");
109   m_old_value_sp = m_new_value_sp;
110   Address watch_address(GetLoadAddress());
111   if (!m_type.IsValid()) {
112     // Don't know how to report new & old values, since we couldn't make a
113     // scalar type for this watchpoint. This works around an assert in
114     // ValueObjectMemory::Create.
115     // FIXME: This should not happen, but if it does in some case we care about,
116     // we can go grab the value raw and print it as unsigned.
117     return false;
118   }
119   m_new_value_sp = ValueObjectMemory::Create(
120       exe_ctx.GetBestExecutionContextScope(), watch_name.GetStringRef(),
121       watch_address, m_type);
122   m_new_value_sp = m_new_value_sp->CreateConstantValue(watch_name);
123   return (m_new_value_sp && m_new_value_sp->GetError().Success());
124 }
125 
126 void Watchpoint::IncrementFalseAlarmsAndReviseHitCount() {
127   ++m_false_alarms;
128   if (m_false_alarms) {
129     if (m_hit_count >= m_false_alarms) {
130       m_hit_count -= m_false_alarms;
131       m_false_alarms = 0;
132     } else {
133       m_false_alarms -= m_hit_count;
134       m_hit_count = 0;
135     }
136   }
137 }
138 
139 // RETURNS - true if we should stop at this breakpoint, false if we
140 // should continue.
141 
142 bool Watchpoint::ShouldStop(StoppointCallbackContext *context) {
143   IncrementHitCount();
144 
145   return IsEnabled();
146 }
147 
148 void Watchpoint::GetDescription(Stream *s, lldb::DescriptionLevel level) {
149   DumpWithLevel(s, level);
150 }
151 
152 void Watchpoint::Dump(Stream *s) const {
153   DumpWithLevel(s, lldb::eDescriptionLevelBrief);
154 }
155 
156 // If prefix is nullptr, we display the watch id and ignore the prefix
157 // altogether.
158 void Watchpoint::DumpSnapshots(Stream *s, const char *prefix) const {
159   if (!prefix) {
160     s->Printf("\nWatchpoint %u hit:", GetID());
161     prefix = "";
162   }
163 
164   if (m_old_value_sp) {
165     const char *old_value_cstr = m_old_value_sp->GetValueAsCString();
166     if (old_value_cstr && old_value_cstr[0])
167       s->Printf("\n%sold value: %s", prefix, old_value_cstr);
168     else {
169       const char *old_summary_cstr = m_old_value_sp->GetSummaryAsCString();
170       if (old_summary_cstr && old_summary_cstr[0])
171         s->Printf("\n%sold value: %s", prefix, old_summary_cstr);
172     }
173   }
174 
175   if (m_new_value_sp) {
176     const char *new_value_cstr = m_new_value_sp->GetValueAsCString();
177     if (new_value_cstr && new_value_cstr[0])
178       s->Printf("\n%snew value: %s", prefix, new_value_cstr);
179     else {
180       const char *new_summary_cstr = m_new_value_sp->GetSummaryAsCString();
181       if (new_summary_cstr && new_summary_cstr[0])
182         s->Printf("\n%snew value: %s", prefix, new_summary_cstr);
183     }
184   }
185 }
186 
187 void Watchpoint::DumpWithLevel(Stream *s,
188                                lldb::DescriptionLevel description_level) const {
189   if (s == nullptr)
190     return;
191 
192   assert(description_level >= lldb::eDescriptionLevelBrief &&
193          description_level <= lldb::eDescriptionLevelVerbose);
194 
195   s->Printf("Watchpoint %u: addr = 0x%8.8" PRIx64
196             " size = %u state = %s type = %s%s",
197             GetID(), GetLoadAddress(), m_byte_size,
198             IsEnabled() ? "enabled" : "disabled", m_watch_read ? "r" : "",
199             m_watch_write ? "w" : "");
200 
201   if (description_level >= lldb::eDescriptionLevelFull) {
202     if (!m_decl_str.empty())
203       s->Printf("\n    declare @ '%s'", m_decl_str.c_str());
204     if (!m_watch_spec_str.empty())
205       s->Printf("\n    watchpoint spec = '%s'", m_watch_spec_str.c_str());
206 
207     // Dump the snapshots we have taken.
208     DumpSnapshots(s, "    ");
209 
210     if (GetConditionText())
211       s->Printf("\n    condition = '%s'", GetConditionText());
212     m_options.GetCallbackDescription(s, description_level);
213   }
214 
215   if (description_level >= lldb::eDescriptionLevelVerbose) {
216     s->Printf("\n    hw_index = %i  hit_count = %-4u  ignore_count = %-4u",
217               GetHardwareIndex(), GetHitCount(), GetIgnoreCount());
218   }
219 }
220 
221 bool Watchpoint::IsEnabled() const { return m_enabled; }
222 
223 // Within StopInfo.cpp, we purposely turn on the ephemeral mode right before
224 // temporarily disable the watchpoint in order to perform possible watchpoint
225 // actions without triggering further watchpoint events. After the temporary
226 // disabled watchpoint is enabled, we then turn off the ephemeral mode.
227 
228 void Watchpoint::TurnOnEphemeralMode() { m_is_ephemeral = true; }
229 
230 void Watchpoint::TurnOffEphemeralMode() {
231   m_is_ephemeral = false;
232   // Leaving ephemeral mode, reset the m_disabled_count!
233   m_disabled_count = 0;
234 }
235 
236 bool Watchpoint::IsDisabledDuringEphemeralMode() {
237   return m_disabled_count > 1 && m_is_ephemeral;
238 }
239 
240 void Watchpoint::SetEnabled(bool enabled, bool notify) {
241   if (!enabled) {
242     if (!m_is_ephemeral)
243       SetHardwareIndex(LLDB_INVALID_INDEX32);
244     else
245       ++m_disabled_count;
246 
247     // Don't clear the snapshots for now.
248     // Within StopInfo.cpp, we purposely do disable/enable watchpoint while
249     // performing watchpoint actions.
250   }
251   bool changed = enabled != m_enabled;
252   m_enabled = enabled;
253   if (notify && !m_is_ephemeral && changed)
254     SendWatchpointChangedEvent(enabled ? eWatchpointEventTypeEnabled
255                                        : eWatchpointEventTypeDisabled);
256 }
257 
258 void Watchpoint::SetWatchpointType(uint32_t type, bool notify) {
259   int old_watch_read = m_watch_read;
260   int old_watch_write = m_watch_write;
261   m_watch_read = (type & LLDB_WATCH_TYPE_READ) != 0;
262   m_watch_write = (type & LLDB_WATCH_TYPE_WRITE) != 0;
263   if (notify &&
264       (old_watch_read != m_watch_read || old_watch_write != m_watch_write))
265     SendWatchpointChangedEvent(eWatchpointEventTypeTypeChanged);
266 }
267 
268 bool Watchpoint::WatchpointRead() const { return m_watch_read != 0; }
269 
270 bool Watchpoint::WatchpointWrite() const { return m_watch_write != 0; }
271 
272 uint32_t Watchpoint::GetIgnoreCount() const { return m_ignore_count; }
273 
274 void Watchpoint::SetIgnoreCount(uint32_t n) {
275   bool changed = m_ignore_count != n;
276   m_ignore_count = n;
277   if (changed)
278     SendWatchpointChangedEvent(eWatchpointEventTypeIgnoreChanged);
279 }
280 
281 bool Watchpoint::InvokeCallback(StoppointCallbackContext *context) {
282   return m_options.InvokeCallback(context, GetID());
283 }
284 
285 void Watchpoint::SetCondition(const char *condition) {
286   if (condition == nullptr || condition[0] == '\0') {
287     if (m_condition_up)
288       m_condition_up.reset();
289   } else {
290     // Pass nullptr for expr_prefix (no translation-unit level definitions).
291     Status error;
292     m_condition_up.reset(m_target.GetUserExpressionForLanguage(
293         condition, llvm::StringRef(), lldb::eLanguageTypeUnknown,
294         UserExpression::eResultTypeAny, EvaluateExpressionOptions(), nullptr,
295         error));
296     if (error.Fail()) {
297       // FIXME: Log something...
298       m_condition_up.reset();
299     }
300   }
301   SendWatchpointChangedEvent(eWatchpointEventTypeConditionChanged);
302 }
303 
304 const char *Watchpoint::GetConditionText() const {
305   if (m_condition_up)
306     return m_condition_up->GetUserText();
307   else
308     return nullptr;
309 }
310 
311 void Watchpoint::SendWatchpointChangedEvent(
312     lldb::WatchpointEventType eventKind) {
313   if (!m_being_created &&
314       GetTarget().EventTypeHasListeners(
315           Target::eBroadcastBitWatchpointChanged)) {
316     WatchpointEventData *data =
317         new Watchpoint::WatchpointEventData(eventKind, shared_from_this());
318     GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data);
319   }
320 }
321 
322 void Watchpoint::SendWatchpointChangedEvent(WatchpointEventData *data) {
323   if (data == nullptr)
324     return;
325 
326   if (!m_being_created &&
327       GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged))
328     GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data);
329   else
330     delete data;
331 }
332 
333 Watchpoint::WatchpointEventData::WatchpointEventData(
334     WatchpointEventType sub_type, const WatchpointSP &new_watchpoint_sp)
335     : EventData(), m_watchpoint_event(sub_type),
336       m_new_watchpoint_sp(new_watchpoint_sp) {}
337 
338 Watchpoint::WatchpointEventData::~WatchpointEventData() = default;
339 
340 ConstString Watchpoint::WatchpointEventData::GetFlavorString() {
341   static ConstString g_flavor("Watchpoint::WatchpointEventData");
342   return g_flavor;
343 }
344 
345 ConstString Watchpoint::WatchpointEventData::GetFlavor() const {
346   return WatchpointEventData::GetFlavorString();
347 }
348 
349 WatchpointSP &Watchpoint::WatchpointEventData::GetWatchpoint() {
350   return m_new_watchpoint_sp;
351 }
352 
353 WatchpointEventType
354 Watchpoint::WatchpointEventData::GetWatchpointEventType() const {
355   return m_watchpoint_event;
356 }
357 
358 void Watchpoint::WatchpointEventData::Dump(Stream *s) const {}
359 
360 const Watchpoint::WatchpointEventData *
361 Watchpoint::WatchpointEventData::GetEventDataFromEvent(const Event *event) {
362   if (event) {
363     const EventData *event_data = event->GetData();
364     if (event_data &&
365         event_data->GetFlavor() == WatchpointEventData::GetFlavorString())
366       return static_cast<const WatchpointEventData *>(event->GetData());
367   }
368   return nullptr;
369 }
370 
371 WatchpointEventType
372 Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent(
373     const EventSP &event_sp) {
374   const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get());
375 
376   if (data == nullptr)
377     return eWatchpointEventTypeInvalidType;
378   else
379     return data->GetWatchpointEventType();
380 }
381 
382 WatchpointSP Watchpoint::WatchpointEventData::GetWatchpointFromEvent(
383     const EventSP &event_sp) {
384   WatchpointSP wp_sp;
385 
386   const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get());
387   if (data)
388     wp_sp = data->m_new_watchpoint_sp;
389 
390   return wp_sp;
391 }
392