EventLoop.cpp 17 KB

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