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 "third_party/libevent/event.h"
20 #if defined(OS_MACOSX)
21 #include "base/mac/scoped_nsautorelease_pool.h"
24 // Lifecycle of struct event
25 // Libevent uses two main data structures:
26 // struct event_base (of which there is one per message pump), and
27 // struct event (of which there is roughly one per socket).
28 // The socket's struct event is created in
29 // MessagePumpLibevent::WatchFileDescriptor(),
30 // is owned by the FileDescriptorWatcher, and is destroyed in
31 // StopWatchingFileDescriptor().
32 // It is moved into and out of lists in struct event_base by
33 // the libevent functions event_add() and event_del().
36 // At the moment bad things happen if a FileDescriptorWatcher
37 // is active after its MessagePumpLibevent has been destroyed.
38 // See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
39 // Not clear yet whether that situation occurs in practice,
40 // but if it does, we need to fix it.
44 // Return 0 on success
45 // Too small a function to bother putting in a library?
46 static int SetNonBlocking(int fd
) {
47 int flags
= fcntl(fd
, F_GETFL
, 0);
50 return fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
53 MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
60 MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
62 StopWatchingFileDescriptor();
66 bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
67 event
* e
= ReleaseEvent();
71 // event_del() is a no-op if the event isn't active.
72 int rv
= event_del(e
);
79 void MessagePumpLibevent::FileDescriptorWatcher::Init(event
*e
) {
86 event
*MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
87 struct event
*e
= event_
;
92 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanReadWithoutBlocking(
93 int fd
, MessagePumpLibevent
* pump
) {
94 // Since OnFileCanWriteWithoutBlocking() gets called first, it can stop
95 // watching the file descriptor.
98 pump
->WillProcessIOEvent();
99 watcher_
->OnFileCanReadWithoutBlocking(fd
);
100 pump
->DidProcessIOEvent();
103 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking(
104 int fd
, MessagePumpLibevent
* pump
) {
106 pump
->WillProcessIOEvent();
107 watcher_
->OnFileCanWriteWithoutBlocking(fd
);
108 pump
->DidProcessIOEvent();
111 MessagePumpLibevent::MessagePumpLibevent()
112 : keep_running_(true),
114 processed_io_events_(false),
115 event_base_(event_base_new()),
117 wakeup_pipe_out_(-1) {
122 MessagePumpLibevent::~MessagePumpLibevent() {
123 DCHECK(wakeup_event_
);
125 event_del(wakeup_event_
);
126 delete wakeup_event_
;
127 if (wakeup_pipe_in_
>= 0) {
128 if (IGNORE_EINTR(close(wakeup_pipe_in_
)) < 0)
129 DPLOG(ERROR
) << "close";
131 if (wakeup_pipe_out_
>= 0) {
132 if (IGNORE_EINTR(close(wakeup_pipe_out_
)) < 0)
133 DPLOG(ERROR
) << "close";
135 event_base_free(event_base_
);
138 bool MessagePumpLibevent::WatchFileDescriptor(int fd
,
141 FileDescriptorWatcher
*controller
,
146 DCHECK(mode
== WATCH_READ
|| mode
== WATCH_WRITE
|| mode
== WATCH_READ_WRITE
);
147 // WatchFileDescriptor should be called on the pump thread. It is not
148 // threadsafe, and your watcher may never be registered.
149 DCHECK(watch_file_descriptor_caller_checker_
.CalledOnValidThread());
151 int event_mask
= persistent
? EV_PERSIST
: 0;
152 if (mode
& WATCH_READ
) {
153 event_mask
|= EV_READ
;
155 if (mode
& WATCH_WRITE
) {
156 event_mask
|= EV_WRITE
;
159 scoped_ptr
<event
> evt(controller
->ReleaseEvent());
160 if (evt
.get() == NULL
) {
161 // Ownership is transferred to the controller.
162 evt
.reset(new event
);
164 // Make sure we don't pick up any funky internal libevent masks.
165 int old_interest_mask
= evt
.get()->ev_events
&
166 (EV_READ
| EV_WRITE
| EV_PERSIST
);
168 // Combine old/new event masks.
169 event_mask
|= old_interest_mask
;
171 // Must disarm the event before we can reuse it.
172 event_del(evt
.get());
174 // It's illegal to use this function to listen on 2 separate fds with the
175 // same |controller|.
176 if (EVENT_FD(evt
.get()) != fd
) {
177 NOTREACHED() << "FDs don't match" << EVENT_FD(evt
.get()) << "!=" << fd
;
182 // Set current interest mask and message pump for this event.
183 event_set(evt
.get(), fd
, event_mask
, OnLibeventNotification
, controller
);
185 // Tell libevent which message pump this socket will belong to when we add it.
186 if (event_base_set(event_base_
, evt
.get())) {
190 // Add this socket to the list of monitored sockets.
191 if (event_add(evt
.get(), NULL
)) {
195 // Transfer ownership of evt to controller.
196 controller
->Init(evt
.release());
198 controller
->set_watcher(delegate
);
199 controller
->set_pump(this);
204 void MessagePumpLibevent::AddIOObserver(IOObserver
*obs
) {
205 io_observers_
.AddObserver(obs
);
208 void MessagePumpLibevent::RemoveIOObserver(IOObserver
*obs
) {
209 io_observers_
.RemoveObserver(obs
);
212 // Tell libevent to break out of inner loop.
213 static void timer_callback(int fd
, short events
, void *context
)
215 event_base_loopbreak((struct event_base
*)context
);
219 void MessagePumpLibevent::Run(Delegate
* delegate
) {
220 AutoReset
<bool> auto_reset_keep_running(&keep_running_
, true);
221 AutoReset
<bool> auto_reset_in_run(&in_run_
, true);
223 // event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
224 // Instead, make our own timer and reuse it on each call to event_base_loop().
225 scoped_ptr
<event
> timer_event(new event
);
228 #if defined(OS_MACOSX)
229 mac::ScopedNSAutoreleasePool autorelease_pool
;
232 bool did_work
= delegate
->DoWork();
236 event_base_loop(event_base_
, EVLOOP_NONBLOCK
);
237 did_work
|= processed_io_events_
;
238 processed_io_events_
= false;
242 did_work
|= delegate
->DoDelayedWork(&delayed_work_time_
);
249 did_work
= delegate
->DoIdleWork();
256 // EVLOOP_ONCE tells libevent to only block once,
257 // but to service all pending events when it wakes up.
258 if (delayed_work_time_
.is_null()) {
259 event_base_loop(event_base_
, EVLOOP_ONCE
);
261 TimeDelta delay
= delayed_work_time_
- TimeTicks::Now();
262 if (delay
> TimeDelta()) {
263 struct timeval poll_tv
;
264 poll_tv
.tv_sec
= delay
.InSeconds();
265 poll_tv
.tv_usec
= delay
.InMicroseconds() % Time::kMicrosecondsPerSecond
;
266 event_set(timer_event
.get(), -1, 0, timer_callback
, event_base_
);
267 event_base_set(event_base_
, timer_event
.get());
268 event_add(timer_event
.get(), &poll_tv
);
269 event_base_loop(event_base_
, EVLOOP_ONCE
);
270 event_del(timer_event
.get());
272 // It looks like delayed_work_time_ indicates a time in the past, so we
273 // need to call DoDelayedWork now.
274 delayed_work_time_
= TimeTicks();
280 void MessagePumpLibevent::Quit() {
281 DCHECK(in_run_
) << "Quit was called outside of Run!";
282 // Tell both libevent and Run that they should break out of their loops.
283 keep_running_
= false;
287 void MessagePumpLibevent::ScheduleWork() {
288 // Tell libevent (in a threadsafe way) that it should break out of its loop.
290 int nwrite
= HANDLE_EINTR(write(wakeup_pipe_in_
, &buf
, 1));
291 DCHECK(nwrite
== 1 || errno
== EAGAIN
)
292 << "[nwrite:" << nwrite
<< "] [errno:" << errno
<< "]";
295 void MessagePumpLibevent::ScheduleDelayedWork(
296 const TimeTicks
& delayed_work_time
) {
297 // We know that we can't be blocked on Wait right now since this method can
298 // only be called on the same thread as Run, so we only need to update our
299 // record of how long to sleep when we do sleep.
300 delayed_work_time_
= delayed_work_time
;
303 void MessagePumpLibevent::WillProcessIOEvent() {
304 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
307 void MessagePumpLibevent::DidProcessIOEvent() {
308 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
311 bool MessagePumpLibevent::Init() {
314 DLOG(ERROR
) << "pipe() failed, errno: " << errno
;
317 if (SetNonBlocking(fds
[0])) {
318 DLOG(ERROR
) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno
;
321 if (SetNonBlocking(fds
[1])) {
322 DLOG(ERROR
) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno
;
325 wakeup_pipe_out_
= fds
[0];
326 wakeup_pipe_in_
= fds
[1];
328 wakeup_event_
= new event
;
329 event_set(wakeup_event_
, wakeup_pipe_out_
, EV_READ
| EV_PERSIST
,
331 event_base_set(event_base_
, wakeup_event_
);
333 if (event_add(wakeup_event_
, 0))
339 void MessagePumpLibevent::OnLibeventNotification(int fd
, short flags
,
341 WeakPtr
<FileDescriptorWatcher
> controller
=
342 static_cast<FileDescriptorWatcher
*>(context
)->weak_factory_
.GetWeakPtr();
343 DCHECK(controller
.get());
345 MessagePumpLibevent
* pump
= controller
->pump();
346 pump
->processed_io_events_
= true;
348 if (flags
& EV_WRITE
) {
349 controller
->OnFileCanWriteWithoutBlocking(fd
, pump
);
351 // Check |controller| in case it's been deleted in
352 // controller->OnFileCanWriteWithoutBlocking().
353 if (controller
.get() && flags
& EV_READ
) {
354 controller
->OnFileCanReadWithoutBlocking(fd
, pump
);
358 // Called if a byte is received on the wakeup pipe.
360 void MessagePumpLibevent::OnWakeup(int socket
, short flags
, void* context
) {
361 MessagePumpLibevent
* that
= static_cast<MessagePumpLibevent
*>(context
);
362 DCHECK(that
->wakeup_pipe_out_
== socket
);
364 // Remove and discard the wakeup byte.
366 int nread
= HANDLE_EINTR(read(socket
, &buf
, 1));
368 that
->processed_io_events_
= true;
369 // Tell libevent to break out of inner loop.
370 event_base_loopbreak(that
->event_base_
);