EventLoop.cpp 26 KB

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