EventLoop.cpp 17 KB

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