EventLoopImplementationUnix.cpp 16 KB

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