EventLoop.cpp 25 KB

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