EventLoop.cpp 25 KB

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