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/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/ioctl.h>
     46 #include <sys/socket.h>
     47 #include <sys/un.h>
     48 #include <sys/eventfd.h>
     49 #include <jni.h>
     50 
     51 namespace adbconnection {
     52 
     53 // Messages sent from the transport
     54 using dt_fd_forward::kListenStartMessage;
     55 using dt_fd_forward::kListenEndMessage;
     56 using dt_fd_forward::kAcceptMessage;
     57 using dt_fd_forward::kCloseMessage;
     58 
     59 // Messages sent to the transport
     60 using dt_fd_forward::kPerformHandshakeMessage;
     61 using dt_fd_forward::kSkipHandshakeMessage;
     62 
     63 using android::base::StringPrintf;
     64 
     65 static constexpr const char kJdwpHandshake[14] = {
     66   'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
     67 };
     68 
     69 static constexpr int kEventfdLocked = 0;
     70 static constexpr int kEventfdUnlocked = 1;
     71 static constexpr int kControlSockSendTimeout = 10;
     72 
     73 static constexpr size_t kPacketHeaderLen = 11;
     74 static constexpr off_t kPacketSizeOff = 0;
     75 static constexpr off_t kPacketIdOff = 4;
     76 static constexpr off_t kPacketCommandSetOff = 9;
     77 static constexpr off_t kPacketCommandOff = 10;
     78 
     79 static constexpr uint8_t kDdmCommandSet = 199;
     80 static constexpr uint8_t kDdmChunkCommand = 1;
     81 
     82 static AdbConnectionState* gState;
     83 
     84 static bool IsDebuggingPossible() {
     85   return art::Dbg::IsJdwpAllowed();
     86 }
     87 
     88 // Begin running the debugger.
     89 void AdbConnectionDebuggerController::StartDebugger() {
     90   if (IsDebuggingPossible()) {
     91     connection_->StartDebuggerThreads();
     92   } else {
     93     LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
     94   }
     95 }
     96 
     97 // The debugger should begin shutting down since the runtime is ending. We don't actually do
     98 // anything here. The real shutdown has already happened as far as the agent is concerned.
     99 void AdbConnectionDebuggerController::StopDebugger() { }
    100 
    101 bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
    102   return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
    103 }
    104 
    105 void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
    106                                                const art::ArrayRef<const uint8_t>& data) {
    107   connection_->PublishDdmData(type, data);
    108 }
    109 
    110 class ScopedEventFdLock {
    111  public:
    112   explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
    113     TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
    114   }
    115 
    116   ~ScopedEventFdLock() {
    117     TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
    118   }
    119 
    120  private:
    121   int fd_;
    122   uint64_t data_;
    123 };
    124 
    125 AdbConnectionState::AdbConnectionState(const std::string& agent_name)
    126   : agent_name_(agent_name),
    127     controller_(this),
    128     ddm_callback_(this),
    129     sleep_event_fd_(-1),
    130     control_sock_(-1),
    131     local_agent_control_sock_(-1),
    132     remote_agent_control_sock_(-1),
    133     adb_connection_socket_(-1),
    134     adb_write_event_fd_(-1),
    135     shutting_down_(false),
    136     agent_loaded_(false),
    137     agent_listening_(false),
    138     agent_has_socket_(false),
    139     sent_agent_fds_(false),
    140     performed_handshake_(false),
    141     notified_ddm_active_(false),
    142     next_ddm_id_(1),
    143     started_debugger_threads_(false) {
    144   // Setup the addr.
    145   control_addr_.controlAddrUn.sun_family = AF_UNIX;
    146   control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
    147   memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
    148 
    149   // Add the startup callback.
    150   art::ScopedObjectAccess soa(art::Thread::Current());
    151   art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
    152 }
    153 
    154 static jobject CreateAdbConnectionThread(art::Thread* thr) {
    155   JNIEnv* env = thr->GetJniEnv();
    156   // Move to native state to talk with the jnienv api.
    157   art::ScopedThreadStateChange stsc(thr, art::kNative);
    158   ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
    159   ScopedLocalRef<jobject> thr_group(
    160       env,
    161       env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
    162                                 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
    163   return env->NewObject(art::WellKnownClasses::java_lang_Thread,
    164                         art::WellKnownClasses::java_lang_Thread_init,
    165                         thr_group.get(),
    166                         thr_name.get(),
    167                         /*Priority*/ 0,
    168                         /*Daemon*/ true);
    169 }
    170 
    171 struct CallbackData {
    172   AdbConnectionState* this_;
    173   jobject thr_;
    174 };
    175 
    176 static void* CallbackFunction(void* vdata) {
    177   std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
    178   CHECK(data->this_ == gState);
    179   art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
    180                                           true,
    181                                           data->thr_);
    182   CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
    183   // The name in Attach() is only for logging. Set the thread name. This is important so
    184   // that the thread is no longer seen as starting up.
    185   {
    186     art::ScopedObjectAccess soa(self);
    187     self->SetThreadName(kAdbConnectionThreadName);
    188   }
    189 
    190   // Release the peer.
    191   JNIEnv* env = self->GetJniEnv();
    192   env->DeleteGlobalRef(data->thr_);
    193   data->thr_ = nullptr;
    194   {
    195     // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
    196     // before going into the provided code.
    197     art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
    198     art::Runtime::Current()->EndThreadBirth();
    199   }
    200   data->this_->RunPollLoop(self);
    201   int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
    202   CHECK_EQ(detach_result, 0);
    203 
    204   // Get rid of the connection
    205   gState = nullptr;
    206   delete data->this_;
    207 
    208   return nullptr;
    209 }
    210 
    211 void AdbConnectionState::StartDebuggerThreads() {
    212   // First do all the final setup we need.
    213   CHECK_EQ(adb_write_event_fd_.get(), -1);
    214   CHECK_EQ(sleep_event_fd_.get(), -1);
    215   CHECK_EQ(local_agent_control_sock_.get(), -1);
    216   CHECK_EQ(remote_agent_control_sock_.get(), -1);
    217 
    218   sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
    219   CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
    220   adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
    221   CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
    222 
    223   {
    224     art::ScopedObjectAccess soa(art::Thread::Current());
    225     art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
    226   }
    227   // Setup the socketpair we use to talk to the agent.
    228   bool has_sockets;
    229   do {
    230     has_sockets = android::base::Socketpair(AF_UNIX,
    231                                             SOCK_SEQPACKET | SOCK_CLOEXEC,
    232                                             0,
    233                                             &local_agent_control_sock_,
    234                                             &remote_agent_control_sock_);
    235   } while (!has_sockets && errno == EINTR);
    236   if (!has_sockets) {
    237     PLOG(FATAL) << "Unable to create socketpair for agent control!";
    238   }
    239 
    240   // Next start the threads.
    241   art::Thread* self = art::Thread::Current();
    242   art::ScopedObjectAccess soa(self);
    243   {
    244     art::Runtime* runtime = art::Runtime::Current();
    245     art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
    246     if (runtime->IsShuttingDownLocked()) {
    247       // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
    248       LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
    249       return;
    250     }
    251     runtime->StartThreadBirth();
    252   }
    253   ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
    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();
    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(dup(adb_connection_socket_));
    430   CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
    431   android::base::unique_fd write_fd(dup(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(dup(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     PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")";
    480     return android::base::unique_fd(-1);
    481   } else {
    482     VLOG(jdwp) << "Fds have been received from ADB!";
    483   }
    484 
    485   return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
    486 }
    487 
    488 bool AdbConnectionState::SetupAdbConnection() {
    489   int        sleep_ms     = 500;
    490   const int  sleep_max_ms = 2*1000;
    491 
    492   android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET, 0));
    493   if (sock < 0) {
    494     PLOG(ERROR) << "Could not create ADB control socket";
    495     return false;
    496   }
    497   struct timeval timeout;
    498   timeout.tv_sec = kControlSockSendTimeout;
    499   timeout.tv_usec = 0;
    500   setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
    501   int32_t pid = getpid();
    502 
    503   while (!shutting_down_) {
    504     // If adbd isn't running, because USB debugging was disabled or
    505     // perhaps the system is restarting it for "adb root", the
    506     // connect() will fail.  We loop here forever waiting for it
    507     // to come back.
    508     //
    509     // Waking up and polling every couple of seconds is generally a
    510     // bad thing to do, but we only do this if the application is
    511     // debuggable *and* adbd isn't running.  Still, for the sake
    512     // of battery life, we should consider timing out and giving
    513     // up after a few minutes in case somebody ships an app with
    514     // the debuggable flag set.
    515     int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
    516     if (ret == 0) {
    517       bool trusted = sock >= 0;
    518 #ifdef ART_TARGET_ANDROID
    519       // Needed for socket_peer_is_trusted.
    520       trusted = trusted && socket_peer_is_trusted(sock);
    521 #endif
    522       if (!trusted) {
    523         LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
    524         if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
    525           PLOG(ERROR) << "trouble shutting down socket";
    526         }
    527         return false;
    528       }
    529       /* now try to send our pid to the ADB daemon */
    530       ret = TEMP_FAILURE_RETRY(send(sock, &pid, sizeof(pid), 0));
    531       if (ret == sizeof(pid)) {
    532         VLOG(jdwp) << "PID " << pid << " sent to adb";
    533         control_sock_ = std::move(sock);
    534         return true;
    535       } else {
    536         PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
    537         return false;
    538       }
    539     } else {
    540       if (VLOG_IS_ON(jdwp)) {
    541         PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
    542       }
    543 
    544       usleep(sleep_ms * 1000);
    545 
    546       sleep_ms += (sleep_ms >> 1);
    547       if (sleep_ms > sleep_max_ms) {
    548         sleep_ms = sleep_max_ms;
    549       }
    550     }
    551   }
    552   return false;
    553 }
    554 
    555 void AdbConnectionState::RunPollLoop(art::Thread* self) {
    556   CHECK_NE(agent_name_, "");
    557   CHECK_EQ(self->GetState(), art::kNative);
    558   // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
    559   // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
    560   // http://b/71769596
    561   // art::Locks::mutator_lock_->AssertNotHeld(self);
    562   self->SetState(art::kWaitingInMainDebuggerLoop);
    563   // shutting_down_ set by StopDebuggerThreads
    564   while (!shutting_down_) {
    565     // First get the control_sock_ from adb if we don't have one. We only need to do this once.
    566     if (control_sock_ == -1 && !SetupAdbConnection()) {
    567       LOG(ERROR) << "Failed to setup adb connection.";
    568       return;
    569     }
    570     while (!shutting_down_ && control_sock_ != -1) {
    571       bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
    572       struct pollfd pollfds[4] = {
    573         { sleep_event_fd_, POLLIN, 0 },
    574         // -1 as an fd causes it to be ignored by poll
    575         { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
    576         // Check for the control_sock_ actually going away. Only do this if we don't have an active
    577         // connection.
    578         { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
    579         // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
    580         // have a real connection yet or the socket through adb needs to be listened to for incoming
    581         // data that the agent or this plugin can handle.
    582         { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
    583       };
    584       int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
    585       if (res < 0) {
    586         PLOG(ERROR) << "Failed to poll!";
    587         return;
    588       }
    589       // We don't actually care about doing this we just use it to wake us up.
    590       // const struct pollfd& sleep_event_poll     = pollfds[0];
    591       const struct pollfd& agent_control_sock_poll = pollfds[1];
    592       const struct pollfd& control_sock_poll       = pollfds[2];
    593       const struct pollfd& adb_socket_poll         = pollfds[3];
    594       if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
    595         DCHECK(agent_loaded_);
    596         char buf[257];
    597         res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
    598         if (res < 0) {
    599           PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
    600           continue;
    601         } else {
    602           buf[res + 1] = '\0';
    603           VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
    604         }
    605         if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
    606           agent_listening_ = true;
    607           if (adb_connection_socket_ != -1) {
    608             SendAgentFds(/*require_handshake*/ !performed_handshake_);
    609           }
    610         } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
    611           agent_listening_ = false;
    612         } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
    613           CloseFds();
    614           agent_has_socket_ = false;
    615         } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
    616           agent_has_socket_ = true;
    617           sent_agent_fds_ = false;
    618           // We will only ever do the handshake once so reset this.
    619           performed_handshake_ = false;
    620         } else {
    621           LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
    622         }
    623       } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
    624         bool maybe_send_fds = false;
    625         {
    626           // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
    627           ScopedEventFdLock sefdl(adb_write_event_fd_);
    628           android::base::unique_fd new_fd(ReadFdFromAdb());
    629           if (new_fd == -1) {
    630             // Something went wrong. We need to retry getting the control socket.
    631             PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!";
    632             control_sock_.reset();
    633             break;
    634           } else if (adb_connection_socket_ != -1) {
    635             // We already have a connection.
    636             VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
    637             if (new_fd >= 0) {
    638               new_fd.reset();
    639             }
    640           } else {
    641             VLOG(jdwp) << "Adb connection established with fd " << new_fd;
    642             adb_connection_socket_ = std::move(new_fd);
    643             maybe_send_fds = true;
    644           }
    645         }
    646         if (maybe_send_fds && agent_loaded_ && agent_listening_) {
    647           VLOG(jdwp) << "Sending fds as soon as we received them.";
    648           // The agent was already loaded so this must be after a disconnection. Therefore have the
    649           // transport perform the handshake.
    650           SendAgentFds(/*require_handshake*/ true);
    651         }
    652       } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
    653         // The other end of the adb connection just dropped it.
    654         // Reset the connection since we don't have an active socket through the adb server.
    655         DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
    656                                    << "connection active";
    657         control_sock_.reset();
    658         break;
    659       } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
    660         DCHECK(!agent_has_socket_);
    661         if (!agent_loaded_) {
    662           HandleDataWithoutAgent(self);
    663         } else if (agent_listening_ && !sent_agent_fds_) {
    664           VLOG(jdwp) << "Sending agent fds again on data.";
    665           // Agent was already loaded so it can deal with the handshake.
    666           SendAgentFds(/*require_handshake*/ true);
    667         }
    668       } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
    669         DCHECK(!agent_has_socket_);
    670         CloseFds();
    671       } else {
    672         VLOG(jdwp) << "Woke up poll without anything to do!";
    673       }
    674     }
    675   }
    676 }
    677 
    678 static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
    679   uint32_t res;
    680   memcpy(&res, *in, sizeof(uint32_t));
    681   *in = (*in) + sizeof(uint32_t);
    682   return ntohl(res);
    683 }
    684 
    685 void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
    686   DCHECK(!agent_loaded_);
    687   DCHECK(!agent_listening_);
    688   // TODO Should we check in some other way if we are userdebug/eng?
    689   CHECK(art::Dbg::IsJdwpAllowed());
    690   // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
    691   if (!performed_handshake_) {
    692     PerformHandshake();
    693     return;
    694   }
    695   // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
    696   // to see if it's one we can handle. This doesn't change the state of the socket.
    697   alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
    698   ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
    699                                         packet_header,
    700                                         sizeof(packet_header),
    701                                         MSG_PEEK));
    702   // We want to be very careful not to change the socket state until we know we succeeded. This will
    703   // let us fall-back to just loading the agent and letting it deal with everything.
    704   if (res <= 0) {
    705     // Close the socket. We either hit EOF or an error.
    706     if (res < 0) {
    707       PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
    708     }
    709     CloseFds();
    710     return;
    711   } else if (res < static_cast<int>(kPacketHeaderLen)) {
    712     LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
    713     AttachJdwpAgent(self);
    714     return;
    715   }
    716   uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
    717   uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
    718   uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
    719   uint8_t pkt_cmd = packet_header[kPacketCommandOff];
    720   if (pkt_cmd_set != kDdmCommandSet ||
    721       pkt_cmd != kDdmChunkCommand ||
    722       full_len < kPacketHeaderLen) {
    723     VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
    724     AttachJdwpAgent(self);
    725     return;
    726   }
    727   uint32_t avail = -1;
    728   res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
    729   if (res < 0) {
    730     PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
    731     CloseFds();
    732     return;
    733   } else if (avail < full_len) {
    734     LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
    735                  << "Expected " << full_len << " bytes but only " << avail << " are readable. "
    736                  << "Loading jdwp agent to deal with this.";
    737     AttachJdwpAgent(self);
    738     return;
    739   }
    740   // Actually read the data.
    741   std::vector<uint8_t> full_pkt;
    742   full_pkt.resize(full_len);
    743   res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
    744   if (res < 0) {
    745     PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
    746     CloseFds();
    747     return;
    748   }
    749   DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
    750   size_t data_size = full_len - kPacketHeaderLen;
    751   if (data_size < (sizeof(uint32_t) * 2)) {
    752     // This is an error (the data isn't long enough) but to match historical behavior we need to
    753     // ignore it.
    754     return;
    755   }
    756   uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
    757   uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
    758   uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
    759   if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
    760     // This is an error (the data isn't long enough) but to match historical behavior we need to
    761     // ignore it.
    762     return;
    763   }
    764 
    765   if (!notified_ddm_active_) {
    766     NotifyDdms(/*active*/ true);
    767   }
    768   uint32_t reply_type;
    769   std::vector<uint8_t> reply;
    770   if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
    771                                 ddm_type,
    772                                 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
    773                                                            ddm_len),
    774                                 /*out*/&reply_type,
    775                                 /*out*/&reply)) {
    776     // To match historical behavior we don't send any response when there is no data to reply with.
    777     return;
    778   }
    779   SendDdmPacket(pkt_id,
    780                 DdmPacketType::kReply,
    781                 reply_type,
    782                 art::ArrayRef<const uint8_t>(reply));
    783 }
    784 
    785 void AdbConnectionState::PerformHandshake() {
    786   CHECK(!performed_handshake_);
    787   // Check to make sure we are able to read the whole handshake.
    788   uint32_t avail = -1;
    789   int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
    790   if (res < 0 || avail < sizeof(kJdwpHandshake)) {
    791     if (res < 0) {
    792       PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
    793     }
    794     LOG(WARNING) << "Closing connection to broken client.";
    795     CloseFds();
    796     return;
    797   }
    798   // Perform the handshake.
    799   char handshake_msg[sizeof(kJdwpHandshake)];
    800   res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
    801                                 handshake_msg,
    802                                 sizeof(handshake_msg),
    803                                 MSG_DONTWAIT));
    804   if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
    805       strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
    806     if (res < 0) {
    807       PLOG(ERROR) << "Failed to read handshake!";
    808     }
    809     LOG(WARNING) << "Handshake failed!";
    810     CloseFds();
    811     return;
    812   }
    813   // Send the handshake back.
    814   res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
    815                                 kJdwpHandshake,
    816                                 sizeof(kJdwpHandshake),
    817                                 0));
    818   if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
    819     PLOG(ERROR) << "Failed to send jdwp-handshake response.";
    820     CloseFds();
    821     return;
    822   }
    823   performed_handshake_ = true;
    824 }
    825 
    826 void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
    827   art::Runtime* runtime = art::Runtime::Current();
    828   self->AssertNoPendingException();
    829   runtime->AttachAgent(/* JNIEnv */ nullptr,
    830                        MakeAgentArg(),
    831                        /* classloader */ nullptr);
    832   if (self->IsExceptionPending()) {
    833     LOG(ERROR) << "Failed to load agent " << agent_name_;
    834     art::ScopedObjectAccess soa(self);
    835     self->GetException()->Dump();
    836     self->ClearException();
    837     return;
    838   }
    839   agent_loaded_ = true;
    840 }
    841 
    842 bool ContainsArgument(const std::string& opts, const char* arg) {
    843   return opts.find(arg) != std::string::npos;
    844 }
    845 
    846 bool ValidateJdwpOptions(const std::string& opts) {
    847   bool res = true;
    848   // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
    849   // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
    850   // for the fd's to be passed down.
    851   if (ContainsArgument(opts, "server=n")) {
    852     res = false;
    853     LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
    854   }
    855   // We don't start the jdwp agent until threads are already running. It is far too late to suspend
    856   // everything.
    857   if (ContainsArgument(opts, "suspend=y")) {
    858     res = false;
    859     LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
    860   }
    861   return res;
    862 }
    863 
    864 std::string AdbConnectionState::MakeAgentArg() {
    865   const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
    866   DCHECK(ValidateJdwpOptions(opts));
    867   // TODO Get agent_name_ from something user settable?
    868   return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
    869       "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
    870       // See the comment above for why we need to be server=y. Since the agent defaults to server=n
    871       // we will add it if it wasn't already present for the convenience of the user.
    872       (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
    873       // See the comment above for why we need to be suspend=n. Since the agent defaults to
    874       // suspend=y we will add it if it wasn't already present.
    875       (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n") +
    876       "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
    877 }
    878 
    879 void AdbConnectionState::StopDebuggerThreads() {
    880   // The regular agent system will take care of unloading the agent (if needed).
    881   shutting_down_ = true;
    882   // Wakeup the poll loop.
    883   uint64_t data = 1;
    884   if (sleep_event_fd_ != -1) {
    885     TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
    886   }
    887 }
    888 
    889 // The plugin initialization function.
    890 extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
    891   DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
    892   // TODO Provide some way for apps to set this maybe?
    893   DCHECK(gState == nullptr);
    894   gState = new AdbConnectionState(kDefaultJdwpAgentName);
    895   return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
    896 }
    897 
    898 extern "C" bool ArtPlugin_Deinitialize() {
    899   gState->StopDebuggerThreads();
    900   if (!gState->DebuggerThreadsStarted()) {
    901     // If debugger threads were started then those threads will delete the state once they are done.
    902     delete gState;
    903   }
    904   return true;
    905 }
    906 
    907 }  // namespace adbconnection
    908