EventLoop.cpp 31 KB

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