File: DynamicLoadWarningTest.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 (307 lines) | stat: -rw-r--r-- 12,126 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
 * Copyright (c) 2023, 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 8307478
 * @summary Test that a warning is printed when an agent is dynamically loaded
 * @requires vm.jvmti
 * @modules jdk.attach jdk.jcmd
 * @library /test/lib /test/jdk
 * @build Application JavaAgent
 * @run junit/othervm/native DynamicLoadWarningTest
 */

import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.concurrent.atomic.AtomicBoolean;
import com.sun.tools.attach.VirtualMachine;

import jdk.test.lib.JDKToolLauncher;
import jdk.test.lib.Platform;
import jdk.test.lib.Utils;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.util.JarUtils;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;

class DynamicLoadWarningTest {
    private static final String JVMTI_AGENT_WARNING = "WARNING: A JVM TI agent has been loaded dynamically";
    private static final String JAVA_AGENT_WARNING  = "WARNING: A Java agent has been loaded dynamically";

    // JVM TI agents
    private static final String JVMTI_AGENT1_LIB = "JvmtiAgent1";
    private static final String JVMTI_AGENT2_LIB = "JvmtiAgent2";
    private static String jvmtiAgentPath1;
    private static String jvmtiAgentPath2;

    // Java agent
    private static final String TEST_CLASSES = System.getProperty("test.classes");
    private static String javaAgent;

    @BeforeAll
    static void setup() throws Exception {
        // get absolute path to JVM TI agents
        String libname1 = Platform.buildSharedLibraryName(JVMTI_AGENT1_LIB);
        String libname2 = Platform.buildSharedLibraryName(JVMTI_AGENT2_LIB);
        jvmtiAgentPath1 = Path.of(Utils.TEST_NATIVE_PATH, libname1).toAbsolutePath().toString();
        jvmtiAgentPath2 = Path.of(Utils.TEST_NATIVE_PATH, libname2).toAbsolutePath().toString();

        // create JAR file with Java agent
        Manifest man = new Manifest();
        Attributes attrs = man.getMainAttributes();
        attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
        attrs.put(new Attributes.Name("Agent-Class"), "JavaAgent");
        Path jarfile = Path.of("javaagent.jar");
        Path classes = Path.of(TEST_CLASSES);
        JarUtils.createJarFile(jarfile, man, classes, Path.of("JavaAgent.class"));
        javaAgent = jarfile.toString();
    }

    /**
     * Actions to load JvmtiAgent1 into a running VM.
     */
    private static Stream<OnAttachAction> loadJvmtiAgent1() {
        // load agent with the attach API
        OnAttachAction loadJvmtiAgent = (pid, vm) -> vm.loadAgentLibrary(JVMTI_AGENT1_LIB);

        // jcmd <pid> JVMTI.agent_load <agent>
        OnAttachAction jcmdAgentLoad = jcmdAgentLoad(jvmtiAgentPath1);

        return Stream.of(loadJvmtiAgent, jcmdAgentLoad);
    }

    /**
     * Test loading JvmtiAgent1 into a running VM.
     */
    @ParameterizedTest
    @MethodSource("loadJvmtiAgent1")
    void testLoadOneJvmtiAgent(OnAttachAction loadJvmtiAgent1) throws Exception {
        // dynamically load loadJvmtiAgent1
        test().whenRunning(loadJvmtiAgent1)
                .stderrShouldContain(JVMTI_AGENT_WARNING);

        // opt-in via command line option to allow dynamic loading of agents
        test().withOpts("-XX:+EnableDynamicAgentLoading")
                .whenRunning(loadJvmtiAgent1)
                .stderrShouldNotContain(JVMTI_AGENT_WARNING);

        // start loadJvmtiAgent1 via the command line, then dynamically load loadJvmtiAgent1
        test().withOpts("-agentpath:" + jvmtiAgentPath1)
                .whenRunning(loadJvmtiAgent1)
                .stderrShouldNotContain(JVMTI_AGENT_WARNING);

        // dynamically load loadJvmtiAgent1 twice, should be one warning
        test().whenRunning(loadJvmtiAgent1)
                .whenRunning(loadJvmtiAgent1)
                .stderrShouldContain(JVMTI_AGENT_WARNING, 1);
    }

    /**
     * Test loading JvmtiAgent1 and JvmtiAgent2 into a running VM.
     */
    @ParameterizedTest
    @MethodSource("loadJvmtiAgent1")
    void testLoadTwoJvmtiAgents(OnAttachAction loadJvmtiAgent1) throws Exception {
        OnAttachAction loadJvmtiAgent2 = (pid, vm) -> vm.loadAgentLibrary(JVMTI_AGENT2_LIB);
        OnAttachAction jcmdAgentLoad2 = jcmdAgentLoad(jvmtiAgentPath2);

        // dynamically load loadJvmtiAgent1, then dynamically load loadJvmtiAgent2 with attach API
        test().whenRunning(loadJvmtiAgent1)
                .whenRunning(loadJvmtiAgent2)
                .stderrShouldContain(JVMTI_AGENT_WARNING, 2);

        // dynamically load loadJvmtiAgent1, then dynamically load loadJvmtiAgent2 with jcmd
        test().whenRunning(loadJvmtiAgent1)
                .whenRunning(jcmdAgentLoad2)
                .stderrShouldContain(JVMTI_AGENT_WARNING, 2);

        // start loadJvmtiAgent2 via the command line, then dynamically load loadJvmtiAgent1
        test().withOpts("-agentpath:" + jvmtiAgentPath2)
                .whenRunning(loadJvmtiAgent1)
                .stderrShouldContain(JVMTI_AGENT_WARNING);
    }

