blob: a7857a1eaf8d82a7e3757b7db71ab7fa30b9c4ec [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 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/*
18 * JDWP initialization.
19 */
20
21#include "atomic.h"
22#include "debugger.h"
23#include "jdwp/jdwp_priv.h"
24#include "logging.h"
25
26#include <stdlib.h>
27#include <unistd.h>
28#include <sys/time.h>
29#include <time.h>
30#include <errno.h>
31
32namespace art {
33
34namespace JDWP {
35
Elliott Hughes376a7a02011-10-24 18:35:55 -070036static void* StartJdwpThread(void* arg);
Elliott Hughes872d4ec2011-10-21 17:07:15 -070037
38/*
39 * JdwpNetStateBase class implementation
40 */
41JdwpNetStateBase::JdwpNetStateBase() : socket_lock_("JdwpNetStateBase lock") {
42 clientSock = -1;
43}
44
45/*
46 * Write a packet. Grabs a mutex to assure atomicity.
47 */
48ssize_t JdwpNetStateBase::writePacket(ExpandBuf* pReply) {
49 MutexLock mu(socket_lock_);
50 return write(clientSock, expandBufGetBuffer(pReply), expandBufGetLength(pReply));
51}
52
53/*
54 * Write a buffered packet. Grabs a mutex to assure atomicity.
55 */
56ssize_t JdwpNetStateBase::writeBufferedPacket(const iovec* iov, int iovcnt) {
57 MutexLock mu(socket_lock_);
58 return writev(clientSock, iov, iovcnt);
59}
60
Elliott Hughes376a7a02011-10-24 18:35:55 -070061bool JdwpState::IsConnected() {
62 return (*transport->isConnected)(this);
Elliott Hughes872d4ec2011-10-21 17:07:15 -070063}
64
Elliott Hughes376a7a02011-10-24 18:35:55 -070065bool JdwpState::SendRequest(ExpandBuf* pReq) {
66 return (*transport->sendRequest)(this, pReq);
Elliott Hughes872d4ec2011-10-21 17:07:15 -070067}
68
Elliott Hughes376a7a02011-10-24 18:35:55 -070069/*
70 * Get the next "request" serial number. We use this when sending
71 * packets to the debugger.
72 */
73uint32_t JdwpState::NextRequestSerial() {
74 MutexLock mu(serial_lock_);
75 return requestSerial++;
Elliott Hughes872d4ec2011-10-21 17:07:15 -070076}
77
Elliott Hughes376a7a02011-10-24 18:35:55 -070078/*
79 * Get the next "event" serial number. We use this in the response to
80 * message type EventRequest.Set.
81 */
82uint32_t JdwpState::NextEventSerial() {
83 MutexLock mu(serial_lock_);
84 return eventSerial++;
Elliott Hughes872d4ec2011-10-21 17:07:15 -070085}
86
Elliott Hughes376a7a02011-10-24 18:35:55 -070087JdwpState::JdwpState(const JdwpOptions* options)
88 : options_(options),
89 thread_start_lock_("JDWP thread start lock"),
Elliott Hughes872d4ec2011-10-21 17:07:15 -070090 thread_start_cond_("JDWP thread start condition variable"),
91 debug_thread_started_(false),
92 debugThreadId(0),
93 run(false),
94 transport(NULL),
95 netState(NULL),
96 attach_lock_("JDWP attach lock"),
97 attach_cond_("JDWP attach condition variable"),
98 lastActivityWhen(0),
99 requestSerial(0x10000000),
100 eventSerial(0x20000000),
101 serial_lock_("JDWP serial lock"),
102 numEvents(0),
103 eventList(NULL),
104 event_lock_("JDWP event lock"),
105 event_thread_lock_("JDWP event thread lock"),
106 event_thread_cond_("JDWP event thread condition variable"),
107 eventThreadId(0),
108 ddmActive(false) {
109}
110
111/*
112 * Initialize JDWP.
113 *
114 * Does not return until JDWP thread is running, but may return before
115 * the thread is accepting network connections.
116 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700117JdwpState* JdwpState::Create(const JdwpOptions* options) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700118 /* comment this out when debugging JDWP itself */
119 //android_setMinPriority(LOG_TAG, ANDROID_LOG_DEBUG);
120
Elliott Hughes376a7a02011-10-24 18:35:55 -0700121 JdwpState* state = new JdwpState(options);
122 switch (options->transport) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700123 case kJdwpTransportSocket:
124 // LOGD("prepping for JDWP over TCP");
125 state->transport = SocketTransport();
126 break;
127#ifdef HAVE_ANDROID_OS
128 case kJdwpTransportAndroidAdb:
129 // LOGD("prepping for JDWP over ADB");
130 state->transport = AndroidAdbTransport();
131 break;
132#endif
133 default:
Elliott Hughes376a7a02011-10-24 18:35:55 -0700134 LOG(FATAL) << "Unknown transport: " << options->transport;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700135 }
136
Elliott Hughes376a7a02011-10-24 18:35:55 -0700137 if (!(*state->transport->startup)(state, options)) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700138 goto fail;
139 }
140
141 /*
142 * Grab a mutex or two before starting the thread. This ensures they
143 * won't signal the cond var before we're waiting.
144 */
145 state->thread_start_lock_.Lock();
Elliott Hughes376a7a02011-10-24 18:35:55 -0700146 if (options->suspend) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700147 state->attach_lock_.Lock();
148 }
149
150 /*
151 * We have bound to a port, or are trying to connect outbound to a
152 * debugger. Create the JDWP thread and let it continue the mission.
153 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700154 CHECK_PTHREAD_CALL(pthread_create, (&state->debugThreadHandle, NULL, StartJdwpThread, state), "JDWP thread");
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700155
156 /*
157 * Wait until the thread finishes basic initialization.
158 * TODO: cond vars should be waited upon in a loop
159 */
160 state->thread_start_cond_.Wait(state->thread_start_lock_);
161 state->thread_start_lock_.Unlock();
162
163 /*
164 * For suspend=y, wait for the debugger to connect to us or for us to
165 * connect to the debugger.
166 *
167 * The JDWP thread will signal us when it connects successfully or
168 * times out (for timeout=xxx), so we have to check to see what happened
169 * when we wake up.
170 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700171 if (options->suspend) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700172 {
173 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
174
175 state->attach_cond_.Wait(state->attach_lock_);
176 state->attach_lock_.Unlock();
177 }
178
Elliott Hughes376a7a02011-10-24 18:35:55 -0700179 if (!state->IsActive()) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700180 LOG(ERROR) << "JDWP connection failed";
181 goto fail;
182 }
183
184 LOG(INFO) << "JDWP connected";
185
186 /*
187 * Ordinarily we would pause briefly to allow the debugger to set
188 * breakpoints and so on, but for "suspend=y" the VM init code will
189 * pause the VM when it sends the VM_START message.
190 */
191 }
192
193 return state;
194
195fail:
Elliott Hughes376a7a02011-10-24 18:35:55 -0700196 delete state; // frees state
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700197 return NULL;
198}
199
200/*
201 * Reset all session-related state. There should not be an active connection
202 * to the client at this point. The rest of the VM still thinks there is
203 * a debugger attached.
204 *
205 * This includes freeing up the debugger event list.
206 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700207void JdwpState::ResetState() {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700208 /* could reset the serial numbers, but no need to */
209
Elliott Hughes376a7a02011-10-24 18:35:55 -0700210 UnregisterAll(this);
211 CHECK(eventList == NULL);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700212
213 /*
214 * Should not have one of these in progress. If the debugger went away
215 * mid-request, though, we could see this.
216 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700217 if (eventThreadId != 0) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700218 LOG(WARNING) << "resetting state while event in progress";
219 DCHECK(false);
220 }
221}
222
223/*
224 * Tell the JDWP thread to shut down. Frees "state".
225 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700226JdwpState::~JdwpState() {
227 if (transport != NULL) {
228 if (IsConnected()) {
229 PostVMDeath();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700230 }
231
232 /*
233 * Close down the network to inspire the thread to halt.
234 */
235 LOG(DEBUG) << "JDWP shutting down net...";
Elliott Hughes376a7a02011-10-24 18:35:55 -0700236 (*transport->shutdown)(this);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700237
Elliott Hughes376a7a02011-10-24 18:35:55 -0700238 if (debug_thread_started_) {
239 run = false;
240 void* threadReturn;
241 if (pthread_join(debugThreadHandle, &threadReturn) != 0) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700242 LOG(WARNING) << "JDWP thread join failed";
243 }
244 }
245
246 LOG(DEBUG) << "JDWP freeing netstate...";
Elliott Hughes376a7a02011-10-24 18:35:55 -0700247 (*transport->free)(this);
248 netState = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700249 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700250 CHECK(netState == NULL);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700251
Elliott Hughes376a7a02011-10-24 18:35:55 -0700252 ResetState();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700253}
254
255/*
256 * Are we talking to a debugger?
257 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700258bool JdwpState::IsActive() {
259 return IsConnected();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700260}
261
262/*
263 * Entry point for JDWP thread. The thread was created through the VM
264 * mechanisms, so there is a java/lang/Thread associated with us.
265 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700266static void* StartJdwpThread(void* arg) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700267 JdwpState* state = reinterpret_cast<JdwpState*>(arg);
268 CHECK(state != NULL);
269
Elliott Hughes376a7a02011-10-24 18:35:55 -0700270 state->Run();
271 return NULL;
272}
273
274void JdwpState::Run() {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700275 Runtime* runtime = Runtime::Current();
276 runtime->AttachCurrentThread("JDWP", true);
277
278 LOG(VERBOSE) << "JDWP: thread running";
279
280 /*
Elliott Hughes376a7a02011-10-24 18:35:55 -0700281 * Finish initializing, then notify the creating thread that
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700282 * we're running.
283 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700284 debugThreadHandle = pthread_self();
285 run = true;
286 android_atomic_release_store(true, &debug_thread_started_);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700287
Elliott Hughes376a7a02011-10-24 18:35:55 -0700288 thread_start_lock_.Lock();
289 thread_start_cond_.Broadcast();
290 thread_start_lock_.Unlock();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700291
292 /* set the thread state to VMWAIT so GCs don't wait for us */
293 Dbg::ThreadWaiting();
294
295 /*
296 * Loop forever if we're in server mode, processing connections. In
297 * non-server mode, we bail out of the thread when the debugger drops
298 * us.
299 *
300 * We broadcast a notification when a debugger attaches, after we
301 * successfully process the handshake.
302 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700303 while (run) {
304 if (options_->server) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700305 /*
306 * Block forever, waiting for a connection. To support the
307 * "timeout=xxx" option we'll need to tweak this.
308 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700309 if (!(*transport->accept)(this)) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700310 break;
311 }
312 } else {
313 /*
314 * If we're not acting as a server, we need to connect out to the
315 * debugger. To support the "timeout=xxx" option we need to
316 * have a timeout if the handshake reply isn't received in a
317 * reasonable amount of time.
318 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700319 if (!(*transport->establish)(this)) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700320 /* wake anybody who was waiting for us to succeed */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700321 MutexLock mu(attach_lock_);
322 attach_cond_.Broadcast();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700323 break;
324 }
325 }
326
327 /* prep debug code to handle the new connection */
328 Dbg::Connected();
329
330 /* process requests until the debugger drops */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700331 bool first = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700332 while (true) {
333 // sanity check -- shouldn't happen?
334 if (Thread::Current()->GetState() != Thread::kVmWait) {
335 LOG(ERROR) << "JDWP thread no longer in VMWAIT (now " << Thread::Current()->GetState() << "); resetting";
336 Dbg::ThreadWaiting();
337 }
338
Elliott Hughes376a7a02011-10-24 18:35:55 -0700339 if (!(*transport->processIncoming)(this)) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700340 /* blocking read */
341 break;
342 }
343
Elliott Hughes376a7a02011-10-24 18:35:55 -0700344 if (first && !(*transport->awaitingHandshake)(this)) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700345 /* handshake worked, tell the interpreter that we're active */
346 first = false;
347
348 /* set thread ID; requires object registry to be active */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700349 debugThreadId = Dbg::GetThreadSelfId();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700350
351 /* wake anybody who's waiting for us */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700352 MutexLock mu(attach_lock_);
353 attach_cond_.Broadcast();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700354 }
355 }
356
Elliott Hughes376a7a02011-10-24 18:35:55 -0700357 (*transport->close)(this);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700358
Elliott Hughes376a7a02011-10-24 18:35:55 -0700359 if (ddmActive) {
360 ddmActive = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700361
362 /* broadcast the disconnect; must be in RUNNING state */
363 Dbg::ThreadRunning();
364 Dbg::DdmDisconnected();
365 Dbg::ThreadWaiting();
366 }
367
368 /* release session state, e.g. remove breakpoint instructions */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700369 ResetState();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700370
371 /* tell the interpreter that the debugger is no longer around */
372 Dbg::Disconnected();
373
374 /* if we had threads suspended, resume them now */
375 Dbg::UndoDebuggerSuspensions();
376
377 /* if we connected out, this was a one-shot deal */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700378 if (!options_->server) {
379 run = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700380 }
381 }
382
383 /* back to running, for thread shutdown */
384 Dbg::ThreadRunning();
385
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700386 LOG(VERBOSE) << "JDWP: thread detaching and exiting...";
387 runtime->DetachCurrentThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700388}
389
Elliott Hughes376a7a02011-10-24 18:35:55 -0700390pthread_t JdwpState::GetDebugThread() {
391 return debugThreadHandle;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700392}
393
394/*
395 * Support routines for waitForDebugger().
396 *
397 * We can't have a trivial "waitForDebugger" function that returns the
398 * instant the debugger connects, because we run the risk of executing code
399 * before the debugger has had a chance to configure breakpoints or issue
400 * suspend calls. It would be nice to just sit in the suspended state, but
401 * most debuggers don't expect any threads to be suspended when they attach.
402 *
403 * There's no JDWP event we can post to tell the debugger, "we've stopped,
404 * and we like it that way". We could send a fake breakpoint, which should
405 * cause the debugger to immediately send a resume, but the debugger might
406 * send the resume immediately or might throw an exception of its own upon
407 * receiving a breakpoint event that it didn't ask for.
408 *
409 * What we really want is a "wait until the debugger is done configuring
410 * stuff" event. We can approximate this with a "wait until the debugger
411 * has been idle for a brief period".
412 */
413
414/*
415 * Get a notion of the current time, in milliseconds.
416 */
417int64_t GetNowMsec() {
418#ifdef HAVE_POSIX_CLOCKS
419 struct timespec now;
420 clock_gettime(CLOCK_MONOTONIC, &now);
421 return now.tv_sec * 1000LL + now.tv_nsec / 1000000LL;
422#else
423 struct timeval now;
424 gettimeofday(&now, NULL);
425 return now.tv_sec * 1000LL + now.tv_usec / 1000LL;
426#endif
427}
428
429/*
430 * Return the time, in milliseconds, since the last debugger activity.
431 *
432 * Returns -1 if no debugger is attached, or 0 if we're in the middle of
433 * processing a debugger request.
434 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700435int64_t JdwpState::LastDebuggerActivity() {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700436 if (!Dbg::IsDebuggerConnected()) {
437 LOG(DEBUG) << "no active debugger";
438 return -1;
439 }
440
Elliott Hughes376a7a02011-10-24 18:35:55 -0700441 int64_t last = QuasiAtomicRead64(&lastActivityWhen);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700442
443 /* initializing or in the middle of something? */
444 if (last == 0) {
445 LOG(VERBOSE) << "+++ last=busy";
446 return 0;
447 }
448
449 /* now get the current time */
450 int64_t now = GetNowMsec();
451 CHECK_GT(now, last);
452
453 LOG(VERBOSE) << "+++ debugger interval=" << (now - last);
454 return now - last;
455}
456
457static const char* kTransportNames[] = {
458 "Unknown",
459 "Socket",
460 "AndroidAdb",
461};
462std::ostream& operator<<(std::ostream& os, const JdwpTransportType& value) {
463 int32_t int_value = static_cast<int32_t>(value);
464 if (value >= kJdwpTransportUnknown && value <= kJdwpTransportAndroidAdb) {
465 os << kTransportNames[int_value];
466 } else {
467 os << "JdwpTransportType[" << int_value << "]";
468 }
469 return os;
470}
471
472} // namespace JDWP
473
474} // namespace art