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