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