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