EventLoopImplementationUnix.cpp 18 KB

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