blob: 0824eb459b610349a945568aa08daa056680dbea [file] [log] [blame]
Alex Lightfbf96702017-12-14 13:27:13 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <array>
18
19#include "adbconnection.h"
20
21#include "android-base/endian.h"
22#include "android-base/stringprintf.h"
Andreas Gampedfcd82c2018-10-16 20:22:37 -070023#include "base/file_utils.h"
Alex Lightfbf96702017-12-14 13:27:13 -080024#include "base/logging.h"
25#include "base/macros.h"
26#include "base/mutex.h"
Elliott Hughesc2efd4d2018-10-25 13:14:55 -070027#include "base/socket_peer_is_trusted.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010028#include "jni/java_vm_ext.h"
29#include "jni/jni_env_ext.h"
Alex Lightfbf96702017-12-14 13:27:13 -080030#include "mirror/throwable.h"
Orion Hodsond41c7592019-01-27 09:25:47 +000031#include "nativehelper/scoped_local_ref.h"
Alex Lightfbf96702017-12-14 13:27:13 -080032#include "runtime-inl.h"
33#include "runtime_callbacks.h"
34#include "scoped_thread_state_change-inl.h"
35#include "well_known_classes.h"
36
37#include "jdwp/jdwp_priv.h"
38
39#include "fd_transport.h"
40
41#include "poll.h"
42
Alex Light15b81132018-01-24 13:29:07 -080043#include <sys/ioctl.h>
Alex Lightfbf96702017-12-14 13:27:13 -080044#include <sys/socket.h>
45#include <sys/un.h>
46#include <sys/eventfd.h>
47#include <jni.h>
48
49namespace adbconnection {
50
Alex Light15b81132018-01-24 13:29:07 -080051// Messages sent from the transport
Alex Lightfbf96702017-12-14 13:27:13 -080052using dt_fd_forward::kListenStartMessage;
53using dt_fd_forward::kListenEndMessage;
54using dt_fd_forward::kAcceptMessage;
55using dt_fd_forward::kCloseMessage;
56
Alex Light15b81132018-01-24 13:29:07 -080057// Messages sent to the transport
58using dt_fd_forward::kPerformHandshakeMessage;
59using dt_fd_forward::kSkipHandshakeMessage;
60
Alex Lightfbf96702017-12-14 13:27:13 -080061using android::base::StringPrintf;
62
Alex Light15b81132018-01-24 13:29:07 -080063static constexpr const char kJdwpHandshake[14] = {
64 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
65};
66
Alex Lightfbf96702017-12-14 13:27:13 -080067static constexpr int kEventfdLocked = 0;
68static constexpr int kEventfdUnlocked = 1;
69static constexpr int kControlSockSendTimeout = 10;
70
Alex Light15b81132018-01-24 13:29:07 -080071static constexpr size_t kPacketHeaderLen = 11;
72static constexpr off_t kPacketSizeOff = 0;
73static constexpr off_t kPacketIdOff = 4;
74static constexpr off_t kPacketCommandSetOff = 9;
75static constexpr off_t kPacketCommandOff = 10;
76
77static constexpr uint8_t kDdmCommandSet = 199;
78static constexpr uint8_t kDdmChunkCommand = 1;
79
Alex Lightfbf96702017-12-14 13:27:13 -080080static AdbConnectionState* gState;
81
82static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080083 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080084}
85
86// Begin running the debugger.
87void AdbConnectionDebuggerController::StartDebugger() {
88 if (IsDebuggingPossible()) {
89 connection_->StartDebuggerThreads();
90 } else {
91 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
92 }
93}
94
95// The debugger should begin shutting down since the runtime is ending. We don't actually do
96// anything here. The real shutdown has already happened as far as the agent is concerned.
97void AdbConnectionDebuggerController::StopDebugger() { }
98
99bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
100 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
101}
102
103void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
104 const art::ArrayRef<const uint8_t>& data) {
105 connection_->PublishDdmData(type, data);
106}
107
108class ScopedEventFdLock {
109 public:
110 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
111 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
112 }
113
114 ~ScopedEventFdLock() {
115 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
116 }
117
118 private:
119 int fd_;
120 uint64_t data_;
121};
122
123AdbConnectionState::AdbConnectionState(const std::string& agent_name)
124 : agent_name_(agent_name),
125 controller_(this),
126 ddm_callback_(this),
127 sleep_event_fd_(-1),
128 control_sock_(-1),
129 local_agent_control_sock_(-1),
130 remote_agent_control_sock_(-1),
131 adb_connection_socket_(-1),
132 adb_write_event_fd_(-1),
133 shutting_down_(false),
134 agent_loaded_(false),
135 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800136 agent_has_socket_(false),
137 sent_agent_fds_(false),
138 performed_handshake_(false),
139 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800140 next_ddm_id_(1),
141 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800142 // Setup the addr.
143 control_addr_.controlAddrUn.sun_family = AF_UNIX;
144 control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + sizeof(kJdwpControlName) - 1;
145 memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, sizeof(kJdwpControlName) - 1);
146
147 // Add the startup callback.
148 art::ScopedObjectAccess soa(art::Thread::Current());
149 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
150}
151
152static jobject CreateAdbConnectionThread(art::Thread* thr) {
153 JNIEnv* env = thr->GetJniEnv();
154 // Move to native state to talk with the jnienv api.
155 art::ScopedThreadStateChange stsc(thr, art::kNative);
156 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
157 ScopedLocalRef<jobject> thr_group(
158 env,
159 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
160 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
161 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
162 art::WellKnownClasses::java_lang_Thread_init,
163 thr_group.get(),
164 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700165 /*Priority=*/ 0,
166 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800167}
168
169struct CallbackData {
170 AdbConnectionState* this_;
171 jobject thr_;
172};
173
174static void* CallbackFunction(void* vdata) {
175 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
Alex Lightd6f9d852018-01-25 11:26:28 -0800176 CHECK(data->this_ == gState);
Alex Lightfbf96702017-12-14 13:27:13 -0800177 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
178 true,
179 data->thr_);
180 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
181 // The name in Attach() is only for logging. Set the thread name. This is important so
182 // that the thread is no longer seen as starting up.
183 {
184 art::ScopedObjectAccess soa(self);
185 self->SetThreadName(kAdbConnectionThreadName);
186 }
187
188 // Release the peer.
189 JNIEnv* env = self->GetJniEnv();
190 env->DeleteGlobalRef(data->thr_);
191 data->thr_ = nullptr;
192 {
193 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
194 // before going into the provided code.
195 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
196 art::Runtime::Current()->EndThreadBirth();
197 }
198 data->this_->RunPollLoop(self);
199 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
200 CHECK_EQ(detach_result, 0);
201
Alex Lightd6f9d852018-01-25 11:26:28 -0800202 // Get rid of the connection
203 gState = nullptr;
204 delete data->this_;
205
Alex Lightfbf96702017-12-14 13:27:13 -0800206 return nullptr;
207}
208
209void AdbConnectionState::StartDebuggerThreads() {
210 // First do all the final setup we need.
211 CHECK_EQ(adb_write_event_fd_.get(), -1);
212 CHECK_EQ(sleep_event_fd_.get(), -1);
213 CHECK_EQ(local_agent_control_sock_.get(), -1);
214 CHECK_EQ(remote_agent_control_sock_.get(), -1);
215
216 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
217 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
218 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
219 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
220
221 {
222 art::ScopedObjectAccess soa(art::Thread::Current());
223 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
224 }
225 // Setup the socketpair we use to talk to the agent.
226 bool has_sockets;
227 do {
228 has_sockets = android::base::Socketpair(AF_UNIX,
229 SOCK_SEQPACKET | SOCK_CLOEXEC,
230 0,
231 &local_agent_control_sock_,
232 &remote_agent_control_sock_);
233 } while (!has_sockets && errno == EINTR);
234 if (!has_sockets) {
235 PLOG(FATAL) << "Unable to create socketpair for agent control!";
236 }
237
238 // Next start the threads.
239 art::Thread* self = art::Thread::Current();
240 art::ScopedObjectAccess soa(self);
241 {
242 art::Runtime* runtime = art::Runtime::Current();
243 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
244 if (runtime->IsShuttingDownLocked()) {
245 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
246 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
247 return;
248 }
249 runtime->StartThreadBirth();
250 }
251 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700252 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
253 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800254 pthread_t pthread;
255 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800256 started_debugger_threads_ = true;
Alex Lightfbf96702017-12-14 13:27:13 -0800257 int pthread_create_result = pthread_create(&pthread,
258 nullptr,
259 &CallbackFunction,
260 data.get());
261 if (pthread_create_result != 0) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800262 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800263 // If the create succeeded the other thread will call EndThreadBirth.
264 art::Runtime* runtime = art::Runtime::Current();
265 soa.Env()->DeleteGlobalRef(data->thr_);
266 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
267 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
268 runtime->EndThreadBirth();
269 return;
270 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700271 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800272}
273
274static bool FlagsSet(int16_t data, int16_t flags) {
275 return (data & flags) == flags;
276}
277
278void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800279 {
280 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
281 // closed.
282 ScopedEventFdLock lk(adb_write_event_fd_);
283 // shutdown(adb_connection_socket_, SHUT_RDWR);
284 adb_connection_socket_.reset();
285 }
286
287 // If we didn't load anything we will need to do the handshake again.
288 performed_handshake_ = false;
289
290 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
291 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700292 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800293 }
294}
295
296void AdbConnectionState::NotifyDdms(bool active) {
297 art::ScopedObjectAccess soa(art::Thread::Current());
298 DCHECK_NE(notified_ddm_active_, active);
299 notified_ddm_active_ = active;
300 if (active) {
301 art::Dbg::DdmConnected();
302 } else {
303 art::Dbg::DdmDisconnected();
304 }
Alex Lightfbf96702017-12-14 13:27:13 -0800305}
306
307uint32_t AdbConnectionState::NextDdmId() {
308 // Just have a normal counter but always set the sign bit.
309 return (next_ddm_id_++) | 0x80000000;
310}
311
312void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800313 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
314}
315
316void AdbConnectionState::SendDdmPacket(uint32_t id,
317 DdmPacketType packet_type,
318 uint32_t type,
319 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800320 // Get the write_event early to fail fast.
321 ScopedEventFdLock lk(adb_write_event_fd_);
322 if (adb_connection_socket_ == -1) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800323 VLOG(jdwp) << "Not sending ddms data of type "
324 << StringPrintf("%c%c%c%c",
325 static_cast<char>(type >> 24),
326 static_cast<char>(type >> 16),
327 static_cast<char>(type >> 8),
328 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800329 // Adb is not connected.
330 return;
331 }
332
333 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
334 // after we have sent our data.
335 static constexpr uint32_t kDdmPacketHeaderSize =
336 kJDWPHeaderLen // jdwp command packet size
337 + sizeof(uint32_t) // Type
338 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800339 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800340 uint8_t* pkt_data = pkt.data();
341
342 // Write the length first.
343 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
344 pkt_data += sizeof(uint32_t);
345
346 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800347 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800348 pkt_data += sizeof(uint32_t);
349
350 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800351 *(pkt_data++) = static_cast<uint8_t>(packet_type);
352 switch (packet_type) {
353 case DdmPacketType::kCmd: {
354 // Now the cmd-set
355 *(pkt_data++) = kJDWPDdmCmdSet;
356 // Now the command
357 *(pkt_data++) = kJDWPDdmCmd;
358 break;
359 }
360 case DdmPacketType::kReply: {
361 // This is the error code bytes which are all 0
362 *(pkt_data++) = 0;
363 *(pkt_data++) = 0;
364 }
365 }
Alex Lightfbf96702017-12-14 13:27:13 -0800366
Alex Light15b81132018-01-24 13:29:07 -0800367 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800368 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800369 uint32_t net_type = htonl(type);
370 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800371 pkt_data += sizeof(uint32_t);
372
373 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800374 uint32_t net_len = htonl(data.size());
375 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800376 pkt_data += sizeof(uint32_t);
377
378 static uint32_t constexpr kIovSize = 2;
379 struct iovec iovs[kIovSize] = {
380 { pkt.data(), pkt.size() },
381 { const_cast<uint8_t*>(data.data()), data.size() },
382 };
383 // now pkt_header has the header.
384 // use writev to send the actual data.
385 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
386 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
387 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
388 static_cast<char>(type >> 24),
389 static_cast<char>(type >> 16),
390 static_cast<char>(type >> 8),
391 static_cast<char>(type),
392 res, data.size() + kDdmPacketHeaderSize);
393 } else {
394 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
395 static_cast<char>(type >> 24),
396 static_cast<char>(type >> 16),
397 static_cast<char>(type >> 8),
398 static_cast<char>(type),
399 data.size() + kDdmPacketHeaderSize);
400 }
401}
402
Alex Light15b81132018-01-24 13:29:07 -0800403void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800404 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800405 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800406 union {
407 cmsghdr cm;
408 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
409 } cm_un;
410 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800411 iov.iov_base = const_cast<char*>(message);
412 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800413
414 msghdr msg;
415 msg.msg_name = nullptr;
416 msg.msg_namelen = 0;
417 msg.msg_iov = &iov;
418 msg.msg_iovlen = 1;
419 msg.msg_flags = 0;
420 msg.msg_control = cm_un.buffer;
421 msg.msg_controllen = sizeof(cm_un.buffer);
422
423 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
424 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
425 cmsg->cmsg_level = SOL_SOCKET;
426 cmsg->cmsg_type = SCM_RIGHTS;
427
428 // Duplicate the fds before sending them.
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700429 android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800430 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700431 android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800432 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700433 android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
Alex Lightfbf96702017-12-14 13:27:13 -0800434 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
435
436 dt_fd_forward::FdSet {
437 read_fd.get(), write_fd.get(), write_lock_fd.get()
438 }.WriteData(CMSG_DATA(cmsg));
439
440 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
441 if (res < 0) {
442 PLOG(ERROR) << "Failed to send agent adb connection fds.";
443 } else {
444 sent_agent_fds_ = true;
445 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
446 }
447}
448
449android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
450 // We don't actually care about the data that is sent. We do need to receive something though.
451 char dummy = '!';
452 union {
453 cmsghdr cm;
454 char buffer[CMSG_SPACE(sizeof(int))];
455 } cm_un;
456
457 iovec iov;
458 iov.iov_base = &dummy;
459 iov.iov_len = 1;
460
461 msghdr msg;
462 msg.msg_name = nullptr;
463 msg.msg_namelen = 0;
464 msg.msg_iov = &iov;
465 msg.msg_iovlen = 1;
466 msg.msg_flags = 0;
467 msg.msg_control = cm_un.buffer;
468 msg.msg_controllen = sizeof(cm_un.buffer);
469
470 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
471 cmsg->cmsg_len = msg.msg_controllen;
472 cmsg->cmsg_level = SOL_SOCKET;
473 cmsg->cmsg_type = SCM_RIGHTS;
474 (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
475
476 int rc = TEMP_FAILURE_RETRY(recvmsg(control_sock_, &msg, 0));
477
478 if (rc <= 0) {
Alex Lightfbf96702017-12-14 13:27:13 -0800479 return android::base::unique_fd(-1);
480 } else {
481 VLOG(jdwp) << "Fds have been received from ADB!";
482 }
483
484 return android::base::unique_fd((reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0]);
485}
486
487bool AdbConnectionState::SetupAdbConnection() {
488 int sleep_ms = 500;
489 const int sleep_max_ms = 2*1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800490
Alex Light54f535a2018-06-04 14:14:19 -0700491 android::base::unique_fd sock(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
Alex Lightfbf96702017-12-14 13:27:13 -0800492 if (sock < 0) {
493 PLOG(ERROR) << "Could not create ADB control socket";
494 return false;
495 }
496 struct timeval timeout;
497 timeout.tv_sec = kControlSockSendTimeout;
498 timeout.tv_usec = 0;
499 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
Josh Gao4b49bb72018-02-12 15:06:42 -0800500 int32_t pid = getpid();
Alex Lightfbf96702017-12-14 13:27:13 -0800501
502 while (!shutting_down_) {
503 // If adbd isn't running, because USB debugging was disabled or
504 // perhaps the system is restarting it for "adb root", the
505 // connect() will fail. We loop here forever waiting for it
506 // to come back.
507 //
508 // Waking up and polling every couple of seconds is generally a
509 // bad thing to do, but we only do this if the application is
510 // debuggable *and* adbd isn't running. Still, for the sake
511 // of battery life, we should consider timing out and giving
512 // up after a few minutes in case somebody ships an app with
513 // the debuggable flag set.
514 int ret = connect(sock, &control_addr_.controlAddrPlain, control_addr_len_);
515 if (ret == 0) {
Elliott Hughesc2efd4d2018-10-25 13:14:55 -0700516 bool trusted = sock >= 0 && art::SocketPeerIsTrusted(sock);
Alex Lightfbf96702017-12-14 13:27:13 -0800517 if (!trusted) {
518 LOG(ERROR) << "adb socket is not trusted. Aborting connection.";
519 if (sock >= 0 && shutdown(sock, SHUT_RDWR)) {
520 PLOG(ERROR) << "trouble shutting down socket";
521 }
522 return false;
523 }
524 /* now try to send our pid to the ADB daemon */
Josh Gao4b49bb72018-02-12 15:06:42 -0800525 ret = TEMP_FAILURE_RETRY(send(sock, &pid, sizeof(pid), 0));
526 if (ret == sizeof(pid)) {
527 VLOG(jdwp) << "PID " << pid << " sent to adb";
Alex Lightfbf96702017-12-14 13:27:13 -0800528 control_sock_ = std::move(sock);
529 return true;
530 } else {
531 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB. Aborting connection.";
532 return false;
533 }
534 } else {
Alex Lightd9258672018-02-12 14:47:16 -0800535 if (VLOG_IS_ON(jdwp)) {
536 PLOG(ERROR) << "Can't connect to ADB control socket. Will retry.";
537 }
Alex Lightfbf96702017-12-14 13:27:13 -0800538
539 usleep(sleep_ms * 1000);
540
541 sleep_ms += (sleep_ms >> 1);
542 if (sleep_ms > sleep_max_ms) {
543 sleep_ms = sleep_max_ms;
544 }
545 }
546 }
547 return false;
548}
549
550void AdbConnectionState::RunPollLoop(art::Thread* self) {
Alex Lightd6f9d852018-01-25 11:26:28 -0800551 CHECK_NE(agent_name_, "");
Alex Lightfbf96702017-12-14 13:27:13 -0800552 CHECK_EQ(self->GetState(), art::kNative);
Ziang Wan92db59b2019-07-22 21:19:24 +0000553 art::Locks::mutator_lock_->AssertNotHeld(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800554 self->SetState(art::kWaitingInMainDebuggerLoop);
555 // shutting_down_ set by StopDebuggerThreads
556 while (!shutting_down_) {
557 // First get the control_sock_ from adb if we don't have one. We only need to do this once.
558 if (control_sock_ == -1 && !SetupAdbConnection()) {
559 LOG(ERROR) << "Failed to setup adb connection.";
560 return;
561 }
562 while (!shutting_down_ && control_sock_ != -1) {
Alex Light15b81132018-01-24 13:29:07 -0800563 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800564 struct pollfd pollfds[4] = {
565 { sleep_event_fd_, POLLIN, 0 },
566 // -1 as an fd causes it to be ignored by poll
567 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
568 // Check for the control_sock_ actually going away. Only do this if we don't have an active
569 // connection.
570 { (adb_connection_socket_ == -1 ? control_sock_ : -1), POLLIN | POLLRDHUP, 0 },
571 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
572 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800573 // data that the agent or this plugin can handle.
574 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800575 };
576 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
577 if (res < 0) {
578 PLOG(ERROR) << "Failed to poll!";
579 return;
580 }
581 // We don't actually care about doing this we just use it to wake us up.
582 // const struct pollfd& sleep_event_poll = pollfds[0];
583 const struct pollfd& agent_control_sock_poll = pollfds[1];
584 const struct pollfd& control_sock_poll = pollfds[2];
585 const struct pollfd& adb_socket_poll = pollfds[3];
586 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
587 DCHECK(agent_loaded_);
588 char buf[257];
589 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
590 if (res < 0) {
591 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
592 continue;
593 } else {
594 buf[res + 1] = '\0';
595 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
596 }
597 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
598 agent_listening_ = true;
599 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700600 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800601 }
602 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
603 agent_listening_ = false;
604 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
605 CloseFds();
606 agent_has_socket_ = false;
607 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
608 agent_has_socket_ = true;
609 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800610 // We will only ever do the handshake once so reset this.
611 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800612 } else {
613 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
614 }
615 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
616 bool maybe_send_fds = false;
617 {
618 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
619 ScopedEventFdLock sefdl(adb_write_event_fd_);
620 android::base::unique_fd new_fd(ReadFdFromAdb());
621 if (new_fd == -1) {
622 // Something went wrong. We need to retry getting the control socket.
Alex Lightfbf96702017-12-14 13:27:13 -0800623 control_sock_.reset();
624 break;
625 } else if (adb_connection_socket_ != -1) {
626 // We already have a connection.
627 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
628 if (new_fd >= 0) {
629 new_fd.reset();
630 }
631 } else {
632 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
633 adb_connection_socket_ = std::move(new_fd);
634 maybe_send_fds = true;
635 }
636 }
637 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
638 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800639 // The agent was already loaded so this must be after a disconnection. Therefore have the
640 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700641 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800642 }
643 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
644 // The other end of the adb connection just dropped it.
645 // Reset the connection since we don't have an active socket through the adb server.
646 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
647 << "connection active";
648 control_sock_.reset();
649 break;
650 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
651 DCHECK(!agent_has_socket_);
652 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800653 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800654 } else if (agent_listening_ && !sent_agent_fds_) {
655 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800656 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700657 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800658 }
Alex Light15b81132018-01-24 13:29:07 -0800659 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
660 DCHECK(!agent_has_socket_);
661 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800662 } else {
663 VLOG(jdwp) << "Woke up poll without anything to do!";
664 }
665 }
666 }
667}
668
Alex Light15b81132018-01-24 13:29:07 -0800669static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
670 uint32_t res;
671 memcpy(&res, *in, sizeof(uint32_t));
672 *in = (*in) + sizeof(uint32_t);
673 return ntohl(res);
674}
675
676void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
677 DCHECK(!agent_loaded_);
678 DCHECK(!agent_listening_);
679 // TODO Should we check in some other way if we are userdebug/eng?
680 CHECK(art::Dbg::IsJdwpAllowed());
681 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
682 if (!performed_handshake_) {
683 PerformHandshake();
684 return;
685 }
686 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
687 // to see if it's one we can handle. This doesn't change the state of the socket.
688 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
689 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
690 packet_header,
691 sizeof(packet_header),
692 MSG_PEEK));
693 // We want to be very careful not to change the socket state until we know we succeeded. This will
694 // let us fall-back to just loading the agent and letting it deal with everything.
695 if (res <= 0) {
696 // Close the socket. We either hit EOF or an error.
697 if (res < 0) {
698 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
699 }
700 CloseFds();
701 return;
702 } else if (res < static_cast<int>(kPacketHeaderLen)) {
703 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
704 AttachJdwpAgent(self);
705 return;
706 }
707 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
708 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
709 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
710 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
711 if (pkt_cmd_set != kDdmCommandSet ||
712 pkt_cmd != kDdmChunkCommand ||
713 full_len < kPacketHeaderLen) {
714 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
715 AttachJdwpAgent(self);
716 return;
717 }
718 uint32_t avail = -1;
719 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
720 if (res < 0) {
721 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
722 CloseFds();
723 return;
724 } else if (avail < full_len) {
725 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
726 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
727 << "Loading jdwp agent to deal with this.";
728 AttachJdwpAgent(self);
729 return;
730 }
731 // Actually read the data.
732 std::vector<uint8_t> full_pkt;
733 full_pkt.resize(full_len);
734 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
735 if (res < 0) {
736 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
737 CloseFds();
738 return;
739 }
740 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
741 size_t data_size = full_len - kPacketHeaderLen;
742 if (data_size < (sizeof(uint32_t) * 2)) {
743 // This is an error (the data isn't long enough) but to match historical behavior we need to
744 // ignore it.
745 return;
746 }
747 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
748 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
749 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
750 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
751 // This is an error (the data isn't long enough) but to match historical behavior we need to
752 // ignore it.
753 return;
754 }
755
756 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700757 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800758 }
759 uint32_t reply_type;
760 std::vector<uint8_t> reply;
761 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
762 ddm_type,
763 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
764 ddm_len),
765 /*out*/&reply_type,
766 /*out*/&reply)) {
767 // To match historical behavior we don't send any response when there is no data to reply with.
768 return;
769 }
770 SendDdmPacket(pkt_id,
771 DdmPacketType::kReply,
772 reply_type,
773 art::ArrayRef<const uint8_t>(reply));
774}
775
776void AdbConnectionState::PerformHandshake() {
777 CHECK(!performed_handshake_);
778 // Check to make sure we are able to read the whole handshake.
779 uint32_t avail = -1;
780 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
781 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
782 if (res < 0) {
783 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
784 }
785 LOG(WARNING) << "Closing connection to broken client.";
786 CloseFds();
787 return;
788 }
789 // Perform the handshake.
790 char handshake_msg[sizeof(kJdwpHandshake)];
791 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
792 handshake_msg,
793 sizeof(handshake_msg),
794 MSG_DONTWAIT));
795 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
796 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
797 if (res < 0) {
798 PLOG(ERROR) << "Failed to read handshake!";
799 }
800 LOG(WARNING) << "Handshake failed!";
801 CloseFds();
802 return;
803 }
804 // Send the handshake back.
805 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
806 kJdwpHandshake,
807 sizeof(kJdwpHandshake),
808 0));
809 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
810 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
811 CloseFds();
812 return;
813 }
814 performed_handshake_ = true;
815}
816
817void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700818 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800819 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700820 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700821 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700822 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800823 if (self->IsExceptionPending()) {
824 LOG(ERROR) << "Failed to load agent " << agent_name_;
825 art::ScopedObjectAccess soa(self);
826 self->GetException()->Dump();
827 self->ClearException();
828 return;
829 }
830 agent_loaded_ = true;
831}
832
Alex Light81f75c32018-01-26 09:46:32 -0800833bool ContainsArgument(const std::string& opts, const char* arg) {
834 return opts.find(arg) != std::string::npos;
835}
836
837bool ValidateJdwpOptions(const std::string& opts) {
838 bool res = true;
839 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
840 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
841 // for the fd's to be passed down.
842 if (ContainsArgument(opts, "server=n")) {
843 res = false;
844 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
845 }
846 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
847 // everything.
848 if (ContainsArgument(opts, "suspend=y")) {
849 res = false;
850 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
851 }
852 return res;
853}
854
Alex Lightfbf96702017-12-14 13:27:13 -0800855std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800856 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800857 DCHECK(ValidateJdwpOptions(opts));
858 // TODO Get agent_name_ from something user settable?
859 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
860 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
861 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
862 // we will add it if it wasn't already present for the convenience of the user.
863 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
864 // See the comment above for why we need to be suspend=n. Since the agent defaults to
865 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700866 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800867 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800868}
869
870void AdbConnectionState::StopDebuggerThreads() {
871 // The regular agent system will take care of unloading the agent (if needed).
872 shutting_down_ = true;
873 // Wakeup the poll loop.
874 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800875 if (sleep_event_fd_ != -1) {
876 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
877 }
Alex Lightfbf96702017-12-14 13:27:13 -0800878}
879
880// The plugin initialization function.
Alex Light3b08bcc2019-09-11 09:48:51 -0700881extern "C" bool ArtPlugin_Initialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800882 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
883 // TODO Provide some way for apps to set this maybe?
Alex Lightd6f9d852018-01-25 11:26:28 -0800884 DCHECK(gState == nullptr);
Alex Lightfbf96702017-12-14 13:27:13 -0800885 gState = new AdbConnectionState(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800886 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800887}
888
889extern "C" bool ArtPlugin_Deinitialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800890 gState->StopDebuggerThreads();
Alex Lightd6f9d852018-01-25 11:26:28 -0800891 if (!gState->DebuggerThreadsStarted()) {
892 // If debugger threads were started then those threads will delete the state once they are done.
893 delete gState;
894 }
Alex Lightfbf96702017-12-14 13:27:13 -0800895 return true;
896}
897
898} // namespace adbconnection