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