1 //===-- Breakpoint.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 "llvm/Support/Casting.h"
10 
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Breakpoint/BreakpointLocation.h"
13 #include "lldb/Breakpoint/BreakpointLocationCollection.h"
14 #include "lldb/Breakpoint/BreakpointResolver.h"
15 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
16 #include "lldb/Core/Address.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleList.h"
19 #include "lldb/Core/SearchFilter.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Target/SectionLoadList.h"
22 #include "lldb/Symbol/CompileUnit.h"
23 #include "lldb/Symbol/Function.h"
24 #include "lldb/Symbol/Symbol.h"
25 #include "lldb/Symbol/SymbolContext.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/ThreadSpec.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/Stream.h"
30 #include "lldb/Utility/StreamString.h"
31 
32 #include <memory>
33 
34 using namespace lldb;
35 using namespace lldb_private;
36 using namespace llvm;
37 
38 ConstString Breakpoint::GetEventIdentifier() {
39   static ConstString g_identifier("event-identifier.breakpoint.changed");
40   return g_identifier;
41 }
42 
43 const char *Breakpoint::g_option_names[static_cast<uint32_t>(
44     Breakpoint::OptionNames::LastOptionName)]{"Names", "Hardware"};
45 
46 // Breakpoint constructor
47 Breakpoint::Breakpoint(Target &target, SearchFilterSP &filter_sp,
48                        BreakpointResolverSP &resolver_sp, bool hardware,
49                        bool resolve_indirect_symbols)
50     : m_being_created(true), m_hardware(hardware), m_target(target),
51       m_filter_sp(filter_sp), m_resolver_sp(resolver_sp),
52       m_options_up(new BreakpointOptions(true)), m_locations(*this),
53       m_resolve_indirect_symbols(resolve_indirect_symbols), m_hit_count(0) {
54   m_being_created = false;
55 }
56 
57 Breakpoint::Breakpoint(Target &new_target, Breakpoint &source_bp)
58     : m_being_created(true), m_hardware(source_bp.m_hardware),
59       m_target(new_target), m_name_list(source_bp.m_name_list),
60       m_options_up(new BreakpointOptions(*source_bp.m_options_up)),
61       m_locations(*this),
62       m_resolve_indirect_symbols(source_bp.m_resolve_indirect_symbols),
63       m_hit_count(0) {
64   // Now go through and copy the filter & resolver:
65   m_resolver_sp = source_bp.m_resolver_sp->CopyForBreakpoint(*this);
66   m_filter_sp = source_bp.m_filter_sp->CopyForBreakpoint(*this);
67 }
68 
69 // Destructor
70 Breakpoint::~Breakpoint() = default;
71 
72 // Serialization
73 StructuredData::ObjectSP Breakpoint::SerializeToStructuredData() {
74   // Serialize the resolver:
75   StructuredData::DictionarySP breakpoint_dict_sp(
76       new StructuredData::Dictionary());
77   StructuredData::DictionarySP breakpoint_contents_sp(
78       new StructuredData::Dictionary());
79 
80   if (!m_name_list.empty()) {
81     StructuredData::ArraySP names_array_sp(new StructuredData::Array());
82     for (auto name : m_name_list) {
83       names_array_sp->AddItem(
84           StructuredData::StringSP(new StructuredData::String(name)));
85     }
86     breakpoint_contents_sp->AddItem(Breakpoint::GetKey(OptionNames::Names),
87                                     names_array_sp);
88   }
89 
90   breakpoint_contents_sp->AddBooleanItem(
91       Breakpoint::GetKey(OptionNames::Hardware), m_hardware);
92 
93   StructuredData::ObjectSP resolver_dict_sp(
94       m_resolver_sp->SerializeToStructuredData());
95   if (!resolver_dict_sp)
96     return StructuredData::ObjectSP();
97 
98   breakpoint_contents_sp->AddItem(BreakpointResolver::GetSerializationKey(),
99                                   resolver_dict_sp);
100 
101   StructuredData::ObjectSP filter_dict_sp(
102       m_filter_sp->SerializeToStructuredData());
103   if (!filter_dict_sp)
104     return StructuredData::ObjectSP();
105 
106   breakpoint_contents_sp->AddItem(SearchFilter::GetSerializationKey(),
107                                   filter_dict_sp);
108 
109   StructuredData::ObjectSP options_dict_sp(
110       m_options_up->SerializeToStructuredData());
111   if (!options_dict_sp)
112     return StructuredData::ObjectSP();
113 
114   breakpoint_contents_sp->AddItem(BreakpointOptions::GetSerializationKey(),
115                                   options_dict_sp);
116 
117   breakpoint_dict_sp->AddItem(GetSerializationKey(), breakpoint_contents_sp);
118   return breakpoint_dict_sp;
119 }
120 
121 lldb::BreakpointSP Breakpoint::CreateFromStructuredData(
122     Target &target, StructuredData::ObjectSP &object_data, Status &error) {
123   BreakpointSP result_sp;
124 
125   StructuredData::Dictionary *breakpoint_dict = object_data->GetAsDictionary();
126 
127   if (!breakpoint_dict || !breakpoint_dict->IsValid()) {
128     error.SetErrorString("Can't deserialize from an invalid data object.");
129     return result_sp;
130   }
131 
132   StructuredData::Dictionary *resolver_dict;
133   bool success = breakpoint_dict->GetValueForKeyAsDictionary(
134       BreakpointResolver::GetSerializationKey(), resolver_dict);
135   if (!success) {
136     error.SetErrorStringWithFormat(
137         "Breakpoint data missing toplevel resolver key");
138     return result_sp;
139   }
140 
141   Status create_error;
142   BreakpointResolverSP resolver_sp =
143       BreakpointResolver::CreateFromStructuredData(*resolver_dict,
144                                                    create_error);
145   if (create_error.Fail()) {
146     error.SetErrorStringWithFormat(
147         "Error creating breakpoint resolver from data: %s.",
148         create_error.AsCString());
149     return result_sp;
150   }
151 
152   StructuredData::Dictionary *filter_dict;
153   success = breakpoint_dict->GetValueForKeyAsDictionary(
154       SearchFilter::GetSerializationKey(), filter_dict);
155   SearchFilterSP filter_sp;
156   if (!success)
157     filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
158         target.shared_from_this());
159   else {
160     filter_sp = SearchFilter::CreateFromStructuredData(target, *filter_dict,
161                                                        create_error);
162     if (create_error.Fail()) {
163       error.SetErrorStringWithFormat(
164           "Error creating breakpoint filter from data: %s.",
165           create_error.AsCString());
166       return result_sp;
167     }
168   }
169 
170   std::unique_ptr<BreakpointOptions> options_up;
171   StructuredData::Dictionary *options_dict;
172   success = breakpoint_dict->GetValueForKeyAsDictionary(
173       BreakpointOptions::GetSerializationKey(), options_dict);
174   if (success) {
175     options_up = BreakpointOptions::CreateFromStructuredData(
176         target, *options_dict, create_error);
177     if (create_error.Fail()) {
178       error.SetErrorStringWithFormat(
179           "Error creating breakpoint options from data: %s.",
180           create_error.AsCString());
181       return result_sp;
182     }
183   }
184 
185   bool hardware = false;
186   success = breakpoint_dict->GetValueForKeyAsBoolean(
187       Breakpoint::GetKey(OptionNames::Hardware), hardware);
188 
189   result_sp =
190       target.CreateBreakpoint(filter_sp, resolver_sp, false, hardware, true);
191 
192   if (result_sp && options_up) {
193     result_sp->m_options_up = std::move(options_up);
194   }
195 
196   StructuredData::Array *names_array;
197   success = breakpoint_dict->GetValueForKeyAsArray(
198       Breakpoint::GetKey(OptionNames::Names), names_array);
199   if (success && names_array) {
200     size_t num_names = names_array->GetSize();
201     for (size_t i = 0; i < num_names; i++) {
202       llvm::StringRef name;
203       Status error;
204       success = names_array->GetItemAtIndexAsString(i, name);
205       target.AddNameToBreakpoint(result_sp, name.str().c_str(), error);
206     }
207   }
208 
209   return result_sp;
210 }
211 
212 bool Breakpoint::SerializedBreakpointMatchesNames(
213     StructuredData::ObjectSP &bkpt_object_sp, std::vector<std::string> &names) {
214   if (!bkpt_object_sp)
215     return false;
216 
217   StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
218   if (!bkpt_dict)
219     return false;
220 
221   if (names.empty())
222     return true;
223 
224   StructuredData::Array *names_array;
225 
226   bool success =
227       bkpt_dict->GetValueForKeyAsArray(GetKey(OptionNames::Names), names_array);
228   // If there are no names, it can't match these names;
229   if (!success)
230     return false;
231 
232   size_t num_names = names_array->GetSize();
233   std::vector<std::string>::iterator begin = names.begin();
234   std::vector<std::string>::iterator end = names.end();
235 
236   for (size_t i = 0; i < num_names; i++) {
237     llvm::StringRef name;
238     if (names_array->GetItemAtIndexAsString(i, name)) {
239       if (std::find(begin, end, name) != end) {
240         return true;
241       }
242     }
243   }
244   return false;
245 }
246 
247 const lldb::TargetSP Breakpoint::GetTargetSP() {
248   return m_target.shared_from_this();
249 }
250 
251 bool Breakpoint::IsInternal() const { return LLDB_BREAK_ID_IS_INTERNAL(m_bid); }
252 
253 BreakpointLocationSP Breakpoint::AddLocation(const Address &addr,
254                                              bool *new_location) {
255   return m_locations.AddLocation(addr, m_resolve_indirect_symbols,
256                                  new_location);
257 }
258 
259 BreakpointLocationSP Breakpoint::FindLocationByAddress(const Address &addr) {
260   return m_locations.FindByAddress(addr);
261 }
262 
263 break_id_t Breakpoint::FindLocationIDByAddress(const Address &addr) {
264   return m_locations.FindIDByAddress(addr);
265 }
266 
267 BreakpointLocationSP Breakpoint::FindLocationByID(break_id_t bp_loc_id) {
268   return m_locations.FindByID(bp_loc_id);
269 }
270 
271 BreakpointLocationSP Breakpoint::GetLocationAtIndex(size_t index) {
272   return m_locations.GetByIndex(index);
273 }
274 
275 void Breakpoint::RemoveInvalidLocations(const ArchSpec &arch) {
276   m_locations.RemoveInvalidLocations(arch);
277 }
278 
279 // For each of the overall options we need to decide how they propagate to the
280 // location options.  This will determine the precedence of options on the
281 // breakpoint vs. its locations.
282 
283 // Disable at the breakpoint level should override the location settings. That
284 // way you can conveniently turn off a whole breakpoint without messing up the
285 // individual settings.
286 
287 void Breakpoint::SetEnabled(bool enable) {
288   if (enable == m_options_up->IsEnabled())
289     return;
290 
291   m_options_up->SetEnabled(enable);
292   if (enable)
293     m_locations.ResolveAllBreakpointSites();
294   else
295     m_locations.ClearAllBreakpointSites();
296 
297   SendBreakpointChangedEvent(enable ? eBreakpointEventTypeEnabled
298                                     : eBreakpointEventTypeDisabled);
299 }
300 
301 bool Breakpoint::IsEnabled() { return m_options_up->IsEnabled(); }
302 
303 void Breakpoint::SetIgnoreCount(uint32_t n) {
304   if (m_options_up->GetIgnoreCount() == n)
305     return;
306 
307   m_options_up->SetIgnoreCount(n);
308   SendBreakpointChangedEvent(eBreakpointEventTypeIgnoreChanged);
309 }
310 
311 void Breakpoint::DecrementIgnoreCount() {
312   uint32_t ignore = m_options_up->GetIgnoreCount();
313   if (ignore != 0)
314     m_options_up->SetIgnoreCount(ignore - 1);
315 }
316 
317 uint32_t Breakpoint::GetIgnoreCount() const {
318   return m_options_up->GetIgnoreCount();
319 }
320 
321 bool Breakpoint::IgnoreCountShouldStop() {
322   uint32_t ignore = GetIgnoreCount();
323   if (ignore != 0) {
324     // When we get here we know the location that caused the stop doesn't have
325     // an ignore count, since by contract we call it first...  So we don't have
326     // to find & decrement it, we only have to decrement our own ignore count.
327     DecrementIgnoreCount();
328     return false;
329   } else
330     return true;
331 }
332 
333 uint32_t Breakpoint::GetHitCount() const { return m_hit_count; }
334 
335 bool Breakpoint::IsOneShot() const { return m_options_up->IsOneShot(); }
336 
337 void Breakpoint::SetOneShot(bool one_shot) {
338   m_options_up->SetOneShot(one_shot);
339 }
340 
341 bool Breakpoint::IsAutoContinue() const {
342   return m_options_up->IsAutoContinue();
343 }
344 
345 void Breakpoint::SetAutoContinue(bool auto_continue) {
346   m_options_up->SetAutoContinue(auto_continue);
347 }
348 
349 void Breakpoint::SetThreadID(lldb::tid_t thread_id) {
350   if (m_options_up->GetThreadSpec()->GetTID() == thread_id)
351     return;
352 
353   m_options_up->GetThreadSpec()->SetTID(thread_id);
354   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
355 }
356 
357 lldb::tid_t Breakpoint::GetThreadID() const {
358   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
359     return LLDB_INVALID_THREAD_ID;
360   else
361     return m_options_up->GetThreadSpecNoCreate()->GetTID();
362 }
363 
364 void Breakpoint::SetThreadIndex(uint32_t index) {
365   if (m_options_up->GetThreadSpec()->GetIndex() == index)
366     return;
367 
368   m_options_up->GetThreadSpec()->SetIndex(index);
369   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
370 }
371 
372 uint32_t Breakpoint::GetThreadIndex() const {
373   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
374     return 0;
375   else
376     return m_options_up->GetThreadSpecNoCreate()->GetIndex();
377 }
378 
379 void Breakpoint::SetThreadName(const char *thread_name) {
380   if (m_options_up->GetThreadSpec()->GetName() != nullptr &&
381       ::strcmp(m_options_up->GetThreadSpec()->GetName(), thread_name) == 0)
382     return;
383 
384   m_options_up->GetThreadSpec()->SetName(thread_name);
385   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
386 }
387 
388 const char *Breakpoint::GetThreadName() const {
389   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
390     return nullptr;
391   else
392     return m_options_up->GetThreadSpecNoCreate()->GetName();
393 }
394 
395 void Breakpoint::SetQueueName(const char *queue_name) {
396   if (m_options_up->GetThreadSpec()->GetQueueName() != nullptr &&
397       ::strcmp(m_options_up->GetThreadSpec()->GetQueueName(), queue_name) == 0)
398     return;
399 
400   m_options_up->GetThreadSpec()->SetQueueName(queue_name);
401   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
402 }
403 
404 const char *Breakpoint::GetQueueName() const {
405   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
406     return nullptr;
407   else
408     return m_options_up->GetThreadSpecNoCreate()->GetQueueName();
409 }
410 
411 void Breakpoint::SetCondition(const char *condition) {
412   m_options_up->SetCondition(condition);
413   SendBreakpointChangedEvent(eBreakpointEventTypeConditionChanged);
414 }
415 
416 const char *Breakpoint::GetConditionText() const {
417   return m_options_up->GetConditionText();
418 }
419 
420 // This function is used when "baton" doesn't need to be freed
421 void Breakpoint::SetCallback(BreakpointHitCallback callback, void *baton,
422                              bool is_synchronous) {
423   // The default "Baton" class will keep a copy of "baton" and won't free or
424   // delete it when it goes goes out of scope.
425   m_options_up->SetCallback(callback, std::make_shared<UntypedBaton>(baton),
426                             is_synchronous);
427 
428   SendBreakpointChangedEvent(eBreakpointEventTypeCommandChanged);
429 }
430 
431 // This function is used when a baton needs to be freed and therefore is
432 // contained in a "Baton" subclass.
433 void Breakpoint::SetCallback(BreakpointHitCallback callback,
434                              const BatonSP &callback_baton_sp,
435                              bool is_synchronous) {
436   m_options_up->SetCallback(callback, callback_baton_sp, is_synchronous);
437 }
438 
439 void Breakpoint::ClearCallback() { m_options_up->ClearCallback(); }
440 
441 bool Breakpoint::InvokeCallback(StoppointCallbackContext *context,
442                                 break_id_t bp_loc_id) {
443   return m_options_up->InvokeCallback(context, GetID(), bp_loc_id);
444 }
445 
446 BreakpointOptions *Breakpoint::GetOptions() { return m_options_up.get(); }
447 
448 const BreakpointOptions *Breakpoint::GetOptions() const {
449   return m_options_up.get();
450 }
451 
452 void Breakpoint::ResolveBreakpoint() {
453   if (m_resolver_sp)
454     m_resolver_sp->ResolveBreakpoint(*m_filter_sp);
455 }
456 
457 void Breakpoint::ResolveBreakpointInModules(
458     ModuleList &module_list, BreakpointLocationCollection &new_locations) {
459   m_locations.StartRecordingNewLocations(new_locations);
460 
461   m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list);
462 
463   m_locations.StopRecordingNewLocations();
464 }
465 
466 void Breakpoint::ResolveBreakpointInModules(ModuleList &module_list,
467                                             bool send_event) {
468   if (m_resolver_sp) {
469     // If this is not an internal breakpoint, set up to record the new
470     // locations, then dispatch an event with the new locations.
471     if (!IsInternal() && send_event) {
472       BreakpointEventData *new_locations_event = new BreakpointEventData(
473           eBreakpointEventTypeLocationsAdded, shared_from_this());
474 
475       ResolveBreakpointInModules(
476           module_list, new_locations_event->GetBreakpointLocationCollection());
477 
478       if (new_locations_event->GetBreakpointLocationCollection().GetSize() !=
479           0) {
480         SendBreakpointChangedEvent(new_locations_event);
481       } else
482         delete new_locations_event;
483     } else {
484       m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list);
485     }
486   }
487 }
488 
489 void Breakpoint::ClearAllBreakpointSites() {
490   m_locations.ClearAllBreakpointSites();
491 }
492 
493 // ModulesChanged: Pass in a list of new modules, and
494 
495 void Breakpoint::ModulesChanged(ModuleList &module_list, bool load,
496                                 bool delete_locations) {
497   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
498   if (log)
499     log->Printf("Breakpoint::ModulesChanged: num_modules: %zu load: %i "
500                 "delete_locations: %i\n",
501                 module_list.GetSize(), load, delete_locations);
502 
503   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
504   if (load) {
505     // The logic for handling new modules is:
506     // 1) If the filter rejects this module, then skip it. 2) Run through the
507     // current location list and if there are any locations
508     //    for that module, we mark the module as "seen" and we don't try to
509     //    re-resolve
510     //    breakpoint locations for that module.
511     //    However, we do add breakpoint sites to these locations if needed.
512     // 3) If we don't see this module in our breakpoint location list, call
513     // ResolveInModules.
514 
515     ModuleList new_modules; // We'll stuff the "unseen" modules in this list,
516                             // and then resolve
517     // them after the locations pass.  Have to do it this way because resolving
518     // breakpoints will add new locations potentially.
519 
520     for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
521       bool seen = false;
522       if (!m_filter_sp->ModulePasses(module_sp))
523         continue;
524 
525       BreakpointLocationCollection locations_with_no_section;
526       for (BreakpointLocationSP break_loc_sp :
527            m_locations.BreakpointLocations()) {
528 
529         // If the section for this location was deleted, that means it's Module
530         // has gone away but somebody forgot to tell us. Let's clean it up
531         // here.
532         Address section_addr(break_loc_sp->GetAddress());
533         if (section_addr.SectionWasDeleted()) {
534           locations_with_no_section.Add(break_loc_sp);
535           continue;
536         }
537 
538         if (!break_loc_sp->IsEnabled())
539           continue;
540 
541         SectionSP section_sp(section_addr.GetSection());
542 
543         // If we don't have a Section, that means this location is a raw
544         // address that we haven't resolved to a section yet.  So we'll have to
545         // look in all the new modules to resolve this location. Otherwise, if
546         // it was set in this module, re-resolve it here.
547         if (section_sp && section_sp->GetModule() == module_sp) {
548           if (!seen)
549             seen = true;
550 
551           if (!break_loc_sp->ResolveBreakpointSite()) {
552             if (log)
553               log->Printf("Warning: could not set breakpoint site for "
554                           "breakpoint location %d of breakpoint %d.\n",
555                           break_loc_sp->GetID(), GetID());
556           }
557         }
558       }
559 
560       size_t num_to_delete = locations_with_no_section.GetSize();
561 
562       for (size_t i = 0; i < num_to_delete; i++)
563         m_locations.RemoveLocation(locations_with_no_section.GetByIndex(i));
564 
565       if (!seen)
566         new_modules.AppendIfNeeded(module_sp);
567     }
568 
569     if (new_modules.GetSize() > 0) {
570       ResolveBreakpointInModules(new_modules);
571     }
572   } else {
573     // Go through the currently set locations and if any have breakpoints in
574     // the module list, then remove their breakpoint sites, and their locations
575     // if asked to.
576 
577     BreakpointEventData *removed_locations_event;
578     if (!IsInternal())
579       removed_locations_event = new BreakpointEventData(
580           eBreakpointEventTypeLocationsRemoved, shared_from_this());
581     else
582       removed_locations_event = nullptr;
583 
584     size_t num_modules = module_list.GetSize();
585     for (size_t i = 0; i < num_modules; i++) {
586       ModuleSP module_sp(module_list.GetModuleAtIndexUnlocked(i));
587       if (m_filter_sp->ModulePasses(module_sp)) {
588         size_t loc_idx = 0;
589         size_t num_locations = m_locations.GetSize();
590         BreakpointLocationCollection locations_to_remove;
591         for (loc_idx = 0; loc_idx < num_locations; loc_idx++) {
592           BreakpointLocationSP break_loc_sp(m_locations.GetByIndex(loc_idx));
593           SectionSP section_sp(break_loc_sp->GetAddress().GetSection());
594           if (section_sp && section_sp->GetModule() == module_sp) {
595             // Remove this breakpoint since the shared library is unloaded, but
596             // keep the breakpoint location around so we always get complete
597             // hit count and breakpoint lifetime info
598             break_loc_sp->ClearBreakpointSite();
599             if (removed_locations_event) {
600               removed_locations_event->GetBreakpointLocationCollection().Add(
601                   break_loc_sp);
602             }
603             if (delete_locations)
604               locations_to_remove.Add(break_loc_sp);
605           }
606         }
607 
608         if (delete_locations) {
609           size_t num_locations_to_remove = locations_to_remove.GetSize();
610           for (loc_idx = 0; loc_idx < num_locations_to_remove; loc_idx++)
611             m_locations.RemoveLocation(locations_to_remove.GetByIndex(loc_idx));
612         }
613       }
614     }
615     SendBreakpointChangedEvent(removed_locations_event);
616   }
617 }
618 
619 namespace {
620 static bool SymbolContextsMightBeEquivalent(SymbolContext &old_sc,
621                                             SymbolContext &new_sc) {
622   bool equivalent_scs = false;
623 
624   if (old_sc.module_sp.get() == new_sc.module_sp.get()) {
625     // If these come from the same module, we can directly compare the
626     // pointers:
627     if (old_sc.comp_unit && new_sc.comp_unit &&
628         (old_sc.comp_unit == new_sc.comp_unit)) {
629       if (old_sc.function && new_sc.function &&
630           (old_sc.function == new_sc.function)) {
631         equivalent_scs = true;
632       }
633     } else if (old_sc.symbol && new_sc.symbol &&
634                (old_sc.symbol == new_sc.symbol)) {
635       equivalent_scs = true;
636     }
637   } else {
638     // Otherwise we will compare by name...
639     if (old_sc.comp_unit && new_sc.comp_unit) {
640       if (FileSpec::Equal(*old_sc.comp_unit, *new_sc.comp_unit, true)) {
641         // Now check the functions:
642         if (old_sc.function && new_sc.function &&
643             (old_sc.function->GetName() == new_sc.function->GetName())) {
644           equivalent_scs = true;
645         }
646       }
647     } else if (old_sc.symbol && new_sc.symbol) {
648       if (Mangled::Compare(old_sc.symbol->GetMangled(),
649                            new_sc.symbol->GetMangled()) == 0) {
650         equivalent_scs = true;
651       }
652     }
653   }
654   return equivalent_scs;
655 }
656 } // anonymous namespace
657 
658 void Breakpoint::ModuleReplaced(ModuleSP old_module_sp,
659                                 ModuleSP new_module_sp) {
660   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
661   if (log)
662     log->Printf("Breakpoint::ModulesReplaced for %s\n",
663                 old_module_sp->GetSpecificationDescription().c_str());
664   // First find all the locations that are in the old module
665 
666   BreakpointLocationCollection old_break_locs;
667   for (BreakpointLocationSP break_loc_sp : m_locations.BreakpointLocations()) {
668     SectionSP section_sp = break_loc_sp->GetAddress().GetSection();
669     if (section_sp && section_sp->GetModule() == old_module_sp) {
670       old_break_locs.Add(break_loc_sp);
671     }
672   }
673 
674   size_t num_old_locations = old_break_locs.GetSize();
675 
676   if (num_old_locations == 0) {
677     // There were no locations in the old module, so we just need to check if
678     // there were any in the new module.
679     ModuleList temp_list;
680     temp_list.Append(new_module_sp);
681     ResolveBreakpointInModules(temp_list);
682   } else {
683     // First search the new module for locations. Then compare this with the
684     // old list, copy over locations that "look the same" Then delete the old
685     // locations. Finally remember to post the creation event.
686     //
687     // Two locations are the same if they have the same comp unit & function
688     // (by name) and there are the same number of locations in the old function
689     // as in the new one.
690 
691     ModuleList temp_list;
692     temp_list.Append(new_module_sp);
693     BreakpointLocationCollection new_break_locs;
694     ResolveBreakpointInModules(temp_list, new_break_locs);
695     BreakpointLocationCollection locations_to_remove;
696     BreakpointLocationCollection locations_to_announce;
697 
698     size_t num_new_locations = new_break_locs.GetSize();
699 
700     if (num_new_locations > 0) {
701       // Break out the case of one location -> one location since that's the
702       // most common one, and there's no need to build up the structures needed
703       // for the merge in that case.
704       if (num_new_locations == 1 && num_old_locations == 1) {
705         bool equivalent_locations = false;
706         SymbolContext old_sc, new_sc;
707         // The only way the old and new location can be equivalent is if they
708         // have the same amount of information:
709         BreakpointLocationSP old_loc_sp = old_break_locs.GetByIndex(0);
710         BreakpointLocationSP new_loc_sp = new_break_locs.GetByIndex(0);
711 
712         if (old_loc_sp->GetAddress().CalculateSymbolContext(&old_sc) ==
713             new_loc_sp->GetAddress().CalculateSymbolContext(&new_sc)) {
714           equivalent_locations =
715               SymbolContextsMightBeEquivalent(old_sc, new_sc);
716         }
717 
718         if (equivalent_locations) {
719           m_locations.SwapLocation(old_loc_sp, new_loc_sp);
720         } else {
721           locations_to_remove.Add(old_loc_sp);
722           locations_to_announce.Add(new_loc_sp);
723         }
724       } else {
725         // We don't want to have to keep computing the SymbolContexts for these
726         // addresses over and over, so lets get them up front:
727 
728         typedef std::map<lldb::break_id_t, SymbolContext> IDToSCMap;
729         IDToSCMap old_sc_map;
730         for (size_t idx = 0; idx < num_old_locations; idx++) {
731           SymbolContext sc;
732           BreakpointLocationSP bp_loc_sp = old_break_locs.GetByIndex(idx);
733           lldb::break_id_t loc_id = bp_loc_sp->GetID();
734           bp_loc_sp->GetAddress().CalculateSymbolContext(&old_sc_map[loc_id]);
735         }
736 
737         std::map<lldb::break_id_t, SymbolContext> new_sc_map;
738         for (size_t idx = 0; idx < num_new_locations; idx++) {
739           SymbolContext sc;
740           BreakpointLocationSP bp_loc_sp = new_break_locs.GetByIndex(idx);
741           lldb::break_id_t loc_id = bp_loc_sp->GetID();
742           bp_loc_sp->GetAddress().CalculateSymbolContext(&new_sc_map[loc_id]);
743         }
744         // Take an element from the old Symbol Contexts
745         while (old_sc_map.size() > 0) {
746           lldb::break_id_t old_id = old_sc_map.begin()->first;
747           SymbolContext &old_sc = old_sc_map.begin()->second;
748 
749           // Count the number of entries equivalent to this SC for the old
750           // list:
751           std::vector<lldb::break_id_t> old_id_vec;
752           old_id_vec.push_back(old_id);
753 
754           IDToSCMap::iterator tmp_iter;
755           for (tmp_iter = ++old_sc_map.begin(); tmp_iter != old_sc_map.end();
756                tmp_iter++) {
757             if (SymbolContextsMightBeEquivalent(old_sc, tmp_iter->second))
758               old_id_vec.push_back(tmp_iter->first);
759           }
760 
761           // Now find all the equivalent locations in the new list.
762           std::vector<lldb::break_id_t> new_id_vec;
763           for (tmp_iter = new_sc_map.begin(); tmp_iter != new_sc_map.end();
764                tmp_iter++) {
765             if (SymbolContextsMightBeEquivalent(old_sc, tmp_iter->second))
766               new_id_vec.push_back(tmp_iter->first);
767           }
768 
769           // Alright, if we have the same number of potentially equivalent
770           // locations in the old and new modules, we'll just map them one to
771           // one in ascending ID order (assuming the resolver's order would
772           // match the equivalent ones. Otherwise, we'll dump all the old ones,
773           // and just take the new ones, erasing the elements from both maps as
774           // we go.
775 
776           if (old_id_vec.size() == new_id_vec.size()) {
777             llvm::sort(old_id_vec);
778             llvm::sort(new_id_vec);
779             size_t num_elements = old_id_vec.size();
780             for (size_t idx = 0; idx < num_elements; idx++) {
781               BreakpointLocationSP old_loc_sp =
782                   old_break_locs.FindByIDPair(GetID(), old_id_vec[idx]);
783               BreakpointLocationSP new_loc_sp =
784                   new_break_locs.FindByIDPair(GetID(), new_id_vec[idx]);
785               m_locations.SwapLocation(old_loc_sp, new_loc_sp);
786               old_sc_map.erase(old_id_vec[idx]);
787               new_sc_map.erase(new_id_vec[idx]);
788             }
789           } else {
790             for (lldb::break_id_t old_id : old_id_vec) {
791               locations_to_remove.Add(
792                   old_break_locs.FindByIDPair(GetID(), old_id));
793               old_sc_map.erase(old_id);
794             }
795             for (lldb::break_id_t new_id : new_id_vec) {
796               locations_to_announce.Add(
797                   new_break_locs.FindByIDPair(GetID(), new_id));
798               new_sc_map.erase(new_id);
799             }
800           }
801         }
802       }
803     }
804 
805     // Now remove the remaining old locations, and cons up a removed locations
806     // event. Note, we don't put the new locations that were swapped with an
807     // old location on the locations_to_remove list, so we don't need to worry
808     // about telling the world about removing a location we didn't tell them
809     // about adding.
810 
811     BreakpointEventData *locations_event;
812     if (!IsInternal())
813       locations_event = new BreakpointEventData(
814           eBreakpointEventTypeLocationsRemoved, shared_from_this());
815     else
816       locations_event = nullptr;
817 
818     for (BreakpointLocationSP loc_sp :
819          locations_to_remove.BreakpointLocations()) {
820       m_locations.RemoveLocation(loc_sp);
821       if (locations_event)
822         locations_event->GetBreakpointLocationCollection().Add(loc_sp);
823     }
824     SendBreakpointChangedEvent(locations_event);
825 
826     // And announce the new ones.
827 
828     if (!IsInternal()) {
829       locations_event = new BreakpointEventData(
830           eBreakpointEventTypeLocationsAdded, shared_from_this());
831       for (BreakpointLocationSP loc_sp :
832            locations_to_announce.BreakpointLocations())
833         locations_event->GetBreakpointLocationCollection().Add(loc_sp);
834 
835       SendBreakpointChangedEvent(locations_event);
836     }
837     m_locations.Compact();
838   }
839 }
840 
841 void Breakpoint::Dump(Stream *) {}
842 
843 size_t Breakpoint::GetNumResolvedLocations() const {
844   // Return the number of breakpoints that are actually resolved and set down
845   // in the inferior process.
846   return m_locations.GetNumResolvedLocations();
847 }
848 
849 bool Breakpoint::HasResolvedLocations() const {
850   return GetNumResolvedLocations() > 0;
851 }
852 
853 size_t Breakpoint::GetNumLocations() const { return m_locations.GetSize(); }
854 
855 bool Breakpoint::AddName(llvm::StringRef new_name) {
856   m_name_list.insert(new_name.str().c_str());
857   return true;
858 }
859 
860 void Breakpoint::GetDescription(Stream *s, lldb::DescriptionLevel level,
861                                 bool show_locations) {
862   assert(s != nullptr);
863 
864   if (!m_kind_description.empty()) {
865     if (level == eDescriptionLevelBrief) {
866       s->PutCString(GetBreakpointKind());
867       return;
868     } else
869       s->Printf("Kind: %s\n", GetBreakpointKind());
870   }
871 
872   const size_t num_locations = GetNumLocations();
873   const size_t num_resolved_locations = GetNumResolvedLocations();
874 
875   // They just made the breakpoint, they don't need to be told HOW they made
876   // it... Also, we'll print the breakpoint number differently depending on
877   // whether there is 1 or more locations.
878   if (level != eDescriptionLevelInitial) {
879     s->Printf("%i: ", GetID());
880     GetResolverDescription(s);
881     GetFilterDescription(s);
882   }
883 
884   switch (level) {
885   case lldb::eDescriptionLevelBrief:
886   case lldb::eDescriptionLevelFull:
887     if (num_locations > 0) {
888       s->Printf(", locations = %" PRIu64, (uint64_t)num_locations);
889       if (num_resolved_locations > 0)
890         s->Printf(", resolved = %" PRIu64 ", hit count = %d",
891                   (uint64_t)num_resolved_locations, GetHitCount());
892     } else {
893       // Don't print the pending notification for exception resolvers since we
894       // don't generally know how to set them until the target is run.
895       if (m_resolver_sp->getResolverID() !=
896           BreakpointResolver::ExceptionResolver)
897         s->Printf(", locations = 0 (pending)");
898     }
899 
900     GetOptions()->GetDescription(s, level);
901 
902     if (m_precondition_sp)
903       m_precondition_sp->GetDescription(*s, level);
904 
905     if (level == lldb::eDescriptionLevelFull) {
906       if (!m_name_list.empty()) {
907         s->EOL();
908         s->Indent();
909         s->Printf("Names:");
910         s->EOL();
911         s->IndentMore();
912         for (std::string name : m_name_list) {
913           s->Indent();
914           s->Printf("%s\n", name.c_str());
915         }
916         s->IndentLess();
917       }
918       s->IndentLess();
919       s->EOL();
920     }
921     break;
922 
923   case lldb::eDescriptionLevelInitial:
924     s->Printf("Breakpoint %i: ", GetID());
925     if (num_locations == 0) {
926       s->Printf("no locations (pending).");
927     } else if (num_locations == 1 && !show_locations) {
928       // There is only one location, so we'll just print that location
929       // information.
930       GetLocationAtIndex(0)->GetDescription(s, level);
931     } else {
932       s->Printf("%" PRIu64 " locations.", static_cast<uint64_t>(num_locations));
933     }
934     s->EOL();
935     break;
936 
937   case lldb::eDescriptionLevelVerbose:
938     // Verbose mode does a debug dump of the breakpoint
939     Dump(s);
940     s->EOL();
941     // s->Indent();
942     GetOptions()->GetDescription(s, level);
943     break;
944 
945   default:
946     break;
947   }
948 
949   // The brief description is just the location name (1.2 or whatever).  That's
950   // pointless to show in the breakpoint's description, so suppress it.
951   if (show_locations && level != lldb::eDescriptionLevelBrief) {
952     s->IndentMore();
953     for (size_t i = 0; i < num_locations; ++i) {
954       BreakpointLocation *loc = GetLocationAtIndex(i).get();
955       loc->GetDescription(s, level);
956       s->EOL();
957     }
958     s->IndentLess();
959   }
960 }
961 
962 void Breakpoint::GetResolverDescription(Stream *s) {
963   if (m_resolver_sp)
964     m_resolver_sp->GetDescription(s);
965 }
966 
967 bool Breakpoint::GetMatchingFileLine(ConstString filename,
968                                      uint32_t line_number,
969                                      BreakpointLocationCollection &loc_coll) {
970   // TODO: To be correct, this method needs to fill the breakpoint location
971   // collection
972   //       with the location IDs which match the filename and line_number.
973   //
974 
975   if (m_resolver_sp) {
976     BreakpointResolverFileLine *resolverFileLine =
977         dyn_cast<BreakpointResolverFileLine>(m_resolver_sp.get());
978     if (resolverFileLine &&
979         resolverFileLine->m_file_spec.GetFilename() == filename &&
980         resolverFileLine->m_line_number == line_number) {
981       return true;
982     }
983   }
984   return false;
985 }
986 
987 void Breakpoint::GetFilterDescription(Stream *s) {
988   m_filter_sp->GetDescription(s);
989 }
990 
991 bool Breakpoint::EvaluatePrecondition(StoppointCallbackContext &context) {
992   if (!m_precondition_sp)
993     return true;
994 
995   return m_precondition_sp->EvaluatePrecondition(context);
996 }
997 
998 bool Breakpoint::BreakpointPrecondition::EvaluatePrecondition(
999     StoppointCallbackContext &context) {
1000   return true;
1001 }
1002 
1003 void Breakpoint::BreakpointPrecondition::GetDescription(
1004     Stream &stream, lldb::DescriptionLevel level) {}
1005 
1006 Status
1007 Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) {
1008   Status error;
1009   error.SetErrorString("Base breakpoint precondition has no options.");
1010   return error;
1011 }
1012 
1013 void Breakpoint::SendBreakpointChangedEvent(
1014     lldb::BreakpointEventType eventKind) {
1015   if (!m_being_created && !IsInternal() &&
1016       GetTarget().EventTypeHasListeners(
1017           Target::eBroadcastBitBreakpointChanged)) {
1018     BreakpointEventData *data =
1019         new Breakpoint::BreakpointEventData(eventKind, shared_from_this());
1020 
1021     GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, data);
1022   }
1023 }
1024 
1025 void Breakpoint::SendBreakpointChangedEvent(BreakpointEventData *data) {
1026   if (data == nullptr)
1027     return;
1028 
1029   if (!m_being_created && !IsInternal() &&
1030       GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged))
1031     GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, data);
1032   else
1033     delete data;
1034 }
1035 
1036 Breakpoint::BreakpointEventData::BreakpointEventData(
1037     BreakpointEventType sub_type, const BreakpointSP &new_breakpoint_sp)
1038     : EventData(), m_breakpoint_event(sub_type),
1039       m_new_breakpoint_sp(new_breakpoint_sp) {}
1040 
1041 Breakpoint::BreakpointEventData::~BreakpointEventData() = default;
1042 
1043 ConstString Breakpoint::BreakpointEventData::GetFlavorString() {
1044   static ConstString g_flavor("Breakpoint::BreakpointEventData");
1045   return g_flavor;
1046 }
1047 
1048 ConstString Breakpoint::BreakpointEventData::GetFlavor() const {
1049   return BreakpointEventData::GetFlavorString();
1050 }
1051 
1052 BreakpointSP &Breakpoint::BreakpointEventData::GetBreakpoint() {
1053   return m_new_breakpoint_sp;
1054 }
1055 
1056 BreakpointEventType
1057 Breakpoint::BreakpointEventData::GetBreakpointEventType() const {
1058   return m_breakpoint_event;
1059 }
1060 
1061 void Breakpoint::BreakpointEventData::Dump(Stream *s) const {}
1062 
1063 const Breakpoint::BreakpointEventData *
1064 Breakpoint::BreakpointEventData::GetEventDataFromEvent(const Event *event) {
1065   if (event) {
1066     const EventData *event_data = event->GetData();
1067     if (event_data &&
1068         event_data->GetFlavor() == BreakpointEventData::GetFlavorString())
1069       return static_cast<const BreakpointEventData *>(event->GetData());
1070   }
1071   return nullptr;
1072 }
1073 
1074 BreakpointEventType
1075 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1076     const EventSP &event_sp) {
1077   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1078 
1079   if (data == nullptr)
1080     return eBreakpointEventTypeInvalidType;
1081   else
1082     return data->GetBreakpointEventType();
1083 }
1084 
1085 BreakpointSP Breakpoint::BreakpointEventData::GetBreakpointFromEvent(
1086     const EventSP &event_sp) {
1087   BreakpointSP bp_sp;
1088 
1089   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1090   if (data)
1091     bp_sp = data->m_new_breakpoint_sp;
1092 
1093   return bp_sp;
1094 }
1095 
1096 size_t Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1097     const EventSP &event_sp) {
1098   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1099   if (data)
1100     return data->m_locations.GetSize();
1101 
1102   return 0;
1103 }
1104 
1105 lldb::BreakpointLocationSP
1106 Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent(
1107     const lldb::EventSP &event_sp, uint32_t bp_loc_idx) {
1108   lldb::BreakpointLocationSP bp_loc_sp;
1109 
1110   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1111   if (data) {
1112     bp_loc_sp = data->m_locations.GetByIndex(bp_loc_idx);
1113   }
1114 
1115   return bp_loc_sp;
1116 }
1117