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