]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Breakpoint/Breakpoint.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Breakpoint / Breakpoint.cpp
1 //===-- Breakpoint.cpp ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 #include "llvm/Support/Casting.h"
14
15 // Project includes
16 #include "lldb/Breakpoint/Breakpoint.h"
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 #include "lldb/Breakpoint/BreakpointLocationCollection.h"
19 #include "lldb/Breakpoint/BreakpointResolver.h"
20 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
21 #include "lldb/Core/Address.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/ModuleList.h"
24 #include "lldb/Core/SearchFilter.h"
25 #include "lldb/Core/Section.h"
26 #include "lldb/Target/SectionLoadList.h"
27 #include "lldb/Symbol/CompileUnit.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Symbol/Symbol.h"
30 #include "lldb/Symbol/SymbolContext.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/ThreadSpec.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/Utility/Stream.h"
35 #include "lldb/Utility/StreamString.h"
36
37 using namespace lldb;
38 using namespace lldb_private;
39 using namespace llvm;
40
41 const ConstString &Breakpoint::GetEventIdentifier() {
42   static ConstString g_identifier("event-identifier.breakpoint.changed");
43   return g_identifier;
44 }
45
46 const char *Breakpoint::g_option_names[static_cast<uint32_t>(
47     Breakpoint::OptionNames::LastOptionName)]{"Names", "Hardware"};
48
49 //----------------------------------------------------------------------
50 // Breakpoint constructor
51 //----------------------------------------------------------------------
52 Breakpoint::Breakpoint(Target &target, SearchFilterSP &filter_sp,
53                        BreakpointResolverSP &resolver_sp, bool hardware,
54                        bool resolve_indirect_symbols)
55     : m_being_created(true), m_hardware(hardware), m_target(target),
56       m_filter_sp(filter_sp), m_resolver_sp(resolver_sp),
57       m_options_up(new BreakpointOptions(true)), m_locations(*this),
58       m_resolve_indirect_symbols(resolve_indirect_symbols), m_hit_count(0) {
59   m_being_created = false;
60 }
61
62 Breakpoint::Breakpoint(Target &new_target, Breakpoint &source_bp)
63     : m_being_created(true), m_hardware(source_bp.m_hardware),
64       m_target(new_target), m_name_list(source_bp.m_name_list),
65       m_options_up(new BreakpointOptions(*source_bp.m_options_up.get())),
66       m_locations(*this),
67       m_resolve_indirect_symbols(source_bp.m_resolve_indirect_symbols),
68       m_hit_count(0) {
69   // Now go through and copy the filter & resolver:
70   m_resolver_sp = source_bp.m_resolver_sp->CopyForBreakpoint(*this);
71   m_filter_sp = source_bp.m_filter_sp->CopyForBreakpoint(*this);
72 }
73
74 //----------------------------------------------------------------------
75 // Destructor
76 //----------------------------------------------------------------------
77 Breakpoint::~Breakpoint() = default;
78
79 //----------------------------------------------------------------------
80 // Serialization
81 //----------------------------------------------------------------------
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     Target &target, StructuredData::ObjectSP &object_data, Status &error) {
132   BreakpointSP result_sp;
133
134   StructuredData::Dictionary *breakpoint_dict = object_data->GetAsDictionary();
135
136   if (!breakpoint_dict || !breakpoint_dict->IsValid()) {
137     error.SetErrorString("Can't deserialize from an invalid data object.");
138     return result_sp;
139   }
140
141   StructuredData::Dictionary *resolver_dict;
142   bool success = breakpoint_dict->GetValueForKeyAsDictionary(
143       BreakpointResolver::GetSerializationKey(), resolver_dict);
144   if (!success) {
145     error.SetErrorStringWithFormat(
146         "Breakpoint data missing toplevel resolver key");
147     return result_sp;
148   }
149
150   Status create_error;
151   BreakpointResolverSP resolver_sp =
152       BreakpointResolver::CreateFromStructuredData(*resolver_dict,
153                                                    create_error);
154   if (create_error.Fail()) {
155     error.SetErrorStringWithFormat(
156         "Error creating breakpoint resolver from data: %s.",
157         create_error.AsCString());
158     return result_sp;
159   }
160
161   StructuredData::Dictionary *filter_dict;
162   success = breakpoint_dict->GetValueForKeyAsDictionary(
163       SearchFilter::GetSerializationKey(), filter_dict);
164   SearchFilterSP filter_sp;
165   if (!success)
166     filter_sp.reset(
167         new SearchFilterForUnconstrainedSearches(target.shared_from_this()));
168   else {
169     filter_sp = SearchFilter::CreateFromStructuredData(target, *filter_dict,
170                                                        create_error);
171     if (create_error.Fail()) {
172       error.SetErrorStringWithFormat(
173           "Error creating breakpoint filter from data: %s.",
174           create_error.AsCString());
175       return result_sp;
176     }
177   }
178
179   std::unique_ptr<BreakpointOptions> options_up;
180   StructuredData::Dictionary *options_dict;
181   success = breakpoint_dict->GetValueForKeyAsDictionary(
182       BreakpointOptions::GetSerializationKey(), options_dict);
183   if (success) {
184     options_up = BreakpointOptions::CreateFromStructuredData(
185         target, *options_dict, create_error);
186     if (create_error.Fail()) {
187       error.SetErrorStringWithFormat(
188           "Error creating breakpoint options from data: %s.",
189           create_error.AsCString());
190       return result_sp;
191     }
192   }
193
194   bool hardware = false;
195   success = breakpoint_dict->GetValueForKeyAsBoolean(
196       Breakpoint::GetKey(OptionNames::Hardware), hardware);
197
198   result_sp =
199       target.CreateBreakpoint(filter_sp, resolver_sp, false, hardware, true);
200
201   if (result_sp && options_up) {
202     result_sp->m_options_up = std::move(options_up);
203   }
204
205   StructuredData::Array *names_array;
206   success = breakpoint_dict->GetValueForKeyAsArray(
207       Breakpoint::GetKey(OptionNames::Names), names_array);
208   if (success && names_array) {
209     size_t num_names = names_array->GetSize();
210     for (size_t i = 0; i < num_names; i++) {
211       llvm::StringRef name;
212       Status error;
213       success = names_array->GetItemAtIndexAsString(i, name);
214       target.AddNameToBreakpoint(result_sp, name.str().c_str(), error);
215     }
216   }
217
218   return result_sp;
219 }
220
221 bool Breakpoint::SerializedBreakpointMatchesNames(
222     StructuredData::ObjectSP &bkpt_object_sp, std::vector<std::string> &names) {
223   if (!bkpt_object_sp)
224     return false;
225
226   StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
227   if (!bkpt_dict)
228     return false;
229
230   if (names.empty())
231     return true;
232
233   StructuredData::Array *names_array;
234
235   bool success =
236       bkpt_dict->GetValueForKeyAsArray(GetKey(OptionNames::Names), names_array);
237   // If there are no names, it can't match these names;
238   if (!success)
239     return false;
240
241   size_t num_names = names_array->GetSize();
242   std::vector<std::string>::iterator begin = names.begin();
243   std::vector<std::string>::iterator end = names.end();
244
245   for (size_t i = 0; i < num_names; i++) {
246     llvm::StringRef name;
247     if (names_array->GetItemAtIndexAsString(i, name)) {
248       if (std::find(begin, end, name) != end) {
249         return true;
250       }
251     }
252   }
253   return false;
254 }
255
256 const lldb::TargetSP Breakpoint::GetTargetSP() {
257   return m_target.shared_from_this();
258 }
259
260 bool Breakpoint::IsInternal() const { return LLDB_BREAK_ID_IS_INTERNAL(m_bid); }
261
262 BreakpointLocationSP Breakpoint::AddLocation(const Address &addr,
263                                              bool *new_location) {
264   return m_locations.AddLocation(addr, m_resolve_indirect_symbols,
265                                  new_location);
266 }
267
268 BreakpointLocationSP Breakpoint::FindLocationByAddress(const Address &addr) {
269   return m_locations.FindByAddress(addr);
270 }
271
272 break_id_t Breakpoint::FindLocationIDByAddress(const Address &addr) {
273   return m_locations.FindIDByAddress(addr);
274 }
275
276 BreakpointLocationSP Breakpoint::FindLocationByID(break_id_t bp_loc_id) {
277   return m_locations.FindByID(bp_loc_id);
278 }
279
280 BreakpointLocationSP Breakpoint::GetLocationAtIndex(size_t index) {
281   return m_locations.GetByIndex(index);
282 }
283
284 void Breakpoint::RemoveInvalidLocations(const ArchSpec &arch) {
285   m_locations.RemoveInvalidLocations(arch);
286 }
287
288 // For each of the overall options we need to decide how they propagate to the
289 // location options.  This will determine the precedence of options on the
290 // breakpoint vs. its locations.
291
292 // Disable at the breakpoint level should override the location settings. That
293 // way you can conveniently turn off a whole breakpoint without messing up the
294 // individual settings.
295
296 void Breakpoint::SetEnabled(bool enable) {
297   if (enable == m_options_up->IsEnabled())
298     return;
299
300   m_options_up->SetEnabled(enable);
301   if (enable)
302     m_locations.ResolveAllBreakpointSites();
303   else
304     m_locations.ClearAllBreakpointSites();
305
306   SendBreakpointChangedEvent(enable ? eBreakpointEventTypeEnabled
307                                     : eBreakpointEventTypeDisabled);
308 }
309
310 bool Breakpoint::IsEnabled() { return m_options_up->IsEnabled(); }
311
312 void Breakpoint::SetIgnoreCount(uint32_t n) {
313   if (m_options_up->GetIgnoreCount() == n)
314     return;
315
316   m_options_up->SetIgnoreCount(n);
317   SendBreakpointChangedEvent(eBreakpointEventTypeIgnoreChanged);
318 }
319
320 void Breakpoint::DecrementIgnoreCount() {
321   uint32_t ignore = m_options_up->GetIgnoreCount();
322   if (ignore != 0)
323     m_options_up->SetIgnoreCount(ignore - 1);
324 }
325
326 uint32_t Breakpoint::GetIgnoreCount() const {
327   return m_options_up->GetIgnoreCount();
328 }
329
330 bool Breakpoint::IgnoreCountShouldStop() {
331   uint32_t ignore = GetIgnoreCount();
332   if (ignore != 0) {
333     // When we get here we know the location that caused the stop doesn't have
334     // an ignore count, since by contract we call it first...  So we don't have
335     // to find & decrement it, we only have to decrement our own ignore count.
336     DecrementIgnoreCount();
337     return false;
338   } else
339     return true;
340 }
341
342 uint32_t Breakpoint::GetHitCount() const { return m_hit_count; }
343
344 bool Breakpoint::IsOneShot() const { return m_options_up->IsOneShot(); }
345
346 void Breakpoint::SetOneShot(bool one_shot) {
347   m_options_up->SetOneShot(one_shot);
348 }
349
350 bool Breakpoint::IsAutoContinue() const { 
351   return m_options_up->IsAutoContinue();
352 }
353
354 void Breakpoint::SetAutoContinue(bool auto_continue) {
355   m_options_up->SetAutoContinue(auto_continue);
356 }
357
358 void Breakpoint::SetThreadID(lldb::tid_t thread_id) {
359   if (m_options_up->GetThreadSpec()->GetTID() == thread_id)
360     return;
361
362   m_options_up->GetThreadSpec()->SetTID(thread_id);
363   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
364 }
365
366 lldb::tid_t Breakpoint::GetThreadID() const {
367   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
368     return LLDB_INVALID_THREAD_ID;
369   else
370     return m_options_up->GetThreadSpecNoCreate()->GetTID();
371 }
372
373 void Breakpoint::SetThreadIndex(uint32_t index) {
374   if (m_options_up->GetThreadSpec()->GetIndex() == index)
375     return;
376
377   m_options_up->GetThreadSpec()->SetIndex(index);
378   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
379 }
380
381 uint32_t Breakpoint::GetThreadIndex() const {
382   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
383     return 0;
384   else
385     return m_options_up->GetThreadSpecNoCreate()->GetIndex();
386 }
387
388 void Breakpoint::SetThreadName(const char *thread_name) {
389   if (m_options_up->GetThreadSpec()->GetName() != nullptr &&
390       ::strcmp(m_options_up->GetThreadSpec()->GetName(), thread_name) == 0)
391     return;
392
393   m_options_up->GetThreadSpec()->SetName(thread_name);
394   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
395 }
396
397 const char *Breakpoint::GetThreadName() const {
398   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
399     return nullptr;
400   else
401     return m_options_up->GetThreadSpecNoCreate()->GetName();
402 }
403
404 void Breakpoint::SetQueueName(const char *queue_name) {
405   if (m_options_up->GetThreadSpec()->GetQueueName() != nullptr &&
406       ::strcmp(m_options_up->GetThreadSpec()->GetQueueName(), queue_name) == 0)
407     return;
408
409   m_options_up->GetThreadSpec()->SetQueueName(queue_name);
410   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
411 }
412
413 const char *Breakpoint::GetQueueName() const {
414   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
415     return nullptr;
416   else
417     return m_options_up->GetThreadSpecNoCreate()->GetQueueName();
418 }
419
420 void Breakpoint::SetCondition(const char *condition) {
421   m_options_up->SetCondition(condition);
422   SendBreakpointChangedEvent(eBreakpointEventTypeConditionChanged);
423 }
424
425 const char *Breakpoint::GetConditionText() const {
426   return m_options_up->GetConditionText();
427 }
428
429 // This function is used when "baton" doesn't need to be freed
430 void Breakpoint::SetCallback(BreakpointHitCallback callback, void *baton,
431                              bool is_synchronous) {
432   // The default "Baton" class will keep a copy of "baton" and won't free or
433   // delete it when it goes goes out of scope.
434   m_options_up->SetCallback(callback, std::make_shared<UntypedBaton>(baton),
435                             is_synchronous);
436
437   SendBreakpointChangedEvent(eBreakpointEventTypeCommandChanged);
438 }
439
440 // This function is used when a baton needs to be freed and therefore is
441 // contained in a "Baton" subclass.
442 void Breakpoint::SetCallback(BreakpointHitCallback callback,
443                              const BatonSP &callback_baton_sp,
444                              bool is_synchronous) {
445   m_options_up->SetCallback(callback, callback_baton_sp, is_synchronous);
446 }
447
448 void Breakpoint::ClearCallback() { m_options_up->ClearCallback(); }
449
450 bool Breakpoint::InvokeCallback(StoppointCallbackContext *context,
451                                 break_id_t bp_loc_id) {
452   return m_options_up->InvokeCallback(context, GetID(), bp_loc_id);
453 }
454
455 BreakpointOptions *Breakpoint::GetOptions() { return m_options_up.get(); }
456
457 const BreakpointOptions *Breakpoint::GetOptions() const {
458   return m_options_up.get();
459 }
460
461 void Breakpoint::ResolveBreakpoint() {
462   if (m_resolver_sp)
463     m_resolver_sp->ResolveBreakpoint(*m_filter_sp);
464 }
465
466 void Breakpoint::ResolveBreakpointInModules(
467     ModuleList &module_list, BreakpointLocationCollection &new_locations) {
468   m_locations.StartRecordingNewLocations(new_locations);
469
470   m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list);
471
472   m_locations.StopRecordingNewLocations();
473 }
474
475 void Breakpoint::ResolveBreakpointInModules(ModuleList &module_list,
476                                             bool send_event) {
477   if (m_resolver_sp) {
478     // If this is not an internal breakpoint, set up to record the new
479     // locations, then dispatch an event with the new locations.
480     if (!IsInternal() && send_event) {
481       BreakpointEventData *new_locations_event = new BreakpointEventData(
482           eBreakpointEventTypeLocationsAdded, shared_from_this());
483
484       ResolveBreakpointInModules(
485           module_list, new_locations_event->GetBreakpointLocationCollection());
486
487       if (new_locations_event->GetBreakpointLocationCollection().GetSize() !=
488           0) {
489         SendBreakpointChangedEvent(new_locations_event);
490       } else
491         delete new_locations_event;
492     } else {
493       m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list);
494     }
495   }
496 }
497
498 void Breakpoint::ClearAllBreakpointSites() {
499   m_locations.ClearAllBreakpointSites();
500 }
501
502 //----------------------------------------------------------------------
503 // ModulesChanged: Pass in a list of new modules, and
504 //----------------------------------------------------------------------
505
506 void Breakpoint::ModulesChanged(ModuleList &module_list, bool load,
507                                 bool delete_locations) {
508   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
509   if (log)
510     log->Printf("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             if (log)
564               log->Printf("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 (FileSpec::Equal(*old_sc.comp_unit, *new_sc.comp_unit, true)) {
652         // Now check the functions:
653         if (old_sc.function && new_sc.function &&
654             (old_sc.function->GetName() == new_sc.function->GetName())) {
655           equivalent_scs = true;
656         }
657       }
658     } else if (old_sc.symbol && new_sc.symbol) {
659       if (Mangled::Compare(old_sc.symbol->GetMangled(),
660                            new_sc.symbol->GetMangled()) == 0) {
661         equivalent_scs = true;
662       }
663     }
664   }
665   return equivalent_scs;
666 }
667 } // anonymous namespace
668
669 void Breakpoint::ModuleReplaced(ModuleSP old_module_sp,
670                                 ModuleSP new_module_sp) {
671   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
672   if (log)
673     log->Printf("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.begin(), old_id_vec.end());
789             llvm::sort(new_id_vec.begin(), new_id_vec.end());
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 size_t Breakpoint::GetNumLocations() const { return m_locations.GetSize(); }
861
862 bool Breakpoint::AddName(llvm::StringRef new_name) {
863   m_name_list.insert(new_name.str().c_str());
864   return true;
865 }
866
867 void Breakpoint::GetDescription(Stream *s, lldb::DescriptionLevel level,
868                                 bool show_locations) {
869   assert(s != nullptr);
870
871   if (!m_kind_description.empty()) {
872     if (level == eDescriptionLevelBrief) {
873       s->PutCString(GetBreakpointKind());
874       return;
875     } else
876       s->Printf("Kind: %s\n", GetBreakpointKind());
877   }
878
879   const size_t num_locations = GetNumLocations();
880   const size_t num_resolved_locations = GetNumResolvedLocations();
881
882   // They just made the breakpoint, they don't need to be told HOW they made
883   // it... Also, we'll print the breakpoint number differently depending on
884   // whether there is 1 or more locations.
885   if (level != eDescriptionLevelInitial) {
886     s->Printf("%i: ", GetID());
887     GetResolverDescription(s);
888     GetFilterDescription(s);
889   }
890
891   switch (level) {
892   case lldb::eDescriptionLevelBrief:
893   case lldb::eDescriptionLevelFull:
894     if (num_locations > 0) {
895       s->Printf(", locations = %" PRIu64, (uint64_t)num_locations);
896       if (num_resolved_locations > 0)
897         s->Printf(", resolved = %" PRIu64 ", hit count = %d",
898                   (uint64_t)num_resolved_locations, GetHitCount());
899     } else {
900       // Don't print the pending notification for exception resolvers since we
901       // don't generally know how to set them until the target is run.
902       if (m_resolver_sp->getResolverID() !=
903           BreakpointResolver::ExceptionResolver)
904         s->Printf(", locations = 0 (pending)");
905     }
906
907     GetOptions()->GetDescription(s, level);
908
909     if (m_precondition_sp)
910       m_precondition_sp->GetDescription(*s, level);
911
912     if (level == lldb::eDescriptionLevelFull) {
913       if (!m_name_list.empty()) {
914         s->EOL();
915         s->Indent();
916         s->Printf("Names:");
917         s->EOL();
918         s->IndentMore();
919         for (std::string name : m_name_list) {
920           s->Indent();
921           s->Printf("%s\n", name.c_str());
922         }
923         s->IndentLess();
924       }
925       s->IndentLess();
926       s->EOL();
927     }
928     break;
929
930   case lldb::eDescriptionLevelInitial:
931     s->Printf("Breakpoint %i: ", GetID());
932     if (num_locations == 0) {
933       s->Printf("no locations (pending).");
934     } else if (num_locations == 1 && !show_locations) {
935       // There is only one location, so we'll just print that location
936       // information.
937       GetLocationAtIndex(0)->GetDescription(s, level);
938     } else {
939       s->Printf("%" PRIu64 " locations.", static_cast<uint64_t>(num_locations));
940     }
941     s->EOL();
942     break;
943
944   case lldb::eDescriptionLevelVerbose:
945     // Verbose mode does a debug dump of the breakpoint
946     Dump(s);
947     s->EOL();
948     // s->Indent();
949     GetOptions()->GetDescription(s, level);
950     break;
951
952   default:
953     break;
954   }
955
956   // The brief description is just the location name (1.2 or whatever).  That's
957   // pointless to show in the breakpoint's description, so suppress it.
958   if (show_locations && level != lldb::eDescriptionLevelBrief) {
959     s->IndentMore();
960     for (size_t i = 0; i < num_locations; ++i) {
961       BreakpointLocation *loc = GetLocationAtIndex(i).get();
962       loc->GetDescription(s, level);
963       s->EOL();
964     }
965     s->IndentLess();
966   }
967 }
968
969 void Breakpoint::GetResolverDescription(Stream *s) {
970   if (m_resolver_sp)
971     m_resolver_sp->GetDescription(s);
972 }
973
974 bool Breakpoint::GetMatchingFileLine(const ConstString &filename,
975                                      uint32_t line_number,
976                                      BreakpointLocationCollection &loc_coll) {
977   // TODO: To be correct, this method needs to fill the breakpoint location
978   // collection
979   //       with the location IDs which match the filename and line_number.
980   //
981
982   if (m_resolver_sp) {
983     BreakpointResolverFileLine *resolverFileLine =
984         dyn_cast<BreakpointResolverFileLine>(m_resolver_sp.get());
985     if (resolverFileLine &&
986         resolverFileLine->m_file_spec.GetFilename() == filename &&
987         resolverFileLine->m_line_number == line_number) {
988       return true;
989     }
990   }
991   return false;
992 }
993
994 void Breakpoint::GetFilterDescription(Stream *s) {
995   m_filter_sp->GetDescription(s);
996 }
997
998 bool Breakpoint::EvaluatePrecondition(StoppointCallbackContext &context) {
999   if (!m_precondition_sp)
1000     return true;
1001
1002   return m_precondition_sp->EvaluatePrecondition(context);
1003 }
1004
1005 bool Breakpoint::BreakpointPrecondition::EvaluatePrecondition(
1006     StoppointCallbackContext &context) {
1007   return true;
1008 }
1009
1010 void Breakpoint::BreakpointPrecondition::GetDescription(
1011     Stream &stream, lldb::DescriptionLevel level) {}
1012
1013 Status
1014 Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) {
1015   Status error;
1016   error.SetErrorString("Base breakpoint precondition has no options.");
1017   return error;
1018 }
1019
1020 void Breakpoint::SendBreakpointChangedEvent(
1021     lldb::BreakpointEventType eventKind) {
1022   if (!m_being_created && !IsInternal() &&
1023       GetTarget().EventTypeHasListeners(
1024           Target::eBroadcastBitBreakpointChanged)) {
1025     BreakpointEventData *data =
1026         new Breakpoint::BreakpointEventData(eventKind, shared_from_this());
1027
1028     GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, data);
1029   }
1030 }
1031
1032 void Breakpoint::SendBreakpointChangedEvent(BreakpointEventData *data) {
1033   if (data == nullptr)
1034     return;
1035
1036   if (!m_being_created && !IsInternal() &&
1037       GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged))
1038     GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, data);
1039   else
1040     delete data;
1041 }
1042
1043 Breakpoint::BreakpointEventData::BreakpointEventData(
1044     BreakpointEventType sub_type, const BreakpointSP &new_breakpoint_sp)
1045     : EventData(), m_breakpoint_event(sub_type),
1046       m_new_breakpoint_sp(new_breakpoint_sp) {}
1047
1048 Breakpoint::BreakpointEventData::~BreakpointEventData() = default;
1049
1050 const ConstString &Breakpoint::BreakpointEventData::GetFlavorString() {
1051   static ConstString g_flavor("Breakpoint::BreakpointEventData");
1052   return g_flavor;
1053 }
1054
1055 const ConstString &Breakpoint::BreakpointEventData::GetFlavor() const {
1056   return BreakpointEventData::GetFlavorString();
1057 }
1058
1059 BreakpointSP &Breakpoint::BreakpointEventData::GetBreakpoint() {
1060   return m_new_breakpoint_sp;
1061 }
1062
1063 BreakpointEventType
1064 Breakpoint::BreakpointEventData::GetBreakpointEventType() const {
1065   return m_breakpoint_event;
1066 }
1067
1068 void Breakpoint::BreakpointEventData::Dump(Stream *s) const {}
1069
1070 const Breakpoint::BreakpointEventData *
1071 Breakpoint::BreakpointEventData::GetEventDataFromEvent(const Event *event) {
1072   if (event) {
1073     const EventData *event_data = event->GetData();
1074     if (event_data &&
1075         event_data->GetFlavor() == BreakpointEventData::GetFlavorString())
1076       return static_cast<const BreakpointEventData *>(event->GetData());
1077   }
1078   return nullptr;
1079 }
1080
1081 BreakpointEventType
1082 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1083     const EventSP &event_sp) {
1084   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1085
1086   if (data == nullptr)
1087     return eBreakpointEventTypeInvalidType;
1088   else
1089     return data->GetBreakpointEventType();
1090 }
1091
1092 BreakpointSP Breakpoint::BreakpointEventData::GetBreakpointFromEvent(
1093     const EventSP &event_sp) {
1094   BreakpointSP bp_sp;
1095
1096   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1097   if (data)
1098     bp_sp = data->m_new_breakpoint_sp;
1099
1100   return bp_sp;
1101 }
1102
1103 size_t Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1104     const EventSP &event_sp) {
1105   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1106   if (data)
1107     return data->m_locations.GetSize();
1108
1109   return 0;
1110 }
1111
1112 lldb::BreakpointLocationSP
1113 Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent(
1114     const lldb::EventSP &event_sp, uint32_t bp_loc_idx) {
1115   lldb::BreakpointLocationSP bp_loc_sp;
1116
1117   const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get());
1118   if (data) {
1119     bp_loc_sp = data->m_locations.GetByIndex(bp_loc_idx);
1120   }
1121
1122   return bp_loc_sp;
1123 }