Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(94)

Side by Side Diff: base/message_pump_io_ios.cc

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

Powered by Google App Engine
This is Rietveld 408576698