CEventLoop.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #include <AK/JsonArray.h>
  2. #include <AK/JsonObject.h>
  3. #include <AK/JsonValue.h>
  4. #include <AK/Time.h>
  5. #include <LibCore/CEvent.h>
  6. #include <LibCore/CEventLoop.h>
  7. #include <LibCore/CLocalSocket.h>
  8. #include <LibCore/CLock.h>
  9. #include <LibCore/CNotifier.h>
  10. #include <LibCore/CObject.h>
  11. #include <LibCore/CSyscallUtils.h>
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <sys/select.h>
  18. #include <sys/socket.h>
  19. #include <sys/time.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. //#define CEVENTLOOP_DEBUG
  23. //#define DEFERRED_INVOKE_DEBUG
  24. static CEventLoop* s_main_event_loop;
  25. static Vector<CEventLoop*>* s_event_loop_stack;
  26. HashMap<int, NonnullOwnPtr<CEventLoop::EventLoopTimer>>* CEventLoop::s_timers;
  27. HashTable<CNotifier*>* CEventLoop::s_notifiers;
  28. int CEventLoop::s_next_timer_id = 1;
  29. int CEventLoop::s_wake_pipe_fds[2];
  30. CLocalServer CEventLoop::s_rpc_server;
  31. CEventLoop::CEventLoop()
  32. {
  33. if (!s_event_loop_stack) {
  34. s_event_loop_stack = new Vector<CEventLoop*>;
  35. s_timers = new HashMap<int, NonnullOwnPtr<CEventLoop::EventLoopTimer>>;
  36. s_notifiers = new HashTable<CNotifier*>;
  37. }
  38. if (!s_main_event_loop) {
  39. s_main_event_loop = this;
  40. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  41. ASSERT(rc == 0);
  42. s_event_loop_stack->append(this);
  43. auto rpc_path = String::format("/tmp/rpc.%d", getpid());
  44. rc = unlink(rpc_path.characters());
  45. if (rc < 0 && errno != ENOENT) {
  46. perror("unlink");
  47. ASSERT_NOT_REACHED();
  48. }
  49. bool listening = s_rpc_server.listen(rpc_path);
  50. ASSERT(listening);
  51. s_rpc_server.on_ready_to_accept = [&] {
  52. auto* client = s_rpc_server.accept();
  53. ASSERT(client);
  54. JsonArray objects;
  55. for (auto& object : CObject::all_objects()) {
  56. JsonObject json_object;
  57. json_object.set("class_name", object.class_name());
  58. json_object.set("address", String::format("%p", &object));
  59. json_object.set("name", object.name());
  60. json_object.set("parent", String::format("%p", object.parent()));
  61. objects.append(move(json_object));
  62. }
  63. client->write(objects.to_string());
  64. client->delete_later();
  65. };
  66. }
  67. #ifdef CEVENTLOOP_DEBUG
  68. dbg() << getpid() << " CEventLoop constructed :)";
  69. #endif
  70. }
  71. CEventLoop::~CEventLoop()
  72. {
  73. }
  74. CEventLoop& CEventLoop::main()
  75. {
  76. ASSERT(s_main_event_loop);
  77. return *s_main_event_loop;
  78. }
  79. CEventLoop& CEventLoop::current()
  80. {
  81. return *s_event_loop_stack->last();
  82. }
  83. void CEventLoop::quit(int code)
  84. {
  85. m_exit_requested = true;
  86. m_exit_code = code;
  87. }
  88. struct CEventLoopPusher {
  89. public:
  90. CEventLoopPusher(CEventLoop& event_loop)
  91. : m_event_loop(event_loop)
  92. {
  93. if (&m_event_loop != s_main_event_loop) {
  94. m_event_loop.take_pending_events_from(CEventLoop::current());
  95. s_event_loop_stack->append(&event_loop);
  96. }
  97. }
  98. ~CEventLoopPusher()
  99. {
  100. if (&m_event_loop != s_main_event_loop) {
  101. s_event_loop_stack->take_last();
  102. CEventLoop::current().take_pending_events_from(m_event_loop);
  103. }
  104. }
  105. private:
  106. CEventLoop& m_event_loop;
  107. };
  108. int CEventLoop::exec()
  109. {
  110. CEventLoopPusher pusher(*this);
  111. for (;;) {
  112. if (m_exit_requested)
  113. return m_exit_code;
  114. pump();
  115. }
  116. ASSERT_NOT_REACHED();
  117. }
  118. void CEventLoop::pump(WaitMode mode)
  119. {
  120. if (m_queued_events.is_empty())
  121. wait_for_event(mode);
  122. decltype(m_queued_events) events;
  123. {
  124. LOCKER(m_lock);
  125. events = move(m_queued_events);
  126. }
  127. for (int i = 0; i < events.size(); ++i) {
  128. auto& queued_event = events.at(i);
  129. ASSERT(queued_event.event);
  130. auto* receiver = queued_event.receiver.ptr();
  131. auto& event = *queued_event.event;
  132. #ifdef CEVENTLOOP_DEBUG
  133. if (receiver)
  134. dbg() << "CEventLoop: " << *receiver << " event " << (int)event.type();
  135. #endif
  136. if (!receiver) {
  137. switch (event.type()) {
  138. case CEvent::Quit:
  139. ASSERT_NOT_REACHED();
  140. return;
  141. default:
  142. dbg() << "Event type " << event.type() << " with no receiver :(";
  143. }
  144. } else if (event.type() == CEvent::Type::DeferredInvoke) {
  145. #ifdef DEFERRED_INVOKE_DEBUG
  146. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  147. #endif
  148. static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver);
  149. } else {
  150. receiver->event(event);
  151. }
  152. if (m_exit_requested) {
  153. LOCKER(m_lock);
  154. #ifdef CEVENTLOOP_DEBUG
  155. dbg() << "CEventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
  156. #endif
  157. decltype(m_queued_events) new_event_queue;
  158. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  159. for (; i < events.size(); ++i)
  160. new_event_queue.unchecked_append(move(events[i]));
  161. new_event_queue.append(move(m_queued_events));
  162. m_queued_events = move(new_event_queue);
  163. return;
  164. }
  165. }
  166. }
  167. void CEventLoop::post_event(CObject& receiver, NonnullOwnPtr<CEvent>&& event)
  168. {
  169. LOCKER(m_lock);
  170. #ifdef CEVENTLOOP_DEBUG
  171. dbg() << "CEventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
  172. #endif
  173. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  174. }
  175. void CEventLoop::wait_for_event(WaitMode mode)
  176. {
  177. fd_set rfds;
  178. fd_set wfds;
  179. FD_ZERO(&rfds);
  180. FD_ZERO(&wfds);
  181. int max_fd = 0;
  182. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  183. FD_SET(fd, &set);
  184. if (fd > max_fd)
  185. max_fd = fd;
  186. };
  187. int max_fd_added = -1;
  188. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  189. max_fd = max(max_fd, max_fd_added);
  190. for (auto& notifier : *s_notifiers) {
  191. if (notifier->event_mask() & CNotifier::Read)
  192. add_fd_to_set(notifier->fd(), rfds);
  193. if (notifier->event_mask() & CNotifier::Write)
  194. add_fd_to_set(notifier->fd(), wfds);
  195. if (notifier->event_mask() & CNotifier::Exceptional)
  196. ASSERT_NOT_REACHED();
  197. }
  198. bool queued_events_is_empty;
  199. {
  200. LOCKER(m_lock);
  201. queued_events_is_empty = m_queued_events.is_empty();
  202. }
  203. timeval now;
  204. struct timeval timeout = { 0, 0 };
  205. bool should_wait_forever = false;
  206. if (mode == WaitMode::WaitForEvents) {
  207. if (!s_timers->is_empty() && queued_events_is_empty) {
  208. gettimeofday(&now, nullptr);
  209. get_next_timer_expiration(timeout);
  210. timeval_sub(timeout, now, timeout);
  211. } else {
  212. should_wait_forever = true;
  213. }
  214. } else {
  215. should_wait_forever = false;
  216. }
  217. int marked_fd_count = CSyscallUtils::safe_syscall(select, max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  218. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  219. char buffer[32];
  220. auto nread = read(s_wake_pipe_fds[0], buffer, sizeof(buffer));
  221. if (nread < 0) {
  222. perror("read from wake pipe");
  223. ASSERT_NOT_REACHED();
  224. }
  225. ASSERT(nread > 0);
  226. }
  227. if (!s_timers->is_empty()) {
  228. gettimeofday(&now, nullptr);
  229. }
  230. for (auto& it : *s_timers) {
  231. auto& timer = *it.value;
  232. if (!timer.has_expired(now))
  233. continue;
  234. #ifdef CEVENTLOOP_DEBUG
  235. dbg() << "CEventLoop: Timer " << timer.timer_id << " has expired, sending CTimerEvent to " << timer.owner;
  236. #endif
  237. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  238. if (timer.should_reload) {
  239. timer.reload(now);
  240. } else {
  241. // FIXME: Support removing expired timers that don't want to reload.
  242. ASSERT_NOT_REACHED();
  243. }
  244. }
  245. if (!marked_fd_count)
  246. return;
  247. for (auto& notifier : *s_notifiers) {
  248. if (FD_ISSET(notifier->fd(), &rfds)) {
  249. if (notifier->on_ready_to_read)
  250. post_event(*notifier, make<CNotifierReadEvent>(notifier->fd()));
  251. }
  252. if (FD_ISSET(notifier->fd(), &wfds)) {
  253. if (notifier->on_ready_to_write)
  254. post_event(*notifier, make<CNotifierWriteEvent>(notifier->fd()));
  255. }
  256. }
  257. }
  258. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  259. {
  260. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  261. }
  262. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  263. {
  264. fire_time = now;
  265. fire_time.tv_sec += interval / 1000;
  266. fire_time.tv_usec += (interval % 1000) * 1000;
  267. }
  268. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  269. {
  270. ASSERT(!s_timers->is_empty());
  271. bool has_checked_any = false;
  272. for (auto& it : *s_timers) {
  273. auto& fire_time = it.value->fire_time;
  274. 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))
  275. soonest = fire_time;
  276. has_checked_any = true;
  277. }
  278. }
  279. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  280. {
  281. ASSERT(milliseconds >= 0);
  282. auto timer = make<EventLoopTimer>();
  283. timer->owner = object.make_weak_ptr();
  284. timer->interval = milliseconds;
  285. timeval now;
  286. gettimeofday(&now, nullptr);
  287. timer->reload(now);
  288. timer->should_reload = should_reload;
  289. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  290. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  291. timer->timer_id = timer_id;
  292. s_timers->set(timer_id, move(timer));
  293. return timer_id;
  294. }
  295. bool CEventLoop::unregister_timer(int timer_id)
  296. {
  297. auto it = s_timers->find(timer_id);
  298. if (it == s_timers->end())
  299. return false;
  300. s_timers->remove(it);
  301. return true;
  302. }
  303. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  304. {
  305. s_notifiers->set(&notifier);
  306. }
  307. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  308. {
  309. s_notifiers->remove(&notifier);
  310. }
  311. void CEventLoop::wake()
  312. {
  313. char ch = '!';
  314. int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
  315. if (nwritten < 0) {
  316. perror("CEventLoop::wake: write");
  317. ASSERT_NOT_REACHED();
  318. }
  319. }