EventLoop.cpp 23 KB

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