blob: cdf97141a03476aa40d96d271afbf421d5248aee [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>
Josh Gaobd396c02020-01-22 18:02:19 -080018#include <iterator>
Alex Lightfbf96702017-12-14 13:27:13 -080019
20#include "adbconnection.h"
21
Josh Gaobd396c02020-01-22 18:02:19 -080022#include "adbconnection/client.h"
Alex Lightfbf96702017-12-14 13:27:13 -080023#include "android-base/endian.h"
24#include "android-base/stringprintf.h"
Andreas Gampedfcd82c2018-10-16 20:22:37 -070025#include "base/file_utils.h"
Alex Lightfbf96702017-12-14 13:27:13 -080026#include "base/logging.h"
27#include "base/macros.h"
28#include "base/mutex.h"
Alex Lightfc588092020-01-23 15:39:08 -080029#include "base/socket_peer_is_trusted.h"
30#include "debugger.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010031#include "jni/java_vm_ext.h"
32#include "jni/jni_env_ext.h"
Alex Lightfbf96702017-12-14 13:27:13 -080033#include "mirror/throwable.h"
Orion Hodsond41c7592019-01-27 09:25:47 +000034#include "nativehelper/scoped_local_ref.h"
Alex Lightfbf96702017-12-14 13:27:13 -080035#include "runtime-inl.h"
36#include "runtime_callbacks.h"
37#include "scoped_thread_state_change-inl.h"
38#include "well_known_classes.h"
39
Alex Lightfbf96702017-12-14 13:27:13 -080040#include "fd_transport.h"
41
42#include "poll.h"
43
Alex Light15b81132018-01-24 13:29:07 -080044#include <sys/ioctl.h>
Alex Lightfbf96702017-12-14 13:27:13 -080045#include <sys/socket.h>
Alex Lightfc588092020-01-23 15:39:08 -080046#include <sys/uio.h>
Alex Lightfbf96702017-12-14 13:27:13 -080047#include <sys/un.h>
48#include <sys/eventfd.h>
49#include <jni.h>
50
51namespace adbconnection {
52
Alex Lightfc588092020-01-23 15:39:08 -080053static constexpr size_t kJdwpHeaderLen = 11U;
54/* DDM support */
55static constexpr uint8_t kJdwpDdmCmdSet = 199U; // 0xc7, or 'G'+128
56static constexpr uint8_t kJdwpDdmCmd = 1U;
57
Alex Light15b81132018-01-24 13:29:07 -080058// Messages sent from the transport
Alex Lightfbf96702017-12-14 13:27:13 -080059using dt_fd_forward::kListenStartMessage;
60using dt_fd_forward::kListenEndMessage;
61using dt_fd_forward::kAcceptMessage;
62using dt_fd_forward::kCloseMessage;
63
Alex Light15b81132018-01-24 13:29:07 -080064// Messages sent to the transport
65using dt_fd_forward::kPerformHandshakeMessage;
66using dt_fd_forward::kSkipHandshakeMessage;
67
Alex Lightfbf96702017-12-14 13:27:13 -080068using android::base::StringPrintf;
69
Alex Light15b81132018-01-24 13:29:07 -080070static constexpr const char kJdwpHandshake[14] = {
71 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
72};
73
Alex Lightfbf96702017-12-14 13:27:13 -080074static constexpr int kEventfdLocked = 0;
75static constexpr int kEventfdUnlocked = 1;
Alex Lightfbf96702017-12-14 13:27:13 -080076
Alex Light15b81132018-01-24 13:29:07 -080077static constexpr size_t kPacketHeaderLen = 11;
78static constexpr off_t kPacketSizeOff = 0;
79static constexpr off_t kPacketIdOff = 4;
80static constexpr off_t kPacketCommandSetOff = 9;
81static constexpr off_t kPacketCommandOff = 10;
82
83static constexpr uint8_t kDdmCommandSet = 199;
84static constexpr uint8_t kDdmChunkCommand = 1;
85
Flash Liu013e2082019-10-31 11:18:55 +080086static std::optional<AdbConnectionState> gState;
Alex Lightfbf96702017-12-14 13:27:13 -080087
88static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080089 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080090}
91
92// Begin running the debugger.
93void AdbConnectionDebuggerController::StartDebugger() {
94 if (IsDebuggingPossible()) {
95 connection_->StartDebuggerThreads();
96 } else {
97 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
98 }
99}
100
101// The debugger should begin shutting down since the runtime is ending. We don't actually do
102// anything here. The real shutdown has already happened as far as the agent is concerned.
103void AdbConnectionDebuggerController::StopDebugger() { }
104
105bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
106 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
107}
108
109void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
110 const art::ArrayRef<const uint8_t>& data) {
111 connection_->PublishDdmData(type, data);
112}
113
114class ScopedEventFdLock {
115 public:
116 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
117 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
118 }
119
120 ~ScopedEventFdLock() {
121 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
122 }
123
124 private:
125 int fd_;
126 uint64_t data_;
127};
128
129AdbConnectionState::AdbConnectionState(const std::string& agent_name)
130 : agent_name_(agent_name),
131 controller_(this),
132 ddm_callback_(this),
133 sleep_event_fd_(-1),
Josh Gaobd396c02020-01-22 18:02:19 -0800134 control_ctx_(nullptr, adbconnection_client_destroy),
Alex Lightfbf96702017-12-14 13:27:13 -0800135 local_agent_control_sock_(-1),
136 remote_agent_control_sock_(-1),
137 adb_connection_socket_(-1),
138 adb_write_event_fd_(-1),
139 shutting_down_(false),
140 agent_loaded_(false),
141 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800142 agent_has_socket_(false),
143 sent_agent_fds_(false),
144 performed_handshake_(false),
145 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800146 next_ddm_id_(1),
147 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800148 // Setup the addr.
149 control_addr_.controlAddrUn.sun_family = AF_UNIX;
150 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
151 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
152
153 // Add the startup callback.
154 art::ScopedObjectAccess soa(art::Thread::Current());
155 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
156}
157
Flash Liu013e2082019-10-31 11:18:55 +0800158AdbConnectionState::~AdbConnectionState() {
159 // Remove the startup callback.
160 art::Thread* self = art::Thread::Current();
161 if (self != nullptr) {
162 art::ScopedObjectAccess soa(self);
163 art::Runtime::Current()->GetRuntimeCallbacks()->RemoveDebuggerControlCallback(&controller_);
164 }
165}
166
Alex Lightfbf96702017-12-14 13:27:13 -0800167static jobject CreateAdbConnectionThread(art::Thread* thr) {
168 JNIEnv* env = thr->GetJniEnv();
169 // Move to native state to talk with the jnienv api.
170 art::ScopedThreadStateChange stsc(thr, art::kNative);
171 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
172 ScopedLocalRef<jobject> thr_group(
173 env,
174 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
175 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
176 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
177 art::WellKnownClasses::java_lang_Thread_init,
178 thr_group.get(),
179 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700180 /*Priority=*/ 0,
181 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800182}
183
184struct CallbackData {
185 AdbConnectionState* this_;
186 jobject thr_;
187};
188
189static void* CallbackFunction(void* vdata) {
190 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
191 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
192 true,
193 data->thr_);
194 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
195 // The name in Attach() is only for logging. Set the thread name. This is important so
196 // that the thread is no longer seen as starting up.
197 {
198 art::ScopedObjectAccess soa(self);
199 self->SetThreadName(kAdbConnectionThreadName);
200 }
201
202 // Release the peer.
203 JNIEnv* env = self->GetJniEnv();
204 env->DeleteGlobalRef(data->thr_);
205 data->thr_ = nullptr;
206 {
207 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
208 // before going into the provided code.
209 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
210 art::Runtime::Current()->EndThreadBirth();
211 }
212 data->this_->RunPollLoop(self);
213 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
214 CHECK_EQ(detach_result, 0);
215
216 return nullptr;
217}
218
219void AdbConnectionState::StartDebuggerThreads() {
220 // First do all the final setup we need.
221 CHECK_EQ(adb_write_event_fd_.get(), -1);
222 CHECK_EQ(sleep_event_fd_.get(), -1);
223 CHECK_EQ(local_agent_control_sock_.get(), -1);
224 CHECK_EQ(remote_agent_control_sock_.get(), -1);
225
226 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
227 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
228 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
229 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
230
231 {
232 art::ScopedObjectAccess soa(art::Thread::Current());
233 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
234 }
235 // Setup the socketpair we use to talk to the agent.
236 bool has_sockets;
237 do {
238 has_sockets = android::base::Socketpair(AF_UNIX,
239 SOCK_SEQPACKET | SOCK_CLOEXEC,
240 0,
241 &local_agent_control_sock_,
242 &remote_agent_control_sock_);
243 } while (!has_sockets && errno == EINTR);
244 if (!has_sockets) {
245 PLOG(FATAL) << "Unable to create socketpair for agent control!";
246 }
247
248 // Next start the threads.
249 art::Thread* self = art::Thread::Current();
250 art::ScopedObjectAccess soa(self);
251 {
252 art::Runtime* runtime = art::Runtime::Current();
253 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
254 if (runtime->IsShuttingDownLocked()) {
255 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
256 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
257 return;
258 }
259 runtime->StartThreadBirth();
260 }
261 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700262 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
263 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800264 pthread_t pthread;
265 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800266 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800267 int pthread_create_result = pthread_create(&pthread,
268 nullptr,
269 &CallbackFunction,
270 data.get());
271 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800272 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800273 // If the create succeeded the other thread will call EndThreadBirth.
274 art::Runtime* runtime = art::Runtime::Current();
275 soa.Env()->DeleteGlobalRef(data->thr_);
276 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
277 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
278 runtime->EndThreadBirth();
279 return;
280 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700281 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800282}
283
284static bool FlagsSet(int16_t data, int16_t flags) {
285 return (data & flags) == flags;
286}
287
288void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800289 {
290 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
291 // closed.
292 ScopedEventFdLock lk(adb_write_event_fd_);
293 // shutdown(adb_connection_socket_, SHUT_RDWR);
294 adb_connection_socket_.reset();
295 }
296
297 // If we didn't load anything we will need to do the handshake again.
298 performed_handshake_ = false;
299
300 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
301 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700302 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800303 }
304}
305
306void AdbConnectionState::NotifyDdms(bool active) {
307 art::ScopedObjectAccess soa(art::Thread::Current());
308 DCHECK_NE(notified_ddm_active_, active);
309 notified_ddm_active_ = active;
310 if (active) {
311 art::Dbg::DdmConnected();
312 } else {
313 art::Dbg::DdmDisconnected();
314 }
Alex Lightfbf96702017-12-14 13:27:13 -0800315}
316
317uint32_t AdbConnectionState::NextDdmId() {
318 // Just have a normal counter but always set the sign bit.
319 return (next_ddm_id_++) | 0x80000000;
320}
321
322void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800323 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
324}
325
326void AdbConnectionState::SendDdmPacket(uint32_t id,
327 DdmPacketType packet_type,
328 uint32_t type,
329 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800330 // Get the write_event early to fail fast.
331 ScopedEventFdLock lk(adb_write_event_fd_);
332 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800333 VLOG(jdwp) << "Not sending ddms data of type "
334 << StringPrintf("%c%c%c%c",
335 static_cast<char>(type >> 24),
336 static_cast<char>(type >> 16),
337 static_cast<char>(type >> 8),
338 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800339 // Adb is not connected.
340 return;
341 }
342
343 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
344 // after we have sent our data.
345 static constexpr uint32_t kDdmPacketHeaderSize =
Alex Lightfc588092020-01-23 15:39:08 -0800346 kJdwpHeaderLen // jdwp command packet size
Alex Lightfbf96702017-12-14 13:27:13 -0800347 + sizeof(uint32_t) // Type
348 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800349 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800350 uint8_t* pkt_data = pkt.data();
351
352 // Write the length first.
353 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
354 pkt_data += sizeof(uint32_t);
355
356 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800357 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800358 pkt_data += sizeof(uint32_t);
359
360 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800361 *(pkt_data++) = static_cast<uint8_t>(packet_type);
362 switch (packet_type) {
363 case DdmPacketType::kCmd: {
364 // Now the cmd-set
Alex Lightfc588092020-01-23 15:39:08 -0800365 *(pkt_data++) = kJdwpDdmCmdSet;
Alex Light15b81132018-01-24 13:29:07 -0800366 // Now the command
Alex Lightfc588092020-01-23 15:39:08 -0800367 *(pkt_data++) = kJdwpDdmCmd;
Alex Light15b81132018-01-24 13:29:07 -0800368 break;
369 }
370 case DdmPacketType::kReply: {
371 // This is the error code bytes which are all 0
372 *(pkt_data++) = 0;
373 *(pkt_data++) = 0;
374 }
375 }
Alex Lightfbf96702017-12-14 13:27:13 -0800376
Alex Light15b81132018-01-24 13:29:07 -0800377 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800378 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800379 uint32_t net_type = htonl(type);
380 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800381 pkt_data += sizeof(uint32_t);
382
383 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800384 uint32_t net_len = htonl(data.size());
385 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800386 pkt_data += sizeof(uint32_t);
387
388 static uint32_t constexpr kIovSize = 2;
389 struct iovec iovs[kIovSize] = {
390 { pkt.data(), pkt.size() },
391 { const_cast<uint8_t*>(data.data()), data.size() },
392 };
393 // now pkt_header has the header.
394 // use writev to send the actual data.
395 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
396 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
397 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %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 res, data.size() + kDdmPacketHeaderSize);
403 } else {
404 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
405 static_cast<char>(type >> 24),
406 static_cast<char>(type >> 16),
407 static_cast<char>(type >> 8),
408 static_cast<char>(type),
409 data.size() + kDdmPacketHeaderSize);
410 }
411}
412
Alex Light15b81132018-01-24 13:29:07 -0800413void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800414 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800415 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800416 union {
417 cmsghdr cm;
418 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
419 } cm_un;
420 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800421 iov.iov_base = const_cast<char*>(message);
422 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800423
424 msghdr msg;
425 msg.msg_name = nullptr;
426 msg.msg_namelen = 0;
427 msg.msg_iov = &iov;
428 msg.msg_iovlen = 1;
429 msg.msg_flags = 0;
430 msg.msg_control = cm_un.buffer;
431 msg.msg_controllen = sizeof(cm_un.buffer);
432
433 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
434 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
435 cmsg->cmsg_level = SOL_SOCKET;
436 cmsg->cmsg_type = SCM_RIGHTS;
437
438 // Duplicate the fds before sending them.
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700439 android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800440 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700441 android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800442 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700443 android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
Alex Lightfbf96702017-12-14 13:27:13 -0800444 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
445
446 dt_fd_forward::FdSet {
447 read_fd.get(), write_fd.get(), write_lock_fd.get()
448 }.WriteData(CMSG_DATA(cmsg));
449
450 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
451 if (res < 0) {
452 PLOG(ERROR) << "Failed to send agent adb connection fds.";
453 } else {
454 sent_agent_fds_ = true;
455 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
456 }
457}
458
459android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
Josh Gaobd396c02020-01-22 18:02:19 -0800460 return android::base::unique_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800461}
462
463bool AdbConnectionState::SetupAdbConnection() {
Josh Gaobd396c02020-01-22 18:02:19 -0800464 int sleep_ms = 500;
465 const int sleep_max_ms = 2 * 1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800466
Josh Gaobd396c02020-01-22 18:02:19 -0800467 const AdbConnectionClientInfo infos[] = {
468 {.type = AdbConnectionClientInfoType::pid, .data.pid = static_cast<uint64_t>(getpid())},
469 {.type = AdbConnectionClientInfoType::debuggable, .data.debuggable = true},
470 };
471 const AdbConnectionClientInfo* info_ptrs[] = {&infos[0], &infos[1]};
Alex Lightfbf96702017-12-14 13:27:13 -0800472
473 while (!shutting_down_) {
474 // If adbd isn't running, because USB debugging was disabled or
475 // perhaps the system is restarting it for "adb root", the
476 // connect() will fail. We loop here forever waiting for it
477 // to come back.
478 //
479 // Waking up and polling every couple of seconds is generally a
480 // bad thing to do, but we only do this if the application is
481 // debuggable *and* adbd isn't running. Still, for the sake
482 // of battery life, we should consider timing out and giving
483 // up after a few minutes in case somebody ships an app with
484 // the debuggable flag set.
Josh Gaobd396c02020-01-22 18:02:19 -0800485 control_ctx_.reset(adbconnection_client_new(info_ptrs, std::size(infos)));
486 if (control_ctx_) {
487 return true;
488 }
Alex Lightfbf96702017-12-14 13:27:13 -0800489
Josh Gaobd396c02020-01-22 18:02:19 -0800490 // We failed to connect.
491 usleep(sleep_ms * 1000);
Alex Lightfbf96702017-12-14 13:27:13 -0800492
Josh Gaobd396c02020-01-22 18:02:19 -0800493 sleep_ms += (sleep_ms >> 1);
494 if (sleep_ms > sleep_max_ms) {
495 sleep_ms = sleep_max_ms;
Alex Lightfbf96702017-12-14 13:27:13 -0800496 }
497 }
Josh Gaobd396c02020-01-22 18:02:19 -0800498
Alex Lightfbf96702017-12-14 13:27:13 -0800499 return false;
500}
501
502void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800503 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800504 CHECK_EQ(self->GetState(), art::kNative);
Ziang Wan92db59b2019-07-22 21:19:24 +0000505 art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800506 self->SetState(art::kWaitingInMainDebuggerLoop);
507 // shutting_down_ set by StopDebuggerThreads
508 while (!shutting_down_) {
Josh Gaobd396c02020-01-22 18:02:19 -0800509 // First, connect to adbd if we haven't already.
510 if (!control_ctx_ && !SetupAdbConnection()) {
Alex Lightfbf96702017-12-14 13:27:13 -0800511 LOG(ERROR) << "Failed to setup adb connection.";
512 return;
513 }
Josh Gaobd396c02020-01-22 18:02:19 -0800514 while (!shutting_down_ && control_ctx_) {
Alex Light15b81132018-01-24 13:29:07 -0800515 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800516 struct pollfd pollfds[4] = {
517 { sleep_event_fd_, POLLIN, 0 },
518 // -1 as an fd causes it to be ignored by poll
519 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
520 // Check for the control_sock_ actually going away. Only do this if we don't have an active
521 // connection.
Josh Gaobd396c02020-01-22 18:02:19 -0800522 { (adb_connection_socket_ == -1 ? adbconnection_client_pollfd(control_ctx_.get()) : -1),
523 POLLIN | POLLRDHUP, 0 },
Alex Lightfbf96702017-12-14 13:27:13 -0800524 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
525 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800526 // data that the agent or this plugin can handle.
527 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800528 };
529 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
530 if (res < 0) {
531 PLOG(ERROR) << "Failed to poll!";
532 return;
533 }
534 // We don't actually care about doing this we just use it to wake us up.
535 // const struct pollfd& sleep_event_poll = pollfds[0];
536 const struct pollfd& agent_control_sock_poll = pollfds[1];
537 const struct pollfd& control_sock_poll = pollfds[2];
538 const struct pollfd& adb_socket_poll = pollfds[3];
539 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
540 DCHECK(agent_loaded_);
541 char buf[257];
542 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
543 if (res < 0) {
544 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
545 continue;
546 } else {
547 buf[res + 1] = '\0';
548 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
549 }
550 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
551 agent_listening_ = true;
552 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700553 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800554 }
555 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
556 agent_listening_ = false;
557 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
558 CloseFds();
559 agent_has_socket_ = false;
560 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
561 agent_has_socket_ = true;
562 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800563 // We will only ever do the handshake once so reset this.
564 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800565 } else {
566 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
567 }
568 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
569 bool maybe_send_fds = false;
570 {
571 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
572 ScopedEventFdLock sefdl(adb_write_event_fd_);
Josh Gaobd396c02020-01-22 18:02:19 -0800573 android::base::unique_fd new_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800574 if (new_fd == -1) {
575 // Something went wrong. We need to retry getting the control socket.
Josh Gaobd396c02020-01-22 18:02:19 -0800576 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800577 break;
578 } else if (adb_connection_socket_ != -1) {
579 // We already have a connection.
580 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
581 if (new_fd >= 0) {
582 new_fd.reset();
583 }
584 } else {
585 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
586 adb_connection_socket_ = std::move(new_fd);
587 maybe_send_fds = true;
588 }
589 }
590 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
591 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800592 // The agent was already loaded so this must be after a disconnection. Therefore have the
593 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700594 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800595 }
596 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
597 // The other end of the adb connection just dropped it.
598 // Reset the connection since we don't have an active socket through the adb server.
599 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
600 << "connection active";
Josh Gaobd396c02020-01-22 18:02:19 -0800601 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800602 break;
603 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
604 DCHECK(!agent_has_socket_);
605 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800606 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800607 } else if (agent_listening_ && !sent_agent_fds_) {
608 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800609 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700610 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800611 }
Alex Light15b81132018-01-24 13:29:07 -0800612 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
613 DCHECK(!agent_has_socket_);
614 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800615 } else {
616 VLOG(jdwp) << "Woke up poll without anything to do!";
617 }
618 }
619 }
620}
621
Alex Light15b81132018-01-24 13:29:07 -0800622static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
623 uint32_t res;
624 memcpy(&res, *in, sizeof(uint32_t));
625 *in = (*in) + sizeof(uint32_t);
626 return ntohl(res);
627}
628
629void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
630 DCHECK(!agent_loaded_);
631 DCHECK(!agent_listening_);
632 // TODO Should we check in some other way if we are userdebug/eng?
633 CHECK(art::Dbg::IsJdwpAllowed());
634 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
635 if (!performed_handshake_) {
636 PerformHandshake();
637 return;
638 }
639 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
640 // to see if it's one we can handle. This doesn't change the state of the socket.
641 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
642 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
643 packet_header,
644 sizeof(packet_header),
645 MSG_PEEK));
646 // We want to be very careful not to change the socket state until we know we succeeded. This will
647 // let us fall-back to just loading the agent and letting it deal with everything.
648 if (res <= 0) {
649 // Close the socket. We either hit EOF or an error.
650 if (res < 0) {
651 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
652 }
653 CloseFds();
654 return;
655 } else if (res < static_cast<int>(kPacketHeaderLen)) {
656 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
657 AttachJdwpAgent(self);
658 return;
659 }
660 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
661 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
662 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
663 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
664 if (pkt_cmd_set != kDdmCommandSet ||
665 pkt_cmd != kDdmChunkCommand ||
666 full_len < kPacketHeaderLen) {
667 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
668 AttachJdwpAgent(self);
669 return;
670 }
671 uint32_t avail = -1;
672 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
673 if (res < 0) {
674 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
675 CloseFds();
676 return;
677 } else if (avail < full_len) {
678 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
679 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
680 << "Loading jdwp agent to deal with this.";
681 AttachJdwpAgent(self);
682 return;
683 }
684 // Actually read the data.
685 std::vector<uint8_t> full_pkt;
686 full_pkt.resize(full_len);
687 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
688 if (res < 0) {
689 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
690 CloseFds();
691 return;
692 }
693 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
694 size_t data_size = full_len - kPacketHeaderLen;
695 if (data_size < (sizeof(uint32_t) * 2)) {
696 // This is an error (the data isn't long enough) but to match historical behavior we need to
697 // ignore it.
698 return;
699 }
700 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
701 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
702 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
703 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
704 // This is an error (the data isn't long enough) but to match historical behavior we need to
705 // ignore it.
706 return;
707 }
708
709 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700710 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800711 }
712 uint32_t reply_type;
713 std::vector<uint8_t> reply;
714 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
715 ddm_type,
716 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
717 ddm_len),
718 /*out*/&reply_type,
719 /*out*/&reply)) {
720 // To match historical behavior we don't send any response when there is no data to reply with.
721 return;
722 }
723 SendDdmPacket(pkt_id,
724 DdmPacketType::kReply,
725 reply_type,
726 art::ArrayRef<const uint8_t>(reply));
727}
728
729void AdbConnectionState::PerformHandshake() {
730 CHECK(!performed_handshake_);
731 // Check to make sure we are able to read the whole handshake.
732 uint32_t avail = -1;
733 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
734 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
735 if (res < 0) {
736 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
737 }
738 LOG(WARNING) << "Closing connection to broken client.";
739 CloseFds();
740 return;
741 }
742 // Perform the handshake.
743 char handshake_msg[sizeof(kJdwpHandshake)];
744 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
745 handshake_msg,
746 sizeof(handshake_msg),
747 MSG_DONTWAIT));
748 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
749 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
750 if (res < 0) {
751 PLOG(ERROR) << "Failed to read handshake!";
752 }
753 LOG(WARNING) << "Handshake failed!";
754 CloseFds();
755 return;
756 }
757 // Send the handshake back.
758 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
759 kJdwpHandshake,
760 sizeof(kJdwpHandshake),
761 0));
762 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
763 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
764 CloseFds();
765 return;
766 }
767 performed_handshake_ = true;
768}
769
770void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700771 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800772 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700773 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700774 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700775 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800776 if (self->IsExceptionPending()) {
777 LOG(ERROR) << "Failed to load agent " << agent_name_;
778 art::ScopedObjectAccess soa(self);
779 self->GetException()->Dump();
780 self->ClearException();
781 return;
782 }
783 agent_loaded_ = true;
784}
785
Alex Light81f75c32018-01-26 09:46:32 -0800786bool ContainsArgument(const std::string& opts, const char* arg) {
787 return opts.find(arg) != std::string::npos;
788}
789
790bool ValidateJdwpOptions(const std::string& opts) {
791 bool res = true;
792 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
793 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
794 // for the fd's to be passed down.
795 if (ContainsArgument(opts, "server=n")) {
796 res = false;
797 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
798 }
799 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
800 // everything.
801 if (ContainsArgument(opts, "suspend=y")) {
802 res = false;
803 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
804 }
805 return res;
806}
807
Alex Lightfbf96702017-12-14 13:27:13 -0800808std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800809 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800810 DCHECK(ValidateJdwpOptions(opts));
811 // TODO Get agent_name_ from something user settable?
812 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
813 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
814 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
815 // we will add it if it wasn't already present for the convenience of the user.
816 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
817 // See the comment above for why we need to be suspend=n. Since the agent defaults to
818 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700819 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800820 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800821}
822
823void AdbConnectionState::StopDebuggerThreads() {
824 // The regular agent system will take care of unloading the agent (if needed).
825 shutting_down_ = true;
826 // Wakeup the poll loop.
827 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800828 if (sleep_event_fd_ != -1) {
829 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
830 }
Alex Lightfbf96702017-12-14 13:27:13 -0800831}
832
833// The plugin initialization function.
Alex Light3b08bcc2019-09-11 09:48:51 -0700834extern "C" bool ArtPlugin_Initialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800835 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
836 // TODO Provide some way for apps to set this maybe?
Flash Liu013e2082019-10-31 11:18:55 +0800837 gState.emplace(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800838 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800839}
840
841extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800842 gState->StopDebuggerThreads();
Alex Lightfbf96702017-12-14 13:27:13 -0800843 return true;
844}
845
846} // namespace adbconnection