EventLoop.cpp 23 KB

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