1 /*
   2  * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 /*
  26  * eventHandler
  27  *
  28  * This module handles events as they come in directly from JVMTI
  29  * and also maps them to JDI events.  JDI events are those requested
  30  * at the JDI or JDWP level and seen on those levels.  Mapping is
  31  * one-to-many, a JVMTI event may map to several JDI events, or
  32  * to none.  Part of that mapping process is filteration, which
  33  * eventFilter sub-module handles.  A JDI EventRequest corresponds
  34  * to a HandlerNode and a JDI filter to the hidden HandlerNode data
  35  * used by eventFilter.  For example, if at the JDI level the user
  36  * executed:
  37  *
  38  *   EventRequestManager erm = vm.eventRequestManager();
  39  *   BreakpointRequest bp = erm.createBreakpointRequest();
  40  *   bp.enable();
  41  *   ClassPrepareRequest req = erm.createClassPrepareRequest();
  42  *   req.enable();
  43  *   req = erm.createClassPrepareRequest();
  44  *   req.addClassFilter("Foo*");
  45  *   req.enable();
  46  *
  47  * Three handlers would be created, the first with a LocationOnly
  48  * filter and the last with a ClassMatch  filter.
  49  * When a JVMTI class prepare event for "Foobar"
  50  * comes in, the second handler will create one JDI event, the
  51  * third handler will compare the class signature, and since
  52  * it matchs create a second event.  There may also be internal
  53  * events as there are in this case, one created by the front-end
  54  * and one by the back-end.
  55  *
  56  * Each event kind has a handler chain, which is a doublely linked
  57  * list of handlers for that kind of event.
  58  */
  59 #include "util.h"
  60 #include "eventHandler.h"
  61 #include "eventHandlerRestricted.h"
  62 #include "eventFilter.h"
  63 #include "eventFilterRestricted.h"
  64 #include "standardHandlers.h"
  65 #include "threadControl.h"
  66 #include "eventHelper.h"
  67 #include "classTrack.h"
  68 #include "commonRef.h"
  69 #include "debugLoop.h"
  70 
  71 static HandlerID requestIdCounter;
  72 static jbyte currentSessionID;
  73 
  74 /* Counter of active callbacks and flag for vm_death */
  75 static int      active_callbacks   = 0;
  76 static jboolean vm_death_callback_active = JNI_FALSE;
  77 static jrawMonitorID callbackLock;
  78 static jrawMonitorID callbackBlock;
  79 
  80 /* Macros to surround callback code (non-VM_DEATH callbacks).
  81  *   Note that this just keeps a count of the non-VM_DEATH callbacks that
  82  *   are currently active, it does not prevent these callbacks from
  83  *   operating in parallel. It's the VM_DEATH callback that will wait
  84  *   for all these callbacks to finish up, so that it can report the
  85  *   VM_DEATH in a clean state.
  86  *   If the VM_DEATH callback is active in the BEGIN macro then this
  87  *   callback just blocks until released by the VM_DEATH callback.
  88  *   If the VM_DEATH callback is active in the END macro, then this
  89  *   callback will notify the VM_DEATH callback if it's the last one,
  90  *   and then block until released by the VM_DEATH callback.
  91  *   Why block? These threads are often the threads of the Java program,
  92  *   not blocking might mean that a return would continue execution of
  93  *   some java thread in the middle of VM_DEATH, this seems troubled.
  94  *
  95  *   WARNING: No not 'return' or 'goto' out of the BEGIN_CALLBACK/END_CALLBACK
  96  *            block, this will mess up the count.
  97  */
  98 
  99 #define BEGIN_CALLBACK()                                                \
 100 { /* BEGIN OF CALLBACK */                                               \
 101     jboolean bypass = JNI_TRUE;                                         \
 102     debugMonitorEnter(callbackLock); {                                  \
 103         if (vm_death_callback_active) {                                 \
 104             /* allow VM_DEATH callback to finish */                     \
 105             debugMonitorExit(callbackLock);                             \
 106             /* Now block because VM is about to die */                  \
 107             debugMonitorEnter(callbackBlock);                           \
 108             debugMonitorExit(callbackBlock);                            \
 109         } else {                                                        \
 110             active_callbacks++;                                         \
 111             bypass = JNI_FALSE;                                         \
 112             debugMonitorExit(callbackLock);                             \
 113         }                                                               \
 114     }                                                                   \
 115     if ( !bypass ) {                                                    \
 116         /* BODY OF CALLBACK CODE */
 117 
 118 #define END_CALLBACK() /* Part of bypass if body */                     \
 119         debugMonitorEnter(callbackLock); {                              \
 120             active_callbacks--;                                         \
 121             if (active_callbacks < 0) {                                 \
 122                 EXIT_ERROR(0, "Problems tracking active callbacks");    \
 123             }                                                           \
 124             if (vm_death_callback_active) {                             \
 125                 if (active_callbacks == 0) {                            \
 126                     debugMonitorNotifyAll(callbackLock);                \
 127                 }                                                       \
 128                 /* allow VM_DEATH callback to finish */                 \
 129                 debugMonitorExit(callbackLock);                         \
 130                 /* Now block because VM is about to die */              \
 131                 debugMonitorEnter(callbackBlock);                       \
 132                 debugMonitorExit(callbackBlock);                        \
 133             } else {                                                    \
 134                 debugMonitorExit(callbackLock);                         \
 135             }                                                           \
 136         }                                                               \
 137     }                                                                   \
 138 } /* END OF CALLBACK */
 139 
 140 /*
 141  * We are starting with a very simple locking scheme
 142  * for event handling.  All readers and writers of data in
 143  * the handlers[] chain must own this lock for the duration
 144  * of its use. If contention becomes a problem, we can:
 145  *
 146  * 1) create a lock per event type.
 147  * 2) move to a readers/writers approach where multiple threads
 148  * can access the chains simultaneously while reading (the
 149  * normal activity of an event callback).
 150  */
 151 static jrawMonitorID handlerLock;
 152 
 153 typedef struct HandlerChain_ {
 154     HandlerNode *first;
 155     /* add lock here */
 156 } HandlerChain;
 157 
 158 /*
 159  * This array maps event kinds to handler chains.
 160  * Protected by handlerLock.
 161  */
 162 
 163 static HandlerChain __handlers[EI_max-EI_min+1];
 164 
 165 /* Given a HandlerNode, these access our private data.
 166  */
 167 #define PRIVATE_DATA(node) \
 168        (&(((EventHandlerRestricted_HandlerNode*)(void*)(node))->private_ehpd))
 169 
 170 #define NEXT(node) (PRIVATE_DATA(node)->private_next)
 171 #define PREV(node) (PRIVATE_DATA(node)->private_prev)
 172 #define CHAIN(node) (PRIVATE_DATA(node)->private_chain)
 173 #define HANDLER_FUNCTION(node) (PRIVATE_DATA(node)->private_handlerFunction)
 174 
 175 static jclass getObjectClass(jobject object);
 176 static jvmtiError freeHandler(HandlerNode *node);
 177 
 178 static jvmtiError freeHandlerChain(HandlerChain *chain);
 179 
 180 static HandlerChain *
 181 getHandlerChain(EventIndex i)
 182 {
 183     if ( i < EI_min || i > EI_max ) {
 184         EXIT_ERROR(AGENT_ERROR_INVALID_EVENT_TYPE,"bad index for handler");
 185     }
 186     return &(__handlers[i-EI_min]);
 187 }
 188 
 189 static void
 190 insert(HandlerChain *chain, HandlerNode *node)
 191 {
 192     HandlerNode *oldHead = chain->first;
 193     NEXT(node) = oldHead;
 194     PREV(node) = NULL;
 195     CHAIN(node) = chain;
 196     if (oldHead != NULL) {
 197         PREV(oldHead) = node;
 198     }
 199     chain->first = node;
 200 }
 201 
 202 static HandlerNode *
 203 findInChain(HandlerChain *chain, HandlerID handlerID)
 204 {
 205     HandlerNode *node = chain->first;
 206     while (node != NULL) {
 207         if (node->handlerID == handlerID) {
 208             return node;
 209         }
 210         node = NEXT(node);
 211     }
 212     return NULL;
 213 }
 214 
 215 static HandlerNode *
 216 find(EventIndex ei, HandlerID handlerID)
 217 {
 218     return findInChain(getHandlerChain(ei), handlerID);
 219 }
 220 
 221 /**
 222  * Deinsert.  Safe for non-inserted nodes.
 223  */
 224 static void
 225 deinsert(HandlerNode *node)
 226 {
 227     HandlerChain *chain = CHAIN(node);
 228 
 229     if (chain == NULL) {
 230         return;
 231     }
 232     if (chain->first == node) {
 233         chain->first = NEXT(node);
 234     }
 235     if (NEXT(node) != NULL) {
 236         PREV(NEXT(node)) = PREV(node);
 237     }
 238     if (PREV(node) != NULL) {
 239         NEXT(PREV(node)) = NEXT(node);
 240     }
 241     CHAIN(node) = NULL;
 242 }
 243 
 244 jboolean
 245 eventHandlerRestricted_iterator(EventIndex ei,
 246                               IteratorFunction func, void *arg)
 247 {
 248     HandlerChain *chain;
 249     HandlerNode *node;
 250     JNIEnv *env;
 251 
 252     chain = getHandlerChain(ei);
 253     node = chain->first;
 254     env = getEnv();
 255 
 256     if ( func == NULL ) {
 257         EXIT_ERROR(AGENT_ERROR_INTERNAL,"iterator function NULL");
 258     }
 259 
 260     while (node != NULL) {
 261         if (((func)(env, node, arg))) {
 262             return JNI_TRUE;
 263         }
 264         node = NEXT(node);
 265     }
 266     return JNI_FALSE;
 267 }
 268 
 269 /* BREAKPOINT, METHOD_ENTRY and SINGLE_STEP events are covered by
 270  * the co-location of events policy. Of these three co-located
 271  * events, METHOD_ENTRY is always reported first and BREAKPOINT
 272  * is always reported last. Here are the possible combinations and
 273  * their order:
 274  *
 275  * (p1) METHOD_ENTRY, BREAKPOINT (existing)
 276  * (p2) METHOD_ENTRY, BREAKPOINT (new)
 277  * (p1) METHOD_ENTRY, SINGLE_STEP
 278  * (p1) METHOD_ENTRY, SINGLE_STEP, BREAKPOINT (existing)
 279  * (p1/p2) METHOD_ENTRY, SINGLE_STEP, BREAKPOINT (new)
 280  * (p1) SINGLE_STEP, BREAKPOINT (existing)
 281  * (p2) SINGLE_STEP, BREAKPOINT (new)
 282  *
 283  * BREAKPOINT (existing) indicates a BREAKPOINT that is set before
 284  * the other co-located event is posted. BREAKPOINT (new) indicates
 285  * a BREAKPOINT that is set after the other co-located event is
 286  * posted and before the thread has resumed execution.
 287  *
 288  * Co-location of events policy used to be implemented via
 289  * temporary BREAKPOINTs along with deferring the reporting of
 290  * non-BREAKPOINT co-located events, but the temporary BREAKPOINTs
 291  * caused performance problems on VMs where setting or clearing
 292  * BREAKPOINTs is expensive, e.g., HotSpot.
 293  *
 294  * The policy is now implemented in two phases. Phase 1: when a
 295  * METHOD_ENTRY or SINGLE_STEP event is received, if there is an
 296  * existing co-located BREAKPOINT, then the current event is
 297  * deferred. When the BREAKPOINT event is processed, the event
 298  * bag will contain the deferred METHOD_ENTRY and/or SINGLE_STEP
 299  * events along with the BREAKPOINT event. For a METHOD_ENTRY
 300  * event where there is not an existing co-located BREAKPOINT,
 301  * if SINGLE_STEP events are also enabled for the thread, then
 302  * the METHOD_ENTRY event is deferred. When the SINGLE_STEP event
 303  * is processed, the event bag will also contain the deferred
 304  * METHOD_ENTRY event. This covers each of the combinations
 305  * marked with 'p1' above.
 306  *
 307  * Phase 2: if there is no existing co-located BREAKPOINT, then the
 308  * location information for the METHOD_ENTRY or SINGLE_STEP event
 309  * is recorded in the ThreadNode. If the next event for the thread
 310  * is a co-located BREAKPOINT, then the first BREAKPOINT event will
 311  * be skipped since it cannot be delivered in the same event set.
 312  * This covers each of the combinations marked with 'p2' above.
 313  *
 314  * For the combination marked p1/p2, part of the case is handled
 315  * during phase 1 and the rest is handled during phase 2.
 316  *
 317  * The recording of information in the ThreadNode is handled in
 318  * this routine. The special handling of the next event for the
 319  * thread is handled in skipEventReport().
 320  */
 321 
 322 static jboolean
 323 deferEventReport(JNIEnv *env, jthread thread,
 324             EventIndex ei, jclass clazz, jmethodID method, jlocation location)
 325 {
 326     jboolean deferring = JNI_FALSE;
 327 
 328     switch (ei) {
 329         case EI_METHOD_ENTRY:
 330             if (!isMethodNative(method)) {
 331                 jvmtiError error;
 332                 jlocation start;
 333                 jlocation end;
 334                 error = methodLocation(method, &start, &end);
 335                 if (error == JVMTI_ERROR_NONE) {
 336                     deferring = isBreakpointSet(clazz, method, start) ||
 337                                 threadControl_getInstructionStepMode(thread)
 338                                     == JVMTI_ENABLE;
 339                     if (!deferring) {
 340                         threadControl_saveCLEInfo(env, thread, ei,
 341                                                   clazz, method, start);
 342                     }
 343                 }
 344             }
 345             break;
 346         case EI_SINGLE_STEP:
 347             deferring = isBreakpointSet(clazz, method, location);
 348             if (!deferring) {
 349                 threadControl_saveCLEInfo(env, thread, ei,
 350                                           clazz, method, location);
 351             }
 352             break;
 353         default:
 354             break;
 355     }
 356     /* TO DO: Once JVMTI supports a way to know if we're
 357      * at the end of a method, we should check here for
 358      * break and step events which precede a method exit
 359      * event.
 360      */
 361     return deferring;
 362 }
 363 
 364 /* Handle phase 2 of the co-located events policy. See detailed
 365  * comments in deferEventReport() above.
 366  */
 367 static jboolean
 368 skipEventReport(JNIEnv *env, jthread thread, EventIndex ei,
 369                         jclass clazz, jmethodID method, jlocation location)
 370 {
 371     jboolean skipping = JNI_FALSE;
 372 
 373     if (ei == EI_BREAKPOINT) {
 374         if (threadControl_cmpCLEInfo(env, thread, clazz, method, location)) {
 375             LOG_MISC(("Co-located breakpoint event found: "
 376                 "%s,thread=%p,clazz=%p,method=%p,location=%d",
 377                 eventText(ei), thread, clazz, method, location));
 378             skipping = JNI_TRUE;
 379         }
 380     }
 381 
 382     threadControl_clearCLEInfo(env, thread);
 383 
 384     return skipping;
 385 }
 386 
 387 static void
 388 reportEvents(JNIEnv *env, jbyte sessionID, jthread thread, EventIndex ei,
 389              jclass clazz, jmethodID method, jlocation location,
 390              struct bag *eventBag)
 391 {
 392     jbyte suspendPolicy;
 393     jboolean invoking;
 394 
 395     if (bagSize(eventBag) < 1) {
 396         return;
 397     }
 398 
 399     /*
 400      * Never report events before initialization completes
 401      */
 402     if (!debugInit_isInitComplete()) {
 403         return;
 404     }
 405 
 406     /*
 407      * Check to see if we should skip reporting this event due to
 408      * co-location of events policy.
 409      */
 410     if (thread != NULL &&
 411            skipEventReport(env, thread, ei, clazz, method, location)) {
 412         LOG_MISC(("event report being skipped: "
 413             "ei=%s,thread=%p,clazz=%p,method=%p,location=%d",
 414             eventText(ei), thread, clazz, method, location));
 415         bagDeleteAll(eventBag);
 416         return;
 417     }
 418 
 419     /* We delay the reporting of some events so that they can be
 420      * properly grouped into event sets with upcoming events. If
 421      * the reporting is to be deferred, the event commands remain
 422      * in the event bag until a subsequent event occurs.  Event is
 423      * NULL for synthetic events (e.g. unload).
 424      */
 425     if (thread == NULL
 426          || !deferEventReport(env, thread, ei,
 427                         clazz, method, location)) {
 428         struct bag *completedBag = bagDup(eventBag);
 429         bagDeleteAll(eventBag);
 430         if (completedBag == NULL) {
 431             /*
 432              * TO DO: Report, but don't terminate?
 433              */
 434             return;
 435         } else {
 436             suspendPolicy = eventHelper_reportEvents(sessionID, completedBag);
 437             if (thread != NULL && suspendPolicy != JDWP_SUSPEND_POLICY(NONE)) {
 438                 do {
 439                     /* The events have been reported and this
 440                      * thread is about to continue, but it may
 441                      * have been started up just to perform a
 442                      * requested method invocation. If so, we do
 443                      * the invoke now and then stop again waiting
 444                      * for another continue. By then another
 445                      * invoke request can be in place, so there is
 446                      * a loop around this code.
 447                      */
 448                     invoking = invoker_doInvoke(thread);
 449                     if (invoking) {
 450                         eventHelper_reportInvokeDone(sessionID, thread);
 451                     }
 452                 } while (invoking);
 453             }
 454             bagDestroyBag(completedBag);
 455         }
 456     }
 457 }
 458 
 459 /* A bagEnumerateFunction.  Create a synthetic class unload event
 460  * for every class no longer present.  Analogous to event_callback
 461  * combined with a handler in a unload specific (no event
 462  * structure) kind of way.
 463  */
 464 static jboolean
 465 synthesizeUnloadEvent(void *signatureVoid, void *envVoid)
 466 {
 467     JNIEnv *env = (JNIEnv *)envVoid;
 468     char *signature = *(char **)signatureVoid;
 469     char *classname;
 470     HandlerNode *node;
 471     jbyte eventSessionID = currentSessionID;
 472     struct bag *eventBag = eventHelper_createEventBag();
 473 
 474     /* TO DO: Report null error, but don't die */
 475     JDI_ASSERT(eventBag != NULL);
 476 
 477     /* Signature needs to last, so convert extra copy to
 478      * classname
 479      */
 480     classname = jvmtiAllocate((int)strlen(signature)+1);
 481     (void)strcpy(classname, signature);
 482     convertSignatureToClassname(classname);
 483 
 484     debugMonitorEnter(handlerLock);
 485 
 486     node = getHandlerChain(EI_GC_FINISH)->first;
 487     while (node != NULL) {
 488         /* save next so handlers can remove themselves */
 489         HandlerNode *next = NEXT(node);
 490         jboolean shouldDelete;
 491 
 492         if (eventFilterRestricted_passesUnloadFilter(env, classname,
 493                                                      node,
 494                                                      &shouldDelete)) {
 495             /* There may be multiple handlers, the signature will
 496              * be freed when the event helper thread has written
 497              * it.  So each event needs a separate allocation.
 498              */
 499             char *durableSignature = jvmtiAllocate((int)strlen(signature)+1);
 500             (void)strcpy(durableSignature, signature);
 501 
 502             eventHelper_recordClassUnload(node->handlerID,
 503                                           durableSignature,
 504                                           eventBag);
 505         }
 506         if (shouldDelete) {
 507             /* We can safely free the node now that we are done
 508              * using it.
 509              */
 510             (void)freeHandler(node);
 511         }
 512         node = next;
 513     }
 514 
 515     debugMonitorExit(handlerLock);
 516 
 517     if (eventBag != NULL) {
 518         reportEvents(env, eventSessionID, (jthread)NULL, 0,
 519                             (jclass)NULL, (jmethodID)NULL, 0, eventBag);
 520 
 521         /*
 522          * bag was created locally, destroy it here.
 523          */
 524         bagDestroyBag(eventBag);
 525     }
 526 
 527     jvmtiDeallocate(signature);
 528     jvmtiDeallocate(classname);
 529 
 530     return JNI_TRUE;
 531 }
 532 
 533 /* Garbage Collection Happened */
 534 static unsigned int garbageCollected = 0;
 535 
 536 /*
 537  * Run the event through each HandlerNode's filter, and if it passes, call the HandlerNode's
 538  * HandlerFunction for the event, and then report all accumulated events to the debugger.
 539  */
 540 static void
 541 filterAndHandleEvent(JNIEnv *env, EventInfo *evinfo, EventIndex ei,
 542                      struct bag *eventBag, jbyte eventSessionID)
 543 {
 544     debugMonitorEnter(handlerLock);
 545     {
 546         HandlerNode *node;
 547         char        *classname;
 548 
 549         /* We must keep track of all classes prepared to know what's unloaded */
 550         if (evinfo->ei == EI_CLASS_PREPARE) {
 551             classTrack_addPreparedClass(env, evinfo->clazz);
 552         }
 553 
 554         node = getHandlerChain(ei)->first;
 555         classname = getClassname(evinfo->clazz);
 556 
 557         /* Filter the event over each handler node. */
 558         while (node != NULL) {
 559             /* Save next so handlers can remove themselves. */
 560             HandlerNode *next = NEXT(node);
 561             jboolean shouldDelete;
 562 
 563             /* passesFilter() will set evinfo->matchesFiber true if appropriate. */
 564             if (eventFilterRestricted_passesFilter(env, classname,
 565                                                    evinfo, node,
 566                                                    &shouldDelete, JNI_FALSE /* filterOnly */)) {
 567                 HandlerFunction func = HANDLER_FUNCTION(node);
 568                 if (func == NULL) {
 569                     EXIT_ERROR(AGENT_ERROR_INTERNAL,"handler function NULL");
 570                 }
 571                 /* Handle the event by calling the event handler. */
 572                 (*func)(env, evinfo, node, eventBag);
 573             }
 574             if (shouldDelete) {
 575                 /* We can safely free the node now that we are done using it. */
 576                 (void)freeHandler(node);
 577             }
 578             node = next;
 579         }
 580         jvmtiDeallocate(classname);
 581     }
 582     debugMonitorExit(handlerLock);
 583 
 584     /*
 585      * The events destined for the debugger were accumulated in eventBag. Report all these events.
 586      */
 587     if (eventBag != NULL) {
 588         reportEvents(env, eventSessionID, evinfo->thread, evinfo->ei,
 589                      evinfo->clazz, evinfo->method, evinfo->location, eventBag);
 590     }
 591 }
 592 
 593 /*
 594  * Called when we are not notifying the debugging of all fibers, and we are seeing an event
 595  * on a fiber that we have not notified the debugger about yet. If the event passes the event
 596  * filters, then we will notify the debugger with a THREAD_START and add it to our list of
 597  * fibers. Otherwise we ignore it.
 598  */
 599 static void
 600 filterAndAddFiber(JNIEnv *env, EventInfo *evinfo, EventIndex ei, jbyte eventSessionID,
 601                   jthread thread, jthread fiber)
 602 {
 603     jboolean needToAddFiber = JNI_FALSE; /* Assume we won't need to add the fiber. */;
 604 
 605     /*
 606      * Although we have received a JVMTI event for a fiber that we have not added yet,
 607      * we only need to add it if we are going to pass the fiber on to the debugger. This
 608      * might not end up happening due to event filtering. For example, we got a breakpoint
 609      * on a carrier thread running a fiber, but the breakpoint HandlerNode specifies that
 610      * event must be on a certain thread, so the event may end up being dropped. Therefore
 611      * we need to do a dry run with the filtering to see if we really need to add this fiber.
 612      */
 613     {
 614         HandlerNode *node = getHandlerChain(ei)->first;
 615         char        *classname  = getClassname(evinfo->clazz);
 616 
 617         debugMonitorEnter(handlerLock);
 618 
 619         /* Filter the event over each handler node. */
 620         while (node != NULL) {
 621             /* Save next so handlers can remove themselves */
 622             HandlerNode *next = NEXT(node);
 623             jboolean shouldDelete;
 624 
 625             /* passesFilter() will set evinfo->matchesFiber true if appropriate. */
 626             if (eventFilterRestricted_passesFilter(env, classname,
 627                                                    evinfo, node,
 628                                                    &shouldDelete, JNI_TRUE /* filterOnly */)) {
 629                 if (evinfo->matchesFiber) {
 630                     /* If we match even one filter and it matches on the fiber, then we need
 631                      * to add the fiber. */
 632                     needToAddFiber = JNI_TRUE;
 633                     break;
 634                 }
 635             }
 636             JDI_ASSERT(!shouldDelete);
 637             node = next;
 638         }
 639 
 640         debugMonitorExit(handlerLock);
 641         jvmtiDeallocate(classname);
 642     }
 643 
 644     if (needToAddFiber) {
 645         /* Make sure this fiber gets added to the fibers list. */
 646         threadControl_addFiber(fiber);
 647 
 648         /*
 649          * When the FIBER_SCHEDULED event arrived for this fiber, we ignored it since we don't
 650          * want to notify the debugger about fibers until there is a non-fiber event that
 651          * arrives on it (like a breakpoint). Now that this has happened, we need to send
 652          * a FIBER_SCHEDULED event (which will be converted into a THREAD_START event) so
 653          * the debugger will know about the fiber. Otherwise it will be unhappy when it gets
 654          * an event for a fiber that it never got a THREAD_START event for.
 655          */
 656         EventInfo info;
 657         struct bag *eventBag = eventHelper_createEventBag();
 658 
 659         JDI_ASSERT(evinfo->fiber != NULL);
 660         (void)memset(&info,0,sizeof(info));
 661         info.ei         = EI_FIBER_SCHEDULED;
 662         info.thread     = thread;
 663         info.fiber      = fiber;
 664         info.matchesFiber = JNI_TRUE;
 665 
 666         /* Note: filterAndHandleEvent() expects EI_THREAD_START instead of EI_FIBER_SCHEDULED. */
 667         filterAndHandleEvent(env, &info, EI_THREAD_START, eventBag, eventSessionID);
 668         JDI_ASSERT(bagSize(eventBag) == 0);
 669         bagDestroyBag(eventBag);
 670     }
 671 }
 672 
 673 /*
 674  * The JVMTI generic event callback. Each event is passed to a sequence of
 675  * handlers in a chain until the chain ends or one handler
 676  * consumes the event.
 677  */
 678 static void
 679 event_callback_helper(JNIEnv *env, EventInfo *evinfo)
 680 {
 681     struct bag *eventBag;
 682     jbyte eventSessionID = currentSessionID; /* session could change */
 683     jthrowable currentException;
 684     jthread thread;
 685     EventIndex ei = evinfo->ei;
 686 
 687     LOG_MISC(("event_callback(): ei=%s", eventText(ei)));
 688     log_debugee_location("event_callback()", evinfo->thread, evinfo->method, evinfo->location);
 689 
 690     if (evinfo->thread != NULL) {
 691         /* fiber fixme: ignore all events on the fiber helper thread. Remove this when
 692          * the need for helper threads goes away.
 693          */
 694         jclass threadClass = JNI_FUNC_PTR(env, GetObjectClass)(env, evinfo->thread);
 695         if (JNI_FUNC_PTR(env, IsSameObject)(env, threadClass, gdata->innocuousThreadClass)) {
 696             return;
 697         }
 698     }
 699 
 700     /* fiber fixme: little hack to ignore THREAD_START events while we are creating a fiber
 701      * helper thread. The need for this will eventually go away. */
 702     if (gdata->ignoreEvents) {
 703         return;
 704     }
 705 
 706     /* We want to preserve any current exception that might get
 707      * wiped out during event handling (e.g. JNI calls). We have
 708      * to rely on space for the local reference on the current
 709      * frame because doing a PushLocalFrame here might itself
 710      * generate an exception.
 711      */
 712     currentException = JNI_FUNC_PTR(env,ExceptionOccurred)(env);
 713     JNI_FUNC_PTR(env,ExceptionClear)(env);
 714 
 715     /* See if a garbage collection finish event happened earlier.
 716      *
 717      * Note: The "if" is an optimization to avoid entering the lock on every
 718      *       event; garbageCollected may be zapped before we enter
 719      *       the lock but then this just becomes one big no-op.
 720      */
 721     if ( garbageCollected > 0 ) {
 722         struct bag *unloadedSignatures = NULL;
 723 
 724         /* We want to compact the hash table of all
 725          * objects sent to the front end by removing objects that have
 726          * been collected.
 727          */
 728         commonRef_compact();
 729 
 730         /* We also need to simulate the class unload events. */
 731 
 732         debugMonitorEnter(handlerLock);
 733 
 734         /* Clear garbage collection counter */
 735         garbageCollected = 0;
 736 
 737         /* Analyze which class unloads occurred */
 738         unloadedSignatures = classTrack_processUnloads(env);
 739 
 740         debugMonitorExit(handlerLock);
 741 
 742         /* Generate the synthetic class unload events and/or just cleanup.  */
 743         if ( unloadedSignatures != NULL ) {
 744             (void)bagEnumerateOver(unloadedSignatures, synthesizeUnloadEvent,
 745                              (void *)env);
 746             bagDestroyBag(unloadedSignatures);
 747         }
 748     }
 749 
 750     thread = evinfo->thread;
 751     if (thread != NULL) {
 752         if (gdata->fibersSupported) {
 753             /*
 754              * Get the event fiber if one is running on this thread and has not already
 755              * been set, which is the case for fiber related JVMTI events.
 756              */
 757             if (evinfo->fiber == NULL) {
 758                 evinfo->fiber = getThreadFiber(thread);
 759             }
 760         }
 761 
 762         /*
 763          * Record the fact that we're entering an event
 764          * handler so that thread operations (status, interrupt,
 765          * stop) can be done correctly and so that thread
 766          * resources can be allocated.  This must be done before
 767          * grabbing any locks.
 768          */
 769         eventBag = threadControl_onEventHandlerEntry(
 770             eventSessionID, evinfo, currentException);
 771         if ( eventBag == NULL ) {
 772             jboolean invoking;
 773             do {
 774                 /* The event has been 'handled' and this
 775                  * thread is about to continue, but it may
 776                  * have been started up just to perform a
 777                  * requested method invocation. If so, we do
 778                  * the invoke now and then stop again waiting
 779                  * for another continue. By then another
 780                  * invoke request can be in place, so there is
 781                  * a loop around this code.
 782                  */
 783                 invoking = invoker_doInvoke(thread);
 784                 if (invoking) {
 785                     eventHelper_reportInvokeDone(eventSessionID, thread);
 786                 }
 787             } while (invoking);
 788             return; /* Do nothing, event was consumed */
 789         }
 790     } else {
 791         eventBag = eventHelper_createEventBag();
 792         if (eventBag == NULL) {
 793             /*
 794              * TO DO: Report, but don't die
 795              */
 796             eventBag = NULL;  /* to shut up lint */
 797         }
 798     }
 799 
 800     /* We want the fiber scheduled/terminated events to mimic thread start/end events */
 801     if (ei == EI_FIBER_SCHEDULED) {
 802         ei = EI_THREAD_START;
 803     }
 804     if (ei == EI_FIBER_TERMINATED) {
 805         ei = EI_THREAD_END;
 806     }
 807 
 808     if (gdata->fibersSupported) {
 809         /* Add the fiber if we haven't added it before. */
 810         if (evinfo->fiber != NULL && !threadControl_isKnownFiber(evinfo->fiber)) {
 811             if (gdata->notifyDebuggerOfAllFibers) {
 812                 /* Make sure this fiber gets added to the fibers list. */
 813                 threadControl_addFiber(evinfo->fiber);
 814             } else {
 815                 /* Add this fiber if it passes the event filters. */
 816                 filterAndAddFiber(env, evinfo, ei, eventSessionID, thread, evinfo->fiber);
 817             }
 818         }
 819     }
 820 
 821     filterAndHandleEvent(env, evinfo, ei, eventBag, eventSessionID);
 822 
 823     /* we are continuing after VMDeathEvent - now we are dead */
 824     if (evinfo->ei == EI_VM_DEATH) {
 825         gdata->vmDead = JNI_TRUE;
 826     }
 827 
 828     /*
 829      * If the bag was created locally, destroy it here.
 830      */
 831     if (thread == NULL) {
 832         bagDestroyBag(eventBag);
 833     }
 834 
 835     /* Always restore any exception that was set beforehand.  If
 836      * there is a pending async exception, StopThread will be
 837      * called from threadControl_onEventHandlerExit immediately
 838      * below.  Depending on VM implementation and state, the async
 839      * exception might immediately overwrite the currentException,
 840      * or it might be delayed until later.  */
 841     if (currentException != NULL) {
 842         JNI_FUNC_PTR(env,Throw)(env, currentException);
 843     } else {
 844         JNI_FUNC_PTR(env,ExceptionClear)(env);
 845     }
 846 
 847     /*
 848      * Release thread resources and perform any delayed operations.
 849      */
 850     if (thread != NULL) {
 851         threadControl_onEventHandlerExit(evinfo->ei, thread, eventBag);
 852     }
 853 }
 854 
 855 static void
 856 event_callback(JNIEnv *env, EventInfo *evinfo)
 857 {
 858     /* fiber fixme: There are a bunch of WITH_LOCAL_REFS that we can remove now that
 859      * we are doing one here. */
 860     WITH_LOCAL_REFS(env, 64) {
 861         event_callback_helper(env, evinfo);
 862     } END_WITH_LOCAL_REFS(env);
 863 }
 864 
 865 /* Returns a local ref to the declaring class for an object. */
 866 static jclass
 867 getObjectClass(jobject object)
 868 {
 869     jclass clazz;
 870     JNIEnv *env = getEnv();
 871 
 872     clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
 873 
 874     return clazz;
 875 }
 876 
 877 /* Returns a local ref to the declaring class for a method, or NULL. */
 878 jclass
 879 getMethodClass(jvmtiEnv *jvmti_env, jmethodID method)
 880 {
 881     jclass clazz = NULL;
 882     jvmtiError error;
 883 
 884     if ( method == NULL ) {
 885         return NULL;
 886     }
 887     error = methodClass(method, &clazz);
 888     if ( error != JVMTI_ERROR_NONE ) {
 889         EXIT_ERROR(error,"Can't get jclass for a methodID, invalid?");
 890         return NULL;
 891     }
 892     return clazz;
 893 }
 894 
 895 /* Event callback for JVMTI_EVENT_SINGLE_STEP */
 896 static void JNICALL
 897 cbSingleStep(jvmtiEnv *jvmti_env, JNIEnv *env,
 898                         jthread thread, jmethodID method, jlocation location)
 899 {
 900     EventInfo info;
 901 
 902     LOG_CB(("cbSingleStep: thread=%p", thread));
 903 
 904     BEGIN_CALLBACK() {
 905         (void)memset(&info,0,sizeof(info));
 906         info.ei         = EI_SINGLE_STEP;
 907         info.thread     = thread;
 908         info.clazz      = getMethodClass(jvmti_env, method);
 909         info.method     = method;
 910         info.location   = location;
 911         event_callback(env, &info);
 912     } END_CALLBACK();
 913 
 914     LOG_MISC(("END cbSingleStep"));
 915 }
 916 
 917 /* Event callback for JVMTI_EVENT_BREAKPOINT */
 918 static void JNICALL
 919 cbBreakpoint(jvmtiEnv *jvmti_env, JNIEnv *env,
 920                         jthread thread, jmethodID method, jlocation location)
 921 {
 922     EventInfo info;
 923 
 924     LOG_CB(("cbBreakpoint: thread=%p", thread));
 925 
 926     BEGIN_CALLBACK() {
 927         (void)memset(&info,0,sizeof(info));
 928         info.ei         = EI_BREAKPOINT;
 929         info.thread     = thread;
 930         info.clazz      = getMethodClass(jvmti_env, method);
 931         info.method     = method;
 932         info.location   = location;
 933         event_callback(env, &info);
 934     } END_CALLBACK();
 935 
 936     LOG_MISC(("END cbBreakpoint"));
 937 }
 938 
 939 /* Event callback for JVMTI_EVENT_FRAME_POP */
 940 static void JNICALL
 941 cbFramePop(jvmtiEnv *jvmti_env, JNIEnv *env,
 942                         jthread thread, jmethodID method,
 943                         jboolean wasPoppedByException)
 944 {
 945     EventInfo info;
 946 
 947     /* JDWP does not return these events when popped due to an exception. */
 948     if ( wasPoppedByException ) {
 949         return;
 950     }
 951 
 952     LOG_CB(("cbFramePop: thread=%p", thread));
 953 
 954     BEGIN_CALLBACK() {
 955         (void)memset(&info,0,sizeof(info));
 956         info.ei         = EI_FRAME_POP;
 957         info.thread     = thread;
 958         info.clazz      = getMethodClass(jvmti_env, method);
 959         info.method     = method;
 960         event_callback(env, &info);
 961     } END_CALLBACK();
 962 
 963     LOG_MISC(("END cbFramePop"));
 964 }
 965 
 966 /* Event callback for JVMTI_EVENT_EXCEPTION */
 967 static void JNICALL
 968 cbException(jvmtiEnv *jvmti_env, JNIEnv *env,
 969                         jthread thread, jmethodID method,
 970                         jlocation location, jobject exception,
 971                         jmethodID catch_method, jlocation catch_location)
 972 {
 973     EventInfo info;
 974 
 975     LOG_CB(("cbException: thread=%p", thread));
 976 
 977     BEGIN_CALLBACK() {
 978         (void)memset(&info,0,sizeof(info));
 979         info.ei                         = EI_EXCEPTION;
 980         info.thread                     = thread;
 981         info.clazz                      = getMethodClass(jvmti_env, method);
 982         info.method                     = method;
 983         info.location                   = location;
 984         info.object                     = exception;
 985         info.u.exception.catch_clazz    = getMethodClass(jvmti_env, catch_method);
 986         info.u.exception.catch_method   = catch_method;
 987         info.u.exception.catch_location = catch_location;
 988         event_callback(env, &info);
 989     } END_CALLBACK();
 990 
 991     LOG_MISC(("END cbException"));
 992 }
 993 
 994 /* Event callback for JVMTI_EVENT_THREAD_START */
 995 static void JNICALL
 996 cbThreadStart(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
 997 {
 998     EventInfo info;
 999 
1000     LOG_CB(("cbThreadStart: thread=%p", thread));
1001 
1002     BEGIN_CALLBACK() {
1003         (void)memset(&info,0,sizeof(info));
1004         info.ei         = EI_THREAD_START;
1005         info.thread     = thread;
1006         event_callback(env, &info);
1007     } END_CALLBACK();
1008 
1009     LOG_MISC(("END cbThreadStart"));
1010 }
1011 
1012 /* Event callback for JVMTI_EVENT_THREAD_END */
1013 static void JNICALL
1014 cbThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
1015 {
1016     EventInfo info;
1017 
1018     LOG_CB(("cbThreadEnd: thread=%p", thread));
1019 
1020     BEGIN_CALLBACK() {
1021         (void)memset(&info,0,sizeof(info));
1022         info.ei         = EI_THREAD_END;
1023         info.thread     = thread;
1024         event_callback(env, &info);
1025     } END_CALLBACK();
1026 
1027     LOG_MISC(("END cbThreadEnd"));
1028 }
1029 
1030 /* Event callback for JVMTI_EVENT_CLASS_PREPARE */
1031 static void JNICALL
1032 cbClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *env,
1033                         jthread thread, jclass klass)
1034 {
1035     EventInfo info;
1036 
1037     LOG_CB(("cbClassPrepare: thread=%p", thread));
1038 
1039     BEGIN_CALLBACK() {
1040         (void)memset(&info,0,sizeof(info));
1041         info.ei         = EI_CLASS_PREPARE;
1042         info.thread     = thread;
1043         info.clazz      = klass;
1044         event_callback(env, &info);
1045     } END_CALLBACK();
1046 
1047     LOG_MISC(("END cbClassPrepare"));
1048 }
1049 
1050 /* Event callback for JVMTI_EVENT_GARBAGE_COLLECTION_FINISH */
1051 static void JNICALL
1052 cbGarbageCollectionFinish(jvmtiEnv *jvmti_env)
1053 {
1054     LOG_CB(("cbGarbageCollectionFinish"));
1055     ++garbageCollected;
1056     LOG_MISC(("END cbGarbageCollectionFinish"));
1057 }
1058 
1059 /* Event callback for JVMTI_EVENT_CLASS_LOAD */
1060 static void JNICALL
1061 cbClassLoad(jvmtiEnv *jvmti_env, JNIEnv *env,
1062                         jthread thread, jclass klass)
1063 {
1064     EventInfo info;
1065 
1066     LOG_CB(("cbClassLoad: thread=%p", thread));
1067 
1068     BEGIN_CALLBACK() {
1069         (void)memset(&info,0,sizeof(info));
1070         info.ei         = EI_CLASS_LOAD;
1071         info.thread     = thread;
1072         info.clazz      = klass;
1073         event_callback(env, &info);
1074     } END_CALLBACK();
1075 
1076     LOG_MISC(("END cbClassLoad"));
1077 }
1078 
1079 /* Event callback for JVMTI_EVENT_FIELD_ACCESS */
1080 static void JNICALL
1081 cbFieldAccess(jvmtiEnv *jvmti_env, JNIEnv *env,
1082                         jthread thread, jmethodID method,
1083                         jlocation location, jclass field_klass,
1084                         jobject object, jfieldID field)
1085 {
1086     EventInfo info;
1087 
1088     LOG_CB(("cbFieldAccess: thread=%p", thread));
1089 
1090     BEGIN_CALLBACK() {
1091         (void)memset(&info,0,sizeof(info));
1092         info.ei                         = EI_FIELD_ACCESS;
1093         info.thread                     = thread;
1094         info.clazz                      = getMethodClass(jvmti_env, method);
1095         info.method                     = method;
1096         info.location                   = location;
1097         info.u.field_access.field_clazz = field_klass;
1098         info.object                     = object;
1099         info.u.field_access.field       = field;
1100         event_callback(env, &info);
1101     } END_CALLBACK();
1102 
1103     LOG_MISC(("END cbFieldAccess"));
1104 }
1105 
1106 /* Event callback for JVMTI_EVENT_FIELD_MODIFICATION */
1107 static void JNICALL
1108 cbFieldModification(jvmtiEnv *jvmti_env, JNIEnv *env,
1109         jthread thread, jmethodID method,
1110         jlocation location, jclass field_klass, jobject object, jfieldID field,
1111         char signature_type, jvalue new_value)
1112 {
1113     EventInfo info;
1114 
1115     LOG_CB(("cbFieldModification: thread=%p", thread));
1116 
1117     BEGIN_CALLBACK() {
1118         (void)memset(&info,0,sizeof(info));
1119         info.ei                                 = EI_FIELD_MODIFICATION;
1120         info.thread                             = thread;
1121         info.clazz                              = getMethodClass(jvmti_env, method);
1122         info.method                             = method;
1123         info.location                           = location;
1124         info.u.field_modification.field         = field;
1125         info.u.field_modification.field_clazz   = field_klass;
1126         info.object                             = object;
1127         info.u.field_modification.signature_type= signature_type;
1128         info.u.field_modification.new_value     = new_value;
1129         event_callback(env, &info);
1130     } END_CALLBACK();
1131 
1132     LOG_MISC(("END cbFieldModification"));
1133 }
1134 
1135 /* Event callback for JVMTI_EVENT_EXCEPTION_CATCH */
1136 static void JNICALL
1137 cbExceptionCatch(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread,
1138         jmethodID method, jlocation location, jobject exception)
1139 {
1140     EventInfo info;
1141 
1142     LOG_CB(("cbExceptionCatch: thread=%p", thread));
1143 
1144     BEGIN_CALLBACK() {
1145         (void)memset(&info,0,sizeof(info));
1146         info.ei         = EI_EXCEPTION_CATCH;
1147         info.thread     = thread;
1148         info.clazz      = getMethodClass(jvmti_env, method);
1149         info.method     = method;
1150         info.location   = location;
1151         info.object     = exception;
1152         event_callback(env, &info);
1153     } END_CALLBACK();
1154 
1155     LOG_MISC(("END cbExceptionCatch"));
1156 }
1157 
1158 /* Event callback for JVMTI_EVENT_METHOD_ENTRY */
1159 static void JNICALL
1160 cbMethodEntry(jvmtiEnv *jvmti_env, JNIEnv *env,
1161                         jthread thread, jmethodID method)
1162 {
1163     EventInfo info;
1164 
1165     LOG_CB(("cbMethodEntry: thread=%p", thread));
1166 
1167     BEGIN_CALLBACK() {
1168         (void)memset(&info,0,sizeof(info));
1169         info.ei         = EI_METHOD_ENTRY;
1170         info.thread     = thread;
1171         info.clazz      = getMethodClass(jvmti_env, method);
1172         info.method     = method;
1173         event_callback(env, &info);
1174     } END_CALLBACK();
1175 
1176     LOG_MISC(("END cbMethodEntry"));
1177 }
1178 
1179 /* Event callback for JVMTI_EVENT_METHOD_EXIT */
1180 static void JNICALL
1181 cbMethodExit(jvmtiEnv *jvmti_env, JNIEnv *env,
1182                         jthread thread, jmethodID method,
1183                         jboolean wasPoppedByException, jvalue return_value)
1184 {
1185     EventInfo info;
1186 
1187     /* JDWP does not return these events when popped due to an exception. */
1188     if ( wasPoppedByException ) {
1189         return;
1190     }
1191 
1192     LOG_CB(("cbMethodExit: thread=%p", thread));
1193 
1194     BEGIN_CALLBACK() {
1195         (void)memset(&info,0,sizeof(info));
1196         info.ei         = EI_METHOD_EXIT;
1197         info.thread     = thread;
1198         info.clazz      = getMethodClass(jvmti_env, method);
1199         info.method     = method;
1200         info.u.method_exit.return_value = return_value;
1201         event_callback(env, &info);
1202     } END_CALLBACK();
1203 
1204     LOG_MISC(("END cbMethodExit"));
1205 }
1206 
1207 /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTER */
1208 static void JNICALL
1209 cbMonitorContendedEnter(jvmtiEnv *jvmti_env, JNIEnv *env,
1210                         jthread thread, jobject object)
1211 {
1212     EventInfo info;
1213     jvmtiError error;
1214     jmethodID  method;
1215     jlocation  location;
1216 
1217     LOG_CB(("cbMonitorContendedEnter: thread=%p", thread));
1218 
1219     BEGIN_CALLBACK() {
1220         (void)memset(&info,0,sizeof(info));
1221         info.ei         = EI_MONITOR_CONTENDED_ENTER;
1222         info.thread     = thread;
1223         info.object     = object;
1224         /* get current location of contended monitor enter */
1225         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1226                 (gdata->jvmti, thread, 0, &method, &location);
1227         if (error == JVMTI_ERROR_NONE) {
1228             info.location = location;
1229             info.method   = method;
1230             info.clazz    = getMethodClass(jvmti_env, method);
1231         } else {
1232             info.location = -1;
1233         }
1234         event_callback(env, &info);
1235     } END_CALLBACK();
1236 
1237     LOG_MISC(("END cbMonitorContendedEnter"));
1238 }
1239 
1240 /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTERED */
1241 static void JNICALL
1242 cbMonitorContendedEntered(jvmtiEnv *jvmti_env, JNIEnv *env,
1243                         jthread thread, jobject object)
1244 {
1245     EventInfo info;
1246     jvmtiError error;
1247     jmethodID  method;
1248     jlocation  location;
1249 
1250     LOG_CB(("cbMonitorContendedEntered: thread=%p", thread));
1251 
1252     BEGIN_CALLBACK() {
1253         (void)memset(&info,0,sizeof(info));
1254         info.ei         = EI_MONITOR_CONTENDED_ENTERED;
1255         info.thread     = thread;
1256         info.object     = object;
1257         /* get current location of contended monitor enter */
1258         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1259                 (gdata->jvmti, thread, 0, &method, &location);
1260         if (error == JVMTI_ERROR_NONE) {
1261             info.location = location;
1262             info.method   = method;
1263             info.clazz    = getMethodClass(jvmti_env, method);
1264         } else {
1265             info.location = -1;
1266         }
1267         event_callback(env, &info);
1268     } END_CALLBACK();
1269 
1270     LOG_MISC(("END cbMonitorContendedEntered"));
1271 }
1272 
1273 /* Event callback for JVMTI_EVENT_MONITOR_WAIT */
1274 static void JNICALL
1275 cbMonitorWait(jvmtiEnv *jvmti_env, JNIEnv *env,
1276                         jthread thread, jobject object,
1277                         jlong timeout)
1278 {
1279     EventInfo info;
1280     jvmtiError error;
1281     jmethodID  method;
1282     jlocation  location;
1283 
1284     LOG_CB(("cbMonitorWait: thread=%p", thread));
1285 
1286     BEGIN_CALLBACK() {
1287         (void)memset(&info,0,sizeof(info));
1288         info.ei         = EI_MONITOR_WAIT;
1289         info.thread     = thread;
1290         info.object     = object;
1291         /* The info.clazz is used for both class filtering and for location info.
1292          * For monitor wait event the class filtering is done for class of monitor
1293          * object. So here info.clazz is set to class of monitor object here and it
1294          * is reset to class of method before writing location info.
1295          * See writeMonitorEvent in eventHelper.c
1296          */
1297         info.clazz      = getObjectClass(object);
1298         info.u.monitor.timeout = timeout;
1299 
1300         /* get location of monitor wait() method. */
1301         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1302                 (gdata->jvmti, thread, 0, &method, &location);
1303         if (error == JVMTI_ERROR_NONE) {
1304             info.location = location;
1305             info.method   = method;
1306         } else {
1307             info.location = -1;
1308         }
1309         event_callback(env, &info);
1310     } END_CALLBACK();
1311 
1312     LOG_MISC(("END cbMonitorWait"));
1313 }
1314 
1315 /* Event callback for JVMTI_EVENT_MONITOR_WAIT */
1316 static void JNICALL
1317 cbMonitorWaited(jvmtiEnv *jvmti_env, JNIEnv *env,
1318                         jthread thread, jobject object,
1319                         jboolean timed_out)
1320 {
1321     EventInfo info;
1322     jvmtiError error;
1323     jmethodID  method;
1324     jlocation  location;
1325 
1326     LOG_CB(("cbMonitorWaited: thread=%p", thread));
1327 
1328     BEGIN_CALLBACK() {
1329         (void)memset(&info,0,sizeof(info));
1330         info.ei         = EI_MONITOR_WAITED;
1331         info.thread     = thread;
1332         info.object     = object;
1333         /* The info.clazz is used for both class filtering and for location info.
1334          * For monitor waited event the class filtering is done for class of monitor
1335          * object. So here info.clazz is set to class of monitor object here and it
1336          * is reset to class of method before writing location info.
1337          * See writeMonitorEvent in eventHelper.c
1338          */
1339         info.clazz      = getObjectClass(object);
1340         info.u.monitor.timed_out = timed_out;
1341 
1342         /* get location of monitor wait() method */
1343         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1344                 (gdata->jvmti, thread, 0, &method, &location);
1345         if (error == JVMTI_ERROR_NONE) {
1346             info.location = location;
1347             info.method   = method;
1348         } else {
1349             info.location = -1;
1350         }
1351         event_callback(env, &info);
1352     } END_CALLBACK();
1353 
1354     LOG_MISC(("END cbMonitorWaited"));
1355 }
1356 
1357 /* Event callback for JVMTI_EVENT_VM_INIT */
1358 static void JNICALL
1359 cbVMInit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
1360 {
1361     EventInfo info;
1362 
1363     LOG_CB(("cbVMInit"));
1364 
1365     BEGIN_CALLBACK() {
1366         (void)memset(&info,0,sizeof(info));
1367         info.ei         = EI_VM_INIT;
1368         info.thread     = thread;
1369         event_callback(env, &info);
1370     } END_CALLBACK();
1371 
1372     LOG_MISC(("END cbVMInit"));
1373 }
1374 
1375 /* Event callback for JVMTI_EVENT_VM_DEATH */
1376 static void JNICALL
1377 cbVMDeath(jvmtiEnv *jvmti_env, JNIEnv *env)
1378 {
1379     jvmtiError error;
1380     EventInfo info;
1381     LOG_CB(("cbVMDeath"));
1382 
1383     /* Clear out ALL callbacks at this time, we don't want any more. */
1384     /*    This should prevent any new BEGIN_CALLBACK() calls. */
1385     (void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));
1386     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)
1387                 (gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));
1388     if (error != JVMTI_ERROR_NONE) {
1389         EXIT_ERROR(error,"Can't clear event callbacks on vm death");
1390     }
1391 
1392     /* Now that no new callbacks will be made, we need to wait for the ones
1393      *   that are still active to complete.
1394      *   The BEGIN_CALLBACK/END_CALLBACK macros implement the VM_DEATH
1395      *   callback protocol. Once the callback table is cleared (above),
1396      *   we can have callback threads in different stages:
1397      *   1) after callback function entry and before BEGIN_CALLBACK
1398      *      macro; we catch these threads with callbackBlock in the
1399      *      BEGIN_CALLBACK macro
1400      *   2) after BEGIN_CALLBACK macro and before END_CALLBACK macro; we
1401      *      catch these threads with callbackBlock in the END_CALLBACK
1402      *      macro
1403      *   3) after END_CALLBACK macro; these threads have made it past
1404      *      callbackBlock and callbackLock and don't count as active
1405      *
1406      *   Since some of the callback threads could be blocked or suspended
1407      *   we will resume all threads suspended by the debugger for a short
1408      *   time to flush out all callbacks. Note that the callback threads
1409      *   will block from returning to the VM in both macros. Some threads
1410      *   not associated with callbacks, but suspended by the debugger may
1411      *   continue on, but not for long.
1412      *   Once the last callback finishes, it will notify this thread and
1413      *   we fall out of the loop below and actually process the VM_DEATH
1414      *   event.
1415      */
1416     debugMonitorEnter(callbackBlock); {
1417         debugMonitorEnter(callbackLock); {
1418             vm_death_callback_active = JNI_TRUE;
1419             (void)threadControl_resumeAll();
1420             while (active_callbacks > 0) {
1421                 /* wait for active CALLBACKs to check in (and block) */
1422                 debugMonitorWait(callbackLock);
1423             }
1424         } debugMonitorExit(callbackLock);
1425 
1426         /* Only now should we actually process the VM death event */
1427         (void)memset(&info,0,sizeof(info));
1428         info.ei                 = EI_VM_DEATH;
1429         event_callback(env, &info);
1430 
1431         /* Here we unblock all the callbacks and let them return to the
1432          *   VM.  It's not clear this is necessary, but leaving threads
1433          *   blocked doesn't seem like a good idea. They don't have much
1434          *   life left anyway.
1435          */
1436     } debugMonitorExit(callbackBlock);
1437 
1438     /*
1439      * The VM will die soon after the completion of this callback -
1440      * we synchronize with both the command loop and the debug loop
1441      * for a more orderly shutdown.
1442      */
1443     commandLoop_sync();
1444     debugLoop_sync();
1445 
1446     LOG_MISC(("END cbVMDeath"));
1447 }
1448 
1449 /* Event callback for JVMTI_EVENT_FIBER_SCHEDULED */
1450 static void JNICALL
1451 cbFiberScheduled(jvmtiEnv *jvmti_env, JNIEnv *env,
1452                  jthread thread, jthread fiber)
1453 {
1454     EventInfo info;
1455 
1456     LOG_CB(("cbFiberScheduled: thread=%p", thread));
1457     /*tty_message("cbFiberScheduled: thread=%p", thread);*/
1458     JDI_ASSERT(gdata->fibersSupported);
1459 
1460     /*
1461      * Now would be a good time to cache the ThreadGroup for fibers (carrier threads)
1462      * if we haven't already.
1463      *
1464      * fiber fixme: the is kind of a hack. What happens if custom
1465      * scheduler uses carrier threads in multple group? What if as a result of this a
1466      * Fiber can move between thread groups? We should have a dedicated
1467      * thread group for all fibers, or allow a fiber to set its ThreadGroup.
1468      */
1469     if (gdata->fiberThreadGroup == NULL) {
1470         jvmtiThreadInfo info;
1471         jvmtiError error;
1472 
1473         (void)memset(&info, 0, sizeof(info));
1474         error = JVMTI_FUNC_PTR(gdata->jvmti,GetThreadInfo)
1475             (gdata->jvmti, thread, &info);
1476 
1477         if (error != JVMTI_ERROR_NONE) {
1478             EXIT_ERROR(error, "could not get fiber ThreadGroup");
1479         } else {
1480             debugMonitorEnter(callbackBlock); /* fiber fixme: any monitor will do, but there probably is a better choice. */
1481             /* Make sure there wasn't a race before setting. saveGlobalRef() will assert if the
1482              * target is not NULL. */
1483             if (gdata->fiberThreadGroup == NULL) {
1484                 saveGlobalRef(env, info.thread_group, &gdata->fiberThreadGroup);
1485             }
1486             debugMonitorExit(callbackBlock);
1487         }
1488     }
1489 
1490     /* Ignore FIBER_SCHEDULED events unless we are notifying the debugger of all fibers. */
1491     if (!gdata->notifyDebuggerOfAllFibers) {
1492         return;
1493     }
1494 
1495     BEGIN_CALLBACK() {
1496         (void)memset(&info,0,sizeof(info));
1497         info.ei         = EI_FIBER_SCHEDULED;
1498         info.thread     = thread;
1499         info.fiber      = fiber;
1500         event_callback(env, &info);
1501     } END_CALLBACK();
1502 
1503     LOG_MISC(("END cbFiberScheduled"));
1504 }
1505 
1506 /* Event callback for JVMTI_EVENT_FIBER_TERMINATED */
1507 static void JNICALL
1508 cbFiberTerminated(jvmtiEnv *jvmti_env, JNIEnv *env,
1509                   jthread thread, jthread fiber)
1510 {
1511     EventInfo info;
1512 
1513     LOG_CB(("cbFiberTerminated: thread=%p", thread));
1514     /*tty_message("cbFiberTerminated: thread=%p", thread);*/
1515     JDI_ASSERT(gdata->fibersSupported);
1516 
1517     if (!gdata->notifyDebuggerOfAllFibers && !threadControl_isKnownFiber(fiber)) {
1518         /* This is not a fiber we are tracking, so don't deliver a FIBER_TERMINATED event for it. */
1519         return;
1520     }
1521 
1522     BEGIN_CALLBACK() {
1523         (void)memset(&info,0,sizeof(info));
1524         info.ei         = EI_FIBER_TERMINATED;
1525         info.thread     = thread;
1526         info.fiber      = fiber;
1527         event_callback(env, &info);
1528     } END_CALLBACK();
1529 
1530     LOG_MISC(("END cbFiberTerminated"));
1531 }
1532 
1533 /* Event callback for JVMTI_EVENT_FIBER_MOUNT */
1534 static void JNICALL
1535 cbFiberMount(jvmtiEnv *jvmti_env, JNIEnv *env,
1536              jthread thread, jthread fiber)
1537 {
1538     LOG_CB(("cbFiberMount: thread=%p", thread));
1539     /*tty_message("cbFiberMount: thread=%p", thread);*/
1540     JDI_ASSERT(gdata->fibersSupported);
1541 
1542     /* Ignore FIBER_MOUNT events unless we are doing fiber debugging. */
1543     if (!gdata->fibersSupported) {
1544         return;
1545     }
1546 
1547     threadControl_mountFiber(fiber, thread, currentSessionID);
1548 
1549     LOG_MISC(("END cbFiberMount"));
1550 }
1551 
1552 /* Event callback for JVMTI_EVENT_FIBER_UNMOUNT */
1553 static void JNICALL
1554 cbFiberUnmount(jvmtiEnv *jvmti_env, JNIEnv *env,
1555                jthread thread, jthread fiber)
1556 {
1557     LOG_CB(("cbFiberUnmount: thread=%p", thread));
1558     /*tty_message("cbFiberUnmount: thread=%p", thread);*/
1559     JDI_ASSERT(gdata->fibersSupported);
1560 
1561     /* Ignore FIBER_UNMOUNT events unless we are doing fiber debugging. */
1562     if (!gdata->fibersSupported) {
1563         return;
1564     }
1565 
1566     threadControl_unmountFiber(fiber, thread);
1567 
1568     LOG_MISC(("END cbFiberUnmount"));
1569 }
1570 
1571 /* Event callback for JVMTI_EVENT_CONTINUATION_RUN */
1572 static void JNICALL
1573 cbContinuationRun(jvmtiEnv *jvmti_env, JNIEnv *env,
1574                   jthread thread, jint continuation_frame_count)
1575 {
1576     LOG_CB(("cbContinuationRun: thread=%p", thread));
1577     //tty_message("cbContinuationRun: thread=%p continuation_frame_count=%d", thread, continuation_frame_count);
1578     JDI_ASSERT(gdata->fibersSupported);
1579 
1580     threadControl_continuationRun(thread, continuation_frame_count);
1581 
1582     LOG_MISC(("END cbContinuationRun"));
1583 }
1584 
1585 /* Event callback for JVMTI_EVENT_CONTINUATION_YIELD */
1586 static void JNICALL
1587 cbContinuationYield(jvmtiEnv *jvmti_env, JNIEnv *env,
1588                     jthread thread, jint continuation_frame_count)
1589 {
1590     LOG_CB(("cbContinuationYield: thread=%p", thread));
1591     //tty_message("cbContinuationYield: thread=%p continuation_frame_count=%d", thread, continuation_frame_count);
1592     JDI_ASSERT(gdata->fibersSupported);
1593 
1594     threadControl_continuationYield(thread, continuation_frame_count);
1595 
1596     LOG_MISC(("END cbContinuationYield"));
1597 }
1598 
1599 /**
1600  * Delete this handler (do not delete permanent handlers):
1601  * Deinsert handler from active list,
1602  * make it inactive, and free it's memory
1603  * Assumes handlerLock held.
1604  */
1605 static jvmtiError
1606 freeHandler(HandlerNode *node) {
1607     jvmtiError error = JVMTI_ERROR_NONE;
1608 
1609     /* deinsert the handler node before disableEvents() to make
1610      * sure the event will be disabled when no other event
1611      * handlers are installed.
1612      */
1613     if (node != NULL && (!node->permanent)) {
1614         deinsert(node);
1615         error = eventFilterRestricted_deinstall(node);
1616         jvmtiDeallocate(node);
1617     }
1618 
1619     return error;
1620 }
1621 
1622 /**
1623  * Delete all the handlers on this chain (do not delete permanent handlers).
1624  * Assumes handlerLock held.
1625  */
1626 static jvmtiError
1627 freeHandlerChain(HandlerChain *chain)
1628 {
1629     HandlerNode *node;
1630     jvmtiError   error;
1631 
1632     error = JVMTI_ERROR_NONE;
1633     node  = chain->first;
1634     while ( node != NULL ) {
1635         HandlerNode *next;
1636         jvmtiError   singleError;
1637 
1638         next = NEXT(node);
1639         singleError = freeHandler(node);
1640         if ( singleError != JVMTI_ERROR_NONE ) {
1641             error = singleError;
1642         }
1643         node = next;
1644     }
1645     return error;
1646 }
1647 
1648 /**
1649  * Deinsert and free all memory.  Safe for non-inserted nodes.
1650  */
1651 jvmtiError
1652 eventHandler_free(HandlerNode *node)
1653 {
1654     jvmtiError error;
1655 
1656     debugMonitorEnter(handlerLock);
1657 
1658     error = freeHandler(node);
1659 
1660     debugMonitorExit(handlerLock);
1661 
1662     return error;
1663 }
1664 
1665 /**
1666  * Free all handlers of this kind created by the JDWP client,
1667  * that is, doesn't free handlers internally created by back-end.
1668  */
1669 jvmtiError
1670 eventHandler_freeAll(EventIndex ei)
1671 {
1672     jvmtiError error = JVMTI_ERROR_NONE;
1673     HandlerNode *node;
1674 
1675     debugMonitorEnter(handlerLock);
1676     node = getHandlerChain(ei)->first;
1677     while (node != NULL) {
1678         HandlerNode *next = NEXT(node);    /* allows node removal */
1679         if (node->handlerID != 0) {        /* don't free internal handlers */
1680             error = freeHandler(node);
1681             if (error != JVMTI_ERROR_NONE) {
1682                 break;
1683             }
1684         }
1685         node = next;
1686     }
1687     debugMonitorExit(handlerLock);
1688     return error;
1689 }
1690 
1691 /***
1692  * Delete all breakpoints on "clazz".
1693  */
1694 void
1695 eventHandler_freeClassBreakpoints(jclass clazz)
1696 {
1697     HandlerNode *node;
1698     JNIEnv *env = getEnv();
1699 
1700     debugMonitorEnter(handlerLock);
1701     node = getHandlerChain(EI_BREAKPOINT)->first;
1702     while (node != NULL) {
1703         HandlerNode *next = NEXT(node); /* allows node removal */
1704         if (eventFilterRestricted_isBreakpointInClass(env, clazz,
1705                                                       node)) {
1706             (void)freeHandler(node);
1707         }
1708         node = next;
1709     }
1710     debugMonitorExit(handlerLock);
1711 }
1712 
1713 jvmtiError
1714 eventHandler_freeByID(EventIndex ei, HandlerID handlerID)
1715 {
1716     jvmtiError error;
1717     HandlerNode *node;
1718 
1719     debugMonitorEnter(handlerLock);
1720     node = find(ei, handlerID);
1721     if (node != NULL) {
1722         error = freeHandler(node);
1723     } else {
1724         /* already freed */
1725         error = JVMTI_ERROR_NONE;
1726     }
1727     debugMonitorExit(handlerLock);
1728     return error;
1729 }
1730 
1731 void
1732 eventHandler_initialize(jbyte sessionID)
1733 {
1734     jvmtiError error;
1735     jint i;
1736 
1737     requestIdCounter = 1;
1738     currentSessionID = sessionID;
1739 
1740     /* This is for BEGIN_CALLBACK/END_CALLBACK handling, make sure this
1741      *   is done while none of these callbacks are active.
1742      */
1743     active_callbacks = 0;
1744     vm_death_callback_active = JNI_FALSE;
1745     callbackLock = debugMonitorCreate("JDWP Callback Lock");
1746     callbackBlock = debugMonitorCreate("JDWP Callback Block");
1747 
1748     handlerLock = debugMonitorCreate("JDWP Event Handler Lock");
1749 
1750     for (i = EI_min; i <= EI_max; ++i) {
1751         getHandlerChain(i)->first = NULL;
1752     }
1753 
1754     /*
1755      * Permanently enabled some events.
1756      */
1757     error = threadControl_setEventMode(JVMTI_ENABLE,
1758                                       EI_VM_INIT, NULL);
1759     if (error != JVMTI_ERROR_NONE) {
1760         EXIT_ERROR(error,"Can't enable vm init events");
1761     }
1762     error = threadControl_setEventMode(JVMTI_ENABLE,
1763                                       EI_VM_DEATH, NULL);
1764     if (error != JVMTI_ERROR_NONE) {
1765         EXIT_ERROR(error,"Can't enable vm death events");
1766     }
1767     error = threadControl_setEventMode(JVMTI_ENABLE,
1768                                       EI_THREAD_START, NULL);
1769     if (error != JVMTI_ERROR_NONE) {
1770         EXIT_ERROR(error,"Can't enable thread start events");
1771     }
1772     error = threadControl_setEventMode(JVMTI_ENABLE,
1773                                        EI_THREAD_END, NULL);
1774     if (error != JVMTI_ERROR_NONE) {
1775         EXIT_ERROR(error,"Can't enable thread end events");
1776     }
1777     error = threadControl_setEventMode(JVMTI_ENABLE,
1778                                        EI_CLASS_PREPARE, NULL);
1779     if (error != JVMTI_ERROR_NONE) {
1780         EXIT_ERROR(error,"Can't enable class prepare events");
1781     }
1782     error = threadControl_setEventMode(JVMTI_ENABLE,
1783                                        EI_GC_FINISH, NULL);
1784     if (error != JVMTI_ERROR_NONE) {
1785         EXIT_ERROR(error,"Can't enable garbage collection finish events");
1786     }
1787     /* Only enable fiber events if fiber support is enabled. */
1788     if (gdata->fibersSupported) {
1789         error = threadControl_setEventMode(JVMTI_ENABLE,
1790                                            EI_FIBER_SCHEDULED, NULL);
1791         if (error != JVMTI_ERROR_NONE) {
1792             EXIT_ERROR(error,"Can't enable fiber scheduled events");
1793         }
1794         error = threadControl_setEventMode(JVMTI_ENABLE,
1795                                            EI_FIBER_TERMINATED, NULL);
1796         if (error != JVMTI_ERROR_NONE) {
1797             EXIT_ERROR(error,"Can't enable fiber terminated events");
1798         }
1799         error = threadControl_setEventMode(JVMTI_ENABLE,
1800                                            EI_FIBER_MOUNT, NULL);
1801         if (error != JVMTI_ERROR_NONE) {
1802             EXIT_ERROR(error,"Can't enable fiber mount events");
1803         }
1804         error = threadControl_setEventMode(JVMTI_ENABLE,
1805                                            EI_FIBER_UNMOUNT, NULL);
1806         if (error != JVMTI_ERROR_NONE) {
1807             EXIT_ERROR(error,"Can't enable fiber unmount events");
1808         }
1809         error = threadControl_setEventMode(JVMTI_ENABLE,
1810                                            EI_CONTINUATION_RUN, NULL);
1811         if (error != JVMTI_ERROR_NONE) {
1812             EXIT_ERROR(error,"Can't enable continuation run events");
1813         }
1814         error = threadControl_setEventMode(JVMTI_ENABLE,
1815                                            EI_CONTINUATION_YIELD, NULL);
1816         if (error != JVMTI_ERROR_NONE) {
1817             EXIT_ERROR(error,"Can't enable continuation yield events");
1818         }
1819     }
1820 
1821     (void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));
1822     /* Event callback for JVMTI_EVENT_SINGLE_STEP */
1823     gdata->callbacks.SingleStep                 = &cbSingleStep;
1824     /* Event callback for JVMTI_EVENT_BREAKPOINT */
1825     gdata->callbacks.Breakpoint                 = &cbBreakpoint;
1826     /* Event callback for JVMTI_EVENT_FRAME_POP */
1827     gdata->callbacks.FramePop                   = &cbFramePop;
1828     /* Event callback for JVMTI_EVENT_EXCEPTION */
1829     gdata->callbacks.Exception                  = &cbException;
1830     /* Event callback for JVMTI_EVENT_THREAD_START */
1831     gdata->callbacks.ThreadStart                = &cbThreadStart;
1832     /* Event callback for JVMTI_EVENT_THREAD_END */
1833     gdata->callbacks.ThreadEnd                  = &cbThreadEnd;
1834     /* Event callback for JVMTI_EVENT_CLASS_PREPARE */
1835     gdata->callbacks.ClassPrepare               = &cbClassPrepare;
1836     /* Event callback for JVMTI_EVENT_CLASS_LOAD */
1837     gdata->callbacks.ClassLoad                  = &cbClassLoad;
1838     /* Event callback for JVMTI_EVENT_FIELD_ACCESS */
1839     gdata->callbacks.FieldAccess                = &cbFieldAccess;
1840     /* Event callback for JVMTI_EVENT_FIELD_MODIFICATION */
1841     gdata->callbacks.FieldModification          = &cbFieldModification;
1842     /* Event callback for JVMTI_EVENT_EXCEPTION_CATCH */
1843     gdata->callbacks.ExceptionCatch             = &cbExceptionCatch;
1844     /* Event callback for JVMTI_EVENT_METHOD_ENTRY */
1845     gdata->callbacks.MethodEntry                = &cbMethodEntry;
1846     /* Event callback for JVMTI_EVENT_METHOD_EXIT */
1847     gdata->callbacks.MethodExit                 = &cbMethodExit;
1848     /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTER */
1849     gdata->callbacks.MonitorContendedEnter      = &cbMonitorContendedEnter;
1850     /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTERED */
1851     gdata->callbacks.MonitorContendedEntered    = &cbMonitorContendedEntered;
1852     /* Event callback for JVMTI_EVENT_MONITOR_WAIT */
1853     gdata->callbacks.MonitorWait                = &cbMonitorWait;
1854     /* Event callback for JVMTI_EVENT_MONITOR_WAITED */
1855     gdata->callbacks.MonitorWaited              = &cbMonitorWaited;
1856     /* Event callback for JVMTI_EVENT_VM_INIT */
1857     gdata->callbacks.VMInit                     = &cbVMInit;
1858     /* Event callback for JVMTI_EVENT_VM_DEATH */
1859     gdata->callbacks.VMDeath                    = &cbVMDeath;
1860     /* Event callback for JVMTI_EVENT_GARBAGE_COLLECTION_FINISH */
1861     gdata->callbacks.GarbageCollectionFinish    = &cbGarbageCollectionFinish;
1862     /* Event callback for JVMTI_EVENT_FIBER_SCHEDULED */
1863     gdata->callbacks.FiberScheduled             = &cbFiberScheduled;
1864     /* Event callback for JVMTI_EVENT_FIBER_TERMINATED */
1865     gdata->callbacks.FiberTerminated            = &cbFiberTerminated;
1866     /* Event callback for JVMTI_EVENT_FIBER_MOUNT */
1867     gdata->callbacks.FiberMount                 = &cbFiberMount;
1868     /* Event callback for JVMTI_EVENT_FIBER_UNMOUNT */
1869     gdata->callbacks.FiberUnmount               = &cbFiberUnmount;
1870     /* Event callback for JVMTI_EVENT_CONTINUATION_RUN */
1871     gdata->callbacks.ContinuationRun            = &cbContinuationRun;
1872     /* Event callback for JVMTI_EVENT_CONTINUATION_YIELD */
1873     gdata->callbacks.ContinuationYield          = &cbContinuationYield;
1874 
1875     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)
1876                 (gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));
1877     if (error != JVMTI_ERROR_NONE) {
1878         EXIT_ERROR(error,"Can't set event callbacks");
1879     }
1880 
1881     /* Notify other modules that the event callbacks are in place */
1882     threadControl_onHook();
1883 
1884     /* Get the event helper thread initialized */
1885     eventHelper_initialize(sessionID);
1886 }
1887 
1888 void
1889 eventHandler_reset(jbyte sessionID)
1890 {
1891     int i;
1892 
1893     debugMonitorEnter(handlerLock);
1894 
1895     /* We must do this first so that if any invokes complete,
1896      * there will be no attempt to send them to the front
1897      * end. Waiting for threadControl_reset leaves a window where
1898      * the invoke completions can sneak through.
1899      */
1900     threadControl_detachInvokes();
1901 
1902     /* Reset the event helper thread, purging all queued and
1903      * in-process commands.
1904      */
1905     eventHelper_reset(sessionID);
1906 
1907     /* delete all handlers */
1908     for (i = EI_min; i <= EI_max; i++) {
1909         (void)freeHandlerChain(getHandlerChain(i));
1910     }
1911 
1912     requestIdCounter = 1;
1913     currentSessionID = sessionID;
1914 
1915     debugMonitorExit(handlerLock);
1916 }
1917 
1918 void
1919 eventHandler_lock(void)
1920 {
1921     debugMonitorEnter(handlerLock);
1922 }
1923 
1924 void
1925 eventHandler_unlock(void)
1926 {
1927     debugMonitorExit(handlerLock);
1928 }
1929 
1930 /***** handler creation *****/
1931 
1932 HandlerNode *
1933 eventHandler_alloc(jint filterCount, EventIndex ei, jbyte suspendPolicy)
1934 {
1935     HandlerNode *node = eventFilterRestricted_alloc(filterCount);
1936 
1937     if (node != NULL) {
1938         node->ei = ei;
1939         node->suspendPolicy = suspendPolicy;
1940         node->permanent = JNI_FALSE;
1941     }
1942 
1943     return node;
1944 }
1945 
1946 
1947 HandlerID
1948 eventHandler_allocHandlerID(void)
1949 {
1950     jint handlerID;
1951     debugMonitorEnter(handlerLock);
1952     handlerID = ++requestIdCounter;
1953     debugMonitorExit(handlerLock);
1954     return handlerID;
1955 }
1956 
1957 
1958 static jvmtiError
1959 installHandler(HandlerNode *node,
1960               HandlerFunction func,
1961               jboolean external)
1962 {
1963     jvmtiError error;
1964 
1965     if ( func == NULL ) {
1966         return AGENT_ERROR_INVALID_EVENT_TYPE;
1967     }
1968 
1969     debugMonitorEnter(handlerLock);
1970 
1971     HANDLER_FUNCTION(node) = func;
1972 
1973     node->handlerID = external? ++requestIdCounter : 0;
1974     error = eventFilterRestricted_install(node);
1975     if (error == JVMTI_ERROR_NONE) {
1976         insert(getHandlerChain(node->ei), node);
1977     }
1978 
1979     debugMonitorExit(handlerLock);
1980 
1981     return error;
1982 }
1983 
1984 static HandlerNode *
1985 createInternal(EventIndex ei, HandlerFunction func,
1986                jthread thread, jclass clazz, jmethodID method,
1987                jlocation location, jboolean permanent)
1988 {
1989     jint index = 0;
1990     jvmtiError error = JVMTI_ERROR_NONE;
1991     HandlerNode *node;
1992 
1993     /*
1994      * Start with necessary allocations
1995      */
1996     node = eventHandler_alloc(
1997         ((thread == NULL)? 0 : 1) + ((clazz == NULL)? 0 : 1),
1998         ei, JDWP_SUSPEND_POLICY(NONE));
1999     if (node == NULL) {
2000         return NULL;
2001     }
2002 
2003     node->permanent = permanent;
2004 
2005     if (thread != NULL) {
2006         error = eventFilter_setThreadOnlyFilter(node, index++, thread);
2007     }
2008 
2009     if ((error == JVMTI_ERROR_NONE) && (clazz != NULL)) {
2010         error = eventFilter_setLocationOnlyFilter(node, index++, clazz,
2011                                                   method, location);
2012     }
2013     /*
2014      * Create the new handler node
2015      */
2016     error = installHandler(node, func, JNI_FALSE);
2017 
2018     if (error != JVMTI_ERROR_NONE) {
2019         (void)eventHandler_free(node);
2020         node = NULL;
2021     }
2022     return node;
2023 }
2024 
2025 HandlerNode *
2026 eventHandler_createPermanentInternal(EventIndex ei, HandlerFunction func)
2027 {
2028     return createInternal(ei, func, NULL,
2029                           NULL, NULL, 0, JNI_TRUE);
2030 }
2031 
2032 HandlerNode *
2033 eventHandler_createInternalThreadOnly(EventIndex ei,
2034                                       HandlerFunction func,
2035                                       jthread thread)
2036 {
2037     return createInternal(ei, func, thread,
2038                           NULL, NULL, 0, JNI_FALSE);
2039 }
2040 
2041 HandlerNode *
2042 eventHandler_createInternalBreakpoint(HandlerFunction func,
2043                                       jthread thread,
2044                                       jclass clazz,
2045                                       jmethodID method,
2046                                       jlocation location)
2047 {
2048     return createInternal(EI_BREAKPOINT, func, thread,
2049                           clazz, method, location, JNI_FALSE);
2050 }
2051 
2052 jvmtiError
2053 eventHandler_installExternal(HandlerNode *node)
2054 {
2055     return installHandler(node,
2056                           standardHandlers_defaultHandler(node->ei),
2057                           JNI_TRUE);
2058 }
2059 
2060 /***** debugging *****/
2061 
2062 void
2063 eventHandler_dumpAllHandlers(jboolean dumpPermanent)
2064 {
2065     int ei;
2066     for (ei = EI_min; ei <= EI_max; ++ei) {
2067         eventHandler_dumpHandlers(ei, dumpPermanent);
2068     }
2069 }
2070 
2071 void
2072 eventHandler_dumpHandlers(EventIndex ei, jboolean dumpPermanent)
2073 {
2074   HandlerNode *nextNode;
2075   nextNode = getHandlerChain(ei)->first;
2076   if (nextNode != NULL) {
2077       tty_message("\nHandlers for %s(%d)", eventIndex2EventName(ei), ei);
2078       while (nextNode != NULL) {
2079           HandlerNode *node = nextNode;
2080           nextNode = NEXT(node);
2081           
2082           if (node->permanent && !dumpPermanent) {
2083               continue; // ignore permanent handlers
2084           }
2085 
2086           tty_message("node(%p) handlerID(%d) suspendPolicy(%d) permanent(%d)",
2087                       node, node->handlerID, node->suspendPolicy, node->permanent);
2088           eventFilter_dumpHandlerFilters(node);
2089       }
2090   }
2091 }
2092 
2093 void
2094 eventHandler_dumpHandler(HandlerNode *node)
2095 {
2096   tty_message("Handler for %s(%d)\n", eventIndex2EventName(node->ei), node->ei);
2097   eventFilter_dumpHandlerFilters(node);
2098 }