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