EventLoop.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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/IDAllocator.h>
  28. #include <AK/JsonObject.h>
  29. #include <AK/JsonValue.h>
  30. #include <AK/Time.h>
  31. #include <LibCore/Event.h>
  32. #include <LibCore/EventLoop.h>
  33. #include <LibCore/LocalServer.h>
  34. #include <LibCore/LocalSocket.h>
  35. #include <LibCore/Notifier.h>
  36. #include <LibCore/Object.h>
  37. #include <LibCore/SyscallUtils.h>
  38. #include <LibThread/Lock.h>
  39. #include <errno.h>
  40. #include <fcntl.h>
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include <sys/select.h>
  45. #include <sys/socket.h>
  46. #include <sys/time.h>
  47. #include <time.h>
  48. #include <unistd.h>
  49. //#define CEVENTLOOP_DEBUG
  50. //#define DEFERRED_INVOKE_DEBUG
  51. namespace Core {
  52. class RPCClient;
  53. struct EventLoopTimer {
  54. int timer_id { 0 };
  55. int interval { 0 };
  56. timeval fire_time { 0, 0 };
  57. bool should_reload { false };
  58. TimerShouldFireWhenNotVisible fire_when_not_visible { TimerShouldFireWhenNotVisible::No };
  59. WeakPtr<Object> owner;
  60. void reload(const timeval& now);
  61. bool has_expired(const timeval& now) const;
  62. };
  63. struct EventLoop::Private {
  64. LibThread::Lock lock;
  65. };
  66. static EventLoop* s_main_event_loop;
  67. static Vector<EventLoop*>* s_event_loop_stack;
  68. static IDAllocator s_id_allocator;
  69. static HashMap<int, NonnullOwnPtr<EventLoopTimer>>* s_timers;
  70. static HashTable<Notifier*>* s_notifiers;
  71. int EventLoop::s_wake_pipe_fds[2];
  72. static RefPtr<LocalServer> s_rpc_server;
  73. HashMap<int, RefPtr<RPCClient>> s_rpc_clients;
  74. class RPCClient : public Object {
  75. C_OBJECT(RPCClient)
  76. public:
  77. explicit RPCClient(RefPtr<LocalSocket> socket)
  78. : m_socket(move(socket))
  79. , m_client_id(s_id_allocator.allocate())
  80. {
  81. s_rpc_clients.set(m_client_id, this);
  82. add_child(*m_socket);
  83. m_socket->on_ready_to_read = [this] {
  84. u32 length;
  85. int nread = m_socket->read((u8*)&length, sizeof(length));
  86. if (nread == 0) {
  87. dbg() << "RPC client disconnected";
  88. shutdown();
  89. return;
  90. }
  91. ASSERT(nread == sizeof(length));
  92. auto request = m_socket->read(length);
  93. auto request_json = JsonValue::from_string(request);
  94. if (!request_json.is_object()) {
  95. dbg() << "RPC client sent invalid request";
  96. shutdown();
  97. return;
  98. }
  99. handle_request(request_json.as_object());
  100. };
  101. }
  102. virtual ~RPCClient() override
  103. {
  104. }
  105. void send_response(const JsonObject& response)
  106. {
  107. auto serialized = response.to_string();
  108. u32 length = serialized.length();
  109. m_socket->write((const u8*)&length, sizeof(length));
  110. m_socket->write(serialized);
  111. }
  112. void handle_request(const JsonObject& request)
  113. {
  114. auto type = request.get("type").as_string_or({});
  115. if (type.is_null()) {
  116. dbg() << "RPC client sent request without type field";
  117. return;
  118. }
  119. if (type == "Identify") {
  120. JsonObject response;
  121. response.set("type", type);
  122. response.set("pid", getpid());
  123. #ifdef __serenity__
  124. char buffer[1024];
  125. if (get_process_name(buffer, sizeof(buffer)) >= 0) {
  126. response.set("process_name", buffer);
  127. } else {
  128. response.set("process_name", JsonValue());
  129. }
  130. #endif
  131. send_response(response);
  132. return;
  133. }
  134. if (type == "GetAllObjects") {
  135. JsonObject response;
  136. response.set("type", type);
  137. JsonArray objects;
  138. for (auto& object : Object::all_objects()) {
  139. JsonObject json_object;
  140. object.save_to(json_object);
  141. objects.append(move(json_object));
  142. }
  143. response.set("objects", move(objects));
  144. send_response(response);
  145. return;
  146. }
  147. if (type == "Disconnect") {
  148. shutdown();
  149. return;
  150. }
  151. }
  152. void shutdown()
  153. {
  154. s_rpc_clients.remove(m_client_id);
  155. s_id_allocator.deallocate(m_client_id);
  156. }
  157. private:
  158. RefPtr<LocalSocket> m_socket;
  159. int m_client_id { -1 };
  160. };
  161. EventLoop::EventLoop()
  162. : m_private(make<Private>())
  163. {
  164. if (!s_event_loop_stack) {
  165. s_event_loop_stack = new Vector<EventLoop*>;
  166. s_timers = new HashMap<int, NonnullOwnPtr<EventLoopTimer>>;
  167. s_notifiers = new HashTable<Notifier*>;
  168. }
  169. if (!s_main_event_loop) {
  170. s_main_event_loop = this;
  171. #if defined(SOCK_NONBLOCK)
  172. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  173. #else
  174. int rc = pipe(s_wake_pipe_fds);
  175. fcntl(s_wake_pipe_fds[0], F_SETFD, FD_CLOEXEC);
  176. fcntl(s_wake_pipe_fds[1], F_SETFD, FD_CLOEXEC);
  177. #endif
  178. ASSERT(rc == 0);
  179. s_event_loop_stack->append(this);
  180. auto rpc_path = String::format("/tmp/rpc.%d", getpid());
  181. rc = unlink(rpc_path.characters());
  182. if (rc < 0 && errno != ENOENT) {
  183. perror("unlink");
  184. ASSERT_NOT_REACHED();
  185. }
  186. s_rpc_server = LocalServer::construct();
  187. s_rpc_server->set_name("Core::EventLoop_RPC_server");
  188. bool listening = s_rpc_server->listen(rpc_path);
  189. ASSERT(listening);
  190. s_rpc_server->on_ready_to_accept = [&] {
  191. RPCClient::construct(s_rpc_server->accept());
  192. };
  193. }
  194. #ifdef CEVENTLOOP_DEBUG
  195. dbg() << getpid() << " Core::EventLoop constructed :)";
  196. #endif
  197. }
  198. EventLoop::~EventLoop()
  199. {
  200. }
  201. EventLoop& EventLoop::main()
  202. {
  203. ASSERT(s_main_event_loop);
  204. return *s_main_event_loop;
  205. }
  206. EventLoop& EventLoop::current()
  207. {
  208. EventLoop* event_loop = s_event_loop_stack->last();
  209. ASSERT(event_loop != nullptr);
  210. return *event_loop;
  211. }
  212. void EventLoop::quit(int code)
  213. {
  214. dbg() << "Core::EventLoop::quit(" << code << ")";
  215. m_exit_requested = true;
  216. m_exit_code = code;
  217. }
  218. void EventLoop::unquit()
  219. {
  220. dbg() << "Core::EventLoop::unquit()";
  221. m_exit_requested = false;
  222. m_exit_code = 0;
  223. }
  224. struct EventLoopPusher {
  225. public:
  226. EventLoopPusher(EventLoop& event_loop)
  227. : m_event_loop(event_loop)
  228. {
  229. if (&m_event_loop != s_main_event_loop) {
  230. m_event_loop.take_pending_events_from(EventLoop::current());
  231. s_event_loop_stack->append(&event_loop);
  232. }
  233. }
  234. ~EventLoopPusher()
  235. {
  236. if (&m_event_loop != s_main_event_loop) {
  237. s_event_loop_stack->take_last();
  238. EventLoop::current().take_pending_events_from(m_event_loop);
  239. }
  240. }
  241. private:
  242. EventLoop& m_event_loop;
  243. };
  244. int EventLoop::exec()
  245. {
  246. EventLoopPusher pusher(*this);
  247. for (;;) {
  248. if (m_exit_requested)
  249. return m_exit_code;
  250. pump();
  251. }
  252. ASSERT_NOT_REACHED();
  253. }
  254. void EventLoop::pump(WaitMode mode)
  255. {
  256. if (m_queued_events.is_empty())
  257. wait_for_event(mode);
  258. decltype(m_queued_events) events;
  259. {
  260. LOCKER(m_private->lock);
  261. events = move(m_queued_events);
  262. }
  263. for (size_t i = 0; i < events.size(); ++i) {
  264. auto& queued_event = events.at(i);
  265. #ifndef __clang__
  266. ASSERT(queued_event.event);
  267. #endif
  268. auto* receiver = queued_event.receiver.ptr();
  269. auto& event = *queued_event.event;
  270. #ifdef CEVENTLOOP_DEBUG
  271. if (receiver)
  272. dbg() << "Core::EventLoop: " << *receiver << " event " << (int)event.type();
  273. #endif
  274. if (!receiver) {
  275. switch (event.type()) {
  276. case Event::Quit:
  277. ASSERT_NOT_REACHED();
  278. return;
  279. default:
  280. dbg() << "Event type " << event.type() << " with no receiver :(";
  281. }
  282. } else if (event.type() == Event::Type::DeferredInvoke) {
  283. #ifdef DEFERRED_INVOKE_DEBUG
  284. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  285. #endif
  286. static_cast<DeferredInvocationEvent&>(event).m_invokee(*receiver);
  287. } else {
  288. NonnullRefPtr<Object> protector(*receiver);
  289. receiver->dispatch_event(event);
  290. }
  291. if (m_exit_requested) {
  292. LOCKER(m_private->lock);
  293. #ifdef CEVENTLOOP_DEBUG
  294. dbg() << "Core::EventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
  295. #endif
  296. decltype(m_queued_events) new_event_queue;
  297. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  298. for (; i < events.size(); ++i)
  299. new_event_queue.unchecked_append(move(events[i]));
  300. new_event_queue.append(move(m_queued_events));
  301. m_queued_events = move(new_event_queue);
  302. return;
  303. }
  304. }
  305. }
  306. void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event)
  307. {
  308. LOCKER(m_private->lock);
  309. #ifdef CEVENTLOOP_DEBUG
  310. dbg() << "Core::EventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
  311. #endif
  312. m_queued_events.empend(receiver, move(event));
  313. }
  314. void EventLoop::wait_for_event(WaitMode mode)
  315. {
  316. fd_set rfds;
  317. fd_set wfds;
  318. FD_ZERO(&rfds);
  319. FD_ZERO(&wfds);
  320. int max_fd = 0;
  321. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  322. FD_SET(fd, &set);
  323. if (fd > max_fd)
  324. max_fd = fd;
  325. };
  326. int max_fd_added = -1;
  327. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  328. max_fd = max(max_fd, max_fd_added);
  329. for (auto& notifier : *s_notifiers) {
  330. if (notifier->event_mask() & Notifier::Read)
  331. add_fd_to_set(notifier->fd(), rfds);
  332. if (notifier->event_mask() & Notifier::Write)
  333. add_fd_to_set(notifier->fd(), wfds);
  334. if (notifier->event_mask() & Notifier::Exceptional)
  335. ASSERT_NOT_REACHED();
  336. }
  337. bool queued_events_is_empty;
  338. {
  339. LOCKER(m_private->lock);
  340. queued_events_is_empty = m_queued_events.is_empty();
  341. }
  342. timeval now;
  343. struct timeval timeout = { 0, 0 };
  344. bool should_wait_forever = false;
  345. if (mode == WaitMode::WaitForEvents) {
  346. if (!s_timers->is_empty() && queued_events_is_empty) {
  347. gettimeofday(&now, nullptr);
  348. get_next_timer_expiration(timeout);
  349. timeval_sub(timeout, now, timeout);
  350. if (timeout.tv_sec < 0) {
  351. timeout.tv_sec = 0;
  352. timeout.tv_usec = 0;
  353. }
  354. } else {
  355. should_wait_forever = true;
  356. }
  357. } else {
  358. should_wait_forever = false;
  359. }
  360. int marked_fd_count = Core::safe_syscall(select, max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  361. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  362. char buffer[32];
  363. auto nread = read(s_wake_pipe_fds[0], buffer, sizeof(buffer));
  364. if (nread < 0) {
  365. perror("read from wake pipe");
  366. ASSERT_NOT_REACHED();
  367. }
  368. ASSERT(nread > 0);
  369. }
  370. if (!s_timers->is_empty()) {
  371. gettimeofday(&now, nullptr);
  372. }
  373. for (auto& it : *s_timers) {
  374. auto& timer = *it.value;
  375. if (!timer.has_expired(now))
  376. continue;
  377. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  378. && it.value->owner
  379. && !it.value->owner->is_visible_for_timer_purposes()) {
  380. continue;
  381. }
  382. #ifdef CEVENTLOOP_DEBUG
  383. dbg() << "Core::EventLoop: Timer " << timer.timer_id << " has expired, sending Core::TimerEvent to " << timer.owner;
  384. #endif
  385. post_event(*timer.owner, make<TimerEvent>(timer.timer_id));
  386. if (timer.should_reload) {
  387. timer.reload(now);
  388. } else {
  389. // FIXME: Support removing expired timers that don't want to reload.
  390. ASSERT_NOT_REACHED();
  391. }
  392. }
  393. if (!marked_fd_count)
  394. return;
  395. for (auto& notifier : *s_notifiers) {
  396. if (FD_ISSET(notifier->fd(), &rfds)) {
  397. if (notifier->on_ready_to_read)
  398. post_event(*notifier, make<NotifierReadEvent>(notifier->fd()));
  399. }
  400. if (FD_ISSET(notifier->fd(), &wfds)) {
  401. if (notifier->on_ready_to_write)
  402. post_event(*notifier, make<NotifierWriteEvent>(notifier->fd()));
  403. }
  404. }
  405. }
  406. bool EventLoopTimer::has_expired(const timeval& now) const
  407. {
  408. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  409. }
  410. void EventLoopTimer::reload(const timeval& now)
  411. {
  412. fire_time = now;
  413. fire_time.tv_sec += interval / 1000;
  414. fire_time.tv_usec += (interval % 1000) * 1000;
  415. }
  416. void EventLoop::get_next_timer_expiration(timeval& soonest)
  417. {
  418. ASSERT(!s_timers->is_empty());
  419. bool has_checked_any = false;
  420. for (auto& it : *s_timers) {
  421. auto& fire_time = it.value->fire_time;
  422. if (it.value->fire_when_not_visible == TimerShouldFireWhenNotVisible::No
  423. && it.value->owner
  424. && !it.value->owner->is_visible_for_timer_purposes()) {
  425. continue;
  426. }
  427. if (!has_checked_any || fire_time.tv_sec < soonest.tv_sec || (fire_time.tv_sec == soonest.tv_sec && fire_time.tv_usec < soonest.tv_usec))
  428. soonest = fire_time;
  429. has_checked_any = true;
  430. }
  431. }
  432. int EventLoop::register_timer(Object& object, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible fire_when_not_visible)
  433. {
  434. ASSERT(milliseconds >= 0);
  435. auto timer = make<EventLoopTimer>();
  436. timer->owner = object.make_weak_ptr();
  437. timer->interval = milliseconds;
  438. timeval now;
  439. gettimeofday(&now, nullptr);
  440. timer->reload(now);
  441. timer->should_reload = should_reload;
  442. timer->fire_when_not_visible = fire_when_not_visible;
  443. int timer_id = s_id_allocator.allocate();
  444. timer->timer_id = timer_id;
  445. s_timers->set(timer_id, move(timer));
  446. return timer_id;
  447. }
  448. bool EventLoop::unregister_timer(int timer_id)
  449. {
  450. s_id_allocator.deallocate(timer_id);
  451. auto it = s_timers->find(timer_id);
  452. if (it == s_timers->end())
  453. return false;
  454. s_timers->remove(it);
  455. return true;
  456. }
  457. void EventLoop::register_notifier(Badge<Notifier>, Notifier& notifier)
  458. {
  459. s_notifiers->set(&notifier);
  460. }
  461. void EventLoop::unregister_notifier(Badge<Notifier>, Notifier& notifier)
  462. {
  463. s_notifiers->remove(&notifier);
  464. }
  465. void EventLoop::wake()
  466. {
  467. char ch = '!';
  468. int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
  469. if (nwritten < 0) {
  470. perror("EventLoop::wake: write");
  471. ASSERT_NOT_REACHED();
  472. }
  473. }
  474. EventLoop::QueuedEvent::QueuedEvent(Object& receiver, NonnullOwnPtr<Event> event)
  475. : receiver(receiver.make_weak_ptr())
  476. , event(move(event))
  477. {
  478. }
  479. EventLoop::QueuedEvent::QueuedEvent(QueuedEvent&& other)
  480. : receiver(other.receiver)
  481. , event(move(other.event))
  482. {
  483. }
  484. EventLoop::QueuedEvent::~QueuedEvent()
  485. {
  486. }
  487. }