1 /*
2 * Copyright (C) 2008 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 <errno.h>
18 #include <stdio.h>
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 #include <unistd.h>
22
23 #include "android-base/stringprintf.h"
24
25 #include "base/logging.h"
26 #include "jdwp/jdwp_priv.h"
27 #include "thread-inl.h"
28
29 #ifdef ART_TARGET_ANDROID
30 #include "cutils/sockets.h"
31 #endif
32
33 /*
34 * The JDWP <-> ADB transport protocol is explained in detail
35 * in system/core/adb/jdwp_service.c. Here's a summary.
36 *
37 * 1/ when the JDWP thread starts, it tries to connect to a Unix
38 * domain stream socket (@jdwp-control) that is opened by the
39 * ADB daemon.
40 *
41 * 2/ it then sends the current process PID as a string of 4 hexadecimal
42 * chars (no terminating zero)
43 *
44 * 3/ then, it uses recvmsg to receive file descriptors from the
45 * daemon. each incoming file descriptor is a pass-through to
46 * a given JDWP debugger, that can be used to read the usual
47 * JDWP-handshake, etc...
48 */
49
50 static constexpr char kJdwpControlName[] = "\0jdwp-control";
51 static constexpr size_t kJdwpControlNameLen = sizeof(kJdwpControlName) - 1;
52 /* This timeout is for connect/send with control socket. In practice, the
53 * connect should never timeout since it's just connect to a local unix domain
54 * socket. But in case adb is buggy and doesn't respond to any connection, the
55 * connect will block. For send, actually it would never block since we only send
56 * several bytes and the kernel buffer is big enough to accept it. 10 seconds
57 * should be far enough.
58 */
59 static constexpr int kControlSockSendTimeout = 10;
60
61 namespace art {
62
63 namespace JDWP {
64
65 using android::base::StringPrintf;
66
67 struct JdwpAdbState : public JdwpNetStateBase {
68 public:
JdwpAdbStateart::JDWP::JdwpAdbState69 explicit JdwpAdbState(JdwpState* state)
70 : JdwpNetStateBase(state),
71 state_lock_("JdwpAdbState lock", kJdwpAdbStateLock) {
72 control_sock_ = -1;
73 shutting_down_ = false;
74
75 control_addr_.controlAddrUn.sun_family = AF_UNIX;
76 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + kJdwpControlNameLen;
77 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, kJdwpControlNameLen);
78 }
79
~JdwpAdbStateart::JDWP::JdwpAdbState80 ~JdwpAdbState() {
81 if (clientSock != -1) {
82 shutdown(clientSock, SHUT_RDWR);
83 close(clientSock);
84 }
85 if (control_sock_ != -1) {
86 shutdown(control_sock_, SHUT_RDWR);
87 close(control_sock_);
88 }
89 }
90
91 virtual bool Accept() REQUIRES(!state_lock_);
92
Establishart::JDWP::JdwpAdbState93 virtual bool Establish(const JdwpOptions*) {
94 return false;
95 }
96
Shutdownart::JDWP::JdwpAdbState97 virtual void Shutdown() REQUIRES(!state_lock_) {
98 int control_sock;
99 int local_clientSock;
100 {
101 MutexLock mu(Thread::Current(), state_lock_);
102 shutting_down_ = true;
103 control_sock = this->control_sock_;
104 local_clientSock = this->clientSock;
105 /* clear these out so it doesn't wake up and try to reuse them */
106 this->control_sock_ = this->clientSock = -1;
107 }
108
109 if (local_clientSock != -1) {
110 shutdown(local_clientSock, SHUT_RDWR);
111 }
112
113 if (control_sock != -1) {
114 shutdown(control_sock, SHUT_RDWR);
115 }
116
117 WakePipe();
118 }
119
120 virtual bool ProcessIncoming() REQUIRES(!state_lock_);
121
122 private:
123 int ReceiveClientFd() REQUIRES(!state_lock_);
124
IsDownart::JDWP::JdwpAdbState125 bool IsDown() REQUIRES(!state_lock_) {
126 MutexLock mu(Thread::Current(), state_lock_);
127 return shutting_down_;
128 }
129
ControlSockart::JDWP::JdwpAdbState130 int ControlSock() REQUIRES(!state_lock_) {
131 MutexLock mu(Thread::Current(), state_lock_);
132 if (shutting_down_) {
133 CHECK_EQ(control_sock_, -1);
134 }
135 return control_sock_;
136 }
137
138 int control_sock_ GUARDED_BY(state_lock_);
139 bool shutting_down_ GUARDED_BY(state_lock_);
140 Mutex state_lock_;
141
142 socklen_t control_addr_len_;
143 union {
144 sockaddr_un controlAddrUn;
145 sockaddr controlAddrPlain;
146 } control_addr_;
147 };
148
149 /*
150 * Do initial prep work, e.g. binding to ports and opening files. This
151 * runs in the main thread, before the JDWP thread starts, so it shouldn't
152 * do anything that might block forever.
153 */
InitAdbTransport(JdwpState * state,const JdwpOptions *)154 bool InitAdbTransport(JdwpState* state, const JdwpOptions*) {
155 VLOG(jdwp) << "ADB transport startup";
156 state->netState = new JdwpAdbState(state);
157 return (state->netState != nullptr);
158 }
159
160 /*
161 * Receive a file descriptor from ADB. The fd can be used to communicate
162 * directly with a debugger or DDMS.
163 *
164 * Returns the file descriptor on success. On failure, returns -1 and
165 * closes netState->control_sock_.
166 */
ReceiveClientFd()167 int JdwpAdbState::ReceiveClientFd() {
168 char dummy = '!';
169 union {
170 cmsghdr cm;
171 char buffer[CMSG_SPACE(sizeof(int))];
172 } cm_un;
173
174 iovec iov;
175 iov.iov_base = &dummy;
176 iov.iov_len = 1;
177
178 msghdr msg;
179 msg.msg_name = nullptr;
180 msg.msg_namelen = 0;
181 msg.msg_iov = &iov;
182 msg.msg_iovlen = 1;
183 msg.msg_flags = 0;
184 msg.msg_control = cm_un.buffer;
185 msg.msg_controllen = sizeof(cm_un.buffer);
186
187 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
188 cmsg->cmsg_len = msg.msg_controllen;
189 cmsg->cmsg_level = SOL_SOCKET;
190 cmsg->cmsg_type = SCM_RIGHTS;
191 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
192
193 int rc = TEMP_FAILURE_RETRY(recvmsg(ControlSock(), &msg, 0));
194
195 if (rc <= 0) {
196 if (rc == -1) {
197 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << ControlSock() << ")";
198 }
199 MutexLock mu(Thread::Current(), state_lock_);
200 close(control_sock_);
201 control_sock_ = -1;
202 return -1;
203 }
204
205 return (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0];
206 }
207
208 /*
209 * Block forever, waiting for a debugger to connect to us. Called from the
210 * JDWP thread.
211 *
212 * This needs to un-block and return "false" if the VM is shutting down. It
213 * should return "true" when it successfully accepts a connection.
214 */
Accept()215 bool JdwpAdbState::Accept() {
216 int retryCount = 0;
217
218 /* first, ensure that we get a connection to the ADB daemon */
219
220 retry:
221 if (IsDown()) {
222 return false;
223 }
224
225 if (ControlSock() == -1) {
226 int sleep_ms = 500;
227 const int sleep_max_ms = 2*1000;
228 char buff[5];
229
230 int sock = socket(AF_UNIX, SOCK_SEQPACKET, 0);
231 if (sock < 0) {
232 PLOG(ERROR) << "Could not create ADB control socket";
233 return false;
234 }
235 struct timeval timeout;
236 timeout.tv_sec = kControlSockSendTimeout;
237 timeout.tv_usec = 0;
238 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
239 {
240 MutexLock mu(Thread::Current(), state_lock_);
241 control_sock_ = sock;
242 if (shutting_down_) {
243 return false;
244 }
245 if (!MakePipe()) {
246 return false;
247 }
248 }
249
250 snprintf(buff, sizeof(buff), "%04x", getpid());
251 buff[4] = 0;
252
253 for (;;) {
254 /*
255 * If adbd isn't running, because USB debugging was disabled or
256 * perhaps the system is restarting it for "adb root", the
257 * connect() will fail. We loop here forever waiting for it
258 * to come back.
259 *
260 * Waking up and polling every couple of seconds is generally a
261 * bad thing to do, but we only do this if the application is
262 * debuggable *and* adbd isn't running. Still, for the sake
263 * of battery life, we should consider timing out and giving
264 * up after a few minutes in case somebody ships an app with
265 * the debuggable flag set.
266 */
267 int ret = connect(ControlSock(), &control_addr_.controlAddrPlain, control_addr_len_);
268 if (!ret) {
269 int control_sock = ControlSock();
270 #ifdef ART_TARGET_ANDROID
271 if (control_sock < 0 || !socket_peer_is_trusted(control_sock)) {
272 if (control_sock >= 0 && shutdown(control_sock, SHUT_RDWR)) {
273 PLOG(ERROR) << "trouble shutting down socket";
274 }
275 return false;
276 }
277 #endif
278
279 /* now try to send our pid to the ADB daemon */
280 ret = TEMP_FAILURE_RETRY(send(control_sock, buff, 4, 0));
281 if (ret == 4) {
282 VLOG(jdwp) << StringPrintf("PID sent as '%.*s' to ADB", 4, buff);
283 break;
284 }
285
286 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB";
287 return false;
288 }
289 if (VLOG_IS_ON(jdwp)) {
290 PLOG(ERROR) << "Can't connect to ADB control socket";
291 }
292
293 usleep(sleep_ms * 1000);
294
295 sleep_ms += (sleep_ms >> 1);
296 if (sleep_ms > sleep_max_ms) {
297 sleep_ms = sleep_max_ms;
298 }
299 if (IsDown()) {
300 return false;
301 }
302 }
303 }
304
305 VLOG(jdwp) << "trying to receive file descriptor from ADB";
306 /* now we can receive a client file descriptor */
307 int sock = ReceiveClientFd();
308 {
309 MutexLock mu(Thread::Current(), state_lock_);
310 clientSock = sock;
311 if (shutting_down_) {
312 return false; // suppress logs and additional activity
313 }
314 }
315 if (clientSock == -1) {
316 if (++retryCount > 5) {
317 LOG(ERROR) << "adb connection max retries exceeded";
318 return false;
319 }
320 goto retry;
321 } else {
322 VLOG(jdwp) << "received file descriptor " << clientSock << " from ADB";
323 SetAwaitingHandshake(true);
324 input_count_ = 0;
325 return true;
326 }
327 }
328
329 /*
330 * Process incoming data. If no data is available, this will block until
331 * some arrives.
332 *
333 * If we get a full packet, handle it.
334 *
335 * To take some of the mystery out of life, we want to reject incoming
336 * connections if we already have a debugger attached. If we don't, the
337 * debugger will just mysteriously hang until it times out. We could just
338 * close the listen socket, but there's a good chance we won't be able to
339 * bind to the same port again, which would confuse utilities.
340 *
341 * Returns "false" on error (indicating that the connection has been severed),
342 * "true" if things are still okay.
343 */
ProcessIncoming()344 bool JdwpAdbState::ProcessIncoming() {
345 int readCount;
346
347 CHECK_NE(clientSock, -1);
348
349 if (!HaveFullPacket()) {
350 /* read some more, looping until we have data */
351 errno = 0;
352 while (1) {
353 int selCount;
354 fd_set readfds;
355 int maxfd = -1;
356 int fd;
357
358 FD_ZERO(&readfds);
359
360 /* configure fds; note these may get zapped by another thread */
361 fd = ControlSock();
362 if (fd >= 0) {
363 FD_SET(fd, &readfds);
364 if (maxfd < fd) {
365 maxfd = fd;
366 }
367 }
368 fd = clientSock;
369 if (fd >= 0) {
370 FD_SET(fd, &readfds);
371 if (maxfd < fd) {
372 maxfd = fd;
373 }
374 }
375 fd = wake_pipe_[0];
376 if (fd >= 0) {
377 FD_SET(fd, &readfds);
378 if (maxfd < fd) {
379 maxfd = fd;
380 }
381 } else {
382 LOG(INFO) << "NOTE: entering select w/o wakepipe";
383 }
384
385 if (maxfd < 0) {
386 VLOG(jdwp) << "+++ all fds are closed";
387 return false;
388 }
389
390 /*
391 * Select blocks until it sees activity on the file descriptors.
392 * Closing the local file descriptor does not count as activity,
393 * so we can't rely on that to wake us up (it works for read()
394 * and accept(), but not select()).
395 *
396 * We can do one of three things: (1) send a signal and catch
397 * EINTR, (2) open an additional fd ("wake pipe") and write to
398 * it when it's time to exit, or (3) time out periodically and
399 * re-issue the select. We're currently using #2, as it's more
400 * reliable than #1 and generally better than #3. Wastes two fds.
401 */
402 selCount = select(maxfd + 1, &readfds, nullptr, nullptr, nullptr);
403 if (selCount < 0) {
404 if (errno == EINTR) {
405 continue;
406 }
407 PLOG(ERROR) << "select failed";
408 goto fail;
409 }
410
411 if (wake_pipe_[0] >= 0 && FD_ISSET(wake_pipe_[0], &readfds)) {
412 VLOG(jdwp) << "Got wake-up signal, bailing out of select";
413 goto fail;
414 }
415 int control_sock = ControlSock();
416 if (control_sock >= 0 && FD_ISSET(control_sock, &readfds)) {
417 int sock = ReceiveClientFd();
418 if (sock >= 0) {
419 LOG(INFO) << "Ignoring second debugger -- accepting and dropping";
420 close(sock);
421 } else {
422 CHECK_EQ(ControlSock(), -1);
423 /*
424 * Remote side most likely went away, so our next read
425 * on clientSock will fail and throw us out of the loop.
426 */
427 }
428 }
429 if (clientSock >= 0 && FD_ISSET(clientSock, &readfds)) {
430 readCount = read(clientSock, input_buffer_ + input_count_, sizeof(input_buffer_) - input_count_);
431 if (readCount < 0) {
432 /* read failed */
433 if (errno != EINTR) {
434 goto fail;
435 }
436 VLOG(jdwp) << "+++ EINTR hit";
437 return true;
438 } else if (readCount == 0) {
439 /* EOF hit -- far end went away */
440 VLOG(jdwp) << "+++ peer disconnected";
441 goto fail;
442 } else {
443 break;
444 }
445 }
446 }
447
448 input_count_ += readCount;
449 if (!HaveFullPacket()) {
450 return true; /* still not there yet */
451 }
452 }
453
454 /*
455 * Special-case the initial handshake. For some bizarre reason we're
456 * expected to emulate bad tty settings by echoing the request back
457 * exactly as it was sent. Note the handshake is always initiated by
458 * the debugger, no matter who connects to whom.
459 *
460 * Other than this one case, the protocol [claims to be] stateless.
461 */
462 if (IsAwaitingHandshake()) {
463 if (memcmp(input_buffer_, kMagicHandshake, kMagicHandshakeLen) != 0) {
464 LOG(ERROR) << StringPrintf("ERROR: bad handshake '%.14s'", input_buffer_);
465 goto fail;
466 }
467
468 errno = 0;
469 int cc = TEMP_FAILURE_RETRY(write(clientSock, input_buffer_, kMagicHandshakeLen));
470 if (cc != kMagicHandshakeLen) {
471 PLOG(ERROR) << "Failed writing handshake bytes (" << cc << " of " << kMagicHandshakeLen << ")";
472 goto fail;
473 }
474
475 ConsumeBytes(kMagicHandshakeLen);
476 SetAwaitingHandshake(false);
477 VLOG(jdwp) << "+++ handshake complete";
478 return true;
479 }
480
481 /*
482 * Handle this packet.
483 */
484 return state_->HandlePacket();
485
486 fail:
487 Close();
488 return false;
489 }
490
491 } // namespace JDWP
492
493 } // namespace art
494