CEventLoop.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  36. ASSERT(rc == 0);
  37. s_event_loop_stack->append(this);
  38. }
  39. #ifdef CEVENTLOOP_DEBUG
  40. dbg() << getpid() << " CEventLoop constructed :)";
  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. ASSERT(queued_event.event);
  102. auto* receiver = queued_event.receiver.ptr();
  103. auto& event = *queued_event.event;
  104. #ifdef CEVENTLOOP_DEBUG
  105. if (receiver)
  106. dbg() << "CEventLoop: " << *receiver << " event " << (int)event.type();
  107. #endif
  108. if (!receiver) {
  109. switch (event.type()) {
  110. case CEvent::Quit:
  111. ASSERT_NOT_REACHED();
  112. return;
  113. default:
  114. dbg() << "Event type " << event.type() << " with no receiver :(";
  115. }
  116. } else if (event.type() == CEvent::Type::DeferredInvoke) {
  117. #ifdef DEFERRED_INVOKE_DEBUG
  118. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  119. #endif
  120. static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver);
  121. } else {
  122. receiver->event(event);
  123. }
  124. if (m_exit_requested) {
  125. LOCKER(m_lock);
  126. #ifdef CEVENTLOOP_DEBUG
  127. dbg() << "CEventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
  128. #endif
  129. decltype(m_queued_events) new_event_queue;
  130. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  131. for (; i < events.size(); ++i)
  132. new_event_queue.unchecked_append(move(events[i]));
  133. new_event_queue.append(move(m_queued_events));
  134. m_queued_events = move(new_event_queue);
  135. return;
  136. }
  137. }
  138. }
  139. void CEventLoop::post_event(CObject& receiver, NonnullOwnPtr<CEvent>&& event)
  140. {
  141. LOCKER(m_lock);
  142. #ifdef CEVENTLOOP_DEBUG
  143. dbg() << "CEventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
  144. #endif
  145. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  146. }
  147. void CEventLoop::wait_for_event(WaitMode mode)
  148. {
  149. fd_set rfds;
  150. fd_set wfds;
  151. FD_ZERO(&rfds);
  152. FD_ZERO(&wfds);
  153. int max_fd = 0;
  154. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  155. FD_SET(fd, &set);
  156. if (fd > max_fd)
  157. max_fd = fd;
  158. };
  159. int max_fd_added = -1;
  160. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  161. max_fd = max(max_fd, max_fd_added);
  162. for (auto& notifier : *s_notifiers) {
  163. if (notifier->event_mask() & CNotifier::Read)
  164. add_fd_to_set(notifier->fd(), rfds);
  165. if (notifier->event_mask() & CNotifier::Write)
  166. add_fd_to_set(notifier->fd(), wfds);
  167. if (notifier->event_mask() & CNotifier::Exceptional)
  168. ASSERT_NOT_REACHED();
  169. }
  170. bool queued_events_is_empty;
  171. {
  172. LOCKER(m_lock);
  173. queued_events_is_empty = m_queued_events.is_empty();
  174. }
  175. timeval now;
  176. struct timeval timeout = { 0, 0 };
  177. bool should_wait_forever = false;
  178. if (mode == WaitMode::WaitForEvents) {
  179. if (!s_timers->is_empty() && queued_events_is_empty) {
  180. gettimeofday(&now, nullptr);
  181. get_next_timer_expiration(timeout);
  182. timeval_sub(timeout, now, timeout);
  183. } else {
  184. should_wait_forever = true;
  185. }
  186. } else {
  187. should_wait_forever = false;
  188. }
  189. int marked_fd_count = CSyscallUtils::safe_syscall(select, max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  190. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  191. char buffer[32];
  192. auto nread = read(s_wake_pipe_fds[0], buffer, sizeof(buffer));
  193. if (nread < 0) {
  194. perror("read from wake pipe");
  195. ASSERT_NOT_REACHED();
  196. }
  197. ASSERT(nread > 0);
  198. }
  199. if (!s_timers->is_empty()) {
  200. gettimeofday(&now, nullptr);
  201. }
  202. for (auto& it : *s_timers) {
  203. auto& timer = *it.value;
  204. if (!timer.has_expired(now))
  205. continue;
  206. #ifdef CEVENTLOOP_DEBUG
  207. dbg() << "CEventLoop: Timer " << timer.timer_id << " has expired, sending CTimerEvent to " << timer.owner;
  208. #endif
  209. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  210. if (timer.should_reload) {
  211. timer.reload(now);
  212. } else {
  213. // FIXME: Support removing expired timers that don't want to reload.
  214. ASSERT_NOT_REACHED();
  215. }
  216. }
  217. if (!marked_fd_count)
  218. return;
  219. for (auto& notifier : *s_notifiers) {
  220. if (FD_ISSET(notifier->fd(), &rfds)) {
  221. if (notifier->on_ready_to_read)
  222. post_event(*notifier, make<CNotifierReadEvent>(notifier->fd()));
  223. }
  224. if (FD_ISSET(notifier->fd(), &wfds)) {
  225. if (notifier->on_ready_to_write)
  226. post_event(*notifier, make<CNotifierWriteEvent>(notifier->fd()));
  227. }
  228. }
  229. }
  230. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  231. {
  232. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  233. }
  234. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  235. {
  236. fire_time = now;
  237. fire_time.tv_sec += interval / 1000;
  238. fire_time.tv_usec += (interval % 1000) * 1000;
  239. }
  240. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  241. {
  242. ASSERT(!s_timers->is_empty());
  243. bool has_checked_any = false;
  244. for (auto& it : *s_timers) {
  245. auto& fire_time = it.value->fire_time;
  246. 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))
  247. soonest = fire_time;
  248. has_checked_any = true;
  249. }
  250. }
  251. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  252. {
  253. ASSERT(milliseconds >= 0);
  254. auto timer = make<EventLoopTimer>();
  255. timer->owner = object.make_weak_ptr();
  256. timer->interval = milliseconds;
  257. timeval now;
  258. gettimeofday(&now, nullptr);
  259. timer->reload(now);
  260. timer->should_reload = should_reload;
  261. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  262. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  263. timer->timer_id = timer_id;
  264. s_timers->set(timer_id, move(timer));
  265. return timer_id;
  266. }
  267. bool CEventLoop::unregister_timer(int timer_id)
  268. {
  269. auto it = s_timers->find(timer_id);
  270. if (it == s_timers->end())
  271. return false;
  272. s_timers->remove(it);
  273. return true;
  274. }
  275. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  276. {
  277. s_notifiers->set(&notifier);
  278. }
  279. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  280. {
  281. s_notifiers->remove(&notifier);
  282. }
  283. void CEventLoop::wake()
  284. {
  285. char ch = '!';
  286. int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
  287. if (nwritten < 0) {
  288. perror("CEventLoop::wake: write");
  289. ASSERT_NOT_REACHED();
  290. }
  291. }