    /**
     * Test loading Java agent into a running VM.
     */
    @Test
    void testLoadJavaAgent() throws Exception {
        OnAttachAction loadJavaAgent = (pid, vm) -> vm.loadAgent(javaAgent);

        // agent dynamically loaded
        test().whenRunning(loadJavaAgent)
                .stderrShouldContain(JAVA_AGENT_WARNING);

        // opt-in via command line option to allow dynamic loading of agents
        test().withOpts("-XX:+EnableDynamicAgentLoading")
                .whenRunning(loadJavaAgent)
                .stderrShouldNotContain(JAVA_AGENT_WARNING);
    }

    /**
     * Represents an operation that accepts a process identifier and a VirtualMachine
     * that the current JVM is attached to.
     */
    private interface OnAttachAction {
        void accept(long pid, VirtualMachine vm) throws Exception;
    }

    /**
     * Returns an operation that invokes "jcmd <pid> JVMTI.agent_load <agentpath>" to
     * load the given agent library into the JVM that the current JVM is attached to.
     */
    private static OnAttachAction jcmdAgentLoad(String agentPath) {
        return (pid, vm) -> {
            String[] jcmd = JDKToolLauncher.createUsingTestJDK("jcmd")
                    .addToolArg(Long.toString(pid))
                    .addToolArg("JVMTI.agent_load")
                    .addToolArg(agentPath)
                    .getCommand();
            System.out.println(Arrays.stream(jcmd).collect(Collectors.joining(" ")));
            Process p = new ProcessBuilder(jcmd).inheritIO().start();
            assertEquals(0, p.waitFor());
        };
    }

    /**
     * Returns a new app runner.
     */
    private static AppRunner test() {
        return new AppRunner();
    }

    /**
     * Runs an application in its own VM. Once started, it attachs to the VM, runs a set
     * of actions, then checks that the output contains, or does not contain, a string.
     */
    private static class AppRunner {
        private String[] vmopts = new String[0];
        private List<OnAttachAction> actions = new ArrayList<>();

        /**
         * Specifies VM options to run the application.
         */
        AppRunner withOpts(String... vmopts) {
            this.vmopts = vmopts;
            return this;
        }

        /**
         * Specifies an action to run when the attached to the running application.
         */
        AppRunner whenRunning(OnAttachAction action) {
            actions.add(action);
            return this;
        }

        OutputAnalyzer run() throws Exception {
            // start a listener socket that the application will connect to
            try (ServerSocket listener = new ServerSocket()) {
                InetAddress lh = InetAddress.getLoopbackAddress();
                listener.bind(new InetSocketAddress(lh, 0));

                var done = new AtomicBoolean();

                // start a thread to wait for the application to phone home
                Thread.ofPlatform().daemon().start(() -> {
                    try (Socket s = listener.accept();
                         DataInputStream in = new DataInputStream(s.getInputStream())) {

                        // read pid
                        long pid = in.readLong();

                        // attach and run the actions with the vm object
                        VirtualMachine vm = VirtualMachine.attach(Long.toString(pid));
                        try {
                            for (OnAttachAction action : actions) {
                                action.accept(pid, vm);
                            }
                        } finally {
                            vm.detach();
                        }
                        done.set(true);

                        // shutdown
                        s.getOutputStream().write(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });

                // launch application with the given VM options, waiting for it to terminate
                Stream<String> s1 = Stream.of(vmopts);
                Stream<String> s2 = Stream.of("Application", Integer.toString(listener.getLocalPort()));
                String[] opts = Stream.concat(s1, s2).toArray(String[]::new);
                OutputAnalyzer outputAnalyzer = ProcessTools
                        .executeTestJava(opts)
                        .outputTo(System.out)
                        .errorTo(System.out);
                assertEquals(0, outputAnalyzer.getExitValue());
                assertTrue(done.get(), "Attach or action failed, see log for details");
                return outputAnalyzer;
            }
        }

        /**
         * Run the application, checking that standard error contains a string.
         */
        void stderrShouldContain(String s) throws Exception {
            run().stderrShouldContain(s);
        }

        /**
         * Run the application, checking that standard error contains the given number of
         * occurrences of a string.
         */
        void stderrShouldContain(String s, int occurrences) throws Exception {
            List<String> lines = run().asLines();
            int count = (int) lines.stream().filter(line -> line.indexOf(s) >= 0).count();
            assertEquals(occurrences, count);
        }

        /**
         * Run the application, checking that standard error does not contain a string.
         */
        void stderrShouldNotContain(String s) throws Exception {
            run().stderrShouldNotContain(s);
        }
    }
}