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