File: ClassUnloadEventTest.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (215 lines) | stat: -rw-r--r-- 9,276 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
 * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 8256811
 * @modules java.base/jdk.internal.org.objectweb.asm
 *          java.base/jdk.internal.misc
 * @library /test/lib
 * @build jdk.test.whitebox.WhiteBox
 * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
 * @run main/othervm/native ClassUnloadEventTest run
 */

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Label;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.test.lib.classloader.ClassUnloadCommon;

import com.sun.jdi.*;
import com.sun.jdi.connect.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;

import java.util.*;
import java.io.*;

public class ClassUnloadEventTest {
    static final String CLASS_NAME_PREFIX = "SampleClass__";
    static final String CLASS_NAME_ALT_PREFIX = CLASS_NAME_PREFIX + "Alt__";
    static final int NUM_CLASSES = 10;
    static final int NUM_ALT_CLASSES = NUM_CLASSES / 2;

    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            try {
                runDebuggee();
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        } else {
            runDebugger();
        }
    }

    private static class TestClassLoader extends ClassLoader implements Opcodes {
        private static byte[] generateSampleClass(String name) {
            ClassWriter cw = new ClassWriter(0);

            cw.visit(52, ACC_SUPER | ACC_PUBLIC, name, null, "java/lang/Object", null);
            MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "m", "()V", null, null);
            mv.visitCode();
            mv.visitInsn(RETURN);
            mv.visitMaxs(0, 0);
            mv.visitEnd();
            cw.visitEnd();
            return cw.toByteArray();
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            if (name.startsWith(CLASS_NAME_PREFIX)) {
                byte[] bytecode = generateSampleClass(name);
                return defineClass(name, bytecode, 0, bytecode.length);
            } else {
                return super.findClass(name);
            }
        }
    }

    private static void runDebuggee() {
        System.out.println("Running debuggee");
        ClassLoader loader = new TestClassLoader();
        for (int index = 0; index < NUM_CLASSES; index++) {
            try {
                if (index < NUM_ALT_CLASSES) {
                    Class.forName(CLASS_NAME_ALT_PREFIX + index, true, loader);
                } else {
                    Class.forName(CLASS_NAME_PREFIX + index, true, loader);
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to create Sample class", e);
            }
        }
        loader = null;

        // Do a short delay to make sure that the debug agent is done processing all
        // ClassPrepare events. Otherwise the debug agent might still be holding on to
        // a reference to a class, which will prevent it from unloading during the GC.
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }

        // Trigger class unloading
        ClassUnloadCommon.triggerUnloading();

        // We rely on JVMTI to post all pending ObjectFree events at VM shutdown.
        // It will trigger the JDWP agent to synthesize expected ClassUnloadEvents events.
        System.out.println("Exiting debuggee");
    }

    private static void runDebugger() throws Exception {
        System.out.println("Running debugger");
        HashSet<String> unloadedSampleClasses = new HashSet<>();
        HashSet<String> unloadedSampleClasses_alt = new HashSet<>();
        VirtualMachine vm = null;
        vm = connectAndLaunchVM();
        ClassUnloadRequest classUnloadRequest = vm.eventRequestManager().createClassUnloadRequest();
        classUnloadRequest.addClassFilter(CLASS_NAME_PREFIX + "*");
        classUnloadRequest.enable();

        ClassUnloadRequest classUnloadRequest_alt = vm.eventRequestManager().createClassUnloadRequest();
        classUnloadRequest_alt.addClassFilter(CLASS_NAME_ALT_PREFIX + "*");
        classUnloadRequest_alt.enable();

        EventSet eventSet = null;
        boolean exited = false;
        while (!exited && (eventSet = vm.eventQueue().remove()) != null) {
            System.out.println("EventSet: " + eventSet);
            for (Event event : eventSet) {
                if (event instanceof ClassUnloadEvent) {
                    String className = ((ClassUnloadEvent)event).className();

                    // The unloaded class should always match CLASS_NAME_PREFIX.
                    if (className.indexOf(CLASS_NAME_PREFIX) == -1) {
                        throw new RuntimeException("FAILED: Unexpected unloaded class: " + className);
                    }

                    // Unloaded classes with ALT names should only occur on the classUnloadRequest_alt.
                    if (event.request() == classUnloadRequest_alt) {
                        unloadedSampleClasses_alt.add(className);
                        if (className.indexOf(CLASS_NAME_ALT_PREFIX) == -1) {
                            throw new RuntimeException("FAILED: non-alt class unload event for classUnloadRequest_alt.");
                        }
                    } else {
                        unloadedSampleClasses.add(className);
                    }

                    // If the unloaded class matches the ALT prefix, then we should have
                    // unload events in this EventSet for each of the two ClassUnloadRequesta.
                    int expectedEventSetSize;
                    if (className.indexOf(CLASS_NAME_ALT_PREFIX) != -1) {
                        expectedEventSetSize = 2;
                    } else {
                        expectedEventSetSize = 1;
                    }
                    if (eventSet.size() != expectedEventSetSize) {
                        throw new RuntimeException("FAILED: Unexpected eventSet size: " + eventSet.size());
                    }
                }

                if (event instanceof VMDeathEvent) {
                    exited = true;
                    break;
                }
            }
            eventSet.resume();
        }

        /* Dump debuggee output. */
        Process p = vm.process();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line = in.readLine();
        while (line != null) {
            System.out.println("stdout: " + line);
            line = in.readLine();
        }
        line = err.readLine();
        while (line != null) {
            System.out.println("stderr: " + line);
            line = err.readLine();
        }

        if (unloadedSampleClasses.size() != NUM_CLASSES) {
            throw new RuntimeException("Wrong number of class unload events: expected " + NUM_CLASSES + " got " + unloadedSampleClasses.size());
        }
        if (unloadedSampleClasses_alt.size() != NUM_ALT_CLASSES) {
            throw new RuntimeException("Wrong number of alt class unload events: expected " + NUM_ALT_CLASSES + " got " + unloadedSampleClasses_alt.size());
        }
    }

    private static VirtualMachine connectAndLaunchVM() throws IOException,
                                                              IllegalConnectorArgumentsException,
                                                              VMStartException {
        LaunchingConnector launchingConnector = Bootstrap.virtualMachineManager().defaultConnector();
        Map<String, Connector.Argument> arguments = launchingConnector.defaultArguments();
        arguments.get("main").setValue(ClassUnloadEventTest.class.getName());
        arguments.get("options").setValue("--add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xlog:class+unload=info -Xlog:gc");
        return launchingConnector.launch(arguments);
    }
}