EventLoop.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, kleines Filmröllchen <malu.bertsch@gmail.com>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Assertions.h>
  9. #include <AK/Badge.h>
  10. #include <AK/Debug.h>
  11. #include <AK/Format.h>
  12. #include <AK/IDAllocator.h>
  13. #include <AK/JsonObject.h>
  14. #include <AK/JsonValue.h>
  15. #include <AK/NeverDestroyed.h>
  16. #include <AK/Singleton.h>
  17. #include <AK/TemporaryChange.h>
  18. #include <AK/Time.h>
  19. #include <LibCore/Event.h>
  20. #include <LibCore/EventLoop.h>
  21. #include <LibCore/LocalServer.h>
  22. #include <LibCore/Notifier.h>
  23. #include <LibCore/Object.h>
  24. #include <LibCore/Promise.h>
  25. #include <LibCore/SessionManagement.h>
  26. #include <LibCore/Socket.h>
  27. #include <LibCore/ThreadEventQueue.h>
  28. #include <LibThreading/Mutex.h>
  29. #include <LibThreading/MutexProtected.h>
  30. #include <errno.h>
  31. #include <fcntl.h>
  32. #include <signal.h>
  33. #include <stdio.h>
  34. #include <string.h>
  35. #include <sys/select.h>
  36. #include <sys/socket.h>
  37. #include <sys/time.h>
  38. #include <sys/types.h>
  39. #include <time.h>
  40. #include <unistd.h>
  41. #ifdef AK_OS_SERENITY
  42. # include <LibCore/Account.h>
  43. extern bool s_global_initializers_ran;
  44. #endif
  45. namespace Core {
  46. struct EventLoopTimer {
  47. int timer_id { 0 };
  48. Time interval;
  49. Time fire_time;
  50. bool should_reload { false };
  51. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  52. WeakPtr<Object> owner;
  53. void reload(Time const& now);
  54. bool has_expired(Time const& now) const;
  55. };
  56. struct EventLoop::Private {
  57. ThreadEventQueue& thread_event_queue;
  58. Private()
  59. : thread_event_queue(ThreadEventQueue::current())
  60. {
  61. }
  62. };
  63. static Threading::MutexProtected<NeverDestroyed<IDAllocator>> s_id_allocator;
  64. // Each thread has its own event loop stack, its own timers, notifiers and a wake pipe.
  65. static thread_local Vector<EventLoop&>* s_event_loop_stack;
  66. static thread_local HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
  67. static thread_local HashTable<Notifier*>* s_notifiers;
  68. // The wake pipe is both responsible for notifying us when someone calls wake(), as well as POSIX signals.
  69. // While wake() pushes zero into the pipe, signal numbers (by defintion nonzero, see signal_numbers.h) are pushed into the pipe verbatim.
  70. thread_local int EventLoop::s_wake_pipe_fds[2];
  71. thread_local bool EventLoop::s_wake_pipe_initialized { false };
  72. void EventLoop::initialize_wake_pipes()
  73. {
  74. if (!s_wake_pipe_initialized) {
  75. #if defined(SOCK_NONBLOCK)
  76. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  77. #else
  78. int rc = pipe(s_wake_pipe_fds);
  79. fcntl(s_wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  80. fcntl(s_wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  81. #endif
  82. VERIFY(rc == 0);
  83. s_wake_pipe_initialized = true;
  84. }
  85. }
  86. bool EventLoop::has_been_instantiated()
  87. {
  88. return s_event_loop_stack != nullptr && !s_event_loop_stack->is_empty();
  89. }
  90. class SignalHandlers : public RefCounted<SignalHandlers> {
  91. AK_MAKE_NONCOPYABLE(SignalHandlers);
  92. AK_MAKE_NONMOVABLE(SignalHandlers);
  93. public:
  94. SignalHandlers(int signo, void (*handle_signal)(int));
  95. ~SignalHandlers();
  96. void dispatch();
  97. int add(Function<void(int)>&& handler);
  98. bool remove(int handler_id);
  99. bool is_empty() const
  100. {
  101. if (m_calling_handlers) {
  102. for (auto& handler : m_handlers_pending) {
  103. if (handler.value)
  104. return false; // an add is pending
  105. }
  106. }
  107. return m_handlers.is_empty();
  108. }
  109. bool have(int handler_id) const
  110. {
  111. if (m_calling_handlers) {
  112. auto it = m_handlers_pending.find(handler_id);
  113. if (it != m_handlers_pending.end()) {
  114. if (!it->value)
  115. return false; // a deletion is pending
  116. }
  117. }
  118. return m_handlers.contains(handler_id);
  119. }
  120. int m_signo;
  121. void (*m_original_handler)(int); // TODO: can't use sighandler_t?
  122. HashMap<int, Function<void(int)>> m_handlers;
  123. HashMap<int, Function<void(int)>> m_handlers_pending;
  124. bool m_calling_handlers { false };
  125. };
  126. struct SignalHandlersInfo {
  127. HashMap<int, NonnullRefPtr<SignalHandlers>> signal_handlers;
  128. int next_signal_id { 0 };
  129. };
  130. static Singleton<SignalHandlersInfo> s_signals;
  131. template<bool create_if_null = true>
  132. inline SignalHandlersInfo* signals_info()
  133. {
  134. return s_signals.ptr();
  135. }
  136. pid_t EventLoop::s_pid;
  137. EventLoop::EventLoop()
  138. : m_wake_pipe_fds(&s_wake_pipe_fds)
  139. , m_private(make<Private>())
  140. {
  141. #ifdef AK_OS_SERENITY
  142. if (!s_global_initializers_ran) {
  143. // NOTE: Trying to have an event loop as a global variable will lead to initialization-order fiascos,
  144. // as the event loop constructor accesses and/or sets other global variables.
  145. // Therefore, we crash the program before ASAN catches us.
  146. // If you came here because of the assertion failure, please redesign your program to not have global event loops.
  147. // The common practice is to initialize the main event loop in the main function, and if necessary,
  148. // pass event loop references around or access them with EventLoop::with_main_locked() and EventLoop::current().
  149. VERIFY_NOT_REACHED();
  150. }
  151. #endif
  152. if (!s_event_loop_stack) {
  153. s_event_loop_stack = new Vector<EventLoop&>;
  154. s_timers = new HashMap<int, NonnullOwnPtr<EventLoopTimer>>;
  155. s_notifiers = new HashTable<Notifier*>;
  156. }
  157. if (s_event_loop_stack->is_empty()) {
  158. s_pid = getpid();
  159. s_event_loop_stack->append(*this);
  160. }
  161. initialize_wake_pipes();
  162. dbgln_if(EVENTLOOP_DEBUG, "{} Core::EventLoop constructed :)", getpid());
  163. }
  164. EventLoop::~EventLoop()
  165. {
  166. if (!s_event_loop_stack->is_empty() && &s_event_loop_stack->last() == this)
  167. s_event_loop_stack->take_last();
  168. }
  169. #define VERIFY_EVENT_LOOP_INITIALIZED() \
  170. do { \
  171. if (!s_event_loop_stack) { \
  172. warnln("EventLoop static API was called without prior EventLoop init!"); \
  173. VERIFY_NOT_REACHED(); \
  174. } \
  175. } while (0)
  176. EventLoop& EventLoop::current()
  177. {
  178. VERIFY_EVENT_LOOP_INITIALIZED();
  179. return s_event_loop_stack->last();
  180. }
  181. void EventLoop::quit(int code)
  182. {
  183. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::quit({})", code);
  184. m_exit_requested = true;
  185. m_exit_code = code;
  186. }
  187. void EventLoop::unquit()
  188. {
  189. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::unquit()");
  190. m_exit_requested = false;
  191. m_exit_code = 0;
  192. }
  193. struct EventLoopPusher {
  194. public:
  195. EventLoopPusher(EventLoop& event_loop)
  196. : m_event_loop(event_loop)
  197. {
  198. if (EventLoop::has_been_instantiated()) {
  199. s_event_loop_stack->append(event_loop);
  200. }
  201. }
  202. ~EventLoopPusher()
  203. {
  204. if (EventLoop::has_been_instantiated()) {
  205. s_event_loop_stack->take_last();
  206. }
  207. }
  208. private:
  209. EventLoop& m_event_loop;
  210. };
  211. int EventLoop::exec()
  212. {
  213. EventLoopPusher pusher(*this);
  214. for (;;) {
  215. if (m_exit_requested)
  216. return m_exit_code;
  217. pump();
  218. }
  219. VERIFY_NOT_REACHED();
  220. }
  221. void EventLoop::spin_until(Function<bool()> goal_condition)
  222. {
  223. EventLoopPusher pusher(*this);
  224. while (!goal_condition())
  225. pump();
  226. }
  227. size_t EventLoop::pump(WaitMode mode)
  228. {
  229. // Pumping the event loop from another thread is not allowed.
  230. VERIFY(&m_private->thread_event_queue == &ThreadEventQueue::current());
  231. wait_for_event(mode);
  232. return m_private->thread_event_queue.process();
  233. }
  234. void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
  235. {
  236. m_private->thread_event_queue.post_event(receiver, move(event));
  237. }
  238. void EventLoop::add_job(NonnullRefPtr<Promise<NonnullRefPtr<Object>>> job_promise)
  239. {
  240. ThreadEventQueue::current().add_job(move(job_promise));
  241. }
  242. SignalHandlers::SignalHandlers(int signo, void (*handle_signal)(int))
  243. : m_signo(signo)
  244. , m_original_handler(signal(signo, handle_signal))
  245. {
  246. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Registered handler for signal {}", m_signo);
  247. }
  248. SignalHandlers::~SignalHandlers()
  249. {
  250. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Unregistering handler for signal {}", m_signo);
  251. signal(m_signo, m_original_handler);
  252. }
  253. void SignalHandlers::dispatch()
  254. {
  255. TemporaryChange change(m_calling_handlers, true);
  256. for (auto& handler : m_handlers)
  257. handler.value(m_signo);
  258. if (!m_handlers_pending.is_empty()) {
  259. // Apply pending adds/removes
  260. for (auto& handler : m_handlers_pending) {
  261. if (handler.value) {
  262. auto result = m_handlers.set(handler.key, move(handler.value));
  263. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  264. } else {
  265. m_handlers.remove(handler.key);
  266. }
  267. }
  268. m_handlers_pending.clear();
  269. }
  270. }
  271. int SignalHandlers::add(Function<void(int)>&& handler)
  272. {
  273. int id = ++signals_info()->next_signal_id; // TODO: worry about wrapping and duplicates?
  274. if (m_calling_handlers)
  275. m_handlers_pending.set(id, move(handler));
  276. else
  277. m_handlers.set(id, move(handler));
  278. return id;
  279. }
  280. bool SignalHandlers::remove(int handler_id)
  281. {
  282. VERIFY(handler_id != 0);
  283. if (m_calling_handlers) {
  284. auto it = m_handlers.find(handler_id);
  285. if (it != m_handlers.end()) {
  286. // Mark pending remove
  287. m_handlers_pending.set(handler_id, {});
  288. return true;
  289. }
  290. it = m_handlers_pending.find(handler_id);
  291. if (it != m_handlers_pending.end()) {
  292. if (!it->value)
  293. return false; // already was marked as deleted
  294. it->value = nullptr;
  295. return true;
  296. }
  297. return false;
  298. }
  299. return m_handlers.remove(handler_id);
  300. }
  301. void EventLoop::dispatch_signal(int signo)
  302. {
  303. auto& info = *signals_info();
  304. auto handlers = info.signal_handlers.find(signo);
  305. if (handlers != info.signal_handlers.end()) {
  306. // Make sure we bump the ref count while dispatching the handlers!
  307. // This allows a handler to unregister/register while the handlers
  308. // are being called!
  309. auto handler = handlers->value;
  310. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: dispatching signal {}", signo);
  311. handler->dispatch();
  312. }
  313. }
  314. void EventLoop::handle_signal(int signo)
  315. {
  316. VERIFY(signo != 0);
  317. // We MUST check if the current pid still matches, because there
  318. // is a window between fork() and exec() where a signal delivered
  319. // to our fork could be inadvertently routed to the parent process!
  320. if (getpid() == s_pid) {
  321. int nwritten = write(s_wake_pipe_fds[1], &signo, sizeof(signo));
  322. if (nwritten < 0) {
  323. perror("EventLoop::register_signal: write");
  324. VERIFY_NOT_REACHED();
  325. }
  326. } else {
  327. // We're a fork who received a signal, reset s_pid
  328. s_pid = 0;
  329. }
  330. }
  331. int EventLoop::register_signal(int signo, Function<void(int)> handler)
  332. {
  333. VERIFY(signo != 0);
  334. auto& info = *signals_info();
  335. auto handlers = info.signal_handlers.find(signo);
  336. if (handlers == info.signal_handlers.end()) {
  337. auto signal_handlers = adopt_ref(*new SignalHandlers(signo, EventLoop::handle_signal));
  338. auto handler_id = signal_handlers->add(move(handler));
  339. info.signal_handlers.set(signo, move(signal_handlers));
  340. return handler_id;
  341. } else {
  342. return handlers->value->add(move(handler));
  343. }
  344. }
  345. void EventLoop::unregister_signal(int handler_id)
  346. {
  347. VERIFY(handler_id != 0);
  348. int remove_signo = 0;
  349. auto& info = *signals_info();
  350. for (auto& h : info.signal_handlers) {
  351. auto& handlers = *h.value;
  352. if (handlers.remove(handler_id)) {
  353. if (handlers.is_empty())
  354. remove_signo = handlers.m_signo;
  355. break;
  356. }
  357. }
  358. if (remove_signo != 0)
  359. info.signal_handlers.remove(remove_signo);
  360. }
  361. void EventLoop::notify_forked(ForkEvent event)
  362. {
  363. VERIFY_EVENT_LOOP_INITIALIZED();
  364. switch (event) {
  365. case ForkEvent::Child:
  366. s_event_loop_stack->clear();
  367. s_timers->clear();
  368. s_notifiers->clear();
  369. s_wake_pipe_initialized = false;
  370. initialize_wake_pipes();
  371. if (auto* info = signals_info<false>()) {
  372. info->signal_handlers.clear();
  373. info->next_signal_id = 0;
  374. }
  375. s_pid = 0;
  376. return;
  377. }
  378. VERIFY_NOT_REACHED();
  379. }
  380. void EventLoop::wait_for_event(WaitMode mode)
  381. {
  382. fd_set rfds;
  383. fd_set wfds;
  384. retry:
  385. // Set up the file descriptors for select().
  386. // Basically, we translate high-level event information into low-level selectable file descriptors.
  387. FD_ZERO(&rfds);
  388. FD_ZERO(&wfds);
  389. int max_fd = 0;
  390. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  391. FD_SET(fd, &set);
  392. if (fd > max_fd)
  393. max_fd = fd;
  394. };
  395. int max_fd_added = -1;
  396. // The wake pipe informs us of POSIX signals as well as manual calls to wake()
  397. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  398. max_fd = max(max_fd, max_fd_added);
  399. for (auto& notifier : *s_notifiers) {
  400. if (notifier->type() == Notifier::Type::Read)
  401. add_fd_to_set(notifier->fd(), rfds);
  402. if (notifier->type() == Notifier::Type::Write)
  403. add_fd_to_set(notifier->fd(), wfds);
  404. if (notifier->type() == Notifier::Type::Exceptional)
  405. VERIFY_NOT_REACHED();
  406. }
  407. bool has_pending_events = m_private->thread_event_queue.has_pending_events();
  408. // Figure out how long to wait at maximum.
  409. // This mainly depends on the WaitMode and whether we have pending events, but also the next expiring timer.
  410. Time now;
  411. struct timeval timeout = { 0, 0 };
  412. bool should_wait_forever = false;
  413. if (mode == WaitMode::WaitForEvents && !has_pending_events) {
  414. auto next_timer_expiration = get_next_timer_expiration();
  415. if (next_timer_expiration.has_value()) {
  416. now = Time::now_monotonic_coarse();
  417. auto computed_timeout = next_timer_expiration.value() - now;
  418. if (computed_timeout.is_negative())
  419. computed_timeout = Time::zero();
  420. timeout = computed_timeout.to_timeval();
  421. } else {
  422. should_wait_forever = true;
  423. }
  424. }
  425. try_select_again:
  426. // select() and wait for file system events, calls to wake(), POSIX signals, or timer expirations.
  427. int marked_fd_count = select(max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  428. // Because POSIX, we might spuriously return from select() with EINTR; just select again.
  429. if (marked_fd_count < 0) {
  430. int saved_errno = errno;
  431. if (saved_errno == EINTR) {
  432. if (m_exit_requested)
  433. return;
  434. goto try_select_again;
  435. }
  436. dbgln("Core::EventLoop::wait_for_event: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  437. VERIFY_NOT_REACHED();
  438. }
  439. // We woke up due to a call to wake() or a POSIX signal.
  440. // Handle signals and see whether we need to handle events as well.
  441. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  442. int wake_events[8];
  443. ssize_t nread;
  444. // We might receive another signal while read()ing here. The signal will go to the handle_signal properly,
  445. // but we get interrupted. Therefore, just retry while we were interrupted.
  446. do {
  447. errno = 0;
  448. nread = read(s_wake_pipe_fds[0], wake_events, sizeof(wake_events));
  449. if (nread == 0)
  450. break;
  451. } while (nread < 0 && errno == EINTR);
  452. if (nread < 0) {
  453. perror("Core::EventLoop::wait_for_event: read from wake pipe");
  454. VERIFY_NOT_REACHED();
  455. }
  456. VERIFY(nread > 0);
  457. bool wake_requested = false;
  458. int event_count = nread / sizeof(wake_events[0]);
  459. for (int i = 0; i < event_count; i++) {
  460. if (wake_events[i] != 0)
  461. dispatch_signal(wake_events[i]);
  462. else
  463. wake_requested = true;
  464. }
  465. if (!wake_requested && nread == sizeof(wake_events))
  466. goto retry;
  467. }
  468. if (!s_timers->is_empty()) {
  469. now = Time::now_monotonic_coarse();
  470. }
  471. // Handle expired timers.
  472. for (auto& it : *s_timers) {
  473. auto& timer = *it.value;
  474. if (!timer.has_expired(now))
  475. continue;
  476. auto owner = timer.owner.strong_ref();
  477. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  478. && owner && !owner->is_visible_for_timer_purposes()) {
  479. continue;
  480. }
  481. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Timer {} has expired, sending Core::TimerEvent to {}", timer.timer_id, *owner);
  482. if (owner)
  483. post_event(*owner, make<TimerEvent>(timer.timer_id));
  484. if (timer.should_reload) {
  485. timer.reload(now);
  486. } else {
  487. // FIXME: Support removing expired timers that don't want to reload.
  488. VERIFY_NOT_REACHED();
  489. }
  490. }
  491. if (!marked_fd_count)
  492. return;
  493. // Handle file system notifiers by making them normal events.
  494. for (auto& notifier : *s_notifiers) {
  495. if (notifier->type() == Notifier::Type::Read && FD_ISSET(notifier->fd(), &rfds)) {
  496. post_event(*notifier, make<NotifierActivationEvent>(notifier->fd()));
  497. }
  498. if (notifier->type() == Notifier::Type::Write && FD_ISSET(notifier->fd(), &wfds)) {
  499. post_event(*notifier, make<NotifierActivationEvent>(notifier->fd()));
  500. }
  501. }
  502. }
  503. bool EventLoopTimer::has_expired(Time const& now) const
  504. {
  505. return now > fire_time;
  506. }
  507. void EventLoopTimer::reload(Time const& now)
  508. {
  509. fire_time = now + interval;
  510. }
  511. Optional<Time> EventLoop::get_next_timer_expiration()
  512. {
  513. auto now = Time::now_monotonic_coarse();
  514. Optional<Time> soonest {};
  515. for (auto& it : *s_timers) {
  516. auto& fire_time = it.value->fire_time;
  517. auto owner = it.value->owner.strong_ref();
  518. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  519. && owner && !owner->is_visible_for_timer_purposes()) {
  520. continue;
  521. }
  522. // OPTIMIZATION: If we have a timer that needs to fire right away, we can stop looking here.
  523. // FIXME: This whole operation could be O(1) with a better data structure.
  524. if (fire_time < now)
  525. return now;
  526. if (!soonest.has_value() || fire_time < soonest.value())
  527. soonest = fire_time;
  528. }
  529. return soonest;
  530. }
  531. int EventLoop::register_timer(Object& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  532. {
  533. VERIFY_EVENT_LOOP_INITIALIZED();
  534. VERIFY(milliseconds >= 0);
  535. auto timer = make<EventLoopTimer>();
  536. timer->owner = object;
  537. timer->interval = Time::from_milliseconds(milliseconds);
  538. timer->reload(Time::now_monotonic_coarse());
  539. timer->should_reload = should_reload;
  540. timer->fire_when_not_visible = fire_when_not_visible;
  541. int timer_id = s_id_allocator.with_locked([](auto& allocator) { return allocator->allocate(); });
  542. timer->timer_id = timer_id;
  543. s_timers->set(timer_id, move(timer));
  544. return timer_id;
  545. }
  546. bool EventLoop::unregister_timer(int timer_id)
  547. {
  548. VERIFY_EVENT_LOOP_INITIALIZED();
  549. s_id_allocator.with_locked([&](auto& allocator) { allocator->deallocate(timer_id); });
  550. auto it = s_timers->find(timer_id);
  551. if (it == s_timers->end())
  552. return false;
  553. s_timers->remove(it);
  554. return true;
  555. }
  556. void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
  557. {
  558. VERIFY_EVENT_LOOP_INITIALIZED();
  559. s_notifiers->set(&notifier);
  560. }
  561. void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
  562. {
  563. VERIFY_EVENT_LOOP_INITIALIZED();
  564. s_notifiers->remove(&notifier);
  565. }
  566. void EventLoop::wake()
  567. {
  568. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::wake()");
  569. int wake_event = 0;
  570. int nwritten = write((*m_wake_pipe_fds)[1], &wake_event, sizeof(wake_event));
  571. if (nwritten < 0) {
  572. perror("EventLoop::wake: write");
  573. VERIFY_NOT_REACHED();
  574. }
  575. }
  576. void EventLoop::deferred_invoke(Function<void()> invokee)
  577. {
  578. auto context = DeferredInvocationContext::construct();
  579. post_event(context, make<Core::DeferredInvocationEvent>(context, move(invokee)));
  580. }
  581. void deferred_invoke(Function<void()> invokee)
  582. {
  583. EventLoop::current().deferred_invoke(move(invokee));
  584. }
  585. }