Home | History | Annotate | Download | only in adbconnection
      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/file_utils.h"
     24 #include "base/logging.h"
     25 #include "base/macros.h"
     26 #include "base/mutex.h"
     27 #include "base/socket_peer_is_trusted.h"
     28 #include "jni/java_vm_ext.h"
     29 #include "jni/jni_env_ext.h"
     30 #include "mirror/throwable.h"
     31 #include "nativehelper/scoped_local_ref.h"
     32 #include "runtime-inl.h"
     33 #include "runtime_callbacks.h"
     34 #include "scoped_thread_state_change-inl.h"
     35 #include "well_known_classes.h"
     36 
     37 #include "jdwp/jdwp_priv.h"
     38 
     39 #include "fd_transport.h"
     40 
     41 #include "poll.h"
     42 
     43 #include <sys/ioctl.h>
     44 #include <sys/socket.h>
     45 #include <sys/un.h>
     46 #include <sys/eventfd.h>
     47 #include <jni.h>
     48 
     49 namespace adbconnection {
     50 
     51 // Messages sent from the transport
     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 // Messages sent to the transport
     58 using dt_fd_forward::kPerformHandshakeMessage;
     59 using dt_fd_forward::kSkipHandshakeMessage;
     60 
     61 using android::base::StringPrintf;
     62 
     63 static constexpr const char kJdwpHandshake[14] = {
     64   'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
     65 };
     66 
     67 static constexpr int kEventfdLocked = 0;
     68 static constexpr int kEventfdUnlocked = 1;
     69 static constexpr int kControlSockSendTimeout = 10;
     70 
     71 static constexpr size_t kPacketHeaderLen = 11;
     72 static constexpr off_t kPacketSizeOff = 0;
     73 static constexpr off_t kPacketIdOff = 4;
     74 static constexpr off_t kPacketCommandSetOff = 9;
     75 static constexpr off_t kPacketCommandOff = 10;
     76 
     77 static constexpr uint8_t kDdmCommandSet = 199;
     78 static constexpr uint8_t kDdmChunkCommand = 1;
     79 
     80 static AdbConnectionState* gState;
     81 
     82 static bool IsDebuggingPossible() {
     83   return art::Dbg::IsJdwpAllowed();
     84 }
     85 
     86 // Begin running the debugger.
     87 void AdbConnectionDebuggerController::StartDebugger() {
     88   if (IsDebuggingPossible()) {
     89     connection_->StartDebuggerThreads();
     90   } else {
     91     LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
     92   }
     93 }
     94 
     95 // The debugger should begin shutting down since the runtime is ending. We don't actually do
     96 // anything here. The real shutdown has already happened as far as the agent is concerned.
     97 void AdbConnectionDebuggerController::StopDebugger() { }
     98 
     99 bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
    100   return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
    101 }
    102 
    103 void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
    104                                                const art::ArrayRef<const uint8_t>& data) {
    105   connection_->PublishDdmData(type, data);
    106 }
    107 
    108 class ScopedEventFdLock {
    109  public:
    110   explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
    111     TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
    112   }
    113 
    114   ~ScopedEventFdLock() {
    115     TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
    116   }
    117 
    118  private:
    119   int fd_;
    120   uint64_t data_;
    121 };
    122 
    123 AdbConnectionState::AdbConnectionState(const std::string& agent_name)
    124   : agent_name_(agent_name),
    125     controller_(this),
    126     ddm_callback_(this),
    127     sleep_event_fd_(-1),
    128     control_sock_(-1),
    129     local_agent_control_sock_(-1),
    130     remote_agent_control_sock_(-1),
    131     adb_connection_socket_(-1),
    132     adb_write_event_fd_(-1),
    133     shutting_down_(false),
    134     agent_loaded_(false),
    135     agent_listening_(false),
    136     agent_has_socket_(false),
    137     sent_agent_fds_(false),
    138     performed_handshake_(false),
    139     notified_ddm_active_(false),
    140     next_ddm_id_(1),
    141     started_debugger_threads_(false) {
    142   // Setup the addr.
    143   control_addr_.controlAddrUn.sun_family = AF_UNIX;
    144   control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
    145   memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
    146 
    147   // Add the startup callback.
    148   art::ScopedObjectAccess soa(art::Thread::Current());
    149   art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
    150 }
    151 
    152 static jobject CreateAdbConnectionThread(art::Thread* thr) {
    153   JNIEnv* env = thr->GetJniEnv();
    154   // Move to native state to talk with the jnienv api.
    155   art::ScopedThreadStateChange stsc(thr, art::kNative);
    156   ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
    157   ScopedLocalRef<jobject> thr_group(
    158       env,
    159       env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
    160                                 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
    161   return env->NewObject(art::WellKnownClasses::java_lang_Thread,
    162                         art::WellKnownClasses::java_lang_Thread_init,
    163                         thr_group.get(),
    164                         thr_name.get(),
    165                         /*Priority=*/ 0,
    166                         /*Daemon=*/ true);
    167 }
    168 
    169 struct CallbackData {
    170   AdbConnectionState* this_;
    171   jobject thr_;
    172 };
    173 
    174 static void* CallbackFunction(void* vdata) {
    175   std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
    176   CHECK(data->this_ == gState);
    177   art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
    178                                           true,
    179                                           data->thr_);
    180   CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
    181   // The name in Attach() is only for logging. Set the thread name. This is important so
    182   // that the thread is no longer seen as starting up.
    183   {
    184     art::ScopedObjectAccess soa(self);
    185     self->SetThreadName(kAdbConnectionThreadName);
    186   }
    187 
    188   // Release the peer.
    189   JNIEnv* env = self->GetJniEnv();
    190   env->DeleteGlobalRef(data->thr_);
    191   data->thr_ = nullptr;
    192   {
    193     // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
    194     // before going into the provided code.
    195     art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
    196     art::Runtime::Current()->EndThreadBirth();
    197   }
    198   data->this_->RunPollLoop(self);
    199   int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
    200   CHECK_EQ(detach_result, 0);
    201 
    202   // Get rid of the connection
    203   gState = nullptr;
    204   delete data->this_;
    205 
    206   return nullptr;
    207 }
    208 
    209 void AdbConnectionState::StartDebuggerThreads() {
    210   // First do all the final setup we need.
    211   CHECK_EQ(adb_write_event_fd_.get(), -1);
    212   CHECK_EQ(sleep_event_fd_.get(), -1);
    213   CHECK_EQ(local_agent_control_sock_.get(), -1);
    214   CHECK_EQ(remote_agent_control_sock_.get(), -1);
    215 
    216   sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
    217   CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
    218   adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
    219   CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
    220 
    221   {
    222     art::ScopedObjectAccess soa(art::Thread::Current());
    223     art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
    224   }
    225   // Setup the socketpair we use to talk to the agent.
    226   bool has_sockets;
    227   do {
    228     has_sockets = android::base::Socketpair(AF_UNIX,
    229                                             SOCK_SEQPACKET | SOCK_CLOEXEC,
    230                                             0,
    231                                             &local_agent_control_sock_,
    232                                             &remote_agent_control_sock_);
    233   } while (!has_sockets && errno == EINTR);
    234   if (!has_sockets) {
    235     PLOG(FATAL) << "Unable to create socketpair for agent control!";
    236   }
    237 
    238   // Next start the threads.
    239   art::Thread* self = art::Thread::Current();
    240   art::ScopedObjectAccess soa(self);
    241   {
    242     art::Runtime* runtime = art::Runtime::Current();
    243     art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
    244     if (runtime->IsShuttingDownLocked()) {
    245       // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
    246       LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
    247       return;
    248     }
    249     runtime->StartThreadBirth();
    250   }
    251   ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
    252   // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
    253   //       created (exception support required).
    254   pthread_t pthread;
    255   std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
    256   started_debugger_threads_ = true;
    257   int pthread_create_result = pthread_create(&pthread,
    258                                              nullptr,
    259                                              &CallbackFunction,
    260                                              data.get());
    261   if (pthread_create_result != 0) {
    262     started_debugger_threads_ = false;
    263     // If the create succeeded the other thread will call EndThreadBirth.
    264     art::Runtime* runtime = art::Runtime::Current();
    265     soa.Env()->DeleteGlobalRef(data->thr_);
    266     LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
    267     art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
    268     runtime->EndThreadBirth();
    269     return;
    270   }
    271   data.release();  // NOLINT pthreads API.
    272 }
    273 
    274 static bool FlagsSet(int16_t data, int16_t flags) {
    275   return (data & flags) == flags;
    276 }
    277 
    278 void AdbConnectionState::CloseFds() {
    279   {
    280     // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
    281     // closed.
    282     ScopedEventFdLock lk(adb_write_event_fd_);
    283     // shutdown(adb_connection_socket_, SHUT_RDWR);
    284     adb_connection_socket_.reset();
    285   }
    286 
    287   // If we didn't load anything we will need to do the handshake again.
    288   performed_handshake_ = false;
    289 
    290   // If the agent isn't loaded we might need to tell ddms code the connection is closed.
    291   if (!agent_loaded_ && notified_ddm_active_) {
    292     NotifyDdms(/*active=*/false);
    293   }
    294 }
    295 
    296 void AdbConnectionState::NotifyDdms(bool active) {
    297   art::ScopedObjectAccess soa(art::Thread::Current());
    298   DCHECK_NE(notified_ddm_active_, active);
    299   notified_ddm_active_ = active;
    300   if (active) {
    301     art::Dbg::DdmConnected();
    302   } else {
    303     art::Dbg::DdmDisconnected();
    304   }
    305 }
    306 
    307 uint32_t AdbConnectionState::NextDdmId() {
    308   // Just have a normal counter but always set the sign bit.
    309   return (next_ddm_id_++) | 0x80000000;
    310 }
    311 
    312 void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
    313   SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
    314 }
    315 
    316 void AdbConnectionState::SendDdmPacket(uint32_t id,
    317                                        DdmPacketType packet_type,
    318                                        uint32_t type,
    319                                        art::ArrayRef<const uint8_t> data) {
    320   // Get the write_event early to fail fast.
    321   ScopedEventFdLock lk(adb_write_event_fd_);
    322   if (adb_connection_socket_ == -1) {
    323     VLOG(jdwp) << "Not sending ddms data of type "
    324                << StringPrintf("%c%c%c%c",
    325                                static_cast<char>(type >> 24),
    326                                static_cast<char>(type >> 16),
    327                                static_cast<char>(type >> 8),
    328                                static_cast<char>(type)) << " due to no connection!";
    329     // Adb is not connected.
    330     return;
    331   }
    332 
    333   // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
    334   // after we have sent our data.
    335   static constexpr uint32_t kDdmPacketHeaderSize =
    336       kJDWPHeaderLen       // jdwp command packet size
    337       + sizeof(uint32_t)   // Type
    338       + sizeof(uint32_t);  // length
    339   alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
    340   uint8_t* pkt_data = pkt.data();
    341 
    342   // Write the length first.
    343   *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
    344   pkt_data += sizeof(uint32_t);
    345 
    346   // Write the id next;
    347   *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
    348   pkt_data += sizeof(uint32_t);
    349 
    350   // next the flags. (0 for cmd packet because DDMS).
    351   *(pkt_data++) = static_cast<uint8_t>(packet_type);
    352   switch (packet_type) {
    353     case DdmPacketType::kCmd: {
    354       // Now the cmd-set
    355       *(pkt_data++) = kJDWPDdmCmdSet;
    356       // Now the command
    357       *(pkt_data++) = kJDWPDdmCmd;
    358       break;
    359     }
    360     case DdmPacketType::kReply: {
    361       // This is the error code bytes which are all 0
    362       *(pkt_data++) = 0;
    363       *(pkt_data++) = 0;
    364     }
    365   }
    366 
    367   // These are at unaligned addresses so we need to do them manually.
    368   // now the type.
    369   uint32_t net_type = htonl(type);
    370   memcpy(pkt_data, &net_type, sizeof(net_type));
    371   pkt_data += sizeof(uint32_t);
    372 
    373   // Now the data.size()
    374   uint32_t net_len = htonl(data.size());
    375   memcpy(pkt_data, &net_len, sizeof(net_len));
    376   pkt_data += sizeof(uint32_t);
    377 
    378   static uint32_t constexpr kIovSize = 2;
    379   struct iovec iovs[kIovSize] = {
    380     { pkt.data(), pkt.size() },
    381     { const_cast<uint8_t*>(data.data()), data.size() },
    382   };
    383   // now pkt_header has the header.
    384   // use writev to send the actual data.
    385   ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
    386   if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
    387     PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
    388                                 static_cast<char>(type >> 24),
    389                                 static_cast<char>(type >> 16),
    390                                 static_cast<char>(type >> 8),
    391                                 static_cast<char>(type),
    392                                 res, data.size() + kDdmPacketHeaderSize);
    393   } else {
    394     VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
    395                                static_cast<char>(type >> 24),
    396                                static_cast<char>(type >> 16),
    397                                static_cast<char>(type >> 8),
    398                                static_cast<char>(type),
    399                                data.size() + kDdmPacketHeaderSize);
    400   }
    401 }
    402 
    403 void AdbConnectionState::SendAgentFds(bool require_handshake) {
    404   DCHECK(!sent_agent_fds_);
    405   const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
    406   union {
    407     cmsghdr cm;
    408     char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
    409   } cm_un;
    410   iovec iov;
    411   iov.iov_base       = const_cast<char*>(message);
    412   iov.iov_len        = strlen(message) + 1;
    413 
    414   msghdr msg;
    415   msg.msg_name       = nullptr;
    416   msg.msg_namelen    = 0;
    417   msg.msg_iov        = &iov;
    418   msg.msg_iovlen     = 1;
    419   msg.msg_flags      = 0;
    420   msg.msg_control    = cm_un.buffer;
    421   msg.msg_controllen = sizeof(cm_un.buffer);
    422 
    423   cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
    424   cmsg->cmsg_len   = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
    425   cmsg->cmsg_level = SOL_SOCKET;
    426   cmsg->cmsg_type  = SCM_RIGHTS;
    427 
    428   // Duplicate the fds before sending them.
    429   android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
    430   CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
    431   android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
    432   CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
    433   android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
    434   CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
    435 
    436   dt_fd_forward::FdSet {
    437     read_fd.get(), write_fd.get(), write_lock_fd.get()
    438   }.WriteData(CMSG_DATA(cmsg));
    439 
    440   int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
    441   if (res < 0) {
    442     PLOG(ERROR) << "Failed to send agent adb connection fds.";
    443   } else {
    444     sent_agent_fds_ = true;
    445     VLOG(jdwp) << "Fds have been sent to jdwp agent!";
    446   }
    447 }
    448 
    449 android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
    450   // We don't actually care about the data that is sent. We do need to receive something though.
    451   char dummy = '!';
    452   union {
    453     cmsghdr cm;
    454     char buffer[CMSG_SPACE(sizeof(int))];
    455   } cm_un;
    456 
    457   iovec iov;
    458   iov.iov_base       = &dummy;
    459   iov.iov_len        = 1;
    460 
    461   msghdr msg;
    462   msg.msg_name       = nullptr;
    463   msg.msg_namelen    = 0;
    464   msg.msg_iov        = &iov;
    465   msg.msg_iovlen     = 1;
    466   msg.msg_flags      = 0;
    467   msg.msg_control    = cm_un.buffer;
    468   msg.msg_controllen = sizeof(cm_un.buffer);
    469 
    470   cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
    471   cmsg->cmsg_len   = msg.msg_controllen;
    472   cmsg->cmsg_level = SOL_SOCKET;
    473   cmsg->cmsg_type  = SCM_RIGHTS;
    474   (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
    475 
    476   int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0));
    477 
    478   if (rc <= 0) {
    479     return android::base::unique_fd(-1);
    480   } else {
    481     VLOG(jdwp) << "Fds have been received from ADB!";
    482   }
    483 
    484   return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
    485 }
    486 
    487 bool AdbConnectionState::SetupAdbConnection() {
    488   int        sleep_ms     = 500;
    489   const int  sleep_max_ms = 2*1000;
    490 
    491   android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
    492   if (sock < 0) {
    493     PLOG(ERROR) << "Could not create ADB control socket";
    494     return false;
    495   }
    496   struct timeval timeout;
    497   timeout.tv_sec = kControlSockSendTimeout;
    498   timeout.tv_usec = 0;
    499   setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
    500   int32_t pid = getpid();
    501 
    502   while (!shutting_down_) {
    503     // If adbd isn't running, because USB debugging was disabled or
    504     // perhaps the system is restarting it for "adb root", the
    505     // connect() will fail.  We loop here forever waiting for it
    506     // to come back.
    507     //
    508     // Waking up and polling every couple of seconds is generally a
    509     // bad thing to do, but we only do this if the application is
    510     // debuggable *and* adbd isn't running.  Still, for the sake
    511     // of battery life, we should consider timing out and giving
    512     // up after a few minutes in case somebody ships an app with
    513     // the debuggable flag set.
    514     int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
    515     if (ret == 0) {
    516       bool trusted = sock >= 0 && art::SocketPeerIsTrusted(sock);
    517       if (!trusted) {
    518         LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
    519         if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
    520           PLOG(ERROR) << "trouble shutting down socket";
    521         }
    522         return false;
    523       }
    524       /* now try to send our pid to the ADB daemon */
    525       ret = TEMP_FAILURE_RETRY(send(sock, &pid, sizeof(pid), 0));
    526       if (ret == sizeof(pid)) {
    527         VLOG(jdwp) << "PID " << pid << " sent to adb";
    528         control_sock_ = std::move(sock);
    529         return true;
    530       } else {
    531         PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
    532         return false;
    533       }
    534     } else {
    535       if (VLOG_IS_ON(jdwp)) {
    536         PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
    537       }
    538 
    539       usleep(sleep_ms * 1000);
    540 
    541       sleep_ms += (sleep_ms >> 1);
    542       if (sleep_ms > sleep_max_ms) {
    543         sleep_ms = sleep_max_ms;
    544       }
    545     }
    546   }
    547   return false;
    548 }
    549 
    550 void AdbConnectionState::RunPollLoop(art::Thread* self) {
    551   CHECK_NE(agent_name_, "");
    552   CHECK_EQ(self->GetState(), art::kNative);
    553   // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
    554   // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
    555   // http://b/71769596
    556   // art::Locks::mutator_lock_->AssertNotHeld(self);
    557   self->SetState(art::kWaitingInMainDebuggerLoop);
    558   // shutting_down_ set by StopDebuggerThreads
    559   while (!shutting_down_) {
    560     // First get the control_sock_ from adb if we don't have one. We only need to do this once.
    561     if (control_sock_ == -1 && !SetupAdbConnection()) {
    562       LOG(ERROR) << "Failed to setup adb connection.";
    563       return;
    564     }
    565     while (!shutting_down_ && control_sock_ != -1) {
    566       bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
    567       struct pollfd pollfds[4] = {
    568         { sleep_event_fd_, POLLIN, 0 },
    569         // -1 as an fd causes it to be ignored by poll
    570         { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
    571         // Check for the control_sock_ actually going away. Only do this if we don't have an active
    572         // connection.
    573         { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
    574         // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
    575         // have a real connection yet or the socket through adb needs to be listened to for incoming
    576         // data that the agent or this plugin can handle.
    577         { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
    578       };
    579       int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
    580       if (res < 0) {
    581         PLOG(ERROR) << "Failed to poll!";
    582         return;
    583       }
    584       // We don't actually care about doing this we just use it to wake us up.
    585       // const struct pollfd& sleep_event_poll     = pollfds[0];
    586       const struct pollfd& agent_control_sock_poll = pollfds[1];
    587       const struct pollfd& control_sock_poll       = pollfds[2];
    588       const struct pollfd& adb_socket_poll         = pollfds[3];
    589       if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
    590         DCHECK(agent_loaded_);
    591         char buf[257];
    592         res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
    593         if (res < 0) {
    594           PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
    595           continue;
    596         } else {
    597           buf[res + 1] = '\0';
    598           VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
    599         }
    600         if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
    601           agent_listening_ = true;
    602           if (adb_connection_socket_ != -1) {
    603             SendAgentFds(/*require_handshake=*/ !performed_handshake_);
    604           }
    605         } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
    606           agent_listening_ = false;
    607         } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
    608           CloseFds();
    609           agent_has_socket_ = false;
    610         } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
    611           agent_has_socket_ = true;
    612           sent_agent_fds_ = false;
    613           // We will only ever do the handshake once so reset this.
    614           performed_handshake_ = false;
    615         } else {
    616           LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
    617         }
    618       } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
    619         bool maybe_send_fds = false;
    620         {
    621           // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
    622           ScopedEventFdLock sefdl(adb_write_event_fd_);
    623           android::base::unique_fd new_fd(ReadFdFromAdb());
    624           if (new_fd == -1) {
    625             // Something went wrong. We need to retry getting the control socket.
    626             control_sock_.reset();
    627             break;
    628           } else if (adb_connection_socket_ != -1) {
    629             // We already have a connection.
    630             VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
    631             if (new_fd >= 0) {
    632               new_fd.reset();
    633             }
    634           } else {
    635             VLOG(jdwp) << "Adb connection established with fd " << new_fd;
    636             adb_connection_socket_ = std::move(new_fd);
    637             maybe_send_fds = true;
    638           }
    639         }
    640         if (maybe_send_fds && agent_loaded_ && agent_listening_) {
    641           VLOG(jdwp) << "Sending fds as soon as we received them.";
    642           // The agent was already loaded so this must be after a disconnection. Therefore have the
    643           // transport perform the handshake.
    644           SendAgentFds(/*require_handshake=*/ true);
    645         }
    646       } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
    647         // The other end of the adb connection just dropped it.
    648         // Reset the connection since we don't have an active socket through the adb server.
    649         DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
    650                                    << "connection active";
    651         control_sock_.reset();
    652         break;
    653       } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
    654         DCHECK(!agent_has_socket_);
    655         if (!agent_loaded_) {
    656           HandleDataWithoutAgent(self);
    657         } else if (agent_listening_ && !sent_agent_fds_) {
    658           VLOG(jdwp) << "Sending agent fds again on data.";
    659           // Agent was already loaded so it can deal with the handshake.
    660           SendAgentFds(/*require_handshake=*/ true);
    661         }
    662       } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
    663         DCHECK(!agent_has_socket_);
    664         CloseFds();
    665       } else {
    666         VLOG(jdwp) << "Woke up poll without anything to do!";
    667       }
    668     }
    669   }
    670 }
    671 
    672 static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
    673   uint32_t res;
    674   memcpy(&res, *in, sizeof(uint32_t));
    675   *in = (*in) + sizeof(uint32_t);
    676   return ntohl(res);
    677 }
    678 
    679 void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
    680   DCHECK(!agent_loaded_);
    681   DCHECK(!agent_listening_);
    682   // TODO Should we check in some other way if we are userdebug/eng?
    683   CHECK(art::Dbg::IsJdwpAllowed());
    684   // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
    685   if (!performed_handshake_) {
    686     PerformHandshake();
    687     return;
    688   }
    689   // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
    690   // to see if it's one we can handle. This doesn't change the state of the socket.
    691   alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
    692   ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
    693                                         packet_header,
    694                                         sizeof(packet_header),
    695                                         MSG_PEEK));
    696   // We want to be very careful not to change the socket state until we know we succeeded. This will
    697   // let us fall-back to just loading the agent and letting it deal with everything.
    698   if (res <= 0) {
    699     // Close the socket. We either hit EOF or an error.
    700     if (res < 0) {
    701       PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
    702     }
    703     CloseFds();
    704     return;
    705   } else if (res < static_cast<int>(kPacketHeaderLen)) {
    706     LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
    707     AttachJdwpAgent(self);
    708     return;
    709   }
    710   uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
    711   uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
    712   uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
    713   uint8_t pkt_cmd = packet_header[kPacketCommandOff];
    714   if (pkt_cmd_set != kDdmCommandSet ||
    715       pkt_cmd != kDdmChunkCommand ||
    716       full_len < kPacketHeaderLen) {
    717     VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
    718     AttachJdwpAgent(self);
    719     return;
    720   }
    721   uint32_t avail = -1;
    722   res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
    723   if (res < 0) {
    724     PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
    725     CloseFds();
    726     return;
    727   } else if (avail < full_len) {
    728     LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
    729                  << "Expected " << full_len << " bytes but only " << avail << " are readable. "
    730                  << "Loading jdwp agent to deal with this.";
    731     AttachJdwpAgent(self);
    732     return;
    733   }
    734   // Actually read the data.
    735   std::vector<uint8_t> full_pkt;
    736   full_pkt.resize(full_len);
    737   res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
    738   if (res < 0) {
    739     PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
    740     CloseFds();
    741     return;
    742   }
    743   DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
    744   size_t data_size = full_len - kPacketHeaderLen;
    745   if (data_size < (sizeof(uint32_t) * 2)) {
    746     // This is an error (the data isn't long enough) but to match historical behavior we need to
    747     // ignore it.
    748     return;
    749   }
    750   uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
    751   uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
    752   uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
    753   if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
    754     // This is an error (the data isn't long enough) but to match historical behavior we need to
    755     // ignore it.
    756     return;
    757   }
    758 
    759   if (!notified_ddm_active_) {
    760     NotifyDdms(/*active=*/ true);
    761   }
    762   uint32_t reply_type;
    763   std::vector<uint8_t> reply;
    764   if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
    765                                 ddm_type,
    766                                 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
    767                                                            ddm_len),
    768                                 /*out*/&reply_type,
    769                                 /*out*/&reply)) {
    770     // To match historical behavior we don't send any response when there is no data to reply with.
    771     return;
    772   }
    773   SendDdmPacket(pkt_id,
    774                 DdmPacketType::kReply,
    775                 reply_type,
    776                 art::ArrayRef<const uint8_t>(reply));
    777 }
    778 
    779 void AdbConnectionState::PerformHandshake() {
    780   CHECK(!performed_handshake_);
    781   // Check to make sure we are able to read the whole handshake.
    782   uint32_t avail = -1;
    783   int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
    784   if (res < 0 || avail < sizeof(kJdwpHandshake)) {
    785     if (res < 0) {
    786       PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
    787     }
    788     LOG(WARNING) << "Closing connection to broken client.";
    789     CloseFds();
    790     return;
    791   }
    792   // Perform the handshake.
    793   char handshake_msg[sizeof(kJdwpHandshake)];
    794   res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
    795                                 handshake_msg,
    796                                 sizeof(handshake_msg),
    797                                 MSG_DONTWAIT));
    798   if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
    799       strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
    800     if (res < 0) {
    801       PLOG(ERROR) << "Failed to read handshake!";
    802     }
    803     LOG(WARNING) << "Handshake failed!";
    804     CloseFds();
    805     return;
    806   }
    807   // Send the handshake back.
    808   res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
    809                                 kJdwpHandshake,
    810                                 sizeof(kJdwpHandshake),
    811                                 0));
    812   if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
    813     PLOG(ERROR) << "Failed to send jdwp-handshake response.";
    814     CloseFds();
    815     return;
    816   }
    817   performed_handshake_ = true;
    818 }
    819 
    820 void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
    821   art::Runtime* runtime = art::Runtime::Current();
    822   self->AssertNoPendingException();
    823   runtime->AttachAgent(/* env= */ nullptr,
    824                        MakeAgentArg(),
    825                        /* class_loader= */ nullptr);
    826   if (self->IsExceptionPending()) {
    827     LOG(ERROR) << "Failed to load agent " << agent_name_;
    828     art::ScopedObjectAccess soa(self);
    829     self->GetException()->Dump();
    830     self->ClearException();
    831     return;
    832   }
    833   agent_loaded_ = true;
    834 }
    835 
    836 bool ContainsArgument(const std::string& opts, const char* arg) {
    837   return opts.find(arg) != std::string::npos;
    838 }
    839 
    840 bool ValidateJdwpOptions(const std::string& opts) {
    841   bool res = true;
    842   // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
    843   // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
    844   // for the fd's to be passed down.
    845   if (ContainsArgument(opts, "server=n")) {
    846     res = false;
    847     LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
    848   }
    849   // We don't start the jdwp agent until threads are already running. It is far too late to suspend
    850   // everything.
    851   if (ContainsArgument(opts, "suspend=y")) {
    852     res = false;
    853     LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
    854   }
    855   return res;
    856 }
    857 
    858 std::string AdbConnectionState::MakeAgentArg() {
    859   const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
    860   DCHECK(ValidateJdwpOptions(opts));
    861   // TODO Get agent_name_ from something user settable?
    862   return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
    863       "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
    864       // See the comment above for why we need to be server=y. Since the agent defaults to server=n
    865       // we will add it if it wasn't already present for the convenience of the user.
    866       (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
    867       // See the comment above for why we need to be suspend=n. Since the agent defaults to
    868       // suspend=y we will add it if it wasn't already present.
    869       (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
    870       "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
    871 }
    872 
    873 void AdbConnectionState::StopDebuggerThreads() {
    874   // The regular agent system will take care of unloading the agent (if needed).
    875   shutting_down_ = true;
    876   // Wakeup the poll loop.
    877   uint64_t data = 1;
    878   if (sleep_event_fd_ != -1) {
    879     TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
    880   }
    881 }
    882 
    883 // The plugin initialization function.
    884 extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
    885   DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
    886   // TODO Provide some way for apps to set this maybe?
    887   DCHECK(gState == nullptr);
    888   gState = new AdbConnectionState(kDefaultJdwpAgentName);
    889   return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
    890 }
    891 
    892 extern "C" bool ArtPlugin_Deinitialize() {
    893   gState->StopDebuggerThreads();
    894   if (!gState->DebuggerThreadsStarted()) {
    895     // If debugger threads were started then those threads will delete the state once they are done.
    896     delete gState;
    897   }
    898   return true;
    899 }
    900 
    901 }  // namespace adbconnection
    902