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