2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #include "jdwp/JdwpPriv.h"
17 #include "jdwp/JdwpHandler.h"
18 #include <sys/socket.h>
23 /* the JDWP <-> ADB transport protocol is explained in details
24 * in //device/tools/adb/jdwp_service.c, here's a summary.
26 * 1/ when the JDWP thread starts, it tries to connect to a Unix
27 * domain stream socket (@jdwp-control) that is opened by the
30 * 2/ it then sends the current process PID as a string of 4 hexadecimal
31 * chars (no terminating zero)
33 * 3/ then, it uses recvmsg to receive file descriptors from the
34 * daemon. each incoming file descriptor is a pass-through to
35 * a given JDWP debugger, that can be used to read the usual
36 * JDWP-handshake, etc...
40 #define kInputBufferSize 8192
42 #define kMagicHandshake "JDWP-Handshake"
43 #define kMagicHandshakeLen (sizeof(kMagicHandshake)-1)
45 #define kJdwpControlName "\0jdwp-control"
46 #define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
51 bool awaitingHandshake;
56 unsigned char inputBuffer[kInputBufferSize];
58 socklen_t controlAddrLen;
60 struct sockaddr_un controlAddrUn;
61 struct sockaddr controlAddrPlain;
66 adbStateFree( JdwpNetState* netState )
71 if (netState->clientSock >= 0) {
72 shutdown(netState->clientSock, SHUT_RDWR);
73 close(netState->clientSock);
75 if (netState->controlSock >= 0) {
76 shutdown(netState->controlSock, SHUT_RDWR);
77 close(netState->controlSock);
79 if (netState->wakeFds[0] >= 0) {
80 close(netState->wakeFds[0]);
81 netState->wakeFds[0] = -1;
83 if (netState->wakeFds[1] >= 0) {
84 close(netState->wakeFds[1]);
85 netState->wakeFds[1] = -1;
92 static JdwpNetState* adbStateAlloc()
94 JdwpNetState* netState = (JdwpNetState*) calloc(sizeof(*netState),1);
96 netState->controlSock = -1;
97 netState->clientSock = -1;
99 netState->controlAddr.controlAddrUn.sun_family = AF_UNIX;
100 netState->controlAddrLen =
101 sizeof(netState->controlAddr.controlAddrUn.sun_family) +
104 memcpy(netState->controlAddr.controlAddrUn.sun_path,
105 kJdwpControlName, kJdwpControlNameLen);
107 netState->wakeFds[0] = -1;
108 netState->wakeFds[1] = -1;
115 * Do initial prep work, e.g. binding to ports and opening files. This
116 * runs in the main thread, before the JDWP thread starts, so it shouldn't
117 * do anything that might block forever.
119 static bool startup(struct JdwpState* state, const JdwpStartupParams* pParams)
121 JdwpNetState* netState;
123 LOGV("ADB transport startup\n");
125 state->netState = netState = adbStateAlloc();
126 if (netState == NULL)
133 * Receive a file descriptor from ADB. The fd can be used to communicate
134 * directly with a debugger or DDMS.
136 * Returns the file descriptor on success. On failure, returns -1 and
137 * closes netState->controlSock.
139 static int receiveClientFd(JdwpNetState* netState)
142 struct cmsghdr* cmsg;
147 char buffer[CMSG_SPACE(sizeof(int))];
151 iov.iov_base = &dummy;
158 msg.msg_control = cm_un.buffer;
159 msg.msg_controllen = sizeof(cm_un.buffer);
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;
168 ret = recvmsg(netState->controlSock, &msg, 0);
169 } while (ret < 0 && errno == EINTR);
173 LOGW("receiving file descriptor from ADB failed (socket %d): %s\n",
174 netState->controlSock, strerror(errno));
176 LOGD("adbd disconnected\n");
178 close(netState->controlSock);
179 netState->controlSock = -1;
183 return ((int*)(void*)CMSG_DATA(cmsg))[0];
187 * Block forever, waiting for a debugger to connect to us. Called from the
190 * This needs to un-block and return "false" if the VM is shutting down. It
191 * should return "true" when it successfully accepts a connection.
193 static bool acceptConnection(struct JdwpState* state)
195 JdwpNetState* netState = state->netState;
198 /* first, ensure that we get a connection to the ADB daemon */
201 if (netState->shuttingDown)
204 if (netState->controlSock < 0) {
206 const int sleep_max_ms = 2*1000;
209 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
210 if (netState->controlSock < 0) {
211 LOGE("Could not create ADB control socket:%s\n",
216 if (pipe(netState->wakeFds) < 0) {
221 snprintf(buff, sizeof(buff), "%04x", getpid());
226 * If adbd isn't running, because USB debugging was disabled or
227 * perhaps the system is restarting it for "adb root", the
228 * connect() will fail. We loop here forever waiting for it
231 * Waking up and polling every couple of seconds is generally a
232 * bad thing to do, but we only do this if the application is
233 * debuggable *and* adbd isn't running. Still, for the sake
234 * of battery life, we should consider timing out and giving
235 * up after a few minutes in case somebody ships an app with
236 * the debuggable flag set.
238 int ret = connect(netState->controlSock,
239 &netState->controlAddr.controlAddrPlain,
240 netState->controlAddrLen);
242 /* now try to send our pid to the ADB daemon */
244 ret = send( netState->controlSock, buff, 4, 0 );
245 } while (ret < 0 && errno == EINTR);
248 LOGV("PID sent as '%.*s' to ADB\n", 4, buff);
252 LOGE("Weird, can't send JDWP process pid to ADB: %s\n",
256 LOGV("Can't connect to ADB control socket:%s\n",
259 usleep( sleep_ms*1000 );
261 sleep_ms += (sleep_ms >> 1);
262 if (sleep_ms > sleep_max_ms)
263 sleep_ms = sleep_max_ms;
267 LOGV("trying to receive file descriptor from ADB\n");
268 /* now we can receive a client file descriptor */
269 netState->clientSock = receiveClientFd(netState);
270 if (netState->shuttingDown)
271 return false; // suppress logs and additional activity
273 if (netState->clientSock < 0) {
274 if (++retryCount > 5) {
275 LOGE("adb connection max retries exceeded\n");
280 LOGV("received file descriptor %d from ADB\n", netState->clientSock);
281 netState->awaitingHandshake = 1;
282 netState->inputCount = 0;
288 * Connect out to a debugger (for server=n). Not required.
290 static bool establishConnection(struct JdwpState* state)
296 * Close a connection from a debugger (which may have already dropped us).
297 * Only called from the JDWP thread.
299 static void closeConnection(struct JdwpState* state)
301 JdwpNetState* netState;
303 assert(state != NULL && state->netState != NULL);
305 netState = state->netState;
306 if (netState->clientSock < 0)
309 LOGV("+++ closed JDWP <-> ADB connection\n");
311 close(netState->clientSock);
312 netState->clientSock = -1;
316 * Close all network stuff, including the socket we use to listen for
319 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
321 static void adbStateShutdown(struct JdwpNetState* netState)
326 if (netState == NULL)
329 netState->shuttingDown = true;
331 clientSock = netState->clientSock;
332 if (clientSock >= 0) {
333 shutdown(clientSock, SHUT_RDWR);
334 netState->clientSock = -1;
337 controlSock = netState->controlSock;
338 if (controlSock >= 0) {
339 shutdown(controlSock, SHUT_RDWR);
340 netState->controlSock = -1;
343 if (netState->wakeFds[1] >= 0) {
344 LOGV("+++ writing to wakePipe\n");
345 write(netState->wakeFds[1], "", 1);
349 static void netShutdown(JdwpState* state)
351 adbStateShutdown(state->netState);
355 * Free up anything we put in state->netState. This is called after
356 * "netShutdown", after the JDWP thread has stopped.
358 static void netFree(struct JdwpState* state)
360 JdwpNetState* netState = state->netState;
362 adbStateFree(netState);
366 * Is a debugger connected to us?
368 static bool isConnected(struct JdwpState* state)
370 return (state->netState != NULL &&
371 state->netState->clientSock >= 0);
375 * Are we still waiting for the JDWP handshake?
377 static bool awaitingHandshake(struct JdwpState* state)
379 return state->netState->awaitingHandshake;
383 * Figure out if we have a full packet in the buffer.
385 static bool haveFullPacket(JdwpNetState* netState)
389 if (netState->awaitingHandshake)
390 return (netState->inputCount >= (int) kMagicHandshakeLen);
392 if (netState->inputCount < 4)
395 length = get4BE(netState->inputBuffer);
396 return (netState->inputCount >= length);
400 * Consume bytes from the buffer.
402 * This would be more efficient with a circular buffer. However, we're
403 * usually only going to find one packet, which is trivial to handle.
405 static void consumeBytes(JdwpNetState* netState, int count)
408 assert(count <= netState->inputCount);
410 if (count == netState->inputCount) {
411 netState->inputCount = 0;
415 memmove(netState->inputBuffer, netState->inputBuffer + count,
416 netState->inputCount - count);
417 netState->inputCount -= count;
421 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
423 static bool handlePacket(JdwpState* state)
425 JdwpNetState* netState = state->netState;
426 const unsigned char* buf = netState->inputBuffer;
429 u1 flags, cmdSet, cmd;
434 cmd = cmdSet = 0; // shut up gcc
436 length = read4BE(&buf);
439 if ((flags & kJDWPFlagReply) != 0) {
441 error = read2BE(&buf);
444 cmdSet = read1(&buf);
448 assert((int) length <= netState->inputCount);
449 dataLen = length - (buf - netState->inputBuffer);
452 ExpandBuf* pReply = expandBufAlloc();
458 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
459 if (expandBufGetLength(pReply) > 0) {
463 * TODO: we currently assume the write() will complete in one
464 * go, which may not be safe for a network socket. We may need
465 * to mutex this against sendRequest().
467 cc = write(netState->clientSock, expandBufGetBuffer(pReply),
468 expandBufGetLength(pReply));
469 if (cc != (int) expandBufGetLength(pReply)) {
470 LOGE("Failed sending reply to debugger: %s\n", strerror(errno));
471 expandBufFree(pReply);
475 LOGW("No reply created for set=%d cmd=%d\n", cmdSet, cmd);
477 expandBufFree(pReply);
483 LOGV("----------\n");
485 consumeBytes(netState, length);
490 * Process incoming data. If no data is available, this will block until
493 * If we get a full packet, handle it.
495 * To take some of the mystery out of life, we want to reject incoming
496 * connections if we already have a debugger attached. If we don't, the
497 * debugger will just mysteriously hang until it times out. We could just
498 * close the listen socket, but there's a good chance we won't be able to
499 * bind to the same port again, which would confuse utilities.
501 * Returns "false" on error (indicating that the connection has been severed),
502 * "true" if things are still okay.
504 static bool processIncoming(JdwpState* state)
506 JdwpNetState* netState = state->netState;
509 assert(netState->clientSock >= 0);
511 if (!haveFullPacket(netState)) {
512 /* read some more, looping until we have data */
522 /* configure fds; note these may get zapped by another thread */
523 fd = netState->controlSock;
525 FD_SET(fd, &readfds);
529 fd = netState->clientSock;
531 FD_SET(fd, &readfds);
535 fd = netState->wakeFds[0];
537 FD_SET(fd, &readfds);
541 LOGI("NOTE: entering select w/o wakepipe\n");
545 LOGV("+++ all fds are closed\n");
550 * Select blocks until it sees activity on the file descriptors.
551 * Closing the local file descriptor does not count as activity,
552 * so we can't rely on that to wake us up (it works for read()
553 * and accept(), but not select()).
555 * We can do one of three things: (1) send a signal and catch
556 * EINTR, (2) open an additional fd ("wakePipe") and write to
557 * it when it's time to exit, or (3) time out periodically and
558 * re-issue the select. We're currently using #2, as it's more
559 * reliable than #1 and generally better than #3. Wastes two fds.
561 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
565 LOGE("select failed: %s\n", strerror(errno));
569 if (netState->wakeFds[0] >= 0 &&
570 FD_ISSET(netState->wakeFds[0], &readfds))
572 LOGD("Got wake-up signal, bailing out of select\n");
575 if (netState->controlSock >= 0 &&
576 FD_ISSET(netState->controlSock, &readfds))
578 int sock = receiveClientFd(netState);
580 LOGI("Ignoring second debugger -- accepting and dropping\n");
583 assert(netState->controlSock < 0);
585 * Remote side most likely went away, so our next read
586 * on netState->clientSock will fail and throw us out
591 if (netState->clientSock >= 0 &&
592 FD_ISSET(netState->clientSock, &readfds))
594 readCount = read(netState->clientSock,
595 netState->inputBuffer + netState->inputCount,
596 sizeof(netState->inputBuffer) - netState->inputCount);
601 LOGD("+++ EINTR hit\n");
603 } else if (readCount == 0) {
604 /* EOF hit -- far end went away */
605 LOGV("+++ peer disconnected\n");
612 netState->inputCount += readCount;
613 if (!haveFullPacket(netState))
614 return true; /* still not there yet */
618 * Special-case the initial handshake. For some bizarre reason we're
619 * expected to emulate bad tty settings by echoing the request back
620 * exactly as it was sent. Note the handshake is always initiated by
621 * the debugger, no matter who connects to whom.
623 * Other than this one case, the protocol [claims to be] stateless.
625 if (netState->awaitingHandshake) {
628 if (memcmp(netState->inputBuffer,
629 kMagicHandshake, kMagicHandshakeLen) != 0)
631 LOGE("ERROR: bad handshake '%.14s'\n", netState->inputBuffer);
636 cc = write(netState->clientSock, netState->inputBuffer,
638 if (cc != kMagicHandshakeLen) {
639 LOGE("Failed writing handshake bytes: %s (%d of %d)\n",
640 strerror(errno), cc, (int) kMagicHandshakeLen);
644 consumeBytes(netState, kMagicHandshakeLen);
645 netState->awaitingHandshake = false;
646 LOGV("+++ handshake complete\n");
651 * Handle this packet.
653 return handlePacket(state);
656 closeConnection(state);
663 * The entire packet must be sent with a single write() call to avoid
666 * Returns "true" if it was sent successfully.
668 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
670 JdwpNetState* netState = state->netState;
673 if (netState->clientSock < 0) {
674 /* can happen with some DDMS events */
675 LOGV("NOT sending request -- no debugger is attached\n");
680 * TODO: we currently assume the write() will complete in one
681 * go, which may not be safe for a network socket. We may need
682 * to mutex this against handlePacket().
685 cc = write(netState->clientSock, expandBufGetBuffer(pReq),
686 expandBufGetLength(pReq));
687 if (cc != (int) expandBufGetLength(pReq)) {
688 LOGE("Failed sending req to debugger: %s (%d of %d)\n",
689 strerror(errno), cc, (int) expandBufGetLength(pReq));
697 * Send a request that was split into multiple buffers.
699 * The entire packet must be sent with a single writev() call to avoid
702 * Returns "true" if it was sent successfully.
704 static bool sendBufferedRequest(JdwpState* state, const struct iovec* iov,
707 JdwpNetState* netState = state->netState;
709 if (netState->clientSock < 0) {
710 /* can happen with some DDMS events */
711 LOGV("NOT sending request -- no debugger is attached\n");
717 for (i = 0; i < iovcnt; i++)
718 expected += iov[i].iov_len;
721 * TODO: we currently assume the writev() will complete in one
722 * go, which may not be safe for a network socket. We may need
723 * to mutex this against handlePacket().
726 actual = writev(netState->clientSock, iov, iovcnt);
727 if ((size_t)actual != expected) {
728 LOGE("Failed sending b-req to debugger: %s (%d of %zu)\n",
729 strerror(errno), (int) actual, expected);
740 static const JdwpTransport socketTransport = {
757 const JdwpTransport* dvmJdwpAndroidAdbTransport()
759 return &socketTransport;