CEventLoop.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. ObjectPtr<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. s_rpc_server = CLocalServer::construct();
  129. s_rpc_server->set_name("CEventLoop_RPC_server");
  130. bool listening = s_rpc_server->listen(rpc_path);
  131. ASSERT(listening);
  132. s_rpc_server->on_ready_to_accept = [&] {
  133. auto client_socket = s_rpc_server->accept();
  134. ASSERT(client_socket);
  135. new RPCClient(move(client_socket));
  136. };
  137. }
  138. #ifdef CEVENTLOOP_DEBUG
  139. dbg() << getpid() << " CEventLoop constructed :)";
  140. #endif
  141. }
  142. CEventLoop::~CEventLoop()
  143. {
  144. }
  145. CEventLoop& CEventLoop::main()
  146. {
  147. ASSERT(s_main_event_loop);
  148. return *s_main_event_loop;
  149. }
  150. CEventLoop& CEventLoop::current()
  151. {
  152. return *s_event_loop_stack->last();
  153. }
  154. void CEventLoop::quit(int code)
  155. {
  156. m_exit_requested = true;
  157. m_exit_code = code;
  158. }
  159. struct CEventLoopPusher {
  160. public:
  161. CEventLoopPusher(CEventLoop& event_loop)
  162. : m_event_loop(event_loop)
  163. {
  164. if (&m_event_loop != s_main_event_loop) {
  165. m_event_loop.take_pending_events_from(CEventLoop::current());
  166. s_event_loop_stack->append(&event_loop);
  167. }
  168. }
  169. ~CEventLoopPusher()
  170. {
  171. if (&m_event_loop != s_main_event_loop) {
  172. s_event_loop_stack->take_last();
  173. CEventLoop::current().take_pending_events_from(m_event_loop);
  174. }
  175. }
  176. private:
  177. CEventLoop& m_event_loop;
  178. };
  179. int CEventLoop::exec()
  180. {
  181. CEventLoopPusher pusher(*this);
  182. for (;;) {
  183. if (m_exit_requested)
  184. return m_exit_code;
  185. pump();
  186. }
  187. ASSERT_NOT_REACHED();
  188. }
  189. void CEventLoop::pump(WaitMode mode)
  190. {
  191. if (m_queued_events.is_empty())
  192. wait_for_event(mode);
  193. decltype(m_queued_events) events;
  194. {
  195. LOCKER(m_lock);
  196. events = move(m_queued_events);
  197. }
  198. for (int i = 0; i < events.size(); ++i) {
  199. auto& queued_event = events.at(i);
  200. ASSERT(queued_event.event);
  201. auto* receiver = queued_event.receiver.ptr();
  202. auto& event = *queued_event.event;
  203. #ifdef CEVENTLOOP_DEBUG
  204. if (receiver)
  205. dbg() << "CEventLoop: " << *receiver << " event " << (int)event.type();
  206. #endif
  207. if (!receiver) {
  208. switch (event.type()) {
  209. case CEvent::Quit:
  210. ASSERT_NOT_REACHED();
  211. return;
  212. default:
  213. dbg() << "Event type " << event.type() << " with no receiver :(";
  214. }
  215. } else if (event.type() == CEvent::Type::DeferredInvoke) {
  216. #ifdef DEFERRED_INVOKE_DEBUG
  217. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  218. #endif
  219. static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver);
  220. } else {
  221. receiver->dispatch_event(event);
  222. }
  223. if (m_exit_requested) {
  224. LOCKER(m_lock);
  225. #ifdef CEVENTLOOP_DEBUG
  226. dbg() << "CEventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
  227. #endif
  228. decltype(m_queued_events) new_event_queue;
  229. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  230. for (; i < events.size(); ++i)
  231. new_event_queue.unchecked_append(move(events[i]));
  232. new_event_queue.append(move(m_queued_events));
  233. m_queued_events = move(new_event_queue);
  234. return;
  235. }
  236. }
  237. }
  238. void CEventLoop::post_event(CObject& receiver, NonnullOwnPtr<CEvent>&& event)
  239. {
  240. LOCKER(m_lock);
  241. #ifdef CEVENTLOOP_DEBUG
  242. dbg() << "CEventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
  243. #endif
  244. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  245. }
  246. void CEventLoop::wait_for_event(WaitMode mode)
  247. {
  248. fd_set rfds;
  249. fd_set wfds;
  250. FD_ZERO(&rfds);
  251. FD_ZERO(&wfds);
  252. int max_fd = 0;
  253. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  254. FD_SET(fd, &set);
  255. if (fd > max_fd)
  256. max_fd = fd;
  257. };
  258. int max_fd_added = -1;
  259. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  260. max_fd = max(max_fd, max_fd_added);
  261. for (auto& notifier : *s_notifiers) {
  262. if (notifier->event_mask() & CNotifier::Read)
  263. add_fd_to_set(notifier->fd(), rfds);
  264. if (notifier->event_mask() & CNotifier::Write)
  265. add_fd_to_set(notifier->fd(), wfds);
  266. if (notifier->event_mask() & CNotifier::Exceptional)
  267. ASSERT_NOT_REACHED();
  268. }
  269. bool queued_events_is_empty;
  270. {
  271. LOCKER(m_lock);
  272. queued_events_is_empty = m_queued_events.is_empty();
  273. }
  274. timeval now;
  275. struct timeval timeout = { 0, 0 };
  276. bool should_wait_forever = false;
  277. if (mode == WaitMode::WaitForEvents) {
  278. if (!s_timers->is_empty() && queued_events_is_empty) {
  279. gettimeofday(&now, nullptr);
  280. get_next_timer_expiration(timeout);
  281. timeval_sub(timeout, now, timeout);
  282. } else {
  283. should_wait_forever = true;
  284. }
  285. } else {
  286. should_wait_forever = false;
  287. }
  288. int marked_fd_count = CSyscallUtils::safe_syscall(select, max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  289. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  290. char buffer[32];
  291. auto nread = read(s_wake_pipe_fds[0], buffer, sizeof(buffer));
  292. if (nread < 0) {
  293. perror("read from wake pipe");
  294. ASSERT_NOT_REACHED();
  295. }
  296. ASSERT(nread > 0);
  297. }
  298. if (!s_timers->is_empty()) {
  299. gettimeofday(&now, nullptr);
  300. }
  301. for (auto& it : *s_timers) {
  302. auto& timer = *it.value;
  303. if (!timer.has_expired(now))
  304. continue;
  305. #ifdef CEVENTLOOP_DEBUG
  306. dbg() << "CEventLoop: Timer " << timer.timer_id << " has expired, sending CTimerEvent to " << timer.owner;
  307. #endif
  308. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  309. if (timer.should_reload) {
  310. timer.reload(now);
  311. } else {
  312. // FIXME: Support removing expired timers that don't want to reload.
  313. ASSERT_NOT_REACHED();
  314. }
  315. }
  316. if (!marked_fd_count)
  317. return;
  318. for (auto& notifier : *s_notifiers) {
  319. if (FD_ISSET(notifier->fd(), &rfds)) {
  320. if (notifier->on_ready_to_read)
  321. post_event(*notifier, make<CNotifierReadEvent>(notifier->fd()));
  322. }
  323. if (FD_ISSET(notifier->fd(), &wfds)) {
  324. if (notifier->on_ready_to_write)
  325. post_event(*notifier, make<CNotifierWriteEvent>(notifier->fd()));
  326. }
  327. }
  328. }
  329. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  330. {
  331. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  332. }
  333. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  334. {
  335. fire_time = now;
  336. fire_time.tv_sec += interval / 1000;
  337. fire_time.tv_usec += (interval % 1000) * 1000;
  338. }
  339. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  340. {
  341. ASSERT(!s_timers->is_empty());
  342. bool has_checked_any = false;
  343. for (auto& it : *s_timers) {
  344. auto& fire_time = it.value->fire_time;
  345. 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))
  346. soonest = fire_time;
  347. has_checked_any = true;
  348. }
  349. }
  350. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  351. {
  352. ASSERT(milliseconds >= 0);
  353. auto timer = make<EventLoopTimer>();
  354. timer->owner = object.make_weak_ptr();
  355. timer->interval = milliseconds;
  356. timeval now;
  357. gettimeofday(&now, nullptr);
  358. timer->reload(now);
  359. timer->should_reload = should_reload;
  360. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  361. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  362. timer->timer_id = timer_id;
  363. s_timers->set(timer_id, move(timer));
  364. return timer_id;
  365. }
  366. bool CEventLoop::unregister_timer(int timer_id)
  367. {
  368. auto it = s_timers->find(timer_id);
  369. if (it == s_timers->end())
  370. return false;
  371. s_timers->remove(it);
  372. return true;
  373. }
  374. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  375. {
  376. s_notifiers->set(&notifier);
  377. }
  378. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  379. {
  380. s_notifiers->remove(&notifier);
  381. }
  382. void CEventLoop::wake()
  383. {
  384. char ch = '!';
  385. int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
  386. if (nwritten < 0) {
  387. perror("CEventLoop::wake: write");
  388. ASSERT_NOT_REACHED();
  389. }
  390. }