EventLoop.cpp 24 KB

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