EventLoop.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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 <LibThread/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 RPCClient;
  38. struct EventLoopTimer {
  39. int timer_id { 0 };
  40. int interval { 0 };
  41. timeval fire_time { 0, 0 };
  42. bool should_reload { false };
  43. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  44. WeakPtr<Object> owner;
  45. void reload(const timeval& now);
  46. bool has_expired(const timeval& now) const;
  47. };
  48. struct EventLoop::Private {
  49. LibThread::Lock lock;
  50. };
  51. static EventLoop* s_main_event_loop;
  52. static Vector<EventLoop*>* s_event_loop_stack;
  53. static NeverDestroyed<IDAllocator> s_id_allocator;
  54. static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
  55. static HashTable<Notifier*>* s_notifiers;
  56. int EventLoop::s_wake_pipe_fds[2];
  57. static RefPtr<LocalServer> s_rpc_server;
  58. HashMap<int, RefPtr<RPCClient>> s_rpc_clients;
  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. template<bool create_if_null = true>
  100. inline SignalHandlersInfo* signals_info()
  101. {
  102. static SignalHandlersInfo* s_signals;
  103. return AK::Singleton<SignalHandlersInfo>::get(s_signals);
  104. }
  105. pid_t EventLoop::s_pid;
  106. class RPCClient : public Object {
  107. C_OBJECT(RPCClient)
  108. public:
  109. explicit RPCClient(RefPtr<LocalSocket> socket)
  110. : m_socket(move(socket))
  111. , m_client_id(s_id_allocator->allocate())
  112. {
  113. #ifdef __serenity__
  114. s_rpc_clients.set(m_client_id, this);
  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 ~RPCClient() 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_rpc_clients.remove(m_client_id);
  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()
  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 (!s_rpc_server) {
  249. if (!start_rpc_server())
  250. dbgln("Core::EventLoop: Failed to start an RPC server");
  251. }
  252. #endif
  253. }
  254. dbgln_if(EVENTLOOP_DEBUG, "{} Core::EventLoop constructed :)", getpid());
  255. }
  256. EventLoop::~EventLoop()
  257. {
  258. }
  259. bool EventLoop::start_rpc_server()
  260. {
  261. #ifdef __serenity__
  262. s_rpc_server = LocalServer::construct();
  263. s_rpc_server->set_name("Core::EventLoop_RPC_server");
  264. s_rpc_server->on_ready_to_accept = [&] {
  265. RPCClient::construct(s_rpc_server->accept());
  266. };
  267. return s_rpc_server->listen(String::formatted("/tmp/rpc/{}", getpid()));
  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. EventLoop* event_loop = s_event_loop_stack->last();
  280. VERIFY(event_loop != nullptr);
  281. return *event_loop;
  282. }
  283. void EventLoop::quit(int code)
  284. {
  285. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::quit({})", code);
  286. m_exit_requested = true;
  287. m_exit_code = code;
  288. }
  289. void EventLoop::unquit()
  290. {
  291. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::unquit()");
  292. m_exit_requested = false;
  293. m_exit_code = 0;
  294. }
  295. struct EventLoopPusher {
  296. public:
  297. EventLoopPusher(EventLoop& event_loop)
  298. : m_event_loop(event_loop)
  299. {
  300. if (&m_event_loop != s_main_event_loop) {
  301. m_event_loop.take_pending_events_from(EventLoop::current());
  302. s_event_loop_stack->append(&event_loop);
  303. }
  304. }
  305. ~EventLoopPusher()
  306. {
  307. if (&m_event_loop != s_main_event_loop) {
  308. s_event_loop_stack->take_last();
  309. EventLoop::current().take_pending_events_from(m_event_loop);
  310. }
  311. }
  312. private:
  313. EventLoop& m_event_loop;
  314. };
  315. int EventLoop::exec()
  316. {
  317. EventLoopPusher pusher(*this);
  318. for (;;) {
  319. if (m_exit_requested)
  320. return m_exit_code;
  321. pump();
  322. }
  323. VERIFY_NOT_REACHED();
  324. }
  325. void EventLoop::pump(WaitMode mode)
  326. {
  327. wait_for_event(mode);
  328. decltype(m_queued_events) events;
  329. {
  330. LOCKER(m_private->lock);
  331. events = move(m_queued_events);
  332. }
  333. for (size_t i = 0; i < events.size(); ++i) {
  334. auto& queued_event = events.at(i);
  335. auto receiver = queued_event.receiver.strong_ref();
  336. auto& event = *queued_event.event;
  337. if (receiver)
  338. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: {} event {}", *receiver, event.type());
  339. if (!receiver) {
  340. switch (event.type()) {
  341. case Event::Quit:
  342. VERIFY_NOT_REACHED();
  343. return;
  344. default:
  345. dbgln_if(EVENTLOOP_DEBUG, "Event type {} with no receiver :(", event.type());
  346. break;
  347. }
  348. } else if (event.type() == Event::Type::DeferredInvoke) {
  349. dbgln_if(DEFERRED_INVOKE_DEBUG, "DeferredInvoke: receiver = {}", *receiver);
  350. static_cast<DeferredInvocationEvent&>(event).m_invokee(*receiver);
  351. } else {
  352. NonnullRefPtr<Object> protector(*receiver);
  353. receiver->dispatch_event(event);
  354. }
  355. if (m_exit_requested) {
  356. LOCKER(m_private->lock);
  357. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Exit requested. Rejigging {} events.", events.size() - i);
  358. decltype(m_queued_events) new_event_queue;
  359. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  360. for (++i; i < events.size(); ++i)
  361. new_event_queue.unchecked_append(move(events[i]));
  362. new_event_queue.append(move(m_queued_events));
  363. m_queued_events = move(new_event_queue);
  364. return;
  365. }
  366. }
  367. }
  368. void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
  369. {
  370. LOCKER(m_private->lock);
  371. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::post_event: ({}) << receivier={}, event={}", m_queued_events.size(), receiver, event);
  372. m_queued_events.empend(receiver, move(event));
  373. }
  374. SignalHandlers::SignalHandlers(int signo, void (*handle_signal)(int))
  375. : m_signo(signo)
  376. , m_original_handler(signal(signo, handle_signal))
  377. {
  378. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Registered handler for signal {}", m_signo);
  379. }
  380. SignalHandlers::~SignalHandlers()
  381. {
  382. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Unregistering handler for signal {}", m_signo);
  383. signal(m_signo, m_original_handler);
  384. }
  385. void SignalHandlers::dispatch()
  386. {
  387. TemporaryChange change(m_calling_handlers, true);
  388. for (auto& handler : m_handlers)
  389. handler.value(m_signo);
  390. if (!m_handlers_pending.is_empty()) {
  391. // Apply pending adds/removes
  392. for (auto& handler : m_handlers_pending) {
  393. if (handler.value) {
  394. auto result = m_handlers.set(handler.key, move(handler.value));
  395. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  396. } else {
  397. m_handlers.remove(handler.key);
  398. }
  399. }
  400. m_handlers_pending.clear();
  401. }
  402. }
  403. int SignalHandlers::add(Function<void(int)>&& handler)
  404. {
  405. int id = ++signals_info()->next_signal_id; // TODO: worry about wrapping and duplicates?
  406. if (m_calling_handlers)
  407. m_handlers_pending.set(id, move(handler));
  408. else
  409. m_handlers.set(id, move(handler));
  410. return id;
  411. }
  412. bool SignalHandlers::remove(int handler_id)
  413. {
  414. VERIFY(handler_id != 0);
  415. if (m_calling_handlers) {
  416. auto it = m_handlers.find(handler_id);
  417. if (it != m_handlers.end()) {
  418. // Mark pending remove
  419. m_handlers_pending.set(handler_id, {});
  420. return true;
  421. }
  422. it = m_handlers_pending.find(handler_id);
  423. if (it != m_handlers_pending.end()) {
  424. if (!it->value)
  425. return false; // already was marked as deleted
  426. it->value = nullptr;
  427. return true;
  428. }
  429. return false;
  430. }
  431. return m_handlers.remove(handler_id);
  432. }
  433. void EventLoop::dispatch_signal(int signo)
  434. {
  435. auto& info = *signals_info();
  436. auto handlers = info.signal_handlers.find(signo);
  437. if (handlers != info.signal_handlers.end()) {
  438. // Make sure we bump the ref count while dispatching the handlers!
  439. // This allows a handler to unregister/register while the handlers
  440. // are being called!
  441. auto handler = handlers->value;
  442. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: dispatching signal {}", signo);
  443. handler->dispatch();
  444. }
  445. }
  446. void EventLoop::handle_signal(int signo)
  447. {
  448. VERIFY(signo != 0);
  449. // We MUST check if the current pid still matches, because there
  450. // is a window between fork() and exec() where a signal delivered
  451. // to our fork could be inadvertedly routed to the parent process!
  452. if (getpid() == s_pid) {
  453. int nwritten = write(s_wake_pipe_fds[1], &signo, sizeof(signo));
  454. if (nwritten < 0) {
  455. perror("EventLoop::register_signal: write");
  456. VERIFY_NOT_REACHED();
  457. }
  458. } else {
  459. // We're a fork who received a signal, reset s_pid
  460. s_pid = 0;
  461. }
  462. }
  463. int EventLoop::register_signal(int signo, Function<void(int)> handler)
  464. {
  465. VERIFY(signo != 0);
  466. auto& info = *signals_info();
  467. auto handlers = info.signal_handlers.find(signo);
  468. if (handlers == info.signal_handlers.end()) {
  469. auto signal_handlers = adopt_ref(*new SignalHandlers(signo, EventLoop::handle_signal));
  470. auto handler_id = signal_handlers->add(move(handler));
  471. info.signal_handlers.set(signo, move(signal_handlers));
  472. return handler_id;
  473. } else {
  474. return handlers->value->add(move(handler));
  475. }
  476. }
  477. void EventLoop::unregister_signal(int handler_id)
  478. {
  479. VERIFY(handler_id != 0);
  480. int remove_signo = 0;
  481. auto& info = *signals_info();
  482. for (auto& h : info.signal_handlers) {
  483. auto& handlers = *h.value;
  484. if (handlers.remove(handler_id)) {
  485. if (handlers.is_empty())
  486. remove_signo = handlers.m_signo;
  487. break;
  488. }
  489. }
  490. if (remove_signo != 0)
  491. info.signal_handlers.remove(remove_signo);
  492. }
  493. void EventLoop::notify_forked(ForkEvent event)
  494. {
  495. switch (event) {
  496. case ForkEvent::Child:
  497. s_main_event_loop = nullptr;
  498. s_event_loop_stack->clear();
  499. s_timers->clear();
  500. s_notifiers->clear();
  501. if (auto* info = signals_info<false>()) {
  502. info->signal_handlers.clear();
  503. info->next_signal_id = 0;
  504. }
  505. s_pid = 0;
  506. #ifdef __serenity__
  507. s_rpc_server = nullptr;
  508. s_rpc_clients.clear();
  509. #endif
  510. return;
  511. }
  512. VERIFY_NOT_REACHED();
  513. }
  514. void EventLoop::wait_for_event(WaitMode mode)
  515. {
  516. fd_set rfds;
  517. fd_set wfds;
  518. retry:
  519. FD_ZERO(&rfds);
  520. FD_ZERO(&wfds);
  521. int max_fd = 0;
  522. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  523. FD_SET(fd, &set);
  524. if (fd > max_fd)
  525. max_fd = fd;
  526. };
  527. int max_fd_added = -1;
  528. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  529. max_fd = max(max_fd, max_fd_added);
  530. for (auto& notifier : *s_notifiers) {
  531. if (notifier->event_mask() & Notifier::Read)
  532. add_fd_to_set(notifier->fd(), rfds);
  533. if (notifier->event_mask() & Notifier::Write)
  534. add_fd_to_set(notifier->fd(), wfds);
  535. if (notifier->event_mask() & Notifier::Exceptional)
  536. VERIFY_NOT_REACHED();
  537. }
  538. bool queued_events_is_empty;
  539. {
  540. LOCKER(m_private->lock);
  541. queued_events_is_empty = m_queued_events.is_empty();
  542. }
  543. timeval now;
  544. struct timeval timeout = { 0, 0 };
  545. bool should_wait_forever = false;
  546. if (mode == WaitMode::WaitForEvents && queued_events_is_empty) {
  547. auto next_timer_expiration = get_next_timer_expiration();
  548. if (next_timer_expiration.has_value()) {
  549. timespec now_spec;
  550. clock_gettime(CLOCK_MONOTONIC_COARSE, &now_spec);
  551. now.tv_sec = now_spec.tv_sec;
  552. now.tv_usec = now_spec.tv_nsec / 1000;
  553. timeval_sub(next_timer_expiration.value(), now, timeout);
  554. if (timeout.tv_sec < 0 || (timeout.tv_sec == 0 && timeout.tv_usec < 0)) {
  555. timeout.tv_sec = 0;
  556. timeout.tv_usec = 0;
  557. }
  558. } else {
  559. should_wait_forever = true;
  560. }
  561. }
  562. try_select_again:
  563. int marked_fd_count = select(max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  564. if (marked_fd_count < 0) {
  565. int saved_errno = errno;
  566. if (saved_errno == EINTR) {
  567. if (m_exit_requested)
  568. return;
  569. goto try_select_again;
  570. }
  571. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop::wait_for_event: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  572. VERIFY_NOT_REACHED();
  573. }
  574. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  575. int wake_events[8];
  576. auto nread = read(s_wake_pipe_fds[0], wake_events, sizeof(wake_events));
  577. if (nread < 0) {
  578. perror("read from wake pipe");
  579. VERIFY_NOT_REACHED();
  580. }
  581. VERIFY(nread > 0);
  582. bool wake_requested = false;
  583. int event_count = nread / sizeof(wake_events[0]);
  584. for (int i = 0; i < event_count; i++) {
  585. if (wake_events[i] != 0)
  586. dispatch_signal(wake_events[i]);
  587. else
  588. wake_requested = true;
  589. }
  590. if (!wake_requested && nread == sizeof(wake_events))
  591. goto retry;
  592. }
  593. if (!s_timers->is_empty()) {
  594. timespec now_spec;
  595. clock_gettime(CLOCK_MONOTONIC_COARSE, &now_spec);
  596. now.tv_sec = now_spec.tv_sec;
  597. now.tv_usec = now_spec.tv_nsec / 1000;
  598. }
  599. for (auto& it : *s_timers) {
  600. auto& timer = *it.value;
  601. if (!timer.has_expired(now))
  602. continue;
  603. auto owner = timer.owner.strong_ref();
  604. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  605. && owner && !owner->is_visible_for_timer_purposes()) {
  606. continue;
  607. }
  608. dbgln_if(EVENTLOOP_DEBUG, "Core::EventLoop: Timer {} has expired, sending Core::TimerEvent to {}", timer.timer_id, *owner);
  609. if (owner)
  610. post_event(*owner, make<TimerEvent>(timer.timer_id));
  611. if (timer.should_reload) {
  612. timer.reload(now);
  613. } else {
  614. // FIXME: Support removing expired timers that don't want to reload.
  615. VERIFY_NOT_REACHED();
  616. }
  617. }
  618. if (!marked_fd_count)
  619. return;
  620. for (auto& notifier : *s_notifiers) {
  621. if (FD_ISSET(notifier->fd(), &rfds)) {
  622. if (notifier->event_mask() & Notifier::Event::Read)
  623. post_event(*notifier, make<NotifierReadEvent>(notifier->fd()));
  624. }
  625. if (FD_ISSET(notifier->fd(), &wfds)) {
  626. if (notifier->event_mask() & Notifier::Event::Write)
  627. post_event(*notifier, make<NotifierWriteEvent>(notifier->fd()));
  628. }
  629. }
  630. }
  631. bool EventLoopTimer::has_expired(const timeval& now) const
  632. {
  633. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  634. }
  635. void EventLoopTimer::reload(const timeval& now)
  636. {
  637. fire_time = now;
  638. fire_time.tv_sec += interval / 1000;
  639. fire_time.tv_usec += (interval % 1000) * 1000;
  640. }
  641. Optional<struct timeval> EventLoop::get_next_timer_expiration()
  642. {
  643. Optional<struct timeval> 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.tv_sec < soonest.value().tv_sec || (fire_time.tv_sec == soonest.value().tv_sec && fire_time.tv_usec < soonest.value().tv_usec))
  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 = milliseconds;
  662. timeval now;
  663. timespec now_spec;
  664. clock_gettime(CLOCK_MONOTONIC_COARSE, &now_spec);
  665. now.tv_sec = now_spec.tv_sec;
  666. now.tv_usec = now_spec.tv_nsec / 1000;
  667. timer->reload(now);
  668. timer->should_reload = should_reload;
  669. timer->fire_when_not_visible = fire_when_not_visible;
  670. int timer_id = s_id_allocator->allocate();
  671. timer->timer_id = timer_id;
  672. s_timers->set(timer_id, move(timer));
  673. return timer_id;
  674. }
  675. bool EventLoop::unregister_timer(int timer_id)
  676. {
  677. s_id_allocator->deallocate(timer_id);
  678. auto it = s_timers->find(timer_id);
  679. if (it == s_timers->end())
  680. return false;
  681. s_timers->remove(it);
  682. return true;
  683. }
  684. void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
  685. {
  686. s_notifiers->set(&notifier);
  687. }
  688. void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
  689. {
  690. s_notifiers->remove(&notifier);
  691. }
  692. void EventLoop::wake()
  693. {
  694. int wake_event = 0;
  695. int nwritten = write(s_wake_pipe_fds[1], &wake_event, sizeof(wake_event));
  696. if (nwritten < 0) {
  697. perror("EventLoop::wake: write");
  698. VERIFY_NOT_REACHED();
  699. }
  700. }
  701. EventLoop::QueuedEvent::QueuedEvent(Object& receiver, NonnullOwnPtr<Event> event)
  702. : receiver(receiver)
  703. , event(move(event))
  704. {
  705. }
  706. EventLoop::QueuedEvent::QueuedEvent(QueuedEvent&& other)
  707. : receiver(other.receiver)
  708. , event(move(other.event))
  709. {
  710. }
  711. EventLoop::QueuedEvent::~QueuedEvent()
  712. {
  713. }
  714. }