CEventLoop.cpp 9.1 KB

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