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)
50 struct JdwpNetState : public JdwpNetStateBase {
52 bool awaitingHandshake;
57 unsigned char inputBuffer[kInputBufferSize];
59 socklen_t controlAddrLen;
61 struct sockaddr_un controlAddrUn;
62 struct sockaddr controlAddrPlain;
68 awaitingHandshake = false;
75 controlAddr.controlAddrUn.sun_family = AF_UNIX;
76 controlAddrLen = sizeof(controlAddr.controlAddrUn.sun_family) +
78 memcpy(controlAddr.controlAddrUn.sun_path, kJdwpControlName,
84 adbStateFree( JdwpNetState* netState )
89 if (netState->clientSock >= 0) {
90 shutdown(netState->clientSock, SHUT_RDWR);
91 close(netState->clientSock);
93 if (netState->controlSock >= 0) {
94 shutdown(netState->controlSock, SHUT_RDWR);
95 close(netState->controlSock);
97 if (netState->wakeFds[0] >= 0) {
98 close(netState->wakeFds[0]);
99 netState->wakeFds[0] = -1;
101 if (netState->wakeFds[1] >= 0) {
102 close(netState->wakeFds[1]);
103 netState->wakeFds[1] = -1;
110 * Do initial prep work, e.g. binding to ports and opening files. This
111 * runs in the main thread, before the JDWP thread starts, so it shouldn't
112 * do anything that might block forever.
114 static bool startup(struct JdwpState* state, const JdwpStartupParams* pParams)
116 JdwpNetState* netState;
118 ALOGV("ADB transport startup");
120 state->netState = netState = new JdwpNetState;
121 if (netState == NULL)
128 * Receive a file descriptor from ADB. The fd can be used to communicate
129 * directly with a debugger or DDMS.
131 * Returns the file descriptor on success. On failure, returns -1 and
132 * closes netState->controlSock.
134 static int receiveClientFd(JdwpNetState* netState)
137 struct cmsghdr* cmsg;
142 char buffer[CMSG_SPACE(sizeof(int))];
146 iov.iov_base = &dummy;
153 msg.msg_control = cm_un.buffer;
154 msg.msg_controllen = sizeof(cm_un.buffer);
156 cmsg = CMSG_FIRSTHDR(&msg);
157 cmsg->cmsg_len = msg.msg_controllen;
158 cmsg->cmsg_level = SOL_SOCKET;
159 cmsg->cmsg_type = SCM_RIGHTS;
160 ((int*)(void*)CMSG_DATA(cmsg))[0] = -1;
163 ret = recvmsg(netState->controlSock, &msg, 0);
164 } while (ret < 0 && errno == EINTR);
168 ALOGW("receiving file descriptor from ADB failed (socket %d): %s",
169 netState->controlSock, strerror(errno));
171 close(netState->controlSock);
172 netState->controlSock = -1;
176 return ((int*)(void*)CMSG_DATA(cmsg))[0];
180 * Block forever, waiting for a debugger to connect to us. Called from the
183 * This needs to un-block and return "false" if the VM is shutting down. It
184 * should return "true" when it successfully accepts a connection.
186 static bool acceptConnection(struct JdwpState* state)
188 JdwpNetState* netState = state->netState;
191 /* first, ensure that we get a connection to the ADB daemon */
194 if (netState->shuttingDown)
197 if (netState->controlSock < 0) {
199 const int sleep_max_ms = 2*1000;
202 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
203 if (netState->controlSock < 0) {
204 ALOGE("Could not create ADB control socket:%s",
209 if (pipe(netState->wakeFds) < 0) {
210 ALOGE("pipe failed");
214 snprintf(buff, sizeof(buff), "%04x", getpid());
219 * If adbd isn't running, because USB debugging was disabled or
220 * perhaps the system is restarting it for "adb root", the
221 * connect() will fail. We loop here forever waiting for it
224 * Waking up and polling every couple of seconds is generally a
225 * bad thing to do, but we only do this if the application is
226 * debuggable *and* adbd isn't running. Still, for the sake
227 * of battery life, we should consider timing out and giving
228 * up after a few minutes in case somebody ships an app with
229 * the debuggable flag set.
231 int ret = connect(netState->controlSock,
232 &netState->controlAddr.controlAddrPlain,
233 netState->controlAddrLen);
235 if (!socket_peer_is_trusted(netState->controlSock)) {
236 if (shutdown(netState->controlSock, SHUT_RDWR)) {
237 ALOGE("trouble shutting down socket: %s", strerror(errno));
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 ALOGV("PID sent as '%.*s' to ADB", 4, buff);
252 ALOGE("Weird, can't send JDWP process pid to ADB: %s",
256 ALOGV("Can't connect to ADB control socket:%s",
259 usleep( sleep_ms*1000 );
261 sleep_ms += (sleep_ms >> 1);
262 if (sleep_ms > sleep_max_ms)
263 sleep_ms = sleep_max_ms;
265 if (netState->shuttingDown)
270 ALOGV("trying to receive file descriptor from ADB");
271 /* now we can receive a client file descriptor */
272 netState->clientSock = receiveClientFd(netState);
273 if (netState->shuttingDown)
274 return false; // suppress logs and additional activity
276 if (netState->clientSock < 0) {
277 if (++retryCount > 5) {
278 ALOGE("adb connection max retries exceeded");
283 ALOGV("received file descriptor %d from ADB", netState->clientSock);
284 netState->awaitingHandshake = 1;
285 netState->inputCount = 0;
291 * Connect out to a debugger (for server=n). Not required.
293 static bool establishConnection(struct JdwpState* state)
299 * Close a connection from a debugger (which may have already dropped us).
300 * Only called from the JDWP thread.
302 static void closeConnection(struct JdwpState* state)
304 JdwpNetState* netState;
306 assert(state != NULL && state->netState != NULL);
308 netState = state->netState;
309 if (netState->clientSock < 0)
312 ALOGV("+++ closed JDWP <-> ADB connection");
314 close(netState->clientSock);
315 netState->clientSock = -1;
319 * Close all network stuff, including the socket we use to listen for
322 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
324 static void adbStateShutdown(struct JdwpNetState* netState)
329 if (netState == NULL)
332 netState->shuttingDown = true;
334 clientSock = netState->clientSock;
335 if (clientSock >= 0) {
336 shutdown(clientSock, SHUT_RDWR);
337 netState->clientSock = -1;
340 controlSock = netState->controlSock;
341 if (controlSock >= 0) {
342 shutdown(controlSock, SHUT_RDWR);
343 netState->controlSock = -1;
346 if (netState->wakeFds[1] >= 0) {
347 ALOGV("+++ writing to wakePipe");
348 write(netState->wakeFds[1], "", 1);
352 static void netShutdown(JdwpState* state)
354 adbStateShutdown(state->netState);
358 * Free up anything we put in state->netState. This is called after
359 * "netShutdown", after the JDWP thread has stopped.
361 static void netFree(struct JdwpState* state)
363 JdwpNetState* netState = state->netState;
365 adbStateFree(netState);
369 * Is a debugger connected to us?
371 static bool isConnected(struct JdwpState* state)
373 return (state->netState != NULL &&
374 state->netState->clientSock >= 0);
378 * Are we still waiting for the JDWP handshake?
380 static bool awaitingHandshake(struct JdwpState* state)
382 return state->netState->awaitingHandshake;
386 * Figure out if we have a full packet in the buffer.
388 static bool haveFullPacket(JdwpNetState* netState)
392 if (netState->awaitingHandshake)
393 return (netState->inputCount >= (int) kMagicHandshakeLen);
395 if (netState->inputCount < 4)
398 length = get4BE(netState->inputBuffer);
399 return (netState->inputCount >= length);
403 * Consume bytes from the buffer.
405 * This would be more efficient with a circular buffer. However, we're
406 * usually only going to find one packet, which is trivial to handle.
408 static void consumeBytes(JdwpNetState* netState, int count)
411 assert(count <= netState->inputCount);
413 if (count == netState->inputCount) {
414 netState->inputCount = 0;
418 memmove(netState->inputBuffer, netState->inputBuffer + count,
419 netState->inputCount - count);
420 netState->inputCount -= count;
424 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
426 static bool handlePacket(JdwpState* state)
428 JdwpNetState* netState = state->netState;
429 const unsigned char* buf = netState->inputBuffer;
432 u1 flags, cmdSet, cmd;
437 cmd = cmdSet = 0; // shut up gcc
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) {
463 ssize_t cc = netState->writePacket(pReply);
465 if (cc != (ssize_t) expandBufGetLength(pReply)) {
466 ALOGE("Failed sending reply to debugger: %s", strerror(errno));
467 expandBufFree(pReply);
471 ALOGW("No reply created for set=%d cmd=%d", cmdSet, cmd);
473 expandBufFree(pReply);
481 consumeBytes(netState, length);
486 * Process incoming data. If no data is available, this will block until
489 * If we get a full packet, handle it.
491 * To take some of the mystery out of life, we want to reject incoming
492 * connections if we already have a debugger attached. If we don't, the
493 * debugger will just mysteriously hang until it times out. We could just
494 * close the listen socket, but there's a good chance we won't be able to
495 * bind to the same port again, which would confuse utilities.
497 * Returns "false" on error (indicating that the connection has been severed),
498 * "true" if things are still okay.
500 static bool processIncoming(JdwpState* state)
502 JdwpNetState* netState = state->netState;
505 assert(netState->clientSock >= 0);
507 if (!haveFullPacket(netState)) {
508 /* read some more, looping until we have data */
518 /* configure fds; note these may get zapped by another thread */
519 fd = netState->controlSock;
521 FD_SET(fd, &readfds);
525 fd = netState->clientSock;
527 FD_SET(fd, &readfds);
531 fd = netState->wakeFds[0];
533 FD_SET(fd, &readfds);
537 ALOGI("NOTE: entering select w/o wakepipe");
541 ALOGV("+++ all fds are closed");
546 * Select blocks until it sees activity on the file descriptors.
547 * Closing the local file descriptor does not count as activity,
548 * so we can't rely on that to wake us up (it works for read()
549 * and accept(), but not select()).
551 * We can do one of three things: (1) send a signal and catch
552 * EINTR, (2) open an additional fd ("wakePipe") and write to
553 * it when it's time to exit, or (3) time out periodically and
554 * re-issue the select. We're currently using #2, as it's more
555 * reliable than #1 and generally better than #3. Wastes two fds.
557 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
561 ALOGE("select failed: %s", strerror(errno));
565 if (netState->wakeFds[0] >= 0 &&
566 FD_ISSET(netState->wakeFds[0], &readfds))
568 ALOGD("Got wake-up signal, bailing out of select");
571 if (netState->controlSock >= 0 &&
572 FD_ISSET(netState->controlSock, &readfds))
574 int sock = receiveClientFd(netState);
576 ALOGI("Ignoring second debugger -- accepting and dropping");
579 assert(netState->controlSock < 0);
581 * Remote side most likely went away, so our next read
582 * on netState->clientSock will fail and throw us out
587 if (netState->clientSock >= 0 &&
588 FD_ISSET(netState->clientSock, &readfds))
590 readCount = read(netState->clientSock,
591 netState->inputBuffer + netState->inputCount,
592 sizeof(netState->inputBuffer) - netState->inputCount);
597 ALOGD("+++ EINTR hit");
599 } else if (readCount == 0) {
600 /* EOF hit -- far end went away */
601 ALOGV("+++ peer disconnected");
608 netState->inputCount += readCount;
609 if (!haveFullPacket(netState))
610 return true; /* still not there yet */
614 * Special-case the initial handshake. For some bizarre reason we're
615 * expected to emulate bad tty settings by echoing the request back
616 * exactly as it was sent. Note the handshake is always initiated by
617 * the debugger, no matter who connects to whom.
619 * Other than this one case, the protocol [claims to be] stateless.
621 if (netState->awaitingHandshake) {
624 if (memcmp(netState->inputBuffer,
625 kMagicHandshake, kMagicHandshakeLen) != 0)
627 ALOGE("ERROR: bad handshake '%.14s'", netState->inputBuffer);
632 cc = write(netState->clientSock, netState->inputBuffer,
634 if (cc != kMagicHandshakeLen) {
635 ALOGE("Failed writing handshake bytes: %s (%d of %d)",
636 strerror(errno), cc, (int) kMagicHandshakeLen);
640 consumeBytes(netState, kMagicHandshakeLen);
641 netState->awaitingHandshake = false;
642 ALOGV("+++ handshake complete");
647 * Handle this packet.
649 return handlePacket(state);
652 closeConnection(state);
659 * The entire packet must be sent with a single write() call to avoid
662 * Returns "true" if it was sent successfully.
664 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
666 JdwpNetState* netState = state->netState;
668 if (netState->clientSock < 0) {
669 /* can happen with some DDMS events */
670 ALOGV("NOT sending request -- no debugger is attached");
676 ssize_t cc = netState->writePacket(pReq);
678 if (cc != (ssize_t) expandBufGetLength(pReq)) {
679 ALOGE("Failed sending req to debugger: %s (%d of %d)",
680 strerror(errno), (int) cc, (int) expandBufGetLength(pReq));
688 * Send a request that was split into multiple buffers.
690 * The entire packet must be sent with a single writev() call to avoid
693 * Returns "true" if it was sent successfully.
695 static bool sendBufferedRequest(JdwpState* state, const struct iovec* iov,
698 JdwpNetState* netState = state->netState;
700 if (netState->clientSock < 0) {
701 /* can happen with some DDMS events */
702 ALOGV("NOT sending request -- no debugger is attached");
708 for (i = 0; i < iovcnt; i++)
709 expected += iov[i].iov_len;
711 ssize_t actual = netState->writeBufferedPacket(iov, iovcnt);
713 if ((size_t)actual != expected) {
714 ALOGE("Failed sending b-req to debugger: %s (%d of %zu)",
715 strerror(errno), (int) actual, expected);
726 static const JdwpTransport socketTransport = {
743 const JdwpTransport* dvmJdwpAndroidAdbTransport()
745 return &socketTransport;