blob: c512b0678beb477dfc1abe0f2f14d8ebe1ef66fd [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
Alex Lightfbf96702017-12-14 13:27:13 -080086static AdbConnectionState* gState;
87
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
158static jobject CreateAdbConnectionThread(art::Thread* thr) {
159 JNIEnv* env = thr->GetJniEnv();
160 // Move to native state to talk with the jnienv api.
161 art::ScopedThreadStateChange stsc(thr, art::kNative);
162 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
163 ScopedLocalRef<jobject> thr_group(
164 env,
165 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
166 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
167 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
168 art::WellKnownClasses::java_lang_Thread_init,
169 thr_group.get(),
170 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700171 /*Priority=*/ 0,
172 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800173}
174
175struct CallbackData {
176 AdbConnectionState* this_;
177 jobject thr_;
178};
179
180static void* CallbackFunction(void* vdata) {
181 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
Alex Lightd6f9d852018-01-25 11:26:28 -0800182 CHECK(data->this_ == gState);
Alex Lightfbf96702017-12-14 13:27:13 -0800183 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
184 true,
185 data->thr_);
186 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
187 // The name in Attach() is only for logging. Set the thread name. This is important so
188 // that the thread is no longer seen as starting up.
189 {
190 art::ScopedObjectAccess soa(self);
191 self->SetThreadName(kAdbConnectionThreadName);
192 }
193
194 // Release the peer.
195 JNIEnv* env = self->GetJniEnv();
196 env->DeleteGlobalRef(data->thr_);
197 data->thr_ = nullptr;
198 {
199 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
200 // before going into the provided code.
201 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
202 art::Runtime::Current()->EndThreadBirth();
203 }
204 data->this_->RunPollLoop(self);
205 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
206 CHECK_EQ(detach_result, 0);
207
Alex Lightd6f9d852018-01-25 11:26:28 -0800208 // Get rid of the connection
209 gState = nullptr;
210 delete data->this_;
211
Alex Lightfbf96702017-12-14 13:27:13 -0800212 return nullptr;
213}
214
215void AdbConnectionState::StartDebuggerThreads() {
216 // First do all the final setup we need.
217 CHECK_EQ(adb_write_event_fd_.get(), -1);
218 CHECK_EQ(sleep_event_fd_.get(), -1);
219 CHECK_EQ(local_agent_control_sock_.get(), -1);
220 CHECK_EQ(remote_agent_control_sock_.get(), -1);
221
222 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
223 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
224 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
225 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
226
227 {
228 art::ScopedObjectAccess soa(art::Thread::Current());
229 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
230 }
231 // Setup the socketpair we use to talk to the agent.
232 bool has_sockets;
233 do {
234 has_sockets = android::base::Socketpair(AF_UNIX,
235 SOCK_SEQPACKET | SOCK_CLOEXEC,
236 0,
237 &local_agent_control_sock_,
238 &remote_agent_control_sock_);
239 } while (!has_sockets && errno == EINTR);
240 if (!has_sockets) {
241 PLOG(FATAL) << "Unable to create socketpair for agent control!";
242 }
243
244 // Next start the threads.
245 art::Thread* self = art::Thread::Current();
246 art::ScopedObjectAccess soa(self);
247 {
248 art::Runtime* runtime = art::Runtime::Current();
249 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
250 if (runtime->IsShuttingDownLocked()) {
251 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
252 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
253 return;
254 }
255 runtime->StartThreadBirth();
256 }
257 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700258 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
259 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800260 pthread_t pthread;
261 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800262 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800263 int pthread_create_result = pthread_create(&pthread,
264 nullptr,
265 &CallbackFunction,
266 data.get());
267 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800268 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800269 // If the create succeeded the other thread will call EndThreadBirth.
270 art::Runtime* runtime = art::Runtime::Current();
271 soa.Env()->DeleteGlobalRef(data->thr_);
272 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
273 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
274 runtime->EndThreadBirth();
275 return;
276 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700277 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800278}
279
280static bool FlagsSet(int16_t data, int16_t flags) {
281 return (data & flags) == flags;
282}
283
284void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800285 {
286 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
287 // closed.
288 ScopedEventFdLock lk(adb_write_event_fd_);
289 // shutdown(adb_connection_socket_, SHUT_RDWR);
290 adb_connection_socket_.reset();
291 }
292
293 // If we didn't load anything we will need to do the handshake again.
294 performed_handshake_ = false;
295
296 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
297 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700298 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800299 }
300}
301
302void AdbConnectionState::NotifyDdms(bool active) {
303 art::ScopedObjectAccess soa(art::Thread::Current());
304 DCHECK_NE(notified_ddm_active_, active);
305 notified_ddm_active_ = active;
306 if (active) {
307 art::Dbg::DdmConnected();
308 } else {
309 art::Dbg::DdmDisconnected();
310 }
Alex Lightfbf96702017-12-14 13:27:13 -0800311}
312
313uint32_t AdbConnectionState::NextDdmId() {
314 // Just have a normal counter but always set the sign bit.
315 return (next_ddm_id_++) | 0x80000000;
316}
317
318void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800319 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
320}
321
322void AdbConnectionState::SendDdmPacket(uint32_t id,
323 DdmPacketType packet_type,
324 uint32_t type,
325 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800326 // Get the write_event early to fail fast.
327 ScopedEventFdLock lk(adb_write_event_fd_);
328 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800329 VLOG(jdwp) << "Not sending ddms data of type "
330 << StringPrintf("%c%c%c%c",
331 static_cast<char>(type >> 24),
332 static_cast<char>(type >> 16),
333 static_cast<char>(type >> 8),
334 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800335 // Adb is not connected.
336 return;
337 }
338
339 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
340 // after we have sent our data.
341 static constexpr uint32_t kDdmPacketHeaderSize =
Alex Lightfc588092020-01-23 15:39:08 -0800342 kJdwpHeaderLen // jdwp command packet size
Alex Lightfbf96702017-12-14 13:27:13 -0800343 + sizeof(uint32_t) // Type
344 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800345 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800346 uint8_t* pkt_data = pkt.data();
347
348 // Write the length first.
349 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
350 pkt_data += sizeof(uint32_t);
351
352 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800353 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800354 pkt_data += sizeof(uint32_t);
355
356 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800357 *(pkt_data++) = static_cast<uint8_t>(packet_type);
358 switch (packet_type) {
359 case DdmPacketType::kCmd: {
360 // Now the cmd-set
Alex Lightfc588092020-01-23 15:39:08 -0800361 *(pkt_data++) = kJdwpDdmCmdSet;
Alex Light15b81132018-01-24 13:29:07 -0800362 // Now the command
Alex Lightfc588092020-01-23 15:39:08 -0800363 *(pkt_data++) = kJdwpDdmCmd;
Alex Light15b81132018-01-24 13:29:07 -0800364 break;
365 }
366 case DdmPacketType::kReply: {
367 // This is the error code bytes which are all 0
368 *(pkt_data++) = 0;
369 *(pkt_data++) = 0;
370 }
371 }
Alex Lightfbf96702017-12-14 13:27:13 -0800372
Alex Light15b81132018-01-24 13:29:07 -0800373 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800374 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800375 uint32_t net_type = htonl(type);
376 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800377 pkt_data += sizeof(uint32_t);
378
379 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800380 uint32_t net_len = htonl(data.size());
381 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800382 pkt_data += sizeof(uint32_t);
383
384 static uint32_t constexpr kIovSize = 2;
385 struct iovec iovs[kIovSize] = {
386 { pkt.data(), pkt.size() },
387 { const_cast<uint8_t*>(data.data()), data.size() },
388 };
389 // now pkt_header has the header.
390 // use writev to send the actual data.
391 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
392 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
393 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
394 static_cast<char>(type >> 24),
395 static_cast<char>(type >> 16),
396 static_cast<char>(type >> 8),
397 static_cast<char>(type),
398 res, data.size() + kDdmPacketHeaderSize);
399 } else {
400 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
401 static_cast<char>(type >> 24),
402 static_cast<char>(type >> 16),
403 static_cast<char>(type >> 8),
404 static_cast<char>(type),
405 data.size() + kDdmPacketHeaderSize);
406 }
407}
408
Alex Light15b81132018-01-24 13:29:07 -0800409void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800410 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800411 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800412 union {
413 cmsghdr cm;
414 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
415 } cm_un;
416 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800417 iov.iov_base = const_cast<char*>(message);
418 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800419
420 msghdr msg;
421 msg.msg_name = nullptr;
422 msg.msg_namelen = 0;
423 msg.msg_iov = &iov;
424 msg.msg_iovlen = 1;
425 msg.msg_flags = 0;
426 msg.msg_control = cm_un.buffer;
427 msg.msg_controllen = sizeof(cm_un.buffer);
428
429 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
430 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
431 cmsg->cmsg_level = SOL_SOCKET;
432 cmsg->cmsg_type = SCM_RIGHTS;
433
434 // Duplicate the fds before sending them.
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700435 android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800436 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700437 android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800438 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700439 android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
Alex Lightfbf96702017-12-14 13:27:13 -0800440 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
441
442 dt_fd_forward::FdSet {
443 read_fd.get(), write_fd.get(), write_lock_fd.get()
444 }.WriteData(CMSG_DATA(cmsg));
445
446 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
447 if (res < 0) {
448 PLOG(ERROR) << "Failed to send agent adb connection fds.";
449 } else {
450 sent_agent_fds_ = true;
451 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
452 }
453}
454
455android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
Josh Gaobd396c02020-01-22 18:02:19 -0800456 return android::base::unique_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800457}
458
459bool AdbConnectionState::SetupAdbConnection() {
Josh Gaobd396c02020-01-22 18:02:19 -0800460 int sleep_ms = 500;
461 const int sleep_max_ms = 2 * 1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800462
Josh Gaobd396c02020-01-22 18:02:19 -0800463 const AdbConnectionClientInfo infos[] = {
464 {.type = AdbConnectionClientInfoType::pid, .data.pid = static_cast<uint64_t>(getpid())},
465 {.type = AdbConnectionClientInfoType::debuggable, .data.debuggable = true},
466 };
467 const AdbConnectionClientInfo* info_ptrs[] = {&infos[0], &infos[1]};
Alex Lightfbf96702017-12-14 13:27:13 -0800468
469 while (!shutting_down_) {
470 // If adbd isn't running, because USB debugging was disabled or
471 // perhaps the system is restarting it for "adb root", the
472 // connect() will fail. We loop here forever waiting for it
473 // to come back.
474 //
475 // Waking up and polling every couple of seconds is generally a
476 // bad thing to do, but we only do this if the application is
477 // debuggable *and* adbd isn't running. Still, for the sake
478 // of battery life, we should consider timing out and giving
479 // up after a few minutes in case somebody ships an app with
480 // the debuggable flag set.
Josh Gaobd396c02020-01-22 18:02:19 -0800481 control_ctx_.reset(adbconnection_client_new(info_ptrs, std::size(infos)));
482 if (control_ctx_) {
483 return true;
484 }
Alex Lightfbf96702017-12-14 13:27:13 -0800485
Josh Gaobd396c02020-01-22 18:02:19 -0800486 // We failed to connect.
487 usleep(sleep_ms * 1000);
Alex Lightfbf96702017-12-14 13:27:13 -0800488
Josh Gaobd396c02020-01-22 18:02:19 -0800489 sleep_ms += (sleep_ms >> 1);
490 if (sleep_ms > sleep_max_ms) {
491 sleep_ms = sleep_max_ms;
Alex Lightfbf96702017-12-14 13:27:13 -0800492 }
493 }
Josh Gaobd396c02020-01-22 18:02:19 -0800494
Alex Lightfbf96702017-12-14 13:27:13 -0800495 return false;
496}
497
498void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800499 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800500 CHECK_EQ(self->GetState(), art::kNative);
Ziang Wan92db59b2019-07-22 21:19:24 +0000501 art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800502 self->SetState(art::kWaitingInMainDebuggerLoop);
503 // shutting_down_ set by StopDebuggerThreads
504 while (!shutting_down_) {
Josh Gaobd396c02020-01-22 18:02:19 -0800505 // First, connect to adbd if we haven't already.
506 if (!control_ctx_ && !SetupAdbConnection()) {
Alex Lightfbf96702017-12-14 13:27:13 -0800507 LOG(ERROR) << "Failed to setup adb connection.";
508 return;
509 }
Josh Gaobd396c02020-01-22 18:02:19 -0800510 while (!shutting_down_ && control_ctx_) {
Alex Light15b81132018-01-24 13:29:07 -0800511 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800512 struct pollfd pollfds[4] = {
513 { sleep_event_fd_, POLLIN, 0 },
514 // -1 as an fd causes it to be ignored by poll
515 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
516 // Check for the control_sock_ actually going away. Only do this if we don't have an active
517 // connection.
Josh Gaobd396c02020-01-22 18:02:19 -0800518 { (adb_connection_socket_ == -1 ? adbconnection_client_pollfd(control_ctx_.get()) : -1),
519 POLLIN | POLLRDHUP, 0 },
Alex Lightfbf96702017-12-14 13:27:13 -0800520 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
521 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800522 // data that the agent or this plugin can handle.
523 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800524 };
525 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
526 if (res < 0) {
527 PLOG(ERROR) << "Failed to poll!";
528 return;
529 }
530 // We don't actually care about doing this we just use it to wake us up.
531 // const struct pollfd& sleep_event_poll = pollfds[0];
532 const struct pollfd& agent_control_sock_poll = pollfds[1];
533 const struct pollfd& control_sock_poll = pollfds[2];
534 const struct pollfd& adb_socket_poll = pollfds[3];
535 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
536 DCHECK(agent_loaded_);
537 char buf[257];
538 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
539 if (res < 0) {
540 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
541 continue;
542 } else {
543 buf[res + 1] = '\0';
544 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
545 }
546 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
547 agent_listening_ = true;
548 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700549 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800550 }
551 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
552 agent_listening_ = false;
553 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
554 CloseFds();
555 agent_has_socket_ = false;
556 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
557 agent_has_socket_ = true;
558 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800559 // We will only ever do the handshake once so reset this.
560 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800561 } else {
562 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
563 }
564 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
565 bool maybe_send_fds = false;
566 {
567 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
568 ScopedEventFdLock sefdl(adb_write_event_fd_);
Josh Gaobd396c02020-01-22 18:02:19 -0800569 android::base::unique_fd new_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800570 if (new_fd == -1) {
571 // Something went wrong. We need to retry getting the control socket.
Josh Gaobd396c02020-01-22 18:02:19 -0800572 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800573 break;
574 } else if (adb_connection_socket_ != -1) {
575 // We already have a connection.
576 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
577 if (new_fd >= 0) {
578 new_fd.reset();
579 }
580 } else {
581 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
582 adb_connection_socket_ = std::move(new_fd);
583 maybe_send_fds = true;
584 }
585 }
586 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
587 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800588 // The agent was already loaded so this must be after a disconnection. Therefore have the
589 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700590 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800591 }
592 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
593 // The other end of the adb connection just dropped it.
594 // Reset the connection since we don't have an active socket through the adb server.
595 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
596 << "connection active";
Josh Gaobd396c02020-01-22 18:02:19 -0800597 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800598 break;
599 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
600 DCHECK(!agent_has_socket_);
601 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800602 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800603 } else if (agent_listening_ && !sent_agent_fds_) {
604 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800605 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700606 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800607 }
Alex Light15b81132018-01-24 13:29:07 -0800608 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
609 DCHECK(!agent_has_socket_);
610 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800611 } else {
612 VLOG(jdwp) << "Woke up poll without anything to do!";
613 }
614 }
615 }
616}
617
Alex Light15b81132018-01-24 13:29:07 -0800618static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
619 uint32_t res;
620 memcpy(&res, *in, sizeof(uint32_t));
621 *in = (*in) + sizeof(uint32_t);
622 return ntohl(res);
623}
624
625void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
626 DCHECK(!agent_loaded_);
627 DCHECK(!agent_listening_);
628 // TODO Should we check in some other way if we are userdebug/eng?
629 CHECK(art::Dbg::IsJdwpAllowed());
630 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
631 if (!performed_handshake_) {
632 PerformHandshake();
633 return;
634 }
635 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
636 // to see if it's one we can handle. This doesn't change the state of the socket.
637 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
638 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
639 packet_header,
640 sizeof(packet_header),
641 MSG_PEEK));
642 // We want to be very careful not to change the socket state until we know we succeeded. This will
643 // let us fall-back to just loading the agent and letting it deal with everything.
644 if (res <= 0) {
645 // Close the socket. We either hit EOF or an error.
646 if (res < 0) {
647 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
648 }
649 CloseFds();
650 return;
651 } else if (res < static_cast<int>(kPacketHeaderLen)) {
652 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
653 AttachJdwpAgent(self);
654 return;
655 }
656 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
657 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
658 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
659 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
660 if (pkt_cmd_set != kDdmCommandSet ||
661 pkt_cmd != kDdmChunkCommand ||
662 full_len < kPacketHeaderLen) {
663 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
664 AttachJdwpAgent(self);
665 return;
666 }
667 uint32_t avail = -1;
668 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
669 if (res < 0) {
670 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
671 CloseFds();
672 return;
673 } else if (avail < full_len) {
674 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
675 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
676 << "Loading jdwp agent to deal with this.";
677 AttachJdwpAgent(self);
678 return;
679 }
680 // Actually read the data.
681 std::vector<uint8_t> full_pkt;
682 full_pkt.resize(full_len);
683 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
684 if (res < 0) {
685 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
686 CloseFds();
687 return;
688 }
689 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
690 size_t data_size = full_len - kPacketHeaderLen;
691 if (data_size < (sizeof(uint32_t) * 2)) {
692 // This is an error (the data isn't long enough) but to match historical behavior we need to
693 // ignore it.
694 return;
695 }
696 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
697 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
698 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
699 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
700 // This is an error (the data isn't long enough) but to match historical behavior we need to
701 // ignore it.
702 return;
703 }
704
705 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700706 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800707 }
708 uint32_t reply_type;
709 std::vector<uint8_t> reply;
710 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
711 ddm_type,
712 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
713 ddm_len),
714 /*out*/&reply_type,
715 /*out*/&reply)) {
716 // To match historical behavior we don't send any response when there is no data to reply with.
717 return;
718 }
719 SendDdmPacket(pkt_id,
720 DdmPacketType::kReply,
721 reply_type,
722 art::ArrayRef<const uint8_t>(reply));
723}
724
725void AdbConnectionState::PerformHandshake() {
726 CHECK(!performed_handshake_);
727 // Check to make sure we are able to read the whole handshake.
728 uint32_t avail = -1;
729 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
730 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
731 if (res < 0) {
732 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
733 }
734 LOG(WARNING) << "Closing connection to broken client.";
735 CloseFds();
736 return;
737 }
738 // Perform the handshake.
739 char handshake_msg[sizeof(kJdwpHandshake)];
740 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
741 handshake_msg,
742 sizeof(handshake_msg),
743 MSG_DONTWAIT));
744 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
745 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
746 if (res < 0) {
747 PLOG(ERROR) << "Failed to read handshake!";
748 }
749 LOG(WARNING) << "Handshake failed!";
750 CloseFds();
751 return;
752 }
753 // Send the handshake back.
754 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
755 kJdwpHandshake,
756 sizeof(kJdwpHandshake),
757 0));
758 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
759 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
760 CloseFds();
761 return;
762 }
763 performed_handshake_ = true;
764}
765
766void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700767 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800768 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700769 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700770 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700771 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800772 if (self->IsExceptionPending()) {
773 LOG(ERROR) << "Failed to load agent " << agent_name_;
774 art::ScopedObjectAccess soa(self);
775 self->GetException()->Dump();
776 self->ClearException();
777 return;
778 }
779 agent_loaded_ = true;
780}
781
Alex Light81f75c32018-01-26 09:46:32 -0800782bool ContainsArgument(const std::string& opts, const char* arg) {
783 return opts.find(arg) != std::string::npos;
784}
785
786bool ValidateJdwpOptions(const std::string& opts) {
787 bool res = true;
788 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
789 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
790 // for the fd's to be passed down.
791 if (ContainsArgument(opts, "server=n")) {
792 res = false;
793 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
794 }
795 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
796 // everything.
797 if (ContainsArgument(opts, "suspend=y")) {
798 res = false;
799 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
800 }
801 return res;
802}
803
Alex Lightfbf96702017-12-14 13:27:13 -0800804std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800805 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800806 DCHECK(ValidateJdwpOptions(opts));
807 // TODO Get agent_name_ from something user settable?
808 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
809 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
810 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
811 // we will add it if it wasn't already present for the convenience of the user.
812 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
813 // See the comment above for why we need to be suspend=n. Since the agent defaults to
814 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700815 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800816 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800817}
818
819void AdbConnectionState::StopDebuggerThreads() {
820 // The regular agent system will take care of unloading the agent (if needed).
821 shutting_down_ = true;
822 // Wakeup the poll loop.
823 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800824 if (sleep_event_fd_ != -1) {
825 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
826 }
Alex Lightfbf96702017-12-14 13:27:13 -0800827}
828
829// The plugin initialization function.
Alex Light3b08bcc2019-09-11 09:48:51 -0700830extern "C" bool ArtPlugin_Initialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800831 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
832 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800833 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800834 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800835 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800836}
837
838extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800839 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800840 if (!gState->DebuggerThreadsStarted()) {
841 // If debugger threads were started then those threads will delete the state once they are done.
842 delete gState;
843 }
Alex Lightfbf96702017-12-14 13:27:13 -0800844 return true;
845}
846
847} // namespace adbconnection