1 /*
  2  * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 /*
 26  * @test
 27  * @summary Exercise the java.lang.instrument.Instrumentation APIs on classes archived
 28  *          using CDS/AppCDSv1/AppCDSv2.
 29  * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds /test/hotspot/jtreg/runtime/cds/appcds/test-classes
 30  * @requires vm.cds
 31  * @requires vm.jvmti
 32  * @build jdk.test.whitebox.WhiteBox
 33  *        InstrumentationApp
 34  *        InstrumentationClassFileTransformer
 35  *        InstrumentationRegisterClassFileTransformer
 36  * @run main/othervm InstrumentationTest
 37  */
 38 
 39 // Note: TestCommon is from /test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java
 40 // Note: Util       is from /test/hotspot/jtreg/runtime/cds/appcds/test-classes/TestCommon.java
 41 
 42 import com.sun.tools.attach.VirtualMachine;
 43 import java.io.File;
 44 import java.io.FileInputStream;
 45 import java.util.Scanner;
 46 import jdk.test.lib.Asserts;
 47 import jdk.test.lib.cds.CDSOptions;
 48 import jdk.test.lib.cds.CDSTestUtils;
 49 import jdk.test.lib.process.OutputAnalyzer;
 50 import jdk.test.lib.helpers.ClassFileInstaller;
 51 
 52 public class InstrumentationTest {
 53     public static String bootClasses[] = {
 54         "InstrumentationApp$Intf",
 55         "InstrumentationApp$Bar",
 56         "jdk.test.whitebox.WhiteBox",
 57     };
 58     public static String appClasses[] = {
 59         "InstrumentationApp",
 60         "InstrumentationApp$Foo",
 61         "InstrumentationApp$MyLoader",
 62     };
 63     public static String custClasses[] = {
 64         "InstrumentationApp$Coo",
 65     };
 66     public static String sharedClasses[] = TestCommon.concat(bootClasses, appClasses);
 67 
 68     public static String agentClasses[] = {
 69         "InstrumentationClassFileTransformer",
 70         "InstrumentationRegisterClassFileTransformer",
 71         "Util",
 72     };
 73 
 74     public static void main(String[] args) throws Throwable {
 75         runTest(false);
 76         runTest(true);
 77     }
 78 
 79     public static void runTest(boolean attachAgent) throws Throwable {
 80         String bootJar =
 81             ClassFileInstaller.writeJar("InstrumentationBoot.jar", bootClasses);
 82         String appJar =
 83             ClassFileInstaller.writeJar("InstrumentationApp.jar",
 84                                         TestCommon.concat(appClasses,
 85                                                           "InstrumentationApp$ArchivedIfAppCDSv2Enabled"));
 86         String custJar =
 87             ClassFileInstaller.writeJar("InstrumentationCust.jar", custClasses);
 88         String agentJar =
 89             ClassFileInstaller.writeJar("InstrumentationAgent.jar",
 90                                         ClassFileInstaller.Manifest.fromSourceFile("InstrumentationAgent.mf"),
 91                                         agentClasses);
 92 
 93         String bootCP = "-Xbootclasspath/a:" + bootJar;
 94 
 95         System.out.println("");
 96         System.out.println("============================================================");
 97         System.out.println("CDS: NO, attachAgent: " + (attachAgent ? "YES" : "NO"));
 98         System.out.println("============================================================");
 99         System.out.println("");
100 
101         String agentCmdArg, flagFile;
102         if (attachAgent) {
103             // we will attach the agent, so don't specify -javaagent in the command line. We'll use
104             // something harmless like -showversion to make it easier to construct the command line
105             agentCmdArg = "-showversion";
106         } else {
107             agentCmdArg = "-javaagent:" + agentJar;
108         }
109 
110         // First, run the test class directly, w/o sharing, as a baseline reference
111         flagFile = getFlagFile(attachAgent);
112         AgentAttachThread t = doAttach(attachAgent, flagFile, agentJar);
113         CDSOptions opts = (new CDSOptions())
114             .setUseVersion(false)
115             .setXShareMode("off")
116             .addSuffix(bootCP,
117                        "-cp", appJar,
118                        "-XX:+UnlockDiagnosticVMOptions",
119                        "-XX:+WhiteBoxAPI",
120                        "-Xshare:off",
121                        agentCmdArg,
122                        "InstrumentationApp", flagFile, bootJar, appJar, custJar);
123         CDSTestUtils.run(opts)
124                     .assertNormalExit();
125         checkAttach(t);
126 
127         // Dump the AppCDS archive. On some platforms AppCDSv2 may not be enabled, so we
128         // first try the v2 classlist, and if that fails, revert to the v1 classlist.
129         // Note that the InstrumentationApp$ArchivedIfAppCDSv2Enabled class is archived
130         // only if V2 is enabled. This is tested by InstrumentationApp.isAppCDSV2Enabled().
131         String[] v2Classes = {
132             "InstrumentationApp$ArchivedIfAppCDSv2Enabled",
133             "java/lang/Object id: 0",
134             "InstrumentationApp$Intf id: 1",
135             "InstrumentationApp$Coo  id: 2 super: 0 interfaces: 1 source: " + custJar,
136         };
137         String[] sharedClassesWithV2 = TestCommon.concat(v2Classes, sharedClasses);
138         OutputAnalyzer out = TestCommon.dump(appJar, sharedClassesWithV2, bootCP);
139         if (out.getExitValue() != 0) {
140             System.out.println("Redumping with AppCDSv2 disabled");
141                 TestCommon.testDump(appJar, sharedClasses, bootCP);
142         }
143 
144         // Run with AppCDS.
145         System.out.println("");
146         System.out.println("============================================================");
147         System.out.println("CDS: YES, attachAgent: " + (attachAgent ? "YES" : "NO"));
148         System.out.println("============================================================");
149         System.out.println("");
150 
151         flagFile = getFlagFile(attachAgent);
152         t = doAttach(attachAgent, flagFile, agentJar);
153         out = TestCommon.execAuto("-cp", appJar,
154                 bootCP,
155                 "-XX:+UnlockDiagnosticVMOptions",
156                 "-XX:+WhiteBoxAPI",
157                 agentCmdArg,
158                "InstrumentationApp", flagFile, bootJar, appJar, custJar);
159 
160         opts = (new CDSOptions()).setXShareMode("auto");
161         TestCommon.checkExec(out, opts);
162         checkAttach(t);
163     }
164 
165     static int flagFileSerial = 1;
166     static private String getFlagFile(boolean attachAgent) {
167         if (attachAgent) {
168             // Do not reuse the same file name as Windows may fail to
169             // delete the file.
170             return "attach.flag." + ProcessHandle.current().pid() +
171                     "." + (flagFileSerial++) + "." + System.currentTimeMillis();
172         } else {
173             return "noattach";
174         }
175     }
176 
177     static AgentAttachThread doAttach(boolean attachAgent, String flagFile, String agentJar) throws Throwable {
178         if (!attachAgent) {
179             return null;
180         }
181 
182         // Hand-shake protocol with the child process
183         // [1] Parent process (this process) launches child process (InstrumentationApp)
184         //     and then waits until child process writes its pid into the flagFile.
185         // [2] Child process process starts up, writes its pid into the flagFile,
186         //     and waits for the flagFile to be deleted.
187         // [3] When parent process gets the pid, it attaches to the child process
188         //     (if we attempt to attach to a process too early, the SIGQUIT
189         //     may cause the child to die) and deletes the flagFile.
190         // [4] Child process resumes execution.
191 
192         File f = new File(flagFile);
193         f.delete();
194         if (f.exists()) {
195             throw new RuntimeException("Flag file should not exist: " + f);
196         }
197 
198         // At this point, the child process is not yet launched. Note that
199         // TestCommon.exec() and OutputAnalyzer.OutputAnalyzer() both block
200         // until the child process has finished.
201         //
202         // So, we will launch a AgentAttachThread which will poll the flagFile
203         // until the child process is launched.
204         AgentAttachThread t = new AgentAttachThread(flagFile, agentJar);
205         t.start();
206         return t;
207     }
208 
209     static void checkAttach(AgentAttachThread thread) throws Throwable {
210         if (thread != null) {
211             thread.check();
212         }
213     }
214 
215     static class AgentAttachThread extends Thread {
216         String flagFile;
217         String agentJar;
218         volatile boolean succeeded;
219 
220         AgentAttachThread(String flagFile, String agentJar) {
221             this.flagFile = flagFile;
222             this.agentJar = agentJar;
223             this.succeeded = false;
224         }
225 
226         static String getPid(String flagFile) throws Throwable {
227             while (true) {
228                 // Keep polling until the child process has been launched. If for some
229                 // reason the child process fails to launch, this test will be terminated
230                 // by JTREG's time-out mechanism.
231                 Thread.sleep(100);
232                 File f = new File(flagFile);
233                 if (f.exists() && f.length() > 100) {
234                     try (FileInputStream in = new FileInputStream(f)) {
235                         Scanner scanner = new Scanner(in);
236                         return Long.toString(scanner.nextLong());
237                     } catch (Throwable t) {
238                         // This may happen on Windows if the child process has not
239                         // fully closed the output stream to the flagFile
240                         System.out.println("Ignored: " + t);
241                         t.printStackTrace(System.out);
242                         continue;
243                     }
244                 }
245             }
246         }
247 
248         public void run() {
249             try {
250                 String pid = getPid(flagFile);
251                 System.out.println("child pid = " + pid);
252                 VirtualMachine vm = VirtualMachine.attach(pid);
253                 System.out.println(agentJar);
254                 vm.loadAgent(agentJar);
255             } catch (Throwable t) {
256                 t.printStackTrace();
257                 throw new RuntimeException(t);
258             }
259 
260             // Delete the flagFile to indicate to the child process that we
261             // have attached to it, so it should proceed.
262             File f = new File(flagFile);
263             for (int i=0; i<5; i++) {
264                 // The detele may fail on Windows if the child JVM is checking
265                 // f.exists() at exactly the same time?? Let's do a little
266                 // dance.
267                 f.delete();
268                 try {
269                     Thread.sleep(10);
270                 } catch (Throwable t) {;}
271             }
272             if (f.exists()) {
273                 throw new RuntimeException("Failed to delete " + f);
274             }
275             System.out.println("Attach succeeded (parent)");
276             succeeded = true;
277         }
278 
279         void check() throws Throwable {
280             super.join();
281             if (!succeeded) {
282                 throw new RuntimeException("Attaching agent to child VM failed");
283             }
284         }
285     }
286 }
287