Main.java revision 021c5f285550bf1cfa435db6a8bc7e77843e2b7d
1/*
2 * Copyright (C) 2015 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
17import java.io.BufferedReader;
18import java.io.File;
19import java.io.FileReader;
20import java.lang.ref.WeakReference;
21import java.lang.reflect.Constructor;
22import java.lang.reflect.Method;
23
24public class Main {
25    static final String DEX_FILE = System.getenv("DEX_LOCATION") + "/141-class-unload-ex.jar";
26    static final String LIBRARY_SEARCH_PATH = System.getProperty("java.library.path");
27    static String nativeLibraryName;
28
29    public static void main(String[] args) throws Exception {
30        nativeLibraryName = args[0];
31        Class<?> pathClassLoader = Class.forName("dalvik.system.PathClassLoader");
32        if (pathClassLoader == null) {
33            throw new AssertionError("Couldn't find path class loader class");
34        }
35        Constructor<?> constructor =
36            pathClassLoader.getDeclaredConstructor(String.class, String.class, ClassLoader.class);
37        try {
38            testUnloadClass(constructor);
39            testUnloadLoader(constructor);
40            // Test that we don't unload if we have an instance.
41            testNoUnloadInstance(constructor);
42            // Test JNI_OnLoad and JNI_OnUnload.
43            testLoadAndUnloadLibrary(constructor);
44            // Test that stack traces keep the classes live.
45            testStackTrace(constructor);
46            // Stress test to make sure we dont leak memory.
47            stressTest(constructor);
48            // Test that the oat files are unloaded.
49            testOatFilesUnloaded(getPid());
50            // Test that objects keep class loader live for sticky GC.
51            testStickyUnload(constructor);
52        } catch (Exception e) {
53            e.printStackTrace();
54        }
55    }
56
57    private static void testOatFilesUnloaded(int pid) throws Exception {
58        System.loadLibrary(nativeLibraryName);
59        // Stop the JIT to ensure its threads and work queue are not keeping classes
60        // artifically alive.
61        stopJit();
62        Runtime.getRuntime().gc();
63        System.runFinalization();
64        BufferedReader reader = new BufferedReader(new FileReader ("/proc/" + pid + "/maps"));
65        String line;
66        int count = 0;
67        while ((line = reader.readLine()) != null) {
68            if (line.contains("@141-class-unload-ex.jar")) {
69                System.out.println(line);
70                ++count;
71            }
72        }
73        System.out.println("Number of loaded unload-ex maps " + count);
74        startJit();
75    }
76
77    private static void stressTest(Constructor<?> constructor) throws Exception {
78        for (int i = 0; i <= 100; ++i) {
79            setUpUnloadLoader(constructor, false);
80            if (i % 10 == 0) {
81                Runtime.getRuntime().gc();
82            }
83        }
84    }
85
86    private static void testUnloadClass(Constructor<?> constructor) throws Exception {
87        WeakReference<Class> klass = setUpUnloadClassWeak(constructor);
88        // No strong references to class loader, should get unloaded.
89        Runtime.getRuntime().gc();
90        WeakReference<Class> klass2 = setUpUnloadClassWeak(constructor);
91        Runtime.getRuntime().gc();
92        // If the weak reference is cleared, then it was unloaded.
93        System.out.println(klass.get());
94        System.out.println(klass2.get());
95    }
96
97    private static void testUnloadLoader(Constructor<?> constructor)
98        throws Exception {
99      WeakReference<ClassLoader> loader = setUpUnloadLoader(constructor, true);
100      // No strong references to class loader, should get unloaded.
101      Runtime.getRuntime().gc();
102      // If the weak reference is cleared, then it was unloaded.
103      System.out.println(loader.get());
104    }
105
106    private static void testStackTrace(Constructor<?> constructor) throws Exception {
107        Class<?> klass = setUpUnloadClass(constructor);
108        WeakReference<Class> weak_klass = new WeakReference(klass);
109        Method stackTraceMethod = klass.getDeclaredMethod("generateStackTrace");
110        Throwable throwable = (Throwable) stackTraceMethod.invoke(klass);
111        stackTraceMethod = null;
112        klass = null;
113        Runtime.getRuntime().gc();
114        boolean isNull = weak_klass.get() == null;
115        System.out.println("class null " + isNull + " " + throwable.getMessage());
116    }
117
118    private static void testLoadAndUnloadLibrary(Constructor<?> constructor) throws Exception {
119        WeakReference<ClassLoader> loader = setUpLoadLibrary(constructor);
120        // No strong references to class loader, should get unloaded.
121        Runtime.getRuntime().gc();
122        // If the weak reference is cleared, then it was unloaded.
123        System.out.println(loader.get());
124    }
125
126    private static Object testNoUnloadHelper(ClassLoader loader) throws Exception {
127        Class<?> intHolder = loader.loadClass("IntHolder");
128        return intHolder.newInstance();
129    }
130
131    static class Pair {
132      public Pair(Object o, ClassLoader l) {
133        object = o;
134        classLoader = new WeakReference<ClassLoader>(l);
135      }
136
137      public Object object;
138      public WeakReference<ClassLoader> classLoader;
139    }
140
141    private static Pair testNoUnloadInstanceHelper(Constructor<?> constructor) throws Exception {
142        ClassLoader loader = (ClassLoader) constructor.newInstance(
143            DEX_FILE, LIBRARY_SEARCH_PATH, ClassLoader.getSystemClassLoader());
144        Object o = testNoUnloadHelper(loader);
145        return new Pair(o, loader);
146    }
147
148    private static void testNoUnloadInstance(Constructor<?> constructor) throws Exception {
149        Pair p = testNoUnloadInstanceHelper(constructor);
150        Runtime.getRuntime().gc();
151        // If the class loader was unloded too early due to races, just pass the test.
152        boolean isNull = p.classLoader.get() == null;
153        System.out.println("loader null " + isNull);
154    }
155
156    private static Class<?> setUpUnloadClass(Constructor<?> constructor) throws Exception {
157        ClassLoader loader = (ClassLoader) constructor.newInstance(
158            DEX_FILE, LIBRARY_SEARCH_PATH, ClassLoader.getSystemClassLoader());
159        Class<?> intHolder = loader.loadClass("IntHolder");
160        Method getValue = intHolder.getDeclaredMethod("getValue");
161        Method setValue = intHolder.getDeclaredMethod("setValue", Integer.TYPE);
162        // Make sure we don't accidentally preserve the value in the int holder, the class
163        // initializer should be re-run.
164        System.out.println((int) getValue.invoke(intHolder));
165        setValue.invoke(intHolder, 2);
166        System.out.println((int) getValue.invoke(intHolder));
167        waitForCompilation(intHolder);
168        return intHolder;
169    }
170
171    private static Object allocObjectInOtherClassLoader(Constructor<?> constructor)
172            throws Exception {
173      ClassLoader loader = (ClassLoader) constructor.newInstance(
174              DEX_FILE, LIBRARY_SEARCH_PATH, ClassLoader.getSystemClassLoader());
175      return loader.loadClass("IntHolder").newInstance();
176    }
177
178    // Regression test for public issue 227182.
179    private static void testStickyUnload(Constructor<?> constructor) throws Exception {
180        String s = "";
181        for (int i = 0; i < 10; ++i) {
182            s = "";
183            // The object is the only thing preventing the class loader from being unloaded.
184            Object o = allocObjectInOtherClassLoader(constructor);
185            for (int j = 0; j < 1000; ++j) {
186                s += j + " ";
187            }
188            // Make sure the object still has a valid class (hasn't been incorrectly unloaded).
189            s += o.getClass().getName();
190            o = null;
191        }
192        System.out.println("Too small " + (s.length() < 1000));
193    }
194
195    private static WeakReference<Class> setUpUnloadClassWeak(Constructor<?> constructor)
196            throws Exception {
197        return new WeakReference<Class>(setUpUnloadClass(constructor));
198    }
199
200    private static WeakReference<ClassLoader> setUpUnloadLoader(Constructor<?> constructor,
201                                                                boolean waitForCompilation)
202        throws Exception {
203        ClassLoader loader = (ClassLoader) constructor.newInstance(
204            DEX_FILE, LIBRARY_SEARCH_PATH, ClassLoader.getSystemClassLoader());
205        Class<?> intHolder = loader.loadClass("IntHolder");
206        Method setValue = intHolder.getDeclaredMethod("setValue", Integer.TYPE);
207        setValue.invoke(intHolder, 2);
208        if (waitForCompilation) {
209            waitForCompilation(intHolder);
210        }
211        return new WeakReference(loader);
212    }
213
214    private static void waitForCompilation(Class<?> intHolder) throws Exception {
215      // Load the native library so that we can call waitForCompilation.
216      Method loadLibrary = intHolder.getDeclaredMethod("loadLibrary", String.class);
217      loadLibrary.invoke(intHolder, nativeLibraryName);
218      // Wait for JIT compilation to finish since the async threads may prevent unloading.
219      Method waitForCompilation = intHolder.getDeclaredMethod("waitForCompilation");
220      waitForCompilation.invoke(intHolder);
221    }
222
223    private static WeakReference<ClassLoader> setUpLoadLibrary(Constructor<?> constructor)
224        throws Exception {
225        ClassLoader loader = (ClassLoader) constructor.newInstance(
226            DEX_FILE, LIBRARY_SEARCH_PATH, ClassLoader.getSystemClassLoader());
227        Class<?> intHolder = loader.loadClass("IntHolder");
228        Method loadLibrary = intHolder.getDeclaredMethod("loadLibrary", String.class);
229        loadLibrary.invoke(intHolder, nativeLibraryName);
230        waitForCompilation(intHolder);
231        return new WeakReference(loader);
232    }
233
234    private static int getPid() throws Exception {
235      return Integer.parseInt(new File("/proc/self").getCanonicalFile().getName());
236    }
237
238    public static native void stopJit();
239    public static native void startJit();
240}
241