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 #include "llvm/Support/Casting.h"
11 
12 #include "lldb/Breakpoint/Breakpoint.h"
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Breakpoint/BreakpointLocationCollection.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 using namespace lldb;
34 using namespace lldb_private;
35 using namespace llvm;
36 
GetEventIdentifier()37 const ConstString &Breakpoint::GetEventIdentifier() {
38   static ConstString g_identifier("event-identifier.breakpoint.changed");
39   return g_identifier;
40 }
41 
42 const char *Breakpoint::g_option_names[static_cast<uint32_t>(
43     Breakpoint::OptionNames::LastOptionName)]{"Names", "Hardware"};
44 
45 //----------------------------------------------------------------------
46 // Breakpoint constructor
47 //----------------------------------------------------------------------
Breakpoint(Target & target,SearchFilterSP & filter_sp,BreakpointResolverSP & resolver_sp,bool hardware,bool resolve_indirect_symbols)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 
Breakpoint(Target & new_target,Breakpoint & source_bp)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.get())),
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 //----------------------------------------------------------------------
71 // Destructor
72 //----------------------------------------------------------------------
73 Breakpoint::~Breakpoint() = default;
74 
75 //----------------------------------------------------------------------
76 // Serialization
77 //----------------------------------------------------------------------
SerializeToStructuredData()78 StructuredData::ObjectSP Breakpoint::SerializeToStructuredData() {
79   // Serialize the resolver:
80   StructuredData::DictionarySP breakpoint_dict_sp(
81       new StructuredData::Dictionary());
82   StructuredData::DictionarySP breakpoint_contents_sp(
83       new StructuredData::Dictionary());
84 
85   if (!m_name_list.empty()) {
86     StructuredData::ArraySP names_array_sp(new StructuredData::Array());
87     for (auto name : m_name_list) {
88       names_array_sp->AddItem(
89           StructuredData::StringSP(new StructuredData::String(name)));
90     }
91     breakpoint_contents_sp->AddItem(Breakpoint::GetKey(OptionNames::Names),
92                                     names_array_sp);
93   }
94 
95   breakpoint_contents_sp->AddBooleanItem(
96       Breakpoint::GetKey(OptionNames::Hardware), m_hardware);
97 
98   StructuredData::ObjectSP resolver_dict_sp(
99       m_resolver_sp->SerializeToStructuredData());
100   if (!resolver_dict_sp)
101     return StructuredData::ObjectSP();
102 
103   breakpoint_contents_sp->AddItem(BreakpointResolver::GetSerializationKey(),
104                                   resolver_dict_sp);
105 
106   StructuredData::ObjectSP filter_dict_sp(
107       m_filter_sp->SerializeToStructuredData());
108   if (!filter_dict_sp)
109     return StructuredData::ObjectSP();
110 
111   breakpoint_contents_sp->AddItem(SearchFilter::GetSerializationKey(),
112                                   filter_dict_sp);
113 
114   StructuredData::ObjectSP options_dict_sp(
115       m_options_up->SerializeToStructuredData());
116   if (!options_dict_sp)
117     return StructuredData::ObjectSP();
118 
119   breakpoint_contents_sp->AddItem(BreakpointOptions::GetSerializationKey(),
120                                   options_dict_sp);
121 
122   breakpoint_dict_sp->AddItem(GetSerializationKey(), breakpoint_contents_sp);
123   return breakpoint_dict_sp;
124 }
125 
CreateFromStructuredData(Target & target,StructuredData::ObjectSP & object_data,Status & error)126 lldb::BreakpointSP Breakpoint::CreateFromStructuredData(
127     Target &target, StructuredData::ObjectSP &object_data, Status &error) {
128   BreakpointSP result_sp;
129 
130   StructuredData::Dictionary *breakpoint_dict = object_data->GetAsDictionary();
131 
132   if (!breakpoint_dict || !breakpoint_dict->IsValid()) {
133     error.SetErrorString("Can't deserialize from an invalid data object.");
134     return result_sp;
135   }
136 
137   StructuredData::Dictionary *resolver_dict;
138   bool success = breakpoint_dict->GetValueForKeyAsDictionary(
139       BreakpointResolver::GetSerializationKey(), resolver_dict);
140   if (!success) {
141     error.SetErrorStringWithFormat(
142         "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.reset(
163         new SearchFilterForUnconstrainedSearches(target.shared_from_this()));
164   else {
165     filter_sp = SearchFilter::CreateFromStructuredData(target, *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   success = breakpoint_dict->GetValueForKeyAsDictionary(
178       BreakpointOptions::GetSerializationKey(), options_dict);
179   if (success) {
180     options_up = BreakpointOptions::CreateFromStructuredData(
181         target, *options_dict, create_error);
182     if (create_error.Fail()) {
183       error.SetErrorStringWithFormat(
184           "Error creating breakpoint options from data: %s.",
185           create_error.AsCString());
186       return result_sp;
187     }
188   }
189 
190   bool hardware = false;
191   success = breakpoint_dict->GetValueForKeyAsBoolean(
192       Breakpoint::GetKey(OptionNames::Hardware), hardware);
193 
194   result_sp =
195       target.CreateBreakpoint(filter_sp, resolver_sp, false, hardware, true);
196 
197   if (result_sp && options_up) {
198     result_sp->m_options_up = std::move(options_up);
199   }
200 
201   StructuredData::Array *names_array;
202   success = breakpoint_dict->GetValueForKeyAsArray(
203       Breakpoint::GetKey(OptionNames::Names), names_array);
204   if (success && names_array) {
205     size_t num_names = names_array->GetSize();
206     for (size_t i = 0; i < num_names; i++) {
207       llvm::StringRef name;
208       Status error;
209       success = names_array->GetItemAtIndexAsString(i, name);
210       target.AddNameToBreakpoint(result_sp, name.str().c_str(), error);
211     }
212   }
213 
214   return result_sp;
215 }
216 
SerializedBreakpointMatchesNames(StructuredData::ObjectSP & bkpt_object_sp,std::vector<std::string> & names)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   std::vector<std::string>::iterator begin = names.begin();
239   std::vector<std::string>::iterator end = names.end();
240 
241   for (size_t i = 0; i < num_names; i++) {
242     llvm::StringRef name;
243     if (names_array->GetItemAtIndexAsString(i, name)) {
244       if (std::find(begin, end, name) != end) {
245         return true;
246       }
247     }
248   }
249   return false;
250 }
251 
GetTargetSP()252 const lldb::TargetSP Breakpoint::GetTargetSP() {
253   return m_target.shared_from_this();
254 }
255 
IsInternal() const256 bool Breakpoint::IsInternal() const { return LLDB_BREAK_ID_IS_INTERNAL(m_bid); }
257 
AddLocation(const Address & addr,bool * new_location)258 BreakpointLocationSP Breakpoint::AddLocation(const Address &addr,
259                                              bool *new_location) {
260   return m_locations.AddLocation(addr, m_resolve_indirect_symbols,
261                                  new_location);
262 }
263 
FindLocationByAddress(const Address & addr)264 BreakpointLocationSP Breakpoint::FindLocationByAddress(const Address &addr) {
265   return m_locations.FindByAddress(addr);
266 }
267 
FindLocationIDByAddress(const Address & addr)268 break_id_t Breakpoint::FindLocationIDByAddress(const Address &addr) {
269   return m_locations.FindIDByAddress(addr);
270 }
271 
FindLocationByID(break_id_t bp_loc_id)272 BreakpointLocationSP Breakpoint::FindLocationByID(break_id_t bp_loc_id) {
273   return m_locations.FindByID(bp_loc_id);
274 }
275 
GetLocationAtIndex(size_t index)276 BreakpointLocationSP Breakpoint::GetLocationAtIndex(size_t index) {
277   return m_locations.GetByIndex(index);
278 }
279 
RemoveInvalidLocations(const ArchSpec & arch)280 void Breakpoint::RemoveInvalidLocations(const ArchSpec &arch) {
281   m_locations.RemoveInvalidLocations(arch);
282 }
283 
284 // For each of the overall options we need to decide how they propagate to the
285 // location options.  This will determine the precedence of options on the
286 // breakpoint vs. its locations.
287 
288 // Disable at the breakpoint level should override the location settings. That
289 // way you can conveniently turn off a whole breakpoint without messing up the
290 // individual settings.
291 
SetEnabled(bool enable)292 void Breakpoint::SetEnabled(bool enable) {
293   if (enable == m_options_up->IsEnabled())
294     return;
295 
296   m_options_up->SetEnabled(enable);
297   if (enable)
298     m_locations.ResolveAllBreakpointSites();
299   else
300     m_locations.ClearAllBreakpointSites();
301 
302   SendBreakpointChangedEvent(enable ? eBreakpointEventTypeEnabled
303                                     : eBreakpointEventTypeDisabled);
304 }
305 
IsEnabled()306 bool Breakpoint::IsEnabled() { return m_options_up->IsEnabled(); }
307 
SetIgnoreCount(uint32_t n)308 void Breakpoint::SetIgnoreCount(uint32_t n) {
309   if (m_options_up->GetIgnoreCount() == n)
310     return;
311 
312   m_options_up->SetIgnoreCount(n);
313   SendBreakpointChangedEvent(eBreakpointEventTypeIgnoreChanged);
314 }
315 
DecrementIgnoreCount()316 void Breakpoint::DecrementIgnoreCount() {
317   uint32_t ignore = m_options_up->GetIgnoreCount();
318   if (ignore != 0)
319     m_options_up->SetIgnoreCount(ignore - 1);
320 }
321 
GetIgnoreCount() const322 uint32_t Breakpoint::GetIgnoreCount() const {
323   return m_options_up->GetIgnoreCount();
324 }
325 
IgnoreCountShouldStop()326 bool Breakpoint::IgnoreCountShouldStop() {
327   uint32_t ignore = GetIgnoreCount();
328   if (ignore != 0) {
329     // When we get here we know the location that caused the stop doesn't have
330     // an ignore count, since by contract we call it first...  So we don't have
331     // to find & decrement it, we only have to decrement our own ignore count.
332     DecrementIgnoreCount();
333     return false;
334   } else
335     return true;
336 }
337 
GetHitCount() const338 uint32_t Breakpoint::GetHitCount() const { return m_hit_count; }
339 
IsOneShot() const340 bool Breakpoint::IsOneShot() const { return m_options_up->IsOneShot(); }
341 
SetOneShot(bool one_shot)342 void Breakpoint::SetOneShot(bool one_shot) {
343   m_options_up->SetOneShot(one_shot);
344 }
345 
IsAutoContinue() const346 bool Breakpoint::IsAutoContinue() const {
347   return m_options_up->IsAutoContinue();
348 }
349 
SetAutoContinue(bool auto_continue)350 void Breakpoint::SetAutoContinue(bool auto_continue) {
351   m_options_up->SetAutoContinue(auto_continue);
352 }
353 
SetThreadID(lldb::tid_t thread_id)354 void Breakpoint::SetThreadID(lldb::tid_t thread_id) {
355   if (m_options_up->GetThreadSpec()->GetTID() == thread_id)
356     return;
357 
358   m_options_up->GetThreadSpec()->SetTID(thread_id);
359   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
360 }
361 
GetThreadID() const362 lldb::tid_t Breakpoint::GetThreadID() const {
363   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
364     return LLDB_INVALID_THREAD_ID;
365   else
366     return m_options_up->GetThreadSpecNoCreate()->GetTID();
367 }
368 
SetThreadIndex(uint32_t index)369 void Breakpoint::SetThreadIndex(uint32_t index) {
370   if (m_options_up->GetThreadSpec()->GetIndex() == index)
371     return;
372 
373   m_options_up->GetThreadSpec()->SetIndex(index);
374   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
375 }
376 
GetThreadIndex() const377 uint32_t Breakpoint::GetThreadIndex() const {
378   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
379     return 0;
380   else
381     return m_options_up->GetThreadSpecNoCreate()->GetIndex();
382 }
383 
SetThreadName(const char * thread_name)384 void Breakpoint::SetThreadName(const char *thread_name) {
385   if (m_options_up->GetThreadSpec()->GetName() != nullptr &&
386       ::strcmp(m_options_up->GetThreadSpec()->GetName(), thread_name) == 0)
387     return;
388 
389   m_options_up->GetThreadSpec()->SetName(thread_name);
390   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
391 }
392 
GetThreadName() const393 const char *Breakpoint::GetThreadName() const {
394   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
395     return nullptr;
396   else
397     return m_options_up->GetThreadSpecNoCreate()->GetName();
398 }
399 
SetQueueName(const char * queue_name)400 void Breakpoint::SetQueueName(const char *queue_name) {
401   if (m_options_up->GetThreadSpec()->GetQueueName() != nullptr &&
402       ::strcmp(m_options_up->GetThreadSpec()->GetQueueName(), queue_name) == 0)
403     return;
404 
405   m_options_up->GetThreadSpec()->SetQueueName(queue_name);
406   SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged);
407 }
408 
GetQueueName() const409 const char *Breakpoint::GetQueueName() const {
410   if (m_options_up->GetThreadSpecNoCreate() == nullptr)
411     return nullptr;
412   else
413     return m_options_up->GetThreadSpecNoCreate()->GetQueueName();
414 }
415 
SetCondition(const char * condition)416 void Breakpoint::SetCondition(const char *condition) {
417   m_options_up->SetCondition(condition);
418   SendBreakpointChangedEvent(eBreakpointEventTypeConditionChanged);
419 }
420 
GetConditionText() const421 const char *Breakpoint::GetConditionText() const {
422   return m_options_up->GetConditionText();
423 }
424 
425 // This function is used when "baton" doesn't need to be freed
SetCallback(BreakpointHitCallback callback,void * baton,bool is_synchronous)426 void Breakpoint::SetCallback(BreakpointHitCallback callback, void *baton,
427                              bool is_synchronous) {
428   // The default "Baton" class will keep a copy of "baton" and won't free or
429   // delete it when it goes goes out of scope.
430   m_options_up->SetCallback(callback, std::make_shared<UntypedBaton>(baton),
431                             is_synchronous);
432 
433   SendBreakpointChangedEvent(eBreakpointEventTypeCommandChanged);
434 }
435 
436 // This function is used when a baton needs to be freed and therefore is
437 // contained in a "Baton" subclass.
SetCallback(BreakpointHitCallback callback,const BatonSP & callback_baton_sp,bool is_synchronous)438 void Breakpoint::SetCallback(BreakpointHitCallback callback,
439                              const BatonSP &callback_baton_sp,
440                              bool is_synchronous) {
441   m_options_up->SetCallback(callback, callback_baton_sp, is_synchronous);
442 }
443 
ClearCallback()444 void Breakpoint::ClearCallback() { m_options_up->ClearCallback(); }
445 
InvokeCallback(StoppointCallbackContext * context,break_id_t bp_loc_id)446 bool Breakpoint::InvokeCallback(StoppointCallbackContext *context,
447                                 break_id_t bp_loc_id) {
448   return m_options_up->InvokeCallback(context, GetID(), bp_loc_id);
449 }
450 
GetOptions()451 BreakpointOptions *Breakpoint::GetOptions() { return m_options_up.get(); }
452 
GetOptions() const453 const BreakpointOptions *Breakpoint::GetOptions() const {
454   return m_options_up.get();
455 }
456 
ResolveBreakpoint()457 void Breakpoint::ResolveBreakpoint() {
458   if (m_resolver_sp)
459     m_resolver_sp->ResolveBreakpoint(*m_filter_sp);
460 }
461 
ResolveBreakpointInModules(ModuleList & module_list,BreakpointLocationCollection & new_locations)462 void Breakpoint::ResolveBreakpointInModules(
463     ModuleList &module_list, BreakpointLocationCollection &new_locations) {
464   m_locations.StartRecordingNewLocations(new_locations);
465 
466   m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list);
467 
468   m_locations.StopRecordingNewLocations();
469 }
470 
ResolveBreakpointInModules(ModuleList & module_list,bool send_event)471 void Breakpoint::ResolveBreakpointInModules(ModuleList &module_list,
472                                             bool send_event) {
473   if (m_resolver_sp) {
474     // If this is not an internal breakpoint, set up to record the new
475     // locations, then dispatch an event with the new locations.
476     if (!IsInternal() && send_event) {
477       BreakpointEventData *new_locations_event = new BreakpointEventData(
478           eBreakpointEventTypeLocationsAdded, shared_from_this());
479 
480       ResolveBreakpointInModules(
481           module_list, new_locations_event->GetBreakpointLocationCollection());
482 
483       if (new_locations_event->GetBreakpointLocationCollection().GetSize() !=
484           0) {
485         SendBreakpointChangedEvent(new_locations_event);
486       } else
487         delete new_locations_event;
488     } else {
489       m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list);
490     }
491   }
492 }
493 
ClearAllBreakpointSites()494 void Breakpoint::ClearAllBreakpointSites() {
495   m_locations.ClearAllBreakpointSites();
496 }
497 
498 //----------------------------------------------------------------------
499 // ModulesChanged: Pass in a list of new modules, and
500 //----------------------------------------------------------------------
501 
ModulesChanged(ModuleList & module_list,bool load,bool delete_locations)502 void Breakpoint::ModulesChanged(ModuleList &module_list, bool load,
503                                 bool delete_locations) {
504   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
505   if (log)
506     log->Printf("Breakpoint::ModulesChanged: num_modules: %zu load: %i "
507                 "delete_locations: %i\n",
508                 module_list.GetSize(), load, delete_locations);
509 
510   std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
511   if (load) {
512     // The logic for handling new modules is:
513     // 1) If the filter rejects this module, then skip it. 2) Run through the
514     // current location list and if there are any locations
515     //    for that module, we mark the module as "seen" and we don't try to
516     //    re-resolve
517     //    breakpoint locations for that module.
518     //    However, we do add breakpoint sites to these locations if needed.
519     // 3) If we don't see this module in our breakpoint location list, call
520     // ResolveInModules.
521 
522     ModuleList new_modules; // We'll stuff the "unseen" modules in this list,
523                             // and then resolve
524     // them after the locations pass.  Have to do it this way because resolving
525     // breakpoints will add new locations potentially.
526 
527     for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
528       bool seen = false;
529       if (!m_filter_sp->ModulePasses(module_sp))
530         continue;
531 
532       BreakpointLocationCollection locations_with_no_section;
533       for (BreakpointLocationSP break_loc_sp :
534            m_locations.BreakpointLocations()) {
535 
536         // If the section for this location was deleted, that means it's Module
537         // has gone away but somebody forgot to tell us. Let's clean it up
538         // here.
539         Address section_addr(break_loc_sp->GetAddress());
540         if (section_addr.SectionWasDeleted()) {
541           locations_with_no_section.Add(break_loc_sp);
542           continue;
543         }
544 
545         if (!break_loc_sp->IsEnabled())
546           continue;
547 
548         SectionSP section_sp(section_addr.GetSection());
549 
550         // If we don't have a Section, that means this location is a raw
551         // address that we haven't resolved to a section yet.  So we'll have to
552         // look in all the new modules to resolve this location. Otherwise, if
553         // it was set in this module, re-resolve it here.
554         if (section_sp && section_sp->GetModule() == module_sp) {
555           if (!seen)
556             seen = true;
557 
558           if (!break_loc_sp->ResolveBreakpointSite()) {
559             if (log)
560               log->Printf("Warning: could not set breakpoint site for "
561                           "breakpoint location %d of breakpoint %d.\n",
562                           break_loc_sp->GetID(), GetID());
563           }
564         }
565       }
566 
567       size_t num_to_delete = locations_with_no_section.GetSize();
568 
569       for (size_t i = 0; i < num_to_delete; i++)
570         m_locations.RemoveLocation(locations_with_no_section.GetByIndex(i));
571 
572       if (!seen)
573         new_modules.AppendIfNeeded(module_sp);
574     }
575 
576     if (new_modules.GetSize() > 0) {
577       ResolveBreakpointInModules(new_modules);
578     }
579   } else {
580     // Go through the currently set locations and if any have breakpoints in
581     // the module list, then remove their breakpoint sites, and their locations
582     // if asked to.
583 
584     BreakpointEventData *removed_locations_event;
585     if (!IsInternal())
586       removed_locations_event = new BreakpointEventData(
587           eBreakpointEventTypeLocationsRemoved, shared_from_this());
588     else
589       removed_locations_event = nullptr;
590 
591     size_t num_modules = module_list.GetSize();
592     for (size_t i = 0; i < num_modules; i++) {
593       ModuleSP module_sp(module_list.GetModuleAtIndexUnlocked(i));
594       if (m_filter_sp->ModulePasses(module_sp)) {
595         size_t loc_idx = 0;
596         size_t num_locations = m_locations.GetSize();
597         BreakpointLocationCollection locations_to_remove;
598         for (loc_idx = 0; loc_idx < num_locations; loc_idx++) {
599           BreakpointLocationSP break_loc_sp(m_locations.GetByIndex(loc_idx));
600           SectionSP section_sp(break_loc_sp->GetAddress().GetSection());
601           if (section_sp && section_sp->GetModule() == module_sp) {
602             // Remove this breakpoint since the shared library is unloaded, but
603             // keep the breakpoint location around so we always get complete
604             // hit count and breakpoint lifetime info
605             break_loc_sp->ClearBreakpointSite();
606             if (removed_locations_event) {
607               removed_locations_event->GetBreakpointLocationCollection().Add(
608                   break_loc_sp);
609             }
610             if (delete_locations)
611               locations_to_remove.Add(break_loc_sp);
612           }
613         }
614 
615         if (delete_locations) {
616           size_t num_locations_to_remove = locations_to_remove.GetSize();
617           for (loc_idx = 0; loc_idx < num_locations_to_remove; loc_idx++)
618             m_locations.RemoveLocation(locations_to_remove.GetByIndex(loc_idx));
619         }
620       }
621     }
622     SendBreakpointChangedEvent(removed_locations_event);
623   }
624 }
625 
626 namespace {
SymbolContextsMightBeEquivalent(SymbolContext & old_sc,SymbolContext & new_sc)627 static bool SymbolContextsMightBeEquivalent(SymbolContext &old_sc,
628                                             SymbolContext &new_sc) {
629   bool equivalent_scs = false;
630 
631   if (old_sc.module_sp.get() == new_sc.module_sp.get()) {
632     // If these come from the same module, we can directly compare the
633     // pointers:
634     if (old_sc.comp_unit && new_sc.comp_unit &&
635         (old_sc.comp_unit == new_sc.comp_unit)) {
636       if (old_sc.function && new_sc.function &&
637           (old_sc.function == new_sc.function)) {
638         equivalent_scs = true;
639       }
640     } else if (old_sc.symbol && new_sc.symbol &&
641                (old_sc.symbol == new_sc.symbol)) {
642       equivalent_scs = true;
643     }
644   } else {
645     // Otherwise we will compare by name...
646     if (old_sc.comp_unit && new_sc.comp_unit) {
647       if (FileSpec::Equal(*old_sc.comp_unit, *new_sc.comp_unit, true)) {
648         // Now check the functions:
649         if (old_sc.function && new_sc.function &&
650             (old_sc.function->GetName() == new_sc.function->GetName())) {
651           equivalent_scs = true;
652         }
653       }
654     } else if (old_sc.symbol && new_sc.symbol) {
655       if (Mangled::Compare(old_sc.symbol->GetMangled(),
656                            new_sc.symbol->GetMangled()) == 0) {
657         equivalent_scs = true;
658       }
659     }
660   }
661   return equivalent_scs;
662 }
663 } // anonymous namespace
664 
ModuleReplaced(ModuleSP old_module_sp,ModuleSP new_module_sp)665 void Breakpoint::ModuleReplaced(ModuleSP old_module_sp,
666                                 ModuleSP new_module_sp) {
667   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
668   if (log)
669     log->Printf("Breakpoint::ModulesReplaced for %s\n",
670                 old_module_sp->GetSpecificationDescription().c_str());
671   // First find all the locations that are in the old module
672 
673   BreakpointLocationCollection old_break_locs;
674   for (BreakpointLocationSP break_loc_sp : m_locations.BreakpointLocations()) {
675     SectionSP section_sp = break_loc_sp->GetAddress().GetSection();
676     if (section_sp && section_sp->GetModule() == old_module_sp) {
677       old_break_locs.Add(break_loc_sp);
678     }
679   }
680 
681   size_t num_old_locations = old_break_locs.GetSize();
682 
683   if (num_old_locations == 0) {
684     // There were no locations in the old module, so we just need to check if
685     // there were any in the new module.
686     ModuleList temp_list;
687     temp_list.Append(new_module_sp);
688     ResolveBreakpointInModules(temp_list);
689   } else {
690     // First search the new module for locations. Then compare this with the
691     // old list, copy over locations that "look the same" Then delete the old
692     // locations. Finally remember to post the creation event.
693     //
694     // Two locations are the same if they have the same comp unit & function
695     // (by name) and there are the same number of locations in the old function
696     // as in the new one.
697 
698     ModuleList temp_list;
699     temp_list.Append(new_module_sp);
700     BreakpointLocationCollection new_break_locs;
701     ResolveBreakpointInModules(temp_list, new_break_locs);
702     BreakpointLocationCollection locations_to_remove;
703     BreakpointLocationCollection locations_to_announce;
704 
705     size_t num_new_locations = new_break_locs.GetSize();
706 
707     if (num_new_locations > 0) {
708       // Break out the case of one location -> one location since that's the
709       // most common one, and there's no need to build up the structures needed
710       // for the merge in that case.
711       if (num_new_locations == 1 && num_old_locations == 1) {
712         bool equivalent_locations = false;
713         SymbolContext old_sc, new_sc;
714         // The only way the old and new location can be equivalent is if they
715         // have the same amount of information:
716         BreakpointLocationSP old_loc_sp = old_break_locs.GetByIndex(0);
717         BreakpointLocationSP new_loc_sp = new_break_locs.GetByIndex(0);
718 
719         if (old_loc_sp->GetAddress().CalculateSymbolContext(&old_sc) ==
720             new_loc_sp->GetAddress().CalculateSymbolContext(&new_sc)) {
721           equivalent_locations =
722               SymbolContextsMightBeEquivalent(old_sc, new_sc);
723         }
724 
725         if (equivalent_locations) {
726           m_locations.SwapLocation(old_loc_sp, new_loc_sp);
727         } else {
728           locations_to_remove.Add(old_loc_sp);
729           locations_to_announce.Add(new_loc_sp);
730         }
731       } else {
732         // We don't want to have to keep computing the SymbolContexts for these
733         // addresses over and over, so lets get them up front:
734 
735         typedef std::map<lldb::break_id_t, SymbolContext> IDToSCMap;
736         IDToSCMap old_sc_map;
737         for (size_t idx = 0; idx < num_old_locations; idx++) {
738           SymbolContext sc;
739           BreakpointLocationSP bp_loc_sp = old_break_locs.GetByIndex(idx);
740           lldb::break_id_t loc_id = bp_loc_sp->GetID();
741           bp_loc_sp->GetAddress().CalculateSymbolContext(&old_sc_map[loc_id]);
742         }
743 
744         std::map<lldb::break_id_t, SymbolContext> new_sc_map;
745         for (size_t idx = 0; idx < num_new_locations; idx++) {
746           SymbolContext sc;
747           BreakpointLocationSP bp_loc_sp = new_break_locs.GetByIndex(idx);
748           lldb::break_id_t loc_id = bp_loc_sp->GetID();
749           bp_loc_sp->GetAddress().CalculateSymbolContext(&new_sc_map[loc_id]);
750         }
751         // Take an element from the old Symbol Contexts
752         while (old_sc_map.size() > 0) {
753           lldb::break_id_t old_id = old_sc_map.begin()->first;
754           SymbolContext &old_sc = old_sc_map.begin()->second;
755 
756           // Count the number of entries equivalent to this SC for the old
757           // list:
758           std::vector<lldb::break_id_t> old_id_vec;
759           old_id_vec.push_back(old_id);
760 
761           IDToSCMap::iterator tmp_iter;
762           for (tmp_iter = ++old_sc_map.begin(); tmp_iter != old_sc_map.end();
763                tmp_iter++) {
764             if (SymbolContextsMightBeEquivalent(old_sc, tmp_iter->second))
765               old_id_vec.push_back(tmp_iter->first);
766           }
767 
768           // Now find all the equivalent locations in the new list.
769           std::vector<lldb::break_id_t> new_id_vec;
770           for (tmp_iter = new_sc_map.begin(); tmp_iter != new_sc_map.end();
771                tmp_iter++) {
772             if (SymbolContextsMightBeEquivalent(old_sc, tmp_iter->second))
773               new_id_vec.push_back(tmp_iter->first);
774           }
775 
776           // Alright, if we have the same number of potentially equivalent
777           // locations in the old and new modules, we'll just map them one to
778           // one in ascending ID order (assuming the resolver's order would
779           // match the equivalent ones. Otherwise, we'll dump all the old ones,
780           // and just take the new ones, erasing the elements from both maps as
781           // we go.
782 
783           if (old_id_vec.size() == new_id_vec.size()) {
784             llvm::sort(old_id_vec);
785             llvm::sort(new_id_vec);
786             size_t num_elements = old_id_vec.size();
787             for (size_t idx = 0; idx < num_elements; idx++) {
788               BreakpointLocationSP old_loc_sp =
789                   old_break_locs.FindByIDPair(GetID(), old_id_vec[idx]);
790               BreakpointLocationSP new_loc_sp =
791                   new_break_locs.FindByIDPair(GetID(), new_id_vec[idx]);
792               m_locations.SwapLocation(old_loc_sp, new_loc_sp);
793               old_sc_map.erase(old_id_vec[idx]);
794               new_sc_map.erase(new_id_vec[idx]);
795             }
796           } else {
797             for (lldb::break_id_t old_id : old_id_vec) {
798               locations_to_remove.Add(
799                   old_break_locs.FindByIDPair(GetID(), old_id));
800               old_sc_map.erase(old_id);
801             }
802             for (lldb::break_id_t new_id : new_id_vec) {
803               locations_to_announce.Add(
804                   new_break_locs.FindByIDPair(GetID(), new_id));
805               new_sc_map.erase(new_id);
806             }
807           }
808         }
809       }
810     }
811 
812     // Now remove the remaining old locations, and cons up a removed locations
813     // event. Note, we don't put the new locations that were swapped with an
814     // old location on the locations_to_remove list, so we don't need to worry
815     // about telling the world about removing a location we didn't tell them
816     // about adding.
817 
818     BreakpointEventData *locations_event;
819     if (!IsInternal())
820       locations_event = new BreakpointEventData(
821           eBreakpointEventTypeLocationsRemoved, shared_from_this());
822     else
823       locations_event = nullptr;
824 
825     for (BreakpointLocationSP loc_sp :
826          locations_to_remove.BreakpointLocations()) {
827       m_locations.RemoveLocation(loc_sp);
828       if (locations_event)
829         locations_event->GetBreakpointLocationCollection().Add(loc_sp);
830     }
831     SendBreakpointChangedEvent(locations_event);
832 
833     // And announce the new ones.
834 
835     if (!IsInternal()) {
836       locations_event = new BreakpointEventData(
837           eBreakpointEventTypeLocationsAdded, shared_from_this());
838       for (BreakpointLocationSP loc_sp :
839            locations_to_announce.BreakpointLocations())
840         locations_event->GetBreakpointLocationCollection().Add(loc_sp);
841 
842       SendBreakpointChangedEvent(locations_event);
843     }
844     m_locations.Compact();
845   }
846 }
847 
Dump(Stream *)848 void Breakpoint::Dump(Stream *) {}
849 
GetNumResolvedLocations() const850 size_t Breakpoint::GetNumResolvedLocations() const {
851   // Return the number of breakpoints that are actually resolved and set down
852   // in the inferior process.
853   return m_locations.GetNumResolvedLocations();
854 }
855 
HasResolvedLocations() const856 bool Breakpoint::HasResolvedLocations() const {
857   return GetNumResolvedLocations() > 0;
858 }
859 
GetNumLocations() const860 size_t Breakpoint::GetNumLocations() const { return m_locations.GetSize(); }
861 
AddName(llvm::StringRef new_name)862 bool Breakpoint::AddName(llvm::StringRef new_name) {
863   m_name_list.insert(new_name.str().c_str());
864   return true;
865 }
866 
GetDescription(Stream * s,lldb::DescriptionLevel level,bool show_locations)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 
GetResolverDescription(Stream * s)969 void Breakpoint::GetResolverDescription(Stream *s) {
970   if (m_resolver_sp)
971     m_resolver_sp->GetDescription(s);
972 }
973 
GetMatchingFileLine(const ConstString & filename,uint32_t line_number,BreakpointLocationCollection & loc_coll)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 
GetFilterDescription(Stream * s)994 void Breakpoint::GetFilterDescription(Stream *s) {
995   m_filter_sp->GetDescription(s);
996 }
997 
EvaluatePrecondition(StoppointCallbackContext & context)998 bool Breakpoint::EvaluatePrecondition(StoppointCallbackContext &context) {
999   if (!m_precondition_sp)
1000     return true;
1001 
1002   return m_precondition_sp->EvaluatePrecondition(context);
1003 }
1004 
EvaluatePrecondition(StoppointCallbackContext & context)1005 bool Breakpoint::BreakpointPrecondition::EvaluatePrecondition(
1006     StoppointCallbackContext &context) {
1007   return true;
1008 }
1009 
GetDescription(Stream & stream,lldb::DescriptionLevel level)1010 void Breakpoint::BreakpointPrecondition::GetDescription(
1011     Stream &stream, lldb::DescriptionLevel level) {}
1012 
1013 Status
ConfigurePrecondition(Args & options)1014 Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) {
1015   Status error;
1016   error.SetErrorString("Base breakpoint precondition has no options.");
1017   return error;
1018 }
1019 
SendBreakpointChangedEvent(lldb::BreakpointEventType eventKind)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 
SendBreakpointChangedEvent(BreakpointEventData * data)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 
BreakpointEventData(BreakpointEventType sub_type,const BreakpointSP & new_breakpoint_sp)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 
GetFlavorString()1050 const ConstString &Breakpoint::BreakpointEventData::GetFlavorString() {
1051   static ConstString g_flavor("Breakpoint::BreakpointEventData");
1052   return g_flavor;
1053 }
1054 
GetFlavor() const1055 const ConstString &Breakpoint::BreakpointEventData::GetFlavor() const {
1056   return BreakpointEventData::GetFlavorString();
1057 }
1058 
GetBreakpoint()1059 BreakpointSP &Breakpoint::BreakpointEventData::GetBreakpoint() {
1060   return m_new_breakpoint_sp;
1061 }
1062 
1063 BreakpointEventType
GetBreakpointEventType() const1064 Breakpoint::BreakpointEventData::GetBreakpointEventType() const {
1065   return m_breakpoint_event;
1066 }
1067 
Dump(Stream * s) const1068 void Breakpoint::BreakpointEventData::Dump(Stream *s) const {}
1069 
1070 const Breakpoint::BreakpointEventData *
GetEventDataFromEvent(const Event * event)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
GetBreakpointEventTypeFromEvent(const EventSP & event_sp)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 
GetBreakpointFromEvent(const EventSP & event_sp)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 
GetNumBreakpointLocationsFromEvent(const EventSP & event_sp)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
GetBreakpointLocationAtIndexFromEvent(const lldb::EventSP & event_sp,uint32_t bp_loc_idx)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 }
1124