EventLoop.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Badge.h>
  7. #include <AK/Debug.h>
  8. #include <AK/Format.h>
  9. #include <AK/IDAllocator.h>
  10. #include <AK/JsonObject.h>
  11. #include <AK/JsonValue.h>
  12. #include <AK/NeverDestroyed.h>
  13. #include <AK/Singleton.h>
  14. #include <AK/TemporaryChange.h>
  15. #include <AK/Time.h>
  16. #include <LibCore/Event.h>
  17. #include <LibCore/EventLoop.h>
  18. #include <LibCore/LocalServer.h>
  19. #include <LibCore/LocalSocket.h>
  20. #include <LibCore/Notifier.h>
  21. #include <LibCore/Object.h>
  22. #include <LibThreading/Mutex.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <signal.h>
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <sys/select.h>
  29. #include <sys/socket.h>
  30. #include <sys/time.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. namespace Core {
  34. class InspectorServerConnection;
  35. [[maybe_unused]] static bool connect_to_inspector_server();
  36. struct EventLoopTimer {
  37. int timer_id { 0 };
  38. Time interval;
  39. Time fire_time;
  40. bool should_reload { false };
  41. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  42. WeakPtr<Object> owner;
  43. void reload(const Time& now);
  44. bool has_expired(const Time& now) const;
  45. };
  46. struct EventLoop::Private {
  47. Threading::Mutex lock;
  48. };
  49. static EventLoop* s_main_event_loop;
  50. static Vector<EventLoop&>* s_event_loop_stack;
  51. static NeverDestroyed<IDAllocator> s_id_allocator;
  52. static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
  53. static HashTable<Notifier*>* s_notifiers;
  54. int EventLoop::s_wake_pipe_fds[2];
  55. static RefPtr<InspectorServerConnection> s_inspector_server_connection;
  56. bool EventLoop::has_been_instantiated()
  57. {
  58. return s_main_event_loop;
  59. }
  60. class SignalHandlers : public RefCounted<SignalHandlers> {
  61. AK_MAKE_NONCOPYABLE(SignalHandlers);
  62. AK_MAKE_NONMOVABLE(SignalHandlers);
  63. public:
  64. SignalHandlers(int signo, void (*handle_signal)(int));
  65. ~SignalHandlers();
  66. void dispatch();
  67. int add(Function<void(int)>&& handler);
  68. bool remove(int handler_id);
  69. bool is_empty() const
  70. {
  71. if (m_calling_handlers) {
  72. for (auto& handler : m_handlers_pending) {
  73. if (handler.value)
  74. return false; // an add is pending
  75. }
  76. }
  77. return m_handlers.is_empty();
  78. }
  79. bool have(int handler_id) const
  80. {
  81. if (m_calling_handlers) {
  82. auto it = m_handlers_pending.find(handler_id);
  83. if (it != m_handlers_pending.end()) {
  84. if (!it->value)
  85. return false; // a deletion is pending
  86. }
  87. }
  88. return m_handlers.contains(handler_id);
  89. }
  90. int m_signo;
  91. void (*m_original_handler)(int); // TODO: can't use sighandler_t?
  92. HashMap<int, Function<void(int)>> m_handlers;
  93. HashMap<int, Function<void(int)>> m_handlers_pending;
  94. bool m_calling_handlers { false };
  95. };
  96. struct SignalHandlersInfo {
  97. HashMap<int, NonnullRefPtr<SignalHandlers>> signal_handlers;
  98. int next_signal_id { 0 };
  99. };
  100. static Singleton<SignalHandlersInfo> s_signals;
  101. template<bool create_if_null = true>
  102. inline SignalHandlersInfo* signals_info()
  103. {
  104. return s_signals.ptr();
  105. }
  106. pid_t EventLoop::s_pid;
  107. class InspectorServerConnection : public Object {
  108. C_OBJECT(InspectorServerConnection)
  109. private:
  110. explicit InspectorServerConnection(RefPtr<LocalSocket> socket)
  111. : m_socket(move(socket))
  112. , m_client_id(s_id_allocator->allocate())
  113. {
  114. #ifdef __serenity__
  115. add_child(*m_socket);
  116. m_socket->on_ready_to_read = [this] {
  117. u32 length;
  118. int nread = m_socket->read((u8*)&length, sizeof(length));
  119. if (nread == 0) {
  120. dbgln_if(EVENTLOOP_DEBUG, "RPC client disconnected");
  121. shutdown();
  122. return;
  123. }
  124. VERIFY(nread == sizeof(length));
  125. auto request = m_socket->read(length);
  126. auto request_json = JsonValue::from_string(request);
  127. if (request_json.is_error() || !request_json.value().is_object()) {
  128. dbgln("RPC client sent invalid request");
  129. shutdown();
  130. return;
  131. }
  132. handle_request(request_json.value().as_object());
  133. };
  134. #else
  135. warnln("RPC Client constructed outside serenity, this is very likely a bug!");
  136. #endif
  137. }
  138. virtual ~InspectorServerConnection() override
  139. {
  140. if (auto inspected_object = m_inspected_object.strong_ref())
  141. inspected_object->decrement_inspector_count({});
  142. }
  143. public:
  144. void send_response(const JsonObject& response)
  145. {
  146. auto serialized = response.to_string();
  147. u32 length = serialized.length();
  148. m_socket->write((const u8*)&length, sizeof(length));
  149. m_socket->write(serialized);
  150. }
  151. void handle_request(const JsonObject& request)
  152. {
  153. auto type = request.get("type").as_string_or({});
  154. if (type.is_null()) {
  155. dbgln("RPC client sent request without type field");
  156. return;
  157. }
  158. if (type == "Identify") {
  159. JsonObject response;
  160. response.set("type", type);
  161. response.set("pid", getpid());
  162. #ifdef __serenity__
  163. char buffer[1024];
  164. if (get_process_name(buffer, sizeof(buffer)) >= 0) {
  165. response.set("process_name", buffer);
  166. } else {
  167. response.set("process_name", JsonValue());
  168. }
  169. #endif
  170. send_response(response);
  171. return;
  172. }
  173. if (type == "GetAllObjects") {
  174. JsonObject response;
  175. response.set("type", type);
  176. JsonArray objects;
  177. for (auto& object : Object::all_objects()) {
  178. JsonObject json_object;
  179. object.save_to(json_object);
  180. objects.append(move(json_object));
  181. }
  182. response.set("objects", move(objects));
  183. send_response(response);
  184. return;
  185. }
  186. if (type == "SetInspectedObject") {
  187. auto address = request.get("address").to_number<FlatPtr>();
  188. for (auto& object : Object::all_objects()) {
  189. if ((FlatPtr)&object == address) {
  190. if (auto inspected_object = m_inspected_object.strong_ref())
  191. inspected_object->decrement_inspector_count({});
  192. m_inspected_object = object;
  193. object.increment_inspector_count({});
  194. break;
  195. }
  196. }
  197. return;
  198. }
  199. if (type == "SetProperty") {
  200. auto address = request.get("address").to_number<FlatPtr>();
  201. for (auto& object : Object::all_objects()) {
  202. if ((FlatPtr)&object == address) {
  203. bool success = object.set_property(request.get("name").to_string(), request.get("value"));
  204. JsonObject response;
  205. response.set("type", "SetProperty");
  206. response.set("success", success);
  207. send_response(response);
  208. break;
  209. }
  210. }
  211. return;
  212. }
  213. if (type == "Disconnect") {
  214. shutdown();
  215. return;
  216. }
  217. }
  218. void shutdown()
  219. {
  220. s_id_allocator->deallocate(m_client_id);
  221. }
  222. private:
  223. RefPtr<LocalSocket> m_socket;
  224. WeakPtr<Object> m_inspected_object;
  225. int m_client_id { -1 };
  226. };
  227. EventLoop::EventLoop([[maybe_unused]] MakeInspectable make_inspectable)
  228. : m_private(make<Private>())
  229. {
  230. if (!s_event_loop_stack) {
  231. s_event_loop_stack = new Vector<EventLoop&>;
  232. s_timers = new HashMap<int, NonnullOwnPtr<EventLoopTimer>>;
  233. s_notifiers = new HashTable<Notifier*>;
  234. }
  235. if (!s_main_event_loop) {
  236. s_main_event_loop = this;
  237. s_pid = getpid();
  238. #if defined(SOCK_NONBLOCK)
  239. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  240. #else
  241. int rc = pipe(s_wake_pipe_fds);
  242. fcntl(s_wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  243. fcntl(s_wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  244. #endif
  245. VERIFY(rc == 0);
  246. s_event_loop_stack->append(*this);
  247. #ifdef __serenity__
  248. if (getuid() != 0
  249. && make_inspectable == MakeInspectable::Yes
  250. && !s_inspector_server_connection) {
  251. if (!connect_to_inspector_server())
  252. dbgln("Core::EventLoop: Failed to connect to InspectorServer");
  253. }
  254. #endif
  255. }
  256. dbgln_if(EVENTLOOP_DEBUG, "{} Core::EventLoop constructed :)", getpid());
  257. }
  258. EventLoop::~EventLoop()
  259. {
  260. // NOTE: Pop the main event loop off of the stack when destroyed.
  261. if (this == s_main_event_loop) {
  262. s_event_loop_stack->take_last();
  263. s_main_event_loop = nullptr;
  264. }
  265. }
  266. bool connect_to_inspector_server()
  267. {
  268. #ifdef __serenity__
  269. auto socket = Core::LocalSocket::construct();
  270. if (!socket->connect(SocketAddress::local("/tmp/portal/inspectables")))
  271. return false;
  272. s_inspector_server_connection = InspectorServerConnection::construct(move(socket));
  273. return true;
  274. #else
  275. VERIFY_NOT_REACHED();
  276. #endif
  277. }
  278. EventLoop& EventLoop::main()
  279. {
  280. VERIFY(s_main_event_loop);
  281. return *s_main_event_loop;
  282. }
  283. EventLoop& EventLoop::current()
  284. {
  285. return s_event_loop_stack->last();
  286. }
  287. void EventLoop::quit(int code)
  288. {
  289. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::quit({})", code);
  290. m_exit_requested = true;
  291. m_exit_code = code;
  292. }
  293. void EventLoop::unquit()
  294. {
  295. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::unquit()");
  296. m_exit_requested = false;
  297. m_exit_code = 0;
  298. }
  299. struct EventLoopPusher {
  300. public:
  301. EventLoopPusher(EventLoop& event_loop)
  302. : m_event_loop(event_loop)
  303. {
  304. if (&m_event_loop != s_main_event_loop) {
  305. m_event_loop.take_pending_events_from(EventLoop::current());
  306. s_event_loop_stack->append(event_loop);
  307. }
  308. }
  309. ~EventLoopPusher()
  310. {
  311. if (&m_event_loop != s_main_event_loop) {
  312. s_event_loop_stack->take_last();
  313. EventLoop::current().take_pending_events_from(m_event_loop);
  314. }
  315. }
  316. private:
  317. EventLoop& m_event_loop;
  318. };
  319. int EventLoop::exec()
  320. {
  321. EventLoopPusher pusher(*this);
  322. for (;;) {
  323. if (m_exit_requested)
  324. return m_exit_code;
  325. pump();
  326. }
  327. VERIFY_NOT_REACHED();
  328. }
  329. void EventLoop::spin_until(Function<bool()> goal_condition)
  330. {
  331. EventLoopPusher pusher(*this);
  332. while (!goal_condition())
  333. pump();
  334. }
  335. void EventLoop::pump(WaitMode mode)
  336. {
  337. wait_for_event(mode);
  338. decltype(m_queued_events) events;
  339. {
  340. Threading::MutexLocker locker(m_private->lock);
  341. events = move(m_queued_events);
  342. }
  343. for (size_t i = 0; i < events.size(); ++i) {
  344. auto& queued_event = events.at(i);
  345. auto receiver = queued_event.receiver.strong_ref();
  346. auto& event = *queued_event.event;
  347. if (receiver)
  348. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: {} event {}", *receiver, event.type());
  349. if (!receiver) {
  350. switch (event.type()) {
  351. case Event::Quit:
  352. VERIFY_NOT_REACHED();
  353. return;
  354. default:
  355. dbgln_if(EVENTLOOP_DEBUG, "Event type {} with no receiver :(", event.type());
  356. break;
  357. }
  358. } else if (event.type() == Event::Type::DeferredInvoke) {
  359. dbgln_if(DEFERRED_INVOKE_DEBUG, "DeferredInvoke: receiver = {}", *receiver);
  360. static_cast<DeferredInvocationEvent&>(event).m_invokee();
  361. } else {
  362. NonnullRefPtr<Object> protector(*receiver);
  363. receiver->dispatch_event(event);
  364. }
  365. if (m_exit_requested) {
  366. Threading::MutexLocker locker(m_private->lock);
  367. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Exit requested. Rejigging {} events.", events.size() - i);
  368. decltype(m_queued_events) new_event_queue;
  369. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  370. for (++i; i < events.size(); ++i)
  371. new_event_queue.unchecked_append(move(events[i]));
  372. new_event_queue.extend(move(m_queued_events));
  373. m_queued_events = move(new_event_queue);
  374. return;
  375. }
  376. }
  377. }
  378. void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
  379. {
  380. Threading::MutexLocker lock(m_private->lock);
  381. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::post_event: ({}) << receivier={}, event={}", m_queued_events.size(), receiver, event);
  382. m_queued_events.empend(receiver, move(event));
  383. }
  384. SignalHandlers::SignalHandlers(int signo, void (*handle_signal)(int))
  385. : m_signo(signo)
  386. , m_original_handler(signal(signo, handle_signal))
  387. {
  388. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Registered handler for signal {}", m_signo);
  389. }
  390. SignalHandlers::~SignalHandlers()
  391. {
  392. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Unregistering handler for signal {}", m_signo);
  393. signal(m_signo, m_original_handler);
  394. }
  395. void SignalHandlers::dispatch()
  396. {
  397. TemporaryChange change(m_calling_handlers, true);
  398. for (auto& handler : m_handlers)
  399. handler.value(m_signo);
  400. if (!m_handlers_pending.is_empty()) {
  401. // Apply pending adds/removes
  402. for (auto& handler : m_handlers_pending) {
  403. if (handler.value) {
  404. auto result = m_handlers.set(handler.key, move(handler.value));
  405. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  406. } else {
  407. m_handlers.remove(handler.key);
  408. }
  409. }
  410. m_handlers_pending.clear();
  411. }
  412. }
  413. int SignalHandlers::add(Function<void(int)>&& handler)
  414. {
  415. int id = ++signals_info()->next_signal_id; // TODO: worry about wrapping and duplicates?
  416. if (m_calling_handlers)
  417. m_handlers_pending.set(id, move(handler));
  418. else
  419. m_handlers.set(id, move(handler));
  420. return id;
  421. }
  422. bool SignalHandlers::remove(int handler_id)
  423. {
  424. VERIFY(handler_id != 0);
  425. if (m_calling_handlers) {
  426. auto it = m_handlers.find(handler_id);
  427. if (it != m_handlers.end()) {
  428. // Mark pending remove
  429. m_handlers_pending.set(handler_id, {});
  430. return true;
  431. }
  432. it = m_handlers_pending.find(handler_id);
  433. if (it != m_handlers_pending.end()) {
  434. if (!it->value)
  435. return false; // already was marked as deleted
  436. it->value = nullptr;
  437. return true;
  438. }
  439. return false;
  440. }
  441. return m_handlers.remove(handler_id);
  442. }
  443. void EventLoop::dispatch_signal(int signo)
  444. {
  445. auto& info = *signals_info();
  446. auto handlers = info.signal_handlers.find(signo);
  447. if (handlers != info.signal_handlers.end()) {
  448. // Make sure we bump the ref count while dispatching the handlers!
  449. // This allows a handler to unregister/register while the handlers
  450. // are being called!
  451. auto handler = handlers->value;
  452. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: dispatching signal {}", signo);
  453. handler->dispatch();
  454. }
  455. }
  456. void EventLoop::handle_signal(int signo)
  457. {
  458. VERIFY(signo != 0);
  459. // We MUST check if the current pid still matches, because there
  460. // is a window between fork() and exec() where a signal delivered
  461. // to our fork could be inadvertedly routed to the parent process!
  462. if (getpid() == s_pid) {
  463. int nwritten = write(s_wake_pipe_fds[1], &signo, sizeof(signo));
  464. if (nwritten < 0) {
  465. perror("EventLoop::register_signal: write");
  466. VERIFY_NOT_REACHED();
  467. }
  468. } else {
  469. // We're a fork who received a signal, reset s_pid
  470. s_pid = 0;
  471. }
  472. }
  473. int EventLoop::register_signal(int signo, Function<void(int)> handler)
  474. {
  475. VERIFY(signo != 0);
  476. auto& info = *signals_info();
  477. auto handlers = info.signal_handlers.find(signo);
  478. if (handlers == info.signal_handlers.end()) {
  479. auto signal_handlers = adopt_ref(*new SignalHandlers(signo, EventLoop::handle_signal));
  480. auto handler_id = signal_handlers->add(move(handler));
  481. info.signal_handlers.set(signo, move(signal_handlers));
  482. return handler_id;
  483. } else {
  484. return handlers->value->add(move(handler));
  485. }
  486. }
  487. void EventLoop::unregister_signal(int handler_id)
  488. {
  489. VERIFY(handler_id != 0);
  490. int remove_signo = 0;
  491. auto& info = *signals_info();
  492. for (auto& h : info.signal_handlers) {
  493. auto& handlers = *h.value;
  494. if (handlers.remove(handler_id)) {
  495. if (handlers.is_empty())
  496. remove_signo = handlers.m_signo;
  497. break;
  498. }
  499. }
  500. if (remove_signo != 0)
  501. info.signal_handlers.remove(remove_signo);
  502. }
  503. void EventLoop::notify_forked(ForkEvent event)
  504. {
  505. switch (event) {
  506. case ForkEvent::Child:
  507. s_main_event_loop = nullptr;
  508. s_event_loop_stack->clear();
  509. s_timers->clear();
  510. s_notifiers->clear();
  511. if (auto* info = signals_info<false>()) {
  512. info->signal_handlers.clear();
  513. info->next_signal_id = 0;
  514. }
  515. s_pid = 0;
  516. #ifdef __serenity__
  517. s_inspector_server_connection = nullptr;
  518. #endif
  519. return;
  520. }
  521. VERIFY_NOT_REACHED();
  522. }
  523. void EventLoop::wait_for_event(WaitMode mode)
  524. {
  525. fd_set rfds;
  526. fd_set wfds;
  527. retry:
  528. FD_ZERO(&rfds);
  529. FD_ZERO(&wfds);
  530. int max_fd = 0;
  531. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  532. FD_SET(fd, &set);
  533. if (fd > max_fd)
  534. max_fd = fd;
  535. };
  536. int max_fd_added = -1;
  537. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  538. max_fd = max(max_fd, max_fd_added);
  539. for (auto& notifier : *s_notifiers) {
  540. if (notifier->event_mask() & Notifier::Read)
  541. add_fd_to_set(notifier->fd(), rfds);
  542. if (notifier->event_mask() & Notifier::Write)
  543. add_fd_to_set(notifier->fd(), wfds);
  544. if (notifier->event_mask() & Notifier::Exceptional)
  545. VERIFY_NOT_REACHED();
  546. }
  547. bool queued_events_is_empty;
  548. {
  549. Threading::MutexLocker locker(m_private->lock);
  550. queued_events_is_empty = m_queued_events.is_empty();
  551. }
  552. Time now;
  553. struct timeval timeout = { 0, 0 };
  554. bool should_wait_forever = false;
  555. if (mode == WaitMode::WaitForEvents && queued_events_is_empty) {
  556. auto next_timer_expiration = get_next_timer_expiration();
  557. if (next_timer_expiration.has_value()) {
  558. now = Time::now_monotonic_coarse();
  559. auto computed_timeout = next_timer_expiration.value() - now;
  560. if (computed_timeout.is_negative())
  561. computed_timeout = Time::zero();
  562. timeout = computed_timeout.to_timeval();
  563. } else {
  564. should_wait_forever = true;
  565. }
  566. }
  567. try_select_again:
  568. int marked_fd_count = select(max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  569. if (marked_fd_count < 0) {
  570. int saved_errno = errno;
  571. if (saved_errno == EINTR) {
  572. if (m_exit_requested)
  573. return;
  574. goto try_select_again;
  575. }
  576. dbgln("Core::EventLoop::wait_for_event: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  577. VERIFY_NOT_REACHED();
  578. }
  579. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  580. int wake_events[8];
  581. auto nread = read(s_wake_pipe_fds[0], wake_events, sizeof(wake_events));
  582. if (nread < 0) {
  583. perror("read from wake pipe");
  584. VERIFY_NOT_REACHED();
  585. }
  586. VERIFY(nread > 0);
  587. bool wake_requested = false;
  588. int event_count = nread / sizeof(wake_events[0]);
  589. for (int i = 0; i < event_count; i++) {
  590. if (wake_events[i] != 0)
  591. dispatch_signal(wake_events[i]);
  592. else
  593. wake_requested = true;
  594. }
  595. if (!wake_requested && nread == sizeof(wake_events))
  596. goto retry;
  597. }
  598. if (!s_timers->is_empty()) {
  599. now = Time::now_monotonic_coarse();
  600. }
  601. for (auto& it : *s_timers) {
  602. auto& timer = *it.value;
  603. if (!timer.has_expired(now))
  604. continue;
  605. auto owner = timer.owner.strong_ref();
  606. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  607. && owner && !owner->is_visible_for_timer_purposes()) {
  608. continue;
  609. }
  610. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Timer {} has expired, sending Core::TimerEvent to {}", timer.timer_id, *owner);
  611. if (owner)
  612. post_event(*owner, make<TimerEvent>(timer.timer_id));
  613. if (timer.should_reload) {
  614. timer.reload(now);
  615. } else {
  616. // FIXME: Support removing expired timers that don't want to reload.
  617. VERIFY_NOT_REACHED();
  618. }
  619. }
  620. if (!marked_fd_count)
  621. return;
  622. for (auto& notifier : *s_notifiers) {
  623. if (FD_ISSET(notifier->fd(), &rfds)) {
  624. if (notifier->event_mask() & Notifier::Event::Read)
  625. post_event(*notifier, make<NotifierReadEvent>(notifier->fd()));
  626. }
  627. if (FD_ISSET(notifier->fd(), &wfds)) {
  628. if (notifier->event_mask() & Notifier::Event::Write)
  629. post_event(*notifier, make<NotifierWriteEvent>(notifier->fd()));
  630. }
  631. }
  632. }
  633. bool EventLoopTimer::has_expired(const Time& now) const
  634. {
  635. return now > fire_time;
  636. }
  637. void EventLoopTimer::reload(const Time& now)
  638. {
  639. fire_time = now + interval;
  640. }
  641. Optional<Time> EventLoop::get_next_timer_expiration()
  642. {
  643. Optional<Time> soonest {};
  644. for (auto& it : *s_timers) {
  645. auto& fire_time = it.value->fire_time;
  646. auto owner = it.value->owner.strong_ref();
  647. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  648. && owner && !owner->is_visible_for_timer_purposes()) {
  649. continue;
  650. }
  651. if (!soonest.has_value() || fire_time < soonest.value())
  652. soonest = fire_time;
  653. }
  654. return soonest;
  655. }
  656. int EventLoop::register_timer(Object& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  657. {
  658. VERIFY(milliseconds >= 0);
  659. auto timer = make<EventLoopTimer>();
  660. timer->owner = object;
  661. timer->interval = Time::from_milliseconds(milliseconds);
  662. timer->reload(Time::now_monotonic_coarse());
  663. timer->should_reload = should_reload;
  664. timer->fire_when_not_visible = fire_when_not_visible;
  665. int timer_id = s_id_allocator->allocate();
  666. timer->timer_id = timer_id;
  667. s_timers->set(timer_id, move(timer));
  668. return timer_id;
  669. }
  670. bool EventLoop::unregister_timer(int timer_id)
  671. {
  672. s_id_allocator->deallocate(timer_id);
  673. auto it = s_timers->find(timer_id);
  674. if (it == s_timers->end())
  675. return false;
  676. s_timers->remove(it);
  677. return true;
  678. }
  679. void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
  680. {
  681. s_notifiers->set(&notifier);
  682. }
  683. void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
  684. {
  685. s_notifiers->remove(&notifier);
  686. }
  687. void EventLoop::wake()
  688. {
  689. int wake_event = 0;
  690. int nwritten = write(s_wake_pipe_fds[1], &wake_event, sizeof(wake_event));
  691. if (nwritten < 0) {
  692. perror("EventLoop::wake: write");
  693. VERIFY_NOT_REACHED();
  694. }
  695. }
  696. EventLoop::QueuedEvent::QueuedEvent(Object& receiver, NonnullOwnPtr<Event> event)
  697. : receiver(receiver)
  698. , event(move(event))
  699. {
  700. }
  701. EventLoop::QueuedEvent::QueuedEvent(QueuedEvent&& other)
  702. : receiver(other.receiver)
  703. , event(move(other.event))
  704. {
  705. }
  706. EventLoop::QueuedEvent::~QueuedEvent()
  707. {
  708. }
  709. }