EventLoop.cpp 29 KB

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