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