EventLoopImplementationUnix.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. struct timeval timeout = { 0, 0 };
  143. bool should_wait_forever = false;
  144. if (mode == EventLoopImplementation::PumpMode::WaitForEvents && !has_pending_events) {
  145. auto next_timer_expiration = get_next_timer_expiration();
  146. if (next_timer_expiration.has_value()) {
  147. auto now = MonotonicTime::now_coarse();
  148. auto computed_timeout = next_timer_expiration.value() - now;
  149. if (computed_timeout.is_negative())
  150. computed_timeout = Duration::zero();
  151. timeout = computed_timeout.to_timeval();
  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. int marked_fd_count = select(max_fd + 1, &read_fds, &write_fds, nullptr, should_wait_forever ? nullptr : &timeout);
  159. // Because POSIX, we might spuriously return from select() with EINTR; just select again.
  160. if (marked_fd_count < 0) {
  161. int saved_errno = errno;
  162. if (saved_errno == EINTR)
  163. goto try_select_again;
  164. dbgln("EventLoopImplementationUnix::wait_for_events: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  165. VERIFY_NOT_REACHED();
  166. }
  167. // We woke up due to a call to wake() or a POSIX signal.
  168. // Handle signals and see whether we need to handle events as well.
  169. if (FD_ISSET(thread_data.wake_pipe_fds[0], &read_fds)) {
  170. int wake_events[8];
  171. ssize_t nread;
  172. // We might receive another signal while read()ing here. The signal will go to the handle_signal properly,
  173. // but we get interrupted. Therefore, just retry while we were interrupted.
  174. do {
  175. errno = 0;
  176. nread = read(thread_data.wake_pipe_fds[0], wake_events, sizeof(wake_events));
  177. if (nread == 0)
  178. break;
  179. } while (nread < 0 && errno == EINTR);
  180. if (nread < 0) {
  181. perror("EventLoopImplementationUnix::wait_for_events: read from wake pipe");
  182. VERIFY_NOT_REACHED();
  183. }
  184. VERIFY(nread > 0);
  185. bool wake_requested = false;
  186. int event_count = nread / sizeof(wake_events[0]);
  187. for (int i = 0; i < event_count; i++) {
  188. if (wake_events[i] != 0)
  189. dispatch_signal(wake_events[i]);
  190. else
  191. wake_requested = true;
  192. }
  193. if (!wake_requested && nread == sizeof(wake_events))
  194. goto retry;
  195. }
  196. // Handle expired timers.
  197. if (!thread_data.timers.is_empty()) {
  198. auto now = MonotonicTime::now_coarse();
  199. for (auto& it : thread_data.timers) {
  200. auto& timer = *it.value;
  201. if (!timer.has_expired(now))
  202. continue;
  203. auto owner = timer.owner.strong_ref();
  204. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  205. && owner && !owner->is_visible_for_timer_purposes()) {
  206. continue;
  207. }
  208. if (owner)
  209. ThreadEventQueue::current().post_event(*owner, make<TimerEvent>(timer.timer_id));
  210. if (timer.should_reload) {
  211. timer.reload(now);
  212. } else {
  213. // FIXME: Support removing expired timers that don't want to reload.
  214. VERIFY_NOT_REACHED();
  215. }
  216. }
  217. }
  218. if (!marked_fd_count)
  219. return;
  220. // Handle file system notifiers by making them normal events.
  221. for (auto& notifier : thread_data.notifiers) {
  222. if (notifier->type() == Notifier::Type::Read && FD_ISSET(notifier->fd(), &read_fds)) {
  223. ThreadEventQueue::current().post_event(*notifier, make<NotifierActivationEvent>(notifier->fd()));
  224. }
  225. if (notifier->type() == Notifier::Type::Write && FD_ISSET(notifier->fd(), &write_fds)) {
  226. ThreadEventQueue::current().post_event(*notifier, make<NotifierActivationEvent>(notifier->fd()));
  227. }
  228. }
  229. }
  230. class SignalHandlers : public RefCounted<SignalHandlers> {
  231. AK_MAKE_NONCOPYABLE(SignalHandlers);
  232. AK_MAKE_NONMOVABLE(SignalHandlers);
  233. public:
  234. SignalHandlers(int signal_number, void (*handle_signal)(int));
  235. ~SignalHandlers();
  236. void dispatch();
  237. int add(Function<void(int)>&& handler);
  238. bool remove(int handler_id);
  239. bool is_empty() const
  240. {
  241. if (m_calling_handlers) {
  242. for (auto& handler : m_handlers_pending) {
  243. if (handler.value)
  244. return false; // an add is pending
  245. }
  246. }
  247. return m_handlers.is_empty();
  248. }
  249. bool have(int handler_id) const
  250. {
  251. if (m_calling_handlers) {
  252. auto it = m_handlers_pending.find(handler_id);
  253. if (it != m_handlers_pending.end()) {
  254. if (!it->value)
  255. return false; // a deletion is pending
  256. }
  257. }
  258. return m_handlers.contains(handler_id);
  259. }
  260. int m_signal_number;
  261. void (*m_original_handler)(int); // TODO: can't use sighandler_t?
  262. HashMap<int, Function<void(int)>> m_handlers;
  263. HashMap<int, Function<void(int)>> m_handlers_pending;
  264. bool m_calling_handlers { false };
  265. };
  266. struct SignalHandlersInfo {
  267. HashMap<int, NonnullRefPtr<SignalHandlers>> signal_handlers;
  268. int next_signal_id { 0 };
  269. };
  270. static Singleton<SignalHandlersInfo> s_signals;
  271. template<bool create_if_null = true>
  272. inline SignalHandlersInfo* signals_info()
  273. {
  274. return s_signals.ptr();
  275. }
  276. void EventLoopManagerUnix::dispatch_signal(int signal_number)
  277. {
  278. auto& info = *signals_info();
  279. auto handlers = info.signal_handlers.find(signal_number);
  280. if (handlers != info.signal_handlers.end()) {
  281. // Make sure we bump the ref count while dispatching the handlers!
  282. // This allows a handler to unregister/register while the handlers
  283. // are being called!
  284. auto handler = handlers->value;
  285. handler->dispatch();
  286. }
  287. }
  288. void EventLoopImplementationUnix::notify_forked_and_in_child()
  289. {
  290. auto& thread_data = ThreadData::the();
  291. thread_data.timers.clear();
  292. thread_data.notifiers.clear();
  293. thread_data.initialize_wake_pipe();
  294. if (auto* info = signals_info<false>()) {
  295. info->signal_handlers.clear();
  296. info->next_signal_id = 0;
  297. }
  298. thread_data.pid = getpid();
  299. }
  300. Optional<MonotonicTime> EventLoopManagerUnix::get_next_timer_expiration()
  301. {
  302. auto now = MonotonicTime::now_coarse();
  303. Optional<MonotonicTime> soonest {};
  304. for (auto& it : ThreadData::the().timers) {
  305. auto& fire_time = it.value->fire_time;
  306. auto owner = it.value->owner.strong_ref();
  307. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  308. && owner && !owner->is_visible_for_timer_purposes()) {
  309. continue;
  310. }
  311. // OPTIMIZATION: If we have a timer that needs to fire right away, we can stop looking here.
  312. // FIXME: This whole operation could be O(1) with a better data structure.
  313. if (fire_time < now)
  314. return now;
  315. if (!soonest.has_value() || fire_time < soonest.value())
  316. soonest = fire_time;
  317. }
  318. return soonest;
  319. }
  320. SignalHandlers::SignalHandlers(int signal_number, void (*handle_signal)(int))
  321. : m_signal_number(signal_number)
  322. , m_original_handler(signal(signal_number, handle_signal))
  323. {
  324. }
  325. SignalHandlers::~SignalHandlers()
  326. {
  327. signal(m_signal_number, m_original_handler);
  328. }
  329. void SignalHandlers::dispatch()
  330. {
  331. TemporaryChange change(m_calling_handlers, true);
  332. for (auto& handler : m_handlers)
  333. handler.value(m_signal_number);
  334. if (!m_handlers_pending.is_empty()) {
  335. // Apply pending adds/removes
  336. for (auto& handler : m_handlers_pending) {
  337. if (handler.value) {
  338. auto result = m_handlers.set(handler.key, move(handler.value));
  339. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  340. } else {
  341. m_handlers.remove(handler.key);
  342. }
  343. }
  344. m_handlers_pending.clear();
  345. }
  346. }
  347. int SignalHandlers::add(Function<void(int)>&& handler)
  348. {
  349. int id = ++signals_info()->next_signal_id; // TODO: worry about wrapping and duplicates?
  350. if (m_calling_handlers)
  351. m_handlers_pending.set(id, move(handler));
  352. else
  353. m_handlers.set(id, move(handler));
  354. return id;
  355. }
  356. bool SignalHandlers::remove(int handler_id)
  357. {
  358. VERIFY(handler_id != 0);
  359. if (m_calling_handlers) {
  360. auto it = m_handlers.find(handler_id);
  361. if (it != m_handlers.end()) {
  362. // Mark pending remove
  363. m_handlers_pending.set(handler_id, {});
  364. return true;
  365. }
  366. it = m_handlers_pending.find(handler_id);
  367. if (it != m_handlers_pending.end()) {
  368. if (!it->value)
  369. return false; // already was marked as deleted
  370. it->value = nullptr;
  371. return true;
  372. }
  373. return false;
  374. }
  375. return m_handlers.remove(handler_id);
  376. }
  377. void EventLoopManagerUnix::handle_signal(int signal_number)
  378. {
  379. VERIFY(signal_number != 0);
  380. auto& thread_data = ThreadData::the();
  381. // We MUST check if the current pid still matches, because there
  382. // is a window between fork() and exec() where a signal delivered
  383. // to our fork could be inadvertently routed to the parent process!
  384. if (getpid() == thread_data.pid) {
  385. int nwritten = write(thread_data.wake_pipe_fds[1], &signal_number, sizeof(signal_number));
  386. if (nwritten < 0) {
  387. perror("EventLoopImplementationUnix::register_signal: write");
  388. VERIFY_NOT_REACHED();
  389. }
  390. } else {
  391. // We're a fork who received a signal, reset thread_data.pid.
  392. thread_data.pid = getpid();
  393. }
  394. }
  395. int EventLoopManagerUnix::register_signal(int signal_number, Function<void(int)> handler)
  396. {
  397. VERIFY(signal_number != 0);
  398. auto& info = *signals_info();
  399. auto handlers = info.signal_handlers.find(signal_number);
  400. if (handlers == info.signal_handlers.end()) {
  401. auto signal_handlers = adopt_ref(*new SignalHandlers(signal_number, EventLoopManagerUnix::handle_signal));
  402. auto handler_id = signal_handlers->add(move(handler));
  403. info.signal_handlers.set(signal_number, move(signal_handlers));
  404. return handler_id;
  405. } else {
  406. return handlers->value->add(move(handler));
  407. }
  408. }
  409. void EventLoopManagerUnix::unregister_signal(int handler_id)
  410. {
  411. VERIFY(handler_id != 0);
  412. int remove_signal_number = 0;
  413. auto& info = *signals_info();
  414. for (auto& h : info.signal_handlers) {
  415. auto& handlers = *h.value;
  416. if (handlers.remove(handler_id)) {
  417. if (handlers.is_empty())
  418. remove_signal_number = handlers.m_signal_number;
  419. break;
  420. }
  421. }
  422. if (remove_signal_number != 0)
  423. info.signal_handlers.remove(remove_signal_number);
  424. }
  425. int EventLoopManagerUnix::register_timer(EventReceiver& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  426. {
  427. VERIFY(milliseconds >= 0);
  428. auto& thread_data = ThreadData::the();
  429. auto timer = make<EventLoopTimer>();
  430. timer->owner = object;
  431. timer->interval = Duration::from_milliseconds(milliseconds);
  432. timer->reload(MonotonicTime::now_coarse());
  433. timer->should_reload = should_reload;
  434. timer->fire_when_not_visible = fire_when_not_visible;
  435. int timer_id = thread_data.id_allocator.allocate();
  436. timer->timer_id = timer_id;
  437. thread_data.timers.set(timer_id, move(timer));
  438. return timer_id;
  439. }
  440. bool EventLoopManagerUnix::unregister_timer(int timer_id)
  441. {
  442. auto& thread_data = ThreadData::the();
  443. thread_data.id_allocator.deallocate(timer_id);
  444. return thread_data.timers.remove(timer_id);
  445. }
  446. void EventLoopManagerUnix::register_notifier(Notifier& notifier)
  447. {
  448. ThreadData::the().notifiers.set(&notifier);
  449. }
  450. void EventLoopManagerUnix::unregister_notifier(Notifier& notifier)
  451. {
  452. ThreadData::the().notifiers.remove(&notifier);
  453. }
  454. void EventLoopManagerUnix::did_post_event()
  455. {
  456. }
  457. EventLoopManagerUnix::~EventLoopManagerUnix() = default;
  458. NonnullOwnPtr<EventLoopImplementation> EventLoopManagerUnix::make_implementation()
  459. {
  460. return adopt_own(*new EventLoopImplementationUnix);
  461. }
  462. }