• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1998, 2007, 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 *
getHandlerChain(EventIndex i)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
insert(HandlerChain * chain,HandlerNode * node)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 *
findInChain(HandlerChain * chain,HandlerID handlerID)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 *
find(EventIndex ei,HandlerID handlerID)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
deinsert(HandlerNode * node)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
eventHandlerRestricted_iterator(EventIndex ei,IteratorFunction func,void * arg)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
deferEventReport(JNIEnv * env,jthread thread,EventIndex ei,jclass clazz,jmethodID method,jlocation location)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
skipEventReport(JNIEnv * env,jthread thread,EventIndex ei,jclass clazz,jmethodID method,jlocation location)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
reportEvents(JNIEnv * env,jbyte sessionID,jthread thread,EventIndex ei,jclass clazz,jmethodID method,jlocation location,struct bag * eventBag)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 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
synthesizeUnloadEvent(void * signatureVoid,void * envVoid)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     if (eventBag == NULL) {
475         /* TO DO: Report, but don't die
476          */
477         JDI_ASSERT(eventBag != NULL);
478     }
479 
480     /* Signature needs to last, so convert extra copy to
481      * classname
482      */
483     classname = jvmtiAllocate((int)strlen(signature)+1);
484     (void)strcpy(classname, signature);
485     convertSignatureToClassname(classname);
486 
487     debugMonitorEnter(handlerLock);
488 
489     node = getHandlerChain(EI_GC_FINISH)->first;
490     while (node != NULL) {
491         /* save next so handlers can remove themselves */
492         HandlerNode *next = NEXT(node);
493         jboolean shouldDelete;
494 
495         if (eventFilterRestricted_passesUnloadFilter(env, classname,
496                                                      node,
497                                                      &shouldDelete)) {
498             /* There may be multiple handlers, the signature will
499              * be freed when the event helper thread has written
500              * it.  So each event needs a separate allocation.
501              */
502             char *durableSignature = jvmtiAllocate((int)strlen(signature)+1);
503             (void)strcpy(durableSignature, signature);
504 
505             eventHelper_recordClassUnload(node->handlerID,
506                                           durableSignature,
507                                           eventBag);
508         }
509         if (shouldDelete) {
510             /* We can safely free the node now that we are done
511              * using it.
512              */
513             (void)freeHandler(node);
514         }
515         node = next;
516     }
517 
518     debugMonitorExit(handlerLock);
519 
520     if (eventBag != NULL) {
521         reportEvents(env, eventSessionID, (jthread)NULL, 0,
522                             (jclass)NULL, (jmethodID)NULL, 0, eventBag);
523 
524         /*
525          * bag was created locally, destroy it here.
526          */
527         bagDestroyBag(eventBag);
528     }
529 
530     jvmtiDeallocate(signature);
531     jvmtiDeallocate(classname);
532 
533     return JNI_TRUE;
534 }
535 
536 /* Garbage Collection Happened */
537 static unsigned int garbageCollected = 0;
538 
539 /* The JVMTI generic event callback. Each event is passed to a sequence of
540  * handlers in a chain until the chain ends or one handler
541  * consumes the event.
542  */
543 static void
event_callback(JNIEnv * env,EventInfo * evinfo)544 event_callback(JNIEnv *env, EventInfo *evinfo)
545 {
546     struct bag *eventBag;
547     jbyte eventSessionID = currentSessionID; /* session could change */
548     jthrowable currentException;
549     jthread thread;
550 
551     LOG_MISC(("event_callback(): ei=%s", eventText(evinfo->ei)));
552     log_debugee_location("event_callback()", evinfo->thread, evinfo->method, evinfo->location);
553 
554     /* We want to preserve any current exception that might get
555      * wiped out during event handling (e.g. JNI calls). We have
556      * to rely on space for the local reference on the current
557      * frame because doing a PushLocalFrame here might itself
558      * generate an exception.
559      */
560     currentException = JNI_FUNC_PTR(env,ExceptionOccurred)(env);
561     JNI_FUNC_PTR(env,ExceptionClear)(env);
562 
563     /* See if a garbage collection finish event happened earlier.
564      *
565      * Note: The "if" is an optimization to avoid entering the lock on every
566      *       event; garbageCollected may be zapped before we enter
567      *       the lock but then this just becomes one big no-op.
568      */
569     if ( garbageCollected > 0 ) {
570         struct bag *unloadedSignatures = NULL;
571 
572         /* We want to compact the hash table of all
573          * objects sent to the front end by removing objects that have
574          * been collected.
575          */
576         commonRef_compact();
577 
578         /* We also need to simulate the class unload events. */
579 
580         debugMonitorEnter(handlerLock);
581 
582         /* Clear garbage collection counter */
583         garbageCollected = 0;
584 
585         /* Analyze which class unloads occurred */
586         unloadedSignatures = classTrack_processUnloads(env);
587 
588         debugMonitorExit(handlerLock);
589 
590         /* Generate the synthetic class unload events and/or just cleanup.  */
591         if ( unloadedSignatures != NULL ) {
592             (void)bagEnumerateOver(unloadedSignatures, synthesizeUnloadEvent,
593                              (void *)env);
594             bagDestroyBag(unloadedSignatures);
595         }
596     }
597 
598     thread = evinfo->thread;
599     if (thread != NULL) {
600         /*
601          * Record the fact that we're entering an event
602          * handler so that thread operations (status, interrupt,
603          * stop) can be done correctly and so that thread
604          * resources can be allocated.  This must be done before
605          * grabbing any locks.
606          */
607         eventBag = threadControl_onEventHandlerEntry(eventSessionID,
608                                  evinfo->ei, thread, currentException);
609         if ( eventBag == NULL ) {
610             jboolean invoking;
611             do {
612                 /* The event has been 'handled' and this
613                  * thread is about to continue, but it may
614                  * have been started up just to perform a
615                  * requested method invocation. If so, we do
616                  * the invoke now and then stop again waiting
617                  * for another continue. By then another
618                  * invoke request can be in place, so there is
619                  * a loop around this code.
620                  */
621                 invoking = invoker_doInvoke(thread);
622                 if (invoking) {
623                     eventHelper_reportInvokeDone(eventSessionID, thread);
624                 }
625             } while (invoking);
626             return; /* Do nothing, event was consumed */
627         }
628     } else {
629         eventBag = eventHelper_createEventBag();
630         if (eventBag == NULL) {
631             /*
632              * TO DO: Report, but don't die
633              */
634             eventBag = NULL;  /* to shut up lint */
635         }
636     }
637 
638     debugMonitorEnter(handlerLock);
639     {
640         HandlerNode *node;
641         char        *classname;
642 
643         /* We must keep track of all classes prepared to know what's unloaded */
644         if (evinfo->ei == EI_CLASS_PREPARE) {
645             classTrack_addPreparedClass(env, evinfo->clazz);
646         }
647 
648         node = getHandlerChain(evinfo->ei)->first;
649         classname = getClassname(evinfo->clazz);
650 
651         while (node != NULL) {
652             /* save next so handlers can remove themselves */
653             HandlerNode *next = NEXT(node);
654             jboolean shouldDelete;
655 
656             if (eventFilterRestricted_passesFilter(env, classname,
657                                                    evinfo, node,
658                                                    &shouldDelete)) {
659                 HandlerFunction func;
660 
661                 func = HANDLER_FUNCTION(node);
662                 if ( func == NULL ) {
663                     EXIT_ERROR(AGENT_ERROR_INTERNAL,"handler function NULL");
664                 }
665                 (*func)(env, evinfo, node, eventBag);
666             }
667             if (shouldDelete) {
668                 /* We can safely free the node now that we are done
669                  * using it.
670                  */
671                 (void)freeHandler(node);
672             }
673             node = next;
674         }
675         jvmtiDeallocate(classname);
676     }
677     debugMonitorExit(handlerLock);
678 
679     if (eventBag != NULL) {
680         reportEvents(env, eventSessionID, thread, evinfo->ei,
681                 evinfo->clazz, evinfo->method, evinfo->location, eventBag);
682     }
683 
684     /* we are continuing after VMDeathEvent - now we are dead */
685     if (evinfo->ei == EI_VM_DEATH) {
686         gdata->vmDead = JNI_TRUE;
687     }
688 
689     /*
690      * If the bag was created locally, destroy it here.
691      */
692     if (thread == NULL) {
693         bagDestroyBag(eventBag);
694     }
695 
696     /* Always restore any exception that was set beforehand.  If
697      * there is a pending async exception, StopThread will be
698      * called from threadControl_onEventHandlerExit immediately
699      * below.  Depending on VM implementation and state, the async
700      * exception might immediately overwrite the currentException,
701      * or it might be delayed until later.  */
702     if (currentException != NULL) {
703         JNI_FUNC_PTR(env,Throw)(env, currentException);
704     } else {
705         JNI_FUNC_PTR(env,ExceptionClear)(env);
706     }
707 
708     /*
709      * Release thread resources and perform any delayed operations.
710      */
711     if (thread != NULL) {
712         threadControl_onEventHandlerExit(evinfo->ei, thread, eventBag);
713     }
714 }
715 
716 /* Returns a local ref to the declaring class for an object. */
717 static jclass
getObjectClass(jobject object)718 getObjectClass(jobject object)
719 {
720     jclass clazz;
721     JNIEnv *env = getEnv();
722 
723     clazz = JNI_FUNC_PTR(env,GetObjectClass)(env, object);
724 
725     return clazz;
726 }
727 
728 /* Returns a local ref to the declaring class for a method, or NULL. */
729 jclass
getMethodClass(jvmtiEnv * jvmti_env,jmethodID method)730 getMethodClass(jvmtiEnv *jvmti_env, jmethodID method)
731 {
732     jclass clazz = NULL;
733     jvmtiError error;
734 
735     if ( method == NULL ) {
736         return NULL;
737     }
738     error = methodClass(method, &clazz);
739     if ( error != JVMTI_ERROR_NONE ) {
740         EXIT_ERROR(error,"Can't get jclass for a methodID, invalid?");
741         return NULL;
742     }
743     return clazz;
744 }
745 
746 /* ANDROID-CHANGED: Android keeps track of object unloads by watching this event instead of looking
747  * through jweaks since there are a limited number of those. This does not cause any corresponding
748  * jdwp event and is merely passed on to the commonRef system.
749  */
750 static void JNICALL
cbObjectFree(jvmtiEnv * jvmti_env,jlong tag)751 cbObjectFree(jvmtiEnv* jvmti_env, jlong tag)
752 {
753   commonRef_handleFreedObject(tag);
754 }
755 
756 /* Event callback for JVMTI_EVENT_SINGLE_STEP */
757 static void JNICALL
cbSingleStep(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jlocation location)758 cbSingleStep(jvmtiEnv *jvmti_env, JNIEnv *env,
759                         jthread thread, jmethodID method, jlocation location)
760 {
761     EventInfo info;
762 
763     LOG_CB(("cbSingleStep: thread=%p", thread));
764 
765     BEGIN_CALLBACK() {
766         (void)memset(&info,0,sizeof(info));
767         info.ei         = EI_SINGLE_STEP;
768         info.thread     = thread;
769         info.clazz      = getMethodClass(jvmti_env, method);
770         info.method     = method;
771         info.location   = location;
772         event_callback(env, &info);
773     } END_CALLBACK();
774 
775     LOG_MISC(("END cbSingleStep"));
776 }
777 
778 /* Event callback for JVMTI_EVENT_BREAKPOINT */
779 static void JNICALL
cbBreakpoint(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jlocation location)780 cbBreakpoint(jvmtiEnv *jvmti_env, JNIEnv *env,
781                         jthread thread, jmethodID method, jlocation location)
782 {
783     EventInfo info;
784 
785     LOG_CB(("cbBreakpoint: thread=%p", thread));
786 
787     BEGIN_CALLBACK() {
788         (void)memset(&info,0,sizeof(info));
789         info.ei         = EI_BREAKPOINT;
790         info.thread     = thread;
791         info.clazz      = getMethodClass(jvmti_env, method);
792         info.method     = method;
793         info.location   = location;
794         event_callback(env, &info);
795     } END_CALLBACK();
796 
797     LOG_MISC(("END cbBreakpoint"));
798 }
799 
800 /* Event callback for JVMTI_EVENT_FRAME_POP */
801 static void JNICALL
cbFramePop(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jboolean wasPoppedByException)802 cbFramePop(jvmtiEnv *jvmti_env, JNIEnv *env,
803                         jthread thread, jmethodID method,
804                         jboolean wasPoppedByException)
805 {
806     EventInfo info;
807 
808     /* JDWP does not return these events when popped due to an exception. */
809     if ( wasPoppedByException ) {
810         return;
811     }
812 
813     LOG_CB(("cbFramePop: thread=%p", thread));
814 
815     BEGIN_CALLBACK() {
816         (void)memset(&info,0,sizeof(info));
817         info.ei         = EI_FRAME_POP;
818         info.thread     = thread;
819         info.clazz      = getMethodClass(jvmti_env, method);
820         info.method     = method;
821         event_callback(env, &info);
822     } END_CALLBACK();
823 
824     LOG_MISC(("END cbFramePop"));
825 }
826 
827 /* Event callback for JVMTI_EVENT_EXCEPTION */
828 static void JNICALL
cbException(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jlocation location,jobject exception,jmethodID catch_method,jlocation catch_location)829 cbException(jvmtiEnv *jvmti_env, JNIEnv *env,
830                         jthread thread, jmethodID method,
831                         jlocation location, jobject exception,
832                         jmethodID catch_method, jlocation catch_location)
833 {
834     EventInfo info;
835 
836     LOG_CB(("cbException: thread=%p", thread));
837 
838     BEGIN_CALLBACK() {
839         (void)memset(&info,0,sizeof(info));
840         info.ei                         = EI_EXCEPTION;
841         info.thread                     = thread;
842         info.clazz                      = getMethodClass(jvmti_env, method);
843         info.method                     = method;
844         info.location                   = location;
845         info.object                     = exception;
846         info.u.exception.catch_clazz    = getMethodClass(jvmti_env, catch_method);
847         info.u.exception.catch_method   = catch_method;
848         info.u.exception.catch_location = catch_location;
849         event_callback(env, &info);
850     } END_CALLBACK();
851 
852     LOG_MISC(("END cbException"));
853 }
854 
855 /* Event callback for JVMTI_EVENT_THREAD_START */
856 static void JNICALL
cbThreadStart(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread)857 cbThreadStart(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
858 {
859     EventInfo info;
860 
861     LOG_CB(("cbThreadStart: thread=%p", thread));
862 
863     BEGIN_CALLBACK() {
864         (void)memset(&info,0,sizeof(info));
865         info.ei         = EI_THREAD_START;
866         info.thread     = thread;
867         event_callback(env, &info);
868     } END_CALLBACK();
869 
870     LOG_MISC(("END cbThreadStart"));
871 }
872 
873 /* Event callback for JVMTI_EVENT_THREAD_END */
874 static void JNICALL
cbThreadEnd(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread)875 cbThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
876 {
877     EventInfo info;
878 
879     LOG_CB(("cbThreadEnd: thread=%p", thread));
880 
881     BEGIN_CALLBACK() {
882         (void)memset(&info,0,sizeof(info));
883         info.ei         = EI_THREAD_END;
884         info.thread     = thread;
885         event_callback(env, &info);
886     } END_CALLBACK();
887 
888     LOG_MISC(("END cbThreadEnd"));
889 }
890 
891 /* Event callback for JVMTI_EVENT_CLASS_PREPARE */
892 static void JNICALL
cbClassPrepare(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jclass klass)893 cbClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *env,
894                         jthread thread, jclass klass)
895 {
896     /* ANDROID-CHANGED: b/111394423 Android sends ClassPrepare events for arrays too. We don't
897      * really care about these though and they can cause deadlocks since they may be sent on jit
898      * threads so just ignore them.
899      */
900     if (isArrayClass(klass)) {
901       return;
902     }
903     EventInfo info;
904 
905     LOG_CB(("cbClassPrepare: thread=%p", thread));
906 
907     BEGIN_CALLBACK() {
908         (void)memset(&info,0,sizeof(info));
909         info.ei         = EI_CLASS_PREPARE;
910         info.thread     = thread;
911         info.clazz      = klass;
912         event_callback(env, &info);
913     } END_CALLBACK();
914 
915     LOG_MISC(("END cbClassPrepare"));
916 }
917 
918 /* Event callback for JVMTI_EVENT_GARBAGE_COLLECTION_FINISH */
919 static void JNICALL
cbGarbageCollectionFinish(jvmtiEnv * jvmti_env)920 cbGarbageCollectionFinish(jvmtiEnv *jvmti_env)
921 {
922     LOG_CB(("cbGarbageCollectionFinish"));
923     ++garbageCollected;
924     LOG_MISC(("END cbGarbageCollectionFinish"));
925 }
926 
927 /* Event callback for JVMTI_EVENT_CLASS_LOAD */
928 static void JNICALL
cbClassLoad(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jclass klass)929 cbClassLoad(jvmtiEnv *jvmti_env, JNIEnv *env,
930                         jthread thread, jclass klass)
931 {
932     /* ANDROID-CHANGED: b/111394423 Android sends ClassLoad events for arrays too. We don't really
933      * care about these though and they can cause deadlocks since they may be sent on jit threads so
934      * just ignore them.
935      */
936     if (isArrayClass(klass)) {
937       return;
938     }
939     EventInfo info;
940 
941     LOG_CB(("cbClassLoad: thread=%p", thread));
942 
943     BEGIN_CALLBACK() {
944         (void)memset(&info,0,sizeof(info));
945         info.ei         = EI_CLASS_LOAD;
946         info.thread     = thread;
947         info.clazz      = klass;
948         event_callback(env, &info);
949     } END_CALLBACK();
950 
951     LOG_MISC(("END cbClassLoad"));
952 }
953 
954 /* Event callback for JVMTI_EVENT_FIELD_ACCESS */
955 static void JNICALL
cbFieldAccess(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jlocation location,jclass field_klass,jobject object,jfieldID field)956 cbFieldAccess(jvmtiEnv *jvmti_env, JNIEnv *env,
957                         jthread thread, jmethodID method,
958                         jlocation location, jclass field_klass,
959                         jobject object, jfieldID field)
960 {
961     EventInfo info;
962 
963     LOG_CB(("cbFieldAccess: thread=%p", thread));
964 
965     BEGIN_CALLBACK() {
966         (void)memset(&info,0,sizeof(info));
967         info.ei                         = EI_FIELD_ACCESS;
968         info.thread                     = thread;
969         info.clazz                      = getMethodClass(jvmti_env, method);
970         info.method                     = method;
971         info.location                   = location;
972         info.u.field_access.field_clazz = field_klass;
973         info.object                     = object;
974         info.u.field_access.field       = field;
975         event_callback(env, &info);
976     } END_CALLBACK();
977 
978     LOG_MISC(("END cbFieldAccess"));
979 }
980 
981 /* Event callback for JVMTI_EVENT_FIELD_MODIFICATION */
982 static void JNICALL
cbFieldModification(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jlocation location,jclass field_klass,jobject object,jfieldID field,char signature_type,jvalue new_value)983 cbFieldModification(jvmtiEnv *jvmti_env, JNIEnv *env,
984         jthread thread, jmethodID method,
985         jlocation location, jclass field_klass, jobject object, jfieldID field,
986         char signature_type, jvalue new_value)
987 {
988     EventInfo info;
989 
990     LOG_CB(("cbFieldModification: thread=%p", thread));
991 
992     BEGIN_CALLBACK() {
993         (void)memset(&info,0,sizeof(info));
994         info.ei                                 = EI_FIELD_MODIFICATION;
995         info.thread                             = thread;
996         info.clazz                              = getMethodClass(jvmti_env, method);
997         info.method                             = method;
998         info.location                           = location;
999         info.u.field_modification.field         = field;
1000         info.u.field_modification.field_clazz   = field_klass;
1001         info.object                             = object;
1002         info.u.field_modification.signature_type= signature_type;
1003         info.u.field_modification.new_value     = new_value;
1004         event_callback(env, &info);
1005     } END_CALLBACK();
1006 
1007     LOG_MISC(("END cbFieldModification"));
1008 }
1009 
1010 /* Event callback for JVMTI_EVENT_EXCEPTION_CATCH */
1011 static void JNICALL
cbExceptionCatch(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jlocation location,jobject exception)1012 cbExceptionCatch(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread,
1013         jmethodID method, jlocation location, jobject exception)
1014 {
1015     EventInfo info;
1016 
1017     LOG_CB(("cbExceptionCatch: thread=%p", thread));
1018 
1019     BEGIN_CALLBACK() {
1020         (void)memset(&info,0,sizeof(info));
1021         info.ei         = EI_EXCEPTION_CATCH;
1022         info.thread     = thread;
1023         info.clazz      = getMethodClass(jvmti_env, method);
1024         info.method     = method;
1025         info.location   = location;
1026         info.object     = exception;
1027         event_callback(env, &info);
1028     } END_CALLBACK();
1029 
1030     LOG_MISC(("END cbExceptionCatch"));
1031 }
1032 
1033 /* Event callback for JVMTI_EVENT_METHOD_ENTRY */
1034 static void JNICALL
cbMethodEntry(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method)1035 cbMethodEntry(jvmtiEnv *jvmti_env, JNIEnv *env,
1036                         jthread thread, jmethodID method)
1037 {
1038     EventInfo info;
1039 
1040     LOG_CB(("cbMethodEntry: thread=%p", thread));
1041 
1042     BEGIN_CALLBACK() {
1043         (void)memset(&info,0,sizeof(info));
1044         info.ei         = EI_METHOD_ENTRY;
1045         info.thread     = thread;
1046         info.clazz      = getMethodClass(jvmti_env, method);
1047         info.method     = method;
1048         event_callback(env, &info);
1049     } END_CALLBACK();
1050 
1051     LOG_MISC(("END cbMethodEntry"));
1052 }
1053 
1054 /* Event callback for JVMTI_EVENT_METHOD_EXIT */
1055 static void JNICALL
cbMethodExit(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jmethodID method,jboolean wasPoppedByException,jvalue return_value)1056 cbMethodExit(jvmtiEnv *jvmti_env, JNIEnv *env,
1057                         jthread thread, jmethodID method,
1058                         jboolean wasPoppedByException, jvalue return_value)
1059 {
1060     EventInfo info;
1061 
1062     /* JDWP does not return these events when popped due to an exception. */
1063     if ( wasPoppedByException ) {
1064         return;
1065     }
1066 
1067     LOG_CB(("cbMethodExit: thread=%p", thread));
1068 
1069     BEGIN_CALLBACK() {
1070         (void)memset(&info,0,sizeof(info));
1071         info.ei         = EI_METHOD_EXIT;
1072         info.thread     = thread;
1073         info.clazz      = getMethodClass(jvmti_env, method);
1074         info.method     = method;
1075         info.u.method_exit.return_value = return_value;
1076         event_callback(env, &info);
1077     } END_CALLBACK();
1078 
1079     LOG_MISC(("END cbMethodExit"));
1080 }
1081 
1082 /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTER */
1083 static void JNICALL
cbMonitorContendedEnter(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jobject object)1084 cbMonitorContendedEnter(jvmtiEnv *jvmti_env, JNIEnv *env,
1085                         jthread thread, jobject object)
1086 {
1087     EventInfo info;
1088     jvmtiError error;
1089     jmethodID  method;
1090     jlocation  location;
1091 
1092     LOG_CB(("cbMonitorContendedEnter: thread=%p", thread));
1093 
1094     BEGIN_CALLBACK() {
1095         (void)memset(&info,0,sizeof(info));
1096         info.ei         = EI_MONITOR_CONTENDED_ENTER;
1097         info.thread     = thread;
1098         info.object     = object;
1099         /* get current location of contended monitor enter */
1100         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1101                 (gdata->jvmti, thread, 0, &method, &location);
1102         if (error == JVMTI_ERROR_NONE) {
1103             info.location = location;
1104             info.method   = method;
1105             info.clazz    = getMethodClass(jvmti_env, method);
1106         } else {
1107             info.location = -1;
1108         }
1109         event_callback(env, &info);
1110     } END_CALLBACK();
1111 
1112     LOG_MISC(("END cbMonitorContendedEnter"));
1113 }
1114 
1115 /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTERED */
1116 static void JNICALL
cbMonitorContendedEntered(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jobject object)1117 cbMonitorContendedEntered(jvmtiEnv *jvmti_env, JNIEnv *env,
1118                         jthread thread, jobject object)
1119 {
1120     EventInfo info;
1121     jvmtiError error;
1122     jmethodID  method;
1123     jlocation  location;
1124 
1125     LOG_CB(("cbMonitorContendedEntered: thread=%p", thread));
1126 
1127     BEGIN_CALLBACK() {
1128         (void)memset(&info,0,sizeof(info));
1129         info.ei         = EI_MONITOR_CONTENDED_ENTERED;
1130         info.thread     = thread;
1131         info.object     = object;
1132         /* get current location of contended monitor enter */
1133         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1134                 (gdata->jvmti, thread, 0, &method, &location);
1135         if (error == JVMTI_ERROR_NONE) {
1136             info.location = location;
1137             info.method   = method;
1138             info.clazz    = getMethodClass(jvmti_env, method);
1139         } else {
1140             info.location = -1;
1141         }
1142         event_callback(env, &info);
1143     } END_CALLBACK();
1144 
1145     LOG_MISC(("END cbMonitorContendedEntered"));
1146 }
1147 
1148 /* Event callback for JVMTI_EVENT_MONITOR_WAIT */
1149 static void JNICALL
cbMonitorWait(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jobject object,jlong timeout)1150 cbMonitorWait(jvmtiEnv *jvmti_env, JNIEnv *env,
1151                         jthread thread, jobject object,
1152                         jlong timeout)
1153 {
1154     EventInfo info;
1155     jvmtiError error;
1156     jmethodID  method;
1157     jlocation  location;
1158 
1159     LOG_CB(("cbMonitorWait: thread=%p", thread));
1160 
1161     BEGIN_CALLBACK() {
1162         (void)memset(&info,0,sizeof(info));
1163         info.ei         = EI_MONITOR_WAIT;
1164         info.thread     = thread;
1165         info.object     = object;
1166         /* The info.clazz is used for both class filtering and for location info.
1167          * For monitor wait event the class filtering is done for class of monitor
1168          * object. So here info.clazz is set to class of monitor object here and it
1169          * is reset to class of method before writing location info.
1170          * See writeMonitorEvent in eventHelper.c
1171          */
1172         info.clazz      = getObjectClass(object);
1173         info.u.monitor.timeout = timeout;
1174 
1175         /* get location of monitor wait() method. */
1176         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1177                 (gdata->jvmti, thread, 0, &method, &location);
1178         if (error == JVMTI_ERROR_NONE) {
1179             info.location = location;
1180             info.method   = method;
1181         } else {
1182             info.location = -1;
1183         }
1184         event_callback(env, &info);
1185     } END_CALLBACK();
1186 
1187     LOG_MISC(("END cbMonitorWait"));
1188 }
1189 
1190 /* Event callback for JVMTI_EVENT_MONITOR_WAIT */
1191 static void JNICALL
cbMonitorWaited(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread,jobject object,jboolean timed_out)1192 cbMonitorWaited(jvmtiEnv *jvmti_env, JNIEnv *env,
1193                         jthread thread, jobject object,
1194                         jboolean timed_out)
1195 {
1196     EventInfo info;
1197     jvmtiError error;
1198     jmethodID  method;
1199     jlocation  location;
1200 
1201     LOG_CB(("cbMonitorWaited: thread=%p", thread));
1202 
1203     BEGIN_CALLBACK() {
1204         (void)memset(&info,0,sizeof(info));
1205         info.ei         = EI_MONITOR_WAITED;
1206         info.thread     = thread;
1207         info.object     = object;
1208         /* The info.clazz is used for both class filtering and for location info.
1209          * For monitor waited event the class filtering is done for class of monitor
1210          * object. So here info.clazz is set to class of monitor object here and it
1211          * is reset to class of method before writing location info.
1212          * See writeMonitorEvent in eventHelper.c
1213          */
1214         info.clazz      = getObjectClass(object);
1215         info.u.monitor.timed_out = timed_out;
1216 
1217         /* get location of monitor wait() method */
1218         error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
1219                 (gdata->jvmti, thread, 0, &method, &location);
1220         if (error == JVMTI_ERROR_NONE) {
1221             info.location = location;
1222             info.method   = method;
1223         } else {
1224             info.location = -1;
1225         }
1226         event_callback(env, &info);
1227     } END_CALLBACK();
1228 
1229     LOG_MISC(("END cbMonitorWaited"));
1230 }
1231 
1232 /* Event callback for JVMTI_EVENT_VM_INIT */
1233 static void JNICALL
cbVMInit(jvmtiEnv * jvmti_env,JNIEnv * env,jthread thread)1234 cbVMInit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread)
1235 {
1236     EventInfo info;
1237 
1238     LOG_CB(("cbVMInit"));
1239 
1240     BEGIN_CALLBACK() {
1241         (void)memset(&info,0,sizeof(info));
1242         info.ei         = EI_VM_INIT;
1243         info.thread     = thread;
1244         event_callback(env, &info);
1245     } END_CALLBACK();
1246 
1247     LOG_MISC(("END cbVMInit"));
1248 }
1249 
1250 /* Event callback for JVMTI_EVENT_VM_DEATH */
1251 static void JNICALL
cbVMDeath(jvmtiEnv * jvmti_env,JNIEnv * env)1252 cbVMDeath(jvmtiEnv *jvmti_env, JNIEnv *env)
1253 {
1254     jvmtiError error;
1255     EventInfo info;
1256     LOG_CB(("cbVMDeath"));
1257 
1258     /* Clear out ALL callbacks at this time, we don't want any more. */
1259     /*    This should prevent any new BEGIN_CALLBACK() calls. */
1260     (void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));
1261     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)
1262                 (gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));
1263     if (error != JVMTI_ERROR_NONE) {
1264         EXIT_ERROR(error,"Can't clear event callbacks on vm death");
1265     }
1266 
1267     /* Now that no new callbacks will be made, we need to wait for the ones
1268      *   that are still active to complete.
1269      *   The BEGIN_CALLBACK/END_CALLBACK macros implement the VM_DEATH
1270      *   callback protocol. Once the callback table is cleared (above),
1271      *   we can have callback threads in different stages:
1272      *   1) after callback function entry and before BEGIN_CALLBACK
1273      *      macro; we catch these threads with callbackBlock in the
1274      *      BEGIN_CALLBACK macro
1275      *   2) after BEGIN_CALLBACK macro and before END_CALLBACK macro; we
1276      *      catch these threads with callbackBlock in the END_CALLBACK
1277      *      macro
1278      *   3) after END_CALLBACK macro; these threads have made it past
1279      *      callbackBlock and callbackLock and don't count as active
1280      *
1281      *   Since some of the callback threads could be blocked or suspended
1282      *   we will resume all threads suspended by the debugger for a short
1283      *   time to flush out all callbacks. Note that the callback threads
1284      *   will block from returning to the VM in both macros. Some threads
1285      *   not associated with callbacks, but suspended by the debugger may
1286      *   continue on, but not for long.
1287      *   Once the last callback finishes, it will notify this thread and
1288      *   we fall out of the loop below and actually process the VM_DEATH
1289      *   event.
1290      */
1291     debugMonitorEnter(callbackBlock); {
1292         debugMonitorEnter(callbackLock); {
1293             vm_death_callback_active = JNI_TRUE;
1294             (void)threadControl_resumeAll();
1295             while (active_callbacks > 0) {
1296                 /* wait for active CALLBACKs to check in (and block) */
1297                 debugMonitorWait(callbackLock);
1298             }
1299         } debugMonitorExit(callbackLock);
1300 
1301         /* Only now should we actually process the VM death event */
1302         (void)memset(&info,0,sizeof(info));
1303         info.ei                 = EI_VM_DEATH;
1304         event_callback(env, &info);
1305 
1306         /* Here we unblock all the callbacks and let them return to the
1307          *   VM.  It's not clear this is necessary, but leaving threads
1308          *   blocked doesn't seem like a good idea. They don't have much
1309          *   life left anyway.
1310          */
1311     } debugMonitorExit(callbackBlock);
1312 
1313     /*
1314      * The VM will die soon after the completion of this callback - we
1315      * may need to do a final synchronization with the command loop to
1316      * avoid the VM terminating with replying to the final (resume)
1317      * command.
1318      */
1319     debugLoop_sync();
1320 
1321     LOG_MISC(("END cbVMDeath"));
1322 }
1323 
1324 /**
1325  * Delete this handler (do not delete permanent handlers):
1326  * Deinsert handler from active list,
1327  * make it inactive, and free it's memory
1328  * Assumes handlerLock held.
1329  */
1330 static jvmtiError
freeHandler(HandlerNode * node)1331 freeHandler(HandlerNode *node) {
1332     jvmtiError error = JVMTI_ERROR_NONE;
1333 
1334     /* deinsert the handler node before disableEvents() to make
1335      * sure the event will be disabled when no other event
1336      * handlers are installed.
1337      */
1338     if (node != NULL && (!node->permanent)) {
1339         deinsert(node);
1340         error = eventFilterRestricted_deinstall(node);
1341         jvmtiDeallocate(node);
1342     }
1343 
1344     return error;
1345 }
1346 
1347 /**
1348  * Delete all the handlers on this chain (do not delete permanent handlers).
1349  * Assumes handlerLock held.
1350  */
1351 static jvmtiError
freeHandlerChain(HandlerChain * chain)1352 freeHandlerChain(HandlerChain *chain)
1353 {
1354     HandlerNode *node;
1355     jvmtiError   error;
1356 
1357     error = JVMTI_ERROR_NONE;
1358     node  = chain->first;
1359     while ( node != NULL ) {
1360         HandlerNode *next;
1361         jvmtiError   singleError;
1362 
1363         next = NEXT(node);
1364         singleError = freeHandler(node);
1365         if ( singleError != JVMTI_ERROR_NONE ) {
1366             error = singleError;
1367         }
1368         node = next;
1369     }
1370     return error;
1371 }
1372 
1373 /**
1374  * Deinsert and free all memory.  Safe for non-inserted nodes.
1375  */
1376 jvmtiError
eventHandler_free(HandlerNode * node)1377 eventHandler_free(HandlerNode *node)
1378 {
1379     jvmtiError error;
1380 
1381     debugMonitorEnter(handlerLock);
1382 
1383     error = freeHandler(node);
1384 
1385     debugMonitorExit(handlerLock);
1386 
1387     return error;
1388 }
1389 
1390 /**
1391  * Free all handlers of this kind created by the JDWP client,
1392  * that is, doesn't free handlers internally created by back-end.
1393  */
1394 jvmtiError
eventHandler_freeAll(EventIndex ei)1395 eventHandler_freeAll(EventIndex ei)
1396 {
1397     jvmtiError error = JVMTI_ERROR_NONE;
1398     HandlerNode *node;
1399 
1400     debugMonitorEnter(handlerLock);
1401     node = getHandlerChain(ei)->first;
1402     while (node != NULL) {
1403         HandlerNode *next = NEXT(node);    /* allows node removal */
1404         if (node->handlerID != 0) {        /* don't free internal handlers */
1405             error = freeHandler(node);
1406             if (error != JVMTI_ERROR_NONE) {
1407                 break;
1408             }
1409         }
1410         node = next;
1411     }
1412     debugMonitorExit(handlerLock);
1413     return error;
1414 }
1415 
1416 /***
1417  * Delete all breakpoints on "clazz".
1418  */
1419 void
eventHandler_freeClassBreakpoints(jclass clazz)1420 eventHandler_freeClassBreakpoints(jclass clazz)
1421 {
1422     HandlerNode *node;
1423     JNIEnv *env = getEnv();
1424 
1425     debugMonitorEnter(handlerLock);
1426     node = getHandlerChain(EI_BREAKPOINT)->first;
1427     while (node != NULL) {
1428         HandlerNode *next = NEXT(node); /* allows node removal */
1429         if (eventFilterRestricted_isBreakpointInClass(env, clazz,
1430                                                       node)) {
1431             (void)freeHandler(node);
1432         }
1433         node = next;
1434     }
1435     debugMonitorExit(handlerLock);
1436 }
1437 
1438 jvmtiError
eventHandler_freeByID(EventIndex ei,HandlerID handlerID)1439 eventHandler_freeByID(EventIndex ei, HandlerID handlerID)
1440 {
1441     jvmtiError error;
1442     HandlerNode *node;
1443 
1444     debugMonitorEnter(handlerLock);
1445     node = find(ei, handlerID);
1446     if (node != NULL) {
1447         error = freeHandler(node);
1448     } else {
1449         /* already freed */
1450         error = JVMTI_ERROR_NONE;
1451     }
1452     debugMonitorExit(handlerLock);
1453     return error;
1454 }
1455 
1456 void
eventHandler_initialize(jbyte sessionID)1457 eventHandler_initialize(jbyte sessionID)
1458 {
1459     jvmtiError error;
1460     jint i;
1461 
1462     requestIdCounter = 1;
1463     currentSessionID = sessionID;
1464 
1465     /* This is for BEGIN_CALLBACK/END_CALLBACK handling, make sure this
1466      *   is done while none of these callbacks are active.
1467      */
1468     active_callbacks = 0;
1469     vm_death_callback_active = JNI_FALSE;
1470     callbackLock = debugMonitorCreate("JDWP Callback Lock");
1471     callbackBlock = debugMonitorCreate("JDWP Callback Block");
1472 
1473     handlerLock = debugMonitorCreate("JDWP Event Handler Lock");
1474 
1475     for (i = EI_min; i <= EI_max; ++i) {
1476         getHandlerChain(i)->first = NULL;
1477     }
1478 
1479     /*
1480      * Permanently enabled some events.
1481      */
1482     error = threadControl_setEventMode(JVMTI_ENABLE,
1483                                       EI_VM_INIT, NULL);
1484     if (error != JVMTI_ERROR_NONE) {
1485         EXIT_ERROR(error,"Can't enable vm init events");
1486     }
1487     error = threadControl_setEventMode(JVMTI_ENABLE,
1488                                       EI_VM_DEATH, NULL);
1489     if (error != JVMTI_ERROR_NONE) {
1490         EXIT_ERROR(error,"Can't enable vm death events");
1491     }
1492     error = threadControl_setEventMode(JVMTI_ENABLE,
1493                                       EI_THREAD_START, NULL);
1494     if (error != JVMTI_ERROR_NONE) {
1495         EXIT_ERROR(error,"Can't enable thread start events");
1496     }
1497     error = threadControl_setEventMode(JVMTI_ENABLE,
1498                                        EI_THREAD_END, NULL);
1499     if (error != JVMTI_ERROR_NONE) {
1500         EXIT_ERROR(error,"Can't enable thread end events");
1501     }
1502     error = threadControl_setEventMode(JVMTI_ENABLE,
1503                                        EI_CLASS_PREPARE, NULL);
1504     if (error != JVMTI_ERROR_NONE) {
1505         EXIT_ERROR(error,"Can't enable class prepare events");
1506     }
1507     error = threadControl_setEventMode(JVMTI_ENABLE,
1508                                        EI_GC_FINISH, NULL);
1509     if (error != JVMTI_ERROR_NONE) {
1510         EXIT_ERROR(error,"Can't enable garbage collection finish events");
1511     }
1512     /* ANDROID-CHANGED: Permanently enable object free for common-ref tracking */
1513     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventNotificationMode)
1514                 (gdata->jvmti, JVMTI_ENABLE, JVMTI_EVENT_OBJECT_FREE, NULL);
1515     if (error != JVMTI_ERROR_NONE) {
1516         EXIT_ERROR(error,"Can't enable object free events");
1517     }
1518 
1519     (void)memset(&(gdata->callbacks),0,sizeof(gdata->callbacks));
1520     /* ANDROID-CHANGED: Event callback for common-ref tracking */
1521     gdata->callbacks.ObjectFree                 = &cbObjectFree;
1522     /* Event callback for JVMTI_EVENT_SINGLE_STEP */
1523     gdata->callbacks.SingleStep                 = &cbSingleStep;
1524     /* Event callback for JVMTI_EVENT_BREAKPOINT */
1525     gdata->callbacks.Breakpoint                 = &cbBreakpoint;
1526     /* Event callback for JVMTI_EVENT_FRAME_POP */
1527     gdata->callbacks.FramePop                   = &cbFramePop;
1528     /* Event callback for JVMTI_EVENT_EXCEPTION */
1529     gdata->callbacks.Exception                  = &cbException;
1530     /* Event callback for JVMTI_EVENT_THREAD_START */
1531     gdata->callbacks.ThreadStart                = &cbThreadStart;
1532     /* Event callback for JVMTI_EVENT_THREAD_END */
1533     gdata->callbacks.ThreadEnd                  = &cbThreadEnd;
1534     /* Event callback for JVMTI_EVENT_CLASS_PREPARE */
1535     gdata->callbacks.ClassPrepare               = &cbClassPrepare;
1536     /* Event callback for JVMTI_EVENT_CLASS_LOAD */
1537     gdata->callbacks.ClassLoad                  = &cbClassLoad;
1538     /* Event callback for JVMTI_EVENT_FIELD_ACCESS */
1539     gdata->callbacks.FieldAccess                = &cbFieldAccess;
1540     /* Event callback for JVMTI_EVENT_FIELD_MODIFICATION */
1541     gdata->callbacks.FieldModification          = &cbFieldModification;
1542     /* Event callback for JVMTI_EVENT_EXCEPTION_CATCH */
1543     gdata->callbacks.ExceptionCatch             = &cbExceptionCatch;
1544     /* Event callback for JVMTI_EVENT_METHOD_ENTRY */
1545     gdata->callbacks.MethodEntry                = &cbMethodEntry;
1546     /* Event callback for JVMTI_EVENT_METHOD_EXIT */
1547     gdata->callbacks.MethodExit                 = &cbMethodExit;
1548     /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTER */
1549     gdata->callbacks.MonitorContendedEnter      = &cbMonitorContendedEnter;
1550     /* Event callback for JVMTI_EVENT_MONITOR_CONTENDED_ENTERED */
1551     gdata->callbacks.MonitorContendedEntered    = &cbMonitorContendedEntered;
1552     /* Event callback for JVMTI_EVENT_MONITOR_WAIT */
1553     gdata->callbacks.MonitorWait                = &cbMonitorWait;
1554     /* Event callback for JVMTI_EVENT_MONITOR_WAITED */
1555     gdata->callbacks.MonitorWaited              = &cbMonitorWaited;
1556     /* Event callback for JVMTI_EVENT_VM_INIT */
1557     gdata->callbacks.VMInit                     = &cbVMInit;
1558     /* Event callback for JVMTI_EVENT_VM_DEATH */
1559     gdata->callbacks.VMDeath                    = &cbVMDeath;
1560     /* Event callback for JVMTI_EVENT_GARBAGE_COLLECTION_FINISH */
1561     gdata->callbacks.GarbageCollectionFinish    = &cbGarbageCollectionFinish;
1562 
1563     error = JVMTI_FUNC_PTR(gdata->jvmti,SetEventCallbacks)
1564                 (gdata->jvmti, &(gdata->callbacks), sizeof(gdata->callbacks));
1565     if (error != JVMTI_ERROR_NONE) {
1566         EXIT_ERROR(error,"Can't set event callbacks");
1567     }
1568 
1569     /* Notify other modules that the event callbacks are in place */
1570     threadControl_onHook();
1571 
1572     /* Get the event helper thread initialized */
1573     eventHelper_initialize(sessionID);
1574 }
1575 
1576 void
eventHandler_reset(jbyte sessionID)1577 eventHandler_reset(jbyte sessionID)
1578 {
1579     int i;
1580 
1581     debugMonitorEnter(handlerLock);
1582 
1583     /* We must do this first so that if any invokes complete,
1584      * there will be no attempt to send them to the front
1585      * end. Waiting for threadControl_reset leaves a window where
1586      * the invoke completions can sneak through.
1587      */
1588     threadControl_detachInvokes();
1589 
1590     /* Reset the event helper thread, purging all queued and
1591      * in-process commands.
1592      */
1593     eventHelper_reset(sessionID);
1594 
1595     /* delete all handlers */
1596     for (i = EI_min; i <= EI_max; i++) {
1597         (void)freeHandlerChain(getHandlerChain(i));
1598     }
1599 
1600     requestIdCounter = 1;
1601     currentSessionID = sessionID;
1602 
1603     debugMonitorExit(handlerLock);
1604 }
1605 
1606 void
eventHandler_lock(void)1607 eventHandler_lock(void)
1608 {
1609     debugMonitorEnter(handlerLock);
1610 }
1611 
1612 void
eventHandler_unlock(void)1613 eventHandler_unlock(void)
1614 {
1615     debugMonitorExit(handlerLock);
1616 }
1617 
1618 /***** handler creation *****/
1619 
1620 HandlerNode *
eventHandler_alloc(jint filterCount,EventIndex ei,jbyte suspendPolicy)1621 eventHandler_alloc(jint filterCount, EventIndex ei, jbyte suspendPolicy)
1622 {
1623     HandlerNode *node = eventFilterRestricted_alloc(filterCount);
1624 
1625     if (node != NULL) {
1626         node->ei = ei;
1627         node->suspendPolicy = suspendPolicy;
1628         node->permanent = JNI_FALSE;
1629     }
1630 
1631     return node;
1632 }
1633 
1634 
1635 HandlerID
eventHandler_allocHandlerID(void)1636 eventHandler_allocHandlerID(void)
1637 {
1638     jint handlerID;
1639     debugMonitorEnter(handlerLock);
1640     handlerID = ++requestIdCounter;
1641     debugMonitorExit(handlerLock);
1642     return handlerID;
1643 }
1644 
1645 
1646 static jvmtiError
installHandler(HandlerNode * node,HandlerFunction func,jboolean external)1647 installHandler(HandlerNode *node,
1648               HandlerFunction func,
1649               jboolean external)
1650 {
1651     jvmtiError error;
1652 
1653     if ( func == NULL ) {
1654         return AGENT_ERROR_INVALID_EVENT_TYPE;
1655     }
1656 
1657     debugMonitorEnter(handlerLock);
1658 
1659     HANDLER_FUNCTION(node) = func;
1660 
1661     node->handlerID = external? ++requestIdCounter : 0;
1662     error = eventFilterRestricted_install(node);
1663     if (error == JVMTI_ERROR_NONE) {
1664         insert(getHandlerChain(node->ei), node);
1665     }
1666 
1667     debugMonitorExit(handlerLock);
1668 
1669     return error;
1670 }
1671 
1672 static HandlerNode *
createInternal(EventIndex ei,HandlerFunction func,jthread thread,jclass clazz,jmethodID method,jlocation location,jboolean permanent)1673 createInternal(EventIndex ei, HandlerFunction func,
1674                jthread thread, jclass clazz, jmethodID method,
1675                jlocation location, jboolean permanent)
1676 {
1677     jint index = 0;
1678     jvmtiError error = JVMTI_ERROR_NONE;
1679     HandlerNode *node;
1680 
1681     /*
1682      * Start with necessary allocations
1683      */
1684     node = eventHandler_alloc(
1685         ((thread == NULL)? 0 : 1) + ((clazz == NULL)? 0 : 1),
1686         ei, JDWP_SUSPEND_POLICY(NONE));
1687     if (node == NULL) {
1688         return NULL;
1689     }
1690 
1691     node->permanent = permanent;
1692 
1693     if (thread != NULL) {
1694         error = eventFilter_setThreadOnlyFilter(node, index++, thread);
1695     }
1696 
1697     if ((error == JVMTI_ERROR_NONE) && (clazz != NULL)) {
1698         error = eventFilter_setLocationOnlyFilter(node, index++, clazz,
1699                                                   method, location);
1700     }
1701     /*
1702      * Create the new handler node
1703      */
1704     error = installHandler(node, func, JNI_FALSE);
1705 
1706     if (error != JVMTI_ERROR_NONE) {
1707         (void)eventHandler_free(node);
1708         node = NULL;
1709     }
1710     return node;
1711 }
1712 
1713 HandlerNode *
eventHandler_createPermanentInternal(EventIndex ei,HandlerFunction func)1714 eventHandler_createPermanentInternal(EventIndex ei, HandlerFunction func)
1715 {
1716     return createInternal(ei, func, NULL,
1717                           NULL, NULL, (jlocation)NULL, JNI_TRUE);
1718 }
1719 
1720 HandlerNode *
eventHandler_createInternalThreadOnly(EventIndex ei,HandlerFunction func,jthread thread)1721 eventHandler_createInternalThreadOnly(EventIndex ei,
1722                                       HandlerFunction func,
1723                                       jthread thread)
1724 {
1725     return createInternal(ei, func, thread,
1726                           NULL, NULL, (jlocation)NULL, JNI_FALSE);
1727 }
1728 
1729 HandlerNode *
eventHandler_createInternalBreakpoint(HandlerFunction func,jthread thread,jclass clazz,jmethodID method,jlocation location)1730 eventHandler_createInternalBreakpoint(HandlerFunction func,
1731                                       jthread thread,
1732                                       jclass clazz,
1733                                       jmethodID method,
1734                                       jlocation location)
1735 {
1736     return createInternal(EI_BREAKPOINT, func, thread,
1737                           clazz, method, location, JNI_FALSE);
1738 }
1739 
1740 jvmtiError
eventHandler_installExternal(HandlerNode * node)1741 eventHandler_installExternal(HandlerNode *node)
1742 {
1743     return installHandler(node,
1744                           standardHandlers_defaultHandler(node->ei),
1745                           JNI_TRUE);
1746 }
1747