blob: 7105a681c2bf7fb8a1d8b047c1002cc496e53118 [file] [log] [blame]
David Anderson1de73842021-05-13 20:18:14 -07001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "epoll.h"
18
19#include <sys/unistd.h>
20
21#include <unordered_set>
22
23#include <android-base/file.h>
Bart Van Assche20954a82022-10-17 11:07:05 -070024#include <android-base/logging.h>
David Anderson1de73842021-05-13 20:18:14 -070025#include <gtest/gtest.h>
26
27namespace android {
28namespace init {
29
30std::unordered_set<void*> sValidObjects;
31
32class CatchDtor final {
33 public:
Bart Van Assche20954a82022-10-17 11:07:05 -070034 CatchDtor() { CHECK(sValidObjects.emplace(this).second); }
35 CatchDtor(const CatchDtor&) { CHECK(sValidObjects.emplace(this).second); }
36 CatchDtor(const CatchDtor&&) { CHECK(sValidObjects.emplace(this).second); }
37 ~CatchDtor() { CHECK_EQ(sValidObjects.erase(this), size_t{1}); }
David Anderson1de73842021-05-13 20:18:14 -070038};
39
40TEST(epoll, UnregisterHandler) {
41 Epoll epoll;
42 ASSERT_RESULT_OK(epoll.Open());
43
44 int fds[2];
45 ASSERT_EQ(pipe(fds), 0);
46
47 CatchDtor catch_dtor;
Bart Van Assche20954a82022-10-17 11:07:05 -070048 bool handler_invoked = false;
David Anderson1de73842021-05-13 20:18:14 -070049 auto handler = [&, catch_dtor]() -> void {
50 auto result = epoll.UnregisterHandler(fds[0]);
51 ASSERT_EQ(result.ok(), !handler_invoked);
52 handler_invoked = true;
Bart Van Assche20954a82022-10-17 11:07:05 -070053 // The assert statement below verifies that the UnregisterHandler() call
54 // above did not destroy the current std::function<> instance.
David Anderson1de73842021-05-13 20:18:14 -070055 ASSERT_NE(sValidObjects.find((void*)&catch_dtor), sValidObjects.end());
56 };
57
58 epoll.RegisterHandler(fds[0], std::move(handler));
59
60 uint8_t byte = 0xee;
61 ASSERT_TRUE(android::base::WriteFully(fds[1], &byte, sizeof(byte)));
62
Bart Van Asschebc5c4a42022-10-14 09:13:19 -070063 auto epoll_result = epoll.Wait({});
64 ASSERT_RESULT_OK(epoll_result);
65 ASSERT_EQ(*epoll_result, 1);
David Anderson1de73842021-05-13 20:18:14 -070066 ASSERT_TRUE(handler_invoked);
67}
68
69} // namespace init
70} // namespace android