blob: 80cfc83d3c3f85d2d401361458034bade6a37c32 [file] [log] [blame]
Alex Lightfbf96702017-12-14 13:27:13 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <array>
18
19#include "adbconnection.h"
20
21#include "android-base/endian.h"
22#include "android-base/stringprintf.h"
23#include "base/logging.h"
24#include "base/macros.h"
25#include "base/mutex.h"
26#include "java_vm_ext.h"
27#include "jni_env_ext.h"
28#include "mirror/throwable.h"
29#include "nativehelper/ScopedLocalRef.h"
30#include "runtime-inl.h"
31#include "runtime_callbacks.h"
32#include "scoped_thread_state_change-inl.h"
33#include "well_known_classes.h"
34
35#include "jdwp/jdwp_priv.h"
36
37#include "fd_transport.h"
38
39#include "poll.h"
40
41#ifdef ART_TARGET_ANDROID
42#include "cutils/sockets.h"
43#endif
44
45#include <sys/socket.h>
46#include <sys/un.h>
47#include <sys/eventfd.h>
48#include <jni.h>
49
50namespace adbconnection {
51
52using dt_fd_forward::kListenStartMessage;
53using dt_fd_forward::kListenEndMessage;
54using dt_fd_forward::kAcceptMessage;
55using dt_fd_forward::kCloseMessage;
56
57using android::base::StringPrintf;
58
59static constexpr int kEventfdLocked = 0;
60static constexpr int kEventfdUnlocked = 1;
61static constexpr int kControlSockSendTimeout = 10;
62
63static AdbConnectionState* gState;
64
65static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080066 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080067}
68
69// Begin running the debugger.
70void AdbConnectionDebuggerController::StartDebugger() {
71 if (IsDebuggingPossible()) {
72 connection_->StartDebuggerThreads();
73 } else {
74 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
75 }
76}
77
78// The debugger should begin shutting down since the runtime is ending. We don't actually do
79// anything here. The real shutdown has already happened as far as the agent is concerned.
80void AdbConnectionDebuggerController::StopDebugger() { }
81
82bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
83 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
84}
85
86void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
87 const art::ArrayRef<const uint8_t>& data) {
88 connection_->PublishDdmData(type, data);
89}
90
91class ScopedEventFdLock {
92 public:
93 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
94 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
95 }
96
97 ~ScopedEventFdLock() {
98 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
99 }
100
101 private:
102 int fd_;
103 uint64_t data_;
104};
105
106AdbConnectionState::AdbConnectionState(const std::string& agent_name)
107 : agent_name_(agent_name),
108 controller_(this),
109 ddm_callback_(this),
110 sleep_event_fd_(-1),
111 control_sock_(-1),
112 local_agent_control_sock_(-1),
113 remote_agent_control_sock_(-1),
114 adb_connection_socket_(-1),
115 adb_write_event_fd_(-1),
116 shutting_down_(false),
117 agent_loaded_(false),
118 agent_listening_(false),
119 next_ddm_id_(1) {
120 // Setup the addr.
121 control_addr_.controlAddrUn.sun_family = AF_UNIX;
122 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
123 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
124
125 // Add the startup callback.
126 art::ScopedObjectAccess soa(art::Thread::Current());
127 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
128}
129
130static jobject CreateAdbConnectionThread(art::Thread* thr) {
131 JNIEnv* env = thr->GetJniEnv();
132 // Move to native state to talk with the jnienv api.
133 art::ScopedThreadStateChange stsc(thr, art::kNative);
134 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
135 ScopedLocalRef<jobject> thr_group(
136 env,
137 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
138 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
139 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
140 art::WellKnownClasses::java_lang_Thread_init,
141 thr_group.get(),
142 thr_name.get(),
143 /*Priority*/ 0,
144 /*Daemon*/ true);
145}
146
147struct CallbackData {
148 AdbConnectionState* this_;
149 jobject thr_;
150};
151
152static void* CallbackFunction(void* vdata) {
153 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
154 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
155 true,
156 data->thr_);
157 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
158 // The name in Attach() is only for logging. Set the thread name. This is important so
159 // that the thread is no longer seen as starting up.
160 {
161 art::ScopedObjectAccess soa(self);
162 self->SetThreadName(kAdbConnectionThreadName);
163 }
164
165 // Release the peer.
166 JNIEnv* env = self->GetJniEnv();
167 env->DeleteGlobalRef(data->thr_);
168 data->thr_ = nullptr;
169 {
170 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
171 // before going into the provided code.
172 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
173 art::Runtime::Current()->EndThreadBirth();
174 }
175 data->this_->RunPollLoop(self);
176 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
177 CHECK_EQ(detach_result, 0);
178
179 return nullptr;
180}
181
182void AdbConnectionState::StartDebuggerThreads() {
183 // First do all the final setup we need.
184 CHECK_EQ(adb_write_event_fd_.get(), -1);
185 CHECK_EQ(sleep_event_fd_.get(), -1);
186 CHECK_EQ(local_agent_control_sock_.get(), -1);
187 CHECK_EQ(remote_agent_control_sock_.get(), -1);
188
189 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
190 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
191 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
192 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
193
194 {
195 art::ScopedObjectAccess soa(art::Thread::Current());
196 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
197 }
198 // Setup the socketpair we use to talk to the agent.
199 bool has_sockets;
200 do {
201 has_sockets = android::base::Socketpair(AF_UNIX,
202 SOCK_SEQPACKET | SOCK_CLOEXEC,
203 0,
204 &local_agent_control_sock_,
205 &remote_agent_control_sock_);
206 } while (!has_sockets && errno == EINTR);
207 if (!has_sockets) {
208 PLOG(FATAL) << "Unable to create socketpair for agent control!";
209 }
210
211 // Next start the threads.
212 art::Thread* self = art::Thread::Current();
213 art::ScopedObjectAccess soa(self);
214 {
215 art::Runtime* runtime = art::Runtime::Current();
216 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
217 if (runtime->IsShuttingDownLocked()) {
218 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
219 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
220 return;
221 }
222 runtime->StartThreadBirth();
223 }
224 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
225 pthread_t pthread;
226 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
227 int pthread_create_result = pthread_create(&pthread,
228 nullptr,
229 &CallbackFunction,
230 data.get());
231 if (pthread_create_result != 0) {
232 // If the create succeeded the other thread will call EndThreadBirth.
233 art::Runtime* runtime = art::Runtime::Current();
234 soa.Env()->DeleteGlobalRef(data->thr_);
235 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
236 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
237 runtime->EndThreadBirth();
238 return;
239 }
240 data.release();
241}
242
243static bool FlagsSet(int16_t data, int16_t flags) {
244 return (data & flags) == flags;
245}
246
247void AdbConnectionState::CloseFds() {
248 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is closed.
249 ScopedEventFdLock lk(adb_write_event_fd_);
250 // shutdown(adb_connection_socket_, SHUT_RDWR);
251 adb_connection_socket_.reset();
252}
253
254uint32_t AdbConnectionState::NextDdmId() {
255 // Just have a normal counter but always set the sign bit.
256 return (next_ddm_id_++) | 0x80000000;
257}
258
259void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
260 // Get the write_event early to fail fast.
261 ScopedEventFdLock lk(adb_write_event_fd_);
262 if (adb_connection_socket_ == -1) {
263 LOG(WARNING) << "Not sending ddms data of type "
264 << StringPrintf("%c%c%c%c",
265 static_cast<char>(type >> 24),
266 static_cast<char>(type >> 16),
267 static_cast<char>(type >> 8),
268 static_cast<char>(type)) << " due to no connection!";
269 // Adb is not connected.
270 return;
271 }
272
273 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
274 // after we have sent our data.
275 static constexpr uint32_t kDdmPacketHeaderSize =
276 kJDWPHeaderLen // jdwp command packet size
277 + sizeof(uint32_t) // Type
278 + sizeof(uint32_t); // length
279 std::array<uint8_t, kDdmPacketHeaderSize> pkt;
280 uint8_t* pkt_data = pkt.data();
281
282 // Write the length first.
283 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
284 pkt_data += sizeof(uint32_t);
285
286 // Write the id next;
287 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(NextDdmId());
288 pkt_data += sizeof(uint32_t);
289
290 // next the flags. (0 for cmd packet because DDMS).
291 *(pkt_data++) = 0;
292 // Now the cmd-set
293 *(pkt_data++) = kJDWPDdmCmdSet;
294 // Now the command
295 *(pkt_data++) = kJDWPDdmCmd;
296
297 // now the type.
298 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(type);
299 pkt_data += sizeof(uint32_t);
300
301 // Now the data.size()
302 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(data.size());
303 pkt_data += sizeof(uint32_t);
304
305 static uint32_t constexpr kIovSize = 2;
306 struct iovec iovs[kIovSize] = {
307 { pkt.data(), pkt.size() },
308 { const_cast<uint8_t*>(data.data()), data.size() },
309 };
310 // now pkt_header has the header.
311 // use writev to send the actual data.
312 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
313 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
314 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
315 static_cast<char>(type >> 24),
316 static_cast<char>(type >> 16),
317 static_cast<char>(type >> 8),
318 static_cast<char>(type),
319 res, data.size() + kDdmPacketHeaderSize);
320 } else {
321 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
322 static_cast<char>(type >> 24),
323 static_cast<char>(type >> 16),
324 static_cast<char>(type >> 8),
325 static_cast<char>(type),
326 data.size() + kDdmPacketHeaderSize);
327 }
328}
329
330void AdbConnectionState::SendAgentFds() {
331 // TODO
332 DCHECK(!sent_agent_fds_);
333 char dummy = '!';
334 union {
335 cmsghdr cm;
336 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
337 } cm_un;
338 iovec iov;
339 iov.iov_base = &dummy;
340 iov.iov_len = 1;
341
342 msghdr msg;
343 msg.msg_name = nullptr;
344 msg.msg_namelen = 0;
345 msg.msg_iov = &iov;
346 msg.msg_iovlen = 1;
347 msg.msg_flags = 0;
348 msg.msg_control = cm_un.buffer;
349 msg.msg_controllen = sizeof(cm_un.buffer);
350
351 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
352 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
353 cmsg->cmsg_level = SOL_SOCKET;
354 cmsg->cmsg_type = SCM_RIGHTS;
355
356 // Duplicate the fds before sending them.
357 android::base::unique_fd read_fd(dup(adb_connection_socket_));
358 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
359 android::base::unique_fd write_fd(dup(adb_connection_socket_));
360 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
361 android::base::unique_fd write_lock_fd(dup(adb_write_event_fd_));
362 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
363
364 dt_fd_forward::FdSet {
365 read_fd.get(), write_fd.get(), write_lock_fd.get()
366 }.WriteData(CMSG_DATA(cmsg));
367
368 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
369 if (res < 0) {
370 PLOG(ERROR) << "Failed to send agent adb connection fds.";
371 } else {
372 sent_agent_fds_ = true;
373 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
374 }
375}
376
377android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
378 // We don't actually care about the data that is sent. We do need to receive something though.
379 char dummy = '!';
380 union {
381 cmsghdr cm;
382 char buffer[CMSG_SPACE(sizeof(int))];
383 } cm_un;
384
385 iovec iov;
386 iov.iov_base = &dummy;
387 iov.iov_len = 1;
388
389 msghdr msg;
390 msg.msg_name = nullptr;
391 msg.msg_namelen = 0;
392 msg.msg_iov = &iov;
393 msg.msg_iovlen = 1;
394 msg.msg_flags = 0;
395 msg.msg_control = cm_un.buffer;
396 msg.msg_controllen = sizeof(cm_un.buffer);
397
398 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
399 cmsg->cmsg_len = msg.msg_controllen;
400 cmsg->cmsg_level = SOL_SOCKET;
401 cmsg->cmsg_type = SCM_RIGHTS;
402 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
403
404 int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0));
405
406 if (rc <= 0) {
407 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")";
408 return android::base::unique_fd(-1);
409 } else {
410 VLOG(jdwp) << "Fds have been received from ADB!";
411 }
412
413 return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
414}
415
416bool AdbConnectionState::SetupAdbConnection() {
417 int sleep_ms = 500;
418 const int sleep_max_ms = 2*1000;
419 char buff[sizeof(pid_t) + 1];
420
421 android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET, 0));
422 if (sock < 0) {
423 PLOG(ERROR) << "Could not create ADB control socket";
424 return false;
425 }
426 struct timeval timeout;
427 timeout.tv_sec = kControlSockSendTimeout;
428 timeout.tv_usec = 0;
429 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
430 snprintf(buff, sizeof(buff), "%04x", getpid());
431 buff[sizeof(pid_t)] = 0;
432
433 while (!shutting_down_) {
434 // If adbd isn't running, because USB debugging was disabled or
435 // perhaps the system is restarting it for "adb root", the
436 // connect() will fail. We loop here forever waiting for it
437 // to come back.
438 //
439 // Waking up and polling every couple of seconds is generally a
440 // bad thing to do, but we only do this if the application is
441 // debuggable *and* adbd isn't running. Still, for the sake
442 // of battery life, we should consider timing out and giving
443 // up after a few minutes in case somebody ships an app with
444 // the debuggable flag set.
445 int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
446 if (ret == 0) {
447 bool trusted = sock >= 0;
448#ifdef ART_TARGET_ANDROID
449 // Needed for socket_peer_is_trusted.
450 trusted = trusted && socket_peer_is_trusted(sock);
451#endif
452 if (!trusted) {
453 LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
454 if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
455 PLOG(ERROR) << "trouble shutting down socket";
456 }
457 return false;
458 }
459 /* now try to send our pid to the ADB daemon */
460 ret = TEMP_FAILURE_RETRY(send(sock, buff, sizeof(pid_t), 0));
461 if (ret == sizeof(pid_t)) {
462 LOG(INFO) << "PID " << getpid() << " send to adb";
463 control_sock_ = std::move(sock);
464 return true;
465 } else {
466 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
467 return false;
468 }
469 } else {
470 PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
471
472 usleep(sleep_ms * 1000);
473
474 sleep_ms += (sleep_ms >> 1);
475 if (sleep_ms > sleep_max_ms) {
476 sleep_ms = sleep_max_ms;
477 }
478 }
479 }
480 return false;
481}
482
483void AdbConnectionState::RunPollLoop(art::Thread* self) {
484 CHECK_EQ(self->GetState(), art::kNative);
485 art::Locks::mutator_lock_->AssertNotHeld(self);
486 self->SetState(art::kWaitingInMainDebuggerLoop);
487 // shutting_down_ set by StopDebuggerThreads
488 while (!shutting_down_) {
489 // First get the control_sock_ from adb if we don't have one. We only need to do this once.
490 if (control_sock_ == -1 && !SetupAdbConnection()) {
491 LOG(ERROR) << "Failed to setup adb connection.";
492 return;
493 }
494 while (!shutting_down_ && control_sock_ != -1) {
495 struct pollfd pollfds[4] = {
496 { sleep_event_fd_, POLLIN, 0 },
497 // -1 as an fd causes it to be ignored by poll
498 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
499 // Check for the control_sock_ actually going away. Only do this if we don't have an active
500 // connection.
501 { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
502 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
503 // have a real connection yet or the socket through adb needs to be listened to for incoming
504 // data that the agent can handle.
505 { ((!agent_has_socket_ && !sent_agent_fds_) ? adb_connection_socket_ : -1), POLLIN, 0 }
506 };
507 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
508 if (res < 0) {
509 PLOG(ERROR) << "Failed to poll!";
510 return;
511 }
512 // We don't actually care about doing this we just use it to wake us up.
513 // const struct pollfd& sleep_event_poll = pollfds[0];
514 const struct pollfd& agent_control_sock_poll = pollfds[1];
515 const struct pollfd& control_sock_poll = pollfds[2];
516 const struct pollfd& adb_socket_poll = pollfds[3];
517 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
518 DCHECK(agent_loaded_);
519 char buf[257];
520 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
521 if (res < 0) {
522 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
523 continue;
524 } else {
525 buf[res + 1] = '\0';
526 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
527 }
528 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
529 agent_listening_ = true;
530 if (adb_connection_socket_ != -1) {
531 SendAgentFds();
532 }
533 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
534 agent_listening_ = false;
535 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
536 CloseFds();
537 agent_has_socket_ = false;
538 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
539 agent_has_socket_ = true;
540 sent_agent_fds_ = false;
541 } else {
542 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
543 }
544 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
545 bool maybe_send_fds = false;
546 {
547 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
548 ScopedEventFdLock sefdl(adb_write_event_fd_);
549 android::base::unique_fd new_fd(ReadFdFromAdb());
550 if (new_fd == -1) {
551 // Something went wrong. We need to retry getting the control socket.
552 PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!";
553 control_sock_.reset();
554 break;
555 } else if (adb_connection_socket_ != -1) {
556 // We already have a connection.
557 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
558 if (new_fd >= 0) {
559 new_fd.reset();
560 }
561 } else {
562 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
563 adb_connection_socket_ = std::move(new_fd);
564 maybe_send_fds = true;
565 }
566 }
567 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
568 VLOG(jdwp) << "Sending fds as soon as we received them.";
569 SendAgentFds();
570 }
571 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
572 // The other end of the adb connection just dropped it.
573 // Reset the connection since we don't have an active socket through the adb server.
574 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
575 << "connection active";
576 control_sock_.reset();
577 break;
578 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
579 DCHECK(!agent_has_socket_);
580 if (!agent_loaded_) {
581 DCHECK(!agent_listening_);
Alex Light2ce6fc82017-12-18 16:42:36 -0800582 // TODO Should we check in some other way if we are userdebug/eng?
583 CHECK(art::Dbg::IsJdwpAllowed());
Alex Lightfbf96702017-12-14 13:27:13 -0800584 // Load the agent now!
585 self->AssertNoPendingException();
Andreas Gampe7b38e692017-12-28 19:18:28 -0800586 art::Runtime::Current()->AttachAgent(/* JNIEnv* */ nullptr,
587 MakeAgentArg(),
Alex Light2ce6fc82017-12-18 16:42:36 -0800588 /* classloader */ nullptr,
589 /*allow_non_debuggable_tooling*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800590 if (self->IsExceptionPending()) {
591 LOG(ERROR) << "Failed to load agent " << agent_name_;
592 art::ScopedObjectAccess soa(self);
593 self->GetException()->Dump();
594 self->ClearException();
595 return;
596 }
597 agent_loaded_ = true;
598 } else if (agent_listening_ && !sent_agent_fds_) {
599 VLOG(jdwp) << "Sending agent fds again on data.";
600 SendAgentFds();
601 }
602 } else {
603 VLOG(jdwp) << "Woke up poll without anything to do!";
604 }
605 }
606 }
607}
608
609std::string AdbConnectionState::MakeAgentArg() {
610 // TODO Get this from something user settable?
611 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
612 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",")
613 + "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
614}
615
616void AdbConnectionState::StopDebuggerThreads() {
617 // The regular agent system will take care of unloading the agent (if needed).
618 shutting_down_ = true;
619 // Wakeup the poll loop.
620 uint64_t data = 1;
621 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
622}
623
624// The plugin initialization function.
625extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
626 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
627 // TODO Provide some way for apps to set this maybe?
628 gState = new AdbConnectionState(kDefaultJdwpAgentName);
629 CHECK(gState != nullptr);
630 return true;
631}
632
633extern "C" bool ArtPlugin_Deinitialize() {
634 CHECK(gState != nullptr);
635 // Just do this a second time?
636 // TODO I don't think this should be needed.
637 gState->StopDebuggerThreads();
638 delete gState;
639 return true;
640}
641
642} // namespace adbconnection