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