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
  457
  458

base / message_loop / message_pump_epoll_unittest.cc [blame]

// Copyright 2012 The Chromium Authors
// 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_epoll.h"

#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>

#include <memory>
#include <string_view>
#include <utility>

#include "base/containers/span.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/message_loop/message_pump_type.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/synchronization/waitable_event_watcher.h"
#include "base/task/current_thread.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/gtest_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

class MessagePumpEpollTest : public testing::Test {
 public:
  MessagePumpEpollTest()
      : task_environment_(std::make_unique<test::SingleThreadTaskEnvironment>(
            test::SingleThreadTaskEnvironment::MainThreadType::UI)),
        io_thread_("MessagePumpEpollTestIOThread") {}
  ~MessagePumpEpollTest() override = default;

  int receiver() const { return receiver_.get(); }
  int sender() const { return sender_.get(); }

  scoped_refptr<SingleThreadTaskRunner> io_runner() const {
    return io_thread_.task_runner();
  }

  void ClearNotifications() {
    int unused;
    while (read(receiver_.get(), &unused, sizeof(unused)) == sizeof(unused)) {
    }
  }

  void Notify() {
    const int data = 42;
    PCHECK(write(sender_.get(), &data, sizeof(data)) == sizeof(data));
  }

 protected:
  void SetUp() override {
    Thread::Options options(MessagePumpType::IO, 0);
    ASSERT_TRUE(io_thread_.StartWithOptions(std::move(options)));
    int fds[2];
    int rv = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
    CHECK_EQ(rv, 0);
    PCHECK(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0);
    receiver_ = base::ScopedFD(fds[0]);
    sender_ = base::ScopedFD(fds[1]);
  }

  void TearDown() override {
    // Some tests watch `receiver_` from the `io_thread_`. The `io_thread_` must
    // thus be joined to ensure those watches are complete before closing the
    // sockets.
    io_thread_.Stop();
  }

  void SimulateIOEvent(MessagePumpEpoll* pump,
                       MessagePumpEpoll::FdWatchController* controller) {
    pump->HandleEvent(0, /*can_read=*/true, /*can_write=*/true, controller);
  }

  static constexpr char null_byte_ = 0;
  std::unique_ptr<test::SingleThreadTaskEnvironment> task_environment_;

 private:
  Thread io_thread_;
  base::ScopedFD receiver_;
  base::ScopedFD sender_;
};

namespace {

TEST_F(MessagePumpEpollTest, QuitOutsideOfRun) {
  auto pump = std::make_unique<MessagePumpEpoll>();
  ASSERT_DCHECK_DEATH(pump->Quit());
}

class BaseWatcher : public MessagePumpEpoll::FdWatcher {
 public:
  BaseWatcher() = default;
  ~BaseWatcher() override = default;

  // base:MessagePumpEpoll::FdWatcher interface
  void OnFileCanReadWithoutBlocking(int /* fd */) override { NOTREACHED(); }
  void OnFileCanWriteWithoutBlocking(int /* fd */) override { NOTREACHED(); }
};

class DeleteWatcher : public BaseWatcher {
 public:
  explicit DeleteWatcher(
      std::unique_ptr<MessagePumpEpoll::FdWatchController> controller)
      : controller_(std::move(controller)) {}

  ~DeleteWatcher() override { DCHECK(!controller_); }

  MessagePumpEpoll::FdWatchController* controller() {
    return controller_.get();
  }

  void OnFileCanWriteWithoutBlocking(int /* fd */) override {
    DCHECK(controller_);
    controller_.reset();
  }

