OSDN Git Service

am bd79e449: Fix an issue where we\'re adding 4x the intended offset.
[android-x86/dalvik.git] / vm / jdwp / JdwpEvent.c
1 /*
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  * Send events to the debugger.
18  */
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"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stddef.h>     /* for offsetof() */
28 #include <unistd.h>
29
30 /*
31 General notes:
32
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
37 events.
38
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.
42
43
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.
49
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.
56
57 The current mechanism works like this:
58   Event thread:
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.
64   JDWP thread:
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
69      been posted.
70
71 Some care must be taken to avoid deadlock:
72
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
78
79 So we need to mark thread B in such a way that thread A doesn't wait for it.
80
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.
87
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.
92 */
93
94
95 #define kJdwpEventCommandSet    64
96 #define kJdwpCompositeCommand   100
97
98 /*
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.
102  */
103 typedef struct ModBasket {
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 */
113 } ModBasket;
114
115 /*
116  * Get the next "request" serial number.  We use this when sending
117  * packets to the debugger.
118  */
119 u4 dvmJdwpNextRequestSerial(JdwpState* state)
120 {
121     u4 result;
122
123     dvmDbgLockMutex(&state->serialLock);
124     result = state->requestSerial++;
125     dvmDbgUnlockMutex(&state->serialLock);
126
127     return result;
128 }
129
130 /*
131  * Get the next "event" serial number.  We use this in the response to
132  * message type EventRequest.Set.
133  */
134 u4 dvmJdwpNextEventSerial(JdwpState* state)
135 {
136     u4 result;
137
138     dvmDbgLockMutex(&state->serialLock);
139     result = state->eventSerial++;
140     dvmDbgUnlockMutex(&state->serialLock);
141
142     return result;
143 }
144
145 /*
146  * Lock the "event" mutex, which guards the list of registered events.
147  */
148 static void lockEventMutex(JdwpState* state)
149 {
150     //dvmDbgThreadWaiting();
151     dvmDbgLockMutex(&state->eventLock);
152     //dvmDbgThreadRunning();
153 }
154
155 /*
156  * Unlock the "event" mutex.
157  */
158 static void unlockEventMutex(JdwpState* state)
159 {
160     dvmDbgUnlockMutex(&state->eventLock);
161 }
162
163 /*
164  * Add an event to the list.  Ordering is not important.
165  *
166  * If something prevents the event from being registered, e.g. it's a
167  * single-step request on a thread that doesn't exist, the event will
168  * not be added to the list, and an appropriate error will be returned.
169  */
170 JdwpError dvmJdwpRegisterEvent(JdwpState* state, JdwpEvent* pEvent)
171 {
172     JdwpError err = ERR_NONE;
173     int i;
174
175     lockEventMutex(state);
176
177     assert(state != NULL);
178     assert(pEvent != NULL);
179     assert(pEvent->prev == NULL);
180     assert(pEvent->next == NULL);
181
182     /*
183      * If one or more LocationOnly mods are used, register them with
184      * the interpreter.
185      */
186     for (i = 0; i < pEvent->modCount; i++) {
187         JdwpEventMod* pMod = &pEvent->mods[i];
188         if (pMod->modKind == MK_LOCATION_ONLY) {
189             /* should only be for Breakpoint, Step, and Exception */
190             dvmDbgWatchLocation(&pMod->locationOnly.loc);
191         }
192         if (pMod->modKind == MK_STEP) {
193             /* should only be for EK_SINGLE_STEP; should only be one */
194             dvmDbgConfigureStep(pMod->step.threadId, pMod->step.size,
195                 pMod->step.depth);
196         }
197     }
198
199     /*
200      * Add to list.
201      */
202     if (state->eventList != NULL) {
203         pEvent->next = state->eventList;
204         state->eventList->prev = pEvent;
205     }
206     state->eventList = pEvent;
207     state->numEvents++;
208
209 bail:
210     unlockEventMutex(state);
211
212     return err;
213 }
214
215 /*
216  * Remove an event from the list.  This will also remove the event from
217  * any optimization tables, e.g. breakpoints.
218  *
219  * Does not free the JdwpEvent.
220  *
221  * Grab the eventLock before calling here.
222  */
223 static void unregisterEvent(JdwpState* state, JdwpEvent* pEvent)
224 {
225     int i;
226
227     if (pEvent->prev == NULL) {
228         /* head of the list */
229         assert(state->eventList == pEvent);
230
231         state->eventList = pEvent->next;
232     } else {
233         pEvent->prev->next = pEvent->next;
234     }
235
236     if (pEvent->next != NULL) {
237         pEvent->next->prev = pEvent->prev;
238         pEvent->next = NULL;
239     }
240     pEvent->prev = NULL;
241
242     /*
243      * Unhook us from the interpreter, if necessary.
244      */
245     for (i = 0; i < pEvent->modCount; i++) {
246         JdwpEventMod* pMod = &pEvent->mods[i];
247         if (pMod->modKind == MK_LOCATION_ONLY) {
248             /* should only be for Breakpoint, Step, and Exception */
249             dvmDbgUnwatchLocation(&pMod->locationOnly.loc);
250         }
251         if (pMod->modKind == MK_STEP) {
252             /* should only be for EK_SINGLE_STEP; should only be one */
253             dvmDbgUnconfigureStep(pMod->step.threadId);
254         }
255     }
256
257     state->numEvents--;
258     assert(state->numEvents != 0 || state->eventList == NULL);
259 }
260
261 /*
262  * Remove the event with the given ID from the list.
263  *
264  * Failure to find the event isn't really an error, but it is a little
265  * weird.  (It looks like Eclipse will try to be extra careful and will
266  * explicitly remove one-off single-step events.)
267  */
268 void dvmJdwpUnregisterEventById(JdwpState* state, u4 requestId)
269 {
270     JdwpEvent* pEvent;
271
272     lockEventMutex(state);
273
274     pEvent = state->eventList;
275     while (pEvent != NULL) {
276         if (pEvent->requestId == requestId) {
277             unregisterEvent(state, pEvent);
278             dvmJdwpEventFree(pEvent);
279             goto done;      /* there can be only one with a given ID */
280         }
281
282         pEvent = pEvent->next;
283     }
284
285     //LOGD("Odd: no match when removing event reqId=0x%04x\n", requestId);
286
287 done:
288     unlockEventMutex(state);
289 }
290
291 /*
292  * Remove all entries from the event list.
293  */
294 void dvmJdwpUnregisterAll(JdwpState* state)
295 {
296     JdwpEvent* pEvent;
297     JdwpEvent* pNextEvent;
298
299     lockEventMutex(state);
300
301     pEvent = state->eventList;
302     while (pEvent != NULL) {
303         pNextEvent = pEvent->next;
304
305         unregisterEvent(state, pEvent);
306         dvmJdwpEventFree(pEvent);
307         pEvent = pNextEvent;
308     }
309
310     state->eventList = NULL;
311
312     unlockEventMutex(state);
313 }
314
315
316
317 /*
318  * Allocate a JdwpEvent struct with enough space to hold the specified
319  * number of mod records.
320  */
321 JdwpEvent* dvmJdwpEventAlloc(int numMods)
322 {
323     JdwpEvent* newEvent;
324     int allocSize = offsetof(JdwpEvent, mods) +
325                     numMods * sizeof(newEvent->mods[0]);
326
327     newEvent = (JdwpEvent*)malloc(allocSize);
328     memset(newEvent, 0, allocSize);
329     return newEvent;
330 }
331
332 /*
333  * Free a JdwpEvent.
334  *
335  * Do not call this until the event has been removed from the list.
336  */
337 void dvmJdwpEventFree(JdwpEvent* pEvent)
338 {
339     int i;
340
341     if (pEvent == NULL)
342         return;
343
344     /* make sure it was removed from the list */
345     assert(pEvent->prev == NULL);
346     assert(pEvent->next == NULL);
347     /* want to assert state->eventList != pEvent */
348
349     /*
350      * Free any hairy bits in the mods.
351      */
352     for (i = 0; i < pEvent->modCount; i++) {
353         if (pEvent->mods[i].modKind == MK_CLASS_MATCH) {
354             free(pEvent->mods[i].classMatch.classPattern);
355             pEvent->mods[i].classMatch.classPattern = NULL;
356         }
357         if (pEvent->mods[i].modKind == MK_CLASS_EXCLUDE) {
358             free(pEvent->mods[i].classExclude.classPattern);
359             pEvent->mods[i].classExclude.classPattern = NULL;
360         }
361     }
362
363     free(pEvent);
364 }
365
366 /*
367  * Allocate storage for matching events.  To keep things simple we
368  * use an array with enough storage for the entire list.
369  *
370  * The state->eventLock should be held before calling.
371  */
372 static JdwpEvent** allocMatchList(JdwpState* state)
373 {
374     return (JdwpEvent**) malloc(sizeof(JdwpEvent*) * state->numEvents);
375 }
376
377 /*
378  * Run through the list and remove any entries with an expired "count" mod
379  * from the event list, then free the match list.
380  */
381 static void cleanupMatchList(JdwpState* state, JdwpEvent** matchList,
382     int matchCount)
383 {
384     JdwpEvent** ppEvent = matchList;
385
386     while (matchCount--) {
387         JdwpEvent* pEvent = *ppEvent;
388         int i;
389
390         for (i = 0; i < pEvent->modCount; i++) {
391             if (pEvent->mods[i].modKind == MK_COUNT &&
392                 pEvent->mods[i].count.count == 0)
393             {
394                 LOGV("##### Removing expired event\n");
395                 unregisterEvent(state, pEvent);
396                 dvmJdwpEventFree(pEvent);
397                 break;
398             }
399         }
400
401         ppEvent++;
402     }
403
404     free(matchList);
405 }
406
407 /*
408  * Match a string against a "restricted regular expression", which is just
409  * a string that may start or end with '*' (e.g. "*.Foo" or "java.*").
410  *
411  * ("Restricted name globbing" might have been a better term.)
412  */
413 static bool patternMatch(const char* pattern, const char* target)
414 {
415     int patLen = strlen(pattern);
416
417     if (pattern[0] == '*') {
418         int targetLen = strlen(target);
419         patLen--;
420         // TODO: remove printf when we find a test case to verify this
421         LOGE(">>> comparing '%s' to '%s'\n",
422             pattern+1, target + (targetLen-patLen));
423
424         if (targetLen < patLen)
425             return false;
426         return strcmp(pattern+1, target + (targetLen-patLen)) == 0;
427     } else if (pattern[patLen-1] == '*') {
428         int i;
429
430         return strncmp(pattern, target, patLen-1) == 0;
431     } else {
432         return strcmp(pattern, target) == 0;
433     }
434 }
435
436 /*
437  * See if two locations are equal.
438  *
439  * It's tempting to do a bitwise compare ("struct ==" or memcmp), but if
440  * the storage wasn't zeroed out there could be undefined values in the
441  * padding.  Besides, the odds of "idx" being equal while the others aren't
442  * is very small, so this is usually just a simple integer comparison.
443  */
444 static inline bool locationMatch(const JdwpLocation* pLoc1,
445     const JdwpLocation* pLoc2)
446 {
447     return pLoc1->idx == pLoc2->idx &&
448            pLoc1->methodId == pLoc2->methodId &&
449            pLoc1->classId == pLoc2->classId &&
450            pLoc1->typeTag == pLoc2->typeTag;
451 }
452
453 /*
454  * See if the event's mods match up with the contents of "basket".
455  *
456  * If we find a Count mod before rejecting an event, we decrement it.  We
457  * need to do this even if later mods cause us to ignore the event.
458  */
459 static bool modsMatch(JdwpState* state, JdwpEvent* pEvent, ModBasket* basket)
460 {
461     JdwpEventMod* pMod = pEvent->mods;
462     int i;
463
464     for (i = pEvent->modCount; i > 0; i--, pMod++) {
465         switch (pMod->modKind) {
466         case MK_COUNT:
467             assert(pMod->count.count > 0);
468             pMod->count.count--;
469             break;
470         case MK_CONDITIONAL:
471             assert(false);  // should not be getting these
472             break;
473         case MK_THREAD_ONLY:
474             if (pMod->threadOnly.threadId != basket->threadId)
475                 return false;
476             break;
477         case MK_CLASS_ONLY:
478             if (!dvmDbgMatchType(basket->classId,
479                     pMod->classOnly.referenceTypeId))
480                 return false;
481             break;
482         case MK_CLASS_MATCH:
483             if (!patternMatch(pMod->classMatch.classPattern,
484                     basket->className))
485                 return false;
486             break;
487         case MK_CLASS_EXCLUDE:
488             if (patternMatch(pMod->classMatch.classPattern,
489                     basket->className))
490                 return false;
491             break;
492         case MK_LOCATION_ONLY:
493             if (!locationMatch(&pMod->locationOnly.loc, basket->pLoc))
494                 return false;
495             break;
496         case MK_EXCEPTION_ONLY:
497             if (pMod->exceptionOnly.refTypeId != 0 &&
498                 !dvmDbgMatchType(basket->excepClassId,
499                                  pMod->exceptionOnly.refTypeId))
500                 return false;
501             if ((basket->caught && !pMod->exceptionOnly.caught) ||
502                 (!basket->caught && !pMod->exceptionOnly.uncaught))
503                 return false;
504             break;
505         case MK_FIELD_ONLY:
506             // TODO
507             break;
508         case MK_STEP:
509             if (pMod->step.threadId != basket->threadId)
510                 return false;
511             break;
512         case MK_INSTANCE_ONLY:
513             if (pMod->instanceOnly.objectId != basket->thisPtr)
514                 return false;
515             break;
516         default:
517             LOGE("unhandled mod kind %d\n", pMod->modKind);
518             assert(false);
519             break;
520         }
521     }
522
523     return true;
524 }
525
526 /*
527  * Find all events of type "eventKind" with mods that match up with the
528  * rest of the arguments.
529  *
530  * Found events are appended to "matchList", and "*pMatchCount" is advanced,
531  * so this may be called multiple times for grouped events.
532  *
533  * DO NOT call this multiple times for the same eventKind, as Count mods are
534  * decremented during the scan.
535  */
536 static void findMatchingEvents(JdwpState* state, enum JdwpEventKind eventKind,
537     ModBasket* basket, JdwpEvent** matchList, int* pMatchCount)
538 {
539     JdwpEvent* pEvent;
540
541     /* start after the existing entries */
542     matchList += *pMatchCount;
543
544     pEvent = state->eventList;
545     while (pEvent != NULL) {
546         if (pEvent->eventKind == eventKind && modsMatch(state, pEvent, basket))
547         {
548             *matchList++ = pEvent;
549             (*pMatchCount)++;
550         }
551
552         pEvent = pEvent->next;
553     }
554 }
555
556 /*
557  * Scan through the list of matches and determine the most severe
558  * suspension policy.
559  */
560 static enum JdwpSuspendPolicy scanSuspendPolicy(JdwpEvent** matchList,
561     int matchCount)
562 {
563     enum JdwpSuspendPolicy policy = SP_NONE;
564
565     while (matchCount--) {
566         if ((*matchList)->suspendPolicy > policy)
567             policy = (*matchList)->suspendPolicy;
568         matchList++;
569     }
570
571     return policy;
572 }
573
574 /*
575  * Three possibilities:
576  *  SP_NONE - do nothing
577  *  SP_EVENT_THREAD - suspend ourselves
578  *  SP_ALL - suspend everybody except JDWP support thread
579  */
580 static void suspendByPolicy(JdwpState* state,
581     enum JdwpSuspendPolicy suspendPolicy)
582 {
583     if (suspendPolicy == SP_NONE)
584         return;
585
586     if (suspendPolicy == SP_ALL) {
587         dvmDbgSuspendVM(true);
588     } else {
589         assert(suspendPolicy == SP_EVENT_THREAD);
590     }
591
592     /* this is rare but possible -- see CLASS_PREPARE handling */
593     if (dvmDbgGetThreadSelfId() == state->debugThreadId) {
594         LOGI("NOTE: suspendByPolicy not suspending JDWP thread\n");
595         return;
596     }
597
598     DebugInvokeReq* pReq = dvmDbgGetInvokeReq();
599     while (true) {
600         pReq->ready = true;
601         dvmDbgSuspendSelf();
602         pReq->ready = false;
603
604         /*
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.
607          */
608         if (!pReq->invokeNeeded) {
609             /*LOGD("suspendByPolicy: no invoke needed\n");*/
610             break;
611         }
612
613         /* grab this before posting/suspending again */
614         dvmJdwpSetWaitForEventThread(state, dvmDbgGetThreadSelfId());
615
616         /* leave pReq->invokeNeeded raised so we can check reentrancy */
617         LOGV("invoking method...\n");
618         dvmDbgExecuteMethod(pReq);
619
620         pReq->err = ERR_NONE;
621
622         /* clear this before signaling */
623         pReq->invokeNeeded = false;
624
625         LOGV("invoke complete, signaling and self-suspending\n");
626         dvmDbgLockMutex(&pReq->lock);
627         dvmDbgCondSignal(&pReq->cv);
628         dvmDbgUnlockMutex(&pReq->lock);
629     }
630 }
631
632 /*
633  * Determine if there is a method invocation in progress in the current
634  * thread.
635  *
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.
638  */
639 static bool invokeInProgress(JdwpState* state)
640 {
641     DebugInvokeReq* pReq = dvmDbgGetInvokeReq();
642     return pReq->invokeNeeded;
643 }
644
645 /*
646  * We need the JDWP thread to hold off on doing stuff while we post an
647  * event and then suspend ourselves.
648  *
649  * Call this with a threadId of zero if you just want to wait for the
650  * current thread operation to complete.
651  *
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.
654  */
655 void dvmJdwpSetWaitForEventThread(JdwpState* state, ObjectId threadId)
656 {
657     bool waited = false;
658
659     /* this is held for very brief periods; contention is unlikely */
660     dvmDbgLockMutex(&state->eventThreadLock);
661
662     /*
663      * If another thread is already doing stuff, wait for it.  This can
664      * go to sleep indefinitely.
665      */
666     while (state->eventThreadId != 0) {
667         LOGV("event in progress (0x%llx), 0x%llx sleeping\n",
668             state->eventThreadId, threadId);
669         waited = true;
670         dvmDbgCondWait(&state->eventThreadCond, &state->eventThreadLock);
671     }
672
673     if (waited || threadId != 0)
674         LOGV("event token grabbed (0x%llx)\n", threadId);
675     if (threadId != 0)
676         state->eventThreadId = threadId;
677
678     dvmDbgUnlockMutex(&state->eventThreadLock);
679 }
680
681 /*
682  * Clear the threadId and signal anybody waiting.
683  */
684 void dvmJdwpClearWaitForEventThread(JdwpState* state)
685 {
686     /*
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.
690      */
691     dvmDbgLockMutex(&state->eventThreadLock);
692
693     assert(state->eventThreadId != 0);
694     LOGV("cleared event token (0x%llx)\n", state->eventThreadId);
695
696     state->eventThreadId = 0;
697
698     dvmDbgCondSignal(&state->eventThreadCond);
699
700     dvmDbgUnlockMutex(&state->eventThreadLock);
701 }
702
703
704 /*
705  * Prep an event.  Allocates storage for the message and leaves space for
706  * the header.
707  */
708 static ExpandBuf* eventPrep(void)
709 {
710     ExpandBuf* pReq;
711
712     pReq = expandBufAlloc();
713     expandBufAddSpace(pReq, kJDWPHeaderLen);
714
715     return pReq;
716 }
717
718 /*
719  * Write the header into the buffer and send the packet off to the debugger.
720  *
721  * Takes ownership of "pReq" (currently discards it).
722  */
723 static void eventFinish(JdwpState* state, ExpandBuf* pReq)
724 {
725     u1* buf = expandBufGetBuffer(pReq);
726
727     set4BE(buf, expandBufGetLength(pReq));
728     set4BE(buf+4, dvmJdwpNextRequestSerial(state));
729     set1(buf+8, 0);     /* flags */
730     set1(buf+9, kJdwpEventCommandSet);
731     set1(buf+10, kJdwpCompositeCommand);
732
733     dvmJdwpSendRequest(state, pReq);
734
735     expandBufFree(pReq);
736 }
737
738
739 /*
740  * Tell the debugger that we have finished initializing.  This is always
741  * sent, even if the debugger hasn't requested it.
742  *
743  * This should be sent "before the main thread is started and before
744  * any application code has been executed".  The thread ID in the message
745  * must be for the main thread.
746  */
747 bool dvmJdwpPostVMStart(JdwpState* state, bool suspend)
748 {
749     enum JdwpSuspendPolicy suspendPolicy;
750     ObjectId threadId = dvmDbgGetThreadSelfId();
751     
752     if (suspend)
753         suspendPolicy = SP_ALL;
754     else
755         suspendPolicy = SP_NONE;
756
757     /* probably don't need this here */
758     lockEventMutex(state);
759
760     ExpandBuf* pReq = NULL;
761     if (true) {
762         LOGV("EVENT: %s\n", dvmJdwpEventKindStr(EK_VM_START));
763         LOGV("  suspendPolicy=%s\n", dvmJdwpSuspendPolicyStr(suspendPolicy));
764
765         pReq = eventPrep();
766         expandBufAdd1(pReq, suspendPolicy);
767         expandBufAdd4BE(pReq, 1);
768
769         expandBufAdd1(pReq, EK_VM_START);
770         expandBufAdd4BE(pReq, 0);       /* requestId */
771         expandBufAdd8BE(pReq, threadId);
772     }
773
774     unlockEventMutex(state);
775
776     /* send request and possibly suspend ourselves */
777     if (pReq != NULL) {
778         int oldStatus = dvmDbgThreadWaiting();
779         if (suspendPolicy != SP_NONE)
780             dvmJdwpSetWaitForEventThread(state, threadId);
781
782         eventFinish(state, pReq);
783
784         suspendByPolicy(state, suspendPolicy);
785         dvmDbgThreadContinuing(oldStatus);
786     }
787
788     return true;
789 }
790
791 /*
792  * A location of interest has been reached.  This handles:
793  *   Breakpoint
794  *   SingleStep
795  *   MethodEntry
796  *   MethodExit
797  * These four types must be grouped together in a single response.  The
798  * "eventFlags" indicates the type of event(s) that have happened.
799  *
800  * Valid mods:
801  *   Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, InstanceOnly
802  *   LocationOnly (for breakpoint/step only)
803  *   Step (for step only)
804  *
805  * Interesting test cases:
806  *  - Put a breakpoint on a native method.  Eclipse creates METHOD_ENTRY
807  *    and METHOD_EXIT events with a ClassOnly mod on the method's class.
808  *  - Use "run to line".  Eclipse creates a BREAKPOINT with Count=1.
809  *  - Single-step to a line with a breakpoint.  Should get a single
810  *    event message with both events in it.
811  */
812 bool dvmJdwpPostLocationEvent(JdwpState* state, const JdwpLocation* pLoc,
813     ObjectId thisPtr, int eventFlags)
814 {
815     enum JdwpSuspendPolicy suspendPolicy = SP_NONE;
816     ModBasket basket;
817     JdwpEvent** matchList;
818     int matchCount;
819     char* nameAlloc = NULL;
820
821     memset(&basket, 0, sizeof(basket));
822     basket.pLoc = pLoc;
823     basket.classId = pLoc->classId;
824     basket.thisPtr = thisPtr;
825     basket.threadId = dvmDbgGetThreadSelfId();
826     basket.className = nameAlloc =
827         dvmDescriptorToName(dvmDbgGetClassDescriptor(pLoc->classId));
828
829     /*
830      * On rare occasions we may need to execute interpreted code in the VM
831      * while handling a request from the debugger.  Don't fire breakpoints
832      * while doing so.  (I don't think we currently do this at all, so
833      * this is mostly paranoia.)
834      */
835     if (basket.threadId == state->debugThreadId) {
836         LOGV("Ignoring location event in JDWP thread\n");
837         free(nameAlloc);
838         return false;
839     }
840
841     /*
842      * The debugger variable display tab may invoke the interpreter to format
843      * complex objects.  We want to ignore breakpoints and method entry/exit
844      * traps while working on behalf of the debugger.
845      *
846      * If we don't ignore them, the VM will get hung up, because we'll
847      * suspend on a breakpoint while the debugger is still waiting for its
848      * method invocation to complete.
849      */
850     if (invokeInProgress(state)) {
851         LOGV("Not checking breakpoints during invoke (%s)\n", basket.className);
852         free(nameAlloc);
853         return false;
854     }
855
856     /* don't allow the list to be updated while we scan it */
857     lockEventMutex(state);
858
859     matchList = allocMatchList(state);
860     matchCount = 0;
861
862     if ((eventFlags & DBG_BREAKPOINT) != 0)
863         findMatchingEvents(state, EK_BREAKPOINT, &basket, matchList,
864             &matchCount);
865     if ((eventFlags & DBG_SINGLE_STEP) != 0)
866         findMatchingEvents(state, EK_SINGLE_STEP, &basket, matchList,
867             &matchCount);
868     if ((eventFlags & DBG_METHOD_ENTRY) != 0)
869         findMatchingEvents(state, EK_METHOD_ENTRY, &basket, matchList,
870             &matchCount);
871     if ((eventFlags & DBG_METHOD_EXIT) != 0)
872         findMatchingEvents(state, EK_METHOD_EXIT, &basket, matchList,
873             &matchCount);
874
875     ExpandBuf* pReq = NULL;
876     if (matchCount != 0) {
877         int i;
878
879         LOGV("EVENT: %s(%d total) %s.%s thread=%llx code=%llx)\n",
880             dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
881             basket.className,
882             dvmDbgGetMethodName(pLoc->classId, pLoc->methodId),
883             basket.threadId, pLoc->idx);
884
885         suspendPolicy = scanSuspendPolicy(matchList, matchCount);
886         LOGV("  suspendPolicy=%s\n",
887             dvmJdwpSuspendPolicyStr(suspendPolicy));
888
889         pReq = eventPrep();
890         expandBufAdd1(pReq, suspendPolicy);
891         expandBufAdd4BE(pReq, matchCount);
892
893         for (i = 0; i < matchCount; i++) {
894             expandBufAdd1(pReq, matchList[i]->eventKind);
895             expandBufAdd4BE(pReq, matchList[i]->requestId);
896             expandBufAdd8BE(pReq, basket.threadId);
897             dvmJdwpAddLocation(pReq, pLoc);
898         }
899     }
900
901     cleanupMatchList(state, matchList, matchCount);
902     unlockEventMutex(state);
903
904     /* send request and possibly suspend ourselves */
905     if (pReq != NULL) {
906         int oldStatus = dvmDbgThreadWaiting();
907         if (suspendPolicy != SP_NONE)
908             dvmJdwpSetWaitForEventThread(state, basket.threadId);
909
910         eventFinish(state, pReq);
911
912         suspendByPolicy(state, suspendPolicy);
913         dvmDbgThreadContinuing(oldStatus);
914     }
915
916     free(nameAlloc);
917     return matchCount != 0;
918 }
919
920 /*
921  * A thread is starting or stopping.
922  *
923  * Valid mods:
924  *  Count, ThreadOnly
925  */
926 bool dvmJdwpPostThreadChange(JdwpState* state, ObjectId threadId, bool start)
927 {
928     enum JdwpSuspendPolicy suspendPolicy = SP_NONE;
929     ModBasket basket;
930     JdwpEvent** matchList;
931     int matchCount;
932
933     assert(threadId = dvmDbgGetThreadSelfId());
934
935     /*
936      * I don't think this can happen.
937      */
938     if (invokeInProgress(state)) {
939         LOGW("Not posting thread change during invoke\n");
940         return false;
941     }
942
943     memset(&basket, 0, sizeof(basket));
944     basket.threadId = threadId;
945
946     /* don't allow the list to be updated while we scan it */
947     lockEventMutex(state);
948
949     matchList = allocMatchList(state);
950     matchCount = 0;
951
952     if (start)
953         findMatchingEvents(state, EK_THREAD_START, &basket, matchList,
954             &matchCount);
955     else
956         findMatchingEvents(state, EK_THREAD_DEATH, &basket, matchList,
957             &matchCount);
958
959     ExpandBuf* pReq = NULL;
960     if (matchCount != 0) {
961         int i;
962
963         LOGV("EVENT: %s(%d total) thread=%llx)\n",
964             dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
965             basket.threadId);
966
967         suspendPolicy = scanSuspendPolicy(matchList, matchCount);
968         LOGV("  suspendPolicy=%s\n",
969             dvmJdwpSuspendPolicyStr(suspendPolicy));
970
971         pReq = eventPrep();
972         expandBufAdd1(pReq, suspendPolicy);
973         expandBufAdd4BE(pReq, matchCount);
974
975         for (i = 0; i < matchCount; i++) {
976             expandBufAdd1(pReq, matchList[i]->eventKind);
977             expandBufAdd4BE(pReq, matchList[i]->requestId);
978             expandBufAdd8BE(pReq, basket.threadId);
979         }
980
981     }
982
983     cleanupMatchList(state, matchList, matchCount);
984     unlockEventMutex(state);
985
986     /* send request and possibly suspend ourselves */
987     if (pReq != NULL) {
988         int oldStatus = dvmDbgThreadWaiting();
989         if (suspendPolicy != SP_NONE)
990             dvmJdwpSetWaitForEventThread(state, basket.threadId);
991
992         eventFinish(state, pReq);
993
994         suspendByPolicy(state, suspendPolicy);
995         dvmDbgThreadContinuing(oldStatus);
996     }
997
998     return matchCount != 0;
999 }
1000
1001 /*
1002  * Send a polite "VM is dying" message to the debugger.
1003  *
1004  * Skips the usual "event token" stuff.
1005  */
1006 bool dvmJdwpPostVMDeath(JdwpState* state)
1007 {
1008     ExpandBuf* pReq;
1009
1010     LOGV("EVENT: %s\n", dvmJdwpEventKindStr(EK_VM_DEATH));
1011
1012     pReq = eventPrep();
1013     expandBufAdd1(pReq, SP_NONE);
1014     expandBufAdd4BE(pReq, 1);
1015
1016     expandBufAdd1(pReq, EK_VM_DEATH);
1017     expandBufAdd4BE(pReq, 0);
1018     eventFinish(state, pReq);
1019     return true;
1020 }
1021
1022
1023 /*
1024  * An exception has been thrown.  It may or may not have been caught.
1025  *
1026  * Valid mods:
1027  *  Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, LocationOnly,
1028  *    ExceptionOnly, InstanceOnly
1029  */
1030 bool dvmJdwpPostException(JdwpState* state, const JdwpLocation* pThrowLoc,
1031     ObjectId exceptionId, RefTypeId exceptionClassId,
1032     const JdwpLocation* pCatchLoc, ObjectId thisPtr)
1033 {
1034     enum JdwpSuspendPolicy suspendPolicy = SP_NONE;
1035     ModBasket basket;
1036     JdwpEvent** matchList;
1037     int matchCount;
1038     char* nameAlloc = NULL;
1039
1040     memset(&basket, 0, sizeof(basket));
1041     basket.pLoc = pThrowLoc;
1042     basket.classId = pThrowLoc->classId;
1043     basket.threadId = dvmDbgGetThreadSelfId();
1044     basket.className = nameAlloc =
1045         dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId));
1046     basket.excepClassId = exceptionClassId;
1047     basket.caught = (pCatchLoc->classId != 0);
1048     basket.thisPtr = thisPtr;
1049
1050     /* don't try to post an exception caused by the debugger */
1051     if (invokeInProgress(state)) {
1052         LOGV("Not posting exception hit during invoke (%s)\n",basket.className);
1053         free(nameAlloc);
1054         return false;
1055     }
1056
1057     /* don't allow the list to be updated while we scan it */
1058     lockEventMutex(state);
1059
1060     matchList = allocMatchList(state);
1061     matchCount = 0;
1062
1063     findMatchingEvents(state, EK_EXCEPTION, &basket, matchList, &matchCount);
1064
1065     ExpandBuf* pReq = NULL;
1066     if (matchCount != 0) {
1067         int i;
1068
1069         LOGV("EVENT: %s(%d total) thread=%llx exceptId=%llx caught=%d)\n",
1070             dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
1071             basket.threadId, exceptionId, basket.caught);
1072         LOGV("  throw: %d %llx %x %lld (%s.%s)\n", pThrowLoc->typeTag,
1073             pThrowLoc->classId, pThrowLoc->methodId, pThrowLoc->idx,
1074             dvmDbgGetClassDescriptor(pThrowLoc->classId),
1075             dvmDbgGetMethodName(pThrowLoc->classId, pThrowLoc->methodId));
1076         if (pCatchLoc->classId == 0) {
1077             LOGV("  catch: (not caught)\n");
1078         } else {
1079             LOGV("  catch: %d %llx %x %lld (%s.%s)\n", pCatchLoc->typeTag,
1080                 pCatchLoc->classId, pCatchLoc->methodId, pCatchLoc->idx,
1081                 dvmDbgGetClassDescriptor(pCatchLoc->classId),
1082                 dvmDbgGetMethodName(pCatchLoc->classId, pCatchLoc->methodId));
1083         }
1084
1085         suspendPolicy = scanSuspendPolicy(matchList, matchCount);
1086         LOGV("  suspendPolicy=%s\n",
1087             dvmJdwpSuspendPolicyStr(suspendPolicy));
1088
1089         pReq = eventPrep();
1090         expandBufAdd1(pReq, suspendPolicy);
1091         expandBufAdd4BE(pReq, matchCount);
1092
1093         for (i = 0; i < matchCount; i++) {
1094             expandBufAdd1(pReq, matchList[i]->eventKind);
1095             expandBufAdd4BE(pReq, matchList[i]->requestId);
1096             expandBufAdd8BE(pReq, basket.threadId);
1097
1098             dvmJdwpAddLocation(pReq, pThrowLoc);
1099             expandBufAdd1(pReq, JT_OBJECT);
1100             expandBufAdd8BE(pReq, exceptionId);
1101             dvmJdwpAddLocation(pReq, pCatchLoc);
1102         }
1103     }
1104
1105     cleanupMatchList(state, matchList, matchCount);
1106     unlockEventMutex(state);
1107
1108     /* send request and possibly suspend ourselves */
1109     if (pReq != NULL) {
1110         int oldStatus = dvmDbgThreadWaiting();
1111         if (suspendPolicy != SP_NONE)
1112             dvmJdwpSetWaitForEventThread(state, basket.threadId);
1113
1114         eventFinish(state, pReq);
1115
1116         suspendByPolicy(state, suspendPolicy);
1117         dvmDbgThreadContinuing(oldStatus);
1118     }
1119
1120     free(nameAlloc);
1121     return matchCount != 0;
1122 }
1123
1124 /*
1125  * Announce that a class has been loaded.
1126  *
1127  * Valid mods:
1128  *  Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude
1129  */
1130 bool dvmJdwpPostClassPrepare(JdwpState* state, int tag, RefTypeId refTypeId,
1131     const char* signature, int status)
1132 {
1133     enum JdwpSuspendPolicy suspendPolicy = SP_NONE;
1134     ModBasket basket;
1135     JdwpEvent** matchList;
1136     int matchCount;
1137     char* nameAlloc = NULL;
1138
1139     memset(&basket, 0, sizeof(basket));
1140     basket.classId = refTypeId;
1141     basket.threadId = dvmDbgGetThreadSelfId();
1142     basket.className = nameAlloc =
1143         dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId));
1144
1145     /* suppress class prep caused by debugger */
1146     if (invokeInProgress(state)) {
1147         LOGV("Not posting class prep caused by invoke (%s)\n",basket.className);
1148         free(nameAlloc);
1149         return false;
1150     }
1151
1152     /* don't allow the list to be updated while we scan it */
1153     lockEventMutex(state);
1154
1155     matchList = allocMatchList(state);
1156     matchCount = 0;
1157
1158     findMatchingEvents(state, EK_CLASS_PREPARE, &basket, matchList,
1159         &matchCount);
1160
1161     ExpandBuf* pReq = NULL;
1162     if (matchCount != 0) {
1163         int i;
1164
1165         LOGV("EVENT: %s(%d total) thread=%llx)\n",
1166             dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
1167             basket.threadId);
1168
1169         suspendPolicy = scanSuspendPolicy(matchList, matchCount);
1170         LOGV("  suspendPolicy=%s\n",
1171             dvmJdwpSuspendPolicyStr(suspendPolicy));
1172
1173         if (basket.threadId == state->debugThreadId) {
1174             /*
1175              * JDWP says that, for a class prep in the debugger thread, we
1176              * should set threadId to null and if any threads were supposed
1177              * to be suspended then we suspend all other threads.
1178              */
1179             LOGV("  NOTE: class prepare in debugger thread!\n");
1180             basket.threadId = 0;
1181             if (suspendPolicy == SP_EVENT_THREAD)
1182                 suspendPolicy = SP_ALL;
1183         }
1184
1185         pReq = eventPrep();
1186         expandBufAdd1(pReq, suspendPolicy);
1187         expandBufAdd4BE(pReq, matchCount);
1188
1189         for (i = 0; i < matchCount; i++) {
1190             expandBufAdd1(pReq, matchList[i]->eventKind);
1191             expandBufAdd4BE(pReq, matchList[i]->requestId);
1192             expandBufAdd8BE(pReq, basket.threadId);
1193
1194             expandBufAdd1(pReq, tag);
1195             expandBufAdd8BE(pReq, refTypeId);
1196             expandBufAddUtf8String(pReq, (const u1*) signature);
1197             expandBufAdd4BE(pReq, status);
1198         }
1199     }
1200
1201     cleanupMatchList(state, matchList, matchCount);
1202
1203     unlockEventMutex(state);
1204
1205     /* send request and possibly suspend ourselves */
1206     if (pReq != NULL) {
1207         int oldStatus = dvmDbgThreadWaiting();
1208         if (suspendPolicy != SP_NONE)
1209             dvmJdwpSetWaitForEventThread(state, basket.threadId);
1210
1211         eventFinish(state, pReq);
1212
1213         suspendByPolicy(state, suspendPolicy);
1214         dvmDbgThreadContinuing(oldStatus);
1215     }
1216
1217     free(nameAlloc);
1218     return matchCount != 0;
1219 }
1220
1221 /*
1222  * Unload a class.
1223  *
1224  * Valid mods:
1225  *  Count, ClassMatch, ClassExclude
1226  */
1227 bool dvmJdwpPostClassUnload(JdwpState* state, RefTypeId refTypeId)
1228 {
1229     assert(false);      // TODO
1230     return false;
1231 }
1232
1233 /*
1234  * Get or set a field.
1235  *
1236  * Valid mods:
1237  *  Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, FieldOnly,
1238  *    InstanceOnly
1239  */
1240 bool dvmJdwpPostFieldAccess(JdwpState* state, int STUFF, ObjectId thisPtr,
1241     bool modified)
1242 {
1243     assert(false);      // TODO
1244     return false;
1245 }
1246
1247 /*
1248  * Send up a chunk of DDM data.
1249  *
1250  * While this takes the form of a JDWP "event", it doesn't interact with
1251  * other debugger traffic, and can't suspend the VM, so we skip all of
1252  * the fun event token gymnastics.
1253  */
1254 void dvmJdwpDdmSendChunk(JdwpState* state, int type, int len, const u1* buf)
1255 {
1256     ExpandBuf* pReq;
1257     u1* outBuf;
1258
1259     /*
1260      * Write the chunk header and data into the ExpandBuf.
1261      */
1262     pReq = expandBufAlloc();
1263     expandBufAddSpace(pReq, kJDWPHeaderLen);
1264     expandBufAdd4BE(pReq, type);
1265     expandBufAdd4BE(pReq, len);
1266     if (len > 0) {
1267         outBuf = expandBufAddSpace(pReq, len);
1268         memcpy(outBuf, buf, len);
1269     }
1270
1271     /*
1272      * Go back and write the JDWP header.
1273      */
1274     outBuf = expandBufGetBuffer(pReq);
1275
1276     set4BE(outBuf, expandBufGetLength(pReq));
1277     set4BE(outBuf+4, dvmJdwpNextRequestSerial(state));
1278     set1(outBuf+8, 0);     /* flags */
1279     set1(outBuf+9, kJDWPDdmCmdSet);
1280     set1(outBuf+10, kJDWPDdmCmd);
1281
1282     /*
1283      * Send it up.
1284      */
1285     //LOGD("Sending chunk (type=0x%08x len=%d)\n", type, len);
1286     dvmJdwpSendRequest(state, pReq);
1287
1288     expandBufFree(pReq);
1289 }
1290