EventLoop.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Badge.h>
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/IDAllocator.h>
  29. #include <AK/JsonObject.h>
  30. #include <AK/JsonValue.h>
  31. #include <AK/NeverDestroyed.h>
  32. #include <AK/Singleton.h>
  33. #include <AK/TemporaryChange.h>
  34. #include <AK/Time.h>
  35. #include <LibCore/Event.h>
  36. #include <LibCore/EventLoop.h>
  37. #include <LibCore/LocalServer.h>
  38. #include <LibCore/LocalSocket.h>
  39. #include <LibCore/Notifier.h>
  40. #include <LibCore/Object.h>
  41. #include <LibCore/SyscallUtils.h>
  42. #include <LibThread/Lock.h>
  43. #include <errno.h>
  44. #include <fcntl.h>
  45. #include <signal.h>
  46. #include <stdio.h>
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <sys/select.h>
  50. #include <sys/socket.h>
  51. #include <sys/stat.h>
  52. #include <sys/time.h>
  53. #include <time.h>
  54. #include <unistd.h>
  55. //#define EVENTLOOP_DEBUG
  56. //#define DEFERRED_INVOKE_DEBUG
  57. namespace Core {
  58. class RPCClient;
  59. struct EventLoopTimer {
  60. int timer_id { 0 };
  61. int interval { 0 };
  62. timeval fire_time { 0, 0 };
  63. bool should_reload { false };
  64. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  65. WeakPtr<Object> owner;
  66. void reload(const timeval& now);
  67. bool has_expired(const timeval& now) const;
  68. };
  69. struct EventLoop::Private {
  70. LibThread::Lock lock;
  71. };
  72. static EventLoop* s_main_event_loop;
  73. static Vector<EventLoop*>* s_event_loop_stack;
  74. static NeverDestroyed<IDAllocator> s_id_allocator;
  75. static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
  76. static HashTable<Notifier*>* s_notifiers;
  77. int EventLoop::s_wake_pipe_fds[2];
  78. static RefPtr<LocalServer> s_rpc_server;
  79. HashMap<int, RefPtr<RPCClient>> s_rpc_clients;
  80. class SignalHandlers : public RefCounted<SignalHandlers> {
  81. AK_MAKE_NONCOPYABLE(SignalHandlers);
  82. AK_MAKE_NONMOVABLE(SignalHandlers);
  83. public:
  84. SignalHandlers(int signo, void (*handle_signal)(int));
  85. ~SignalHandlers();
  86. void dispatch();
  87. int add(Function<void(int)>&& handler);
  88. bool remove(int handler_id);
  89. bool is_empty() const
  90. {
  91. if (m_calling_handlers) {
  92. for (auto& handler : m_handlers_pending) {
  93. if (handler.value)
  94. return false; // an add is pending
  95. }
  96. }
  97. return m_handlers.is_empty();
  98. }
  99. bool have(int handler_id) const
  100. {
  101. if (m_calling_handlers) {
  102. auto it = m_handlers_pending.find(handler_id);
  103. if (it != m_handlers_pending.end()) {
  104. if (!it->value)
  105. return false; // a deletion is pending
  106. }
  107. }
  108. return m_handlers.contains(handler_id);
  109. }
  110. int m_signo;
  111. void (*m_original_handler)(int); // TODO: can't use sighandler_t?
  112. HashMap<int, Function<void(int)>> m_handlers;
  113. HashMap<int, Function<void(int)>> m_handlers_pending;
  114. bool m_calling_handlers { false };
  115. };
  116. struct SignalHandlersInfo {
  117. HashMap<int, NonnullRefPtr<SignalHandlers>> signal_handlers;
  118. int next_signal_id { 0 };
  119. };
  120. template<bool create_if_null = true>
  121. inline SignalHandlersInfo* signals_info()
  122. {
  123. static SignalHandlersInfo* s_signals;
  124. return AK::Singleton<SignalHandlersInfo>::get(s_signals);
  125. }
  126. pid_t EventLoop::s_pid;
  127. class RPCClient : public Object {
  128. C_OBJECT(RPCClient)
  129. public:
  130. explicit RPCClient(RefPtr<LocalSocket> socket)
  131. : m_socket(move(socket))
  132. , m_client_id(s_id_allocator->allocate())
  133. {
  134. #ifdef __serenity__
  135. s_rpc_clients.set(m_client_id, this);
  136. add_child(*m_socket);
  137. m_socket->on_ready_to_read = [this] {
  138. u32 length;
  139. int nread = m_socket->read((u8*)&length, sizeof(length));
  140. if (nread == 0) {
  141. # ifdef EVENTLOOP_DEBUG
  142. dbgln("RPC client disconnected");
  143. # endif
  144. shutdown();
  145. return;
  146. }
  147. ASSERT(nread == sizeof(length));
  148. auto request = m_socket->read(length);
  149. auto request_json = JsonValue::from_string(request);
  150. if (!request_json.has_value() || !request_json.value().is_object()) {
  151. dbgln("RPC client sent invalid request");
  152. shutdown();
  153. return;
  154. }
  155. handle_request(request_json.value().as_object());
  156. };
  157. #else
  158. warnln("RPC Client constructed outside serenity, this is very likely a bug!");
  159. #endif
  160. }
  161. virtual ~RPCClient() override
  162. {
  163. if (auto inspected_object = m_inspected_object.strong_ref())
  164. inspected_object->decrement_inspector_count({});
  165. }
  166. void send_response(const JsonObject& response)
  167. {
  168. auto serialized = response.to_string();
  169. u32 length = serialized.length();
  170. m_socket->write((const u8*)&length, sizeof(length));
  171. m_socket->write(serialized);
  172. }
  173. void handle_request(const JsonObject& request)
  174. {
  175. auto type = request.get("type").as_string_or({});
  176. if (type.is_null()) {
  177. dbgln("RPC client sent request without type field");
  178. return;
  179. }
  180. if (type == "Identify") {
  181. JsonObject response;
  182. response.set("type", type);
  183. response.set("pid", getpid());
  184. #ifdef __serenity__
  185. char buffer[1024];
  186. if (get_process_name(buffer, sizeof(buffer)) >= 0) {
  187. response.set("process_name", buffer);
  188. } else {
  189. response.set("process_name", JsonValue());
  190. }
  191. #endif
  192. send_response(response);
  193. return;
  194. }
  195. if (type == "GetAllObjects") {
  196. JsonObject response;
  197. response.set("type", type);
  198. JsonArray objects;
  199. for (auto& object : Object::all_objects()) {
  200. JsonObject json_object;
  201. object.save_to(json_object);
  202. objects.append(move(json_object));
  203. }
  204. response.set("objects", move(objects));
  205. send_response(response);
  206. return;
  207. }
  208. if (type == "SetInspectedObject") {
  209. auto address = request.get("address").to_number<FlatPtr>();
  210. for (auto& object : Object::all_objects()) {
  211. if ((FlatPtr)&object == address) {
  212. if (auto inspected_object = m_inspected_object.strong_ref())
  213. inspected_object->decrement_inspector_count({});
  214. m_inspected_object = object;
  215. object.increment_inspector_count({});
  216. break;
  217. }
  218. }
  219. return;
  220. }
  221. if (type == "SetProperty") {
  222. auto address = request.get("address").to_number<FlatPtr>();
  223. for (auto& object : Object::all_objects()) {
  224. if ((FlatPtr)&object == address) {
  225. bool success = object.set_property(request.get("name").to_string(), request.get("value"));
  226. JsonObject response;
  227. response.set("type", "SetProperty");
  228. response.set("success", success);
  229. send_response(response);
  230. break;
  231. }
  232. }
  233. return;
  234. }
  235. if (type == "Disconnect") {
  236. shutdown();
  237. return;
  238. }
  239. }
  240. void shutdown()
  241. {
  242. s_rpc_clients.remove(m_client_id);
  243. s_id_allocator->deallocate(m_client_id);
  244. }
  245. private:
  246. RefPtr<LocalSocket> m_socket;
  247. WeakPtr<Object> m_inspected_object;
  248. int m_client_id { -1 };
  249. };
  250. EventLoop::EventLoop()
  251. : m_private(make<Private>())
  252. {
  253. if (!s_event_loop_stack) {
  254. s_event_loop_stack = new Vector<EventLoop*>;
  255. s_timers = new HashMap<int, NonnullOwnPtr<EventLoopTimer>>;
  256. s_notifiers = new HashTable<Notifier*>;
  257. }
  258. if (!s_main_event_loop) {
  259. s_main_event_loop = this;
  260. s_pid = getpid();
  261. #if defined(SOCK_NONBLOCK)
  262. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  263. #else
  264. int rc = pipe(s_wake_pipe_fds);
  265. fcntl(s_wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  266. fcntl(s_wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  267. #endif
  268. ASSERT(rc == 0);
  269. s_event_loop_stack->append(this);
  270. #ifdef __serenity__
  271. if (!s_rpc_server) {
  272. if (!start_rpc_server())
  273. dbgln("Core::EventLoop: Failed to start an RPC server");
  274. }
  275. #endif
  276. }
  277. #ifdef EVENTLOOP_DEBUG
  278. dbgln("{} Core::EventLoop constructed :)", getpid());
  279. #endif
  280. }
  281. EventLoop::~EventLoop()
  282. {
  283. }
  284. bool EventLoop::start_rpc_server()
  285. {
  286. #ifdef __serenity__
  287. s_rpc_server = LocalServer::construct();
  288. s_rpc_server->set_name("Core::EventLoop_RPC_server");
  289. s_rpc_server->on_ready_to_accept = [&] {
  290. RPCClient::construct(s_rpc_server->accept());
  291. };
  292. return s_rpc_server->listen(String::formatted("/tmp/rpc/{}", getpid()));
  293. #else
  294. ASSERT_NOT_REACHED();
  295. #endif
  296. }
  297. EventLoop& EventLoop::main()
  298. {
  299. ASSERT(s_main_event_loop);
  300. return *s_main_event_loop;
  301. }
  302. EventLoop& EventLoop::current()
  303. {
  304. EventLoop* event_loop = s_event_loop_stack->last();
  305. ASSERT(event_loop != nullptr);
  306. return *event_loop;
  307. }
  308. void EventLoop::quit(int code)
  309. {
  310. #ifdef EVENTLOOP_DEBUG
  311. dbgln("Core::EventLoop::quit({})", code);
  312. #endif
  313. m_exit_requested = true;
  314. m_exit_code = code;
  315. }
  316. void EventLoop::unquit()
  317. {
  318. #ifdef EVENTLOOP_DEBUG
  319. dbgln("Core::EventLoop::unquit()");
  320. #endif
  321. m_exit_requested = false;
  322. m_exit_code = 0;
  323. }
  324. struct EventLoopPusher {
  325. public:
  326. EventLoopPusher(EventLoop& event_loop)
  327. : m_event_loop(event_loop)
  328. {
  329. if (&m_event_loop != s_main_event_loop) {
  330. m_event_loop.take_pending_events_from(EventLoop::current());
  331. s_event_loop_stack->append(&event_loop);
  332. }
  333. }
  334. ~EventLoopPusher()
  335. {
  336. if (&m_event_loop != s_main_event_loop) {
  337. s_event_loop_stack->take_last();
  338. EventLoop::current().take_pending_events_from(m_event_loop);
  339. }
  340. }
  341. private:
  342. EventLoop& m_event_loop;
  343. };
  344. int EventLoop::exec()
  345. {
  346. EventLoopPusher pusher(*this);
  347. for (;;) {
  348. if (m_exit_requested)
  349. return m_exit_code;
  350. pump();
  351. }
  352. ASSERT_NOT_REACHED();
  353. }
  354. void EventLoop::pump(WaitMode mode)
  355. {
  356. wait_for_event(mode);
  357. decltype(m_queued_events) events;
  358. {
  359. LOCKER(m_private->lock);
  360. events = move(m_queued_events);
  361. }
  362. for (size_t i = 0; i < events.size(); ++i) {
  363. auto& queued_event = events.at(i);
  364. auto receiver = queued_event.receiver.strong_ref();
  365. auto& event = *queued_event.event;
  366. #ifdef EVENTLOOP_DEBUG
  367. if (receiver)
  368. dbgln("Core::EventLoop: {} event {}", *receiver, event.type());
  369. #endif
  370. if (!receiver) {
  371. switch (event.type()) {
  372. case Event::Quit:
  373. ASSERT_NOT_REACHED();
  374. return;
  375. default:
  376. #ifdef EVENTLOOP_DEBUG
  377. dbgln("Event type {} with no receiver :(", event.type());
  378. #endif
  379. break;
  380. }
  381. } else if (event.type() == Event::Type::DeferredInvoke) {
  382. #ifdef DEFERRED_INVOKE_DEBUG
  383. dbgln("DeferredInvoke: receiver = {}", *receiver);
  384. #endif
  385. static_cast<DeferredInvocationEvent&>(event).m_invokee(*receiver);
  386. } else {
  387. NonnullRefPtr<Object> protector(*receiver);
  388. receiver->dispatch_event(event);
  389. }
  390. if (m_exit_requested) {
  391. LOCKER(m_private->lock);
  392. #ifdef EVENTLOOP_DEBUG
  393. dbgln("Core::EventLoop: Exit requested. Rejigging {} events.", events.size() - i);
  394. #endif
  395. decltype(m_queued_events) new_event_queue;
  396. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  397. for (++i; i < events.size(); ++i)
  398. new_event_queue.unchecked_append(move(events[i]));
  399. new_event_queue.append(move(m_queued_events));
  400. m_queued_events = move(new_event_queue);
  401. return;
  402. }
  403. }
  404. }
  405. void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
  406. {
  407. LOCKER(m_private->lock);
  408. #ifdef EVENTLOOP_DEBUG
  409. dbgln("Core::EventLoop::post_event: ({}) << receivier={}, event={}", m_queued_events.size(), receiver, event);
  410. #endif
  411. m_queued_events.empend(receiver, move(event));
  412. }
  413. SignalHandlers::SignalHandlers(int signo, void (*handle_signal)(int))
  414. : m_signo(signo)
  415. , m_original_handler(signal(signo, handle_signal))
  416. {
  417. #ifdef EVENTLOOP_DEBUG
  418. dbgln("Core::EventLoop: Registered handler for signal {}", m_signo);
  419. #endif
  420. }
  421. SignalHandlers::~SignalHandlers()
  422. {
  423. #ifdef EVENTLOOP_DEBUG
  424. dbgln("Core::EventLoop: Unregistering handler for signal {}", m_signo);
  425. #endif
  426. signal(m_signo, m_original_handler);
  427. }
  428. void SignalHandlers::dispatch()
  429. {
  430. TemporaryChange change(m_calling_handlers, true);
  431. for (auto& handler : m_handlers)
  432. handler.value(m_signo);
  433. if (!m_handlers_pending.is_empty()) {
  434. // Apply pending adds/removes
  435. for (auto& handler : m_handlers_pending) {
  436. if (handler.value) {
  437. auto result = m_handlers.set(handler.key, move(handler.value));
  438. ASSERT(result == AK::HashSetResult::InsertedNewEntry);
  439. } else {
  440. m_handlers.remove(handler.key);
  441. }
  442. }
  443. m_handlers_pending.clear();
  444. }
  445. }
  446. int SignalHandlers::add(Function<void(int)>&& handler)
  447. {
  448. int id = ++signals_info()->next_signal_id; // TODO: worry about wrapping and duplicates?
  449. if (m_calling_handlers)
  450. m_handlers_pending.set(id, move(handler));
  451. else
  452. m_handlers.set(id, move(handler));
  453. return id;
  454. }
  455. bool SignalHandlers::remove(int handler_id)
  456. {
  457. ASSERT(handler_id != 0);
  458. if (m_calling_handlers) {
  459. auto it = m_handlers.find(handler_id);
  460. if (it != m_handlers.end()) {
  461. // Mark pending remove
  462. m_handlers_pending.set(handler_id, {});
  463. return true;
  464. }
  465. it = m_handlers_pending.find(handler_id);
  466. if (it != m_handlers_pending.end()) {
  467. if (!it->value)
  468. return false; // already was marked as deleted
  469. it->value = nullptr;
  470. return true;
  471. }
  472. return false;
  473. }
  474. return m_handlers.remove(handler_id);
  475. }
  476. void EventLoop::dispatch_signal(int signo)
  477. {
  478. auto& info = *signals_info();
  479. auto handlers = info.signal_handlers.find(signo);
  480. if (handlers != info.signal_handlers.end()) {
  481. // Make sure we bump the ref count while dispatching the handlers!
  482. // This allows a handler to unregister/register while the handlers
  483. // are being called!
  484. auto handler = handlers->value;
  485. #ifdef EVENTLOOP_DEBUG
  486. dbgln("Core::EventLoop: dispatching signal {}", signo);
  487. #endif
  488. handler->dispatch();
  489. }
  490. }
  491. void EventLoop::handle_signal(int signo)
  492. {
  493. ASSERT(signo != 0);
  494. // We MUST check if the current pid still matches, because there
  495. // is a window between fork() and exec() where a signal delivered
  496. // to our fork could be inadvertedly routed to the parent process!
  497. if (getpid() == s_pid) {
  498. int nwritten = write(s_wake_pipe_fds[1], &signo, sizeof(signo));
  499. if (nwritten < 0) {
  500. perror("EventLoop::register_signal: write");
  501. ASSERT_NOT_REACHED();
  502. }
  503. } else {
  504. // We're a fork who received a signal, reset s_pid
  505. s_pid = 0;
  506. }
  507. }
  508. int EventLoop::register_signal(int signo, Function<void(int)> handler)
  509. {
  510. ASSERT(signo != 0);
  511. auto& info = *signals_info();
  512. auto handlers = info.signal_handlers.find(signo);
  513. if (handlers == info.signal_handlers.end()) {
  514. auto signal_handlers = adopt(*new SignalHandlers(signo, EventLoop::handle_signal));
  515. auto handler_id = signal_handlers->add(move(handler));
  516. info.signal_handlers.set(signo, move(signal_handlers));
  517. return handler_id;
  518. } else {
  519. return handlers->value->add(move(handler));
  520. }
  521. }
  522. void EventLoop::unregister_signal(int handler_id)
  523. {
  524. ASSERT(handler_id != 0);
  525. int remove_signo = 0;
  526. auto& info = *signals_info();
  527. for (auto& h : info.signal_handlers) {
  528. auto& handlers = *h.value;
  529. if (handlers.remove(handler_id)) {
  530. if (handlers.is_empty())
  531. remove_signo = handlers.m_signo;
  532. break;
  533. }
  534. }
  535. if (remove_signo != 0)
  536. info.signal_handlers.remove(remove_signo);
  537. }
  538. void EventLoop::notify_forked(ForkEvent event)
  539. {
  540. switch (event) {
  541. case ForkEvent::Child:
  542. s_main_event_loop = nullptr;
  543. s_event_loop_stack->clear();
  544. s_timers->clear();
  545. s_notifiers->clear();
  546. if (auto* info = signals_info<false>()) {
  547. info->signal_handlers.clear();
  548. info->next_signal_id = 0;
  549. }
  550. s_pid = 0;
  551. #ifdef __serenity__
  552. s_rpc_server = nullptr;
  553. s_rpc_clients.clear();
  554. #endif
  555. return;
  556. }
  557. ASSERT_NOT_REACHED();
  558. }
  559. void EventLoop::wait_for_event(WaitMode mode)
  560. {
  561. fd_set rfds;
  562. fd_set wfds;
  563. retry:
  564. FD_ZERO(&rfds);
  565. FD_ZERO(&wfds);
  566. int max_fd = 0;
  567. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  568. FD_SET(fd, &set);
  569. if (fd > max_fd)
  570. max_fd = fd;
  571. };
  572. int max_fd_added = -1;
  573. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  574. max_fd = max(max_fd, max_fd_added);
  575. for (auto& notifier : *s_notifiers) {
  576. if (notifier->event_mask() & Notifier::Read)
  577. add_fd_to_set(notifier->fd(), rfds);
  578. if (notifier->event_mask() & Notifier::Write)
  579. add_fd_to_set(notifier->fd(), wfds);
  580. if (notifier->event_mask() & Notifier::Exceptional)
  581. ASSERT_NOT_REACHED();
  582. }
  583. bool queued_events_is_empty;
  584. {
  585. LOCKER(m_private->lock);
  586. queued_events_is_empty = m_queued_events.is_empty();
  587. }
  588. timeval now;
  589. struct timeval timeout = { 0, 0 };
  590. bool should_wait_forever = false;
  591. if (mode == WaitMode::WaitForEvents && queued_events_is_empty) {
  592. auto next_timer_expiration = get_next_timer_expiration();
  593. if (next_timer_expiration.has_value()) {
  594. timespec now_spec;
  595. clock_gettime(CLOCK_MONOTONIC_COARSE, &now_spec);
  596. now.tv_sec = now_spec.tv_sec;
  597. now.tv_usec = now_spec.tv_nsec / 1000;
  598. timeval_sub(next_timer_expiration.value(), now, timeout);
  599. if (timeout.tv_sec < 0 || (timeout.tv_sec == 0 && timeout.tv_usec < 0)) {
  600. timeout.tv_sec = 0;
  601. timeout.tv_usec = 0;
  602. }
  603. } else {
  604. should_wait_forever = true;
  605. }
  606. }
  607. try_select_again:
  608. int marked_fd_count = select(max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  609. if (marked_fd_count < 0) {
  610. int saved_errno = errno;
  611. if (saved_errno == EINTR) {
  612. if (m_exit_requested)
  613. return;
  614. goto try_select_again;
  615. }
  616. #ifdef EVENTLOOP_DEBUG
  617. dbgln("Core::EventLoop::wait_for_event: {} ({}: {})", marked_fd_count, saved_errno, strerror(saved_errno));
  618. #endif
  619. // Blow up, similar to Core::safe_syscall.
  620. ASSERT_NOT_REACHED();
  621. }
  622. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  623. int wake_events[8];
  624. auto nread = read(s_wake_pipe_fds[0], wake_events, sizeof(wake_events));
  625. if (nread < 0) {
  626. perror("read from wake pipe");
  627. ASSERT_NOT_REACHED();
  628. }
  629. ASSERT(nread > 0);
  630. bool wake_requested = false;
  631. int event_count = nread / sizeof(wake_events[0]);
  632. for (int i = 0; i < event_count; i++) {
  633. if (wake_events[i] != 0)
  634. dispatch_signal(wake_events[i]);
  635. else
  636. wake_requested = true;
  637. }
  638. if (!wake_requested && nread == sizeof(wake_events))
  639. goto retry;
  640. }
  641. if (!s_timers->is_empty()) {
  642. timespec now_spec;
  643. clock_gettime(CLOCK_MONOTONIC_COARSE, &now_spec);
  644. now.tv_sec = now_spec.tv_sec;
  645. now.tv_usec = now_spec.tv_nsec / 1000;
  646. }
  647. for (auto& it : *s_timers) {
  648. auto& timer = *it.value;
  649. if (!timer.has_expired(now))
  650. continue;
  651. auto owner = timer.owner.strong_ref();
  652. if (timer.fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  653. && owner && !owner->is_visible_for_timer_purposes()) {
  654. continue;
  655. }
  656. #ifdef EVENTLOOP_DEBUG
  657. dbgln("Core::EventLoop: Timer {} has expired, sending Core::TimerEvent to {}", timer.timer_id, *owner);
  658. #endif
  659. if (owner)
  660. post_event(*owner, make<TimerEvent>(timer.timer_id));
  661. if (timer.should_reload) {
  662. timer.reload(now);
  663. } else {
  664. // FIXME: Support removing expired timers that don't want to reload.
  665. ASSERT_NOT_REACHED();
  666. }
  667. }
  668. if (!marked_fd_count)
  669. return;
  670. for (auto& notifier : *s_notifiers) {
  671. if (FD_ISSET(notifier->fd(), &rfds)) {
  672. if (notifier->event_mask() & Notifier::Event::Read)
  673. post_event(*notifier, make<NotifierReadEvent>(notifier->fd()));
  674. }
  675. if (FD_ISSET(notifier->fd(), &wfds)) {
  676. if (notifier->event_mask() & Notifier::Event::Write)
  677. post_event(*notifier, make<NotifierWriteEvent>(notifier->fd()));
  678. }
  679. }
  680. }
  681. bool EventLoopTimer::has_expired(const timeval& now) const
  682. {
  683. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  684. }
  685. void EventLoopTimer::reload(const timeval& now)
  686. {
  687. fire_time = now;
  688. fire_time.tv_sec += interval / 1000;
  689. fire_time.tv_usec += (interval % 1000) * 1000;
  690. }
  691. Optional<struct timeval> EventLoop::get_next_timer_expiration()
  692. {
  693. Optional<struct timeval> soonest {};
  694. for (auto& it : *s_timers) {
  695. auto& fire_time = it.value->fire_time;
  696. auto owner = it.value->owner.strong_ref();
  697. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  698. && owner && !owner->is_visible_for_timer_purposes()) {
  699. continue;
  700. }
  701. if (!soonest.has_value() || fire_time.tv_sec < soonest.value().tv_sec || (fire_time.tv_sec == soonest.value().tv_sec && fire_time.tv_usec < soonest.value().tv_usec))
  702. soonest = fire_time;
  703. }
  704. return soonest;
  705. }
  706. int EventLoop::register_timer(Object& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  707. {
  708. ASSERT(milliseconds >= 0);
  709. auto timer = make<EventLoopTimer>();
  710. timer->owner = object;
  711. timer->interval = milliseconds;
  712. timeval now;
  713. timespec now_spec;
  714. clock_gettime(CLOCK_MONOTONIC_COARSE, &now_spec);
  715. now.tv_sec = now_spec.tv_sec;
  716. now.tv_usec = now_spec.tv_nsec / 1000;
  717. timer->reload(now);
  718. timer->should_reload = should_reload;
  719. timer->fire_when_not_visible = fire_when_not_visible;
  720. int timer_id = s_id_allocator->allocate();
  721. timer->timer_id = timer_id;
  722. s_timers->set(timer_id, move(timer));
  723. return timer_id;
  724. }
  725. bool EventLoop::unregister_timer(int timer_id)
  726. {
  727. s_id_allocator->deallocate(timer_id);
  728. auto it = s_timers->find(timer_id);
  729. if (it == s_timers->end())
  730. return false;
  731. s_timers->remove(it);
  732. return true;
  733. }
  734. void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
  735. {
  736. s_notifiers->set(&notifier);
  737. }
  738. void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
  739. {
  740. s_notifiers->remove(&notifier);
  741. }
  742. void EventLoop::wake()
  743. {
  744. int wake_event = 0;
  745. int nwritten = write(s_wake_pipe_fds[1], &wake_event, sizeof(wake_event));
  746. if (nwritten < 0) {
  747. perror("EventLoop::wake: write");
  748. ASSERT_NOT_REACHED();
  749. }
  750. }
  751. EventLoop::QueuedEvent::QueuedEvent(Object& receiver, NonnullOwnPtr<Event> event)
  752. : receiver(receiver)
  753. , event(move(event))
  754. {
  755. }
  756. EventLoop::QueuedEvent::QueuedEvent(QueuedEvent&& other)
  757. : receiver(other.receiver)
  758. , event(move(other.event))
  759. {
  760. }
  761. EventLoop::QueuedEvent::~QueuedEvent()
  762. {
  763. }
  764. }