1 /*
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>
24 #include <android-base/logging.h>
25 #include <gtest/gtest.h>
26
27 namespace android {
28 namespace init {
29
30 std::unordered_set<void*> sValidObjects;
31
32 class CatchDtor final {
33 public:
CatchDtor()34 CatchDtor() { CHECK(sValidObjects.emplace(this).second); }
CatchDtor(const CatchDtor &)35 CatchDtor(const CatchDtor&) { CHECK(sValidObjects.emplace(this).second); }
CatchDtor(const CatchDtor &&)36 CatchDtor(const CatchDtor&&) { CHECK(sValidObjects.emplace(this).second); }
~CatchDtor()37 ~CatchDtor() { CHECK_EQ(sValidObjects.erase(this), size_t{1}); }
38 };
39
TEST(epoll,UnregisterHandler)40 TEST(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;
48 bool handler_invoked = false;
49 auto handler = [&, catch_dtor]() -> void {
50 auto result = epoll.UnregisterHandler(fds[0]);
51 ASSERT_EQ(result.ok(), !handler_invoked);
52 handler_invoked = true;
53 // The assert statement below verifies that the UnregisterHandler() call
54 // above did not destroy the current std::function<> instance.
55 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
63 auto epoll_result = epoll.Wait({});
64 ASSERT_RESULT_OK(epoll_result);
65 ASSERT_EQ(*epoll_result, 1);
66 ASSERT_TRUE(handler_invoked);
67 }
68
69 } // namespace init
70 } // namespace android
71