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