EventLoopImplementationUnix.cpp 18 KB

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