1 /*
   2  * Copyright (c) 2014, 2019, 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/appcds /test/hotspot/jtreg/runtime/appcds/test-classes
  30  * @requires vm.cds
  31  * @requires vm.flavor != "minimal"
  32  * @build sun.hotspot.WhiteBox
  33  *        InstrumentationApp
  34  *        InstrumentationClassFileTransformer
  35  *        InstrumentationRegisterClassFileTransformer
  36  * @run main/othervm InstrumentationTest
  37  */
  38 
  39 // Note: TestCommon is from /test/hotspot/jtreg/runtime/appcds/TestCommon.java
  40 // Note: Util       is from /test/hotspot/jtreg/runtime/appcds/test-classes/Util.java
  41 
  42 import com.sun.tools.attach.VirtualMachine;
  43 import java.io.File;
  44 import java.io.FileOutputStream;
  45 import jdk.test.lib.Asserts;
  46 import jdk.test.lib.cds.CDSOptions;
  47 import jdk.test.lib.process.OutputAnalyzer;
  48 import jdk.test.lib.process.ProcessTools;
  49 
  50 public class InstrumentationTest {
  51     public static String bootClasses[] = {
  52         "InstrumentationApp$Intf",
  53         "InstrumentationApp$Bar",
  54         "sun.hotspot.WhiteBox",
  55     };
  56     public static String appClasses[] = {
  57         "InstrumentationApp",
  58         "InstrumentationApp$Foo",
  59         "InstrumentationApp$MyLoader",
  60     };
  61     public static String custClasses[] = {
  62         "InstrumentationApp$Coo",
  63     };
  64     public static String sharedClasses[] = TestCommon.concat(bootClasses, appClasses);
  65 
  66     public static String agentClasses[] = {
  67         "InstrumentationClassFileTransformer",
  68         "InstrumentationRegisterClassFileTransformer",
  69         "Util",
  70     };
  71 
  72     public static void main(String[] args) throws Throwable {
  73         runTest(false);
  74         runTest(true);
  75     }
  76 
  77     public static void runTest(boolean attachAgent) throws Throwable {
  78         String bootJar =
  79             ClassFileInstaller.writeJar("InstrumentationBoot.jar", bootClasses);
  80         String appJar =
  81             ClassFileInstaller.writeJar("InstrumentationApp.jar",
  82                                         TestCommon.concat(appClasses,
  83                                                           "InstrumentationApp$ArchivedIfAppCDSv2Enabled"));
  84         String custJar =
  85             ClassFileInstaller.writeJar("InstrumentationCust.jar", custClasses);
  86         String agentJar =
  87             ClassFileInstaller.writeJar("InstrumentationAgent.jar",
  88                                         ClassFileInstaller.Manifest.fromSourceFile("InstrumentationAgent.mf"),
  89                                         agentClasses);
  90 
  91         String bootCP = "-Xbootclasspath/a:" + bootJar;
  92 
  93         System.out.println("");
  94         System.out.println("============================================================");
  95         System.out.println("CDS: NO, attachAgent: " + (attachAgent ? "YES" : "NO"));
  96         System.out.println("============================================================");
  97         System.out.println("");
  98 
  99         String agentCmdArg, flagFile;
 100         if (attachAgent) {
 101             // we will attach the agent, so don't specify -javaagent in the command line. We'll use
 102             // something harmless like -showversion to make it easier to construct the command line
 103             agentCmdArg = "-showversion";
 104         } else {
 105             agentCmdArg = "-javaagent:" + agentJar;
 106         }
 107 
 108         // First, run the test class directly, w/o sharing, as a baseline reference
 109         flagFile = getFlagFile(attachAgent);
 110         AgentAttachThread t = doAttach(attachAgent, flagFile, agentJar);
 111         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
 112                 bootCP,
 113                 "-cp", appJar,
 114                 "-XX:+UnlockDiagnosticVMOptions",
 115                 "-XX:+WhiteBoxAPI",
 116                 "-Xshare:off",
 117                 agentCmdArg,
 118                 "InstrumentationApp", flagFile, bootJar, appJar, custJar);
 119         Process process = pb.start();
 120         if (t != null) {
 121             t.setPid(process.pid());
 122         }
 123         TestCommon.executeAndLog(process, "no-sharing").shouldHaveExitValue(0);
 124         checkAttach(t);
 125 
 126         // Dump the AppCDS archive. On some platforms AppCDSv2 may not be enabled, so we
 127         // first try the v2 classlist, and if that fails, revert to the v1 classlist.
 128         // Note that the InstrumentationApp$ArchivedIfAppCDSv2Enabled class is archived
 129         // only if V2 is enabled. This is tested by InstrumentationApp.isAppCDSV2Enabled().
 130         String[] v2Classes = {
 131             "InstrumentationApp$ArchivedIfAppCDSv2Enabled",
 132             "java/lang/Object id: 0",
 133             "InstrumentationApp$Intf id: 1",
 134             "InstrumentationApp$Coo  id: 2 super: 0 interfaces: 1 source: " + custJar,
 135         };
 136         String[] sharedClassesWithV2 = TestCommon.concat(v2Classes, sharedClasses);
 137         OutputAnalyzer out = TestCommon.dump(appJar, sharedClassesWithV2, bootCP);
 138         if (out.getExitValue() != 0) {
 139             System.out.println("Redumping with AppCDSv2 disabled");
 140                 TestCommon.testDump(appJar, sharedClasses, bootCP);
 141         }
 142 
 143         // Run with AppCDS.
 144         System.out.println("");
 145         System.out.println("============================================================");
 146         System.out.println("CDS: YES, attachAgent: " + (attachAgent ? "YES" : "NO"));
 147         System.out.println("============================================================");
 148         System.out.println("");
 149 
 150         flagFile = getFlagFile(attachAgent);
 151         t = doAttach(attachAgent, flagFile, agentJar);
 152         pb = TestCommon.createProcessBuilderWithAutoArchive("-cp", appJar,
 153                 bootCP,
 154                 "-XX:+UnlockDiagnosticVMOptions",
 155                 "-XX:+WhiteBoxAPI",
 156                 agentCmdArg,
 157                "InstrumentationApp", flagFile, bootJar, appJar, custJar);
 158         process = pb.start();
 159         if (t != null) {
 160             t.setPid(process.pid());
 161         }
 162         out = TestCommon.executeAndLog(process, "auto");
 163         CDSOptions opts = (new CDSOptions()).setXShareMode("auto");
 164         TestCommon.checkExec(out, opts);
 165         checkAttach(t);
 166     }
 167 
 168     static int flagFileSerial = 1;
 169     static private String getFlagFile(boolean attachAgent) {
 170         if (attachAgent) {
 171             // Do not reuse the same file name as Windows may fail to
 172             // delete the file.
 173             return "attach.flag." + ProcessHandle.current().pid() +
 174                     "." + (flagFileSerial++) + "." + System.currentTimeMillis();
 175         } else {
 176             return "noattach";
 177         }
 178     }
 179 
 180     static AgentAttachThread doAttach(boolean attachAgent, String flagFile, String agentJar) throws Throwable {
 181         if (!attachAgent) {
 182             return null;
 183         }
 184 
 185         // We use the flagFile to prevent the child process to make progress, until we have
 186         // attached to it.
 187         File f = new File(flagFile);
 188         try (FileOutputStream o = new FileOutputStream(f)) {
 189             o.write(1);
 190         }
 191         if (!f.exists()) {
 192             throw new RuntimeException("Failed to create " + f);
 193         }
 194 
 195         // At this point, the child process is not yet launched. Note that
 196         // TestCommon.exec() and OutputAnalyzer.OutputAnalyzer() both block
 197         // until the child process has finished.
 198         //
 199         // So, we will launch a AgentAttachThread which will poll the system
 200         // until the child process is launched, and then do the attachment.
 201         // The child process is uniquely identified by having flagFile in its
 202         // command-line -- see AgentAttachThread.getPid().
 203         AgentAttachThread t = new AgentAttachThread(flagFile, agentJar);
 204         t.start();
 205         return t;
 206     }
 207 
 208     static void checkAttach(AgentAttachThread thread) throws Throwable {
 209         if (thread != null) {
 210             thread.check();
 211         }
 212     }
 213 
 214     static class AgentAttachThread extends Thread {
 215         String flagFile;
 216         String agentJar;
 217         volatile boolean succeeded;
 218         volatile long pid;
 219         volatile boolean pidIsKnown;
 220 
 221         AgentAttachThread(String flagFile, String agentJar) {
 222             this.flagFile = flagFile;
 223             this.agentJar = agentJar;
 224             this.succeeded = false;
 225             this.pidIsKnown = false;
 226         }
 227 
 228         void setPid(long pid) {
 229             this.pid = pid;
 230             this.pidIsKnown = true;
 231         }
 232 
 233         String getPid() throws Throwable {
 234             while (!pidIsKnown) {
 235                 // Keep polling until the child process has been launched, and its pid is known.
 236                 // If for some reason the child process fails to launch, this test will be terminated
 237                 // by JTREG's time-out mechanism.
 238                 Thread.sleep(100);
 239             }
 240             System.out.println("pid = " + pid);
 241             return Long.toString(pid);
 242         }
 243 
 244         public void run() {
 245             try {
 246                 String pidStr = getPid();
 247                 VirtualMachine vm = VirtualMachine.attach(pidStr);
 248                 System.out.println(agentJar);
 249                 vm.loadAgent(agentJar);
 250             } catch (Throwable t) {
 251                 t.printStackTrace();
 252                 throw new RuntimeException(t);
 253             }
 254 
 255             // Delete the flagFile to indicate to the child process that we
 256             // have attached to it, so it should proceed.
 257             File f = new File(flagFile);
 258             for (int i=0; i<5; i++) {
 259                 // The detele may fail on Windows if the child JVM is checking
 260                 // f.exists() at exactly the same time?? Let's do a little
 261                 // dance.
 262                 f.delete();
 263                 try {
 264                     Thread.sleep(10);
 265                 } catch (Throwable t) {;}
 266             }
 267             if (f.exists()) {
 268                 throw new RuntimeException("Failed to delete " + f);
 269             }
 270             System.out.println("Attach succeeded (parent)");
 271             succeeded = true;
 272         }
 273 
 274         void check() throws Throwable {
 275             super.join();
 276             if (!succeeded) {
 277                 throw new RuntimeException("Attaching agent to child VM failed");
 278             }
 279         }
 280     }
 281 }
 282