blob: ed22af9fd5349f231d0168ed140a821ae49f87e7 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16#include "jdwp/JdwpPriv.h"
17#include "jdwp/JdwpHandler.h"
18#include <sys/socket.h>
19#include <sys/un.h>
20#include <errno.h>
21#include <unistd.h>
22
23/* the JDWP <-> ADB transport protocol is explained in details
24 * in //device/tools/adb/jdwp_service.c, here's a summary.
25 *
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
28 * ADB daemon.
29 *
30 * 2/ it then sends the current process PID as a string of 4 hexadecimal
31 * chars (no terminating zero)
32 *
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...
37 *
38 */
39
40#define kInputBufferSize 8192
41
42#define kMagicHandshake "JDWP-Handshake"
43#define kMagicHandshakeLen (sizeof(kMagicHandshake)-1)
44
45#define kJdwpControlName "\0jdwp-control"
46#define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
47
48struct JdwpNetState {
49 int controlSock;
50 int clientSock;
51 bool awaitingHandshake;
52 int wakeFds[2];
53
54 int inputCount;
55 unsigned char inputBuffer[kInputBufferSize];
56
57 socklen_t controlAddrLen;
58 union {
59 struct sockaddr_un controlAddrUn;
60 struct sockaddr controlAddrPlain;
61 } controlAddr;
62};
63
64static void
65adbStateFree( JdwpNetState* netState )
66{
67 if (netState == NULL)
68 return;
69
70 if (netState->clientSock >= 0) {
71 shutdown(netState->clientSock, SHUT_RDWR);
72 close(netState->clientSock);
73 }
74 if (netState->controlSock >= 0) {
75 shutdown(netState->controlSock, SHUT_RDWR);
76 close(netState->controlSock);
77 }
78 if (netState->wakeFds[0] >= 0) {
79 close(netState->wakeFds[0]);
80 netState->wakeFds[0] = -1;
81 }
82 if (netState->wakeFds[1] >= 0) {
83 close(netState->wakeFds[1]);
84 netState->wakeFds[1] = -1;
85 }
86
87 free(netState);
88}
89
90
91static JdwpNetState*
92adbStateAlloc(void)
93{
94 JdwpNetState* netState = calloc(sizeof(*netState),1);
95
96 netState->controlSock = -1;
97 netState->clientSock = -1;
98
99 netState->controlAddr.controlAddrUn.sun_family = AF_UNIX;
100 netState->controlAddrLen =
101 sizeof(netState->controlAddr.controlAddrUn.sun_family) +
102 kJdwpControlNameLen;
103
104 memcpy(netState->controlAddr.controlAddrUn.sun_path,
105 kJdwpControlName, kJdwpControlNameLen);
106
107 netState->wakeFds[0] = -1;
108 netState->wakeFds[1] = -1;
109
110 return netState;
111}
112
113
114/*
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.
118 */
119static bool startup(struct JdwpState* state, const JdwpStartupParams* pParams)
120{
121 JdwpNetState* netState;
122
123 LOGV("ADB transport startup\n");
124
125 state->netState = netState = adbStateAlloc();
126 if (netState == NULL)
127 return false;
128
129 return true;
130}
131
Andy McFadden305efe62009-05-28 14:55:57 -0700132/*
133 * Receive a file descriptor from ADB. The fd can be used to communicate
134 * directly with a debugger or DDMS.
135 *
136 * Returns the file descriptor on success, -1 on call failure. If ADB
137 * went away, this closes netState->controlSock and returns -2.
138 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800139static int receiveClientFd(JdwpNetState* netState)
140{
141 struct msghdr msg;
142 struct cmsghdr* cmsg;
143 struct iovec iov;
144 char dummy = '!';
145 union {
146 struct cmsghdr cm;
147 char buffer[CMSG_SPACE(sizeof(int))];
148 } cm_un;
149 int ret;
150
151 iov.iov_base = &dummy;
152 iov.iov_len = 1;
153 msg.msg_name = NULL;
154 msg.msg_namelen = 0;
155 msg.msg_iov = &iov;
156 msg.msg_iovlen = 1;
157 msg.msg_flags = 0;
158 msg.msg_control = cm_un.buffer;
159 msg.msg_controllen = sizeof(cm_un.buffer);
160
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*)CMSG_DATA(cmsg))[0] = -1;
166
167 do {
168 ret = recvmsg(netState->controlSock, &msg, 0);
169 } while (ret < 0 && errno == EINTR);
170
171 if (ret < 0) {
172 LOGE("receiving file descriptor from ADB failed (socket %d): %s\n",
173 netState->controlSock, strerror(errno));
174 return -1;
Andy McFadden305efe62009-05-28 14:55:57 -0700175 } else if (ret == 0) {
176 close(netState->controlSock);
177 netState->controlSock = -1;
178 return -2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800179 }
180
181 return ((int*)CMSG_DATA(cmsg))[0];
182}
183
184/*
185 * Block forever, waiting for a debugger to connect to us. Called from the
186 * JDWP thread.
187 *
188 * This needs to un-block and return "false" if the VM is shutting down. It
189 * should return "true" when it successfully accepts a connection.
190 */
191static bool acceptConnection(struct JdwpState* state)
192{
193 JdwpNetState* netState = state->netState;
Andy McFadden305efe62009-05-28 14:55:57 -0700194 int retryCount = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800195
196 /* first, ensure that we get a connection to the ADB daemon */
197
Andy McFadden305efe62009-05-28 14:55:57 -0700198retry:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800199 if (netState->controlSock < 0)
200 {
201 int sleep_ms = 500;
202 const int sleep_max_ms = 2*1000;
203 char buff[5];
204
205 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
206 if (netState->controlSock < 0) {
207 LOGE("Could not create ADB control socket:%s\n",
208 strerror(errno));
209 return false;
210 }
211
212 if (pipe(netState->wakeFds) < 0) {
213 LOGE("pipe failed");
214 return false;
215 }
216
217 snprintf(buff, sizeof(buff), "%04x", getpid());
218 buff[4] = 0;
219
220 for (;;) {
Andy McFadden305efe62009-05-28 14:55:57 -0700221 /*
222 * If adbd isn't running, because USB debugging was disabled or
223 * perhaps the system is restarting it for "adb root", the
224 * connect() will fail. We loop here forever waiting for it
225 * to come back.
226 *
227 * Waking up and polling every couple of seconds is generally a
228 * bad thing to do, but we only do this if the application is
229 * debuggable *and* adbd isn't running. Still, for the sake
230 * of battery life, we should consider timing out and giving
231 * up after a few minutes in case somebody ships an app with
232 * the debuggable flag set.
233 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800234 int ret = connect(netState->controlSock,
235 &netState->controlAddr.controlAddrPlain,
236 netState->controlAddrLen);
237 if (!ret) {
238 /* now try to send our pid to the ADB daemon */
239 do {
240 ret = send( netState->controlSock, buff, 4, 0 );
241 } while (ret < 0 && errno == EINTR);
242
243 if (ret >= 0) {
244 LOGV("PID sent as '%.*s' to ADB\n", 4, buff);
245 break;
246 }
247
248 LOGE("Weird, can't send JDWP process pid to ADB: %s\n",
249 strerror(errno));
250 return false;
251 }
252 LOGV("Can't connect to ADB control socket:%s\n",
253 strerror(errno));
254
255 usleep( sleep_ms*1000 );
256
257 sleep_ms += (sleep_ms >> 1);
258 if (sleep_ms > sleep_max_ms)
259 sleep_ms = sleep_max_ms;
260 }
261 }
262
263 LOGV("trying to receive file descriptor from ADB\n");
264 /* now we can receive a client file descriptor */
265 netState->clientSock = receiveClientFd(netState);
Andy McFadden305efe62009-05-28 14:55:57 -0700266 if (netState->clientSock == -1) {
267 return false;
268 } else if (netState->clientSock == -2) {
269 LOGD("adbd dropped us; retrying connection\n");
270 assert(netState->controlSock < 0);
271 if (++retryCount > 5) {
272 /* shouldn't be possible, but we check it just in case */
273 LOGE("max retries exceeded\n");
274 return false;
275 }
276 goto retry;
277 } else {
278 LOGV("received file descriptor %d from ADB\n", netState->clientSock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800279 netState->awaitingHandshake = 1;
280 netState->inputCount = 0;
Andy McFadden305efe62009-05-28 14:55:57 -0700281 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800282 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800283}
284
285/*
286 * Connect out to a debugger (for server=n). Not required.
287 */
288static bool establishConnection(struct JdwpState* state)
289{
290 return false;
291}
292
293/*
294 * Close a connection from a debugger (which may have already dropped us).
295 * Only called from the JDWP thread.
296 */
297static void closeConnection(struct JdwpState* state)
298{
299 JdwpNetState* netState;
300
301 assert(state != NULL && state->netState != NULL);
302
303 netState = state->netState;
304 if (netState->clientSock < 0)
305 return;
306
307 LOGV("+++ closed JDWP <-> ADB connection\n");
308
309 close(netState->clientSock);
310 netState->clientSock = -1;
311}
312
313/*
314 * Close all network stuff, including the socket we use to listen for
315 * new connections.
316 *
317 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
318 */
319static void adbStateShutdown(struct JdwpNetState* netState)
320{
321 int controlSock;
322 int clientSock;
323
324 if (netState == NULL)
325 return;
326
327 clientSock = netState->clientSock;
328 if (clientSock >= 0) {
329 shutdown(clientSock, SHUT_RDWR);
330 netState->clientSock = -1;
331 }
332
333 controlSock = netState->controlSock;
334 if (controlSock >= 0) {
335 shutdown(controlSock, SHUT_RDWR);
336 netState->controlSock = -1;
337 }
338
339 if (netState->wakeFds[1] >= 0) {
340 LOGV("+++ writing to wakePipe\n");
341 (void) write(netState->wakeFds[1], "", 1);
342 }
343}
344
345static void netShutdown(JdwpState* state)
346{
347 adbStateShutdown(state->netState);
348}
349
350/*
351 * Free up anything we put in state->netState. This is called after
352 * "netShutdown", after the JDWP thread has stopped.
353 */
354static void netFree(struct JdwpState* state)
355{
356 JdwpNetState* netState = state->netState;
357
358 adbStateFree(netState);
359}
360
361/*
362 * Is a debugger connected to us?
363 */
364static bool isConnected(struct JdwpState* state)
365{
366 return (state->netState != NULL &&
367 state->netState->clientSock >= 0);
368}
369
370/*
371 * Are we still waiting for the JDWP handshake?
372 */
373static bool awaitingHandshake(struct JdwpState* state)
374{
375 return state->netState->awaitingHandshake;
376}
377
378/*
379 * Figure out if we have a full packet in the buffer.
380 */
381static bool haveFullPacket(JdwpNetState* netState)
382{
383 long length;
384
385 if (netState->awaitingHandshake)
386 return (netState->inputCount >= (int) kMagicHandshakeLen);
387
388 if (netState->inputCount < 4)
389 return false;
390
391 length = get4BE(netState->inputBuffer);
392 return (netState->inputCount >= length);
393}
394
395/*
396 * Consume bytes from the buffer.
397 *
398 * This would be more efficient with a circular buffer. However, we're
399 * usually only going to find one packet, which is trivial to handle.
400 */
401static void consumeBytes(JdwpNetState* netState, int count)
402{
403 assert(count > 0);
404 assert(count <= netState->inputCount);
405
406 if (count == netState->inputCount) {
407 netState->inputCount = 0;
408 return;
409 }
410
411 memmove(netState->inputBuffer, netState->inputBuffer + count,
412 netState->inputCount - count);
413 netState->inputCount -= count;
414}
415
416/*
417 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
418 */
419static bool handlePacket(JdwpState* state)
420{
421 JdwpNetState* netState = state->netState;
422 const unsigned char* buf = netState->inputBuffer;
423 JdwpReqHeader hdr;
424 u4 length, id;
425 u1 flags, cmdSet, cmd;
426 u2 error;
427 bool reply;
428 int dataLen;
429
430 cmd = cmdSet = 0; // shut up gcc
431
432 /*dumpPacket(netState->inputBuffer);*/
433
434 length = read4BE(&buf);
435 id = read4BE(&buf);
436 flags = read1(&buf);
437 if ((flags & kJDWPFlagReply) != 0) {
438 reply = true;
439 error = read2BE(&buf);
440 } else {
441 reply = false;
442 cmdSet = read1(&buf);
443 cmd = read1(&buf);
444 }
445
446 assert((int) length <= netState->inputCount);
447 dataLen = length - (buf - netState->inputBuffer);
448
449 if (!reply) {
450 ExpandBuf* pReply = expandBufAlloc();
451
452 hdr.length = length;
453 hdr.id = id;
454 hdr.cmdSet = cmdSet;
455 hdr.cmd = cmd;
456 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
457 if (expandBufGetLength(pReply) > 0) {
458 int cc;
459
460 /*
461 * TODO: we currently assume the write() will complete in one
462 * go, which may not be safe for a network socket. We may need
463 * to mutex this against sendRequest().
464 */
465 cc = write(netState->clientSock, expandBufGetBuffer(pReply),
466 expandBufGetLength(pReply));
467 if (cc != (int) expandBufGetLength(pReply)) {
468 LOGE("Failed sending reply to debugger: %s\n", strerror(errno));
469 expandBufFree(pReply);
470 return false;
471 }
472 } else {
473 LOGW("No reply created for set=%d cmd=%d\n", cmdSet, cmd);
474 }
475 expandBufFree(pReply);
476 } else {
477 LOGV("reply?!\n");
478 assert(false);
479 }
480
481 LOGV("----------\n");
482
483 consumeBytes(netState, length);
484 return true;
485}
486
487/*
488 * Process incoming data. If no data is available, this will block until
489 * some arrives.
490 *
491 * If we get a full packet, handle it.
492 *
493 * To take some of the mystery out of life, we want to reject incoming
494 * connections if we already have a debugger attached. If we don't, the
495 * debugger will just mysteriously hang until it times out. We could just
496 * close the listen socket, but there's a good chance we won't be able to
497 * bind to the same port again, which would confuse utilities.
498 *
499 * Returns "false" on error (indicating that the connection has been severed),
500 * "true" if things are still okay.
501 */
502static bool processIncoming(JdwpState* state)
503{
504 JdwpNetState* netState = state->netState;
505 int readCount;
506
507 assert(netState->clientSock >= 0);
508
509 if (!haveFullPacket(netState)) {
510 /* read some more, looping until we have data */
511 errno = 0;
512 while (1) {
513 int selCount;
514 fd_set readfds;
515 int maxfd = -1;
516 int fd;
517
518 FD_ZERO(&readfds);
519
520 /* configure fds; note these may get zapped by another thread */
521 fd = netState->controlSock;
522 if (fd >= 0) {
523 FD_SET(fd, &readfds);
524 if (maxfd < fd)
525 maxfd = fd;
526 }
527 fd = netState->clientSock;
528 if (fd >= 0) {
529 FD_SET(fd, &readfds);
530 if (maxfd < fd)
531 maxfd = fd;
532 }
533 fd = netState->wakeFds[0];
534 if (fd >= 0) {
535 FD_SET(fd, &readfds);
536 if (maxfd < fd)
537 maxfd = fd;
538 } else {
539 LOGI("NOTE: entering select w/o wakepipe\n");
540 }
541
542 if (maxfd < 0) {
543 LOGV("+++ all fds are closed\n");
544 return false;
545 }
546
547 /*
548 * Select blocks until it sees activity on the file descriptors.
549 * Closing the local file descriptor does not count as activity,
550 * so we can't rely on that to wake us up (it works for read()
551 * and accept(), but not select()).
552 *
553 * We can do one of three things: (1) send a signal and catch
554 * EINTR, (2) open an additional fd ("wakePipe") and write to
555 * it when it's time to exit, or (3) time out periodically and
556 * re-issue the select. We're currently using #2, as it's more
557 * reliable than #1 and generally better than #3. Wastes two fds.
558 */
559 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
560 if (selCount < 0) {
561 if (errno == EINTR)
562 continue;
563 LOGE("select failed: %s\n", strerror(errno));
564 goto fail;
565 }
566
567 if (netState->wakeFds[0] >= 0 &&
568 FD_ISSET(netState->wakeFds[0], &readfds))
569 {
570 LOGD("Got wake-up signal, bailing out of select\n");
571 goto fail;
572 }
573 if (netState->controlSock >= 0 &&
574 FD_ISSET(netState->controlSock, &readfds))
575 {
576 LOGI("Ignoring second debugger -- accepting and dropping\n");
577 int sock = receiveClientFd(netState);
Andy McFadden305efe62009-05-28 14:55:57 -0700578 if (sock >= 0)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800579 close(sock);
580 }
581 if (netState->clientSock >= 0 &&
582 FD_ISSET(netState->clientSock, &readfds))
583 {
584 readCount = read(netState->clientSock,
585 netState->inputBuffer + netState->inputCount,
586 sizeof(netState->inputBuffer) - netState->inputCount);
587 if (readCount < 0) {
588 /* read failed */
589 if (errno != EINTR)
590 goto fail;
591 LOGD("+++ EINTR hit\n");
592 return true;
593 } else if (readCount == 0) {
594 /* EOF hit -- far end went away */
Andy McFadden305efe62009-05-28 14:55:57 -0700595 LOGV("+++ peer disconnected\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800596 goto fail;
597 } else
598 break;
599 }
600 }
601
602 netState->inputCount += readCount;
603 if (!haveFullPacket(netState))
604 return true; /* still not there yet */
605 }
606
607 /*
608 * Special-case the initial handshake. For some bizarre reason we're
609 * expected to emulate bad tty settings by echoing the request back
610 * exactly as it was sent. Note the handshake is always initiated by
611 * the debugger, no matter who connects to whom.
612 *
613 * Other than this one case, the protocol [claims to be] stateless.
614 */
615 if (netState->awaitingHandshake) {
616 int cc;
617
618 if (memcmp(netState->inputBuffer,
619 kMagicHandshake, kMagicHandshakeLen) != 0)
620 {
621 LOGE("ERROR: bad handshake '%.14s'\n", netState->inputBuffer);
622 goto fail;
623 }
624
625 errno = 0;
626 cc = write(netState->clientSock, netState->inputBuffer,
627 kMagicHandshakeLen);
628 if (cc != kMagicHandshakeLen) {
629 LOGE("Failed writing handshake bytes: %s (%d of %d)\n",
630 strerror(errno), cc, (int) kMagicHandshakeLen);
631 goto fail;
632 }
633
634 consumeBytes(netState, kMagicHandshakeLen);
635 netState->awaitingHandshake = false;
636 LOGV("+++ handshake complete\n");
637 return true;
638 }
639
640 /*
641 * Handle this packet.
642 */
643 return handlePacket(state);
644
645fail:
646 closeConnection(state);
647 return false;
648}
649
650/*
651 * Send a request.
652 *
653 * The entire packet must be sent with a single write() call to avoid
654 * threading issues.
655 *
656 * Returns "true" if it was sent successfully.
657 */
658static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
659{
660 JdwpNetState* netState = state->netState;
661 int cc;
662
663 /* dumpPacket(expandBufGetBuffer(pReq)); */
664 if (netState->clientSock < 0) {
665 /* can happen with some DDMS events */
666 LOGV("NOT sending request -- no debugger is attached\n");
667 return false;
668 }
669
670 /*
671 * TODO: we currently assume the write() will complete in one
672 * go, which may not be safe for a network socket. We may need
673 * to mutex this against handlePacket().
674 */
675 errno = 0;
676 cc = write(netState->clientSock, expandBufGetBuffer(pReq),
677 expandBufGetLength(pReq));
678 if (cc != (int) expandBufGetLength(pReq)) {
679 LOGE("Failed sending req to debugger: %s (%d of %d)\n",
680 strerror(errno), cc, (int) expandBufGetLength(pReq));
681 return false;
682 }
683
684 return true;
685}
686
687
688/*
689 * Our functions.
690 */
691static const JdwpTransport socketTransport = {
692 startup,
693 acceptConnection,
694 establishConnection,
695 closeConnection,
696 netShutdown,
697 netFree,
698 isConnected,
699 awaitingHandshake,
700 processIncoming,
701 sendRequest
702};
703
704/*
705 * Return our set.
706 */
707const JdwpTransport* dvmJdwpAndroidAdbTransport(void)
708{
709 return &socketTransport;
710}
711