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
base / message_loop / io_watcher_fd_unittest.cc [blame]
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <array>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <string_view>
#include <utility>
#include "base/containers/span.h"
#include "base/files/scoped_file.h"
#include "base/message_loop/io_watcher.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/java_handler_thread.h"
#endif
namespace base {
namespace {
// TODO(crbug.com/379190028): Introduce new types here as file descriptor
// support is added.
enum class FdIOCapableMessagePumpType {
kDefaultIO,
#if BUILDFLAG(IS_ANDROID)
kAndroid,
#endif
};
std::pair<ScopedFD, ScopedFD> CreateSocketPair() {
int fds[2];
CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
PCHECK(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0);
PCHECK(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0);
return {ScopedFD(fds[0]), ScopedFD(fds[1])};
}
void WriteToSocket(int fd, std::string_view msg) {
const ssize_t result = HANDLE_EINTR(write(fd, msg.data(), msg.size()));
CHECK_EQ(result, static_cast<ssize_t>(msg.size()));
}
void FillSocket(int fd) {
const std::array<char, 1024> kJunk = {};
ssize_t result;
do {
result = HANDLE_EINTR(write(fd, kJunk.data(), kJunk.size()));
} while (result > 0);
}
std::string ReadFromSocket(int fd) {
char buffer[256];
const ssize_t result = HANDLE_EINTR(read(fd, buffer, std::size(buffer)));
if (result <= 0) {
return {};
}
const auto contents = span(buffer).first(static_cast<size_t>(result));
return std::string(contents.begin(), contents.end());
}
template <typename Fn>
void RunOnTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner, Fn fn) {
RunLoop loop;
task_runner->PostTask(FROM_HERE,
BindLambdaForTesting([&fn, quit = loop.QuitClosure()] {
fn();
quit.Run();
}));
loop.Run();
}
class TestFdWatcher;
class IOWatcherFdTest
: public testing::Test,
public testing::WithParamInterface<FdIOCapableMessagePumpType> {
public:
void SetUp() override {
switch (GetParam()) {
case FdIOCapableMessagePumpType::kDefaultIO:
thread_.emplace("IO thread");
thread_->StartWithOptions(Thread::Options(MessagePumpType::IO, 0));
io_task_runner_ = thread_->task_runner();
break;
#if BUILDFLAG(IS_ANDROID)
case FdIOCapableMessagePumpType::kAndroid:
java_thread_.emplace("Java thread");
java_thread_->Start();
io_task_runner_ = java_thread_->task_runner();
break;
#endif
}
}
void TearDown() override {
thread_.reset();
#if BUILDFLAG(IS_ANDROID)
if (java_thread_) {
java_thread_->Stop();
java_thread_.reset();
}
#endif
}
std::unique_ptr<TestFdWatcher> CreateWatcher();
// This is useful for ensuring that read and write can be observed at the
// same time on a socket's peer, since the operations which signal both read
// and write availability will happen on the same thread that dispatches
// signals.
void MakePeerReadableAndWritableFromIOThread(int fd) {
RunOnTaskRunner(io_task_runner_, [fd] {
WriteToSocket(fd, "x");
while (!ReadFromSocket(fd).empty()) {
}
});
}
private:
test::TaskEnvironment task_environment_;
std::optional<Thread> thread_;
#if BUILDFLAG(IS_ANDROID)
std::optional<android::JavaHandlerThread> java_thread_;
#endif
scoped_refptr<SequencedTaskRunner> io_task_runner_;
};
class TestFdWatcher : public IOWatcher::FdWatcher {
public:
explicit TestFdWatcher(scoped_refptr<SequencedTaskRunner> io_task_runner)
: io_task_runner_(std::move(io_task_runner)) {}
~TestFdWatcher() override { Stop(); }
int num_events() {
AutoLock lock(lock_);
return num_events_;
}
void reset_num_events() {
AutoLock lock(lock_);
num_events_ = 0;
}
void set_cancel_on_read() { cancel_on_read_ = true; }
void set_cancel_on_write() { cancel_on_write_ = true; }
void Watch(const ScopedFD& fd,
IOWatcher::FdWatchDuration duration,
IOWatcher::FdWatchMode mode) {
RunOnTaskRunner(io_task_runner_, [this, fd = fd.get(), duration, mode] {
watch_ = IOWatcher::Get()->WatchFileDescriptor(fd, duration, mode, *this);
});
}
void Stop() {
RunOnTaskRunner(io_task_runner_, [this] { watch_.reset(); });
}
std::string WaitForNextMessage() {
AutoLock lock(lock_);
while (messages_.empty()) {
messages_available_.Wait();
}
std::string next_message = messages_.front();
messages_.pop();
return next_message;
}
void WaitForDisconnect() { disconnect_event_.Wait(); }
void WaitForWritable() { writable_event_.Wait(); }
void WaitForReadableOrWritable() { readable_or_writable_event_.Wait(); }
// IOWatcher::FdWatcher:
void OnFdReadable(int fd) override {
bool did_read_something = false;
{
AutoLock lock(lock_);
++num_events_;
readable_or_writable_event_.Signal();
for (;;) {
std::string message = ReadFromSocket(fd);
if (message.empty()) {
break;
}
did_read_something = true;
messages_.push(std::move(message));
messages_available_.Signal();
}
}
if (!did_read_something) {
disconnect_event_.Signal();
}
if (cancel_on_read_) {
watch_.reset();
}
}
void OnFdWritable(int fd) override {
{
AutoLock lock(lock_);
++num_events_;
writable_event_.Signal();
readable_or_writable_event_.Signal();
}
if (cancel_on_write_) {
watch_.reset();
}
}
private:
const scoped_refptr<SequencedTaskRunner> io_task_runner_;
// The active watch, started by Watch(). Only one at a time and must be
// created and destroyed on `io_task_runner_`.
std::unique_ptr<IOWatcher::FdWatch> watch_;
// Signaled when `watch_` observes writability.
WaitableEvent writable_event_{WaitableEvent::ResetPolicy::AUTOMATIC};
// Signaled when `watch_` observes either readability or writability.
WaitableEvent readable_or_writable_event_{
WaitableEvent::ResetPolicy::AUTOMATIC};
// Signaled when `watch_` observes disconnection - i.e., readability when
// nothing is available to read.
WaitableEvent disconnect_event_;
// If set by a test, observing readability will immediately destroy `watch_`.
bool cancel_on_read_ = false;
// If set by a test, observing writability will immediately destroy `watch_`.
bool cancel_on_write_ = false;
Lock lock_;
// Message queue accumulated as readability is signaled.
ConditionVariable messages_available_{&lock_};
std::queue<std::string> messages_ GUARDED_BY(lock_);
// Counts the number of observed events of any kind.
int num_events_ GUARDED_BY(lock_) = 0;
};
std::unique_ptr<TestFdWatcher> IOWatcherFdTest::CreateWatcher() {
return std::make_unique<TestFdWatcher>(io_task_runner_);
}
TEST_P(IOWatcherFdTest, ReadOnce) {
// Test that a one-shot read watch sees a single readable event and no more.
auto [a, b] = CreateSocketPair();
auto watcher1 = CreateWatcher();
watcher1->Watch(b, IOWatcher::FdWatchDuration::kOneShot,
IOWatcher::FdWatchMode::kRead);
WriteToSocket(a.get(), "ping");
EXPECT_EQ("ping", watcher1->WaitForNextMessage());
auto watcher2 = CreateWatcher();
watcher2->Watch(b, IOWatcher::FdWatchDuration::kOneShot,
IOWatcher::FdWatchMode::kRead);
WriteToSocket(a.get(), "pong");
EXPECT_EQ("pong", watcher2->WaitForNextMessage());
EXPECT_EQ(1, watcher1->num_events());
}
TEST_P(IOWatcherFdTest, ReadPersistent) {
// Tests that a persistent read watch can see multiple events.
auto [a, b] = CreateSocketPair();
auto watcher = CreateWatcher();
watcher->Watch(b, IOWatcher::FdWatchDuration::kPersistent,
IOWatcher::FdWatchMode::kRead);
WriteToSocket(a.get(), "ping");
EXPECT_EQ("ping", watcher->WaitForNextMessage());
WriteToSocket(a.get(), "pong");
EXPECT_EQ("pong", watcher->WaitForNextMessage());
EXPECT_EQ(2, watcher->num_events());
a.reset();
watcher->WaitForDisconnect();
}
TEST_P(IOWatcherFdTest, StopWatch) {
// Tests that a stopped watch doesn't continue dispatching events.
auto [a, b] = CreateSocketPair();
auto watcher = CreateWatcher();
watcher->Watch(b, IOWatcher::FdWatchDuration::kPersistent,
IOWatcher::FdWatchMode::kRead);
WriteToSocket(a.get(), "ping");
EXPECT_EQ("ping", watcher->WaitForNextMessage());
WriteToSocket(a.get(), "pong");
EXPECT_EQ("pong", watcher->WaitForNextMessage());
watcher->Stop();
watcher->reset_num_events();
WriteToSocket(a.get(), "abc");
WriteToSocket(a.get(), "123");
EXPECT_EQ(0, watcher->num_events());
}
TEST_P(IOWatcherFdTest, Write) {
// Tests basic one-shot write watching.
auto [a, b] = CreateSocketPair();
FillSocket(b.get());
auto watcher = CreateWatcher();
watcher->Watch(b, IOWatcher::FdWatchDuration::kOneShot,
IOWatcher::FdWatchMode::kWrite);
MakePeerReadableAndWritableFromIOThread(a.get());
watcher->WaitForWritable();
WriteToSocket(b.get(), "x");
}
TEST_P(IOWatcherFdTest, ReadWriteUnifiedOneShot) {
// Tests that a one-shot read-write watch will observe at most one event
// even if the watched object becomes both readable and writable.
auto [a, b] = CreateSocketPair();
FillSocket(b.get());
auto watcher = CreateWatcher();
watcher->Watch(b, IOWatcher::FdWatchDuration::kOneShot,
IOWatcher::FdWatchMode::kReadWrite);
MakePeerReadableAndWritableFromIOThread(a.get());
watcher->WaitForReadableOrWritable();
EXPECT_EQ(1, watcher->num_events());
}
TEST_P(IOWatcherFdTest, ReadWriteSeparateOneShot) {
// Tests that separate one-shot read and write watches can observe the same
// descriptor concurrently.
auto [a, b] = CreateSocketPair();
FillSocket(b.get());
auto read_watcher = CreateWatcher();
auto write_watcher = CreateWatcher();
read_watcher->Watch(b, IOWatcher::FdWatchDuration::kOneShot,
IOWatcher::FdWatchMode::kRead);
write_watcher->Watch(b, IOWatcher::FdWatchDuration::kOneShot,
IOWatcher::FdWatchMode::kWrite);
MakePeerReadableAndWritableFromIOThread(a.get());
EXPECT_EQ("x", read_watcher->WaitForNextMessage());
write_watcher->WaitForWritable();
}
TEST_P(IOWatcherFdTest, CancelDuringRead) {
// Tests that the watcher behaves safely when watching both read and write
// with a persistent watch which is cancelled while handling a read.
auto [a, b] = CreateSocketPair();
FillSocket(b.get());
auto watcher = CreateWatcher();
watcher->set_cancel_on_read();
watcher->Watch(b, IOWatcher::FdWatchDuration::kPersistent,
IOWatcher::FdWatchMode::kReadWrite);
MakePeerReadableAndWritableFromIOThread(a.get());
EXPECT_EQ("x", watcher->WaitForNextMessage());
EXPECT_LE(watcher->num_events(), 2);
}
TEST_P(IOWatcherFdTest, CancelDuringWrite) {
// Tests that the watcher behaves safely when watching both read and write
// with a persistent watch which is cancelled while handling a write.
auto [a, b] = CreateSocketPair();
FillSocket(b.get());
auto watcher = CreateWatcher();
watcher->set_cancel_on_write();
watcher->Watch(b, IOWatcher::FdWatchDuration::kPersistent,
IOWatcher::FdWatchMode::kReadWrite);
MakePeerReadableAndWritableFromIOThread(a.get());
EXPECT_LE(watcher->num_events(), 2);
}
INSTANTIATE_TEST_SUITE_P(,
IOWatcherFdTest,
testing::Values(
#if BUILDFLAG(IS_ANDROID)
FdIOCapableMessagePumpType::kAndroid,
#endif
FdIOCapableMessagePumpType::kDefaultIO));
} // namespace
} // namespace base