blob: 2234ce4fa24b880806e18bbdbac27760ad7c6543 [file] [log] [blame]
Alex Lightfbf96702017-12-14 13:27:13 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <array>
Josh Gaobd396c02020-01-22 18:02:19 -080018#include <iterator>
Alex Lightfbf96702017-12-14 13:27:13 -080019
20#include "adbconnection.h"
21
Josh Gaobd396c02020-01-22 18:02:19 -080022#include "adbconnection/client.h"
Alex Lightfbf96702017-12-14 13:27:13 -080023#include "android-base/endian.h"
24#include "android-base/stringprintf.h"
Andreas Gampedfcd82c2018-10-16 20:22:37 -070025#include "base/file_utils.h"
Alex Lightfbf96702017-12-14 13:27:13 -080026#include "base/logging.h"
27#include "base/macros.h"
28#include "base/mutex.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010029#include "jni/java_vm_ext.h"
30#include "jni/jni_env_ext.h"
Alex Lightfbf96702017-12-14 13:27:13 -080031#include "mirror/throwable.h"
Orion Hodsond41c7592019-01-27 09:25:47 +000032#include "nativehelper/scoped_local_ref.h"
Alex Lightfbf96702017-12-14 13:27:13 -080033#include "runtime-inl.h"
34#include "runtime_callbacks.h"
35#include "scoped_thread_state_change-inl.h"
36#include "well_known_classes.h"
37
38#include "jdwp/jdwp_priv.h"
39
40#include "fd_transport.h"
41
42#include "poll.h"
43
Alex Light15b81132018-01-24 13:29:07 -080044#include <sys/ioctl.h>
Alex Lightfbf96702017-12-14 13:27:13 -080045#include <sys/socket.h>
46#include <sys/un.h>
47#include <sys/eventfd.h>
48#include <jni.h>
49
50namespace adbconnection {
51
Alex Light15b81132018-01-24 13:29:07 -080052// Messages sent from the transport
Alex Lightfbf96702017-12-14 13:27:13 -080053using dt_fd_forward::kListenStartMessage;
54using dt_fd_forward::kListenEndMessage;
55using dt_fd_forward::kAcceptMessage;
56using dt_fd_forward::kCloseMessage;
57
Alex Light15b81132018-01-24 13:29:07 -080058// Messages sent to the transport
59using dt_fd_forward::kPerformHandshakeMessage;
60using dt_fd_forward::kSkipHandshakeMessage;
61
Alex Lightfbf96702017-12-14 13:27:13 -080062using android::base::StringPrintf;
63
Alex Light15b81132018-01-24 13:29:07 -080064static constexpr const char kJdwpHandshake[14] = {
65 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
66};
67
Alex Lightfbf96702017-12-14 13:27:13 -080068static constexpr int kEventfdLocked = 0;
69static constexpr int kEventfdUnlocked = 1;
Alex Lightfbf96702017-12-14 13:27:13 -080070
Alex Light15b81132018-01-24 13:29:07 -080071static constexpr size_t kPacketHeaderLen = 11;
72static constexpr off_t kPacketSizeOff = 0;
73static constexpr off_t kPacketIdOff = 4;
74static constexpr off_t kPacketCommandSetOff = 9;
75static constexpr off_t kPacketCommandOff = 10;
76
77static constexpr uint8_t kDdmCommandSet = 199;
78static constexpr uint8_t kDdmChunkCommand = 1;
79
Alex Lightfbf96702017-12-14 13:27:13 -080080static AdbConnectionState* gState;
81
82static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080083 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080084}
85
86// Begin running the debugger.
87void AdbConnectionDebuggerController::StartDebugger() {
88 if (IsDebuggingPossible()) {
89 connection_->StartDebuggerThreads();
90 } else {
91 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
92 }
93}
94
95// The debugger should begin shutting down since the runtime is ending. We don't actually do
96// anything here. The real shutdown has already happened as far as the agent is concerned.
97void AdbConnectionDebuggerController::StopDebugger() { }
98
99bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
100 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
101}
102
103void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
104 const art::ArrayRef<const uint8_t>& data) {
105 connection_->PublishDdmData(type, data);
106}
107
108class ScopedEventFdLock {
109 public:
110 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
111 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
112 }
113
114 ~ScopedEventFdLock() {
115 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
116 }
117
118 private:
119 int fd_;
120 uint64_t data_;
121};
122
123AdbConnectionState::AdbConnectionState(const std::string& agent_name)
124 : agent_name_(agent_name),
125 controller_(this),
126 ddm_callback_(this),
127 sleep_event_fd_(-1),
Josh Gaobd396c02020-01-22 18:02:19 -0800128 control_ctx_(nullptr, adbconnection_client_destroy),
Alex Lightfbf96702017-12-14 13:27:13 -0800129 local_agent_control_sock_(-1),
130 remote_agent_control_sock_(-1),
131 adb_connection_socket_(-1),
132 adb_write_event_fd_(-1),
133 shutting_down_(false),
134 agent_loaded_(false),
135 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800136 agent_has_socket_(false),
137 sent_agent_fds_(false),
138 performed_handshake_(false),
139 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800140 next_ddm_id_(1),
141 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800142 // Setup the addr.
143 control_addr_.controlAddrUn.sun_family = AF_UNIX;
144 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
145 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
146
147 // Add the startup callback.
148 art::ScopedObjectAccess soa(art::Thread::Current());
149 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
150}
151
152static jobject CreateAdbConnectionThread(art::Thread* thr) {
153 JNIEnv* env = thr->GetJniEnv();
154 // Move to native state to talk with the jnienv api.
155 art::ScopedThreadStateChange stsc(thr, art::kNative);
156 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
157 ScopedLocalRef<jobject> thr_group(
158 env,
159 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
160 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
161 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
162 art::WellKnownClasses::java_lang_Thread_init,
163 thr_group.get(),
164 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700165 /*Priority=*/ 0,
166 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800167}
168
169struct CallbackData {
170 AdbConnectionState* this_;
171 jobject thr_;
172};
173
174static void* CallbackFunction(void* vdata) {
175 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
Alex Lightd6f9d852018-01-25 11:26:28 -0800176 CHECK(data->this_ == gState);
Alex Lightfbf96702017-12-14 13:27:13 -0800177 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
178 true,
179 data->thr_);
180 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
181 // The name in Attach() is only for logging. Set the thread name. This is important so
182 // that the thread is no longer seen as starting up.
183 {
184 art::ScopedObjectAccess soa(self);
185 self->SetThreadName(kAdbConnectionThreadName);
186 }
187
188 // Release the peer.
189 JNIEnv* env = self->GetJniEnv();
190 env->DeleteGlobalRef(data->thr_);
191 data->thr_ = nullptr;
192 {
193 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
194 // before going into the provided code.
195 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
196 art::Runtime::Current()->EndThreadBirth();
197 }
198 data->this_->RunPollLoop(self);
199 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
200 CHECK_EQ(detach_result, 0);
201
Alex Lightd6f9d852018-01-25 11:26:28 -0800202 // Get rid of the connection
203 gState = nullptr;
204 delete data->this_;
205
Alex Lightfbf96702017-12-14 13:27:13 -0800206 return nullptr;
207}
208
209void AdbConnectionState::StartDebuggerThreads() {
210 // First do all the final setup we need.
211 CHECK_EQ(adb_write_event_fd_.get(), -1);
212 CHECK_EQ(sleep_event_fd_.get(), -1);
213 CHECK_EQ(local_agent_control_sock_.get(), -1);
214 CHECK_EQ(remote_agent_control_sock_.get(), -1);
215
216 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
217 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
218 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
219 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
220
221 {
222 art::ScopedObjectAccess soa(art::Thread::Current());
223 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
224 }
225 // Setup the socketpair we use to talk to the agent.
226 bool has_sockets;
227 do {
228 has_sockets = android::base::Socketpair(AF_UNIX,
229 SOCK_SEQPACKET | SOCK_CLOEXEC,
230 0,
231 &local_agent_control_sock_,
232 &remote_agent_control_sock_);
233 } while (!has_sockets && errno == EINTR);
234 if (!has_sockets) {
235 PLOG(FATAL) << "Unable to create socketpair for agent control!";
236 }
237
238 // Next start the threads.
239 art::Thread* self = art::Thread::Current();
240 art::ScopedObjectAccess soa(self);
241 {
242 art::Runtime* runtime = art::Runtime::Current();
243 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
244 if (runtime->IsShuttingDownLocked()) {
245 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
246 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
247 return;
248 }
249 runtime->StartThreadBirth();
250 }
251 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700252 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
253 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800254 pthread_t pthread;
255 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800256 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800257 int pthread_create_result = pthread_create(&pthread,
258 nullptr,
259 &CallbackFunction,
260 data.get());
261 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800262 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800263 // If the create succeeded the other thread will call EndThreadBirth.
264 art::Runtime* runtime = art::Runtime::Current();
265 soa.Env()->DeleteGlobalRef(data->thr_);
266 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
267 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
268 runtime->EndThreadBirth();
269 return;
270 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700271 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800272}
273
274static bool FlagsSet(int16_t data, int16_t flags) {
275 return (data & flags) == flags;
276}
277
278void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800279 {
280 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
281 // closed.
282 ScopedEventFdLock lk(adb_write_event_fd_);
283 // shutdown(adb_connection_socket_, SHUT_RDWR);
284 adb_connection_socket_.reset();
285 }
286
287 // If we didn't load anything we will need to do the handshake again.
288 performed_handshake_ = false;
289
290 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
291 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700292 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800293 }
294}
295
296void AdbConnectionState::NotifyDdms(bool active) {
297 art::ScopedObjectAccess soa(art::Thread::Current());
298 DCHECK_NE(notified_ddm_active_, active);
299 notified_ddm_active_ = active;
300 if (active) {
301 art::Dbg::DdmConnected();
302 } else {
303 art::Dbg::DdmDisconnected();
304 }
Alex Lightfbf96702017-12-14 13:27:13 -0800305}
306
307uint32_t AdbConnectionState::NextDdmId() {
308 // Just have a normal counter but always set the sign bit.
309 return (next_ddm_id_++) | 0x80000000;
310}
311
312void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800313 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
314}
315
316void AdbConnectionState::SendDdmPacket(uint32_t id,
317 DdmPacketType packet_type,
318 uint32_t type,
319 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800320 // Get the write_event early to fail fast.
321 ScopedEventFdLock lk(adb_write_event_fd_);
322 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800323 VLOG(jdwp) << "Not sending ddms data of type "
324 << StringPrintf("%c%c%c%c",
325 static_cast<char>(type >> 24),
326 static_cast<char>(type >> 16),
327 static_cast<char>(type >> 8),
328 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800329 // Adb is not connected.
330 return;
331 }
332
333 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
334 // after we have sent our data.
335 static constexpr uint32_t kDdmPacketHeaderSize =
336 kJDWPHeaderLen // jdwp command packet size
337 + sizeof(uint32_t) // Type
338 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800339 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800340 uint8_t* pkt_data = pkt.data();
341
342 // Write the length first.
343 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
344 pkt_data += sizeof(uint32_t);
345
346 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800347 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800348 pkt_data += sizeof(uint32_t);
349
350 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800351 *(pkt_data++) = static_cast<uint8_t>(packet_type);
352 switch (packet_type) {
353 case DdmPacketType::kCmd: {
354 // Now the cmd-set
355 *(pkt_data++) = kJDWPDdmCmdSet;
356 // Now the command
357 *(pkt_data++) = kJDWPDdmCmd;
358 break;
359 }
360 case DdmPacketType::kReply: {
361 // This is the error code bytes which are all 0
362 *(pkt_data++) = 0;
363 *(pkt_data++) = 0;
364 }
365 }
Alex Lightfbf96702017-12-14 13:27:13 -0800366
Alex Light15b81132018-01-24 13:29:07 -0800367 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800368 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800369 uint32_t net_type = htonl(type);
370 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800371 pkt_data += sizeof(uint32_t);
372
373 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800374 uint32_t net_len = htonl(data.size());
375 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800376 pkt_data += sizeof(uint32_t);
377
378 static uint32_t constexpr kIovSize = 2;
379 struct iovec iovs[kIovSize] = {
380 { pkt.data(), pkt.size() },
381 { const_cast<uint8_t*>(data.data()), data.size() },
382 };
383 // now pkt_header has the header.
384 // use writev to send the actual data.
385 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
386 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
387 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
388 static_cast<char>(type >> 24),
389 static_cast<char>(type >> 16),
390 static_cast<char>(type >> 8),
391 static_cast<char>(type),
392 res, data.size() + kDdmPacketHeaderSize);
393 } else {
394 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
395 static_cast<char>(type >> 24),
396 static_cast<char>(type >> 16),
397 static_cast<char>(type >> 8),
398 static_cast<char>(type),
399 data.size() + kDdmPacketHeaderSize);
400 }
401}
402
Alex Light15b81132018-01-24 13:29:07 -0800403void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800404 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800405 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800406 union {
407 cmsghdr cm;
408 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
409 } cm_un;
410 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800411 iov.iov_base = const_cast<char*>(message);
412 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800413
414 msghdr msg;
415 msg.msg_name = nullptr;
416 msg.msg_namelen = 0;
417 msg.msg_iov = &iov;
418 msg.msg_iovlen = 1;
419 msg.msg_flags = 0;
420 msg.msg_control = cm_un.buffer;
421 msg.msg_controllen = sizeof(cm_un.buffer);
422
423 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
424 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
425 cmsg->cmsg_level = SOL_SOCKET;
426 cmsg->cmsg_type = SCM_RIGHTS;
427
428 // Duplicate the fds before sending them.
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700429 android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800430 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700431 android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800432 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700433 android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
Alex Lightfbf96702017-12-14 13:27:13 -0800434 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
435
436 dt_fd_forward::FdSet {
437 read_fd.get(), write_fd.get(), write_lock_fd.get()
438 }.WriteData(CMSG_DATA(cmsg));
439
440 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
441 if (res < 0) {
442 PLOG(ERROR) << "Failed to send agent adb connection fds.";
443 } else {
444 sent_agent_fds_ = true;
445 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
446 }
447}
448
449android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
Josh Gaobd396c02020-01-22 18:02:19 -0800450 return android::base::unique_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800451}
452
453bool AdbConnectionState::SetupAdbConnection() {
Josh Gaobd396c02020-01-22 18:02:19 -0800454 int sleep_ms = 500;
455 const int sleep_max_ms = 2 * 1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800456
Josh Gaobd396c02020-01-22 18:02:19 -0800457 const AdbConnectionClientInfo infos[] = {
458 {.type = AdbConnectionClientInfoType::pid, .data.pid = static_cast<uint64_t>(getpid())},
459 {.type = AdbConnectionClientInfoType::debuggable, .data.debuggable = true},
460 };
461 const AdbConnectionClientInfo* info_ptrs[] = {&infos[0], &infos[1]};
Alex Lightfbf96702017-12-14 13:27:13 -0800462
463 while (!shutting_down_) {
464 // If adbd isn't running, because USB debugging was disabled or
465 // perhaps the system is restarting it for "adb root", the
466 // connect() will fail. We loop here forever waiting for it
467 // to come back.
468 //
469 // Waking up and polling every couple of seconds is generally a
470 // bad thing to do, but we only do this if the application is
471 // debuggable *and* adbd isn't running. Still, for the sake
472 // of battery life, we should consider timing out and giving
473 // up after a few minutes in case somebody ships an app with
474 // the debuggable flag set.
Josh Gaobd396c02020-01-22 18:02:19 -0800475 control_ctx_.reset(adbconnection_client_new(info_ptrs, std::size(infos)));
476 if (control_ctx_) {
477 return true;
478 }
Alex Lightfbf96702017-12-14 13:27:13 -0800479
Josh Gaobd396c02020-01-22 18:02:19 -0800480 // We failed to connect.
481 usleep(sleep_ms * 1000);
Alex Lightfbf96702017-12-14 13:27:13 -0800482
Josh Gaobd396c02020-01-22 18:02:19 -0800483 sleep_ms += (sleep_ms >> 1);
484 if (sleep_ms > sleep_max_ms) {
485 sleep_ms = sleep_max_ms;
Alex Lightfbf96702017-12-14 13:27:13 -0800486 }
487 }
Josh Gaobd396c02020-01-22 18:02:19 -0800488
Alex Lightfbf96702017-12-14 13:27:13 -0800489 return false;
490}
491
492void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800493 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800494 CHECK_EQ(self->GetState(), art::kNative);
Ziang Wan92db59b2019-07-22 21:19:24 +0000495 art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800496 self->SetState(art::kWaitingInMainDebuggerLoop);
497 // shutting_down_ set by StopDebuggerThreads
498 while (!shutting_down_) {
Josh Gaobd396c02020-01-22 18:02:19 -0800499 // First, connect to adbd if we haven't already.
500 if (!control_ctx_ && !SetupAdbConnection()) {
Alex Lightfbf96702017-12-14 13:27:13 -0800501 LOG(ERROR) << "Failed to setup adb connection.";
502 return;
503 }
Josh Gaobd396c02020-01-22 18:02:19 -0800504 while (!shutting_down_ && control_ctx_) {
Alex Light15b81132018-01-24 13:29:07 -0800505 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800506 struct pollfd pollfds[4] = {
507 { sleep_event_fd_, POLLIN, 0 },
508 // -1 as an fd causes it to be ignored by poll
509 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
510 // Check for the control_sock_ actually going away. Only do this if we don't have an active
511 // connection.
Josh Gaobd396c02020-01-22 18:02:19 -0800512 { (adb_connection_socket_ == -1 ? adbconnection_client_pollfd(control_ctx_.get()) : -1),
513 POLLIN | POLLRDHUP, 0 },
Alex Lightfbf96702017-12-14 13:27:13 -0800514 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
515 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800516 // data that the agent or this plugin can handle.
517 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800518 };
519 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
520 if (res < 0) {
521 PLOG(ERROR) << "Failed to poll!";
522 return;
523 }
524 // We don't actually care about doing this we just use it to wake us up.
525 // const struct pollfd& sleep_event_poll = pollfds[0];
526 const struct pollfd& agent_control_sock_poll = pollfds[1];
527 const struct pollfd& control_sock_poll = pollfds[2];
528 const struct pollfd& adb_socket_poll = pollfds[3];
529 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
530 DCHECK(agent_loaded_);
531 char buf[257];
532 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
533 if (res < 0) {
534 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
535 continue;
536 } else {
537 buf[res + 1] = '\0';
538 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
539 }
540 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
541 agent_listening_ = true;
542 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700543 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800544 }
545 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
546 agent_listening_ = false;
547 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
548 CloseFds();
549 agent_has_socket_ = false;
550 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
551 agent_has_socket_ = true;
552 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800553 // We will only ever do the handshake once so reset this.
554 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800555 } else {
556 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
557 }
558 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
559 bool maybe_send_fds = false;
560 {
561 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
562 ScopedEventFdLock sefdl(adb_write_event_fd_);
Josh Gaobd396c02020-01-22 18:02:19 -0800563 android::base::unique_fd new_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800564 if (new_fd == -1) {
565 // Something went wrong. We need to retry getting the control socket.
Josh Gaobd396c02020-01-22 18:02:19 -0800566 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800567 break;
568 } else if (adb_connection_socket_ != -1) {
569 // We already have a connection.
570 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
571 if (new_fd >= 0) {
572 new_fd.reset();
573 }
574 } else {
575 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
576 adb_connection_socket_ = std::move(new_fd);
577 maybe_send_fds = true;
578 }
579 }
580 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
581 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800582 // The agent was already loaded so this must be after a disconnection. Therefore have the
583 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700584 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800585 }
586 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
587 // The other end of the adb connection just dropped it.
588 // Reset the connection since we don't have an active socket through the adb server.
589 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
590 << "connection active";
Josh Gaobd396c02020-01-22 18:02:19 -0800591 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800592 break;
593 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
594 DCHECK(!agent_has_socket_);
595 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800596 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800597 } else if (agent_listening_ && !sent_agent_fds_) {
598 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800599 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700600 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800601 }
Alex Light15b81132018-01-24 13:29:07 -0800602 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
603 DCHECK(!agent_has_socket_);
604 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800605 } else {
606 VLOG(jdwp) << "Woke up poll without anything to do!";
607 }
608 }
609 }
610}
611
Alex Light15b81132018-01-24 13:29:07 -0800612static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
613 uint32_t res;
614 memcpy(&res, *in, sizeof(uint32_t));
615 *in = (*in) + sizeof(uint32_t);
616 return ntohl(res);
617}
618
619void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
620 DCHECK(!agent_loaded_);
621 DCHECK(!agent_listening_);
622 // TODO Should we check in some other way if we are userdebug/eng?
623 CHECK(art::Dbg::IsJdwpAllowed());
624 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
625 if (!performed_handshake_) {
626 PerformHandshake();
627 return;
628 }
629 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
630 // to see if it's one we can handle. This doesn't change the state of the socket.
631 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
632 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
633 packet_header,
634 sizeof(packet_header),
635 MSG_PEEK));
636 // We want to be very careful not to change the socket state until we know we succeeded. This will
637 // let us fall-back to just loading the agent and letting it deal with everything.
638 if (res <= 0) {
639 // Close the socket. We either hit EOF or an error.
640 if (res < 0) {
641 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
642 }
643 CloseFds();
644 return;
645 } else if (res < static_cast<int>(kPacketHeaderLen)) {
646 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
647 AttachJdwpAgent(self);
648 return;
649 }
650 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
651 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
652 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
653 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
654 if (pkt_cmd_set != kDdmCommandSet ||
655 pkt_cmd != kDdmChunkCommand ||
656 full_len < kPacketHeaderLen) {
657 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
658 AttachJdwpAgent(self);
659 return;
660 }
661 uint32_t avail = -1;
662 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
663 if (res < 0) {
664 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
665 CloseFds();
666 return;
667 } else if (avail < full_len) {
668 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
669 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
670 << "Loading jdwp agent to deal with this.";
671 AttachJdwpAgent(self);
672 return;
673 }
674 // Actually read the data.
675 std::vector<uint8_t> full_pkt;
676 full_pkt.resize(full_len);
677 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
678 if (res < 0) {
679 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
680 CloseFds();
681 return;
682 }
683 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
684 size_t data_size = full_len - kPacketHeaderLen;
685 if (data_size < (sizeof(uint32_t) * 2)) {
686 // This is an error (the data isn't long enough) but to match historical behavior we need to
687 // ignore it.
688 return;
689 }
690 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
691 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
692 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
693 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
694 // This is an error (the data isn't long enough) but to match historical behavior we need to
695 // ignore it.
696 return;
697 }
698
699 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700700 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800701 }
702 uint32_t reply_type;
703 std::vector<uint8_t> reply;
704 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
705 ddm_type,
706 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
707 ddm_len),
708 /*out*/&reply_type,
709 /*out*/&reply)) {
710 // To match historical behavior we don't send any response when there is no data to reply with.
711 return;
712 }
713 SendDdmPacket(pkt_id,
714 DdmPacketType::kReply,
715 reply_type,
716 art::ArrayRef<const uint8_t>(reply));
717}
718
719void AdbConnectionState::PerformHandshake() {
720 CHECK(!performed_handshake_);
721 // Check to make sure we are able to read the whole handshake.
722 uint32_t avail = -1;
723 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
724 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
725 if (res < 0) {
726 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
727 }
728 LOG(WARNING) << "Closing connection to broken client.";
729 CloseFds();
730 return;
731 }
732 // Perform the handshake.
733 char handshake_msg[sizeof(kJdwpHandshake)];
734 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
735 handshake_msg,
736 sizeof(handshake_msg),
737 MSG_DONTWAIT));
738 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
739 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
740 if (res < 0) {
741 PLOG(ERROR) << "Failed to read handshake!";
742 }
743 LOG(WARNING) << "Handshake failed!";
744 CloseFds();
745 return;
746 }
747 // Send the handshake back.
748 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
749 kJdwpHandshake,
750 sizeof(kJdwpHandshake),
751 0));
752 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
753 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
754 CloseFds();
755 return;
756 }
757 performed_handshake_ = true;
758}
759
760void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700761 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800762 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700763 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700764 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700765 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800766 if (self->IsExceptionPending()) {
767 LOG(ERROR) << "Failed to load agent " << agent_name_;
768 art::ScopedObjectAccess soa(self);
769 self->GetException()->Dump();
770 self->ClearException();
771 return;
772 }
773 agent_loaded_ = true;
774}
775
Alex Light81f75c32018-01-26 09:46:32 -0800776bool ContainsArgument(const std::string& opts, const char* arg) {
777 return opts.find(arg) != std::string::npos;
778}
779
780bool ValidateJdwpOptions(const std::string& opts) {
781 bool res = true;
782 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
783 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
784 // for the fd's to be passed down.
785 if (ContainsArgument(opts, "server=n")) {
786 res = false;
787 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
788 }
789 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
790 // everything.
791 if (ContainsArgument(opts, "suspend=y")) {
792 res = false;
793 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
794 }
795 return res;
796}
797
Alex Lightfbf96702017-12-14 13:27:13 -0800798std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800799 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800800 DCHECK(ValidateJdwpOptions(opts));
801 // TODO Get agent_name_ from something user settable?
802 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
803 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
804 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
805 // we will add it if it wasn't already present for the convenience of the user.
806 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
807 // See the comment above for why we need to be suspend=n. Since the agent defaults to
808 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700809 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800810 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800811}
812
813void AdbConnectionState::StopDebuggerThreads() {
814 // The regular agent system will take care of unloading the agent (if needed).
815 shutting_down_ = true;
816 // Wakeup the poll loop.
817 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800818 if (sleep_event_fd_ != -1) {
819 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
820 }
Alex Lightfbf96702017-12-14 13:27:13 -0800821}
822
823// The plugin initialization function.
Alex Light3b08bcc2019-09-11 09:48:51 -0700824extern "C" bool ArtPlugin_Initialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800825 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
826 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800827 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800828 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800829 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800830}
831
832extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800833 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800834 if (!gState->DebuggerThreadsStarted()) {
835 // If debugger threads were started then those threads will delete the state once they are done.
836 delete gState;
837 }
Alex Lightfbf96702017-12-14 13:27:13 -0800838 return true;
839}
840
841} // namespace adbconnection