1 /*
   2  * Copyright (c) 2016, 2017, 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 package requires;
  24 
  25 import java.io.IOException;
  26 import java.nio.file.Files;
  27 import java.nio.file.Path;
  28 import java.nio.file.Paths;
  29 import java.nio.file.StandardOpenOption;
  30 import java.util.ArrayList;
  31 import java.util.HashMap;
  32 import java.util.List;
  33 import java.util.Map;
  34 import java.util.concurrent.Callable;
  35 import java.util.concurrent.TimeUnit;
  36 import java.util.regex.Matcher;
  37 import java.util.regex.Pattern;
  38 
  39 import sun.hotspot.cpuinfo.CPUInfo;
  40 import sun.hotspot.gc.GC;
  41 import sun.hotspot.WhiteBox;
  42 import jdk.test.lib.Platform;
  43 
  44 /**
  45  * The Class to be invoked by jtreg prior Test Suite execution to
  46  * collect information about VM.
  47  * Do not use any API's that may not be available in all target VMs.
  48  * Properties set by this Class will be available in the @requires expressions.
  49  */
  50 public class VMProps implements Callable<Map<String, String>> {
  51 
  52     private static final WhiteBox WB = WhiteBox.getWhiteBox();
  53 
  54     /**
  55      * Collects information about VM properties.
  56      * This method will be invoked by jtreg.
  57      *
  58      * @return Map of property-value pairs.
  59      */
  60     @Override
  61     public Map<String, String> call() {
  62         Map<String, String> map = new HashMap<>();
  63         map.put("vm.flavor", vmFlavor());
  64         map.put("vm.compMode", vmCompMode());
  65         map.put("vm.bits", vmBits());
  66         map.put("vm.flightRecorder", vmFlightRecorder());
  67         map.put("vm.simpleArch", vmArch());
  68         map.put("vm.debug", vmDebug());
  69         map.put("vm.jvmci", vmJvmci());
  70         map.put("vm.emulatedClient", vmEmulatedClient());
  71         map.put("vm.cpu.features", cpuFeatures());
  72         map.put("vm.rtm.cpu", vmRTMCPU());
  73         map.put("vm.rtm.os", vmRTMOS());
  74         map.put("vm.aot", vmAOT());
  75         // vm.cds is true if the VM is compiled with cds support.
  76         map.put("vm.cds", vmCDS());
  77         map.put("vm.cds.custom.loaders", vmCDSForCustomLoaders());
  78         // vm.graal.enabled is true if Graal is used as JIT
  79         map.put("vm.graal.enabled", isGraalEnabled());
  80         map.put("docker.support", dockerSupport());
  81         vmGC(map); // vm.gc.X = true/false
  82 
  83         VMProps.dump(map);
  84         return map;
  85     }
  86 
  87     /**
  88      * Prints a stack trace before returning null.
  89      * Used by the various helper functions which parse information from
  90      * VM properties in the case where they don't find an expected property
  91      * or a propoerty doesn't conform to an expected format.
  92      *
  93      * @return null
  94      */
  95     private String nullWithException(String message) {
  96         new Exception(message).printStackTrace();
  97         return null;
  98     }
  99 
 100     /**
 101      * @return vm.simpleArch value of "os.simpleArch" property of tested JDK.
 102      */
 103     protected String vmArch() {
 104         String arch = System.getProperty("os.arch");
 105         if (arch.equals("x86_64") || arch.equals("amd64")) {
 106             return "x64";
 107         }
 108         else if (arch.contains("86")) {
 109             return "x86";
 110         } else {
 111             return arch;
 112         }
 113     }
 114 
 115 
 116 
 117     /**
 118      * @return VM type value extracted from the "java.vm.name" property.
 119      */
 120     protected String vmFlavor() {
 121         // E.g. "Java HotSpot(TM) 64-Bit Server VM"
 122         String vmName = System.getProperty("java.vm.name");
 123         if (vmName == null) {
 124             return nullWithException("Can't get 'java.vm.name' property");
 125         }
 126 
 127         Pattern startP = Pattern.compile(".* (\\S+) VM");
 128         Matcher m = startP.matcher(vmName);
 129         if (m.matches()) {
 130             return m.group(1).toLowerCase();
 131         }
 132         return nullWithException("Can't get VM flavor from 'java.vm.name'");
 133     }
 134 
 135     /**
 136      * @return VM compilation mode extracted from the "java.vm.info" property.
 137      */
 138     protected String vmCompMode() {
 139         // E.g. "mixed mode"
 140         String vmInfo = System.getProperty("java.vm.info");
 141         if (vmInfo == null) {
 142             return nullWithException("Can't get 'java.vm.info' property");
 143         }
 144         if (vmInfo.toLowerCase().indexOf("mixed mode") != -1) {
 145             return "Xmixed";
 146         } else if (vmInfo.toLowerCase().indexOf("compiled mode") != -1) {
 147             return "Xcomp";
 148         } else if (vmInfo.toLowerCase().indexOf("interpreted mode") != -1) {
 149             return "Xint";
 150         } else {
 151             return nullWithException("Can't get compilation mode from 'java.vm.info'");
 152         }
 153     }
 154 
 155     /**
 156      * @return VM bitness, the value of the "sun.arch.data.model" property.
 157      */
 158     protected String vmBits() {
 159         String dataModel = System.getProperty("sun.arch.data.model");
 160         if (dataModel != null) {
 161             return dataModel;
 162         } else {
 163             return nullWithException("Can't get 'sun.arch.data.model' property");
 164         }
 165     }
 166 
 167     /**
 168      * @return "true" if Flight Recorder is enabled, "false" if is disabled.
 169      */
 170     protected String vmFlightRecorder() {
 171         Boolean isUnlockedCommercialFatures = WB.getBooleanVMFlag("UnlockCommercialFeatures");
 172         Boolean isFlightRecorder = WB.getBooleanVMFlag("FlightRecorder");
 173         String startFROptions = WB.getStringVMFlag("StartFlightRecording");
 174         if (isUnlockedCommercialFatures != null && isUnlockedCommercialFatures) {
 175             if (isFlightRecorder != null && isFlightRecorder) {
 176                 return "true";
 177             }
 178             if (startFROptions != null && !startFROptions.isEmpty()) {
 179                 return "true";
 180             }
 181         }
 182         return "false";
 183     }
 184 
 185     /**
 186      * @return debug level value extracted from the "jdk.debug" property.
 187      */
 188     protected String vmDebug() {
 189         String debug = System.getProperty("jdk.debug");
 190         if (debug != null) {
 191             return "" + debug.contains("debug");
 192         } else {
 193             return nullWithException("Can't get 'jdk.debug' property");
 194         }
 195     }
 196 
 197     /**
 198      * @return true if VM supports JVMCI and false otherwise
 199      */
 200     protected String vmJvmci() {
 201         // builds with jvmci have this flag
 202         return "" + (WB.getBooleanVMFlag("EnableJVMCI") != null);
 203     }
 204 
 205     /**
 206      * @return true if VM runs in emulated-client mode and false otherwise.
 207      */
 208     protected String vmEmulatedClient() {
 209         String vmInfo = System.getProperty("java.vm.info");
 210         if (vmInfo == null) {
 211             return "false";
 212         }
 213         return "" + vmInfo.contains(" emulated-client");
 214     }
 215 
 216     /**
 217      * @return supported CPU features
 218      */
 219     protected String cpuFeatures() {
 220         return CPUInfo.getFeatures().toString();
 221     }
 222 
 223     /**
 224      * For all existing GC sets vm.gc.X property.
 225      * Example vm.gc.G1=true means:
 226      *    VM supports G1
 227      *    User either set G1 explicitely (-XX:+UseG1GC) or did not set any GC
 228      * @param map - property-value pairs
 229      */
 230     protected void vmGC(Map<String, String> map){
 231         GC currentGC = GC.current();
 232         boolean isByErgo = GC.currentSetByErgo();
 233         List<GC> supportedGC = GC.allSupported();
 234         for (GC gc: GC.values()) {
 235             boolean isSupported = supportedGC.contains(gc);
 236             boolean isAcceptable = isSupported && (gc == currentGC || isByErgo);
 237             map.put("vm.gc." + gc.name(), "" + isAcceptable);
 238         }
 239     }
 240 
 241     /**
 242      * @return true if VM runs RTM supported OS and false otherwise.
 243      */
 244     protected String vmRTMOS() {
 245         boolean isRTMOS = true;
 246 
 247         if (Platform.isAix()) {
 248             // Actually, this works since AIX 7.1.3.30, but os.version property
 249             // is set to 7.1.
 250             isRTMOS = (Platform.getOsVersionMajor()  > 7) ||
 251                       (Platform.getOsVersionMajor() == 7 && Platform.getOsVersionMinor() > 1);
 252 
 253         } else if (Platform.isLinux()) {
 254             if (Platform.isPPC()) {
 255                 isRTMOS = (Platform.getOsVersionMajor()  > 4) ||
 256                           (Platform.getOsVersionMajor() == 4 && Platform.getOsVersionMinor() > 1);
 257             }
 258         }
 259         return "" + isRTMOS;
 260     }
 261 
 262     /**
 263      * @return true if VM runs RTM supported CPU and false otherwise.
 264      */
 265     protected String vmRTMCPU() {
 266         boolean vmRTMCPU = (Platform.isPPC() ? CPUInfo.hasFeature("tcheck") : CPUInfo.hasFeature("rtm"));
 267 
 268         return "" + vmRTMCPU;
 269     }
 270 
 271     /**
 272      * @return true if VM supports AOT and false otherwise
 273      */
 274     protected String vmAOT() {
 275         // builds with aot have jaotc in <JDK>/bin
 276         Path bin = Paths.get(System.getProperty("java.home"))
 277                         .resolve("bin");
 278         Path jaotc;
 279         if (Platform.isWindows()) {
 280             jaotc = bin.resolve("jaotc.exe");
 281         } else {
 282             jaotc = bin.resolve("jaotc");
 283         }
 284         return "" + Files.exists(jaotc);
 285     }
 286 
 287     /**
 288      * Check for CDS support.
 289      *
 290      * @return true if CDS is supported by the VM to be tested.
 291      */
 292     protected String vmCDS() {
 293         if (WB.isCDSIncludedInVmBuild()) {
 294             return "true";
 295         } else {
 296             return "false";
 297         }
 298     }
 299 
 300     /**
 301      * Check for CDS support for custom loaders.
 302      *
 303      * @return true if CDS is supported for customer loader by the VM to be tested.
 304      */
 305     protected String vmCDSForCustomLoaders() {
 306         if (vmCDS().equals("true") && Platform.areCustomLoadersSupportedForCDS()) {
 307             return "true";
 308         } else {
 309             return "false";
 310         }
 311     }
 312 
 313     /**
 314      * Check if Graal is used as JIT compiler.
 315      *
 316      * @return true if Graal is used as JIT compiler.
 317      */
 318     protected String isGraalEnabled() {
 319         // Graal is enabled if following conditions are true:
 320         // - we are not in Interpreter mode
 321         // - UseJVMCICompiler flag is true
 322         // - jvmci.Compiler variable is equal to 'graal'
 323         // - TieredCompilation is not used or TieredStopAtLevel is greater than 3
 324 
 325         Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler");
 326         if (useCompiler == null || !useCompiler)
 327             return "false";
 328 
 329         Boolean useJvmciComp = WB.getBooleanVMFlag("UseJVMCICompiler");
 330         if (useJvmciComp == null || !useJvmciComp)
 331             return "false";
 332 
 333         // This check might be redundant but let's keep it for now.
 334         String jvmciCompiler = System.getProperty("jvmci.Compiler");
 335         if (jvmciCompiler == null || !jvmciCompiler.equals("graal")) {
 336             return "false";
 337         }
 338 
 339         Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation");
 340         Long compLevel = WB.getIntxVMFlag("TieredStopAtLevel");
 341         // if TieredCompilation is enabled and compilation level is <= 3 then no Graal is used
 342         if (tieredCompilation != null && tieredCompilation && compLevel != null && compLevel <= 3)
 343             return "false";
 344 
 345         return "true";
 346     }
 347 
 348 
 349    /**
 350      * A simple check for docker support
 351      *
 352      * @return true if docker is supported in a given environment
 353      */
 354     protected String dockerSupport() {
 355         boolean isSupported = false;
 356         if (Platform.isLinux()) {
 357            // currently docker testing is only supported for Linux, 
 358            // on x64, AArch64 and ppc64le platforms
 359 
 360            String arch = System.getProperty("os.arch");
 361 
 362            if (Platform.isX64()) {
 363               isSupported = true;
 364            }
 365            else if (Platform.isAArch64()) {
 366               isSupported = true;
 367            }
 368            else if (arch.equals("ppc64le")) {
 369               isSupported = true;
 370            }
 371         }
 372 
 373         if (isSupported) {
 374            try {
 375               isSupported = checkDockerSupport();
 376            } catch (Exception e) {
 377               isSupported = false;
 378            }
 379         }
 380 
 381         return (isSupported) ? "true" : "false";
 382     }
 383 
 384     private boolean checkDockerSupport() throws IOException, InterruptedException {
 385         ProcessBuilder pb = new ProcessBuilder("docker", "ps");
 386         Process p = pb.start();
 387         p.waitFor(10, TimeUnit.SECONDS);
 388 
 389         return (p.exitValue() == 0);
 390     }
 391 
 392 
 393 
 394     /**
 395      * Dumps the map to the file if the file name is given as the property.
 396      * This functionality could be helpful to know context in the real
 397      * execution.
 398      *
 399      * @param map
 400      */
 401     protected static void dump(Map<String, String> map) {
 402         String dumpFileName = System.getProperty("vmprops.dump");
 403         if (dumpFileName == null) {
 404             return;
 405         }
 406         List<String> lines = new ArrayList<>();
 407         map.forEach((k, v) -> lines.add(k + ":" + v));
 408         try {
 409             Files.write(Paths.get(dumpFileName), lines, StandardOpenOption.APPEND);
 410         } catch (IOException e) {
 411             throw new RuntimeException("Failed to dump properties into '"
 412                     + dumpFileName + "'", e);
 413         }
 414     }
 415 
 416     /**
 417      * This method is for the testing purpose only.
 418      * @param args
 419      */
 420     public static void main(String args[]) {
 421         Map<String, String> map = new VMProps().call();
 422         map.forEach((k, v) -> System.out.println(k + ": '" + v + "'"));
 423     }
 424 }