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.
17 #include "jdwp/JdwpPriv.h"
18 #include "jdwp/JdwpHandler.h"
19 #include <sys/socket.h>
23 #include <cutils/sockets.h>
26 * The JDWP <-> ADB transport protocol is explained in detail
27 * in system/core/adb/jdwp_service.c. Here's a summary.
29 * 1/ when the JDWP thread starts, it tries to connect to a Unix
30 * domain stream socket (@jdwp-control) that is opened by the
33 * 2/ it then sends the current process PID as a string of 4 hexadecimal
34 * chars (no terminating zero)
36 * 3/ then, it uses recvmsg to receive file descriptors from the
37 * daemon. each incoming file descriptor is a pass-through to
38 * a given JDWP debugger, that can be used to read the usual
39 * JDWP-handshake, etc...
42 #define kInputBufferSize 8192
44 #define kMagicHandshake "JDWP-Handshake"
45 #define kMagicHandshakeLen (sizeof(kMagicHandshake)-1)
47 #define kJdwpControlName "\0jdwp-control"
48 #define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
53 bool awaitingHandshake;
58 unsigned char inputBuffer[kInputBufferSize];
60 socklen_t controlAddrLen;
62 struct sockaddr_un controlAddrUn;
63 struct sockaddr controlAddrPlain;
68 adbStateFree( JdwpNetState* netState )
73 if (netState->clientSock >= 0) {
74 shutdown(netState->clientSock, SHUT_RDWR);
75 close(netState->clientSock);
77 if (netState->controlSock >= 0) {
78 shutdown(netState->controlSock, SHUT_RDWR);
79 close(netState->controlSock);
81 if (netState->wakeFds[0] >= 0) {
82 close(netState->wakeFds[0]);
83 netState->wakeFds[0] = -1;
85 if (netState->wakeFds[1] >= 0) {
86 close(netState->wakeFds[1]);
87 netState->wakeFds[1] = -1;
94 static JdwpNetState* adbStateAlloc()
96 JdwpNetState* netState = (JdwpNetState*) calloc(sizeof(*netState),1);
98 netState->controlSock = -1;
99 netState->clientSock = -1;
101 netState->controlAddr.controlAddrUn.sun_family = AF_UNIX;
102 netState->controlAddrLen =
103 sizeof(netState->controlAddr.controlAddrUn.sun_family) +
106 memcpy(netState->controlAddr.controlAddrUn.sun_path,
107 kJdwpControlName, kJdwpControlNameLen);
109 netState->wakeFds[0] = -1;
110 netState->wakeFds[1] = -1;
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.
121 static bool startup(struct JdwpState* state, const JdwpStartupParams* pParams)
123 JdwpNetState* netState;
125 LOGV("ADB transport startup");
127 state->netState = netState = adbStateAlloc();
128 if (netState == NULL)
135 * Receive a file descriptor from ADB. The fd can be used to communicate
136 * directly with a debugger or DDMS.
138 * Returns the file descriptor on success. On failure, returns -1 and
139 * closes netState->controlSock.
141 static int receiveClientFd(JdwpNetState* netState)
144 struct cmsghdr* cmsg;
149 char buffer[CMSG_SPACE(sizeof(int))];
153 iov.iov_base = &dummy;
160 msg.msg_control = cm_un.buffer;
161 msg.msg_controllen = sizeof(cm_un.buffer);
163 cmsg = CMSG_FIRSTHDR(&msg);
164 cmsg->cmsg_len = msg.msg_controllen;
165 cmsg->cmsg_level = SOL_SOCKET;
166 cmsg->cmsg_type = SCM_RIGHTS;
167 ((int*)(void*)CMSG_DATA(cmsg))[0] = -1;
170 ret = recvmsg(netState->controlSock, &msg, 0);
171 } while (ret < 0 && errno == EINTR);
175 LOGW("receiving file descriptor from ADB failed (socket %d): %s",
176 netState->controlSock, strerror(errno));
178 LOGD("adbd disconnected");
180 close(netState->controlSock);
181 netState->controlSock = -1;
185 return ((int*)(void*)CMSG_DATA(cmsg))[0];
189 * Block forever, waiting for a debugger to connect to us. Called from the
192 * This needs to un-block and return "false" if the VM is shutting down. It
193 * should return "true" when it successfully accepts a connection.
195 static bool acceptConnection(struct JdwpState* state)
197 JdwpNetState* netState = state->netState;
200 /* first, ensure that we get a connection to the ADB daemon */
203 if (netState->shuttingDown)
206 if (netState->controlSock < 0) {
208 const int sleep_max_ms = 2*1000;
211 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
212 if (netState->controlSock < 0) {
213 LOGE("Could not create ADB control socket:%s",
218 if (pipe(netState->wakeFds) < 0) {
223 snprintf(buff, sizeof(buff), "%04x", getpid());
228 * If adbd isn't running, because USB debugging was disabled or
229 * perhaps the system is restarting it for "adb root", the
230 * connect() will fail. We loop here forever waiting for it
233 * Waking up and polling every couple of seconds is generally a
234 * bad thing to do, but we only do this if the application is
235 * debuggable *and* adbd isn't running. Still, for the sake
236 * of battery life, we should consider timing out and giving
237 * up after a few minutes in case somebody ships an app with
238 * the debuggable flag set.
240 int ret = connect(netState->controlSock,
241 &netState->controlAddr.controlAddrPlain,
242 netState->controlAddrLen);
244 if (!socket_peer_is_trusted(netState->controlSock)) {
245 if (shutdown(netState->controlSock, SHUT_RDWR)) {
246 LOGE("trouble shutting down socket: %s", strerror(errno));
251 /* now try to send our pid to the ADB daemon */
253 ret = send( netState->controlSock, buff, 4, 0 );
254 } while (ret < 0 && errno == EINTR);
257 LOGV("PID sent as '%.*s' to ADB", 4, buff);
261 LOGE("Weird, can't send JDWP process pid to ADB: %s",
265 LOGV("Can't connect to ADB control socket:%s",
268 usleep( sleep_ms*1000 );
270 sleep_ms += (sleep_ms >> 1);
271 if (sleep_ms > sleep_max_ms)
272 sleep_ms = sleep_max_ms;
274 if (netState->shuttingDown)
279 LOGV("trying to receive file descriptor from ADB");
280 /* now we can receive a client file descriptor */
281 netState->clientSock = receiveClientFd(netState);
282 if (netState->shuttingDown)
283 return false; // suppress logs and additional activity
285 if (netState->clientSock < 0) {
286 if (++retryCount > 5) {
287 LOGE("adb connection max retries exceeded");
292 LOGV("received file descriptor %d from ADB", netState->clientSock);
293 netState->awaitingHandshake = 1;
294 netState->inputCount = 0;
300 * Connect out to a debugger (for server=n). Not required.
302 static bool establishConnection(struct JdwpState* state)
308 * Close a connection from a debugger (which may have already dropped us).
309 * Only called from the JDWP thread.
311 static void closeConnection(struct JdwpState* state)
313 JdwpNetState* netState;
315 assert(state != NULL && state->netState != NULL);
317 netState = state->netState;
318 if (netState->clientSock < 0)
321 LOGV("+++ closed JDWP <-> ADB connection");
323 close(netState->clientSock);
324 netState->clientSock = -1;
328 * Close all network stuff, including the socket we use to listen for
331 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
333 static void adbStateShutdown(struct JdwpNetState* netState)
338 if (netState == NULL)
341 netState->shuttingDown = true;
343 clientSock = netState->clientSock;
344 if (clientSock >= 0) {
345 shutdown(clientSock, SHUT_RDWR);
346 netState->clientSock = -1;
349 controlSock = netState->controlSock;
350 if (controlSock >= 0) {
351 shutdown(controlSock, SHUT_RDWR);
352 netState->controlSock = -1;
355 if (netState->wakeFds[1] >= 0) {
356 LOGV("+++ writing to wakePipe");
357 write(netState->wakeFds[1], "", 1);
361 static void netShutdown(JdwpState* state)
363 adbStateShutdown(state->netState);
367 * Free up anything we put in state->netState. This is called after
368 * "netShutdown", after the JDWP thread has stopped.
370 static void netFree(struct JdwpState* state)
372 JdwpNetState* netState = state->netState;
374 adbStateFree(netState);
378 * Is a debugger connected to us?
380 static bool isConnected(struct JdwpState* state)
382 return (state->netState != NULL &&
383 state->netState->clientSock >= 0);
387 * Are we still waiting for the JDWP handshake?
389 static bool awaitingHandshake(struct JdwpState* state)
391 return state->netState->awaitingHandshake;
395 * Figure out if we have a full packet in the buffer.
397 static bool haveFullPacket(JdwpNetState* netState)
401 if (netState->awaitingHandshake)
402 return (netState->inputCount >= (int) kMagicHandshakeLen);
404 if (netState->inputCount < 4)
407 length = get4BE(netState->inputBuffer);
408 return (netState->inputCount >= length);
412 * Consume bytes from the buffer.
414 * This would be more efficient with a circular buffer. However, we're
415 * usually only going to find one packet, which is trivial to handle.
417 static void consumeBytes(JdwpNetState* netState, int count)
420 assert(count <= netState->inputCount);
422 if (count == netState->inputCount) {
423 netState->inputCount = 0;
427 memmove(netState->inputBuffer, netState->inputBuffer + count,
428 netState->inputCount - count);
429 netState->inputCount -= count;
433 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
435 static bool handlePacket(JdwpState* state)
437 JdwpNetState* netState = state->netState;
438 const unsigned char* buf = netState->inputBuffer;
441 u1 flags, cmdSet, cmd;
446 cmd = cmdSet = 0; // shut up gcc
448 length = read4BE(&buf);
451 if ((flags & kJDWPFlagReply) != 0) {
453 error = read2BE(&buf);
456 cmdSet = read1(&buf);
460 assert((int) length <= netState->inputCount);
461 dataLen = length - (buf - netState->inputBuffer);
464 ExpandBuf* pReply = expandBufAlloc();
470 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
471 if (expandBufGetLength(pReply) > 0) {
475 * TODO: we currently assume the write() will complete in one
476 * go, which may not be safe for a network socket. We may need
477 * to mutex this against sendRequest().
479 cc = write(netState->clientSock, expandBufGetBuffer(pReply),
480 expandBufGetLength(pReply));
481 if (cc != (int) expandBufGetLength(pReply)) {
482 LOGE("Failed sending reply to debugger: %s", strerror(errno));
483 expandBufFree(pReply);
487 LOGW("No reply created for set=%d cmd=%d", cmdSet, cmd);
489 expandBufFree(pReply);
497 consumeBytes(netState, length);
502 * Process incoming data. If no data is available, this will block until
505 * If we get a full packet, handle it.
507 * To take some of the mystery out of life, we want to reject incoming
508 * connections if we already have a debugger attached. If we don't, the
509 * debugger will just mysteriously hang until it times out. We could just
510 * close the listen socket, but there's a good chance we won't be able to
511 * bind to the same port again, which would confuse utilities.
513 * Returns "false" on error (indicating that the connection has been severed),
514 * "true" if things are still okay.
516 static bool processIncoming(JdwpState* state)
518 JdwpNetState* netState = state->netState;
521 assert(netState->clientSock >= 0);
523 if (!haveFullPacket(netState)) {
524 /* read some more, looping until we have data */
534 /* configure fds; note these may get zapped by another thread */
535 fd = netState->controlSock;
537 FD_SET(fd, &readfds);
541 fd = netState->clientSock;
543 FD_SET(fd, &readfds);
547 fd = netState->wakeFds[0];
549 FD_SET(fd, &readfds);
553 LOGI("NOTE: entering select w/o wakepipe");
557 LOGV("+++ all fds are closed");
562 * Select blocks until it sees activity on the file descriptors.
563 * Closing the local file descriptor does not count as activity,
564 * so we can't rely on that to wake us up (it works for read()
565 * and accept(), but not select()).
567 * We can do one of three things: (1) send a signal and catch
568 * EINTR, (2) open an additional fd ("wakePipe") and write to
569 * it when it's time to exit, or (3) time out periodically and
570 * re-issue the select. We're currently using #2, as it's more
571 * reliable than #1 and generally better than #3. Wastes two fds.
573 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
577 LOGE("select failed: %s", strerror(errno));
581 if (netState->wakeFds[0] >= 0 &&
582 FD_ISSET(netState->wakeFds[0], &readfds))
584 LOGD("Got wake-up signal, bailing out of select");
587 if (netState->controlSock >= 0 &&
588 FD_ISSET(netState->controlSock, &readfds))
590 int sock = receiveClientFd(netState);
592 LOGI("Ignoring second debugger -- accepting and dropping");
595 assert(netState->controlSock < 0);
597 * Remote side most likely went away, so our next read
598 * on netState->clientSock will fail and throw us out
603 if (netState->clientSock >= 0 &&
604 FD_ISSET(netState->clientSock, &readfds))
606 readCount = read(netState->clientSock,
607 netState->inputBuffer + netState->inputCount,
608 sizeof(netState->inputBuffer) - netState->inputCount);
613 LOGD("+++ EINTR hit");
615 } else if (readCount == 0) {
616 /* EOF hit -- far end went away */
617 LOGV("+++ peer disconnected");
624 netState->inputCount += readCount;
625 if (!haveFullPacket(netState))
626 return true; /* still not there yet */
630 * Special-case the initial handshake. For some bizarre reason we're
631 * expected to emulate bad tty settings by echoing the request back
632 * exactly as it was sent. Note the handshake is always initiated by
633 * the debugger, no matter who connects to whom.
635 * Other than this one case, the protocol [claims to be] stateless.
637 if (netState->awaitingHandshake) {
640 if (memcmp(netState->inputBuffer,
641 kMagicHandshake, kMagicHandshakeLen) != 0)
643 LOGE("ERROR: bad handshake '%.14s'", netState->inputBuffer);
648 cc = write(netState->clientSock, netState->inputBuffer,
650 if (cc != kMagicHandshakeLen) {
651 LOGE("Failed writing handshake bytes: %s (%d of %d)",
652 strerror(errno), cc, (int) kMagicHandshakeLen);
656 consumeBytes(netState, kMagicHandshakeLen);
657 netState->awaitingHandshake = false;
658 LOGV("+++ handshake complete");
663 * Handle this packet.
665 return handlePacket(state);
668 closeConnection(state);
675 * The entire packet must be sent with a single write() call to avoid
678 * Returns "true" if it was sent successfully.
680 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
682 JdwpNetState* netState = state->netState;
685 if (netState->clientSock < 0) {
686 /* can happen with some DDMS events */
687 LOGV("NOT sending request -- no debugger is attached");
692 * TODO: we currently assume the write() will complete in one
693 * go, which may not be safe for a network socket. We may need
694 * to mutex this against handlePacket().
697 cc = write(netState->clientSock, expandBufGetBuffer(pReq),
698 expandBufGetLength(pReq));
699 if (cc != (int) expandBufGetLength(pReq)) {
700 LOGE("Failed sending req to debugger: %s (%d of %d)",
701 strerror(errno), cc, (int) expandBufGetLength(pReq));
709 * Send a request that was split into multiple buffers.
711 * The entire packet must be sent with a single writev() call to avoid
714 * Returns "true" if it was sent successfully.
716 static bool sendBufferedRequest(JdwpState* state, const struct iovec* iov,
719 JdwpNetState* netState = state->netState;
721 if (netState->clientSock < 0) {
722 /* can happen with some DDMS events */
723 LOGV("NOT sending request -- no debugger is attached");
729 for (i = 0; i < iovcnt; i++)
730 expected += iov[i].iov_len;
733 * TODO: we currently assume the writev() will complete in one
734 * go, which may not be safe for a network socket. We may need
735 * to mutex this against handlePacket().
738 actual = writev(netState->clientSock, iov, iovcnt);
739 if ((size_t)actual != expected) {
740 LOGE("Failed sending b-req to debugger: %s (%d of %zu)",
741 strerror(errno), (int) actual, expected);
752 static const JdwpTransport socketTransport = {
769 const JdwpTransport* dvmJdwpAndroidAdbTransport()
771 return &socketTransport;