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/globals.h"
28 #include "base/logging.h"
29 #include "base/macros.h"
30 #include "base/mutex.h"
31 #include "base/socket_peer_is_trusted.h"
32 #include "debugger.h"
33 #include "jni/java_vm_ext.h"
34 #include "jni/jni_env_ext.h"
35 #include "mirror/throwable.h"
36 #include "nativehelper/scoped_local_ref.h"
37 #include "runtime-inl.h"
38 #include "runtime_callbacks.h"
39 #include "scoped_thread_state_change-inl.h"
40 #include "well_known_classes.h"
41
42 #include "fd_transport.h"
43
44 #include "poll.h"
45
46 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48 #include <sys/uio.h>
49 #include <sys/un.h>
50 #include <sys/eventfd.h>
51 #include <jni.h>
52
53 namespace adbconnection {
54
55 static constexpr size_t kJdwpHeaderLen = 11U;
56 /* DDM support */
57 static constexpr uint8_t kJdwpDdmCmdSet = 199U; // 0xc7, or 'G'+128
58 static constexpr uint8_t kJdwpDdmCmd = 1U;
59
60 // Messages sent from the transport
61 using dt_fd_forward::kListenStartMessage;
62 using dt_fd_forward::kListenEndMessage;
63 using dt_fd_forward::kAcceptMessage;
64 using dt_fd_forward::kCloseMessage;
65 using dt_fd_forward::kHandshakeCompleteMessage;
66
67 // Messages sent to the transport
68 using dt_fd_forward::kPerformHandshakeMessage;
69 using dt_fd_forward::kSkipHandshakeMessage;
70
71 using android::base::StringPrintf;
72
73 static constexpr const char kJdwpHandshake[14] = {
74 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
75 };
76
77 static constexpr int kEventfdLocked = 0;
78 static constexpr int kEventfdUnlocked = 1;
79
80 static constexpr size_t kPacketHeaderLen = 11;
81 static constexpr off_t kPacketSizeOff = 0;
82 static constexpr off_t kPacketIdOff = 4;
83 static constexpr off_t kPacketCommandSetOff = 9;
84 static constexpr off_t kPacketCommandOff = 10;
85
86 static constexpr uint8_t kDdmCommandSet = 199;
87 static constexpr uint8_t kDdmChunkCommand = 1;
88
89 static std::optional<AdbConnectionState> gState;
90 static std::optional<pthread_t> gPthread;
91
IsDebuggingPossible()92 static bool IsDebuggingPossible() {
93 return art::Dbg::IsJdwpAllowed();
94 }
95
96 // Begin running the debugger.
StartDebugger()97 void AdbConnectionDebuggerController::StartDebugger() {
98 // The debugger thread is started for a debuggable or profileable-from-shell process.
99 // The pid will be send to adbd for adb's "track-jdwp" and "track-app" services.
100 // The thread will also set up the jdwp tunnel if the process is debuggable.
101 if (IsDebuggingPossible() || art::Runtime::Current()->IsProfileableFromShell()) {
102 connection_->StartDebuggerThreads();
103 } else {
104 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
105 }
106 }
107
108 // The debugger should have already shut down since the runtime is ending. As far
109 // as the agent is concerned shutdown already happened when we went to kDeath
110 // state. We need to clean up our threads still though and this is a good time
111 // to do it since the runtime is still able to handle all the normal state
112 // transitions.
StopDebugger()113 void AdbConnectionDebuggerController::StopDebugger() {
114 // Stop our threads.
115 gState->StopDebuggerThreads();
116 // Wait for our threads to actually return and cleanup the pthread.
117 if (gPthread.has_value()) {
118 void* ret_unused;
119 if (TEMP_FAILURE_RETRY(pthread_join(gPthread.value(), &ret_unused)) != 0) {
120 PLOG(ERROR) << "Failed to join debugger threads!";
121 }
122 gPthread.reset();
123 }
124 }
125
IsDebuggerConfigured()126 bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
127 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
128 }
129
DdmPublishChunk(uint32_t type,const art::ArrayRef<const uint8_t> & data)130 void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
131 const art::ArrayRef<const uint8_t>& data) {
132 connection_->PublishDdmData(type, data);
133 }
134
135 class ScopedEventFdLock {
136 public:
ScopedEventFdLock(int fd)137 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
138 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
139 }
140
~ScopedEventFdLock()141 ~ScopedEventFdLock() {
142 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
143 }
144
145 private:
146 int fd_;
147 uint64_t data_;
148 };
149
AdbConnectionState(const std::string & agent_name)150 AdbConnectionState::AdbConnectionState(const std::string& agent_name)
151 : agent_name_(agent_name),
152 controller_(this),
153 ddm_callback_(this),
154 sleep_event_fd_(-1),
155 control_ctx_(nullptr, adbconnection_client_destroy),
156 local_agent_control_sock_(-1),
157 remote_agent_control_sock_(-1),
158 adb_connection_socket_(-1),
159 adb_write_event_fd_(-1),
160 shutting_down_(false),
161 agent_loaded_(false),
162 agent_listening_(false),
163 agent_has_socket_(false),
164 sent_agent_fds_(false),
165 performed_handshake_(false),
166 notified_ddm_active_(false),
167 next_ddm_id_(1),
168 started_debugger_threads_(false) {
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 || !performed_handshake_) {
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 char* isa = GetInstructionSetString(art::Runtime::Current()->GetInstructionSet());
485 const AdbConnectionClientInfo infos[] = {
486 {.type = AdbConnectionClientInfoType::pid,
487 .data.pid = static_cast<uint64_t>(getpid())},
488 {.type = AdbConnectionClientInfoType::debuggable,
489 .data.debuggable = IsDebuggingPossible()},
490 {.type = AdbConnectionClientInfoType::profileable,
491 .data.profileable = art::Runtime::Current()->IsProfileableFromShell()},
492 {.type = AdbConnectionClientInfoType::architecture,
493 // GetInstructionSetString() returns a null-terminating C-style string.
494 .data.architecture.name = isa,
495 .data.architecture.size = strlen(isa)},
496 };
497 const AdbConnectionClientInfo *info_ptrs[] = {&infos[0], &infos[1], &infos[2], &infos[3]};
498
499 while (!shutting_down_) {
500 // If adbd isn't running, because USB debugging was disabled or
501 // perhaps the system is restarting it for "adb root", the
502 // connect() will fail. We loop here forever waiting for it
503 // to come back.
504 //
505 // Waking up and polling every couple of seconds is generally a
506 // bad thing to do, but we only do this if the application is
507 // debuggable *and* adbd isn't running. Still, for the sake
508 // of battery life, we should consider timing out and giving
509 // up after a few minutes in case somebody ships an app with
510 // the debuggable flag set.
511 control_ctx_.reset(adbconnection_client_new(info_ptrs, std::size(infos)));
512 if (control_ctx_) {
513 return true;
514 }
515
516 // We failed to connect.
517 usleep(sleep_ms * 1000);
518
519 sleep_ms += (sleep_ms >> 1);
520 if (sleep_ms > sleep_max_ms) {
521 sleep_ms = sleep_max_ms;
522 }
523 }
524
525 return false;
526 }
527
RunPollLoop(art::Thread * self)528 void AdbConnectionState::RunPollLoop(art::Thread* self) {
529 DCHECK(IsDebuggingPossible() || art::Runtime::Current()->IsProfileableFromShell());
530 CHECK_NE(agent_name_, "");
531 CHECK_EQ(self->GetState(), art::kNative);
532 art::Locks::mutator_lock_->AssertNotHeld(self);
533 self->SetState(art::kWaitingInMainDebuggerLoop);
534 // shutting_down_ set by StopDebuggerThreads
535 while (!shutting_down_) {
536 // First, connect to adbd if we haven't already.
537 if (!control_ctx_ && !SetupAdbConnection()) {
538 LOG(ERROR) << "Failed to setup adb connection.";
539 return;
540 }
541 while (!shutting_down_ && control_ctx_) {
542 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
543 struct pollfd pollfds[4] = {
544 { sleep_event_fd_, POLLIN, 0 },
545 // -1 as an fd causes it to be ignored by poll
546 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
547 // Check for the control_sock_ actually going away. Only do this if we don't have an active
548 // connection.
549 { (adb_connection_socket_ == -1 ? adbconnection_client_pollfd(control_ctx_.get()) : -1),
550 POLLIN | POLLRDHUP, 0 },
551 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
552 // have a real connection yet or the socket through adb needs to be listened to for incoming
553 // data that the agent or this plugin can handle.
554 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
555 };
556 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
557 if (res < 0) {
558 PLOG(ERROR) << "Failed to poll!";
559 return;
560 }
561 // We don't actually care about doing this we just use it to wake us up.
562 // const struct pollfd& sleep_event_poll = pollfds[0];
563 const struct pollfd& agent_control_sock_poll = pollfds[1];
564 const struct pollfd& control_sock_poll = pollfds[2];
565 const struct pollfd& adb_socket_poll = pollfds[3];
566 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
567 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
568 DCHECK(agent_loaded_);
569 char buf[257];
570 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
571 if (res < 0) {
572 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
573 continue;
574 } else {
575 buf[res + 1] = '\0';
576 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
577 }
578 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
579 agent_listening_ = true;
580 if (adb_connection_socket_ != -1) {
581 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
582 }
583 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
584 agent_listening_ = false;
585 } else if (memcmp(kHandshakeCompleteMessage, buf, sizeof(kHandshakeCompleteMessage)) == 0) {
586 if (agent_has_socket_) {
587 performed_handshake_ = true;
588 }
589 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
590 CloseFds();
591 agent_has_socket_ = false;
592 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
593 agent_has_socket_ = true;
594 sent_agent_fds_ = false;
595 // We will only ever do the handshake once so reset this.
596 performed_handshake_ = false;
597 } else {
598 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
599 }
600 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
601 if (!IsDebuggingPossible()) {
602 // For a profielable process, this path can execute when the adbd restarts.
603 control_ctx_.reset();
604 break;
605 }
606 bool maybe_send_fds = false;
607 {
608 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
609 ScopedEventFdLock sefdl(adb_write_event_fd_);
610 android::base::unique_fd new_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
611 if (new_fd == -1) {
612 // Something went wrong. We need to retry getting the control socket.
613 control_ctx_.reset();
614 break;
615 } else if (adb_connection_socket_ != -1) {
616 // We already have a connection.
617 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
618 if (new_fd >= 0) {
619 new_fd.reset();
620 }
621 } else {
622 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
623 adb_connection_socket_ = std::move(new_fd);
624 maybe_send_fds = true;
625 }
626 }
627 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
628 VLOG(jdwp) << "Sending fds as soon as we received them.";
629 // The agent was already loaded so this must be after a disconnection. Therefore have the
630 // transport perform the handshake.
631 SendAgentFds(/*require_handshake=*/ true);
632 }
633 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
634 // The other end of the adb connection just dropped it.
635 // Reset the connection since we don't have an active socket through the adb server.
636 // Note this path is expected for either debuggable or profileable processes.
637 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
638 << "connection active";
639 control_ctx_.reset();
640 break;
641 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
642 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
643 DCHECK(!agent_has_socket_);
644 if (!agent_loaded_) {
645 HandleDataWithoutAgent(self);
646 } else if (agent_listening_ && !sent_agent_fds_) {
647 VLOG(jdwp) << "Sending agent fds again on data.";
648 // Agent was already loaded so it can deal with the handshake.
649 SendAgentFds(/*require_handshake=*/ true);
650 }
651 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
652 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
653 DCHECK(!agent_has_socket_);
654 CloseFds();
655 } else {
656 VLOG(jdwp) << "Woke up poll without anything to do!";
657 }
658 }
659 }
660 }
661
ReadUint32AndAdvance(uint8_t ** in)662 static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
663 uint32_t res;
664 memcpy(&res, *in, sizeof(uint32_t));
665 *in = (*in) + sizeof(uint32_t);
666 return ntohl(res);
667 }
668
HandleDataWithoutAgent(art::Thread * self)669 void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
670 DCHECK(!agent_loaded_);
671 DCHECK(!agent_listening_);
672 // TODO Should we check in some other way if we are userdebug/eng?
673 CHECK(art::Dbg::IsJdwpAllowed());
674 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
675 if (!performed_handshake_) {
676 PerformHandshake();
677 return;
678 }
679 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
680 // to see if it's one we can handle. This doesn't change the state of the socket.
681 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
682 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
683 packet_header,
684 sizeof(packet_header),
685 MSG_PEEK));
686 // We want to be very careful not to change the socket state until we know we succeeded. This will
687 // let us fall-back to just loading the agent and letting it deal with everything.
688 if (res <= 0) {
689 // Close the socket. We either hit EOF or an error.
690 if (res < 0) {
691 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
692 }
693 CloseFds();
694 return;
695 } else if (res < static_cast<int>(kPacketHeaderLen)) {
696 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
697 AttachJdwpAgent(self);
698 return;
699 }
700 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
701 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
702 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
703 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
704 if (pkt_cmd_set != kDdmCommandSet ||
705 pkt_cmd != kDdmChunkCommand ||
706 full_len < kPacketHeaderLen) {
707 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
708 AttachJdwpAgent(self);
709 return;
710 }
711 uint32_t avail = -1;
712 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
713 if (res < 0) {
714 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
715 CloseFds();
716 return;
717 } else if (avail < full_len) {
718 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
719 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
720 << "Loading jdwp agent to deal with this.";
721 AttachJdwpAgent(self);
722 return;
723 }
724 // Actually read the data.
725 std::vector<uint8_t> full_pkt;
726 full_pkt.resize(full_len);
727 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
728 if (res < 0) {
729 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
730 CloseFds();
731 return;
732 }
733 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
734 size_t data_size = full_len - kPacketHeaderLen;
735 if (data_size < (sizeof(uint32_t) * 2)) {
736 // This is an error (the data isn't long enough) but to match historical behavior we need to
737 // ignore it.
738 return;
739 }
740 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
741 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
742 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
743 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
744 // This is an error (the data isn't long enough) but to match historical behavior we need to
745 // ignore it.
746 return;
747 }
748
749 if (!notified_ddm_active_) {
750 NotifyDdms(/*active=*/ true);
751 }
752 uint32_t reply_type;
753 std::vector<uint8_t> reply;
754 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
755 ddm_type,
756 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
757 ddm_len),
758 /*out*/&reply_type,
759 /*out*/&reply)) {
760 // To match historical behavior we don't send any response when there is no data to reply with.
761 return;
762 }
763 SendDdmPacket(pkt_id,
764 DdmPacketType::kReply,
765 reply_type,
766 art::ArrayRef<const uint8_t>(reply));
767 }
768
PerformHandshake()769 void AdbConnectionState::PerformHandshake() {
770 CHECK(!performed_handshake_);
771 // Check to make sure we are able to read the whole handshake.
772 uint32_t avail = -1;
773 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
774 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
775 if (res < 0) {
776 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
777 }
778 LOG(WARNING) << "Closing connection to broken client.";
779 CloseFds();
780 return;
781 }
782 // Perform the handshake.
783 char handshake_msg[sizeof(kJdwpHandshake)];
784 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
785 handshake_msg,
786 sizeof(handshake_msg),
787 MSG_DONTWAIT));
788 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
789 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
790 if (res < 0) {
791 PLOG(ERROR) << "Failed to read handshake!";
792 }
793 LOG(WARNING) << "Handshake failed!";
794 CloseFds();
795 return;
796 }
797 // Send the handshake back.
798 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
799 kJdwpHandshake,
800 sizeof(kJdwpHandshake),
801 0));
802 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
803 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
804 CloseFds();
805 return;
806 }
807 performed_handshake_ = true;
808 }
809
AttachJdwpAgent(art::Thread * self)810 void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
811 art::Runtime* runtime = art::Runtime::Current();
812 self->AssertNoPendingException();
813 runtime->AttachAgent(/* env= */ nullptr,
814 MakeAgentArg(),
815 /* class_loader= */ nullptr);
816 if (self->IsExceptionPending()) {
817 LOG(ERROR) << "Failed to load agent " << agent_name_;
818 art::ScopedObjectAccess soa(self);
819 self->GetException()->Dump();
820 self->ClearException();
821 return;
822 }
823 agent_loaded_ = true;
824 }
825
ContainsArgument(const std::string & opts,const char * arg)826 bool ContainsArgument(const std::string& opts, const char* arg) {
827 return opts.find(arg) != std::string::npos;
828 }
829
ValidateJdwpOptions(const std::string & opts)830 bool ValidateJdwpOptions(const std::string& opts) {
831 bool res = true;
832 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
833 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
834 // for the fd's to be passed down.
835 if (ContainsArgument(opts, "server=n")) {
836 res = false;
837 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
838 }
839 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
840 // everything.
841 if (ContainsArgument(opts, "suspend=y")) {
842 res = false;
843 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
844 }
845 return res;
846 }
847
MakeAgentArg()848 std::string AdbConnectionState::MakeAgentArg() {
849 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
850 DCHECK(ValidateJdwpOptions(opts));
851 // TODO Get agent_name_ from something user settable?
852 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
853 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
854 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
855 // we will add it if it wasn't already present for the convenience of the user.
856 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
857 // See the comment above for why we need to be suspend=n. Since the agent defaults to
858 // suspend=y we will add it if it wasn't already present.
859 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
860 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
861 }
862
StopDebuggerThreads()863 void AdbConnectionState::StopDebuggerThreads() {
864 // The regular agent system will take care of unloading the agent (if needed).
865 shutting_down_ = true;
866 // Wakeup the poll loop.
867 uint64_t data = 1;
868 if (sleep_event_fd_ != -1) {
869 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
870 }
871 }
872
873 // The plugin initialization function.
ArtPlugin_Initialize()874 extern "C" bool ArtPlugin_Initialize() {
875 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
876 // TODO Provide some way for apps to set this maybe?
877 gState.emplace(kDefaultJdwpAgentName);
878 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
879 }
880
ArtPlugin_Deinitialize()881 extern "C" bool ArtPlugin_Deinitialize() {
882 // We don't actually have to do anything here. The debugger (if one was
883 // attached) was shutdown by the move to the kDeath runtime phase and the
884 // adbconnection threads were shutdown by StopDebugger.
885 return true;
886 }
887
888 } // namespace adbconnection
889