blob: 205013335bbe72f77c40dcbcd4ed5cf923620ec1 [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"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010026#include "jni/java_vm_ext.h"
27#include "jni/jni_env_ext.h"
Alex Lightfbf96702017-12-14 13:27:13 -080028#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
Alex Light15b81132018-01-24 13:29:07 -080045#include <sys/ioctl.h>
Alex Lightfbf96702017-12-14 13:27:13 -080046#include <sys/socket.h>
47#include <sys/un.h>
48#include <sys/eventfd.h>
49#include <jni.h>
50
51namespace adbconnection {
52
Alex Light15b81132018-01-24 13:29:07 -080053// Messages sent from the transport
Alex Lightfbf96702017-12-14 13:27:13 -080054using dt_fd_forward::kListenStartMessage;
55using dt_fd_forward::kListenEndMessage;
56using dt_fd_forward::kAcceptMessage;
57using dt_fd_forward::kCloseMessage;
58
Alex Light15b81132018-01-24 13:29:07 -080059// Messages sent to the transport
60using dt_fd_forward::kPerformHandshakeMessage;
61using dt_fd_forward::kSkipHandshakeMessage;
62
Alex Lightfbf96702017-12-14 13:27:13 -080063using android::base::StringPrintf;
64
Alex Light15b81132018-01-24 13:29:07 -080065static constexpr const char kJdwpHandshake[14] = {
66 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
67};
68
Alex Lightfbf96702017-12-14 13:27:13 -080069static constexpr int kEventfdLocked = 0;
70static constexpr int kEventfdUnlocked = 1;
71static constexpr int kControlSockSendTimeout = 10;
72
Alex Light15b81132018-01-24 13:29:07 -080073static constexpr size_t kPacketHeaderLen = 11;
74static constexpr off_t kPacketSizeOff = 0;
75static constexpr off_t kPacketIdOff = 4;
76static constexpr off_t kPacketCommandSetOff = 9;
77static constexpr off_t kPacketCommandOff = 10;
78
79static constexpr uint8_t kDdmCommandSet = 199;
80static constexpr uint8_t kDdmChunkCommand = 1;
81
Alex Lightfbf96702017-12-14 13:27:13 -080082static AdbConnectionState* gState;
83
84static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080085 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080086}
87
88// Begin running the debugger.
89void AdbConnectionDebuggerController::StartDebugger() {
90 if (IsDebuggingPossible()) {
91 connection_->StartDebuggerThreads();
92 } else {
93 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
94 }
95}
96
97// The debugger should begin shutting down since the runtime is ending. We don't actually do
98// anything here. The real shutdown has already happened as far as the agent is concerned.
99void AdbConnectionDebuggerController::StopDebugger() { }
100
101bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
102 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
103}
104
105void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
106 const art::ArrayRef<const uint8_t>& data) {
107 connection_->PublishDdmData(type, data);
108}
109
110class ScopedEventFdLock {
111 public:
112 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
113 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
114 }
115
116 ~ScopedEventFdLock() {
117 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
118 }
119
120 private:
121 int fd_;
122 uint64_t data_;
123};
124
125AdbConnectionState::AdbConnectionState(const std::string& agent_name)
126 : agent_name_(agent_name),
127 controller_(this),
128 ddm_callback_(this),
129 sleep_event_fd_(-1),
130 control_sock_(-1),
131 local_agent_control_sock_(-1),
132 remote_agent_control_sock_(-1),
133 adb_connection_socket_(-1),
134 adb_write_event_fd_(-1),
135 shutting_down_(false),
136 agent_loaded_(false),
137 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800138 agent_has_socket_(false),
139 sent_agent_fds_(false),
140 performed_handshake_(false),
141 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800142 next_ddm_id_(1),
143 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800144 // Setup the addr.
145 control_addr_.controlAddrUn.sun_family = AF_UNIX;
146 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
147 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
148
149 // Add the startup callback.
150 art::ScopedObjectAccess soa(art::Thread::Current());
151 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
152}
153
154static jobject CreateAdbConnectionThread(art::Thread* thr) {
155 JNIEnv* env = thr->GetJniEnv();
156 // Move to native state to talk with the jnienv api.
157 art::ScopedThreadStateChange stsc(thr, art::kNative);
158 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
159 ScopedLocalRef<jobject> thr_group(
160 env,
161 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
162 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
163 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
164 art::WellKnownClasses::java_lang_Thread_init,
165 thr_group.get(),
166 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700167 /*Priority=*/ 0,
168 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800169}
170
171struct CallbackData {
172 AdbConnectionState* this_;
173 jobject thr_;
174};
175
176static void* CallbackFunction(void* vdata) {
177 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
Alex Lightd6f9d852018-01-25 11:26:28 -0800178 CHECK(data->this_ == gState);
Alex Lightfbf96702017-12-14 13:27:13 -0800179 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
180 true,
181 data->thr_);
182 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
183 // The name in Attach() is only for logging. Set the thread name. This is important so
184 // that the thread is no longer seen as starting up.
185 {
186 art::ScopedObjectAccess soa(self);
187 self->SetThreadName(kAdbConnectionThreadName);
188 }
189
190 // Release the peer.
191 JNIEnv* env = self->GetJniEnv();
192 env->DeleteGlobalRef(data->thr_);
193 data->thr_ = nullptr;
194 {
195 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
196 // before going into the provided code.
197 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
198 art::Runtime::Current()->EndThreadBirth();
199 }
200 data->this_->RunPollLoop(self);
201 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
202 CHECK_EQ(detach_result, 0);
203
Alex Lightd6f9d852018-01-25 11:26:28 -0800204 // Get rid of the connection
205 gState = nullptr;
206 delete data->this_;
207
Alex Lightfbf96702017-12-14 13:27:13 -0800208 return nullptr;
209}
210
211void AdbConnectionState::StartDebuggerThreads() {
212 // First do all the final setup we need.
213 CHECK_EQ(adb_write_event_fd_.get(), -1);
214 CHECK_EQ(sleep_event_fd_.get(), -1);
215 CHECK_EQ(local_agent_control_sock_.get(), -1);
216 CHECK_EQ(remote_agent_control_sock_.get(), -1);
217
218 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
219 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
220 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
221 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
222
223 {
224 art::ScopedObjectAccess soa(art::Thread::Current());
225 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
226 }
227 // Setup the socketpair we use to talk to the agent.
228 bool has_sockets;
229 do {
230 has_sockets = android::base::Socketpair(AF_UNIX,
231 SOCK_SEQPACKET | SOCK_CLOEXEC,
232 0,
233 &local_agent_control_sock_,
234 &remote_agent_control_sock_);
235 } while (!has_sockets && errno == EINTR);
236 if (!has_sockets) {
237 PLOG(FATAL) << "Unable to create socketpair for agent control!";
238 }
239
240 // Next start the threads.
241 art::Thread* self = art::Thread::Current();
242 art::ScopedObjectAccess soa(self);
243 {
244 art::Runtime* runtime = art::Runtime::Current();
245 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
246 if (runtime->IsShuttingDownLocked()) {
247 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
248 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
249 return;
250 }
251 runtime->StartThreadBirth();
252 }
253 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700254 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
255 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800256 pthread_t pthread;
257 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800258 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800259 int pthread_create_result = pthread_create(&pthread,
260 nullptr,
261 &CallbackFunction,
262 data.get());
263 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800264 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800265 // If the create succeeded the other thread will call EndThreadBirth.
266 art::Runtime* runtime = art::Runtime::Current();
267 soa.Env()->DeleteGlobalRef(data->thr_);
268 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
269 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
270 runtime->EndThreadBirth();
271 return;
272 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700273 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800274}
275
276static bool FlagsSet(int16_t data, int16_t flags) {
277 return (data & flags) == flags;
278}
279
280void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800281 {
282 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
283 // closed.
284 ScopedEventFdLock lk(adb_write_event_fd_);
285 // shutdown(adb_connection_socket_, SHUT_RDWR);
286 adb_connection_socket_.reset();
287 }
288
289 // If we didn't load anything we will need to do the handshake again.
290 performed_handshake_ = false;
291
292 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
293 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700294 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800295 }
296}
297
298void AdbConnectionState::NotifyDdms(bool active) {
299 art::ScopedObjectAccess soa(art::Thread::Current());
300 DCHECK_NE(notified_ddm_active_, active);
301 notified_ddm_active_ = active;
302 if (active) {
303 art::Dbg::DdmConnected();
304 } else {
305 art::Dbg::DdmDisconnected();
306 }
Alex Lightfbf96702017-12-14 13:27:13 -0800307}
308
309uint32_t AdbConnectionState::NextDdmId() {
310 // Just have a normal counter but always set the sign bit.
311 return (next_ddm_id_++) | 0x80000000;
312}
313
314void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800315 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
316}
317
318void AdbConnectionState::SendDdmPacket(uint32_t id,
319 DdmPacketType packet_type,
320 uint32_t type,
321 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800322 // Get the write_event early to fail fast.
323 ScopedEventFdLock lk(adb_write_event_fd_);
324 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800325 VLOG(jdwp) << "Not sending ddms data of type "
326 << StringPrintf("%c%c%c%c",
327 static_cast<char>(type >> 24),
328 static_cast<char>(type >> 16),
329 static_cast<char>(type >> 8),
330 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800331 // Adb is not connected.
332 return;
333 }
334
335 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
336 // after we have sent our data.
337 static constexpr uint32_t kDdmPacketHeaderSize =
338 kJDWPHeaderLen // jdwp command packet size
339 + sizeof(uint32_t) // Type
340 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800341 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800342 uint8_t* pkt_data = pkt.data();
343
344 // Write the length first.
345 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
346 pkt_data += sizeof(uint32_t);
347
348 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800349 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800350 pkt_data += sizeof(uint32_t);
351
352 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800353 *(pkt_data++) = static_cast<uint8_t>(packet_type);
354 switch (packet_type) {
355 case DdmPacketType::kCmd: {
356 // Now the cmd-set
357 *(pkt_data++) = kJDWPDdmCmdSet;
358 // Now the command
359 *(pkt_data++) = kJDWPDdmCmd;
360 break;
361 }
362 case DdmPacketType::kReply: {
363 // This is the error code bytes which are all 0
364 *(pkt_data++) = 0;
365 *(pkt_data++) = 0;
366 }
367 }
Alex Lightfbf96702017-12-14 13:27:13 -0800368
Alex Light15b81132018-01-24 13:29:07 -0800369 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800370 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800371 uint32_t net_type = htonl(type);
372 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800373 pkt_data += sizeof(uint32_t);
374
375 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800376 uint32_t net_len = htonl(data.size());
377 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800378 pkt_data += sizeof(uint32_t);
379
380 static uint32_t constexpr kIovSize = 2;
381 struct iovec iovs[kIovSize] = {
382 { pkt.data(), pkt.size() },
383 { const_cast<uint8_t*>(data.data()), data.size() },
384 };
385 // now pkt_header has the header.
386 // use writev to send the actual data.
387 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
388 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
389 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
390 static_cast<char>(type >> 24),
391 static_cast<char>(type >> 16),
392 static_cast<char>(type >> 8),
393 static_cast<char>(type),
394 res, data.size() + kDdmPacketHeaderSize);
395 } else {
396 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
397 static_cast<char>(type >> 24),
398 static_cast<char>(type >> 16),
399 static_cast<char>(type >> 8),
400 static_cast<char>(type),
401 data.size() + kDdmPacketHeaderSize);
402 }
403}
404
Alex Light15b81132018-01-24 13:29:07 -0800405void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800406 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800407 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800408 union {
409 cmsghdr cm;
410 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
411 } cm_un;
412 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800413 iov.iov_base = const_cast<char*>(message);
414 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800415
416 msghdr msg;
417 msg.msg_name = nullptr;
418 msg.msg_namelen = 0;
419 msg.msg_iov = &iov;
420 msg.msg_iovlen = 1;
421 msg.msg_flags = 0;
422 msg.msg_control = cm_un.buffer;
423 msg.msg_controllen = sizeof(cm_un.buffer);
424
425 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
426 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
427 cmsg->cmsg_level = SOL_SOCKET;
428 cmsg->cmsg_type = SCM_RIGHTS;
429
430 // Duplicate the fds before sending them.
431 android::base::unique_fd read_fd(dup(adb_connection_socket_));
432 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
433 android::base::unique_fd write_fd(dup(adb_connection_socket_));
434 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
435 android::base::unique_fd write_lock_fd(dup(adb_write_event_fd_));
436 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
437
438 dt_fd_forward::FdSet {
439 read_fd.get(), write_fd.get(), write_lock_fd.get()
440 }.WriteData(CMSG_DATA(cmsg));
441
442 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
443 if (res < 0) {
444 PLOG(ERROR) << "Failed to send agent adb connection fds.";
445 } else {
446 sent_agent_fds_ = true;
447 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
448 }
449}
450
451android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
452 // We don't actually care about the data that is sent. We do need to receive something though.
453 char dummy = '!';
454 union {
455 cmsghdr cm;
456 char buffer[CMSG_SPACE(sizeof(int))];
457 } cm_un;
458
459 iovec iov;
460 iov.iov_base = &dummy;
461 iov.iov_len = 1;
462
463 msghdr msg;
464 msg.msg_name = nullptr;
465 msg.msg_namelen = 0;
466 msg.msg_iov = &iov;
467 msg.msg_iovlen = 1;
468 msg.msg_flags = 0;
469 msg.msg_control = cm_un.buffer;
470 msg.msg_controllen = sizeof(cm_un.buffer);
471
472 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
473 cmsg->cmsg_len = msg.msg_controllen;
474 cmsg->cmsg_level = SOL_SOCKET;
475 cmsg->cmsg_type = SCM_RIGHTS;
476 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
477
478 int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0));
479
480 if (rc <= 0) {
481 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")";
482 return android::base::unique_fd(-1);
483 } else {
484 VLOG(jdwp) << "Fds have been received from ADB!";
485 }
486
487 return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
488}
489
490bool AdbConnectionState::SetupAdbConnection() {
491 int sleep_ms = 500;
492 const int sleep_max_ms = 2*1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800493
Alex Light54f535a2018-06-04 14:14:19 -0700494 android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
Alex Lightfbf96702017-12-14 13:27:13 -0800495 if (sock < 0) {
496 PLOG(ERROR) << "Could not create ADB control socket";
497 return false;
498 }
499 struct timeval timeout;
500 timeout.tv_sec = kControlSockSendTimeout;
501 timeout.tv_usec = 0;
502 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
Josh Gao4b49bb72018-02-12 15:06:42 -0800503 int32_t pid = getpid();
Alex Lightfbf96702017-12-14 13:27:13 -0800504
505 while (!shutting_down_) {
506 // If adbd isn't running, because USB debugging was disabled or
507 // perhaps the system is restarting it for "adb root", the
508 // connect() will fail. We loop here forever waiting for it
509 // to come back.
510 //
511 // Waking up and polling every couple of seconds is generally a
512 // bad thing to do, but we only do this if the application is
513 // debuggable *and* adbd isn't running. Still, for the sake
514 // of battery life, we should consider timing out and giving
515 // up after a few minutes in case somebody ships an app with
516 // the debuggable flag set.
517 int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
518 if (ret == 0) {
519 bool trusted = sock >= 0;
520#ifdef ART_TARGET_ANDROID
521 // Needed for socket_peer_is_trusted.
522 trusted = trusted && socket_peer_is_trusted(sock);
523#endif
524 if (!trusted) {
525 LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
526 if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
527 PLOG(ERROR) << "trouble shutting down socket";
528 }
529 return false;
530 }
531 /* now try to send our pid to the ADB daemon */
Josh Gao4b49bb72018-02-12 15:06:42 -0800532 ret = TEMP_FAILURE_RETRY(send(sock, &pid, sizeof(pid), 0));
533 if (ret == sizeof(pid)) {
534 VLOG(jdwp) << "PID " << pid << " sent to adb";
Alex Lightfbf96702017-12-14 13:27:13 -0800535 control_sock_ = std::move(sock);
536 return true;
537 } else {
538 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
539 return false;
540 }
541 } else {
Alex Lightd9258672018-02-12 14:47:16 -0800542 if (VLOG_IS_ON(jdwp)) {
543 PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
544 }
Alex Lightfbf96702017-12-14 13:27:13 -0800545
546 usleep(sleep_ms * 1000);
547
548 sleep_ms += (sleep_ms >> 1);
549 if (sleep_ms > sleep_max_ms) {
550 sleep_ms = sleep_max_ms;
551 }
552 }
553 }
554 return false;
555}
556
557void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800558 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800559 CHECK_EQ(self->GetState(), art::kNative);
Yi Konge11d50f2018-01-09 16:55:04 -0800560 // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
561 // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
562 // http://b/71769596
563 // art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800564 self->SetState(art::kWaitingInMainDebuggerLoop);
565 // shutting_down_ set by StopDebuggerThreads
566 while (!shutting_down_) {
567 // First get the control_sock_ from adb if we don't have one. We only need to do this once.
568 if (control_sock_ == -1 && !SetupAdbConnection()) {
569 LOG(ERROR) << "Failed to setup adb connection.";
570 return;
571 }
572 while (!shutting_down_ && control_sock_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800573 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800574 struct pollfd pollfds[4] = {
575 { sleep_event_fd_, POLLIN, 0 },
576 // -1 as an fd causes it to be ignored by poll
577 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
578 // Check for the control_sock_ actually going away. Only do this if we don't have an active
579 // connection.
580 { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
581 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
582 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800583 // data that the agent or this plugin can handle.
584 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800585 };
586 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
587 if (res < 0) {
588 PLOG(ERROR) << "Failed to poll!";
589 return;
590 }
591 // We don't actually care about doing this we just use it to wake us up.
592 // const struct pollfd& sleep_event_poll = pollfds[0];
593 const struct pollfd& agent_control_sock_poll = pollfds[1];
594 const struct pollfd& control_sock_poll = pollfds[2];
595 const struct pollfd& adb_socket_poll = pollfds[3];
596 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
597 DCHECK(agent_loaded_);
598 char buf[257];
599 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
600 if (res < 0) {
601 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
602 continue;
603 } else {
604 buf[res + 1] = '\0';
605 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
606 }
607 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
608 agent_listening_ = true;
609 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700610 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800611 }
612 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
613 agent_listening_ = false;
614 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
615 CloseFds();
616 agent_has_socket_ = false;
617 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
618 agent_has_socket_ = true;
619 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800620 // We will only ever do the handshake once so reset this.
621 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800622 } else {
623 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
624 }
625 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
626 bool maybe_send_fds = false;
627 {
628 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
629 ScopedEventFdLock sefdl(adb_write_event_fd_);
630 android::base::unique_fd new_fd(ReadFdFromAdb());
631 if (new_fd == -1) {
632 // Something went wrong. We need to retry getting the control socket.
633 PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!";
634 control_sock_.reset();
635 break;
636 } else if (adb_connection_socket_ != -1) {
637 // We already have a connection.
638 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
639 if (new_fd >= 0) {
640 new_fd.reset();
641 }
642 } else {
643 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
644 adb_connection_socket_ = std::move(new_fd);
645 maybe_send_fds = true;
646 }
647 }
648 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
649 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800650 // The agent was already loaded so this must be after a disconnection. Therefore have the
651 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700652 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800653 }
654 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
655 // The other end of the adb connection just dropped it.
656 // Reset the connection since we don't have an active socket through the adb server.
657 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
658 << "connection active";
659 control_sock_.reset();
660 break;
661 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
662 DCHECK(!agent_has_socket_);
663 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800664 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800665 } else if (agent_listening_ && !sent_agent_fds_) {
666 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800667 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700668 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800669 }
Alex Light15b81132018-01-24 13:29:07 -0800670 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
671 DCHECK(!agent_has_socket_);
672 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800673 } else {
674 VLOG(jdwp) << "Woke up poll without anything to do!";
675 }
676 }
677 }
678}
679
Alex Light15b81132018-01-24 13:29:07 -0800680static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
681 uint32_t res;
682 memcpy(&res, *in, sizeof(uint32_t));
683 *in = (*in) + sizeof(uint32_t);
684 return ntohl(res);
685}
686
687void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
688 DCHECK(!agent_loaded_);
689 DCHECK(!agent_listening_);
690 // TODO Should we check in some other way if we are userdebug/eng?
691 CHECK(art::Dbg::IsJdwpAllowed());
692 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
693 if (!performed_handshake_) {
694 PerformHandshake();
695 return;
696 }
697 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
698 // to see if it's one we can handle. This doesn't change the state of the socket.
699 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
700 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
701 packet_header,
702 sizeof(packet_header),
703 MSG_PEEK));
704 // We want to be very careful not to change the socket state until we know we succeeded. This will
705 // let us fall-back to just loading the agent and letting it deal with everything.
706 if (res <= 0) {
707 // Close the socket. We either hit EOF or an error.
708 if (res < 0) {
709 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
710 }
711 CloseFds();
712 return;
713 } else if (res < static_cast<int>(kPacketHeaderLen)) {
714 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
715 AttachJdwpAgent(self);
716 return;
717 }
718 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
719 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
720 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
721 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
722 if (pkt_cmd_set != kDdmCommandSet ||
723 pkt_cmd != kDdmChunkCommand ||
724 full_len < kPacketHeaderLen) {
725 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
726 AttachJdwpAgent(self);
727 return;
728 }
729 uint32_t avail = -1;
730 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
731 if (res < 0) {
732 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
733 CloseFds();
734 return;
735 } else if (avail < full_len) {
736 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
737 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
738 << "Loading jdwp agent to deal with this.";
739 AttachJdwpAgent(self);
740 return;
741 }
742 // Actually read the data.
743 std::vector<uint8_t> full_pkt;
744 full_pkt.resize(full_len);
745 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
746 if (res < 0) {
747 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
748 CloseFds();
749 return;
750 }
751 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
752 size_t data_size = full_len - kPacketHeaderLen;
753 if (data_size < (sizeof(uint32_t) * 2)) {
754 // This is an error (the data isn't long enough) but to match historical behavior we need to
755 // ignore it.
756 return;
757 }
758 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
759 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
760 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
761 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
762 // This is an error (the data isn't long enough) but to match historical behavior we need to
763 // ignore it.
764 return;
765 }
766
767 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700768 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800769 }
770 uint32_t reply_type;
771 std::vector<uint8_t> reply;
772 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
773 ddm_type,
774 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
775 ddm_len),
776 /*out*/&reply_type,
777 /*out*/&reply)) {
778 // To match historical behavior we don't send any response when there is no data to reply with.
779 return;
780 }
781 SendDdmPacket(pkt_id,
782 DdmPacketType::kReply,
783 reply_type,
784 art::ArrayRef<const uint8_t>(reply));
785}
786
787void AdbConnectionState::PerformHandshake() {
788 CHECK(!performed_handshake_);
789 // Check to make sure we are able to read the whole handshake.
790 uint32_t avail = -1;
791 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
792 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
793 if (res < 0) {
794 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
795 }
796 LOG(WARNING) << "Closing connection to broken client.";
797 CloseFds();
798 return;
799 }
800 // Perform the handshake.
801 char handshake_msg[sizeof(kJdwpHandshake)];
802 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
803 handshake_msg,
804 sizeof(handshake_msg),
805 MSG_DONTWAIT));
806 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
807 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
808 if (res < 0) {
809 PLOG(ERROR) << "Failed to read handshake!";
810 }
811 LOG(WARNING) << "Handshake failed!";
812 CloseFds();
813 return;
814 }
815 // Send the handshake back.
816 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
817 kJdwpHandshake,
818 sizeof(kJdwpHandshake),
819 0));
820 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
821 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
822 CloseFds();
823 return;
824 }
825 performed_handshake_ = true;
826}
827
828void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700829 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800830 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700831 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700832 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700833 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800834 if (self->IsExceptionPending()) {
835 LOG(ERROR) << "Failed to load agent " << agent_name_;
836 art::ScopedObjectAccess soa(self);
837 self->GetException()->Dump();
838 self->ClearException();
839 return;
840 }
841 agent_loaded_ = true;
842}
843
Alex Light81f75c32018-01-26 09:46:32 -0800844bool ContainsArgument(const std::string& opts, const char* arg) {
845 return opts.find(arg) != std::string::npos;
846}
847
848bool ValidateJdwpOptions(const std::string& opts) {
849 bool res = true;
850 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
851 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
852 // for the fd's to be passed down.
853 if (ContainsArgument(opts, "server=n")) {
854 res = false;
855 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
856 }
857 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
858 // everything.
859 if (ContainsArgument(opts, "suspend=y")) {
860 res = false;
861 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
862 }
863 return res;
864}
865
Alex Lightfbf96702017-12-14 13:27:13 -0800866std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800867 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800868 DCHECK(ValidateJdwpOptions(opts));
869 // TODO Get agent_name_ from something user settable?
870 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
871 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
872 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
873 // we will add it if it wasn't already present for the convenience of the user.
874 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
875 // See the comment above for why we need to be suspend=n. Since the agent defaults to
876 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700877 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800878 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800879}
880
881void AdbConnectionState::StopDebuggerThreads() {
882 // The regular agent system will take care of unloading the agent (if needed).
883 shutting_down_ = true;
884 // Wakeup the poll loop.
885 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800886 if (sleep_event_fd_ != -1) {
887 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
888 }
Alex Lightfbf96702017-12-14 13:27:13 -0800889}
890
891// The plugin initialization function.
892extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
893 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
894 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800895 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800896 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800897 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800898}
899
900extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800901 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800902 if (!gState->DebuggerThreadsStarted()) {
903 // If debugger threads were started then those threads will delete the state once they are done.
904 delete gState;
905 }
Alex Lightfbf96702017-12-14 13:27:13 -0800906 return true;
907}
908
909} // namespace adbconnection