EventLoop.cpp 23 KB

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