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 <errno.h> 18 #include <stdio.h> 19 #include <sys/socket.h> 20 #include <sys/un.h> 21 #include <unistd.h> 22 23 #include "base/logging.h" 24 #include "base/stringprintf.h" 25 #include "jdwp/jdwp_priv.h" 26 27 #ifdef HAVE_ANDROID_OS 28 #include "cutils/sockets.h" 29 #endif 30 31 /* 32 * The JDWP <-> ADB transport protocol is explained in detail 33 * in system/core/adb/jdwp_service.c. Here's a summary. 34 * 35 * 1/ when the JDWP thread starts, it tries to connect to a Unix 36 * domain stream socket (@jdwp-control) that is opened by the 37 * ADB daemon. 38 * 39 * 2/ it then sends the current process PID as a string of 4 hexadecimal 40 * chars (no terminating zero) 41 * 42 * 3/ then, it uses recvmsg to receive file descriptors from the 43 * daemon. each incoming file descriptor is a pass-through to 44 * a given JDWP debugger, that can be used to read the usual 45 * JDWP-handshake, etc... 46 */ 47 48 #define kJdwpControlName "\0jdwp-control" 49 #define kJdwpControlNameLen (sizeof(kJdwpControlName)-1) 50 51 namespace art { 52 53 namespace JDWP { 54 55 struct JdwpAdbState : public JdwpNetStateBase { 56 public: 57 explicit JdwpAdbState(JdwpState* state) : JdwpNetStateBase(state) { 58 control_sock_ = -1; 59 shutting_down_ = false; 60 61 control_addr_.controlAddrUn.sun_family = AF_UNIX; 62 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + kJdwpControlNameLen; 63 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, kJdwpControlNameLen); 64 } 65 66 ~JdwpAdbState() { 67 if (clientSock != -1) { 68 shutdown(clientSock, SHUT_RDWR); 69 close(clientSock); 70 } 71 if (control_sock_ != -1) { 72 shutdown(control_sock_, SHUT_RDWR); 73 close(control_sock_); 74 } 75 } 76 77 virtual bool Accept(); 78 79 virtual bool Establish(const JdwpOptions*) { 80 return false; 81 } 82 83 virtual void Shutdown() { 84 shutting_down_ = true; 85 86 int control_sock = this->control_sock_; 87 int clientSock = this->clientSock; 88 89 /* clear these out so it doesn't wake up and try to reuse them */ 90 this->control_sock_ = this->clientSock = -1; 91 92 if (clientSock != -1) { 93 shutdown(clientSock, SHUT_RDWR); 94 } 95 96 if (control_sock != -1) { 97 shutdown(control_sock, SHUT_RDWR); 98 } 99 100 WakePipe(); 101 } 102 103 virtual bool ProcessIncoming(); 104 105 private: 106 int ReceiveClientFd(); 107 108 int control_sock_; 109 bool shutting_down_; 110 111 socklen_t control_addr_len_; 112 union { 113 sockaddr_un controlAddrUn; 114 sockaddr controlAddrPlain; 115 } control_addr_; 116 }; 117 118 /* 119 * Do initial prep work, e.g. binding to ports and opening files. This 120 * runs in the main thread, before the JDWP thread starts, so it shouldn't 121 * do anything that might block forever. 122 */ 123 bool InitAdbTransport(JdwpState* state, const JdwpOptions*) { 124 VLOG(jdwp) << "ADB transport startup"; 125 state->netState = new JdwpAdbState(state); 126 return (state->netState != NULL); 127 } 128 129 /* 130 * Receive a file descriptor from ADB. The fd can be used to communicate 131 * directly with a debugger or DDMS. 132 * 133 * Returns the file descriptor on success. On failure, returns -1 and 134 * closes netState->control_sock_. 135 */ 136 int JdwpAdbState::ReceiveClientFd() { 137 char dummy = '!'; 138 union { 139 cmsghdr cm; 140 char buffer[CMSG_SPACE(sizeof(int))]; 141 } cm_un; 142 143 iovec iov; 144 iov.iov_base = &dummy; 145 iov.iov_len = 1; 146 147 msghdr msg; 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 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); 157 cmsg->cmsg_len = msg.msg_controllen; 158 cmsg->cmsg_level = SOL_SOCKET; 159 cmsg->cmsg_type = SCM_RIGHTS; 160 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1; 161 162 int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0)); 163 164 if (rc <= 0) { 165 if (rc == -1) { 166 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")"; 167 } 168 close(control_sock_); 169 control_sock_ = -1; 170 return -1; 171 } 172 173 return (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]; 174 } 175 176 /* 177 * Block forever, waiting for a debugger to connect to us. Called from the 178 * JDWP thread. 179 * 180 * This needs to un-block and return "false" if the VM is shutting down. It 181 * should return "true" when it successfully accepts a connection. 182 */ 183 bool JdwpAdbState::Accept() { 184 int retryCount = 0; 185 186 /* first, ensure that we get a connection to the ADB daemon */ 187 188 retry: 189 if (shutting_down_) { 190 return false; 191 } 192 193 if (control_sock_ == -1) { 194 int sleep_ms = 500; 195 const int sleep_max_ms = 2*1000; 196 char buff[5]; 197 198 control_sock_ = socket(PF_UNIX, SOCK_STREAM, 0); 199 if (control_sock_ < 0) { 200 PLOG(ERROR) << "Could not create ADB control socket"; 201 return false; 202 } 203 204 if (!MakePipe()) { 205 return false; 206 } 207 208 snprintf(buff, sizeof(buff), "%04x", getpid()); 209 buff[4] = 0; 210 211 for (;;) { 212 /* 213 * If adbd isn't running, because USB debugging was disabled or 214 * perhaps the system is restarting it for "adb root", the 215 * connect() will fail. We loop here forever waiting for it 216 * to come back. 217 * 218 * Waking up and polling every couple of seconds is generally a 219 * bad thing to do, but we only do this if the application is 220 * debuggable *and* adbd isn't running. Still, for the sake 221 * of battery life, we should consider timing out and giving 222 * up after a few minutes in case somebody ships an app with 223 * the debuggable flag set. 224 */ 225 int ret = connect(control_sock_, &control_addr_.controlAddrPlain, control_addr_len_); 226 if (!ret) { 227 #ifdef HAVE_ANDROID_OS 228 if (!socket_peer_is_trusted(control_sock_)) { 229 if (shutdown(control_sock_, SHUT_RDWR)) { 230 PLOG(ERROR) << "trouble shutting down socket"; 231 } 232 return false; 233 } 234 #endif 235 236 /* now try to send our pid to the ADB daemon */ 237 ret = TEMP_FAILURE_RETRY(send(control_sock_, buff, 4, 0)); 238 if (ret >= 0) { 239 VLOG(jdwp) << StringPrintf("PID sent as '%.*s' to ADB", 4, buff); 240 break; 241 } 242 243 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB"; 244 return false; 245 } 246 if (VLOG_IS_ON(jdwp)) { 247 PLOG(ERROR) << "Can't connect to ADB control socket"; 248 } 249 250 usleep(sleep_ms * 1000); 251 252 sleep_ms += (sleep_ms >> 1); 253 if (sleep_ms > sleep_max_ms) { 254 sleep_ms = sleep_max_ms; 255 } 256 if (shutting_down_) { 257 return false; 258 } 259 } 260 } 261 262 VLOG(jdwp) << "trying to receive file descriptor from ADB"; 263 /* now we can receive a client file descriptor */ 264 clientSock = ReceiveClientFd(); 265 if (shutting_down_) { 266 return false; // suppress logs and additional activity 267 } 268 if (clientSock == -1) { 269 if (++retryCount > 5) { 270 LOG(ERROR) << "adb connection max retries exceeded"; 271 return false; 272 } 273 goto retry; 274 } else { 275 VLOG(jdwp) << "received file descriptor " << clientSock << " from ADB"; 276 SetAwaitingHandshake(true); 277 input_count_ = 0; 278 return true; 279 } 280 } 281 282 /* 283 * Process incoming data. If no data is available, this will block until 284 * some arrives. 285 * 286 * If we get a full packet, handle it. 287 * 288 * To take some of the mystery out of life, we want to reject incoming 289 * connections if we already have a debugger attached. If we don't, the 290 * debugger will just mysteriously hang until it times out. We could just 291 * close the listen socket, but there's a good chance we won't be able to 292 * bind to the same port again, which would confuse utilities. 293 * 294 * Returns "false" on error (indicating that the connection has been severed), 295 * "true" if things are still okay. 296 */ 297 bool JdwpAdbState::ProcessIncoming() { 298 int readCount; 299 300 CHECK_NE(clientSock, -1); 301 302 if (!HaveFullPacket()) { 303 /* read some more, looping until we have data */ 304 errno = 0; 305 while (1) { 306 int selCount; 307 fd_set readfds; 308 int maxfd = -1; 309 int fd; 310 311 FD_ZERO(&readfds); 312 313 /* configure fds; note these may get zapped by another thread */ 314 fd = control_sock_; 315 if (fd >= 0) { 316 FD_SET(fd, &readfds); 317 if (maxfd < fd) { 318 maxfd = fd; 319 } 320 } 321 fd = clientSock; 322 if (fd >= 0) { 323 FD_SET(fd, &readfds); 324 if (maxfd < fd) { 325 maxfd = fd; 326 } 327 } 328 fd = wake_pipe_[0]; 329 if (fd >= 0) { 330 FD_SET(fd, &readfds); 331 if (maxfd < fd) { 332 maxfd = fd; 333 } 334 } else { 335 LOG(INFO) << "NOTE: entering select w/o wakepipe"; 336 } 337 338 if (maxfd < 0) { 339 VLOG(jdwp) << "+++ all fds are closed"; 340 return false; 341 } 342 343 /* 344 * Select blocks until it sees activity on the file descriptors. 345 * Closing the local file descriptor does not count as activity, 346 * so we can't rely on that to wake us up (it works for read() 347 * and accept(), but not select()). 348 * 349 * We can do one of three things: (1) send a signal and catch 350 * EINTR, (2) open an additional fd ("wake pipe") and write to 351 * it when it's time to exit, or (3) time out periodically and 352 * re-issue the select. We're currently using #2, as it's more 353 * reliable than #1 and generally better than #3. Wastes two fds. 354 */ 355 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL); 356 if (selCount < 0) { 357 if (errno == EINTR) { 358 continue; 359 } 360 PLOG(ERROR) << "select failed"; 361 goto fail; 362 } 363 364 if (wake_pipe_[0] >= 0 && FD_ISSET(wake_pipe_[0], &readfds)) { 365 VLOG(jdwp) << "Got wake-up signal, bailing out of select"; 366 goto fail; 367 } 368 if (control_sock_ >= 0 && FD_ISSET(control_sock_, &readfds)) { 369 int sock = ReceiveClientFd(); 370 if (sock >= 0) { 371 LOG(INFO) << "Ignoring second debugger -- accepting and dropping"; 372 close(sock); 373 } else { 374 CHECK_EQ(control_sock_, -1); 375 /* 376 * Remote side most likely went away, so our next read 377 * on clientSock will fail and throw us out of the loop. 378 */ 379 } 380 } 381 if (clientSock >= 0 && FD_ISSET(clientSock, &readfds)) { 382 readCount = read(clientSock, input_buffer_ + input_count_, sizeof(input_buffer_) - input_count_); 383 if (readCount < 0) { 384 /* read failed */ 385 if (errno != EINTR) { 386 goto fail; 387 } 388 VLOG(jdwp) << "+++ EINTR hit"; 389 return true; 390 } else if (readCount == 0) { 391 /* EOF hit -- far end went away */ 392 VLOG(jdwp) << "+++ peer disconnected"; 393 goto fail; 394 } else { 395 break; 396 } 397 } 398 } 399 400 input_count_ += readCount; 401 if (!HaveFullPacket()) { 402 return true; /* still not there yet */ 403 } 404 } 405 406 /* 407 * Special-case the initial handshake. For some bizarre reason we're 408 * expected to emulate bad tty settings by echoing the request back 409 * exactly as it was sent. Note the handshake is always initiated by 410 * the debugger, no matter who connects to whom. 411 * 412 * Other than this one case, the protocol [claims to be] stateless. 413 */ 414 if (IsAwaitingHandshake()) { 415 if (memcmp(input_buffer_, kMagicHandshake, kMagicHandshakeLen) != 0) { 416 LOG(ERROR) << StringPrintf("ERROR: bad handshake '%.14s'", input_buffer_); 417 goto fail; 418 } 419 420 errno = 0; 421 int cc = TEMP_FAILURE_RETRY(write(clientSock, input_buffer_, kMagicHandshakeLen)); 422 if (cc != kMagicHandshakeLen) { 423 PLOG(ERROR) << "Failed writing handshake bytes (" << cc << " of " << kMagicHandshakeLen << ")"; 424 goto fail; 425 } 426 427 ConsumeBytes(kMagicHandshakeLen); 428 SetAwaitingHandshake(false); 429 VLOG(jdwp) << "+++ handshake complete"; 430 return true; 431 } 432 433 /* 434 * Handle this packet. 435 */ 436 return state_->HandlePacket(); 437 438 fail: 439 Close(); 440 return false; 441 } 442 443 } // namespace JDWP 444 445 } // namespace art 446