Home | History | Annotate | Download | only in jdwp
      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  * The "exceptionId" has not been added to the GC-visible object registry,
   1031  * because there's a pretty good chance that we're not going to send it
   1032  * up the debugger.
   1033  */
   1034 bool dvmJdwpPostException(JdwpState* state, const JdwpLocation* pThrowLoc,
   1035     ObjectId exceptionId, RefTypeId exceptionClassId,
   1036     const JdwpLocation* pCatchLoc, ObjectId thisPtr)
   1037 {
   1038     enum JdwpSuspendPolicy suspendPolicy = SP_NONE;
   1039     ModBasket basket;
   1040     JdwpEvent** matchList;
   1041     int matchCount;
   1042     char* nameAlloc = NULL;
   1043 
   1044     memset(&basket, 0, sizeof(basket));
   1045     basket.pLoc = pThrowLoc;
   1046     basket.classId = pThrowLoc->classId;
   1047     basket.threadId = dvmDbgGetThreadSelfId();
   1048     basket.className = nameAlloc =
   1049         dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId));
   1050     basket.excepClassId = exceptionClassId;
   1051     basket.caught = (pCatchLoc->classId != 0);
   1052     basket.thisPtr = thisPtr;
   1053 
   1054     /* don't try to post an exception caused by the debugger */
   1055     if (invokeInProgress(state)) {
   1056         LOGV("Not posting exception hit during invoke (%s)\n",basket.className);
   1057         free(nameAlloc);
   1058         return false;
   1059     }
   1060 
   1061     /* don't allow the list to be updated while we scan it */
   1062     lockEventMutex(state);
   1063 
   1064     matchList = allocMatchList(state);
   1065     matchCount = 0;
   1066 
   1067     findMatchingEvents(state, EK_EXCEPTION, &basket, matchList, &matchCount);
   1068 
   1069     ExpandBuf* pReq = NULL;
   1070     if (matchCount != 0) {
   1071         int i;
   1072 
   1073         LOGV("EVENT: %s(%d total) thread=%llx exceptId=%llx caught=%d)\n",
   1074             dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
   1075             basket.threadId, exceptionId, basket.caught);
   1076         LOGV("  throw: %d %llx %x %lld (%s.%s)\n", pThrowLoc->typeTag,
   1077             pThrowLoc->classId, pThrowLoc->methodId, pThrowLoc->idx,
   1078             dvmDbgGetClassDescriptor(pThrowLoc->classId),
   1079             dvmDbgGetMethodName(pThrowLoc->classId, pThrowLoc->methodId));
   1080         if (pCatchLoc->classId == 0) {
   1081             LOGV("  catch: (not caught)\n");
   1082         } else {
   1083             LOGV("  catch: %d %llx %x %lld (%s.%s)\n", pCatchLoc->typeTag,
   1084                 pCatchLoc->classId, pCatchLoc->methodId, pCatchLoc->idx,
   1085                 dvmDbgGetClassDescriptor(pCatchLoc->classId),
   1086                 dvmDbgGetMethodName(pCatchLoc->classId, pCatchLoc->methodId));
   1087         }
   1088 
   1089         suspendPolicy = scanSuspendPolicy(matchList, matchCount);
   1090         LOGV("  suspendPolicy=%s\n",
   1091             dvmJdwpSuspendPolicyStr(suspendPolicy));
   1092 
   1093         pReq = eventPrep();
   1094         expandBufAdd1(pReq, suspendPolicy);
   1095         expandBufAdd4BE(pReq, matchCount);
   1096 
   1097         for (i = 0; i < matchCount; i++) {
   1098             expandBufAdd1(pReq, matchList[i]->eventKind);
   1099             expandBufAdd4BE(pReq, matchList[i]->requestId);
   1100             expandBufAdd8BE(pReq, basket.threadId);
   1101 
   1102             dvmJdwpAddLocation(pReq, pThrowLoc);
   1103             expandBufAdd1(pReq, JT_OBJECT);
   1104             expandBufAdd8BE(pReq, exceptionId);
   1105             dvmJdwpAddLocation(pReq, pCatchLoc);
   1106         }
   1107 
   1108         /* don't let the GC discard it */
   1109         dvmDbgRegisterObjectId(exceptionId);
   1110     }
   1111 
   1112     cleanupMatchList(state, matchList, matchCount);
   1113     unlockEventMutex(state);
   1114 
   1115     /* send request and possibly suspend ourselves */
   1116     if (pReq != NULL) {
   1117         int oldStatus = dvmDbgThreadWaiting();
   1118         if (suspendPolicy != SP_NONE)
   1119             dvmJdwpSetWaitForEventThread(state, basket.threadId);
   1120 
   1121         eventFinish(state, pReq);
   1122 
   1123         suspendByPolicy(state, suspendPolicy);
   1124         dvmDbgThreadContinuing(oldStatus);
   1125     }
   1126 
   1127     free(nameAlloc);
   1128     return matchCount != 0;
   1129 }
   1130 
   1131 /*
   1132  * Announce that a class has been loaded.
   1133  *
   1134  * Valid mods:
   1135  *  Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude
   1136  */
   1137 bool dvmJdwpPostClassPrepare(JdwpState* state, int tag, RefTypeId refTypeId,
   1138     const char* signature, int status)
   1139 {
   1140     enum JdwpSuspendPolicy suspendPolicy = SP_NONE;
   1141     ModBasket basket;
   1142     JdwpEvent** matchList;
   1143     int matchCount;
   1144     char* nameAlloc = NULL;
   1145 
   1146     memset(&basket, 0, sizeof(basket));
   1147     basket.classId = refTypeId;
   1148     basket.threadId = dvmDbgGetThreadSelfId();
   1149     basket.className = nameAlloc =
   1150         dvmDescriptorToName(dvmDbgGetClassDescriptor(basket.classId));
   1151 
   1152     /* suppress class prep caused by debugger */
   1153     if (invokeInProgress(state)) {
   1154         LOGV("Not posting class prep caused by invoke (%s)\n",basket.className);
   1155         free(nameAlloc);
   1156         return false;
   1157     }
   1158 
   1159     /* don't allow the list to be updated while we scan it */
   1160     lockEventMutex(state);
   1161 
   1162     matchList = allocMatchList(state);
   1163     matchCount = 0;
   1164 
   1165     findMatchingEvents(state, EK_CLASS_PREPARE, &basket, matchList,
   1166         &matchCount);
   1167 
   1168     ExpandBuf* pReq = NULL;
   1169     if (matchCount != 0) {
   1170         int i;
   1171 
   1172         LOGV("EVENT: %s(%d total) thread=%llx)\n",
   1173             dvmJdwpEventKindStr(matchList[0]->eventKind), matchCount,
   1174             basket.threadId);
   1175 
   1176         suspendPolicy = scanSuspendPolicy(matchList, matchCount);
   1177         LOGV("  suspendPolicy=%s\n",
   1178             dvmJdwpSuspendPolicyStr(suspendPolicy));
   1179 
   1180         if (basket.threadId == state->debugThreadId) {
   1181             /*
   1182              * JDWP says that, for a class prep in the debugger thread, we
   1183              * should set threadId to null and if any threads were supposed
   1184              * to be suspended then we suspend all other threads.
   1185              */
   1186             LOGV("  NOTE: class prepare in debugger thread!\n");
   1187             basket.threadId = 0;
   1188             if (suspendPolicy == SP_EVENT_THREAD)
   1189                 suspendPolicy = SP_ALL;
   1190         }
   1191 
   1192         pReq = eventPrep();
   1193         expandBufAdd1(pReq, suspendPolicy);
   1194         expandBufAdd4BE(pReq, matchCount);
   1195 
   1196         for (i = 0; i < matchCount; i++) {
   1197             expandBufAdd1(pReq, matchList[i]->eventKind);
   1198             expandBufAdd4BE(pReq, matchList[i]->requestId);
   1199             expandBufAdd8BE(pReq, basket.threadId);
   1200 
   1201             expandBufAdd1(pReq, tag);
   1202             expandBufAdd8BE(pReq, refTypeId);
   1203             expandBufAddUtf8String(pReq, (const u1*) signature);
   1204             expandBufAdd4BE(pReq, status);
   1205         }
   1206     }
   1207 
   1208     cleanupMatchList(state, matchList, matchCount);
   1209 
   1210     unlockEventMutex(state);
   1211 
   1212     /* send request and possibly suspend ourselves */
   1213     if (pReq != NULL) {
   1214         int oldStatus = dvmDbgThreadWaiting();
   1215         if (suspendPolicy != SP_NONE)
   1216             dvmJdwpSetWaitForEventThread(state, basket.threadId);
   1217 
   1218         eventFinish(state, pReq);
   1219 
   1220         suspendByPolicy(state, suspendPolicy);
   1221         dvmDbgThreadContinuing(oldStatus);
   1222     }
   1223 
   1224     free(nameAlloc);
   1225     return matchCount != 0;
   1226 }
   1227 
   1228 /*
   1229  * Unload a class.
   1230  *
   1231  * Valid mods:
   1232  *  Count, ClassMatch, ClassExclude
   1233  */
   1234 bool dvmJdwpPostClassUnload(JdwpState* state, RefTypeId refTypeId)
   1235 {
   1236     assert(false);      // TODO
   1237     return false;
   1238 }
   1239 
   1240 /*
   1241  * Get or set a field.
   1242  *
   1243  * Valid mods:
   1244  *  Count, ThreadOnly, ClassOnly, ClassMatch, ClassExclude, FieldOnly,
   1245  *    InstanceOnly
   1246  */
   1247 bool dvmJdwpPostFieldAccess(JdwpState* state, int STUFF, ObjectId thisPtr,
   1248     bool modified)
   1249 {
   1250     assert(false);      // TODO
   1251     return false;
   1252 }
   1253 
   1254 /*
   1255  * Send up a chunk of DDM data.
   1256  *
   1257  * While this takes the form of a JDWP "event", it doesn't interact with
   1258  * other debugger traffic, and can't suspend the VM, so we skip all of
   1259  * the fun event token gymnastics.
   1260  */
   1261 void dvmJdwpDdmSendChunkV(JdwpState* state, int type, const struct iovec* iov,
   1262     int iovcnt)
   1263 {
   1264     u1 header[kJDWPHeaderLen + 8];
   1265     size_t dataLen = 0;
   1266     int i;
   1267 
   1268     assert(iov != NULL);
   1269     assert(iovcnt > 0 && iovcnt < 10);
   1270 
   1271     /*
   1272      * "Wrap" the contents of the iovec with a JDWP/DDMS header.  We do
   1273      * this by creating a new copy of the vector with space for the header.
   1274      */
   1275     struct iovec wrapiov[iovcnt+1];
   1276     for (i = 0; i < iovcnt; i++) {
   1277         wrapiov[i+1].iov_base = iov[i].iov_base;
   1278         wrapiov[i+1].iov_len = iov[i].iov_len;
   1279         dataLen += iov[i].iov_len;
   1280     }
   1281 
   1282     /* form the header (JDWP plus DDMS) */
   1283     set4BE(header, sizeof(header) + dataLen);
   1284     set4BE(header+4, dvmJdwpNextRequestSerial(state));
   1285     set1(header+8, 0);     /* flags */
   1286     set1(header+9, kJDWPDdmCmdSet);
   1287     set1(header+10, kJDWPDdmCmd);
   1288     set4BE(header+11, type);
   1289     set4BE(header+15, dataLen);
   1290 
   1291     wrapiov[0].iov_base = header;
   1292     wrapiov[0].iov_len = sizeof(header);
   1293 
   1294     dvmJdwpSendBufferedRequest(state, wrapiov, iovcnt+1);
   1295 }
   1296 
   1297