1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_LIBEVENT_H_
6 #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_LIBEVENT_H_
7 
8 #include "base/compiler_specific.h"
9 #include "base/location.h"
10 #include "base/macros.h"
11 #include "base/message_loop/message_pump.h"
12 #include "base/threading/thread_checker.h"
13 #include "base/time/time.h"
14 
15 // Declare structs we need from libevent.h rather than including it
16 struct event_base;
17 struct event;
18 
19 namespace base {
20 
21 // Class to monitor sockets and issue callbacks when sockets are ready for I/O
22 // TODO(dkegel): add support for background file IO somehow
23 class BASE_EXPORT MessagePumpLibevent : public MessagePump {
24  public:
25   // Used with WatchFileDescriptor to asynchronously monitor the I/O readiness
26   // of a file descriptor.
27   class Watcher {
28    public:
29     // Called from MessageLoop::Run when an FD can be read from/written to
30     // without blocking
31     virtual void OnFileCanReadWithoutBlocking(int fd) = 0;
32     virtual void OnFileCanWriteWithoutBlocking(int fd) = 0;
33 
34    protected:
~Watcher()35     virtual ~Watcher() {}
36   };
37 
38   // Object returned by WatchFileDescriptor to manage further watching.
39   class FileDescriptorWatcher {
40    public:
41     explicit FileDescriptorWatcher(const tracked_objects::Location& from_here);
42     ~FileDescriptorWatcher();  // Implicitly calls StopWatchingFileDescriptor.
43 
44     // NOTE: These methods aren't called StartWatching()/StopWatching() to
45     // avoid confusion with the win32 ObjectWatcher class.
46 
47     // Stop watching the FD, always safe to call.  No-op if there's nothing
48     // to do.
49     bool StopWatchingFileDescriptor();
50 
created_from_location()51     const tracked_objects::Location& created_from_location() {
52       return created_from_location_;
53     }
54 
55    private:
56     friend class MessagePumpLibevent;
57     friend class MessagePumpLibeventTest;
58 
59     // Called by MessagePumpLibevent, ownership of |e| is transferred to this
60     // object.
61     void Init(event* e);
62 
63     // Used by MessagePumpLibevent to take ownership of event_.
64     event* ReleaseEvent();
65 
set_pump(MessagePumpLibevent * pump)66     void set_pump(MessagePumpLibevent* pump) { pump_ = pump; }
pump()67     MessagePumpLibevent* pump() const { return pump_; }
68 
set_watcher(Watcher * watcher)69     void set_watcher(Watcher* watcher) { watcher_ = watcher; }
70 
71     void OnFileCanReadWithoutBlocking(int fd, MessagePumpLibevent* pump);
72     void OnFileCanWriteWithoutBlocking(int fd, MessagePumpLibevent* pump);
73 
74     event* event_;
75     MessagePumpLibevent* pump_;
76     Watcher* watcher_;
77     // If this pointer is non-NULL, the pointee is set to true in the
78     // destructor.
79     bool* was_destroyed_;
80 
81     const tracked_objects::Location created_from_location_;
82 
83     DISALLOW_COPY_AND_ASSIGN(FileDescriptorWatcher);
84   };
85 
86   enum Mode {
87     WATCH_READ = 1 << 0,
88     WATCH_WRITE = 1 << 1,
89     WATCH_READ_WRITE = WATCH_READ | WATCH_WRITE
90   };
91 
92   MessagePumpLibevent();
93   ~MessagePumpLibevent() override;
94 
95   // Have the current thread's message loop watch for a a situation in which
96   // reading/writing to the FD can be performed without blocking.
97   // Callers must provide a preallocated FileDescriptorWatcher object which
98   // can later be used to manage the lifetime of this event.
99   // If a FileDescriptorWatcher is passed in which is already attached to
100   // an event, then the effect is cumulative i.e. after the call |controller|
101   // will watch both the previous event and the new one.
102   // If an error occurs while calling this method in a cumulative fashion, the
103   // event previously attached to |controller| is aborted.
104   // Returns true on success.
105   // Must be called on the same thread the message_pump is running on.
106   // TODO(dkegel): switch to edge-triggered readiness notification
107   bool WatchFileDescriptor(int fd,
108                            bool persistent,
109                            int mode,
110                            FileDescriptorWatcher* controller,
111                            Watcher* delegate);
112 
113   // MessagePump methods:
114   void Run(Delegate* delegate) override;
115   void Quit() override;
116   void ScheduleWork() override;
117   void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
118 
119  private:
120   friend class MessagePumpLibeventTest;
121 
122   // Risky part of constructor.  Returns true on success.
123   bool Init();
124 
125   // Called by libevent to tell us a registered FD can be read/written to.
126   static void OnLibeventNotification(int fd, short flags, void* context);
127 
128   // Unix pipe used to implement ScheduleWork()
129   // ... callback; called by libevent inside Run() when pipe is ready to read
130   static void OnWakeup(int socket, short flags, void* context);
131 
132   // This flag is set to false when Run should return.
133   bool keep_running_;
134 
135   // This flag is set when inside Run.
136   bool in_run_;
137 
138   // This flag is set if libevent has processed I/O events.
139   bool processed_io_events_;
140 
141   // The time at which we should call DoDelayedWork.
142   TimeTicks delayed_work_time_;
143 
144   // Libevent dispatcher.  Watches all sockets registered with it, and sends
145   // readiness callbacks when a socket is ready for I/O.
146   event_base* event_base_;
147 
148   // ... write end; ScheduleWork() writes a single byte to it
149   int wakeup_pipe_in_;
150   // ... read end; OnWakeup reads it and then breaks Run() out of its sleep
151   int wakeup_pipe_out_;
152   // ... libevent wrapper for read end
153   event* wakeup_event_;
154 
155   ThreadChecker watch_file_descriptor_caller_checker_;
156   DISALLOW_COPY_AND_ASSIGN(MessagePumpLibevent);
157 };
158 
159 }  // namespace base
160 
161 #endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_LIBEVENT_H_
162