blob: 98896a604d034929dbb8b6c44a0527b9bde2558d [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) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800323 VLOG(jdwp) << "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!";
Alex Lightfbf96702017-12-14 13:27:13 -0800329 // 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;
Alex Lightfbf96702017-12-14 13:27:13 -0800491
492 android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET, 0));
493 if (sock < 0) {
494 PLOG(ERROR) << "Could not create ADB control socket";
495 return false;
496 }
497 struct timeval timeout;
498 timeout.tv_sec = kControlSockSendTimeout;
499 timeout.tv_usec = 0;
500 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
Josh Gao4b49bb72018-02-12 15:06:42 -0800501 int32_t pid = getpid();
Alex Lightfbf96702017-12-14 13:27:13 -0800502
503 while (!shutting_down_) {
504 // If adbd isn't running, because USB debugging was disabled or
505 // perhaps the system is restarting it for "adb root", the
506 // connect() will fail. We loop here forever waiting for it
507 // to come back.
508 //
509 // Waking up and polling every couple of seconds is generally a
510 // bad thing to do, but we only do this if the application is
511 // debuggable *and* adbd isn't running. Still, for the sake
512 // of battery life, we should consider timing out and giving
513 // up after a few minutes in case somebody ships an app with
514 // the debuggable flag set.
515 int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
516 if (ret == 0) {
517 bool trusted = sock >= 0;
518#ifdef ART_TARGET_ANDROID
519 // Needed for socket_peer_is_trusted.
520 trusted = trusted && socket_peer_is_trusted(sock);
521#endif
522 if (!trusted) {
523 LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
524 if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
525 PLOG(ERROR) << "trouble shutting down socket";
526 }
527 return false;
528 }
529 /* now try to send our pid to the ADB daemon */
Josh Gao4b49bb72018-02-12 15:06:42 -0800530 ret = TEMP_FAILURE_RETRY(send(sock, &pid, sizeof(pid), 0));
531 if (ret == sizeof(pid)) {
532 VLOG(jdwp) << "PID " << pid << " sent to adb";
Alex Lightfbf96702017-12-14 13:27:13 -0800533 control_sock_ = std::move(sock);
534 return true;
535 } else {
536 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
537 return false;
538 }
539 } else {
540 PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
541
542 usleep(sleep_ms * 1000);
543
544 sleep_ms += (sleep_ms >> 1);
545 if (sleep_ms > sleep_max_ms) {
546 sleep_ms = sleep_max_ms;
547 }
548 }
549 }
550 return false;
551}
552
553void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800554 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800555 CHECK_EQ(self->GetState(), art::kNative);
Yi Konge11d50f2018-01-09 16:55:04 -0800556 // TODO: Clang prebuilt for r316199 produces bogus thread safety analysis warning for holding both
557 // exclusive and shared lock in the same scope. Remove the assertion as a temporary workaround.
558 // http://b/71769596
559 // art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800560 self->SetState(art::kWaitingInMainDebuggerLoop);
561 // shutting_down_ set by StopDebuggerThreads
562 while (!shutting_down_) {
563 // First get the control_sock_ from adb if we don't have one. We only need to do this once.
564 if (control_sock_ == -1 && !SetupAdbConnection()) {
565 LOG(ERROR) << "Failed to setup adb connection.";
566 return;
567 }
568 while (!shutting_down_ && control_sock_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800569 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800570 struct pollfd pollfds[4] = {
571 { sleep_event_fd_, POLLIN, 0 },
572 // -1 as an fd causes it to be ignored by poll
573 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
574 // Check for the control_sock_ actually going away. Only do this if we don't have an active
575 // connection.
576 { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
577 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
578 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800579 // data that the agent or this plugin can handle.
580 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800581 };
582 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
583 if (res < 0) {
584 PLOG(ERROR) << "Failed to poll!";
585 return;
586 }
587 // We don't actually care about doing this we just use it to wake us up.
588 // const struct pollfd& sleep_event_poll = pollfds[0];
589 const struct pollfd& agent_control_sock_poll = pollfds[1];
590 const struct pollfd& control_sock_poll = pollfds[2];
591 const struct pollfd& adb_socket_poll = pollfds[3];
592 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
593 DCHECK(agent_loaded_);
594 char buf[257];
595 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
596 if (res < 0) {
597 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
598 continue;
599 } else {
600 buf[res + 1] = '\0';
601 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
602 }
603 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
604 agent_listening_ = true;
605 if (adb_connection_socket_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800606 SendAgentFds(/*require_handshake*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800607 }
608 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
609 agent_listening_ = false;
610 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
611 CloseFds();
612 agent_has_socket_ = false;
613 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
614 agent_has_socket_ = true;
615 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800616 // We will only ever do the handshake once so reset this.
617 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800618 } else {
619 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
620 }
621 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
622 bool maybe_send_fds = false;
623 {
624 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
625 ScopedEventFdLock sefdl(adb_write_event_fd_);
626 android::base::unique_fd new_fd(ReadFdFromAdb());
627 if (new_fd == -1) {
628 // Something went wrong. We need to retry getting the control socket.
629 PLOG(ERROR) << "Something went wrong getting fds from adb. Retry!";
630 control_sock_.reset();
631 break;
632 } else if (adb_connection_socket_ != -1) {
633 // We already have a connection.
634 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
635 if (new_fd >= 0) {
636 new_fd.reset();
637 }
638 } else {
639 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
640 adb_connection_socket_ = std::move(new_fd);
641 maybe_send_fds = true;
642 }
643 }
644 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
645 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800646 // The agent was already loaded so this must be after a disconnection. Therefore have the
647 // transport perform the handshake.
648 SendAgentFds(/*require_handshake*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800649 }
650 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
651 // The other end of the adb connection just dropped it.
652 // Reset the connection since we don't have an active socket through the adb server.
653 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
654 << "connection active";
655 control_sock_.reset();
656 break;
657 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
658 DCHECK(!agent_has_socket_);
659 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800660 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800661 } else if (agent_listening_ && !sent_agent_fds_) {
662 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800663 // Agent was already loaded so it can deal with the handshake.
664 SendAgentFds(/*require_handshake*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800665 }
Alex Light15b81132018-01-24 13:29:07 -0800666 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
667 DCHECK(!agent_has_socket_);
668 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800669 } else {
670 VLOG(jdwp) << "Woke up poll without anything to do!";
671 }
672 }
673 }
674}
675
Alex Light15b81132018-01-24 13:29:07 -0800676static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
677 uint32_t res;
678 memcpy(&res, *in, sizeof(uint32_t));
679 *in = (*in) + sizeof(uint32_t);
680 return ntohl(res);
681}
682
683void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
684 DCHECK(!agent_loaded_);
685 DCHECK(!agent_listening_);
686 // TODO Should we check in some other way if we are userdebug/eng?
687 CHECK(art::Dbg::IsJdwpAllowed());
688 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
689 if (!performed_handshake_) {
690 PerformHandshake();
691 return;
692 }
693 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
694 // to see if it's one we can handle. This doesn't change the state of the socket.
695 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
696 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
697 packet_header,
698 sizeof(packet_header),
699 MSG_PEEK));
700 // We want to be very careful not to change the socket state until we know we succeeded. This will
701 // let us fall-back to just loading the agent and letting it deal with everything.
702 if (res <= 0) {
703 // Close the socket. We either hit EOF or an error.
704 if (res < 0) {
705 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
706 }
707 CloseFds();
708 return;
709 } else if (res < static_cast<int>(kPacketHeaderLen)) {
710 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
711 AttachJdwpAgent(self);
712 return;
713 }
714 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
715 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
716 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
717 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
718 if (pkt_cmd_set != kDdmCommandSet ||
719 pkt_cmd != kDdmChunkCommand ||
720 full_len < kPacketHeaderLen) {
721 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
722 AttachJdwpAgent(self);
723 return;
724 }
725 uint32_t avail = -1;
726 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
727 if (res < 0) {
728 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
729 CloseFds();
730 return;
731 } else if (avail < full_len) {
732 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
733 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
734 << "Loading jdwp agent to deal with this.";
735 AttachJdwpAgent(self);
736 return;
737 }
738 // Actually read the data.
739 std::vector<uint8_t> full_pkt;
740 full_pkt.resize(full_len);
741 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
742 if (res < 0) {
743 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
744 CloseFds();
745 return;
746 }
747 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
748 size_t data_size = full_len - kPacketHeaderLen;
749 if (data_size < (sizeof(uint32_t) * 2)) {
750 // This is an error (the data isn't long enough) but to match historical behavior we need to
751 // ignore it.
752 return;
753 }
754 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
755 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
756 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
757 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
758 // This is an error (the data isn't long enough) but to match historical behavior we need to
759 // ignore it.
760 return;
761 }
762
763 if (!notified_ddm_active_) {
764 NotifyDdms(/*active*/ true);
765 }
766 uint32_t reply_type;
767 std::vector<uint8_t> reply;
768 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
769 ddm_type,
770 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
771 ddm_len),
772 /*out*/&reply_type,
773 /*out*/&reply)) {
774 // To match historical behavior we don't send any response when there is no data to reply with.
775 return;
776 }
777 SendDdmPacket(pkt_id,
778 DdmPacketType::kReply,
779 reply_type,
780 art::ArrayRef<const uint8_t>(reply));
781}
782
783void AdbConnectionState::PerformHandshake() {
784 CHECK(!performed_handshake_);
785 // Check to make sure we are able to read the whole handshake.
786 uint32_t avail = -1;
787 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
788 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
789 if (res < 0) {
790 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
791 }
792 LOG(WARNING) << "Closing connection to broken client.";
793 CloseFds();
794 return;
795 }
796 // Perform the handshake.
797 char handshake_msg[sizeof(kJdwpHandshake)];
798 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
799 handshake_msg,
800 sizeof(handshake_msg),
801 MSG_DONTWAIT));
802 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
803 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
804 if (res < 0) {
805 PLOG(ERROR) << "Failed to read handshake!";
806 }
807 LOG(WARNING) << "Handshake failed!";
808 CloseFds();
809 return;
810 }
811 // Send the handshake back.
812 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
813 kJdwpHandshake,
814 sizeof(kJdwpHandshake),
815 0));
816 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
817 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
818 CloseFds();
819 return;
820 }
821 performed_handshake_ = true;
822}
823
824void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
825 self->AssertNoPendingException();
826 art::Runtime::Current()->AttachAgent(/* JNIEnv */ nullptr,
827 MakeAgentArg(),
828 /* classloader */ nullptr,
829 /*allow_non_debuggable_tooling*/ true);
830 if (self->IsExceptionPending()) {
831 LOG(ERROR) << "Failed to load agent " << agent_name_;
832 art::ScopedObjectAccess soa(self);
833 self->GetException()->Dump();
834 self->ClearException();
835 return;
836 }
837 agent_loaded_ = true;
838}
839
Alex Light81f75c32018-01-26 09:46:32 -0800840bool ContainsArgument(const std::string& opts, const char* arg) {
841 return opts.find(arg) != std::string::npos;
842}
843
844bool ValidateJdwpOptions(const std::string& opts) {
845 bool res = true;
846 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
847 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
848 // for the fd's to be passed down.
849 if (ContainsArgument(opts, "server=n")) {
850 res = false;
851 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
852 }
853 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
854 // everything.
855 if (ContainsArgument(opts, "suspend=y")) {
856 res = false;
857 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
858 }
859 return res;
860}
861
Alex Lightfbf96702017-12-14 13:27:13 -0800862std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800863 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800864 DCHECK(ValidateJdwpOptions(opts));
865 // TODO Get agent_name_ from something user settable?
866 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
867 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
868 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
869 // we will add it if it wasn't already present for the convenience of the user.
870 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
871 // See the comment above for why we need to be suspend=n. Since the agent defaults to
872 // suspend=y we will add it if it wasn't already present.
873 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n") +
874 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800875}
876
877void AdbConnectionState::StopDebuggerThreads() {
878 // The regular agent system will take care of unloading the agent (if needed).
879 shutting_down_ = true;
880 // Wakeup the poll loop.
881 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800882 if (sleep_event_fd_ != -1) {
883 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
884 }
Alex Lightfbf96702017-12-14 13:27:13 -0800885}
886
887// The plugin initialization function.
888extern "C" bool ArtPlugin_Initialize() REQUIRES_SHARED(art::Locks::mutator_lock_) {
889 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
890 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800891 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800892 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800893 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800894}
895
896extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800897 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800898 if (!gState->DebuggerThreadsStarted()) {
899 // If debugger threads were started then those threads will delete the state once they are done.
900 delete gState;
901 }
Alex Lightfbf96702017-12-14 13:27:13 -0800902 return true;
903}
904
905} // namespace adbconnection