1 //===-- Broadcaster.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 "lldb/Utility/Broadcaster.h"
10 #include "lldb/Utility/Event.h"
11 #include "lldb/Utility/LLDBLog.h"
12 #include "lldb/Utility/Listener.h"
13 #include "lldb/Utility/Stream.h"
14 #include "lldb/Utility/StreamString.h"
15 
16 #include <algorithm>
17 #include <memory>
18 #include <utility>
19 
20 #include <cassert>
21 #include <cstddef>
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
Broadcaster(BroadcasterManagerSP manager_sp,const char * name)26 Broadcaster::Broadcaster(BroadcasterManagerSP manager_sp, const char *name)
27     : m_broadcaster_sp(std::make_shared<BroadcasterImpl>(*this)),
28       m_manager_sp(std::move(manager_sp)), m_broadcaster_name(name) {
29   Log *log = GetLog(LLDBLog::Object);
30   LLDB_LOG(log, "{0} Broadcaster::Broadcaster(\"{1}\")",
31            static_cast<void *>(this), GetBroadcasterName());
32 }
33 
BroadcasterImpl(Broadcaster & broadcaster)34 Broadcaster::BroadcasterImpl::BroadcasterImpl(Broadcaster &broadcaster)
35     : m_broadcaster(broadcaster), m_listeners(), m_listeners_mutex(),
36       m_hijacking_listeners(), m_hijacking_masks() {}
37 
~Broadcaster()38 Broadcaster::~Broadcaster() {
39   Log *log = GetLog(LLDBLog::Object);
40   LLDB_LOG(log, "{0} Broadcaster::~Broadcaster(\"{1}\")",
41            static_cast<void *>(this), GetBroadcasterName());
42 
43   Clear();
44 }
45 
CheckInWithManager()46 void Broadcaster::CheckInWithManager() {
47   if (m_manager_sp) {
48     m_manager_sp->SignUpListenersForBroadcaster(*this);
49   }
50 }
51 
52 llvm::SmallVector<std::pair<ListenerSP, uint32_t &>, 4>
GetListeners()53 Broadcaster::BroadcasterImpl::GetListeners() {
54   llvm::SmallVector<std::pair<ListenerSP, uint32_t &>, 4> listeners;
55   listeners.reserve(m_listeners.size());
56 
57   for (auto it = m_listeners.begin(); it != m_listeners.end();) {
58     lldb::ListenerSP curr_listener_sp(it->first.lock());
59     if (curr_listener_sp && it->second) {
60       listeners.emplace_back(std::move(curr_listener_sp), it->second);
61       ++it;
62     } else
63       it = m_listeners.erase(it);
64   }
65 
66   return listeners;
67 }
68 
Clear()69 void Broadcaster::BroadcasterImpl::Clear() {
70   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
71 
72   // Make sure the listener forgets about this broadcaster. We do this in the
73   // broadcaster in case the broadcaster object initiates the removal.
74   for (auto &pair : GetListeners())
75     pair.first->BroadcasterWillDestruct(&m_broadcaster);
76 
77   m_listeners.clear();
78 }
79 
GetBroadcaster()80 Broadcaster *Broadcaster::BroadcasterImpl::GetBroadcaster() {
81   return &m_broadcaster;
82 }
83 
GetEventNames(Stream & s,uint32_t event_mask,bool prefix_with_broadcaster_name) const84 bool Broadcaster::BroadcasterImpl::GetEventNames(
85     Stream &s, uint32_t event_mask, bool prefix_with_broadcaster_name) const {
86   uint32_t num_names_added = 0;
87   if (event_mask && !m_event_names.empty()) {
88     event_names_map::const_iterator end = m_event_names.end();
89     for (uint32_t bit = 1u, mask = event_mask; mask != 0 && bit != 0;
90          bit <<= 1, mask >>= 1) {
91       if (mask & 1) {
92         event_names_map::const_iterator pos = m_event_names.find(bit);
93         if (pos != end) {
94           if (num_names_added > 0)
95             s.PutCString(", ");
96 
97           if (prefix_with_broadcaster_name) {
98             s.PutCString(GetBroadcasterName());
99             s.PutChar('.');
100           }
101           s.PutCString(pos->second);
102           ++num_names_added;
103         }
104       }
105     }
106   }
107   return num_names_added > 0;
108 }
109 
AddInitialEventsToListener(const lldb::ListenerSP & listener_sp,uint32_t requested_events)110 void Broadcaster::AddInitialEventsToListener(
111     const lldb::ListenerSP &listener_sp, uint32_t requested_events) {}
112 
113 uint32_t
AddListener(const lldb::ListenerSP & listener_sp,uint32_t event_mask)114 Broadcaster::BroadcasterImpl::AddListener(const lldb::ListenerSP &listener_sp,
115                                           uint32_t event_mask) {
116   if (!listener_sp)
117     return 0;
118 
119   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
120 
121   // See if we already have this listener, and if so, update its mask
122 
123   bool handled = false;
124 
125   for (auto &pair : GetListeners()) {
126     if (pair.first == listener_sp) {
127       handled = true;
128       pair.second |= event_mask;
129       m_broadcaster.AddInitialEventsToListener(listener_sp, event_mask);
130       break;
131     }
132   }
133 
134   if (!handled) {
135     // Grant a new listener the available event bits
136     m_listeners.push_back(
137         std::make_pair(lldb::ListenerWP(listener_sp), event_mask));
138 
139     // Individual broadcasters decide whether they have outstanding data when a
140     // listener attaches, and insert it into the listener with this method.
141     m_broadcaster.AddInitialEventsToListener(listener_sp, event_mask);
142   }
143 
144   // Return the event bits that were granted to the listener
145   return event_mask;
146 }
147 
EventTypeHasListeners(uint32_t event_type)148 bool Broadcaster::BroadcasterImpl::EventTypeHasListeners(uint32_t event_type) {
149   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
150 
151   if (!m_hijacking_listeners.empty() && event_type & m_hijacking_masks.back())
152     return true;
153 
154   for (auto &pair : GetListeners()) {
155     if (pair.second & event_type)
156       return true;
157   }
158   return false;
159 }
160 
RemoveListener(lldb_private::Listener * listener,uint32_t event_mask)161 bool Broadcaster::BroadcasterImpl::RemoveListener(
162     lldb_private::Listener *listener, uint32_t event_mask) {
163   if (!listener)
164     return false;
165 
166   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
167   for (auto &pair : GetListeners()) {
168     if (pair.first.get() == listener) {
169       pair.second &= ~event_mask;
170       return true;
171     }
172   }
173   return false;
174 }
175 
RemoveListener(const lldb::ListenerSP & listener_sp,uint32_t event_mask)176 bool Broadcaster::BroadcasterImpl::RemoveListener(
177     const lldb::ListenerSP &listener_sp, uint32_t event_mask) {
178   return RemoveListener(listener_sp.get(), event_mask);
179 }
180 
BroadcastEvent(EventSP & event_sp)181 void Broadcaster::BroadcasterImpl::BroadcastEvent(EventSP &event_sp) {
182   return PrivateBroadcastEvent(event_sp, false);
183 }
184 
BroadcastEventIfUnique(EventSP & event_sp)185 void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(EventSP &event_sp) {
186   return PrivateBroadcastEvent(event_sp, true);
187 }
188 
PrivateBroadcastEvent(EventSP & event_sp,bool unique)189 void Broadcaster::BroadcasterImpl::PrivateBroadcastEvent(EventSP &event_sp,
190                                                          bool unique) {
191   // Can't add a nullptr event...
192   if (!event_sp)
193     return;
194 
195   // Update the broadcaster on this event
196   event_sp->SetBroadcaster(&m_broadcaster);
197 
198   const uint32_t event_type = event_sp->GetType();
199 
200   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
201 
202   ListenerSP hijacking_listener_sp;
203 
204   if (!m_hijacking_listeners.empty()) {
205     assert(!m_hijacking_masks.empty());
206     hijacking_listener_sp = m_hijacking_listeners.back();
207     if ((event_type & m_hijacking_masks.back()) == 0)
208       hijacking_listener_sp.reset();
209   }
210 
211   Log *log = GetLog(LLDBLog::Events);
212   if (!log && event_sp->GetData())
213     log = event_sp->GetData()->GetLogChannel();
214 
215   if (log) {
216     StreamString event_description;
217     event_sp->Dump(&event_description);
218     LLDB_LOGF(log,
219               "%p Broadcaster(\"%s\")::BroadcastEvent (event_sp = {%s}, "
220               "unique =%i) hijack = %p",
221               static_cast<void *>(this), GetBroadcasterName(),
222               event_description.GetData(), unique,
223               static_cast<void *>(hijacking_listener_sp.get()));
224   }
225 
226   if (hijacking_listener_sp) {
227     if (unique && hijacking_listener_sp->PeekAtNextEventForBroadcasterWithType(
228                       &m_broadcaster, event_type))
229       return;
230     hijacking_listener_sp->AddEvent(event_sp);
231   } else {
232     for (auto &pair : GetListeners()) {
233       if (!(pair.second & event_type))
234         continue;
235       if (unique && pair.first->PeekAtNextEventForBroadcasterWithType(
236                         &m_broadcaster, event_type))
237         continue;
238 
239       pair.first->AddEvent(event_sp);
240     }
241   }
242 }
243 
BroadcastEvent(uint32_t event_type,EventData * event_data)244 void Broadcaster::BroadcasterImpl::BroadcastEvent(uint32_t event_type,
245                                                   EventData *event_data) {
246   auto event_sp = std::make_shared<Event>(event_type, event_data);
247   PrivateBroadcastEvent(event_sp, false);
248 }
249 
BroadcastEvent(uint32_t event_type,const lldb::EventDataSP & event_data_sp)250 void Broadcaster::BroadcasterImpl::BroadcastEvent(
251     uint32_t event_type, const lldb::EventDataSP &event_data_sp) {
252   auto event_sp = std::make_shared<Event>(event_type, event_data_sp);
253   PrivateBroadcastEvent(event_sp, false);
254 }
255 
BroadcastEventIfUnique(uint32_t event_type,EventData * event_data)256 void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(
257     uint32_t event_type, EventData *event_data) {
258   auto event_sp = std::make_shared<Event>(event_type, event_data);
259   PrivateBroadcastEvent(event_sp, true);
260 }
261 
HijackBroadcaster(const lldb::ListenerSP & listener_sp,uint32_t event_mask)262 bool Broadcaster::BroadcasterImpl::HijackBroadcaster(
263     const lldb::ListenerSP &listener_sp, uint32_t event_mask) {
264   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
265 
266   Log *log = GetLog(LLDBLog::Events);
267   LLDB_LOG(
268       log,
269       "{0} Broadcaster(\"{1}\")::HijackBroadcaster (listener(\"{2}\")={3})",
270       static_cast<void *>(this), GetBroadcasterName(),
271       listener_sp->m_name.c_str(), static_cast<void *>(listener_sp.get()));
272   m_hijacking_listeners.push_back(listener_sp);
273   m_hijacking_masks.push_back(event_mask);
274   return true;
275 }
276 
IsHijackedForEvent(uint32_t event_mask)277 bool Broadcaster::BroadcasterImpl::IsHijackedForEvent(uint32_t event_mask) {
278   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
279 
280   if (!m_hijacking_listeners.empty())
281     return (event_mask & m_hijacking_masks.back()) != 0;
282   return false;
283 }
284 
GetHijackingListenerName()285 const char *Broadcaster::BroadcasterImpl::GetHijackingListenerName() {
286   if (m_hijacking_listeners.size()) {
287     return m_hijacking_listeners.back()->GetName();
288   }
289   return nullptr;
290 }
291 
RestoreBroadcaster()292 void Broadcaster::BroadcasterImpl::RestoreBroadcaster() {
293   std::lock_guard<std::recursive_mutex> guard(m_listeners_mutex);
294 
295   if (!m_hijacking_listeners.empty()) {
296     ListenerSP listener_sp = m_hijacking_listeners.back();
297     Log *log = GetLog(LLDBLog::Events);
298     LLDB_LOG(log,
299              "{0} Broadcaster(\"{1}\")::RestoreBroadcaster (about to pop "
300              "listener(\"{2}\")={3})",
301              static_cast<void *>(this), GetBroadcasterName(),
302              listener_sp->m_name.c_str(),
303              static_cast<void *>(listener_sp.get()));
304     m_hijacking_listeners.pop_back();
305   }
306   if (!m_hijacking_masks.empty())
307     m_hijacking_masks.pop_back();
308 }
309 
GetBroadcasterClass() const310 ConstString &Broadcaster::GetBroadcasterClass() const {
311   static ConstString class_name("lldb.anonymous");
312   return class_name;
313 }
314 
operator <(const BroadcastEventSpec & rhs) const315 bool BroadcastEventSpec::operator<(const BroadcastEventSpec &rhs) const {
316   if (GetBroadcasterClass() == rhs.GetBroadcasterClass()) {
317     return GetEventBits() < rhs.GetEventBits();
318   }
319   return GetBroadcasterClass() < rhs.GetBroadcasterClass();
320 }
321 
BroadcasterManager()322 BroadcasterManager::BroadcasterManager() : m_manager_mutex() {}
323 
MakeBroadcasterManager()324 lldb::BroadcasterManagerSP BroadcasterManager::MakeBroadcasterManager() {
325   return lldb::BroadcasterManagerSP(new BroadcasterManager());
326 }
327 
RegisterListenerForEvents(const lldb::ListenerSP & listener_sp,const BroadcastEventSpec & event_spec)328 uint32_t BroadcasterManager::RegisterListenerForEvents(
329     const lldb::ListenerSP &listener_sp, const BroadcastEventSpec &event_spec) {
330   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
331 
332   collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end();
333   uint32_t available_bits = event_spec.GetEventBits();
334 
335   while (iter != end_iter &&
336          (iter = find_if(iter, end_iter,
337                          BroadcasterClassMatches(
338                              event_spec.GetBroadcasterClass()))) != end_iter) {
339     available_bits &= ~((*iter).first.GetEventBits());
340     iter++;
341   }
342 
343   if (available_bits != 0) {
344     m_event_map.insert(event_listener_key(
345         BroadcastEventSpec(event_spec.GetBroadcasterClass(), available_bits),
346         listener_sp));
347     m_listeners.insert(listener_sp);
348   }
349 
350   return available_bits;
351 }
352 
UnregisterListenerForEvents(const lldb::ListenerSP & listener_sp,const BroadcastEventSpec & event_spec)353 bool BroadcasterManager::UnregisterListenerForEvents(
354     const lldb::ListenerSP &listener_sp, const BroadcastEventSpec &event_spec) {
355   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
356   bool removed_some = false;
357 
358   if (m_listeners.erase(listener_sp) == 0)
359     return false;
360 
361   ListenerMatchesAndSharedBits predicate(event_spec, listener_sp);
362   std::vector<BroadcastEventSpec> to_be_readded;
363   uint32_t event_bits_to_remove = event_spec.GetEventBits();
364 
365   // Go through the map and delete the exact matches, and build a list of
366   // matches that weren't exact to re-add:
367   while (true) {
368     collection::iterator iter, end_iter = m_event_map.end();
369     iter = find_if(m_event_map.begin(), end_iter, predicate);
370     if (iter == end_iter) {
371       break;
372     }
373     uint32_t iter_event_bits = (*iter).first.GetEventBits();
374     removed_some = true;
375 
376     if (event_bits_to_remove != iter_event_bits) {
377       uint32_t new_event_bits = iter_event_bits & ~event_bits_to_remove;
378       to_be_readded.emplace_back(event_spec.GetBroadcasterClass(),
379                                  new_event_bits);
380     }
381     m_event_map.erase(iter);
382   }
383 
384   // Okay now add back the bits that weren't completely removed:
385   for (size_t i = 0; i < to_be_readded.size(); i++) {
386     m_event_map.insert(event_listener_key(to_be_readded[i], listener_sp));
387   }
388 
389   return removed_some;
390 }
391 
GetListenerForEventSpec(const BroadcastEventSpec & event_spec) const392 ListenerSP BroadcasterManager::GetListenerForEventSpec(
393     const BroadcastEventSpec &event_spec) const {
394   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
395 
396   collection::const_iterator iter, end_iter = m_event_map.end();
397   iter = find_if(m_event_map.begin(), end_iter,
398                  BroadcastEventSpecMatches(event_spec));
399   if (iter != end_iter)
400     return (*iter).second;
401 
402   return nullptr;
403 }
404 
RemoveListener(Listener * listener)405 void BroadcasterManager::RemoveListener(Listener *listener) {
406   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
407   ListenerMatchesPointer predicate(listener);
408   listener_collection::iterator iter = m_listeners.begin(),
409                                 end_iter = m_listeners.end();
410 
411   iter = std::find_if(iter, end_iter, predicate);
412   if (iter != end_iter)
413     m_listeners.erase(iter);
414 
415   while (true) {
416     collection::iterator iter, end_iter = m_event_map.end();
417     iter = find_if(m_event_map.begin(), end_iter, predicate);
418     if (iter == end_iter)
419       break;
420 
421     m_event_map.erase(iter);
422   }
423 }
424 
RemoveListener(const lldb::ListenerSP & listener_sp)425 void BroadcasterManager::RemoveListener(const lldb::ListenerSP &listener_sp) {
426   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
427   ListenerMatches predicate(listener_sp);
428 
429   if (m_listeners.erase(listener_sp) == 0)
430     return;
431 
432   while (true) {
433     collection::iterator iter, end_iter = m_event_map.end();
434     iter = find_if(m_event_map.begin(), end_iter, predicate);
435     if (iter == end_iter)
436       break;
437 
438     m_event_map.erase(iter);
439   }
440 }
441 
SignUpListenersForBroadcaster(Broadcaster & broadcaster)442 void BroadcasterManager::SignUpListenersForBroadcaster(
443     Broadcaster &broadcaster) {
444   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
445 
446   collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end();
447 
448   while (iter != end_iter &&
449          (iter = find_if(iter, end_iter,
450                          BroadcasterClassMatches(
451                              broadcaster.GetBroadcasterClass()))) != end_iter) {
452     (*iter).second->StartListeningForEvents(&broadcaster,
453                                             (*iter).first.GetEventBits());
454     iter++;
455   }
456 }
457 
Clear()458 void BroadcasterManager::Clear() {
459   std::lock_guard<std::recursive_mutex> guard(m_manager_mutex);
460   listener_collection::iterator end_iter = m_listeners.end();
461 
462   for (listener_collection::iterator iter = m_listeners.begin();
463        iter != end_iter; iter++)
464     (*iter)->BroadcasterManagerWillDestruct(this->shared_from_this());
465   m_listeners.clear();
466   m_event_map.clear();
467 }
468