EventLoop.cpp 29 KB

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