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