2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * Send events to the debugger.
19 #include "jdwp/JdwpPriv.h"
20 #include "jdwp/JdwpConstants.h"
21 #include "jdwp/JdwpHandler.h"
22 #include "jdwp/JdwpEvent.h"
23 #include "jdwp/ExpandBuf.h"
27 #include <stddef.h> /* for offsetof() */
33 The event add/remove stuff usually happens from the debugger thread,
34 in response to requests from the debugger, but can also happen as the
35 result of an event in an arbitrary thread (e.g. an event with a "count"
36 mod expires). It's important to keep the event list locked when processing
39 Event posting can happen from any thread. The JDWP thread will not usually
40 post anything but VM start/death, but if a JDWP request causes a class
41 to be loaded, the ClassPrepare event will come from the JDWP thread.
44 We can have serialization issues when we post an event to the debugger.
45 For example, a thread could send an "I hit a breakpoint and am suspending
46 myself" message to the debugger. Before it manages to suspend itself, the
47 debugger's response ("not interested, resume thread") arrives and is
48 processed. We try to resume a thread that hasn't yet suspended.
50 This means that, after posting an event to the debugger, we need to wait
51 for the event thread to suspend itself (and, potentially, all other threads)
52 before processing any additional requests from the debugger. While doing
53 so we need to be aware that multiple threads may be hitting breakpoints
54 or other events simultaneously, so we either need to wait for all of them
55 or serialize the events with each other.
57 The current mechanism works like this:
59 - If I'm going to suspend, grab the "I am posting an event" token. Wait
60 for it if it's not currently available.
61 - Post the event to the debugger.
62 - If appropriate, suspend others and then myself. As part of suspending
63 myself, release the "I am posting" token.
65 - When an event arrives, see if somebody is posting an event. If so,
66 sleep until we can acquire the "I am posting an event" token. Release
67 it immediately and continue processing -- the event we have already
68 received should not interfere with other events that haven't yet
71 Some care must be taken to avoid deadlock:
73 - thread A and thread B exit near-simultaneously, and post thread-death
74 events with a "suspend all" clause
75 - thread A gets the event token, thread B sits and waits for it
76 - thread A wants to suspend all other threads, but thread B is waiting
77 for the token and can't be suspended
79 So we need to mark thread B in such a way that thread A doesn't wait for it.
81 If we just bracket the "grab event token" call with a change to VMWAIT
82 before sleeping, the switch back to RUNNING state when we get the token
83 will cause thread B to suspend (remember, thread A's global suspend is
84 still in force, even after it releases the token). Suspending while
85 holding the event token is very bad, because it prevents the JDWP thread
86 from processing incoming messages.
88 We need to change to VMWAIT state at the *start* of posting an event,
89 and stay there until we either finish posting the event or decide to
90 put ourselves to sleep. That way we don't interfere with anyone else and
91 don't allow anyone else to interfere with us.
95 #define kJdwpEventCommandSet 64
96 #define kJdwpCompositeCommand 100
99 * Stuff to compare against when deciding if a mod matches. Only the
100 * values for mods valid for the event being evaluated will be filled in.
101 * The rest will be zeroed.
104 const JdwpLocation* pLoc; /* LocationOnly */
105 const char* className; /* ClassMatch/ClassExclude */
106 ObjectId threadId; /* ThreadOnly */
107 RefTypeId classId; /* ClassOnly */
108 RefTypeId excepClassId; /* ExceptionOnly */
109 bool caught; /* ExceptionOnly */
110 FieldId field; /* FieldOnly */
111 ObjectId thisPtr; /* InstanceOnly */
112 /* nothing for StepOnly -- handled differently */
116 * Get the next "request" serial number. We use this when sending
117 * packets to the debugger.
119 u4 dvmJdwpNextRequestSerial(JdwpState* state)
121 dvmDbgLockMutex(&state->serialLock);
122 u4 result = state->requestSerial++;
123 dvmDbgUnlockMutex(&state->serialLock);
129 * Get the next "event" serial number. We use this in the response to
130 * message type EventRequest.Set.
132 u4 dvmJdwpNextEventSerial(JdwpState* state)
134 dvmDbgLockMutex(&state->serialLock);
135 u4 result = state->eventSerial++;
136 dvmDbgUnlockMutex(&state->serialLock);
142 * Lock the "event" mutex, which guards the list of registered events.
144 static void lockEventMutex(JdwpState* state)
146 //dvmDbgThreadWaiting();
147 dvmDbgLockMutex(&state->eventLock);
148 //dvmDbgThreadRunning();
152 * Unlock the "event" mutex.
154 static void unlockEventMutex(JdwpState* state)
156 dvmDbgUnlockMutex(&state->eventLock);
160 * Dump an event to the log file.
162 static void dumpEvent(const JdwpEvent* pEvent)
164 LOGI("Event id=0x%4x %p (prev=%p next=%p):",
165 pEvent->requestId, pEvent, pEvent->prev, pEvent->next);
166 LOGI(" kind=%s susp=%s modCount=%d",
167 dvmJdwpEventKindStr(pEvent->eventKind),
168 dvmJdwpSuspendPolicyStr(pEvent->suspendPolicy),
171 for (int i = 0; i < pEvent->modCount; i++) {
172 const JdwpEventMod* pMod = &pEvent->mods[i];
173 JdwpModKind kind = static_cast<JdwpModKind>(pMod->modKind);
174 LOGI(" %s", dvmJdwpModKindStr(kind));
175 /* TODO - show details */
180 * Add an event to the list. Ordering is not important.
182 * If something prevents the event from being registered, e.g. it's a
183 * single-step request on a thread that doesn't exist, the event will
184 * not be added to the list, and an appropriate error will be returned.
186 JdwpError dvmJdwpRegisterEvent(JdwpState* state, JdwpEvent* pEvent)
188 lockEventMutex(state);
190 assert(state != NULL);
191 assert(pEvent != NULL);
192 assert(pEvent->prev == NULL);
193 assert(pEvent->next == NULL);
196 * If one or more "break"-type mods are used, register them with
199 for (int i = 0; i < pEvent->modCount; i++) {
200 const JdwpEventMod* pMod = &pEvent->mods[i];
201 if (pMod->modKind == MK_LOCATION_ONLY) {
202 /* should only be for Breakpoint, Step, and Exception */
203 dvmDbgWatchLocation(&pMod->locationOnly.loc);
204 } else if (pMod->modKind == MK_STEP) {
205 /* should only be for EK_SINGLE_STEP; should only be one */
206 JdwpStepSize size = static_cast<JdwpStepSize>(pMod->step.size);
207 JdwpStepDepth depth = static_cast<JdwpStepDepth>(pMod->step.depth);
208 dvmDbgConfigureStep(pMod->step.threadId, size, depth);
209 } else if (pMod->modKind == MK_FIELD_ONLY) {
210 /* should be for EK_FIELD_ACCESS or EK_FIELD_MODIFICATION */
211 dumpEvent(pEvent); /* TODO - need for field watches */
218 if (state->eventList != NULL) {
219 pEvent->next = state->eventList;
220 state->eventList->prev = pEvent;
222 state->eventList = pEvent;
225 unlockEventMutex(state);
231 * Remove an event from the list. This will also remove the event from
232 * any optimization tables, e.g. breakpoints.
234 * Does not free the JdwpEvent.
236 * Grab the eventLock before calling here.
238 static void unregisterEvent(JdwpState* state, JdwpEvent* pEvent)
240 if (pEvent->prev == NULL) {
241 /* head of the list */
242 assert(state->eventList == pEvent);
244 state->eventList = pEvent->next;
246 pEvent->prev->next = pEvent->next;
249 if (pEvent->next != NULL) {
250 pEvent->next->prev = pEvent->prev;
256 * Unhook us from the interpreter, if necessary.
258 for (int i = 0; i < pEvent->modCount; i++) {
259 JdwpEventMod* pMod = &pEvent->mods[i];
260 if (pMod->modKind == MK_LOCATION_ONLY) {
261 /* should only be for Breakpoint, Step, and Exception */
262 dvmDbgUnwatchLocation(&pMod->locationOnly.loc);
264 if (pMod->modKind == MK_STEP) {
265 /* should only be for EK_SINGLE_STEP; should only be one */
266 dvmDbgUnconfigureStep(pMod->step.threadId);
271 assert(state->numEvents != 0 || state->eventList == NULL);
275 * Remove the event with the given ID from the list.
277 * Failure to find the event isn't really an error, but it is a little
278 * weird. (It looks like Eclipse will try to be extra careful and will
279 * explicitly remove one-off single-step events.)
281 void dvmJdwpUnregisterEventById(JdwpState* state, u4 requestId)
283 lockEventMutex(state);
285 JdwpEvent* pEvent = state->eventList;
286 while (pEvent != NULL) {
287 if (pEvent->requestId == requestId) {
288 unregisterEvent(state, pEvent);
289 dvmJdwpEventFree(pEvent);
290 goto done; /* there can be only one with a given ID */
293 pEvent = pEvent->next;
296 //LOGD("Odd: no match when removing event reqId=0x%04x", requestId);
299 unlockEventMutex(state);
303 * Remove all entries from the event list.
305 void dvmJdwpUnregisterAll(JdwpState* state)
307 lockEventMutex(state);
309 JdwpEvent* pEvent = state->eventList;
310 while (pEvent != NULL) {
311 JdwpEvent* pNextEvent = pEvent->next;
313 unregisterEvent(state, pEvent);
314 dvmJdwpEventFree(pEvent);
318 state->eventList = NULL;
320 unlockEventMutex(state);
326 * Allocate a JdwpEvent struct with enough space to hold the specified
327 * number of mod records.
329 JdwpEvent* dvmJdwpEventAlloc(int numMods)
332 int allocSize = offsetof(JdwpEvent, mods) +
333 numMods * sizeof(newEvent->mods[0]);
335 newEvent = (JdwpEvent*)malloc(allocSize);
336 memset(newEvent, 0, allocSize);
343 * Do not call this until the event has been removed from the list.
345 void dvmJdwpEventFree(JdwpEvent* pEvent)
350 /* make sure it was removed from the list */
351 assert(pEvent->prev == NULL);
352 assert(pEvent->next == NULL);
353 /* want to assert state->eventList != pEvent */
356 * Free any hairy bits in the mods.
358 for (int i = 0; i < pEvent->modCount; i++) {
359 if (pEvent->mods[i].modKind == MK_CLASS_MATCH) {
360 free(pEvent->mods[i].classMatch.classPattern);
361 pEvent->mods[i].classMatch.classPattern = NULL;
363 if (pEvent->mods[i].modKind == MK_CLASS_EXCLUDE) {
364 free(pEvent->mods[i].classExclude.classPattern);
365 pEvent->mods[i].classExclude.classPattern = NULL;
373 * Allocate storage for matching events. To keep things simple we
374 * use an array with enough storage for the entire list.
376 * The state->eventLock should be held before calling.
378 static JdwpEvent** allocMatchList(JdwpState* state)
380 return (JdwpEvent**) malloc(sizeof(JdwpEvent*) * state->numEvents);
384 * Run through the list and remove any entries with an expired "count" mod
385 * from the event list, then free the match list.
387 static void cleanupMatchList(JdwpState* state, JdwpEvent** matchList,
390 JdwpEvent** ppEvent = matchList;
392 while (matchCount--) {
393 JdwpEvent* pEvent = *ppEvent;
395 for (int i = 0; i < pEvent->modCount; i++) {
396 if (pEvent->mods[i].modKind == MK_COUNT &&
397 pEvent->mods[i].count.count == 0)
399 LOGV("##### Removing expired event");
400 unregisterEvent(state, pEvent);
401 dvmJdwpEventFree(pEvent);
413 * Match a string against a "restricted regular expression", which is just
414 * a string that may start or end with '*' (e.g. "*.Foo" or "java.*").
416 * ("Restricted name globbing" might have been a better term.)
418 static bool patternMatch(const char* pattern, const char* target)
420 int patLen = strlen(pattern);
422 if (pattern[0] == '*') {
423 int targetLen = strlen(target);
425 // TODO: remove printf when we find a test case to verify this
426 LOGE(">>> comparing '%s' to '%s'",
427 pattern+1, target + (targetLen-patLen));
429 if (targetLen < patLen)
431 return strcmp(pattern+1, target + (targetLen-patLen)) == 0;
432 } else if (pattern[patLen-1] == '*') {
433 return strncmp(pattern, target, patLen-1) == 0;
435 return strcmp(pattern, target) == 0;
440 * See if two locations are equal.
442 * It's tempting to do a bitwise compare ("struct ==" or memcmp), but if
443 * the storage wasn't zeroed out there could be undefined values in the
444 * padding. Besides, the odds of "idx" being equal while the others aren't
445 * is very small, so this is usually just a simple integer comparison.
447 static inline bool locationMatch(const JdwpLocation* pLoc1,
448 const JdwpLocation* pLoc2)
450 return pLoc1->idx == pLoc2->idx &&
451 pLoc1->methodId == pLoc2->methodId &&
452 pLoc1->classId == pLoc2->classId &&
453 pLoc1->typeTag == pLoc2->typeTag;
457 * See if the event's mods match up with the contents of "basket".
459 * If we find a Count mod before rejecting an event, we decrement it. We
460 * need to do this even if later mods cause us to ignore the event.
462 static bool modsMatch(JdwpState* state, JdwpEvent* pEvent, ModBasket* basket)
464 JdwpEventMod* pMod = pEvent->mods;
466 for (int i = pEvent->modCount; i > 0; i--, pMod++) {
467 switch (pMod->modKind) {
469 assert(pMod->count.count > 0);
473 assert(false); // should not be getting these
476 if (pMod->threadOnly.threadId != basket->threadId)
480 if (!dvmDbgMatchType(basket->classId, pMod->classOnly.refTypeId))
484 if (!patternMatch(pMod->classMatch.classPattern,
488 case MK_CLASS_EXCLUDE:
489 if (patternMatch(pMod->classMatch.classPattern,
493 case MK_LOCATION_ONLY:
494 if (!locationMatch(&pMod->locationOnly.loc, basket->pLoc))
497 case MK_EXCEPTION_ONLY:
498 if (pMod->exceptionOnly.refTypeId != 0 &&
499 !dvmDbgMatchType(basket->excepClassId,
500 pMod->exceptionOnly.refTypeId))
502 if ((basket->caught && !pMod->exceptionOnly.caught) ||
503 (!basket->caught && !pMod->exceptionOnly.uncaught))
507 if (!dvmDbgMatchType(basket->classId, pMod->fieldOnly.refTypeId) ||
508 pMod->fieldOnly.fieldId != basket->field)
512 if (pMod->step.threadId != basket->threadId)
515 case MK_INSTANCE_ONLY:
516 if (pMod->instanceOnly.objectId != basket->thisPtr)
520 LOGE("unhandled mod kind %d", pMod->modKind);
530 * Find all events of type "eventKind" with mods that match up with the
531 * rest of the arguments.
533 * Found events are appended to "matchList", and "*pMatchCount" is advanced,
534 * so this may be called multiple times for grouped events.
536 * DO NOT call this multiple times for the same eventKind, as Count mods are
537 * decremented during the scan.
539 static void findMatchingEvents(JdwpState* state, JdwpEventKind eventKind,
540 ModBasket* basket, JdwpEvent** matchList, int* pMatchCount)
542 /* start after the existing entries */
543 matchList += *pMatchCount;
545 JdwpEvent* pEvent = state->eventList;
546 while (pEvent != NULL) {
547 if (pEvent->eventKind == eventKind && modsMatch(state, pEvent, basket))
549 *matchList++ = pEvent;
553 pEvent = pEvent->next;
558 * Scan through the list of matches and determine the most severe
561 static JdwpSuspendPolicy scanSuspendPolicy(JdwpEvent** matchList,
564 JdwpSuspendPolicy policy = SP_NONE;
566 while (matchCount--) {
567 if ((*matchList)->suspendPolicy > policy)
568 policy = (*matchList)->suspendPolicy;
576 * Three possibilities:
577 * SP_NONE - do nothing
578 * SP_EVENT_THREAD - suspend ourselves
579 * SP_ALL - suspend everybody except JDWP support thread
581 static void suspendByPolicy(JdwpState* state, JdwpSuspendPolicy suspendPolicy)
583 if (suspendPolicy == SP_NONE)
586 if (suspendPolicy == SP_ALL) {
587 dvmDbgSuspendVM(true);
589 assert(suspendPolicy == SP_EVENT_THREAD);
592 /* this is rare but possible -- see CLASS_PREPARE handling */
593 if (dvmDbgGetThreadSelfId() == state->debugThreadId) {
594 LOGI("NOTE: suspendByPolicy not suspending JDWP thread");
598 DebugInvokeReq* pReq = dvmDbgGetInvokeReq();
605 * The JDWP thread has told us (and possibly all other threads) to
606 * resume. See if it has left anything in our DebugInvokeReq mailbox.
608 if (!pReq->invokeNeeded) {
609 /*LOGD("suspendByPolicy: no invoke needed");*/
613 /* grab this before posting/suspending again */
614 dvmJdwpSetWaitForEventThread(state, dvmDbgGetThreadSelfId());
616 /* leave pReq->invokeNeeded raised so we can check reentrancy */
617 LOGV("invoking method...");
618 dvmDbgExecuteMethod(pReq);
620 pReq->err = ERR_NONE;
622 /* clear this before signaling */
623 pReq->invokeNeeded = false;
625 LOGV("invoke complete, signaling and self-suspending");
626 dvmDbgLockMutex(&pReq->lock);
627 dvmDbgCondSignal(&pReq->cv);
628 dvmDbgUnlockMutex(&pReq->lock);
633 * Determine if there is a method invocation in progress in the current
636 * We look at the "invokeNeeded" flag in the per-thread DebugInvokeReq
637 * state. If set, we're in the process of invoking a method.
639 static bool invokeInProgress(JdwpState* state)
641 DebugInvokeReq* pReq = dvmDbgGetInvokeReq();
642 return pReq->invokeNeeded;
646 * We need the JDWP thread to hold off on doing stuff while we post an
647 * event and then suspend ourselves.
649 * Call this with a threadId of zero if you just want to wait for the
650 * current thread operation to complete.
652 * This could go to sleep waiting for another thread, so it's important
653 * that the thread be marked as VMWAIT before calling here.
655 void dvmJdwpSetWaitForEventThread(JdwpState* state, ObjectId threadId)
659 /* this is held for very brief periods; contention is unlikely */
660 dvmDbgLockMutex(&state->eventThreadLock);
663 * If another thread is already doing stuff, wait for it. This can
664 * go to sleep indefinitely.
666 while (state->eventThreadId != 0) {
667 LOGV("event in progress (0x%llx), 0x%llx sleeping",
668 state->eventThreadId, threadId);
670 dvmDbgCondWait(&state->eventThreadCond, &state->eventThreadLock);
673 if (waited || threadId != 0)
674 LOGV("event token grabbed (0x%llx)", threadId);
676 state->eventThreadId = threadId;
678 dvmDbgUnlockMutex(&state->eventThreadLock);
682 * Clear the threadId and signal anybody waiting.
684 void dvmJdwpClearWaitForEventThread(JdwpState* state)
687 * Grab the mutex. Don't try to go in/out of VMWAIT mode, as this
688 * function is called by dvmSuspendSelf(), and the transition back
689 * to RUNNING would confuse it.
691 dvmDbgLockMutex(&state->eventThreadLock);
693 assert(state->eventThreadId != 0);
694 LOGV("cleared event token (0x%llx)", state->eventThreadId);
696 state->eventThreadId = 0;
698 dvmDbgCondSignal(&state->eventThreadCond);
700 dvmDbgUnlockMutex(&state->eventThreadLock);
705 * Prep an event. Allocates storage for the message and leaves space for
708 static ExpandBuf* eventPrep()
710 ExpandBuf* pReq = expandBufAlloc();
711 expandBufAddSpace(pReq, kJDWPHeaderLen);
717 * Write the header into the buffer and send the packet off to the debugger.
719 * Takes ownership of "pReq" (currently discards it).
721 static void eventFinish(JdwpState* state, ExpandBuf* pReq)
723 u1* buf = expandBufGetBuffer(pReq);
725 set4BE(buf, expandBufGetLength(pReq));
726 set4BE(buf+4, dvmJdwpNextRequestSerial(state));
727 set1(buf+8, 0); /* flags */
728 set1(buf+9, kJdwpEventCommandSet);
729 set1(buf+10, kJdwpCompositeCommand);
731 dvmJdwpSendRequest(state, pReq);
738 * Tell the debugger that we have finished initializing. This is always
739 * sent, even if the debugger hasn't requested it.
741 * This should be sent "before the main thread is started and before
742 * any application code has been executed". The thread ID in the message
743 * must be for the main thread.
745 bool dvmJdwpPostVMStart(JdwpState* state, bool suspend)
747 JdwpSuspendPolicy suspendPolicy;
748 ObjectId threadId = dvmDbgGetThreadSelfId();
751 suspendPolicy = SP_ALL;
753 suspendPolicy = SP_NONE;
755 /* probably don't need this here */
756 lockEventMutex(state);
758 ExpandBuf* pReq = NULL;
760 LOGV("EVENT: %s", dvmJdwpEventKindStr(EK_VM_START));
761 LOGV(" suspendPolicy=%s", dvmJdwpSuspendPolicyStr(suspendPolicy));
764 expandBufAdd1(pReq, suspendPolicy);
765 expandBufAdd4BE(pReq, 1);
767 expandBufAdd1(pReq, EK_VM_START);
768 expandBufAdd4BE(pReq, 0); /* requestId */
769 expandBufAdd8BE(pReq, threadId);
772 unlockEventMutex(state);
774 /* send request and possibly suspend ourselves */
776 int oldStatus = dvmDbgThreadWaiting();
777 if (suspendPolicy != SP_NONE)
778 dvmJdwpSetWaitForEventThread(state, threadId);
780 eventFinish(state, pReq);
782 suspendByPolicy(state, suspendPolicy);
783 dvmDbgThreadContinuing(oldStatus);
790 * A location of interest has been reached. This handles:
795 * These four types must be grouped together in a single response. The
796 * "eventFlags" indicates the type of event(s) that have happened.
799 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, InstanceOnly
800 * LocationOnly (for breakpoint/step only)
801 * Step (for step only)
803 * Interesting test cases:
804 * - Put a breakpoint on a native method. Eclipse creates METHOD_ENTRY
805 * and METHOD_EXIT events with a ClassOnly mod on the method's class.
806 * - Use "run to line". Eclipse creates a BREAKPOINT with Count=1.
807 * - Single-step to a line with a breakpoint. Should get a single
808 * event message with both events in it.
810 bool dvmJdwpPostLocationEvent(JdwpState* state, const JdwpLocation* pLoc,
811 ObjectId thisPtr, int eventFlags)
813 JdwpSuspendPolicy suspendPolicy = SP_NONE;
815 char* nameAlloc = NULL;
817 memset(&basket, 0, sizeof(basket));
819 basket.classId = pLoc->classId;
820 basket.thisPtr = thisPtr;
821 basket.threadId = dvmDbgGetThreadSelfId();
822 basket.className = nameAlloc =
823 dvmDescriptorToName(dvmDbgGetClassDescriptor(pLoc->classId));
826 * On rare occasions we may need to execute interpreted code in the VM
827 * while handling a request from the debugger. Don't fire breakpoints
828 * while doing so. (I don't think we currently do this at all, so
829 * this is mostly paranoia.)
831 if (basket.threadId == state->debugThreadId) {
832 LOGV("Ignoring location event in JDWP thread");
838 * The debugger variable display tab may invoke the interpreter to format
839 * complex objects. We want to ignore breakpoints and method entry/exit
840 * traps while working on behalf of the debugger.
842 * If we don't ignore them, the VM will get hung up, because we'll
843 * suspend on a breakpoint while the debugger is still waiting for its
844 * method invocation to complete.
846 if (invokeInProgress(state)) {
847 LOGV("Not checking breakpoints during invoke (%s)", basket.className);
852 /* don't allow the list to be updated while we scan it */
853 lockEventMutex(state);
855 JdwpEvent** matchList = allocMatchList(state);
858 if ((eventFlags & DBG_BREAKPOINT) != 0)
859 findMatchingEvents(state, EK_BREAKPOINT, &basket, matchList,
861 if ((eventFlags & DBG_SINGLE_STEP) != 0)
862 findMatchingEvents(state, EK_SINGLE_STEP, &basket, matchList,
864 if ((eventFlags & DBG_METHOD_ENTRY) != 0)
865 findMatchingEvents(state, EK_METHOD_ENTRY, &basket, matchList,
867 if ((eventFlags & DBG_METHOD_EXIT) != 0)
868 findMatchingEvents(state, EK_METHOD_EXIT, &basket, matchList,
871 ExpandBuf* pReq = NULL;
872 if (matchCount != 0) {
873 LOGV("EVENT: %s(%d total) %s.%s thread=%llx code=%llx)",
874 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
876 dvmDbgGetMethodName(pLoc->classId, pLoc->methodId),
877 basket.threadId, pLoc->idx);
879 suspendPolicy = scanSuspendPolicy(matchList, matchCount);
880 LOGV(" suspendPolicy=%s",
881 dvmJdwpSuspendPolicyStr(suspendPolicy));
884 expandBufAdd1(pReq, suspendPolicy);
885 expandBufAdd4BE(pReq, matchCount);
887 for (int i = 0; i < matchCount; i++) {
888 expandBufAdd1(pReq, matchList[i]->eventKind);
889 expandBufAdd4BE(pReq, matchList[i]->requestId);
890 expandBufAdd8BE(pReq, basket.threadId);
891 dvmJdwpAddLocation(pReq, pLoc);
895 cleanupMatchList(state, matchList, matchCount);
896 unlockEventMutex(state);
898 /* send request and possibly suspend ourselves */
900 int oldStatus = dvmDbgThreadWaiting();
901 if (suspendPolicy != SP_NONE)
902 dvmJdwpSetWaitForEventThread(state, basket.threadId);
904 eventFinish(state, pReq);
906 suspendByPolicy(state, suspendPolicy);
907 dvmDbgThreadContinuing(oldStatus);
911 return matchCount != 0;
915 * A thread is starting or stopping.
920 bool dvmJdwpPostThreadChange(JdwpState* state, ObjectId threadId, bool start)
922 JdwpSuspendPolicy suspendPolicy = SP_NONE;
924 assert(threadId == dvmDbgGetThreadSelfId());
927 * I don't think this can happen.
929 if (invokeInProgress(state)) {
930 LOGW("Not posting thread change during invoke");
935 memset(&basket, 0, sizeof(basket));
936 basket.threadId = threadId;
938 /* don't allow the list to be updated while we scan it */
939 lockEventMutex(state);
941 JdwpEvent** matchList = allocMatchList(state);
945 findMatchingEvents(state, EK_THREAD_START, &basket, matchList,
948 findMatchingEvents(state, EK_THREAD_DEATH, &basket, matchList,
951 ExpandBuf* pReq = NULL;
952 if (matchCount != 0) {
953 LOGV("EVENT: %s(%d total) thread=%llx)",
954 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
957 suspendPolicy = scanSuspendPolicy(matchList, matchCount);
958 LOGV(" suspendPolicy=%s",
959 dvmJdwpSuspendPolicyStr(suspendPolicy));
962 expandBufAdd1(pReq, suspendPolicy);
963 expandBufAdd4BE(pReq, matchCount);
965 for (int i = 0; i < matchCount; i++) {
966 expandBufAdd1(pReq, matchList[i]->eventKind);
967 expandBufAdd4BE(pReq, matchList[i]->requestId);
968 expandBufAdd8BE(pReq, basket.threadId);
973 cleanupMatchList(state, matchList, matchCount);
974 unlockEventMutex(state);
976 /* send request and possibly suspend ourselves */
978 int oldStatus = dvmDbgThreadWaiting();
979 if (suspendPolicy != SP_NONE)
980 dvmJdwpSetWaitForEventThread(state, basket.threadId);
982 eventFinish(state, pReq);
984 suspendByPolicy(state, suspendPolicy);
985 dvmDbgThreadContinuing(oldStatus);
988 return matchCount != 0;
992 * Send a polite "VM is dying" message to the debugger.
994 * Skips the usual "event token" stuff.
996 bool dvmJdwpPostVMDeath(JdwpState* state)
998 LOGV("EVENT: %s", dvmJdwpEventKindStr(EK_VM_DEATH));
1000 ExpandBuf* pReq = eventPrep();
1001 expandBufAdd1(pReq, SP_NONE);
1002 expandBufAdd4BE(pReq, 1);
1004 expandBufAdd1(pReq, EK_VM_DEATH);
1005 expandBufAdd4BE(pReq, 0);
1006 eventFinish(state, pReq);
1012 * An exception has been thrown. It may or may not have been caught.
1015 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, LocationOnly,
1016 * ExceptionOnly, InstanceOnly
1018 * The "exceptionId" has not been added to the GC-visible object registry,
1019 * because there's a pretty good chance that we're not going to send it
1022 bool dvmJdwpPostException(JdwpState* state, const JdwpLocation* pThrowLoc,
1023 ObjectId exceptionId, RefTypeId exceptionClassId,
1024 const JdwpLocation* pCatchLoc, ObjectId thisPtr)
1026 JdwpSuspendPolicy suspendPolicy = SP_NONE;
1028 char* nameAlloc = NULL;
1030 memset(&basket, 0, sizeof(basket));
1031 basket.pLoc = pThrowLoc;
1032 basket.classId = pThrowLoc->classId;
1033 basket.threadId = dvmDbgGetThreadSelfId();
1034 basket.className = nameAlloc =
1035 dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId));
1036 basket.excepClassId = exceptionClassId;
1037 basket.caught = (pCatchLoc->classId != 0);
1038 basket.thisPtr = thisPtr;
1040 /* don't try to post an exception caused by the debugger */
1041 if (invokeInProgress(state)) {
1042 LOGV("Not posting exception hit during invoke (%s)",basket.className);
1047 /* don't allow the list to be updated while we scan it */
1048 lockEventMutex(state);
1050 JdwpEvent** matchList = allocMatchList(state);
1053 findMatchingEvents(state, EK_EXCEPTION, &basket, matchList, &matchCount);
1055 ExpandBuf* pReq = NULL;
1056 if (matchCount != 0) {
1057 LOGV("EVENT: %s(%d total) thread=%llx exceptId=%llx caught=%d)",
1058 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
1059 basket.threadId, exceptionId, basket.caught);
1060 LOGV(" throw: %d %llx %x %lld (%s.%s)", pThrowLoc->typeTag,
1061 pThrowLoc->classId, pThrowLoc->methodId, pThrowLoc->idx,
1062 dvmDbgGetClassDescriptor(pThrowLoc->classId),
1063 dvmDbgGetMethodName(pThrowLoc->classId, pThrowLoc->methodId));
1064 if (pCatchLoc->classId == 0) {
1065 LOGV(" catch: (not caught)");
1067 LOGV(" catch: %d %llx %x %lld (%s.%s)", pCatchLoc->typeTag,
1068 pCatchLoc->classId, pCatchLoc->methodId, pCatchLoc->idx,
1069 dvmDbgGetClassDescriptor(pCatchLoc->classId),
1070 dvmDbgGetMethodName(pCatchLoc->classId, pCatchLoc->methodId));
1073 suspendPolicy = scanSuspendPolicy(matchList, matchCount);
1074 LOGV(" suspendPolicy=%s",
1075 dvmJdwpSuspendPolicyStr(suspendPolicy));
1078 expandBufAdd1(pReq, suspendPolicy);
1079 expandBufAdd4BE(pReq, matchCount);
1081 for (int i = 0; i < matchCount; i++) {
1082 expandBufAdd1(pReq, matchList[i]->eventKind);
1083 expandBufAdd4BE(pReq, matchList[i]->requestId);
1084 expandBufAdd8BE(pReq, basket.threadId);
1086 dvmJdwpAddLocation(pReq, pThrowLoc);
1087 expandBufAdd1(pReq, JT_OBJECT);
1088 expandBufAdd8BE(pReq, exceptionId);
1089 dvmJdwpAddLocation(pReq, pCatchLoc);
1092 /* don't let the GC discard it */
1093 dvmDbgRegisterObjectId(exceptionId);
1096 cleanupMatchList(state, matchList, matchCount);
1097 unlockEventMutex(state);
1099 /* send request and possibly suspend ourselves */
1101 int oldStatus = dvmDbgThreadWaiting();
1102 if (suspendPolicy != SP_NONE)
1103 dvmJdwpSetWaitForEventThread(state, basket.threadId);
1105 eventFinish(state, pReq);
1107 suspendByPolicy(state, suspendPolicy);
1108 dvmDbgThreadContinuing(oldStatus);
1112 return matchCount != 0;
1116 * Announce that a class has been loaded.
1119 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude
1121 bool dvmJdwpPostClassPrepare(JdwpState* state, int tag, RefTypeId refTypeId,
1122 const char* signature, int status)
1124 JdwpSuspendPolicy suspendPolicy = SP_NONE;
1126 char* nameAlloc = NULL;
1128 memset(&basket, 0, sizeof(basket));
1129 basket.classId = refTypeId;
1130 basket.threadId = dvmDbgGetThreadSelfId();
1131 basket.className = nameAlloc =
1132 dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId));
1134 /* suppress class prep caused by debugger */
1135 if (invokeInProgress(state)) {
1136 LOGV("Not posting class prep caused by invoke (%s)",basket.className);
1141 /* don't allow the list to be updated while we scan it */
1142 lockEventMutex(state);
1144 JdwpEvent** matchList = allocMatchList(state);
1147 findMatchingEvents(state, EK_CLASS_PREPARE, &basket, matchList,
1150 ExpandBuf* pReq = NULL;
1151 if (matchCount != 0) {
1152 LOGV("EVENT: %s(%d total) thread=%llx)",
1153 dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
1156 suspendPolicy = scanSuspendPolicy(matchList, matchCount);
1157 LOGV(" suspendPolicy=%s",
1158 dvmJdwpSuspendPolicyStr(suspendPolicy));
1160 if (basket.threadId == state->debugThreadId) {
1162 * JDWP says that, for a class prep in the debugger thread, we
1163 * should set threadId to null and if any threads were supposed
1164 * to be suspended then we suspend all other threads.
1166 LOGV(" NOTE: class prepare in debugger thread!");
1167 basket.threadId = 0;
1168 if (suspendPolicy == SP_EVENT_THREAD)
1169 suspendPolicy = SP_ALL;
1173 expandBufAdd1(pReq, suspendPolicy);
1174 expandBufAdd4BE(pReq, matchCount);
1176 for (int i = 0; i < matchCount; i++) {
1177 expandBufAdd1(pReq, matchList[i]->eventKind);
1178 expandBufAdd4BE(pReq, matchList[i]->requestId);
1179 expandBufAdd8BE(pReq, basket.threadId);
1181 expandBufAdd1(pReq, tag);
1182 expandBufAdd8BE(pReq, refTypeId);
1183 expandBufAddUtf8String(pReq, (const u1*) signature);
1184 expandBufAdd4BE(pReq, status);
1188 cleanupMatchList(state, matchList, matchCount);
1190 unlockEventMutex(state);
1192 /* send request and possibly suspend ourselves */
1194 int oldStatus = dvmDbgThreadWaiting();
1195 if (suspendPolicy != SP_NONE)
1196 dvmJdwpSetWaitForEventThread(state, basket.threadId);
1198 eventFinish(state, pReq);
1200 suspendByPolicy(state, suspendPolicy);
1201 dvmDbgThreadContinuing(oldStatus);
1205 return matchCount != 0;
1212 * Count, ClassMatch, ClassExclude
1214 bool dvmJdwpPostClassUnload(JdwpState* state, RefTypeId refTypeId)
1216 assert(false); // TODO
1221 * Get or set a field.
1224 * Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, FieldOnly,
1227 bool dvmJdwpPostFieldAccess(JdwpState* state, int STUFF, ObjectId thisPtr,
1228 bool modified, JValue newValue)
1230 assert(false); // TODO
1235 * Send up a chunk of DDM data.
1237 * While this takes the form of a JDWP "event", it doesn't interact with
1238 * other debugger traffic, and can't suspend the VM, so we skip all of
1239 * the fun event token gymnastics.
1241 void dvmJdwpDdmSendChunkV(JdwpState* state, int type, const struct iovec* iov,
1244 u1 header[kJDWPHeaderLen + 8];
1247 assert(iov != NULL);
1248 assert(iovcnt > 0 && iovcnt < 10);
1251 * "Wrap" the contents of the iovec with a JDWP/DDMS header. We do
1252 * this by creating a new copy of the vector with space for the header.
1254 struct iovec wrapiov[iovcnt+1];
1255 for (int i = 0; i < iovcnt; i++) {
1256 wrapiov[i+1].iov_base = iov[i].iov_base;
1257 wrapiov[i+1].iov_len = iov[i].iov_len;
1258 dataLen += iov[i].iov_len;
1261 /* form the header (JDWP plus DDMS) */
1262 set4BE(header, sizeof(header) + dataLen);
1263 set4BE(header+4, dvmJdwpNextRequestSerial(state));
1264 set1(header+8, 0); /* flags */
1265 set1(header+9, kJDWPDdmCmdSet);
1266 set1(header+10, kJDWPDdmCmd);
1267 set4BE(header+11, type);
1268 set4BE(header+15, dataLen);
1270 wrapiov[0].iov_base = header;
1271 wrapiov[0].iov_len = sizeof(header);
1274 * Make sure we're in VMWAIT in case the write blocks.
1276 int oldStatus = dvmDbgThreadWaiting();
1277 dvmJdwpSendBufferedRequest(state, wrapiov, iovcnt+1);
1278 dvmDbgThreadContinuing(oldStatus);