EventLoop.cpp 23 KB

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