EventLoop.cpp 30 KB

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