EventLoop.cpp 25 KB

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