JdwpAdb.cpp revision 128689844fda7f9287cc7494ec357397b6d59576
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 50struct JdwpNetState : public JdwpNetStateBase { 51 int controlSock; 52 bool awaitingHandshake; 53 bool shuttingDown; 54 int wakeFds[2]; 55 56 int inputCount; 57 unsigned char inputBuffer[kInputBufferSize]; 58 59 socklen_t controlAddrLen; 60 union { 61 struct sockaddr_un controlAddrUn; 62 struct sockaddr controlAddrPlain; 63 } controlAddr; 64 65 JdwpNetState() 66 { 67 controlSock = -1; 68 awaitingHandshake = false; 69 shuttingDown = false; 70 wakeFds[0] = -1; 71 wakeFds[1] = -1; 72 73 inputCount = 0; 74 75 controlAddr.controlAddrUn.sun_family = AF_UNIX; 76 controlAddrLen = sizeof(controlAddr.controlAddrUn.sun_family) + 77 kJdwpControlNameLen; 78 memcpy(controlAddr.controlAddrUn.sun_path, kJdwpControlName, 79 kJdwpControlNameLen); 80 } 81}; 82 83static void 84adbStateFree( JdwpNetState* netState ) 85{ 86 if (netState == NULL) 87 return; 88 89 if (netState->clientSock >= 0) { 90 shutdown(netState->clientSock, SHUT_RDWR); 91 close(netState->clientSock); 92 } 93 if (netState->controlSock >= 0) { 94 shutdown(netState->controlSock, SHUT_RDWR); 95 close(netState->controlSock); 96 } 97 if (netState->wakeFds[0] >= 0) { 98 close(netState->wakeFds[0]); 99 netState->wakeFds[0] = -1; 100 } 101 if (netState->wakeFds[1] >= 0) { 102 close(netState->wakeFds[1]); 103 netState->wakeFds[1] = -1; 104 } 105 106 delete netState; 107} 108 109/* 110 * Do initial prep work, e.g. binding to ports and opening files. This 111 * runs in the main thread, before the JDWP thread starts, so it shouldn't 112 * do anything that might block forever. 113 */ 114static bool startup(struct JdwpState* state, const JdwpStartupParams* pParams) 115{ 116 JdwpNetState* netState; 117 118 LOGV("ADB transport startup"); 119 120 state->netState = netState = new JdwpNetState; 121 if (netState == NULL) 122 return false; 123 124 return true; 125} 126 127/* 128 * Receive a file descriptor from ADB. The fd can be used to communicate 129 * directly with a debugger or DDMS. 130 * 131 * Returns the file descriptor on success. On failure, returns -1 and 132 * closes netState->controlSock. 133 */ 134static int receiveClientFd(JdwpNetState* netState) 135{ 136 struct msghdr msg; 137 struct cmsghdr* cmsg; 138 struct iovec iov; 139 char dummy = '!'; 140 union { 141 struct cmsghdr cm; 142 char buffer[CMSG_SPACE(sizeof(int))]; 143 } cm_un; 144 int ret; 145 146 iov.iov_base = &dummy; 147 iov.iov_len = 1; 148 msg.msg_name = NULL; 149 msg.msg_namelen = 0; 150 msg.msg_iov = &iov; 151 msg.msg_iovlen = 1; 152 msg.msg_flags = 0; 153 msg.msg_control = cm_un.buffer; 154 msg.msg_controllen = sizeof(cm_un.buffer); 155 156 cmsg = CMSG_FIRSTHDR(&msg); 157 cmsg->cmsg_len = msg.msg_controllen; 158 cmsg->cmsg_level = SOL_SOCKET; 159 cmsg->cmsg_type = SCM_RIGHTS; 160 ((int*)(void*)CMSG_DATA(cmsg))[0] = -1; 161 162 do { 163 ret = recvmsg(netState->controlSock, &msg, 0); 164 } while (ret < 0 && errno == EINTR); 165 166 if (ret <= 0) { 167 if (ret < 0) { 168 LOGW("receiving file descriptor from ADB failed (socket %d): %s", 169 netState->controlSock, strerror(errno)); 170 } else { 171 LOGD("adbd disconnected"); 172 } 173 close(netState->controlSock); 174 netState->controlSock = -1; 175 return -1; 176 } 177 178 return ((int*)(void*)CMSG_DATA(cmsg))[0]; 179} 180 181/* 182 * Block forever, waiting for a debugger to connect to us. Called from the 183 * JDWP thread. 184 * 185 * This needs to un-block and return "false" if the VM is shutting down. It 186 * should return "true" when it successfully accepts a connection. 187 */ 188static bool acceptConnection(struct JdwpState* state) 189{ 190 JdwpNetState* netState = state->netState; 191 int retryCount = 0; 192 193 /* first, ensure that we get a connection to the ADB daemon */ 194 195retry: 196 if (netState->shuttingDown) 197 return false; 198 199 if (netState->controlSock < 0) { 200 int sleep_ms = 500; 201 const int sleep_max_ms = 2*1000; 202 char buff[5]; 203 204 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0); 205 if (netState->controlSock < 0) { 206 LOGE("Could not create ADB control socket:%s", 207 strerror(errno)); 208 return false; 209 } 210 211 if (pipe(netState->wakeFds) < 0) { 212 LOGE("pipe failed"); 213 return false; 214 } 215 216 snprintf(buff, sizeof(buff), "%04x", getpid()); 217 buff[4] = 0; 218 219 for (;;) { 220 /* 221 * If adbd isn't running, because USB debugging was disabled or 222 * perhaps the system is restarting it for "adb root", the 223 * connect() will fail. We loop here forever waiting for it 224 * to come back. 225 * 226 * Waking up and polling every couple of seconds is generally a 227 * bad thing to do, but we only do this if the application is 228 * debuggable *and* adbd isn't running. Still, for the sake 229 * of battery life, we should consider timing out and giving 230 * up after a few minutes in case somebody ships an app with 231 * the debuggable flag set. 232 */ 233 int ret = connect(netState->controlSock, 234 &netState->controlAddr.controlAddrPlain, 235 netState->controlAddrLen); 236 if (!ret) { 237 if (!socket_peer_is_trusted(netState->controlSock)) { 238 if (shutdown(netState->controlSock, SHUT_RDWR)) { 239 LOGE("trouble shutting down socket: %s", strerror(errno)); 240 } 241 return false; 242 } 243 244 /* now try to send our pid to the ADB daemon */ 245 do { 246 ret = send( netState->controlSock, buff, 4, 0 ); 247 } while (ret < 0 && errno == EINTR); 248 249 if (ret >= 0) { 250 LOGV("PID sent as '%.*s' to ADB", 4, buff); 251 break; 252 } 253 254 LOGE("Weird, can't send JDWP process pid to ADB: %s", 255 strerror(errno)); 256 return false; 257 } 258 LOGV("Can't connect to ADB control socket:%s", 259 strerror(errno)); 260 261 usleep( sleep_ms*1000 ); 262 263 sleep_ms += (sleep_ms >> 1); 264 if (sleep_ms > sleep_max_ms) 265 sleep_ms = sleep_max_ms; 266 267 if (netState->shuttingDown) 268 return false; 269 } 270 } 271 272 LOGV("trying to receive file descriptor from ADB"); 273 /* now we can receive a client file descriptor */ 274 netState->clientSock = receiveClientFd(netState); 275 if (netState->shuttingDown) 276 return false; // suppress logs and additional activity 277 278 if (netState->clientSock < 0) { 279 if (++retryCount > 5) { 280 LOGE("adb connection max retries exceeded"); 281 return false; 282 } 283 goto retry; 284 } else { 285 LOGV("received file descriptor %d from ADB", netState->clientSock); 286 netState->awaitingHandshake = 1; 287 netState->inputCount = 0; 288 return true; 289 } 290} 291 292/* 293 * Connect out to a debugger (for server=n). Not required. 294 */ 295static bool establishConnection(struct JdwpState* state) 296{ 297 return false; 298} 299 300/* 301 * Close a connection from a debugger (which may have already dropped us). 302 * Only called from the JDWP thread. 303 */ 304static void closeConnection(struct JdwpState* state) 305{ 306 JdwpNetState* netState; 307 308 assert(state != NULL && state->netState != NULL); 309 310 netState = state->netState; 311 if (netState->clientSock < 0) 312 return; 313 314 LOGV("+++ closed JDWP <-> ADB connection"); 315 316 close(netState->clientSock); 317 netState->clientSock = -1; 318} 319 320/* 321 * Close all network stuff, including the socket we use to listen for 322 * new connections. 323 * 324 * May be called from a non-JDWP thread, e.g. when the VM is shutting down. 325 */ 326static void adbStateShutdown(struct JdwpNetState* netState) 327{ 328 int controlSock; 329 int clientSock; 330 331 if (netState == NULL) 332 return; 333 334 netState->shuttingDown = true; 335 336 clientSock = netState->clientSock; 337 if (clientSock >= 0) { 338 shutdown(clientSock, SHUT_RDWR); 339 netState->clientSock = -1; 340 } 341 342 controlSock = netState->controlSock; 343 if (controlSock >= 0) { 344 shutdown(controlSock, SHUT_RDWR); 345 netState->controlSock = -1; 346 } 347 348 if (netState->wakeFds[1] >= 0) { 349 LOGV("+++ writing to wakePipe"); 350 write(netState->wakeFds[1], "", 1); 351 } 352} 353 354static void netShutdown(JdwpState* state) 355{ 356 adbStateShutdown(state->netState); 357} 358 359/* 360 * Free up anything we put in state->netState. This is called after 361 * "netShutdown", after the JDWP thread has stopped. 362 */ 363static void netFree(struct JdwpState* state) 364{ 365 JdwpNetState* netState = state->netState; 366 367 adbStateFree(netState); 368} 369 370/* 371 * Is a debugger connected to us? 372 */ 373static bool isConnected(struct JdwpState* state) 374{ 375 return (state->netState != NULL && 376 state->netState->clientSock >= 0); 377} 378 379/* 380 * Are we still waiting for the JDWP handshake? 381 */ 382static bool awaitingHandshake(struct JdwpState* state) 383{ 384 return state->netState->awaitingHandshake; 385} 386 387/* 388 * Figure out if we have a full packet in the buffer. 389 */ 390static bool haveFullPacket(JdwpNetState* netState) 391{ 392 long length; 393 394 if (netState->awaitingHandshake) 395 return (netState->inputCount >= (int) kMagicHandshakeLen); 396 397 if (netState->inputCount < 4) 398 return false; 399 400 length = get4BE(netState->inputBuffer); 401 return (netState->inputCount >= length); 402} 403 404/* 405 * Consume bytes from the buffer. 406 * 407 * This would be more efficient with a circular buffer. However, we're 408 * usually only going to find one packet, which is trivial to handle. 409 */ 410static void consumeBytes(JdwpNetState* netState, int count) 411{ 412 assert(count > 0); 413 assert(count <= netState->inputCount); 414 415 if (count == netState->inputCount) { 416 netState->inputCount = 0; 417 return; 418 } 419 420 memmove(netState->inputBuffer, netState->inputBuffer + count, 421 netState->inputCount - count); 422 netState->inputCount -= count; 423} 424 425/* 426 * Handle a packet. Returns "false" if we encounter a connection-fatal error. 427 */ 428static bool handlePacket(JdwpState* state) 429{ 430 JdwpNetState* netState = state->netState; 431 const unsigned char* buf = netState->inputBuffer; 432 JdwpReqHeader hdr; 433 u4 length, id; 434 u1 flags, cmdSet, cmd; 435 u2 error; 436 bool reply; 437 int dataLen; 438 439 cmd = cmdSet = 0; // shut up gcc 440 441 length = read4BE(&buf); 442 id = read4BE(&buf); 443 flags = read1(&buf); 444 if ((flags & kJDWPFlagReply) != 0) { 445 reply = true; 446 error = read2BE(&buf); 447 } else { 448 reply = false; 449 cmdSet = read1(&buf); 450 cmd = read1(&buf); 451 } 452 453 assert((int) length <= netState->inputCount); 454 dataLen = length - (buf - netState->inputBuffer); 455 456 if (!reply) { 457 ExpandBuf* pReply = expandBufAlloc(); 458 459 hdr.length = length; 460 hdr.id = id; 461 hdr.cmdSet = cmdSet; 462 hdr.cmd = cmd; 463 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply); 464 if (expandBufGetLength(pReply) > 0) { 465 ssize_t cc = netState->writePacket(pReply); 466 467 if (cc != (ssize_t) expandBufGetLength(pReply)) { 468 LOGE("Failed sending reply to debugger: %s", strerror(errno)); 469 expandBufFree(pReply); 470 return false; 471 } 472 } else { 473 LOGW("No reply created for set=%d cmd=%d", cmdSet, cmd); 474 } 475 expandBufFree(pReply); 476 } else { 477 LOGV("reply?!"); 478 assert(false); 479 } 480 481 LOGV("----------"); 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"); 540 } 541 542 if (maxfd < 0) { 543 LOGV("+++ all fds are closed"); 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", 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"); 571 goto fail; 572 } 573 if (netState->controlSock >= 0 && 574 FD_ISSET(netState->controlSock, &readfds)) 575 { 576 int sock = receiveClientFd(netState); 577 if (sock >= 0) { 578 LOGI("Ignoring second debugger -- accepting and dropping"); 579 close(sock); 580 } else { 581 assert(netState->controlSock < 0); 582 /* 583 * Remote side most likely went away, so our next read 584 * on netState->clientSock will fail and throw us out 585 * of the loop. 586 */ 587 } 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"); 600 return true; 601 } else if (readCount == 0) { 602 /* EOF hit -- far end went away */ 603 LOGV("+++ peer disconnected"); 604 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'", 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)", 638 strerror(errno), cc, (int) kMagicHandshakeLen); 639 goto fail; 640 } 641 642 consumeBytes(netState, kMagicHandshakeLen); 643 netState->awaitingHandshake = false; 644 LOGV("+++ handshake complete"); 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 670 if (netState->clientSock < 0) { 671 /* can happen with some DDMS events */ 672 LOGV("NOT sending request -- no debugger is attached"); 673 return false; 674 } 675 676 errno = 0; 677 678 ssize_t cc = netState->writePacket(pReq); 679 680 if (cc != (ssize_t) expandBufGetLength(pReq)) { 681 LOGE("Failed sending req to debugger: %s (%d of %d)", 682 strerror(errno), (int) cc, (int) expandBufGetLength(pReq)); 683 return false; 684 } 685 686 return true; 687} 688 689/* 690 * Send a request that was split into multiple buffers. 691 * 692 * The entire packet must be sent with a single writev() call to avoid 693 * threading issues. 694 * 695 * Returns "true" if it was sent successfully. 696 */ 697static bool sendBufferedRequest(JdwpState* state, const struct iovec* iov, 698 int iovcnt) 699{ 700 JdwpNetState* netState = state->netState; 701 702 if (netState->clientSock < 0) { 703 /* can happen with some DDMS events */ 704 LOGV("NOT sending request -- no debugger is attached"); 705 return false; 706 } 707 708 size_t expected = 0; 709 int i; 710 for (i = 0; i < iovcnt; i++) 711 expected += iov[i].iov_len; 712 713 ssize_t actual = netState->writeBufferedPacket(iov, iovcnt); 714 715 if ((size_t)actual != expected) { 716 LOGE("Failed sending b-req to debugger: %s (%d of %zu)", 717 strerror(errno), (int) actual, expected); 718 return false; 719 } 720 721 return true; 722} 723 724 725/* 726 * Our functions. 727 */ 728static const JdwpTransport socketTransport = { 729 startup, 730 acceptConnection, 731 establishConnection, 732 closeConnection, 733 netShutdown, 734 netFree, 735 isConnected, 736 awaitingHandshake, 737 processIncoming, 738 sendRequest, 739 sendBufferedRequest 740}; 741 742/* 743 * Return our set. 744 */ 745const JdwpTransport* dvmJdwpAndroidAdbTransport() 746{ 747 return &socketTransport; 748} 749