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.
5 #include "base/message_loop/message_pump_libevent.h"
11 #include "base/auto_reset.h"
12 #include "base/compiler_specific.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 "third_party/libevent/event.h"
21 #if defined(OS_MACOSX)
22 #include "base/mac/scoped_nsautorelease_pool.h"
25 // Lifecycle of struct event
26 // Libevent uses two main data structures:
27 // struct event_base (of which there is one per message pump), and
28 // struct event (of which there is roughly one per socket).
29 // The socket's struct event is created in
30 // MessagePumpLibevent::WatchFileDescriptor(),
31 // is owned by the FileDescriptorWatcher, and is destroyed in
32 // StopWatchingFileDescriptor().
33 // It is moved into and out of lists in struct event_base by
34 // the libevent functions event_add() and event_del().
37 // At the moment bad things happen if a FileDescriptorWatcher
38 // is active after its MessagePumpLibevent has been destroyed.
39 // See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
40 // Not clear yet whether that situation occurs in practice,
41 // but if it does, we need to fix it.
45 // Return 0 on success
46 // Too small a function to bother putting in a library?
47 static int SetNonBlocking(int fd
) {
48 int flags
= fcntl(fd
, F_GETFL
, 0);
51 return fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
54 MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
58 was_destroyed_(NULL
) {
61 MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
63 StopWatchingFileDescriptor();
66 DCHECK(!*was_destroyed_
);
67 *was_destroyed_
= true;
71 bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
72 event
* e
= ReleaseEvent();
76 // event_del() is a no-op if the event isn't active.
77 int rv
= event_del(e
);
84 void MessagePumpLibevent::FileDescriptorWatcher::Init(event
*e
) {
91 event
*MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
92 struct event
*e
= event_
;
97 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanReadWithoutBlocking(
98 int fd
, MessagePumpLibevent
* pump
) {
99 // Since OnFileCanWriteWithoutBlocking() gets called first, it can stop
100 // watching the file descriptor.
103 pump
->WillProcessIOEvent();
104 watcher_
->OnFileCanReadWithoutBlocking(fd
);
105 pump
->DidProcessIOEvent();
108 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking(
109 int fd
, MessagePumpLibevent
* pump
) {
111 pump
->WillProcessIOEvent();
112 watcher_
->OnFileCanWriteWithoutBlocking(fd
);
113 pump
->DidProcessIOEvent();
116 MessagePumpLibevent::MessagePumpLibevent()
117 : keep_running_(true),
119 processed_io_events_(false),
120 event_base_(event_base_new()),
122 wakeup_pipe_out_(-1) {
127 MessagePumpLibevent::~MessagePumpLibevent() {
128 DCHECK(wakeup_event_
);
130 event_del(wakeup_event_
);
131 delete wakeup_event_
;
132 if (wakeup_pipe_in_
>= 0) {
133 if (IGNORE_EINTR(close(wakeup_pipe_in_
)) < 0)
134 DPLOG(ERROR
) << "close";
136 if (wakeup_pipe_out_
>= 0) {
137 if (IGNORE_EINTR(close(wakeup_pipe_out_
)) < 0)
138 DPLOG(ERROR
) << "close";
140 event_base_free(event_base_
);
143 bool MessagePumpLibevent::WatchFileDescriptor(int fd
,
146 FileDescriptorWatcher
*controller
,
151 DCHECK(mode
== WATCH_READ
|| mode
== WATCH_WRITE
|| mode
== WATCH_READ_WRITE
);
152 // WatchFileDescriptor should be called on the pump thread. It is not
153 // threadsafe, and your watcher may never be registered.
154 DCHECK(watch_file_descriptor_caller_checker_
.CalledOnValidThread());
156 int event_mask
= persistent
? EV_PERSIST
: 0;
157 if (mode
& WATCH_READ
) {
158 event_mask
|= EV_READ
;
160 if (mode
& WATCH_WRITE
) {
161 event_mask
|= EV_WRITE
;
164 scoped_ptr
<event
> evt(controller
->ReleaseEvent());
165 if (evt
.get() == NULL
) {
166 // Ownership is transferred to the controller.
167 evt
.reset(new event
);
169 // Make sure we don't pick up any funky internal libevent masks.
170 int old_interest_mask
= evt
.get()->ev_events
&
171 (EV_READ
| EV_WRITE
| EV_PERSIST
);
173 // Combine old/new event masks.
174 event_mask
|= old_interest_mask
;
176 // Must disarm the event before we can reuse it.
177 event_del(evt
.get());
179 // It's illegal to use this function to listen on 2 separate fds with the
180 // same |controller|.
181 if (EVENT_FD(evt
.get()) != fd
) {
182 NOTREACHED() << "FDs don't match" << EVENT_FD(evt
.get()) << "!=" << fd
;
187 // Set current interest mask and message pump for this event.
188 event_set(evt
.get(), fd
, event_mask
, OnLibeventNotification
, controller
);
190 // Tell libevent which message pump this socket will belong to when we add it.
191 if (event_base_set(event_base_
, evt
.get())) {
195 // Add this socket to the list of monitored sockets.
196 if (event_add(evt
.get(), NULL
)) {
200 // Transfer ownership of evt to controller.
201 controller
->Init(evt
.release());
203 controller
->set_watcher(delegate
);
204 controller
->set_pump(this);
209 void MessagePumpLibevent::AddIOObserver(IOObserver
*obs
) {
210 io_observers_
.AddObserver(obs
);
213 void MessagePumpLibevent::RemoveIOObserver(IOObserver
*obs
) {
214 io_observers_
.RemoveObserver(obs
);
217 // Tell libevent to break out of inner loop.
218 static void timer_callback(int fd
, short events
, void *context
)
220 event_base_loopbreak((struct event_base
*)context
);
224 void MessagePumpLibevent::Run(Delegate
* delegate
) {
225 AutoReset
<bool> auto_reset_keep_running(&keep_running_
, true);
226 AutoReset
<bool> auto_reset_in_run(&in_run_
, true);
228 // event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
229 // Instead, make our own timer and reuse it on each call to event_base_loop().
230 scoped_ptr
<event
> timer_event(new event
);
233 #if defined(OS_MACOSX)
234 mac::ScopedNSAutoreleasePool autorelease_pool
;
237 bool did_work
= delegate
->DoWork();
241 event_base_loop(event_base_
, EVLOOP_NONBLOCK
);
242 did_work
|= processed_io_events_
;
243 processed_io_events_
= false;
247 did_work
|= delegate
->DoDelayedWork(&delayed_work_time_
);
254 did_work
= delegate
->DoIdleWork();
261 // EVLOOP_ONCE tells libevent to only block once,
262 // but to service all pending events when it wakes up.
263 if (delayed_work_time_
.is_null()) {
264 event_base_loop(event_base_
, EVLOOP_ONCE
);
266 TimeDelta delay
= delayed_work_time_
- TimeTicks::Now();
267 if (delay
> TimeDelta()) {
268 struct timeval poll_tv
;
269 poll_tv
.tv_sec
= delay
.InSeconds();
270 poll_tv
.tv_usec
= delay
.InMicroseconds() % Time::kMicrosecondsPerSecond
;
271 event_set(timer_event
.get(), -1, 0, timer_callback
, event_base_
);
272 event_base_set(event_base_
, timer_event
.get());
273 event_add(timer_event
.get(), &poll_tv
);
274 event_base_loop(event_base_
, EVLOOP_ONCE
);
275 event_del(timer_event
.get());
277 // It looks like delayed_work_time_ indicates a time in the past, so we
278 // need to call DoDelayedWork now.
279 delayed_work_time_
= TimeTicks();
288 void MessagePumpLibevent::Quit() {
289 DCHECK(in_run_
) << "Quit was called outside of Run!";
290 // Tell both libevent and Run that they should break out of their loops.
291 keep_running_
= false;
295 void MessagePumpLibevent::ScheduleWork() {
296 // Tell libevent (in a threadsafe way) that it should break out of its loop.
298 int nwrite
= HANDLE_EINTR(write(wakeup_pipe_in_
, &buf
, 1));
299 DCHECK(nwrite
== 1 || errno
== EAGAIN
)
300 << "[nwrite:" << nwrite
<< "] [errno:" << errno
<< "]";
303 void MessagePumpLibevent::ScheduleDelayedWork(
304 const TimeTicks
& delayed_work_time
) {
305 // We know that we can't be blocked on Wait right now since this method can
306 // only be called on the same thread as Run, so we only need to update our
307 // record of how long to sleep when we do sleep.
308 delayed_work_time_
= delayed_work_time
;
311 void MessagePumpLibevent::WillProcessIOEvent() {
312 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
315 void MessagePumpLibevent::DidProcessIOEvent() {
316 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
319 bool MessagePumpLibevent::Init() {
322 DLOG(ERROR
) << "pipe() failed, errno: " << errno
;
325 if (SetNonBlocking(fds
[0])) {
326 DLOG(ERROR
) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno
;
329 if (SetNonBlocking(fds
[1])) {
330 DLOG(ERROR
) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno
;
333 wakeup_pipe_out_
= fds
[0];
334 wakeup_pipe_in_
= fds
[1];
336 wakeup_event_
= new event
;
337 event_set(wakeup_event_
, wakeup_pipe_out_
, EV_READ
| EV_PERSIST
,
339 event_base_set(event_base_
, wakeup_event_
);
341 if (event_add(wakeup_event_
, 0))
347 void MessagePumpLibevent::OnLibeventNotification(int fd
,
350 FileDescriptorWatcher
* controller
=
351 static_cast<FileDescriptorWatcher
*>(context
);
353 TRACE_EVENT1("toplevel", "MessagePumpLibevent::OnLibeventNotification",
356 MessagePumpLibevent
* pump
= controller
->pump();
357 pump
->processed_io_events_
= true;
359 if ((flags
& (EV_READ
| EV_WRITE
)) == (EV_READ
| EV_WRITE
)) {
360 // Both callbacks will be called. It is necessary to check that |controller|
362 bool controller_was_destroyed
= false;
363 controller
->was_destroyed_
= &controller_was_destroyed
;
364 controller
->OnFileCanWriteWithoutBlocking(fd
, pump
);
365 if (!controller_was_destroyed
)
366 controller
->OnFileCanReadWithoutBlocking(fd
, pump
);
367 if (!controller_was_destroyed
)
368 controller
->was_destroyed_
= nullptr;
369 } else if (flags
& EV_WRITE
) {
370 controller
->OnFileCanWriteWithoutBlocking(fd
, pump
);
371 } else if (flags
& EV_READ
) {
372 controller
->OnFileCanReadWithoutBlocking(fd
, pump
);
376 // Called if a byte is received on the wakeup pipe.
378 void MessagePumpLibevent::OnWakeup(int socket
, short flags
, void* context
) {
379 MessagePumpLibevent
* that
= static_cast<MessagePumpLibevent
*>(context
);
380 DCHECK(that
->wakeup_pipe_out_
== socket
);
382 // Remove and discard the wakeup byte.
384 int nread
= HANDLE_EINTR(read(socket
, &buf
, 1));
386 that
->processed_io_events_
= true;
387 // Tell libevent to break out of inner loop.
388 event_base_loopbreak(that
->event_base_
);