EventLoop.cpp 30 KB

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