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   private static final boolean DALVIK_RUN = "Dalvik".equals(System.getProperty("java.vm.name"));
27 
28   // Taken from jdwp tests.
29   public static class MarkerObj {
30     public static int cnt = 0;
finalize()31     public void finalize() { cnt++; }
32   }
33   public static class GcMarker {
34     private final ReferenceQueue mQueue;
35     private final ArrayList<PhantomReference> mList;
GcMarker()36     public GcMarker() {
37       mQueue = new ReferenceQueue();
38       mList = new ArrayList<PhantomReference>(3);
39     }
add(Object referent)40     public void add(Object referent) {
41       mList.add(new PhantomReference(referent, mQueue));
42     }
waitForGc()43     public void waitForGc() {
44       waitForGc(mList.size());
45     }
waitForGc(int numberOfExpectedFinalizations)46     public void waitForGc(int numberOfExpectedFinalizations) {
47       if (numberOfExpectedFinalizations > mList.size()) {
48         throw new IllegalArgumentException("wait condition will never be met");
49       }
50       // Request finalization of objects, and subsequent reference enqueueing.
51       // Repeat until reference queue reaches expected size.
52       do {
53           System.runFinalization();
54           Runtime.getRuntime().gc();
55           try { Thread.sleep(10); } catch (Exception e) {}
56       } while (isLive(numberOfExpectedFinalizations));
57     }
isLive(int numberOfExpectedFinalizations)58     private boolean isLive(int numberOfExpectedFinalizations) {
59       int numberFinalized = 0;
60       for (int i = 0, n = mList.size(); i < n; i++) {
61         if (mList.get(i).isEnqueued()) {
62           numberFinalized++;
63         }
64       }
65       return numberFinalized < numberOfExpectedFinalizations;
66     }
67   }
68 
run()69   public static void run() throws Exception {
70     doTest();
71   }
72 
doTest()73   public static void doTest() throws Exception {
74     // Use a list to ensure objects must be allocated.
75     ArrayList<Object> l = new ArrayList<>(100);
76 
77     setupObjectFreeCallback();
78 
79     enableFreeTracking(true);
80     run(l);
81 
82     enableFreeTracking(false);
83     run(l);
84 
85     enableFreeTracking(true);
86     if (DALVIK_RUN) {
87       stress(400000);
88     } else {
89       // For JVM the JVMTI tag handling is not running as expected for the stress test
90       // (b/252990223).
91       stress(10000);
92     }
93   }
94 
run(ArrayList<Object> l)95   private static void run(ArrayList<Object> l) {
96     allocate(l, 1);
97     l.clear();
98 
99     gcAndWait();
100 
101     getAndPrintTags();
102     System.out.println("---");
103 
104     // Note: the reporting will not depend on the heap layout (which could be unstable). Walking
105     //       the tag table should give us a stable output order.
106     for (int i = 10; i <= 1000; i *= 10) {
107       allocate(l, i);
108     }
109     l.clear();
110 
111     gcAndWait();
112 
113     getAndPrintTags();
114     System.out.println("---");
115 
116     gcAndWait();
117 
118     getAndPrintTags();
119     System.out.println("---");
120   }
121 
122   private static int errors = 0;
123 
stressAllocate(int i, BiConsumer<Integer, Object> saver)124   private static void stressAllocate(int i, BiConsumer<Integer, Object> saver) {
125     Object obj = new Object();
126     Main.setTag(obj, i);
127     setTag2(obj, i + 1);
128     saver.accept(i, obj);
129   }
130 
stress(int allocations)131   private static void stress(int allocations) {
132     getCollectedTags(0);
133     getCollectedTags(1);
134     final int num_obj = allocations;
135     final Object[] saved = new Object[num_obj/2];
136     // Allocate objects, Save every other one. We want to be sure that it's only the deleted objects
137     // that get their tags cleared and non-deleted objects correctly keep track of their tags.
138     for (int i = 1; i <= num_obj; ++i) {
139       stressAllocate(i, (idx, obj) -> {
140         if ((idx.intValue() - 1) % 2 == 0) {
141           saved[(idx.intValue() - 1)/2] = obj;
142         }
143       });
144     }
145     gcAndWait();
146     long[] freedTags1 = getCollectedTags(0);
147     long[] freedTags2 = getCollectedTags(1);
148     // Sort the freedtags
149     Arrays.sort(freedTags1);
150     Arrays.sort(freedTags2);
151     // Make sure we freed all the ones we expect to and both envs agree on this.
152     if (freedTags1.length == num_obj / 2 && freedTags2.length == num_obj / 2) {
153       System.out.println("Free counts as expected");
154     } else {
155       System.out.println("Free counts " + freedTags1.length + " " + freedTags2.length);
156     }
157     for (int i = 0; i < freedTags1.length; ++i) {
158       if (freedTags1[i] + 1 != freedTags2[i]) {
159         System.out.println("Mismatched tags " + (freedTags1[i] + 1) + " " + freedTags2[i]);
160         break;
161       }
162     }
163     // Make sure the saved-tags aren't present.
164     for (int i = 0; i < saved.length; i++) {
165       // index = (tag - 1)/2 --> (index * 2) + 1 = tag
166       long expectedTag1 = (i * 2) + 1;
167       if (Main.getTag(saved[i]) != expectedTag1) {
168         System.out.println("Saved object has unexpected tag in env 1. Expected "
169                            + expectedTag1 + " got " + Main.getTag(saved[i]));
170       }
171       if (getTag2(saved[i]) != 1 + expectedTag1) {
172         System.out.println("Saved object has unexpected tag in env 2. Expected "
173                            + (expectedTag1 + 1) + " got " + getTag2(saved[i]));
174       }
175       if (Arrays.binarySearch(freedTags1, expectedTag1) >= 0) {
176         System.out.println("Saved object was marked as deleted in env 1. Object was "
177                            + expectedTag1);
178       }
179       if (Arrays.binarySearch(freedTags2, expectedTag1 + 1) >= 0) {
180         System.out.println("Saved object was marked as deleted in env 2. Object was "
181                            + (expectedTag1 + 1));
182       }
183     }
184   }
185 
allocate(ArrayList<Object> l, long tag)186   private static void allocate(ArrayList<Object> l, long tag) {
187     Object obj = new Object();
188     l.add(obj);
189     Main.setTag(obj, tag);
190   }
191 
getAndPrintTags()192   private static void getAndPrintTags() {
193     long[] freedTags = getCollectedTags(0);
194     Arrays.sort(freedTags);
195     System.out.println(Arrays.toString(freedTags));
196   }
197 
getMarker()198   private static GcMarker getMarker() {
199     GcMarker m = new GcMarker();
200     m.add(new MarkerObj());
201     return m;
202   }
203 
gcAndWait()204   private static void gcAndWait() {
205     GcMarker marker = getMarker();
206     marker.waitForGc();
207   }
208 
setupObjectFreeCallback()209   private static native void setupObjectFreeCallback();
enableFreeTracking(boolean enable)210   private static native void enableFreeTracking(boolean enable);
getCollectedTags(int index)211   private static native long[] getCollectedTags(int index);
setTag2(Object o, long tag)212   private static native void setTag2(Object o, long tag);
getTag2(Object o)213   private static native long getTag2(Object o);
214 }
215