EventLoop.cpp 27 KB

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