EventLoop.cpp 15 KB

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