blob: 634d6b56dfa222f64b13dc89c019c9fc10f9840e [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
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(),
167 /*Priority*/ 0,
168 /*Daemon*/ true);
169}
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()));
254 pthread_t pthread;
255 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800256 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800257 int pthread_create_result = pthread_create(&pthread,
258 nullptr,
259 &CallbackFunction,
260 data.get());
261 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800262 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800263 // If the create succeeded the other thread will call EndThreadBirth.
264 art::Runtime* runtime = art::Runtime::Current();
265 soa.Env()->DeleteGlobalRef(data->thr_);
266 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
267 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
268 runtime->EndThreadBirth();
269 return;
270 }
271 data.release();
272}
273
274static bool FlagsSet(int16_t data, int16_t flags) {
275 return (data & flags) == flags;
276}
277
278void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800279 {
280 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
281 // closed.
282 ScopedEventFdLock lk(adb_write_event_fd_);
283 // shutdown(adb_connection_socket_, SHUT_RDWR);
284 adb_connection_socket_.reset();
285 }
286
287 // If we didn't load anything we will need to do the handshake again.
288 performed_handshake_ = false;
289
290 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
291 if (!agent_loaded_ && notified_ddm_active_) {
292 NotifyDdms(/*active*/false);
293 }
294}
295
296void AdbConnectionState::NotifyDdms(bool active) {
297 art::ScopedObjectAccess soa(art::Thread::Current());
298 DCHECK_NE(notified_ddm_active_, active);
299 notified_ddm_active_ = active;
300 if (active) {
301 art::Dbg::DdmConnected();
302 } else {
303 art::Dbg::DdmDisconnected();
304 }
Alex Lightfbf96702017-12-14 13:27:13 -0800305}
306
307uint32_t AdbConnectionState::NextDdmId() {
308 // Just have a normal counter but always set the sign bit.
309 return (next_ddm_id_++) | 0x80000000;
310}
311
312void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800313 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
314}
315
316void AdbConnectionState::SendDdmPacket(uint32_t id,
317 DdmPacketType packet_type,
318 uint32_t type,
319 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800320 // Get the write_event early to fail fast.
321 ScopedEventFdLock lk(adb_write_event_fd_);
322 if (adb_connection_socket_ == -1) {
323 LOG(WARNING) << "Not sending ddms data of type "
324 << StringPrintf("%c%c%c%c",
325 static_cast<char>(type >> 24),
326 static_cast<char>(type >> 16),
327 static_cast<char>(type >> 8),
328 static_cast<char>(type)) << " due to no connection!";
329 // Adb is not connected.
330 return;
331 }
332
333 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
334 // after we have sent our data.
335 static constexpr uint32_t kDdmPacketHeaderSize =
336 kJDWPHeaderLen // jdwp command packet size
337 + sizeof(uint32_t) // Type
338 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800339 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800340 uint8_t* pkt_data = pkt.data();
341
342 // Write the length first.
343 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
344 pkt_data += sizeof(uint32_t);
345
346 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800347 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800348 pkt_data += sizeof(uint32_t);
349
350 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800351 *(pkt_data++) = static_cast<uint8_t>(packet_type);
352 switch (packet_type) {
353 case DdmPacketType::kCmd: {
354 // Now the cmd-set
355 *(pkt_data++) = kJDWPDdmCmdSet;
356 // Now the command
357 *(pkt_data++) = kJDWPDdmCmd;
358 break;
359 }
360 case DdmPacketType::kReply: {
361 // This is the error code bytes which are all 0
362 *(pkt_data++) = 0;
363 *(pkt_data++) = 0;
364 }
365 }
Alex Lightfbf96702017-12-14 13:27:13 -0800366
Alex Light15b81132018-01-24 13:29:07 -0800367 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800368 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800369 uint32_t net_type = htonl(type);
370 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800371 pkt_data += sizeof(uint32_t);
372
373 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800374 uint32_t net_len = htonl(data.size());
375 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800376 pkt_data += sizeof(uint32_t);
377
378 static uint32_t constexpr kIovSize = 2;
379 struct iovec iovs[kIovSize] = {
380 { pkt.data(), pkt.size() },
381 { const_cast<uint8_t*>(data.data()), data.size() },
382 };
383 // now pkt_header has the header.
384 // use writev to send the actual data.
385 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
386 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
387 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
388 static_cast<char>(type >> 24),
389 static_cast<char>(type >> 16),
390 static_cast<char>(type >> 8),
391 static_cast<char>(type),
392 res, data.size() + kDdmPacketHeaderSize);
393 } else {
394 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
395 static_cast<char>(type >> 24),
396 static_cast<char>(type >> 16),
397 static_cast<char>(type >> 8),
398 static_cast<char>(type),
399 data.size() + kDdmPacketHeaderSize);
400 }
401}
402
Alex Light15b81132018-01-24 13:29:07 -0800403void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800404 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800405 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800406 union {
407 cmsghdr cm;
408 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
409 } cm_un;
410 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800411 iov.iov_base = const_cast<char*>(message);
412 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800413
414 msghdr msg;
415 msg.msg_name = nullptr;
416 msg.msg_namelen = 0;
417 msg.msg_iov = &iov;
418 msg.msg_iovlen = 1;
419 msg.msg_flags = 0;
420 msg.msg_control = cm_un.buffer;
421 msg.msg_controllen = sizeof(cm_un.buffer);
422
423 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
424 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
425 cmsg->cmsg_level = SOL_SOCKET;
426 cmsg->cmsg_type = SCM_RIGHTS;
427
428 // Duplicate the fds before sending them.
429 android::base::unique_fd read_fd(dup(adb_connection_socket_));
430 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
431 android::base::unique_fd write_fd(dup(adb_connection_socket_));
432 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
433 android::base::unique_fd write_lock_fd(dup(adb_write_event_fd_));
434 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
435
436 dt_fd_forward::FdSet {
437 read_fd.get(), write_fd.get(), write_lock_fd.get()
438 }.WriteData(CMSG_DATA(cmsg));
439
440 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
441 if (res < 0) {
442 PLOG(ERROR) << "Failed to send agent adb connection fds.";
443 } else {
444 sent_agent_fds_ = true;
445 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
446 }
447}
448
449android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
450 // We don't actually care about the data that is sent. We do need to receive something though.
451 char dummy = '!';
452 union {
453 cmsghdr cm;
454 char buffer[CMSG_SPACE(sizeof(int))];
455 } cm_un;
456
457 iovec iov;
458 iov.iov_base = &dummy;
459 iov.iov_len = 1;
460
461 msghdr msg;
462 msg.msg_name = nullptr;
463 msg.msg_namelen = 0;
464 msg.msg_iov = &iov;
465 msg.msg_iovlen = 1;
466 msg.msg_flags = 0;
467 msg.msg_control = cm_un.buffer;
468 msg.msg_controllen = sizeof(cm_un.buffer);
469
470 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
471 cmsg->cmsg_len = msg.msg_controllen;
472 cmsg->cmsg_level = SOL_SOCKET;
473 cmsg->cmsg_type = SCM_RIGHTS;
474 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
475
476 int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0));
477
478 if (rc <= 0) {
479 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << control_sock_ << ")";
480 return android::base::unique_fd(-1);
481 } else {
482 VLOG(jdwp) << "Fds have been received from ADB!";
483 }
484
485 return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
486}
487
488bool AdbConnectionState::SetupAdbConnection() {
489 int sleep_ms = 500;
490 const int sleep_max_ms = 2*1000;
491 char buff[sizeof(pid_t) + 1];
492
493 android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET, 0));
494 if (sock < 0) {
495 PLOG(ERROR) << "Could not create ADB control socket";
496 return false;
497 }
498 struct timeval timeout;
499 timeout.tv_sec = kControlSockSendTimeout;
500 timeout.tv_usec = 0;
501 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
502 snprintf(buff, sizeof(buff), "%04x", getpid());
503 buff[sizeof(pid_t)] = 0;
504
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 */
532 ret = TEMP_FAILURE_RETRY(send(sock, buff, sizeof(pid_t), 0));
533 if (ret == sizeof(pid_t)) {
534 LOG(INFO) << "PID " << getpid() << " send to adb";
535 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 {
542 PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
543
544 usleep(sleep_ms * 1000);
545
546 sleep_ms += (sleep_ms >> 1);
547 if (sleep_ms > sleep_max_ms) {
548 sleep_ms = sleep_max_ms;
549 }
550 }
551 }
552 return false;
553}
554
555void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800556 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800557 CHECK_EQ(self->GetState(), art::kNative);
558 art::Locks::mutator_lock_->AssertNotHeld(self);
559 self->SetState(art::kWaitingInMainDebuggerLoop);
560 // shutting_down_ set by StopDebuggerThreads
561 while (!shutting_down_) {
562 // First get the control_sock_ from adb if we don't have one. We only need to do this once.
563 if (control_sock_ == -1 && !SetupAdbConnection()) {
564 LOG(ERROR) << "Failed to setup adb connection.";
565 return;
566 }
567 while (!shutting_down_ && control_sock_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800568 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800569 struct pollfd pollfds[4] = {
570 { sleep_event_fd_, POLLIN, 0 },
571 // -1 as an fd causes it to be ignored by poll
572 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
573 // Check for the control_sock_ actually going away. Only do this if we don't have an active
574 // connection.
575 { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
576 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
577 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800578 // data that the agent or this plugin can handle.
579 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800580 };
581 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
582 if (res < 0) {
583 PLOG(ERROR) << "Failed to poll!";
584 return;
585 }
586 // We don't actually care about doing this we just use it to wake us up.
587 // const struct pollfd& sleep_event_poll = pollfds[0];
588 const struct pollfd& agent_control_sock_poll = pollfds[1];
589 const struct pollfd& control_sock_poll = pollfds[2];
590 const struct pollfd& adb_socket_poll = pollfds[3];
591 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
592 DCHECK(agent_loaded_);
593 char buf[257];
594 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
595 if (res < 0) {
596 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
597 continue;
598 } else {
599 buf[res + 1] = '\0';
600 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
601 }
602 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
603 agent_listening_ = true;
604 if (adb_connection_socket_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800605 SendAgentFds(/*require_handshake*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800606 }
607 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
608 agent_listening_ = false;
609 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
610 CloseFds();
611 agent_has_socket_ = false;
612 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
613 agent_has_socket_ = true;
614 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800615 // We will only ever do the handshake once so reset this.
616 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800617 } else {
618 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
619 }
620 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
621 bool maybe_send_fds = false;
622 {
623 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
624 ScopedEventFdLock sefdl(adb_write_event_fd_);
625 android::base::unique_fd new_fd(ReadFdFromAdb());
626 if (new_fd == -1) {
627 // Something went wrong. We need to retry getting the control socket.
628 PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!";
629 control_sock_.reset();
630 break;
631 } else if (adb_connection_socket_ != -1) {
632 // We already have a connection.
633 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
634 if (new_fd >= 0) {
635 new_fd.reset();
636 }
637 } else {
638 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
639 adb_connection_socket_ = std::move(new_fd);
640 maybe_send_fds = true;
641 }
642 }
643 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
644 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800645 // The agent was already loaded so this must be after a disconnection. Therefore have the
646 // transport perform the handshake.
647 SendAgentFds(/*require_handshake*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800648 }
649 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
650 // The other end of the adb connection just dropped it.
651 // Reset the connection since we don't have an active socket through the adb server.
652 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
653 << "connection active";
654 control_sock_.reset();
655 break;
656 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
657 DCHECK(!agent_has_socket_);
658 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800659 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800660 } else if (agent_listening_ && !sent_agent_fds_) {
661 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800662 // Agent was already loaded so it can deal with the handshake.
663 SendAgentFds(/*require_handshake*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800664 }
Alex Light15b81132018-01-24 13:29:07 -0800665 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
666 DCHECK(!agent_has_socket_);
667 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800668 } else {
669 VLOG(jdwp) << "Woke up poll without anything to do!";
670 }
671 }
672 }
673}
674
Alex Light15b81132018-01-24 13:29:07 -0800675static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
676 uint32_t res;
677 memcpy(&res, *in, sizeof(uint32_t));
678 *in = (*in) + sizeof(uint32_t);
679 return ntohl(res);
680}
681
682void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
683 DCHECK(!agent_loaded_);
684 DCHECK(!agent_listening_);
685 // TODO Should we check in some other way if we are userdebug/eng?
686 CHECK(art::Dbg::IsJdwpAllowed());
687 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
688 if (!performed_handshake_) {
689 PerformHandshake();
690 return;
691 }
692 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
693 // to see if it's one we can handle. This doesn't change the state of the socket.
694 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
695 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
696 packet_header,
697 sizeof(packet_header),
698 MSG_PEEK));
699 // We want to be very careful not to change the socket state until we know we succeeded. This will
700 // let us fall-back to just loading the agent and letting it deal with everything.
701 if (res <= 0) {
702 // Close the socket. We either hit EOF or an error.
703 if (res < 0) {
704 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
705 }
706 CloseFds();
707 return;
708 } else if (res < static_cast<int>(kPacketHeaderLen)) {
709 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
710 AttachJdwpAgent(self);
711 return;
712 }
713 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
714 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
715 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
716 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
717 if (pkt_cmd_set != kDdmCommandSet ||
718 pkt_cmd != kDdmChunkCommand ||
719 full_len < kPacketHeaderLen) {
720 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
721 AttachJdwpAgent(self);
722 return;
723 }
724 uint32_t avail = -1;
725 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
726 if (res < 0) {
727 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
728 CloseFds();
729 return;
730 } else if (avail < full_len) {
731 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
732 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
733 << "Loading jdwp agent to deal with this.";
734 AttachJdwpAgent(self);
735 return;
736 }
737 // Actually read the data.
738 std::vector<uint8_t> full_pkt;
739 full_pkt.resize(full_len);
740 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
741 if (res < 0) {
742 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
743 CloseFds();
744 return;
745 }
746 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
747 size_t data_size = full_len - kPacketHeaderLen;
748 if (data_size < (sizeof(uint32_t) * 2)) {
749 // This is an error (the data isn't long enough) but to match historical behavior we need to
750 // ignore it.
751 return;
752 }
753 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
754 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
755 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
756 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
757 // This is an error (the data isn't long enough) but to match historical behavior we need to
758 // ignore it.
759 return;
760 }
761
762 if (!notified_ddm_active_) {
763 NotifyDdms(/*active*/ true);
764 }
765 uint32_t reply_type;
766 std::vector<uint8_t> reply;
767 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
768 ddm_type,
769 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
770 ddm_len),
771 /*out*/&reply_type,
772 /*out*/&reply)) {
773 // To match historical behavior we don't send any response when there is no data to reply with.
774 return;
775 }
776 SendDdmPacket(pkt_id,
777 DdmPacketType::kReply,
778 reply_type,
779 art::ArrayRef<const uint8_t>(reply));
780}
781
782void AdbConnectionState::PerformHandshake() {
783 CHECK(!performed_handshake_);
784 // Check to make sure we are able to read the whole handshake.
785 uint32_t avail = -1;
786 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
787 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
788 if (res < 0) {
789 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
790 }
791 LOG(WARNING) << "Closing connection to broken client.";
792 CloseFds();
793 return;
794 }
795 // Perform the handshake.
796 char handshake_msg[sizeof(kJdwpHandshake)];
797 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
798 handshake_msg,
799 sizeof(handshake_msg),
800 MSG_DONTWAIT));
801 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
802 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
803 if (res < 0) {
804 PLOG(ERROR) << "Failed to read handshake!";
805 }
806 LOG(WARNING) << "Handshake failed!";
807 CloseFds();
808 return;
809 }
810 // Send the handshake back.
811 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
812 kJdwpHandshake,
813 sizeof(kJdwpHandshake),
814 0));
815 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
816 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
817 CloseFds();
818 return;
819 }
820 performed_handshake_ = true;
821}
822
823void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
824 self->AssertNoPendingException();
825 art::Runtime::Current()->AttachAgent(/* JNIEnv */ nullptr,
826 MakeAgentArg(),
827 /* classloader */ nullptr,
828 /*allow_non_debuggable_tooling*/ true);
829 if (self->IsExceptionPending()) {
830 LOG(ERROR) << "Failed to load agent " << agent_name_;
831 art::ScopedObjectAccess soa(self);
832 self->GetException()->Dump();
833 self->ClearException();
834 return;
835 }
836 agent_loaded_ = true;
837}
838
Alex Light81f75c32018-01-26 09:46:32 -0800839bool ContainsArgument(const std::string& opts, const char* arg) {
840 return opts.find(arg) != std::string::npos;
841}
842
843bool ValidateJdwpOptions(const std::string& opts) {
844 bool res = true;
845 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
846 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
847 // for the fd's to be passed down.
848 if (ContainsArgument(opts, "server=n")) {
849 res = false;
850 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
851 }
852 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
853 // everything.
854 if (ContainsArgument(opts, "suspend=y")) {
855 res = false;
856 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
857 }
858 return res;
859}
860
Alex Lightfbf96702017-12-14 13:27:13 -0800861std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800862 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800863 DCHECK(ValidateJdwpOptions(opts));
864 // TODO Get agent_name_ from something user settable?
865 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
866 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
867 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
868 // we will add it if it wasn't already present for the convenience of the user.
869 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
870 // See the comment above for why we need to be suspend=n. Since the agent defaults to
871 // suspend=y we will add it if it wasn't already present.
872 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n") +
873 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800874}
875
876void AdbConnectionState::StopDebuggerThreads() {
877 // The regular agent system will take care of unloading the agent (if needed).
878 shutting_down_ = true;
879 // Wakeup the poll loop.
880 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800881 if (sleep_event_fd_ != -1) {
882 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
883 }
Alex Lightfbf96702017-12-14 13:27:13 -0800884}
885
886// The plugin initialization function.
887extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
888 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
889 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800890 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800891 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800892 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800893}
894
895extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800896 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800897 if (!gState->DebuggerThreadsStarted()) {
898 // If debugger threads were started then those threads will delete the state once they are done.
899 delete gState;
900 }
Alex Lightfbf96702017-12-14 13:27:13 -0800901 return true;
902}
903
904} // namespace adbconnection