blob: f9ebe40e151d5e0d3fe5604ab3249ab51f94aaa0 [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>
Alex Light75d21892020-03-25 14:18:56 -070018#include <cstddef>
Josh Gaobd396c02020-01-22 18:02:19 -080019#include <iterator>
Alex Lightfbf96702017-12-14 13:27:13 -080020
21#include "adbconnection.h"
22
Josh Gaobd396c02020-01-22 18:02:19 -080023#include "adbconnection/client.h"
Alex Lightfbf96702017-12-14 13:27:13 -080024#include "android-base/endian.h"
25#include "android-base/stringprintf.h"
Andreas Gampedfcd82c2018-10-16 20:22:37 -070026#include "base/file_utils.h"
Alex Lightf51d1822021-02-01 19:25:35 -080027#include "base/globals.h"
Alex Lightfbf96702017-12-14 13:27:13 -080028#include "base/logging.h"
29#include "base/macros.h"
30#include "base/mutex.h"
Alex Lightfc588092020-01-23 15:39:08 -080031#include "base/socket_peer_is_trusted.h"
32#include "debugger.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010033#include "jni/java_vm_ext.h"
34#include "jni/jni_env_ext.h"
Alex Lightfbf96702017-12-14 13:27:13 -080035#include "mirror/throwable.h"
Orion Hodsond41c7592019-01-27 09:25:47 +000036#include "nativehelper/scoped_local_ref.h"
Alex Lightfbf96702017-12-14 13:27:13 -080037#include "runtime-inl.h"
38#include "runtime_callbacks.h"
39#include "scoped_thread_state_change-inl.h"
40#include "well_known_classes.h"
41
Alex Lightfbf96702017-12-14 13:27:13 -080042#include "fd_transport.h"
43
44#include "poll.h"
45
Alex Light15b81132018-01-24 13:29:07 -080046#include <sys/ioctl.h>
Alex Lightfbf96702017-12-14 13:27:13 -080047#include <sys/socket.h>
Alex Lightfc588092020-01-23 15:39:08 -080048#include <sys/uio.h>
Alex Lightfbf96702017-12-14 13:27:13 -080049#include <sys/un.h>
50#include <sys/eventfd.h>
51#include <jni.h>
52
53namespace adbconnection {
54
Alex Lightfc588092020-01-23 15:39:08 -080055static constexpr size_t kJdwpHeaderLen = 11U;
56/* DDM support */
57static constexpr uint8_t kJdwpDdmCmdSet = 199U; // 0xc7, or 'G'+128
58static constexpr uint8_t kJdwpDdmCmd = 1U;
59
Alex Light15b81132018-01-24 13:29:07 -080060// Messages sent from the transport
Alex Lightfbf96702017-12-14 13:27:13 -080061using dt_fd_forward::kListenStartMessage;
62using dt_fd_forward::kListenEndMessage;
63using dt_fd_forward::kAcceptMessage;
64using dt_fd_forward::kCloseMessage;
Alex Lightf51d1822021-02-01 19:25:35 -080065using dt_fd_forward::kHandshakeCompleteMessage;
Alex Lightfbf96702017-12-14 13:27:13 -080066
Alex Light15b81132018-01-24 13:29:07 -080067// Messages sent to the transport
68using dt_fd_forward::kPerformHandshakeMessage;
69using dt_fd_forward::kSkipHandshakeMessage;
70
Alex Lightfbf96702017-12-14 13:27:13 -080071using android::base::StringPrintf;
72
Alex Light15b81132018-01-24 13:29:07 -080073static constexpr const char kJdwpHandshake[14] = {
74 'J', 'D', 'W', 'P', '-', 'H', 'a', 'n', 'd', 's', 'h', 'a', 'k', 'e'
75};
76
Alex Lightfbf96702017-12-14 13:27:13 -080077static constexpr int kEventfdLocked = 0;
78static constexpr int kEventfdUnlocked = 1;
Alex Lightfbf96702017-12-14 13:27:13 -080079
Alex Light15b81132018-01-24 13:29:07 -080080static constexpr size_t kPacketHeaderLen = 11;
81static constexpr off_t kPacketSizeOff = 0;
82static constexpr off_t kPacketIdOff = 4;
83static constexpr off_t kPacketCommandSetOff = 9;
84static constexpr off_t kPacketCommandOff = 10;
85
86static constexpr uint8_t kDdmCommandSet = 199;
87static constexpr uint8_t kDdmChunkCommand = 1;
88
Flash Liu013e2082019-10-31 11:18:55 +080089static std::optional<AdbConnectionState> gState;
Alex Light75d21892020-03-25 14:18:56 -070090static std::optional<pthread_t> gPthread;
Alex Lightfbf96702017-12-14 13:27:13 -080091
92static bool IsDebuggingPossible() {
Alex Light2ce6fc82017-12-18 16:42:36 -080093 return art::Dbg::IsJdwpAllowed();
Alex Lightfbf96702017-12-14 13:27:13 -080094}
95
96// Begin running the debugger.
97void AdbConnectionDebuggerController::StartDebugger() {
Shukang Zhou670ea842020-02-06 14:53:14 -080098 // The debugger thread is started for a debuggable or profileable-from-shell process.
99 // The pid will be send to adbd for adb's "track-jdwp" and "track-app" services.
100 // The thread will also set up the jdwp tunnel if the process is debuggable.
101 if (IsDebuggingPossible() || art::Runtime::Current()->IsProfileableFromShell()) {
Alex Lightfbf96702017-12-14 13:27:13 -0800102 connection_->StartDebuggerThreads();
103 } else {
104 LOG(ERROR) << "Not starting debugger since process cannot load the jdwp agent.";
105 }
106}
107
Alex Light75d21892020-03-25 14:18:56 -0700108// The debugger should have already shut down since the runtime is ending. As far
109// as the agent is concerned shutdown already happened when we went to kDeath
110// state. We need to clean up our threads still though and this is a good time
111// to do it since the runtime is still able to handle all the normal state
112// transitions.
113void AdbConnectionDebuggerController::StopDebugger() {
114 // Stop our threads.
115 gState->StopDebuggerThreads();
116 // Wait for our threads to actually return and cleanup the pthread.
117 if (gPthread.has_value()) {
118 void* ret_unused;
119 if (TEMP_FAILURE_RETRY(pthread_join(gPthread.value(), &ret_unused)) != 0) {
120 PLOG(ERROR) << "Failed to join debugger threads!";
121 }
122 gPthread.reset();
123 }
124}
Alex Lightfbf96702017-12-14 13:27:13 -0800125
126bool AdbConnectionDebuggerController::IsDebuggerConfigured() {
127 return IsDebuggingPossible() && !art::Runtime::Current()->GetJdwpOptions().empty();
128}
129
130void AdbConnectionDdmCallback::DdmPublishChunk(uint32_t type,
131 const art::ArrayRef<const uint8_t>& data) {
132 connection_->PublishDdmData(type, data);
133}
134
135class ScopedEventFdLock {
136 public:
137 explicit ScopedEventFdLock(int fd) : fd_(fd), data_(0) {
138 TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_)));
139 }
140
141 ~ScopedEventFdLock() {
142 TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_)));
143 }
144
145 private:
146 int fd_;
147 uint64_t data_;
148};
149
150AdbConnectionState::AdbConnectionState(const std::string& agent_name)
151 : agent_name_(agent_name),
152 controller_(this),
153 ddm_callback_(this),
154 sleep_event_fd_(-1),
Josh Gaobd396c02020-01-22 18:02:19 -0800155 control_ctx_(nullptr, adbconnection_client_destroy),
Alex Lightfbf96702017-12-14 13:27:13 -0800156 local_agent_control_sock_(-1),
157 remote_agent_control_sock_(-1),
158 adb_connection_socket_(-1),
159 adb_write_event_fd_(-1),
160 shutting_down_(false),
161 agent_loaded_(false),
162 agent_listening_(false),
Alex Light15b81132018-01-24 13:29:07 -0800163 agent_has_socket_(false),
164 sent_agent_fds_(false),
165 performed_handshake_(false),
166 notified_ddm_active_(false),
Alex Lightd6f9d852018-01-25 11:26:28 -0800167 next_ddm_id_(1),
168 started_debugger_threads_(false) {
Alex Lightfbf96702017-12-14 13:27:13 -0800169 // Add the startup callback.
170 art::ScopedObjectAccess soa(art::Thread::Current());
171 art::Runtime::Current()->GetRuntimeCallbacks()->AddDebuggerControlCallback(&controller_);
172}
173
Flash Liu013e2082019-10-31 11:18:55 +0800174AdbConnectionState::~AdbConnectionState() {
175 // Remove the startup callback.
176 art::Thread* self = art::Thread::Current();
177 if (self != nullptr) {
178 art::ScopedObjectAccess soa(self);
179 art::Runtime::Current()->GetRuntimeCallbacks()->RemoveDebuggerControlCallback(&controller_);
180 }
181}
182
Alex Lightfbf96702017-12-14 13:27:13 -0800183static jobject CreateAdbConnectionThread(art::Thread* thr) {
184 JNIEnv* env = thr->GetJniEnv();
185 // Move to native state to talk with the jnienv api.
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000186 art::ScopedThreadStateChange stsc(thr, art::ThreadState::kNative);
Alex Lightfbf96702017-12-14 13:27:13 -0800187 ScopedLocalRef<jstring> thr_name(env, env->NewStringUTF(kAdbConnectionThreadName));
188 ScopedLocalRef<jobject> thr_group(
189 env,
190 env->GetStaticObjectField(art::WellKnownClasses::java_lang_ThreadGroup,
191 art::WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
192 return env->NewObject(art::WellKnownClasses::java_lang_Thread,
193 art::WellKnownClasses::java_lang_Thread_init,
194 thr_group.get(),
195 thr_name.get(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700196 /*Priority=*/ 0,
197 /*Daemon=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800198}
199
200struct CallbackData {
201 AdbConnectionState* this_;
202 jobject thr_;
203};
204
205static void* CallbackFunction(void* vdata) {
206 std::unique_ptr<CallbackData> data(reinterpret_cast<CallbackData*>(vdata));
207 art::Thread* self = art::Thread::Attach(kAdbConnectionThreadName,
208 true,
209 data->thr_);
210 CHECK(self != nullptr) << "threads_being_born_ should have ensured thread could be attached.";
211 // The name in Attach() is only for logging. Set the thread name. This is important so
212 // that the thread is no longer seen as starting up.
213 {
214 art::ScopedObjectAccess soa(self);
215 self->SetThreadName(kAdbConnectionThreadName);
216 }
217
218 // Release the peer.
219 JNIEnv* env = self->GetJniEnv();
220 env->DeleteGlobalRef(data->thr_);
221 data->thr_ = nullptr;
222 {
223 // The StartThreadBirth was called in the parent thread. We let the runtime know we are up
224 // before going into the provided code.
225 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
226 art::Runtime::Current()->EndThreadBirth();
227 }
228 data->this_->RunPollLoop(self);
229 int detach_result = art::Runtime::Current()->GetJavaVM()->DetachCurrentThread();
230 CHECK_EQ(detach_result, 0);
231
232 return nullptr;
233}
234
235void AdbConnectionState::StartDebuggerThreads() {
236 // First do all the final setup we need.
237 CHECK_EQ(adb_write_event_fd_.get(), -1);
238 CHECK_EQ(sleep_event_fd_.get(), -1);
239 CHECK_EQ(local_agent_control_sock_.get(), -1);
240 CHECK_EQ(remote_agent_control_sock_.get(), -1);
241
242 sleep_event_fd_.reset(eventfd(kEventfdLocked, EFD_CLOEXEC));
243 CHECK_NE(sleep_event_fd_.get(), -1) << "Unable to create wakeup eventfd.";
244 adb_write_event_fd_.reset(eventfd(kEventfdUnlocked, EFD_CLOEXEC));
245 CHECK_NE(adb_write_event_fd_.get(), -1) << "Unable to create write-lock eventfd.";
246
247 {
248 art::ScopedObjectAccess soa(art::Thread::Current());
249 art::Runtime::Current()->GetRuntimeCallbacks()->AddDdmCallback(&ddm_callback_);
250 }
251 // Setup the socketpair we use to talk to the agent.
252 bool has_sockets;
253 do {
254 has_sockets = android::base::Socketpair(AF_UNIX,
255 SOCK_SEQPACKET | SOCK_CLOEXEC,
256 0,
257 &local_agent_control_sock_,
258 &remote_agent_control_sock_);
259 } while (!has_sockets && errno == EINTR);
260 if (!has_sockets) {
261 PLOG(FATAL) << "Unable to create socketpair for agent control!";
262 }
263
264 // Next start the threads.
265 art::Thread* self = art::Thread::Current();
266 art::ScopedObjectAccess soa(self);
267 {
268 art::Runtime* runtime = art::Runtime::Current();
269 art::MutexLock mu(self, *art::Locks::runtime_shutdown_lock_);
270 if (runtime->IsShuttingDownLocked()) {
271 // The runtime is shutting down so we cannot create new threads. This shouldn't really happen.
272 LOG(ERROR) << "The runtime is shutting down when we are trying to start up the debugger!";
273 return;
274 }
275 runtime->StartThreadBirth();
276 }
277 ScopedLocalRef<jobject> thr(soa.Env(), CreateAdbConnectionThread(soa.Self()));
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700278 // Note: Using pthreads instead of std::thread to not abort when the thread cannot be
279 // created (exception support required).
Alex Lightfbf96702017-12-14 13:27:13 -0800280 std::unique_ptr<CallbackData> data(new CallbackData { this, soa.Env()->NewGlobalRef(thr.get()) });
Alex Lightd6f9d852018-01-25 11:26:28 -0800281 started_debugger_threads_ = true;
Alex Light75d21892020-03-25 14:18:56 -0700282 gPthread.emplace();
283 int pthread_create_result = pthread_create(&gPthread.value(),
Alex Lightfbf96702017-12-14 13:27:13 -0800284 nullptr,
285 &CallbackFunction,
286 data.get());
287 if (pthread_create_result != 0) {
Alex Light75d21892020-03-25 14:18:56 -0700288 gPthread.reset();
Alex Lightd6f9d852018-01-25 11:26:28 -0800289 started_debugger_threads_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800290 // If the create succeeded the other thread will call EndThreadBirth.
291 art::Runtime* runtime = art::Runtime::Current();
292 soa.Env()->DeleteGlobalRef(data->thr_);
293 LOG(ERROR) << "Failed to create thread for adb-jdwp connection manager!";
294 art::MutexLock mu(art::Thread::Current(), *art::Locks::runtime_shutdown_lock_);
295 runtime->EndThreadBirth();
296 return;
297 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700298 data.release(); // NOLINT pthreads API.
Alex Lightfbf96702017-12-14 13:27:13 -0800299}
300
301static bool FlagsSet(int16_t data, int16_t flags) {
302 return (data & flags) == flags;
303}
304
305void AdbConnectionState::CloseFds() {
Alex Light15b81132018-01-24 13:29:07 -0800306 {
307 // Lock the write_event_fd so that concurrent PublishDdms will see that the connection is
308 // closed.
309 ScopedEventFdLock lk(adb_write_event_fd_);
310 // shutdown(adb_connection_socket_, SHUT_RDWR);
311 adb_connection_socket_.reset();
312 }
313
314 // If we didn't load anything we will need to do the handshake again.
315 performed_handshake_ = false;
316
317 // If the agent isn't loaded we might need to tell ddms code the connection is closed.
318 if (!agent_loaded_ && notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700319 NotifyDdms(/*active=*/false);
Alex Light15b81132018-01-24 13:29:07 -0800320 }
321}
322
323void AdbConnectionState::NotifyDdms(bool active) {
324 art::ScopedObjectAccess soa(art::Thread::Current());
325 DCHECK_NE(notified_ddm_active_, active);
326 notified_ddm_active_ = active;
327 if (active) {
328 art::Dbg::DdmConnected();
329 } else {
330 art::Dbg::DdmDisconnected();
331 }
Alex Lightfbf96702017-12-14 13:27:13 -0800332}
333
334uint32_t AdbConnectionState::NextDdmId() {
335 // Just have a normal counter but always set the sign bit.
336 return (next_ddm_id_++) | 0x80000000;
337}
338
339void AdbConnectionState::PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data) {
Alex Light15b81132018-01-24 13:29:07 -0800340 SendDdmPacket(NextDdmId(), DdmPacketType::kCmd, type, data);
341}
342
343void AdbConnectionState::SendDdmPacket(uint32_t id,
344 DdmPacketType packet_type,
345 uint32_t type,
346 art::ArrayRef<const uint8_t> data) {
Alex Lightfbf96702017-12-14 13:27:13 -0800347 // Get the write_event early to fail fast.
348 ScopedEventFdLock lk(adb_write_event_fd_);
Alex Lightf51d1822021-02-01 19:25:35 -0800349 if (adb_connection_socket_ == -1 || !performed_handshake_) {
Alex Lighta17cc2e2018-02-02 13:56:14 -0800350 VLOG(jdwp) << "Not sending ddms data of type "
351 << StringPrintf("%c%c%c%c",
352 static_cast<char>(type >> 24),
353 static_cast<char>(type >> 16),
354 static_cast<char>(type >> 8),
355 static_cast<char>(type)) << " due to no connection!";
Alex Lightfbf96702017-12-14 13:27:13 -0800356 // Adb is not connected.
357 return;
358 }
359
360 // the adb_write_event_fd_ will ensure that the adb_connection_socket_ will not go away until
361 // after we have sent our data.
362 static constexpr uint32_t kDdmPacketHeaderSize =
Alex Lightfc588092020-01-23 15:39:08 -0800363 kJdwpHeaderLen // jdwp command packet size
Alex Lightfbf96702017-12-14 13:27:13 -0800364 + sizeof(uint32_t) // Type
365 + sizeof(uint32_t); // length
Alex Light15b81132018-01-24 13:29:07 -0800366 alignas(sizeof(uint32_t)) std::array<uint8_t, kDdmPacketHeaderSize> pkt;
Alex Lightfbf96702017-12-14 13:27:13 -0800367 uint8_t* pkt_data = pkt.data();
368
369 // Write the length first.
370 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(kDdmPacketHeaderSize + data.size());
371 pkt_data += sizeof(uint32_t);
372
373 // Write the id next;
Alex Light15b81132018-01-24 13:29:07 -0800374 *reinterpret_cast<uint32_t*>(pkt_data) = htonl(id);
Alex Lightfbf96702017-12-14 13:27:13 -0800375 pkt_data += sizeof(uint32_t);
376
377 // next the flags. (0 for cmd packet because DDMS).
Alex Light15b81132018-01-24 13:29:07 -0800378 *(pkt_data++) = static_cast<uint8_t>(packet_type);
379 switch (packet_type) {
380 case DdmPacketType::kCmd: {
381 // Now the cmd-set
Alex Lightfc588092020-01-23 15:39:08 -0800382 *(pkt_data++) = kJdwpDdmCmdSet;
Alex Light15b81132018-01-24 13:29:07 -0800383 // Now the command
Alex Lightfc588092020-01-23 15:39:08 -0800384 *(pkt_data++) = kJdwpDdmCmd;
Alex Light15b81132018-01-24 13:29:07 -0800385 break;
386 }
387 case DdmPacketType::kReply: {
388 // This is the error code bytes which are all 0
389 *(pkt_data++) = 0;
390 *(pkt_data++) = 0;
391 }
392 }
Alex Lightfbf96702017-12-14 13:27:13 -0800393
Alex Light15b81132018-01-24 13:29:07 -0800394 // These are at unaligned addresses so we need to do them manually.
Alex Lightfbf96702017-12-14 13:27:13 -0800395 // now the type.
Alex Light15b81132018-01-24 13:29:07 -0800396 uint32_t net_type = htonl(type);
397 memcpy(pkt_data, &net_type, sizeof(net_type));
Alex Lightfbf96702017-12-14 13:27:13 -0800398 pkt_data += sizeof(uint32_t);
399
400 // Now the data.size()
Alex Light15b81132018-01-24 13:29:07 -0800401 uint32_t net_len = htonl(data.size());
402 memcpy(pkt_data, &net_len, sizeof(net_len));
Alex Lightfbf96702017-12-14 13:27:13 -0800403 pkt_data += sizeof(uint32_t);
404
405 static uint32_t constexpr kIovSize = 2;
406 struct iovec iovs[kIovSize] = {
407 { pkt.data(), pkt.size() },
408 { const_cast<uint8_t*>(data.data()), data.size() },
409 };
410 // now pkt_header has the header.
411 // use writev to send the actual data.
412 ssize_t res = TEMP_FAILURE_RETRY(writev(adb_connection_socket_, iovs, kIovSize));
413 if (static_cast<size_t>(res) != (kDdmPacketHeaderSize + data.size())) {
414 PLOG(ERROR) << StringPrintf("Failed to send DDMS packet %c%c%c%c to debugger (%zd of %zu)",
415 static_cast<char>(type >> 24),
416 static_cast<char>(type >> 16),
417 static_cast<char>(type >> 8),
418 static_cast<char>(type),
419 res, data.size() + kDdmPacketHeaderSize);
420 } else {
421 VLOG(jdwp) << StringPrintf("sent DDMS packet %c%c%c%c to debugger %zu",
422 static_cast<char>(type >> 24),
423 static_cast<char>(type >> 16),
424 static_cast<char>(type >> 8),
425 static_cast<char>(type),
426 data.size() + kDdmPacketHeaderSize);
427 }
428}
429
Alex Light15b81132018-01-24 13:29:07 -0800430void AdbConnectionState::SendAgentFds(bool require_handshake) {
Alex Lightfbf96702017-12-14 13:27:13 -0800431 DCHECK(!sent_agent_fds_);
Alex Light15b81132018-01-24 13:29:07 -0800432 const char* message = require_handshake ? kPerformHandshakeMessage : kSkipHandshakeMessage;
Alex Lightfbf96702017-12-14 13:27:13 -0800433 union {
434 cmsghdr cm;
435 char buffer[CMSG_SPACE(dt_fd_forward::FdSet::kDataLength)];
436 } cm_un;
437 iovec iov;
Alex Light15b81132018-01-24 13:29:07 -0800438 iov.iov_base = const_cast<char*>(message);
439 iov.iov_len = strlen(message) + 1;
Alex Lightfbf96702017-12-14 13:27:13 -0800440
441 msghdr msg;
442 msg.msg_name = nullptr;
443 msg.msg_namelen = 0;
444 msg.msg_iov = &iov;
445 msg.msg_iovlen = 1;
446 msg.msg_flags = 0;
447 msg.msg_control = cm_un.buffer;
448 msg.msg_controllen = sizeof(cm_un.buffer);
449
450 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
451 cmsg->cmsg_len = CMSG_LEN(dt_fd_forward::FdSet::kDataLength);
452 cmsg->cmsg_level = SOL_SOCKET;
453 cmsg->cmsg_type = SCM_RIGHTS;
454
455 // Duplicate the fds before sending them.
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700456 android::base::unique_fd read_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800457 CHECK_NE(read_fd.get(), -1) << "Failed to dup read_fd_: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700458 android::base::unique_fd write_fd(art::DupCloexec(adb_connection_socket_));
Alex Lightfbf96702017-12-14 13:27:13 -0800459 CHECK_NE(write_fd.get(), -1) << "Failed to dup write_fd: " << strerror(errno);
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700460 android::base::unique_fd write_lock_fd(art::DupCloexec(adb_write_event_fd_));
Alex Lightfbf96702017-12-14 13:27:13 -0800461 CHECK_NE(write_lock_fd.get(), -1) << "Failed to dup write_lock_fd: " << strerror(errno);
462
463 dt_fd_forward::FdSet {
464 read_fd.get(), write_fd.get(), write_lock_fd.get()
465 }.WriteData(CMSG_DATA(cmsg));
466
467 int res = TEMP_FAILURE_RETRY(sendmsg(local_agent_control_sock_, &msg, MSG_EOR));
468 if (res < 0) {
469 PLOG(ERROR) << "Failed to send agent adb connection fds.";
470 } else {
471 sent_agent_fds_ = true;
472 VLOG(jdwp) << "Fds have been sent to jdwp agent!";
473 }
474}
475
476android::base::unique_fd AdbConnectionState::ReadFdFromAdb() {
Josh Gaobd396c02020-01-22 18:02:19 -0800477 return android::base::unique_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800478}
479
480bool AdbConnectionState::SetupAdbConnection() {
Josh Gaobd396c02020-01-22 18:02:19 -0800481 int sleep_ms = 500;
482 const int sleep_max_ms = 2 * 1000;
Alex Lightfbf96702017-12-14 13:27:13 -0800483
Shukang Zhou670ea842020-02-06 14:53:14 -0800484 const char* isa = GetInstructionSetString(art::Runtime::Current()->GetInstructionSet());
Josh Gaobd396c02020-01-22 18:02:19 -0800485 const AdbConnectionClientInfo infos[] = {
Shukang Zhou670ea842020-02-06 14:53:14 -0800486 {.type = AdbConnectionClientInfoType::pid,
487 .data.pid = static_cast<uint64_t>(getpid())},
488 {.type = AdbConnectionClientInfoType::debuggable,
489 .data.debuggable = IsDebuggingPossible()},
490 {.type = AdbConnectionClientInfoType::profileable,
491 .data.profileable = art::Runtime::Current()->IsProfileableFromShell()},
492 {.type = AdbConnectionClientInfoType::architecture,
493 // GetInstructionSetString() returns a null-terminating C-style string.
494 .data.architecture.name = isa,
495 .data.architecture.size = strlen(isa)},
Josh Gaobd396c02020-01-22 18:02:19 -0800496 };
Shukang Zhou670ea842020-02-06 14:53:14 -0800497 const AdbConnectionClientInfo *info_ptrs[] = {&infos[0], &infos[1], &infos[2], &infos[3]};
Alex Lightfbf96702017-12-14 13:27:13 -0800498
499 while (!shutting_down_) {
500 // If adbd isn't running, because USB debugging was disabled or
501 // perhaps the system is restarting it for "adb root", the
502 // connect() will fail. We loop here forever waiting for it
503 // to come back.
504 //
505 // Waking up and polling every couple of seconds is generally a
506 // bad thing to do, but we only do this if the application is
507 // debuggable *and* adbd isn't running. Still, for the sake
508 // of battery life, we should consider timing out and giving
509 // up after a few minutes in case somebody ships an app with
510 // the debuggable flag set.
Josh Gaobd396c02020-01-22 18:02:19 -0800511 control_ctx_.reset(adbconnection_client_new(info_ptrs, std::size(infos)));
512 if (control_ctx_) {
513 return true;
514 }
Alex Lightfbf96702017-12-14 13:27:13 -0800515
Josh Gaobd396c02020-01-22 18:02:19 -0800516 // We failed to connect.
517 usleep(sleep_ms * 1000);
Alex Lightfbf96702017-12-14 13:27:13 -0800518
Josh Gaobd396c02020-01-22 18:02:19 -0800519 sleep_ms += (sleep_ms >> 1);
520 if (sleep_ms > sleep_max_ms) {
521 sleep_ms = sleep_max_ms;
Alex Lightfbf96702017-12-14 13:27:13 -0800522 }
523 }
Josh Gaobd396c02020-01-22 18:02:19 -0800524
Alex Lightfbf96702017-12-14 13:27:13 -0800525 return false;
526}
527
528void AdbConnectionState::RunPollLoop(art::Thread* self) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800529 DCHECK(IsDebuggingPossible() || art::Runtime::Current()->IsProfileableFromShell());
Alex Lightd6f9d852018-01-25 11:26:28 -0800530 CHECK_NE(agent_name_, "");
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000531 CHECK_EQ(self->GetState(), art::ThreadState::kNative);
Ziang Wan92db59b2019-07-22 21:19:24 +0000532 art::Locks::mutator_lock_->AssertNotHeld(self);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000533 self->SetState(art::ThreadState::kWaitingInMainDebuggerLoop);
Alex Lightfbf96702017-12-14 13:27:13 -0800534 // shutting_down_ set by StopDebuggerThreads
535 while (!shutting_down_) {
Josh Gaobd396c02020-01-22 18:02:19 -0800536 // First, connect to adbd if we haven't already.
537 if (!control_ctx_ && !SetupAdbConnection()) {
Alex Lightfbf96702017-12-14 13:27:13 -0800538 LOG(ERROR) << "Failed to setup adb connection.";
539 return;
540 }
Josh Gaobd396c02020-01-22 18:02:19 -0800541 while (!shutting_down_ && control_ctx_) {
Alex Light15b81132018-01-24 13:29:07 -0800542 bool should_listen_on_connection = !agent_has_socket_ && !sent_agent_fds_;
Alex Lightfbf96702017-12-14 13:27:13 -0800543 struct pollfd pollfds[4] = {
544 { sleep_event_fd_, POLLIN, 0 },
545 // -1 as an fd causes it to be ignored by poll
546 { (agent_loaded_ ? local_agent_control_sock_ : -1), POLLIN, 0 },
547 // Check for the control_sock_ actually going away. Only do this if we don't have an active
548 // connection.
Josh Gaobd396c02020-01-22 18:02:19 -0800549 { (adb_connection_socket_ == -1 ? adbconnection_client_pollfd(control_ctx_.get()) : -1),
550 POLLIN | POLLRDHUP, 0 },
Alex Lightfbf96702017-12-14 13:27:13 -0800551 // if we have not loaded the agent either the adb_connection_socket_ is -1 meaning we don't
552 // have a real connection yet or the socket through adb needs to be listened to for incoming
Alex Light15b81132018-01-24 13:29:07 -0800553 // data that the agent or this plugin can handle.
554 { should_listen_on_connection ? adb_connection_socket_ : -1, POLLIN | POLLRDHUP, 0 }
Alex Lightfbf96702017-12-14 13:27:13 -0800555 };
556 int res = TEMP_FAILURE_RETRY(poll(pollfds, 4, -1));
557 if (res < 0) {
558 PLOG(ERROR) << "Failed to poll!";
559 return;
560 }
561 // We don't actually care about doing this we just use it to wake us up.
562 // const struct pollfd& sleep_event_poll = pollfds[0];
563 const struct pollfd& agent_control_sock_poll = pollfds[1];
564 const struct pollfd& control_sock_poll = pollfds[2];
565 const struct pollfd& adb_socket_poll = pollfds[3];
566 if (FlagsSet(agent_control_sock_poll.revents, POLLIN)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800567 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
Alex Lightfbf96702017-12-14 13:27:13 -0800568 DCHECK(agent_loaded_);
569 char buf[257];
570 res = TEMP_FAILURE_RETRY(recv(local_agent_control_sock_, buf, sizeof(buf) - 1, 0));
571 if (res < 0) {
572 PLOG(ERROR) << "Failed to read message from agent control socket! Retrying";
573 continue;
574 } else {
575 buf[res + 1] = '\0';
576 VLOG(jdwp) << "Local agent control sock has data: " << static_cast<const char*>(buf);
577 }
578 if (memcmp(kListenStartMessage, buf, sizeof(kListenStartMessage)) == 0) {
579 agent_listening_ = true;
580 if (adb_connection_socket_ != -1) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700581 SendAgentFds(/*require_handshake=*/ !performed_handshake_);
Alex Lightfbf96702017-12-14 13:27:13 -0800582 }
583 } else if (memcmp(kListenEndMessage, buf, sizeof(kListenEndMessage)) == 0) {
584 agent_listening_ = false;
Alex Lightf51d1822021-02-01 19:25:35 -0800585 } else if (memcmp(kHandshakeCompleteMessage, buf, sizeof(kHandshakeCompleteMessage)) == 0) {
586 if (agent_has_socket_) {
587 performed_handshake_ = true;
588 }
Alex Lightfbf96702017-12-14 13:27:13 -0800589 } else if (memcmp(kCloseMessage, buf, sizeof(kCloseMessage)) == 0) {
590 CloseFds();
591 agent_has_socket_ = false;
592 } else if (memcmp(kAcceptMessage, buf, sizeof(kAcceptMessage)) == 0) {
593 agent_has_socket_ = true;
594 sent_agent_fds_ = false;
Alex Light15b81132018-01-24 13:29:07 -0800595 // We will only ever do the handshake once so reset this.
596 performed_handshake_ = false;
Alex Lightfbf96702017-12-14 13:27:13 -0800597 } else {
598 LOG(ERROR) << "Unknown message received from debugger! '" << std::string(buf) << "'";
599 }
600 } else if (FlagsSet(control_sock_poll.revents, POLLIN)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800601 if (!IsDebuggingPossible()) {
602 // For a profielable process, this path can execute when the adbd restarts.
603 control_ctx_.reset();
604 break;
605 }
Alex Lightfbf96702017-12-14 13:27:13 -0800606 bool maybe_send_fds = false;
607 {
608 // Hold onto this lock so that concurrent ddm publishes don't try to use an illegal fd.
609 ScopedEventFdLock sefdl(adb_write_event_fd_);
Josh Gaobd396c02020-01-22 18:02:19 -0800610 android::base::unique_fd new_fd(adbconnection_client_receive_jdwp_fd(control_ctx_.get()));
Alex Lightfbf96702017-12-14 13:27:13 -0800611 if (new_fd == -1) {
612 // Something went wrong. We need to retry getting the control socket.
Josh Gaobd396c02020-01-22 18:02:19 -0800613 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800614 break;
615 } else if (adb_connection_socket_ != -1) {
616 // We already have a connection.
617 VLOG(jdwp) << "Ignoring second debugger. Accept then drop!";
618 if (new_fd >= 0) {
619 new_fd.reset();
620 }
621 } else {
622 VLOG(jdwp) << "Adb connection established with fd " << new_fd;
623 adb_connection_socket_ = std::move(new_fd);
624 maybe_send_fds = true;
625 }
626 }
627 if (maybe_send_fds && agent_loaded_ && agent_listening_) {
628 VLOG(jdwp) << "Sending fds as soon as we received them.";
Alex Light15b81132018-01-24 13:29:07 -0800629 // The agent was already loaded so this must be after a disconnection. Therefore have the
630 // transport perform the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700631 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800632 }
633 } else if (FlagsSet(control_sock_poll.revents, POLLRDHUP)) {
634 // The other end of the adb connection just dropped it.
635 // Reset the connection since we don't have an active socket through the adb server.
Shukang Zhou670ea842020-02-06 14:53:14 -0800636 // Note this path is expected for either debuggable or profileable processes.
Alex Lightfbf96702017-12-14 13:27:13 -0800637 DCHECK(!agent_has_socket_) << "We shouldn't be doing anything if there is already a "
638 << "connection active";
Josh Gaobd396c02020-01-22 18:02:19 -0800639 control_ctx_.reset();
Alex Lightfbf96702017-12-14 13:27:13 -0800640 break;
641 } else if (FlagsSet(adb_socket_poll.revents, POLLIN)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800642 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
Alex Lightfbf96702017-12-14 13:27:13 -0800643 DCHECK(!agent_has_socket_);
644 if (!agent_loaded_) {
Alex Light15b81132018-01-24 13:29:07 -0800645 HandleDataWithoutAgent(self);
Alex Lightfbf96702017-12-14 13:27:13 -0800646 } else if (agent_listening_ && !sent_agent_fds_) {
647 VLOG(jdwp) << "Sending agent fds again on data.";
Alex Light15b81132018-01-24 13:29:07 -0800648 // Agent was already loaded so it can deal with the handshake.
Andreas Gampe9b031f72018-10-04 11:03:34 -0700649 SendAgentFds(/*require_handshake=*/ true);
Alex Lightfbf96702017-12-14 13:27:13 -0800650 }
Alex Light15b81132018-01-24 13:29:07 -0800651 } else if (FlagsSet(adb_socket_poll.revents, POLLRDHUP)) {
Shukang Zhou670ea842020-02-06 14:53:14 -0800652 CHECK(IsDebuggingPossible()); // This path is unexpected for a profileable process.
Alex Light15b81132018-01-24 13:29:07 -0800653 DCHECK(!agent_has_socket_);
654 CloseFds();
Alex Lightfbf96702017-12-14 13:27:13 -0800655 } else {
656 VLOG(jdwp) << "Woke up poll without anything to do!";
657 }
658 }
659 }
660}
661
Alex Light15b81132018-01-24 13:29:07 -0800662static uint32_t ReadUint32AndAdvance(/*in-out*/uint8_t** in) {
663 uint32_t res;
664 memcpy(&res, *in, sizeof(uint32_t));
665 *in = (*in) + sizeof(uint32_t);
666 return ntohl(res);
667}
668
669void AdbConnectionState::HandleDataWithoutAgent(art::Thread* self) {
670 DCHECK(!agent_loaded_);
671 DCHECK(!agent_listening_);
672 // TODO Should we check in some other way if we are userdebug/eng?
673 CHECK(art::Dbg::IsJdwpAllowed());
674 // We try to avoid loading the agent which is expensive. First lets just perform the handshake.
675 if (!performed_handshake_) {
676 PerformHandshake();
677 return;
678 }
679 // Read the packet header to figure out if it is one we can handle. We only 'peek' into the stream
680 // to see if it's one we can handle. This doesn't change the state of the socket.
681 alignas(sizeof(uint32_t)) uint8_t packet_header[kPacketHeaderLen];
682 ssize_t res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
683 packet_header,
684 sizeof(packet_header),
685 MSG_PEEK));
686 // We want to be very careful not to change the socket state until we know we succeeded. This will
687 // let us fall-back to just loading the agent and letting it deal with everything.
688 if (res <= 0) {
689 // Close the socket. We either hit EOF or an error.
690 if (res < 0) {
691 PLOG(ERROR) << "Unable to peek into adb socket due to error. Closing socket.";
692 }
693 CloseFds();
694 return;
695 } else if (res < static_cast<int>(kPacketHeaderLen)) {
696 LOG(ERROR) << "Unable to peek into adb socket. Loading agent to handle this. Only read " << res;
697 AttachJdwpAgent(self);
698 return;
699 }
700 uint32_t full_len = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketSizeOff));
701 uint32_t pkt_id = ntohl(*reinterpret_cast<uint32_t*>(packet_header + kPacketIdOff));
702 uint8_t pkt_cmd_set = packet_header[kPacketCommandSetOff];
703 uint8_t pkt_cmd = packet_header[kPacketCommandOff];
704 if (pkt_cmd_set != kDdmCommandSet ||
705 pkt_cmd != kDdmChunkCommand ||
706 full_len < kPacketHeaderLen) {
707 VLOG(jdwp) << "Loading agent due to jdwp packet that cannot be handled by adbconnection.";
708 AttachJdwpAgent(self);
709 return;
710 }
711 uint32_t avail = -1;
712 res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
713 if (res < 0) {
714 PLOG(ERROR) << "Failed to determine amount of readable data in socket! Closing connection";
715 CloseFds();
716 return;
717 } else if (avail < full_len) {
718 LOG(WARNING) << "Unable to handle ddm command in adbconnection due to insufficent data. "
719 << "Expected " << full_len << " bytes but only " << avail << " are readable. "
720 << "Loading jdwp agent to deal with this.";
721 AttachJdwpAgent(self);
722 return;
723 }
724 // Actually read the data.
725 std::vector<uint8_t> full_pkt;
726 full_pkt.resize(full_len);
727 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(), full_pkt.data(), full_len, 0));
728 if (res < 0) {
729 PLOG(ERROR) << "Failed to recv data from adb connection. Closing connection";
730 CloseFds();
731 return;
732 }
733 DCHECK_EQ(memcmp(full_pkt.data(), packet_header, sizeof(packet_header)), 0);
734 size_t data_size = full_len - kPacketHeaderLen;
735 if (data_size < (sizeof(uint32_t) * 2)) {
736 // This is an error (the data isn't long enough) but to match historical behavior we need to
737 // ignore it.
738 return;
739 }
740 uint8_t* ddm_data = full_pkt.data() + kPacketHeaderLen;
741 uint32_t ddm_type = ReadUint32AndAdvance(&ddm_data);
742 uint32_t ddm_len = ReadUint32AndAdvance(&ddm_data);
743 if (ddm_len > data_size - (2 * sizeof(uint32_t))) {
744 // This is an error (the data isn't long enough) but to match historical behavior we need to
745 // ignore it.
746 return;
747 }
748
749 if (!notified_ddm_active_) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700750 NotifyDdms(/*active=*/ true);
Alex Light15b81132018-01-24 13:29:07 -0800751 }
752 uint32_t reply_type;
753 std::vector<uint8_t> reply;
754 if (!art::Dbg::DdmHandleChunk(self->GetJniEnv(),
755 ddm_type,
756 art::ArrayRef<const jbyte>(reinterpret_cast<const jbyte*>(ddm_data),
757 ddm_len),
758 /*out*/&reply_type,
759 /*out*/&reply)) {
760 // To match historical behavior we don't send any response when there is no data to reply with.
761 return;
762 }
763 SendDdmPacket(pkt_id,
764 DdmPacketType::kReply,
765 reply_type,
766 art::ArrayRef<const uint8_t>(reply));
767}
768
769void AdbConnectionState::PerformHandshake() {
770 CHECK(!performed_handshake_);
771 // Check to make sure we are able to read the whole handshake.
772 uint32_t avail = -1;
773 int res = TEMP_FAILURE_RETRY(ioctl(adb_connection_socket_.get(), FIONREAD, &avail));
774 if (res < 0 || avail < sizeof(kJdwpHandshake)) {
775 if (res < 0) {
776 PLOG(ERROR) << "Failed to determine amount of readable data for handshake!";
777 }
778 LOG(WARNING) << "Closing connection to broken client.";
779 CloseFds();
780 return;
781 }
782 // Perform the handshake.
783 char handshake_msg[sizeof(kJdwpHandshake)];
784 res = TEMP_FAILURE_RETRY(recv(adb_connection_socket_.get(),
785 handshake_msg,
786 sizeof(handshake_msg),
787 MSG_DONTWAIT));
788 if (res < static_cast<int>(sizeof(kJdwpHandshake)) ||
789 strncmp(handshake_msg, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) {
790 if (res < 0) {
791 PLOG(ERROR) << "Failed to read handshake!";
792 }
793 LOG(WARNING) << "Handshake failed!";
794 CloseFds();
795 return;
796 }
797 // Send the handshake back.
798 res = TEMP_FAILURE_RETRY(send(adb_connection_socket_.get(),
799 kJdwpHandshake,
800 sizeof(kJdwpHandshake),
801 0));
802 if (res < static_cast<int>(sizeof(kJdwpHandshake))) {
803 PLOG(ERROR) << "Failed to send jdwp-handshake response.";
804 CloseFds();
805 return;
806 }
807 performed_handshake_ = true;
808}
809
810void AdbConnectionState::AttachJdwpAgent(art::Thread* self) {
Alex Lightbd2a4e22018-04-17 09:07:37 -0700811 art::Runtime* runtime = art::Runtime::Current();
Alex Light15b81132018-01-24 13:29:07 -0800812 self->AssertNoPendingException();
Andreas Gampe9b031f72018-10-04 11:03:34 -0700813 runtime->AttachAgent(/* env= */ nullptr,
Alex Lightbd2a4e22018-04-17 09:07:37 -0700814 MakeAgentArg(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700815 /* class_loader= */ nullptr);
Alex Light15b81132018-01-24 13:29:07 -0800816 if (self->IsExceptionPending()) {
817 LOG(ERROR) << "Failed to load agent " << agent_name_;
818 art::ScopedObjectAccess soa(self);
819 self->GetException()->Dump();
820 self->ClearException();
821 return;
822 }
823 agent_loaded_ = true;
824}
825
Alex Light81f75c32018-01-26 09:46:32 -0800826bool ContainsArgument(const std::string& opts, const char* arg) {
827 return opts.find(arg) != std::string::npos;
828}
829
830bool ValidateJdwpOptions(const std::string& opts) {
831 bool res = true;
832 // The adbconnection plugin requires that the jdwp agent be configured as a 'server' because that
833 // is what adb expects and otherwise we will hit a deadlock as the poll loop thread stops waiting
834 // for the fd's to be passed down.
835 if (ContainsArgument(opts, "server=n")) {
836 res = false;
837 LOG(ERROR) << "Cannot start jdwp debugging with server=n from adbconnection.";
838 }
839 // We don't start the jdwp agent until threads are already running. It is far too late to suspend
840 // everything.
841 if (ContainsArgument(opts, "suspend=y")) {
842 res = false;
843 LOG(ERROR) << "Cannot use suspend=y with late-init jdwp.";
844 }
845 return res;
846}
847
Alex Lightfbf96702017-12-14 13:27:13 -0800848std::string AdbConnectionState::MakeAgentArg() {
Alex Lightfbf96702017-12-14 13:27:13 -0800849 const std::string& opts = art::Runtime::Current()->GetJdwpOptions();
Alex Light81f75c32018-01-26 09:46:32 -0800850 DCHECK(ValidateJdwpOptions(opts));
851 // TODO Get agent_name_ from something user settable?
852 return agent_name_ + "=" + opts + (opts.empty() ? "" : ",") +
853 "ddm_already_active=" + (notified_ddm_active_ ? "y" : "n") + "," +
854 // See the comment above for why we need to be server=y. Since the agent defaults to server=n
855 // we will add it if it wasn't already present for the convenience of the user.
856 (ContainsArgument(opts, "server=y") ? "" : "server=y,") +
857 // See the comment above for why we need to be suspend=n. Since the agent defaults to
858 // suspend=y we will add it if it wasn't already present.
Alex Light5ebdc882018-06-04 16:42:30 -0700859 (ContainsArgument(opts, "suspend=n") ? "" : "suspend=n,") +
Alex Light81f75c32018-01-26 09:46:32 -0800860 "transport=dt_fd_forward,address=" + std::to_string(remote_agent_control_sock_);
Alex Lightfbf96702017-12-14 13:27:13 -0800861}
862
863void AdbConnectionState::StopDebuggerThreads() {
864 // The regular agent system will take care of unloading the agent (if needed).
865 shutting_down_ = true;
866 // Wakeup the poll loop.
867 uint64_t data = 1;
Alex Lightd6f9d852018-01-25 11:26:28 -0800868 if (sleep_event_fd_ != -1) {
869 TEMP_FAILURE_RETRY(write(sleep_event_fd_, &data, sizeof(data)));
870 }
Alex Lightfbf96702017-12-14 13:27:13 -0800871}
872
873// The plugin initialization function.
Alex Light3b08bcc2019-09-11 09:48:51 -0700874extern "C" bool ArtPlugin_Initialize() {
Alex Lightfbf96702017-12-14 13:27:13 -0800875 DCHECK(art::Runtime::Current()->GetJdwpProvider() == art::JdwpProvider::kAdbConnection);
876 // TODO Provide some way for apps to set this maybe?
Flash Liu013e2082019-10-31 11:18:55 +0800877 gState.emplace(kDefaultJdwpAgentName);
Alex Light81f75c32018-01-26 09:46:32 -0800878 return ValidateJdwpOptions(art::Runtime::Current()->GetJdwpOptions());
Alex Lightfbf96702017-12-14 13:27:13 -0800879}
880
881extern "C" bool ArtPlugin_Deinitialize() {
Alex Light75d21892020-03-25 14:18:56 -0700882 // We don't actually have to do anything here. The debugger (if one was
883 // attached) was shutdown by the move to the kDeath runtime phase and the
884 // adbconnection threads were shutdown by StopDebugger.
Alex Lightfbf96702017-12-14 13:27:13 -0800885 return true;
886}
887
888} // namespace adbconnection