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

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: Address minor review comments 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 }
65 } 17
66 18 MessagePumpIOSForIO::FileDescriptorWatcher::~FileDescriptorWatcher() {
67 MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() { 19 StopWatchingFileDescriptor();
68 if (event_) { 20 }
69 StopWatchingFileDescriptor(); 21
70 } 22 bool MessagePumpIOSForIO::FileDescriptorWatcher::StopWatchingFileDescriptor() {
71 } 23 if (fdref_ == NULL)
72
73 bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
74 event* e = ReleaseEvent();
75 if (e == NULL)
76 return true; 24 return true;
77 25
78 // event_del() is a no-op if the event isn't active. 26 CFFileDescriptorDisableCallBacks(fdref_, callback_types_);
79 int rv = event_del(e); 27 pump_->RemoveRunLoopSource(fd_source_);
80 delete e; 28 fd_source_.reset();
29 fdref_.reset();
30 callback_types_ = 0;
81 pump_ = NULL; 31 pump_ = NULL;
82 watcher_ = NULL; 32 watcher_ = NULL;
83 return (rv == 0); 33 return true;
84 } 34 }
85 35
86 void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e) { 36 void MessagePumpIOSForIO::FileDescriptorWatcher::Init(
87 DCHECK(e); 37 CFFileDescriptorRef fdref,
88 DCHECK(!event_); 38 CFOptionFlags callback_types,
89 39 CFRunLoopSourceRef fd_source,
90 event_ = e; 40 bool is_persistent) {
91 } 41 DCHECK(fdref);
92 42 DCHECK(!fdref_);
93 event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() { 43
94 struct event *e = event_; 44 is_persistent_ = is_persistent;
95 event_ = NULL; 45 fdref_.reset(fdref);
96 return e; 46 callback_types_ = callback_types;
97 } 47 fd_source_.reset(fd_source);
98 48 }
99 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanReadWithoutBlocking( 49
100 int fd, MessagePumpLibevent* pump) { 50 void MessagePumpIOSForIO::FileDescriptorWatcher::OnFileCanReadWithoutBlocking(
101 // Since OnFileCanWriteWithoutBlocking() gets called first, it can stop 51 int fd,
102 // watching the file descriptor. 52 MessagePumpIOSForIO* pump) {
103 if (!watcher_) 53 DCHECK(callback_types_ & kCFFileDescriptorReadCallBack);
104 return;
105 pump->WillProcessIOEvent(); 54 pump->WillProcessIOEvent();
106 watcher_->OnFileCanReadWithoutBlocking(fd); 55 watcher_->OnFileCanReadWithoutBlocking(fd);
107 pump->DidProcessIOEvent(); 56 pump->DidProcessIOEvent();
108 } 57 }
109 58
110 void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking( 59 void MessagePumpIOSForIO::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking(
111 int fd, MessagePumpLibevent* pump) { 60 int fd,
112 DCHECK(watcher_); 61 MessagePumpIOSForIO* pump) {
62 DCHECK(callback_types_ & kCFFileDescriptorWriteCallBack);
113 pump->WillProcessIOEvent(); 63 pump->WillProcessIOEvent();
114 watcher_->OnFileCanWriteWithoutBlocking(fd); 64 watcher_->OnFileCanWriteWithoutBlocking(fd);
115 pump->DidProcessIOEvent(); 65 pump->DidProcessIOEvent();
116 } 66 }
117 67
118 MessagePumpLibevent::MessagePumpLibevent() 68 MessagePumpIOSForIO::MessagePumpIOSForIO() {
119 : keep_running_(true), 69 }
120 in_run_(false), 70
121 processed_io_events_(false), 71 MessagePumpIOSForIO::~MessagePumpIOSForIO() {
122 event_base_(event_base_new()), 72 }
123 wakeup_pipe_in_(-1), 73
124 wakeup_pipe_out_(-1) { 74 bool MessagePumpIOSForIO::WatchFileDescriptor(
125 if (!Init()) 75 int fd,
126 NOTREACHED(); 76 bool persistent,
127 } 77 int mode,
128 78 FileDescriptorWatcher *controller,
129 MessagePumpLibevent::~MessagePumpLibevent() { 79 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); 80 DCHECK_GE(fd, 0);
151 DCHECK(controller); 81 DCHECK(controller);
152 DCHECK(delegate); 82 DCHECK(delegate);
153 DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE); 83 DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
84
154 // WatchFileDescriptor should be called on the pump thread. It is not 85 // WatchFileDescriptor should be called on the pump thread. It is not
155 // threadsafe, and your watcher may never be registered. 86 // threadsafe, and your watcher may never be registered.
156 DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread()); 87 DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread());
157 88
158 int event_mask = persistent ? EV_PERSIST : 0; 89 CFFileDescriptorContext source_context = {0};
159 if ((mode & WATCH_READ) != 0) { 90 source_context.info = controller;
160 event_mask |= EV_READ; 91
161 } 92 CFOptionFlags callback_types = 0;
162 if ((mode & WATCH_WRITE) != 0) { 93 if (mode & WATCH_READ) {
163 event_mask |= EV_WRITE; 94 callback_types |= kCFFileDescriptorReadCallBack;
164 } 95 }
165 96 if (mode & WATCH_WRITE) {
166 scoped_ptr<event> evt(controller->ReleaseEvent()); 97 callback_types |= kCFFileDescriptorWriteCallBack;
167 if (evt.get() == NULL) { 98 }
168 // Ownership is transferred to the controller. 99
169 evt.reset(new event); 100 CFFileDescriptorRef fdref = controller->fdref_;
101 if (fdref == NULL) {
102 base::mac::ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref(
103 CFFileDescriptorCreate(kCFAllocatorDefault, fd, false, HandleFdIOEvent,
104 &source_context));
105 if (scoped_fdref == NULL) {
106 NOTREACHED() << "CFFileDescriptorCreate failed";
107 return false;
108 }
109
110 CFFileDescriptorEnableCallBacks(scoped_fdref, callback_types);
111
112 // TODO(wtc): what should the 'order' argument be?
113 base::mac::ScopedCFTypeRef<CFRunLoopSourceRef> scoped_fd_source(
114 CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault,
115 scoped_fdref,
116 0));
117 if (scoped_fd_source == NULL) {
118 NOTREACHED() << "CFFileDescriptorCreateRunLoopSource failed";
119 return false;
120 }
121 CFRunLoopAddSource(run_loop(), scoped_fd_source, kCFRunLoopCommonModes);
122
123 // Transfer ownership of scoped_fdref and fd_source to controller.
124 controller->Init(scoped_fdref.release(), callback_types,
125 scoped_fd_source.release(), persistent);
170 } else { 126 } 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 127 // It's illegal to use this function to listen on 2 separate fds with the
182 // same |controller|. 128 // same |controller|.
183 if (EVENT_FD(evt.get()) != fd) { 129 if (CFFileDescriptorGetNativeDescriptor(fdref) != fd) {
184 NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd; 130 NOTREACHED() << "FDs don't match: "
185 return false; 131 << CFFileDescriptorGetNativeDescriptor(fdref)
186 } 132 << " != " << fd;
187 } 133 return false;
188 134 }
189 // Set current interest mask and message pump for this event. 135 if (persistent != controller->is_persistent_) {
190 event_set(evt.get(), fd, event_mask, OnLibeventNotification, controller); 136 NOTREACHED() << "persistent doesn't match";
191 137 return false;
192 // Tell libevent which message pump this socket will belong to when we add it. 138 }
193 if (event_base_set(event_base_, evt.get()) != 0) { 139
194 return false; 140 // Combine old/new event masks.
195 } 141 CFFileDescriptorDisableCallBacks(fdref, controller->callback_types_);
196 142 controller->callback_types_ |= callback_types;
197 // Add this socket to the list of monitored sockets. 143 CFFileDescriptorEnableCallBacks(fdref, controller->callback_types_);
198 if (event_add(evt.get(), NULL) != 0) { 144 }
199 return false;
200 }
201
202 // Transfer ownership of evt to controller.
203 controller->Init(evt.release());
204 145
205 controller->set_watcher(delegate); 146 controller->set_watcher(delegate);
206 controller->set_pump(this); 147 controller->set_pump(this);
207 148
208 return true; 149 return true;
209 } 150 }
210 151
211 void MessagePumpLibevent::AddIOObserver(IOObserver *obs) { 152 void MessagePumpIOSForIO::RemoveRunLoopSource(CFRunLoopSourceRef source) {
153 CFRunLoopRemoveSource(run_loop(), source, kCFRunLoopCommonModes);
154 }
155
156 void MessagePumpIOSForIO::AddIOObserver(IOObserver *obs) {
212 io_observers_.AddObserver(obs); 157 io_observers_.AddObserver(obs);
213 } 158 }
214 159
215 void MessagePumpLibevent::RemoveIOObserver(IOObserver *obs) { 160 void MessagePumpIOSForIO::RemoveIOObserver(IOObserver *obs) {
216 io_observers_.RemoveObserver(obs); 161 io_observers_.RemoveObserver(obs);
217 } 162 }
218 163
219 // Tell libevent to break out of inner loop. 164 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()); 165 FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
314 } 166 }
315 167
316 void MessagePumpLibevent::DidProcessIOEvent() { 168 void MessagePumpIOSForIO::DidProcessIOEvent() {
317 FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent()); 169 FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
318 } 170 }
319 171
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 172 // static
348 void MessagePumpLibevent::OnLibeventNotification(int fd, short flags, 173 void MessagePumpIOSForIO::HandleFdIOEvent(CFFileDescriptorRef fdref,
349 void* context) { 174 CFOptionFlags callback_types,
350 base::WeakPtr<FileDescriptorWatcher> controller = 175 void* context) {
351 static_cast<FileDescriptorWatcher*>(context)->weak_factory_.GetWeakPtr(); 176 // Ensure that |fdref| will remain live for the duration of this function
wtc 2012/11/29 20:30:34 Can you get the retain count of |fdref| on entry t
blundell 2012/11/30 11:19:52 The retain count is 2, so in fact the system is re
wtc 2012/11/30 15:14:20 In https://chromiumcodereview.appspot.com/11412101
352 DCHECK(controller.get()); 177 // call even if |controller| is deleted or |StopWatchingFileDescriptor()| is
353 178 // called, either of which will cause |fdref| to be released.
354 MessagePumpLibevent* pump = controller->pump(); 179 mac::ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref(
355 pump->processed_io_events_ = true; 180 fdref, base::scoped_policy::RETAIN);
356 181 int fd = CFFileDescriptorGetNativeDescriptor(scoped_fdref);
357 if (flags & EV_WRITE) { 182
183 FileDescriptorWatcher* controller =
184 static_cast<FileDescriptorWatcher*>(context);
185 DCHECK_EQ(scoped_fdref, controller->fdref_);
186
187 MessagePumpIOSForIO* pump = controller->pump();
188 if (callback_types & kCFFileDescriptorWriteCallBack)
358 controller->OnFileCanWriteWithoutBlocking(fd, pump); 189 controller->OnFileCanWriteWithoutBlocking(fd, pump);
359 } 190
360 // Check |controller| in case it's been deleted in 191 // Perform the read callback only if the file descriptor has not been
361 // controller->OnFileCanWriteWithoutBlocking(). 192 // invalidated in the write callback. As |FileDescriptorWatcher| invalidates
362 if (controller.get() && flags & EV_READ) { 193 // its file descriptor on destruction, the file descriptor being valid also
194 // guarantees that |controller| has not been deleted.
195 if (callback_types & kCFFileDescriptorReadCallBack &&
196 CFFileDescriptorIsValid(scoped_fdref)) {
197 DCHECK_EQ(scoped_fdref, controller->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 the file descriptor is still
367 // Called if a byte is received on the wakeup pipe. 202 // valid and the controller is persistent.
368 // static 203 if (CFFileDescriptorIsValid(scoped_fdref) && controller->is_persistent_) {
369 void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) { 204 DCHECK_EQ(scoped_fdref, controller->fdref_);
370 base::MessagePumpLibevent* that = 205 CFFileDescriptorEnableCallBacks(fdref, callback_types);
371 static_cast<base::MessagePumpLibevent*>(context); 206 }
372 DCHECK(that->wakeup_pipe_out_ == socket);
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 } 207 }
382 208
383 } // namespace base 209 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698