blob: 3a89f34628f6fc8c4db714ac35f4d6cbd8ec509d [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
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 "logging.h"
18#include "jdwp/jdwp_priv.h"
19#include "jdwp/jdwp_handler.h"
20#include "stringprintf.h"
21
22#include <errno.h>
23#include <stdio.h>
24#include <sys/socket.h>
25#include <sys/un.h>
26#include <unistd.h>
27
28#ifdef HAVE_ANDROID_OS
29#include "cutils/sockets.h"
30#endif
31
32/*
33 * The JDWP <-> ADB transport protocol is explained in detail
34 * in system/core/adb/jdwp_service.c. Here's a summary.
35 *
36 * 1/ when the JDWP thread starts, it tries to connect to a Unix
37 * domain stream socket (@jdwp-control) that is opened by the
38 * ADB daemon.
39 *
40 * 2/ it then sends the current process PID as a string of 4 hexadecimal
41 * chars (no terminating zero)
42 *
43 * 3/ then, it uses recvmsg to receive file descriptors from the
44 * daemon. each incoming file descriptor is a pass-through to
45 * a given JDWP debugger, that can be used to read the usual
46 * JDWP-handshake, etc...
47 */
48
49#define kInputBufferSize 8192
50
51#define kMagicHandshake "JDWP-Handshake"
52#define kMagicHandshakeLen (sizeof(kMagicHandshake)-1)
53
54#define kJdwpControlName "\0jdwp-control"
55#define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
56
57namespace art {
58
59namespace JDWP {
60
61struct JdwpNetState : public JdwpNetStateBase {
62 int controlSock;
63 bool awaitingHandshake;
64 bool shuttingDown;
65 int wakeFds[2];
66
67 int inputCount;
68 unsigned char inputBuffer[kInputBufferSize];
69
70 socklen_t controlAddrLen;
71 union {
72 struct sockaddr_un controlAddrUn;
73 struct sockaddr controlAddrPlain;
74 } controlAddr;
75
76 JdwpNetState() {
77 controlSock = -1;
78 awaitingHandshake = false;
79 shuttingDown = false;
80 wakeFds[0] = -1;
81 wakeFds[1] = -1;
82
83 inputCount = 0;
84
85 controlAddr.controlAddrUn.sun_family = AF_UNIX;
86 controlAddrLen = sizeof(controlAddr.controlAddrUn.sun_family) + kJdwpControlNameLen;
87 memcpy(controlAddr.controlAddrUn.sun_path, kJdwpControlName, kJdwpControlNameLen);
88 }
89};
90
91static void adbStateFree(JdwpNetState* netState) {
92 if (netState == NULL) {
93 return;
94 }
95
96 if (netState->clientSock >= 0) {
97 shutdown(netState->clientSock, SHUT_RDWR);
98 close(netState->clientSock);
99 }
100 if (netState->controlSock >= 0) {
101 shutdown(netState->controlSock, SHUT_RDWR);
102 close(netState->controlSock);
103 }
104 if (netState->wakeFds[0] >= 0) {
105 close(netState->wakeFds[0]);
106 netState->wakeFds[0] = -1;
107 }
108 if (netState->wakeFds[1] >= 0) {
109 close(netState->wakeFds[1]);
110 netState->wakeFds[1] = -1;
111 }
112
113 delete netState;
114}
115
116/*
117 * Do initial prep work, e.g. binding to ports and opening files. This
118 * runs in the main thread, before the JDWP thread starts, so it shouldn't
119 * do anything that might block forever.
120 */
121static bool startup(JdwpState* state, const JdwpStartupParams* pParams) {
122 JdwpNetState* netState;
123
124 LOG(VERBOSE) << "ADB transport startup";
125
126 state->netState = netState = new JdwpNetState;
127 if (netState == NULL) {
128 return false;
129 }
130 return true;
131}
132
133/*
134 * Receive a file descriptor from ADB. The fd can be used to communicate
135 * directly with a debugger or DDMS.
136 *
137 * Returns the file descriptor on success. On failure, returns -1 and
138 * closes netState->controlSock.
139 */
140static int receiveClientFd(JdwpNetState* netState) {
141 struct msghdr msg;
142 struct cmsghdr* cmsg;
143 iovec iov;
144 char dummy = '!';
145 union {
146 struct cmsghdr cm;
147 char buffer[CMSG_SPACE(sizeof(int))];
148 } cm_un;
149 int ret;
150
151 iov.iov_base = &dummy;
152 iov.iov_len = 1;
153 msg.msg_name = NULL;
154 msg.msg_namelen = 0;
155 msg.msg_iov = &iov;
156 msg.msg_iovlen = 1;
157 msg.msg_flags = 0;
158 msg.msg_control = cm_un.buffer;
159 msg.msg_controllen = sizeof(cm_un.buffer);
160
161 cmsg = CMSG_FIRSTHDR(&msg);
162 cmsg->cmsg_len = msg.msg_controllen;
163 cmsg->cmsg_level = SOL_SOCKET;
164 cmsg->cmsg_type = SCM_RIGHTS;
165 ((int*)(void*)CMSG_DATA(cmsg))[0] = -1;
166
167 do {
168 ret = recvmsg(netState->controlSock, &msg, 0);
169 } while (ret < 0 && errno == EINTR);
170
171 if (ret <= 0) {
172 if (ret < 0) {
173 PLOG(WARNING) << "receiving file descriptor from ADB failed (socket " << netState->controlSock << ")";
174 }
175 close(netState->controlSock);
176 netState->controlSock = -1;
177 return -1;
178 }
179
180 return ((int*)(void*)CMSG_DATA(cmsg))[0];
181}
182
183/*
184 * Block forever, waiting for a debugger to connect to us. Called from the
185 * JDWP thread.
186 *
187 * This needs to un-block and return "false" if the VM is shutting down. It
188 * should return "true" when it successfully accepts a connection.
189 */
190static bool acceptConnection(JdwpState* state) {
191 JdwpNetState* netState = state->netState;
192 int retryCount = 0;
193
194 /* first, ensure that we get a connection to the ADB daemon */
195
196retry:
197 if (netState->shuttingDown) {
198 return false;
199 }
200
201 if (netState->controlSock < 0) {
202 int sleep_ms = 500;
203 const int sleep_max_ms = 2*1000;
204 char buff[5];
205
206 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
207 if (netState->controlSock < 0) {
208 PLOG(ERROR) << "Could not create ADB control socket";
209 return false;
210 }
211
212 if (pipe(netState->wakeFds) < 0) {
213 PLOG(ERROR) << "pipe failed";
214 return false;
215 }
216
217 snprintf(buff, sizeof(buff), "%04x", getpid());
218 buff[4] = 0;
219
220 for (;;) {
221 /*
222 * If adbd isn't running, because USB debugging was disabled or
223 * perhaps the system is restarting it for "adb root", the
224 * connect() will fail. We loop here forever waiting for it
225 * to come back.
226 *
227 * Waking up and polling every couple of seconds is generally a
228 * bad thing to do, but we only do this if the application is
229 * debuggable *and* adbd isn't running. Still, for the sake
230 * of battery life, we should consider timing out and giving
231 * up after a few minutes in case somebody ships an app with
232 * the debuggable flag set.
233 */
234 int ret = connect(netState->controlSock, &netState->controlAddr.controlAddrPlain, netState->controlAddrLen);
235 if (!ret) {
236#ifdef HAVE_ANDROID_OS
237 if (!socket_peer_is_trusted(netState->controlSock)) {
238 if (shutdown(netState->controlSock, SHUT_RDWR)) {
239 PLOG(ERROR) << "trouble shutting down socket";
240 }
241 return false;
242 }
243#endif
244
245 /* now try to send our pid to the ADB daemon */
246 do {
247 ret = send( netState->controlSock, buff, 4, 0 );
248 } while (ret < 0 && errno == EINTR);
249
250 if (ret >= 0) {
251 LOG(VERBOSE) << StringPrintf("PID sent as '%.*s' to ADB", 4, buff);
252 break;
253 }
254
255 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB";
256 return false;
257 }
258 PLOG(VERBOSE) << "Can't connect to ADB control socket";
259
260 usleep( sleep_ms*1000 );
261
262 sleep_ms += (sleep_ms >> 1);
263 if (sleep_ms > sleep_max_ms) {
264 sleep_ms = sleep_max_ms;
265 }
266 if (netState->shuttingDown) {
267 return false;
268 }
269 }
270 }
271
272 LOG(VERBOSE) << "trying to receive file descriptor from ADB";
273 /* now we can receive a client file descriptor */
274 netState->clientSock = receiveClientFd(netState);
275 if (netState->shuttingDown) {
276 return false; // suppress logs and additional activity
277 }
278 if (netState->clientSock < 0) {
279 if (++retryCount > 5) {
280 LOG(ERROR) << "adb connection max retries exceeded";
281 return false;
282 }
283 goto retry;
284 } else {
285 LOG(VERBOSE) << "received file descriptor " << netState->clientSock << " from ADB";
286 netState->awaitingHandshake = 1;
287 netState->inputCount = 0;
288 return true;
289 }
290}
291
292/*
293 * Connect out to a debugger (for server=n). Not required.
294 */
295static bool establishConnection(JdwpState* state) {
296 return false;
297}
298
299/*
300 * Close a connection from a debugger (which may have already dropped us).
301 * Only called from the JDWP thread.
302 */
303static void closeConnection(JdwpState* state) {
304 CHECK(state != NULL && state->netState != NULL);
305
306 JdwpNetState* netState = state->netState;
307 if (netState->clientSock < 0) {
308 return;
309 }
310
311 LOG(VERBOSE) << "+++ closed JDWP <-> ADB connection";
312
313 close(netState->clientSock);
314 netState->clientSock = -1;
315}
316
317/*
318 * Close all network stuff, including the socket we use to listen for
319 * new connections.
320 *
321 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
322 */
323static void adbStateShutdown(JdwpNetState* netState) {
324 int controlSock;
325 int clientSock;
326
327 if (netState == NULL) {
328 return;
329 }
330
331 netState->shuttingDown = true;
332
333 clientSock = netState->clientSock;
334 if (clientSock >= 0) {
335 shutdown(clientSock, SHUT_RDWR);
336 netState->clientSock = -1;
337 }
338
339 controlSock = netState->controlSock;
340 if (controlSock >= 0) {
341 shutdown(controlSock, SHUT_RDWR);
342 netState->controlSock = -1;
343 }
344
345 if (netState->wakeFds[1] >= 0) {
346 LOG(VERBOSE) << "+++ writing to wakePipe";
347 write(netState->wakeFds[1], "", 1);
348 }
349}
350
351static void netShutdown(JdwpState* state) {
352 adbStateShutdown(state->netState);
353}
354
355/*
356 * Free up anything we put in state->netState. This is called after
357 * "netShutdown", after the JDWP thread has stopped.
358 */
359static void netFree(JdwpState* state) {
360 JdwpNetState* netState = state->netState;
361 adbStateFree(netState);
362}
363
364/*
365 * Is a debugger connected to us?
366 */
367static bool isConnected(JdwpState* state) {
368 return (state->netState != NULL && state->netState->clientSock >= 0);
369}
370
371/*
372 * Are we still waiting for the JDWP handshake?
373 */
374static bool awaitingHandshake(JdwpState* state) {
375 return state->netState->awaitingHandshake;
376}
377
378/*
379 * Figure out if we have a full packet in the buffer.
380 */
381static bool haveFullPacket(JdwpNetState* netState) {
382 if (netState->awaitingHandshake) {
383 return (netState->inputCount >= (int) kMagicHandshakeLen);
384 }
385 if (netState->inputCount < 4) {
386 return false;
387 }
388 long length = get4BE(netState->inputBuffer);
389 return (netState->inputCount >= length);
390}
391
392/*
393 * Consume bytes from the buffer.
394 *
395 * This would be more efficient with a circular buffer. However, we're
396 * usually only going to find one packet, which is trivial to handle.
397 */
398static void consumeBytes(JdwpNetState* netState, int count) {
399 CHECK_GT(count, 0);
400 CHECK_LE(count, netState->inputCount);
401
402 if (count == netState->inputCount) {
403 netState->inputCount = 0;
404 return;
405 }
406
407 memmove(netState->inputBuffer, netState->inputBuffer + count, netState->inputCount - count);
408 netState->inputCount -= count;
409}
410
411/*
412 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
413 */
414static bool handlePacket(JdwpState* state) {
415 JdwpNetState* netState = state->netState;
416 const unsigned char* buf = netState->inputBuffer;
417 JdwpReqHeader hdr;
418 uint32_t length, id;
419 uint8_t flags, cmdSet, cmd;
420 uint16_t error;
421 bool reply;
422 int dataLen;
423
424 cmd = cmdSet = 0; // shut up gcc
425
426 length = read4BE(&buf);
427 id = read4BE(&buf);
428 flags = read1(&buf);
429 if ((flags & kJDWPFlagReply) != 0) {
430 reply = true;
431 error = read2BE(&buf);
432 } else {
433 reply = false;
434 cmdSet = read1(&buf);
435 cmd = read1(&buf);
436 }
437
438 CHECK_LE((int) length, netState->inputCount);
439 dataLen = length - (buf - netState->inputBuffer);
440
441 if (!reply) {
442 ExpandBuf* pReply = expandBufAlloc();
443
444 hdr.length = length;
445 hdr.id = id;
446 hdr.cmdSet = cmdSet;
447 hdr.cmd = cmd;
448 ProcessRequest(state, &hdr, buf, dataLen, pReply);
449 if (expandBufGetLength(pReply) > 0) {
450 ssize_t cc = netState->writePacket(pReply);
451
452 if (cc != (ssize_t) expandBufGetLength(pReply)) {
453 PLOG(ERROR) << "Failed sending reply to debugger";
454 expandBufFree(pReply);
455 return false;
456 }
457 } else {
458 LOG(WARNING) << "No reply created for set=" << cmdSet << " cmd=" << cmd;
459 }
460 expandBufFree(pReply);
461 } else {
462 LOG(FATAL) << "reply?!";
463 }
464
465 LOG(VERBOSE) << "----------";
466
467 consumeBytes(netState, length);
468 return true;
469}
470
471/*
472 * Process incoming data. If no data is available, this will block until
473 * some arrives.
474 *
475 * If we get a full packet, handle it.
476 *
477 * To take some of the mystery out of life, we want to reject incoming
478 * connections if we already have a debugger attached. If we don't, the
479 * debugger will just mysteriously hang until it times out. We could just
480 * close the listen socket, but there's a good chance we won't be able to
481 * bind to the same port again, which would confuse utilities.
482 *
483 * Returns "false" on error (indicating that the connection has been severed),
484 * "true" if things are still okay.
485 */
486static bool processIncoming(JdwpState* state) {
487 JdwpNetState* netState = state->netState;
488 int readCount;
489
490 CHECK_GE(netState->clientSock, 0);
491
492 if (!haveFullPacket(netState)) {
493 /* read some more, looping until we have data */
494 errno = 0;
495 while (1) {
496 int selCount;
497 fd_set readfds;
498 int maxfd = -1;
499 int fd;
500
501 FD_ZERO(&readfds);
502
503 /* configure fds; note these may get zapped by another thread */
504 fd = netState->controlSock;
505 if (fd >= 0) {
506 FD_SET(fd, &readfds);
507 if (maxfd < fd) {
508 maxfd = fd;
509 }
510 }
511 fd = netState->clientSock;
512 if (fd >= 0) {
513 FD_SET(fd, &readfds);
514 if (maxfd < fd) {
515 maxfd = fd;
516 }
517 }
518 fd = netState->wakeFds[0];
519 if (fd >= 0) {
520 FD_SET(fd, &readfds);
521 if (maxfd < fd) {
522 maxfd = fd;
523 }
524 } else {
525 LOG(INFO) << "NOTE: entering select w/o wakepipe";
526 }
527
528 if (maxfd < 0) {
529 LOG(VERBOSE) << "+++ all fds are closed";
530 return false;
531 }
532
533 /*
534 * Select blocks until it sees activity on the file descriptors.
535 * Closing the local file descriptor does not count as activity,
536 * so we can't rely on that to wake us up (it works for read()
537 * and accept(), but not select()).
538 *
539 * We can do one of three things: (1) send a signal and catch
540 * EINTR, (2) open an additional fd ("wakePipe") and write to
541 * it when it's time to exit, or (3) time out periodically and
542 * re-issue the select. We're currently using #2, as it's more
543 * reliable than #1 and generally better than #3. Wastes two fds.
544 */
545 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
546 if (selCount < 0) {
547 if (errno == EINTR) {
548 continue;
549 }
550 PLOG(ERROR) << "select failed";
551 goto fail;
552 }
553
554 if (netState->wakeFds[0] >= 0 && FD_ISSET(netState->wakeFds[0], &readfds)) {
555 LOG(DEBUG) << "Got wake-up signal, bailing out of select";
556 goto fail;
557 }
558 if (netState->controlSock >= 0 && FD_ISSET(netState->controlSock, &readfds)) {
559 int sock = receiveClientFd(netState);
560 if (sock >= 0) {
561 LOG(INFO) << "Ignoring second debugger -- accepting and dropping";
562 close(sock);
563 } else {
564 CHECK_LT(netState->controlSock, 0);
565 /*
566 * Remote side most likely went away, so our next read
567 * on netState->clientSock will fail and throw us out
568 * of the loop.
569 */
570 }
571 }
572 if (netState->clientSock >= 0 && FD_ISSET(netState->clientSock, &readfds)) {
573 readCount = read(netState->clientSock, netState->inputBuffer + netState->inputCount, sizeof(netState->inputBuffer) - netState->inputCount);
574 if (readCount < 0) {
575 /* read failed */
576 if (errno != EINTR) {
577 goto fail;
578 }
579 LOG(DEBUG) << "+++ EINTR hit";
580 return true;
581 } else if (readCount == 0) {
582 /* EOF hit -- far end went away */
583 LOG(VERBOSE) << "+++ peer disconnected";
584 goto fail;
585 } else {
586 break;
587 }
588 }
589 }
590
591 netState->inputCount += readCount;
592 if (!haveFullPacket(netState)) {
593 return true; /* still not there yet */
594 }
595 }
596
597 /*
598 * Special-case the initial handshake. For some bizarre reason we're
599 * expected to emulate bad tty settings by echoing the request back
600 * exactly as it was sent. Note the handshake is always initiated by
601 * the debugger, no matter who connects to whom.
602 *
603 * Other than this one case, the protocol [claims to be] stateless.
604 */
605 if (netState->awaitingHandshake) {
606 int cc;
607
608 if (memcmp(netState->inputBuffer, kMagicHandshake, kMagicHandshakeLen) != 0) {
609 LOG(ERROR) << StringPrintf("ERROR: bad handshake '%.14s'", netState->inputBuffer);
610 goto fail;
611 }
612
613 errno = 0;
614 cc = write(netState->clientSock, netState->inputBuffer, kMagicHandshakeLen);
615 if (cc != kMagicHandshakeLen) {
616 PLOG(ERROR) << "Failed writing handshake bytes (" << cc << " of " << kMagicHandshakeLen << ")";
617 goto fail;
618 }
619
620 consumeBytes(netState, kMagicHandshakeLen);
621 netState->awaitingHandshake = false;
622 LOG(VERBOSE) << "+++ handshake complete";
623 return true;
624 }
625
626 /*
627 * Handle this packet.
628 */
629 return handlePacket(state);
630
631fail:
632 closeConnection(state);
633 return false;
634}
635
636/*
637 * Send a request.
638 *
639 * The entire packet must be sent with a single write() call to avoid
640 * threading issues.
641 *
642 * Returns "true" if it was sent successfully.
643 */
644static bool sendRequest(JdwpState* state, ExpandBuf* pReq) {
645 JdwpNetState* netState = state->netState;
646
647 if (netState->clientSock < 0) {
648 /* can happen with some DDMS events */
649 LOG(VERBOSE) << "NOT sending request -- no debugger is attached";
650 return false;
651 }
652
653 errno = 0;
654
655 ssize_t cc = netState->writePacket(pReq);
656
657 if (cc != (ssize_t) expandBufGetLength(pReq)) {
658 PLOG(ERROR) << "Failed sending req to debugger (" << cc << " of " << expandBufGetLength(pReq) << ")";
659 return false;
660 }
661
662 return true;
663}
664
665/*
666 * Send a request that was split into multiple buffers.
667 *
668 * The entire packet must be sent with a single writev() call to avoid
669 * threading issues.
670 *
671 * Returns "true" if it was sent successfully.
672 */
673static bool sendBufferedRequest(JdwpState* state, const iovec* iov, int iovcnt) {
674 JdwpNetState* netState = state->netState;
675
676 if (netState->clientSock < 0) {
677 /* can happen with some DDMS events */
678 LOG(VERBOSE) << "NOT sending request -- no debugger is attached";
679 return false;
680 }
681
682 size_t expected = 0;
683 int i;
684 for (i = 0; i < iovcnt; i++) {
685 expected += iov[i].iov_len;
686 }
687
688 ssize_t actual = netState->writeBufferedPacket(iov, iovcnt);
689 if ((size_t)actual != expected) {
690 PLOG(ERROR) << "Failed sending b-req to debugger (" << actual << " of " << expected << ")";
691 return false;
692 }
693
694 return true;
695}
696
697/*
698 * Our functions.
699 */
700static const JdwpTransport adbTransport = {
701 startup,
702 acceptConnection,
703 establishConnection,
704 closeConnection,
705 netShutdown,
706 netFree,
707 isConnected,
708 awaitingHandshake,
709 processIncoming,
710 sendRequest,
711 sendBufferedRequest
712};
713
714/*
715 * Return our set.
716 */
717const JdwpTransport* AndroidAdbTransport() {
718 return &adbTransport;
719}
720
721} // namespace JDWP
722
723} // namespace art