blob: 6f45be8a66fed32b0c7915e717657af97f401c2a [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() {
Shukang Zhou670ea842020-02-06 14:53:14 -080094 // The debugger thread is started for a debuggable or profileable-from-shell process.
95 // The pid will be send to adbd for adb's "track-jdwp" and "track-app" services.
96 // The thread will also set up the jdwp tunnel if the process is debuggable.
97 if (IsDebuggingPossible() || art::Runtime::Current()->IsProfileableFromShell()) {
Alex Lightfbf96702017-12-14 13:27:13 -080098 connection_->StartDebuggerThreads();
99 } else {
100 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
101 }
102}
103
104// The debugger should begin shutting down since the runtime is ending. We don't actually do
105// anything here. The real shutdown has already happened as far as the agent is concerned.
106void AdbConnectionDebuggerController::StopDebugger() { }
107
108bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
109 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
110}
111
112void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
113 const art::ArrayRef<const uint8_t>& data) {
114 connection_->PublishDdmData(type, data);
115}
116
117class ScopedEventFdLock {
118 public:
119 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
120 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
121 }
122
123 ~ScopedEventFdLock() {
124 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
125 }
126
127 private:
128 int fd_;
129 uint64_t data_;
130};
131
132AdbConnectionState::AdbConnectionState(const std::string& agent_name)
133 : agent_name_(agent_name),
134 controller_(this),
135 ddm_callback_(this),
136 sleep_event_fd_(-1),
Josh Gaobd396c02020-01-22 18:02:19 -0800137 control_ctx_(nullptr, adbconnection_client_destroy),
Alex Lightfbf96702017-12-14 13:27:13 -0800138 local_agent_control_sock_(-1),
139 remote_agent_control_sock_(-1),
140 adb_connection_socket_(-1),
141 adb_write_event_fd_(-1),
142 shutting_down_(false),
143 agent_loaded_(false),
144 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800145 agent_has_socket_(false),
146 sent_agent_fds_(false),
147 performed_handshake_(false),
148 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800149 next_ddm_id_(1),
150 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800151 // Add the startup callback.
152 art::ScopedObjectAccess soa(art::Thread::Current());
153 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
154}
155
Flash Liu013e2082019-10-31 11:18:55 +0800156AdbConnectionState::~AdbConnectionState() {
157 // Remove the startup callback.
158 art::Thread* self = art::Thread::Current();
159 if (self != nullptr) {
160 art::ScopedObjectAccess soa(self);
161 art::Runtime::Current()->GetRuntimeCallbacks()->RemoveDebuggerControlCallback(&controller_);
162 }
163}
164
Alex Lightfbf96702017-12-14 13:27:13 -0800165static jobject CreateAdbConnectionThread(art::Thread* thr) {
166 JNIEnv* env = thr->GetJniEnv();
167 // Move to native state to talk with the jnienv api.
168 art::ScopedThreadStateChange stsc(thr, art::kNative);
169 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
170 ScopedLocalRef<jobject> thr_group(
171 env,
172 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
173 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
174 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
175 art::WellKnownClasses::java_lang_Thread_init,
176 thr_group.get(),
177 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700178 /*Priority=*/ 0,
179 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800180}
181
182struct CallbackData {
183 AdbConnectionState* this_;
184 jobject thr_;
185};
186
187static void* CallbackFunction(void* vdata) {
188 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
189 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
190 true,
191 data->thr_);
192 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
193 // The name in Attach() is only for logging. Set the thread name. This is important so
194 // that the thread is no longer seen as starting up.
195 {
196 art::ScopedObjectAccess soa(self);
197 self->SetThreadName(kAdbConnectionThreadName);
198 }
199
200 // Release the peer.
201 JNIEnv* env = self->GetJniEnv();
202 env->DeleteGlobalRef(data->thr_);
203 data->thr_ = nullptr;
204 {
205 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
206 // before going into the provided code.
207 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
208 art::Runtime::Current()->EndThreadBirth();
209 }
210 data->this_->RunPollLoop(self);
211 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
212 CHECK_EQ(detach_result, 0);
213
214 return nullptr;
215}
216
217void AdbConnectionState::StartDebuggerThreads() {
218 // First do all the final setup we need.
219 CHECK_EQ(adb_write_event_fd_.get(), -1);
220 CHECK_EQ(sleep_event_fd_.get(), -1);
221 CHECK_EQ(local_agent_control_sock_.get(), -1);
222 CHECK_EQ(remote_agent_control_sock_.get(), -1);
223
224 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
225 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
226 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
227 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
228
229 {
230 art::ScopedObjectAccess soa(art::Thread::Current());
231 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
232 }
233 // Setup the socketpair we use to talk to the agent.
234 bool has_sockets;
235 do {
236 has_sockets = android::base::Socketpair(AF_UNIX,
237 SOCK_SEQPACKET | SOCK_CLOEXEC,
238 0,
239 &local_agent_control_sock_,
240 &remote_agent_control_sock_);
241 } while (!has_sockets && errno == EINTR);
242 if (!has_sockets) {
243 PLOG(FATAL) << "Unable to create socketpair for agent control!";
244 }
245
246 // Next start the threads.
247 art::Thread* self = art::Thread::Current();
248 art::ScopedObjectAccess soa(self);
249 {
250 art::Runtime* runtime = art::Runtime::Current();
251 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
252 if (runtime->IsShuttingDownLocked()) {
253 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
254 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
255 return;
256 }
257 runtime->StartThreadBirth();
258 }
259 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700260 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
261 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800262 pthread_t pthread;
263 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800264 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800265 int pthread_create_result = pthread_create(&pthread,
266 nullptr,
267 &CallbackFunction,
268 data.get());
269 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800270 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800271 // If the create succeeded the other thread will call EndThreadBirth.
272 art::Runtime* runtime = art::Runtime::Current();
273 soa.Env()->DeleteGlobalRef(data->thr_);
274 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
275 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
276 runtime->EndThreadBirth();
277 return;
278 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700279 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800280}
281
282static bool FlagsSet(int16_t data, int16_t flags) {
283 return (data & flags) == flags;
284}
285
286void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800287 {
288 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
289 // closed.
290 ScopedEventFdLock lk(adb_write_event_fd_);
291 // shutdown(adb_connection_socket_, SHUT_RDWR);
292 adb_connection_socket_.reset();
293 }
294
295 // If we didn't load anything we will need to do the handshake again.
296 performed_handshake_ = false;
297
298 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
299 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700300 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800301 }
302}
303
304void AdbConnectionState::NotifyDdms(bool active) {
305 art::ScopedObjectAccess soa(art::Thread::Current());
306 DCHECK_NE(notified_ddm_active_, active);
307 notified_ddm_active_ = active;
308 if (active) {
309 art::Dbg::DdmConnected();
310 } else {
311 art::Dbg::DdmDisconnected();
312 }
Alex Lightfbf96702017-12-14 13:27:13 -0800313}
314
315uint32_t AdbConnectionState::NextDdmId() {
316 // Just have a normal counter but always set the sign bit.
317 return (next_ddm_id_++) | 0x80000000;
318}
319
320void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800321 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
322}
323
324void AdbConnectionState::SendDdmPacket(uint32_t id,
325 DdmPacketType packet_type,
326 uint32_t type,
327 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800328 // Get the write_event early to fail fast.
329 ScopedEventFdLock lk(adb_write_event_fd_);
330 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800331 VLOG(jdwp) << "Not sending ddms data of type "
332 << StringPrintf("%c%c%c%c",
333 static_cast<char>(type >> 24),
334 static_cast<char>(type >> 16),
335 static_cast<char>(type >> 8),
336 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800337 // Adb is not connected.
338 return;
339 }
340
341 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
342 // after we have sent our data.
343 static constexpr uint32_t kDdmPacketHeaderSize =
Alex Lightfc588092020-01-23 15:39:08 -0800344 kJdwpHeaderLen // jdwp command packet size
Alex Lightfbf96702017-12-14 13:27:13 -0800345 + sizeof(uint32_t) // Type
346 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800347 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800348 uint8_t* pkt_data = pkt.data();
349
350 // Write the length first.
351 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
352 pkt_data += sizeof(uint32_t);
353
354 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800355 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800356 pkt_data += sizeof(uint32_t);
357
358 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800359 *(pkt_data++) = static_cast<uint8_t>(packet_type);
360 switch (packet_type) {
361 case DdmPacketType::kCmd: {
362 // Now the cmd-set
Alex Lightfc588092020-01-23 15:39:08 -0800363 *(pkt_data++) = kJdwpDdmCmdSet;
Alex Light15b81132018-01-24 13:29:07 -0800364 // Now the command
Alex Lightfc588092020-01-23 15:39:08 -0800365 *(pkt_data++) = kJdwpDdmCmd;
Alex Light15b81132018-01-24 13:29:07 -0800366 break;
367 }
368 case DdmPacketType::kReply: {
369 // This is the error code bytes which are all 0
370 *(pkt_data++) = 0;
371 *(pkt_data++) = 0;
372 }
373 }
Alex Lightfbf96702017-12-14 13:27:13 -0800374
Alex Light15b81132018-01-24 13:29:07 -0800375 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800376 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800377 uint32_t net_type = htonl(type);
378 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800379 pkt_data += sizeof(uint32_t);
380
381 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800382 uint32_t net_len = htonl(data.size());
383 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800384 pkt_data += sizeof(uint32_t);
385
386 static uint32_t constexpr kIovSize = 2;
387 struct iovec iovs[kIovSize] = {
388 { pkt.data(), pkt.size() },
389 { const_cast<uint8_t*>(data.data()), data.size() },
390 };
391 // now pkt_header has the header.
392 // use writev to send the actual data.
393 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
394 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
395 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
396 static_cast<char>(type >> 24),
397 static_cast<char>(type >> 16),
398 static_cast<char>(type >> 8),
399 static_cast<char>(type),
400 res, data.size() + kDdmPacketHeaderSize);
401 } else {
402 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
403 static_cast<char>(type >> 24),
404 static_cast<char>(type >> 16),
405 static_cast<char>(type >> 8),
406 static_cast<char>(type),
407 data.size() + kDdmPacketHeaderSize);
408 }
409}
410
Alex Light15b81132018-01-24 13:29:07 -0800411void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800412 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800413 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800414 union {
415 cmsghdr cm;
416 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
417 } cm_un;
418 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800419 iov.iov_base = const_cast<char*>(message);
420 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800421
422 msghdr msg;
423 msg.msg_name = nullptr;
424 msg.msg_namelen = 0;
425 msg.msg_iov = &iov;
426 msg.msg_iovlen = 1;
427 msg.msg_flags = 0;
428 msg.msg_control = cm_un.buffer;
429 msg.msg_controllen = sizeof(cm_un.buffer);
430
431 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
432 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
433 cmsg->cmsg_level = SOL_SOCKET;
434 cmsg->cmsg_type = SCM_RIGHTS;
435
436 // Duplicate the fds before sending them.
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700437 android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800438 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700439 android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800440 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700441 android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
Alex Lightfbf96702017-12-14 13:27:13 -0800442 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
443
444 dt_fd_forward::FdSet {
445 read_fd.get(), write_fd.get(), write_lock_fd.get()
446 }.WriteData(CMSG_DATA(cmsg));
447
448 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
449 if (res < 0) {
450 PLOG(ERROR) << "Failed to send agent adb connection fds.";
451 } else {
452 sent_agent_fds_ = true;
453 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
454 }
455}
456
457android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
Josh Gaobd396c02020-01-22 18:02:19 -0800458 return android::base::unique_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800459}
460
461bool AdbConnectionState::SetupAdbConnection() {
Josh Gaobd396c02020-01-22 18:02:19 -0800462 int sleep_ms = 500;
463 const int sleep_max_ms = 2 * 1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800464
Shukang Zhou670ea842020-02-06 14:53:14 -0800465 const char* isa = GetInstructionSetString(art::Runtime::Current()->GetInstructionSet());
Josh Gaobd396c02020-01-22 18:02:19 -0800466 const AdbConnectionClientInfo infos[] = {
Shukang Zhou670ea842020-02-06 14:53:14 -0800467 {.type = AdbConnectionClientInfoType::pid,
468 .data.pid = static_cast<uint64_t>(getpid())},
469 {.type = AdbConnectionClientInfoType::debuggable,
470 .data.debuggable = IsDebuggingPossible()},
471 {.type = AdbConnectionClientInfoType::profileable,
472 .data.profileable = art::Runtime::Current()->IsProfileableFromShell()},
473 {.type = AdbConnectionClientInfoType::architecture,
474 // GetInstructionSetString() returns a null-terminating C-style string.
475 .data.architecture.name = isa,
476 .data.architecture.size = strlen(isa)},
Josh Gaobd396c02020-01-22 18:02:19 -0800477 };
Shukang Zhou670ea842020-02-06 14:53:14 -0800478 const AdbConnectionClientInfo *info_ptrs[] = {&infos[0], &infos[1], &infos[2], &infos[3]};
Alex Lightfbf96702017-12-14 13:27:13 -0800479
480 while (!shutting_down_) {
481 // If adbd isn't running, because USB debugging was disabled or
482 // perhaps the system is restarting it for "adb root", the
483 // connect() will fail. We loop here forever waiting for it
484 // to come back.
485 //
486 // Waking up and polling every couple of seconds is generally a
487 // bad thing to do, but we only do this if the application is
488 // debuggable *and* adbd isn't running. Still, for the sake
489 // of battery life, we should consider timing out and giving
490 // up after a few minutes in case somebody ships an app with
491 // the debuggable flag set.
Josh Gaobd396c02020-01-22 18:02:19 -0800492 control_ctx_.reset(adbconnection_client_new(info_ptrs, std::size(infos)));
493 if (control_ctx_) {
494 return true;
495 }
Alex Lightfbf96702017-12-14 13:27:13 -0800496
Josh Gaobd396c02020-01-22 18:02:19 -0800497 // We failed to connect.
498 usleep(sleep_ms * 1000);
Alex Lightfbf96702017-12-14 13:27:13 -0800499
Josh Gaobd396c02020-01-22 18:02:19 -0800500 sleep_ms += (sleep_ms >> 1);
501 if (sleep_ms > sleep_max_ms) {
502 sleep_ms = sleep_max_ms;
Alex Lightfbf96702017-12-14 13:27:13 -0800503 }
504 }
Josh Gaobd396c02020-01-22 18:02:19 -0800505
Alex Lightfbf96702017-12-14 13:27:13 -0800506 return false;
507}
508
509void AdbConnectionState::RunPollLoop(art::Thread* self) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800510 DCHECK(IsDebuggingPossible() || art::Runtime::Current()->IsProfileableFromShell());
Alex Lightd6f9d852018-01-25 11:26:28 -0800511 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800512 CHECK_EQ(self->GetState(), art::kNative);
Ziang Wan92db59b2019-07-22 21:19:24 +0000513 art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800514 self->SetState(art::kWaitingInMainDebuggerLoop);
515 // shutting_down_ set by StopDebuggerThreads
516 while (!shutting_down_) {
Josh Gaobd396c02020-01-22 18:02:19 -0800517 // First, connect to adbd if we haven't already.
518 if (!control_ctx_ && !SetupAdbConnection()) {
Alex Lightfbf96702017-12-14 13:27:13 -0800519 LOG(ERROR) << "Failed to setup adb connection.";
520 return;
521 }
Josh Gaobd396c02020-01-22 18:02:19 -0800522 while (!shutting_down_ && control_ctx_) {
Alex Light15b81132018-01-24 13:29:07 -0800523 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800524 struct pollfd pollfds[4] = {
525 { sleep_event_fd_, POLLIN, 0 },
526 // -1 as an fd causes it to be ignored by poll
527 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
528 // Check for the control_sock_ actually going away. Only do this if we don't have an active
529 // connection.
Josh Gaobd396c02020-01-22 18:02:19 -0800530 { (adb_connection_socket_ == -1 ? adbconnection_client_pollfd(control_ctx_.get()) : -1),
531 POLLIN | POLLRDHUP, 0 },
Alex Lightfbf96702017-12-14 13:27:13 -0800532 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
533 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800534 // data that the agent or this plugin can handle.
535 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800536 };
537 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
538 if (res < 0) {
539 PLOG(ERROR) << "Failed to poll!";
540 return;
541 }
542 // We don't actually care about doing this we just use it to wake us up.
543 // const struct pollfd& sleep_event_poll = pollfds[0];
544 const struct pollfd& agent_control_sock_poll = pollfds[1];
545 const struct pollfd& control_sock_poll = pollfds[2];
546 const struct pollfd& adb_socket_poll = pollfds[3];
547 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800548 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
Alex Lightfbf96702017-12-14 13:27:13 -0800549 DCHECK(agent_loaded_);
550 char buf[257];
551 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
552 if (res < 0) {
553 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
554 continue;
555 } else {
556 buf[res + 1] = '\0';
557 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
558 }
559 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
560 agent_listening_ = true;
561 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700562 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800563 }
564 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
565 agent_listening_ = false;
566 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
567 CloseFds();
568 agent_has_socket_ = false;
569 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
570 agent_has_socket_ = true;
571 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800572 // We will only ever do the handshake once so reset this.
573 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800574 } else {
575 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
576 }
577 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800578 if (!IsDebuggingPossible()) {
579 // For a profielable process, this path can execute when the adbd restarts.
580 control_ctx_.reset();
581 break;
582 }
Alex Lightfbf96702017-12-14 13:27:13 -0800583 bool maybe_send_fds = false;
584 {
585 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
586 ScopedEventFdLock sefdl(adb_write_event_fd_);
Josh Gaobd396c02020-01-22 18:02:19 -0800587 android::base::unique_fd new_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800588 if (new_fd == -1) {
589 // Something went wrong. We need to retry getting the control socket.
Josh Gaobd396c02020-01-22 18:02:19 -0800590 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800591 break;
592 } else if (adb_connection_socket_ != -1) {
593 // We already have a connection.
594 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
595 if (new_fd >= 0) {
596 new_fd.reset();
597 }
598 } else {
599 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
600 adb_connection_socket_ = std::move(new_fd);
601 maybe_send_fds = true;
602 }
603 }
604 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
605 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800606 // The agent was already loaded so this must be after a disconnection. Therefore have the
607 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700608 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800609 }
610 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
611 // The other end of the adb connection just dropped it.
612 // Reset the connection since we don't have an active socket through the adb server.
Shukang Zhou670ea842020-02-06 14:53:14 -0800613 // Note this path is expected for either debuggable or profileable processes.
Alex Lightfbf96702017-12-14 13:27:13 -0800614 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
615 << "connection active";
Josh Gaobd396c02020-01-22 18:02:19 -0800616 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800617 break;
618 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800619 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
Alex Lightfbf96702017-12-14 13:27:13 -0800620 DCHECK(!agent_has_socket_);
621 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800622 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800623 } else if (agent_listening_ && !sent_agent_fds_) {
624 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800625 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700626 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800627 }
Alex Light15b81132018-01-24 13:29:07 -0800628 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800629 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
Alex Light15b81132018-01-24 13:29:07 -0800630 DCHECK(!agent_has_socket_);
631 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800632 } else {
633 VLOG(jdwp) << "Woke up poll without anything to do!";
634 }
635 }
636 }
637}
638
Alex Light15b81132018-01-24 13:29:07 -0800639static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
640 uint32_t res;
641 memcpy(&res, *in, sizeof(uint32_t));
642 *in = (*in) + sizeof(uint32_t);
643 return ntohl(res);
644}
645
646void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
647 DCHECK(!agent_loaded_);
648 DCHECK(!agent_listening_);
649 // TODO Should we check in some other way if we are userdebug/eng?
650 CHECK(art::Dbg::IsJdwpAllowed());
651 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
652 if (!performed_handshake_) {
653 PerformHandshake();
654 return;
655 }
656 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
657 // to see if it's one we can handle. This doesn't change the state of the socket.
658 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
659 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
660 packet_header,
661 sizeof(packet_header),
662 MSG_PEEK));
663 // We want to be very careful not to change the socket state until we know we succeeded. This will
664 // let us fall-back to just loading the agent and letting it deal with everything.
665 if (res <= 0) {
666 // Close the socket. We either hit EOF or an error.
667 if (res < 0) {
668 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
669 }
670 CloseFds();
671 return;
672 } else if (res < static_cast<int>(kPacketHeaderLen)) {
673 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
674 AttachJdwpAgent(self);
675 return;
676 }
677 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
678 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
679 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
680 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
681 if (pkt_cmd_set != kDdmCommandSet ||
682 pkt_cmd != kDdmChunkCommand ||
683 full_len < kPacketHeaderLen) {
684 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
685 AttachJdwpAgent(self);
686 return;
687 }
688 uint32_t avail = -1;
689 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
690 if (res < 0) {
691 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
692 CloseFds();
693 return;
694 } else if (avail < full_len) {
695 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
696 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
697 << "Loading jdwp agent to deal with this.";
698 AttachJdwpAgent(self);
699 return;
700 }
701 // Actually read the data.
702 std::vector<uint8_t> full_pkt;
703 full_pkt.resize(full_len);
704 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
705 if (res < 0) {
706 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
707 CloseFds();
708 return;
709 }
710 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
711 size_t data_size = full_len - kPacketHeaderLen;
712 if (data_size < (sizeof(uint32_t) * 2)) {
713 // This is an error (the data isn't long enough) but to match historical behavior we need to
714 // ignore it.
715 return;
716 }
717 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
718 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
719 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
720 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
721 // This is an error (the data isn't long enough) but to match historical behavior we need to
722 // ignore it.
723 return;
724 }
725
726 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700727 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800728 }
729 uint32_t reply_type;
730 std::vector<uint8_t> reply;
731 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
732 ddm_type,
733 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
734 ddm_len),
735 /*out*/&reply_type,
736 /*out*/&reply)) {
737 // To match historical behavior we don't send any response when there is no data to reply with.
738 return;
739 }
740 SendDdmPacket(pkt_id,
741 DdmPacketType::kReply,
742 reply_type,
743 art::ArrayRef<const uint8_t>(reply));
744}
745
746void AdbConnectionState::PerformHandshake() {
747 CHECK(!performed_handshake_);
748 // Check to make sure we are able to read the whole handshake.
749 uint32_t avail = -1;
750 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
751 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
752 if (res < 0) {
753 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
754 }
755 LOG(WARNING) << "Closing connection to broken client.";
756 CloseFds();
757 return;
758 }
759 // Perform the handshake.
760 char handshake_msg[sizeof(kJdwpHandshake)];
761 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
762 handshake_msg,
763 sizeof(handshake_msg),
764 MSG_DONTWAIT));
765 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
766 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
767 if (res < 0) {
768 PLOG(ERROR) << "Failed to read handshake!";
769 }
770 LOG(WARNING) << "Handshake failed!";
771 CloseFds();
772 return;
773 }
774 // Send the handshake back.
775 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
776 kJdwpHandshake,
777 sizeof(kJdwpHandshake),
778 0));
779 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
780 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
781 CloseFds();
782 return;
783 }
784 performed_handshake_ = true;
785}
786
787void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700788 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800789 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700790 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700791 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700792 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800793 if (self->IsExceptionPending()) {
794 LOG(ERROR) << "Failed to load agent " << agent_name_;
795 art::ScopedObjectAccess soa(self);
796 self->GetException()->Dump();
797 self->ClearException();
798 return;
799 }
800 agent_loaded_ = true;
801}
802
Alex Light81f75c32018-01-26 09:46:32 -0800803bool ContainsArgument(const std::string& opts, const char* arg) {
804 return opts.find(arg) != std::string::npos;
805}
806
807bool ValidateJdwpOptions(const std::string& opts) {
808 bool res = true;
809 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
810 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
811 // for the fd's to be passed down.
812 if (ContainsArgument(opts, "server=n")) {
813 res = false;
814 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
815 }
816 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
817 // everything.
818 if (ContainsArgument(opts, "suspend=y")) {
819 res = false;
820 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
821 }
822 return res;
823}
824
Alex Lightfbf96702017-12-14 13:27:13 -0800825std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800826 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800827 DCHECK(ValidateJdwpOptions(opts));
828 // TODO Get agent_name_ from something user settable?
829 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
830 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
831 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
832 // we will add it if it wasn't already present for the convenience of the user.
833 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
834 // See the comment above for why we need to be suspend=n. Since the agent defaults to
835 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700836 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800837 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800838}
839
840void AdbConnectionState::StopDebuggerThreads() {
841 // The regular agent system will take care of unloading the agent (if needed).
842 shutting_down_ = true;
843 // Wakeup the poll loop.
844 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800845 if (sleep_event_fd_ != -1) {
846 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
847 }
Alex Lightfbf96702017-12-14 13:27:13 -0800848}
849
850// The plugin initialization function.
Alex Light3b08bcc2019-09-11 09:48:51 -0700851extern "C" bool ArtPlugin_Initialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800852 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
853 // TODO Provide some way for apps to set this maybe?
Flash Liu013e2082019-10-31 11:18:55 +0800854 gState.emplace(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800855 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800856}
857
858extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800859 gState->StopDebuggerThreads();
Alex Lightfbf96702017-12-14 13:27:13 -0800860 return true;
861}
862
863} // namespace adbconnection