]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lldb/source/Breakpoint/Watchpoint.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lldb / source / Breakpoint / Watchpoint.cpp
1 //===-- Watchpoint.cpp ------------------------------------------*- C++ -*-===//
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 { return m_is_hardware; }
99
100 bool Watchpoint::IsWatchVariable() const { return m_is_watch_variable; }
101
102 void Watchpoint::SetWatchVariable(bool val) { m_is_watch_variable = val; }
103
104 bool Watchpoint::CaptureWatchedValue(const ExecutionContext &exe_ctx) {
105   ConstString watch_name("$__lldb__watch_value");
106   m_old_value_sp = m_new_value_sp;
107   Address watch_address(GetLoadAddress());
108   if (!m_type.IsValid()) {
109     // Don't know how to report new & old values, since we couldn't make a
110     // scalar type for this watchpoint. This works around an assert in
111     // ValueObjectMemory::Create.
112     // FIXME: This should not happen, but if it does in some case we care about,
113     // we can go grab the value raw and print it as unsigned.
114     return false;
115   }
116   m_new_value_sp = ValueObjectMemory::Create(
117       exe_ctx.GetBestExecutionContextScope(), watch_name.GetStringRef(),
118       watch_address, m_type);
119   m_new_value_sp = m_new_value_sp->CreateConstantValue(watch_name);
120   return (m_new_value_sp && m_new_value_sp->GetError().Success());
121 }
122
123 void Watchpoint::IncrementFalseAlarmsAndReviseHitCount() {
124   ++m_false_alarms;
125   if (m_false_alarms) {
126     if (m_hit_count >= m_false_alarms) {
127       m_hit_count -= m_false_alarms;
128       m_false_alarms = 0;
129     } else {
130       m_false_alarms -= m_hit_count;
131       m_hit_count = 0;
132     }
133   }
134 }
135
136 // RETURNS - true if we should stop at this breakpoint, false if we
137 // should continue.
138
139 bool Watchpoint::ShouldStop(StoppointCallbackContext *context) {
140   IncrementHitCount();
141
142   return IsEnabled();
143 }
144
145 void Watchpoint::GetDescription(Stream *s, lldb::DescriptionLevel level) {
146   DumpWithLevel(s, level);
147 }
148
149 void Watchpoint::Dump(Stream *s) const {
150   DumpWithLevel(s, lldb::eDescriptionLevelBrief);
151 }
152
153 // If prefix is nullptr, we display the watch id and ignore the prefix
154 // altogether.
155 void Watchpoint::DumpSnapshots(Stream *s, const char *prefix) const {
156   if (!prefix) {
157     s->Printf("\nWatchpoint %u hit:", GetID());
158     prefix = "";
159   }
160
161   if (m_old_value_sp) {
162     const char *old_value_cstr = m_old_value_sp->GetValueAsCString();
163     if (old_value_cstr && old_value_cstr[0])
164       s->Printf("\n%sold value: %s", prefix, old_value_cstr);
165     else {
166       const char *old_summary_cstr = m_old_value_sp->GetSummaryAsCString();
167       if (old_summary_cstr && old_summary_cstr[0])
168         s->Printf("\n%sold value: %s", prefix, old_summary_cstr);
169     }
170   }
171
172   if (m_new_value_sp) {
173     const char *new_value_cstr = m_new_value_sp->GetValueAsCString();
174     if (new_value_cstr && new_value_cstr[0])
175       s->Printf("\n%snew value: %s", prefix, new_value_cstr);
176     else {
177       const char *new_summary_cstr = m_new_value_sp->GetSummaryAsCString();
178       if (new_summary_cstr && new_summary_cstr[0])
179         s->Printf("\n%snew value: %s", prefix, new_summary_cstr);
180     }
181   }
182 }
183
184 void Watchpoint::DumpWithLevel(Stream *s,
185                                lldb::DescriptionLevel description_level) const {
186   if (s == nullptr)
187     return;
188
189   assert(description_level >= lldb::eDescriptionLevelBrief &&
190          description_level <= lldb::eDescriptionLevelVerbose);
191
192   s->Printf("Watchpoint %u: addr = 0x%8.8" PRIx64
193             " size = %u state = %s type = %s%s",
194             GetID(), GetLoadAddress(), m_byte_size,
195             IsEnabled() ? "enabled" : "disabled", m_watch_read ? "r" : "",
196             m_watch_write ? "w" : "");
197
198   if (description_level >= lldb::eDescriptionLevelFull) {
199     if (!m_decl_str.empty())
200       s->Printf("\n    declare @ '%s'", m_decl_str.c_str());
201     if (!m_watch_spec_str.empty())
202       s->Printf("\n    watchpoint spec = '%s'", m_watch_spec_str.c_str());
203
204     // Dump the snapshots we have taken.
205     DumpSnapshots(s, "    ");
206
207     if (GetConditionText())
208       s->Printf("\n    condition = '%s'", GetConditionText());
209     m_options.GetCallbackDescription(s, description_level);
210   }
211
212   if (description_level >= lldb::eDescriptionLevelVerbose) {
213     s->Printf("\n    hw_index = %i  hit_count = %-4u  ignore_count = %-4u",
214               GetHardwareIndex(), GetHitCount(), GetIgnoreCount());
215   }
216 }
217
218 bool Watchpoint::IsEnabled() const { return m_enabled; }
219
220 // Within StopInfo.cpp, we purposely turn on the ephemeral mode right before
221 // temporarily disable the watchpoint in order to perform possible watchpoint
222 // actions without triggering further watchpoint events. After the temporary
223 // disabled watchpoint is enabled, we then turn off the 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 && m_is_ephemeral;
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_up)
285       m_condition_up.reset();
286   } else {
287     // Pass nullptr for expr_prefix (no translation-unit level definitions).
288     Status error;
289     m_condition_up.reset(m_target.GetUserExpressionForLanguage(
290         condition, llvm::StringRef(), lldb::eLanguageTypeUnknown,
291         UserExpression::eResultTypeAny, EvaluateExpressionOptions(), nullptr,
292         error));
293     if (error.Fail()) {
294       // FIXME: Log something...
295       m_condition_up.reset();
296     }
297   }
298   SendWatchpointChangedEvent(eWatchpointEventTypeConditionChanged);
299 }
300
301 const char *Watchpoint::GetConditionText() const {
302   if (m_condition_up)
303     return m_condition_up->GetUserText();
304   else
305     return nullptr;
306 }
307
308 void Watchpoint::SendWatchpointChangedEvent(
309     lldb::WatchpointEventType eventKind) {
310   if (!m_being_created &&
311       GetTarget().EventTypeHasListeners(
312           Target::eBroadcastBitWatchpointChanged)) {
313     WatchpointEventData *data =
314         new Watchpoint::WatchpointEventData(eventKind, shared_from_this());
315     GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data);
316   }
317 }
318
319 void Watchpoint::SendWatchpointChangedEvent(WatchpointEventData *data) {
320   if (data == nullptr)
321     return;
322
323   if (!m_being_created &&
324       GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged))
325     GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data);
326   else
327     delete data;
328 }
329
330 Watchpoint::WatchpointEventData::WatchpointEventData(
331     WatchpointEventType sub_type, const WatchpointSP &new_watchpoint_sp)
332     : EventData(), m_watchpoint_event(sub_type),
333       m_new_watchpoint_sp(new_watchpoint_sp) {}
334
335 Watchpoint::WatchpointEventData::~WatchpointEventData() = default;
336
337 ConstString Watchpoint::WatchpointEventData::GetFlavorString() {
338   static ConstString g_flavor("Watchpoint::WatchpointEventData");
339   return g_flavor;
340 }
341
342 ConstString Watchpoint::WatchpointEventData::GetFlavor() const {
343   return WatchpointEventData::GetFlavorString();
344 }
345
346 WatchpointSP &Watchpoint::WatchpointEventData::GetWatchpoint() {
347   return m_new_watchpoint_sp;
348 }
349
350 WatchpointEventType
351 Watchpoint::WatchpointEventData::GetWatchpointEventType() const {
352   return m_watchpoint_event;
353 }
354
355 void Watchpoint::WatchpointEventData::Dump(Stream *s) const {}
356
357 const Watchpoint::WatchpointEventData *
358 Watchpoint::WatchpointEventData::GetEventDataFromEvent(const Event *event) {
359   if (event) {
360     const EventData *event_data = event->GetData();
361     if (event_data &&
362         event_data->GetFlavor() == WatchpointEventData::GetFlavorString())
363       return static_cast<const WatchpointEventData *>(event->GetData());
364   }
365   return nullptr;
366 }
367
368 WatchpointEventType
369 Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent(
370     const EventSP &event_sp) {
371   const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get());
372
373   if (data == nullptr)
374     return eWatchpointEventTypeInvalidType;
375   else
376     return data->GetWatchpointEventType();
377 }
378
379 WatchpointSP Watchpoint::WatchpointEventData::GetWatchpointFromEvent(
380     const EventSP &event_sp) {
381   WatchpointSP wp_sp;
382
383   const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get());
384   if (data)
385     wp_sp = data->m_new_watchpoint_sp;
386
387   return wp_sp;
388 }