1 /*
2 * Copyright (c) 1998, 2013, 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 #if defined(_ALLBSD_SOURCE)
27 #include <stdint.h> /* for uintptr_t */
28 #endif
29
30 #include "util.h"
31 #include "commonRef.h"
32
33 /*
34 * ANDROID-CHANGED: This was modified for android to avoid any use of weak
35 * global (jweak) references. On Android hosts the number of jweak
36 * references active at any one time is limited. By using jweaks to keep
37 * track of objects here we could hit the jweak limit on some very large
38 * apps. The implementation is compatible with any JVMTI implementation
39 * that provides the 'can_tag_objects' and
40 * 'can_generate_object_free_events' capabilities. This works by watching
41 * for the ObjectFree events on tagged objects and storing them in a list
42 * of things that have been deleted.
43 *
44 * Each object sent to the front end is tracked with the RefNode struct
45 * (see util.h).
46 * External to this module, objects are identified by a jlong id which is
47 * simply the sequence number. A JVMTI tag is usually used so that
48 * the presence of a debugger-tracked object will not prevent
49 * its collection. Once an object is collected, its RefNode may be
50 * deleted (these may happen in * either order). Using the sequence number
51 * as the object id prevents ambiguity in the object id when the weak ref
52 * is reused. The RefNode* is stored with the object as it's JVMTI Tag.
53 * This tag also provides the weak-reference behavior.
54 *
55 * The ref member is changed from weak to strong when gc of the object is
56 * to be prevented. Whether or not it is strong, it is never exported
57 * from this module.
58 *
59 * A reference count of each jobject is also maintained here. It tracks
60 * the number times an object has been referenced through
61 * commonRef_refToID. A RefNode is freed once the reference
62 * count is decremented to 0 (with commonRef_release*), even if the
63 * corresponding object has not been collected.
64 *
65 * One hash table is maintained. The mapping of ID to RefNode* is handled
66 * with one hash table that will re-size itself as the number of RefNode's
67 * grow.
68 */
69
70 /* Initial hash table size (must be power of 2) */
71 #define HASH_INIT_SIZE 512
72 /* If element count exceeds HASH_EXPAND_SCALE*hash_size we expand & re-hash */
73 #define HASH_EXPAND_SCALE 8
74 /* Maximum hash table size (must be power of 2) */
75 #define HASH_MAX_SIZE (1024*HASH_INIT_SIZE)
76
77 /* Map a key (ID) to a hash bucket */
78 static jint
hashBucket(jlong key)79 hashBucket(jlong key)
80 {
81 /* Size should always be a power of 2, use mask instead of mod operator */
82 /*LINTED*/
83 return ((jint)key) & (gdata->objectsByIDsize-1);
84 }
85
86 /* Generate a new ID */
87 static jlong
newSeqNum(void)88 newSeqNum(void)
89 {
90 return gdata->nextSeqNum++;
91 }
92
93 /* ANDROID-CHANGED: This helper function is unique to android.
94 * This function gets a local-ref to object the node is pointing to. If the node's object has been
95 * collected it will return NULL. The caller is responsible for calling env->DeleteLocalRef or
96 * env->PopLocalFrame to clean up the reference. This function makes no changes to the passed in
97 * node.
98 */
99 static jobject
getLocalRef(JNIEnv * env,const RefNode * node)100 getLocalRef(JNIEnv *env, const RefNode* node) {
101 if (node->isStrong) {
102 return JNI_FUNC_PTR(env,NewLocalRef)(env, node->ref);
103 }
104 jint count = -1;
105 jobject *objects = NULL;
106 jlong tag = ptr_to_jlong(node);
107 jvmtiError error = JVMTI_FUNC_PTR(gdata->jvmti,GetObjectsWithTags)
108 (gdata->jvmti, 1, &tag, &count, &objects, NULL);
109 if (error != JVMTI_ERROR_NONE) {
110 EXIT_ERROR(error,"GetObjectsWithTags");
111 }
112 if (count != 1 && count != 0) {
113 EXIT_ERROR(AGENT_ERROR_INTERNAL,
114 "GetObjectsWithTags returned multiple objects unexpectedly");
115 }
116 jobject res = (count == 0) ? NULL : objects[0];
117 JVMTI_FUNC_PTR(gdata->jvmti,Deallocate)(gdata->jvmti,(unsigned char*)objects);
118 return res;
119 }
120
121 /* ANDROID-CHANGED: Handler function for objects being freed. */
commonRef_handleFreedObject(jlong tag)122 void commonRef_handleFreedObject(jlong tag) {
123 RefNode* node = (RefNode*)jlong_to_ptr(tag);
124 debugMonitorEnterNoSuspend(gdata->refLock); {
125 // Delete the node and remove it from the hashmap.
126 // If we raced with a deleteNode call and lost the next and prev will be null but we will
127 // not be at the start of the bucket. This is fine.
128 jint slot = hashBucket(node->seqNum);
129 if (node->next != NULL ||
130 node->prev != NULL ||
131 gdata->objectsByID[slot] == node) {
132 /* Detach from id hash table */
133 if (node->prev == NULL) {
134 gdata->objectsByID[slot] = node->next;
135 } else {
136 node->prev->next = node->next;
137 }
138 /* Also fixup back links. */
139 if (node->next != NULL) {
140 node->next->prev = node->prev;
141 }
142 gdata->objectsByIDcount--;
143 }
144 jvmtiDeallocate(node);
145 } debugMonitorExit(gdata->refLock);
146 }
147
148 /* Create a fresh RefNode structure, and tag the object (creating a weak-ref to it).
149 * ANDROID-CHANGED: The definition of RefNode was changed slightly so that node->ref is only for
150 * a strong reference. For weak references we use the node as a tag on the object to keep track if
151 * it.
152 * ANDROID-CHANGED: ref must be a local-reference held live for the duration of this method until it
153 * is fully in the objectByID map.
154 */
155 static RefNode *
createNode(JNIEnv * env,jobject ref)156 createNode(JNIEnv *env, jobject ref)
157 {
158 RefNode *node;
159 jvmtiError error;
160
161 if (ref == NULL) {
162 return NULL;
163 }
164
165 /* Could allocate RefNode's in blocks, not sure it would help much */
166 node = (RefNode*)jvmtiAllocate((int)sizeof(RefNode));
167 if (node == NULL) {
168 return NULL;
169 }
170
171 /* ANDROID-CHANGED: Use local reference to make sure we have a reference. We will use this
172 * reference to set a tag to the node to use as a weak-reference and keep track of the ref.
173 * ANDROID-CHANGED: Set node tag on the ref. This tag now functions as the weak-reference to the
174 * object.
175 */
176 error = JVMTI_FUNC_PTR(gdata->jvmti, SetTag)(gdata->jvmti, ref, ptr_to_jlong(node));
177 if ( error != JVMTI_ERROR_NONE ) {
178 jvmtiDeallocate(node);
179 return NULL;
180 }
181
182 /* Fill in RefNode */
183 node->ref = NULL;
184 node->isStrong = JNI_FALSE;
185 node->count = 1;
186 node->seqNum = newSeqNum();
187
188 /* Count RefNode's created */
189 gdata->objectsByIDcount++;
190 return node;
191 }
192
193 /* Delete a RefNode allocation, delete weak/global ref and clear tag */
194 static void
deleteNode(JNIEnv * env,RefNode * node)195 deleteNode(JNIEnv *env, RefNode *node)
196 {
197 /* ANDROID-CHANGED: use getLocalRef to get a local reference to the node. */
198 WITH_LOCAL_REFS(env, 1) {
199 jobject localRef = getLocalRef(env, node);
200 LOG_MISC(("Freeing %d\n", (int)node->seqNum));
201
202 /* Detach from id hash table */
203 if (node->prev == NULL) {
204 gdata->objectsByID[hashBucket(node->seqNum)] = node->next;
205 } else {
206 node->prev->next = node->next;
207 }
208 /* Also fixup back links. */
209 if (node->next != NULL) {
210 node->next->prev = node->prev;
211 }
212
213 // If we don't get the localref that means the ObjectFree event is being called and the
214 // node will be deleted there.
215 if ( localRef != NULL ) {
216 /* Clear tag */
217 (void)JVMTI_FUNC_PTR(gdata->jvmti,SetTag)
218 (gdata->jvmti, localRef, NULL_OBJECT_ID);
219 if (node->isStrong) {
220 JNI_FUNC_PTR(env,DeleteGlobalRef)(env, node->ref);
221 }
222
223 jvmtiDeallocate(node);
224 } else {
225 // We are going to let the object-free do the final work. Mark this node as not in the
226 // list with both null links but not in the bucket.
227 node->prev = NULL;
228 node->next = NULL;
229 }
230 gdata->objectsByIDcount--;
231 } END_WITH_LOCAL_REFS(env);
232 }
233
234 /* Change a RefNode to have a strong reference */
235 static jobject
strengthenNode(JNIEnv * env,RefNode * node)236 strengthenNode(JNIEnv *env, RefNode *node)
237 {
238 if (!node->isStrong) {
239 /* ANDROID-CHANGED: We need to find and fill in the node->ref when we strengthen a node. */
240 WITH_LOCAL_REFS(env, 1) {
241 /* getLocalRef will return NULL if the referent has been collected. */
242 jobject localRef = getLocalRef(env, node);
243 if (localRef != NULL) {
244 node->ref = JNI_FUNC_PTR(env,NewGlobalRef)(env, localRef);
245 if (node->ref == NULL) {
246 EXIT_ERROR(AGENT_ERROR_NULL_POINTER,"NewGlobalRef");
247 }
248 node->isStrong = JNI_TRUE;
249 }
250 } END_WITH_LOCAL_REFS(env);
251 }
252 return node->ref;
253 }
254
255 /* Change a RefNode to have a weak reference
256 * ANDROID-CHANGED: This is done by deleting the strong reference. We already have a tag in
257 * to the node from when we created the node. Since this is never removed we can simply delete the
258 * global ref, reset node->isStrong & node->ref, and return. Since no part of this can fail we can
259 * change this function to be void too.
260 */
261 static void
weakenNode(JNIEnv * env,RefNode * node)262 weakenNode(JNIEnv *env, RefNode *node)
263 {
264 if (node->isStrong) {
265 JNI_FUNC_PTR(env,DeleteGlobalRef)(env, node->ref);
266 node->ref = NULL;
267 node->isStrong = JNI_FALSE;
268 }
269 }
270
271 /*
272 * Returns the node which contains the common reference for the
273 * given object. The passed reference should not be a weak reference
274 * managed in the object hash table (i.e. returned by commonRef_idToRef)
275 * because no sequence number checking is done.
276 */
277 static RefNode *
findNodeByRef(JNIEnv * env,jobject ref)278 findNodeByRef(JNIEnv *env, jobject ref)
279 {
280 jvmtiError error;
281 jlong tag;
282
283 tag = NULL_OBJECT_ID;
284 error = JVMTI_FUNC_PTR(gdata->jvmti,GetTag)(gdata->jvmti, ref, &tag);
285 if ( error == JVMTI_ERROR_NONE ) {
286 RefNode *node;
287
288 node = (RefNode*)jlong_to_ptr(tag);
289 return node;
290 }
291 return NULL;
292 }
293
294 /* Locate and delete a node based on ID */
295 static void
deleteNodeByID(JNIEnv * env,jlong id,jint refCount)296 deleteNodeByID(JNIEnv *env, jlong id, jint refCount)
297 {
298 /* ANDROID-CHANGED: Rewrite for double-linked list. Also remove ALL_REFS since it's not needed
299 * since the free-callback will do the work of cleaning up when an object gets collected. */
300 jint slot;
301 RefNode *node;
302
303 slot = hashBucket(id);
304 node = gdata->objectsByID[slot];
305
306 while (node != NULL) {
307 if (id == node->seqNum) {
308 node->count -= refCount;
309 if (node->count <= 0) {
310 if ( node->count < 0 ) {
311 EXIT_ERROR(AGENT_ERROR_INTERNAL,"RefNode count < 0");
312 }
313 deleteNode(env, node);
314 }
315 break;
316 }
317 node = node->next;
318 }
319 }
320
321 /*
322 * Returns the node stored in the object hash table for the given object
323 * id. The id should be a value previously returned by
324 * commonRef_refToID.
325 *
326 * NOTE: It is possible that a match is found here, but that the object
327 * is garbage collected by the time the caller inspects node->ref.
328 * Callers should take care using the node->ref object returned here.
329 *
330 */
331 static RefNode *
findNodeByID(JNIEnv * env,jlong id)332 findNodeByID(JNIEnv *env, jlong id)
333 {
334 /* ANDROID-CHANGED: Rewrite for double-linked list */
335 jint slot;
336 RefNode *node;
337
338 slot = hashBucket(id);
339 node = gdata->objectsByID[slot];
340
341 while (node != NULL) {
342 if ( id == node->seqNum ) {
343 if ( node->prev != NULL ) {
344 /* Re-order hash list so this one is up front */
345 node->prev->next = node->next;
346 if (node->next != NULL) {
347 node->next->prev = node->prev;
348 }
349 node->next = gdata->objectsByID[slot];
350 node->next->prev = node;
351 node->prev = NULL;
352 gdata->objectsByID[slot] = node;
353 }
354 break;
355 }
356 node = node->next;
357 }
358 return node;
359 }
360
361 /* Initialize the hash table stored in gdata area */
362 static void
initializeObjectsByID(int size)363 initializeObjectsByID(int size)
364 {
365 /* Size should always be a power of 2 */
366 if ( size > HASH_MAX_SIZE ) size = HASH_MAX_SIZE;
367 gdata->objectsByIDsize = size;
368 gdata->objectsByIDcount = 0;
369 gdata->objectsByID = (RefNode**)jvmtiAllocate((int)sizeof(RefNode*)*size);
370 (void)memset(gdata->objectsByID, 0, (int)sizeof(RefNode*)*size);
371 }
372
373 /* hash in a RefNode */
374 static void
hashIn(RefNode * node)375 hashIn(RefNode *node)
376 {
377 /* ANDROID-CHANGED: Modify for double-linked list */
378 jint slot;
379
380 /* Add to id hashtable */
381 slot = hashBucket(node->seqNum);
382 node->next = gdata->objectsByID[slot];
383 node->prev = NULL;
384 if (node->next != NULL) {
385 node->next->prev = node;
386 }
387 gdata->objectsByID[slot] = node;
388 }
389
390 /* Allocate and add RefNode to hash table
391 * ANDROID-CHANGED: Requires that ref be a held-live local ref.*/
392 static RefNode *
newCommonRef(JNIEnv * env,jobject ref)393 newCommonRef(JNIEnv *env, jobject ref)
394 {
395 RefNode *node;
396
397 /* Allocate the node and set it up */
398 node = createNode(env, ref);
399 if ( node == NULL ) {
400 return NULL;
401 }
402
403 /* See if hash table needs expansion */
404 if ( gdata->objectsByIDcount > gdata->objectsByIDsize*HASH_EXPAND_SCALE &&
405 gdata->objectsByIDsize < HASH_MAX_SIZE ) {
406 RefNode **old;
407 int oldsize;
408 int newsize;
409 int i;
410
411 /* Save old information */
412 old = gdata->objectsByID;
413 oldsize = gdata->objectsByIDsize;
414 /* Allocate new hash table */
415 gdata->objectsByID = NULL;
416 newsize = oldsize*HASH_EXPAND_SCALE;
417 if ( newsize > HASH_MAX_SIZE ) newsize = HASH_MAX_SIZE;
418 initializeObjectsByID(newsize);
419 /* Walk over old one and hash in all the RefNodes */
420 for ( i = 0 ; i < oldsize ; i++ ) {
421 RefNode *onode;
422
423 onode = old[i];
424 while (onode != NULL) {
425 RefNode *next;
426
427 next = onode->next;
428 hashIn(onode);
429 onode = next;
430 }
431 }
432 jvmtiDeallocate(old);
433 }
434
435 /* Add to id hashtable */
436 hashIn(node);
437 return node;
438 }
439
440 /* Initialize the commonRefs usage */
441 void
commonRef_initialize(void)442 commonRef_initialize(void)
443 {
444 gdata->refLock = debugMonitorCreate("JDWP Reference Table Monitor");
445 gdata->nextSeqNum = 1; /* 0 used for error indication */
446 initializeObjectsByID(HASH_INIT_SIZE);
447 }
448
449 /* Reset the commonRefs usage */
450 void
commonRef_reset(JNIEnv * env)451 commonRef_reset(JNIEnv *env)
452 {
453 debugMonitorEnter(gdata->refLock); {
454 int i;
455
456 for (i = 0; i < gdata->objectsByIDsize; i++) {
457 RefNode *node;
458
459 for (node = gdata->objectsByID[i]; node != NULL; node = gdata->objectsByID[i]) {
460 deleteNode(env, node);
461 }
462 gdata->objectsByID[i] = NULL;
463 }
464
465 /* Toss entire hash table and re-create a new one */
466 jvmtiDeallocate(gdata->objectsByID);
467 gdata->objectsByID = NULL;
468 gdata->nextSeqNum = 1; /* 0 used for error indication */
469 initializeObjectsByID(HASH_INIT_SIZE);
470
471 } debugMonitorExit(gdata->refLock);
472 }
473
474 /*
475 * Given a reference obtained from JNI or JVMTI, return an object
476 * id suitable for sending to the debugger front end.
477 */
478 jlong
commonRef_refToID(JNIEnv * env,jobject ref)479 commonRef_refToID(JNIEnv *env, jobject ref)
480 {
481 jlong id;
482
483 if (ref == NULL) {
484 return NULL_OBJECT_ID;
485 }
486
487 id = NULL_OBJECT_ID;
488 debugMonitorEnter(gdata->refLock); {
489 RefNode *node;
490
491 node = findNodeByRef(env, ref);
492 if (node == NULL) {
493 WITH_LOCAL_REFS(env, 1) {
494 node = newCommonRef(env, JNI_FUNC_PTR(env,NewLocalRef)(env, ref));
495 if ( node != NULL ) {
496 id = node->seqNum;
497 }
498 } END_WITH_LOCAL_REFS(env);
499 } else {
500 id = node->seqNum;
501 node->count++;
502 }
503 } debugMonitorExit(gdata->refLock);
504 return id;
505 }
506
507 /*
508 * Given an object ID obtained from the debugger front end, return a
509 * strong, global reference to that object (or NULL if the object
510 * has been collected). The reference can then be used for JNI and
511 * JVMTI calls. Caller is resposible for deleting the returned reference.
512 */
513 jobject
commonRef_idToRef(JNIEnv * env,jlong id)514 commonRef_idToRef(JNIEnv *env, jlong id)
515 {
516 jobject ref;
517
518 ref = NULL;
519 debugMonitorEnter(gdata->refLock); {
520 RefNode *node;
521
522 node = findNodeByID(env, id);
523 if (node != NULL) {
524 if (node->isStrong) {
525 saveGlobalRef(env, node->ref, &ref);
526 } else {
527 jobject lref;
528
529 /* ANDROID-CHANGED: Use getLocalRef helper to get a local-reference to the object
530 * this node weakly points to. It will return NULL if the object has been GCd
531 */
532 lref = getLocalRef(env, node);
533 if ( lref != NULL ) {
534 /* ANDROID-CHANGED: Use lref to save the global ref since that is the only real
535 * jobject we have.
536 */
537 saveGlobalRef(env, lref, &ref);
538 JNI_FUNC_PTR(env,DeleteLocalRef)(env, lref);
539 }
540 /* ANDROID-CHANGED: Otherwise the object was GC'd shortly after we found the node.
541 * The free callback will deal with cleanup once we return.
542 */
543 }
544 }
545 } debugMonitorExit(gdata->refLock);
546 return ref;
547 }
548
549 /* Deletes the global reference that commonRef_idToRef() created */
550 void
commonRef_idToRef_delete(JNIEnv * env,jobject ref)551 commonRef_idToRef_delete(JNIEnv *env, jobject ref)
552 {
553 if ( ref==NULL ) {
554 return;
555 }
556 tossGlobalRef(env, &ref);
557 }
558
559
560 /* Prevent garbage collection of an object */
561 jvmtiError
commonRef_pin(jlong id)562 commonRef_pin(jlong id)
563 {
564 jvmtiError error;
565
566 error = JVMTI_ERROR_NONE;
567 if (id == NULL_OBJECT_ID) {
568 return error;
569 }
570 debugMonitorEnter(gdata->refLock); {
571 JNIEnv *env;
572 RefNode *node;
573
574 env = getEnv();
575 node = findNodeByID(env, id);
576 if (node == NULL) {
577 error = AGENT_ERROR_INVALID_OBJECT;
578 } else {
579 jobject strongRef;
580
581 strongRef = strengthenNode(env, node);
582 if (strongRef == NULL) {
583 /*
584 * Referent has been collected, clean up now.
585 * ANDROID-CHANGED: The node will be cleaned up by the object-free callback.
586 */
587 error = AGENT_ERROR_INVALID_OBJECT;
588 }
589 }
590 } debugMonitorExit(gdata->refLock);
591 return error;
592 }
593
594 /* Permit garbage collection of an object */
595 jvmtiError
commonRef_unpin(jlong id)596 commonRef_unpin(jlong id)
597 {
598 jvmtiError error;
599
600 error = JVMTI_ERROR_NONE;
601 debugMonitorEnter(gdata->refLock); {
602 JNIEnv *env;
603 RefNode *node;
604
605 env = getEnv();
606 node = findNodeByID(env, id);
607 if (node != NULL) {
608 // ANDROID-CHANGED: weakenNode was changed to never fail.
609 weakenNode(env, node);
610 }
611 } debugMonitorExit(gdata->refLock);
612 return error;
613 }
614
615 /* Release tracking of an object by ID */
616 void
commonRef_release(JNIEnv * env,jlong id)617 commonRef_release(JNIEnv *env, jlong id)
618 {
619 debugMonitorEnter(gdata->refLock); {
620 deleteNodeByID(env, id, 1);
621 } debugMonitorExit(gdata->refLock);
622 }
623
624 void
commonRef_releaseMultiple(JNIEnv * env,jlong id,jint refCount)625 commonRef_releaseMultiple(JNIEnv *env, jlong id, jint refCount)
626 {
627 debugMonitorEnter(gdata->refLock); {
628 deleteNodeByID(env, id, refCount);
629 } debugMonitorExit(gdata->refLock);
630 }
631
632 /* Get rid of RefNodes for objects that no longer exist */
633 void
commonRef_compact(void)634 commonRef_compact(void)
635 {
636 // NO-OP.
637 }
638
639 /* Lock the commonRef tables */
640 void
commonRef_lock(void)641 commonRef_lock(void)
642 {
643 debugMonitorEnter(gdata->refLock);
644 }
645
646 /* Unlock the commonRef tables */
647 void
commonRef_unlock(void)648 commonRef_unlock(void)
649 {
650 debugMonitorExit(gdata->refLock);
651 }
652