 private:
  std::unique_ptr<MessagePumpEpoll::FdWatchController> controller_;
};

TEST_F(MessagePumpEpollTest, DeleteWatcher) {
  DeleteWatcher delegate(
      std::make_unique<MessagePumpEpoll::FdWatchController>(FROM_HERE));
  auto pump = std::make_unique<MessagePumpEpoll>();
  pump->WatchFileDescriptor(receiver(), false,
                            MessagePumpEpoll::WATCH_READ_WRITE,
                            delegate.controller(), &delegate);
  SimulateIOEvent(pump.get(), delegate.controller());
}

class StopWatcher : public BaseWatcher {
 public:
  explicit StopWatcher(MessagePumpEpoll::FdWatchController* controller)
      : controller_(controller) {}

  ~StopWatcher() override = default;

  void OnFileCanWriteWithoutBlocking(int /* fd */) override {
    controller_->StopWatchingFileDescriptor();
  }

 private:
  raw_ptr<MessagePumpEpoll::FdWatchController> controller_ = nullptr;
};

TEST_F(MessagePumpEpollTest, StopWatcher) {
  auto pump = std::make_unique<MessagePumpEpoll>();
  MessagePumpEpoll::FdWatchController controller(FROM_HERE);
  StopWatcher delegate(&controller);
  pump->WatchFileDescriptor(receiver(), false,
                            MessagePumpEpoll::WATCH_READ_WRITE, &controller,
                            &delegate);
  SimulateIOEvent(pump.get(), &controller);
}

void QuitMessageLoopAndStart(OnceClosure quit_closure) {
  std::move(quit_closure).Run();

  RunLoop runloop(RunLoop::Type::kNestableTasksAllowed);
  SingleThreadTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
                                                        runloop.QuitClosure());
  runloop.Run();
}

class NestedPumpWatcher : public MessagePumpEpoll::FdWatcher {
 public:
  NestedPumpWatcher() = default;
  ~NestedPumpWatcher() override = default;

  void OnFileCanReadWithoutBlocking(int /* fd */) override {
    RunLoop runloop;
    SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, BindOnce(&QuitMessageLoopAndStart, runloop.QuitClosure()));
    runloop.Run();
  }

  void OnFileCanWriteWithoutBlocking(int /* fd */) override {}
};

TEST_F(MessagePumpEpollTest, NestedPumpWatcher) {
  NestedPumpWatcher delegate;
  auto pump = std::make_unique<MessagePumpEpoll>();
  MessagePumpEpoll::FdWatchController controller(FROM_HERE);
  pump->WatchFileDescriptor(receiver(), false, MessagePumpEpoll::WATCH_READ,
                            &controller, &delegate);
  SimulateIOEvent(pump.get(), &controller);
}

void FatalClosure() {
  FAIL() << "Reached fatal closure.";
}

class QuitWatcher : public BaseWatcher {
 public:
  QuitWatcher(base::OnceClosure quit_closure)
      : quit_closure_(std::move(quit_closure)) {}

  void OnFileCanReadWithoutBlocking(int /* fd */) override {
    // Post a fatal closure to the MessageLoop before we quit it.
    SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, BindOnce(&FatalClosure));

    if (quit_closure_) {
      std::move(quit_closure_).Run();
    }
  }

 private:
  base::OnceClosure quit_closure_;
};

void WriteFDWrapper(const int fd,
                    const char* buf,
                    int size,
                    WaitableEvent* event) {
  ASSERT_TRUE(WriteFileDescriptor(fd, std::string_view(buf, size)));
}

