• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "src/ipc/client_impl.h"
18 
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <unistd.h>
22 
23 #include <utility>
24 
25 #include "perfetto/base/task_runner.h"
26 #include "perfetto/base/utils.h"
27 #include "perfetto/ipc/service_descriptor.h"
28 #include "perfetto/ipc/service_proxy.h"
29 
30 // TODO(primiano): Add ThreadChecker everywhere.
31 
32 // TODO(primiano): Add timeouts.
33 
34 namespace perfetto {
35 namespace ipc {
36 
37 // static
CreateInstance(const char * socket_name,base::TaskRunner * task_runner)38 std::unique_ptr<Client> Client::CreateInstance(const char* socket_name,
39                                                base::TaskRunner* task_runner) {
40   std::unique_ptr<Client> client(new ClientImpl(socket_name, task_runner));
41   return client;
42 }
43 
ClientImpl(const char * socket_name,base::TaskRunner * task_runner)44 ClientImpl::ClientImpl(const char* socket_name, base::TaskRunner* task_runner)
45     : task_runner_(task_runner), weak_ptr_factory_(this) {
46   GOOGLE_PROTOBUF_VERIFY_VERSION;
47   sock_ = base::UnixSocket::Connect(socket_name, this, task_runner);
48 }
49 
~ClientImpl()50 ClientImpl::~ClientImpl() {
51   // Ensure we are not destroyed in the middle of invoking a reply.
52   PERFETTO_DCHECK(!invoking_method_reply_);
53   OnDisconnect(
54       nullptr);  // The base::UnixSocket* ptr is not used in OnDisconnect().
55 }
56 
BindService(base::WeakPtr<ServiceProxy> service_proxy)57 void ClientImpl::BindService(base::WeakPtr<ServiceProxy> service_proxy) {
58   if (!service_proxy)
59     return;
60   if (!sock_->is_connected()) {
61     queued_bindings_.emplace_back(service_proxy);
62     return;
63   }
64   RequestID request_id = ++last_request_id_;
65   Frame frame;
66   frame.set_request_id(request_id);
67   Frame::BindService* req = frame.mutable_msg_bind_service();
68   const char* const service_name = service_proxy->GetDescriptor().service_name;
69   req->set_service_name(service_name);
70   if (!SendFrame(frame)) {
71     PERFETTO_DLOG("BindService(%s) failed", service_name);
72     return service_proxy->OnConnect(false /* success */);
73   }
74   QueuedRequest qr;
75   qr.type = Frame::kMsgBindService;
76   qr.request_id = request_id;
77   qr.service_proxy = service_proxy;
78   queued_requests_.emplace(request_id, std::move(qr));
79 }
80 
UnbindService(ServiceID service_id)81 void ClientImpl::UnbindService(ServiceID service_id) {
82   service_bindings_.erase(service_id);
83 }
84 
BeginInvoke(ServiceID service_id,const std::string & method_name,MethodID remote_method_id,const ProtoMessage & method_args,bool drop_reply,base::WeakPtr<ServiceProxy> service_proxy,int fd)85 RequestID ClientImpl::BeginInvoke(ServiceID service_id,
86                                   const std::string& method_name,
87                                   MethodID remote_method_id,
88                                   const ProtoMessage& method_args,
89                                   bool drop_reply,
90                                   base::WeakPtr<ServiceProxy> service_proxy,
91                                   int fd) {
92   std::string args_proto;
93   RequestID request_id = ++last_request_id_;
94   Frame frame;
95   frame.set_request_id(request_id);
96   Frame::InvokeMethod* req = frame.mutable_msg_invoke_method();
97   req->set_service_id(service_id);
98   req->set_method_id(remote_method_id);
99   req->set_drop_reply(drop_reply);
100   bool did_serialize = method_args.SerializeToString(&args_proto);
101   req->set_args_proto(args_proto);
102   if (!did_serialize || !SendFrame(frame, fd)) {
103     PERFETTO_DLOG("BeginInvoke() failed while sending the frame");
104     return 0;
105   }
106   if (drop_reply)
107     return 0;
108   QueuedRequest qr;
109   qr.type = Frame::kMsgInvokeMethod;
110   qr.request_id = request_id;
111   qr.method_name = method_name;
112   qr.service_proxy = std::move(service_proxy);
113   queued_requests_.emplace(request_id, std::move(qr));
114   return request_id;
115 }
116 
SendFrame(const Frame & frame,int fd)117 bool ClientImpl::SendFrame(const Frame& frame, int fd) {
118   // Serialize the frame into protobuf, add the size header, and send it.
119   std::string buf = BufferedFrameDeserializer::Serialize(frame);
120 
121   // TODO(primiano): this should do non-blocking I/O. But then what if the
122   // socket buffer is full? We might want to either drop the request or throttle
123   // the send and PostTask the reply later? Right now we are making Send()
124   // blocking as a workaround. Propagate bakpressure to the caller instead.
125   bool res = sock_->Send(buf.data(), buf.size(), fd,
126                          base::UnixSocket::BlockingMode::kBlocking);
127   PERFETTO_CHECK(res || !sock_->is_connected());
128   return res;
129 }
130 
OnConnect(base::UnixSocket *,bool connected)131 void ClientImpl::OnConnect(base::UnixSocket*, bool connected) {
132   // Drain the BindService() calls that were queued before establishig the
133   // connection with the host.
134   for (base::WeakPtr<ServiceProxy>& service_proxy : queued_bindings_) {
135     if (connected) {
136       BindService(service_proxy);
137     } else if (service_proxy) {
138       service_proxy->OnConnect(false /* success */);
139     }
140   }
141   queued_bindings_.clear();
142 }
143 
OnDisconnect(base::UnixSocket *)144 void ClientImpl::OnDisconnect(base::UnixSocket*) {
145   for (auto it : service_bindings_) {
146     base::WeakPtr<ServiceProxy>& service_proxy = it.second;
147     task_runner_->PostTask([service_proxy] {
148       if (service_proxy)
149         service_proxy->OnDisconnect();
150     });
151   }
152   service_bindings_.clear();
153   queued_bindings_.clear();
154 }
155 
OnDataAvailable(base::UnixSocket *)156 void ClientImpl::OnDataAvailable(base::UnixSocket*) {
157   size_t rsize;
158   do {
159     auto buf = frame_deserializer_.BeginReceive();
160     base::ScopedFile fd;
161     rsize = sock_->Receive(buf.data, buf.size, &fd);
162     if (fd) {
163       PERFETTO_DCHECK(!received_fd_);
164       int res = fcntl(*fd, F_SETFD, FD_CLOEXEC);
165       PERFETTO_DCHECK(res == 0);
166       received_fd_ = std::move(fd);
167     }
168     if (!frame_deserializer_.EndReceive(rsize)) {
169       // The endpoint tried to send a frame that is way too large.
170       return sock_->Shutdown(true);  // In turn will trigger an OnDisconnect().
171       // TODO(fmayer): check this.
172     }
173   } while (rsize > 0);
174 
175   while (std::unique_ptr<Frame> frame = frame_deserializer_.PopNextFrame())
176     OnFrameReceived(*frame);
177 }
178 
OnFrameReceived(const Frame & frame)179 void ClientImpl::OnFrameReceived(const Frame& frame) {
180   auto queued_requests_it = queued_requests_.find(frame.request_id());
181   if (queued_requests_it == queued_requests_.end()) {
182     PERFETTO_DLOG("OnFrameReceived(): got invalid request_id=%" PRIu64,
183                   static_cast<uint64_t>(frame.request_id()));
184     return;
185   }
186   QueuedRequest req = std::move(queued_requests_it->second);
187   queued_requests_.erase(queued_requests_it);
188 
189   if (req.type == Frame::kMsgBindService &&
190       frame.msg_case() == Frame::kMsgBindServiceReply) {
191     return OnBindServiceReply(std::move(req), frame.msg_bind_service_reply());
192   }
193   if (req.type == Frame::kMsgInvokeMethod &&
194       frame.msg_case() == Frame::kMsgInvokeMethodReply) {
195     return OnInvokeMethodReply(std::move(req), frame.msg_invoke_method_reply());
196   }
197   if (frame.msg_case() == Frame::kMsgRequestError) {
198     PERFETTO_DLOG("Host error: %s", frame.msg_request_error().error().c_str());
199     return;
200   }
201 
202   PERFETTO_DLOG(
203       "OnFrameReceived() request msg_type=%d, received msg_type=%d in reply to "
204       "request_id=%" PRIu64,
205       req.type, frame.msg_case(), static_cast<uint64_t>(frame.request_id()));
206 }
207 
OnBindServiceReply(QueuedRequest req,const Frame::BindServiceReply & reply)208 void ClientImpl::OnBindServiceReply(QueuedRequest req,
209                                     const Frame::BindServiceReply& reply) {
210   base::WeakPtr<ServiceProxy>& service_proxy = req.service_proxy;
211   if (!service_proxy)
212     return;
213   const char* svc_name = service_proxy->GetDescriptor().service_name;
214   if (!reply.success()) {
215     PERFETTO_DLOG("BindService(): unknown service_name=\"%s\"", svc_name);
216     return service_proxy->OnConnect(false /* success */);
217   }
218 
219   auto prev_service = service_bindings_.find(reply.service_id());
220   if (prev_service != service_bindings_.end() && prev_service->second.get()) {
221     PERFETTO_DLOG(
222         "BindService(): Trying to bind service \"%s\" but another service "
223         "named \"%s\" is already bound with the same ID.",
224         svc_name, prev_service->second->GetDescriptor().service_name);
225     return service_proxy->OnConnect(false /* success */);
226   }
227 
228   // Build the method [name] -> [remote_id] map.
229   std::map<std::string, MethodID> methods;
230   for (const auto& method : reply.methods()) {
231     if (method.name().empty() || method.id() <= 0) {
232       PERFETTO_DLOG("OnBindServiceReply(): invalid method \"%s\" -> %" PRIu64,
233                     method.name().c_str(), static_cast<uint64_t>(method.id()));
234       continue;
235     }
236     methods[method.name()] = method.id();
237   }
238   service_proxy->InitializeBinding(weak_ptr_factory_.GetWeakPtr(),
239                                    reply.service_id(), std::move(methods));
240   service_bindings_[reply.service_id()] = service_proxy;
241   service_proxy->OnConnect(true /* success */);
242 }
243 
OnInvokeMethodReply(QueuedRequest req,const Frame::InvokeMethodReply & reply)244 void ClientImpl::OnInvokeMethodReply(QueuedRequest req,
245                                      const Frame::InvokeMethodReply& reply) {
246   base::WeakPtr<ServiceProxy> service_proxy = req.service_proxy;
247   if (!service_proxy)
248     return;
249   std::unique_ptr<ProtoMessage> decoded_reply;
250   if (reply.success()) {
251     // If this becomes a hotspot, optimize by maintaining a dedicated hashtable.
252     for (const auto& method : service_proxy->GetDescriptor().methods) {
253       if (req.method_name == method.name) {
254         decoded_reply = method.reply_proto_decoder(reply.reply_proto());
255         break;
256       }
257     }
258   }
259   const RequestID request_id = req.request_id;
260   invoking_method_reply_ = true;
261   service_proxy->EndInvoke(request_id, std::move(decoded_reply),
262                            reply.has_more());
263   invoking_method_reply_ = false;
264 
265   // If this is a streaming method and future replies will be resolved, put back
266   // the |req| with the callback into the set of active requests.
267   if (reply.has_more())
268     queued_requests_.emplace(request_id, std::move(req));
269 }
270 
271 ClientImpl::QueuedRequest::QueuedRequest() = default;
272 
TakeReceivedFD()273 base::ScopedFile ClientImpl::TakeReceivedFD() {
274   return std::move(received_fd_);
275 }
276 
277 }  // namespace ipc
278 }  // namespace perfetto
279