Broadcaster.h revision 343181
1//===-- Broadcaster.h -------------------------------------------*- 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#ifndef LLDB_UTILITY_BROADCASTER_H
11#define LLDB_UTILITY_BROADCASTER_H
12
13#include "lldb/Utility/ConstString.h"
14#include "lldb/lldb-defines.h"
15#include "lldb/lldb-forward.h"
16
17#include "llvm/ADT/SmallVector.h"
18
19#include <cstdint>
20#include <map>
21#include <memory>
22#include <mutex>
23#include <set>
24#include <string>
25#include <utility>
26#include <vector>
27
28namespace lldb_private {
29class Broadcaster;
30}
31namespace lldb_private {
32class EventData;
33}
34namespace lldb_private {
35class Listener;
36}
37namespace lldb_private {
38class Stream;
39}
40
41namespace lldb_private {
42
43//----------------------------------------------------------------------
44// lldb::BroadcastEventSpec
45//
46// This class is used to specify a kind of event to register for.  The Debugger
47// maintains a list of BroadcastEventSpec's and when it is made
48//----------------------------------------------------------------------
49class BroadcastEventSpec {
50public:
51  BroadcastEventSpec(const ConstString &broadcaster_class, uint32_t event_bits)
52      : m_broadcaster_class(broadcaster_class), m_event_bits(event_bits) {}
53
54  BroadcastEventSpec(const BroadcastEventSpec &rhs);
55
56  ~BroadcastEventSpec() = default;
57
58  const ConstString &GetBroadcasterClass() const { return m_broadcaster_class; }
59
60  uint32_t GetEventBits() const { return m_event_bits; }
61
62  // Tell whether this BroadcastEventSpec is contained in in_spec. That is: (a)
63  // the two spec's share the same broadcaster class (b) the event bits of this
64  // spec are wholly contained in those of in_spec.
65  bool IsContainedIn(BroadcastEventSpec in_spec) const {
66    if (m_broadcaster_class != in_spec.GetBroadcasterClass())
67      return false;
68    uint32_t in_bits = in_spec.GetEventBits();
69    if (in_bits == m_event_bits)
70      return true;
71    else {
72      if ((m_event_bits & in_bits) != 0 && (m_event_bits & ~in_bits) == 0)
73        return true;
74    }
75    return false;
76  }
77
78  bool operator<(const BroadcastEventSpec &rhs) const;
79  BroadcastEventSpec &operator=(const BroadcastEventSpec &rhs);
80
81private:
82  ConstString m_broadcaster_class;
83  uint32_t m_event_bits;
84};
85
86class BroadcasterManager
87    : public std::enable_shared_from_this<BroadcasterManager> {
88public:
89  friend class Listener;
90
91protected:
92  BroadcasterManager();
93
94public:
95  // Listeners hold onto weak pointers to their broadcaster managers.  So they
96  // must be made into shared pointers, which you do with
97  // MakeBroadcasterManager.
98
99  static lldb::BroadcasterManagerSP MakeBroadcasterManager();
100
101  ~BroadcasterManager() = default;
102
103  uint32_t RegisterListenerForEvents(const lldb::ListenerSP &listener_sp,
104                                     BroadcastEventSpec event_spec);
105
106  bool UnregisterListenerForEvents(const lldb::ListenerSP &listener_sp,
107                                   BroadcastEventSpec event_spec);
108
109  lldb::ListenerSP GetListenerForEventSpec(BroadcastEventSpec event_spec) const;
110
111  void SignUpListenersForBroadcaster(Broadcaster &broadcaster);
112
113  void RemoveListener(const lldb::ListenerSP &listener_sp);
114
115  void RemoveListener(Listener *listener);
116
117  void Clear();
118
119private:
120  typedef std::pair<BroadcastEventSpec, lldb::ListenerSP> event_listener_key;
121  typedef std::map<BroadcastEventSpec, lldb::ListenerSP> collection;
122  typedef std::set<lldb::ListenerSP> listener_collection;
123  collection m_event_map;
124  listener_collection m_listeners;
125
126  mutable std::recursive_mutex m_manager_mutex;
127
128  // A couple of comparator classes for find_if:
129
130  class BroadcasterClassMatches {
131  public:
132    BroadcasterClassMatches(const ConstString &broadcaster_class)
133        : m_broadcaster_class(broadcaster_class) {}
134
135    ~BroadcasterClassMatches() = default;
136
137    bool operator()(const event_listener_key input) const {
138      return (input.first.GetBroadcasterClass() == m_broadcaster_class);
139    }
140
141  private:
142    ConstString m_broadcaster_class;
143  };
144
145  class BroadcastEventSpecMatches {
146  public:
147    BroadcastEventSpecMatches(BroadcastEventSpec broadcaster_spec)
148        : m_broadcaster_spec(broadcaster_spec) {}
149
150    ~BroadcastEventSpecMatches() = default;
151
152    bool operator()(const event_listener_key input) const {
153      return (input.first.IsContainedIn(m_broadcaster_spec));
154    }
155
156  private:
157    BroadcastEventSpec m_broadcaster_spec;
158  };
159
160  class ListenerMatchesAndSharedBits {
161  public:
162    explicit ListenerMatchesAndSharedBits(BroadcastEventSpec broadcaster_spec,
163                                          const lldb::ListenerSP listener_sp)
164        : m_broadcaster_spec(broadcaster_spec), m_listener_sp(listener_sp) {}
165
166    ~ListenerMatchesAndSharedBits() = default;
167
168    bool operator()(const event_listener_key input) const {
169      return (input.first.GetBroadcasterClass() ==
170                  m_broadcaster_spec.GetBroadcasterClass() &&
171              (input.first.GetEventBits() &
172               m_broadcaster_spec.GetEventBits()) != 0 &&
173              input.second == m_listener_sp);
174    }
175
176  private:
177    BroadcastEventSpec m_broadcaster_spec;
178    const lldb::ListenerSP m_listener_sp;
179  };
180
181  class ListenerMatches {
182  public:
183    explicit ListenerMatches(const lldb::ListenerSP in_listener_sp)
184        : m_listener_sp(in_listener_sp) {}
185
186    ~ListenerMatches() = default;
187
188    bool operator()(const event_listener_key input) const {
189      if (input.second == m_listener_sp)
190        return true;
191      else
192        return false;
193    }
194
195  private:
196    const lldb::ListenerSP m_listener_sp;
197  };
198
199  class ListenerMatchesPointer {
200  public:
201    ListenerMatchesPointer(const Listener *in_listener)
202        : m_listener(in_listener) {}
203
204    ~ListenerMatchesPointer() = default;
205
206    bool operator()(const event_listener_key input) const {
207      if (input.second.get() == m_listener)
208        return true;
209      else
210        return false;
211    }
212
213    bool operator()(const lldb::ListenerSP input) const {
214      if (input.get() == m_listener)
215        return true;
216      else
217        return false;
218    }
219
220  private:
221    const Listener *m_listener;
222  };
223};
224
225//----------------------------------------------------------------------
226/// @class Broadcaster Broadcaster.h "lldb/Utility/Broadcaster.h" An event
227/// broadcasting class.
228///
229/// The Broadcaster class is designed to be subclassed by objects that wish to
230/// vend events in a multi-threaded environment. Broadcaster objects can each
231/// vend 32 events. Each event is represented by a bit in a 32 bit value and
232/// these bits can be set:
233///     @see Broadcaster::SetEventBits(uint32_t)
234/// or cleared:
235///     @see Broadcaster::ResetEventBits(uint32_t)
236/// When an event gets set the Broadcaster object will notify the Listener
237/// object that is listening for the event (if there is one).
238///
239/// Subclasses should provide broadcast bit definitions for any events they
240/// vend, typically using an enumeration:
241///     \code
242///         class Foo : public Broadcaster
243///         {
244///         public:
245///         //----------------------------------------------------------
246///         // Broadcaster event bits definitions.
247///         //----------------------------------------------------------
248///         enum
249///         {
250///             eBroadcastBitOne   = (1 << 0),
251///             eBroadcastBitTwo   = (1 << 1),
252///             eBroadcastBitThree = (1 << 2),
253///             ...
254///         };
255///     \endcode
256//----------------------------------------------------------------------
257class Broadcaster {
258  friend class Listener;
259  friend class Event;
260
261public:
262  //------------------------------------------------------------------
263  /// Construct with a broadcaster with a name.
264  ///
265  /// @param[in] name
266  ///     A NULL terminated C string that contains the name of the
267  ///     broadcaster object.
268  //------------------------------------------------------------------
269  Broadcaster(lldb::BroadcasterManagerSP manager_sp, const char *name);
270
271  //------------------------------------------------------------------
272  /// Destructor.
273  ///
274  /// The destructor is virtual since this class gets subclassed.
275  //------------------------------------------------------------------
276  virtual ~Broadcaster();
277
278  void CheckInWithManager();
279
280  //------------------------------------------------------------------
281  /// Broadcast an event which has no associated data.
282  ///
283  /// @param[in] event_type
284  ///     The element from the enum defining this broadcaster's events
285  ///     that is being broadcast.
286  ///
287  /// @param[in] event_data
288  ///     User event data that will be owned by the lldb::Event that
289  ///     is created internally.
290  ///
291  /// @param[in] unique
292  ///     If true, then only add an event of this type if there isn't
293  ///     one already in the queue.
294  ///
295  //------------------------------------------------------------------
296  void BroadcastEvent(lldb::EventSP &event_sp) {
297    m_broadcaster_sp->BroadcastEvent(event_sp);
298  }
299
300  void BroadcastEventIfUnique(lldb::EventSP &event_sp) {
301    m_broadcaster_sp->BroadcastEventIfUnique(event_sp);
302  }
303
304  void BroadcastEvent(uint32_t event_type,
305                      const lldb::EventDataSP &event_data_sp) {
306    m_broadcaster_sp->BroadcastEvent(event_type, event_data_sp);
307  }
308
309  void BroadcastEvent(uint32_t event_type, EventData *event_data = nullptr) {
310    m_broadcaster_sp->BroadcastEvent(event_type, event_data);
311  }
312
313  void BroadcastEventIfUnique(uint32_t event_type,
314                              EventData *event_data = nullptr) {
315    m_broadcaster_sp->BroadcastEventIfUnique(event_type, event_data);
316  }
317
318  void Clear() { m_broadcaster_sp->Clear(); }
319
320  virtual void AddInitialEventsToListener(const lldb::ListenerSP &listener_sp,
321                                          uint32_t requested_events);
322
323  //------------------------------------------------------------------
324  /// Listen for any events specified by \a event_mask.
325  ///
326  /// Only one listener can listen to each event bit in a given Broadcaster.
327  /// Once a listener has acquired an event bit, no other broadcaster will
328  /// have access to it until it is relinquished by the first listener that
329  /// gets it. The actual event bits that get acquired by \a listener may be
330  /// different from what is requested in \a event_mask, and to track this the
331  /// actual event bits that are acquired get returned.
332  ///
333  /// @param[in] listener
334  ///     The Listener object that wants to monitor the events that
335  ///     get broadcast by this object.
336  ///
337  /// @param[in] event_mask
338  ///     A bit mask that indicates which events the listener is
339  ///     asking to monitor.
340  ///
341  /// @return
342  ///     The actual event bits that were acquired by \a listener.
343  //------------------------------------------------------------------
344  uint32_t AddListener(const lldb::ListenerSP &listener_sp,
345                       uint32_t event_mask) {
346    return m_broadcaster_sp->AddListener(listener_sp, event_mask);
347  }
348
349  //------------------------------------------------------------------
350  /// Get the NULL terminated C string name of this Broadcaster object.
351  ///
352  /// @return
353  ///     The NULL terminated C string name of this Broadcaster.
354  //------------------------------------------------------------------
355  const ConstString &GetBroadcasterName() { return m_broadcaster_name; }
356
357  //------------------------------------------------------------------
358  /// Get the event name(s) for one or more event bits.
359  ///
360  /// @param[in] event_mask
361  ///     A bit mask that indicates which events to get names for.
362  ///
363  /// @return
364  ///     The NULL terminated C string name of this Broadcaster.
365  //------------------------------------------------------------------
366  bool GetEventNames(Stream &s, const uint32_t event_mask,
367                     bool prefix_with_broadcaster_name) const {
368    return m_broadcaster_sp->GetEventNames(s, event_mask,
369                                           prefix_with_broadcaster_name);
370  }
371
372  //------------------------------------------------------------------
373  /// Set the name for an event bit.
374  ///
375  /// @param[in] event_mask
376  ///     A bit mask that indicates which events the listener is
377  ///     asking to monitor.
378  ///
379  /// @return
380  ///     The NULL terminated C string name of this Broadcaster.
381  //------------------------------------------------------------------
382  void SetEventName(uint32_t event_mask, const char *name) {
383    m_broadcaster_sp->SetEventName(event_mask, name);
384  }
385
386  const char *GetEventName(uint32_t event_mask) const {
387    return m_broadcaster_sp->GetEventName(event_mask);
388  }
389
390  bool EventTypeHasListeners(uint32_t event_type) {
391    return m_broadcaster_sp->EventTypeHasListeners(event_type);
392  }
393
394  //------------------------------------------------------------------
395  /// Removes a Listener from this broadcasters list and frees the event bits
396  /// specified by \a event_mask that were previously acquired by \a listener
397  /// (assuming \a listener was listening to this object) for other listener
398  /// objects to use.
399  ///
400  /// @param[in] listener
401  ///     A Listener object that previously called AddListener.
402  ///
403  /// @param[in] event_mask
404  ///     The event bits \a listener wishes to relinquish.
405  ///
406  /// @return
407  ///     \b True if the listener was listening to this broadcaster
408  ///     and was removed, \b false otherwise.
409  ///
410  /// @see uint32_t Broadcaster::AddListener (Listener*, uint32_t)
411  //------------------------------------------------------------------
412  bool RemoveListener(const lldb::ListenerSP &listener_sp,
413                      uint32_t event_mask = UINT32_MAX) {
414    return m_broadcaster_sp->RemoveListener(listener_sp, event_mask);
415  }
416
417  //------------------------------------------------------------------
418  /// Provides a simple mechanism to temporarily redirect events from
419  /// broadcaster.  When you call this function passing in a listener and
420  /// event type mask, all events from the broadcaster matching the mask will
421  /// now go to the hijacking listener. Only one hijack can occur at a time.
422  /// If we need more than this we will have to implement a Listener stack.
423  ///
424  /// @param[in] listener
425  ///     A Listener object.  You do not need to call StartListeningForEvents
426  ///     for this broadcaster (that would fail anyway since the event bits
427  ///     would most likely be taken by the listener(s) you are usurping.
428  ///
429  /// @param[in] event_mask
430  ///     The event bits \a listener wishes to hijack.
431  ///
432  /// @return
433  ///     \b True if the event mask could be hijacked, \b false otherwise.
434  ///
435  /// @see uint32_t Broadcaster::AddListener (Listener*, uint32_t)
436  //------------------------------------------------------------------
437  bool HijackBroadcaster(const lldb::ListenerSP &listener_sp,
438                         uint32_t event_mask = UINT32_MAX) {
439    return m_broadcaster_sp->HijackBroadcaster(listener_sp, event_mask);
440  }
441
442  bool IsHijackedForEvent(uint32_t event_mask) {
443    return m_broadcaster_sp->IsHijackedForEvent(event_mask);
444  }
445
446  //------------------------------------------------------------------
447  /// Restore the state of the Broadcaster from a previous hijack attempt.
448  ///
449  //------------------------------------------------------------------
450  void RestoreBroadcaster() { m_broadcaster_sp->RestoreBroadcaster(); }
451
452  // This needs to be filled in if you are going to register the broadcaster
453  // with the broadcaster manager and do broadcaster class matching.
454  // FIXME: Probably should make a ManagedBroadcaster subclass with all the bits
455  // needed to work
456  // with the BroadcasterManager, so that it is clearer how to add one.
457  virtual ConstString &GetBroadcasterClass() const;
458
459  lldb::BroadcasterManagerSP GetManager();
460
461protected:
462  // BroadcasterImpl contains the actual Broadcaster implementation.  The
463  // Broadcaster makes a BroadcasterImpl which lives as long as it does.  The
464  // Listeners & the Events hold a weak pointer to the BroadcasterImpl, so that
465  // they can survive if a Broadcaster they were listening to is destroyed w/o
466  // their being able to unregister from it (which can happen if the
467  // Broadcasters & Listeners are being destroyed on separate threads
468  // simultaneously. The Broadcaster itself can't be shared out as a weak
469  // pointer, because some things that are broadcasters (e.g. the Target and
470  // the Process) are shared in their own right.
471  //
472  // For the most part, the Broadcaster functions dispatch to the
473  // BroadcasterImpl, and are documented in the public Broadcaster API above.
474
475  class BroadcasterImpl {
476    friend class Listener;
477    friend class Broadcaster;
478
479  public:
480    BroadcasterImpl(Broadcaster &broadcaster);
481
482    ~BroadcasterImpl() = default;
483
484    void BroadcastEvent(lldb::EventSP &event_sp);
485
486    void BroadcastEventIfUnique(lldb::EventSP &event_sp);
487
488    void BroadcastEvent(uint32_t event_type, EventData *event_data = nullptr);
489
490    void BroadcastEvent(uint32_t event_type,
491                        const lldb::EventDataSP &event_data_sp);
492
493    void BroadcastEventIfUnique(uint32_t event_type,
494                                EventData *event_data = nullptr);
495
496    void Clear();
497
498    uint32_t AddListener(const lldb::ListenerSP &listener_sp,
499                         uint32_t event_mask);
500
501    const char *GetBroadcasterName() const {
502      return m_broadcaster.GetBroadcasterName().AsCString();
503    }
504
505    Broadcaster *GetBroadcaster();
506
507    bool GetEventNames(Stream &s, const uint32_t event_mask,
508                       bool prefix_with_broadcaster_name) const;
509
510    void SetEventName(uint32_t event_mask, const char *name) {
511      m_event_names[event_mask] = name;
512    }
513
514    const char *GetEventName(uint32_t event_mask) const {
515      const auto pos = m_event_names.find(event_mask);
516      if (pos != m_event_names.end())
517        return pos->second.c_str();
518      return nullptr;
519    }
520
521    bool EventTypeHasListeners(uint32_t event_type);
522
523    bool RemoveListener(lldb_private::Listener *listener,
524                        uint32_t event_mask = UINT32_MAX);
525
526    bool RemoveListener(const lldb::ListenerSP &listener_sp,
527                        uint32_t event_mask = UINT32_MAX);
528
529    bool HijackBroadcaster(const lldb::ListenerSP &listener_sp,
530                           uint32_t event_mask = UINT32_MAX);
531
532    bool IsHijackedForEvent(uint32_t event_mask);
533
534    void RestoreBroadcaster();
535
536  protected:
537    void PrivateBroadcastEvent(lldb::EventSP &event_sp, bool unique);
538
539    const char *GetHijackingListenerName();
540
541    //------------------------------------------------------------------
542    //
543    //------------------------------------------------------------------
544    typedef llvm::SmallVector<std::pair<lldb::ListenerWP, uint32_t>, 4>
545        collection;
546    typedef std::map<uint32_t, std::string> event_names_map;
547
548    llvm::SmallVector<std::pair<lldb::ListenerSP, uint32_t &>, 4>
549    GetListeners();
550
551    Broadcaster &m_broadcaster;    ///< The broadcaster that this implements
552    event_names_map m_event_names; ///< Optionally define event names for
553                                   ///readability and logging for each event bit
554    collection m_listeners; ///< A list of Listener / event_mask pairs that are
555                            ///listening to this broadcaster.
556    std::recursive_mutex
557        m_listeners_mutex; ///< A mutex that protects \a m_listeners.
558    std::vector<lldb::ListenerSP> m_hijacking_listeners; // A simple mechanism
559                                                         // to intercept events
560                                                         // from a broadcaster
561    std::vector<uint32_t> m_hijacking_masks; // At some point we may want to
562                                             // have a stack or Listener
563    // collections, but for now this is just for private hijacking.
564
565  private:
566    //------------------------------------------------------------------
567    // For Broadcaster only
568    //------------------------------------------------------------------
569    DISALLOW_COPY_AND_ASSIGN(BroadcasterImpl);
570  };
571
572  typedef std::shared_ptr<BroadcasterImpl> BroadcasterImplSP;
573  typedef std::weak_ptr<BroadcasterImpl> BroadcasterImplWP;
574
575  BroadcasterImplSP GetBroadcasterImpl() { return m_broadcaster_sp; }
576
577  const char *GetHijackingListenerName() {
578    return m_broadcaster_sp->GetHijackingListenerName();
579  }
580  //------------------------------------------------------------------
581  // Classes that inherit from Broadcaster can see and modify these
582  //------------------------------------------------------------------
583
584private:
585  //------------------------------------------------------------------
586  // For Broadcaster only
587  //------------------------------------------------------------------
588  BroadcasterImplSP m_broadcaster_sp;
589  lldb::BroadcasterManagerSP m_manager_sp;
590  const ConstString
591      m_broadcaster_name; ///< The name of this broadcaster object.
592
593  DISALLOW_COPY_AND_ASSIGN(Broadcaster);
594};
595
596} // namespace lldb_private
597
598#endif // LLDB_UTILITY_BROADCASTER_H
599