// Tests that MessagePumpEpoll quits immediately when it is quit from
// within a wakeup.
TEST_F(MessagePumpEpollTest, QuitWatcher) {
  // Delete the old TaskEnvironment so that we can manage our own one here.
  task_environment_.reset();

  auto executor_pump = std::make_unique<MessagePumpEpoll>();
  MessagePumpEpoll* pump = executor_pump.get();
  SingleThreadTaskExecutor executor(std::move(executor_pump));
  RunLoop run_loop;
  QuitWatcher delegate(run_loop.QuitClosure());
  MessagePumpEpoll::FdWatchController controller(FROM_HERE);
  WaitableEvent event(WaitableEvent::ResetPolicy::AUTOMATIC,
                      WaitableEvent::InitialState::NOT_SIGNALED);
  std::unique_ptr<WaitableEventWatcher> watcher(new WaitableEventWatcher);

  // Tell the pump to watch the pipe.
  pump->WatchFileDescriptor(receiver(), false, MessagePumpEpoll::WATCH_READ,
                            &controller, &delegate);

  // Make the IO thread wait for |event| before writing to sender().
  WaitableEventWatcher::EventCallback write_fd_task =
      BindOnce(&WriteFDWrapper, sender(), &null_byte_, 1);
  io_runner()->PostTask(
      FROM_HERE, BindOnce(IgnoreResult(&WaitableEventWatcher::StartWatching),
                          Unretained(watcher.get()), &event,
                          std::move(write_fd_task), io_runner()));

  // Queue |event| to signal on |sequence_manager|.
  SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, BindOnce(&WaitableEvent::Signal, Unretained(&event)));

  // Now run the MessageLoop.
  run_loop.Run();

  // StartWatching can move |watcher| to IO thread. Release on IO thread.
  io_runner()->PostTask(FROM_HERE, BindOnce(&WaitableEventWatcher::StopWatching,
                                            Owned(watcher.release())));
}

class InnerNestedWatcher : public MessagePumpEpoll::FdWatcher {
 public:
  InnerNestedWatcher(MessagePumpEpollTest& test,
                     MessagePumpEpoll::FdWatchController& outer_controller,
                     base::OnceClosure callback)
      : test_(test),
        outer_controller_(outer_controller),
        callback_(std::move(callback)) {
    base::CurrentIOThread::Get().WatchFileDescriptor(
        test_->receiver(), false, MessagePumpEpoll::WATCH_READ, &controller_,
        this);
  }
  ~InnerNestedWatcher() override = default;

  void OnFileCanReadWithoutBlocking(int) override {
    // Cancelling the outer watch from within this inner event handler must be
    // safe.
    outer_controller_->StopWatchingFileDescriptor();
    std::move(callback_).Run();
  }

  void OnFileCanWriteWithoutBlocking(int) override {}

 private:
  const raw_ref<MessagePumpEpollTest> test_;
  const raw_ref<MessagePumpEpoll::FdWatchController> outer_controller_;
  base::OnceClosure callback_;
  MessagePumpEpoll::FdWatchController controller_{FROM_HERE};
};

class OuterNestedWatcher : public MessagePumpEpoll::FdWatcher {
 public:
  OuterNestedWatcher(MessagePumpEpollTest& test, base::OnceClosure callback)
      : test_(test), callback_(std::move(callback)) {
    base::RunLoop loop;
    test_->io_runner()->PostTask(
        FROM_HERE, base::BindOnce(&OuterNestedWatcher::InitOnIOThread,
                                  base::Unretained(this), loop.QuitClosure()));
    loop.Run();
  }

  ~OuterNestedWatcher() override = default;

  void OnFileCanReadWithoutBlocking(int) override {
    // Ensure that another notification will wake any active FdWatcher.
    test_->ClearNotifications();

    base::RunLoop loop;
    std::unique_ptr<InnerNestedWatcher> inner_watcher =
        std::make_unique<InnerNestedWatcher>(test_.get(), *controller_,
                                             loop.QuitClosure());
    test_->Notify();
    loop.Run();

    // Ensure that `InnerNestedWatcher` is destroyed before
    // `OuterNestedWatcher`.
    inner_watcher.reset();
    controller_.reset();
    std::move(callback_).Run();
  }

  void OnFileCanWriteWithoutBlocking(int) override {}

 private:
  void InitOnIOThread(base::OnceClosure ready_callback) {
    controller_ =
        std::make_unique<MessagePumpEpoll::FdWatchController>(FROM_HERE);
    base::CurrentIOThread::Get().WatchFileDescriptor(
        test_->receiver(), false, MessagePumpEpoll::WATCH_READ,
        controller_.get(), this);
    std::move(ready_callback).Run();
  }

