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