EventLoop.cpp 23 KB

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