  const raw_ref<MessagePumpEpollTest> test_;
  base::OnceClosure callback_;
  std::unique_ptr<MessagePumpEpoll::FdWatchController> controller_;
};

TEST_F(MessagePumpEpollTest, NestedNotification) {
  // Regression test for https://crbug.com/1469529. Verifies that it's safe for
  // a nested RunLoop to stop watching a file descriptor while the outer RunLoop
  // is handling an event for the same descriptor.
  base::RunLoop loop;
  OuterNestedWatcher watcher(*this, loop.QuitClosure());
  Notify();
  loop.Run();
}

class RepeatWatcher : public BaseWatcher {
 public:
  RepeatWatcher(MessagePumpEpoll* pump,
                int fd,
                MessagePumpForIO::Mode mode,
                bool persistent,
                int repeat)
      : pump_(pump),
        fd_(fd),
        mode_(mode),
        persistent_(persistent),
        repeat_(repeat),
        fd_watch_controller_(FROM_HERE) {}

  ~RepeatWatcher() override { EXPECT_EQ(repeat_, 0); }

  void StartWatching() {
    const bool watch_success = pump_->WatchFileDescriptor(
        fd_, persistent_, mode_, &fd_watch_controller_, this);
    ASSERT_TRUE(watch_success);
  }

  void OnFileCanReadWithoutBlocking(int fd) override {
    EXPECT_EQ(fd_, fd);
    EXPECT_GT(repeat_, 0);

    --repeat_;

    if (persistent_) {
      if (repeat_ == 0) {
        // Need to stop watching the fd explicitly if it's configured as
        // persistent.
        fd_watch_controller_.StopWatchingFileDescriptor();
      }
    } else {
      if (repeat_ > 0) {
        // Need to restart watching the fd explicitly if it's not configured as
        // persistent.
        StartWatching();
      }
    }
  }

 private:
  raw_ptr<MessagePumpEpoll> pump_;
  int fd_;
  MessagePumpForIO::Mode mode_;
  bool persistent_;
  int repeat_;
  MessagePumpEpoll::FdWatchController fd_watch_controller_;
};

void RepeatEventTest(bool persistent,
                     int repeat,
                     std::unique_ptr<MessagePumpEpoll> executor_pump,
                     int sender,
                     int receiver) {
  MessagePumpEpoll* pump = executor_pump.get();
  SingleThreadTaskExecutor executor(std::move(executor_pump));
  RunLoop run_loop;
  RepeatWatcher delegate(pump, receiver, MessagePumpEpoll::WATCH_READ,
                         persistent, repeat);

  delegate.StartWatching();

  const char null = 0;
  ASSERT_TRUE(WriteFileDescriptor(sender, std::string_view(&null, 1)));

  // The RunLoop must go to the idle state after the callback is called the
  // number of times specified by `repeat`.
  run_loop.RunUntilIdle();
}

// Tests that MessagePumpEpoll calls FdWatcher's callback repeatedly when
// it's configured as persistent.
TEST_F(MessagePumpEpollTest, RepeatPersistentEvent) {
  // Delete the old TaskEnvironment so that we can manage our own one here.
  task_environment_.reset();

  RepeatEventTest(/* persistent= */ true, /* repeat= */ 3,
                  std::make_unique<MessagePumpEpoll>(), sender(), receiver());
}

// Tests that MessagePumpEpoll calls FdWatcher's callback repeatedly when it's
// not configured as persistent but reconfigured in the callback.
TEST_F(MessagePumpEpollTest, RepeatOneShotEvent) {
  // Delete the old TaskEnvironment so that we can manage our own one here.
  task_environment_.reset();

  RepeatEventTest(/* persistent= */ false, /* repeat= */ 3,
                  std::make_unique<MessagePumpEpoll>(), sender(), receiver());
}

}  // namespace
}  // namespace base