EventLoop.cpp 27 KB

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