| David Anderson | 1de7384 | 2021-05-13 20:18:14 -0700 | [diff] [blame] | 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 <gtest/gtest.h> | 
|  | 25 |  | 
|  | 26 | namespace android { | 
|  | 27 | namespace init { | 
|  | 28 |  | 
|  | 29 | std::unordered_set<void*> sValidObjects; | 
|  | 30 |  | 
|  | 31 | class CatchDtor final { | 
|  | 32 | public: | 
|  | 33 | CatchDtor() { sValidObjects.emplace(this); } | 
|  | 34 | CatchDtor(const CatchDtor&) { sValidObjects.emplace(this); } | 
|  | 35 | ~CatchDtor() { | 
|  | 36 | auto iter = sValidObjects.find(this); | 
|  | 37 | if (iter != sValidObjects.end()) { | 
|  | 38 | sValidObjects.erase(iter); | 
|  | 39 | } | 
|  | 40 | } | 
|  | 41 | }; | 
|  | 42 |  | 
|  | 43 | TEST(epoll, UnregisterHandler) { | 
|  | 44 | Epoll epoll; | 
|  | 45 | ASSERT_RESULT_OK(epoll.Open()); | 
|  | 46 |  | 
|  | 47 | int fds[2]; | 
|  | 48 | ASSERT_EQ(pipe(fds), 0); | 
|  | 49 |  | 
|  | 50 | CatchDtor catch_dtor; | 
|  | 51 | bool handler_invoked; | 
|  | 52 | auto handler = [&, catch_dtor]() -> void { | 
|  | 53 | auto result = epoll.UnregisterHandler(fds[0]); | 
|  | 54 | ASSERT_EQ(result.ok(), !handler_invoked); | 
|  | 55 | handler_invoked = true; | 
|  | 56 | ASSERT_NE(sValidObjects.find((void*)&catch_dtor), sValidObjects.end()); | 
|  | 57 | }; | 
|  | 58 |  | 
|  | 59 | epoll.RegisterHandler(fds[0], std::move(handler)); | 
|  | 60 |  | 
|  | 61 | uint8_t byte = 0xee; | 
|  | 62 | ASSERT_TRUE(android::base::WriteFully(fds[1], &byte, sizeof(byte))); | 
|  | 63 |  | 
|  | 64 | auto results = epoll.Wait({}); | 
|  | 65 | ASSERT_RESULT_OK(results); | 
|  | 66 | ASSERT_EQ(results->size(), size_t(1)); | 
|  | 67 |  | 
|  | 68 | for (const auto& function : *results) { | 
|  | 69 | (*function)(); | 
|  | 70 | (*function)(); | 
|  | 71 | } | 
|  | 72 | ASSERT_TRUE(handler_invoked); | 
|  | 73 | } | 
|  | 74 |  | 
|  | 75 | }  // namespace init | 
|  | 76 | }  // namespace android |