EventLoopImplementationUnix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. * Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/IDAllocator.h>
  7. #include <AK/Singleton.h>
  8. #include <AK/TemporaryChange.h>
  9. #include <AK/Time.h>
  10. #include <AK/WeakPtr.h>
  11. #include <LibCore/Event.h>
  12. #include <LibCore/EventLoopImplementationUnix.h>
  13. #include <LibCore/EventReceiver.h>
  14. #include <LibCore/Notifier.h>
  15. #include <LibCore/Socket.h>
  16. #include <LibCore/System.h>
  17. #include <LibCore/ThreadEventQueue.h>
  18. #include <sys/select.h>
  19. #include <unistd.h>
  20. namespace Core {
  21. struct ThreadData;
  22. namespace {
  23. thread_local ThreadData* s_thread_data;
  24. }
  25. struct EventLoopTimer {
  26. int timer_id { 0 };
  27. Duration interval;
  28. MonotonicTime fire_time { MonotonicTime::now_coarse() };
  29. bool should_reload { false };
  30. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  31. WeakPtr<EventReceiver> owner;
  32. void reload(MonotonicTime const& now) { fire_time = now + interval; }
  33. bool has_expired(MonotonicTime const& now) const { return now > fire_time; }
  34. };
  35. struct ThreadData {
  36. static ThreadData& the()
  37. {
  38. if (!s_thread_data) {
  39. // FIXME: Don't leak this.
  40. s_thread_data = new ThreadData;
  41. }
  42. return *s_thread_data;
  43. }
  44. ThreadData()
  45. {
  46. pid = getpid();
  47. initialize_wake_pipe();
  48. }
  49. void initialize_wake_pipe()
  50. {
  51. if (wake_pipe_fds[0] != -1)
  52. close(wake_pipe_fds[0]);
  53. if (wake_pipe_fds[1] != -1)
  54. close(wake_pipe_fds[1]);
  55. #if defined(SOCK_NONBLOCK)
  56. int rc = pipe2(wake_pipe_fds, O_CLOEXEC);
  57. #else
  58. int rc = pipe(wake_pipe_fds);
  59. fcntl(wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  60. fcntl(wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  61. #endif
  62. VERIFY(rc == 0);
  63. }
  64. // Each thread has its own timers, notifiers and a wake pipe.
  65. HashMap<int, NonnullOwnPtr<EventLoopTimer>> timers;
  66. HashTable<Notifier*> notifiers;
  67. // The wake pipe is used to notify another event loop that someone has called wake(), or a signal has been received.
  68. // wake() writes 0i32 into the pipe, signals write the signal number (guaranteed non-zero).
  69. int wake_pipe_fds[2] { -1, -1 };
  70. pid_t pid { 0 };
  71. IDAllocator id_allocator;
  72. };
  73. EventLoopImplementationUnix::EventLoopImplementationUnix()
  74. : m_wake_pipe_fds(&ThreadData::the().wake_pipe_fds)
  75. {
  76. }
  77. EventLoopImplementationUnix::~EventLoopImplementationUnix() = default;
  78. int EventLoopImplementationUnix::exec()
  79. {
  80. for (;;) {
  81. if (m_exit_requested)
  82. return m_exit_code;
  83. pump(PumpMode::WaitForEvents);
  84. }
  85. VERIFY_NOT_REACHED();
  86. }
  87. size_t EventLoopImplementationUnix::pump(PumpMode mode)
  88. {
  89. static_cast<EventLoopManagerUnix&>(EventLoopManager::the()).wait_for_events(mode);
  90. return ThreadEventQueue::current().process();
  91. }
  92. void EventLoopImplementationUnix::quit(int code)
  93. {
  94. m_exit_requested = true;
  95. m_exit_code = code;
  96. }
  97. void EventLoopImplementationUnix::unquit()
  98. {
  99. m_exit_requested = false;
  100. m_exit_code = 0;
  101. }
  102. bool EventLoopImplementationUnix::was_exit_requested() const
  103. {
  104. return m_exit_requested;
  105. }
  106. void EventLoopImplementationUnix::post_event(EventReceiver& receiver, NonnullOwnPtr<Event>&& event)
  107. {
  108. m_thread_event_queue.post_event(receiver, move(event));
  109. if (&m_thread_event_queue != &ThreadEventQueue::current())
  110. wake();
  111. }
  112. void EventLoopImplementationUnix::wake()
  113. {
  114. int wake_event = 0;
  115. MUST(Core::System::write((*m_wake_pipe_fds)[1], { &wake_event, sizeof(wake_event) }));
  116. }
  117. void EventLoopManagerUnix::wait_for_events(EventLoopImplementation::PumpMode mode)
  118. {
  119. auto& thread_data = ThreadData::the();
  120. fd_set read_fds {};
  121. fd_set write_fds {};
  122. retry:
  123. int max_fd = 0;
  124. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  125. FD_SET(fd, &set);
  126. if (fd > max_fd)
  127. max_fd = fd;
  128. };
  129. // The wake pipe informs us of POSIX signals as well as manual calls to wake()
  130. add_fd_to_set(thread_data.wake_pipe_fds[0], read_fds);
  131. for (auto& notifier : thread_data.notifiers) {
  132. if (notifier->type() == Notifier::Type::Read)
  133. add_fd_to_set(notifier->fd(), read_fds);
  134. if (notifier->type() == Notifier::Type::Write)
  135. add_fd_to_set(notifier->fd(), write_fds);
  136. if (notifier->type() == Notifier::Type::Exceptional)
  137. TODO();
  138. }
  139. bool has_pending_events = ThreadEventQueue::current().has_pending_events();
  140. // Figure out how long to wait at maximum.
  141. // This mainly depends on the PumpMode and whether we have pending events, but also the next expiring timer.
  142. MonotonicTime now = MonotonicTime::now_coarse();
  143. struct timeval timeout = { 0, 0 };
  144. bool should_wait_forever = false;
  145. if (mode == EventLoopImplementation::PumpMode::WaitForEvents && !has_pending_events) {
  146. auto next_timer_expiration = get_next_timer_expiration();
  147. if (next_timer_expiration.has_value()) {
  148. now = MonotonicTime::now();
  149. auto computed_timeout = next_timer_expiration.value() - now;
  150. if (computed_timeout.is_negative())
  151. computed_timeout = Duration::zero();
  152. timeout = computed_timeout.to_timeval();
  153. } else {
  154. should_wait_forever = true;
  155. }
  156. }
  157. try_select_again:
  158. // select() and wait for file system events, calls to wake(), POSIX signals, or timer expirations.
  159. int marked_fd_count = select(max_fd + 1, &read_fds, &write_fds, nullptr, should_wait_forever ? nullptr : &timeout);
  160. // Because POSIX, we might spuriously return from select() with EINTR; just select again.
  161. if (marked_fd_count < 0) {
  162. int saved_errno = errno;
  163. if (saved_errno == EINTR)
  164. goto try_select_again;
  165. dbgln("EventLoopImplementationUnix::wait_for_events: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  166. VERIFY_NOT_REACHED();
  167. }
  168. // We woke up due to a call to wake() or a POSIX signal.
  169. // Handle signals and see whether we need to handle events as well.
  170. if (FD_ISSET(thread_data.wake_pipe_fds[0], &read_fds)) {
  171. int wake_events[8];
  172. ssize_t nread;
  173. // We might receive another signal while read()ing here. The signal will go to the handle_signal properly,
  174. // but we get interrupted. Therefore, just retry while we were interrupted.
  175. do {
  176. errno = 0;
  177. nread = read(thread_data.wake_pipe_fds[0], wake_events, sizeof(wake_events));
  178. if (nread == 0)
  179. break;
  180. } while (nread < 0 && errno == EINTR);
  181. if (nread < 0) {
  182. perror("EventLoopImplementationUnix::wait_for_events: read from wake pipe");
  183. VERIFY_NOT_REACHED();
  184. }
  185. VERIFY(nread > 0);
  186. bool wake_requested = false;
  187. int event_count = nread / sizeof(wake_events[0]);
  188. for (int i = 0; i < event_count; i++) {
  189. if (wake_events[i] != 0)
  190. dispatch_signal(wake_events[i]);
  191. else
  192. wake_requested = true;
  193. }
  194. if (!wake_requested && nread == sizeof(wake_events))
  195. goto retry;
  196. }
  197. if (!thread_data.timers.is_empty()) {
  198. now = MonotonicTime::now_coarse();
  199. }
  200. // Handle expired timers.
  201. for (auto& it : thread_data.timers) {
  202. auto& timer = *it.value;
  203. if (!timer.has_expired(now))
  204. continue;
  205. auto owner = timer.owner.strong_ref();
  206. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  207. && owner && !owner->is_visible_for_timer_purposes()) {
  208. continue;
  209. }
  210. if (owner)
  211. ThreadEventQueue::current().post_event(*owner, make<TimerEvent>(timer.timer_id));
  212. if (timer.should_reload) {
  213. timer.reload(now);
  214. } else {
  215. // FIXME: Support removing expired timers that don't want to reload.
  216. VERIFY_NOT_REACHED();
  217. }
  218. }
  219. if (!marked_fd_count)
  220. return;
  221. // Handle file system notifiers by making them normal events.
  222. for (auto& notifier : thread_data.notifiers) {
  223. if (notifier->type() == Notifier::Type::Read && FD_ISSET(notifier->fd(), &read_fds)) {
  224. ThreadEventQueue::current().post_event(*notifier, make<NotifierActivationEvent>(notifier->fd()));
  225. }
  226. if (notifier->type() == Notifier::Type::Write && FD_ISSET(notifier->fd(), &write_fds)) {
  227. ThreadEventQueue::current().post_event(*notifier, make<NotifierActivationEvent>(notifier->fd()));
  228. }
  229. }
  230. }
  231. class SignalHandlers : public RefCounted<SignalHandlers> {
  232. AK_MAKE_NONCOPYABLE(SignalHandlers);
  233. AK_MAKE_NONMOVABLE(SignalHandlers);
  234. public:
  235. SignalHandlers(int signal_number, void (*handle_signal)(int));
  236. ~SignalHandlers();
  237. void dispatch();
  238. int add(Function<void(int)>&& handler);
  239. bool remove(int handler_id);
  240. bool is_empty() const
  241. {
  242. if (m_calling_handlers) {
  243. for (auto& handler : m_handlers_pending) {
  244. if (handler.value)
  245. return false; // an add is pending
  246. }
  247. }
  248. return m_handlers.is_empty();
  249. }
  250. bool have(int handler_id) const
  251. {
  252. if (m_calling_handlers) {
  253. auto it = m_handlers_pending.find(handler_id);
  254. if (it != m_handlers_pending.end()) {
  255. if (!it->value)
  256. return false; // a deletion is pending
  257. }
  258. }
  259. return m_handlers.contains(handler_id);
  260. }
  261. int m_signal_number;
  262. void (*m_original_handler)(int); // TODO: can't use sighandler_t?
  263. HashMap<int, Function<void(int)>> m_handlers;
  264. HashMap<int, Function<void(int)>> m_handlers_pending;
  265. bool m_calling_handlers { false };
  266. };
  267. struct SignalHandlersInfo {
  268. HashMap<int, NonnullRefPtr<SignalHandlers>> signal_handlers;
  269. int next_signal_id { 0 };
  270. };
  271. static Singleton<SignalHandlersInfo> s_signals;
  272. template<bool create_if_null = true>
  273. inline SignalHandlersInfo* signals_info()
  274. {
  275. return s_signals.ptr();
  276. }
  277. void EventLoopManagerUnix::dispatch_signal(int signal_number)
  278. {
  279. auto& info = *signals_info();
  280. auto handlers = info.signal_handlers.find(signal_number);
  281. if (handlers != info.signal_handlers.end()) {
  282. // Make sure we bump the ref count while dispatching the handlers!
  283. // This allows a handler to unregister/register while the handlers
  284. // are being called!
  285. auto handler = handlers->value;
  286. handler->dispatch();
  287. }
  288. }
  289. void EventLoopImplementationUnix::notify_forked_and_in_child()
  290. {
  291. auto& thread_data = ThreadData::the();
  292. thread_data.timers.clear();
  293. thread_data.notifiers.clear();
  294. thread_data.initialize_wake_pipe();
  295. if (auto* info = signals_info<false>()) {
  296. info->signal_handlers.clear();
  297. info->next_signal_id = 0;
  298. }
  299. thread_data.pid = getpid();
  300. }
  301. Optional<MonotonicTime> EventLoopManagerUnix::get_next_timer_expiration()
  302. {
  303. auto now = MonotonicTime::now_coarse();
  304. Optional<MonotonicTime> soonest {};
  305. for (auto& it : ThreadData::the().timers) {
  306. auto& fire_time = it.value->fire_time;
  307. auto owner = it.value->owner.strong_ref();
  308. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  309. && owner && !owner->is_visible_for_timer_purposes()) {
  310. continue;
  311. }
  312. // OPTIMIZATION: If we have a timer that needs to fire right away, we can stop looking here.
  313. // FIXME: This whole operation could be O(1) with a better data structure.
  314. if (fire_time < now)
  315. return now;
  316. if (!soonest.has_value() || fire_time < soonest.value())
  317. soonest = fire_time;
  318. }
  319. return soonest;
  320. }
  321. SignalHandlers::SignalHandlers(int signal_number, void (*handle_signal)(int))
  322. : m_signal_number(signal_number)
  323. , m_original_handler(signal(signal_number, handle_signal))
  324. {
  325. }
  326. SignalHandlers::~SignalHandlers()
  327. {
  328. signal(m_signal_number, m_original_handler);
  329. }
  330. void SignalHandlers::dispatch()
  331. {
  332. TemporaryChange change(m_calling_handlers, true);
  333. for (auto& handler : m_handlers)
  334. handler.value(m_signal_number);
  335. if (!m_handlers_pending.is_empty()) {
  336. // Apply pending adds/removes
  337. for (auto& handler : m_handlers_pending) {
  338. if (handler.value) {
  339. auto result = m_handlers.set(handler.key, move(handler.value));
  340. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  341. } else {
  342. m_handlers.remove(handler.key);
  343. }
  344. }
  345. m_handlers_pending.clear();
  346. }
  347. }
  348. int SignalHandlers::add(Function<void(int)>&& handler)
  349. {
  350. int id = ++signals_info()->next_signal_id; // TODO: worry about wrapping and duplicates?
  351. if (m_calling_handlers)
  352. m_handlers_pending.set(id, move(handler));
  353. else
  354. m_handlers.set(id, move(handler));
  355. return id;
  356. }
  357. bool SignalHandlers::remove(int handler_id)
  358. {
  359. VERIFY(handler_id != 0);
  360. if (m_calling_handlers) {
  361. auto it = m_handlers.find(handler_id);
  362. if (it != m_handlers.end()) {
  363. // Mark pending remove
  364. m_handlers_pending.set(handler_id, {});
  365. return true;
  366. }
  367. it = m_handlers_pending.find(handler_id);
  368. if (it != m_handlers_pending.end()) {
  369. if (!it->value)
  370. return false; // already was marked as deleted
  371. it->value = nullptr;
  372. return true;
  373. }
  374. return false;
  375. }
  376. return m_handlers.remove(handler_id);
  377. }
  378. void EventLoopManagerUnix::handle_signal(int signal_number)
  379. {
  380. VERIFY(signal_number != 0);
  381. auto& thread_data = ThreadData::the();
  382. // We MUST check if the current pid still matches, because there
  383. // is a window between fork() and exec() where a signal delivered
  384. // to our fork could be inadvertently routed to the parent process!
  385. if (getpid() == thread_data.pid) {
  386. int nwritten = write(thread_data.wake_pipe_fds[1], &signal_number, sizeof(signal_number));
  387. if (nwritten < 0) {
  388. perror("EventLoopImplementationUnix::register_signal: write");
  389. VERIFY_NOT_REACHED();
  390. }
  391. } else {
  392. // We're a fork who received a signal, reset thread_data.pid.
  393. thread_data.pid = getpid();
  394. }
  395. }
  396. int EventLoopManagerUnix::register_signal(int signal_number, Function<void(int)> handler)
  397. {
  398. VERIFY(signal_number != 0);
  399. auto& info = *signals_info();
  400. auto handlers = info.signal_handlers.find(signal_number);
  401. if (handlers == info.signal_handlers.end()) {
  402. auto signal_handlers = adopt_ref(*new SignalHandlers(signal_number, EventLoopManagerUnix::handle_signal));
  403. auto handler_id = signal_handlers->add(move(handler));
  404. info.signal_handlers.set(signal_number, move(signal_handlers));
  405. return handler_id;
  406. } else {
  407. return handlers->value->add(move(handler));
  408. }
  409. }
  410. void EventLoopManagerUnix::unregister_signal(int handler_id)
  411. {
  412. VERIFY(handler_id != 0);
  413. int remove_signal_number = 0;
  414. auto& info = *signals_info();
  415. for (auto& h : info.signal_handlers) {
  416. auto& handlers = *h.value;
  417. if (handlers.remove(handler_id)) {
  418. if (handlers.is_empty())
  419. remove_signal_number = handlers.m_signal_number;
  420. break;
  421. }
  422. }
  423. if (remove_signal_number != 0)
  424. info.signal_handlers.remove(remove_signal_number);
  425. }
  426. int EventLoopManagerUnix::register_timer(EventReceiver& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  427. {
  428. VERIFY(milliseconds >= 0);
  429. auto& thread_data = ThreadData::the();
  430. auto timer = make<EventLoopTimer>();
  431. timer->owner = object;
  432. timer->interval = Duration::from_milliseconds(milliseconds);
  433. timer->reload(MonotonicTime::now_coarse());
  434. timer->should_reload = should_reload;
  435. timer->fire_when_not_visible = fire_when_not_visible;
  436. int timer_id = thread_data.id_allocator.allocate();
  437. timer->timer_id = timer_id;
  438. thread_data.timers.set(timer_id, move(timer));
  439. return timer_id;
  440. }
  441. bool EventLoopManagerUnix::unregister_timer(int timer_id)
  442. {
  443. auto& thread_data = ThreadData::the();
  444. thread_data.id_allocator.deallocate(timer_id);
  445. return thread_data.timers.remove(timer_id);
  446. }
  447. void EventLoopManagerUnix::register_notifier(Notifier& notifier)
  448. {
  449. ThreadData::the().notifiers.set(&notifier);
  450. }
  451. void EventLoopManagerUnix::unregister_notifier(Notifier& notifier)
  452. {
  453. ThreadData::the().notifiers.remove(&notifier);
  454. }
  455. void EventLoopManagerUnix::did_post_event()
  456. {
  457. }
  458. EventLoopManagerUnix::~EventLoopManagerUnix() = default;
  459. NonnullOwnPtr<EventLoopImplementation> EventLoopManagerUnix::make_implementation()
  460. {
  461. return adopt_own(*new EventLoopImplementationUnix);
  462. }
  463. }