blob: 1b907b792b3ee257e71431547b2046e1e6c8f835 [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"
Elliott Hughesc2efd4d2018-10-25 13:14:55 -070026#include "base/socket_peer_is_trusted.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010027#include "jni/java_vm_ext.h"
28#include "jni/jni_env_ext.h"
Alex Lightfbf96702017-12-14 13:27:13 -080029#include "mirror/throwable.h"
30#include "nativehelper/ScopedLocalRef.h"
31#include "runtime-inl.h"
32#include "runtime_callbacks.h"
33#include "scoped_thread_state_change-inl.h"
34#include "well_known_classes.h"
35
36#include "jdwp/jdwp_priv.h"
37
38#include "fd_transport.h"
39
40#include "poll.h"
41
Alex Light15b81132018-01-24 13:29:07 -080042#include <sys/ioctl.h>
Alex Lightfbf96702017-12-14 13:27:13 -080043#include <sys/socket.h>
44#include <sys/un.h>
45#include <sys/eventfd.h>
46#include <jni.h>
47
48namespace adbconnection {
49
Alex Light15b81132018-01-24 13:29:07 -080050// Messages sent from the transport
Alex Lightfbf96702017-12-14 13:27:13 -080051using dt_fd_forward::kListenStartMessage;
52using dt_fd_forward::kListenEndMessage;
53using dt_fd_forward::kAcceptMessage;
54using dt_fd_forward::kCloseMessage;
55
Alex Light15b81132018-01-24 13:29:07 -080056// Messages sent to the transport
57using dt_fd_forward::kPerformHandshakeMessage;
58using dt_fd_forward::kSkipHandshakeMessage;
59
Alex Lightfbf96702017-12-14 13:27:13 -080060using android::base::StringPrintf;
61
Alex Light15b81132018-01-24 13:29:07 -080062static constexpr const char kJdwpHandshake[14] = {
63 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
64};
65
Alex Lightfbf96702017-12-14 13:27:13 -080066static constexpr int kEventfdLocked = 0;
67static constexpr int kEventfdUnlocked = 1;
68static constexpr int kControlSockSendTimeout = 10;
69
Alex Light15b81132018-01-24 13:29:07 -080070static constexpr size_t kPacketHeaderLen = 11;
71static constexpr off_t kPacketSizeOff = 0;
72static constexpr off_t kPacketIdOff = 4;
73static constexpr off_t kPacketCommandSetOff = 9;
74static constexpr off_t kPacketCommandOff = 10;
75
76static constexpr uint8_t kDdmCommandSet = 199;
77static constexpr uint8_t kDdmChunkCommand = 1;
78
Alex Lightfbf96702017-12-14 13:27:13 -080079static AdbConnectionState* gState;
80
81static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080082 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080083}
84
85// Begin running the debugger.
86void AdbConnectionDebuggerController::StartDebugger() {
87 if (IsDebuggingPossible()) {
88 connection_->StartDebuggerThreads();
89 } else {
90 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
91 }
92}
93
94// The debugger should begin shutting down since the runtime is ending. We don't actually do
95// anything here. The real shutdown has already happened as far as the agent is concerned.
96void AdbConnectionDebuggerController::StopDebugger() { }
97
98bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
99 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
100}
101
102void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
103 const art::ArrayRef<const uint8_t>& data) {
104 connection_->PublishDdmData(type, data);
105}
106
107class ScopedEventFdLock {
108 public:
109 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
110 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
111 }
112
113 ~ScopedEventFdLock() {
114 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
115 }
116
117 private:
118 int fd_;
119 uint64_t data_;
120};
121
122AdbConnectionState::AdbConnectionState(const std::string& agent_name)
123 : agent_name_(agent_name),
124 controller_(this),
125 ddm_callback_(this),
126 sleep_event_fd_(-1),
127 control_sock_(-1),
128 local_agent_control_sock_(-1),
129 remote_agent_control_sock_(-1),
130 adb_connection_socket_(-1),
131 adb_write_event_fd_(-1),
132 shutting_down_(false),
133 agent_loaded_(false),
134 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800135 agent_has_socket_(false),
136 sent_agent_fds_(false),
137 performed_handshake_(false),
138 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800139 next_ddm_id_(1),
140 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800141 // Setup the addr.
142 control_addr_.controlAddrUn.sun_family = AF_UNIX;
143 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
144 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
145
146 // Add the startup callback.
147 art::ScopedObjectAccess soa(art::Thread::Current());
148 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
149}
150
151static jobject CreateAdbConnectionThread(art::Thread* thr) {
152 JNIEnv* env = thr->GetJniEnv();
153 // Move to native state to talk with the jnienv api.
154 art::ScopedThreadStateChange stsc(thr, art::kNative);
155 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
156 ScopedLocalRef<jobject> thr_group(
157 env,
158 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
159 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
160 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
161 art::WellKnownClasses::java_lang_Thread_init,
162 thr_group.get(),
163 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700164 /*Priority=*/ 0,
165 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800166}
167
168struct CallbackData {
169 AdbConnectionState* this_;
170 jobject thr_;
171};
172
173static void* CallbackFunction(void* vdata) {
174 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
Alex Lightd6f9d852018-01-25 11:26:28 -0800175 CHECK(data->this_ == gState);
Alex Lightfbf96702017-12-14 13:27:13 -0800176 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
177 true,
178 data->thr_);
179 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
180 // The name in Attach() is only for logging. Set the thread name. This is important so
181 // that the thread is no longer seen as starting up.
182 {
183 art::ScopedObjectAccess soa(self);
184 self->SetThreadName(kAdbConnectionThreadName);
185 }
186
187 // Release the peer.
188 JNIEnv* env = self->GetJniEnv();
189 env->DeleteGlobalRef(data->thr_);
190 data->thr_ = nullptr;
191 {
192 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
193 // before going into the provided code.
194 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
195 art::Runtime::Current()->EndThreadBirth();
196 }
197 data->this_->RunPollLoop(self);
198 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
199 CHECK_EQ(detach_result, 0);
200
Alex Lightd6f9d852018-01-25 11:26:28 -0800201 // Get rid of the connection
202 gState = nullptr;
203 delete data->this_;
204
Alex Lightfbf96702017-12-14 13:27:13 -0800205 return nullptr;
206}
207
208void AdbConnectionState::StartDebuggerThreads() {
209 // First do all the final setup we need.
210 CHECK_EQ(adb_write_event_fd_.get(), -1);
211 CHECK_EQ(sleep_event_fd_.get(), -1);
212 CHECK_EQ(local_agent_control_sock_.get(), -1);
213 CHECK_EQ(remote_agent_control_sock_.get(), -1);
214
215 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
216 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
217 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
218 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
219
220 {
221 art::ScopedObjectAccess soa(art::Thread::Current());
222 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
223 }
224 // Setup the socketpair we use to talk to the agent.
225 bool has_sockets;
226 do {
227 has_sockets = android::base::Socketpair(AF_UNIX,
228 SOCK_SEQPACKET | SOCK_CLOEXEC,
229 0,
230 &local_agent_control_sock_,
231 &remote_agent_control_sock_);
232 } while (!has_sockets && errno == EINTR);
233 if (!has_sockets) {
234 PLOG(FATAL) << "Unable to create socketpair for agent control!";
235 }
236
237 // Next start the threads.
238 art::Thread* self = art::Thread::Current();
239 art::ScopedObjectAccess soa(self);
240 {
241 art::Runtime* runtime = art::Runtime::Current();
242 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
243 if (runtime->IsShuttingDownLocked()) {
244 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
245 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
246 return;
247 }
248 runtime->StartThreadBirth();
249 }
250 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
251 pthread_t pthread;
252 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800253 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800254 int pthread_create_result = pthread_create(&pthread,
255 nullptr,
256 &CallbackFunction,
257 data.get());
258 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800259 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800260 // If the create succeeded the other thread will call EndThreadBirth.
261 art::Runtime* runtime = art::Runtime::Current();
262 soa.Env()->DeleteGlobalRef(data->thr_);
263 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
264 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
265 runtime->EndThreadBirth();
266 return;
267 }
268 data.release();
269}
270
271static bool FlagsSet(int16_t data, int16_t flags) {
272 return (data & flags) == flags;
273}
274
275void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800276 {
277 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
278 // closed.
279 ScopedEventFdLock lk(adb_write_event_fd_);
280 // shutdown(adb_connection_socket_, SHUT_RDWR);
281 adb_connection_socket_.reset();
282 }
283
284 // If we didn't load anything we will need to do the handshake again.
285 performed_handshake_ = false;
286
287 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
288 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700289 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800290 }
291}
292
293void AdbConnectionState::NotifyDdms(bool active) {
294 art::ScopedObjectAccess soa(art::Thread::Current());
295 DCHECK_NE(notified_ddm_active_, active);
296 notified_ddm_active_ = active;
297 if (active) {
298 art::Dbg::DdmConnected();
299 } else {
300 art::Dbg::DdmDisconnected();
301 }
Alex Lightfbf96702017-12-14 13:27:13 -0800302}
303
304uint32_t AdbConnectionState::NextDdmId() {
305 // Just have a normal counter but always set the sign bit.
306 return (next_ddm_id_++) | 0x80000000;
307}
308
309void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800310 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
311}
312
313void AdbConnectionState::SendDdmPacket(uint32_t id,
314 DdmPacketType packet_type,
315 uint32_t type,
316 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800317 // Get the write_event early to fail fast.
318 ScopedEventFdLock lk(adb_write_event_fd_);
319 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800320 VLOG(jdwp) << "Not sending ddms data of type "
321 << StringPrintf("%c%c%c%c",
322 static_cast<char>(type >> 24),
323 static_cast<char>(type >> 16),
324 static_cast<char>(type >> 8),
325 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800326 // Adb is not connected.
327 return;
328 }
329
330 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
331 // after we have sent our data.
332 static constexpr uint32_t kDdmPacketHeaderSize =
333 kJDWPHeaderLen // jdwp command packet size
334 + sizeof(uint32_t) // Type
335 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800336 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800337 uint8_t* pkt_data = pkt.data();
338
339 // Write the length first.
340 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
341 pkt_data += sizeof(uint32_t);
342
343 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800344 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800345 pkt_data += sizeof(uint32_t);
346
347 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800348 *(pkt_data++) = static_cast<uint8_t>(packet_type);
349 switch (packet_type) {
350 case DdmPacketType::kCmd: {
351 // Now the cmd-set
352 *(pkt_data++) = kJDWPDdmCmdSet;
353 // Now the command
354 *(pkt_data++) = kJDWPDdmCmd;
355 break;
356 }
357 case DdmPacketType::kReply: {
358 // This is the error code bytes which are all 0
359 *(pkt_data++) = 0;
360 *(pkt_data++) = 0;
361 }
362 }
Alex Lightfbf96702017-12-14 13:27:13 -0800363
Alex Light15b81132018-01-24 13:29:07 -0800364 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800365 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800366 uint32_t net_type = htonl(type);
367 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800368 pkt_data += sizeof(uint32_t);
369
370 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800371 uint32_t net_len = htonl(data.size());
372 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800373 pkt_data += sizeof(uint32_t);
374
375 static uint32_t constexpr kIovSize = 2;
376 struct iovec iovs[kIovSize] = {
377 { pkt.data(), pkt.size() },
378 { const_cast<uint8_t*>(data.data()), data.size() },
379 };
380 // now pkt_header has the header.
381 // use writev to send the actual data.
382 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
383 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
384 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
385 static_cast<char>(type >> 24),
386 static_cast<char>(type >> 16),
387 static_cast<char>(type >> 8),
388 static_cast<char>(type),
389 res, data.size() + kDdmPacketHeaderSize);
390 } else {
391 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
392 static_cast<char>(type >> 24),
393 static_cast<char>(type >> 16),
394 static_cast<char>(type >> 8),
395 static_cast<char>(type),
396 data.size() + kDdmPacketHeaderSize);
397 }
398}
399
Alex Light15b81132018-01-24 13:29:07 -0800400void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800401 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800402 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800403 union {
404 cmsghdr cm;
405 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
406 } cm_un;
407 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800408 iov.iov_base = const_cast<char*>(message);
409 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800410
411 msghdr msg;
412 msg.msg_name = nullptr;
413 msg.msg_namelen = 0;
414 msg.msg_iov = &iov;
415 msg.msg_iovlen = 1;
416 msg.msg_flags = 0;
417 msg.msg_control = cm_un.buffer;
418 msg.msg_controllen = sizeof(cm_un.buffer);
419
420 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
421 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
422 cmsg->cmsg_level = SOL_SOCKET;
423 cmsg->cmsg_type = SCM_RIGHTS;
424
425 // Duplicate the fds before sending them.
426 android::base::unique_fd read_fd(dup(adb_connection_socket_));
427 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
428 android::base::unique_fd write_fd(dup(adb_connection_socket_));
429 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
430 android::base::unique_fd write_lock_fd(dup(adb_write_event_fd_));
431 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
432
433 dt_fd_forward::FdSet {
434 read_fd.get(), write_fd.get(), write_lock_fd.get()
435 }.WriteData(CMSG_DATA(cmsg));
436
437 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
438 if (res < 0) {
439 PLOG(ERROR) << "Failed to send agent adb connection fds.";
440 } else {
441 sent_agent_fds_ = true;
442 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
443 }
444}
445
446android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
447 // We don't actually care about the data that is sent. We do need to receive something though.
448 char dummy = '!';
449 union {
450 cmsghdr cm;
451 char buffer[CMSG_SPACE(sizeof(int))];
452 } cm_un;
453
454 iovec iov;
455 iov.iov_base = &dummy;
456 iov.iov_len = 1;
457
458 msghdr msg;
459 msg.msg_name = nullptr;
460 msg.msg_namelen = 0;
461 msg.msg_iov = &iov;
462 msg.msg_iovlen = 1;
463 msg.msg_flags = 0;
464 msg.msg_control = cm_un.buffer;
465 msg.msg_controllen = sizeof(cm_un.buffer);
466
467 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
468 cmsg->cmsg_len = msg.msg_controllen;
469 cmsg->cmsg_level = SOL_SOCKET;
470 cmsg->cmsg_type = SCM_RIGHTS;
471 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
472
473 int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0));
474
475 if (rc <= 0) {
476 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")";
477 return android::base::unique_fd(-1);
478 } else {
479 VLOG(jdwp) << "Fds have been received from ADB!";
480 }
481
482 return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
483}
484
485bool AdbConnectionState::SetupAdbConnection() {
486 int sleep_ms = 500;
487 const int sleep_max_ms = 2*1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800488
Alex Light54f535a2018-06-04 14:14:19 -0700489 android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
Alex Lightfbf96702017-12-14 13:27:13 -0800490 if (sock < 0) {
491 PLOG(ERROR) << "Could not create ADB control socket";
492 return false;
493 }
494 struct timeval timeout;
495 timeout.tv_sec = kControlSockSendTimeout;
496 timeout.tv_usec = 0;
497 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
Josh Gao4b49bb72018-02-12 15:06:42 -0800498 int32_t pid = getpid();
Alex Lightfbf96702017-12-14 13:27:13 -0800499
500 while (!shutting_down_) {
501 // If adbd isn't running, because USB debugging was disabled or
502 // perhaps the system is restarting it for "adb root", the
503 // connect() will fail. We loop here forever waiting for it
504 // to come back.
505 //
506 // Waking up and polling every couple of seconds is generally a
507 // bad thing to do, but we only do this if the application is
508 // debuggable *and* adbd isn't running. Still, for the sake
509 // of battery life, we should consider timing out and giving
510 // up after a few minutes in case somebody ships an app with
511 // the debuggable flag set.
512 int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
513 if (ret == 0) {
Elliott Hughesc2efd4d2018-10-25 13:14:55 -0700514 bool trusted = sock >= 0 && art::SocketPeerIsTrusted(sock);
Alex Lightfbf96702017-12-14 13:27:13 -0800515 if (!trusted) {
516 LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
517 if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
518 PLOG(ERROR) << "trouble shutting down socket";
519 }
520 return false;
521 }
522 /* now try to send our pid to the ADB daemon */
Josh Gao4b49bb72018-02-12 15:06:42 -0800523 ret = TEMP_FAILURE_RETRY(send(sock, &pid, sizeof(pid), 0));
524 if (ret == sizeof(pid)) {
525 VLOG(jdwp) << "PID " << pid << " sent to adb";
Alex Lightfbf96702017-12-14 13:27:13 -0800526 control_sock_ = std::move(sock);
527 return true;
528 } else {
529 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
530 return false;
531 }
532 } else {
Alex Lightd9258672018-02-12 14:47:16 -0800533 if (VLOG_IS_ON(jdwp)) {
534 PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
535 }
Alex Lightfbf96702017-12-14 13:27:13 -0800536
537 usleep(sleep_ms * 1000);
538
539 sleep_ms += (sleep_ms >> 1);
540 if (sleep_ms > sleep_max_ms) {
541 sleep_ms = sleep_max_ms;
542 }
543 }
544 }
545 return false;
546}
547
548void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800549 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800550 CHECK_EQ(self->GetState(), art::kNative);
Yi Konge11d50f2018-01-09 16:55:04 -0800551 // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
552 // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
553 // http://b/71769596
554 // art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800555 self->SetState(art::kWaitingInMainDebuggerLoop);
556 // shutting_down_ set by StopDebuggerThreads
557 while (!shutting_down_) {
558 // First get the control_sock_ from adb if we don't have one. We only need to do this once.
559 if (control_sock_ == -1 && !SetupAdbConnection()) {
560 LOG(ERROR) << "Failed to setup adb connection.";
561 return;
562 }
563 while (!shutting_down_ && control_sock_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800564 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800565 struct pollfd pollfds[4] = {
566 { sleep_event_fd_, POLLIN, 0 },
567 // -1 as an fd causes it to be ignored by poll
568 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
569 // Check for the control_sock_ actually going away. Only do this if we don't have an active
570 // connection.
571 { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
572 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
573 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800574 // data that the agent or this plugin can handle.
575 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800576 };
577 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
578 if (res < 0) {
579 PLOG(ERROR) << "Failed to poll!";
580 return;
581 }
582 // We don't actually care about doing this we just use it to wake us up.
583 // const struct pollfd& sleep_event_poll = pollfds[0];
584 const struct pollfd& agent_control_sock_poll = pollfds[1];
585 const struct pollfd& control_sock_poll = pollfds[2];
586 const struct pollfd& adb_socket_poll = pollfds[3];
587 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
588 DCHECK(agent_loaded_);
589 char buf[257];
590 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
591 if (res < 0) {
592 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
593 continue;
594 } else {
595 buf[res + 1] = '\0';
596 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
597 }
598 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
599 agent_listening_ = true;
600 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700601 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800602 }
603 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
604 agent_listening_ = false;
605 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
606 CloseFds();
607 agent_has_socket_ = false;
608 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
609 agent_has_socket_ = true;
610 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800611 // We will only ever do the handshake once so reset this.
612 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800613 } else {
614 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
615 }
616 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
617 bool maybe_send_fds = false;
618 {
619 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
620 ScopedEventFdLock sefdl(adb_write_event_fd_);
621 android::base::unique_fd new_fd(ReadFdFromAdb());
622 if (new_fd == -1) {
623 // Something went wrong. We need to retry getting the control socket.
624 PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!";
625 control_sock_.reset();
626 break;
627 } else if (adb_connection_socket_ != -1) {
628 // We already have a connection.
629 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
630 if (new_fd >= 0) {
631 new_fd.reset();
632 }
633 } else {
634 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
635 adb_connection_socket_ = std::move(new_fd);
636 maybe_send_fds = true;
637 }
638 }
639 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
640 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800641 // The agent was already loaded so this must be after a disconnection. Therefore have the
642 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700643 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800644 }
645 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
646 // The other end of the adb connection just dropped it.
647 // Reset the connection since we don't have an active socket through the adb server.
648 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
649 << "connection active";
650 control_sock_.reset();
651 break;
652 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
653 DCHECK(!agent_has_socket_);
654 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800655 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800656 } else if (agent_listening_ && !sent_agent_fds_) {
657 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800658 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700659 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800660 }
Alex Light15b81132018-01-24 13:29:07 -0800661 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
662 DCHECK(!agent_has_socket_);
663 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800664 } else {
665 VLOG(jdwp) << "Woke up poll without anything to do!";
666 }
667 }
668 }
669}
670
Alex Light15b81132018-01-24 13:29:07 -0800671static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
672 uint32_t res;
673 memcpy(&res, *in, sizeof(uint32_t));
674 *in = (*in) + sizeof(uint32_t);
675 return ntohl(res);
676}
677
678void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
679 DCHECK(!agent_loaded_);
680 DCHECK(!agent_listening_);
681 // TODO Should we check in some other way if we are userdebug/eng?
682 CHECK(art::Dbg::IsJdwpAllowed());
683 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
684 if (!performed_handshake_) {
685 PerformHandshake();
686 return;
687 }
688 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
689 // to see if it's one we can handle. This doesn't change the state of the socket.
690 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
691 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
692 packet_header,
693 sizeof(packet_header),
694 MSG_PEEK));
695 // We want to be very careful not to change the socket state until we know we succeeded. This will
696 // let us fall-back to just loading the agent and letting it deal with everything.
697 if (res <= 0) {
698 // Close the socket. We either hit EOF or an error.
699 if (res < 0) {
700 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
701 }
702 CloseFds();
703 return;
704 } else if (res < static_cast<int>(kPacketHeaderLen)) {
705 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
706 AttachJdwpAgent(self);
707 return;
708 }
709 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
710 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
711 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
712 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
713 if (pkt_cmd_set != kDdmCommandSet ||
714 pkt_cmd != kDdmChunkCommand ||
715 full_len < kPacketHeaderLen) {
716 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
717 AttachJdwpAgent(self);
718 return;
719 }
720 uint32_t avail = -1;
721 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
722 if (res < 0) {
723 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
724 CloseFds();
725 return;
726 } else if (avail < full_len) {
727 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
728 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
729 << "Loading jdwp agent to deal with this.";
730 AttachJdwpAgent(self);
731 return;
732 }
733 // Actually read the data.
734 std::vector<uint8_t> full_pkt;
735 full_pkt.resize(full_len);
736 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
737 if (res < 0) {
738 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
739 CloseFds();
740 return;
741 }
742 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
743 size_t data_size = full_len - kPacketHeaderLen;
744 if (data_size < (sizeof(uint32_t) * 2)) {
745 // This is an error (the data isn't long enough) but to match historical behavior we need to
746 // ignore it.
747 return;
748 }
749 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
750 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
751 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
752 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
753 // This is an error (the data isn't long enough) but to match historical behavior we need to
754 // ignore it.
755 return;
756 }
757
758 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700759 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800760 }
761 uint32_t reply_type;
762 std::vector<uint8_t> reply;
763 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
764 ddm_type,
765 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
766 ddm_len),
767 /*out*/&reply_type,
768 /*out*/&reply)) {
769 // To match historical behavior we don't send any response when there is no data to reply with.
770 return;
771 }
772 SendDdmPacket(pkt_id,
773 DdmPacketType::kReply,
774 reply_type,
775 art::ArrayRef<const uint8_t>(reply));
776}
777
778void AdbConnectionState::PerformHandshake() {
779 CHECK(!performed_handshake_);
780 // Check to make sure we are able to read the whole handshake.
781 uint32_t avail = -1;
782 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
783 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
784 if (res < 0) {
785 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
786 }
787 LOG(WARNING) << "Closing connection to broken client.";
788 CloseFds();
789 return;
790 }
791 // Perform the handshake.
792 char handshake_msg[sizeof(kJdwpHandshake)];
793 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
794 handshake_msg,
795 sizeof(handshake_msg),
796 MSG_DONTWAIT));
797 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
798 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
799 if (res < 0) {
800 PLOG(ERROR) << "Failed to read handshake!";
801 }
802 LOG(WARNING) << "Handshake failed!";
803 CloseFds();
804 return;
805 }
806 // Send the handshake back.
807 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
808 kJdwpHandshake,
809 sizeof(kJdwpHandshake),
810 0));
811 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
812 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
813 CloseFds();
814 return;
815 }
816 performed_handshake_ = true;
817}
818
819void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700820 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800821 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700822 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700823 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700824 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800825 if (self->IsExceptionPending()) {
826 LOG(ERROR) << "Failed to load agent " << agent_name_;
827 art::ScopedObjectAccess soa(self);
828 self->GetException()->Dump();
829 self->ClearException();
830 return;
831 }
832 agent_loaded_ = true;
833}
834
Alex Light81f75c32018-01-26 09:46:32 -0800835bool ContainsArgument(const std::string& opts, const char* arg) {
836 return opts.find(arg) != std::string::npos;
837}
838
839bool ValidateJdwpOptions(const std::string& opts) {
840 bool res = true;
841 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
842 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
843 // for the fd's to be passed down.
844 if (ContainsArgument(opts, "server=n")) {
845 res = false;
846 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
847 }
848 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
849 // everything.
850 if (ContainsArgument(opts, "suspend=y")) {
851 res = false;
852 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
853 }
854 return res;
855}
856
Alex Lightfbf96702017-12-14 13:27:13 -0800857std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800858 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800859 DCHECK(ValidateJdwpOptions(opts));
860 // TODO Get agent_name_ from something user settable?
861 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
862 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
863 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
864 // we will add it if it wasn't already present for the convenience of the user.
865 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
866 // See the comment above for why we need to be suspend=n. Since the agent defaults to
867 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700868 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800869 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800870}
871
872void AdbConnectionState::StopDebuggerThreads() {
873 // The regular agent system will take care of unloading the agent (if needed).
874 shutting_down_ = true;
875 // Wakeup the poll loop.
876 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800877 if (sleep_event_fd_ != -1) {
878 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
879 }
Alex Lightfbf96702017-12-14 13:27:13 -0800880}
881
882// The plugin initialization function.
883extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
884 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
885 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800886 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800887 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800888 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800889}
890
891extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800892 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800893 if (!gState->DebuggerThreadsStarted()) {
894 // If debugger threads were started then those threads will delete the state once they are done.
895 delete gState;
896 }
Alex Lightfbf96702017-12-14 13:27:13 -0800897 return true;
898}
899
900} // namespace adbconnection