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