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