CEventLoop.cpp 12 KB

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