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

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, bugfix 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 || mode == WATCH_READ_WRITE);
85
154 // WatchFileDescriptor should be called on the pump thread. It is not 86 // WatchFileDescriptor should be called on the pump thread. It is not
155 // threadsafe, and your watcher may never be registered. 87 // threadsafe, and your watcher may never be registered.
156 DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread()); 88 DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread());
157 89
158 int event_mask = persistent ? EV_PERSIST : 0; 90 CFFileDescriptorContext source_context = {0};
159 if ((mode & WATCH_READ) != 0) { 91 source_context.info = controller;
160 event_mask |= EV_READ; 92
161 } 93 CFOptionFlags callback_types = 0;
162 if ((mode & WATCH_WRITE) != 0) { 94 if (mode & WATCH_READ) {
163 event_mask |= EV_WRITE; 95 callback_types |= kCFFileDescriptorReadCallBack;
164 } 96 }
165 97 if (mode & WATCH_WRITE) {
166 scoped_ptr<event> evt(controller->ReleaseEvent()); 98 callback_types |= kCFFileDescriptorWriteCallBack;
167 if (evt.get() == NULL) { 99 }
168 // Ownership is transferred to the controller. 100
169 evt.reset(new event); 101 CFFileDescriptorRef fdref = controller->fdref_;
102 if (fdref == NULL) {
103 base::mac::ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref(
104 CFFileDescriptorCreate(kCFAllocatorDefault, fd, false, HandleFdIOEvent,
105 &source_context));
106 if (scoped_fdref == NULL) {
107 NOTREACHED() << "CFFileDescriptorCreate failed";
108 return false;
109 }
110
111 CFFileDescriptorEnableCallBacks(scoped_fdref, callback_types);
112
113 // TODO(wtc): what should the 'order' argument be?
114 base::mac::ScopedCFTypeRef<CFRunLoopSourceRef> scoped_fd_source(
115 CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault,
116 scoped_fdref,
117 0));
118 if (scoped_fd_source == NULL) {
119 NOTREACHED() << "CFFileDescriptorCreateRunLoopSource failed";
120 return false;
121 }
122 CFRunLoopAddSource(run_loop(), scoped_fd_source, kCFRunLoopCommonModes);
123
124 // Transfer ownership of scoped_fdref and fd_source to controller.
125 controller->Init(scoped_fdref.release(), callback_types,
126 scoped_fd_source.release(), persistent);
170 } else { 127 } 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 128 // It's illegal to use this function to listen on 2 separate fds with the
182 // same |controller|. 129 // same |controller|.
183 if (EVENT_FD(evt.get()) != fd) { 130 if (CFFileDescriptorGetNativeDescriptor(fdref) != fd) {
184 NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd; 131 NOTREACHED() << "FDs don't match: "
185 return false; 132 << CFFileDescriptorGetNativeDescriptor(fdref)
186 } 133 << " != " << fd;
187 } 134 return false;
188 135 }
189 // Set current interest mask and message pump for this event. 136 if (persistent != controller->is_persistent_) {
190 event_set(evt.get(), fd, event_mask, OnLibeventNotification, controller); 137 NOTREACHED() << "persistent doesn't match";
191 138 return false;
192 // Tell libevent which message pump this socket will belong to when we add it. 139 }
193 if (event_base_set(event_base_, evt.get()) != 0) { 140
194 return false; 141 // Combine old/new event masks.
195 } 142 CFFileDescriptorDisableCallBacks(fdref, controller->callback_types_);
196 143 controller->callback_types_ |= callback_types;
197 // Add this socket to the list of monitored sockets. 144 CFFileDescriptorEnableCallBacks(fdref, controller->callback_types_);
198 if (event_add(evt.get(), NULL) != 0) { 145 }
199 return false;
200 }
201
202 // Transfer ownership of evt to controller.
203 controller->Init(evt.release());
204 146
205 controller->set_watcher(delegate); 147 controller->set_watcher(delegate);
206 controller->set_pump(this); 148 controller->set_pump(this);
207 149
208 return true; 150 return true;
209 } 151 }
210 152
211 void MessagePumpLibevent::AddIOObserver(IOObserver *obs) { 153 void MessagePumpIOSForIO::RemoveRunLoopSource(CFRunLoopSourceRef source) {
154 CFRunLoopRemoveSource(run_loop(), source, kCFRunLoopCommonModes);
155 }
156
157 void MessagePumpIOSForIO::AddIOObserver(IOObserver *obs) {
212 io_observers_.AddObserver(obs); 158 io_observers_.AddObserver(obs);
213 } 159 }
214 160
215 void MessagePumpLibevent::RemoveIOObserver(IOObserver *obs) { 161 void MessagePumpIOSForIO::RemoveIOObserver(IOObserver *obs) {
216 io_observers_.RemoveObserver(obs); 162 io_observers_.RemoveObserver(obs);
217 } 163 }
218 164
219 // Tell libevent to break out of inner loop. 165 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()); 166 FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
314 } 167 }
315 168
316 void MessagePumpLibevent::DidProcessIOEvent() { 169 void MessagePumpIOSForIO::DidProcessIOEvent() {
317 FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent()); 170 FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
318 } 171 }
319 172
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 173 // static
348 void MessagePumpLibevent::OnLibeventNotification(int fd, short flags, 174 void MessagePumpIOSForIO::HandleFdIOEvent(CFFileDescriptorRef fdref,
349 void* context) { 175 CFOptionFlags callback_types,
176 void* context) {
177 int fd = CFFileDescriptorGetNativeDescriptor(fdref);
178
350 base::WeakPtr<FileDescriptorWatcher> controller = 179 base::WeakPtr<FileDescriptorWatcher> controller =
351 static_cast<FileDescriptorWatcher*>(context)->weak_factory_.GetWeakPtr(); 180 static_cast<FileDescriptorWatcher*>(context)->weak_factory_.GetWeakPtr();
352 DCHECK(controller.get()); 181 DCHECK_EQ(fdref, controller->fdref_);
353 182
354 MessagePumpLibevent* pump = controller->pump(); 183 MessagePumpIOSForIO* pump = controller->pump();
355 pump->processed_io_events_ = true; 184 if (callback_types & kCFFileDescriptorWriteCallBack) {
356
357 if (flags & EV_WRITE) {
358 controller->OnFileCanWriteWithoutBlocking(fd, pump); 185 controller->OnFileCanWriteWithoutBlocking(fd, pump);
359 } 186 }
360 // Check |controller| in case it's been deleted in 187
361 // controller->OnFileCanWriteWithoutBlocking(). 188 // Perform the read callback only if (1) the controller has not been deleted
362 if (controller.get() && flags & EV_READ) { 189 // within the write callback and (2) |StopWatchingFileDescriptor()| has not
190 // been called within the write callback. The latter call having been made is
191 // indicated by |controller->fdref_| no longer being equal to |fdref| (NOTE:
192 // It's not enough to check for whether |controller->fdref_| is not NULL, as
193 // another call to |FileDescriptorWatcher::Init()| may have been made from
wtc 2012/11/28 23:59:47 Nit: this comment should mention the FileDescripto
blundell 2012/11/29 15:01:04 Changed the comment entirely (see below discussion
194 // within the callback).
195 if (callback_types & kCFFileDescriptorReadCallBack &&
196 controller.get() && controller->fdref_ == fdref) {
blundell 2012/11/28 16:56:55 Made this change because I saw while testing downs
wtc 2012/11/28 23:59:47 I confirm this can happen during TCPClientSocket::
blundell 2012/11/29 15:01:04 After your comments and Mark's comments about the
197 DCHECK(CFFileDescriptorIsValid(fdref));
363 controller->OnFileCanReadWithoutBlocking(fd, pump); 198 controller->OnFileCanReadWithoutBlocking(fd, pump);
364 } 199 }
365 } 200
366 201 // Re-enable callbacks after the read/write if (1) the controller has not
367 // Called if a byte is received on the wakeup pipe. 202 // been deleted, (2) |StopWatchingFileDescriptor()| has not been called, and
368 // static 203 // (3) the file descriptor watcher is persistent.
369 void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) { 204 if (controller.get() && controller->fdref_ == fdref &&
370 base::MessagePumpLibevent* that = 205 controller->is_persistent_) {
371 static_cast<base::MessagePumpLibevent*>(context); 206 DCHECK(CFFileDescriptorIsValid(fdref));
372 DCHECK(that->wakeup_pipe_out_ == socket); 207 CFFileDescriptorEnableCallBacks(fdref, callback_types);
373 208 }
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 } 209 }
382 210
383 } // namespace base 211 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698