File: RetransformWithMethodParametersTest.java

package info (click to toggle)
openjdk-24 24.0.2%2B12-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 831,900 kB
  • sloc: java: 5,677,020; cpp: 1,323,154; xml: 1,320,524; ansic: 486,889; asm: 405,131; objc: 21,025; sh: 15,221; javascript: 11,049; python: 8,222; makefile: 2,504; perl: 357; awk: 351; sed: 172; pascal: 103; exp: 54; jsp: 24; csh: 3
file content (256 lines) | stat: -rw-r--r-- 9,971 bytes parent folder | download | duplicates (7)
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
 * 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 8240908
 *
 * @library /test/lib
 * @run compile -g -parameters RetransformWithMethodParametersTest.java
 * @run shell MakeJAR.sh retransformAgent
 *
 * @run main/othervm -javaagent:retransformAgent.jar RetransformWithMethodParametersTest
 */

import java.io.File;
import java.io.FileOutputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.ProtectionDomain;
import java.util.Arrays;

import jdk.test.lib.JDKToolLauncher;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.util.ClassTransformer;

/*
 * The test verifies Instrumentation.retransformClasses() (and JVMTI function RetransformClasses)
 * correctly handles MethodParameter attribute:
 * 1) classfile bytes passed to transformers (and JVMTI ClassFileLoadHook event callback) contain the attribute;
 * 2) the attribute is updated if new version has the attribute with different values;
 * 3) the attribute is removed if new version doesn't contain the attribute.
 */

// See ClassTransformer.transform(int) comment for @1 tag explanations.
class MethodParametersTarget {
    // The class contains the only method, so we don't have issue with method sorting
    // and ClassFileReconstituter should restore the same bytes as original classbytes.
    // This method should be ctor, otherwise default ctor will be implicitly declared.
    public MethodParametersTarget(
            int intParam1, String stringParam1 // @1 commentout
            // @1 uncomment   int intParam2, String stringParam2
            )
    {
        // @1 uncomment System.out.println(stringParam2);   // change CP
    }
}

public class RetransformWithMethodParametersTest extends ATransformerManagementTestCase {

    public static void main (String[] args) throws Throwable {
        ATestCaseScaffold test = new RetransformWithMethodParametersTest();
        test.runTest();
    }

    private String targetClassName = "MethodParametersTarget";
    private String classFileName = targetClassName + ".class";
    private String sourceFileName = "RetransformWithMethodParametersTest.java";
    private Class targetClass;
    private byte[] originalClassBytes;

    private byte[] seenClassBytes;
    private byte[] newClassBytes;

    public RetransformWithMethodParametersTest() throws Throwable {
        super("RetransformWithMethodParametersTest");

        File origClassFile = new File(System.getProperty("test.classes", "."), classFileName);
        log("Reading test class from " + origClassFile);
        originalClassBytes = Files.readAllBytes(origClassFile.toPath());
        log("Read " + originalClassBytes.length + " bytes.");
    }

    private void log(Object o) {
        System.out.println(String.valueOf(o));
    }

    private Parameter[] getTargetMethodParameters() throws ClassNotFoundException {
        Class cls = Class.forName(targetClassName);
        // the class contains 1 method (ctor)
        Executable method = cls.getDeclaredConstructors()[0];
        Parameter[] params = method.getParameters();
        log("Params of " + method.getName() + " method (" + params.length + "):");
        for (int i = 0; i < params.length; i++) {
            log("  " + i + ": " + params[i].getName()
                    + " (" + (params[i].isNamePresent() ? "present" : "absent") + ")");
        }
        return params;
    }

    // Verifies MethodParameters attribute is present and contains the expected values.
    private void verifyPresentMethodParams(String... expectedNames) throws Throwable {
        Parameter[] params = getTargetMethodParameters();
        assertEquals(expectedNames.length, params.length);
        for (int i = 0; i < params.length; i++) {
            assertTrue(params[i].isNamePresent());
            assertEquals(expectedNames[i], params[i].getName());
        }
    }

