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 node->prev->prev = node->prev;
347 node->next = gdata->objectsByID[slot];
348 node->next->prev = node;
349 node->prev = NULL;
350 gdata->objectsByID[slot] = node;
351 }
352 break;
353 }
354 node = node->next;
355 }
356 return node;
357 }
358
359 /* Initialize the hash table stored in gdata area */
360 static void
initializeObjectsByID(int size)361 initializeObjectsByID(int size)
362 {
363 /* Size should always be a power of 2 */
364 if ( size > HASH_MAX_SIZE ) size = HASH_MAX_SIZE;
365 gdata->objectsByIDsize = size;
366 gdata->objectsByIDcount = 0;
367 gdata->objectsByID = (RefNode**)jvmtiAllocate((int)sizeof(RefNode*)*size);
368 (void)memset(gdata->objectsByID, 0, (int)sizeof(RefNode*)*size);
369 }
370
371 /* hash in a RefNode */
372 static void
hashIn(RefNode * node)373 hashIn(RefNode *node)
374 {
375 /* ANDROID-CHANGED: Modify for double-linked list */
376 jint slot;
377
378 /* Add to id hashtable */
379 slot = hashBucket(node->seqNum);
380 node->next = gdata->objectsByID[slot];
381 node->prev = NULL;
382 if (node->next != NULL) {
383 node->next->prev = node;
384 }
385 gdata->objectsByID[slot] = node;
386 }
387
388 /* Allocate and add RefNode to hash table
389 * ANDROID-CHANGED: Requires that ref be a held-live local ref.*/
390 static RefNode *
newCommonRef(JNIEnv * env,jobject ref)391 newCommonRef(JNIEnv *env, jobject ref)
392 {
393 RefNode *node;
394
395 /* Allocate the node and set it up */
396 node = createNode(env, ref);
397 if ( node == NULL ) {
398 return NULL;
399 }
400
401 /* See if hash table needs expansion */
402 if ( gdata->objectsByIDcount > gdata->objectsByIDsize*HASH_EXPAND_SCALE &&
403 gdata->objectsByIDsize < HASH_MAX_SIZE ) {
404 RefNode **old;
405 int oldsize;
406 int newsize;
407 int i;
408
409 /* Save old information */
410 old = gdata->objectsByID;
411 oldsize = gdata->objectsByIDsize;
412 /* Allocate new hash table */
413 gdata->objectsByID = NULL;
414 newsize = oldsize*HASH_EXPAND_SCALE;
415 if ( newsize > HASH_MAX_SIZE ) newsize = HASH_MAX_SIZE;
416 initializeObjectsByID(newsize);
417 /* Walk over old one and hash in all the RefNodes */
418 for ( i = 0 ; i < oldsize ; i++ ) {
419 RefNode *onode;
420
421 onode = old[i];
422 while (onode != NULL) {
423 RefNode *next;
424
425 next = onode->next;
426 hashIn(onode);
427 onode = next;
428 }
429 }
430 jvmtiDeallocate(old);
431 }
432
433 /* Add to id hashtable */
434 hashIn(node);
435 return node;
436 }
437
438 /* Initialize the commonRefs usage */
439 void
commonRef_initialize(void)440 commonRef_initialize(void)
441 {
442 gdata->refLock = debugMonitorCreate("JDWP Reference Table Monitor");
443 gdata->nextSeqNum = 1; /* 0 used for error indication */
444 initializeObjectsByID(HASH_INIT_SIZE);
445 }
446
447 /* Reset the commonRefs usage */
448 void
commonRef_reset(JNIEnv * env)449 commonRef_reset(JNIEnv *env)
450 {
451 debugMonitorEnter(gdata->refLock); {
452 int i;
453
454 for (i = 0; i < gdata->objectsByIDsize; i++) {
455 RefNode *node;
456
457 for (node = gdata->objectsByID[i]; node != NULL; node = gdata->objectsByID[i]) {
458 deleteNode(env, node);
459 }
460 gdata->objectsByID[i] = NULL;
461 }
462
463 /* Toss entire hash table and re-create a new one */
464 jvmtiDeallocate(gdata->objectsByID);
465 gdata->objectsByID = NULL;
466 gdata->nextSeqNum = 1; /* 0 used for error indication */
467 initializeObjectsByID(HASH_INIT_SIZE);
468
469 } debugMonitorExit(gdata->refLock);
470 }
471
472 /*
473 * Given a reference obtained from JNI or JVMTI, return an object
474 * id suitable for sending to the debugger front end.
475 */
476 jlong
commonRef_refToID(JNIEnv * env,jobject ref)477 commonRef_refToID(JNIEnv *env, jobject ref)
478 {
479 jlong id;
480
481 if (ref == NULL) {
482 return NULL_OBJECT_ID;
483 }
484
485 id = NULL_OBJECT_ID;
486 debugMonitorEnter(gdata->refLock); {
487 RefNode *node;
488
489 node = findNodeByRef(env, ref);
490 if (node == NULL) {
491 WITH_LOCAL_REFS(env, 1) {
492 node = newCommonRef(env, JNI_FUNC_PTR(env,NewLocalRef)(env, ref));
493 if ( node != NULL ) {
494 id = node->seqNum;
495 }
496 } END_WITH_LOCAL_REFS(env);
497 } else {
498 id = node->seqNum;
499 node->count++;
500 }
501 } debugMonitorExit(gdata->refLock);
502 return id;
503 }
504
505 /*
506 * Given an object ID obtained from the debugger front end, return a
507 * strong, global reference to that object (or NULL if the object
508 * has been collected). The reference can then be used for JNI and
509 * JVMTI calls. Caller is resposible for deleting the returned reference.
510 */
511 jobject
commonRef_idToRef(JNIEnv * env,jlong id)512 commonRef_idToRef(JNIEnv *env, jlong id)
513 {
514 jobject ref;
515
516 ref = NULL;
517 debugMonitorEnter(gdata->refLock); {
518 RefNode *node;
519
520 node = findNodeByID(env, id);
521 if (node != NULL) {
522 if (node->isStrong) {
523 saveGlobalRef(env, node->ref, &ref);
524 } else {
525 jobject lref;
526
527 /* ANDROID-CHANGED: Use getLocalRef helper to get a local-reference to the object
528 * this node weakly points to. It will return NULL if the object has been GCd
529 */
530 lref = getLocalRef(env, node);
531 if ( lref != NULL ) {
532 /* ANDROID-CHANGED: Use lref to save the global ref since that is the only real
533 * jobject we have.
534 */
535 saveGlobalRef(env, lref, &ref);
536 JNI_FUNC_PTR(env,DeleteLocalRef)(env, lref);
537 }
538 /* ANDROID-CHANGED: Otherwise the object was GC'd shortly after we found the node.
539 * The free callback will deal with cleanup once we return.
540 */
541 }
542 }
543 } debugMonitorExit(gdata->refLock);
544 return ref;
545 }
546
547 /* Deletes the global reference that commonRef_idToRef() created */
548 void
commonRef_idToRef_delete(JNIEnv * env,jobject ref)549 commonRef_idToRef_delete(JNIEnv *env, jobject ref)
550 {
551 if ( ref==NULL ) {
552 return;
553 }
554 tossGlobalRef(env, &ref);
555 }
556
557
558 /* Prevent garbage collection of an object */
559 jvmtiError
commonRef_pin(jlong id)560 commonRef_pin(jlong id)
561 {
562 jvmtiError error;
563
564 error = JVMTI_ERROR_NONE;
565 if (id == NULL_OBJECT_ID) {
566 return error;
567 }
568 debugMonitorEnter(gdata->refLock); {
569 JNIEnv *env;
570 RefNode *node;
571
572 env = getEnv();
573 node = findNodeByID(env, id);
574 if (node == NULL) {
575 error = AGENT_ERROR_INVALID_OBJECT;
576 } else {
577 jobject strongRef;
578
579 strongRef = strengthenNode(env, node);
580 if (strongRef == NULL) {
581 /*
582 * Referent has been collected, clean up now.
583 * ANDROID-CHANGED: The node will be cleaned up by the object-free callback.
584 */
585 error = AGENT_ERROR_INVALID_OBJECT;
586 }
587 }
588 } debugMonitorExit(gdata->refLock);
589 return error;
590 }
591
592 /* Permit garbage collection of an object */
593 jvmtiError
commonRef_unpin(jlong id)594 commonRef_unpin(jlong id)
595 {
596 jvmtiError error;
597
598 error = JVMTI_ERROR_NONE;
599 debugMonitorEnter(gdata->refLock); {
600 JNIEnv *env;
601 RefNode *node;
602
603 env = getEnv();
604 node = findNodeByID(env, id);
605 if (node != NULL) {
606 // ANDROID-CHANGED: weakenNode was changed to never fail.
607 weakenNode(env, node);
608 }
609 } debugMonitorExit(gdata->refLock);
610 return error;
611 }
612
613 /* Release tracking of an object by ID */
614 void
commonRef_release(JNIEnv * env,jlong id)615 commonRef_release(JNIEnv *env, jlong id)
616 {
617 debugMonitorEnter(gdata->refLock); {
618 deleteNodeByID(env, id, 1);
619 } debugMonitorExit(gdata->refLock);
620 }
621
622 void
commonRef_releaseMultiple(JNIEnv * env,jlong id,jint refCount)623 commonRef_releaseMultiple(JNIEnv *env, jlong id, jint refCount)
624 {
625 debugMonitorEnter(gdata->refLock); {
626 deleteNodeByID(env, id, refCount);
627 } debugMonitorExit(gdata->refLock);
628 }
629
630 /* Get rid of RefNodes for objects that no longer exist */
631 void
commonRef_compact(void)632 commonRef_compact(void)
633 {
634 // NO-OP.
635 }
636
637 /* Lock the commonRef tables */
638 void
commonRef_lock(void)639 commonRef_lock(void)
640 {
641 debugMonitorEnter(gdata->refLock);
642 }
643
644 /* Unlock the commonRef tables */
645 void
commonRef_unlock(void)646 commonRef_unlock(void)
647 {
648 debugMonitorExit(gdata->refLock);
649 }
650