• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #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 
48 struct 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 
64 static void
adbStateFree(JdwpNetState * netState)65 adbStateFree( 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 
91 static JdwpNetState*
adbStateAlloc(void)92 adbStateAlloc(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  */
startup(struct JdwpState * state,const JdwpStartupParams * pParams)119 static 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 
receiveClientFd(JdwpNetState * netState)132 static int  receiveClientFd(JdwpNetState*  netState)
133 {
134     struct msghdr    msg;
135     struct cmsghdr*  cmsg;
136     struct iovec     iov;
137     char             dummy = '!';
138     union {
139         struct cmsghdr cm;
140         char buffer[CMSG_SPACE(sizeof(int))];
141     } cm_un;
142     int              ret;
143 
144     iov.iov_base       = &dummy;
145     iov.iov_len        = 1;
146     msg.msg_name       = NULL;
147     msg.msg_namelen    = 0;
148     msg.msg_iov        = &iov;
149     msg.msg_iovlen     = 1;
150     msg.msg_flags      = 0;
151     msg.msg_control    = cm_un.buffer;
152     msg.msg_controllen = sizeof(cm_un.buffer);
153 
154     cmsg = CMSG_FIRSTHDR(&msg);
155     cmsg->cmsg_len   = msg.msg_controllen;
156     cmsg->cmsg_level = SOL_SOCKET;
157     cmsg->cmsg_type  = SCM_RIGHTS;
158     ((int*)CMSG_DATA(cmsg))[0] = -1;
159 
160     do {
161         ret = recvmsg(netState->controlSock, &msg, 0);
162     } while (ret < 0 && errno == EINTR);
163 
164     if (ret < 0) {
165         LOGE("receiving file descriptor from ADB failed (socket %d): %s\n",
166              netState->controlSock, strerror(errno));
167         return -1;
168     }
169 
170     return ((int*)CMSG_DATA(cmsg))[0];
171 }
172 
173 /*
174  * Block forever, waiting for a debugger to connect to us.  Called from the
175  * JDWP thread.
176  *
177  * This needs to un-block and return "false" if the VM is shutting down.  It
178  * should return "true" when it successfully accepts a connection.
179  */
acceptConnection(struct JdwpState * state)180 static bool acceptConnection(struct JdwpState* state)
181 {
182     JdwpNetState*  netState = state->netState;
183 
184     /* first, ensure that we get a connection to the ADB daemon */
185 
186     if (netState->controlSock < 0)
187     {
188         int        sleep_ms     = 500;
189         const int  sleep_max_ms = 2*1000;
190         char       buff[5];
191 
192         netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
193         if (netState->controlSock < 0) {
194             LOGE("Could not create ADB control socket:%s\n",
195                  strerror(errno));
196             return false;
197         }
198 
199         if (pipe(netState->wakeFds) < 0) {
200             LOGE("pipe failed");
201             return false;
202         }
203 
204         snprintf(buff, sizeof(buff), "%04x", getpid());
205         buff[4] = 0;
206 
207         for (;;) {
208             int  ret = connect(netState->controlSock,
209                                &netState->controlAddr.controlAddrPlain,
210                                netState->controlAddrLen);
211             if (!ret) {
212                 /* now try to send our pid to the ADB daemon */
213                 do {
214                     ret = send( netState->controlSock, buff, 4, 0 );
215                 } while (ret < 0 && errno == EINTR);
216 
217                 if (ret >= 0) {
218                     LOGV("PID sent as '%.*s' to ADB\n", 4, buff);
219                     break;
220                 }
221 
222                 LOGE("Weird, can't send JDWP process pid to ADB: %s\n",
223                      strerror(errno));
224                 return false;
225             }
226             LOGV("Can't connect to ADB control socket:%s\n",
227                  strerror(errno));
228 
229             usleep( sleep_ms*1000 );
230 
231             sleep_ms += (sleep_ms >> 1);
232             if (sleep_ms > sleep_max_ms)
233                 sleep_ms = sleep_max_ms;
234         }
235     }
236 
237     LOGV("trying to receive file descriptor from ADB\n");
238     /* now we can receive a client file descriptor */
239     netState->clientSock = receiveClientFd(netState);
240     if (netState->clientSock >= 0) {
241         LOGI("received file descriptor %d from ADB\n", netState->clientSock);
242         netState->awaitingHandshake = 1;
243         netState->inputCount = 0;
244     }
245     return (netState->clientSock >= 0);
246 }
247 
248 /*
249  * Connect out to a debugger (for server=n).  Not required.
250  */
establishConnection(struct JdwpState * state)251 static bool establishConnection(struct JdwpState* state)
252 {
253     return false;
254 }
255 
256 /*
257  * Close a connection from a debugger (which may have already dropped us).
258  * Only called from the JDWP thread.
259  */
closeConnection(struct JdwpState * state)260 static void closeConnection(struct JdwpState* state)
261 {
262     JdwpNetState* netState;
263 
264     assert(state != NULL && state->netState != NULL);
265 
266     netState = state->netState;
267     if (netState->clientSock < 0)
268         return;
269 
270     LOGV("+++ closed JDWP <-> ADB connection\n");
271 
272     close(netState->clientSock);
273     netState->clientSock = -1;
274 }
275 
276 /*
277  * Close all network stuff, including the socket we use to listen for
278  * new connections.
279  *
280  * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
281  */
adbStateShutdown(struct JdwpNetState * netState)282 static void adbStateShutdown(struct JdwpNetState* netState)
283 {
284     int  controlSock;
285     int  clientSock;
286 
287     if (netState == NULL)
288         return;
289 
290     clientSock = netState->clientSock;
291     if (clientSock >= 0) {
292         shutdown(clientSock, SHUT_RDWR);
293         netState->clientSock = -1;
294     }
295 
296     controlSock = netState->controlSock;
297     if (controlSock >= 0) {
298         shutdown(controlSock, SHUT_RDWR);
299         netState->controlSock = -1;
300     }
301 
302     if (netState->wakeFds[1] >= 0) {
303         LOGV("+++ writing to wakePipe\n");
304         (void) write(netState->wakeFds[1], "", 1);
305     }
306 }
307 
netShutdown(JdwpState * state)308 static void netShutdown(JdwpState* state)
309 {
310     adbStateShutdown(state->netState);
311 }
312 
313 /*
314  * Free up anything we put in state->netState.  This is called after
315  * "netShutdown", after the JDWP thread has stopped.
316  */
netFree(struct JdwpState * state)317 static void netFree(struct JdwpState* state)
318 {
319     JdwpNetState*  netState = state->netState;
320 
321     adbStateFree(netState);
322 }
323 
324 /*
325  * Is a debugger connected to us?
326  */
isConnected(struct JdwpState * state)327 static bool isConnected(struct JdwpState* state)
328 {
329     return (state->netState != NULL   &&
330             state->netState->clientSock >= 0);
331 }
332 
333 /*
334  * Are we still waiting for the JDWP handshake?
335  */
awaitingHandshake(struct JdwpState * state)336 static bool awaitingHandshake(struct JdwpState* state)
337 {
338     return state->netState->awaitingHandshake;
339 }
340 
341 /*
342  * Figure out if we have a full packet in the buffer.
343  */
haveFullPacket(JdwpNetState * netState)344 static bool haveFullPacket(JdwpNetState* netState)
345 {
346     long length;
347 
348     if (netState->awaitingHandshake)
349         return (netState->inputCount >= (int) kMagicHandshakeLen);
350 
351     if (netState->inputCount < 4)
352         return false;
353 
354     length = get4BE(netState->inputBuffer);
355     return (netState->inputCount >= length);
356 }
357 
358 /*
359  * Consume bytes from the buffer.
360  *
361  * This would be more efficient with a circular buffer.  However, we're
362  * usually only going to find one packet, which is trivial to handle.
363  */
consumeBytes(JdwpNetState * netState,int count)364 static void consumeBytes(JdwpNetState* netState, int count)
365 {
366     assert(count > 0);
367     assert(count <= netState->inputCount);
368 
369     if (count == netState->inputCount) {
370         netState->inputCount = 0;
371         return;
372     }
373 
374     memmove(netState->inputBuffer, netState->inputBuffer + count,
375         netState->inputCount - count);
376     netState->inputCount -= count;
377 }
378 
379 /*
380  * Handle a packet.  Returns "false" if we encounter a connection-fatal error.
381  */
handlePacket(JdwpState * state)382 static bool handlePacket(JdwpState* state)
383 {
384     JdwpNetState* netState = state->netState;
385     const unsigned char* buf = netState->inputBuffer;
386     JdwpReqHeader hdr;
387     u4 length, id;
388     u1 flags, cmdSet, cmd;
389     u2 error;
390     bool reply;
391     int dataLen;
392 
393     cmd = cmdSet = 0;       // shut up gcc
394 
395     /*dumpPacket(netState->inputBuffer);*/
396 
397     length = read4BE(&buf);
398     id = read4BE(&buf);
399     flags = read1(&buf);
400     if ((flags & kJDWPFlagReply) != 0) {
401         reply = true;
402         error = read2BE(&buf);
403     } else {
404         reply = false;
405         cmdSet = read1(&buf);
406         cmd = read1(&buf);
407     }
408 
409     assert((int) length <= netState->inputCount);
410     dataLen = length - (buf - netState->inputBuffer);
411 
412     if (!reply) {
413         ExpandBuf* pReply = expandBufAlloc();
414 
415         hdr.length = length;
416         hdr.id = id;
417         hdr.cmdSet = cmdSet;
418         hdr.cmd = cmd;
419         dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
420         if (expandBufGetLength(pReply) > 0) {
421             int cc;
422 
423             /*
424              * TODO: we currently assume the write() will complete in one
425              * go, which may not be safe for a network socket.  We may need
426              * to mutex this against sendRequest().
427              */
428             cc = write(netState->clientSock, expandBufGetBuffer(pReply),
429                     expandBufGetLength(pReply));
430             if (cc != (int) expandBufGetLength(pReply)) {
431                 LOGE("Failed sending reply to debugger: %s\n", strerror(errno));
432                 expandBufFree(pReply);
433                 return false;
434             }
435         } else {
436             LOGW("No reply created for set=%d cmd=%d\n", cmdSet, cmd);
437         }
438         expandBufFree(pReply);
439     } else {
440         LOGV("reply?!\n");
441         assert(false);
442     }
443 
444     LOGV("----------\n");
445 
446     consumeBytes(netState, length);
447     return true;
448 }
449 
450 /*
451  * Process incoming data.  If no data is available, this will block until
452  * some arrives.
453  *
454  * If we get a full packet, handle it.
455  *
456  * To take some of the mystery out of life, we want to reject incoming
457  * connections if we already have a debugger attached.  If we don't, the
458  * debugger will just mysteriously hang until it times out.  We could just
459  * close the listen socket, but there's a good chance we won't be able to
460  * bind to the same port again, which would confuse utilities.
461  *
462  * Returns "false" on error (indicating that the connection has been severed),
463  * "true" if things are still okay.
464  */
processIncoming(JdwpState * state)465 static bool processIncoming(JdwpState* state)
466 {
467     JdwpNetState* netState = state->netState;
468     int readCount;
469 
470     assert(netState->clientSock >= 0);
471 
472     if (!haveFullPacket(netState)) {
473         /* read some more, looping until we have data */
474         errno = 0;
475         while (1) {
476             int selCount;
477             fd_set readfds;
478             int maxfd = -1;
479             int fd;
480 
481             FD_ZERO(&readfds);
482 
483             /* configure fds; note these may get zapped by another thread */
484             fd = netState->controlSock;
485             if (fd >= 0) {
486                 FD_SET(fd, &readfds);
487                 if (maxfd < fd)
488                     maxfd = fd;
489             }
490             fd = netState->clientSock;
491             if (fd >= 0) {
492                 FD_SET(fd, &readfds);
493                 if (maxfd < fd)
494                     maxfd = fd;
495             }
496             fd = netState->wakeFds[0];
497             if (fd >= 0) {
498                 FD_SET(fd, &readfds);
499                 if (maxfd < fd)
500                     maxfd = fd;
501             } else {
502                 LOGI("NOTE: entering select w/o wakepipe\n");
503             }
504 
505             if (maxfd < 0) {
506                 LOGV("+++ all fds are closed\n");
507                 return false;
508             }
509 
510             /*
511              * Select blocks until it sees activity on the file descriptors.
512              * Closing the local file descriptor does not count as activity,
513              * so we can't rely on that to wake us up (it works for read()
514              * and accept(), but not select()).
515              *
516              * We can do one of three things: (1) send a signal and catch
517              * EINTR, (2) open an additional fd ("wakePipe") and write to
518              * it when it's time to exit, or (3) time out periodically and
519              * re-issue the select.  We're currently using #2, as it's more
520              * reliable than #1 and generally better than #3.  Wastes two fds.
521              */
522             selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
523             if (selCount < 0) {
524                 if (errno == EINTR)
525                     continue;
526                 LOGE("select failed: %s\n", strerror(errno));
527                 goto fail;
528             }
529 
530             if (netState->wakeFds[0] >= 0 &&
531                 FD_ISSET(netState->wakeFds[0], &readfds))
532             {
533                 LOGD("Got wake-up signal, bailing out of select\n");
534                 goto fail;
535             }
536             if (netState->controlSock >= 0 &&
537                 FD_ISSET(netState->controlSock, &readfds))
538             {
539                 LOGI("Ignoring second debugger -- accepting and dropping\n");
540                 int  sock = receiveClientFd(netState);
541                 if (sock < 0)
542                     LOGI("Weird -- client fd reception failed\n");
543                 else
544                     close(sock);
545             }
546             if (netState->clientSock >= 0 &&
547                 FD_ISSET(netState->clientSock, &readfds))
548             {
549                 readCount = read(netState->clientSock,
550                                 netState->inputBuffer + netState->inputCount,
551                     sizeof(netState->inputBuffer) - netState->inputCount);
552                 if (readCount < 0) {
553                     /* read failed */
554                     if (errno != EINTR)
555                         goto fail;
556                     LOGD("+++ EINTR hit\n");
557                     return true;
558                 } else if (readCount == 0) {
559                     /* EOF hit -- far end went away */
560                     LOGD("+++ peer disconnected\n");
561                     goto fail;
562                 } else
563                     break;
564             }
565         }
566 
567         netState->inputCount += readCount;
568         if (!haveFullPacket(netState))
569             return true;        /* still not there yet */
570     }
571 
572     /*
573      * Special-case the initial handshake.  For some bizarre reason we're
574      * expected to emulate bad tty settings by echoing the request back
575      * exactly as it was sent.  Note the handshake is always initiated by
576      * the debugger, no matter who connects to whom.
577      *
578      * Other than this one case, the protocol [claims to be] stateless.
579      */
580     if (netState->awaitingHandshake) {
581         int cc;
582 
583         if (memcmp(netState->inputBuffer,
584                 kMagicHandshake, kMagicHandshakeLen) != 0)
585         {
586             LOGE("ERROR: bad handshake '%.14s'\n", netState->inputBuffer);
587             goto fail;
588         }
589 
590         errno = 0;
591         cc = write(netState->clientSock, netState->inputBuffer,
592                 kMagicHandshakeLen);
593         if (cc != kMagicHandshakeLen) {
594             LOGE("Failed writing handshake bytes: %s (%d of %d)\n",
595                 strerror(errno), cc, (int) kMagicHandshakeLen);
596             goto fail;
597         }
598 
599         consumeBytes(netState, kMagicHandshakeLen);
600         netState->awaitingHandshake = false;
601         LOGV("+++ handshake complete\n");
602         return true;
603     }
604 
605     /*
606      * Handle this packet.
607      */
608     return handlePacket(state);
609 
610 fail:
611     closeConnection(state);
612     return false;
613 }
614 
615 /*
616  * Send a request.
617  *
618  * The entire packet must be sent with a single write() call to avoid
619  * threading issues.
620  *
621  * Returns "true" if it was sent successfully.
622  */
sendRequest(JdwpState * state,ExpandBuf * pReq)623 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
624 {
625     JdwpNetState* netState = state->netState;
626     int cc;
627 
628     /* dumpPacket(expandBufGetBuffer(pReq)); */
629     if (netState->clientSock < 0) {
630         /* can happen with some DDMS events */
631         LOGV("NOT sending request -- no debugger is attached\n");
632         return false;
633     }
634 
635     /*
636      * TODO: we currently assume the write() will complete in one
637      * go, which may not be safe for a network socket.  We may need
638      * to mutex this against handlePacket().
639      */
640     errno = 0;
641     cc = write(netState->clientSock, expandBufGetBuffer(pReq),
642             expandBufGetLength(pReq));
643     if (cc != (int) expandBufGetLength(pReq)) {
644         LOGE("Failed sending req to debugger: %s (%d of %d)\n",
645             strerror(errno), cc, (int) expandBufGetLength(pReq));
646         return false;
647     }
648 
649     return true;
650 }
651 
652 
653 /*
654  * Our functions.
655  */
656 static const JdwpTransport socketTransport = {
657     startup,
658     acceptConnection,
659     establishConnection,
660     closeConnection,
661     netShutdown,
662     netFree,
663     isConnected,
664     awaitingHandshake,
665     processIncoming,
666     sendRequest
667 };
668 
669 /*
670  * Return our set.
671  */
dvmJdwpAndroidAdbTransport(void)672 const JdwpTransport* dvmJdwpAndroidAdbTransport(void)
673 {
674     return &socketTransport;
675 }
676 
677