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 #include "base/message_loop/message_pump_libevent.h"
6 
7 #include <errno.h>
8 #include <unistd.h>
9 
10 #include "base/auto_reset.h"
11 #include "base/compiler_specific.h"
12 #include "base/files/file_util.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/posix/eintr_wrapper.h"
17 #include "base/time/time.h"
18 #include "base/trace_event/trace_event.h"
19 #include "build/build_config.h"
20 
21 #if defined(__ANDROID__) || defined(__ANDROID_HOST__)
22 #include <event2/event.h>
23 #include <event2/event_compat.h>
24 #include <event2/event_struct.h>
25 #else
26 #include "third_party/libevent/event.h"
27 #endif
28 
29 #if defined(OS_MACOSX)
30 #include "base/mac/scoped_nsautorelease_pool.h"
31 #endif
32 
33 // Lifecycle of struct event
34 // Libevent uses two main data structures:
35 // struct event_base (of which there is one per message pump), and
36 // struct event (of which there is roughly one per socket).
37 // The socket's struct event is created in
38 // MessagePumpLibevent::WatchFileDescriptor(),
39 // is owned by the FileDescriptorWatcher, and is destroyed in
40 // StopWatchingFileDescriptor().
41 // It is moved into and out of lists in struct event_base by
42 // the libevent functions event_add() and event_del().
43 //
44 // TODO(dkegel):
45 // At the moment bad things happen if a FileDescriptorWatcher
46 // is active after its MessagePumpLibevent has been destroyed.
47 // See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
48 // Not clear yet whether that situation occurs in practice,
49 // but if it does, we need to fix it.
50 
51 namespace base {
52 
FileDescriptorWatcher()53 MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
54     : event_(NULL),
55       pump_(NULL),
56       watcher_(NULL),
57       was_destroyed_(NULL) {
58 }
59 
~FileDescriptorWatcher()60 MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
61   if (event_) {
62     StopWatchingFileDescriptor();
63   }
64   if (was_destroyed_) {
65     DCHECK(!*was_destroyed_);
66     *was_destroyed_ = true;
67   }
68 }
69 
StopWatchingFileDescriptor()70 bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
71   event* e = ReleaseEvent();
72   if (e == NULL)
73     return true;
74 
75   // event_del() is a no-op if the event isn't active.
76   int rv = event_del(e);
77   delete e;
78   pump_ = NULL;
79   watcher_ = NULL;
80   return (rv == 0);
81 }
82 
Init(event * e)83 void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e) {
84   DCHECK(e);
85   DCHECK(!event_);
86 
87   event_ = e;
88 }
89 
ReleaseEvent()90 event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
91   struct event *e = event_;
92   event_ = NULL;
93   return e;
94 }
95 
OnFileCanReadWithoutBlocking(int fd,MessagePumpLibevent * pump)96 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanReadWithoutBlocking(
97     int fd, MessagePumpLibevent* pump) {
98   // Since OnFileCanWriteWithoutBlocking() gets called first, it can stop
99   // watching the file descriptor.
100   if (!watcher_)
101     return;
102   pump->WillProcessIOEvent();
103   watcher_->OnFileCanReadWithoutBlocking(fd);
104   pump->DidProcessIOEvent();
105 }
106 
OnFileCanWriteWithoutBlocking(int fd,MessagePumpLibevent * pump)107 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking(
108     int fd, MessagePumpLibevent* pump) {
109   DCHECK(watcher_);
110   pump->WillProcessIOEvent();
111   watcher_->OnFileCanWriteWithoutBlocking(fd);
112   pump->DidProcessIOEvent();
113 }
114 
MessagePumpLibevent()115 MessagePumpLibevent::MessagePumpLibevent()
116     : keep_running_(true),
117       in_run_(false),
118       processed_io_events_(false),
119       event_base_(event_base_new()),
120       wakeup_pipe_in_(-1),
121       wakeup_pipe_out_(-1) {
122   if (!Init())
123      NOTREACHED();
124 }
125 
~MessagePumpLibevent()126 MessagePumpLibevent::~MessagePumpLibevent() {
127   DCHECK(wakeup_event_);
128   DCHECK(event_base_);
129   event_del(wakeup_event_);
130   delete wakeup_event_;
131   if (wakeup_pipe_in_ >= 0) {
132     if (IGNORE_EINTR(close(wakeup_pipe_in_)) < 0)
133       DPLOG(ERROR) << "close";
134   }
135   if (wakeup_pipe_out_ >= 0) {
136     if (IGNORE_EINTR(close(wakeup_pipe_out_)) < 0)
137       DPLOG(ERROR) << "close";
138   }
139   event_base_free(event_base_);
140 }
141 
WatchFileDescriptor(int fd,bool persistent,int mode,FileDescriptorWatcher * controller,Watcher * delegate)142 bool MessagePumpLibevent::WatchFileDescriptor(int fd,
143                                               bool persistent,
144                                               int mode,
145                                               FileDescriptorWatcher *controller,
146                                               Watcher *delegate) {
147   DCHECK_GE(fd, 0);
148   DCHECK(controller);
149   DCHECK(delegate);
150   DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
151   // WatchFileDescriptor should be called on the pump thread. It is not
152   // threadsafe, and your watcher may never be registered.
153   DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread());
154 
155   int event_mask = persistent ? EV_PERSIST : 0;
156   if (mode & WATCH_READ) {
157     event_mask |= EV_READ;
158   }
159   if (mode & WATCH_WRITE) {
160     event_mask |= EV_WRITE;
161   }
162 
163   scoped_ptr<event> evt(controller->ReleaseEvent());
164   if (evt.get() == NULL) {
165     // Ownership is transferred to the controller.
166     evt.reset(new event);
167   } else {
168     // Make sure we don't pick up any funky internal libevent masks.
169     int old_interest_mask = evt.get()->ev_events &
170         (EV_READ | EV_WRITE | EV_PERSIST);
171 
172     // Combine old/new event masks.
173     event_mask |= old_interest_mask;
174 
175     // Must disarm the event before we can reuse it.
176     event_del(evt.get());
177 
178     // It's illegal to use this function to listen on 2 separate fds with the
179     // same |controller|.
180     if (EVENT_FD(evt.get()) != fd) {
181       NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
182       return false;
183     }
184   }
185 
186   // Set current interest mask and message pump for this event.
187   event_set(evt.get(), fd, event_mask, OnLibeventNotification, controller);
188 
189   // Tell libevent which message pump this socket will belong to when we add it.
190   if (event_base_set(event_base_, evt.get())) {
191     return false;
192   }
193 
194   // Add this socket to the list of monitored sockets.
195   if (event_add(evt.get(), NULL)) {
196     return false;
197   }
198 
199   // Transfer ownership of evt to controller.
200   controller->Init(evt.release());
201 
202   controller->set_watcher(delegate);
203   controller->set_pump(this);
204 
205   return true;
206 }
207 
AddIOObserver(IOObserver * obs)208 void MessagePumpLibevent::AddIOObserver(IOObserver *obs) {
209   io_observers_.AddObserver(obs);
210 }
211 
RemoveIOObserver(IOObserver * obs)212 void MessagePumpLibevent::RemoveIOObserver(IOObserver *obs) {
213   io_observers_.RemoveObserver(obs);
214 }
215 
216 // Tell libevent to break out of inner loop.
timer_callback(int,short,void * context)217 static void timer_callback(int /* fd */, short /* events */, void *context)
218 {
219   event_base_loopbreak((struct event_base *)context);
220 }
221 
222 // Reentrant!
Run(Delegate * delegate)223 void MessagePumpLibevent::Run(Delegate* delegate) {
224   AutoReset<bool> auto_reset_keep_running(&keep_running_, true);
225   AutoReset<bool> auto_reset_in_run(&in_run_, true);
226 
227   // event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
228   // Instead, make our own timer and reuse it on each call to event_base_loop().
229   scoped_ptr<event> timer_event(new event);
230 
231   for (;;) {
232 #if defined(OS_MACOSX)
233     mac::ScopedNSAutoreleasePool autorelease_pool;
234 #endif
235 
236     bool did_work = delegate->DoWork();
237     if (!keep_running_)
238       break;
239 
240     event_base_loop(event_base_, EVLOOP_NONBLOCK);
241     did_work |= processed_io_events_;
242     processed_io_events_ = false;
243     if (!keep_running_)
244       break;
245 
246     did_work |= delegate->DoDelayedWork(&delayed_work_time_);
247     if (!keep_running_)
248       break;
249 
250     if (did_work)
251       continue;
252 
253     did_work = delegate->DoIdleWork();
254     if (!keep_running_)
255       break;
256 
257     if (did_work)
258       continue;
259 
260     // EVLOOP_ONCE tells libevent to only block once,
261     // but to service all pending events when it wakes up.
262     if (delayed_work_time_.is_null()) {
263       event_base_loop(event_base_, EVLOOP_ONCE);
264     } else {
265       TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
266       if (delay > TimeDelta()) {
267         struct timeval poll_tv;
268         poll_tv.tv_sec = delay.InSeconds();
269         poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
270         event_set(timer_event.get(), -1, 0, timer_callback, event_base_);
271         event_base_set(event_base_, timer_event.get());
272         event_add(timer_event.get(), &poll_tv);
273         event_base_loop(event_base_, EVLOOP_ONCE);
274         event_del(timer_event.get());
275       } else {
276         // It looks like delayed_work_time_ indicates a time in the past, so we
277         // need to call DoDelayedWork now.
278         delayed_work_time_ = TimeTicks();
279       }
280     }
281 
282     if (!keep_running_)
283       break;
284   }
285 }
286 
Quit()287 void MessagePumpLibevent::Quit() {
288   DCHECK(in_run_) << "Quit was called outside of Run!";
289   // Tell both libevent and Run that they should break out of their loops.
290   keep_running_ = false;
291   ScheduleWork();
292 }
293 
ScheduleWork()294 void MessagePumpLibevent::ScheduleWork() {
295   // Tell libevent (in a threadsafe way) that it should break out of its loop.
296   char buf = 0;
297   int nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
298   DCHECK(nwrite == 1 || errno == EAGAIN)
299       << "[nwrite:" << nwrite << "] [errno:" << errno << "]";
300 }
301 
ScheduleDelayedWork(const TimeTicks & delayed_work_time)302 void MessagePumpLibevent::ScheduleDelayedWork(
303     const TimeTicks& delayed_work_time) {
304   // We know that we can't be blocked on Wait right now since this method can
305   // only be called on the same thread as Run, so we only need to update our
306   // record of how long to sleep when we do sleep.
307   delayed_work_time_ = delayed_work_time;
308 }
309 
WillProcessIOEvent()310 void MessagePumpLibevent::WillProcessIOEvent() {
311   FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
312 }
313 
DidProcessIOEvent()314 void MessagePumpLibevent::DidProcessIOEvent() {
315   FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
316 }
317 
Init()318 bool MessagePumpLibevent::Init() {
319   int fds[2];
320   if (pipe(fds)) {
321     DLOG(ERROR) << "pipe() failed, errno: " << errno;
322     return false;
323   }
324   if (!SetNonBlocking(fds[0])) {
325     DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
326     return false;
327   }
328   if (!SetNonBlocking(fds[1])) {
329     DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
330     return false;
331   }
332   wakeup_pipe_out_ = fds[0];
333   wakeup_pipe_in_ = fds[1];
334 
335   wakeup_event_ = new event;
336   event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
337             OnWakeup, this);
338   event_base_set(event_base_, wakeup_event_);
339 
340   if (event_add(wakeup_event_, 0))
341     return false;
342   return true;
343 }
344 
345 // static
OnLibeventNotification(int fd,short flags,void * context)346 void MessagePumpLibevent::OnLibeventNotification(int fd,
347                                                  short flags,
348                                                  void* context) {
349   FileDescriptorWatcher* controller =
350       static_cast<FileDescriptorWatcher*>(context);
351   DCHECK(controller);
352   TRACE_EVENT1("toplevel", "MessagePumpLibevent::OnLibeventNotification",
353                "fd", fd);
354 
355   MessagePumpLibevent* pump = controller->pump();
356   pump->processed_io_events_ = true;
357 
358   if ((flags & (EV_READ | EV_WRITE)) == (EV_READ | EV_WRITE)) {
359     // Both callbacks will be called. It is necessary to check that |controller|
360     // is not destroyed.
361     bool controller_was_destroyed = false;
362     controller->was_destroyed_ = &controller_was_destroyed;
363     controller->OnFileCanWriteWithoutBlocking(fd, pump);
364     if (!controller_was_destroyed)
365       controller->OnFileCanReadWithoutBlocking(fd, pump);
366     if (!controller_was_destroyed)
367       controller->was_destroyed_ = nullptr;
368   } else if (flags & EV_WRITE) {
369     controller->OnFileCanWriteWithoutBlocking(fd, pump);
370   } else if (flags & EV_READ) {
371     controller->OnFileCanReadWithoutBlocking(fd, pump);
372   }
373 }
374 
375 // Called if a byte is received on the wakeup pipe.
376 // static
OnWakeup(int socket,short,void * context)377 void MessagePumpLibevent::OnWakeup(int socket, short /* flags */,
378                                    void* context) {
379   MessagePumpLibevent* that = static_cast<MessagePumpLibevent*>(context);
380   DCHECK(that->wakeup_pipe_out_ == socket);
381 
382   // Remove and discard the wakeup byte.
383   char buf;
384   int nread = HANDLE_EINTR(read(socket, &buf, 1));
385   DCHECK_EQ(nread, 1);
386   that->processed_io_events_ = true;
387   // Tell libevent to break out of inner loop.
388   event_base_loopbreak(that->event_base_);
389 }
390 
391 }  // namespace base
392