Alex Light | fbf9670 | 2017-12-14 13:27:13 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2017 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 <array> |
| 18 | |
| 19 | #include "adbconnection.h" |
| 20 | |
| 21 | #include "android-base/endian.h" |
| 22 | #include "android-base/stringprintf.h" |
| 23 | #include "base/logging.h" |
| 24 | #include "base/macros.h" |
| 25 | #include "base/mutex.h" |
| 26 | #include "java_vm_ext.h" |
| 27 | #include "jni_env_ext.h" |
| 28 | #include "mirror/throwable.h" |
| 29 | #include "nativehelper/ScopedLocalRef.h" |
| 30 | #include "runtime-inl.h" |
| 31 | #include "runtime_callbacks.h" |
| 32 | #include "scoped_thread_state_change-inl.h" |
| 33 | #include "well_known_classes.h" |
| 34 | |
| 35 | #include "jdwp/jdwp_priv.h" |
| 36 | |
| 37 | #include "fd_transport.h" |
| 38 | |
| 39 | #include "poll.h" |
| 40 | |
| 41 | #ifdef ART_TARGET_ANDROID |
| 42 | #include "cutils/sockets.h" |
| 43 | #endif |
| 44 | |
| 45 | #include <sys/socket.h> |
| 46 | #include <sys/un.h> |
| 47 | #include <sys/eventfd.h> |
| 48 | #include <jni.h> |
| 49 | |
| 50 | namespace adbconnection { |
| 51 | |
| 52 | using dt_fd_forward::kListenStartMessage; |
| 53 | using dt_fd_forward::kListenEndMessage; |
| 54 | using dt_fd_forward::kAcceptMessage; |
| 55 | using dt_fd_forward::kCloseMessage; |
| 56 | |
| 57 | using android::base::StringPrintf; |
| 58 | |
| 59 | static constexpr int kEventfdLocked = 0; |
| 60 | static constexpr int kEventfdUnlocked = 1; |
| 61 | static constexpr int kControlSockSendTimeout = 10; |
| 62 | |
| 63 | static AdbConnectionState* gState; |
| 64 | |
| 65 | static bool IsDebuggingPossible() { |
| 66 | // TODO We need to do this on IsJdwpAllowed not IsDebuggable in order to support userdebug |
| 67 | // workloads. For now we will only allow it when we are debuggable so that testing is easier. |
| 68 | return art::Runtime::Current()->IsJavaDebuggable() && art::Dbg::IsJdwpAllowed(); |
| 69 | } |
| 70 | |
| 71 | // Begin running the debugger. |
| 72 | void AdbConnectionDebuggerController::StartDebugger() { |
| 73 | if (IsDebuggingPossible()) { |
| 74 | connection_->StartDebuggerThreads(); |
| 75 | } else { |
| 76 | LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent."; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // The debugger should begin shutting down since the runtime is ending. We don't actually do |
| 81 | // anything here. The real shutdown has already happened as far as the agent is concerned. |
| 82 | void AdbConnectionDebuggerController::StopDebugger() { } |
| 83 | |
| 84 | bool AdbConnectionDebuggerController::IsDebuggerConfigured() { |
| 85 | return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty(); |
| 86 | } |
| 87 | |
| 88 | void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type, |
| 89 | const art::ArrayRef<const uint8_t>& data) { |
| 90 | connection_->PublishDdmData(type, data); |
| 91 | } |
| 92 | |
| 93 | class ScopedEventFdLock { |
| 94 | public: |
| 95 | explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) { |
| 96 | TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_))); |
| 97 | } |
| 98 | |
| 99 | ~ScopedEventFdLock() { |
| 100 | TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_))); |
| 101 | } |
| 102 | |
| 103 | private: |
| 104 | int fd_; |
| 105 | uint64_t data_; |
| 106 | }; |
| 107 | |
| 108 | AdbConnectionState::AdbConnectionState(const std::string& agent_name) |
| 109 | : agent_name_(agent_name), |
| 110 | controller_(this), |
| 111 | ddm_callback_(this), |
| 112 | sleep_event_fd_(-1), |
| 113 | control_sock_(-1), |
| 114 | local_agent_control_sock_(-1), |
| 115 | remote_agent_control_sock_(-1), |
| 116 | adb_connection_socket_(-1), |
| 117 | adb_write_event_fd_(-1), |
| 118 | shutting_down_(false), |
| 119 | agent_loaded_(false), |
| 120 | agent_listening_(false), |
| 121 | next_ddm_id_(1) { |
| 122 | // Setup the addr. |
| 123 | control_addr_.controlAddrUn.sun_family = AF_UNIX; |
| 124 | control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1; |
| 125 | memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1); |
| 126 | |
| 127 | // Add the startup callback. |
| 128 | art::ScopedObjectAccess soa(art::Thread::Current()); |
| 129 | art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_); |
| 130 | } |
| 131 | |
| 132 | static jobject CreateAdbConnectionThread(art::Thread* thr) { |
| 133 | JNIEnv* env = thr->GetJniEnv(); |
| 134 | // Move to native state to talk with the jnienv api. |
| 135 | art::ScopedThreadStateChange stsc(thr, art::kNative); |
| 136 | ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName)); |
| 137 | ScopedLocalRef<jobject> thr_group( |
| 138 | env, |
| 139 | env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup, |
| 140 | art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup)); |
| 141 | return env->NewObject(art::WellKnownClasses::java_lang_Thread, |
| 142 | art::WellKnownClasses::java_lang_Thread_init, |
| 143 | thr_group.get(), |
| 144 | thr_name.get(), |
| 145 | /*Priority*/ 0, |
| 146 | /*Daemon*/ true); |
| 147 | } |
| 148 | |
| 149 | struct CallbackData { |
| 150 | AdbConnectionState* this_; |
| 151 | jobject thr_; |
| 152 | }; |
| 153 | |
| 154 | static void* CallbackFunction(void* vdata) { |
| 155 | std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata)); |
| 156 | art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName, |
| 157 | true, |
| 158 | data->thr_); |
| 159 | CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached."; |
| 160 | // The name in Attach() is only for logging. Set the thread name. This is important so |
| 161 | // that the thread is no longer seen as starting up. |
| 162 | { |
| 163 | art::ScopedObjectAccess soa(self); |
| 164 | self->SetThreadName(kAdbConnectionThreadName); |
| 165 | } |
| 166 | |
| 167 | // Release the peer. |
| 168 | JNIEnv* env = self->GetJniEnv(); |
| 169 | env->DeleteGlobalRef(data->thr_); |
| 170 | data->thr_ = nullptr; |
| 171 | { |
| 172 | // The StartThreadBirth was called in the parent thread. We let the runtime know we are up |
| 173 | // before going into the provided code. |
| 174 | art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_); |
| 175 | art::Runtime::Current()->EndThreadBirth(); |
| 176 | } |
| 177 | data->this_->RunPollLoop(self); |
| 178 | int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread(); |
| 179 | CHECK_EQ(detach_result, 0); |
| 180 | |
| 181 | return nullptr; |
| 182 | } |
| 183 | |
| 184 | void AdbConnectionState::StartDebuggerThreads() { |
| 185 | // First do all the final setup we need. |
| 186 | CHECK_EQ(adb_write_event_fd_.get(), -1); |
| 187 | CHECK_EQ(sleep_event_fd_.get(), -1); |
| 188 | CHECK_EQ(local_agent_control_sock_.get(), -1); |
| 189 | CHECK_EQ(remote_agent_control_sock_.get(), -1); |
| 190 | |
| 191 | sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC)); |
| 192 | CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd."; |
| 193 | adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC)); |
| 194 | CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd."; |
| 195 | |
| 196 | { |
| 197 | art::ScopedObjectAccess soa(art::Thread::Current()); |
| 198 | art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_); |
| 199 | } |
| 200 | // Setup the socketpair we use to talk to the agent. |
| 201 | bool has_sockets; |
| 202 | do { |
| 203 | has_sockets = android::base::Socketpair(AF_UNIX, |
| 204 | SOCK_SEQPACKET | SOCK_CLOEXEC, |
| 205 | 0, |
| 206 | &local_agent_control_sock_, |
| 207 | &remote_agent_control_sock_); |
| 208 | } while (!has_sockets && errno == EINTR); |
| 209 | if (!has_sockets) { |
| 210 | PLOG(FATAL) << "Unable to create socketpair for agent control!"; |
| 211 | } |
| 212 | |
| 213 | // Next start the threads. |
| 214 | art::Thread* self = art::Thread::Current(); |
| 215 | art::ScopedObjectAccess soa(self); |
| 216 | { |
| 217 | art::Runtime* runtime = art::Runtime::Current(); |
| 218 | art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_); |
| 219 | if (runtime->IsShuttingDownLocked()) { |
| 220 | // The runtime is shutting down so we cannot create new threads. This shouldn't really happen. |
| 221 | LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!"; |
| 222 | return; |
| 223 | } |
| 224 | runtime->StartThreadBirth(); |
| 225 | } |
| 226 | ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self())); |
| 227 | pthread_t pthread; |
| 228 | std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) }); |
| 229 | int pthread_create_result = pthread_create(&pthread, |
| 230 | nullptr, |
| 231 | &CallbackFunction, |
| 232 | data.get()); |
| 233 | if (pthread_create_result != 0) { |
| 234 | // If the create succeeded the other thread will call EndThreadBirth. |
| 235 | art::Runtime* runtime = art::Runtime::Current(); |
| 236 | soa.Env()->DeleteGlobalRef(data->thr_); |
| 237 | LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!"; |
| 238 | art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_); |
| 239 | runtime->EndThreadBirth(); |
| 240 | return; |
| 241 | } |
| 242 | data.release(); |
| 243 | } |
| 244 | |
| 245 | static bool FlagsSet(int16_t data, int16_t flags) { |
| 246 | return (data & flags) == flags; |
| 247 | } |
| 248 | |
| 249 | void AdbConnectionState::CloseFds() { |
| 250 | // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is closed. |
| 251 | ScopedEventFdLock lk(adb_write_event_fd_); |
| 252 | // shutdown(adb_connection_socket_, SHUT_RDWR); |
| 253 | adb_connection_socket_.reset(); |
| 254 | } |
| 255 | |
| 256 | uint32_t AdbConnectionState::NextDdmId() { |
| 257 | // Just have a normal counter but always set the sign bit. |
| 258 | return (next_ddm_id_++) | 0x80000000; |
| 259 | } |
| 260 | |
| 261 | void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) { |
| 262 | // Get the write_event early to fail fast. |
| 263 | ScopedEventFdLock lk(adb_write_event_fd_); |
| 264 | if (adb_connection_socket_ == -1) { |
| 265 | LOG(WARNING) << "Not sending ddms data of type " |
| 266 | << StringPrintf("%c%c%c%c", |
| 267 | static_cast<char>(type >> 24), |
| 268 | static_cast<char>(type >> 16), |
| 269 | static_cast<char>(type >> 8), |
| 270 | static_cast<char>(type)) << " due to no connection!"; |
| 271 | // Adb is not connected. |
| 272 | return; |
| 273 | } |
| 274 | |
| 275 | // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until |
| 276 | // after we have sent our data. |
| 277 | static constexpr uint32_t kDdmPacketHeaderSize = |
| 278 | kJDWPHeaderLen // jdwp command packet size |
| 279 | + sizeof(uint32_t) // Type |
| 280 | + sizeof(uint32_t); // length |
| 281 | std::array<uint8_t, kDdmPacketHeaderSize> pkt; |
| 282 | uint8_t* pkt_data = pkt.data(); |
| 283 | |
| 284 | // Write the length first. |
| 285 | *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size()); |
| 286 | pkt_data += sizeof(uint32_t); |
| 287 | |
| 288 | // Write the id next; |
| 289 | *reinterpret_cast<uint32_t*>(pkt_data) = htonl(NextDdmId()); |
| 290 | pkt_data += sizeof(uint32_t); |
| 291 | |
| 292 | // next the flags. (0 for cmd packet because DDMS). |
| 293 | *(pkt_data++) = 0; |
| 294 | // Now the cmd-set |
| 295 | *(pkt_data++) = kJDWPDdmCmdSet; |
| 296 | // Now the command |
| 297 | *(pkt_data++) = kJDWPDdmCmd; |
| 298 | |
| 299 | // now the type. |
| 300 | *reinterpret_cast<uint32_t*>(pkt_data) = htonl(type); |
| 301 | pkt_data += sizeof(uint32_t); |
| 302 | |
| 303 | // Now the data.size() |
| 304 | *reinterpret_cast<uint32_t*>(pkt_data) = htonl(data.size()); |
| 305 | pkt_data += sizeof(uint32_t); |
| 306 | |
| 307 | static uint32_t constexpr kIovSize = 2; |
| 308 | struct iovec iovs[kIovSize] = { |
| 309 | { pkt.data(), pkt.size() }, |
| 310 | { const_cast<uint8_t*>(data.data()), data.size() }, |
| 311 | }; |
| 312 | // now pkt_header has the header. |
| 313 | // use writev to send the actual data. |
| 314 | ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize)); |
| 315 | if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) { |
| 316 | PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)", |
| 317 | static_cast<char>(type >> 24), |
| 318 | static_cast<char>(type >> 16), |
| 319 | static_cast<char>(type >> 8), |
| 320 | static_cast<char>(type), |
| 321 | res, data.size() + kDdmPacketHeaderSize); |
| 322 | } else { |
| 323 | VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu", |
| 324 | static_cast<char>(type >> 24), |
| 325 | static_cast<char>(type >> 16), |
| 326 | static_cast<char>(type >> 8), |
| 327 | static_cast<char>(type), |
| 328 | data.size() + kDdmPacketHeaderSize); |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | void AdbConnectionState::SendAgentFds() { |
| 333 | // TODO |
| 334 | DCHECK(!sent_agent_fds_); |
| 335 | char dummy = '!'; |
| 336 | union { |
| 337 | cmsghdr cm; |
| 338 | char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)]; |
| 339 | } cm_un; |
| 340 | iovec iov; |
| 341 | iov.iov_base = &dummy; |
| 342 | iov.iov_len = 1; |
| 343 | |
| 344 | msghdr msg; |
| 345 | msg.msg_name = nullptr; |
| 346 | msg.msg_namelen = 0; |
| 347 | msg.msg_iov = &iov; |
| 348 | msg.msg_iovlen = 1; |
| 349 | msg.msg_flags = 0; |
| 350 | msg.msg_control = cm_un.buffer; |
| 351 | msg.msg_controllen = sizeof(cm_un.buffer); |
| 352 | |
| 353 | cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); |
| 354 | cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength); |
| 355 | cmsg->cmsg_level = SOL_SOCKET; |
| 356 | cmsg->cmsg_type = SCM_RIGHTS; |
| 357 | |
| 358 | // Duplicate the fds before sending them. |
| 359 | android::base::unique_fd read_fd(dup(adb_connection_socket_)); |
| 360 | CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno); |
| 361 | android::base::unique_fd write_fd(dup(adb_connection_socket_)); |
| 362 | CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno); |
| 363 | android::base::unique_fd write_lock_fd(dup(adb_write_event_fd_)); |
| 364 | CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno); |
| 365 | |
| 366 | dt_fd_forward::FdSet { |
| 367 | read_fd.get(), write_fd.get(), write_lock_fd.get() |
| 368 | }.WriteData(CMSG_DATA(cmsg)); |
| 369 | |
| 370 | int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR)); |
| 371 | if (res < 0) { |
| 372 | PLOG(ERROR) << "Failed to send agent adb connection fds."; |
| 373 | } else { |
| 374 | sent_agent_fds_ = true; |
| 375 | VLOG(jdwp) << "Fds have been sent to jdwp agent!"; |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | android::base::unique_fd AdbConnectionState::ReadFdFromAdb() { |
| 380 | // We don't actually care about the data that is sent. We do need to receive something though. |
| 381 | char dummy = '!'; |
| 382 | union { |
| 383 | cmsghdr cm; |
| 384 | char buffer[CMSG_SPACE(sizeof(int))]; |
| 385 | } cm_un; |
| 386 | |
| 387 | iovec iov; |
| 388 | iov.iov_base = &dummy; |
| 389 | iov.iov_len = 1; |
| 390 | |
| 391 | msghdr msg; |
| 392 | msg.msg_name = nullptr; |
| 393 | msg.msg_namelen = 0; |
| 394 | msg.msg_iov = &iov; |
| 395 | msg.msg_iovlen = 1; |
| 396 | msg.msg_flags = 0; |
| 397 | msg.msg_control = cm_un.buffer; |
| 398 | msg.msg_controllen = sizeof(cm_un.buffer); |
| 399 | |
| 400 | cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); |
| 401 | cmsg->cmsg_len = msg.msg_controllen; |
| 402 | cmsg->cmsg_level = SOL_SOCKET; |
| 403 | cmsg->cmsg_type = SCM_RIGHTS; |
| 404 | (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1; |
| 405 | |
| 406 | int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0)); |
| 407 | |
| 408 | if (rc <= 0) { |
| 409 | PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")"; |
| 410 | return android::base::unique_fd(-1); |
| 411 | } else { |
| 412 | VLOG(jdwp) << "Fds have been received from ADB!"; |
| 413 | } |
| 414 | |
| 415 | return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]); |
| 416 | } |
| 417 | |
| 418 | bool AdbConnectionState::SetupAdbConnection() { |
| 419 | int sleep_ms = 500; |
| 420 | const int sleep_max_ms = 2*1000; |
| 421 | char buff[sizeof(pid_t) + 1]; |
| 422 | |
| 423 | android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET, 0)); |
| 424 | if (sock < 0) { |
| 425 | PLOG(ERROR) << "Could not create ADB control socket"; |
| 426 | return false; |
| 427 | } |
| 428 | struct timeval timeout; |
| 429 | timeout.tv_sec = kControlSockSendTimeout; |
| 430 | timeout.tv_usec = 0; |
| 431 | setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); |
| 432 | snprintf(buff, sizeof(buff), "%04x", getpid()); |
| 433 | buff[sizeof(pid_t)] = 0; |
| 434 | |
| 435 | while (!shutting_down_) { |
| 436 | // If adbd isn't running, because USB debugging was disabled or |
| 437 | // perhaps the system is restarting it for "adb root", the |
| 438 | // connect() will fail. We loop here forever waiting for it |
| 439 | // to come back. |
| 440 | // |
| 441 | // Waking up and polling every couple of seconds is generally a |
| 442 | // bad thing to do, but we only do this if the application is |
| 443 | // debuggable *and* adbd isn't running. Still, for the sake |
| 444 | // of battery life, we should consider timing out and giving |
| 445 | // up after a few minutes in case somebody ships an app with |
| 446 | // the debuggable flag set. |
| 447 | int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_); |
| 448 | if (ret == 0) { |
| 449 | bool trusted = sock >= 0; |
| 450 | #ifdef ART_TARGET_ANDROID |
| 451 | // Needed for socket_peer_is_trusted. |
| 452 | trusted = trusted && socket_peer_is_trusted(sock); |
| 453 | #endif |
| 454 | if (!trusted) { |
| 455 | LOG(ERROR) << "adb socket is not trusted. Aborting connection."; |
| 456 | if (sock >= 0 && shutdown(sock, SHUT_RDWR)) { |
| 457 | PLOG(ERROR) << "trouble shutting down socket"; |
| 458 | } |
| 459 | return false; |
| 460 | } |
| 461 | /* now try to send our pid to the ADB daemon */ |
| 462 | ret = TEMP_FAILURE_RETRY(send(sock, buff, sizeof(pid_t), 0)); |
| 463 | if (ret == sizeof(pid_t)) { |
| 464 | LOG(INFO) << "PID " << getpid() << " send to adb"; |
| 465 | control_sock_ = std::move(sock); |
| 466 | return true; |
| 467 | } else { |
| 468 | PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection."; |
| 469 | return false; |
| 470 | } |
| 471 | } else { |
| 472 | PLOG(ERROR) << "Can't connect to ADB control socket. Will retry."; |
| 473 | |
| 474 | usleep(sleep_ms * 1000); |
| 475 | |
| 476 | sleep_ms += (sleep_ms >> 1); |
| 477 | if (sleep_ms > sleep_max_ms) { |
| 478 | sleep_ms = sleep_max_ms; |
| 479 | } |
| 480 | } |
| 481 | } |
| 482 | return false; |
| 483 | } |
| 484 | |
| 485 | void AdbConnectionState::RunPollLoop(art::Thread* self) { |
| 486 | CHECK_EQ(self->GetState(), art::kNative); |
| 487 | art::Locks::mutator_lock_->AssertNotHeld(self); |
| 488 | self->SetState(art::kWaitingInMainDebuggerLoop); |
| 489 | // shutting_down_ set by StopDebuggerThreads |
| 490 | while (!shutting_down_) { |
| 491 | // First get the control_sock_ from adb if we don't have one. We only need to do this once. |
| 492 | if (control_sock_ == -1 && !SetupAdbConnection()) { |
| 493 | LOG(ERROR) << "Failed to setup adb connection."; |
| 494 | return; |
| 495 | } |
| 496 | while (!shutting_down_ && control_sock_ != -1) { |
| 497 | struct pollfd pollfds[4] = { |
| 498 | { sleep_event_fd_, POLLIN, 0 }, |
| 499 | // -1 as an fd causes it to be ignored by poll |
| 500 | { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 }, |
| 501 | // Check for the control_sock_ actually going away. Only do this if we don't have an active |
| 502 | // connection. |
| 503 | { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 }, |
| 504 | // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't |
| 505 | // have a real connection yet or the socket through adb needs to be listened to for incoming |
| 506 | // data that the agent can handle. |
| 507 | { ((!agent_has_socket_ && !sent_agent_fds_) ? adb_connection_socket_ : -1), POLLIN, 0 } |
| 508 | }; |
| 509 | int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1)); |
| 510 | if (res < 0) { |
| 511 | PLOG(ERROR) << "Failed to poll!"; |
| 512 | return; |
| 513 | } |
| 514 | // We don't actually care about doing this we just use it to wake us up. |
| 515 | // const struct pollfd& sleep_event_poll = pollfds[0]; |
| 516 | const struct pollfd& agent_control_sock_poll = pollfds[1]; |
| 517 | const struct pollfd& control_sock_poll = pollfds[2]; |
| 518 | const struct pollfd& adb_socket_poll = pollfds[3]; |
| 519 | if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) { |
| 520 | DCHECK(agent_loaded_); |
| 521 | char buf[257]; |
| 522 | res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0)); |
| 523 | if (res < 0) { |
| 524 | PLOG(ERROR) << "Failed to read message from agent control socket! Retrying"; |
| 525 | continue; |
| 526 | } else { |
| 527 | buf[res + 1] = '\0'; |
| 528 | VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf); |
| 529 | } |
| 530 | if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) { |
| 531 | agent_listening_ = true; |
| 532 | if (adb_connection_socket_ != -1) { |
| 533 | SendAgentFds(); |
| 534 | } |
| 535 | } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) { |
| 536 | agent_listening_ = false; |
| 537 | } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) { |
| 538 | CloseFds(); |
| 539 | agent_has_socket_ = false; |
| 540 | } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) { |
| 541 | agent_has_socket_ = true; |
| 542 | sent_agent_fds_ = false; |
| 543 | } else { |
| 544 | LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'"; |
| 545 | } |
| 546 | } else if (FlagsSet(control_sock_poll.revents, POLLIN)) { |
| 547 | bool maybe_send_fds = false; |
| 548 | { |
| 549 | // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd. |
| 550 | ScopedEventFdLock sefdl(adb_write_event_fd_); |
| 551 | android::base::unique_fd new_fd(ReadFdFromAdb()); |
| 552 | if (new_fd == -1) { |
| 553 | // Something went wrong. We need to retry getting the control socket. |
| 554 | PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!"; |
| 555 | control_sock_.reset(); |
| 556 | break; |
| 557 | } else if (adb_connection_socket_ != -1) { |
| 558 | // We already have a connection. |
| 559 | VLOG(jdwp) << "Ignoring second debugger. Accept then drop!"; |
| 560 | if (new_fd >= 0) { |
| 561 | new_fd.reset(); |
| 562 | } |
| 563 | } else { |
| 564 | VLOG(jdwp) << "Adb connection established with fd " << new_fd; |
| 565 | adb_connection_socket_ = std::move(new_fd); |
| 566 | maybe_send_fds = true; |
| 567 | } |
| 568 | } |
| 569 | if (maybe_send_fds && agent_loaded_ && agent_listening_) { |
| 570 | VLOG(jdwp) << "Sending fds as soon as we received them."; |
| 571 | SendAgentFds(); |
| 572 | } |
| 573 | } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) { |
| 574 | // The other end of the adb connection just dropped it. |
| 575 | // Reset the connection since we don't have an active socket through the adb server. |
| 576 | DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a " |
| 577 | << "connection active"; |
| 578 | control_sock_.reset(); |
| 579 | break; |
| 580 | } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) { |
| 581 | DCHECK(!agent_has_socket_); |
| 582 | if (!agent_loaded_) { |
| 583 | DCHECK(!agent_listening_); |
| 584 | // Load the agent now! |
| 585 | self->AssertNoPendingException(); |
Andreas Gampe | 7b38e69 | 2017-12-28 19:18:28 -0800 | [diff] [blame] | 586 | art::Runtime::Current()->AttachAgent(/* JNIEnv* */ nullptr, |
| 587 | MakeAgentArg(), |
| 588 | /* classloader */ nullptr); |
Alex Light | fbf9670 | 2017-12-14 13:27:13 -0800 | [diff] [blame] | 589 | if (self->IsExceptionPending()) { |
| 590 | LOG(ERROR) << "Failed to load agent " << agent_name_; |
| 591 | art::ScopedObjectAccess soa(self); |
| 592 | self->GetException()->Dump(); |
| 593 | self->ClearException(); |
| 594 | return; |
| 595 | } |
| 596 | agent_loaded_ = true; |
| 597 | } else if (agent_listening_ && !sent_agent_fds_) { |
| 598 | VLOG(jdwp) << "Sending agent fds again on data."; |
| 599 | SendAgentFds(); |
| 600 | } |
| 601 | } else { |
| 602 | VLOG(jdwp) << "Woke up poll without anything to do!"; |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | std::string AdbConnectionState::MakeAgentArg() { |
| 609 | // TODO Get this from something user settable? |
| 610 | const std::string& opts = art::Runtime::Current()->GetJdwpOptions(); |
| 611 | return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") |
| 612 | + "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_); |
| 613 | } |
| 614 | |
| 615 | void AdbConnectionState::StopDebuggerThreads() { |
| 616 | // The regular agent system will take care of unloading the agent (if needed). |
| 617 | shutting_down_ = true; |
| 618 | // Wakeup the poll loop. |
| 619 | uint64_t data = 1; |
| 620 | TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data))); |
| 621 | } |
| 622 | |
| 623 | // The plugin initialization function. |
| 624 | extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) { |
| 625 | DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection); |
| 626 | // TODO Provide some way for apps to set this maybe? |
| 627 | gState = new AdbConnectionState(kDefaultJdwpAgentName); |
| 628 | CHECK(gState != nullptr); |
| 629 | return true; |
| 630 | } |
| 631 | |
| 632 | extern "C" bool ArtPlugin_Deinitialize() { |
| 633 | CHECK(gState != nullptr); |
| 634 | // Just do this a second time? |
| 635 | // TODO I don't think this should be needed. |
| 636 | gState->StopDebuggerThreads(); |
| 637 | delete gState; |
| 638 | return true; |
| 639 | } |
| 640 | |
| 641 | } // namespace adbconnection |