1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package art;
18 
19 import java.lang.ref.PhantomReference;
20 import java.lang.ref.ReferenceQueue;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.function.BiConsumer;
24 
25 public class Test905 {
26   // Taken from jdwp tests.
27   public static class MarkerObj {
28     public static int cnt = 0;
finalize()29     public void finalize() { cnt++; }
30   }
31   public static class GcMarker {
32     private final ReferenceQueue mQueue;
33     private final ArrayList<PhantomReference> mList;
GcMarker()34     public GcMarker() {
35       mQueue = new ReferenceQueue();
36       mList = new ArrayList<PhantomReference>(3);
37     }
add(Object referent)38     public void add(Object referent) {
39       mList.add(new PhantomReference(referent, mQueue));
40     }
waitForGc()41     public void waitForGc() {
42       waitForGc(mList.size());
43     }
waitForGc(int numberOfExpectedFinalizations)44     public void waitForGc(int numberOfExpectedFinalizations) {
45       if (numberOfExpectedFinalizations > mList.size()) {
46         throw new IllegalArgumentException("wait condition will never be met");
47       }
48       // Request finalization of objects, and subsequent reference enqueueing.
49       // Repeat until reference queue reaches expected size.
50       do {
51           System.runFinalization();
52           Runtime.getRuntime().gc();
53           try { Thread.sleep(10); } catch (Exception e) {}
54       } while (isLive(numberOfExpectedFinalizations));
55     }
isLive(int numberOfExpectedFinalizations)56     private boolean isLive(int numberOfExpectedFinalizations) {
57       int numberFinalized = 0;
58       for (int i = 0, n = mList.size(); i < n; i++) {
59         if (mList.get(i).isEnqueued()) {
60           numberFinalized++;
61         }
62       }
63       return numberFinalized < numberOfExpectedFinalizations;
64     }
65   }
66 
run()67   public static void run() throws Exception {
68     doTest();
69   }
70 
doTest()71   public static void doTest() throws Exception {
72     // Use a list to ensure objects must be allocated.
73     ArrayList<Object> l = new ArrayList<>(100);
74 
75     setupObjectFreeCallback();
76 
77     enableFreeTracking(true);
78     run(l);
79 
80     enableFreeTracking(false);
81     run(l);
82 
83     enableFreeTracking(true);
84     stress();
85   }
86 
run(ArrayList<Object> l)87   private static void run(ArrayList<Object> l) {
88     allocate(l, 1);
89     l.clear();
90 
91     gcAndWait();
92 
93     getAndPrintTags();
94     System.out.println("---");
95 
96     // Note: the reporting will not depend on the heap layout (which could be unstable). Walking
97     //       the tag table should give us a stable output order.
98     for (int i = 10; i <= 1000; i *= 10) {
99       allocate(l, i);
100     }
101     l.clear();
102 
103     gcAndWait();
104 
105     getAndPrintTags();
106     System.out.println("---");
107 
108     gcAndWait();
109 
110     getAndPrintTags();
111     System.out.println("---");
112   }
113 
stressAllocate(int i, BiConsumer<Integer, Object> saver)114   private static void stressAllocate(int i, BiConsumer<Integer, Object> saver) {
115     Object obj = new Object();
116     Main.setTag(obj, i);
117     setTag2(obj, i + 1);
118     saver.accept(i, obj);
119   }
120 
stress()121   private static void stress() {
122     getCollectedTags(0);
123     getCollectedTags(1);
124     final int num_obj = 400000;
125     final Object[] saved = new Object[num_obj/2];
126     // Allocate objects, Save every other one. We want to be sure that it's only the deleted objects
127     // that get their tags cleared and non-deleted objects correctly keep track of their tags.
128     for (int i = 1; i <= num_obj; ++i) {
129       stressAllocate(i, (idx, obj) -> {
130         if ((idx.intValue() - 1) % 2 == 0) {
131           saved[(idx.intValue() - 1)/2] = obj;
132         }
133       });
134     }
135     gcAndWait();
136     long[] freedTags1 = getCollectedTags(0);
137     long[] freedTags2 = getCollectedTags(1);
138     // Sort the freedtags
139     Arrays.sort(freedTags1);
140     Arrays.sort(freedTags2);
141     // Make sure we freed all the ones we expect to and both envs agree on this.
142     System.out.println("Free counts " + freedTags1.length + " " + freedTags2.length);
143     for (int i = 0; i < freedTags1.length; ++i) {
144       if (freedTags1[i] + 1 != freedTags2[i]) {
145         System.out.println("Mismatched tags " + (freedTags1[i] + 1) + " " + freedTags2[i]);
146       }
147     }
148     // Make sure the saved-tags aren't present.
149     for (int i = 0; i < saved.length; i++) {
150       // index = (tag - 1)/2 --> (index * 2) + 1 = tag
151       long expectedTag1 = (i * 2) + 1;
152       if (Main.getTag(saved[i]) != expectedTag1) {
153         System.out.println("Saved object has unexpected tag in env 1. Expected "
154                            + expectedTag1 + " got " + Main.getTag(saved[i]));
155       }
156       if (getTag2(saved[i]) != 1 + expectedTag1) {
157         System.out.println("Saved object has unexpected tag in env 2. Expected "
158                            + (expectedTag1 + 1) + " got " + getTag2(saved[i]));
159       }
160       if (Arrays.binarySearch(freedTags1, expectedTag1) >= 0) {
161         System.out.println("Saved object was marked as deleted in env 1. Object was "
162                            + expectedTag1);
163       }
164       if (Arrays.binarySearch(freedTags2, expectedTag1 + 1) >= 0) {
165         System.out.println("Saved object was marked as deleted in env 2. Object was "
166                            + (expectedTag1 + 1));
167       }
168     }
169   }
170 
allocate(ArrayList<Object> l, long tag)171   private static void allocate(ArrayList<Object> l, long tag) {
172     Object obj = new Object();
173     l.add(obj);
174     Main.setTag(obj, tag);
175   }
176 
getAndPrintTags()177   private static void getAndPrintTags() {
178     long[] freedTags = getCollectedTags(0);
179     Arrays.sort(freedTags);
180     System.out.println(Arrays.toString(freedTags));
181   }
182 
getMarker()183   private static GcMarker getMarker() {
184     GcMarker m = new GcMarker();
185     m.add(new MarkerObj());
186     return m;
187   }
188 
gcAndWait()189   private static void gcAndWait() {
190     GcMarker marker = getMarker();
191     marker.waitForGc();
192   }
193 
setupObjectFreeCallback()194   private static native void setupObjectFreeCallback();
enableFreeTracking(boolean enable)195   private static native void enableFreeTracking(boolean enable);
getCollectedTags(int index)196   private static native long[] getCollectedTags(int index);
setTag2(Object o, long tag)197   private static native void setTag2(Object o, long tag);
getTag2(Object o)198   private static native long getTag2(Object o);
199 }
200