forked from Pissandshittium/pissandshittium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage_pump_kqueue.cc
456 lines (381 loc) · 13.7 KB
/
message_pump_kqueue.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop/message_pump_kqueue.h"
#include <sys/errno.h>
#include "base/auto_reset.h"
#include "base/logging.h"
#include "base/mac/mac_util.h"
#include "base/mac/mach_logging.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/posix/eintr_wrapper.h"
namespace base {
namespace {
// Prior to macOS 10.12, a kqueue could not watch individual Mach ports, only
// port sets. MessagePumpKqueue will directly use Mach ports in the kqueue if
// it is possible.
bool KqueueNeedsPortSet() {
static bool kqueue_needs_port_set = mac::IsAtMostOS10_11();
return kqueue_needs_port_set;
}
int ChangeOneEvent(const ScopedFD& kqueue, kevent64_s* event) {
return HANDLE_EINTR(kevent64(kqueue.get(), event, 1, nullptr, 0, 0, nullptr));
}
} // namespace
MessagePumpKqueue::FdWatchController::FdWatchController(
const Location& from_here)
: FdWatchControllerInterface(from_here) {}
MessagePumpKqueue::FdWatchController::~FdWatchController() {
StopWatchingFileDescriptor();
}
bool MessagePumpKqueue::FdWatchController::StopWatchingFileDescriptor() {
if (!pump_)
return true;
return pump_->StopWatchingFileDescriptor(this);
}
void MessagePumpKqueue::FdWatchController::Init(WeakPtr<MessagePumpKqueue> pump,
int fd,
int mode,
FdWatcher* watcher) {
DCHECK_NE(fd, -1);
DCHECK(!watcher_);
DCHECK(watcher);
DCHECK(pump);
fd_ = fd;
mode_ = mode;
watcher_ = watcher;
pump_ = pump;
}
void MessagePumpKqueue::FdWatchController::Reset() {
fd_ = -1;
mode_ = 0;
watcher_ = nullptr;
pump_ = nullptr;
}
MessagePumpKqueue::MachPortWatchController::MachPortWatchController(
const Location& from_here)
: from_here_(from_here) {}
MessagePumpKqueue::MachPortWatchController::~MachPortWatchController() {
StopWatchingMachPort();
}
bool MessagePumpKqueue::MachPortWatchController::StopWatchingMachPort() {
if (!pump_)
return true;
return pump_->StopWatchingMachPort(this);
}
void MessagePumpKqueue::MachPortWatchController::Init(
WeakPtr<MessagePumpKqueue> pump,
mach_port_t port,
MachPortWatcher* watcher) {
DCHECK(!watcher_);
DCHECK(watcher);
DCHECK(pump);
port_ = port;
watcher_ = watcher;
pump_ = pump;
}
void MessagePumpKqueue::MachPortWatchController::Reset() {
port_ = MACH_PORT_NULL;
watcher_ = nullptr;
pump_ = nullptr;
}
MessagePumpKqueue::MessagePumpKqueue()
: kqueue_(kqueue()), weak_factory_(this) {
PCHECK(kqueue_.is_valid()) << "kqueue";
// Create a Mach port that will be used to wake up the pump by sending
// a message in response to ScheduleWork(). This is significantly faster than
// using an EVFILT_USER event, especially when triggered across threads.
kern_return_t kr = mach_port_allocate(
mach_task_self(), MACH_PORT_RIGHT_RECEIVE,
base::mac::ScopedMachReceiveRight::Receiver(wakeup_).get());
MACH_CHECK(kr == KERN_SUCCESS, kr) << "mach_port_allocate";
kevent64_s event{};
if (KqueueNeedsPortSet()) {
kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_PORT_SET,
mac::ScopedMachPortSet::Receiver(port_set_).get());
MACH_CHECK(kr == KERN_SUCCESS, kr) << "mach_port_allocate PORT_SET";
kr = mach_port_insert_member(mach_task_self(), wakeup_.get(),
port_set_.get());
MACH_CHECK(kr == KERN_SUCCESS, kr) << "mach_port_insert_member";
event.ident = port_set_.get();
event.filter = EVFILT_MACHPORT;
event.flags = EV_ADD;
} else {
// When not using a port set, the wakeup port event can be specified to
// directly receive the Mach message as part of the kevent64() syscall.
// This is not done when using a port set, since that would potentially
// receive client MachPortWatchers' messages.
event.ident = wakeup_.get();
event.filter = EVFILT_MACHPORT;
event.flags = EV_ADD;
event.fflags = MACH_RCV_MSG;
event.ext[0] = reinterpret_cast<uint64_t>(&wakeup_buffer_);
event.ext[1] = sizeof(wakeup_buffer_);
}
int rv = ChangeOneEvent(kqueue_, &event);
PCHECK(rv == 0) << "kevent64";
}
MessagePumpKqueue::~MessagePumpKqueue() {}
void MessagePumpKqueue::Run(Delegate* delegate) {
AutoReset<bool> reset_keep_running(&keep_running_, true);
while (keep_running_) {
mac::ScopedNSAutoreleasePool pool;
bool do_more_work = DoInternalWork(nullptr);
if (!keep_running_)
break;
Delegate::NextWorkInfo next_work_info = delegate->DoWork();
do_more_work |= next_work_info.is_immediate();
if (!keep_running_)
break;
if (do_more_work)
continue;
do_more_work |= delegate->DoIdleWork();
if (!keep_running_)
break;
if (do_more_work)
continue;
DoInternalWork(&next_work_info);
}
}
void MessagePumpKqueue::Quit() {
keep_running_ = false;
ScheduleWork();
}
void MessagePumpKqueue::ScheduleWork() {
mach_msg_empty_send_t message{};
message.header.msgh_size = sizeof(message);
message.header.msgh_bits =
MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MAKE_SEND_ONCE);
message.header.msgh_remote_port = wakeup_.get();
kern_return_t kr = mach_msg_send(&message.header);
if (kr != KERN_SUCCESS) {
// If ScheduleWork() is being called by other threads faster than the pump
// can dispatch work, the kernel message queue for the wakeup port can fill
// up (this happens under base_perftests, for example). The kernel does
// return a SEND_ONCE right in the case of failure, which must be destroyed
// to avoid leaking.
MACH_DLOG_IF(ERROR, (kr & ~MACH_MSG_IPC_SPACE) != MACH_SEND_NO_BUFFER, kr)
<< "mach_msg_send";
mach_msg_destroy(&message.header);
}
}
void MessagePumpKqueue::ScheduleDelayedWork(
const TimeTicks& delayed_work_time) {
// Nothing to do. This MessagePump uses DoWork().
}
bool MessagePumpKqueue::WatchMachReceivePort(
mach_port_t port,
MachPortWatchController* controller,
MachPortWatcher* delegate) {
DCHECK(port != MACH_PORT_NULL);
DCHECK(controller);
DCHECK(delegate);
if (controller->port() != MACH_PORT_NULL) {
DLOG(ERROR)
<< "Cannot use the same MachPortWatchController while it is active";
return false;
}
if (KqueueNeedsPortSet()) {
kern_return_t kr =
mach_port_insert_member(mach_task_self(), port, port_set_.get());
if (kr != KERN_SUCCESS) {
MACH_LOG(ERROR, kr) << "mach_port_insert_member";
return false;
}
} else {
kevent64_s event{};
event.ident = port;
event.filter = EVFILT_MACHPORT;
event.flags = EV_ADD;
int rv = ChangeOneEvent(kqueue_, &event);
if (rv < 0) {
DPLOG(ERROR) << "kevent64";
return false;
}
++event_count_;
}
controller->Init(weak_factory_.GetWeakPtr(), port, delegate);
port_controllers_.AddWithID(controller, port);
return true;
}
bool MessagePumpKqueue::WatchFileDescriptor(int fd,
bool persistent,
int mode,
FdWatchController* controller,
FdWatcher* delegate) {
DCHECK_GE(fd, 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK_NE(mode & Mode::WATCH_READ_WRITE, 0);
if (controller->fd() != -1 && controller->fd() != fd) {
DLOG(ERROR) << "Cannot use the same FdWatchController on two different FDs";
return false;
}
StopWatchingFileDescriptor(controller);
std::vector<kevent64_s> events;
kevent64_s base_event{};
base_event.ident = fd;
base_event.flags = EV_ADD | (!persistent ? EV_ONESHOT : 0);
if (mode & Mode::WATCH_READ) {
base_event.filter = EVFILT_READ;
base_event.udata = fd_controllers_.Add(controller);
events.push_back(base_event);
}
if (mode & Mode::WATCH_WRITE) {
base_event.filter = EVFILT_WRITE;
base_event.udata = fd_controllers_.Add(controller);
events.push_back(base_event);
}
int rv = HANDLE_EINTR(kevent64(kqueue_.get(), events.data(), events.size(),
nullptr, 0, 0, nullptr));
if (rv < 0) {
DPLOG(ERROR) << "WatchFileDescriptor kevent64";
return false;
}
event_count_ += events.size();
controller->Init(weak_factory_.GetWeakPtr(), fd, mode, delegate);
return true;
}
bool MessagePumpKqueue::StopWatchingMachPort(
MachPortWatchController* controller) {
mach_port_t port = controller->port();
controller->Reset();
port_controllers_.Remove(port);
if (KqueueNeedsPortSet()) {
kern_return_t kr =
mach_port_extract_member(mach_task_self(), port, port_set_.get());
if (kr != KERN_SUCCESS) {
MACH_LOG(ERROR, kr) << "mach_port_extract_member";
return false;
}
} else {
kevent64_s event{};
event.ident = port;
event.filter = EVFILT_MACHPORT;
event.flags = EV_DELETE;
--event_count_;
int rv = ChangeOneEvent(kqueue_, &event);
if (rv < 0) {
DPLOG(ERROR) << "kevent64";
return false;
}
}
return true;
}
bool MessagePumpKqueue::StopWatchingFileDescriptor(
FdWatchController* controller) {
int fd = controller->fd();
int mode = controller->mode();
controller->Reset();
if (fd == -1)
return true;
std::vector<kevent64_s> events;
kevent64_s base_event{};
base_event.ident = fd;
base_event.flags = EV_DELETE;
if (mode & Mode::WATCH_READ) {
base_event.filter = EVFILT_READ;
events.push_back(base_event);
}
if (mode & Mode::WATCH_WRITE) {
base_event.filter = EVFILT_WRITE;
events.push_back(base_event);
}
int rv = HANDLE_EINTR(kevent64(kqueue_.get(), events.data(), events.size(),
nullptr, 0, 0, nullptr));
DPLOG_IF(ERROR, rv < 0) << "StopWatchingFileDescriptor kevent64";
// The keys for the IDMap aren't recorded anywhere (they're attached to the
// kevent object in the kernel), so locate the entries by controller pointer.
for (auto it = IDMap<FdWatchController*>::iterator(&fd_controllers_);
!it.IsAtEnd(); it.Advance()) {
if (it.GetCurrentValue() == controller) {
fd_controllers_.Remove(it.GetCurrentKey());
}
}
event_count_ -= events.size();
return rv >= 0;
}
bool MessagePumpKqueue::DoInternalWork(Delegate::NextWorkInfo* next_work_info) {
if (events_.size() < event_count_) {
events_.resize(event_count_);
}
bool poll = next_work_info == nullptr;
int flags = poll ? KEVENT_FLAG_IMMEDIATE : 0;
bool indefinite =
next_work_info != nullptr && next_work_info->delayed_run_time.is_max();
int rv = 0;
do {
timespec timeout{};
if (!indefinite && !poll) {
if (rv != 0) {
// The wait was interrupted and made |next_work_info|'s view of
// TimeTicks::Now() stale. Refresh it before doing another wait.
next_work_info->recent_now = TimeTicks::Now();
}
timeout = next_work_info->remaining_delay().ToTimeSpec();
}
// This does not use HANDLE_EINTR, since retrying the syscall requires
// adjusting the timeout to account for time already waited.
rv = kevent64(kqueue_.get(), nullptr, 0, events_.data(), events_.size(),
flags, indefinite ? nullptr : &timeout);
} while (rv < 0 && errno == EINTR);
PCHECK(rv >= 0) << "kevent64";
return ProcessEvents(rv);
}
bool MessagePumpKqueue::ProcessEvents(int count) {
bool did_work = false;
for (int i = 0; i < count; ++i) {
auto* event = &events_[i];
if (event->filter == EVFILT_READ || event->filter == EVFILT_WRITE) {
did_work = true;
FdWatchController* controller = fd_controllers_.Lookup(event->udata);
if (!controller) {
// The controller was removed by some other work callout before
// this event could be processed.
continue;
}
FdWatcher* delegate = controller->watcher();
if (event->flags & EV_ONESHOT) {
// If this was a one-shot event, the Controller needs to stop tracking
// the descriptor, so it is not double-removed when it is told to stop
// watching.
controller->Reset();
fd_controllers_.Remove(event->udata);
--event_count_;
}
if (event->filter == EVFILT_READ) {
delegate->OnFileCanReadWithoutBlocking(event->ident);
} else if (event->filter == EVFILT_WRITE) {
delegate->OnFileCanWriteWithoutBlocking(event->ident);
}
} else if (event->filter == EVFILT_MACHPORT) {
mach_port_t port = KqueueNeedsPortSet() ? event->data : event->ident;
if (port == wakeup_.get()) {
// The wakeup event has been received, do not treat this as "doing
// work", this just wakes up the pump.
if (KqueueNeedsPortSet()) {
// When using the kqueue directly, the message can be received
// straight into a buffer that was created when adding the event.
// But when using a port set, the message must be drained manually.
wakeup_buffer_.header.msgh_local_port = port;
wakeup_buffer_.header.msgh_size = sizeof(wakeup_buffer_);
kern_return_t kr = mach_msg_receive(&wakeup_buffer_.header);
MACH_LOG_IF(ERROR, kr != KERN_SUCCESS, kr)
<< "mach_msg_receive wakeup";
}
continue;
}
did_work = true;
MachPortWatchController* controller = port_controllers_.Lookup(port);
// The controller could have been removed by some other work callout
// before this event could be processed.
if (controller) {
controller->watcher()->OnMachMessageReceived(port);
}
} else {
NOTREACHED() << "Unexpected event for filter " << event->filter;
}
}
return did_work;
}
} // namespace base