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;
95 JdwpNetState* netState = calloc(sizeof(*netState),1);
97 netState->controlSock = -1;
98 netState->clientSock = -1;
100 netState->controlAddr.controlAddrUn.sun_family = AF_UNIX;
101 netState->controlAddrLen =
102 sizeof(netState->controlAddr.controlAddrUn.sun_family) +
105 memcpy(netState->controlAddr.controlAddrUn.sun_path,
106 kJdwpControlName, kJdwpControlNameLen);
108 netState->wakeFds[0] = -1;
109 netState->wakeFds[1] = -1;
116 * Do initial prep work, e.g. binding to ports and opening files. This
117 * runs in the main thread, before the JDWP thread starts, so it shouldn't
118 * do anything that might block forever.
120 static bool startup(struct JdwpState* state, const JdwpStartupParams* pParams)
122 JdwpNetState* netState;
124 LOGV("ADB transport startup\n");
126 state->netState = netState = adbStateAlloc();
127 if (netState == NULL)
134 * Receive a file descriptor from ADB. The fd can be used to communicate
135 * directly with a debugger or DDMS.
137 * Returns the file descriptor on success. On failure, returns -1 and
138 * closes netState->controlSock.
140 static int receiveClientFd(JdwpNetState* netState)
143 struct cmsghdr* cmsg;
148 char buffer[CMSG_SPACE(sizeof(int))];
152 iov.iov_base = &dummy;
159 msg.msg_control = cm_un.buffer;
160 msg.msg_controllen = sizeof(cm_un.buffer);
162 cmsg = CMSG_FIRSTHDR(&msg);
163 cmsg->cmsg_len = msg.msg_controllen;
164 cmsg->cmsg_level = SOL_SOCKET;
165 cmsg->cmsg_type = SCM_RIGHTS;
166 ((int*)CMSG_DATA(cmsg))[0] = -1;
169 ret = recvmsg(netState->controlSock, &msg, 0);
170 } while (ret < 0 && errno == EINTR);
174 LOGW("receiving file descriptor from ADB failed (socket %d): %s\n",
175 netState->controlSock, strerror(errno));
177 LOGI("adbd disconnected\n");
179 close(netState->controlSock);
180 netState->controlSock = -1;
184 return ((int*)CMSG_DATA(cmsg))[0];
188 * Block forever, waiting for a debugger to connect to us. Called from the
191 * This needs to un-block and return "false" if the VM is shutting down. It
192 * should return "true" when it successfully accepts a connection.
194 static bool acceptConnection(struct JdwpState* state)
196 JdwpNetState* netState = state->netState;
199 /* first, ensure that we get a connection to the ADB daemon */
202 if (netState->shuttingDown)
205 if (netState->controlSock < 0) {
207 const int sleep_max_ms = 2*1000;
210 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
211 if (netState->controlSock < 0) {
212 LOGE("Could not create ADB control socket:%s\n",
217 if (pipe(netState->wakeFds) < 0) {
222 snprintf(buff, sizeof(buff), "%04x", getpid());
227 * If adbd isn't running, because USB debugging was disabled or
228 * perhaps the system is restarting it for "adb root", the
229 * connect() will fail. We loop here forever waiting for it
232 * Waking up and polling every couple of seconds is generally a
233 * bad thing to do, but we only do this if the application is
234 * debuggable *and* adbd isn't running. Still, for the sake
235 * of battery life, we should consider timing out and giving
236 * up after a few minutes in case somebody ships an app with
237 * the debuggable flag set.
239 int ret = connect(netState->controlSock,
240 &netState->controlAddr.controlAddrPlain,
241 netState->controlAddrLen);
243 /* now try to send our pid to the ADB daemon */
245 ret = send( netState->controlSock, buff, 4, 0 );
246 } while (ret < 0 && errno == EINTR);
249 LOGV("PID sent as '%.*s' to ADB\n", 4, buff);
253 LOGE("Weird, can't send JDWP process pid to ADB: %s\n",
257 LOGV("Can't connect to ADB control socket:%s\n",
260 usleep( sleep_ms*1000 );
262 sleep_ms += (sleep_ms >> 1);
263 if (sleep_ms > sleep_max_ms)
264 sleep_ms = sleep_max_ms;
268 LOGV("trying to receive file descriptor from ADB\n");
269 /* now we can receive a client file descriptor */
270 netState->clientSock = receiveClientFd(netState);
271 if (netState->shuttingDown)
272 return false; // suppress logs and additional activity
274 if (netState->clientSock < 0) {
275 if (++retryCount > 5) {
276 LOGE("adb connection max retries exceeded\n");
281 LOGV("received file descriptor %d from ADB\n", netState->clientSock);
282 netState->awaitingHandshake = 1;
283 netState->inputCount = 0;
289 * Connect out to a debugger (for server=n). Not required.
291 static bool establishConnection(struct JdwpState* state)
297 * Close a connection from a debugger (which may have already dropped us).
298 * Only called from the JDWP thread.
300 static void closeConnection(struct JdwpState* state)
302 JdwpNetState* netState;
304 assert(state != NULL && state->netState != NULL);
306 netState = state->netState;
307 if (netState->clientSock < 0)
310 LOGV("+++ closed JDWP <-> ADB connection\n");
312 close(netState->clientSock);
313 netState->clientSock = -1;
317 * Close all network stuff, including the socket we use to listen for
320 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
322 static void adbStateShutdown(struct JdwpNetState* netState)
327 if (netState == NULL)
330 netState->shuttingDown = true;
332 clientSock = netState->clientSock;
333 if (clientSock >= 0) {
334 shutdown(clientSock, SHUT_RDWR);
335 netState->clientSock = -1;
338 controlSock = netState->controlSock;
339 if (controlSock >= 0) {
340 shutdown(controlSock, SHUT_RDWR);
341 netState->controlSock = -1;
344 if (netState->wakeFds[1] >= 0) {
345 LOGV("+++ writing to wakePipe\n");
346 (void) write(netState->wakeFds[1], "", 1);
350 static void netShutdown(JdwpState* state)
352 adbStateShutdown(state->netState);
356 * Free up anything we put in state->netState. This is called after
357 * "netShutdown", after the JDWP thread has stopped.
359 static void netFree(struct JdwpState* state)
361 JdwpNetState* netState = state->netState;
363 adbStateFree(netState);
367 * Is a debugger connected to us?
369 static bool isConnected(struct JdwpState* state)
371 return (state->netState != NULL &&
372 state->netState->clientSock >= 0);
376 * Are we still waiting for the JDWP handshake?
378 static bool awaitingHandshake(struct JdwpState* state)
380 return state->netState->awaitingHandshake;
384 * Figure out if we have a full packet in the buffer.
386 static bool haveFullPacket(JdwpNetState* netState)
390 if (netState->awaitingHandshake)
391 return (netState->inputCount >= (int) kMagicHandshakeLen);
393 if (netState->inputCount < 4)
396 length = get4BE(netState->inputBuffer);
397 return (netState->inputCount >= length);
401 * Consume bytes from the buffer.
403 * This would be more efficient with a circular buffer. However, we're
404 * usually only going to find one packet, which is trivial to handle.
406 static void consumeBytes(JdwpNetState* netState, int count)
409 assert(count <= netState->inputCount);
411 if (count == netState->inputCount) {
412 netState->inputCount = 0;
416 memmove(netState->inputBuffer, netState->inputBuffer + count,
417 netState->inputCount - count);
418 netState->inputCount -= count;
422 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
424 static bool handlePacket(JdwpState* state)
426 JdwpNetState* netState = state->netState;
427 const unsigned char* buf = netState->inputBuffer;
430 u1 flags, cmdSet, cmd;
435 cmd = cmdSet = 0; // shut up gcc
437 /*dumpPacket(netState->inputBuffer);*/
439 length = read4BE(&buf);
442 if ((flags & kJDWPFlagReply) != 0) {
444 error = read2BE(&buf);
447 cmdSet = read1(&buf);
451 assert((int) length <= netState->inputCount);
452 dataLen = length - (buf - netState->inputBuffer);
455 ExpandBuf* pReply = expandBufAlloc();
461 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
462 if (expandBufGetLength(pReply) > 0) {
466 * TODO: we currently assume the write() will complete in one
467 * go, which may not be safe for a network socket. We may need
468 * to mutex this against sendRequest().
470 cc = write(netState->clientSock, expandBufGetBuffer(pReply),
471 expandBufGetLength(pReply));
472 if (cc != (int) expandBufGetLength(pReply)) {
473 LOGE("Failed sending reply to debugger: %s\n", strerror(errno));
474 expandBufFree(pReply);
478 LOGW("No reply created for set=%d cmd=%d\n", cmdSet, cmd);
480 expandBufFree(pReply);
486 LOGV("----------\n");
488 consumeBytes(netState, length);
493 * Process incoming data. If no data is available, this will block until
496 * If we get a full packet, handle it.
498 * To take some of the mystery out of life, we want to reject incoming
499 * connections if we already have a debugger attached. If we don't, the
500 * debugger will just mysteriously hang until it times out. We could just
501 * close the listen socket, but there's a good chance we won't be able to
502 * bind to the same port again, which would confuse utilities.
504 * Returns "false" on error (indicating that the connection has been severed),
505 * "true" if things are still okay.
507 static bool processIncoming(JdwpState* state)
509 JdwpNetState* netState = state->netState;
512 assert(netState->clientSock >= 0);
514 if (!haveFullPacket(netState)) {
515 /* read some more, looping until we have data */
525 /* configure fds; note these may get zapped by another thread */
526 fd = netState->controlSock;
528 FD_SET(fd, &readfds);
532 fd = netState->clientSock;
534 FD_SET(fd, &readfds);
538 fd = netState->wakeFds[0];
540 FD_SET(fd, &readfds);
544 LOGI("NOTE: entering select w/o wakepipe\n");
548 LOGV("+++ all fds are closed\n");
553 * Select blocks until it sees activity on the file descriptors.
554 * Closing the local file descriptor does not count as activity,
555 * so we can't rely on that to wake us up (it works for read()
556 * and accept(), but not select()).
558 * We can do one of three things: (1) send a signal and catch
559 * EINTR, (2) open an additional fd ("wakePipe") and write to
560 * it when it's time to exit, or (3) time out periodically and
561 * re-issue the select. We're currently using #2, as it's more
562 * reliable than #1 and generally better than #3. Wastes two fds.
564 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
568 LOGE("select failed: %s\n", strerror(errno));
572 if (netState->wakeFds[0] >= 0 &&
573 FD_ISSET(netState->wakeFds[0], &readfds))
575 LOGD("Got wake-up signal, bailing out of select\n");
578 if (netState->controlSock >= 0 &&
579 FD_ISSET(netState->controlSock, &readfds))
581 int sock = receiveClientFd(netState);
583 LOGI("Ignoring second debugger -- accepting and dropping\n");
586 assert(netState->controlSock < 0);
588 * Remote side most likely went away, so our next read
589 * on netState->clientSock will fail and throw us out
594 if (netState->clientSock >= 0 &&
595 FD_ISSET(netState->clientSock, &readfds))
597 readCount = read(netState->clientSock,
598 netState->inputBuffer + netState->inputCount,
599 sizeof(netState->inputBuffer) - netState->inputCount);
604 LOGD("+++ EINTR hit\n");
606 } else if (readCount == 0) {
607 /* EOF hit -- far end went away */
608 LOGV("+++ peer disconnected\n");
615 netState->inputCount += readCount;
616 if (!haveFullPacket(netState))
617 return true; /* still not there yet */
621 * Special-case the initial handshake. For some bizarre reason we're
622 * expected to emulate bad tty settings by echoing the request back
623 * exactly as it was sent. Note the handshake is always initiated by
624 * the debugger, no matter who connects to whom.
626 * Other than this one case, the protocol [claims to be] stateless.
628 if (netState->awaitingHandshake) {
631 if (memcmp(netState->inputBuffer,
632 kMagicHandshake, kMagicHandshakeLen) != 0)
634 LOGE("ERROR: bad handshake '%.14s'\n", netState->inputBuffer);
639 cc = write(netState->clientSock, netState->inputBuffer,
641 if (cc != kMagicHandshakeLen) {
642 LOGE("Failed writing handshake bytes: %s (%d of %d)\n",
643 strerror(errno), cc, (int) kMagicHandshakeLen);
647 consumeBytes(netState, kMagicHandshakeLen);
648 netState->awaitingHandshake = false;
649 LOGV("+++ handshake complete\n");
654 * Handle this packet.
656 return handlePacket(state);
659 closeConnection(state);
666 * The entire packet must be sent with a single write() call to avoid
669 * Returns "true" if it was sent successfully.
671 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
673 JdwpNetState* netState = state->netState;
676 /* dumpPacket(expandBufGetBuffer(pReq)); */
677 if (netState->clientSock < 0) {
678 /* can happen with some DDMS events */
679 LOGV("NOT sending request -- no debugger is attached\n");
684 * TODO: we currently assume the write() will complete in one
685 * go, which may not be safe for a network socket. We may need
686 * to mutex this against handlePacket().
689 cc = write(netState->clientSock, expandBufGetBuffer(pReq),
690 expandBufGetLength(pReq));
691 if (cc != (int) expandBufGetLength(pReq)) {
692 LOGE("Failed sending req to debugger: %s (%d of %d)\n",
693 strerror(errno), cc, (int) expandBufGetLength(pReq));
704 static const JdwpTransport socketTransport = {
720 const JdwpTransport* dvmJdwpAndroidAdbTransport(void)
722 return &socketTransport;