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