1 /* 2 * Copyright (C) 2006 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 #ifndef __FDEVENT_H 18 #define __FDEVENT_H 19 20 #include <stddef.h> 21 #include <stdint.h> 22 23 #include <chrono> 24 #include <functional> 25 #include <optional> 26 #include <variant> 27 28 #include "adb_unique_fd.h" 29 30 // Events that may be observed 31 #define FDE_READ 0x0001 32 #define FDE_WRITE 0x0002 33 #define FDE_ERROR 0x0004 34 #define FDE_TIMEOUT 0x0008 35 36 typedef void (*fd_func)(int fd, unsigned events, void *userdata); 37 typedef void (*fd_func2)(struct fdevent* fde, unsigned events, void* userdata); 38 39 struct fdevent { 40 uint64_t id; 41 42 unique_fd fd; 43 int force_eof = 0; 44 45 uint16_t state = 0; 46 uint16_t events = 0; 47 std::optional<std::chrono::milliseconds> timeout; 48 std::chrono::steady_clock::time_point last_active; 49 50 std::variant<fd_func, fd_func2> func; 51 void* arg = nullptr; 52 }; 53 54 // Allocate and initialize a new fdevent object 55 // TODO: Switch these to unique_fd. 56 fdevent *fdevent_create(int fd, fd_func func, void *arg); 57 fdevent* fdevent_create(int fd, fd_func2 func, void* arg); 58 59 // Deallocate an fdevent object that was created by fdevent_create. 60 void fdevent_destroy(fdevent *fde); 61 62 // fdevent_destroy, except releasing the file descriptor previously owned by the fdevent. 63 unique_fd fdevent_release(fdevent* fde); 64 65 // Change which events should cause notifications 66 void fdevent_set(fdevent *fde, unsigned events); 67 void fdevent_add(fdevent *fde, unsigned events); 68 void fdevent_del(fdevent *fde, unsigned events); 69 70 // Set a timeout on an fdevent. 71 // If no events are triggered by the timeout, an FDE_TIMEOUT will be generated. 72 // Note timeouts are not defused automatically; if a timeout is set on an fdevent, it will 73 // trigger repeatedly every |timeout| ms. 74 void fdevent_set_timeout(fdevent* fde, std::optional<std::chrono::milliseconds> timeout); 75 76 // Loop forever, handling events. 77 void fdevent_loop(); 78 79 void check_main_thread(); 80 81 // Queue an operation to run on the main thread. 82 void fdevent_run_on_main_thread(std::function<void()> fn); 83 84 // The following functions are used only for tests. 85 void fdevent_terminate_loop(); 86 size_t fdevent_installed_count(); 87 void fdevent_reset(); 88 void set_main_thread(); 89 90 #endif 91