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