EventLoopImplementationUnix.cpp 16 KB

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