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