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\n");
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\n",
176 netState->controlSock, strerror(errno));
178 LOGD("adbd disconnected\n");
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\n",
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\n", 4, buff);
261 LOGE("Weird, can't send JDWP process pid to ADB: %s\n",
265 LOGV("Can't connect to ADB control socket:%s\n",
268 usleep( sleep_ms*1000 );
270 sleep_ms += (sleep_ms >> 1);
271 if (sleep_ms > sleep_max_ms)
272 sleep_ms = sleep_max_ms;
276 LOGV("trying to receive file descriptor from ADB\n");
277 /* now we can receive a client file descriptor */
278 netState->clientSock = receiveClientFd(netState);
279 if (netState->shuttingDown)
280 return false; // suppress logs and additional activity
282 if (netState->clientSock < 0) {
283 if (++retryCount > 5) {
284 LOGE("adb connection max retries exceeded\n");
289 LOGV("received file descriptor %d from ADB\n", netState->clientSock);
290 netState->awaitingHandshake = 1;
291 netState->inputCount = 0;
297 * Connect out to a debugger (for server=n). Not required.
299 static bool establishConnection(struct JdwpState* state)
305 * Close a connection from a debugger (which may have already dropped us).
306 * Only called from the JDWP thread.
308 static void closeConnection(struct JdwpState* state)
310 JdwpNetState* netState;
312 assert(state != NULL && state->netState != NULL);
314 netState = state->netState;
315 if (netState->clientSock < 0)
318 LOGV("+++ closed JDWP <-> ADB connection\n");
320 close(netState->clientSock);
321 netState->clientSock = -1;
325 * Close all network stuff, including the socket we use to listen for
328 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
330 static void adbStateShutdown(struct JdwpNetState* netState)
335 if (netState == NULL)
338 netState->shuttingDown = true;
340 clientSock = netState->clientSock;
341 if (clientSock >= 0) {
342 shutdown(clientSock, SHUT_RDWR);
343 netState->clientSock = -1;
346 controlSock = netState->controlSock;
347 if (controlSock >= 0) {
348 shutdown(controlSock, SHUT_RDWR);
349 netState->controlSock = -1;
352 if (netState->wakeFds[1] >= 0) {
353 LOGV("+++ writing to wakePipe\n");
354 write(netState->wakeFds[1], "", 1);
358 static void netShutdown(JdwpState* state)
360 adbStateShutdown(state->netState);
364 * Free up anything we put in state->netState. This is called after
365 * "netShutdown", after the JDWP thread has stopped.
367 static void netFree(struct JdwpState* state)
369 JdwpNetState* netState = state->netState;
371 adbStateFree(netState);
375 * Is a debugger connected to us?
377 static bool isConnected(struct JdwpState* state)
379 return (state->netState != NULL &&
380 state->netState->clientSock >= 0);
384 * Are we still waiting for the JDWP handshake?
386 static bool awaitingHandshake(struct JdwpState* state)
388 return state->netState->awaitingHandshake;
392 * Figure out if we have a full packet in the buffer.
394 static bool haveFullPacket(JdwpNetState* netState)
398 if (netState->awaitingHandshake)
399 return (netState->inputCount >= (int) kMagicHandshakeLen);
401 if (netState->inputCount < 4)
404 length = get4BE(netState->inputBuffer);
405 return (netState->inputCount >= length);
409 * Consume bytes from the buffer.
411 * This would be more efficient with a circular buffer. However, we're
412 * usually only going to find one packet, which is trivial to handle.
414 static void consumeBytes(JdwpNetState* netState, int count)
417 assert(count <= netState->inputCount);
419 if (count == netState->inputCount) {
420 netState->inputCount = 0;
424 memmove(netState->inputBuffer, netState->inputBuffer + count,
425 netState->inputCount - count);
426 netState->inputCount -= count;
430 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
432 static bool handlePacket(JdwpState* state)
434 JdwpNetState* netState = state->netState;
435 const unsigned char* buf = netState->inputBuffer;
438 u1 flags, cmdSet, cmd;
443 cmd = cmdSet = 0; // shut up gcc
445 length = read4BE(&buf);
448 if ((flags & kJDWPFlagReply) != 0) {
450 error = read2BE(&buf);
453 cmdSet = read1(&buf);
457 assert((int) length <= netState->inputCount);
458 dataLen = length - (buf - netState->inputBuffer);
461 ExpandBuf* pReply = expandBufAlloc();
467 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
468 if (expandBufGetLength(pReply) > 0) {
472 * TODO: we currently assume the write() will complete in one
473 * go, which may not be safe for a network socket. We may need
474 * to mutex this against sendRequest().
476 cc = write(netState->clientSock, expandBufGetBuffer(pReply),
477 expandBufGetLength(pReply));
478 if (cc != (int) expandBufGetLength(pReply)) {
479 LOGE("Failed sending reply to debugger: %s\n", strerror(errno));
480 expandBufFree(pReply);
484 LOGW("No reply created for set=%d cmd=%d\n", cmdSet, cmd);
486 expandBufFree(pReply);
492 LOGV("----------\n");
494 consumeBytes(netState, length);
499 * Process incoming data. If no data is available, this will block until
502 * If we get a full packet, handle it.
504 * To take some of the mystery out of life, we want to reject incoming
505 * connections if we already have a debugger attached. If we don't, the
506 * debugger will just mysteriously hang until it times out. We could just
507 * close the listen socket, but there's a good chance we won't be able to
508 * bind to the same port again, which would confuse utilities.
510 * Returns "false" on error (indicating that the connection has been severed),
511 * "true" if things are still okay.
513 static bool processIncoming(JdwpState* state)
515 JdwpNetState* netState = state->netState;
518 assert(netState->clientSock >= 0);
520 if (!haveFullPacket(netState)) {
521 /* read some more, looping until we have data */
531 /* configure fds; note these may get zapped by another thread */
532 fd = netState->controlSock;
534 FD_SET(fd, &readfds);
538 fd = netState->clientSock;
540 FD_SET(fd, &readfds);
544 fd = netState->wakeFds[0];
546 FD_SET(fd, &readfds);
550 LOGI("NOTE: entering select w/o wakepipe\n");
554 LOGV("+++ all fds are closed\n");
559 * Select blocks until it sees activity on the file descriptors.
560 * Closing the local file descriptor does not count as activity,
561 * so we can't rely on that to wake us up (it works for read()
562 * and accept(), but not select()).
564 * We can do one of three things: (1) send a signal and catch
565 * EINTR, (2) open an additional fd ("wakePipe") and write to
566 * it when it's time to exit, or (3) time out periodically and
567 * re-issue the select. We're currently using #2, as it's more
568 * reliable than #1 and generally better than #3. Wastes two fds.
570 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
574 LOGE("select failed: %s\n", strerror(errno));
578 if (netState->wakeFds[0] >= 0 &&
579 FD_ISSET(netState->wakeFds[0], &readfds))
581 LOGD("Got wake-up signal, bailing out of select\n");
584 if (netState->controlSock >= 0 &&
585 FD_ISSET(netState->controlSock, &readfds))
587 int sock = receiveClientFd(netState);
589 LOGI("Ignoring second debugger -- accepting and dropping\n");
592 assert(netState->controlSock < 0);
594 * Remote side most likely went away, so our next read
595 * on netState->clientSock will fail and throw us out
600 if (netState->clientSock >= 0 &&
601 FD_ISSET(netState->clientSock, &readfds))
603 readCount = read(netState->clientSock,
604 netState->inputBuffer + netState->inputCount,
605 sizeof(netState->inputBuffer) - netState->inputCount);
610 LOGD("+++ EINTR hit\n");
612 } else if (readCount == 0) {
613 /* EOF hit -- far end went away */
614 LOGV("+++ peer disconnected\n");
621 netState->inputCount += readCount;
622 if (!haveFullPacket(netState))
623 return true; /* still not there yet */
627 * Special-case the initial handshake. For some bizarre reason we're
628 * expected to emulate bad tty settings by echoing the request back
629 * exactly as it was sent. Note the handshake is always initiated by
630 * the debugger, no matter who connects to whom.
632 * Other than this one case, the protocol [claims to be] stateless.
634 if (netState->awaitingHandshake) {
637 if (memcmp(netState->inputBuffer,
638 kMagicHandshake, kMagicHandshakeLen) != 0)
640 LOGE("ERROR: bad handshake '%.14s'\n", netState->inputBuffer);
645 cc = write(netState->clientSock, netState->inputBuffer,
647 if (cc != kMagicHandshakeLen) {
648 LOGE("Failed writing handshake bytes: %s (%d of %d)\n",
649 strerror(errno), cc, (int) kMagicHandshakeLen);
653 consumeBytes(netState, kMagicHandshakeLen);
654 netState->awaitingHandshake = false;
655 LOGV("+++ handshake complete\n");
660 * Handle this packet.
662 return handlePacket(state);
665 closeConnection(state);
672 * The entire packet must be sent with a single write() call to avoid
675 * Returns "true" if it was sent successfully.
677 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
679 JdwpNetState* netState = state->netState;
682 if (netState->clientSock < 0) {
683 /* can happen with some DDMS events */
684 LOGV("NOT sending request -- no debugger is attached\n");
689 * TODO: we currently assume the write() will complete in one
690 * go, which may not be safe for a network socket. We may need
691 * to mutex this against handlePacket().
694 cc = write(netState->clientSock, expandBufGetBuffer(pReq),
695 expandBufGetLength(pReq));
696 if (cc != (int) expandBufGetLength(pReq)) {
697 LOGE("Failed sending req to debugger: %s (%d of %d)\n",
698 strerror(errno), cc, (int) expandBufGetLength(pReq));
706 * Send a request that was split into multiple buffers.
708 * The entire packet must be sent with a single writev() call to avoid
711 * Returns "true" if it was sent successfully.
713 static bool sendBufferedRequest(JdwpState* state, const struct iovec* iov,
716 JdwpNetState* netState = state->netState;
718 if (netState->clientSock < 0) {
719 /* can happen with some DDMS events */
720 LOGV("NOT sending request -- no debugger is attached\n");
726 for (i = 0; i < iovcnt; i++)
727 expected += iov[i].iov_len;
730 * TODO: we currently assume the writev() will complete in one
731 * go, which may not be safe for a network socket. We may need
732 * to mutex this against handlePacket().
735 actual = writev(netState->clientSock, iov, iovcnt);
736 if ((size_t)actual != expected) {
737 LOGE("Failed sending b-req to debugger: %s (%d of %zu)\n",
738 strerror(errno), (int) actual, expected);
749 static const JdwpTransport socketTransport = {
766 const JdwpTransport* dvmJdwpAndroidAdbTransport()
768 return &socketTransport;