    // Verifies MethodParameters attribute is absent.
    private void verifyAbsentMethodParams() throws Throwable {
        Parameter[] params = getTargetMethodParameters();
        for (int i = 0; i < params.length; i++) {
            assertTrue(!params[i].isNamePresent());
        }
    }

    // Retransforms target class using provided class bytes;
    // Returns class bytes passed to the transformer.
    private byte[] retransform(byte[] classBytes) throws Throwable {
        seenClassBytes = null;
        newClassBytes = classBytes;
        fInst.retransformClasses(targetClass);
        assertTrue(targetClassName + " was not seen by transform()", seenClassBytes != null);
        return seenClassBytes;
    }

    // Prints dissassembled class bytes.
    private void printDisassembled(String description, byte[] bytes) throws Exception {
        log(description + " -------------------");

        File f = new File(classFileName);
        try (FileOutputStream fos = new FileOutputStream(f)) {
            fos.write(bytes);
        }
        JDKToolLauncher javap = JDKToolLauncher.create("javap")
                .addToolArg("-verbose")
                .addToolArg("-p")       // Shows all classes and members.
                //.addToolArg("-c")       // Prints out disassembled code
                //.addToolArg("-s")       // Prints internal type signatures.
                .addToolArg(f.toString());
        ProcessBuilder pb = new ProcessBuilder(javap.getCommand());
        OutputAnalyzer out = ProcessTools.executeProcess(pb);
        out.shouldHaveExitValue(0);
        try {
            Files.delete(f.toPath());
        } catch (Exception ex) {
            // ignore
        }
        out.asLines().forEach(s -> log(s));
        log("==========================================");
    }

    // Verifies class bytes are equal.
    private void compareClassBytes(byte[] expected, byte[] actual) throws Exception {

        int pos = Arrays.mismatch(expected, actual);
        if (pos < 0) {
            log("Class bytes are identical.");
            return;
        }
        log("Class bytes are different.");
        printDisassembled("expected", expected);
        printDisassembled("actual", actual);
        fail(targetClassName + " did not match .class file");
    }

    protected final void doRunTest() throws Throwable {
        beVerbose();

        ClassLoader loader = getClass().getClassLoader();
        targetClass = loader.loadClass(targetClassName);
        // sanity check
        assertEquals(targetClassName, targetClass.getName());
        // sanity check
        verifyPresentMethodParams("intParam1", "stringParam1");

        addTransformerToManager(fInst, new Transformer(), true);

        {
            log("Testcase 1: ensure ClassFileReconstituter restores MethodParameters attribute");

            byte[] classBytes = retransform(null);
            compareClassBytes(originalClassBytes, classBytes);

            log("");
        }

        {
            log("Testcase 2: redefine class with changed parameter names");

            byte[] classBytes = Files.readAllBytes(Paths.get(
                    ClassTransformer.fromTestSource(sourceFileName)
                            .transform(1, targetClassName, "-g", "-parameters")));
            retransform(classBytes);
            // MethodParameters attribute should be updated.
            verifyPresentMethodParams("intParam2", "stringParam2");

            log("");
        }

        {
            log("Testcase 3: redefine class with no parameter names");
            // compile without "-parameters"
            byte[] classBytes = Files.readAllBytes(Paths.get(
                    ClassTransformer.fromTestSource(sourceFileName)
                            .transform(1, targetClassName, "-g")));
            retransform(classBytes);
            // MethodParameters attribute should be dropped.
            verifyAbsentMethodParams();

            log("");
        }
    }


    public class Transformer implements ClassFileTransformer {
        public Transformer() {
        }

        public String toString() {
            return Transformer.this.getClass().getName();
        }

        public byte[] transform(ClassLoader loader, String className,
            Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {

            if (className.equals(targetClassName)) {
                log(this + ".transform() sees '" + className
                        + "' of " + classfileBuffer.length + " bytes.");
                seenClassBytes = classfileBuffer;
                if (newClassBytes != null) {
                    log(this + ".transform() sets new classbytes for '" + className
                            + "' of " + newClassBytes.length + " bytes.");
                }
                return newClassBytes;
            }

            return null;
        }
    }
}