• 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/ext/base/utils.h"
27 #include "perfetto/ext/ipc/service_descriptor.h"
28 #include "perfetto/ext/ipc/service_proxy.h"
29 
30 #include "protos/perfetto/ipc/wire_protocol.gen.h"
31 
32 // TODO(primiano): Add ThreadChecker everywhere.
33 
34 // TODO(primiano): Add timeouts.
35 
36 namespace perfetto {
37 namespace ipc {
38 
39 // static
CreateInstance(const char * socket_name,base::TaskRunner * task_runner)40 std::unique_ptr<Client> Client::CreateInstance(const char* socket_name,
41                                                base::TaskRunner* task_runner) {
42   std::unique_ptr<Client> client(new ClientImpl(socket_name, task_runner));
43   return client;
44 }
45 
ClientImpl(const char * socket_name,base::TaskRunner * task_runner)46 ClientImpl::ClientImpl(const char* socket_name, base::TaskRunner* task_runner)
47     : task_runner_(task_runner), weak_ptr_factory_(this) {
48   sock_ = base::UnixSocket::Connect(socket_name, this, task_runner,
49                                     base::SockFamily::kUnix,
50                                     base::SockType::kStream);
51 }
52 
~ClientImpl()53 ClientImpl::~ClientImpl() {
54   // Ensure we are not destroyed in the middle of invoking a reply.
55   PERFETTO_DCHECK(!invoking_method_reply_);
56   OnDisconnect(
57       nullptr);  // The base::UnixSocket* ptr is not used in OnDisconnect().
58 }
59 
BindService(base::WeakPtr<ServiceProxy> service_proxy)60 void ClientImpl::BindService(base::WeakPtr<ServiceProxy> service_proxy) {
61   if (!service_proxy)
62     return;
63   if (!sock_->is_connected()) {
64     queued_bindings_.emplace_back(service_proxy);
65     return;
66   }
67   RequestID request_id = ++last_request_id_;
68   Frame frame;
69   frame.set_request_id(request_id);
70   Frame::BindService* req = frame.mutable_msg_bind_service();
71   const char* const service_name = service_proxy->GetDescriptor().service_name;
72   req->set_service_name(service_name);
73   if (!SendFrame(frame)) {
74     PERFETTO_DLOG("BindService(%s) failed", service_name);
75     return service_proxy->OnConnect(false /* success */);
76   }
77   QueuedRequest qr;
78   qr.type = Frame::kMsgBindServiceFieldNumber;
79   qr.request_id = request_id;
80   qr.service_proxy = service_proxy;
81   queued_requests_.emplace(request_id, std::move(qr));
82 }
83 
UnbindService(ServiceID service_id)84 void ClientImpl::UnbindService(ServiceID service_id) {
85   service_bindings_.erase(service_id);
86 }
87 
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)88 RequestID ClientImpl::BeginInvoke(ServiceID service_id,
89                                   const std::string& method_name,
90                                   MethodID remote_method_id,
91                                   const ProtoMessage& method_args,
92                                   bool drop_reply,
93                                   base::WeakPtr<ServiceProxy> service_proxy,
94                                   int fd) {
95   RequestID request_id = ++last_request_id_;
96   Frame frame;
97   frame.set_request_id(request_id);
98   Frame::InvokeMethod* req = frame.mutable_msg_invoke_method();
99   req->set_service_id(service_id);
100   req->set_method_id(remote_method_id);
101   req->set_drop_reply(drop_reply);
102   req->set_args_proto(method_args.SerializeAsString());
103   if (!SendFrame(frame, fd)) {
104     PERFETTO_DLOG("BeginInvoke() failed while sending the frame");
105     return 0;
106   }
107   if (drop_reply)
108     return 0;
109   QueuedRequest qr;
110   qr.type = Frame::kMsgInvokeMethodFieldNumber;
111   qr.request_id = request_id;
112   qr.method_name = method_name;
113   qr.service_proxy = std::move(service_proxy);
114   queued_requests_.emplace(request_id, std::move(qr));
115   return request_id;
116 }
117 
SendFrame(const Frame & frame,int fd)118 bool ClientImpl::SendFrame(const Frame& frame, int fd) {
119   // Serialize the frame into protobuf, add the size header, and send it.
120   std::string buf = BufferedFrameDeserializer::Serialize(frame);
121 
122   // TODO(primiano): this should do non-blocking I/O. But then what if the
123   // socket buffer is full? We might want to either drop the request or throttle
124   // the send and PostTask the reply later? Right now we are making Send()
125   // blocking as a workaround. Propagate bakpressure to the caller instead.
126   bool res = sock_->Send(buf.data(), buf.size(), fd);
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::kMsgBindServiceFieldNumber &&
190       frame.has_msg_bind_service_reply()) {
191     return OnBindServiceReply(std::move(req), frame.msg_bind_service_reply());
192   }
193   if (req.type == Frame::kMsgInvokeMethodFieldNumber &&
194       frame.has_msg_invoke_method_reply()) {
195     return OnInvokeMethodReply(std::move(req), frame.msg_invoke_method_reply());
196   }
197   if (frame.has_msg_request_error()) {
198     PERFETTO_DLOG("Host error: %s", frame.msg_request_error().error().c_str());
199     return;
200   }
201 
202   PERFETTO_DLOG(
203       "OnFrameReceived() request type=%d, received unknown frame in reply to "
204       "request_id=%" PRIu64,
205       req.type, 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