OSDN Git Service

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