EventLoop.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Badge.h>
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/IDAllocator.h>
  29. #include <AK/JsonObject.h>
  30. #include <AK/JsonValue.h>
  31. #include <AK/NeverDestroyed.h>
  32. #include <AK/TemporaryChange.h>
  33. #include <AK/Time.h>
  34. #include <LibCore/Event.h>
  35. #include <LibCore/EventLoop.h>
  36. #include <LibCore/LocalServer.h>
  37. #include <LibCore/LocalSocket.h>
  38. #include <LibCore/Notifier.h>
  39. #include <LibCore/Object.h>
  40. #include <LibCore/SyscallUtils.h>
  41. #include <LibThread/Lock.h>
  42. #include <errno.h>
  43. #include <fcntl.h>
  44. #include <signal.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <sys/select.h>
  49. #include <sys/socket.h>
  50. #include <sys/stat.h>
  51. #include <sys/time.h>
  52. #include <time.h>
  53. #include <unistd.h>
  54. //#define EVENTLOOP_DEBUG
  55. //#define DEFERRED_INVOKE_DEBUG
  56. namespace Core {
  57. class RPCClient;
  58. struct EventLoopTimer {
  59. int timer_id { 0 };
  60. int interval { 0 };
  61. timeval fire_time { 0, 0 };
  62. bool should_reload { false };
  63. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  64. WeakPtr<Object> owner;
  65. void reload(const timeval& now);
  66. bool has_expired(const timeval& now) const;
  67. };
  68. struct EventLoop::Private {
  69. LibThread::Lock lock;
  70. };
  71. static EventLoop* s_main_event_loop;
  72. static Vector<EventLoop*>* s_event_loop_stack;
  73. static NeverDestroyed<IDAllocator> s_id_allocator;
  74. static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
  75. static HashTable<Notifier*>* s_notifiers;
  76. int EventLoop::s_wake_pipe_fds[2];
  77. HashMap<int, EventLoop::SignalHandlers> EventLoop::s_signal_handlers;
  78. int EventLoop::s_handling_signal = 0;
  79. int EventLoop::s_next_signal_id = 0;
  80. pid_t EventLoop::s_pid;
  81. static RefPtr<LocalServer> s_rpc_server;
  82. HashMap<int, RefPtr<RPCClient>> s_rpc_clients;
  83. class RPCClient : public Object {
  84. C_OBJECT(RPCClient)
  85. public:
  86. explicit RPCClient(RefPtr<LocalSocket> socket)
  87. : m_socket(move(socket))
  88. , m_client_id(s_id_allocator->allocate())
  89. {
  90. s_rpc_clients.set(m_client_id, this);
  91. add_child(*m_socket);
  92. m_socket->on_ready_to_read = [this] {
  93. u32 length;
  94. int nread = m_socket->read((u8*)&length, sizeof(length));
  95. if (nread == 0) {
  96. #ifdef EVENTLOOP_DEBUG
  97. dbgln("RPC client disconnected");
  98. #endif
  99. shutdown();
  100. return;
  101. }
  102. ASSERT(nread == sizeof(length));
  103. auto request = m_socket->read(length);
  104. auto request_json = JsonValue::from_string(request);
  105. if (!request_json.has_value() || !request_json.value().is_object()) {
  106. dbgln("RPC client sent invalid request");
  107. shutdown();
  108. return;
  109. }
  110. handle_request(request_json.value().as_object());
  111. };
  112. }
  113. virtual ~RPCClient() override
  114. {
  115. if (auto inspected_object = m_inspected_object.strong_ref())
  116. inspected_object->decrement_inspector_count({});
  117. }
  118. void send_response(const JsonObject& response)
  119. {
  120. auto serialized = response.to_string();
  121. u32 length = serialized.length();
  122. m_socket->write((const u8*)&length, sizeof(length));
  123. m_socket->write(serialized);
  124. }
  125. void handle_request(const JsonObject& request)
  126. {
  127. auto type = request.get("type").as_string_or({});
  128. if (type.is_null()) {
  129. dbgln("RPC client sent request without type field");
  130. return;
  131. }
  132. if (type == "Identify") {
  133. JsonObject response;
  134. response.set("type", type);
  135. response.set("pid", getpid());
  136. #ifdef __serenity__
  137. char buffer[1024];
  138. if (get_process_name(buffer, sizeof(buffer)) >= 0) {
  139. response.set("process_name", buffer);
  140. } else {
  141. response.set("process_name", JsonValue());
  142. }
  143. #endif
  144. send_response(response);
  145. return;
  146. }
  147. if (type == "GetAllObjects") {
  148. JsonObject response;
  149. response.set("type", type);
  150. JsonArray objects;
  151. for (auto& object : Object::all_objects()) {
  152. JsonObject json_object;
  153. object.save_to(json_object);
  154. objects.append(move(json_object));
  155. }
  156. response.set("objects", move(objects));
  157. send_response(response);
  158. return;
  159. }
  160. if (type == "SetInspectedObject") {
  161. auto address = request.get("address").to_number<FlatPtr>();
  162. for (auto& object : Object::all_objects()) {
  163. if ((FlatPtr)&object == address) {
  164. if (auto inspected_object = m_inspected_object.strong_ref())
  165. inspected_object->decrement_inspector_count({});
  166. m_inspected_object = object;
  167. object.increment_inspector_count({});
  168. break;
  169. }
  170. }
  171. return;
  172. }
  173. if (type == "SetProperty") {
  174. auto address = request.get("address").to_number<FlatPtr>();
  175. for (auto& object : Object::all_objects()) {
  176. if ((FlatPtr)&object == address) {
  177. bool success = object.set_property(request.get("name").to_string(), request.get("value"));
  178. JsonObject response;
  179. response.set("type", "SetProperty");
  180. response.set("success", success);
  181. send_response(response);
  182. break;
  183. }
  184. }
  185. return;
  186. }
  187. if (type == "Disconnect") {
  188. shutdown();
  189. return;
  190. }
  191. }
  192. void shutdown()
  193. {
  194. s_rpc_clients.remove(m_client_id);
  195. s_id_allocator->deallocate(m_client_id);
  196. }
  197. private:
  198. RefPtr<LocalSocket> m_socket;
  199. WeakPtr<Object> m_inspected_object;
  200. int m_client_id { -1 };
  201. };
  202. EventLoop::EventLoop()
  203. : m_private(make<Private>())
  204. {
  205. if (!s_event_loop_stack) {
  206. s_event_loop_stack = new Vector<EventLoop*>;
  207. s_timers = new HashMap<int, NonnullOwnPtr<EventLoopTimer>>;
  208. s_notifiers = new HashTable<Notifier*>;
  209. }
  210. if (!s_main_event_loop) {
  211. s_main_event_loop = this;
  212. s_pid = getpid();
  213. #if defined(SOCK_NONBLOCK)
  214. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  215. #else
  216. int rc = pipe(s_wake_pipe_fds);
  217. fcntl(s_wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  218. fcntl(s_wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  219. #endif
  220. ASSERT(rc == 0);
  221. s_event_loop_stack->append(this);
  222. if (!s_rpc_server) {
  223. if (!start_rpc_server())
  224. dbgln("Core::EventLoop: Failed to start an RPC server");
  225. }
  226. }
  227. #ifdef EVENTLOOP_DEBUG
  228. dbgln("{} Core::EventLoop constructed :)", getpid());
  229. #endif
  230. }
  231. EventLoop::~EventLoop()
  232. {
  233. }
  234. bool EventLoop::start_rpc_server()
  235. {
  236. // Create /tmp/rpc if it doesn't exist.
  237. int rc = mkdir("/tmp/rpc", 0777);
  238. if (rc == 0) {
  239. // Ensure it gets created as 0777 despite our umask.
  240. rc = chmod("/tmp/rpc", 0777);
  241. if (rc < 0) {
  242. perror("chmod /tmp/rpc");
  243. // Continue further.
  244. }
  245. } else if (errno != EEXIST) {
  246. perror("mkdir /tmp/rpc");
  247. return false;
  248. }
  249. auto rpc_path = String::format("/tmp/rpc/%d", getpid());
  250. rc = unlink(rpc_path.characters());
  251. if (rc < 0 && errno != ENOENT) {
  252. perror("unlink");
  253. return false;
  254. }
  255. s_rpc_server = LocalServer::construct();
  256. s_rpc_server->set_name("Core::EventLoop_RPC_server");
  257. s_rpc_server->on_ready_to_accept = [&] {
  258. RPCClient::construct(s_rpc_server->accept());
  259. };
  260. return s_rpc_server->listen(rpc_path);
  261. }
  262. EventLoop& EventLoop::main()
  263. {
  264. ASSERT(s_main_event_loop);
  265. return *s_main_event_loop;
  266. }
  267. EventLoop& EventLoop::current()
  268. {
  269. EventLoop* event_loop = s_event_loop_stack->last();
  270. ASSERT(event_loop != nullptr);
  271. return *event_loop;
  272. }
  273. void EventLoop::quit(int code)
  274. {
  275. #ifdef EVENTLOOP_DEBUG
  276. dbgln("Core::EventLoop::quit({})", code);
  277. #endif
  278. m_exit_requested = true;
  279. m_exit_code = code;
  280. }
  281. void EventLoop::unquit()
  282. {
  283. #ifdef EVENTLOOP_DEBUG
  284. dbgln("Core::EventLoop::unquit()");
  285. #endif
  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. ASSERT_NOT_REACHED();
  318. }
  319. void EventLoop::pump(WaitMode mode)
  320. {
  321. wait_for_event(mode);
  322. decltype(m_queued_events) events;
  323. {
  324. 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. #ifdef EVENTLOOP_DEBUG
  332. if (receiver)
  333. dbgln("Core::EventLoop: {} event {}", *receiver, event.type());
  334. #endif
  335. if (!receiver) {
  336. switch (event.type()) {
  337. case Event::Quit:
  338. ASSERT_NOT_REACHED();
  339. return;
  340. default:
  341. #ifdef EVENTLOOP_DEBUG
  342. dbgln("Event type {} with no receiver :(", event.type());
  343. #endif
  344. break;
  345. }
  346. } else if (event.type() == Event::Type::DeferredInvoke) {
  347. #ifdef DEFERRED_INVOKE_DEBUG
  348. dbgln("DeferredInvoke: receiver = {}", *receiver);
  349. #endif
  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. #ifdef EVENTLOOP_DEBUG
  358. dbgln("Core::EventLoop: Exit requested. Rejigging {} events.", events.size() - i);
  359. #endif
  360. decltype(m_queued_events) new_event_queue;
  361. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  362. for (++i; i < events.size(); ++i)
  363. new_event_queue.unchecked_append(move(events[i]));
  364. new_event_queue.append(move(m_queued_events));
  365. m_queued_events = move(new_event_queue);
  366. return;
  367. }
  368. }
  369. }
  370. void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
  371. {
  372. LOCKER(m_private->lock);
  373. #ifdef EVENTLOOP_DEBUG
  374. dbgln("Core::EventLoop::post_event: ({}) << receivier={}, event={}", m_queued_events.size(), receiver, event);
  375. #endif
  376. m_queued_events.empend(receiver, move(event));
  377. }
  378. EventLoop::SignalHandlers::SignalHandlers(int signo)
  379. : m_signo(signo)
  380. , m_original_handler(signal(signo, EventLoop::handle_signal))
  381. {
  382. #ifdef EVENTLOOP_DEBUG
  383. dbgln("Core::EventLoop: Registered handler for signal {}", m_signo);
  384. #endif
  385. }
  386. EventLoop::SignalHandlers::~SignalHandlers()
  387. {
  388. if (m_valid) {
  389. #ifdef EVENTLOOP_DEBUG
  390. dbgln("Core::EventLoop: Unregistering handler for signal {}", m_signo);
  391. #endif
  392. signal(m_signo, m_original_handler);
  393. }
  394. }
  395. void EventLoop::SignalHandlers::dispatch()
  396. {
  397. for (auto& handler : m_handlers)
  398. handler.value(m_signo);
  399. }
  400. int EventLoop::SignalHandlers::add(Function<void(int)>&& handler)
  401. {
  402. int id = ++EventLoop::s_next_signal_id; // TODO: worry about wrapping and duplicates?
  403. m_handlers.set(id, move(handler));
  404. return id;
  405. }
  406. bool EventLoop::SignalHandlers::remove(int handler_id)
  407. {
  408. ASSERT(handler_id != 0);
  409. return m_handlers.remove(handler_id);
  410. }
  411. void EventLoop::dispatch_signal(int signo)
  412. {
  413. // We need to protect the handler from being removed while handling it
  414. TemporaryChange change(s_handling_signal, signo);
  415. auto handlers = s_signal_handlers.find(signo);
  416. if (handlers != s_signal_handlers.end()) {
  417. #ifdef EVENTLOOP_DEBUG
  418. dbgln("Core::EventLoop: dispatching signal {}", signo);
  419. #endif
  420. handlers->value.dispatch();
  421. }
  422. }
  423. void EventLoop::handle_signal(int signo)
  424. {
  425. ASSERT(signo != 0);
  426. // We MUST check if the current pid still matches, because there
  427. // is a window between fork() and exec() where a signal delivered
  428. // to our fork could be inadvertedly routed to the parent process!
  429. if (getpid() == s_pid) {
  430. int nwritten = write(s_wake_pipe_fds[1], &signo, sizeof(signo));
  431. if (nwritten < 0) {
  432. perror("EventLoop::register_signal: write");
  433. ASSERT_NOT_REACHED();
  434. }
  435. } else {
  436. // We're a fork who received a signal, reset s_pid
  437. s_pid = 0;
  438. }
  439. }
  440. int EventLoop::register_signal(int signo, Function<void(int)> handler)
  441. {
  442. ASSERT(signo != 0);
  443. ASSERT(s_handling_signal != signo); // can't register the same signal while handling it
  444. auto handlers = s_signal_handlers.find(signo);
  445. if (handlers == s_signal_handlers.end()) {
  446. SignalHandlers signal_handlers(signo);
  447. auto handler_id = signal_handlers.add(move(handler));
  448. s_signal_handlers.set(signo, move(signal_handlers));
  449. return handler_id;
  450. } else {
  451. return handlers->value.add(move(handler));
  452. }
  453. }
  454. void EventLoop::unregister_signal(int handler_id)
  455. {
  456. ASSERT(handler_id != 0);
  457. int remove_signo = 0;
  458. for (auto& h : s_signal_handlers) {
  459. auto& handlers = h.value;
  460. if (handlers.m_signo == s_handling_signal) {
  461. // can't remove the same signal while handling it
  462. ASSERT(!handlers.have(handler_id));
  463. } else if (handlers.remove(handler_id)) {
  464. if (handlers.is_empty())
  465. remove_signo = handlers.m_signo;
  466. break;
  467. }
  468. }
  469. if (remove_signo != 0)
  470. s_signal_handlers.remove(remove_signo);
  471. }
  472. void EventLoop::notify_forked(ForkEvent event)
  473. {
  474. switch (event) {
  475. case ForkEvent::Child:
  476. s_main_event_loop = nullptr;
  477. s_event_loop_stack->clear();
  478. s_timers->clear();
  479. s_notifiers->clear();
  480. s_signal_handlers.clear();
  481. s_handling_signal = 0;
  482. s_next_signal_id = 0;
  483. s_pid = 0;
  484. s_rpc_server = nullptr;
  485. s_rpc_clients.clear();
  486. return;
  487. }
  488. ASSERT_NOT_REACHED();
  489. }
  490. void EventLoop::wait_for_event(WaitMode mode)
  491. {
  492. fd_set rfds;
  493. fd_set wfds;
  494. retry:
  495. FD_ZERO(&rfds);
  496. FD_ZERO(&wfds);
  497. int max_fd = 0;
  498. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  499. FD_SET(fd, &set);
  500. if (fd > max_fd)
  501. max_fd = fd;
  502. };
  503. int max_fd_added = -1;
  504. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  505. max_fd = max(max_fd, max_fd_added);
  506. for (auto& notifier : *s_notifiers) {
  507. if (notifier->event_mask() & Notifier::Read)
  508. add_fd_to_set(notifier->fd(), rfds);
  509. if (notifier->event_mask() & Notifier::Write)
  510. add_fd_to_set(notifier->fd(), wfds);
  511. if (notifier->event_mask() & Notifier::Exceptional)
  512. ASSERT_NOT_REACHED();
  513. }
  514. bool queued_events_is_empty;
  515. {
  516. LOCKER(m_private->lock);
  517. queued_events_is_empty = m_queued_events.is_empty();
  518. }
  519. timeval now;
  520. struct timeval timeout = { 0, 0 };
  521. bool should_wait_forever = false;
  522. if (mode == WaitMode::WaitForEvents && queued_events_is_empty) {
  523. auto next_timer_expiration = get_next_timer_expiration();
  524. if (next_timer_expiration.has_value()) {
  525. timespec now_spec;
  526. clock_gettime(CLOCK_MONOTONIC, &now_spec);
  527. now.tv_sec = now_spec.tv_sec;
  528. now.tv_usec = now_spec.tv_nsec / 1000;
  529. timeval_sub(next_timer_expiration.value(), now, timeout);
  530. if (timeout.tv_sec < 0) {
  531. timeout.tv_sec = 0;
  532. timeout.tv_usec = 0;
  533. }
  534. } else {
  535. should_wait_forever = true;
  536. }
  537. }
  538. try_select_again:
  539. int marked_fd_count = select(max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  540. if (marked_fd_count < 0) {
  541. int saved_errno = errno;
  542. if (saved_errno == EINTR) {
  543. if (m_exit_requested)
  544. return;
  545. goto try_select_again;
  546. }
  547. #ifdef EVENTLOOP_DEBUG
  548. dbgln("Core::EventLoop::wait_for_event: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  549. #endif
  550. // Blow up, similar to Core::safe_syscall.
  551. ASSERT_NOT_REACHED();
  552. }
  553. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  554. int wake_events[8];
  555. auto nread = read(s_wake_pipe_fds[0], wake_events, sizeof(wake_events));
  556. if (nread < 0) {
  557. perror("read from wake pipe");
  558. ASSERT_NOT_REACHED();
  559. }
  560. ASSERT(nread > 0);
  561. bool wake_requested = false;
  562. int event_count = nread / sizeof(wake_events[0]);
  563. for (int i = 0; i < event_count; i++) {
  564. if (wake_events[i] != 0)
  565. dispatch_signal(wake_events[i]);
  566. else
  567. wake_requested = true;
  568. }
  569. if (!wake_requested && nread == sizeof(wake_events))
  570. goto retry;
  571. }
  572. if (!s_timers->is_empty()) {
  573. timespec now_spec;
  574. clock_gettime(CLOCK_MONOTONIC, &now_spec);
  575. now.tv_sec = now_spec.tv_sec;
  576. now.tv_usec = now_spec.tv_nsec / 1000;
  577. }
  578. for (auto& it : *s_timers) {
  579. auto& timer = *it.value;
  580. if (!timer.has_expired(now))
  581. continue;
  582. auto owner = timer.owner.strong_ref();
  583. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  584. && owner && !owner->is_visible_for_timer_purposes()) {
  585. continue;
  586. }
  587. #ifdef EVENTLOOP_DEBUG
  588. dbgln("Core::EventLoop: Timer {} has expired, sending Core::TimerEvent to {}", timer.timer_id, *owner);
  589. #endif
  590. if (owner)
  591. post_event(*owner, make<TimerEvent>(timer.timer_id));
  592. if (timer.should_reload) {
  593. timer.reload(now);
  594. } else {
  595. // FIXME: Support removing expired timers that don't want to reload.
  596. ASSERT_NOT_REACHED();
  597. }
  598. }
  599. if (!marked_fd_count)
  600. return;
  601. for (auto& notifier : *s_notifiers) {
  602. if (FD_ISSET(notifier->fd(), &rfds)) {
  603. if (notifier->event_mask() & Notifier::Event::Read)
  604. post_event(*notifier, make<NotifierReadEvent>(notifier->fd()));
  605. }
  606. if (FD_ISSET(notifier->fd(), &wfds)) {
  607. if (notifier->event_mask() & Notifier::Event::Write)
  608. post_event(*notifier, make<NotifierWriteEvent>(notifier->fd()));
  609. }
  610. }
  611. }
  612. bool EventLoopTimer::has_expired(const timeval& now) const
  613. {
  614. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  615. }
  616. void EventLoopTimer::reload(const timeval& now)
  617. {
  618. fire_time = now;
  619. fire_time.tv_sec += interval / 1000;
  620. fire_time.tv_usec += (interval % 1000) * 1000;
  621. }
  622. Optional<struct timeval> EventLoop::get_next_timer_expiration()
  623. {
  624. Optional<struct timeval> soonest {};
  625. for (auto& it : *s_timers) {
  626. auto& fire_time = it.value->fire_time;
  627. auto owner = it.value->owner.strong_ref();
  628. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  629. && owner && !owner->is_visible_for_timer_purposes()) {
  630. continue;
  631. }
  632. 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))
  633. soonest = fire_time;
  634. }
  635. return soonest;
  636. }
  637. int EventLoop::register_timer(Object& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  638. {
  639. ASSERT(milliseconds >= 0);
  640. auto timer = make<EventLoopTimer>();
  641. timer->owner = object;
  642. timer->interval = milliseconds;
  643. timeval now;
  644. timespec now_spec;
  645. clock_gettime(CLOCK_MONOTONIC, &now_spec);
  646. now.tv_sec = now_spec.tv_sec;
  647. now.tv_usec = now_spec.tv_nsec / 1000;
  648. timer->reload(now);
  649. timer->should_reload = should_reload;
  650. timer->fire_when_not_visible = fire_when_not_visible;
  651. int timer_id = s_id_allocator->allocate();
  652. timer->timer_id = timer_id;
  653. s_timers->set(timer_id, move(timer));
  654. return timer_id;
  655. }
  656. bool EventLoop::unregister_timer(int timer_id)
  657. {
  658. s_id_allocator->deallocate(timer_id);
  659. auto it = s_timers->find(timer_id);
  660. if (it == s_timers->end())
  661. return false;
  662. s_timers->remove(it);
  663. return true;
  664. }
  665. void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
  666. {
  667. s_notifiers->set(&notifier);
  668. }
  669. void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
  670. {
  671. s_notifiers->remove(&notifier);
  672. }
  673. void EventLoop::wake()
  674. {
  675. int wake_event = 0;
  676. int nwritten = write(s_wake_pipe_fds[1], &wake_event, sizeof(wake_event));
  677. if (nwritten < 0) {
  678. perror("EventLoop::wake: write");
  679. ASSERT_NOT_REACHED();
  680. }
  681. }
  682. EventLoop::QueuedEvent::QueuedEvent(Object& receiver, NonnullOwnPtr<Event> event)
  683. : receiver(receiver)
  684. , event(move(event))
  685. {
  686. }
  687. EventLoop::QueuedEvent::QueuedEvent(QueuedEvent&& other)
  688. : receiver(other.receiver)
  689. , event(move(other.event))
  690. {
  691. }
  692. EventLoop::QueuedEvent::~QueuedEvent()
  693. {
  694. }
  695. }